@pi-chamber/web 0.9.9-rc.3 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/assets/{DiagramView-Dy4F1cil.js → DiagramView-YPcSEyVl.js} +1 -1
  2. package/dist/assets/{DiffView-C76KYB1I.js → DiffView-IrM_w65M.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-C-TUbGz7.js → FileSaveConflictDialog-CtDwDmHo.js} +1 -1
  4. package/dist/assets/{FilesView-D05cD0Vv.js → FilesView-EUL5SZDG.js} +1 -1
  5. package/dist/assets/{GitView-BrSR7uJk.js → GitView-7K4eJ1V3.js} +3 -3
  6. package/dist/assets/{JsonTreeView-Ds6UD-nj.js → JsonTreeView-Qz0QeRmI.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-D_ClsZYB.js → MarkdownRendererImpl-CsJfFWDC.js} +1 -1
  8. package/dist/assets/{PatchDiff-DaZ-PTug.js → PatchDiff-DNhojsLA.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-FaYzgplj.js → SessionSwitcherContent-l1fTUann.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-D_9pieby.js → SessionSwitcherDropdown-CUyTFUnd.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-DGuqqVhb.js → SessionUnreadDot-CY3rTilj.js} +1 -1
  12. package/dist/assets/{SettingsView-C-YJztlm.js → SettingsView-Cm4cKNof.js} +2 -2
  13. package/dist/assets/{SettingsWindow-Dpw6aF2F.js → SettingsWindow-9FD4QY3p.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-CcbJkYYg.js → ToolOutputDialog-0uj3Kf5J.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-C0c8f4Nt.js → ToolPartDiffPreview-B29vAjqI.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-BvU0E4qX.js → VirtualizedFileDiff-B1Jii7gu.js} +1 -1
  17. package/dist/assets/{computeVirtualFileMetrics-hWwF-t_o.js → computeVirtualFileMetrics-B6RnDAuP.js} +1 -1
  18. package/dist/assets/{contextFileOpenGuard-Y5Z8LQyY.js → contextFileOpenGuard-DIpJPFxL.js} +1 -1
  19. package/dist/assets/{gitStatusPredicates-Dmaw5g31.js → gitStatusPredicates-lhIrHyDw.js} +1 -1
  20. package/dist/assets/{index-CqdQEvR2.js → index-BUxQG4Eq.js} +1 -1
  21. package/dist/assets/{isDiffPlainText-C1dRfEBh.js → isDiffPlainText-r5sF6_KV.js} +1 -1
  22. package/dist/assets/{isFilePlainText-wlC41gsX.js → isFilePlainText-B4e2b2Bv.js} +1 -1
  23. package/dist/assets/{main-CfNlfHvj.js → main-DMYsDuaV.js} +2 -2
  24. package/dist/assets/{main-CkViwsz_.js → main-DSfSGm2f.js} +3 -3
  25. package/dist/assets/{markdownCore-Ci_ipXBM.js → markdownCore-0ygaCYcc.js} +1 -1
  26. package/dist/assets/{miniChat-BFzjOj9l.js → miniChat-DUMRG1q5.js} +2 -2
  27. package/dist/assets/{mobile-D4xKl_yN.js → mobile-DUcoCNyj.js} +2 -2
  28. package/dist/assets/{renderElectronMiniChatApp-BQBx6mC4.js → renderElectronMiniChatApp-BNmJJQdl.js} +2 -2
  29. package/dist/assets/{renderMobileApp-D1Q-yGOv.js → renderMobileApp-DnhfWGEW.js} +3 -3
  30. package/dist/assets/{runtimeEndpointReset-Co9SkOQC.js → runtimeEndpointReset-B0SWG9Uo.js} +3 -3
  31. package/dist/assets/{useAppFontEffects-D00QsL7D.js → useAppFontEffects-CDmJGQlK.js} +7 -7
  32. package/dist/assets/{useFilesViewSearch-BsC82OOk.js → useFilesViewSearch-DDMI---4.js} +1 -1
  33. package/dist/assets/{usePushVisibilityBeacon-Pg0Sln_M.js → usePushVisibilityBeacon-i8sRCEtS.js} +1 -1
  34. package/dist/assets/{useSwitcherItems-BXn8MrAT.js → useSwitcherItems-BT_toOh9.js} +1 -1
  35. package/dist/assets/{vendor-codemirror-language-data-DhJ96dYN.js → vendor-codemirror-language-data-D09wcguI.js} +2 -2
  36. package/dist/assets/{web-components-Bb-NxfNy.js → web-components-Cb0vnR_a.js} +1 -1
  37. package/dist/index.html +1 -1
  38. package/dist/mini-chat.html +1 -1
  39. package/dist/mobile.html +1 -1
  40. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CqdQEvR2.js","assets/useAppFontEffects-D00QsL7D.js","assets/index-BOtRfXre.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BXgR2dKM.css","assets/vendor-base-ui-DXSHfszQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CPm7KWaN.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-DhJ96dYN.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-CNlncqrr.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-hWwF-t_o.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-wlC41gsX.js","assets/isDiffPlainText-C1dRfEBh.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-D_9pieby.js"])))=>i.map(i=>d[i]);
2
- import{_ as ls}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ie,j as t,R as i,b as sc}from"./vendor-react-B5Z1Mdn3.js";import{aP as Ms,aQ as nc,Q as rc,a1 as Mt,a2 as ze,a3 as $e,a4 as Ft,B as Te,I as R,a5 as Ge,a6 as Ot,a8 as rt,t as ae,a as pt,e as Ee,Z as $s,ad as dn,aR as Si,af as Ht,ag as Yt,ah as ds,ai as ss,aj as us,ak as Ss,aF as xs,aS as ys,g as Ps,aT as or,aU as Io,aV as Ro,aW as nn,o as ji,ae as ps,aX as Eo,a7 as ws,aY as Cr,aZ as oc,a_ as ic,a$ as ac,b0 as lc,b1 as cc,b2 as Ar,b3 as dc,x as Kt,b4 as uc,b5 as fc,b6 as hc,b7 as ki,b8 as pc,b9 as mc,ba as Ci,bb as Ai,bc as Ni,aC as Nr,r as rn,m as Qr,ao as gc,ay as bc,aB as Ii,K as js,d as Vr,aa as Gs,ax as Ri,bd as Yn,be as Do,bf as ht,aD as Ei,bg as Di,at as xc,f as Ti,i as yc,bh as wc,h as vc,bi as Es,b as To,c as Sc,bj as jc,u as kc,aE as Cc,aH as Ac,bk as Ir,bl as Nc,bm as Ic,aG as Rc,bn as Ec,bo as Dc,T as Tc,a9 as vs,al as Pi,v as Pc,ab as Mc,bp as Fc,bq as Oc,j as Lc,br as Bc,bs as Mi,bt as _c,bu as Uc,bv as zc,bw as $c,bx as Gc,by as Kc,bz as Wc,bA as Hc,bB as Yc,bC as qc}from"./useAppFontEffects-D00QsL7D.js";import{Z as Po,_ as Qc,$ as Mo,a0 as Vc,i as Jc,a1 as Xc,S as Zc,m as Nt,a2 as un,b as ed,a3 as td,R as Ls,a4 as Fi,a5 as Oi,a6 as sd,a7 as nd,q as Bs,K as rd,a8 as od,a9 as id,aa as ad,ab as Xt,v as Zt,ac as ld,ad as cd,ae as dd,af as Jr,ag as ud,ah as fd,ai as hd,u as le,o as U,aj as pd,f as Xe,B as Ne,ak as _s,al as Pt,am as Fo,an as Rr,a as Xr,T as Zr,U as Bn,ao as md,ap as gd,aq as Li,F as bd,Q as Bi,C as on,ar as Er,h as Dr,d as kn,as as xd,at as yd,au as Oo,av as Xs,aw as ir,ax as Tr,ay as ms,az as Lo,aA as Pr,aB as _i,aC as Mr,aD as wd,aE as vd,aF as Sd,aG as jd,aH as kd,aI as Cd,aJ as Ad,z as Nd,aK as Id,aL as Rd,Y as Ui,P as Ed,J as Dd}from"./index-BOtRfXre.js";import{c as ks,d as zi,p as eo,u as Fr,a as Td}from"./vendor-zustand-GVb4H8HE.js";import{g as cs,b as Pd,c as $i,r as Md,d as Gi,s as Tn,e as Ki,h as fn,i as hn,j as Fd,k as Od,l as Ld,m as Bo,n as qn,f as Bd,a as _d,S as Ud,t as zd,o as $d}from"./SessionUnreadDot-DGuqqVhb.js";import{C as Wi,a as Hi,M as Yi,b as qi,c as Qi,d as Vi,S as Ji,D as Gd,e as Kd,f as Wd,g as Hd,h as Yd,i as qd,j as Qd}from"./vendor-base-ui-DXSHfszQ.js";import{c as Xi,d as Or,P as Vd,D as Zi,e as ea,f as Jd,b as Xd,a as Zd,T as eu,M as tu}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{u as su}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as nu,v as ru,u as ou}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as iu}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-xterm-xterm-CrXqRur4.js";import{usePermissionStore as au}from"./permissionStore-iKN1K2_x.js";const lu="chat";function ta(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ms.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ms.SETTINGS,n),s}return e.tab!==lu&&s.set(Ms.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ms.FILE,e.diffFile),s}function cu(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function du(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=ta(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ms.SESSION)&&s.set(Ms.SESSION,o);const a=[...s.entries()].sort((c,u)=>c[0].localeCompare(u[0])),l=[...n.entries()].sort((c,u)=>c[0].localeCompare(u[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Lr(e,s={}){if(!(typeof window>"u")&&!(!s.force&&du(e)))try{const n=ta(e),r=cu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const uu=["typescript","javascript","tsx","jsx","json","markdown"],sa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let _o=null;const na=()=>(_o??=Promise.all([ls(()=>import("./index-CqdQEvR2.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])),ls(()=>import("./workerFactory-tw7cIdmV.js"),[]),ls(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([110,111,97,98,24,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),_o),pn={},Uo=new Set,Br=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const fu=()=>{for(const e of Br)e()},ra=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:sa[e].lineDiffType})},_r=e=>{typeof window>"u"||Uo.has(e)||(Uo.add(e),na().then(s=>{if(pn[e])return;const n=sa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:uu,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),pn[e]=r,ra(e,r),fu()}))},hu=e=>(Br.add(e),()=>Br.delete(e)),pu=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(pn)){const n=pn[s];n&&ra(s,n)}}},gg=({children:e})=>{const s=nc(),n=Po(!1),r=Po(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(u=>u.metadata.id===o)??n,c=s?.availableThemes.find(u=>u.metadata.id===a)??r;return Ie.useEffect(()=>{let u=!1;return na().then(d=>{u||(d.ensurePierreThemeRegistered(l),d.ensurePierreThemeRegistered(c),pu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,l]),Ie.useEffect(()=>{if(typeof window>"u")return;const u=()=>{_r("unified"),_r("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(u,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const d=window.setTimeout(u,2e3);return()=>window.clearTimeout(d)},[]),t.jsx(t.Fragment,{children:e})},bg=(e="unified")=>{const s=Ie.useSyncExternalStore(hu,()=>pn[e],()=>{});return Ie.useEffect(()=>{_r(e)},[e]),s};function mu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=rc();return e}catch{return"unknown"}}function gu(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function bu(){const e=ed();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function xu(e){const s=new URLSearchParams;return s.set("deviceClass",mu()),s.set("arch",gu()),s.set("platform",bu()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",un()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ar(e,s){try{const n=xu(e);s&&n.set("currentVersion",s);const r=await Nt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand,channel:o.channel==="rc"?"rc":"stable"}}catch(n){return console.warn("Failed to check for updates:",n),null}}function yu(){return Jc()?"mobile":Xc()?"desktop":Zc()?"web":null}const zo={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=ks()((e,s)=>({...zo,checkForUpdates:async()=>{const n=yu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.9.9-rc.3",[l,c]=await Promise.allSettled([Mo(),ar("desktop",a)]),u=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:u?.available??!1,info:u,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ar("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ar("mobile","0.9.9-rc.3"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await Mo();if(!o?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await Vc(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Qc())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(zo)}})),wu={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},vu={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 oa(e){return e&&vu[e]||"var(--primary)"}const $o=({icon:e,className:s,colorToken:n})=>{const r=wu[e??"branch"]??"user-3";return t.jsx(R,{name:r,className:s,style:{color:oa(n)}})},Su=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Mt,{children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Ft,{asChild:!0,children:t.jsxs(Te,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:oa(e?.color)},disabled:a,children:[r?t.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx($o,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(R,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Ge,{sideOffset:8,children:"Git identity"})]}),t.jsx(Ot,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(rt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx($o,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(R,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},ju=e=>e==="/",Us=e=>e.replace(/\\/g,"/"),zs=e=>{if(!e||ju(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),_n=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},to=e=>e.lastIndexOf("/"),ia=e=>{if(Fs(e))return e;const s=to(e);return s<0?e:e.slice(0,s+1)},aa=e=>{const s=to(e);return e.slice(s+1)},la=e=>{const s=zs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=to(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},ca=e=>Fs(e)&&la(e)!==null,ku=e=>{if(!ca(e))return null;const s=zs(e.trim());return aa(s)||s},Cu=(e,s)=>`${ia(e)}${s}/`,gs=e=>{if(!e)return null;const s=zs(Us(e.trim()));return s?s.toLowerCase():null},Go=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},Au=(e,s)=>{const n=zs(Us(e.trim())),r=zs(Us(s.trim()));if(!n)return"";if(!r)return _n(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:_n(n)},Nu=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Ur=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Iu=async()=>td(),Ru=()=>{const[e,s]=Ie.useState(!1),[n,r]=Ie.useState(!1);Ie.useEffect(()=>{s(Ls()),r(Fi())},[]);const o=Ie.useCallback(async c=>e?await Oi(c):{success:!0,path:c},[e]),a=Ie.useCallback(async c=>e?await sd():{success:!0},[e]),l=Ie.useCallback(async c=>e?await nd():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function Eu({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Bs(ne=>ne.homeDirectory),{canRequestAccess:o,startAccessing:a}=Ru(),l=i.useRef(null),c=i.useRef(new Map),[u,d]=i.useState(""),[f,p]=i.useState("~/"),[b,m]=i.useState([]),[g,h]=i.useState(!1),[v,x]=i.useState(!1),[I,w]=i.useState(null),[A,N]=i.useState(0),[C,j]=i.useState(0),[y,k]=i.useState(!1),[E,P]=i.useState(!1),[B,L]=i.useState("right"),z=i.useRef("~/"),Q=u||r;i.useEffect(()=>{if(!e)return;p("~/"),m([]),j(0),k(!1),P(!1),z.current="~/",L("right"),n||requestAnimationFrame(()=>Ur(l.current));let ne=!1;return(async()=>{const q=await Iu();ne||(d(q||r||""),n||requestAnimationFrame(()=>Ur(l.current)))})(),()=>{ne=!0}},[r,e,n]);const O=i.useMemo(()=>ia(f),[f]),M=i.useMemo(()=>Fs(f)?"":aa(f),[f]),T=i.useMemo(()=>Q?Go(O,Q):"",[O,Q]);i.useEffect(()=>{const ne=z.current;ne!==O&&(L(O.length>=ne.length?"right":"left"),z.current=O)},[O]),i.useEffect(()=>{if(!e||!T){m([]),w(null);return}let ne=!1;return h(!0),x(!1),w(null),rd(T).then(ce=>{if(ne)return;x(!1),w(null);const q=ce.filter(fe=>fe.isDirectory).map(fe=>({name:fe.name,path:Us(fe.path)})).sort((fe,_e)=>fe.name.localeCompare(_e.name));m(q)}).catch(ce=>{if(!ne){m([]);const q=od(ce)?ce.reason:"unknown";w(q),x(q==="not-found")}}).finally(()=>{ne||h(!1)}),()=>{ne=!0}},[T,A,e]);const _=i.useMemo(()=>{const ne=M.toLowerCase(),ce=E||M.startsWith(".");return b.filter(q=>q.name.toLowerCase().startsWith(ne)&&(ce||!q.name.startsWith(".")))},[M,b,E]),se=i.useMemo(()=>ku(f),[f]),$=i.useMemo(()=>la(f),[f]),G=i.useMemo(()=>{const ne=[],ce=gs(T);ca(f)&&se&&$&&ne.push({type:"parent",value:"browse:up",name:se,path:$,alreadyAdded:!!(ce&&s.has(ce))});for(const q of _){const fe=gs(q.path);ne.push({type:"directory",value:`browse:${q.path}`,name:q.name,path:q.path,alreadyAdded:!!(fe&&s.has(fe))})}return ne},[s,T,se,_,$,f]);i.useEffect(()=>{j(0)},[f,G.length]);const Ae=i.useMemo(()=>Q?zs(Go(f,Q)):"",[Q,f]),te=gs(Ae),Pe=!!(te&&s.has(te)),Be=i.useMemo(()=>M?_.find(ne=>ne.name===M)??null:null,[M,_]),Y=!!(Ae&&!Pe&&(I===null||I==="not-found")&&(Fs(f)&&v||!Fs(f)&&M.trim().length>0&&Be===null)),F=G[C]??null,K=!!F,J=i.useCallback(ne=>{p(_n(ne))},[]),Z=i.useCallback(ne=>{p(Cu(f,ne.name))},[f]),pe=i.useCallback(ne=>{if(ne){if(ne.type==="parent"){J(ne.path);return}Z(ne)}},[J,Z]),Se=i.useCallback(async ne=>{const ce=await a(ne);if(!ce.success)return ae.error("Failed to open directory",{description:ce.error||"Desktop could not grant file access."}),!1;const q=Q?Au(ne,Q):_n(Us(ne));return J(q),!0},[J,Q,a]),xe=i.useCallback(async()=>{if(!y){k(!0);try{if(Fi()){const ce=await Oi(Ae);if(!ce.success||!ce.path){ce.error&&ce.error!=="Directory selection cancelled"&&ae.error("Failed to select directory",{description:ce.error});return}await Se(ce.path);return}const ne=await id(Ae);if(ne.status==="cancelled")return;if(ne.status!=="picked"){ae.error("Couldn't open a folder picker",{description:ne.error});return}await Se(ne.path)}catch(ne){ae.error("Failed to select directory",{description:ne instanceof Error?ne.message:"Unknown error occurred."})}finally{k(!1)}}},[Se,y,Ae]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:g,isBrowseDirectoryMissing:v,browseErrorReason:I,browseReloadKey:A,setBrowseReloadKey:N,highlightedIndex:C,setHighlightedIndex:j,isPickingLocation:y,showHidden:E,setShowHidden:P,folderEnterFrom:B,explorerRootDirectory:Q,browseDirectoryDisplayPath:O,browseDirectoryAbsolutePath:T,browseFilterQuery:M,filteredEntries:_,rows:G,targetPath:Ae,isAlreadyAdded:Pe,shouldCreateTarget:Y,highlightedRow:F,hasHighlightedBrowseItem:K,canRequestAccess:o,browseToDisplayPath:J,browseToEntry:Z,executeRow:pe,applyPickedLocation:Se,handleBrowseLocation:xe}}const hs=ks()(zi(eo((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=Zt()?.git,o=r?await r.getGitIdentities():await hd();return e({profiles:o,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=Zt()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await fd();if(r&&r.userName&&r.userEmail){const o={id:"global",name:"Global Identity",userName:r.userName,userEmail:r.userEmail,authType:r.sshCommand?"ssh":void 0,sshKey:r.sshCommand?r.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:o})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=Zt()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await ud();return e({discoveredCredentials:r}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const o=r.trim();return o.length>0?o:null};try{let r=null;if(r===null){const o=Zt()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Nt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Jr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};Xt("saving");const o=Zt()?.git;return o?await o.createGitIdentity(r):await dd(r),Xt("saved"),await s().loadProfiles(),!0}catch(r){return Xt("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(c=>c.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};Xt("saving");const l=Zt()?.git;return l?await l.updateGitIdentity(n,a):await cd(n,a),Xt("saved"),await s().loadProfiles(),!0}catch(o){return Xt("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{Xt("saving");const r=Zt()?.git;return r?await r.deleteGitIdentity(n):await ld(n),Xt("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return Xt("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:o}=s();return n==="global"?o||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(o=>!n.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:ad(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=hs);function Du({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:u,isPickingLocation:d}){const f=pt($=>$.addProject),p=le($=>$.setActiveMainTab),b=le($=>$.setSessionSwitcherOpen),m=Ee($=>$.openNewSessionDraft),g=hs($=>$.profiles),h=hs($=>$.globalIdentity),v=hs($=>$.defaultGitIdentityId),x=hs($=>$.loadProfiles),I=hs($=>$.loadGlobalIdentity),w=hs($=>$.loadDefaultGitIdentityId),[A,N]=i.useState(!1),[C,j]=i.useState(!1),[y,k]=i.useState(""),[E,P]=i.useState(null);i.useEffect(()=>{e&&(N(!1),j(!1),k(""),P(null))},[e]),i.useEffect(()=>{e&&(x(),I(),w())},[w,x,I,e]);const B=i.useMemo(()=>{const $=new Map;h&&$.set(h.id,h);for(const G of g)$.set(G.id,G);return Array.from($.values())},[g,h]);i.useEffect(()=>{if(!e||!C||E!==null)return;const $=typeof v=="string"?v.trim():"";if($&&B.some(Ae=>Ae.id===$)){P($);return}const G=B.find(Ae=>Ae.authType==="ssh"||Ae.sshKey);G&&P(G.id)},[B,v,C,e,E]);const L=i.useMemo(()=>B.find($=>$.id===E)??null,[B,E]),z=i.useCallback(($,G)=>{p("chat"),n&&b(!1),m({selectedProjectId:$,directoryOverride:G}),s()},[n,s,m,p,b]),Q=i.useCallback(async $=>{if(!$||A)return;const G=gs($);if(G&&r.has(G))return;let Ae=$;N(!0);try{const te=!C&&a&&gs($)===gs(o);if(C){const Be=y.trim();if(!Be){ae.error("Enter a repository URL before cloning.");return}const Y=await Nt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:Be,destinationPath:$,gitIdentityId:L?.id??null})});if(!Y.ok)throw new Error("Failed to clone git repository");Ae=(await Y.json()).path||$}else if(te&&!(await Nt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:$})})).ok)throw new Error("Failed to select directory");const Pe=f(Ae);if(!Pe){ae.error("Failed to add folder",{description:"Please select a valid directory path."});return}z(Pe.id,Pe.path)}catch(te){ae.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{N(!1)}},[f,r,c,y,C,A,z,L?.id,a,o]),O=!A&&!d&&!u&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,M=O&&y.trim().length>0,T=C?M:O,_=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:A,isCloneMode:C,setIsCloneMode:j,cloneRemoteUrl:y,setCloneRemoteUrl:k,selectedGitIdentityId:E,setSelectedGitIdentityId:P,availableGitIdentities:B,selectedGitIdentity:L,canSubmit:T,submitActionLabel:u?"Already added":C?A?"Cloning...":"Clone & add":A?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:_,finalizeSelection:Q}}const Tu=({open:e,onOpenChange:s})=>{const n=pt(q=>q.projects),{isMobile:r,isTablet:o}=$s(),a=r||o,l=i.useMemo(()=>new Set(n.map(q=>gs(q.path)).filter(q=>!!q)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:u,rowRefs:d,query:f,setQuery:p,isLoading:b,browseErrorReason:m,setBrowseReloadKey:g,highlightedIndex:h,setHighlightedIndex:v,isPickingLocation:x,showHidden:I,setShowHidden:w,folderEnterFrom:A,browseDirectoryDisplayPath:N,browseDirectoryAbsolutePath:C,rows:j,targetPath:y,isAlreadyAdded:k,shouldCreateTarget:E,highlightedRow:P,hasHighlightedBrowseItem:B,canRequestAccess:L,executeRow:z,handleBrowseLocation:Q}=Eu({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:O,isCloneMode:M,setIsCloneMode:T,cloneRemoteUrl:_,setCloneRemoteUrl:se,setSelectedGitIdentityId:$,availableGitIdentities:G,selectedGitIdentity:Ae,canSubmit:te,submitActionLabel:Pe,submitModifierLabel:Be,finalizeSelection:Y}=Du({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:y,shouldCreateTarget:E,browseErrorReason:m,browseDirectoryAbsolutePath:C,isAlreadyAdded:k,isPickingLocation:x});i.useLayoutEffect(()=>{const q=u.current;q&&(q.scrollLeft=q.scrollWidth)},[u,f]),i.useLayoutEffect(()=>{!e||a||Ur(u.current)},[u,e,a]),i.useLayoutEffect(()=>{const q=j[h];q&&d.current.get(q.value)?.scrollIntoView({block:"nearest"})},[h,d,j]);const F=i.useCallback(q=>{if(q.key==="ArrowDown"){q.preventDefault(),v(fe=>Math.min(j.length-1,fe+1));return}if(q.key==="ArrowUp"){q.preventDefault(),v(fe=>Math.max(0,fe-1));return}if(q.key==="Enter"){if(q.preventDefault(),Nu(q)){Y(y);return}B&&z(P);return}q.key==="Backspace"&&f===""&&(q.preventDefault(),c())},[z,Y,c,B,P,f,j.length,v,y]),K=t.jsxs("button",{type:"button",onClick:()=>w(q=>!q),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[I?t.jsx(R,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),J=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(R,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(dn,{ref:u,value:f,onChange:q=>p(Us(q.target.value)),onKeyDown:F,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Te,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:O||x,onMouseDown:q=>q.preventDefault(),onClick:()=>{Q()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(R,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),Z=j.some(q=>q.type==="parent"),pe=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Te,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":M,disabled:O||x,onClick:()=>T(q=>!q),children:[t.jsx(R,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),M?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(dn,{value:_,onChange:q=>se(q.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(Su,{activeProfile:Ae,identities:G,onSelect:q=>$(q.id),isApplying:O,iconOnly:!0})]})]}):null,k?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:U("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",A==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:b?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):m&&m!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:m==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[m==="os-permission"&&L?t.jsx(Te,{size:"xs",onClick:()=>{Q()},disabled:x,children:"Grant access"}):null,t.jsx(Te,{variant:"outline",size:"xs",onClick:()=>g(q=>q+1),children:"Try again"})]})]}):j.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:j.map((q,fe)=>{const _e=fe===h,W=q.type==="directory"&&Z;return t.jsxs("button",{ref:X=>{X?d.current.set(q.value,X):d.current.delete(q.value)},type:"button","aria-label":q.type==="parent"?q.alreadyAdded?`Go back from ${q.name}, already added`:`Go back from ${q.name}`:q.alreadyAdded?`Open ${q.name}, already added`:`Open ${q.name}`,onMouseEnter:()=>v(fe),onMouseDown:X=>X.preventDefault(),onClick:()=>z(q),className:U("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",_e&&"bg-interactive-selection text-interactive-selection-foreground",!_e&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:U("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[q.type==="parent"?t.jsx(R,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(R,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:q.name})]}),q.alreadyAdded?t.jsx("span",{className:U("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",_e?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,q.type==="parent"?t.jsx(R,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(R,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},q.value)})})},N)]})}),Se=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[J,pe]}),xe=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(R,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(R,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:Be}),t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),ne=t.jsx(Te,{size:r?"xs":"default",onClick:()=>{Y(y)},disabled:!te,className:U(r&&"w-full flex-1"),children:Pe}),ce=()=>t.jsxs(t.Fragment,{children:[r?null:xe,t.jsx("div",{className:U("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:ne})]});return r?t.jsx(Si,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ce()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:K}),Se]})}):t.jsx(Ht,{open:e,onOpenChange:s,children:t.jsxs(Yt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(ds,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(ss,{children:"Add folder"}),t.jsx(us,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),K]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Se}),t.jsx(Ss,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ce()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,xg=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=Ee(C=>C.deleteSession),c=Ee(C=>C.deleteSessions),u=le(C=>C.showDeletionDialog),d=le(C=>C.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:b}=$s(),m=f||p||b;i.useEffect(()=>pd(()=>{s(!1)}),[]);const g=i.useCallback(C=>{r({sessions:C.sessions,dateLabel:C.dateLabel})},[]),h=i.useCallback(()=>{r(null),a(!1)},[]),v=i.useCallback(async C=>{if(C.sessions.length===0)return;if(C.sessions.length===1){const E=C.sessions[0];await l(E.id)?ae.success("Session deleted"):ae.error("Failed to delete session");return}const j=C.sessions.map(E=>E.id),{deletedIds:y,failedIds:k}=await c(j);if(y.length>0){const E=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:C.dateLabel?`Removed all sessions from ${C.dateLabel}.`:void 0;ae.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:Cn(E)})}k.length>0&&ae.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>xs.onDeleteRequest(C=>{if(!u){v(C);return}g(C)}),[g,u,v]),i.useEffect(()=>xs.onDirectoryRequest(()=>{s(!0)}),[]);const x=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const C=n.sessions[0];if(!await l(C.id)){ae.error("Failed to delete session"),a(!1);return}ae.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const C=n.sessions.map(E=>E.id),j=await c(C),y=j.deletedIds,k=j.failedIds;if(y.length>0){const E=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ae.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:Cn(E),action:{label:"OK",onClick:()=>{}}})}if(k.length>0&&(ae.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:Cn("Please try again in a moment.")}),y.length===0)){a(!1);return}}h()}finally{a(!1)}}},[n,l,c,h]),I=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",w=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(C=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:cs(C)})},C.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>d(!u),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!u,children:[u?t.jsx(R,{name:"checkbox-blank",className:"size-4"}):t.jsx(R,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Te,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),t.jsx(Te,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),N=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(Si,{open:!!n,onClose:()=>{o||h()},title:N,footer:t.jsx("div",{className:"flex justify-end gap-2",children:A}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),w]})}):t.jsx(Ht,{open:!!n,onOpenChange:C=>{if(!C){if(o)return;h()}},children:t.jsxs(Yt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:N}),I&&t.jsx(us,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),t.jsx(Ss,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),t.jsx(Tu,{open:e,onOpenChange:s})]})},yg=()=>{const e=ys(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(ys.getState().markNotificationSent(s.key),ae.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},Pu=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Mu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Fu(e){const s=e.trim().toLowerCase();return Pu.find(n=>n.slug===s)??null}function Ou(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=Mu[s];if(n)return n;const r=Fu(s);return r?r.slug:"home"}function wg(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"snippets":return"chat-thread";case"prompt-templates":return"terminal";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}function vg(){const e=i.useRef(!1),s=i.useRef(!1),n=Ee(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),a=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=Ee.getState().currentSessionId,b=Ps().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==b){const m=Ee.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,m)}}if(f.settingsPath){a(Ou(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,o,a,l]),u=i.useCallback(()=>{const f=Ee.getState(),p=Ps().getState(),b=le.getState();return{sessionId:or({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),d=i.useCallback((f={})=>{if(s.current)return;const p=u();Lr(p,f)},[u]);i.useEffect(()=>{if(e.current||(e.current=!0,!Io()))return;const f=Ro();(async()=>(await c(f),Lr({...u(),sessionId:f.sessionId??or({currentSessionId:Ee.getState().currentSessionId,piSelectedSessionId:Ps().getState().selectedSessionId,draft:Ee.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),i.useEffect(()=>{const f=()=>{const v=Ee.getState(),x=Ps().getState();return or({currentSessionId:v.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:v.newSessionDraft})};let p=f(),b=Ee.getState().newSessionDraft?.open===!0;const m=()=>{const v=Ee.getState(),x=f(),I=v.newSessionDraft?.open===!0;x===p&&I===b||s.current||(p=x,b=I,d({replace:!0}))},g=Ee.subscribe(()=>{m()}),h=Ps().subscribe(()=>{m()});return()=>{g(),h()}},[d]),i.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,b=le.getState().settingsPage,m=le.getState().pendingDiffFile;return le.subscribe(h=>{if(s.current)return;const v=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==p,I=h.settingsPage!==b,w=h.pendingDiffFile!==m&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,b=h.settingsPage,m=h.pendingDiffFile,(v||x||I||w)&&d()})},[d]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Ro();if(Io())c(p);else{const b=le.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function Lu(e=!0){const s=Mn(r=>r.checkForUpdates),n=i.useRef(s);i.useEffect(()=>{n.current=s},[s]),i.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,u=null;const d=p=>{const b=Math.round(p*1e3);return Math.max(a,Math.min(l,b))},f=p=>{c||(u=window.setTimeout(async()=>{const b=await n.current(),m=typeof b=="number"&&Number.isFinite(b)?d(b):o;f(m)},p))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function Sg(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return Lu(e),null}const Ko=12,Bu=[{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"}],_u=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=Bu,onComplete:a})=>{const l=Ie.useRef(!1);Ie.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ie.useMemo(()=>Array.from({length:Ko},(u,d)=>{const f=Math.PI*2*d/Ko;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?t.jsx("div",{className:U("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(u=>{const d={"--burst-delay":`${u.delay}ms`,"--burst-x":`${u.x}%`,"--burst-y":`${u.y}%`,"--firework-color":`var(${u.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:d,children:c.map((f,p)=>{const b=f.x*u.radius,m=f.y*u.radius,g={"--translate-x":`${b}px`,"--translate-y":`${m}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return t.jsx("span",{className:"firework-particle",style:g},`${u.id}-${p}-${s}`)})},`${u.id}-${s}`)})}):null},Uu=({durationMs:e=3400}={})=>{const[s,n]=Ie.useState({isActive:!1,cycle:0}),r=Ie.useRef(null),o=Ie.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ie.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ie.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Ie.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},da=i.createContext(void 0),jg=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Uu(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(da.Provider,{value:a,children:[e,t.jsx(_u,{isActive:s,burstKey:n})]})},zu={triggerFireworks:()=>{},dismissFireworks:()=>{}},kg=()=>i.useContext(da)??zu,Un=2e3,ua=600*1e3;async function $u(){try{const e=await Nt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const s=await e.json().catch(()=>({}));return{success:!0,autoRestart:s.autoRestart!==!1,jobId:typeof s.jobId=="string"?s.jobId:void 0,channel:s.channel==="rc"?"rc":s.channel==="stable"?"stable":void 0,targetVersion:typeof s.targetVersion=="string"?s.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Gu(e,s=Math.ceil(ua/Un),n=Un,r=Xe()){for(let o=0;o<s;o++){if(Xe()!==r)return{applied:!1,stale:!0};try{const a=await Nt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==r)return{applied:!1,stale:!0};if(a.ok){const l=await a.json().catch(()=>null);if(Xe()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Xe()!==r)return{applied:!1,stale:!0}}await new Promise(a=>setTimeout(a,n))}return{applied:!1}}async function Ku(e,s,n=Math.ceil(ua/Un),r=Un,o=Xe()){for(let a=0;a<n;a++){if(Xe()!==o)return{applied:!1,stale:!0};try{const l=await Nt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Xe()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?s("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&s("updating")}else{if(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Xe()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};s("reconnecting")}else s("reconnecting")}}catch{if(Xe()!==o)return{applied:!1,stale:!0};s("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Wo="https://github.com/RyderAsKing/PiChamber/releases";function Wu(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function Hu(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Ho(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Yu(e,s){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(a!==l)return l-a}return 0}function qu(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const fa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,p]=Ie.useState(null),[b,m]=Ie.useState("idle"),[g,h]=Ie.useState(null),[v,x]=Ie.useState(null),[I,w]=Ie.useState({}),A=n?.version?n.releaseUrl||`${Wo}/tag/v${n.version}`:Wo,N=n?.downloadUrl||A,C=a?.total?Math.round(a.downloaded/a.total*100):0,j=d==="web",y=d==="mobile",k=n?.updateCommand||"pichamber update",E=I.version||n?.version,P=I.channel||n?.channel;Ie.useEffect(()=>{e||(m("idle"),h(null),x(null),w({}))},[e]);const B=async(T=k)=>{(await ws(T)).ok&&(p(T),setTimeout(()=>p(null),2e3))},L=Ie.useCallback(async T=>{await ji(T)},[]),z=Ie.useCallback(async()=>{const T=Xe();m("updating"),h(null),x(null),w({});const _=await $u();if(Xe()!==T)return;if(!_.success){m("error"),h(_.error||"Update failed"),x(_.commands??null);return}if(w({version:_.targetVersion,channel:_.channel}),_.jobId){const $=await Ku(_.jobId,G=>{Xe()===T&&m(G)},void 0,void 0,T);if($.stale||Xe()!==T)return;if($.applied){window.location.reload();return}m("error"),h($.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}m(_.autoRestart?"restarting":"reconnecting");const se=await Gu(n?.currentVersion,void 0,void 0,T);if(!(se.stale||Xe()!==T)){if(se.applied){window.location.reload();return}m("error"),h(se.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),Q=Ie.useCallback(()=>{L(N)},[L,N]),O=b!=="idle"&&b!=="error",M=Ie.useMemo(()=>{if(!n?.body)return null;const T=n.body.trim();if(!T)return null;const _=qu(T);return _.length===0?{kind:"raw",title:"What's new",content:Ho(T)}:{kind:"sections",title:"What's new",sections:[..._].sort(($,G)=>Yu($.version,G.version)).map($=>({version:$.version,dateLabel:Wu($.date),content:Ho(Hu($.raw)||T)}))}},[n?.body]);return t.jsx(Ht,{open:e,onOpenChange:O?void 0:s,children:t.jsxs(Yt,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(ss,{className:"flex items-center gap-2.5",children:[t.jsx(R,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||E)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&E&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),E&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:E})]}),j&&P&&t.jsx("span",{className:"ml-3 typography-meta text-muted-foreground",children:P==="rc"?"RC subscription":"Stable subscription"})]}),t.jsxs("div",{className:"space-y-2",children:[j&&O&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),M&&!O&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ps,{className:"max-h-[400px] p-0",fillContainer:!1,children:M.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:T=>{const se=T.target.closest("a");se&&se.href&&(T.preventDefault(),T.stopPropagation(),L(se.href))},children:t.jsx(Eo,{content:M.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:M.sections.map(T=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",T.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:T.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:_=>{const $=_.target.closest("a");$&&$.href&&(_.preventDefault(),_.stopPropagation(),L($.href))},children:t.jsx(Eo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})})]},T.version))})})}),(l||g)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||g})}),j&&b==="error"&&(v??[k]).length>0&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(R,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:v?"Run these commands:":"Or update via terminal:"})]}),(v??[k]).map(T=>t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:T}),t.jsx(Te,{variant:"ghost",size:"icon",onClick:()=>{B(T)},className:f===T?"text-[var(--status-success)]":void 0,title:f===T?"Copied!":"Copy command","aria-label":f===T?"Copied!":"Copy command",children:f===T?t.jsx(R,{name:"check",className:"h-4 w-4"}):t.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},T))]}),!j&&!y&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[C,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${C}%`}})})]})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:A,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!y&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(R,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!j&&!y&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!y&&o&&t.jsxs("button",{onClick:u,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(R,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),y&&t.jsxs(Te,{onClick:Q,size:"default",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!O&&t.jsxs("button",{onClick:z,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(R,{name:"download",className:"h-4 w-4"}),"Update Now"]}),j&&O&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Qu=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(d=>{d.preventDefault(),d.stopPropagation(),!r&&!s&&n()},[s,r,n]),u=i.useCallback(d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:u,disabled:r,"aria-checked":s,"aria-label":o,className:U("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:U("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),mn=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const u=a.current;u&&c.target instanceof Node&&u.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(ze,{open:r,onOpenChange:o,children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:U("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(R,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{sideOffset:8,className:U("max-w-sm",n),children:e})]})},Cg="w-full min-w-40 max-w-48",Ag="settings",Vu="w-full min-w-40 max-w-48",Ng="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ju="w-full max-w-[24rem]",Ig="min-w-0 flex-1",Rg="flex w-full min-w-0 items-center gap-2",Eg="typography-meta shrink-0 text-muted-foreground tabular-nums",ha="space-y-3.5",Xu="space-y-1.5",Dg="typography-settings-page-title text-muted-foreground",Zu="typography-settings-section-title text-foreground",pa="typography-settings-group-title text-foreground",so="typography-settings-field-label text-foreground",ef="typography-settings-description text-muted-foreground",gn="typography-meta text-muted-foreground",Tg="typography-meta font-medium text-foreground",Pg="typography-settings-section-title text-foreground",tf=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:u,settingsItem:d})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":d,className:U("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Zu,children:e}):e,n,r!=null?t.jsx(mn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:ef,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:U(u),children:a})]})},Mg=({children:e,className:s})=>t.jsx("div",{className:U("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),sf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:U(pa,s),children:e}),Fg=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:U("space-y-2",o),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(sf,{children:e}),n!=null?t.jsx(mn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:gn,children:s}):null]}):null,t.jsx("div",{className:U(a),children:r})]}),an=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const u=s!=null?t.jsx("p",{className:gn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:U("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:so,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),r==="before"?u:null]}),t.jsx("div",{className:U("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},Og=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:U("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:so,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),s!=null?t.jsx("p",{className:U(gn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:U("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Lg=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:U("pt-4",s),children:e}),nf=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:u,info:d})=>{const f=()=>{o||s(!e)},p=r!=null;return t.jsxs("div",{"data-settings-item":l,className:U("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[t.jsx(Cr,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:so,children:n}),u,d!=null?t.jsx(mn,{children:d}):null]}),p?t.jsx("span",{className:gn,children:r}):null]})]})},Bg=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:U("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Qu,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:U("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:gn,children:r}):null]})]}),_g=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:U(Xu,n),children:s});function Ug({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:U("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Te,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}const zr="pichamber:server-update-channel-changed",zg=()=>{typeof window<"u"&&window.dispatchEvent(new Event(zr))},rf=e=>typeof window>"u"?()=>{}:(window.addEventListener(zr,e),()=>window.removeEventListener(zr,e));class of extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(oc,{className:"w-full max-w-md",children:[t.jsx(ic,{className:"text-center",children:t.jsxs(ac,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(R,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(lc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Te,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(R,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function af(e){return t.jsx(of,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const $g=({active:e=!0})=>{const s=Ee(n=>n.currentSessionId);return t.jsx(af,{sessionId:s||void 0,children:t.jsx(cc,{active:e},s??"no-session")})};function lf({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ma=Ie.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:p,...b},m)=>{const g=Ie.useRef(null),h=Ie.useRef(null),[v,x]=Ie.useState(null),I=c??v,w=Ie.useCallback(N=>{const C=g.current;if(!C)return;h.current={startY:N.clientY,startHeight:C.getBoundingClientRect().height};const j=N.currentTarget;j.setPointerCapture(N.pointerId);const y=E=>{const P=h.current;if(!P)return;const B=P.startHeight+(E.clientY-P.startY),L=Math.max(82,B);u?u(L):x(L)},k=()=>{h.current=null,j.removeEventListener("pointermove",y),j.removeEventListener("pointerup",k),j.removeEventListener("pointercancel",k)};j.addEventListener("pointermove",y),j.addEventListener("pointerup",k),j.addEventListener("pointercancel",k),N.preventDefault()},[u]),A=Ie.useCallback(N=>{if(N.target.closest('textarea, button, [role="separator"]'))return;const j=g.current?.querySelector("textarea");j&&document.activeElement!==j&&(N.preventDefault(),j.focus())},[]);return f?t.jsx(ps,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:U("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}):t.jsx("div",{ref:g,onPointerDown:A,style:I!==null?{height:`${I}px`}:void 0,className:U("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:m,className:U("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!d&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],d&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,t.jsx(lf,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});ma.displayName="Textarea";const ga=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],ln=Object.fromEntries(ga.map(e=>[e.key,e.Icon])),$r="pichamber:project-actions-updated",ba=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},es=(e,s)=>`${ba(e)}::${s}`,xa=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:u,divider:d=!0})=>t.jsx(tf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:d,className:c,contentClassName:u,children:l}),Gr=e=>e.name.trim().length>0&&e.command.trim().length>0,cf=e=>e.name.trim().length===0&&e.command.trim().length===0,df=e=>!Gr(e)&&!cf(e),uf=(e,s)=>e.some(r=>s.has(r.id)&&!Gr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Gr)},ff=450,hf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,pf=()=>({id:hf(),name:"",command:"",icon:"play"}),mf=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,u]=i.useState(new Set),d=i.useRef(!1);i.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const I=await Ar(e);if(x)return;n(I.actions),l(JSON.stringify({actions:I.actions})),u(new Set(I.actions.map(w=>w.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),u(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=i.useMemo(()=>uf(s,c),[s,c]),p=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=a!==null&&f.canPersist&&p!==a,m=i.useCallback(async x=>await dc(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),u(new Set(x.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent($r,{detail:{projectId:e.id}})),!0):(ae.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!b||r||d.current)return;const x=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await m(f.actions)}finally{d.current=!1}})())},ff);return()=>{window.clearTimeout(x)}},[b,r,m,f.actions]);const g=i.useCallback(()=>{const x=pf();n(I=>[...I,x])},[]),h=i.useCallback(x=>{n(I=>I.filter(w=>w.id!==x))},[]),v=i.useCallback((x,I)=>{n(w=>w.map(A=>A.id===x?I(A):A))},[]);return t.jsx(xa,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Te,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:g,children:[t.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:U("space-y-6",Ju),children:s.map((x,I)=>{const w=x.icon||"play",A=ln[w]||"play",N=x.name.trim()||`Action ${I+1}`,C=df(x);return t.jsxs("div",{className:ha,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:pa,children:N}),t.jsx(Te,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${N}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(an,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(R,{name:A,className:"h-4 w-4"})})}),t.jsx(Ot,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:ga.map(j=>{const y=j.Icon,k=(x.icon||"play")===j.key;return t.jsx("button",{type:"button",onClick:()=>v(x.id,E=>({...E,icon:j.key})),className:U("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",k&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:t.jsx(R,{name:y,className:"h-4 w-4"})},j.key)})})})]}),t.jsx(dn,{value:x.name,onChange:j=>v(x.id,y=>({...y,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(an,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ma,{value:x.command,onChange:j=>v(x.id,y=>({...y,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),C?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(nf,{checked:x.autoOpenUrl===!0,onChange:j=>v(x.id,y=>({...y,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${N}`}),x.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(an,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(dn,{value:x.openUrl||"",onChange:j=>v(x.id,y=>({...y,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},gf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},bf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Kt(y=>y.providers),u=Kt(y=>y.modelsMetadata),d=le(y=>y.hiddenModels),f=le(y=>y.isFavoriteModel),p=le(y=>y.toggleFavoriteModel),b=le(y=>y.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:g}=uc(),[h,v]=i.useState(!1),[x,I]=i.useState("");i.useEffect(()=>{h||I("")},[h]);const w=e?c.find(y=>y.id===e.providerId):void 0,A=e&&w?(Array.isArray(w.models)?w.models:[]).find(y=>y.id===e.modelId):void 0,N=e?fc(A,e.modelId):s,C=i.useMemo(()=>e?d.filter(y=>!(y.providerID===e.providerId&&y.modelID===e.modelId)):d,[d,e]),j=i.useCallback(y=>{l({providerId:y.providerID,modelId:y.modelID}),v(!1)},[l]);return t.jsxs(Mt,{modal:!1,open:h,onOpenChange:y=>{r||v(y)},children:[t.jsx(Ft,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:U(ki({size:"default"}),Vu,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(hc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:U("truncate",e?"text-foreground":"text-muted-foreground"),children:N})]}),t.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Ot,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(pc,{providers:c,favoriteModels:m,recentModels:g,modelsMetadata:u,searchQuery:x,onSearchQueryChange:I,onSelect:j,labels:{...gf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),v(!1)},disabled:r,autoFocus:!0,onEscape:()=>v(!1),isFavorite:y=>f(y.providerID,y.modelID),onToggleFavorite:y=>p(y.providerID,y.modelID),onReorderFavorite:(y,k)=>b(y.providerID,y.modelID,k.providerID,k.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},lr="w-full max-w-none",xf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Kt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(xa,{title:"Project",divider:!1,children:t.jsxs("div",{className:ha,children:[t.jsx(an,{label:"Name",settingsItem:"projects.name",controlClassName:lr,children:t.jsx(dn,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(an,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:lr,children:t.jsx(bf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:lr,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},yf=e=>{const[s,n]=i.useState(""),[r,o]=i.useState(void 0);i.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const a=i.useMemo(()=>mc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((d,f)=>{o(d&&f?`${d}/${f}`:void 0)},[]),u=i.useCallback(async()=>{if(!e)return null;const d=s.trim();return d?{label:d,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:u,project:e}},wf=450,vf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:a}=e,l=i.useRef(!1);i.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const u=await a();if(u)try{await s(u)}catch{ae.error("Failed to save project settings")}}finally{l.current=!1}})())},wf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},Sf=({project:e,onIdentitySave:s})=>{const n=yf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return vf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(xf,{form:n}),t.jsx(mf,{projectRef:r})]})};function no({...e}){return t.jsx(Wi,{...e})}function ro({...e}){return t.jsx(Hi,{...e})}function oo({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(Yi,{children:t.jsx(qi,{className:U("app-region-no-drag z-50",s),children:t.jsx(Qi,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:U(Ci,e),...o,children:n})})})}function Os({className:e,...s}){return t.jsx(Vi,{className:U(Ai,e),...s})}function ya({className:e,...s}){return t.jsx(Ji,{className:U(Ni,e),...s})}const An=100;function Gg(){const e=le(y=>y.isArchivePageOpen),s=le(y=>y.setArchivePageOpen),n=le(y=>y.setActiveMainTab),r=Ee(y=>y.setCurrentSession),o=Ee(y=>y.unarchiveSession),a=Bs(y=>y.homeDirectory),l=Nr({archived:!0}),[c,u]=i.useState(""),[d,f]=i.useState(null),[p,b]=i.useState(An),m=c.trim().toLowerCase(),g=i.useMemo(()=>e?[...l].sort((y,k)=>(k.time?.archived??0)-(y.time?.archived??0)):[],[l,e]),h=i.useMemo(()=>{const y=new Map;for(const k of g){const E=Ne(rn(k))??"",P=y.get(E);if(P){P.sessions.push(k);continue}y.set(E,{directory:E,label:E?_s(E,a)||E:"other projects",sessions:[k]})}return[...y.values()].sort((k,E)=>E.sessions.length-k.sessions.length)},[a,g]),v=i.useMemo(()=>m?g.filter(y=>(y.title??"").toLowerCase().includes(m)):d===null?g:h.find(y=>y.directory===d)?.sessions??[],[h,m,d,g]),x=v.slice(0,p),I=v.length-x.length,w=l.length,A=i.useCallback(y=>{f(y),b(An)},[]),N=i.useCallback(y=>{const k=Ne(rn(y));r(y.id,k??void 0),n("chat"),s(!1)},[n,r,s]),C=i.useCallback(y=>{o(y.id).then(k=>{k?ae.success("Session restored"):ae.error("Failed to restore session")})},[o]);if(!e)return null;const j=(y,k,E,P,B,L,z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:B,title:L,className:U("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:k}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),z?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>xs.requestDelete({sessions:z,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${k}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},y);return t.jsx(Gd,{open:e,onOpenChange:s,children:t.jsxs(Kd,{children:[t.jsx(Wd,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Hd,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Yd,{className:"sr-only",children:"Archived sessions"}),t.jsx(qd,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Qd,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(R,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[j("__all__","All directories",w,d===null,()=>A(null)),h.map(y=>j(y.directory||"__none__",y.label,y.sessions.length,d===y.directory,()=>A(y.directory),y.directory||void 0,y.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(R,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:y=>{u(y.target.value),b(An)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:v.length===1?`${v.length} archived session`:`${v.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[x.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:m?"No matching archived sessions":"No archived sessions"})}):x.map(y=>{const k=Ne(rn(y))??"",E=k?_s(k,a)||k:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>N(y),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),N(y))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:cs(y)}),m&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:k,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Pd(y.time?.archived??y.time?.updated??y.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),C(y)},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 ${cs(y)}`,children:t.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),xs.requestDelete({sessions:[y],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 ${cs(y)}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},y.id)}),I>0?t.jsx("button",{type:"button",onClick:()=>b(y=>y+An),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const jf=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const s=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=s+n+r;if(o<=0)return{percent:0,hasInput:!1};const a=Math.max(0,n);return{percent:Math.min(100,Math.max(0,a/o*100)),hasInput:!0}},kf=e=>{if(!e||typeof e!="object")return 0;const s=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return s+n+r},Wt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Cf=e=>{if(!e||typeof e!="object")return null;const s=Wt(e.input),n=Wt(e.output),r=Wt(e.cacheRead),o=Wt(e.cacheWrite);return{input:s,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:s+n+r+o}},Yo=e=>{const s=Cf(e.info.usage);if(s)return s;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Wt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,a=Wt(o.input),l=Wt(o.output),c=Wt(o.reasoning),u=Wt(o.cache?.read),d=Wt(o.cache?.write);return{input:a,output:l,reasoning:c,cacheRead:u,cacheWrite:d,total:a+l+c+u+d}},wa=380,cr=8,Af=140;function Nf({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[u,d]=i.useState(!1),[f,p]=i.useState(null),{enabled:b}=Qr();return i.useLayoutEffect(()=>{if(!e||!b||!l)return;const m=()=>{const v=n.current?.getBoundingClientRect(),x=a.current?.getBoundingClientRect();if(!v||!x){p(null);return}const I=v.left-x.left;p(Math.min(Math.max(I,cr),Math.max(cr,x.width-wa-cr)))};m();const g=a.current;if(typeof ResizeObserver>"u"||!g)return;const h=new ResizeObserver(m);return h.observe(g),()=>h.disconnect()},[n,b,e,l]),i.useEffect(()=>{if(e){c(!0),d(!1);return}if(!l)return;d(!0);const m=window.setTimeout(()=>{c(!1),d(!1)},Af);return()=>window.clearTimeout(m)},[e,l]),i.useEffect(()=>{if(!e)return;const m=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[s,e]),i.useEffect(()=>{if(!e)return;const m=g=>{const h=g.target;if(!(h instanceof Node)){s();return}o.current?.contains(h)||n.current?.contains(h)||s()};return document.addEventListener("pointerdown",m,!0),r&&document.addEventListener("wheel",m,!0),()=>{document.removeEventListener("pointerdown",m,!0),r&&document.removeEventListener("wheel",m,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:u,anchorLeft:f,isPopover:b&&f!==null}}const qo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},zn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Nn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(R,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),If=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:u,isPopover:d}=Nf({open:e,onClose:s,anchorRef:n,closeOnWheel:!0});return l?t.jsxs("div",{ref:a,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:U("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",d?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...d?{top:8,left:u??8,width:`min(${wa}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{iconNode:t.jsx(Ii,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:U("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:zn(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:zn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Nn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BUxQG4Eq.js","assets/useAppFontEffects-CDmJGQlK.js","assets/index-BOtRfXre.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BXgR2dKM.css","assets/vendor-base-ui-DXSHfszQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CPm7KWaN.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-D09wcguI.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-CNlncqrr.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-B6RnDAuP.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-B4e2b2Bv.js","assets/isDiffPlainText-r5sF6_KV.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-CUyTFUnd.js"])))=>i.map(i=>d[i]);
2
+ import{_ as ls}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ie,j as t,R as i,b as sc}from"./vendor-react-B5Z1Mdn3.js";import{aP as Ms,aQ as nc,Q as rc,a1 as Mt,a2 as ze,a3 as $e,a4 as Ft,B as Te,I as R,a5 as Ge,a6 as Ot,a8 as rt,t as ae,a as pt,e as Ee,Z as $s,ad as dn,aR as Si,af as Ht,ag as Yt,ah as ds,ai as ss,aj as us,ak as Ss,aF as xs,aS as ys,g as Ps,aT as or,aU as Io,aV as Ro,aW as nn,o as ji,ae as ps,aX as Eo,a7 as ws,aY as Cr,aZ as oc,a_ as ic,a$ as ac,b0 as lc,b1 as cc,b2 as Ar,b3 as dc,x as Kt,b4 as uc,b5 as fc,b6 as hc,b7 as ki,b8 as pc,b9 as mc,ba as Ci,bb as Ai,bc as Ni,aC as Nr,r as rn,m as Qr,ao as gc,ay as bc,aB as Ii,K as js,d as Vr,aa as Gs,ax as Ri,bd as Yn,be as Do,bf as ht,aD as Ei,bg as Di,at as xc,f as Ti,i as yc,bh as wc,h as vc,bi as Es,b as To,c as Sc,bj as jc,u as kc,aE as Cc,aH as Ac,bk as Ir,bl as Nc,bm as Ic,aG as Rc,bn as Ec,bo as Dc,T as Tc,a9 as vs,al as Pi,v as Pc,ab as Mc,bp as Fc,bq as Oc,j as Lc,br as Bc,bs as Mi,bt as _c,bu as Uc,bv as zc,bw as $c,bx as Gc,by as Kc,bz as Wc,bA as Hc,bB as Yc,bC as qc}from"./useAppFontEffects-CDmJGQlK.js";import{Z as Po,_ as Qc,$ as Mo,a0 as Vc,i as Jc,a1 as Xc,S as Zc,m as Nt,a2 as un,b as ed,a3 as td,R as Ls,a4 as Fi,a5 as Oi,a6 as sd,a7 as nd,q as Bs,K as rd,a8 as od,a9 as id,aa as ad,ab as Xt,v as Zt,ac as ld,ad as cd,ae as dd,af as Jr,ag as ud,ah as fd,ai as hd,u as le,o as U,aj as pd,f as Xe,B as Ne,ak as _s,al as Pt,am as Fo,an as Rr,a as Xr,T as Zr,U as Bn,ao as md,ap as gd,aq as Li,F as bd,Q as Bi,C as on,ar as Er,h as Dr,d as kn,as as xd,at as yd,au as Oo,av as Xs,aw as ir,ax as Tr,ay as ms,az as Lo,aA as Pr,aB as _i,aC as Mr,aD as wd,aE as vd,aF as Sd,aG as jd,aH as kd,aI as Cd,aJ as Ad,z as Nd,aK as Id,aL as Rd,Y as Ui,P as Ed,J as Dd}from"./index-BOtRfXre.js";import{c as ks,d as zi,p as eo,u as Fr,a as Td}from"./vendor-zustand-GVb4H8HE.js";import{g as cs,b as Pd,c as $i,r as Md,d as Gi,s as Tn,e as Ki,h as fn,i as hn,j as Fd,k as Od,l as Ld,m as Bo,n as qn,f as Bd,a as _d,S as Ud,t as zd,o as $d}from"./SessionUnreadDot-CY3rTilj.js";import{C as Wi,a as Hi,M as Yi,b as qi,c as Qi,d as Vi,S as Ji,D as Gd,e as Kd,f as Wd,g as Hd,h as Yd,i as qd,j as Qd}from"./vendor-base-ui-DXSHfszQ.js";import{c as Xi,d as Or,P as Vd,D as Zi,e as ea,f as Jd,b as Xd,a as Zd,T as eu,M as tu}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{u as su}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as nu,v as ru,u as ou}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as iu}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-xterm-xterm-CrXqRur4.js";import{usePermissionStore as au}from"./permissionStore-iKN1K2_x.js";const lu="chat";function ta(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ms.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ms.SETTINGS,n),s}return e.tab!==lu&&s.set(Ms.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ms.FILE,e.diffFile),s}function cu(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function du(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=ta(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ms.SESSION)&&s.set(Ms.SESSION,o);const a=[...s.entries()].sort((c,u)=>c[0].localeCompare(u[0])),l=[...n.entries()].sort((c,u)=>c[0].localeCompare(u[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Lr(e,s={}){if(!(typeof window>"u")&&!(!s.force&&du(e)))try{const n=ta(e),r=cu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const uu=["typescript","javascript","tsx","jsx","json","markdown"],sa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let _o=null;const na=()=>(_o??=Promise.all([ls(()=>import("./index-BUxQG4Eq.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])),ls(()=>import("./workerFactory-tw7cIdmV.js"),[]),ls(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([110,111,97,98,24,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),_o),pn={},Uo=new Set,Br=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const fu=()=>{for(const e of Br)e()},ra=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:sa[e].lineDiffType})},_r=e=>{typeof window>"u"||Uo.has(e)||(Uo.add(e),na().then(s=>{if(pn[e])return;const n=sa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:uu,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),pn[e]=r,ra(e,r),fu()}))},hu=e=>(Br.add(e),()=>Br.delete(e)),pu=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(pn)){const n=pn[s];n&&ra(s,n)}}},gg=({children:e})=>{const s=nc(),n=Po(!1),r=Po(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(u=>u.metadata.id===o)??n,c=s?.availableThemes.find(u=>u.metadata.id===a)??r;return Ie.useEffect(()=>{let u=!1;return na().then(d=>{u||(d.ensurePierreThemeRegistered(l),d.ensurePierreThemeRegistered(c),pu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,l]),Ie.useEffect(()=>{if(typeof window>"u")return;const u=()=>{_r("unified"),_r("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(u,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const d=window.setTimeout(u,2e3);return()=>window.clearTimeout(d)},[]),t.jsx(t.Fragment,{children:e})},bg=(e="unified")=>{const s=Ie.useSyncExternalStore(hu,()=>pn[e],()=>{});return Ie.useEffect(()=>{_r(e)},[e]),s};function mu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=rc();return e}catch{return"unknown"}}function gu(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function bu(){const e=ed();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function xu(e){const s=new URLSearchParams;return s.set("deviceClass",mu()),s.set("arch",gu()),s.set("platform",bu()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",un()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ar(e,s){try{const n=xu(e);s&&n.set("currentVersion",s);const r=await Nt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand,channel:o.channel==="rc"?"rc":"stable"}}catch(n){return console.warn("Failed to check for updates:",n),null}}function yu(){return Jc()?"mobile":Xc()?"desktop":Zc()?"web":null}const zo={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=ks()((e,s)=>({...zo,checkForUpdates:async()=>{const n=yu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.9.9",[l,c]=await Promise.allSettled([Mo(),ar("desktop",a)]),u=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:u?.available??!1,info:u,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ar("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ar("mobile","0.9.9"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await Mo();if(!o?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await Vc(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Qc())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(zo)}})),wu={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},vu={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 oa(e){return e&&vu[e]||"var(--primary)"}const $o=({icon:e,className:s,colorToken:n})=>{const r=wu[e??"branch"]??"user-3";return t.jsx(R,{name:r,className:s,style:{color:oa(n)}})},Su=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Mt,{children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Ft,{asChild:!0,children:t.jsxs(Te,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:oa(e?.color)},disabled:a,children:[r?t.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx($o,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(R,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Ge,{sideOffset:8,children:"Git identity"})]}),t.jsx(Ot,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(rt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx($o,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(R,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},ju=e=>e==="/",Us=e=>e.replace(/\\/g,"/"),zs=e=>{if(!e||ju(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),_n=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},to=e=>e.lastIndexOf("/"),ia=e=>{if(Fs(e))return e;const s=to(e);return s<0?e:e.slice(0,s+1)},aa=e=>{const s=to(e);return e.slice(s+1)},la=e=>{const s=zs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=to(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},ca=e=>Fs(e)&&la(e)!==null,ku=e=>{if(!ca(e))return null;const s=zs(e.trim());return aa(s)||s},Cu=(e,s)=>`${ia(e)}${s}/`,gs=e=>{if(!e)return null;const s=zs(Us(e.trim()));return s?s.toLowerCase():null},Go=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},Au=(e,s)=>{const n=zs(Us(e.trim())),r=zs(Us(s.trim()));if(!n)return"";if(!r)return _n(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:_n(n)},Nu=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Ur=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Iu=async()=>td(),Ru=()=>{const[e,s]=Ie.useState(!1),[n,r]=Ie.useState(!1);Ie.useEffect(()=>{s(Ls()),r(Fi())},[]);const o=Ie.useCallback(async c=>e?await Oi(c):{success:!0,path:c},[e]),a=Ie.useCallback(async c=>e?await sd():{success:!0},[e]),l=Ie.useCallback(async c=>e?await nd():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function Eu({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Bs(ne=>ne.homeDirectory),{canRequestAccess:o,startAccessing:a}=Ru(),l=i.useRef(null),c=i.useRef(new Map),[u,d]=i.useState(""),[f,p]=i.useState("~/"),[b,m]=i.useState([]),[g,h]=i.useState(!1),[v,x]=i.useState(!1),[I,w]=i.useState(null),[A,N]=i.useState(0),[C,j]=i.useState(0),[y,k]=i.useState(!1),[E,P]=i.useState(!1),[B,L]=i.useState("right"),z=i.useRef("~/"),Q=u||r;i.useEffect(()=>{if(!e)return;p("~/"),m([]),j(0),k(!1),P(!1),z.current="~/",L("right"),n||requestAnimationFrame(()=>Ur(l.current));let ne=!1;return(async()=>{const q=await Iu();ne||(d(q||r||""),n||requestAnimationFrame(()=>Ur(l.current)))})(),()=>{ne=!0}},[r,e,n]);const O=i.useMemo(()=>ia(f),[f]),M=i.useMemo(()=>Fs(f)?"":aa(f),[f]),T=i.useMemo(()=>Q?Go(O,Q):"",[O,Q]);i.useEffect(()=>{const ne=z.current;ne!==O&&(L(O.length>=ne.length?"right":"left"),z.current=O)},[O]),i.useEffect(()=>{if(!e||!T){m([]),w(null);return}let ne=!1;return h(!0),x(!1),w(null),rd(T).then(ce=>{if(ne)return;x(!1),w(null);const q=ce.filter(fe=>fe.isDirectory).map(fe=>({name:fe.name,path:Us(fe.path)})).sort((fe,_e)=>fe.name.localeCompare(_e.name));m(q)}).catch(ce=>{if(!ne){m([]);const q=od(ce)?ce.reason:"unknown";w(q),x(q==="not-found")}}).finally(()=>{ne||h(!1)}),()=>{ne=!0}},[T,A,e]);const _=i.useMemo(()=>{const ne=M.toLowerCase(),ce=E||M.startsWith(".");return b.filter(q=>q.name.toLowerCase().startsWith(ne)&&(ce||!q.name.startsWith(".")))},[M,b,E]),se=i.useMemo(()=>ku(f),[f]),$=i.useMemo(()=>la(f),[f]),G=i.useMemo(()=>{const ne=[],ce=gs(T);ca(f)&&se&&$&&ne.push({type:"parent",value:"browse:up",name:se,path:$,alreadyAdded:!!(ce&&s.has(ce))});for(const q of _){const fe=gs(q.path);ne.push({type:"directory",value:`browse:${q.path}`,name:q.name,path:q.path,alreadyAdded:!!(fe&&s.has(fe))})}return ne},[s,T,se,_,$,f]);i.useEffect(()=>{j(0)},[f,G.length]);const Ae=i.useMemo(()=>Q?zs(Go(f,Q)):"",[Q,f]),te=gs(Ae),Pe=!!(te&&s.has(te)),Be=i.useMemo(()=>M?_.find(ne=>ne.name===M)??null:null,[M,_]),Y=!!(Ae&&!Pe&&(I===null||I==="not-found")&&(Fs(f)&&v||!Fs(f)&&M.trim().length>0&&Be===null)),F=G[C]??null,K=!!F,J=i.useCallback(ne=>{p(_n(ne))},[]),Z=i.useCallback(ne=>{p(Cu(f,ne.name))},[f]),pe=i.useCallback(ne=>{if(ne){if(ne.type==="parent"){J(ne.path);return}Z(ne)}},[J,Z]),Se=i.useCallback(async ne=>{const ce=await a(ne);if(!ce.success)return ae.error("Failed to open directory",{description:ce.error||"Desktop could not grant file access."}),!1;const q=Q?Au(ne,Q):_n(Us(ne));return J(q),!0},[J,Q,a]),xe=i.useCallback(async()=>{if(!y){k(!0);try{if(Fi()){const ce=await Oi(Ae);if(!ce.success||!ce.path){ce.error&&ce.error!=="Directory selection cancelled"&&ae.error("Failed to select directory",{description:ce.error});return}await Se(ce.path);return}const ne=await id(Ae);if(ne.status==="cancelled")return;if(ne.status!=="picked"){ae.error("Couldn't open a folder picker",{description:ne.error});return}await Se(ne.path)}catch(ne){ae.error("Failed to select directory",{description:ne instanceof Error?ne.message:"Unknown error occurred."})}finally{k(!1)}}},[Se,y,Ae]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:g,isBrowseDirectoryMissing:v,browseErrorReason:I,browseReloadKey:A,setBrowseReloadKey:N,highlightedIndex:C,setHighlightedIndex:j,isPickingLocation:y,showHidden:E,setShowHidden:P,folderEnterFrom:B,explorerRootDirectory:Q,browseDirectoryDisplayPath:O,browseDirectoryAbsolutePath:T,browseFilterQuery:M,filteredEntries:_,rows:G,targetPath:Ae,isAlreadyAdded:Pe,shouldCreateTarget:Y,highlightedRow:F,hasHighlightedBrowseItem:K,canRequestAccess:o,browseToDisplayPath:J,browseToEntry:Z,executeRow:pe,applyPickedLocation:Se,handleBrowseLocation:xe}}const hs=ks()(zi(eo((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=Zt()?.git,o=r?await r.getGitIdentities():await hd();return e({profiles:o,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=Zt()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await fd();if(r&&r.userName&&r.userEmail){const o={id:"global",name:"Global Identity",userName:r.userName,userEmail:r.userEmail,authType:r.sshCommand?"ssh":void 0,sshKey:r.sshCommand?r.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:o})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=Zt()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await ud();return e({discoveredCredentials:r}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const o=r.trim();return o.length>0?o:null};try{let r=null;if(r===null){const o=Zt()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Nt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Jr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};Xt("saving");const o=Zt()?.git;return o?await o.createGitIdentity(r):await dd(r),Xt("saved"),await s().loadProfiles(),!0}catch(r){return Xt("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(c=>c.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};Xt("saving");const l=Zt()?.git;return l?await l.updateGitIdentity(n,a):await cd(n,a),Xt("saved"),await s().loadProfiles(),!0}catch(o){return Xt("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{Xt("saving");const r=Zt()?.git;return r?await r.deleteGitIdentity(n):await ld(n),Xt("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return Xt("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:o}=s();return n==="global"?o||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(o=>!n.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:ad(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=hs);function Du({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:u,isPickingLocation:d}){const f=pt($=>$.addProject),p=le($=>$.setActiveMainTab),b=le($=>$.setSessionSwitcherOpen),m=Ee($=>$.openNewSessionDraft),g=hs($=>$.profiles),h=hs($=>$.globalIdentity),v=hs($=>$.defaultGitIdentityId),x=hs($=>$.loadProfiles),I=hs($=>$.loadGlobalIdentity),w=hs($=>$.loadDefaultGitIdentityId),[A,N]=i.useState(!1),[C,j]=i.useState(!1),[y,k]=i.useState(""),[E,P]=i.useState(null);i.useEffect(()=>{e&&(N(!1),j(!1),k(""),P(null))},[e]),i.useEffect(()=>{e&&(x(),I(),w())},[w,x,I,e]);const B=i.useMemo(()=>{const $=new Map;h&&$.set(h.id,h);for(const G of g)$.set(G.id,G);return Array.from($.values())},[g,h]);i.useEffect(()=>{if(!e||!C||E!==null)return;const $=typeof v=="string"?v.trim():"";if($&&B.some(Ae=>Ae.id===$)){P($);return}const G=B.find(Ae=>Ae.authType==="ssh"||Ae.sshKey);G&&P(G.id)},[B,v,C,e,E]);const L=i.useMemo(()=>B.find($=>$.id===E)??null,[B,E]),z=i.useCallback(($,G)=>{p("chat"),n&&b(!1),m({selectedProjectId:$,directoryOverride:G}),s()},[n,s,m,p,b]),Q=i.useCallback(async $=>{if(!$||A)return;const G=gs($);if(G&&r.has(G))return;let Ae=$;N(!0);try{const te=!C&&a&&gs($)===gs(o);if(C){const Be=y.trim();if(!Be){ae.error("Enter a repository URL before cloning.");return}const Y=await Nt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:Be,destinationPath:$,gitIdentityId:L?.id??null})});if(!Y.ok)throw new Error("Failed to clone git repository");Ae=(await Y.json()).path||$}else if(te&&!(await Nt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:$})})).ok)throw new Error("Failed to select directory");const Pe=f(Ae);if(!Pe){ae.error("Failed to add folder",{description:"Please select a valid directory path."});return}z(Pe.id,Pe.path)}catch(te){ae.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{N(!1)}},[f,r,c,y,C,A,z,L?.id,a,o]),O=!A&&!d&&!u&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,M=O&&y.trim().length>0,T=C?M:O,_=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:A,isCloneMode:C,setIsCloneMode:j,cloneRemoteUrl:y,setCloneRemoteUrl:k,selectedGitIdentityId:E,setSelectedGitIdentityId:P,availableGitIdentities:B,selectedGitIdentity:L,canSubmit:T,submitActionLabel:u?"Already added":C?A?"Cloning...":"Clone & add":A?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:_,finalizeSelection:Q}}const Tu=({open:e,onOpenChange:s})=>{const n=pt(q=>q.projects),{isMobile:r,isTablet:o}=$s(),a=r||o,l=i.useMemo(()=>new Set(n.map(q=>gs(q.path)).filter(q=>!!q)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:u,rowRefs:d,query:f,setQuery:p,isLoading:b,browseErrorReason:m,setBrowseReloadKey:g,highlightedIndex:h,setHighlightedIndex:v,isPickingLocation:x,showHidden:I,setShowHidden:w,folderEnterFrom:A,browseDirectoryDisplayPath:N,browseDirectoryAbsolutePath:C,rows:j,targetPath:y,isAlreadyAdded:k,shouldCreateTarget:E,highlightedRow:P,hasHighlightedBrowseItem:B,canRequestAccess:L,executeRow:z,handleBrowseLocation:Q}=Eu({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:O,isCloneMode:M,setIsCloneMode:T,cloneRemoteUrl:_,setCloneRemoteUrl:se,setSelectedGitIdentityId:$,availableGitIdentities:G,selectedGitIdentity:Ae,canSubmit:te,submitActionLabel:Pe,submitModifierLabel:Be,finalizeSelection:Y}=Du({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:y,shouldCreateTarget:E,browseErrorReason:m,browseDirectoryAbsolutePath:C,isAlreadyAdded:k,isPickingLocation:x});i.useLayoutEffect(()=>{const q=u.current;q&&(q.scrollLeft=q.scrollWidth)},[u,f]),i.useLayoutEffect(()=>{!e||a||Ur(u.current)},[u,e,a]),i.useLayoutEffect(()=>{const q=j[h];q&&d.current.get(q.value)?.scrollIntoView({block:"nearest"})},[h,d,j]);const F=i.useCallback(q=>{if(q.key==="ArrowDown"){q.preventDefault(),v(fe=>Math.min(j.length-1,fe+1));return}if(q.key==="ArrowUp"){q.preventDefault(),v(fe=>Math.max(0,fe-1));return}if(q.key==="Enter"){if(q.preventDefault(),Nu(q)){Y(y);return}B&&z(P);return}q.key==="Backspace"&&f===""&&(q.preventDefault(),c())},[z,Y,c,B,P,f,j.length,v,y]),K=t.jsxs("button",{type:"button",onClick:()=>w(q=>!q),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[I?t.jsx(R,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),J=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(R,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(dn,{ref:u,value:f,onChange:q=>p(Us(q.target.value)),onKeyDown:F,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Te,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:O||x,onMouseDown:q=>q.preventDefault(),onClick:()=>{Q()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(R,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),Z=j.some(q=>q.type==="parent"),pe=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Te,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":M,disabled:O||x,onClick:()=>T(q=>!q),children:[t.jsx(R,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),M?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(dn,{value:_,onChange:q=>se(q.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(Su,{activeProfile:Ae,identities:G,onSelect:q=>$(q.id),isApplying:O,iconOnly:!0})]})]}):null,k?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:U("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",A==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:b?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):m&&m!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:m==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[m==="os-permission"&&L?t.jsx(Te,{size:"xs",onClick:()=>{Q()},disabled:x,children:"Grant access"}):null,t.jsx(Te,{variant:"outline",size:"xs",onClick:()=>g(q=>q+1),children:"Try again"})]})]}):j.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:j.map((q,fe)=>{const _e=fe===h,W=q.type==="directory"&&Z;return t.jsxs("button",{ref:X=>{X?d.current.set(q.value,X):d.current.delete(q.value)},type:"button","aria-label":q.type==="parent"?q.alreadyAdded?`Go back from ${q.name}, already added`:`Go back from ${q.name}`:q.alreadyAdded?`Open ${q.name}, already added`:`Open ${q.name}`,onMouseEnter:()=>v(fe),onMouseDown:X=>X.preventDefault(),onClick:()=>z(q),className:U("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",_e&&"bg-interactive-selection text-interactive-selection-foreground",!_e&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:U("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[q.type==="parent"?t.jsx(R,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(R,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:q.name})]}),q.alreadyAdded?t.jsx("span",{className:U("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",_e?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,q.type==="parent"?t.jsx(R,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(R,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},q.value)})})},N)]})}),Se=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[J,pe]}),xe=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(R,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(R,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:Be}),t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),ne=t.jsx(Te,{size:r?"xs":"default",onClick:()=>{Y(y)},disabled:!te,className:U(r&&"w-full flex-1"),children:Pe}),ce=()=>t.jsxs(t.Fragment,{children:[r?null:xe,t.jsx("div",{className:U("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:ne})]});return r?t.jsx(Si,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ce()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:K}),Se]})}):t.jsx(Ht,{open:e,onOpenChange:s,children:t.jsxs(Yt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(ds,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(ss,{children:"Add folder"}),t.jsx(us,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),K]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Se}),t.jsx(Ss,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ce()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,xg=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=Ee(C=>C.deleteSession),c=Ee(C=>C.deleteSessions),u=le(C=>C.showDeletionDialog),d=le(C=>C.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:b}=$s(),m=f||p||b;i.useEffect(()=>pd(()=>{s(!1)}),[]);const g=i.useCallback(C=>{r({sessions:C.sessions,dateLabel:C.dateLabel})},[]),h=i.useCallback(()=>{r(null),a(!1)},[]),v=i.useCallback(async C=>{if(C.sessions.length===0)return;if(C.sessions.length===1){const E=C.sessions[0];await l(E.id)?ae.success("Session deleted"):ae.error("Failed to delete session");return}const j=C.sessions.map(E=>E.id),{deletedIds:y,failedIds:k}=await c(j);if(y.length>0){const E=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:C.dateLabel?`Removed all sessions from ${C.dateLabel}.`:void 0;ae.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:Cn(E)})}k.length>0&&ae.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>xs.onDeleteRequest(C=>{if(!u){v(C);return}g(C)}),[g,u,v]),i.useEffect(()=>xs.onDirectoryRequest(()=>{s(!0)}),[]);const x=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const C=n.sessions[0];if(!await l(C.id)){ae.error("Failed to delete session"),a(!1);return}ae.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const C=n.sessions.map(E=>E.id),j=await c(C),y=j.deletedIds,k=j.failedIds;if(y.length>0){const E=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ae.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:Cn(E),action:{label:"OK",onClick:()=>{}}})}if(k.length>0&&(ae.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:Cn("Please try again in a moment.")}),y.length===0)){a(!1);return}}h()}finally{a(!1)}}},[n,l,c,h]),I=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",w=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(C=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:cs(C)})},C.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>d(!u),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!u,children:[u?t.jsx(R,{name:"checkbox-blank",className:"size-4"}):t.jsx(R,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Te,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),t.jsx(Te,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),N=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(Si,{open:!!n,onClose:()=>{o||h()},title:N,footer:t.jsx("div",{className:"flex justify-end gap-2",children:A}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),w]})}):t.jsx(Ht,{open:!!n,onOpenChange:C=>{if(!C){if(o)return;h()}},children:t.jsxs(Yt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:N}),I&&t.jsx(us,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),t.jsx(Ss,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),t.jsx(Tu,{open:e,onOpenChange:s})]})},yg=()=>{const e=ys(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(ys.getState().markNotificationSent(s.key),ae.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},Pu=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Mu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Fu(e){const s=e.trim().toLowerCase();return Pu.find(n=>n.slug===s)??null}function Ou(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=Mu[s];if(n)return n;const r=Fu(s);return r?r.slug:"home"}function wg(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"snippets":return"chat-thread";case"prompt-templates":return"terminal";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}function vg(){const e=i.useRef(!1),s=i.useRef(!1),n=Ee(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),a=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=Ee.getState().currentSessionId,b=Ps().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==b){const m=Ee.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,m)}}if(f.settingsPath){a(Ou(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,o,a,l]),u=i.useCallback(()=>{const f=Ee.getState(),p=Ps().getState(),b=le.getState();return{sessionId:or({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),d=i.useCallback((f={})=>{if(s.current)return;const p=u();Lr(p,f)},[u]);i.useEffect(()=>{if(e.current||(e.current=!0,!Io()))return;const f=Ro();(async()=>(await c(f),Lr({...u(),sessionId:f.sessionId??or({currentSessionId:Ee.getState().currentSessionId,piSelectedSessionId:Ps().getState().selectedSessionId,draft:Ee.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),i.useEffect(()=>{const f=()=>{const v=Ee.getState(),x=Ps().getState();return or({currentSessionId:v.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:v.newSessionDraft})};let p=f(),b=Ee.getState().newSessionDraft?.open===!0;const m=()=>{const v=Ee.getState(),x=f(),I=v.newSessionDraft?.open===!0;x===p&&I===b||s.current||(p=x,b=I,d({replace:!0}))},g=Ee.subscribe(()=>{m()}),h=Ps().subscribe(()=>{m()});return()=>{g(),h()}},[d]),i.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,b=le.getState().settingsPage,m=le.getState().pendingDiffFile;return le.subscribe(h=>{if(s.current)return;const v=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==p,I=h.settingsPage!==b,w=h.pendingDiffFile!==m&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,b=h.settingsPage,m=h.pendingDiffFile,(v||x||I||w)&&d()})},[d]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Ro();if(Io())c(p);else{const b=le.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function Lu(e=!0){const s=Mn(r=>r.checkForUpdates),n=i.useRef(s);i.useEffect(()=>{n.current=s},[s]),i.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,u=null;const d=p=>{const b=Math.round(p*1e3);return Math.max(a,Math.min(l,b))},f=p=>{c||(u=window.setTimeout(async()=>{const b=await n.current(),m=typeof b=="number"&&Number.isFinite(b)?d(b):o;f(m)},p))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function Sg(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return Lu(e),null}const Ko=12,Bu=[{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"}],_u=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=Bu,onComplete:a})=>{const l=Ie.useRef(!1);Ie.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ie.useMemo(()=>Array.from({length:Ko},(u,d)=>{const f=Math.PI*2*d/Ko;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?t.jsx("div",{className:U("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(u=>{const d={"--burst-delay":`${u.delay}ms`,"--burst-x":`${u.x}%`,"--burst-y":`${u.y}%`,"--firework-color":`var(${u.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:d,children:c.map((f,p)=>{const b=f.x*u.radius,m=f.y*u.radius,g={"--translate-x":`${b}px`,"--translate-y":`${m}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return t.jsx("span",{className:"firework-particle",style:g},`${u.id}-${p}-${s}`)})},`${u.id}-${s}`)})}):null},Uu=({durationMs:e=3400}={})=>{const[s,n]=Ie.useState({isActive:!1,cycle:0}),r=Ie.useRef(null),o=Ie.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ie.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ie.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Ie.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},da=i.createContext(void 0),jg=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Uu(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(da.Provider,{value:a,children:[e,t.jsx(_u,{isActive:s,burstKey:n})]})},zu={triggerFireworks:()=>{},dismissFireworks:()=>{}},kg=()=>i.useContext(da)??zu,Un=2e3,ua=600*1e3;async function $u(){try{const e=await Nt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const s=await e.json().catch(()=>({}));return{success:!0,autoRestart:s.autoRestart!==!1,jobId:typeof s.jobId=="string"?s.jobId:void 0,channel:s.channel==="rc"?"rc":s.channel==="stable"?"stable":void 0,targetVersion:typeof s.targetVersion=="string"?s.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Gu(e,s=Math.ceil(ua/Un),n=Un,r=Xe()){for(let o=0;o<s;o++){if(Xe()!==r)return{applied:!1,stale:!0};try{const a=await Nt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==r)return{applied:!1,stale:!0};if(a.ok){const l=await a.json().catch(()=>null);if(Xe()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Xe()!==r)return{applied:!1,stale:!0}}await new Promise(a=>setTimeout(a,n))}return{applied:!1}}async function Ku(e,s,n=Math.ceil(ua/Un),r=Un,o=Xe()){for(let a=0;a<n;a++){if(Xe()!==o)return{applied:!1,stale:!0};try{const l=await Nt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Xe()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?s("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&s("updating")}else{if(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Xe()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};s("reconnecting")}else s("reconnecting")}}catch{if(Xe()!==o)return{applied:!1,stale:!0};s("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Wo="https://github.com/RyderAsKing/PiChamber/releases";function Wu(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function Hu(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Ho(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Yu(e,s){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(a!==l)return l-a}return 0}function qu(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const fa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,p]=Ie.useState(null),[b,m]=Ie.useState("idle"),[g,h]=Ie.useState(null),[v,x]=Ie.useState(null),[I,w]=Ie.useState({}),A=n?.version?n.releaseUrl||`${Wo}/tag/v${n.version}`:Wo,N=n?.downloadUrl||A,C=a?.total?Math.round(a.downloaded/a.total*100):0,j=d==="web",y=d==="mobile",k=n?.updateCommand||"pichamber update",E=I.version||n?.version,P=I.channel||n?.channel;Ie.useEffect(()=>{e||(m("idle"),h(null),x(null),w({}))},[e]);const B=async(T=k)=>{(await ws(T)).ok&&(p(T),setTimeout(()=>p(null),2e3))},L=Ie.useCallback(async T=>{await ji(T)},[]),z=Ie.useCallback(async()=>{const T=Xe();m("updating"),h(null),x(null),w({});const _=await $u();if(Xe()!==T)return;if(!_.success){m("error"),h(_.error||"Update failed"),x(_.commands??null);return}if(w({version:_.targetVersion,channel:_.channel}),_.jobId){const $=await Ku(_.jobId,G=>{Xe()===T&&m(G)},void 0,void 0,T);if($.stale||Xe()!==T)return;if($.applied){window.location.reload();return}m("error"),h($.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}m(_.autoRestart?"restarting":"reconnecting");const se=await Gu(n?.currentVersion,void 0,void 0,T);if(!(se.stale||Xe()!==T)){if(se.applied){window.location.reload();return}m("error"),h(se.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),Q=Ie.useCallback(()=>{L(N)},[L,N]),O=b!=="idle"&&b!=="error",M=Ie.useMemo(()=>{if(!n?.body)return null;const T=n.body.trim();if(!T)return null;const _=qu(T);return _.length===0?{kind:"raw",title:"What's new",content:Ho(T)}:{kind:"sections",title:"What's new",sections:[..._].sort(($,G)=>Yu($.version,G.version)).map($=>({version:$.version,dateLabel:Wu($.date),content:Ho(Hu($.raw)||T)}))}},[n?.body]);return t.jsx(Ht,{open:e,onOpenChange:O?void 0:s,children:t.jsxs(Yt,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(ss,{className:"flex items-center gap-2.5",children:[t.jsx(R,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||E)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&E&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),E&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:E})]}),j&&P&&t.jsx("span",{className:"ml-3 typography-meta text-muted-foreground",children:P==="rc"?"RC subscription":"Stable subscription"})]}),t.jsxs("div",{className:"space-y-2",children:[j&&O&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),M&&!O&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ps,{className:"max-h-[400px] p-0",fillContainer:!1,children:M.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:T=>{const se=T.target.closest("a");se&&se.href&&(T.preventDefault(),T.stopPropagation(),L(se.href))},children:t.jsx(Eo,{content:M.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:M.sections.map(T=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",T.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:T.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:_=>{const $=_.target.closest("a");$&&$.href&&(_.preventDefault(),_.stopPropagation(),L($.href))},children:t.jsx(Eo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})})]},T.version))})})}),(l||g)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||g})}),j&&b==="error"&&(v??[k]).length>0&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(R,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:v?"Run these commands:":"Or update via terminal:"})]}),(v??[k]).map(T=>t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:T}),t.jsx(Te,{variant:"ghost",size:"icon",onClick:()=>{B(T)},className:f===T?"text-[var(--status-success)]":void 0,title:f===T?"Copied!":"Copy command","aria-label":f===T?"Copied!":"Copy command",children:f===T?t.jsx(R,{name:"check",className:"h-4 w-4"}):t.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},T))]}),!j&&!y&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[C,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${C}%`}})})]})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:A,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!y&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(R,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!j&&!y&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!y&&o&&t.jsxs("button",{onClick:u,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(R,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),y&&t.jsxs(Te,{onClick:Q,size:"default",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!O&&t.jsxs("button",{onClick:z,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(R,{name:"download",className:"h-4 w-4"}),"Update Now"]}),j&&O&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Qu=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(d=>{d.preventDefault(),d.stopPropagation(),!r&&!s&&n()},[s,r,n]),u=i.useCallback(d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:u,disabled:r,"aria-checked":s,"aria-label":o,className:U("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:U("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),mn=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const u=a.current;u&&c.target instanceof Node&&u.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(ze,{open:r,onOpenChange:o,children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:U("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(R,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{sideOffset:8,className:U("max-w-sm",n),children:e})]})},Cg="w-full min-w-40 max-w-48",Ag="settings",Vu="w-full min-w-40 max-w-48",Ng="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ju="w-full max-w-[24rem]",Ig="min-w-0 flex-1",Rg="flex w-full min-w-0 items-center gap-2",Eg="typography-meta shrink-0 text-muted-foreground tabular-nums",ha="space-y-3.5",Xu="space-y-1.5",Dg="typography-settings-page-title text-muted-foreground",Zu="typography-settings-section-title text-foreground",pa="typography-settings-group-title text-foreground",so="typography-settings-field-label text-foreground",ef="typography-settings-description text-muted-foreground",gn="typography-meta text-muted-foreground",Tg="typography-meta font-medium text-foreground",Pg="typography-settings-section-title text-foreground",tf=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:u,settingsItem:d})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":d,className:U("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Zu,children:e}):e,n,r!=null?t.jsx(mn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:ef,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:U(u),children:a})]})},Mg=({children:e,className:s})=>t.jsx("div",{className:U("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),sf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:U(pa,s),children:e}),Fg=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:U("space-y-2",o),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(sf,{children:e}),n!=null?t.jsx(mn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:gn,children:s}):null]}):null,t.jsx("div",{className:U(a),children:r})]}),an=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const u=s!=null?t.jsx("p",{className:gn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:U("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:so,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),r==="before"?u:null]}),t.jsx("div",{className:U("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},Og=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:U("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:so,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),s!=null?t.jsx("p",{className:U(gn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:U("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Lg=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:U("pt-4",s),children:e}),nf=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:u,info:d})=>{const f=()=>{o||s(!e)},p=r!=null;return t.jsxs("div",{"data-settings-item":l,className:U("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[t.jsx(Cr,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:so,children:n}),u,d!=null?t.jsx(mn,{children:d}):null]}),p?t.jsx("span",{className:gn,children:r}):null]})]})},Bg=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:U("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Qu,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:U("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:gn,children:r}):null]})]}),_g=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:U(Xu,n),children:s});function Ug({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:U("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Te,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}const zr="pichamber:server-update-channel-changed",zg=()=>{typeof window<"u"&&window.dispatchEvent(new Event(zr))},rf=e=>typeof window>"u"?()=>{}:(window.addEventListener(zr,e),()=>window.removeEventListener(zr,e));class of extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(oc,{className:"w-full max-w-md",children:[t.jsx(ic,{className:"text-center",children:t.jsxs(ac,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(R,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(lc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Te,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(R,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function af(e){return t.jsx(of,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const $g=({active:e=!0})=>{const s=Ee(n=>n.currentSessionId);return t.jsx(af,{sessionId:s||void 0,children:t.jsx(cc,{active:e},s??"no-session")})};function lf({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ma=Ie.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:p,...b},m)=>{const g=Ie.useRef(null),h=Ie.useRef(null),[v,x]=Ie.useState(null),I=c??v,w=Ie.useCallback(N=>{const C=g.current;if(!C)return;h.current={startY:N.clientY,startHeight:C.getBoundingClientRect().height};const j=N.currentTarget;j.setPointerCapture(N.pointerId);const y=E=>{const P=h.current;if(!P)return;const B=P.startHeight+(E.clientY-P.startY),L=Math.max(82,B);u?u(L):x(L)},k=()=>{h.current=null,j.removeEventListener("pointermove",y),j.removeEventListener("pointerup",k),j.removeEventListener("pointercancel",k)};j.addEventListener("pointermove",y),j.addEventListener("pointerup",k),j.addEventListener("pointercancel",k),N.preventDefault()},[u]),A=Ie.useCallback(N=>{if(N.target.closest('textarea, button, [role="separator"]'))return;const j=g.current?.querySelector("textarea");j&&document.activeElement!==j&&(N.preventDefault(),j.focus())},[]);return f?t.jsx(ps,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:U("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}):t.jsx("div",{ref:g,onPointerDown:A,style:I!==null?{height:`${I}px`}:void 0,className:U("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:m,className:U("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!d&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],d&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,t.jsx(lf,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});ma.displayName="Textarea";const ga=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],ln=Object.fromEntries(ga.map(e=>[e.key,e.Icon])),$r="pichamber:project-actions-updated",ba=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},es=(e,s)=>`${ba(e)}::${s}`,xa=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:u,divider:d=!0})=>t.jsx(tf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:d,className:c,contentClassName:u,children:l}),Gr=e=>e.name.trim().length>0&&e.command.trim().length>0,cf=e=>e.name.trim().length===0&&e.command.trim().length===0,df=e=>!Gr(e)&&!cf(e),uf=(e,s)=>e.some(r=>s.has(r.id)&&!Gr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Gr)},ff=450,hf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,pf=()=>({id:hf(),name:"",command:"",icon:"play"}),mf=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,u]=i.useState(new Set),d=i.useRef(!1);i.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const I=await Ar(e);if(x)return;n(I.actions),l(JSON.stringify({actions:I.actions})),u(new Set(I.actions.map(w=>w.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),u(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=i.useMemo(()=>uf(s,c),[s,c]),p=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=a!==null&&f.canPersist&&p!==a,m=i.useCallback(async x=>await dc(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),u(new Set(x.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent($r,{detail:{projectId:e.id}})),!0):(ae.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!b||r||d.current)return;const x=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await m(f.actions)}finally{d.current=!1}})())},ff);return()=>{window.clearTimeout(x)}},[b,r,m,f.actions]);const g=i.useCallback(()=>{const x=pf();n(I=>[...I,x])},[]),h=i.useCallback(x=>{n(I=>I.filter(w=>w.id!==x))},[]),v=i.useCallback((x,I)=>{n(w=>w.map(A=>A.id===x?I(A):A))},[]);return t.jsx(xa,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Te,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:g,children:[t.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:U("space-y-6",Ju),children:s.map((x,I)=>{const w=x.icon||"play",A=ln[w]||"play",N=x.name.trim()||`Action ${I+1}`,C=df(x);return t.jsxs("div",{className:ha,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:pa,children:N}),t.jsx(Te,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${N}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(an,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(R,{name:A,className:"h-4 w-4"})})}),t.jsx(Ot,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:ga.map(j=>{const y=j.Icon,k=(x.icon||"play")===j.key;return t.jsx("button",{type:"button",onClick:()=>v(x.id,E=>({...E,icon:j.key})),className:U("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",k&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:t.jsx(R,{name:y,className:"h-4 w-4"})},j.key)})})})]}),t.jsx(dn,{value:x.name,onChange:j=>v(x.id,y=>({...y,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(an,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ma,{value:x.command,onChange:j=>v(x.id,y=>({...y,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),C?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(nf,{checked:x.autoOpenUrl===!0,onChange:j=>v(x.id,y=>({...y,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${N}`}),x.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(an,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(dn,{value:x.openUrl||"",onChange:j=>v(x.id,y=>({...y,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},gf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},bf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Kt(y=>y.providers),u=Kt(y=>y.modelsMetadata),d=le(y=>y.hiddenModels),f=le(y=>y.isFavoriteModel),p=le(y=>y.toggleFavoriteModel),b=le(y=>y.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:g}=uc(),[h,v]=i.useState(!1),[x,I]=i.useState("");i.useEffect(()=>{h||I("")},[h]);const w=e?c.find(y=>y.id===e.providerId):void 0,A=e&&w?(Array.isArray(w.models)?w.models:[]).find(y=>y.id===e.modelId):void 0,N=e?fc(A,e.modelId):s,C=i.useMemo(()=>e?d.filter(y=>!(y.providerID===e.providerId&&y.modelID===e.modelId)):d,[d,e]),j=i.useCallback(y=>{l({providerId:y.providerID,modelId:y.modelID}),v(!1)},[l]);return t.jsxs(Mt,{modal:!1,open:h,onOpenChange:y=>{r||v(y)},children:[t.jsx(Ft,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:U(ki({size:"default"}),Vu,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(hc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:U("truncate",e?"text-foreground":"text-muted-foreground"),children:N})]}),t.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Ot,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(pc,{providers:c,favoriteModels:m,recentModels:g,modelsMetadata:u,searchQuery:x,onSearchQueryChange:I,onSelect:j,labels:{...gf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),v(!1)},disabled:r,autoFocus:!0,onEscape:()=>v(!1),isFavorite:y=>f(y.providerID,y.modelID),onToggleFavorite:y=>p(y.providerID,y.modelID),onReorderFavorite:(y,k)=>b(y.providerID,y.modelID,k.providerID,k.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},lr="w-full max-w-none",xf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Kt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(xa,{title:"Project",divider:!1,children:t.jsxs("div",{className:ha,children:[t.jsx(an,{label:"Name",settingsItem:"projects.name",controlClassName:lr,children:t.jsx(dn,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(an,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:lr,children:t.jsx(bf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:lr,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},yf=e=>{const[s,n]=i.useState(""),[r,o]=i.useState(void 0);i.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const a=i.useMemo(()=>mc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((d,f)=>{o(d&&f?`${d}/${f}`:void 0)},[]),u=i.useCallback(async()=>{if(!e)return null;const d=s.trim();return d?{label:d,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:u,project:e}},wf=450,vf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:a}=e,l=i.useRef(!1);i.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const u=await a();if(u)try{await s(u)}catch{ae.error("Failed to save project settings")}}finally{l.current=!1}})())},wf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},Sf=({project:e,onIdentitySave:s})=>{const n=yf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return vf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(xf,{form:n}),t.jsx(mf,{projectRef:r})]})};function no({...e}){return t.jsx(Wi,{...e})}function ro({...e}){return t.jsx(Hi,{...e})}function oo({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(Yi,{children:t.jsx(qi,{className:U("app-region-no-drag z-50",s),children:t.jsx(Qi,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:U(Ci,e),...o,children:n})})})}function Os({className:e,...s}){return t.jsx(Vi,{className:U(Ai,e),...s})}function ya({className:e,...s}){return t.jsx(Ji,{className:U(Ni,e),...s})}const An=100;function Gg(){const e=le(y=>y.isArchivePageOpen),s=le(y=>y.setArchivePageOpen),n=le(y=>y.setActiveMainTab),r=Ee(y=>y.setCurrentSession),o=Ee(y=>y.unarchiveSession),a=Bs(y=>y.homeDirectory),l=Nr({archived:!0}),[c,u]=i.useState(""),[d,f]=i.useState(null),[p,b]=i.useState(An),m=c.trim().toLowerCase(),g=i.useMemo(()=>e?[...l].sort((y,k)=>(k.time?.archived??0)-(y.time?.archived??0)):[],[l,e]),h=i.useMemo(()=>{const y=new Map;for(const k of g){const E=Ne(rn(k))??"",P=y.get(E);if(P){P.sessions.push(k);continue}y.set(E,{directory:E,label:E?_s(E,a)||E:"other projects",sessions:[k]})}return[...y.values()].sort((k,E)=>E.sessions.length-k.sessions.length)},[a,g]),v=i.useMemo(()=>m?g.filter(y=>(y.title??"").toLowerCase().includes(m)):d===null?g:h.find(y=>y.directory===d)?.sessions??[],[h,m,d,g]),x=v.slice(0,p),I=v.length-x.length,w=l.length,A=i.useCallback(y=>{f(y),b(An)},[]),N=i.useCallback(y=>{const k=Ne(rn(y));r(y.id,k??void 0),n("chat"),s(!1)},[n,r,s]),C=i.useCallback(y=>{o(y.id).then(k=>{k?ae.success("Session restored"):ae.error("Failed to restore session")})},[o]);if(!e)return null;const j=(y,k,E,P,B,L,z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:B,title:L,className:U("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:k}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),z?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>xs.requestDelete({sessions:z,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${k}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},y);return t.jsx(Gd,{open:e,onOpenChange:s,children:t.jsxs(Kd,{children:[t.jsx(Wd,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Hd,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Yd,{className:"sr-only",children:"Archived sessions"}),t.jsx(qd,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Qd,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(R,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[j("__all__","All directories",w,d===null,()=>A(null)),h.map(y=>j(y.directory||"__none__",y.label,y.sessions.length,d===y.directory,()=>A(y.directory),y.directory||void 0,y.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(R,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:y=>{u(y.target.value),b(An)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:v.length===1?`${v.length} archived session`:`${v.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[x.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:m?"No matching archived sessions":"No archived sessions"})}):x.map(y=>{const k=Ne(rn(y))??"",E=k?_s(k,a)||k:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>N(y),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),N(y))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:cs(y)}),m&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:k,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Pd(y.time?.archived??y.time?.updated??y.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),C(y)},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 ${cs(y)}`,children:t.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),xs.requestDelete({sessions:[y],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 ${cs(y)}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},y.id)}),I>0?t.jsx("button",{type:"button",onClick:()=>b(y=>y+An),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const jf=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const s=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=s+n+r;if(o<=0)return{percent:0,hasInput:!1};const a=Math.max(0,n);return{percent:Math.min(100,Math.max(0,a/o*100)),hasInput:!0}},kf=e=>{if(!e||typeof e!="object")return 0;const s=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return s+n+r},Wt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Cf=e=>{if(!e||typeof e!="object")return null;const s=Wt(e.input),n=Wt(e.output),r=Wt(e.cacheRead),o=Wt(e.cacheWrite);return{input:s,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:s+n+r+o}},Yo=e=>{const s=Cf(e.info.usage);if(s)return s;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Wt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,a=Wt(o.input),l=Wt(o.output),c=Wt(o.reasoning),u=Wt(o.cache?.read),d=Wt(o.cache?.write);return{input:a,output:l,reasoning:c,cacheRead:u,cacheWrite:d,total:a+l+c+u+d}},wa=380,cr=8,Af=140;function Nf({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[u,d]=i.useState(!1),[f,p]=i.useState(null),{enabled:b}=Qr();return i.useLayoutEffect(()=>{if(!e||!b||!l)return;const m=()=>{const v=n.current?.getBoundingClientRect(),x=a.current?.getBoundingClientRect();if(!v||!x){p(null);return}const I=v.left-x.left;p(Math.min(Math.max(I,cr),Math.max(cr,x.width-wa-cr)))};m();const g=a.current;if(typeof ResizeObserver>"u"||!g)return;const h=new ResizeObserver(m);return h.observe(g),()=>h.disconnect()},[n,b,e,l]),i.useEffect(()=>{if(e){c(!0),d(!1);return}if(!l)return;d(!0);const m=window.setTimeout(()=>{c(!1),d(!1)},Af);return()=>window.clearTimeout(m)},[e,l]),i.useEffect(()=>{if(!e)return;const m=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[s,e]),i.useEffect(()=>{if(!e)return;const m=g=>{const h=g.target;if(!(h instanceof Node)){s();return}o.current?.contains(h)||n.current?.contains(h)||s()};return document.addEventListener("pointerdown",m,!0),r&&document.addEventListener("wheel",m,!0),()=>{document.removeEventListener("pointerdown",m,!0),r&&document.removeEventListener("wheel",m,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:u,anchorLeft:f,isPopover:b&&f!==null}}const qo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},zn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Nn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(R,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),If=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:u,isPopover:d}=Nf({open:e,onClose:s,anchorRef:n,closeOnWheel:!0});return l?t.jsxs("div",{ref:a,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:U("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",d?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...d?{top:8,left:u??8,width:`min(${wa}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{iconNode:t.jsx(Ii,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:U("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:zn(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:zn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Nn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
3
3
  @keyframes session-metadata-in {
4
4
  from { opacity: 0; transform: translateY(-8px) scale(0.985); }
5
5
  to { opacity: 1; transform: translateY(0) scale(1); }
@@ -50,4 +50,4 @@ ${n}`:""}function Pa(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${
50
50
  `):l.slice(0,-1).join(`
51
51
  `);if(this.tail=a.endsWith(`
52
52
  `)?"":(l[l.length-1]??"").slice(-1024),!c)return;const u=fm(c);if(!u||this.pendingUrls.has(u))return;const d=this.probeGeneration;this.pendingUrls.add(u),hm(u).then(f=>{if(this.pendingUrls.delete(u),!f||this.probeGeneration!==d)return;const p=he.getState().getDirectoryState(s)?.tabs.find(b=>b.id===n);!p||p.previewUrlLocked||p.previewUrl===u||o(s,n,u,{locked:!1,autoOpened:!1})})}}const xm=(e,s)=>{if(s!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Ua(o):null};function ym({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:d,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:b,tabs:m}){const g=he(F=>F.ensureDirectory),h=he(F=>F.setTabSessionId),v=he(F=>F.setTabLifecycle),x=he(F=>F.setConnecting),I=he(F=>F.appendToBuffer),w=he(F=>F.replaceBuffer),A=he(F=>F.setTabPreviewUrl),[N,C]=i.useState(null),[j,y]=i.useState(!1),[k,E]=i.useState(!1),P=i.useRef(new Map),B=i.useRef(null),L=i.useRef(n),z=i.useRef(r),Q=i.useRef(s),O=i.useRef(null),M=i.useRef(new Set),T=i.useRef(new Map),_=i.useRef(m),se=i.useRef(l),$=i.useRef(a),G=i.useRef(e);_.current=m,se.current=l,$.current=a,G.current=e;const Ae=i.useCallback(()=>{const F=L.current;F&&T.current.get(F)?.reset()},[]);i.useEffect(()=>{z.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,d.current).catch(()=>{})},[d,e,r]),i.useEffect(()=>{L.current=n},[n]),i.useEffect(()=>{Q.current=s},[s]);const te=i.useCallback(()=>{for(const F of P.current.values())try{F()}catch{}P.current.clear(),B.current=null,E(!1)},[]);i.useEffect(()=>()=>{te(),z.current=null},[te]);const Pe=i.useCallback((F,K,J)=>{let Z=T.current.get(K);Z||(Z=new bm,T.current.set(K,Z)),Z.scan(F,K,J,A)},[A]),Be=i.useCallback((F,K,J)=>{if(P.current.has(J)){B.current=J;return}const Z=Oo(),pe=()=>Oo()===Z&&Q.current===F&&he.getState().getDirectoryState(F)?.tabs.find(xe=>xe.id===K)?.terminalSessionId===J,Se=e.connect(J,{onEvent:xe=>{if(pe())switch(xe.type){case"snapshot":{L.current===K&&z.current===J?(x(F,K,!1),C(null),y(!1),E(!1),b()):x(F,K,!1),w(F,K,xe.data??"",xe.sequence??0),Pe(F,K,xe.data??""),xe.status==="exited"&&v(F,K,"exited");break}case"reconnecting":{L.current===K&&(C(null),y(!1),E(!0));break}case"data":{xe.data&&(I(F,K,xe.data,xe.sequence,xe.replayData),Pe(F,K,xe.data));break}case"exit":{const ne=typeof xe.exitCode=="number"?xe.exitCode:null,ce=typeof xe.signal=="number"?xe.signal:null,fe=!!he.getState().getDirectoryState(F)?.tabs.find(_e=>_e.id===K)?.label?.startsWith("Action:");I(F,K,`\\r\\n[Process exited${ne!==null?` with code ${ne}`:""}${ce!==null?` (signal ${ce})`:""}]\\r\\n`),v(F,K,"exited"),L.current===K&&(x(F,K,!1),C(fe?null:"Terminal session ended"),y(!1),E(!1));break}}},onError:(xe,ne)=>{if(!pe())return;const ce=L.current===K;if(!ne){ce&&(C(null),y(!1));return}if(xe.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(F)?.tabs.find(fe=>fe.id===K)?.label?.startsWith("Action:")){ce&&(C(null),y(!1),x(F,K,!1),E(!1)),h(F,K,null),v(F,K,"idle");return}ce&&(E(!1),C(`Connection failed: ${xe.message}`),y(!0),x(F,K,!1),v(F,K,"exited"),h(F,K,null))}});P.current.set(J,()=>Se.close()),B.current=J},[I,b,w,Pe,x,v,h,e]),Y=i.useMemo(()=>m.map(F=>`${F.id}:${F.terminalSessionId??""}`).join(","),[m]);return i.useEffect(()=>{if(!l||!a||!s)return;const F=s,K=new Set;for(const J of m)J.terminalSessionId&&(K.add(J.terminalSessionId),Be(F,J.id,J.terminalSessionId));for(const[J,Z]of P.current)if(!K.has(J)){try{Z()}catch{}P.current.delete(J)}},[Y,m,s,l,a,Be]),i.useEffect(()=>yd(()=>{if(!se.current||!$.current)return;const F=Q.current;if(!F)return;const K=[];for(const Z of _.current){if(!Z.terminalSessionId)continue;he.getState().getDirectoryState(F)?.tabs.find(Se=>Se.id===Z.id)?.terminalSessionId===Z.terminalSessionId&&K.push({id:Z.id,terminalSessionId:Z.terminalSessionId})}if(P.current.clear(),B.current=null,K.length===0)return;E(!0),C(null),y(!1);for(const Z of K)Be(F,Z.id,Z.terminalSessionId);const J=O.current;if(J)for(const Z of K)G.current.resize({sessionId:Z.terminalSessionId,...J}).catch(()=>{})}),[Be]),i.useEffect(()=>{let F=!1;if(!l||!a)return;if(!s){C(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const J=s;if(!Q.current||Q.current!==J)return;if(!he.getState().getDirectoryState(J)){g(J);return}const pe=he.getState().getDirectoryState(J);if(!pe||pe.tabs.length===0)return;const Se=pe.activeTabId??pe.tabs[0]?.id??null;if(!Se)return;const xe=pe.tabs.find(W=>W.id===Se)??pe.tabs[0],ne=xe?.terminalSessionId??null,ce=xe?.lifecycle??"idle",q=!!xe?.label?.startsWith("Action:"),fe=he.getState().getBuffer(J,Se),_e=fe.byteLength>0||fe.chunks.length>0;if(!ne){if(ce==="exited"){x(J,Se,!1);return}if(q&&_e){x(J,Se,!1);return}const W=`${J}\0${Se}`;if(M.current.has(W))return;const X=O.current??za;M.current.add(W),C(null),y(!1),E(!1),x(J,Se,!0);try{const ie=await e.createSession({cwd:J,sessionId:Se,cols:X.cols,rows:X.rows,shell:c,loginShell:u,...d.current});if(!he.getState().getDirectoryState(J)?.tabs.find(Me=>Me.id===Se)){try{await e.close(ie.sessionId)}catch{}return}h(J,Se,ie.sessionId);const be=O.current;be&&(be.cols!==X.cols||be.rows!==X.rows)&&e.resize({sessionId:ie.sessionId,...be}).catch(()=>{});return}catch(ie){const ge=he.getState().getDirectoryState(J)?.tabs.find(be=>be.id===Se);if(!ge||ge.terminalSessionId||(x(J,Se,!1),Q.current!==J||L.current!==Se))return;C(ie instanceof Error?ie.message:"Failed to start terminal session"),y(!0),E(!1);return}finally{M.current.delete(W)}}!ne||F||(z.current=ne)})(),()=>{F=!0}},[p,s,r,o,n,a,f,l,g,x,v,h,e,u,c,d]),{connectionError:N,setConnectionError:C,isFatalError:j,setIsFatalError:y,isReconnectPending:k,setIsReconnectPending:E,terminalIdRef:z,lastViewportSizeRef:O,directoryRef:Q,activeTabIdRef:L,disconnectStream:te,resetTerminalPreviewScan:Ae,startStream:Be}}function wm({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:u}){const[d,f]=i.useState(null),p=i.useRef(null),b=i.useCallback(()=>{u||p.current?.focus()},[u]),m=i.useCallback(()=>{u||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[u]);i.useEffect(()=>{!o&&d!==null&&f(null)},[o,d]),i.useEffect(()=>{!c&&d!==null&&f(null)},[c,d]);const g=i.useCallback(w=>{if(!w||n)return;let A=w,N=!1;d&&w.length>0&&(A=gm(w,d),N=!0);const C=s.current;C&&(e.sendInput(C,A).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),N&&(f(null),b()))},[d,b,n,r,e,s]),h=i.useCallback((w,A)=>{const N=l.current;if((!N||N.cols!==w||N.rows!==A)&&(l.current={cols:w,rows:A}),!a)return;const C=s.current;C&&e.resize({sessionId:C,cols:w,rows:A}).catch(()=>{})},[a,l,e,s]),v=i.useCallback(w=>{f(A=>A===w?null:w),b()},[b]),x=i.useCallback(w=>{const A=mm(w,d);A&&(g(A),f(null),b())},[d,b,g]),I=i.useCallback(w=>{if(w.repeat)return;const A=w.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const N=A.length===1?A.toLowerCase():A;if(N in mi){w.preventDefault(),w.stopPropagation(),x(mi[N]);return}const C=xm(w,d);C&&(w.preventDefault(),w.stopPropagation(),g(C),f(null),b())},[d,b,x,g]);return i.useEffect(()=>{if(!(!o||!d||!c))return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[d,I,o,c]),{activeModifier:d,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:b,focusTerminalWhenWindowActive:m,handleViewportInput:g,handleViewportResize:h,handleModifierToggle:v,handleMobileKeyPress:x}}function vm({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:u,activeTabIdRef:d,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:b,setConnectionError:m,setIsFatalError:g,setIsReconnectPending:h}){const v=he(B=>B.createTab),x=he(B=>B.setActiveTab),I=he(B=>B.closeTab),w=he(B=>B.setTabSessionId),A=he(B=>B.setTabLifecycle),[N,C]=i.useState(!1),j=i.useCallback(async()=>{if(!s||N)return;const B=he.getState().getDirectoryState(s),L=n??B?.activeTabId??B?.tabs[0]?.id??null;if(!L)return;const z=B?.tabs.find(Q=>Q.id===L)?.terminalSessionId??null;if(!(!z||!e.restartSession)){C(!0),m(null),g(!1),h(!1),p();try{const Q=c.current??za,O=await e.restartSession(z,{cwd:s,shell:o,loginShell:a,...Q,...l.current});if(he.getState().getDirectoryState(s)?.tabs.find(T=>T.id===L)?.terminalSessionId!==z||(w(s,L,O.sessionId),A(s,L,"running"),u.current!==s||d.current!==L))return;f.current=O.sessionId,b(s,L,O.sessionId)}catch(Q){if(he.getState().getDirectoryState(s)?.tabs.find(M=>M.id===L)?.terminalSessionId!==z||u.current!==s||d.current!==L)return;m(Q instanceof Error?Q.message:"Failed to restart terminal"),g(!1),h(!1),f.current=z,b(s,L,z)}finally{C(!1)}}},[n,d,u,s,r,N,c,p,m,g,h,A,w,b,e,l,f,a,o]),y=i.useCallback(async()=>{await j()},[j]),k=i.useCallback(()=>{if(!s)return;const B=v(s);x(s,B),m(null),g(!1),h(!1)},[v,s,x,m,g,h]),E=i.useCallback(B=>{s&&(x(s,B),m(null),g(!1),h(!1))},[s,x,m,g,h]),P=i.useCallback(B=>{if(!s)return;m(null),g(!1),h(!1);const L=he.getState().getDirectoryState(s)?.tabs.find(z=>z.id===B)?.terminalSessionId;(async()=>{L&&await e.close(L),I(s,B)})().catch(z=>m(z instanceof Error?z.message:"Terminal session ended"))},[I,s,m,g,h,e]);return{isRestarting:N,handleRestart:j,handleHardRestart:y,handleCreateTab:k,handleSelectTab:E,handleCloseTab:P}}const qg=({visible:e,onCloseView:s,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Gs(),{currentTheme:a}=Pi(),l=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground};const{monoFont:c}=Pc(),u=le(re=>re.terminalFontSize),d=le(re=>re.terminalShell),f=le(re=>re.terminalLoginShells.includes(re.terminalShell)),{isMobile:p,isTablet:b,hasTouchOnlyPointer:m}=$s(),g=p||b,h=(g||m)&&o.platform==="web",v=!0,x=le(re=>re.showTerminalQuickKeysOnDesktop),I=g||x,w=Ee(re=>re.currentSessionId),A=Ee(re=>re.newSessionDraft),N=w!==null||A?.open===!0,C=Mc()??null,j=he(re=>C?re.sessions.get(C):void 0),y=he(re=>re.hasHydrated),k=le(re=>re.openContextPreview),E=i.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,v]),P=i.useMemo(()=>{if(j)return E?j.tabs.find(re=>re.id===E)??j.tabs[0]:j.tabs[0]},[j,E]),B=i.useMemo(()=>(j?.tabs??[]).map(re=>({icon:(()=>{const Fe=re.iconKey?ln[re.iconKey]??"terminal":"terminal";return t.jsx(R,{name:Fe,className:"h-4 w-4"})})(),id:re.id,label:re.label,title:re.label,closeLabel:"Close tab"})),[j?.tabs]),L=P?.terminalSessionId??null,z=P?.lifecycle??"idle",Q=i.useMemo(()=>(j?.tabs??[]).map(re=>({id:re.id,terminalSessionId:re.terminalSessionId,label:re.label})),[j?.tabs]),O=P?.isConnecting??!1,M=P?.previewUrl??null,_=le(re=>re.activeMainTab)==="terminal",se=e??_,[$,G]=i.useState(se);i.useEffect(()=>{se&&G(!0)},[se]);const{connectionError:Ae,setConnectionError:te,isFatalError:Pe,setIsFatalError:Be,isReconnectPending:Y,setIsReconnectPending:F,terminalIdRef:K,lastViewportSizeRef:J,directoryRef:Z,activeTabIdRef:pe,resetTerminalPreviewScan:Se,startStream:xe}=ym({terminal:r,effectiveDirectory:C,activeTabId:E,terminalSessionId:L,terminalLifecycle:z,hasOpenedTerminalViewport:$,terminalHydrated:y,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:v,hasActiveContext:N,tabs:Q,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ce.current?.focus()}}),{activeModifier:ne,terminalControllerRef:ce,focusTerminalWhenWindowActive:q,handleViewportInput:fe,handleModifierToggle:_e,handleMobileKeyPress:W}=wm({terminal:r,terminalIdRef:K,isReconnectPending:Y,setConnectionError:te,showQuickKeys:I,isTerminalVisible:se,lastViewportSizeRef:J,terminalSessionId:L,useTouchTerminalInput:h}),{isRestarting:X,handleRestart:ie,handleHardRestart:ge,handleCreateTab:be,handleSelectTab:Me,handleCloseTab:je}=vm({terminal:r,effectiveDirectory:C,activeTabId:E,enableTabs:v,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:J,directoryRef:Z,activeTabIdRef:pe,terminalIdRef:K,resetTerminalPreviewScan:Se,startStream:xe,setConnectionError:te,setIsFatalError:Be,setIsReconnectPending:F});i.useEffect(()=>{if(!se||h)return;if(typeof window>"u"){q();return}const re=window.requestAnimationFrame(()=>{q()});return()=>{window.cancelAnimationFrame(re)}},[E,q,se,h]);const ee=i.useMemo(()=>{const re=Xs[ir].stack;if(typeof window>"u")return(Xs[c]??Xs[ir]).stack;const De=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return De&&De.trim().length>0?De.trim():(Xs[c]??Xs[ir]).stack??re},[c]),me=i.useMemo(()=>Kp(a),[a]),de=`${C??"no-dir"}::${E??"no-tab"}`;if(i.useEffect(()=>{if(!se||h)return;const re=ce.current;if(!re)return;const Fe=()=>{re.fit()};if(typeof window<"u"){const De=window.requestAnimationFrame(()=>{Fe(),q()}),ot=[220,400].map(it=>window.setTimeout(Fe,it));return()=>{window.cancelAnimationFrame(De),ot.forEach(it=>window.clearTimeout(it))}}Fe()},[q,se,h,ce,de,L]),i.useEffect(()=>{if(!se||!h)return;let re=null;const Fe=()=>{re!==null&&window.cancelAnimationFrame(re),re=window.requestAnimationFrame(()=>{re=null,ce.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Fe),()=>{window.removeEventListener("oc:keyboard-settled",Fe),re!==null&&window.cancelAnimationFrame(re)}},[se,ce,de,h]),!N)return t.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!C)return t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{children:"No working directory available for this session."}),t.jsx("button",{onClick:ie,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ke=!L||O||X||Y,We=$,He=j?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx(nm,{items:B,activeId:E,onSelect:Me,onClose:je,onCreate:be})}),t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:U("shrink-0",g?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:be,title:"New tab","aria-label":"New tab",children:t.jsx(R,{name:"add",className:`${g?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ie()},disabled:X,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(R,{name:"restart",className:"h-4 w-4"})}),M?t.jsxs(Te,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{C&&k(C,M)},title:"Open preview pane",children:[t.jsx(R,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,ye=t.jsx(rm,{isTouchTerminal:g,activeModifier:ne,disabled:ke,onKeyPress:W,onModifierToggle:_e});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:U("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",g?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[He?n?sc.createPortal(t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:He}),n):t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[He,s?t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:s,title:"Close terminal view","aria-label":"Close terminal view",children:t.jsx(R,{name:"close",className:"h-4 w-4"})}):null]}):null,!g&&I&&v&&j?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:ye}):null,!g&&I&&!j?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:ye}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:me.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:We&&C&&j?j.tabs.map(re=>{const Fe=re.id===E;return t.jsx(sm,{directory:C,tabId:re.id,sessionId:re.terminalSessionId,sessionKey:`${C}::${re.id}`,isActive:Fe,isTerminalVisible:se,terminal:r,theme:me,fontFamily:ee,fontSize:u,enableTouchScroll:h,lastViewportSizeRef:J,onInput:fe,controllerRef:ce},re.id)}):null}),!Y&&Ae&&t.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[t.jsx("span",{children:Ae}),Pe&&g&&t.jsx(Te,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ge,disabled:X,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),g&&I?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:ye})}):null]})},Sm=48,jm=96,xt=(e,...s)=>{try{e?.(...s)}catch{}},vr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Qg=(e,s)=>{const n=i.useRef(s);n.current=s;const r=s.enabled;i.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const a=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?jm:Sm;let u=!1,d=!1,f=!1,p=null,b=!1,m=0,g=0,h=0,v=0;const x=()=>{u=!1,d=!1,f=!1,p=null},I=()=>{const k=n.current,E=p,P=b;d&&E&&(xt(E==="left"?k.onLeftProgress:k.onRightProgress,P?1:0),xt(k.onDragEnd,E,P)),x()},w=()=>{I(),d||x()},A=k=>{const E=n.current;if(E.enabled===!1){d&&p?I():x();return}if(k.touches.length!==1){d&&p?I():x();return}const P=k.touches[0],B=o.getBoundingClientRect(),L=o.clientWidth,z=!!E.leftOpen,Q=!!E.rightOpen,O=M=>Fp(M,o);if(z||Q){if(O(k.target)){x();return}if(z&&Q){const M=P.clientX<=B.left+c;P.clientX>=B.right-c?(p="right",b=!0):M?(p="left",b=!0):(p=z?"left":"right",b=!0)}else z?(p="left",b=!0):(p="right",b=!0);v=vr(p==="left"?E.leftWidth:E.rightWidth,L),v<10&&(v=L||window.innerWidth||320),v<10&&(v=320),u=!0}else{if(O(k.target)){x();return}p=null,b=!1,v=0,u=!0}m=P.clientX,g=P.clientY,h=Date.now(),d=!1,f=!1},N=k=>{if(!u)return;if(k.touches.length!==1){w();return}const E=k.touches[0],P=E.clientX-m,B=E.clientY-g;if(!f){if(Math.abs(P)<ci&&Math.abs(B)<ci)return;if(Math.abs(B)>Math.abs(P)*en){x();return}if(!p){const Q=n.current;p=P>0?"left":"right",v=vr(p==="left"?Q.leftWidth:Q.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(p==="left"){if(!b&&P<=0){x();return}if(b&&P>=0){x();return}}else{if(!b&&P>=0){x();return}if(b&&P<=0){x();return}}f=!0,d=!0,xt(n.current.onDragStart,p)}if(!d)return;k.cancelable&&k.preventDefault();const L=n.current,z=di(p,b,P,v);xt(p==="left"?L.onLeftProgress:L.onRightProgress,z)},C=(k,E)=>{if(!u){x();return}const P=k-m,B=E-g;if(!p&&!b&&Math.abs(P)>=On&&Math.abs(B)<=Math.abs(P)*en){const T=n.current;p=P>0?"left":"right",v=vr(p==="left"?T.leftWidth:T.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(!p){x();return}const L=Math.max(1,Date.now()-h),z=n.current;if(!d){const T=Math.abs(P),_=Math.abs(B);T>=On&&_<=T*en?p==="left"&&!b&&P>0?(xt(z.onLeftProgress,1),xt(z.onLeftOpen)):p==="right"&&!b&&P<0?(xt(z.onRightProgress,1),xt(z.onRightOpen)):xt(p==="left"?z.onLeftProgress:z.onRightProgress,b?1:0):xt(p==="left"?z.onLeftProgress:z.onRightProgress,b?1:0);const se=p;x(),xt(z.onDragEnd,se);return}const Q=di(p,b,P,v),O=Pp({side:p,isOpenAtStart:b,dx:P,dt:L,progress:Q}),M=p;xt(M==="left"?O?z.onLeftOpen:z.onLeftClose:O?z.onRightOpen:z.onRightClose),x(),xt(z.onDragEnd,M,O)},j=k=>{const E=k.changedTouches[0];if(!E){x();return}const P=E.clientX-m,B=E.clientY-g;u&&(d||Math.abs(P)>=On&&Math.abs(B)<=Math.abs(P)*en)&&k.cancelable&&k.preventDefault(),C(E.clientX,E.clientY)},y=()=>{w()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",N,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",y,{passive:!0}),()=>{try{d&&p&&I()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",N),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",y)}},[e,r])};function Vg({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(R,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function gi({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const km=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,Cm=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Yn(s,n)?null:e,Sr=()=>ms.filter(e=>Pr.has(e.id)).map(e=>({..._i(e)})),Am=()=>{if(typeof window>"u")return Mr;const e=window.localStorage.getItem("openInAppId");return e&&Tr(e)?e:Mr};let jr=!1,Ts=!1,is=!1,as=0,cn=null;const bi=()=>{cn&&(clearTimeout(cn),cn=null)},fs=ks()((e,s)=>({selectedAppId:Am(),availableApps:Sr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(jr||typeof window>"u")return;jr=!0;const n=(u,d=!0)=>{if(!Array.isArray(u)||u.length===0){e({availableApps:Sr(),hasLoadedApps:d});return}const f=new Set(u.map(g=>g.name)),p=new Map(u.map(g=>[g.name,g.iconDataUrl??void 0])),m=ms.filter(g=>f.has(g.appName)||Pr.has(g.id)).map(g=>({..._i(g),iconDataUrl:p.get(g.appName)}));e({availableApps:m,hasLoadedApps:!0})},r=async u=>{if(!Ls()||!un()||Ts||s().hasLoadedApps&&!u)return;const f=ms.map(p=>p.appName);bi(),Ts=!0,is=!1,e({isScanning:!0});try{const{apps:p,success:b,hasCache:m,isCacheStale:g}=await Lo(f,u),h=b&&!m&&p.length===0&&as<3;if(e({isCacheStale:m?g:!1}),n(p,b?!h:!1),b){if(h){const x=[800,1600,3200][as]??3200;as+=1,is=!0,cn=setTimeout(()=>{r()},x);return}as=0,is=!1;return}if(as<3){const x=[1e3,3e3,7e3][as]??7e3;as+=1,is=!0,cn=setTimeout(()=>{r()},x)}}finally{Ts=!1,is||e({isScanning:!1})}};r();const o=u=>{const d=u.detail,f=d&&typeof d.openInAppId=="string"&&d.openInAppId.length>0&&Tr(d.openInAppId)?d.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=u=>{const d=u.detail;Array.isArray(d)&&(as=3,is=!1,e({isScanning:!1,isCacheStale:!1}),n(d))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(jr||s().initialize(),!Ls()||!un()||Ts||s().hasLoadedApps&&!n)return;const o=ms.map(a=>a.appName);bi(),n&&e({hasLoadedApps:!1}),Ts=!0,is=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await Lo(o,n),u=new Set(a.map(b=>b.name)),d=new Map(a.map(b=>[b.name,b.iconDataUrl??void 0])),p=ms.filter(b=>u.has(b.appName)||Pr.has(b.id)).map(b=>({...b,iconDataUrl:d.get(b.appName)}));e({availableApps:p.length>0?p:Sr(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Ts=!1,is||e({isScanning:!1})}},selectApp:async n=>{Tr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Jr({openInAppId:n}))}})),Nm="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",Im="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",kr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Nm:e.id==="terminal"?Im:void 0}),xi=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,o]=i.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):t.jsx("span",{className:U("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},Rm=({directory:e,className:s})=>{const n=fs(g=>g.selectedAppId),r=fs(g=>g.availableApps),o=fs(g=>g.isCacheStale),a=fs(g=>g.isScanning),l=fs(g=>g.initialize),c=fs(g=>g.loadInstalledApps),u=fs(g=>g.selectApp);i.useEffect(()=>{l()},[l]);const d=Ls()&&un(),f=i.useMemo(()=>{const g=r.find(h=>h.id===n)??r.find(h=>h.id===Mr)??r[0]??ms[0];return kr(g||ms[0])},[r,n]);if(!d||!e||r.length===0)return null;const p=async g=>{await wd(e,g.id,g.appName)||await Li(e,g.appName)},b=async g=>{await u(g.id),await p(g)},m=async()=>{(await ws(e)).ok&&ae.success("Path copied to clipboard")};return t.jsxs("div",{className:U("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{p(f)},className:U("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:t.jsx(xi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:U("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Ot,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m()},children:[t.jsx(R,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(vs,{}),r.map(g=>{const h=kr(g);return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{b(g)},children:[t.jsx(xi,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:g.label}),f.id===g.id?t.jsx(R,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},g.id)}),o?t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(R,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},Em="\x1B",Dm=new RegExp(`${Em}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Tm=/https?:\/\/[^\s<>'"`]+/gi,St="__pichamber_auto_discover_preview__",Pm=15e3,Mm=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},Fm=e=>{const s=(e||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Om=e=>{const n=e.replace(Dm,"").match(Tm);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&o.push({raw:a,parsed:l})}catch{}if(o.length>0){const a=l=>{const{parsed:c}=l,u=c.hostname.toLowerCase(),d=u==="localhost"||u==="127.0.0.1"||u==="0.0.0.0"||u==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,b=f==="/"||f==="",m=!!(c.search||c.hash);let g=0;return d&&(g+=50),b&&(g+=30),g-=Math.min(p*5,20),m&&(g-=10),g};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},Lm=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Bm=["dev","start","preview","serve"];async function _m(e,s,n){if(!e)return null;const r=$m(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Gm(n);if(o){const a=await Km(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await Um(e)){const o=await zm(),a=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function Um(e){const s=`${e}/index.html`,n=await Hn(s,e);return typeof n=="string"&&n.trim().length>0}async function zm(){try{const e=await Nt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function $m(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(Bm.some(o=>n.includes(o)))return s}return null}function Gm(e){for(const{pattern:s}of Lm)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Km(e){const s=await Hn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Hn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Hn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Nt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Zt()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Nt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Wm(e){try{const s=await Hn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Hm=(e,s,n)=>new Promise(r=>{let o=!1,a=null,l=null;const c=u=>{o||(o=!0,l&&clearTimeout(l),a?.close(),r(u))};a=e.connect(s,{onEvent:u=>{(u.type==="exit"||u.type==="snapshot"&&u.status==="exited")&&c(!0)},onError:(u,d)=>{d&&c(!0)}}),o?a.close():l=setTimeout(()=>c(!1),n)});function Ym({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=Pi(),{terminal:o}=Gs(),{isMobile:a}=$s(),l=le(W=>W.terminalShell),c=le(W=>W.terminalLoginShells.includes(W.terminalShell)),u=le(W=>W.setSettingsPage),d=le(W=>W.setSettingsDialogOpen),f=le(W=>W.setSettingsProjectsSelectedId),p=le(W=>W.openContextPreview),b=he(W=>W.ensureDirectory),m=he(W=>W.setTabLabel),g=he(W=>W.setTabIconKey),h=he(W=>W.setActiveTab),v=he(W=>W.setConnecting),x=he(W=>W.setTabSessionId),I=he(W=>W.setTabPreviewUrl),w=he(W=>W.projectActionRuns),A=he(W=>W.setProjectActionRun),N=he(W=>W.updateProjectActionRunStatus),C=he(W=>W.removeProjectActionRun),[j,y]=i.useState([]),[k,E]=i.useState(null),[P,B]=i.useState(!1),L=i.useRef({}),z=i.useRef({}),Q=i.useRef({}),O=i.useRef({}),M=i.useRef(new Set),T=i.useRef(0),_=e?.id??null,se=e?.path??"",$=i.useMemo(()=>_?{id:_,path:se}:null,[_,se]),G=i.useCallback(async W=>{await ji(W)},[]),Ae=i.useCallback(async()=>{if(!$)return;const W=T.current+1;T.current=W,B(!0);try{const X=await Ar($);if(T.current!==W)return;const ie=X.actions;y(ie),E(ge=>ge===St||ge&&ie.some(be=>be.id===ge)?ge:null)}catch{if(T.current!==W)return}finally{T.current===W&&B(!1)}},[$]),te=i.useMemo(()=>ba(s||$?.path||""),[s,$?.path]),Pe=i.useMemo(()=>k?j.find(W=>W.id===k)??null:null,[j,k]),Be=i.useMemo(()=>({id:St,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Y=!a,F=i.useMemo(()=>Y?[Be,...j]:j,[j,Be,Y]);i.useEffect(()=>{Ae()},[Ae]),i.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const ie=X.detail;_&&(ie?.projectId&&ie.projectId!==_||Ae())};return window.addEventListener($r,W),()=>{window.removeEventListener($r,W)}},[Ae,_]),i.useEffect(()=>{k&&(k===St&&Y||j.some(W=>W.id===k)||E(null))},[j,Y,k]),i.useEffect(()=>{const W=()=>{const X=he.getState(),ie=X.sessions,ge=X.projectActionRuns;for(const[be,Me]of Object.entries(ge)){const ee=ie.get(Me.directory)?.tabs.find(De=>De.id===Me.tabId);if(!ee||ee.terminalSessionId!==Me.sessionId){C(be);continue}const me=z.current[be]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};z.current[be]=me;const de=F.find(De=>De.id===Me.actionId),ke=X.getBuffer(Me.directory,Me.tabId).chunks;if(!de||ke.length===0)continue;const We=ke.filter(De=>me.lastSeenChunkId===null||De.id>me.lastSeenChunkId);if(We.length===0)continue;const He=We.map(De=>De.data).join(""),ye=`${me.tail}${He}`,re=!me.openedUrl&&de.autoOpenUrl===!0?Om(ye):null,Fe=We[We.length-1]?.id??me.lastSeenChunkId;if(me.lastSeenChunkId=Fe,me.tail=ye.slice(-512),re)if(me.openedUrl=!0,me.openInPreview){const De=ge[be];De&&(I(De.directory,De.tabId,re,{locked:!1,autoOpened:!1}),De.status==="waiting-for-preview"&&N(be,"running"),window.clearTimeout(O.current[be]),delete O.current[be],p(De.directory,re))}else G(re),ae.success("Opened URL from action output");z.current[be]=me}for(const be of Object.keys(z.current))ge[be]||(delete z.current[be],window.clearTimeout(O.current[be]),delete O.current[be])};return W(),he.subscribe((X,ie)=>{(X.sessions!==ie.sessions||X.buffers!==ie.buffers)&&W()})},[F,p,G,w,C,I,N]);const K=i.useCallback(async(W,X={})=>{if(!te)throw new Error("No active directory");const ie=es(te,W.id);b(te);const ge=he.getState(),be=ge.getDirectoryState(te);let Me=L.current[ie]||null;const je=Me?!!be?.tabs.some(de=>de.id===Me):!1;(!Me||!je)&&(Me=ge.createTab(te),L.current[ie]=Me),m(te,Me,`Action: ${W.name}`),g(te,Me,W.icon||"play"),h(te,Me),X.revealTerminal!==!1&&le.getState().openContextPanelTab(te,{mode:"terminal"});const me=he.getState().getDirectoryState(te)?.tabs.find(de=>de.id===Me);return{key:ie,tabId:Me,sessionId:me?.terminalSessionId??null}},[b,te,h,g,m]),J=i.useCallback(async W=>{if(!n&&a)return;if(!te){ae.error("No active directory for action");return}const X=es(te,W.id),ie=w[X];if(!(ie&&ie.status==="running")&&!M.current.has(X)){M.current.add(X);try{const ge=W.id===St?await(async()=>{const[ye,re]=await Promise.all([Ar({id:$?.id??"",path:te}),Wm(te)]),Fe=await _m(te,ye.actions,re);if(!Fe)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:St,name:"Auto-discover",command:Fe.command,icon:"scan-2",autoOpenUrl:!0,openUrl:Fe.previewUrlHint||""}})():W,be=ge.autoOpenUrl===!0&&(ge.openUrl||"").trim().length>0,Me=!be&&W.id!==St,{key:je,tabId:ee,sessionId:me}=await K(ge,{revealTerminal:Me});let de=me;if(!de){v(te,ee,!0);try{de=(await o.createSession({cwd:te,sessionId:ee,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(te,ee,de)}finally{v(te,ee,!1)}}if(!de)throw new Error("Failed to create terminal session");Q.current[je]?.(),v(te,ee,!0);const ke=o.connect(de,{onEvent:ye=>{ye.type==="snapshot"&&(he.getState().replaceBuffer(te,ee,ye.data??"",ye.sequence??0),he.getState().setConnecting(te,ee,!1)),ye.type==="data"&&typeof ye.data=="string"&&ye.data.length>0&&he.getState().appendToBuffer(te,ee,ye.data,ye.sequence,ye.replayData),ye.type==="exit"&&(he.getState().setTabLifecycle(te,ee,"exited"),he.getState().setConnecting(te,ee,!1),he.getState().removeProjectActionRun(je),delete z.current[je],Q.current[je]?.(),delete Q.current[je],window.clearTimeout(O.current[je]),delete O.current[je])},onError:(ye,re)=>{he.getState().setConnecting(te,ee,!1),re&&(he.getState().setTabLifecycle(te,ee,"exited"),he.getState().setTabSessionId(te,ee,null),he.getState().removeProjectActionRun(je))}});Q.current[je]=ke.close;const We=ge.autoOpenUrl?Fm(ge.openUrl):null;A({key:je,directory:te,actionId:ge.id,tabId:ee,sessionId:de,status:ge.id===St&&!We?"waiting-for-preview":"running"}),window.clearTimeout(O.current[je]),delete O.current[je],ge.id===St&&!We&&(O.current[je]=window.setTimeout(()=>{const ye=he.getState(),re=ye.projectActionRuns[je];ye.updateProjectActionRunStatus(je,"running"),re&&(ye.setActiveTab(re.directory,re.tabId),le.getState().openContextPanelTab(re.directory,{mode:"terminal"})),delete O.current[je]},Pm)),z.current[je]={lastSeenChunkId:null,openedUrl:!!We||be,tail:"",openInPreview:ge.id===St};const He=Mm(ge.command.trim().replace(/\r\n|\r/g,`
53
- `));await o.sendInput(de,`${He}\r`),We?(I(te,ee,We,{locked:!0,autoOpened:!0}),p(te,We),ae.success("Opened action URL")):be?(I(te,ee,null,{locked:!0}),ae.error("Invalid custom URL format")):I(te,ee,null,{locked:!1,autoOpened:!1})}catch(ge){C(X),delete z.current[X],Q.current[X]?.(),delete Q.current[X],window.clearTimeout(O.current[X]),delete O.current[X],ae.error(ge instanceof Error?ge.message:"Failed to run action")}finally{M.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,K,n,a,te,c,l,p,w,C,v,A,I,x,$?.id,o]),Z=i.useCallback(async W=>{const X=es(te,W.id),ie=w[X];if(!ie)return;N(X,"stopping");const ge=Hm(o,ie.sessionId,1e3);try{await o.sendInput(ie.sessionId,"")}catch{}const be=await ge;if(he.getState().getDirectoryState(ie.directory)?.tabs.find(ee=>ee.id===ie.tabId)?.terminalSessionId===ie.sessionId&&!be){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ie.sessionId})}catch{}else try{await o.close(ie.sessionId)}catch{}x(ie.directory,ie.tabId,null)}C(X),delete z.current[X],Q.current[X]?.(),delete Q.current[X],window.clearTimeout(O.current[X]),delete O.current[X]},[te,w,C,x,o,N]),pe=i.useCallback(()=>{const W=Pe??F[0];if(!W)return;const X=es(te,W.id),ie=w[X];if(ie?.status!=="stopping"){if(ie){Z(W);return}J(W)}},[F,te,J,w,Pe,Z]),Se=i.useCallback((W,X=!1)=>{if(E(W.id),!X){J(W);return}const ie=es(te,W.id),ge=w[ie];if(ge?.status!=="stopping"){if(ge){Z(W);return}J(W)}},[te,J,w,Z]),xe=i.useCallback(()=>{$?.id&&(f($.id),u("projects"),d(!0))},[d,u,f,$?.id]),ne=Pe??F[0]??null,ce=ne?w[es(te,ne.id)]:null,q=he(W=>ce?W.sessions.get(ce.directory)?.tabs.find(X=>X.id===ce.tabId)?.previewUrl??null:null),fe=!!((n||!a)&&$&&te),_e=Pe??F[0]??null;return{shouldRender:fe,isLoading:P,normalizedDirectory:te,resolvedSelected:_e,displayActions:F,projectActionRuns:w,selectedRunPreviewUrl:q,handlePrimaryClick:pe,handleSelectAction:Se,openProjectActionsSettings:xe,openContextPreview:p}}const yi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:u,displayActions:d,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:b,handleSelectAction:m,openProjectActionsSettings:g,openContextPreview:h}=Ym({projectRef:e,directory:s,allowMobile:o});if(!a||!u)return null;const v=u.icon||"play",x=u.id===St?"scan-2":ln[v]||"play",I=es(c,u.id),w=f[I],A=w?.status==="stopping",N=w?.status==="waiting-for-preview",C=!!(w&&p),j=()=>{!w||!p||h(w.directory,p)},y=u.id===St;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||A,className:U("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:b,"aria-label":w?`Stop ${u.name}`:`Run ${u.name}`,children:A||N?t.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?t.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-5 w-5"})})}),y?t.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:j,children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Ot,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(vs,{}),d.map(k=>{const E=k.icon||"play",P=k.id===St?"scan-2":ln[E]||"play",B=es(c,k.id),L=f[B],z=!!L,Q=L?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m(k,!0)},children:[t.jsx(R,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),Q||L?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):z?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]}):t.jsxs("div",{className:U("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,disabled:l||A,className:U("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":w?`Stop ${u.name}`:`Run ${u.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||N?t.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?t.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-4 w-4"})})})}),y?t.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j,className:U(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:U(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Ot,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(vs,{}),d.map(k=>{const E=k.icon||"play",P=k.id===St?"scan-2":ln[E]||"play",B=es(c,k.id),L=f[B],z=!!L,Q=L?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m(k,!0)},children:[t.jsx(R,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),Q||L?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):z?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]})},qm=i.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:o,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:U(bn,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Ot,{align:"end",className:"w-64",children:[t.jsx(Fc,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(vs,{}),r.map(u=>{const d=u.user,f=!!u.current,p=u.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(rt,{className:"gap-2",disabled:l,onSelect:()=>{f||c(u.id)},children:[d?.avatarUrl?t.jsx("img",{src:d.avatarUrl,alt:d.login?`${d.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(R,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:d?.name?.trim()||d?.login||"GitHub"}),d?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:d.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:p})]}):null]}),f?t.jsx(R,{name:"check",className:"h-4 w-4 text-primary"}):null]},u.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Qm=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:u,remoteUpdateInfo:d,remoteUpdateChecking:f,remoteUpdateError:p,onOpenRemoteUpdate:b}){return t.jsxs(Mt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Ft,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:U(bn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(R,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),t.jsx(Ot,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[o?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:d?.available?`Version ${d.version||""} is available for this instance.`:f?"Looking for updates...":p||"This instance is up to date."})]}),d?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:b,children:"Update"}):null]})}),t.jsx(Oc,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Vm=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Ht,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(us,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ss,{children:[t.jsx(Te,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Te,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Jm=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},Zs=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Xm=i.lazy(()=>ls(()=>import("./SessionSwitcherDropdown-D_9pieby.js"),__vite__mapDeps([116,24,4,5,1,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),Jg=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Pt("ui.header.render");const l=le(D=>D.setSessionSwitcherOpen),c=le(D=>D.toggleSidebar),u=le(D=>D.isSidebarOpen),d=le(D=>D.activeMainTab),f=le(D=>D.setActiveMainTab),p=le(D=>D.shortcutOverrides);le(D=>D.timeFormatPreference),Gs();const b=Ee(D=>!!D.newSessionDraft?.open),m=Ee(D=>D.currentSessionId),g=Ti(m??""),h=Lc(m),v=i.useMemo(()=>{if(!h)return null;const D=h;return{title:h.title??null,directory:D.directory??null,created:h.time?.created??null,slug:D.slug??null,shareUrl:h.share?.url??null,parentId:h.parentID??null}},[h]),x=pt(Fr(D=>{if(!D.activeProjectId)return null;const oe=D.projects.find(ve=>ve.id===D.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),I=Bs(D=>D.homeDirectory),w=i.useMemo(()=>{if(!x)return null;const D=x.label?.trim();if(D)return D;const oe=x.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[x]),{isMobile:A}=$s(),{enabled:N}=Qr(),C=!!(N&&a&&o!==void 0),j=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[y,k]=i.useState(!1),E=null,P=i.useRef(null),[B,L]=i.useState(()=>typeof window>"u"?!1:Ls()),z=i.useMemo(()=>Bi(),[]),Q=Bc(),[O,M]=i.useState(!1),T=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),_=Mi(),se=i.useMemo(()=>{if(typeof window>"u")return null;const D=window.__PICHAMBER_MACOS_MAJOR__;if(typeof D=="number"&&Number.isFinite(D)&&D>0)return D;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const ve=Number.parseInt(oe[1],10),Ue=Number.parseInt(oe[2],10);return Number.isNaN(ve)?null:ve===10?Ue:ve},[]);Ie.useEffect(()=>{typeof window>"u"||L(Ls())},[]);const $=le(D=>D.isSessionSwitcherOpen),G=null,Ae=null,te=[],[Pe,Be]=i.useState(!1),[Y,F]=i.useState(!1),[K,J]=i.useState("Local"),[Z,pe]=i.useState(!0),[Se,xe]=i.useState(!1),[ne,ce]=i.useState(null),[q,fe]=i.useState(!1),[_e,W]=i.useState(null),X=i.useRef(0),ie=i.useMemo(()=>Jm(K),[K]),ge=i.useCallback(async()=>{if(typeof window>"u"||!B)return;const D=Xe(),oe=()=>Xe()===D;try{if(un()){J("Local"),pe(!0);return}pe(!1);const ve=await vd();if(!oe())return;const Ue=Sd(),ct=jd([kd(Ue),...ve.hosts]);if(ct.id===Cd){J("Local"),pe(!0);return}J(Ad(ct.label.trim()||"Instance"))}catch{oe()&&(J("Local"),pe(!0))}},[B]);Ie.useEffect(()=>(ge(),Nd(()=>{X.current+=1,ce(null),W(null),fe(!1),xe(!1),ge()})),[ge]);const be=i.useCallback(async()=>{const D=X.current+1;X.current=D;const oe=Xe(),ve=()=>X.current===D&&Xe()===oe;if(Z){ce(null),W(null);return}fe(!0),W(null);try{const Ue=new URLSearchParams({appType:"web",instanceMode:"remote"}),ct=await Nt(`/api/pi/update-check?${Ue.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ct.ok)throw new Error(`Server responded with ${ct.status}`);const Je=await ct.json();if(!ve())return;ce({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch(Ue){if(!ve())return;ce(null),W(Ue instanceof Error?Ue.message:"Failed to check remote instance updates")}finally{ve()&&fe(!1)}},[Z]);i.useEffect(()=>rf(()=>{Z||be()}),[be,Z]),i.useEffect(()=>{X.current+=1,ce(null),W(null),fe(!1),xe(!1)},[Z,K]),i.useEffect(()=>{if(!B||Z)return;const D=3e3,oe=3600*1e3;let ve=!1,Ue=null;const ct=Je=>{Ue=window.setTimeout(()=>{if(ve||typeof document<"u"&&document.visibilityState!=="visible"){ct(oe);return}be().finally(()=>{ve||ct(oe)})},Je)};return ct(D),()=>{ve=!0,Ue!==null&&window.clearTimeout(Ue)}},[be,Z,K,B]);const Me=i.useCallback(()=>{if(ne?.available){xe(!0);return}be()},[be,ne?.available]),je=m?v??null:null,ee=i.useRef(null),[me,de]=i.useState(0);i.useEffect(()=>{if(!m){ee.current&&(ee.current=null,de(Ue=>Ue+1));return}if(je){ee.current={sessionId:m,session:je,expiresAt:Date.now()+2e3};return}const D=ee.current;if(!D||D.sessionId!==m)return;const oe=D.expiresAt-Date.now();if(oe<=0){ee.current=null,de(Ue=>Ue+1);return}const ve=window.setTimeout(()=>{ee.current?.sessionId===m&&(ee.current=null),de(Ue=>Ue+1)},oe);return()=>{window.clearTimeout(ve)}},[m,je]);const ke=(()=>{if(je)return je;if(!m)return null;const D=ee.current;return D&&D.sessionId===m&&D.expiresAt>Date.now()?D.session:null})(),We=i.useMemo(()=>{const D=typeof ke?.directory=="string"?ke.directory:"";return Zs(D||"")},[ke?.directory]),He=Ee(D=>D.newSessionDraft?.open?Zs(D.newSessionDraft.directoryOverride??""):""),ye=i.useMemo(()=>km({sessionDirectory:We,draftDirectory:He,isNewSessionDraftOpen:b}),[He,b,We]),Fe=Di(ye||null),De=i.useMemo(()=>Cm({activeProjectLabel:w,openDirectory:ye,homeDirectory:I}),[w,I,ye]),ot=!!(De||Fe),it=i.useMemo(()=>m?cs(ke):De??"PiChamber",[ke,m,De]),Ve=_c(),Lt=Ee(D=>D.updateSessionTitle),It=Ee(D=>D.archiveSessions),jt=Ee(D=>D.deleteSessions),[Bt,et]=i.useState(!1),[mt,tt]=i.useState(!1),gt=i.useRef(!1),[kt,qt]=i.useState(""),[yt,we]=i.useState(null),Oe=i.useRef(null);i.useEffect(()=>{gt.current=!1,tt(!1),et(!1),qt(""),we(null)},[m]);const Ce=i.useCallback(()=>{m&&(qt(ke?.title?.trim()||it),et(!0))},[ke?.title,m,it]),Le=i.useCallback(async()=>{if(!m)return;const D=kt.trim();D&&D!==ke?.title?.trim()&&await Lt(m,D),et(!1)},[ke?.title,m,kt,Lt]);i.useEffect(()=>{if(!Bt)return;const D=oe=>{const ve=oe.target;(!ve||!Oe.current?.contains(ve))&&Le()};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[Bt,Le]);const Ye=i.useCallback(()=>{m&&ws(m).then(D=>{ae[D.ok?"success":"error"](D.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ae.error("Failed to copy session ID"))},[m]),ut=i.useCallback(async()=>{if(!m||!ye){ae.error("Nothing to export");return}try{await Ve.syncSession(m)}catch{ae.error("Failed to load the complete session history");return}const D=[];if(D.length===0){ae.error("Nothing to export");return}const oe=Ma(D,ke?.title??null),ve=La(ke?.title??null);await Oa(oe,ve)||Fa(oe,ve),ae.success("Session exported")},[ke?.title,m,ye,Ve]);g?.type==="busy"||g?.type;const Rt=i.useCallback(async()=>{if(!m||!yt)return;const D=Uc(),oe=[m];for(let Je=0;Je<oe.length;Je+=1){const Qs=oe[Je];for(const Jt of D)Jt.parentID===Qs&&!oe.includes(Jt.id)&&oe.push(Jt.id)}const ve=yt;if(we(null),(ve==="archive"?await It(oe):await jt(oe)).failedIds.length>0){ae.error(ve==="archive"?"Failed to archive session":"Failed to delete session");return}ae.success(ve==="archive"?"Session archived":"Session deleted")},[It,m,jt,yt]),Et=le(D=>D.isArchivePageOpen),_t=i.useMemo(()=>Et?{title:"Archive",subtitle:null}:null,[Et]),qe=i.useMemo(()=>Zs(ye||x?.path||""),[x?.path,ye]),st=i.useCallback(()=>{qe&&ws(qe).then(D=>{ae[D.ok?"success":"error"](D.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ae.error("Failed to copy working directory"))},[qe]),wt=i.useMemo(()=>x?{id:x.id,path:x.path}:null,[x]),Ut=i.useRef(null);i.useEffect(()=>{!wt||!qe||(Ut.current={projectRef:wt,directory:qe})},[qe,wt]);const bt=i.useMemo(()=>wt&&qe?{projectRef:wt,directory:qe}:Ut.current,[qe,wt]),Ks=i.useCallback(async D=>{},[]),zt=i.useCallback(()=>{if(typeof document>"u")return;const D=document.activeElement;if(!D)return;const oe=D.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||D.isContentEditable)&&D.blur()},[]),Cs=i.useCallback(()=>{if(A){zt(),l(!$);return}c()},[zt,A,$,l,c]),As=i.useCallback(()=>{on("desktop_open_draft_mini_chat_window",{directory:Zs(ye||x?.path||""),projectId:x?.id??null,apiBaseUrl:Dr(),clientToken:Er()}).catch(D=>{console.warn("[header] failed to open draft mini chat window",D)})},[x?.id,x?.path,ye]),$t=i.useCallback(()=>{if(b){As();return}m&&on("desktop_open_session_mini_chat_window",{sessionId:m,directory:Zs(ye||x?.path||""),apiBaseUrl:Dr(),clientToken:Er()}).catch(D=>{console.warn("[header] failed to open session mini chat window",D)})},[x?.path,m,As,b,ye]),Qt=bn,at=Ef,ue=i.useMemo(()=>n?"sessions":C?r&&o?o:null:r?"git":d,[d,C,n,r,o]),Ze=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&$&&l(!1)},[$,n,e,s,r,l]),ft=i.useCallback(()=>{e?.()},[e]),vt=i.useCallback(()=>{s?.()},[s]),ns=i.useMemo(()=>B&&T&&!O?"5.5rem":Q?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!B||_?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[B,O,T,Q,_]);Ie.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ns)},[ns]);const lt=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",xn=u?"0px":B&&_?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":N?"2.75rem":"2.5rem";Ie.useEffect(()=>{if(!B||!T){M(!1);return}let D=!1;const oe=async()=>{try{const Ue=await on("desktop_is_window_fullscreen");D||M(Ue===!0)}catch{D||M(!1)}},ve=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",ve),()=>{D=!0,window.removeEventListener("pichamber:window-resized",ve)}},[B,T]);const Ws=i.useMemo(()=>!B||!T||se===null?"":se>=26?"h-12":se<=15?"h-14":"",[B,T,se]),Qn=i.useMemo(()=>{if(!(B&&!_))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))"}},[B,_]),Vt=i.useCallback(()=>{if(typeof document>"u")return;const D=P.current?.getBoundingClientRect().height;D&&document.documentElement.style.setProperty("--oc-header-height",`${D}px`)},[]);Ie.useEffect(()=>{if(typeof window>"u")return;Vt();const D=P.current;if(!D||typeof ResizeObserver>"u")return()=>{};let oe=0;const ve=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,Vt()}))},Ue=new ResizeObserver(ve);return Ue.observe(D),window.addEventListener("resize",ve),window.addEventListener("orientationchange",ve),()=>{oe&&cancelAnimationFrame(oe),Ue.disconnect(),window.removeEventListener("resize",ve),window.removeEventListener("orientationchange",ve)}},[Vt]),Ie.useEffect(()=>{Vt()},[Vt,A,Ws]);const Vn=i.useCallback(async D=>{const oe=D.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||D.button===0&&B&&await zc()},[B]),rs=i.useMemo(()=>A?[{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"}]:[],[A]),yn=i.useCallback(D=>Zr(Bn(D,p)),[p]);Ie.useEffect(()=>{!A&&d!=="chat"&&d!=="terminal"&&d!=="diagram"&&f("chat")},[d,A,f]),Ie.useEffect(()=>{const D=oe=>{if(Id(oe)&&!oe.shiftKey&&!oe.altKey){const ve=parseInt(oe.key,10);ve>=1&&ve<=rs.length&&(oe.preventDefault(),A&&(zt(),Ze()),f(rs[ve-1].id))}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[zt,Ze,A,f,rs]),Ie.useEffect(()=>{const D=oe=>{const ve=Bn("toggle_services_menu",p);if(Rd(oe,ve)){oe.preventDefault(),Y?F(!1):(F(!0),ge());return}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[p,Y,ge]);const Hs=D=>{const oe=d===D.id,ve=D.icon==="diff",Ue=ve?null:D.icon,ct=D.id==="chat",Je=Jt=>ve?t.jsx(gi,{size:Jt}):Ue?t.jsx(R,{name:Ue,className:`h-${Jt/4} w-${Jt/4}`}):null,Qs=t.jsxs("button",{type:"button",onClick:()=>f(D.id),className:U("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",oe?"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",ct&&!A&&"min-w-[100px] justify-center"),"aria-label":D.label,"aria-selected":oe,role:"tab",children:[A?Je(20):t.jsxs(t.Fragment,{children:[Je(16),t.jsx("span",{className:"header-tab-label",children:D.label})]}),D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:D.badge})]});return t.jsx(i.Fragment,{children:Qs},D.id)},Ns=t.jsxs(t.Fragment,{children:[t.jsx(Rm,{directory:qe,className:"mr-1"}),B?t.jsx(Qm,{isDesktopApp:B,currentInstanceLabel:K,compactCurrentInstanceLabel:ie,currentInstanceIsLocal:Z,isDesktopServicesOpen:Y,setIsDesktopServicesOpen:F,refreshCurrentInstanceLabel:ge,shortcutLabel:yn,remoteUpdateInfo:ne,remoteUpdateChecking:q,remoteUpdateError:_e,onOpenRemoteUpdate:Me}):null,t.jsx(qm,{isMobile:A,githubAuthStatus:E,githubAccounts:te,githubAvatarUrl:G,githubLogin:Ae,isSwitchingGitHubAccount:Pe,handleGitHubAccountSwitch:Ks})]}),Jn=z&&(b||!!m),Xn=()=>t.jsxs("div",{onMouseDown:Vn,className:U("app-region-drag relative flex h-12 select-none items-center pr-3",Ws),style:Qn,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:lt}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:xn}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[_t?t.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:_t.title}),_t.subtitle?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:_t.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[u?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Qt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Xm,{align:"start",children:t.jsx("button",{type:"button",className:Qt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Bt?t.jsxs("form",{ref:Oe,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:D=>{D.preventDefault(),Le()},children:[t.jsx("input",{value:kt,onChange:D=>qt(D.target.value),autoFocus:!0,onKeyDown:D=>{D.stopPropagation(),D.key==="Escape"&&et(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>et(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":it}),ot?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[De?t.jsx("span",{className:"truncate",children:De}):null,Fe?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:Fe})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!b&&!Bt?t.jsxs(Mt,{open:mt,onOpenChange:tt,onOpenChangeComplete:D=>{!D&&gt.current&&(gt.current=!1,Ce())},children:[t.jsx(Ft,{asChild:!0,children:t.jsx(Te,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(R,{name:"more",className:"size-4"})})}),t.jsxs(Ot,{align:"end",className:"min-w-[190px]",children:[t.jsxs(rt,{onClick:()=>{gt.current=!0},children:[t.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(rt,{onClick:Ye,children:[t.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(rt,{onClick:st,disabled:!qe,children:[t.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>{ut()},children:[t.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>we("archive"),children:[t.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(rt,{className:"text-destructive focus:text-destructive",onClick:()=>we("delete"),children:[t.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),rs.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:rs.map(D=>Hs(D))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(va,{}),bt?t.jsx(yi,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,t.jsx(Df,{visible:Jn,title:b?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:$t,className:U(Qt,"mr-1"),Icon:"picture-in-picture-2"}),Ns,t.jsx($c,{visible:_})]})]})]}),Ys=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:lt}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:xn}})]}),!N&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:ft,className:U(at,ue==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):$?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Cs,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&$&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!$||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!C&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:rs.map(D=>{const oe=d===D.id,ve=D.icon==="diff",Ue=ve?null:D.icon;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{A&&(zt(),Ze()),f(D.id)},"aria-label":D.label,"aria-selected":oe,role:"tab",className:U(at,"relative rounded-lg",ue===D.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ve?t.jsx(gi,{className:"h-5 w-5"}):Ue?t.jsx(R,{name:Ue,className:"h-5 w-5"}):null,D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:D.badge}),D.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[C&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:j.map(D=>{const oe=r&&o===D.id;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{A&&(zt(),Ze()),k(!1),a?.(D.id)},"aria-label":D.label,"aria-selected":oe,role:"tab",className:U(at,"relative rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:D.icon,className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})}),t.jsx(Rf,{open:y,onOpenChange:k,currentSessionId:m,effectiveDirectory:ye||null,isNewSessionDraftOpen:b})]}),bt&&t.jsx(yi,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!C?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:vt,className:U(at,"relative",ue==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),qs=U("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:qs,style:{"--padding-scale":"1"},children:A?Ys():Xn()}),t.jsx(Vm,{action:yt,onClose:()=>we(null),sessionTitle:it,onConfirm:()=>{Rt()}}),t.jsx(fa,{open:Se,onOpenChange:xe,info:ne,downloading:!1,downloaded:!1,progress:null,error:_e,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},wi="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",Zm="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Xg=()=>{const e=le(m=>m.isSidebarOpen),s=le(m=>m.toggleSidebar),n=le(m=>m.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=Zr(Bn("toggle_sidebar",n)),l=Mi(),{enabled:c}=Qr(),u=!e,d=l,f=u||d,p=d,b=i.useCallback(()=>{on("desktop_show_app_menu").catch(m=>{console.warn("[titlebar] failed to open app menu",m)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const m=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},g=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const h=o.current,v=r.current;if(!h||!v){m(0),g(0);return}const x=()=>{const w=Math.max(h.getBoundingClientRect().width,h.scrollWidth);m(w),g(v.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const I=new ResizeObserver(x);return I.observe(h),I.observe(v),()=>{I.disconnect()}},[p]),f?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[d?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:U(wi,"shrink-0"),children:t.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:U(c?Zm:wi,"shrink-0"),children:t.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},vi=200,eg="cubic-bezier(0.22, 1, 0.36, 1)",Zg=e=>{const s=i.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=i.useState(e),[o,a]=i.useState(e);return i.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),vi);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${vi}ms ${eg}`}},eb=()=>{Ui()},tb=e=>{Ee.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),Ui(),Bs.getState().resetForRuntimeSwitch(),Gc.getState().resetForRuntimeSwitch(),Kc.getState().resetForRuntimeSwitch(),Wc(),Hc.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),pt.getState().resetForRuntimeSwitch(),Yc(),qc(),au.getState().reset(),Ed.getState().resetForRuntimeSwitch(),Ri.getState().resetForRuntimeSwitch(e.runtimeKey),Ir.getState().resetForRuntimeSwitch(e.runtimeKey),ys.getState().resetForRuntimeSwitch(e.runtimeKey),hh.getState().resetForRuntimeSwitch(),ht.getState().resetForRuntimeSwitch(e.runtimeKey),Dd.getState().resetForRuntimeSwitch(e.runtimeKey),Ee.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=le.getState();Lr({sessionId:Ee.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0})};export{ma as $,Gg as A,Yo as B,$g as C,ci as D,Vg as E,jg as F,Pu as G,Jg as H,wg as I,fs as J,Su as K,hs as L,wa as M,kg as N,tf as O,Og as P,Vu as Q,Ag as R,Kg as S,qg as T,zg as U,Pg as V,yg as W,fa as X,so as Y,Dg as Z,ef as _,Nf as a,Sf as a0,Qu as a1,sf as a2,mn as a3,ha as a4,gn as a5,an as a6,Ju as a7,Ng as a8,Xu as a9,Fg as aa,_g as ab,Bg as ac,nf as ad,Mg as ae,Lg as af,Ug as ag,Cg as ah,Ig as ai,Rg as aj,Eg as ak,bf as al,Tg as am,Fu as an,Zu as ao,Ou as ap,bg as aq,Rf as b,en as c,Tp as d,Wg as e,On as f,Hg as g,Zg as h,Fp as i,Qg as j,Xg as k,tb as l,vg as m,Sg as n,xg as o,gg as p,no as q,eb as r,Yg as s,ro as t,Mn as u,oo as v,Os as w,ya as x,jf as y,kf as z};
53
+ `));await o.sendInput(de,`${He}\r`),We?(I(te,ee,We,{locked:!0,autoOpened:!0}),p(te,We),ae.success("Opened action URL")):be?(I(te,ee,null,{locked:!0}),ae.error("Invalid custom URL format")):I(te,ee,null,{locked:!1,autoOpened:!1})}catch(ge){C(X),delete z.current[X],Q.current[X]?.(),delete Q.current[X],window.clearTimeout(O.current[X]),delete O.current[X],ae.error(ge instanceof Error?ge.message:"Failed to run action")}finally{M.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,K,n,a,te,c,l,p,w,C,v,A,I,x,$?.id,o]),Z=i.useCallback(async W=>{const X=es(te,W.id),ie=w[X];if(!ie)return;N(X,"stopping");const ge=Hm(o,ie.sessionId,1e3);try{await o.sendInput(ie.sessionId,"")}catch{}const be=await ge;if(he.getState().getDirectoryState(ie.directory)?.tabs.find(ee=>ee.id===ie.tabId)?.terminalSessionId===ie.sessionId&&!be){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ie.sessionId})}catch{}else try{await o.close(ie.sessionId)}catch{}x(ie.directory,ie.tabId,null)}C(X),delete z.current[X],Q.current[X]?.(),delete Q.current[X],window.clearTimeout(O.current[X]),delete O.current[X]},[te,w,C,x,o,N]),pe=i.useCallback(()=>{const W=Pe??F[0];if(!W)return;const X=es(te,W.id),ie=w[X];if(ie?.status!=="stopping"){if(ie){Z(W);return}J(W)}},[F,te,J,w,Pe,Z]),Se=i.useCallback((W,X=!1)=>{if(E(W.id),!X){J(W);return}const ie=es(te,W.id),ge=w[ie];if(ge?.status!=="stopping"){if(ge){Z(W);return}J(W)}},[te,J,w,Z]),xe=i.useCallback(()=>{$?.id&&(f($.id),u("projects"),d(!0))},[d,u,f,$?.id]),ne=Pe??F[0]??null,ce=ne?w[es(te,ne.id)]:null,q=he(W=>ce?W.sessions.get(ce.directory)?.tabs.find(X=>X.id===ce.tabId)?.previewUrl??null:null),fe=!!((n||!a)&&$&&te),_e=Pe??F[0]??null;return{shouldRender:fe,isLoading:P,normalizedDirectory:te,resolvedSelected:_e,displayActions:F,projectActionRuns:w,selectedRunPreviewUrl:q,handlePrimaryClick:pe,handleSelectAction:Se,openProjectActionsSettings:xe,openContextPreview:p}}const yi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:u,displayActions:d,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:b,handleSelectAction:m,openProjectActionsSettings:g,openContextPreview:h}=Ym({projectRef:e,directory:s,allowMobile:o});if(!a||!u)return null;const v=u.icon||"play",x=u.id===St?"scan-2":ln[v]||"play",I=es(c,u.id),w=f[I],A=w?.status==="stopping",N=w?.status==="waiting-for-preview",C=!!(w&&p),j=()=>{!w||!p||h(w.directory,p)},y=u.id===St;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||A,className:U("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:b,"aria-label":w?`Stop ${u.name}`:`Run ${u.name}`,children:A||N?t.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?t.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-5 w-5"})})}),y?t.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:j,children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Ot,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(vs,{}),d.map(k=>{const E=k.icon||"play",P=k.id===St?"scan-2":ln[E]||"play",B=es(c,k.id),L=f[B],z=!!L,Q=L?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m(k,!0)},children:[t.jsx(R,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),Q||L?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):z?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]}):t.jsxs("div",{className:U("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,disabled:l||A,className:U("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":w?`Stop ${u.name}`:`Run ${u.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||N?t.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?t.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-4 w-4"})})})}),y?t.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j,className:U(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:U(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Ot,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(vs,{}),d.map(k=>{const E=k.icon||"play",P=k.id===St?"scan-2":ln[E]||"play",B=es(c,k.id),L=f[B],z=!!L,Q=L?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m(k,!0)},children:[t.jsx(R,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),Q||L?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):z?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]})},qm=i.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:o,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Mt,{children:[t.jsx(Ft,{asChild:!0,children:t.jsx("button",{type:"button",className:U(bn,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Ot,{align:"end",className:"w-64",children:[t.jsx(Fc,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(vs,{}),r.map(u=>{const d=u.user,f=!!u.current,p=u.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(rt,{className:"gap-2",disabled:l,onSelect:()=>{f||c(u.id)},children:[d?.avatarUrl?t.jsx("img",{src:d.avatarUrl,alt:d.login?`${d.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(R,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:d?.name?.trim()||d?.login||"GitHub"}),d?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:d.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:p})]}):null]}),f?t.jsx(R,{name:"check",className:"h-4 w-4 text-primary"}):null]},u.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Qm=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:u,remoteUpdateInfo:d,remoteUpdateChecking:f,remoteUpdateError:p,onOpenRemoteUpdate:b}){return t.jsxs(Mt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Ft,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:U(bn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(R,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),t.jsx(Ot,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[o?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:d?.available?`Version ${d.version||""} is available for this instance.`:f?"Looking for updates...":p||"This instance is up to date."})]}),d?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:b,children:"Update"}):null]})}),t.jsx(Oc,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Vm=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Ht,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(us,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ss,{children:[t.jsx(Te,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Te,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Jm=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},Zs=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Xm=i.lazy(()=>ls(()=>import("./SessionSwitcherDropdown-CUyTFUnd.js"),__vite__mapDeps([116,24,4,5,1,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),Jg=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Pt("ui.header.render");const l=le(D=>D.setSessionSwitcherOpen),c=le(D=>D.toggleSidebar),u=le(D=>D.isSidebarOpen),d=le(D=>D.activeMainTab),f=le(D=>D.setActiveMainTab),p=le(D=>D.shortcutOverrides);le(D=>D.timeFormatPreference),Gs();const b=Ee(D=>!!D.newSessionDraft?.open),m=Ee(D=>D.currentSessionId),g=Ti(m??""),h=Lc(m),v=i.useMemo(()=>{if(!h)return null;const D=h;return{title:h.title??null,directory:D.directory??null,created:h.time?.created??null,slug:D.slug??null,shareUrl:h.share?.url??null,parentId:h.parentID??null}},[h]),x=pt(Fr(D=>{if(!D.activeProjectId)return null;const oe=D.projects.find(ve=>ve.id===D.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),I=Bs(D=>D.homeDirectory),w=i.useMemo(()=>{if(!x)return null;const D=x.label?.trim();if(D)return D;const oe=x.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[x]),{isMobile:A}=$s(),{enabled:N}=Qr(),C=!!(N&&a&&o!==void 0),j=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[y,k]=i.useState(!1),E=null,P=i.useRef(null),[B,L]=i.useState(()=>typeof window>"u"?!1:Ls()),z=i.useMemo(()=>Bi(),[]),Q=Bc(),[O,M]=i.useState(!1),T=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),_=Mi(),se=i.useMemo(()=>{if(typeof window>"u")return null;const D=window.__PICHAMBER_MACOS_MAJOR__;if(typeof D=="number"&&Number.isFinite(D)&&D>0)return D;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const ve=Number.parseInt(oe[1],10),Ue=Number.parseInt(oe[2],10);return Number.isNaN(ve)?null:ve===10?Ue:ve},[]);Ie.useEffect(()=>{typeof window>"u"||L(Ls())},[]);const $=le(D=>D.isSessionSwitcherOpen),G=null,Ae=null,te=[],[Pe,Be]=i.useState(!1),[Y,F]=i.useState(!1),[K,J]=i.useState("Local"),[Z,pe]=i.useState(!0),[Se,xe]=i.useState(!1),[ne,ce]=i.useState(null),[q,fe]=i.useState(!1),[_e,W]=i.useState(null),X=i.useRef(0),ie=i.useMemo(()=>Jm(K),[K]),ge=i.useCallback(async()=>{if(typeof window>"u"||!B)return;const D=Xe(),oe=()=>Xe()===D;try{if(un()){J("Local"),pe(!0);return}pe(!1);const ve=await vd();if(!oe())return;const Ue=Sd(),ct=jd([kd(Ue),...ve.hosts]);if(ct.id===Cd){J("Local"),pe(!0);return}J(Ad(ct.label.trim()||"Instance"))}catch{oe()&&(J("Local"),pe(!0))}},[B]);Ie.useEffect(()=>(ge(),Nd(()=>{X.current+=1,ce(null),W(null),fe(!1),xe(!1),ge()})),[ge]);const be=i.useCallback(async()=>{const D=X.current+1;X.current=D;const oe=Xe(),ve=()=>X.current===D&&Xe()===oe;if(Z){ce(null),W(null);return}fe(!0),W(null);try{const Ue=new URLSearchParams({appType:"web",instanceMode:"remote"}),ct=await Nt(`/api/pi/update-check?${Ue.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ct.ok)throw new Error(`Server responded with ${ct.status}`);const Je=await ct.json();if(!ve())return;ce({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch(Ue){if(!ve())return;ce(null),W(Ue instanceof Error?Ue.message:"Failed to check remote instance updates")}finally{ve()&&fe(!1)}},[Z]);i.useEffect(()=>rf(()=>{Z||be()}),[be,Z]),i.useEffect(()=>{X.current+=1,ce(null),W(null),fe(!1),xe(!1)},[Z,K]),i.useEffect(()=>{if(!B||Z)return;const D=3e3,oe=3600*1e3;let ve=!1,Ue=null;const ct=Je=>{Ue=window.setTimeout(()=>{if(ve||typeof document<"u"&&document.visibilityState!=="visible"){ct(oe);return}be().finally(()=>{ve||ct(oe)})},Je)};return ct(D),()=>{ve=!0,Ue!==null&&window.clearTimeout(Ue)}},[be,Z,K,B]);const Me=i.useCallback(()=>{if(ne?.available){xe(!0);return}be()},[be,ne?.available]),je=m?v??null:null,ee=i.useRef(null),[me,de]=i.useState(0);i.useEffect(()=>{if(!m){ee.current&&(ee.current=null,de(Ue=>Ue+1));return}if(je){ee.current={sessionId:m,session:je,expiresAt:Date.now()+2e3};return}const D=ee.current;if(!D||D.sessionId!==m)return;const oe=D.expiresAt-Date.now();if(oe<=0){ee.current=null,de(Ue=>Ue+1);return}const ve=window.setTimeout(()=>{ee.current?.sessionId===m&&(ee.current=null),de(Ue=>Ue+1)},oe);return()=>{window.clearTimeout(ve)}},[m,je]);const ke=(()=>{if(je)return je;if(!m)return null;const D=ee.current;return D&&D.sessionId===m&&D.expiresAt>Date.now()?D.session:null})(),We=i.useMemo(()=>{const D=typeof ke?.directory=="string"?ke.directory:"";return Zs(D||"")},[ke?.directory]),He=Ee(D=>D.newSessionDraft?.open?Zs(D.newSessionDraft.directoryOverride??""):""),ye=i.useMemo(()=>km({sessionDirectory:We,draftDirectory:He,isNewSessionDraftOpen:b}),[He,b,We]),Fe=Di(ye||null),De=i.useMemo(()=>Cm({activeProjectLabel:w,openDirectory:ye,homeDirectory:I}),[w,I,ye]),ot=!!(De||Fe),it=i.useMemo(()=>m?cs(ke):De??"PiChamber",[ke,m,De]),Ve=_c(),Lt=Ee(D=>D.updateSessionTitle),It=Ee(D=>D.archiveSessions),jt=Ee(D=>D.deleteSessions),[Bt,et]=i.useState(!1),[mt,tt]=i.useState(!1),gt=i.useRef(!1),[kt,qt]=i.useState(""),[yt,we]=i.useState(null),Oe=i.useRef(null);i.useEffect(()=>{gt.current=!1,tt(!1),et(!1),qt(""),we(null)},[m]);const Ce=i.useCallback(()=>{m&&(qt(ke?.title?.trim()||it),et(!0))},[ke?.title,m,it]),Le=i.useCallback(async()=>{if(!m)return;const D=kt.trim();D&&D!==ke?.title?.trim()&&await Lt(m,D),et(!1)},[ke?.title,m,kt,Lt]);i.useEffect(()=>{if(!Bt)return;const D=oe=>{const ve=oe.target;(!ve||!Oe.current?.contains(ve))&&Le()};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[Bt,Le]);const Ye=i.useCallback(()=>{m&&ws(m).then(D=>{ae[D.ok?"success":"error"](D.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ae.error("Failed to copy session ID"))},[m]),ut=i.useCallback(async()=>{if(!m||!ye){ae.error("Nothing to export");return}try{await Ve.syncSession(m)}catch{ae.error("Failed to load the complete session history");return}const D=[];if(D.length===0){ae.error("Nothing to export");return}const oe=Ma(D,ke?.title??null),ve=La(ke?.title??null);await Oa(oe,ve)||Fa(oe,ve),ae.success("Session exported")},[ke?.title,m,ye,Ve]);g?.type==="busy"||g?.type;const Rt=i.useCallback(async()=>{if(!m||!yt)return;const D=Uc(),oe=[m];for(let Je=0;Je<oe.length;Je+=1){const Qs=oe[Je];for(const Jt of D)Jt.parentID===Qs&&!oe.includes(Jt.id)&&oe.push(Jt.id)}const ve=yt;if(we(null),(ve==="archive"?await It(oe):await jt(oe)).failedIds.length>0){ae.error(ve==="archive"?"Failed to archive session":"Failed to delete session");return}ae.success(ve==="archive"?"Session archived":"Session deleted")},[It,m,jt,yt]),Et=le(D=>D.isArchivePageOpen),_t=i.useMemo(()=>Et?{title:"Archive",subtitle:null}:null,[Et]),qe=i.useMemo(()=>Zs(ye||x?.path||""),[x?.path,ye]),st=i.useCallback(()=>{qe&&ws(qe).then(D=>{ae[D.ok?"success":"error"](D.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ae.error("Failed to copy working directory"))},[qe]),wt=i.useMemo(()=>x?{id:x.id,path:x.path}:null,[x]),Ut=i.useRef(null);i.useEffect(()=>{!wt||!qe||(Ut.current={projectRef:wt,directory:qe})},[qe,wt]);const bt=i.useMemo(()=>wt&&qe?{projectRef:wt,directory:qe}:Ut.current,[qe,wt]),Ks=i.useCallback(async D=>{},[]),zt=i.useCallback(()=>{if(typeof document>"u")return;const D=document.activeElement;if(!D)return;const oe=D.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||D.isContentEditable)&&D.blur()},[]),Cs=i.useCallback(()=>{if(A){zt(),l(!$);return}c()},[zt,A,$,l,c]),As=i.useCallback(()=>{on("desktop_open_draft_mini_chat_window",{directory:Zs(ye||x?.path||""),projectId:x?.id??null,apiBaseUrl:Dr(),clientToken:Er()}).catch(D=>{console.warn("[header] failed to open draft mini chat window",D)})},[x?.id,x?.path,ye]),$t=i.useCallback(()=>{if(b){As();return}m&&on("desktop_open_session_mini_chat_window",{sessionId:m,directory:Zs(ye||x?.path||""),apiBaseUrl:Dr(),clientToken:Er()}).catch(D=>{console.warn("[header] failed to open session mini chat window",D)})},[x?.path,m,As,b,ye]),Qt=bn,at=Ef,ue=i.useMemo(()=>n?"sessions":C?r&&o?o:null:r?"git":d,[d,C,n,r,o]),Ze=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&$&&l(!1)},[$,n,e,s,r,l]),ft=i.useCallback(()=>{e?.()},[e]),vt=i.useCallback(()=>{s?.()},[s]),ns=i.useMemo(()=>B&&T&&!O?"5.5rem":Q?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!B||_?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[B,O,T,Q,_]);Ie.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ns)},[ns]);const lt=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",xn=u?"0px":B&&_?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":N?"2.75rem":"2.5rem";Ie.useEffect(()=>{if(!B||!T){M(!1);return}let D=!1;const oe=async()=>{try{const Ue=await on("desktop_is_window_fullscreen");D||M(Ue===!0)}catch{D||M(!1)}},ve=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",ve),()=>{D=!0,window.removeEventListener("pichamber:window-resized",ve)}},[B,T]);const Ws=i.useMemo(()=>!B||!T||se===null?"":se>=26?"h-12":se<=15?"h-14":"",[B,T,se]),Qn=i.useMemo(()=>{if(!(B&&!_))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))"}},[B,_]),Vt=i.useCallback(()=>{if(typeof document>"u")return;const D=P.current?.getBoundingClientRect().height;D&&document.documentElement.style.setProperty("--oc-header-height",`${D}px`)},[]);Ie.useEffect(()=>{if(typeof window>"u")return;Vt();const D=P.current;if(!D||typeof ResizeObserver>"u")return()=>{};let oe=0;const ve=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,Vt()}))},Ue=new ResizeObserver(ve);return Ue.observe(D),window.addEventListener("resize",ve),window.addEventListener("orientationchange",ve),()=>{oe&&cancelAnimationFrame(oe),Ue.disconnect(),window.removeEventListener("resize",ve),window.removeEventListener("orientationchange",ve)}},[Vt]),Ie.useEffect(()=>{Vt()},[Vt,A,Ws]);const Vn=i.useCallback(async D=>{const oe=D.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||D.button===0&&B&&await zc()},[B]),rs=i.useMemo(()=>A?[{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"}]:[],[A]),yn=i.useCallback(D=>Zr(Bn(D,p)),[p]);Ie.useEffect(()=>{!A&&d!=="chat"&&d!=="terminal"&&d!=="diagram"&&f("chat")},[d,A,f]),Ie.useEffect(()=>{const D=oe=>{if(Id(oe)&&!oe.shiftKey&&!oe.altKey){const ve=parseInt(oe.key,10);ve>=1&&ve<=rs.length&&(oe.preventDefault(),A&&(zt(),Ze()),f(rs[ve-1].id))}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[zt,Ze,A,f,rs]),Ie.useEffect(()=>{const D=oe=>{const ve=Bn("toggle_services_menu",p);if(Rd(oe,ve)){oe.preventDefault(),Y?F(!1):(F(!0),ge());return}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[p,Y,ge]);const Hs=D=>{const oe=d===D.id,ve=D.icon==="diff",Ue=ve?null:D.icon,ct=D.id==="chat",Je=Jt=>ve?t.jsx(gi,{size:Jt}):Ue?t.jsx(R,{name:Ue,className:`h-${Jt/4} w-${Jt/4}`}):null,Qs=t.jsxs("button",{type:"button",onClick:()=>f(D.id),className:U("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",oe?"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",ct&&!A&&"min-w-[100px] justify-center"),"aria-label":D.label,"aria-selected":oe,role:"tab",children:[A?Je(20):t.jsxs(t.Fragment,{children:[Je(16),t.jsx("span",{className:"header-tab-label",children:D.label})]}),D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:D.badge})]});return t.jsx(i.Fragment,{children:Qs},D.id)},Ns=t.jsxs(t.Fragment,{children:[t.jsx(Rm,{directory:qe,className:"mr-1"}),B?t.jsx(Qm,{isDesktopApp:B,currentInstanceLabel:K,compactCurrentInstanceLabel:ie,currentInstanceIsLocal:Z,isDesktopServicesOpen:Y,setIsDesktopServicesOpen:F,refreshCurrentInstanceLabel:ge,shortcutLabel:yn,remoteUpdateInfo:ne,remoteUpdateChecking:q,remoteUpdateError:_e,onOpenRemoteUpdate:Me}):null,t.jsx(qm,{isMobile:A,githubAuthStatus:E,githubAccounts:te,githubAvatarUrl:G,githubLogin:Ae,isSwitchingGitHubAccount:Pe,handleGitHubAccountSwitch:Ks})]}),Jn=z&&(b||!!m),Xn=()=>t.jsxs("div",{onMouseDown:Vn,className:U("app-region-drag relative flex h-12 select-none items-center pr-3",Ws),style:Qn,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:lt}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:xn}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[_t?t.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:_t.title}),_t.subtitle?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:_t.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[u?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Qt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Xm,{align:"start",children:t.jsx("button",{type:"button",className:Qt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Bt?t.jsxs("form",{ref:Oe,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:D=>{D.preventDefault(),Le()},children:[t.jsx("input",{value:kt,onChange:D=>qt(D.target.value),autoFocus:!0,onKeyDown:D=>{D.stopPropagation(),D.key==="Escape"&&et(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>et(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":it}),ot?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[De?t.jsx("span",{className:"truncate",children:De}):null,Fe?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:Fe})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!b&&!Bt?t.jsxs(Mt,{open:mt,onOpenChange:tt,onOpenChangeComplete:D=>{!D&&gt.current&&(gt.current=!1,Ce())},children:[t.jsx(Ft,{asChild:!0,children:t.jsx(Te,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(R,{name:"more",className:"size-4"})})}),t.jsxs(Ot,{align:"end",className:"min-w-[190px]",children:[t.jsxs(rt,{onClick:()=>{gt.current=!0},children:[t.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(rt,{onClick:Ye,children:[t.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(rt,{onClick:st,disabled:!qe,children:[t.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>{ut()},children:[t.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>we("archive"),children:[t.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(rt,{className:"text-destructive focus:text-destructive",onClick:()=>we("delete"),children:[t.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),rs.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:rs.map(D=>Hs(D))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(va,{}),bt?t.jsx(yi,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,t.jsx(Df,{visible:Jn,title:b?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:$t,className:U(Qt,"mr-1"),Icon:"picture-in-picture-2"}),Ns,t.jsx($c,{visible:_})]})]})]}),Ys=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:lt}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:xn}})]}),!N&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:ft,className:U(at,ue==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):$?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Cs,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&$&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!$||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!C&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:rs.map(D=>{const oe=d===D.id,ve=D.icon==="diff",Ue=ve?null:D.icon;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{A&&(zt(),Ze()),f(D.id)},"aria-label":D.label,"aria-selected":oe,role:"tab",className:U(at,"relative rounded-lg",ue===D.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ve?t.jsx(gi,{className:"h-5 w-5"}):Ue?t.jsx(R,{name:Ue,className:"h-5 w-5"}):null,D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:D.badge}),D.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[C&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:j.map(D=>{const oe=r&&o===D.id;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{A&&(zt(),Ze()),k(!1),a?.(D.id)},"aria-label":D.label,"aria-selected":oe,role:"tab",className:U(at,"relative rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:D.icon,className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})}),t.jsx(Rf,{open:y,onOpenChange:k,currentSessionId:m,effectiveDirectory:ye||null,isNewSessionDraftOpen:b})]}),bt&&t.jsx(yi,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!C?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:vt,className:U(at,"relative",ue==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),qs=U("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:qs,style:{"--padding-scale":"1"},children:A?Ys():Xn()}),t.jsx(Vm,{action:yt,onClose:()=>we(null),sessionTitle:it,onConfirm:()=>{Rt()}}),t.jsx(fa,{open:Se,onOpenChange:xe,info:ne,downloading:!1,downloaded:!1,progress:null,error:_e,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},wi="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",Zm="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Xg=()=>{const e=le(m=>m.isSidebarOpen),s=le(m=>m.toggleSidebar),n=le(m=>m.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=Zr(Bn("toggle_sidebar",n)),l=Mi(),{enabled:c}=Qr(),u=!e,d=l,f=u||d,p=d,b=i.useCallback(()=>{on("desktop_show_app_menu").catch(m=>{console.warn("[titlebar] failed to open app menu",m)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const m=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},g=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const h=o.current,v=r.current;if(!h||!v){m(0),g(0);return}const x=()=>{const w=Math.max(h.getBoundingClientRect().width,h.scrollWidth);m(w),g(v.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const I=new ResizeObserver(x);return I.observe(h),I.observe(v),()=>{I.disconnect()}},[p]),f?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[d?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:U(wi,"shrink-0"),children:t.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:U(c?Zm:wi,"shrink-0"),children:t.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},vi=200,eg="cubic-bezier(0.22, 1, 0.36, 1)",Zg=e=>{const s=i.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=i.useState(e),[o,a]=i.useState(e);return i.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),vi);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${vi}ms ${eg}`}},eb=()=>{Ui()},tb=e=>{Ee.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),Ui(),Bs.getState().resetForRuntimeSwitch(),Gc.getState().resetForRuntimeSwitch(),Kc.getState().resetForRuntimeSwitch(),Wc(),Hc.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),pt.getState().resetForRuntimeSwitch(),Yc(),qc(),au.getState().reset(),Ed.getState().resetForRuntimeSwitch(),Ri.getState().resetForRuntimeSwitch(e.runtimeKey),Ir.getState().resetForRuntimeSwitch(e.runtimeKey),ys.getState().resetForRuntimeSwitch(e.runtimeKey),hh.getState().resetForRuntimeSwitch(),ht.getState().resetForRuntimeSwitch(e.runtimeKey),Dd.getState().resetForRuntimeSwitch(e.runtimeKey),Ee.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=le.getState();Lr({sessionId:Ee.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0})};export{ma as $,Gg as A,Yo as B,$g as C,ci as D,Vg as E,jg as F,Pu as G,Jg as H,wg as I,fs as J,Su as K,hs as L,wa as M,kg as N,tf as O,Og as P,Vu as Q,Ag as R,Kg as S,qg as T,zg as U,Pg as V,yg as W,fa as X,so as Y,Dg as Z,ef as _,Nf as a,Sf as a0,Qu as a1,sf as a2,mn as a3,ha as a4,gn as a5,an as a6,Ju as a7,Ng as a8,Xu as a9,Fg as aa,_g as ab,Bg as ac,nf as ad,Mg as ae,Lg as af,Ug as ag,Cg as ah,Ig as ai,Rg as aj,Eg as ak,bf as al,Tg as am,Fu as an,Zu as ao,Ou as ap,bg as aq,Rf as b,en as c,Tp as d,Wg as e,On as f,Hg as g,Zg as h,Fp as i,Qg as j,Xg as k,tb as l,vg as m,Sg as n,xg as o,gg as p,no as q,eb as r,Yg as s,ro as t,Mn as u,oo as v,Os as w,ya as x,jf as y,kf as z};