@pi-chamber/web 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramEditor-YPSKccgo.js → DiagramEditor-D_3eJVSw.js} +1 -1
- package/dist/assets/{DiagramView-C-PbBHce.js → DiagramView-pGYm0-DR.js} +1 -1
- package/dist/assets/{DiffView-DfltyfN2.js → DiffView-BApPTLGp.js} +1 -1
- package/dist/assets/{FilesView-BEjbLiK2.js → FilesView-CiPpuGiF.js} +1 -1
- package/dist/assets/{GitView-B_zTaXX4.js → GitView-uW3w_LlQ.js} +3 -3
- package/dist/assets/{JsonTreeView-9p4txyB_.js → JsonTreeView-CpgqCk9_.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CbRPLK2x.js → MarkdownRendererImpl-fI6n3kqT.js} +1 -1
- package/dist/assets/{PatchDiff-rKjeUBRl.js → PatchDiff-BRloGXPs.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-C_VxKFJy.js → SessionSwitcherContent-BQc-vW4s.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-_k4P32o9.js → SessionSwitcherDropdown-v_8TaIZm.js} +2 -2
- package/dist/assets/{SessionUnreadDot-bT_0MixU.js → SessionUnreadDot-A7vSfll2.js} +1 -1
- package/dist/assets/{SettingsView-CqZ1ZAWG.js → SettingsView-CphlZvfd.js} +2 -2
- package/dist/assets/{SettingsWindow-C7vVE35-.js → SettingsWindow-D7UDhYd4.js} +1 -1
- package/dist/assets/{ToolOutputDialog-GBbzATa6.js → ToolOutputDialog-wpU0ylYS.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-Bdb9p5uS.js → ToolPartDiffPreview-BvoQK5Gm.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CA8hQyz9.js → VirtualizedFileDiff-DdPbLdh7.js} +1 -1
- package/dist/assets/{collapsible-uwSKBy-K.js → collapsible-BO6FIjvn.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-9LNCLvAG.js → computeVirtualFileMetrics-DMvXzUJh.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-CZSqdEHk.js → contextFileOpenGuard-BwXQVjtS.js} +1 -1
- package/dist/assets/{gitStatusPredicates-CRmbLl-x.js → gitStatusPredicates-CgNk6M2_.js} +1 -1
- package/dist/assets/index-BebQicw3.css +1 -0
- package/dist/assets/{index-CaP8oFLB.js → index-Bkz23mZq.js} +1 -1
- package/dist/assets/{index-BeJEipxi.js → index-C3SyF-cA.js} +1 -1
- package/dist/assets/{isDiffPlainText-YYyZNTdb.js → isDiffPlainText-BboRbmcm.js} +1 -1
- package/dist/assets/{isFilePlainText-C70Z71bG.js → isFilePlainText-BpTnLRyI.js} +1 -1
- package/dist/assets/{main-CsdVAKy_.js → main-CMOAwZnJ.js} +3 -3
- package/dist/assets/{main-GMQIZjuQ.js → main-xLwCWLu-.js} +2 -2
- package/dist/assets/{markdownCore-BgVcDt0q.js → markdownCore-CmFv4H-w.js} +1 -1
- package/dist/assets/{miniChat-W6YsdiWR.js → miniChat-Vwo4K1IK.js} +2 -2
- package/dist/assets/{mobile-BFR9CR5w.js → mobile-BRaxtEoC.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-B8ZiW-3E.js → renderElectronMiniChatApp-DM4rRUUz.js} +2 -2
- package/dist/assets/{renderMobileApp-C5CdsYP6.js → renderMobileApp-DWWewNhc.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-D3AZYuoF.js → runtimeEndpointReset-BF60eHSx.js} +3 -3
- package/dist/assets/{runtimeSurface-B818u-_c.js → runtimeSurface-SmPSdfop.js} +1 -1
- package/dist/assets/{useAppFontEffects-CYzYRbLp.js → useAppFontEffects-Bg-8jtrQ.js} +99 -99
- package/dist/assets/{useFilesViewSearch-C--GWtn-.js → useFilesViewSearch-GLcYNIUV.js} +1 -1
- package/dist/assets/{usePushVisibilityBeacon-D9lajdAc.js → usePushVisibilityBeacon-VSYBfNoY.js} +1 -1
- package/dist/assets/{useSwitcherItems-DOoi3x_8.js → useSwitcherItems-BkEt9K-N.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-DS_4W5G4.js → vendor-codemirror-language-data-B5cJDWBR.js} +2 -2
- package/dist/assets/vendor-framer-motion-CfplGuM0.js +1 -0
- package/dist/assets/{vendor-motion-dom-DJLgZh4Q.js → vendor-motion-dom-DhJ-sYS5.js} +1 -1
- package/dist/assets/{vendor-motion-utils-BGh8QBgx.js → vendor-motion-utils-CKEGc_YG.js} +1 -1
- package/dist/assets/{web-components-C2cMNPqE.js → web-components-0H9kvZwn.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/server/cors.js +2 -0
- package/server/lib/server/cors.test.js +5 -3
- package/dist/assets/index-Dq8CnRYM.css +0 -1
- package/dist/assets/vendor-framer-motion-BUygY0oN.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{_ as vs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Me,j as t,R as i}from"./vendor-react-B5Z1Mdn3.js";import{cV as Ms,i as xc,cc as bc,D as Rt,E as Fe,F as Le,a as Et,U as Re,I as D,G as Oe,b as Pt,bM as yc,bN as wc,bO as vc,bP as Sc,bQ as nr,bR as qs,ck as Ro,bm as Xe,t as ie,c as dt,k as ve,b9 as ks,bg as ln,M as Ii,aQ as Kt,aR as Ht,bi as us,bj as os,bk as fs,bl as Ns,cW as jc,be as Cs,cX as Xs,cY as Cc,ca as $s,Z as Vs,cZ as rr,c_ as Eo,c$ as Po,d0 as tn,aw as Di,ao as ys,aL as Mo,af as cn,ci as Cr,d1 as kc,d2 as Nc,d3 as Ac,d4 as Ic,K as Dc,d5 as kr,d6 as Rc,L as Gt,d7 as Ec,d8 as Pc,cw as Mc,cj as Tc,d9 as Fc,cS as Lc,as as Ri,at as Ei,da as Pi,u as Nr,r as Ts,bZ as Vr,bd as Oc,Y as Bc,bB as To,bA as _c,bz as zc,bJ as Mi,db as Uc,g as Qr,j as Gs,Q as Ti,dc as lt,d as Ar,dd as $c,de as Gc,bv as Kc,df as Hn,dg as Fo,dh as Fi,bK as Li,di as Ir,dj as Oi,S as Bi,ba as Hc,dk as Wc,dl as Yc,l as _i,bW as qc,dm as Vc,dn as Qc,m as Jc,dp as Xc,e as Zc,dq as ed,bV as td,s as sd,f as nd,a7 as zi,dr as Dr,ds as rd,dt as od,bL as id,cU as ad,du as ld,a3 as cd,aN as Ui,c3 as dd,aB as ud,bn as Ls,dv as fd,dw as hd,bX as pd,dx as md,R as $i,ah as gd,dy as xd,W as Gi,dz as Ki,cC as bd,cD as yd,dA as wd,cu as vd,bU as Sd,dB as jd,dC as Cd}from"./useAppFontEffects-CYzYRbLp.js";import{g as Lo,aW as kd,aX as Oo,aY as Nd,i as Ad,h as Id,A as Dd,r as Mt,C as dn,B as Rd,c as z,aZ as Ed,b as Os,a_ as Jr,a$ as Xr,b0 as Pd,b1 as Md,f as Bs,M as Td,b2 as Fd,b3 as Ld,b4 as Od,as as ts,p as ss,b5 as Bd,b6 as _d,b7 as zd,y as Zr,b8 as Ud,b9 as $d,ba as Gd,u as se,z as Kd,n as ye,bb as _s,D as Ft,bc as Bo,bd as Rr,w as Wn,be as Hd,aA as Wd,$ as eo,m as sn,bf as Yd,bg as qd,T as Hi,G as Vd,l as Wi,j as nn,bh as Er,H as Pr,a4 as jn,bi as Qd,bj as Qs,ay as or,bk as Mr,bl as ws,bm as _o,bn as Tr,bo as Yi,bp as Fr,bq as Jd,ah as Xd,br as Zd,bs as eu,bt as tu,bu as su,ak as nu,a3 as ru,V as ou,k as zo,bv as qi,d as iu,L as au}from"./index-CaP8oFLB.js";import{c as hs,d as Vi,p as to,u as Lr,a as lu}from"./vendor-zustand-GVb4H8HE.js";import{g as ds,d as cu,e as Qi,r as du,h as Ji,i as En,j as Xi,b as un,c as fn,s as uu,k as fu,l as hu,m as Uo,n as Yn,f as pu,S as mu,a as gu,t as xu,o as bu}from"./SessionUnreadDot-bT_0MixU.js";import{i as Zi,j as ea,k as ta,l as sa,m as na,M as ra,S as oa,D as yu,c as wu,d as vu,e as Su,f as ju,g as Cu,h as ku}from"./vendor-base-ui-vkqQ2P9o.js";import{c as so,d as On,P as ia,D as no,e as ro,f as aa,b as Nu,a as Au,T as Iu,M as Du}from"./vendor-dnd-kit-core-CP8ck10N.js";import{u as Ru}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as la,v as Eu,u as ca,h as Pu}from"./vendor-dnd-kit-sortable-B-Icjoj4.js";import{C as da}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{usePermissionStore as Mu}from"./permissionStore-iKN1K2_x.js";const Tu="chat";function ua(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!==Tu&&s.set(Ms.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ms.FILE,e.diffFile),s}function Fu(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 Lu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=ua(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,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Or(e,s={}){if(!(typeof window>"u")&&!(!s.force&&Lu(e)))try{const n=ua(e),r=Fu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ou=["typescript","javascript","tsx","jsx","json","markdown"],fa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let $o=null;const ha=()=>($o??=Promise.all([vs(()=>import("./index-BeJEipxi.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])),vs(()=>import("./workerFactory-tw7cIdmV.js"),[]),vs(()=>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),hn={},Go=new Set,Br=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const Bu=()=>{for(const e of Br)e()},pa=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:fa[e].lineDiffType})},_r=e=>{typeof window>"u"||Go.has(e)||(Go.add(e),ha().then(s=>{if(hn[e])return;const n=fa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ou,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),hn[e]=r,pa(e,r),Bu()}))},_u=e=>(Br.add(e),()=>Br.delete(e)),zu=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(hn)){const n=hn[s];n&&pa(s,n)}}},sx=({children:e})=>{const s=xc(),n=Lo(!1),r=Lo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===o)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Me.useEffect(()=>{let d=!1;return ha().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),zu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Me.useEffect(()=>{if(typeof window>"u")return;const d=()=>{_r("unified"),_r("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},nx=(e="unified")=>{const s=Me.useSyncExternalStore(_u,()=>hn[e],()=>{});return Me.useEffect(()=>{_r(e)},[e]),s};function Uu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=bc();return e}catch{return"unknown"}}function $u(){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 Gu(){const e=Rd();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 Ku(e){const s=new URLSearchParams;return s.set("deviceClass",Uu()),s.set("arch",$u()),s.set("platform",Gu()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",dn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ir(e,s){try{const n=Ku(e);s&&n.set("currentVersion",s);const r=await Mt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Hu(){return Ad()?"mobile":Id()?"desktop":Dd()?"web":null}const Ko={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=hs()((e,s)=>({...Ko,checkForUpdates:async()=>{const n=Hu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.8.0",[l,c]=await Promise.allSettled([Oo(),ir("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ir("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ir("mobile","0.8.0"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await Oo();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 Nd(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 kd())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(Ko)}})),Wu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Yu=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=i.useState(!1),[f,h]=i.useState(""),[x,g]=i.useState(!1),[m,p]=i.useState(!1),[y,b]=i.useState(""),[A,v]=i.useState(!1),C=i.useRef(null),S=i.useCallback(P=>{P.stopPropagation()},[]),I=l.length>1,k=i.useMemo(()=>Wu(y),[y]),w=i.useMemo(()=>{const P=f.toLowerCase();return P?s.filter(B=>B.toLowerCase().includes(P)):s},[f,s]),j=i.useMemo(()=>{const P=f.toLowerCase();return P?n.filter(B=>B.toLowerCase().includes(P)):n},[f,n]),E=P=>{if(P===e){u(!1);return}o(P),u(!1),h("")},T=()=>{g(!0),setTimeout(()=>C.current?.focus(),50)},U=async()=>{if(!(!k||A)){if(I){p(!0);return}v(!0);try{await a(k,l[0]),b(""),g(!1),u(!1)}finally{v(!1)}}},_=async P=>{if(!(!k||A)){v(!0);try{await a(k,P),b(""),g(!1),p(!1),u(!1)}finally{v(!1)}}},$=()=>{p(!1)},K=()=>{b(""),g(!1),p(!1)};return i.useEffect(()=>{d||(h(""),g(!1),p(!1),b(""))},[d]),t.jsxs(Rt,{open:d,onOpenChange:u,children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Oe,{sideOffset:8,children:"Current branch"})]}),t.jsx(Pt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(yc,{className:"h-full min-h-0",children:[t.jsx(wc,{placeholder:"Search branches...",value:f,onValueChange:h,onKeyDown:S}),t.jsxs(vc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Sc,{children:"No branches found."}),t.jsx(nr,{children:m?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:$,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:k})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(P=>t.jsxs("button",{type:"button",onClick:()=>_(P),disabled:A,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[A?t.jsx(D,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,P.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:P.pushUrl})]},P.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:C,placeholder:"New branch name",value:y,onChange:P=>b(P.target.value),onClick:P=>P.stopPropagation(),onKeyDown:P=>{S(P),P.key==="Enter"?(P.preventDefault(),U()):P.key==="Escape"&&(P.preventDefault(),K())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:U,disabled:!k||A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:A?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:K,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsxs(qs,{onSelect:T,children:[t.jsx(D,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Local branches",children:[w.map(P=>t.jsxs(qs,{onSelect:()=>E(P),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:P}),(r?.[P]?.ahead||r?.[P]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[P].ahead||0," ahead ·"," ",r[P].behind||0," behind"]})]}),e===P&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${P}`)),w.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Remote branches",children:[j.map(P=>t.jsx(qs,{onSelect:()=>E(P),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:P})},`remote-${P}`)),j.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},qu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Vu=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,o]=i.useState(!1),[a,l]=i.useState(e||""),[c,d]=i.useState(!1),u=i.useRef(null),f=()=>{!e||!s||(l(e),o(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const m=qu(a);if(m===e){o(!1);return}d(!0);try{await s(e,m),o(!1),l("")}finally{d(!1)}},x=()=>{o(!1),l("")},g=m=>{m.key==="Enter"?(m.preventDefault(),h()):m.key==="Escape"&&(m.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:m=>{m.preventDefault(),h()},children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:m=>l(m.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:g,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:"Rename branch",children:t.jsx(D,{name:"edit",className:"size-4"})})]})]})},Qu=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:o,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:f=!1})=>{const h=i.useRef(!1),x=!!l,g=s.find(S=>S.name===u)??s[0],m=d>0&&f,p=a||e!==null||x||!g||m,y=a||e!==null||x||s.length===0,b=c>0||d>0,A=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=m?"Commit or stash your changes before syncing":g?b?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",C=()=>{g&&r(g)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:m?0:void 0,children:t.jsxs("button",{type:"button",onClick:C,disabled:p,className:z("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:A})]})})}),t.jsx(Oe,{sideOffset:8,children:v})]}),t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:y,"aria-label":"More sync actions",children:t.jsx(D,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Pt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(S=>t.jsx(Xe,{onSelect:I=>{if(h.current){I.preventDefault(),h.current=!1;return}n(S)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(D,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${S.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:S.fetchUrl})]})}),o&&S.name!==u?t.jsx(Re,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:I=>{h.current=!0,I.preventDefault(),I.stopPropagation()},onClick:I=>{h.current=!0,I.preventDefault(),I.stopPropagation(),o(S)},"aria-label":`Remove remote ${S.name}`,title:`Remove remote ${S.name}`,children:l===S.name?t.jsx(D,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(D,{name:"close",className:"size-3.5"})}):null]})},S.name))})]})]})},Ju={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Xu={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 ma(e){return e&&Xu[e]||"var(--primary)"}const Ho=({icon:e,className:s,colorToken:n})=>{const r=Ju[e??"branch"]??"user-3";return t.jsx(D,{name:r,className:s,style:{color:ma(n)}})},ga=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Rt,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs(Re,{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:ma(e?.color)},disabled:a,children:[r?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(Ho,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Oe,{sideOffset:8,children:"Git identity"})]}),t.jsx(Pt,{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(Xe,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(Ho,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(D,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},Zu=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,o=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(Fe,{delayDuration:n,children:[t.jsx(Le,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(D,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),o?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(Oe,{sideOffset:8,children:a})]})},rx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:f,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:g,availableIdentities:m,onSelectIdentity:p,isApplyingIdentity:y,isWorktreeMode:b,onOpenHistory:A,onOpenGraph:v,onOpenStashes:C,onOpenUpdateBranch:S,onOpenReintegrateCommits:I,pullRequest:k,prChecks:w,onOpenPullRequest:j})=>{if(!e)return null;const E=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:A||v||C||S?t.jsxs(Rt,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(D,{name:"more-fill",className:"size-4"})})})}),t.jsx(Oe,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Pt,{align:"end",children:[A?t.jsxs(Xe,{onSelect:A,children:[t.jsx(D,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(Xe,{onSelect:v,children:[t.jsx(D,{name:"git-branch",className:"size-4"}),"Graph"]}):null,C?t.jsxs(Xe,{onSelect:C,children:[t.jsx(D,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,S?t.jsxs(Xe,{onSelect:S,children:[t.jsx(D,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,I?t.jsxs(Xe,{onSelect:I,children:[t.jsx(D,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),T=w?w.state==="success"?"var(--status-success)":w.state==="failure"?"var(--status-error)":"var(--status-warning)":null,U=k?k.state==="merged"?"merged":k.state==="closed"?"closed":k.draft?"draft":w?.state==="failure"||k.mergeable===!1||k.mergeableState==="blocked"||k.mergeableState==="dirty"?"blocked":"open":null,_=k&&j?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",onClick:j,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(D,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${U})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${k.number}`}),T?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:T}}):null]})}),t.jsx(Oe,{sideOffset:8,children:"Open pull request"})]}):null,$=t.jsx(Qu,{syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),K=e.upstreamComparison?t.jsx(Zu,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,P=t.jsx(ga,{activeProfile:g,identities:m,onSelect:p,isApplying:y,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:b?t.jsx(Vu,{currentBranch:e.current,onRename:x}):t.jsx(Yu,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:P})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[_?t.jsx("div",{className:"shrink-0",children:_}):null,t.jsx("div",{className:"min-w-0 flex-1"}),K?t.jsx("div",{className:"min-w-0 shrink",children:K}):null,E,t.jsx("div",{className:"shrink-0",children:$})]})]})},ef=e=>e==="/",zs=e=>e.replace(/\\/g,"/"),Us=e=>{if(!e||ef(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),Bn=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},oo=e=>e.lastIndexOf("/"),xa=e=>{if(Fs(e))return e;const s=oo(e);return s<0?e:e.slice(0,s+1)},ba=e=>{const s=oo(e);return e.slice(s+1)},ya=e=>{const s=Us(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=oo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},wa=e=>Fs(e)&&ya(e)!==null,tf=e=>{if(!wa(e))return null;const s=Us(e.trim());return ba(s)||s},sf=(e,s)=>`${xa(e)}${s}/`,Ss=e=>{if(!e)return null;const s=Us(zs(e.trim()));return s?s.toLowerCase():null},Wo=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},nf=(e,s)=>{const n=Us(zs(e.trim())),r=Us(zs(s.trim()));if(!n)return"";if(!r)return Bn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Bn(n)},rf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,zr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},of=async()=>Ed(),af=()=>{const[e,s]=Me.useState(!1),[n,r]=Me.useState(!1);Me.useEffect(()=>{s(Os()),r(Jr())},[]);const o=Me.useCallback(async c=>e?await Xr(c):{success:!0,path:c},[e]),a=Me.useCallback(async c=>e?await Pd():{success:!0},[e]),l=Me.useCallback(async c=>e?await Md():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function lf({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Bs(Z=>Z.homeDirectory),{canRequestAccess:o,startAccessing:a}=af(),l=i.useRef(null),c=i.useRef(new Map),[d,u]=i.useState(""),[f,h]=i.useState("~/"),[x,g]=i.useState([]),[m,p]=i.useState(!1),[y,b]=i.useState(!1),[A,v]=i.useState(null),[C,S]=i.useState(0),[I,k]=i.useState(0),[w,j]=i.useState(!1),[E,T]=i.useState(!1),[U,_]=i.useState("right"),$=i.useRef("~/"),K=d||r;i.useEffect(()=>{if(!e)return;h("~/"),g([]),k(0),j(!1),T(!1),$.current="~/",_("right"),n||requestAnimationFrame(()=>zr(l.current));let Z=!1;return(async()=>{const L=await of();Z||(u(L||r||""),n||requestAnimationFrame(()=>zr(l.current)))})(),()=>{Z=!0}},[r,e,n]);const P=i.useMemo(()=>xa(f),[f]),B=i.useMemo(()=>Fs(f)?"":ba(f),[f]),R=i.useMemo(()=>K?Wo(P,K):"",[P,K]);i.useEffect(()=>{const Z=$.current;Z!==P&&(_(P.length>=Z.length?"right":"left"),$.current=P)},[P]),i.useEffect(()=>{if(!e||!R){g([]),v(null);return}let Z=!1;return p(!0),b(!1),v(null),Td(R).then(ue=>{if(Z)return;b(!1),v(null);const L=ue.filter(Y=>Y.isDirectory).map(Y=>({name:Y.name,path:zs(Y.path)})).sort((Y,le)=>Y.name.localeCompare(le.name));g(L)}).catch(ue=>{if(!Z){g([]);const L=Fd(ue)?ue.reason:"unknown";v(L),b(L==="not-found")}}).finally(()=>{Z||p(!1)}),()=>{Z=!0}},[R,C,e]);const F=i.useMemo(()=>{const Z=B.toLowerCase(),ue=E||B.startsWith(".");return x.filter(L=>L.name.toLowerCase().startsWith(Z)&&(ue||!L.name.startsWith(".")))},[B,x,E]),V=i.useMemo(()=>tf(f),[f]),G=i.useMemo(()=>ya(f),[f]),M=i.useMemo(()=>{const Z=[],ue=Ss(R);wa(f)&&V&&G&&Z.push({type:"parent",value:"browse:up",name:V,path:G,alreadyAdded:!!(ue&&s.has(ue))});for(const L of F){const Y=Ss(L.path);Z.push({type:"directory",value:`browse:${L.path}`,name:L.name,path:L.path,alreadyAdded:!!(Y&&s.has(Y))})}return Z},[s,R,V,F,G,f]);i.useEffect(()=>{k(0)},[f,M.length]);const ee=i.useMemo(()=>K?Us(Wo(f,K)):"",[K,f]),H=Ss(ee),we=!!(H&&s.has(H)),ce=i.useMemo(()=>B?F.find(Z=>Z.name===B)??null:null,[B,F]),ae=!!(ee&&!we&&(A===null||A==="not-found")&&(Fs(f)&&y||!Fs(f)&&B.trim().length>0&&ce===null)),xe=M[I]??null,be=!!xe,ge=i.useCallback(Z=>{h(Bn(Z))},[]),Se=i.useCallback(Z=>{h(sf(f,Z.name))},[f]),je=i.useCallback(Z=>{if(Z){if(Z.type==="parent"){ge(Z.path);return}Se(Z)}},[ge,Se]),ke=i.useCallback(async Z=>{const ue=await a(Z);if(!ue.success)return ie.error("Failed to open directory",{description:ue.error||"Desktop could not grant file access."}),!1;const L=K?nf(Z,K):Bn(zs(Z));return ge(L),!0},[ge,K,a]),Ce=i.useCallback(async()=>{if(!w){j(!0);try{if(Jr()){const ue=await Xr(ee);if(!ue.success||!ue.path){ue.error&&ue.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:ue.error});return}await ke(ue.path);return}const Z=await Ld(ee);if(Z.status==="cancelled")return;if(Z.status!=="picked"){ie.error("Couldn't open a folder picker",{description:Z.error});return}await ke(Z.path)}catch(Z){ie.error("Failed to select directory",{description:Z instanceof Error?Z.message:"Unknown error occurred."})}finally{j(!1)}}},[ke,w,ee]);return{inputRef:l,rowRefs:c,query:f,setQuery:h,isLoading:m,isBrowseDirectoryMissing:y,browseErrorReason:A,browseReloadKey:C,setBrowseReloadKey:S,highlightedIndex:I,setHighlightedIndex:k,isPickingLocation:w,showHidden:E,setShowHidden:T,folderEnterFrom:U,explorerRootDirectory:K,browseDirectoryDisplayPath:P,browseDirectoryAbsolutePath:R,browseFilterQuery:B,filteredEntries:F,rows:M,targetPath:ee,isAlreadyAdded:we,shouldCreateTarget:ae,highlightedRow:xe,hasHighlightedBrowseItem:be,canRequestAccess:o,browseToDisplayPath:ge,browseToEntry:Se,executeRow:je,applyPickedLocation:ke,handleBrowseLocation:Ce}}const bs=hs()(Vi(to((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=ss()?.git,o=r?await r.getGitIdentities():await Gd();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=ss()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await $d();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=ss()?.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=ss()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Mt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Zr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};ts("saving");const o=ss()?.git;return o?await o.createGitIdentity(r):await zd(r),ts("saved"),await s().loadProfiles(),!0}catch(r){return ts("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};ts("saving");const l=ss()?.git;return l?await l.updateGitIdentity(n,a):await _d(n,a),ts("saved"),await s().loadProfiles(),!0}catch(o){return ts("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{ts("saving");const r=ss()?.git;return r?await r.deleteGitIdentity(n):await Bd(n),ts("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ts("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:Od(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=bs);function cf({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=dt(G=>G.addProject),h=se(G=>G.setActiveMainTab),x=se(G=>G.setSessionSwitcherOpen),g=ve(G=>G.openNewSessionDraft),m=bs(G=>G.profiles),p=bs(G=>G.globalIdentity),y=bs(G=>G.defaultGitIdentityId),b=bs(G=>G.loadProfiles),A=bs(G=>G.loadGlobalIdentity),v=bs(G=>G.loadDefaultGitIdentityId),[C,S]=i.useState(!1),[I,k]=i.useState(!1),[w,j]=i.useState(""),[E,T]=i.useState(null);i.useEffect(()=>{e&&(S(!1),k(!1),j(""),T(null))},[e]),i.useEffect(()=>{e&&(b(),A(),v())},[v,b,A,e]);const U=i.useMemo(()=>{const G=new Map;p&&G.set(p.id,p);for(const M of m)G.set(M.id,M);return Array.from(G.values())},[m,p]);i.useEffect(()=>{if(!e||!I||E!==null)return;const G=typeof y=="string"?y.trim():"";if(G&&U.some(ee=>ee.id===G)){T(G);return}const M=U.find(ee=>ee.authType==="ssh"||ee.sshKey);M&&T(M.id)},[U,y,I,e,E]);const _=i.useMemo(()=>U.find(G=>G.id===E)??null,[U,E]),$=i.useCallback((G,M)=>{h("chat"),n&&x(!1),g({selectedProjectId:G,directoryOverride:M}),s()},[n,s,g,h,x]),K=i.useCallback(async G=>{if(!G||C)return;const M=Ss(G);if(M&&r.has(M))return;let ee=G;S(!0);try{const H=!I&&a&&Ss(G)===Ss(o);if(I){const ce=w.trim();if(!ce){ie.error("Enter a repository URL before cloning.");return}const ae=await Mt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ce,destinationPath:G,gitIdentityId:_?.id??null})});if(!ae.ok)throw new Error("Failed to clone git repository");ee=(await ae.json()).path||G}else if(H&&!(await Mt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:G})})).ok)throw new Error("Failed to select directory");const we=f(ee);if(!we){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}$(we.id,we.path)}catch(H){ie.error("Failed to select directory",{description:H instanceof Error?H.message:"Unknown error occurred."})}finally{S(!1)}},[f,r,c,w,I,C,$,_?.id,a,o]),P=!C&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,B=P&&w.trim().length>0,R=I?B:P,F=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:C,isCloneMode:I,setIsCloneMode:k,cloneRemoteUrl:w,setCloneRemoteUrl:j,selectedGitIdentityId:E,setSelectedGitIdentityId:T,availableGitIdentities:U,selectedGitIdentity:_,canSubmit:R,submitActionLabel:d?"Already added":I?C?"Cloning...":"Clone & add":C?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:F,finalizeSelection:K}}const df=({open:e,onOpenChange:s})=>{const n=dt(L=>L.projects),{isMobile:r,isTablet:o}=ks(),a=r||o,l=i.useMemo(()=>new Set(n.map(L=>Ss(L.path)).filter(L=>!!L)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:d,rowRefs:u,query:f,setQuery:h,isLoading:x,browseErrorReason:g,setBrowseReloadKey:m,highlightedIndex:p,setHighlightedIndex:y,isPickingLocation:b,showHidden:A,setShowHidden:v,folderEnterFrom:C,browseDirectoryDisplayPath:S,browseDirectoryAbsolutePath:I,rows:k,targetPath:w,isAlreadyAdded:j,shouldCreateTarget:E,highlightedRow:T,hasHighlightedBrowseItem:U,canRequestAccess:_,executeRow:$,handleBrowseLocation:K}=lf({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:P,isCloneMode:B,setIsCloneMode:R,cloneRemoteUrl:F,setCloneRemoteUrl:V,setSelectedGitIdentityId:G,availableGitIdentities:M,selectedGitIdentity:ee,canSubmit:H,submitActionLabel:we,submitModifierLabel:ce,finalizeSelection:ae}=cf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:E,browseErrorReason:g,browseDirectoryAbsolutePath:I,isAlreadyAdded:j,isPickingLocation:b});i.useLayoutEffect(()=>{const L=d.current;L&&(L.scrollLeft=L.scrollWidth)},[d,f]),i.useLayoutEffect(()=>{!e||a||zr(d.current)},[d,e,a]),i.useLayoutEffect(()=>{const L=k[p];L&&u.current.get(L.value)?.scrollIntoView({block:"nearest"})},[p,u,k]);const xe=i.useCallback(L=>{if(L.key==="ArrowDown"){L.preventDefault(),y(Y=>Math.min(k.length-1,Y+1));return}if(L.key==="ArrowUp"){L.preventDefault(),y(Y=>Math.max(0,Y-1));return}if(L.key==="Enter"){if(L.preventDefault(),rf(L)){ae(w);return}U&&$(T);return}L.key==="Backspace"&&f===""&&(L.preventDefault(),c())},[$,ae,c,U,T,f,k.length,y,w]),be=t.jsxs("button",{type:"button",onClick:()=>v(L=>!L),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:[A?t.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),ge=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(D,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(ln,{ref:d,value:f,onChange:L=>h(zs(L.target.value)),onKeyDown:xe,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(Re,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:P||b,onMouseDown:L=>L.preventDefault(),onClick:()=>{K()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(D,{name:"folder-open",className:"h-3.5 w-3.5"}),b?"Opening...":"Browse"]})]})}),Se=k.some(L=>L.type==="parent"),je=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(Re,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":B,disabled:P||b,onClick:()=>R(L=>!L),children:[t.jsx(D,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),B?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(ln,{value:F,onChange:L=>V(L.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(ga,{activeProfile:ee,identities:M,onSelect:L=>G(L.id),isApplying:P,iconOnly:!0})]})]}):null,j?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:z("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",C==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):g&&g!=="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:g==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[g==="os-permission"&&_?t.jsx(Re,{size:"xs",onClick:()=>{K()},disabled:b,children:"Grant access"}):null,t.jsx(Re,{variant:"outline",size:"xs",onClick:()=>m(L=>L+1),children:"Try again"})]})]}):k.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:k.map((L,Y)=>{const le=Y===p,W=L.type==="directory"&&Se;return t.jsxs("button",{ref:X=>{X?u.current.set(L.value,X):u.current.delete(L.value)},type:"button","aria-label":L.type==="parent"?L.alreadyAdded?`Go back from ${L.name}, already added`:`Go back from ${L.name}`:L.alreadyAdded?`Open ${L.name}, already added`:`Open ${L.name}`,onMouseEnter:()=>y(Y),onMouseDown:X=>X.preventDefault(),onClick:()=>$(L),className:z("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",le&&"bg-interactive-selection text-interactive-selection-foreground",!le&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:z("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[L.type==="parent"?t.jsx(D,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(D,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:L.name})]}),L.alreadyAdded?t.jsx("span",{className:z("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",le?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,L.type==="parent"?t.jsx(D,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},L.value)})})},S)]})}),ke=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ge,je]}),Ce=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(D,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(D,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:ce}),t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Z=t.jsx(Re,{size:r?"xs":"default",onClick:()=>{ae(w)},disabled:!H,className:z(r&&"w-full flex-1"),children:we}),ue=()=>t.jsxs(t.Fragment,{children:[r?null:Ce,t.jsx("div",{className:z("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:Z})]});return r?t.jsx(Ii,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ue()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:be}),ke]})}):t.jsx(Kt,{open:e,onOpenChange:s,children:t.jsxs(Ht,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(us,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(os,{children:"Add folder"}),t.jsx(fs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),be]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:ke}),t.jsx(Ns,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ue()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,ox=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=jc,c=ve(I=>I.deleteSessions),d=se(I=>I.showDeletionDialog),u=se(I=>I.setShowDeletionDialog),{isMobile:f,isTablet:h,hasTouchInput:x}=ks(),g=f||h||x;i.useEffect(()=>Kd(()=>{s(!1)}),[]);const m=i.useCallback(I=>{r({sessions:I.sessions,dateLabel:I.dateLabel})},[]),p=i.useCallback(()=>{r(null),a(!1)},[]),y=i.useCallback(async I=>{if(I.sessions.length===0)return;if(I.sessions.length===1){const E=I.sessions[0];await l(E.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const k=I.sessions.map(E=>E.id),{deletedIds:w,failedIds:j}=await c(k);if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:I.dateLabel?`Removed all sessions from ${I.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Cn(E)})}j.length>0&&ie.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>Cs.onDeleteRequest(I=>{if(!d){y(I);return}m(I)}),[m,d,y]),i.useEffect(()=>Cs.onDirectoryRequest(()=>{s(!0)}),[]);const b=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const I=n.sessions[0];if(!await l(I.id)){ie.error("Failed to delete session"),a(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const I=n.sessions.map(E=>E.id),k=await c(I),w=k.deletedIds,j=k.failedIds;if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Cn(E),action:{label:"OK",onClick:()=>{}}})}if(j.length>0&&(ie.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:Cn("Please try again in a moment.")}),w.length===0)){a(!1);return}}p()}finally{a(!1)}}},[n,l,c,p]),A=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.`:"",v=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(I=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:ds(I)})},I.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,C=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(D,{name:"checkbox-blank",className:"size-4"}):t.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Re,{variant:"ghost",onClick:p,disabled:o,children:"Cancel"}),t.jsx(Re,{variant:"destructive",onClick:b,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),S=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[g?t.jsx(Ii,{open:!!n,onClose:()=>{o||p()},title:S,footer:t.jsx("div",{className:"flex justify-end gap-2",children:C}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[A&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:A}),v]})}):t.jsx(Kt,{open:!!n,onOpenChange:I=>{if(!I){if(o)return;p()}},children:t.jsxs(Ht,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(us,{children:[t.jsx(os,{children:S}),A&&t.jsx(fs,{children:A})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Ns,{className:"mt-2 gap-2 pt-1 pb-1",children:C})]})}),t.jsx(df,{open:e,onOpenChange:s})]})},ix=()=>{const e=Xs(d=>d.entries),s=se(d=>d.isMobile),n=se(d=>d.activeMainTab),r=ve(d=>d.newSessionDraft),o=ve(d=>d.openNewSessionDraft),a=ve(d=>d.setNewSessionDraftTarget),l=n==="chat",c=i.useMemo(()=>{const d=Cc(r?.worktreeIntent),u=!!r?.open,f=[];for(const h of e.values()){const x=u&&h.key===d,g=x&&l;if(h.state){g||f.push(h);continue}h.receipt&&!x&&f.push(h)}return f},[e,r?.worktreeIntent,r?.open,l]);return c.length===0?null:t.jsx("div",{className:z("pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3",s?"bottom-[calc(var(--oc-safe-area-bottom,0px)+5.5rem)]":"bottom-4"),"aria-live":"polite",children:t.jsx("div",{className:"pointer-events-auto flex w-full max-w-[640px] flex-col gap-2",children:c.map(d=>t.jsx(uf,{entry:d,onDismissFailed:()=>Xs.getState().dismissFailed(d.key),onDismissCompleted:()=>Xs.getState().clearEntry(d.key),onOpenWorktree:()=>{const u=d.receipt;u&&(r?.open?a({directoryOverride:u.path,worktreeIntent:null}):o({directoryOverride:u.path}),Xs.getState().clearEntry(d.key),se.getState().setActiveMainTab("chat"))}},d.key))})})},uf=({entry:e,onDismissFailed:s,onDismissCompleted:n,onOpenWorktree:r})=>{const o=e.state?.phase==="failed",a=!!(e.state&&!o),l=!e.state&&!!e.receipt,c=o?e.state?.label??"Worktree creation failed":a?e.state?.label??"Creating worktree...":e.receipt?`Worktree ready: ${e.receipt.branch??e.path??"new worktree"}`:"",d=o?e.state?.error:l?e.receipt?.path:null;return t.jsxs("div",{className:z("flex items-center gap-3 rounded-xl border px-3 py-2.5 shadow-lg backdrop-blur",o?"border-[var(--status-error-border)] bg-[var(--status-error-background)] text-[var(--status-error-foreground)]":l?"border-[var(--border)] bg-[var(--surface-elevated)] text-foreground":"border-[var(--border)] bg-[var(--surface-muted)] text-muted-foreground"),role:o?"alert":"status",children:[a?t.jsx($s,{variant:"inline",text:null,animationType:"spinner"}):l?t.jsx(D,{name:"git-branch",className:"h-4 w-4 shrink-0 text-[var(--status-success)]"}):t.jsx(D,{name:"alert",className:"h-4 w-4 shrink-0"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"typography-ui-label truncate",children:c}),d?t.jsx("p",{className:"mt-0.5 break-words text-xs opacity-80 line-clamp-2",children:d}):null,a&&e.branch?t.jsx("p",{className:"mt-0.5 truncate text-xs opacity-60",children:e.branch}):null]}),o?t.jsx(Re,{type:"button",variant:"ghost",size:"xs",onClick:s,"aria-label":"Dismiss error",children:"Dismiss"}):null,l?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Re,{type:"button",size:"xs",onClick:r,children:"Open"}),t.jsx(Re,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Dismiss",children:t.jsx(D,{name:"close",className:"h-3.5 w-3.5"})})]}):null,a?t.jsx("span",{className:"hidden shrink-0 text-xs opacity-60 sm:inline",children:"In background"}):null]})},ff=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],hf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function pf(e){const s=e.trim().toLowerCase();return ff.find(n=>n.slug===s)??null}function mf(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=hf[s];if(n)return n;const r=pf(s);return r?r.slug:"home"}function ax(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 lx(){const e=i.useRef(!1),s=i.useRef(!1),n=ve(f=>f.setCurrentSession),r=se(f=>f.setActiveMainTab),o=se(f=>f.setSettingsDialogOpen),a=se(f=>f.setSettingsPage),l=se(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const h=ve.getState().currentSessionId,x=Vs().getState().selectedSessionId;if(f.sessionId!==h||f.sessionId!==x){const g=ve.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,g)}}if(f.settingsPath){a(mf(f.settingsPath)),o(!0);return}se.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]),d=i.useCallback(()=>{const f=ve.getState(),h=Vs().getState(),x=se.getState();return{sessionId:rr({currentSessionId:f.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=i.useCallback((f={})=>{if(s.current)return;const h=d();Or(h,f)},[d]);i.useEffect(()=>{if(e.current||(e.current=!0,!Eo()))return;const f=Po();(async()=>(await c(f),Or({...d(),sessionId:f.sessionId??rr({currentSessionId:ve.getState().currentSessionId,piSelectedSessionId:Vs().getState().selectedSessionId,draft:ve.getState().newSessionDraft}),tab:f.tab??se.getState().activeMainTab,settingsPath:f.settingsPath??se.getState().settingsPage,diffFile:f.diffFile??se.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),i.useEffect(()=>{const f=()=>{const y=ve.getState(),b=Vs().getState();return rr({currentSessionId:y.currentSessionId,piSelectedSessionId:b.selectedSessionId,draft:y.newSessionDraft})};let h=f(),x=ve.getState().newSessionDraft?.open===!0;const g=()=>{const y=ve.getState(),b=f(),A=y.newSessionDraft?.open===!0;b===h&&A===x||s.current||(h=b,x=A,u({replace:!0}))},m=ve.subscribe(()=>{g()}),p=Vs().subscribe(()=>{g()});return()=>{m(),p()}},[u]),i.useEffect(()=>{let f=se.getState().activeMainTab,h=se.getState().isSettingsDialogOpen,x=se.getState().settingsPage,g=se.getState().pendingDiffFile;return se.subscribe(p=>{if(s.current)return;const y=p.activeMainTab!==f,b=p.isSettingsDialogOpen!==h,A=p.settingsPage!==x,v=p.pendingDiffFile!==g&&p.activeMainTab==="diff";f=p.activeMainTab,h=p.isSettingsDialogOpen,x=p.settingsPage,g=p.pendingDiffFile,(y||b||A||v)&&u()})},[u]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const h=Po();if(Eo())c(h);else{const x=se.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function gf(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,d=null;const u=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},f=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),g=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(g)},h))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function cx(){const e=tn(s=>s.connection==="ready",void 0,"chrome");return gf(e),null}const Yo=12,xf=[{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"}],bf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=xf,onComplete:a})=>{const l=Me.useRef(!1);Me.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Me.useMemo(()=>Array.from({length:Yo},(d,u)=>{const f=Math.PI*2*u/Yo;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:z("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((f,h)=>{const x=f.x*d.radius,g=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:m},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},yf=({durationMs:e=3400}={})=>{const[s,n]=Me.useState({isActive:!1,cycle:0}),r=Me.useRef(null),o=Me.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Me.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Me.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 Me.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},va=i.createContext(void 0),dx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=yf(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(va.Provider,{value:a,children:[e,t.jsx(bf,{isActive:s,burstKey:n})]})},wf={triggerFireworks:()=>{},dismissFireworks:()=>{}},ux=()=>i.useContext(va)??wf,qo="https://github.com/RyderAsKing/PiChamber/releases";function vf(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 Sf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Vo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function jf(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 Cf(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 Qo=2e3,kf=600*1e3;async function Nf(){try{const e=await Mt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Af(){try{return(await Mt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function If(e,s=Math.ceil(kf/Qo),n=Qo){for(let r=0;r<s;r++){try{const o=await Mt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await Af())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const Sa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,h]=Me.useState(!1),[x,g]=Me.useState("idle"),[m,p]=Me.useState(null),y=n?.version?n.releaseUrl||`${qo}/tag/v${n.version}`:qo,b=n?.downloadUrl||y,A=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",C=u==="mobile",S=n?.updateCommand||"pichamber update";Me.useEffect(()=>{e||(g("idle"),p(null))},[e]);const I=async()=>{(await cn(S)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},k=Me.useCallback(async U=>{await Di(U)},[]),w=Me.useCallback(async()=>{g("updating"),p(null);const U=await Nf();if(!U.success){g("error"),p(U.error||"Update failed");return}U.autoRestart&&(g("restarting"),await new Promise($=>setTimeout($,2e3))),g("reconnecting"),await If(n?.currentVersion)?window.location.reload():(g("error"),p("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),j=Me.useCallback(()=>{k(b)},[k,b]),E=x!=="idle"&&x!=="error",T=Me.useMemo(()=>{if(!n?.body)return null;const U=n.body.trim();if(!U)return null;const _=Cf(U);return _.length===0?{kind:"raw",title:"What's new",content:Vo(U)}:{kind:"sections",title:"What's new",sections:[..._].sort((K,P)=>jf(K.version,P.version)).map(K=>({version:K.version,dateLabel:vf(K.date),content:Vo(Sf(K.raw)||U)}))}},[n?.body]);return t.jsx(Kt,{open:e,onOpenChange:E?void 0:s,children:t.jsxs(Ht,{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(os,{className:"flex items-center gap-2.5",children:[t.jsx(D,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&E&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(D,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!E&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ys,{className:"max-h-[400px] p-0",fillContainer:!1,children:T.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:U=>{const $=U.target.closest("a");$&&$.href&&(U.preventDefault(),U.stopPropagation(),k($.href))},children:t.jsx(Mo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(U=>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",U.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:U.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 K=_.target.closest("a");K&&K.href&&(_.preventDefault(),_.stopPropagation(),k(K.href))},children:t.jsx(Mo,{content:U.content,disableLinkSafety:!0,enableFileReferences:!1})})]},U.version))})})}),v&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(D,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:S}),t.jsx("button",{onClick:I,className:z("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(D,{name:"check",className:"h-4 w-4"}):t.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]})]}),!v&&!C&&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:[A,"%"]})]}),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:`${A}%`}})})]}),(l||m)&&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||m})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!C&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!C&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!C&&o&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),C&&t.jsxs(Re,{onClick:j,size:"default",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!E&&t.jsxs("button",{onClick:w,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&E&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Df=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=i.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":o,className:z("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:z("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),pn=({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 d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(Fe,{open:r,onOpenChange:o,children:[t.jsx(Le,{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:z("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(D,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Oe,{sideOffset:8,className:z("max-w-sm",n),children:e})]})},fx="w-full min-w-40 max-w-48",hx="settings",Rf="w-full min-w-40 max-w-48",px="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ef="w-full max-w-[24rem]",mx="min-w-0 flex-1",gx="flex w-full min-w-0 items-center gap-2",xx="typography-meta shrink-0 text-muted-foreground tabular-nums",ja="space-y-3.5",Pf="space-y-1.5",bx="typography-settings-page-title text-muted-foreground",Mf="typography-settings-section-title text-foreground",Ca="typography-settings-group-title text-foreground",io="typography-settings-field-label text-foreground",Tf="typography-settings-description text-muted-foreground",mn="typography-meta text-muted-foreground",yx="typography-meta font-medium text-foreground",wx="typography-settings-section-title text-foreground",Ff=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:z("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:Mf,children:e}):e,n,r!=null?t.jsx(pn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Tf,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:z(d),children:a})]})},vx=({children:e,className:s})=>t.jsx("div",{className:z("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Lf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:z(Ca,s),children:e}),Sx=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:z("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(Lf,{children:e}),n!=null?t.jsx(pn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:mn,children:s}):null]}):null,t.jsx("div",{className:z(a),children:r})]}),rn=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:mn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:z("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:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:z("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},jx=({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:z("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:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),s!=null?t.jsx("p",{className:z(mn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:z("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Cx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:z("pt-4",s),children:e}),Of=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:z("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[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:io,children:n}),d,u!=null?t.jsx(pn,{children:u}):null]}),h?t.jsx("span",{className:mn,children:r}):null]})]})},kx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:z("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(Df,{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:z("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:mn,children:r}):null]})]}),Nx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:z(Pf,n),children:s});function Ax({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:z("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Re,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Bf 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(kc,{className:"w-full max-w-md",children:[t.jsx(Nc,{className:"text-center",children:t.jsxs(Ac,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(D,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Ic,{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(Re,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(D,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function _f(e){return t.jsx(Bf,{...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 Ix=({active:e=!0})=>{const s=ve(n=>n.currentSessionId);return t.jsx(_f,{sessionId:s||void 0,children:t.jsx(Dc,{active:e},s??"no-session")})};function zf({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 ka=Me.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:h,...x},g)=>{const m=Me.useRef(null),p=Me.useRef(null),[y,b]=Me.useState(null),A=c??y,v=Me.useCallback(S=>{const I=m.current;if(!I)return;p.current={startY:S.clientY,startHeight:I.getBoundingClientRect().height};const k=S.currentTarget;k.setPointerCapture(S.pointerId);const w=E=>{const T=p.current;if(!T)return;const U=T.startHeight+(E.clientY-T.startY),_=Math.max(82,U);d?d(_):b(_)},j=()=>{p.current=null,k.removeEventListener("pointermove",w),k.removeEventListener("pointerup",j),k.removeEventListener("pointercancel",j)};k.addEventListener("pointermove",w),k.addEventListener("pointerup",j),k.addEventListener("pointercancel",j),S.preventDefault()},[d]),C=Me.useCallback(S=>{if(S.target.closest('textarea, button, [role="separator"]'))return;const k=m.current?.querySelector("textarea");k&&document.activeElement!==k&&(S.preventDefault(),k.focus())},[]);return f?t.jsx(ys,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:z("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:m,onPointerDown:C,style:A!==null?{height:`${A}px`}:void 0,className:z("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:g,className:z("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(zf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ka.displayName="Textarea";const Na=[{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"}],on=Object.fromEntries(Na.map(e=>[e.key,e.Icon])),Ur="pichamber:project-actions-updated",Aa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ns=(e,s)=>`${Aa(e)}::${s}`,Ia=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Ff,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),$r=e=>e.name.trim().length>0&&e.command.trim().length>0,Uf=e=>e.name.trim().length===0&&e.command.trim().length===0,$f=e=>!$r(e)&&!Uf(e),Gf=(e,s)=>e.some(r=>s.has(r.id)&&!$r(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter($r)},Kf=450,Hf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Wf=()=>({id:Hf(),name:"",command:"",icon:"play"}),Yf=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,d]=i.useState(new Set),u=i.useRef(!1);i.useEffect(()=>{let b=!1;return o(!0),(async()=>{try{const A=await kr(e);if(b)return;n(A.actions),l(JSON.stringify({actions:A.actions})),d(new Set(A.actions.map(v=>v.id)))}catch{if(b)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{b||o(!1)}})(),()=>{b=!0}},[e]);const f=i.useMemo(()=>Gf(s,c),[s,c]),h=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=a!==null&&f.canPersist&&h!==a,g=i.useCallback(async b=>await Rc(e,{actions:b,primaryActionId:null})?(l(JSON.stringify({actions:b})),d(new Set(b.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ur,{detail:{projectId:e.id}})),!0):(ie.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!x||r||u.current)return;const b=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await g(f.actions)}finally{u.current=!1}})())},Kf);return()=>{window.clearTimeout(b)}},[x,r,g,f.actions]);const m=i.useCallback(()=>{const b=Wf();n(A=>[...A,b])},[]),p=i.useCallback(b=>{n(A=>A.filter(v=>v.id!==b))},[]),y=i.useCallback((b,A)=>{n(v=>v.map(C=>C.id===b?A(C):C))},[]);return t.jsx(Ia,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Re,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[t.jsx(D,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:z("space-y-6",Ef),children:s.map((b,A)=>{const v=b.icon||"play",C=on[v]||"play",S=b.name.trim()||`Action ${A+1}`,I=$f(b);return t.jsxs("div",{className:ja,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ca,children:S}),t.jsx(Re,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>p(b.id),"aria-label":`Delete ${S}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(rn,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(D,{name:C,className:"h-4 w-4"})})}),t.jsx(Pt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Na.map(k=>{const w=k.Icon,j=(b.icon||"play")===k.key;return t.jsx("button",{type:"button",onClick:()=>y(b.id,E=>({...E,icon:k.key})),className:z("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",j&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${k.label}`,children:t.jsx(D,{name:w,className:"h-4 w-4"})},k.key)})})})]}),t.jsx(ln,{value:b.name,onChange:k=>y(b.id,w=>({...w,name:k.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(rn,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ka,{value:b.command,onChange:k=>y(b.id,w=>({...w,command:k.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),I?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Of,{checked:b.autoOpenUrl===!0,onChange:k=>y(b.id,w=>({...w,...k?{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 ${S}`}),b.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(rn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(ln,{value:b.openUrl||"",onChange:k=>y(b.id,w=>({...w,openUrl:k.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},b.id)})})})},qf={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)"},Vf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Gt(w=>w.providers),d=Gt(w=>w.modelsMetadata),u=se(w=>w.hiddenModels),f=se(w=>w.isFavoriteModel),h=se(w=>w.toggleFavoriteModel),x=se(w=>w.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:m}=Ec(),[p,y]=i.useState(!1),[b,A]=i.useState("");i.useEffect(()=>{p||A("")},[p]);const v=e?c.find(w=>w.id===e.providerId):void 0,C=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,S=e?Pc(C,e.modelId):s,I=i.useMemo(()=>e?u.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):u,[u,e]),k=i.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),y(!1)},[l]);return t.jsxs(Rt,{modal:!1,open:p,onOpenChange:w=>{r||y(w)},children:[t.jsx(Et,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:z(Tc({size:"default"}),Rf,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Mc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:z("truncate",e?"text-foreground":"text-muted-foreground"),children:S})]}),t.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Pt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Fc,{providers:c,favoriteModels:g,recentModels:m,modelsMetadata:d,searchQuery:b,onSearchQueryChange:A,onSelect:k,labels:{...qf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:I,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>h(w.providerID,w.modelID),onReorderFavorite:(w,j)=>x(w.providerID,w.modelID,j.providerID,j.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",Qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Gt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Ia,{title:"Project",divider:!1,children:t.jsxs("div",{className:ja,children:[t.jsx(rn,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(ln,{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(rn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ar,children:t.jsx(Vf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ar,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Jf=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(()=>Lc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=i.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Xf=450,Zf=(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 d=await a();if(d)try{await s(d)}catch{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},Xf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},eh=({project:e,onIdentitySave:s})=>{const n=Jf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Zf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Qf,{form:n}),t.jsx(Yf,{projectRef:r})]})};function Da({...e}){return t.jsx(Zi,{...e})}function Ra({...e}){return t.jsx(ea,{...e})}function Ea({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(ta,{children:t.jsx(sa,{className:z("app-region-no-drag z-50",s),children:t.jsx(na,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:z(Ri,e),...o,children:n})})})}function Gr({className:e,...s}){return t.jsx(ra,{className:z(Ei,e),...s})}function th({className:e,...s}){return t.jsx(oa,{className:z(Pi,e),...s})}const kn=100;function Dx(){const e=se(w=>w.isArchivePageOpen),s=se(w=>w.setArchivePageOpen),n=se(w=>w.setActiveMainTab),r=ve(w=>w.setCurrentSession),o=ve(w=>w.unarchiveSession),a=Bs(w=>w.homeDirectory),l=Nr({archived:!0}),[c,d]=i.useState(""),[u,f]=i.useState(null),[h,x]=i.useState(kn),g=c.trim().toLowerCase(),m=i.useMemo(()=>e?[...l].sort((w,j)=>(j.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),p=i.useMemo(()=>{const w=new Map;for(const j of m){const E=ye(Ts(j))??"",T=w.get(E);if(T){T.sessions.push(j);continue}w.set(E,{directory:E,label:E?_s(E,a)||E:"other projects",sessions:[j]})}return[...w.values()].sort((j,E)=>E.sessions.length-j.sessions.length)},[a,m]),y=i.useMemo(()=>g?m.filter(w=>(w.title??"").toLowerCase().includes(g)):u===null?m:p.find(w=>w.directory===u)?.sessions??[],[p,g,u,m]),b=y.slice(0,h),A=y.length-b.length,v=l.length,C=i.useCallback(w=>{f(w),x(kn)},[]),S=i.useCallback(w=>{const j=ye(Ts(w));r(w.id,j??void 0),n("chat"),s(!1)},[n,r,s]),I=i.useCallback(w=>{o(w.id).then(j=>{j?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const k=(w,j,E,T,U,_,$)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:U,title:_,className:z("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",$?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",T?"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:j}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),$?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Cs.requestDelete({sessions:$,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 ${j}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return t.jsx(yu,{open:e,onOpenChange:s,children:t.jsxs(wu,{children:[t.jsx(vu,{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(Su,{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(ju,{className:"sr-only",children:"Archived sessions"}),t.jsx(Cu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(ku,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(D,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[k("__all__","All directories",v,u===null,()=>C(null)),p.map(w=>k(w.directory||"__none__",w.label,w.sessions.length,u===w.directory,()=>C(w.directory),w.directory||void 0,w.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:w=>{d(w.target.value),x(kn)},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:y.length===1?`${y.length} archived session`:`${y.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:[b.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):b.map(w=>{const j=ye(Ts(w))??"",E=j?_s(j,a)||j: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:()=>S(w),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),S(w))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:ds(w)}),g&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:j,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:cu(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),I(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${ds(w)}`,children:t.jsx(D,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),Cs.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${ds(w)}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),A>0?t.jsx("button",{type:"button",onClick:()=>x(w=>w+kn),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 Pa=380,lr=8,sh=140;function nh({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[d,u]=i.useState(!1),[f,h]=i.useState(null),{enabled:x}=Vr();return i.useLayoutEffect(()=>{if(!e||!x||!l)return;const g=()=>{const y=n.current?.getBoundingClientRect(),b=a.current?.getBoundingClientRect();if(!y||!b){h(null);return}const A=y.left-b.left;h(Math.min(Math.max(A,lr),Math.max(lr,b.width-Pa-lr)))};g();const m=a.current;if(typeof ResizeObserver>"u"||!m)return;const p=new ResizeObserver(g);return p.observe(m),()=>p.disconnect()},[n,x,e,l]),i.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const g=window.setTimeout(()=>{c(!1),u(!1)},sh);return()=>window.clearTimeout(g)},[e,l]),i.useEffect(()=>{if(!e)return;const g=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[s,e]),i.useEffect(()=>{if(!e)return;const g=m=>{const p=m.target;if(!(p instanceof Node)){s();return}o.current?.contains(p)||n.current?.contains(p)||s()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const Jo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},_n=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),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(D,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),rh=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=nh({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:z("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...u?{top:8,left:d??8,width:`min(${Pa}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(Mi,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:z("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:_n(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:_n(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-C3SyF-cA.js","assets/useAppFontEffects-Bg-8jtrQ.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-Bkz23mZq.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BebQicw3.css","assets/vendor-base-ui-vkqQ2P9o.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-SmPSdfop.js","assets/vendor-dnd-kit-core-CP8ck10N.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-B-Icjoj4.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-B5cJDWBR.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-DMvXzUJh.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-BpTnLRyI.js","assets/isDiffPlainText-BboRbmcm.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-v_8TaIZm.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as vs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Me,j as t,R as i}from"./vendor-react-B5Z1Mdn3.js";import{cV as Ms,i as xc,cc as bc,D as Rt,E as Fe,F as Le,a as Et,U as Re,I as D,G as Oe,b as Pt,bM as yc,bN as wc,bO as vc,bP as Sc,bQ as nr,bR as qs,ck as Ro,bm as Xe,t as ie,c as dt,k as ve,b9 as ks,bg as ln,M as Ii,aQ as Kt,aR as Ht,bi as us,bj as os,bk as fs,bl as Ns,cW as jc,be as Cs,cX as Xs,cY as Cc,ca as $s,Z as Vs,cZ as rr,c_ as Eo,c$ as Po,d0 as tn,aw as Di,ao as ys,aL as Mo,af as cn,ci as Cr,d1 as kc,d2 as Nc,d3 as Ac,d4 as Ic,K as Dc,d5 as kr,d6 as Rc,L as Gt,d7 as Ec,d8 as Pc,cw as Mc,cj as Tc,d9 as Fc,cS as Lc,as as Ri,at as Ei,da as Pi,u as Nr,r as Ts,bZ as Vr,bd as Oc,Y as Bc,bB as To,bA as _c,bz as zc,bJ as Mi,db as Uc,g as Qr,j as Gs,Q as Ti,dc as lt,d as Ar,dd as $c,de as Gc,bv as Kc,df as Hn,dg as Fo,dh as Fi,bK as Li,di as Ir,dj as Oi,S as Bi,ba as Hc,dk as Wc,dl as Yc,l as _i,bW as qc,dm as Vc,dn as Qc,m as Jc,dp as Xc,e as Zc,dq as ed,bV as td,s as sd,f as nd,a7 as zi,dr as Dr,ds as rd,dt as od,bL as id,cU as ad,du as ld,a3 as cd,aN as Ui,c3 as dd,aB as ud,bn as Ls,dv as fd,dw as hd,bX as pd,dx as md,R as $i,ah as gd,dy as xd,W as Gi,dz as Ki,cC as bd,cD as yd,dA as wd,cu as vd,bU as Sd,dB as jd,dC as Cd}from"./useAppFontEffects-Bg-8jtrQ.js";import{g as Lo,aW as kd,aX as Oo,aY as Nd,i as Ad,h as Id,A as Dd,r as Mt,C as dn,B as Rd,c as z,aZ as Ed,b as Os,a_ as Jr,a$ as Xr,b0 as Pd,b1 as Md,f as Bs,M as Td,b2 as Fd,b3 as Ld,b4 as Od,as as ts,p as ss,b5 as Bd,b6 as _d,b7 as zd,y as Zr,b8 as Ud,b9 as $d,ba as Gd,u as se,z as Kd,n as ye,bb as _s,D as Ft,bc as Bo,bd as Rr,w as Wn,be as Hd,aA as Wd,$ as eo,m as sn,bf as Yd,bg as qd,T as Hi,G as Vd,l as Wi,j as nn,bh as Er,H as Pr,a4 as jn,bi as Qd,bj as Qs,ay as or,bk as Mr,bl as ws,bm as _o,bn as Tr,bo as Yi,bp as Fr,bq as Jd,ah as Xd,br as Zd,bs as eu,bt as tu,bu as su,ak as nu,a3 as ru,V as ou,k as zo,bv as qi,d as iu,L as au}from"./index-Bkz23mZq.js";import{c as hs,d as Vi,p as to,u as Lr,a as lu}from"./vendor-zustand-GVb4H8HE.js";import{g as ds,d as cu,e as Qi,r as du,h as Ji,i as En,j as Xi,b as un,c as fn,s as uu,k as fu,l as hu,m as Uo,n as Yn,f as pu,S as mu,a as gu,t as xu,o as bu}from"./SessionUnreadDot-A7vSfll2.js";import{i as Zi,j as ea,k as ta,l as sa,m as na,M as ra,S as oa,D as yu,c as wu,d as vu,e as Su,f as ju,g as Cu,h as ku}from"./vendor-base-ui-vkqQ2P9o.js";import{c as so,d as On,P as ia,D as no,e as ro,f as aa,b as Nu,a as Au,T as Iu,M as Du}from"./vendor-dnd-kit-core-CP8ck10N.js";import{u as Ru}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as la,v as Eu,u as ca,h as Pu}from"./vendor-dnd-kit-sortable-B-Icjoj4.js";import{C as da}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{usePermissionStore as Mu}from"./permissionStore-iKN1K2_x.js";const Tu="chat";function ua(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!==Tu&&s.set(Ms.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ms.FILE,e.diffFile),s}function Fu(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 Lu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=ua(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,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Or(e,s={}){if(!(typeof window>"u")&&!(!s.force&&Lu(e)))try{const n=ua(e),r=Fu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ou=["typescript","javascript","tsx","jsx","json","markdown"],fa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let $o=null;const ha=()=>($o??=Promise.all([vs(()=>import("./index-C3SyF-cA.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])),vs(()=>import("./workerFactory-tw7cIdmV.js"),[]),vs(()=>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),hn={},Go=new Set,Br=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const Bu=()=>{for(const e of Br)e()},pa=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:fa[e].lineDiffType})},_r=e=>{typeof window>"u"||Go.has(e)||(Go.add(e),ha().then(s=>{if(hn[e])return;const n=fa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ou,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),hn[e]=r,pa(e,r),Bu()}))},_u=e=>(Br.add(e),()=>Br.delete(e)),zu=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(hn)){const n=hn[s];n&&pa(s,n)}}},sx=({children:e})=>{const s=xc(),n=Lo(!1),r=Lo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===o)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Me.useEffect(()=>{let d=!1;return ha().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),zu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Me.useEffect(()=>{if(typeof window>"u")return;const d=()=>{_r("unified"),_r("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},nx=(e="unified")=>{const s=Me.useSyncExternalStore(_u,()=>hn[e],()=>{});return Me.useEffect(()=>{_r(e)},[e]),s};function Uu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=bc();return e}catch{return"unknown"}}function $u(){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 Gu(){const e=Rd();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 Ku(e){const s=new URLSearchParams;return s.set("deviceClass",Uu()),s.set("arch",$u()),s.set("platform",Gu()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",dn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ir(e,s){try{const n=Ku(e);s&&n.set("currentVersion",s);const r=await Mt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Hu(){return Ad()?"mobile":Id()?"desktop":Dd()?"web":null}const Ko={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=hs()((e,s)=>({...Ko,checkForUpdates:async()=>{const n=Hu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.8.1",[l,c]=await Promise.allSettled([Oo(),ir("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ir("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ir("mobile","0.8.1"),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 Oo();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 Nd(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 kd())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(Ko)}})),Wu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Yu=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=i.useState(!1),[f,h]=i.useState(""),[x,g]=i.useState(!1),[m,p]=i.useState(!1),[y,b]=i.useState(""),[A,v]=i.useState(!1),C=i.useRef(null),S=i.useCallback(P=>{P.stopPropagation()},[]),I=l.length>1,k=i.useMemo(()=>Wu(y),[y]),w=i.useMemo(()=>{const P=f.toLowerCase();return P?s.filter(B=>B.toLowerCase().includes(P)):s},[f,s]),j=i.useMemo(()=>{const P=f.toLowerCase();return P?n.filter(B=>B.toLowerCase().includes(P)):n},[f,n]),E=P=>{if(P===e){u(!1);return}o(P),u(!1),h("")},T=()=>{g(!0),setTimeout(()=>C.current?.focus(),50)},U=async()=>{if(!(!k||A)){if(I){p(!0);return}v(!0);try{await a(k,l[0]),b(""),g(!1),u(!1)}finally{v(!1)}}},_=async P=>{if(!(!k||A)){v(!0);try{await a(k,P),b(""),g(!1),p(!1),u(!1)}finally{v(!1)}}},$=()=>{p(!1)},K=()=>{b(""),g(!1),p(!1)};return i.useEffect(()=>{d||(h(""),g(!1),p(!1),b(""))},[d]),t.jsxs(Rt,{open:d,onOpenChange:u,children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Oe,{sideOffset:8,children:"Current branch"})]}),t.jsx(Pt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(yc,{className:"h-full min-h-0",children:[t.jsx(wc,{placeholder:"Search branches...",value:f,onValueChange:h,onKeyDown:S}),t.jsxs(vc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Sc,{children:"No branches found."}),t.jsx(nr,{children:m?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:$,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:k})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(P=>t.jsxs("button",{type:"button",onClick:()=>_(P),disabled:A,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[A?t.jsx(D,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,P.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:P.pushUrl})]},P.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:C,placeholder:"New branch name",value:y,onChange:P=>b(P.target.value),onClick:P=>P.stopPropagation(),onKeyDown:P=>{S(P),P.key==="Enter"?(P.preventDefault(),U()):P.key==="Escape"&&(P.preventDefault(),K())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:U,disabled:!k||A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:A?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:K,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsxs(qs,{onSelect:T,children:[t.jsx(D,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Local branches",children:[w.map(P=>t.jsxs(qs,{onSelect:()=>E(P),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:P}),(r?.[P]?.ahead||r?.[P]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[P].ahead||0," ahead ·"," ",r[P].behind||0," behind"]})]}),e===P&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${P}`)),w.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Remote branches",children:[j.map(P=>t.jsx(qs,{onSelect:()=>E(P),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:P})},`remote-${P}`)),j.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},qu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Vu=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,o]=i.useState(!1),[a,l]=i.useState(e||""),[c,d]=i.useState(!1),u=i.useRef(null),f=()=>{!e||!s||(l(e),o(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const m=qu(a);if(m===e){o(!1);return}d(!0);try{await s(e,m),o(!1),l("")}finally{d(!1)}},x=()=>{o(!1),l("")},g=m=>{m.key==="Enter"?(m.preventDefault(),h()):m.key==="Escape"&&(m.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:m=>{m.preventDefault(),h()},children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:m=>l(m.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:g,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:"Rename branch",children:t.jsx(D,{name:"edit",className:"size-4"})})]})]})},Qu=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:o,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:f=!1})=>{const h=i.useRef(!1),x=!!l,g=s.find(S=>S.name===u)??s[0],m=d>0&&f,p=a||e!==null||x||!g||m,y=a||e!==null||x||s.length===0,b=c>0||d>0,A=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=m?"Commit or stash your changes before syncing":g?b?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",C=()=>{g&&r(g)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:m?0:void 0,children:t.jsxs("button",{type:"button",onClick:C,disabled:p,className:z("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:A})]})})}),t.jsx(Oe,{sideOffset:8,children:v})]}),t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:y,"aria-label":"More sync actions",children:t.jsx(D,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Pt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(S=>t.jsx(Xe,{onSelect:I=>{if(h.current){I.preventDefault(),h.current=!1;return}n(S)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(D,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${S.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:S.fetchUrl})]})}),o&&S.name!==u?t.jsx(Re,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:I=>{h.current=!0,I.preventDefault(),I.stopPropagation()},onClick:I=>{h.current=!0,I.preventDefault(),I.stopPropagation(),o(S)},"aria-label":`Remove remote ${S.name}`,title:`Remove remote ${S.name}`,children:l===S.name?t.jsx(D,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(D,{name:"close",className:"size-3.5"})}):null]})},S.name))})]})]})},Ju={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Xu={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 ma(e){return e&&Xu[e]||"var(--primary)"}const Ho=({icon:e,className:s,colorToken:n})=>{const r=Ju[e??"branch"]??"user-3";return t.jsx(D,{name:r,className:s,style:{color:ma(n)}})},ga=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Rt,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs(Re,{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:ma(e?.color)},disabled:a,children:[r?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(Ho,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Oe,{sideOffset:8,children:"Git identity"})]}),t.jsx(Pt,{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(Xe,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(Ho,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(D,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},Zu=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,o=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(Fe,{delayDuration:n,children:[t.jsx(Le,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(D,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),o?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(Oe,{sideOffset:8,children:a})]})},rx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:f,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:g,availableIdentities:m,onSelectIdentity:p,isApplyingIdentity:y,isWorktreeMode:b,onOpenHistory:A,onOpenGraph:v,onOpenStashes:C,onOpenUpdateBranch:S,onOpenReintegrateCommits:I,pullRequest:k,prChecks:w,onOpenPullRequest:j})=>{if(!e)return null;const E=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:A||v||C||S?t.jsxs(Rt,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(D,{name:"more-fill",className:"size-4"})})})}),t.jsx(Oe,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Pt,{align:"end",children:[A?t.jsxs(Xe,{onSelect:A,children:[t.jsx(D,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(Xe,{onSelect:v,children:[t.jsx(D,{name:"git-branch",className:"size-4"}),"Graph"]}):null,C?t.jsxs(Xe,{onSelect:C,children:[t.jsx(D,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,S?t.jsxs(Xe,{onSelect:S,children:[t.jsx(D,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,I?t.jsxs(Xe,{onSelect:I,children:[t.jsx(D,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),T=w?w.state==="success"?"var(--status-success)":w.state==="failure"?"var(--status-error)":"var(--status-warning)":null,U=k?k.state==="merged"?"merged":k.state==="closed"?"closed":k.draft?"draft":w?.state==="failure"||k.mergeable===!1||k.mergeableState==="blocked"||k.mergeableState==="dirty"?"blocked":"open":null,_=k&&j?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",onClick:j,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(D,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${U})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${k.number}`}),T?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:T}}):null]})}),t.jsx(Oe,{sideOffset:8,children:"Open pull request"})]}):null,$=t.jsx(Qu,{syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),K=e.upstreamComparison?t.jsx(Zu,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,P=t.jsx(ga,{activeProfile:g,identities:m,onSelect:p,isApplying:y,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:b?t.jsx(Vu,{currentBranch:e.current,onRename:x}):t.jsx(Yu,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:P})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[_?t.jsx("div",{className:"shrink-0",children:_}):null,t.jsx("div",{className:"min-w-0 flex-1"}),K?t.jsx("div",{className:"min-w-0 shrink",children:K}):null,E,t.jsx("div",{className:"shrink-0",children:$})]})]})},ef=e=>e==="/",zs=e=>e.replace(/\\/g,"/"),Us=e=>{if(!e||ef(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),Bn=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},oo=e=>e.lastIndexOf("/"),xa=e=>{if(Fs(e))return e;const s=oo(e);return s<0?e:e.slice(0,s+1)},ba=e=>{const s=oo(e);return e.slice(s+1)},ya=e=>{const s=Us(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=oo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},wa=e=>Fs(e)&&ya(e)!==null,tf=e=>{if(!wa(e))return null;const s=Us(e.trim());return ba(s)||s},sf=(e,s)=>`${xa(e)}${s}/`,Ss=e=>{if(!e)return null;const s=Us(zs(e.trim()));return s?s.toLowerCase():null},Wo=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},nf=(e,s)=>{const n=Us(zs(e.trim())),r=Us(zs(s.trim()));if(!n)return"";if(!r)return Bn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Bn(n)},rf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,zr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},of=async()=>Ed(),af=()=>{const[e,s]=Me.useState(!1),[n,r]=Me.useState(!1);Me.useEffect(()=>{s(Os()),r(Jr())},[]);const o=Me.useCallback(async c=>e?await Xr(c):{success:!0,path:c},[e]),a=Me.useCallback(async c=>e?await Pd():{success:!0},[e]),l=Me.useCallback(async c=>e?await Md():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function lf({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Bs(Z=>Z.homeDirectory),{canRequestAccess:o,startAccessing:a}=af(),l=i.useRef(null),c=i.useRef(new Map),[d,u]=i.useState(""),[f,h]=i.useState("~/"),[x,g]=i.useState([]),[m,p]=i.useState(!1),[y,b]=i.useState(!1),[A,v]=i.useState(null),[C,S]=i.useState(0),[I,k]=i.useState(0),[w,j]=i.useState(!1),[E,T]=i.useState(!1),[U,_]=i.useState("right"),$=i.useRef("~/"),K=d||r;i.useEffect(()=>{if(!e)return;h("~/"),g([]),k(0),j(!1),T(!1),$.current="~/",_("right"),n||requestAnimationFrame(()=>zr(l.current));let Z=!1;return(async()=>{const L=await of();Z||(u(L||r||""),n||requestAnimationFrame(()=>zr(l.current)))})(),()=>{Z=!0}},[r,e,n]);const P=i.useMemo(()=>xa(f),[f]),B=i.useMemo(()=>Fs(f)?"":ba(f),[f]),R=i.useMemo(()=>K?Wo(P,K):"",[P,K]);i.useEffect(()=>{const Z=$.current;Z!==P&&(_(P.length>=Z.length?"right":"left"),$.current=P)},[P]),i.useEffect(()=>{if(!e||!R){g([]),v(null);return}let Z=!1;return p(!0),b(!1),v(null),Td(R).then(ue=>{if(Z)return;b(!1),v(null);const L=ue.filter(Y=>Y.isDirectory).map(Y=>({name:Y.name,path:zs(Y.path)})).sort((Y,le)=>Y.name.localeCompare(le.name));g(L)}).catch(ue=>{if(!Z){g([]);const L=Fd(ue)?ue.reason:"unknown";v(L),b(L==="not-found")}}).finally(()=>{Z||p(!1)}),()=>{Z=!0}},[R,C,e]);const F=i.useMemo(()=>{const Z=B.toLowerCase(),ue=E||B.startsWith(".");return x.filter(L=>L.name.toLowerCase().startsWith(Z)&&(ue||!L.name.startsWith(".")))},[B,x,E]),V=i.useMemo(()=>tf(f),[f]),G=i.useMemo(()=>ya(f),[f]),M=i.useMemo(()=>{const Z=[],ue=Ss(R);wa(f)&&V&&G&&Z.push({type:"parent",value:"browse:up",name:V,path:G,alreadyAdded:!!(ue&&s.has(ue))});for(const L of F){const Y=Ss(L.path);Z.push({type:"directory",value:`browse:${L.path}`,name:L.name,path:L.path,alreadyAdded:!!(Y&&s.has(Y))})}return Z},[s,R,V,F,G,f]);i.useEffect(()=>{k(0)},[f,M.length]);const ee=i.useMemo(()=>K?Us(Wo(f,K)):"",[K,f]),H=Ss(ee),we=!!(H&&s.has(H)),ce=i.useMemo(()=>B?F.find(Z=>Z.name===B)??null:null,[B,F]),ae=!!(ee&&!we&&(A===null||A==="not-found")&&(Fs(f)&&y||!Fs(f)&&B.trim().length>0&&ce===null)),xe=M[I]??null,be=!!xe,ge=i.useCallback(Z=>{h(Bn(Z))},[]),Se=i.useCallback(Z=>{h(sf(f,Z.name))},[f]),je=i.useCallback(Z=>{if(Z){if(Z.type==="parent"){ge(Z.path);return}Se(Z)}},[ge,Se]),ke=i.useCallback(async Z=>{const ue=await a(Z);if(!ue.success)return ie.error("Failed to open directory",{description:ue.error||"Desktop could not grant file access."}),!1;const L=K?nf(Z,K):Bn(zs(Z));return ge(L),!0},[ge,K,a]),Ce=i.useCallback(async()=>{if(!w){j(!0);try{if(Jr()){const ue=await Xr(ee);if(!ue.success||!ue.path){ue.error&&ue.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:ue.error});return}await ke(ue.path);return}const Z=await Ld(ee);if(Z.status==="cancelled")return;if(Z.status!=="picked"){ie.error("Couldn't open a folder picker",{description:Z.error});return}await ke(Z.path)}catch(Z){ie.error("Failed to select directory",{description:Z instanceof Error?Z.message:"Unknown error occurred."})}finally{j(!1)}}},[ke,w,ee]);return{inputRef:l,rowRefs:c,query:f,setQuery:h,isLoading:m,isBrowseDirectoryMissing:y,browseErrorReason:A,browseReloadKey:C,setBrowseReloadKey:S,highlightedIndex:I,setHighlightedIndex:k,isPickingLocation:w,showHidden:E,setShowHidden:T,folderEnterFrom:U,explorerRootDirectory:K,browseDirectoryDisplayPath:P,browseDirectoryAbsolutePath:R,browseFilterQuery:B,filteredEntries:F,rows:M,targetPath:ee,isAlreadyAdded:we,shouldCreateTarget:ae,highlightedRow:xe,hasHighlightedBrowseItem:be,canRequestAccess:o,browseToDisplayPath:ge,browseToEntry:Se,executeRow:je,applyPickedLocation:ke,handleBrowseLocation:Ce}}const bs=hs()(Vi(to((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=ss()?.git,o=r?await r.getGitIdentities():await Gd();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=ss()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await $d();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=ss()?.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=ss()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Mt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Zr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};ts("saving");const o=ss()?.git;return o?await o.createGitIdentity(r):await zd(r),ts("saved"),await s().loadProfiles(),!0}catch(r){return ts("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};ts("saving");const l=ss()?.git;return l?await l.updateGitIdentity(n,a):await _d(n,a),ts("saved"),await s().loadProfiles(),!0}catch(o){return ts("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{ts("saving");const r=ss()?.git;return r?await r.deleteGitIdentity(n):await Bd(n),ts("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ts("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:Od(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=bs);function cf({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=dt(G=>G.addProject),h=se(G=>G.setActiveMainTab),x=se(G=>G.setSessionSwitcherOpen),g=ve(G=>G.openNewSessionDraft),m=bs(G=>G.profiles),p=bs(G=>G.globalIdentity),y=bs(G=>G.defaultGitIdentityId),b=bs(G=>G.loadProfiles),A=bs(G=>G.loadGlobalIdentity),v=bs(G=>G.loadDefaultGitIdentityId),[C,S]=i.useState(!1),[I,k]=i.useState(!1),[w,j]=i.useState(""),[E,T]=i.useState(null);i.useEffect(()=>{e&&(S(!1),k(!1),j(""),T(null))},[e]),i.useEffect(()=>{e&&(b(),A(),v())},[v,b,A,e]);const U=i.useMemo(()=>{const G=new Map;p&&G.set(p.id,p);for(const M of m)G.set(M.id,M);return Array.from(G.values())},[m,p]);i.useEffect(()=>{if(!e||!I||E!==null)return;const G=typeof y=="string"?y.trim():"";if(G&&U.some(ee=>ee.id===G)){T(G);return}const M=U.find(ee=>ee.authType==="ssh"||ee.sshKey);M&&T(M.id)},[U,y,I,e,E]);const _=i.useMemo(()=>U.find(G=>G.id===E)??null,[U,E]),$=i.useCallback((G,M)=>{h("chat"),n&&x(!1),g({selectedProjectId:G,directoryOverride:M}),s()},[n,s,g,h,x]),K=i.useCallback(async G=>{if(!G||C)return;const M=Ss(G);if(M&&r.has(M))return;let ee=G;S(!0);try{const H=!I&&a&&Ss(G)===Ss(o);if(I){const ce=w.trim();if(!ce){ie.error("Enter a repository URL before cloning.");return}const ae=await Mt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ce,destinationPath:G,gitIdentityId:_?.id??null})});if(!ae.ok)throw new Error("Failed to clone git repository");ee=(await ae.json()).path||G}else if(H&&!(await Mt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:G})})).ok)throw new Error("Failed to select directory");const we=f(ee);if(!we){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}$(we.id,we.path)}catch(H){ie.error("Failed to select directory",{description:H instanceof Error?H.message:"Unknown error occurred."})}finally{S(!1)}},[f,r,c,w,I,C,$,_?.id,a,o]),P=!C&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,B=P&&w.trim().length>0,R=I?B:P,F=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:C,isCloneMode:I,setIsCloneMode:k,cloneRemoteUrl:w,setCloneRemoteUrl:j,selectedGitIdentityId:E,setSelectedGitIdentityId:T,availableGitIdentities:U,selectedGitIdentity:_,canSubmit:R,submitActionLabel:d?"Already added":I?C?"Cloning...":"Clone & add":C?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:F,finalizeSelection:K}}const df=({open:e,onOpenChange:s})=>{const n=dt(L=>L.projects),{isMobile:r,isTablet:o}=ks(),a=r||o,l=i.useMemo(()=>new Set(n.map(L=>Ss(L.path)).filter(L=>!!L)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:d,rowRefs:u,query:f,setQuery:h,isLoading:x,browseErrorReason:g,setBrowseReloadKey:m,highlightedIndex:p,setHighlightedIndex:y,isPickingLocation:b,showHidden:A,setShowHidden:v,folderEnterFrom:C,browseDirectoryDisplayPath:S,browseDirectoryAbsolutePath:I,rows:k,targetPath:w,isAlreadyAdded:j,shouldCreateTarget:E,highlightedRow:T,hasHighlightedBrowseItem:U,canRequestAccess:_,executeRow:$,handleBrowseLocation:K}=lf({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:P,isCloneMode:B,setIsCloneMode:R,cloneRemoteUrl:F,setCloneRemoteUrl:V,setSelectedGitIdentityId:G,availableGitIdentities:M,selectedGitIdentity:ee,canSubmit:H,submitActionLabel:we,submitModifierLabel:ce,finalizeSelection:ae}=cf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:E,browseErrorReason:g,browseDirectoryAbsolutePath:I,isAlreadyAdded:j,isPickingLocation:b});i.useLayoutEffect(()=>{const L=d.current;L&&(L.scrollLeft=L.scrollWidth)},[d,f]),i.useLayoutEffect(()=>{!e||a||zr(d.current)},[d,e,a]),i.useLayoutEffect(()=>{const L=k[p];L&&u.current.get(L.value)?.scrollIntoView({block:"nearest"})},[p,u,k]);const xe=i.useCallback(L=>{if(L.key==="ArrowDown"){L.preventDefault(),y(Y=>Math.min(k.length-1,Y+1));return}if(L.key==="ArrowUp"){L.preventDefault(),y(Y=>Math.max(0,Y-1));return}if(L.key==="Enter"){if(L.preventDefault(),rf(L)){ae(w);return}U&&$(T);return}L.key==="Backspace"&&f===""&&(L.preventDefault(),c())},[$,ae,c,U,T,f,k.length,y,w]),be=t.jsxs("button",{type:"button",onClick:()=>v(L=>!L),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:[A?t.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),ge=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(D,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(ln,{ref:d,value:f,onChange:L=>h(zs(L.target.value)),onKeyDown:xe,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(Re,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:P||b,onMouseDown:L=>L.preventDefault(),onClick:()=>{K()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(D,{name:"folder-open",className:"h-3.5 w-3.5"}),b?"Opening...":"Browse"]})]})}),Se=k.some(L=>L.type==="parent"),je=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(Re,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":B,disabled:P||b,onClick:()=>R(L=>!L),children:[t.jsx(D,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),B?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(ln,{value:F,onChange:L=>V(L.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(ga,{activeProfile:ee,identities:M,onSelect:L=>G(L.id),isApplying:P,iconOnly:!0})]})]}):null,j?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:z("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",C==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):g&&g!=="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:g==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[g==="os-permission"&&_?t.jsx(Re,{size:"xs",onClick:()=>{K()},disabled:b,children:"Grant access"}):null,t.jsx(Re,{variant:"outline",size:"xs",onClick:()=>m(L=>L+1),children:"Try again"})]})]}):k.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:k.map((L,Y)=>{const le=Y===p,W=L.type==="directory"&&Se;return t.jsxs("button",{ref:X=>{X?u.current.set(L.value,X):u.current.delete(L.value)},type:"button","aria-label":L.type==="parent"?L.alreadyAdded?`Go back from ${L.name}, already added`:`Go back from ${L.name}`:L.alreadyAdded?`Open ${L.name}, already added`:`Open ${L.name}`,onMouseEnter:()=>y(Y),onMouseDown:X=>X.preventDefault(),onClick:()=>$(L),className:z("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",le&&"bg-interactive-selection text-interactive-selection-foreground",!le&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:z("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[L.type==="parent"?t.jsx(D,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(D,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:L.name})]}),L.alreadyAdded?t.jsx("span",{className:z("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",le?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,L.type==="parent"?t.jsx(D,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},L.value)})})},S)]})}),ke=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ge,je]}),Ce=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(D,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(D,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:ce}),t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Z=t.jsx(Re,{size:r?"xs":"default",onClick:()=>{ae(w)},disabled:!H,className:z(r&&"w-full flex-1"),children:we}),ue=()=>t.jsxs(t.Fragment,{children:[r?null:Ce,t.jsx("div",{className:z("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:Z})]});return r?t.jsx(Ii,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ue()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:be}),ke]})}):t.jsx(Kt,{open:e,onOpenChange:s,children:t.jsxs(Ht,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(us,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(os,{children:"Add folder"}),t.jsx(fs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),be]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:ke}),t.jsx(Ns,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ue()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,ox=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=jc,c=ve(I=>I.deleteSessions),d=se(I=>I.showDeletionDialog),u=se(I=>I.setShowDeletionDialog),{isMobile:f,isTablet:h,hasTouchInput:x}=ks(),g=f||h||x;i.useEffect(()=>Kd(()=>{s(!1)}),[]);const m=i.useCallback(I=>{r({sessions:I.sessions,dateLabel:I.dateLabel})},[]),p=i.useCallback(()=>{r(null),a(!1)},[]),y=i.useCallback(async I=>{if(I.sessions.length===0)return;if(I.sessions.length===1){const E=I.sessions[0];await l(E.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const k=I.sessions.map(E=>E.id),{deletedIds:w,failedIds:j}=await c(k);if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:I.dateLabel?`Removed all sessions from ${I.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Cn(E)})}j.length>0&&ie.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>Cs.onDeleteRequest(I=>{if(!d){y(I);return}m(I)}),[m,d,y]),i.useEffect(()=>Cs.onDirectoryRequest(()=>{s(!0)}),[]);const b=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const I=n.sessions[0];if(!await l(I.id)){ie.error("Failed to delete session"),a(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const I=n.sessions.map(E=>E.id),k=await c(I),w=k.deletedIds,j=k.failedIds;if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Cn(E),action:{label:"OK",onClick:()=>{}}})}if(j.length>0&&(ie.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:Cn("Please try again in a moment.")}),w.length===0)){a(!1);return}}p()}finally{a(!1)}}},[n,l,c,p]),A=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.`:"",v=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(I=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:ds(I)})},I.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,C=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(D,{name:"checkbox-blank",className:"size-4"}):t.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Re,{variant:"ghost",onClick:p,disabled:o,children:"Cancel"}),t.jsx(Re,{variant:"destructive",onClick:b,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),S=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[g?t.jsx(Ii,{open:!!n,onClose:()=>{o||p()},title:S,footer:t.jsx("div",{className:"flex justify-end gap-2",children:C}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[A&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:A}),v]})}):t.jsx(Kt,{open:!!n,onOpenChange:I=>{if(!I){if(o)return;p()}},children:t.jsxs(Ht,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(us,{children:[t.jsx(os,{children:S}),A&&t.jsx(fs,{children:A})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Ns,{className:"mt-2 gap-2 pt-1 pb-1",children:C})]})}),t.jsx(df,{open:e,onOpenChange:s})]})},ix=()=>{const e=Xs(d=>d.entries),s=se(d=>d.isMobile),n=se(d=>d.activeMainTab),r=ve(d=>d.newSessionDraft),o=ve(d=>d.openNewSessionDraft),a=ve(d=>d.setNewSessionDraftTarget),l=n==="chat",c=i.useMemo(()=>{const d=Cc(r?.worktreeIntent),u=!!r?.open,f=[];for(const h of e.values()){const x=u&&h.key===d,g=x&&l;if(h.state){g||f.push(h);continue}h.receipt&&!x&&f.push(h)}return f},[e,r?.worktreeIntent,r?.open,l]);return c.length===0?null:t.jsx("div",{className:z("pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3",s?"bottom-[calc(var(--oc-safe-area-bottom,0px)+5.5rem)]":"bottom-4"),"aria-live":"polite",children:t.jsx("div",{className:"pointer-events-auto flex w-full max-w-[640px] flex-col gap-2",children:c.map(d=>t.jsx(uf,{entry:d,onDismissFailed:()=>Xs.getState().dismissFailed(d.key),onDismissCompleted:()=>Xs.getState().clearEntry(d.key),onOpenWorktree:()=>{const u=d.receipt;u&&(r?.open?a({directoryOverride:u.path,worktreeIntent:null}):o({directoryOverride:u.path}),Xs.getState().clearEntry(d.key),se.getState().setActiveMainTab("chat"))}},d.key))})})},uf=({entry:e,onDismissFailed:s,onDismissCompleted:n,onOpenWorktree:r})=>{const o=e.state?.phase==="failed",a=!!(e.state&&!o),l=!e.state&&!!e.receipt,c=o?e.state?.label??"Worktree creation failed":a?e.state?.label??"Creating worktree...":e.receipt?`Worktree ready: ${e.receipt.branch??e.path??"new worktree"}`:"",d=o?e.state?.error:l?e.receipt?.path:null;return t.jsxs("div",{className:z("flex items-center gap-3 rounded-xl border px-3 py-2.5 shadow-lg backdrop-blur",o?"border-[var(--status-error-border)] bg-[var(--status-error-background)] text-[var(--status-error-foreground)]":l?"border-[var(--border)] bg-[var(--surface-elevated)] text-foreground":"border-[var(--border)] bg-[var(--surface-muted)] text-muted-foreground"),role:o?"alert":"status",children:[a?t.jsx($s,{variant:"inline",text:null,animationType:"spinner"}):l?t.jsx(D,{name:"git-branch",className:"h-4 w-4 shrink-0 text-[var(--status-success)]"}):t.jsx(D,{name:"alert",className:"h-4 w-4 shrink-0"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"typography-ui-label truncate",children:c}),d?t.jsx("p",{className:"mt-0.5 break-words text-xs opacity-80 line-clamp-2",children:d}):null,a&&e.branch?t.jsx("p",{className:"mt-0.5 truncate text-xs opacity-60",children:e.branch}):null]}),o?t.jsx(Re,{type:"button",variant:"ghost",size:"xs",onClick:s,"aria-label":"Dismiss error",children:"Dismiss"}):null,l?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Re,{type:"button",size:"xs",onClick:r,children:"Open"}),t.jsx(Re,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Dismiss",children:t.jsx(D,{name:"close",className:"h-3.5 w-3.5"})})]}):null,a?t.jsx("span",{className:"hidden shrink-0 text-xs opacity-60 sm:inline",children:"In background"}):null]})},ff=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],hf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function pf(e){const s=e.trim().toLowerCase();return ff.find(n=>n.slug===s)??null}function mf(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=hf[s];if(n)return n;const r=pf(s);return r?r.slug:"home"}function ax(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 lx(){const e=i.useRef(!1),s=i.useRef(!1),n=ve(f=>f.setCurrentSession),r=se(f=>f.setActiveMainTab),o=se(f=>f.setSettingsDialogOpen),a=se(f=>f.setSettingsPage),l=se(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const h=ve.getState().currentSessionId,x=Vs().getState().selectedSessionId;if(f.sessionId!==h||f.sessionId!==x){const g=ve.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,g)}}if(f.settingsPath){a(mf(f.settingsPath)),o(!0);return}se.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]),d=i.useCallback(()=>{const f=ve.getState(),h=Vs().getState(),x=se.getState();return{sessionId:rr({currentSessionId:f.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=i.useCallback((f={})=>{if(s.current)return;const h=d();Or(h,f)},[d]);i.useEffect(()=>{if(e.current||(e.current=!0,!Eo()))return;const f=Po();(async()=>(await c(f),Or({...d(),sessionId:f.sessionId??rr({currentSessionId:ve.getState().currentSessionId,piSelectedSessionId:Vs().getState().selectedSessionId,draft:ve.getState().newSessionDraft}),tab:f.tab??se.getState().activeMainTab,settingsPath:f.settingsPath??se.getState().settingsPage,diffFile:f.diffFile??se.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),i.useEffect(()=>{const f=()=>{const y=ve.getState(),b=Vs().getState();return rr({currentSessionId:y.currentSessionId,piSelectedSessionId:b.selectedSessionId,draft:y.newSessionDraft})};let h=f(),x=ve.getState().newSessionDraft?.open===!0;const g=()=>{const y=ve.getState(),b=f(),A=y.newSessionDraft?.open===!0;b===h&&A===x||s.current||(h=b,x=A,u({replace:!0}))},m=ve.subscribe(()=>{g()}),p=Vs().subscribe(()=>{g()});return()=>{m(),p()}},[u]),i.useEffect(()=>{let f=se.getState().activeMainTab,h=se.getState().isSettingsDialogOpen,x=se.getState().settingsPage,g=se.getState().pendingDiffFile;return se.subscribe(p=>{if(s.current)return;const y=p.activeMainTab!==f,b=p.isSettingsDialogOpen!==h,A=p.settingsPage!==x,v=p.pendingDiffFile!==g&&p.activeMainTab==="diff";f=p.activeMainTab,h=p.isSettingsDialogOpen,x=p.settingsPage,g=p.pendingDiffFile,(y||b||A||v)&&u()})},[u]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const h=Po();if(Eo())c(h);else{const x=se.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function gf(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,d=null;const u=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},f=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),g=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(g)},h))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function cx(){const e=tn(s=>s.connection==="ready",void 0,"chrome");return gf(e),null}const Yo=12,xf=[{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"}],bf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=xf,onComplete:a})=>{const l=Me.useRef(!1);Me.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Me.useMemo(()=>Array.from({length:Yo},(d,u)=>{const f=Math.PI*2*u/Yo;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:z("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((f,h)=>{const x=f.x*d.radius,g=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:m},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},yf=({durationMs:e=3400}={})=>{const[s,n]=Me.useState({isActive:!1,cycle:0}),r=Me.useRef(null),o=Me.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Me.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Me.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 Me.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},va=i.createContext(void 0),dx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=yf(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(va.Provider,{value:a,children:[e,t.jsx(bf,{isActive:s,burstKey:n})]})},wf={triggerFireworks:()=>{},dismissFireworks:()=>{}},ux=()=>i.useContext(va)??wf,qo="https://github.com/RyderAsKing/PiChamber/releases";function vf(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 Sf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Vo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function jf(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 Cf(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 Qo=2e3,kf=600*1e3;async function Nf(){try{const e=await Mt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Af(){try{return(await Mt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function If(e,s=Math.ceil(kf/Qo),n=Qo){for(let r=0;r<s;r++){try{const o=await Mt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await Af())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const Sa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,h]=Me.useState(!1),[x,g]=Me.useState("idle"),[m,p]=Me.useState(null),y=n?.version?n.releaseUrl||`${qo}/tag/v${n.version}`:qo,b=n?.downloadUrl||y,A=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",C=u==="mobile",S=n?.updateCommand||"pichamber update";Me.useEffect(()=>{e||(g("idle"),p(null))},[e]);const I=async()=>{(await cn(S)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},k=Me.useCallback(async U=>{await Di(U)},[]),w=Me.useCallback(async()=>{g("updating"),p(null);const U=await Nf();if(!U.success){g("error"),p(U.error||"Update failed");return}U.autoRestart&&(g("restarting"),await new Promise($=>setTimeout($,2e3))),g("reconnecting"),await If(n?.currentVersion)?window.location.reload():(g("error"),p("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),j=Me.useCallback(()=>{k(b)},[k,b]),E=x!=="idle"&&x!=="error",T=Me.useMemo(()=>{if(!n?.body)return null;const U=n.body.trim();if(!U)return null;const _=Cf(U);return _.length===0?{kind:"raw",title:"What's new",content:Vo(U)}:{kind:"sections",title:"What's new",sections:[..._].sort((K,P)=>jf(K.version,P.version)).map(K=>({version:K.version,dateLabel:vf(K.date),content:Vo(Sf(K.raw)||U)}))}},[n?.body]);return t.jsx(Kt,{open:e,onOpenChange:E?void 0:s,children:t.jsxs(Ht,{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(os,{className:"flex items-center gap-2.5",children:[t.jsx(D,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&E&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(D,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!E&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ys,{className:"max-h-[400px] p-0",fillContainer:!1,children:T.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:U=>{const $=U.target.closest("a");$&&$.href&&(U.preventDefault(),U.stopPropagation(),k($.href))},children:t.jsx(Mo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(U=>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",U.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:U.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 K=_.target.closest("a");K&&K.href&&(_.preventDefault(),_.stopPropagation(),k(K.href))},children:t.jsx(Mo,{content:U.content,disableLinkSafety:!0,enableFileReferences:!1})})]},U.version))})})}),v&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(D,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:S}),t.jsx("button",{onClick:I,className:z("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(D,{name:"check",className:"h-4 w-4"}):t.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]})]}),!v&&!C&&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:[A,"%"]})]}),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:`${A}%`}})})]}),(l||m)&&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||m})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!C&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!C&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!C&&o&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),C&&t.jsxs(Re,{onClick:j,size:"default",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!E&&t.jsxs("button",{onClick:w,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&E&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Df=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=i.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":o,className:z("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:z("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),pn=({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 d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(Fe,{open:r,onOpenChange:o,children:[t.jsx(Le,{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:z("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(D,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Oe,{sideOffset:8,className:z("max-w-sm",n),children:e})]})},fx="w-full min-w-40 max-w-48",hx="settings",Rf="w-full min-w-40 max-w-48",px="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ef="w-full max-w-[24rem]",mx="min-w-0 flex-1",gx="flex w-full min-w-0 items-center gap-2",xx="typography-meta shrink-0 text-muted-foreground tabular-nums",ja="space-y-3.5",Pf="space-y-1.5",bx="typography-settings-page-title text-muted-foreground",Mf="typography-settings-section-title text-foreground",Ca="typography-settings-group-title text-foreground",io="typography-settings-field-label text-foreground",Tf="typography-settings-description text-muted-foreground",mn="typography-meta text-muted-foreground",yx="typography-meta font-medium text-foreground",wx="typography-settings-section-title text-foreground",Ff=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:z("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:Mf,children:e}):e,n,r!=null?t.jsx(pn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Tf,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:z(d),children:a})]})},vx=({children:e,className:s})=>t.jsx("div",{className:z("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Lf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:z(Ca,s),children:e}),Sx=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:z("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(Lf,{children:e}),n!=null?t.jsx(pn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:mn,children:s}):null]}):null,t.jsx("div",{className:z(a),children:r})]}),rn=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:mn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:z("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:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:z("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},jx=({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:z("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:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),s!=null?t.jsx("p",{className:z(mn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:z("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Cx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:z("pt-4",s),children:e}),Of=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:z("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[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:io,children:n}),d,u!=null?t.jsx(pn,{children:u}):null]}),h?t.jsx("span",{className:mn,children:r}):null]})]})},kx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:z("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(Df,{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:z("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:mn,children:r}):null]})]}),Nx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:z(Pf,n),children:s});function Ax({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:z("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Re,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Bf 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(kc,{className:"w-full max-w-md",children:[t.jsx(Nc,{className:"text-center",children:t.jsxs(Ac,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(D,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Ic,{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(Re,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(D,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function _f(e){return t.jsx(Bf,{...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 Ix=({active:e=!0})=>{const s=ve(n=>n.currentSessionId);return t.jsx(_f,{sessionId:s||void 0,children:t.jsx(Dc,{active:e},s??"no-session")})};function zf({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 ka=Me.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:h,...x},g)=>{const m=Me.useRef(null),p=Me.useRef(null),[y,b]=Me.useState(null),A=c??y,v=Me.useCallback(S=>{const I=m.current;if(!I)return;p.current={startY:S.clientY,startHeight:I.getBoundingClientRect().height};const k=S.currentTarget;k.setPointerCapture(S.pointerId);const w=E=>{const T=p.current;if(!T)return;const U=T.startHeight+(E.clientY-T.startY),_=Math.max(82,U);d?d(_):b(_)},j=()=>{p.current=null,k.removeEventListener("pointermove",w),k.removeEventListener("pointerup",j),k.removeEventListener("pointercancel",j)};k.addEventListener("pointermove",w),k.addEventListener("pointerup",j),k.addEventListener("pointercancel",j),S.preventDefault()},[d]),C=Me.useCallback(S=>{if(S.target.closest('textarea, button, [role="separator"]'))return;const k=m.current?.querySelector("textarea");k&&document.activeElement!==k&&(S.preventDefault(),k.focus())},[]);return f?t.jsx(ys,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:z("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:m,onPointerDown:C,style:A!==null?{height:`${A}px`}:void 0,className:z("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:g,className:z("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(zf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ka.displayName="Textarea";const Na=[{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"}],on=Object.fromEntries(Na.map(e=>[e.key,e.Icon])),Ur="pichamber:project-actions-updated",Aa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ns=(e,s)=>`${Aa(e)}::${s}`,Ia=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Ff,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),$r=e=>e.name.trim().length>0&&e.command.trim().length>0,Uf=e=>e.name.trim().length===0&&e.command.trim().length===0,$f=e=>!$r(e)&&!Uf(e),Gf=(e,s)=>e.some(r=>s.has(r.id)&&!$r(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter($r)},Kf=450,Hf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Wf=()=>({id:Hf(),name:"",command:"",icon:"play"}),Yf=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,d]=i.useState(new Set),u=i.useRef(!1);i.useEffect(()=>{let b=!1;return o(!0),(async()=>{try{const A=await kr(e);if(b)return;n(A.actions),l(JSON.stringify({actions:A.actions})),d(new Set(A.actions.map(v=>v.id)))}catch{if(b)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{b||o(!1)}})(),()=>{b=!0}},[e]);const f=i.useMemo(()=>Gf(s,c),[s,c]),h=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=a!==null&&f.canPersist&&h!==a,g=i.useCallback(async b=>await Rc(e,{actions:b,primaryActionId:null})?(l(JSON.stringify({actions:b})),d(new Set(b.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ur,{detail:{projectId:e.id}})),!0):(ie.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!x||r||u.current)return;const b=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await g(f.actions)}finally{u.current=!1}})())},Kf);return()=>{window.clearTimeout(b)}},[x,r,g,f.actions]);const m=i.useCallback(()=>{const b=Wf();n(A=>[...A,b])},[]),p=i.useCallback(b=>{n(A=>A.filter(v=>v.id!==b))},[]),y=i.useCallback((b,A)=>{n(v=>v.map(C=>C.id===b?A(C):C))},[]);return t.jsx(Ia,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Re,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[t.jsx(D,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:z("space-y-6",Ef),children:s.map((b,A)=>{const v=b.icon||"play",C=on[v]||"play",S=b.name.trim()||`Action ${A+1}`,I=$f(b);return t.jsxs("div",{className:ja,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ca,children:S}),t.jsx(Re,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>p(b.id),"aria-label":`Delete ${S}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(rn,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(D,{name:C,className:"h-4 w-4"})})}),t.jsx(Pt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Na.map(k=>{const w=k.Icon,j=(b.icon||"play")===k.key;return t.jsx("button",{type:"button",onClick:()=>y(b.id,E=>({...E,icon:k.key})),className:z("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",j&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${k.label}`,children:t.jsx(D,{name:w,className:"h-4 w-4"})},k.key)})})})]}),t.jsx(ln,{value:b.name,onChange:k=>y(b.id,w=>({...w,name:k.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(rn,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ka,{value:b.command,onChange:k=>y(b.id,w=>({...w,command:k.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),I?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Of,{checked:b.autoOpenUrl===!0,onChange:k=>y(b.id,w=>({...w,...k?{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 ${S}`}),b.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(rn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(ln,{value:b.openUrl||"",onChange:k=>y(b.id,w=>({...w,openUrl:k.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},b.id)})})})},qf={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)"},Vf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Gt(w=>w.providers),d=Gt(w=>w.modelsMetadata),u=se(w=>w.hiddenModels),f=se(w=>w.isFavoriteModel),h=se(w=>w.toggleFavoriteModel),x=se(w=>w.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:m}=Ec(),[p,y]=i.useState(!1),[b,A]=i.useState("");i.useEffect(()=>{p||A("")},[p]);const v=e?c.find(w=>w.id===e.providerId):void 0,C=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,S=e?Pc(C,e.modelId):s,I=i.useMemo(()=>e?u.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):u,[u,e]),k=i.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),y(!1)},[l]);return t.jsxs(Rt,{modal:!1,open:p,onOpenChange:w=>{r||y(w)},children:[t.jsx(Et,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:z(Tc({size:"default"}),Rf,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Mc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:z("truncate",e?"text-foreground":"text-muted-foreground"),children:S})]}),t.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Pt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Fc,{providers:c,favoriteModels:g,recentModels:m,modelsMetadata:d,searchQuery:b,onSearchQueryChange:A,onSelect:k,labels:{...qf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:I,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>h(w.providerID,w.modelID),onReorderFavorite:(w,j)=>x(w.providerID,w.modelID,j.providerID,j.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",Qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Gt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Ia,{title:"Project",divider:!1,children:t.jsxs("div",{className:ja,children:[t.jsx(rn,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(ln,{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(rn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ar,children:t.jsx(Vf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ar,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Jf=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(()=>Lc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=i.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Xf=450,Zf=(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 d=await a();if(d)try{await s(d)}catch{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},Xf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},eh=({project:e,onIdentitySave:s})=>{const n=Jf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Zf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Qf,{form:n}),t.jsx(Yf,{projectRef:r})]})};function Da({...e}){return t.jsx(Zi,{...e})}function Ra({...e}){return t.jsx(ea,{...e})}function Ea({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(ta,{children:t.jsx(sa,{className:z("app-region-no-drag z-50",s),children:t.jsx(na,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:z(Ri,e),...o,children:n})})})}function Gr({className:e,...s}){return t.jsx(ra,{className:z(Ei,e),...s})}function th({className:e,...s}){return t.jsx(oa,{className:z(Pi,e),...s})}const kn=100;function Dx(){const e=se(w=>w.isArchivePageOpen),s=se(w=>w.setArchivePageOpen),n=se(w=>w.setActiveMainTab),r=ve(w=>w.setCurrentSession),o=ve(w=>w.unarchiveSession),a=Bs(w=>w.homeDirectory),l=Nr({archived:!0}),[c,d]=i.useState(""),[u,f]=i.useState(null),[h,x]=i.useState(kn),g=c.trim().toLowerCase(),m=i.useMemo(()=>e?[...l].sort((w,j)=>(j.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),p=i.useMemo(()=>{const w=new Map;for(const j of m){const E=ye(Ts(j))??"",T=w.get(E);if(T){T.sessions.push(j);continue}w.set(E,{directory:E,label:E?_s(E,a)||E:"other projects",sessions:[j]})}return[...w.values()].sort((j,E)=>E.sessions.length-j.sessions.length)},[a,m]),y=i.useMemo(()=>g?m.filter(w=>(w.title??"").toLowerCase().includes(g)):u===null?m:p.find(w=>w.directory===u)?.sessions??[],[p,g,u,m]),b=y.slice(0,h),A=y.length-b.length,v=l.length,C=i.useCallback(w=>{f(w),x(kn)},[]),S=i.useCallback(w=>{const j=ye(Ts(w));r(w.id,j??void 0),n("chat"),s(!1)},[n,r,s]),I=i.useCallback(w=>{o(w.id).then(j=>{j?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const k=(w,j,E,T,U,_,$)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:U,title:_,className:z("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",$?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",T?"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:j}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),$?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Cs.requestDelete({sessions:$,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 ${j}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return t.jsx(yu,{open:e,onOpenChange:s,children:t.jsxs(wu,{children:[t.jsx(vu,{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(Su,{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(ju,{className:"sr-only",children:"Archived sessions"}),t.jsx(Cu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(ku,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(D,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[k("__all__","All directories",v,u===null,()=>C(null)),p.map(w=>k(w.directory||"__none__",w.label,w.sessions.length,u===w.directory,()=>C(w.directory),w.directory||void 0,w.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:w=>{d(w.target.value),x(kn)},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:y.length===1?`${y.length} archived session`:`${y.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:[b.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):b.map(w=>{const j=ye(Ts(w))??"",E=j?_s(j,a)||j: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:()=>S(w),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),S(w))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:ds(w)}),g&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:j,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:cu(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),I(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${ds(w)}`,children:t.jsx(D,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),Cs.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${ds(w)}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),A>0?t.jsx("button",{type:"button",onClick:()=>x(w=>w+kn),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 Pa=380,lr=8,sh=140;function nh({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[d,u]=i.useState(!1),[f,h]=i.useState(null),{enabled:x}=Vr();return i.useLayoutEffect(()=>{if(!e||!x||!l)return;const g=()=>{const y=n.current?.getBoundingClientRect(),b=a.current?.getBoundingClientRect();if(!y||!b){h(null);return}const A=y.left-b.left;h(Math.min(Math.max(A,lr),Math.max(lr,b.width-Pa-lr)))};g();const m=a.current;if(typeof ResizeObserver>"u"||!m)return;const p=new ResizeObserver(g);return p.observe(m),()=>p.disconnect()},[n,x,e,l]),i.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const g=window.setTimeout(()=>{c(!1),u(!1)},sh);return()=>window.clearTimeout(g)},[e,l]),i.useEffect(()=>{if(!e)return;const g=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[s,e]),i.useEffect(()=>{if(!e)return;const g=m=>{const p=m.target;if(!(p instanceof Node)){s();return}o.current?.contains(p)||n.current?.contains(p)||s()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const Jo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},_n=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),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(D,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),rh=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=nh({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:z("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...u?{top:8,left:d??8,width:`min(${Pa}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(Mi,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:z("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:_n(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:_n(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); }
|
|
@@ -51,4 +51,4 @@ ${n}`:""}function Ka(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${
|
|
|
51
51
|
`):l.slice(0,-1).join(`
|
|
52
52
|
`);if(this.tail=a.endsWith(`
|
|
53
53
|
`)?"":(l[l.length-1]??"").slice(-1024),!c)return;const d=Qm(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Jm(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const h=he.getState().getDirectoryState(s)?.tabs.find(x=>x.id===n);!h||h.previewUrlLocked||h.previewUrl===d||o(s,n,d,{locked:!1,autoOpened:!1})})}}const sg=(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"?Ja(o):null};function ng({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:h,focusTerminalWhenWindowActive:x}){const g=he(M=>M.ensureDirectory),m=he(M=>M.setTabSessionId),p=he(M=>M.setTabLifecycle),y=he(M=>M.setConnecting),b=he(M=>M.appendToBuffer),A=he(M=>M.replaceBuffer),v=he(M=>M.setTabPreviewUrl),[C,S]=i.useState(null),[I,k]=i.useState(!1),[w,j]=i.useState(!1),E=i.useRef(null),T=i.useRef(null),U=i.useRef(n),_=i.useRef(r),$=i.useRef(s),K=i.useRef(null),P=i.useRef(new Set),B=i.useRef(new tg),R=i.useCallback(()=>{B.current.reset()},[]);i.useEffect(()=>{_.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),i.useEffect(()=>{U.current=n,R()},[n,R]),i.useEffect(()=>{$.current=s},[s]);const F=i.useCallback(()=>{E.current?.(),E.current=null,T.current=null,j(!1)},[]);i.useEffect(()=>()=>{F(),_.current=null},[F]);const V=i.useCallback((M,ee,H)=>{B.current.scan(M,ee,H,v)},[v]),G=i.useCallback((M,ee,H)=>{if(T.current===H)return;F(),T.current=H;const we=e.connect(H,{onEvent:ce=>{if(T.current===H)switch(ce.type){case"snapshot":{y(M,ee,!1),S(null),k(!1),j(!1),x(),A(M,ee,ce.data??"",ce.sequence??0),V(M,ee,ce.data??""),ce.status==="exited"&&p(M,ee,"exited");break}case"reconnecting":{S(null),k(!1),j(!0);break}case"data":{ce.data&&(b(M,ee,ce.data,ce.sequence,ce.replayData),V(M,ee,ce.data));break}case"exit":{const ae=typeof ce.exitCode=="number"?ce.exitCode:null,xe=typeof ce.signal=="number"?ce.signal:null,ge=!!he.getState().getDirectoryState(M)?.tabs.find(Se=>Se.id===ee)?.label?.startsWith("Action:");b(M,ee,`\\r\\n[Process exited${ae!==null?` with code ${ae}`:""}${xe!==null?` (signal ${xe})`:""}]\\r\\n`),p(M,ee,"exited"),y(M,ee,!1),S(ge?null:"Terminal session ended"),k(!1),j(!1),F();break}}},onError:(ce,ae)=>{if(T.current===H){if(!ae){S(null),k(!1);return}if(j(!1),ce.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(M)?.tabs.find(be=>be.id===ee)?.label?.startsWith("Action:")){S(null),k(!1),y(M,ee,!1),m(M,ee,null),p(M,ee,"idle"),F();return}S(`Connection failed: ${ce.message}`),k(!0),y(M,ee,!1),p(M,ee,"exited"),m(M,ee,null),F()}}});E.current=()=>{we.close(),T.current=null}},[b,F,x,A,V,y,p,m,e]);return i.useEffect(()=>{let M=!1;if(!l||!a)return;if(!s){S(h?"No working directory available for terminal.":"Select a session to open the terminal."),F();return}return(async()=>{const H=s;if(!$.current||$.current!==H)return;if(!he.getState().getDirectoryState(H)){g(H);return}const ce=he.getState().getDirectoryState(H);if(!ce||ce.tabs.length===0)return;const ae=ce.activeTabId??ce.tabs[0]?.id??null;if(!ae)return;const xe=ce.tabs.find(Ce=>Ce.id===ae)??ce.tabs[0],be=xe?.terminalSessionId??null,ge=xe?.lifecycle??"idle",Se=!!xe?.label?.startsWith("Action:"),je=he.getState().getBuffer(H,ae),ke=je.byteLength>0||je.chunks.length>0;if(!be){if(ge==="exited"){y(H,ae,!1);return}if(Se&&ke){y(H,ae,!1);return}const Ce=`${H}\0${ae}`;if(P.current.has(Ce))return;const Z=K.current??Xa;P.current.add(Ce),S(null),k(!1),j(!1),y(H,ae,!0);try{const ue=await e.createSession({cwd:H,sessionId:ae,cols:Z.cols,rows:Z.rows,shell:c,loginShell:d,...u.current}),L=!M&&$.current===H&&U.current===ae;if(!he.getState().getDirectoryState(H)?.tabs.find(W=>W.id===ae)){try{await e.close(ue.sessionId)}catch{}return}if(m(H,ae,ue.sessionId),!L)return;const le=K.current;le&&(le.cols!==Z.cols||le.rows!==Z.rows)&&e.resize({sessionId:ue.sessionId,...le}).catch(()=>{});return}catch(ue){const L=he.getState().getDirectoryState(H)?.tabs.find(Y=>Y.id===ae);if(!L||L.terminalSessionId||(y(H,ae,!1),$.current!==H||U.current!==ae))return;S(ue instanceof Error?ue.message:"Failed to start terminal session"),k(!0),j(!1);return}finally{P.current.delete(Ce)}}!be||M||(_.current=be,G(H,ae,be))})(),()=>{M=!0,_.current=null,F()}},[h,s,r,o,n,a,f,l,g,y,p,m,G,F,e,d,c,u]),{connectionError:C,setConnectionError:S,isFatalError:I,setIsFatalError:k,isReconnectPending:w,setIsReconnectPending:j,terminalIdRef:_,lastViewportSizeRef:K,directoryRef:$,activeTabIdRef:U,disconnectStream:F,resetTerminalPreviewScan:R,startStream:G}}function rg({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=i.useState(null),h=i.useRef(null),x=i.useCallback(()=>{d||h.current?.focus()},[d]),g=i.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||h.current?.focus()},[d]);i.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),i.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const m=i.useCallback(v=>{if(!v||n)return;let C=v,S=!1;u&&v.length>0&&(C=eg(v,u),S=!0);const I=s.current;I&&(e.sendInput(I,C).catch(k=>{n||r(k instanceof Error?k.message:"Failed to send input")}),S&&(f(null),x()))},[u,x,n,r,e,s]),p=i.useCallback((v,C)=>{const S=l.current;if((!S||S.cols!==v||S.rows!==C)&&(l.current={cols:v,rows:C}),!a)return;const I=s.current;I&&e.resize({sessionId:I,cols:v,rows:C}).catch(()=>{})},[a,l,e,s]),y=i.useCallback(v=>{f(C=>C===v?null:v),x()},[x]),b=i.useCallback(v=>{const C=Zm(v,u);C&&(m(C),f(null),x())},[u,x,m]),A=i.useCallback(v=>{if(v.repeat)return;const C=v.key;if(!C||C==="Control"||C==="Meta"||C==="Alt"||C==="Shift")return;const S=C.length===1?C.toLowerCase():C;if(S in vi){v.preventDefault(),v.stopPropagation(),b(vi[S]);return}const I=sg(v,u);I&&(v.preventDefault(),v.stopPropagation(),m(I),f(null),x())},[u,x,b,m]);return i.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[u,A,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:h,focusTerminalController:x,focusTerminalWhenWindowActive:g,handleViewportInput:m,handleViewportResize:p,handleModifierToggle:y,handleMobileKeyPress:b}}function og({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,disconnectStream:h,resetTerminalPreviewScan:x,startStream:g,setConnectionError:m,setIsFatalError:p,setIsReconnectPending:y}){const b=he(_=>_.createTab),A=he(_=>_.setActiveTab),v=he(_=>_.closeTab),C=he(_=>_.setTabSessionId),S=he(_=>_.setTabLifecycle),[I,k]=i.useState(!1),w=i.useCallback(async()=>{if(!s||I)return;const _=he.getState().getDirectoryState(s),$=n??_?.activeTabId??_?.tabs[0]?.id??null;if(!$)return;const K=_?.tabs.find(P=>P.id===$)?.terminalSessionId??null;if(!(!K||!e.restartSession)){k(!0),m(null),p(!1),y(!1),h(),x();try{const P=c.current??Xa,B=await e.restartSession(K,{cwd:s,shell:o,loginShell:a,...P,...l.current});if(he.getState().getDirectoryState(s)?.tabs.find(F=>F.id===$)?.terminalSessionId!==K||(C(s,$,B.sessionId),S(s,$,"running"),d.current!==s||u.current!==$))return;f.current=B.sessionId,g(s,$,B.sessionId)}catch(P){if(he.getState().getDirectoryState(s)?.tabs.find(R=>R.id===$)?.terminalSessionId!==K||d.current!==s||u.current!==$)return;m(P instanceof Error?P.message:"Failed to restart terminal"),p(!1),y(!1),f.current=K,g(s,$,K)}finally{k(!1)}}},[n,u,d,h,s,r,I,c,x,m,p,y,S,C,g,e,l,f,a,o]),j=i.useCallback(async()=>{await w()},[w]),E=i.useCallback(()=>{if(!s)return;const _=b(s);A(s,_),m(null),p(!1),y(!1),h()},[b,h,s,A,m,p,y]),T=i.useCallback(_=>{s&&(A(s,_),m(null),p(!1),y(!1),h())},[h,s,A,m,p,y]),U=i.useCallback(_=>{if(!s)return;_===n&&h(),m(null),p(!1),y(!1);const $=he.getState().getDirectoryState(s)?.tabs.find(K=>K.id===_)?.terminalSessionId;(async()=>{$&&await e.close($),v(s,_)})().catch(K=>m(K instanceof Error?K.message:"Terminal session ended"))},[n,v,h,s,m,p,y,e]);return{isRestarting:I,handleRestart:w,handleHardRestart:j,handleCreateTab:E,handleSelectTab:T,handleCloseTab:U}}const Tx=({visible:e})=>{const{terminal:s,runtime:n}=Gs(),{currentTheme:r}=Ui(),o=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});o.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=dd(),l=se(J=>J.terminalFontSize),c=se(J=>J.terminalShell),d=se(J=>J.terminalLoginShells.includes(J.terminalShell)),{isMobile:u,isTablet:f,hasTouchOnlyPointer:h}=ks(),x=u||f,g=(x||h)&&n.platform==="web",m=!0,p=se(J=>J.showTerminalQuickKeysOnDesktop),y=x||p,b=ve(J=>J.currentSessionId),A=ve(J=>J.newSessionDraft),v=b!==null||A?.open===!0,C=ud()??null,S=he(J=>C?J.sessions.get(C):void 0),I=he(J=>J.hasHydrated),k=se(J=>J.openContextPreview),w=i.useMemo(()=>S?S.activeTabId??S.tabs[0]?.id??null:null,[S,m]),j=i.useMemo(()=>{if(S)return w?S.tabs.find(J=>J.id===w)??S.tabs[0]:S.tabs[0]},[S,w]),E=i.useMemo(()=>(S?.tabs??[]).map(J=>({icon:(()=>{const Be=J.iconKey?on[J.iconKey]??"terminal":"terminal";return t.jsx(D,{name:Be,className:"h-4 w-4"})})(),id:J.id,label:J.label,title:J.label,closeLabel:"Close tab"})),[S?.tabs]),T=j?.terminalSessionId??null,U=j?.lifecycle??"idle",_=he(J=>C&&w?J.getBuffer(C,w).chunks:Ln.chunks),$=j?.isConnecting??!1,K=j?.previewUrl??null,B=se(J=>J.activeMainTab)==="terminal",R=e??B,[F,V]=i.useState(R);i.useEffect(()=>{R&&V(!0)},[R]);const{connectionError:G,setConnectionError:M,isFatalError:ee,setIsFatalError:H,isReconnectPending:we,setIsReconnectPending:ce,terminalIdRef:ae,lastViewportSizeRef:xe,directoryRef:be,activeTabIdRef:ge,disconnectStream:Se,resetTerminalPreviewScan:je,startStream:ke}=ng({terminal:s,effectiveDirectory:C,activeTabId:w,terminalSessionId:T,terminalLifecycle:U,hasOpenedTerminalViewport:F,terminalHydrated:I,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:o,enableTabs:m,hasActiveContext:v,focusTerminalWhenWindowActive:()=>{!g&&typeof document<"u"&&document.hasFocus()&&Z.current?.focus()}}),{activeModifier:Ce,terminalControllerRef:Z,focusTerminalWhenWindowActive:ue,handleViewportInput:L,handleViewportResize:Y,handleModifierToggle:le,handleMobileKeyPress:W}=rg({terminal:s,terminalIdRef:ae,isReconnectPending:we,setConnectionError:M,showQuickKeys:y,isTerminalVisible:R,lastViewportSizeRef:xe,terminalSessionId:T,useTouchTerminalInput:g}),{isRestarting:X,handleRestart:te,handleHardRestart:ne,handleCreateTab:Ae,handleSelectTab:Ie,handleCloseTab:Pe}=og({terminal:s,effectiveDirectory:C,activeTabId:w,enableTabs:m,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:o,lastViewportSizeRef:xe,directoryRef:be,activeTabIdRef:ge,terminalIdRef:ae,disconnectStream:Se,resetTerminalPreviewScan:je,startStream:ke,setConnectionError:M,setIsFatalError:H,setIsReconnectPending:ce});i.useEffect(()=>{if(!R||g)return;if(typeof window>"u"){ue();return}const J=window.requestAnimationFrame(()=>{ue()});return()=>{window.cancelAnimationFrame(J)}},[w,ue,R,g]);const De=i.useMemo(()=>{const J=Qs[or].stack;if(typeof window>"u")return(Qs[a]??Qs[or]).stack;const We=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return We&&We.trim().length>0?We.trim():(Qs[a]??Qs[or]).stack??J},[a]),Ge=i.useMemo(()=>Nm(r),[r]),de=`${C??"no-dir"}::${w??"no-tab"}`;if(i.useEffect(()=>{if(!R||g)return;const J=Z.current;if(!J)return;const Be=()=>{J.fit()};if(typeof window<"u"){const We=window.requestAnimationFrame(()=>{Be(),ue()}),Ue=[220,400].map(Ve=>window.setTimeout(Be,Ve));return()=>{window.cancelAnimationFrame(We),Ue.forEach(Ve=>window.clearTimeout(Ve))}}Be()},[ue,R,g,Z,de,T]),i.useEffect(()=>{if(!R||!g)return;let J=null;const Be=()=>{J!==null&&window.cancelAnimationFrame(J),J=window.requestAnimationFrame(()=>{J=null,Z.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Be),()=>{window.removeEventListener("oc:keyboard-settled",Be),J!==null&&window.cancelAnimationFrame(J)}},[R,Z,de,g]),!v)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:te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ze=!T||$||X||we,Ne=F,Ye=t.jsx($m,{isTouchTerminal:x,activeModifier:Ce,disabled:ze,onKeyPress:W,onModifierToggle:le});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:z("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[S?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:z("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(Um,{items:E,activeId:w,onSelect:Ie,onClose:Pe,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Re,{type:"button",size:"xs",variant:"ghost",className:z("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ae,title:"New tab",children:t.jsx(D,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Re,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{te()},disabled:X,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(D,{name:"restart",className:"h-4 w-4"})}),K?t.jsxs(Re,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{C&&k(C,K)},title:"Open preview pane",children:[t.jsx(D,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&y&&m&&S?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Ye}):null,!x&&y&&!S?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:Ge.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Ne?t.jsx(Qa,{ref:J=>{Z.current=J},sessionKey:de,chunks:_,onInput:L,onResize:Y,theme:Ge,fontFamily:De,fontSize:l,enableTouchScroll:g,autoFocus:R,isVisible:R},de):null}),!we&&G&&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:G}),ee&&x&&t.jsx(Re,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ne,disabled:X,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&y?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]})},ig=48,ag=96,mt=(e,...s)=>{try{e?.(...s)}catch{}},wr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Fx=(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"?ag:ig;let d=!1,u=!1,f=!1,h=null,x=!1,g=0,m=0,p=0,y=0;const b=()=>{d=!1,u=!1,f=!1,h=null},A=()=>{const j=n.current,E=h,T=x;u&&E&&(mt(E==="left"?j.onLeftProgress:j.onRightProgress,T?1:0),mt(j.onDragEnd,E,T)),b()},v=()=>{A(),u||b()},C=j=>{const E=n.current;if(E.enabled===!1){u&&h?A():b();return}if(j.touches.length!==1){u&&h?A():b();return}const T=j.touches[0],U=o.getBoundingClientRect(),_=o.clientWidth,$=!!E.leftOpen,K=!!E.rightOpen,P=B=>xm(B,o);if($||K){if(P(j.target)){b();return}if($&&K){const B=T.clientX<=U.left+c;T.clientX>=U.right-c?(h="right",x=!0):B?(h="left",x=!0):(h=$?"left":"right",x=!0)}else $?(h="left",x=!0):(h="right",x=!0);y=wr(h==="left"?E.leftWidth:E.rightWidth,_),y<10&&(y=_||window.innerWidth||320),y<10&&(y=320),d=!0}else{if(P(j.target)){b();return}h=null,x=!1,y=0,d=!0}g=T.clientX,m=T.clientY,p=Date.now(),u=!1,f=!1},S=j=>{if(!d)return;if(j.touches.length!==1){v();return}const E=j.touches[0],T=E.clientX-g,U=E.clientY-m;if(!f){if(Math.abs(T)<pi&&Math.abs(U)<pi)return;if(Math.abs(U)>Math.abs(T)*Zs){b();return}if(!h){const K=n.current;h=T>0?"left":"right",y=wr(h==="left"?K.leftWidth:K.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(h==="left"){if(!x&&T<=0){b();return}if(x&&T>=0){b();return}}else{if(!x&&T>=0){b();return}if(x&&T<=0){b();return}}f=!0,u=!0,mt(n.current.onDragStart,h)}if(!u)return;j.cancelable&&j.preventDefault();const _=n.current,$=mi(h,x,T,y);mt(h==="left"?_.onLeftProgress:_.onRightProgress,$)},I=(j,E)=>{if(!d){b();return}const T=j-g,U=E-m;if(!h&&!x&&Math.abs(T)>=Fn&&Math.abs(U)<=Math.abs(T)*Zs){const R=n.current;h=T>0?"left":"right",y=wr(h==="left"?R.leftWidth:R.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(!h){b();return}const _=Math.max(1,Date.now()-p),$=n.current;if(!u){const R=Math.abs(T),F=Math.abs(U);R>=Fn&&F<=R*Zs?h==="left"&&!x&&T>0?(mt($.onLeftProgress,1),mt($.onLeftOpen)):h==="right"&&!x&&T<0?(mt($.onRightProgress,1),mt($.onRightOpen)):mt(h==="left"?$.onLeftProgress:$.onRightProgress,x?1:0):mt(h==="left"?$.onLeftProgress:$.onRightProgress,x?1:0);const V=h;b(),mt($.onDragEnd,V);return}const K=mi(h,x,T,y),P=mm({side:h,isOpenAtStart:x,dx:T,dt:_,progress:K}),B=h;mt(B==="left"?P?$.onLeftOpen:$.onLeftClose:P?$.onRightOpen:$.onRightClose),b(),mt($.onDragEnd,B,P)},k=j=>{const E=j.changedTouches[0];if(!E){b();return}const T=E.clientX-g,U=E.clientY-m;d&&(u||Math.abs(T)>=Fn&&Math.abs(U)<=Math.abs(T)*Zs)&&j.cancelable&&j.preventDefault(),I(E.clientX,E.clientY)},w=()=>{v()};return o.addEventListener("touchstart",C,{passive:!0}),o.addEventListener("touchmove",S,{passive:!1}),o.addEventListener("touchend",k,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{u&&h&&A()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",C),o.removeEventListener("touchmove",S),o.removeEventListener("touchend",k),o.removeEventListener("touchcancel",w)}},[e,r])};function Lx({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(D,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Si({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 lg=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,cg=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Hn(s,n)?null:e,vr=()=>ws.filter(e=>Tr.has(e.id)).map(e=>({...Yi(e)})),dg=()=>{if(typeof window>"u")return Fr;const e=window.localStorage.getItem("openInAppId");return e&&Mr(e)?e:Fr};let Sr=!1,Ps=!1,ls=!1,cs=0,an=null;const ji=()=>{an&&(clearTimeout(an),an=null)},xs=hs()((e,s)=>({selectedAppId:dg(),availableApps:vr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Sr||typeof window>"u")return;Sr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:vr(),hasLoadedApps:u});return}const f=new Set(d.map(m=>m.name)),h=new Map(d.map(m=>[m.name,m.iconDataUrl??void 0])),g=ws.filter(m=>f.has(m.appName)||Tr.has(m.id)).map(m=>({...Yi(m),iconDataUrl:h.get(m.appName)}));e({availableApps:g,hasLoadedApps:!0})},r=async d=>{if(!Os()||!dn()||Ps||s().hasLoadedApps&&!d)return;const f=ws.map(h=>h.appName);ji(),Ps=!0,ls=!1,e({isScanning:!0});try{const{apps:h,success:x,hasCache:g,isCacheStale:m}=await _o(f,d),p=x&&!g&&h.length===0&&cs<3;if(e({isCacheStale:g?m:!1}),n(h,x?!p:!1),x){if(p){const b=[800,1600,3200][cs]??3200;cs+=1,ls=!0,an=setTimeout(()=>{r()},b);return}cs=0,ls=!1;return}if(cs<3){const b=[1e3,3e3,7e3][cs]??7e3;cs+=1,ls=!0,an=setTimeout(()=>{r()},b)}}finally{Ps=!1,ls||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Mr(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(cs=3,ls=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Sr||s().initialize(),!Os()||!dn()||Ps||s().hasLoadedApps&&!n)return;const o=ws.map(a=>a.appName);ji(),n&&e({hasLoadedApps:!1}),Ps=!0,ls=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await _o(o,n),d=new Set(a.map(x=>x.name)),u=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),h=ws.filter(x=>d.has(x.appName)||Tr.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:h.length>0?h:vr(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{Ps=!1,ls||e({isScanning:!1})}},selectApp:async n=>{Mr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Zr({openInAppId:n}))}})),ug="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",fg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",jr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?ug:e.id==="terminal"?fg:void 0}),Ci=({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:z("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},hg=({directory:e,className:s})=>{const n=xs(m=>m.selectedAppId),r=xs(m=>m.availableApps),o=xs(m=>m.isCacheStale),a=xs(m=>m.isScanning),l=xs(m=>m.initialize),c=xs(m=>m.loadInstalledApps),d=xs(m=>m.selectApp);i.useEffect(()=>{l()},[l]);const u=Os()&&dn(),f=i.useMemo(()=>{const m=r.find(p=>p.id===n)??r.find(p=>p.id===Fr)??r[0]??ws[0];return jr(m||ws[0])},[r,n]);if(!u||!e||r.length===0)return null;const h=async m=>{await Jd(e,m.id,m.appName)||await Hi(e,m.appName)},x=async m=>{await d(m.id),await h(m)},g=async()=>{(await cn(e)).ok&&ie.success("Path copied to clipboard")};return t.jsxs("div",{className:z("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{h(f)},className:z("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(Ci,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Pt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g()},children:[t.jsx(D,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Ls,{}),r.map(m=>{const p=jr(m);return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[t.jsx(Ci,{label:m.label,iconDataUrl:m.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:m.label}),f.id===m.id?t.jsx(D,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(D,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},pg="\x1B",mg=new RegExp(`${pg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),gg=/https?:\/\/[^\s<>'"`]+/gi,vt="__pichamber_auto_discover_preview__",xg=15e3,bg=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},yg=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}},wg=e=>{const n=e.replace(mg,"").match(gg);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,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",h=f.split("/").filter(Boolean).length,x=f==="/"||f==="",g=!!(c.search||c.hash);let m=0;return u&&(m+=50),x&&(m+=30),m-=Math.min(h*5,20),g&&(m-=10),m};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},vg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Sg=["dev","start","preview","serve"];async function jg(e,s,n){if(!e)return null;const r=Ng(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Ag(n);if(o){const a=await Ig(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await Cg(e)){const o=await kg(),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 Cg(e){const s=`${e}/index.html`,n=await Kn(s,e);return typeof n=="string"&&n.trim().length>0}async function kg(){try{const e=await Mt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Ng(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(Sg.some(o=>n.includes(o)))return s}return null}function Ag(e){for(const{pattern:s}of vg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Ig(e){const s=await Kn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Kn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Kn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Mt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=ss()?.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 Mt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Dg(e){try{const s=await Kn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Rg=(e,s,n)=>new Promise(r=>{let o=!1,a=null,l=null;const c=d=>{o||(o=!0,l&&clearTimeout(l),a?.close(),r(d))};a=e.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?a.close():l=setTimeout(()=>c(!1),n)});function Eg({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=Ui(),{terminal:o}=Gs(),{isMobile:a}=ks(),l=se(W=>W.terminalShell),c=se(W=>W.terminalLoginShells.includes(W.terminalShell)),d=se(W=>W.setSettingsPage),u=se(W=>W.setSettingsDialogOpen),f=se(W=>W.setSettingsProjectsSelectedId),h=se(W=>W.openContextPreview),x=he(W=>W.ensureDirectory),g=he(W=>W.setTabLabel),m=he(W=>W.setTabIconKey),p=he(W=>W.setActiveTab),y=he(W=>W.setConnecting),b=he(W=>W.setTabSessionId),A=he(W=>W.setTabPreviewUrl),v=he(W=>W.projectActionRuns),C=he(W=>W.setProjectActionRun),S=he(W=>W.updateProjectActionRunStatus),I=he(W=>W.removeProjectActionRun),[k,w]=i.useState([]),[j,E]=i.useState(null),[T,U]=i.useState(!1),_=i.useRef({}),$=i.useRef({}),K=i.useRef({}),P=i.useRef({}),B=i.useRef(new Set),R=i.useRef(0),F=e?.id??null,V=e?.path??"",G=i.useMemo(()=>F?{id:F,path:V}:null,[F,V]),M=i.useCallback(async W=>{await Di(W)},[]),ee=i.useCallback(async()=>{if(!G)return;const W=R.current+1;R.current=W,U(!0);try{const X=await kr(G);if(R.current!==W)return;const te=X.actions;w(te),E(ne=>ne===vt||ne&&te.some(Ae=>Ae.id===ne)?ne:null)}catch{if(R.current!==W)return}finally{R.current===W&&U(!1)}},[G]),H=i.useMemo(()=>Aa(s||G?.path||""),[s,G?.path]),we=i.useMemo(()=>j?k.find(W=>W.id===j)??null:null,[k,j]),ce=i.useMemo(()=>({id:vt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),ae=!a,xe=i.useMemo(()=>ae?[ce,...k]:k,[k,ce,ae]);i.useEffect(()=>{ee()},[ee]),i.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const te=X.detail;F&&(te?.projectId&&te.projectId!==F||ee())};return window.addEventListener(Ur,W),()=>{window.removeEventListener(Ur,W)}},[ee,F]),i.useEffect(()=>{j&&(j===vt&&ae||k.some(W=>W.id===j)||E(null))},[k,ae,j]),i.useEffect(()=>{const W=()=>{const X=he.getState(),te=X.sessions,ne=X.projectActionRuns;for(const[Ae,Ie]of Object.entries(ne)){const De=te.get(Ie.directory)?.tabs.find(Ue=>Ue.id===Ie.tabId);if(!De||De.terminalSessionId!==Ie.sessionId){I(Ae);continue}const Ge=$.current[Ae]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};$.current[Ae]=Ge;const de=xe.find(Ue=>Ue.id===Ie.actionId),ze=X.getBuffer(Ie.directory,Ie.tabId).chunks;if(!de||ze.length===0)continue;const Ne=ze.filter(Ue=>Ge.lastSeenChunkId===null||Ue.id>Ge.lastSeenChunkId);if(Ne.length===0)continue;const Ye=Ne.map(Ue=>Ue.data).join(""),J=`${Ge.tail}${Ye}`,Be=!Ge.openedUrl&&de.autoOpenUrl===!0?wg(J):null,We=Ne[Ne.length-1]?.id??Ge.lastSeenChunkId;if(Ge.lastSeenChunkId=We,Ge.tail=J.slice(-512),Be)if(Ge.openedUrl=!0,Ge.openInPreview){const Ue=ne[Ae];Ue&&(A(Ue.directory,Ue.tabId,Be,{locked:!1,autoOpened:!1}),Ue.status==="waiting-for-preview"&&S(Ae,"running"),window.clearTimeout(P.current[Ae]),delete P.current[Ae],h(Ue.directory,Be))}else M(Be),ie.success("Opened URL from action output");$.current[Ae]=Ge}for(const Ae of Object.keys($.current))ne[Ae]||(delete $.current[Ae],window.clearTimeout(P.current[Ae]),delete P.current[Ae])};return W(),he.subscribe((X,te)=>{(X.sessions!==te.sessions||X.buffers!==te.buffers)&&W()})},[xe,h,M,v,I,A,S]);const be=i.useCallback(async(W,X={})=>{if(!H)throw new Error("No active directory");const te=ns(H,W.id);x(H);const ne=he.getState(),Ae=ne.getDirectoryState(H);let Ie=_.current[te]||null;const Pe=Ie?!!Ae?.tabs.some(de=>de.id===Ie):!1;(!Ie||!Pe)&&(Ie=ne.createTab(H),_.current[te]=Ie),g(H,Ie,`Action: ${W.name}`),m(H,Ie,W.icon||"play"),p(H,Ie),X.revealTerminal!==!1&&se.getState().openContextPanelTab(H,{mode:"terminal"});const Ge=he.getState().getDirectoryState(H)?.tabs.find(de=>de.id===Ie);return{key:te,tabId:Ie,sessionId:Ge?.terminalSessionId??null}},[x,H,p,m,g]),ge=i.useCallback(async W=>{if(!n&&a)return;if(!H){ie.error("No active directory for action");return}const X=ns(H,W.id),te=v[X];if(!(te&&te.status==="running")&&!B.current.has(X)){B.current.add(X);try{const ne=W.id===vt?await(async()=>{const[J,Be]=await Promise.all([kr({id:G?.id??"",path:H}),Dg(H)]),We=await jg(H,J.actions,Be);if(!We)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:vt,name:"Auto-discover",command:We.command,icon:"scan-2",autoOpenUrl:!0,openUrl:We.previewUrlHint||""}})():W,Ae=ne.autoOpenUrl===!0&&(ne.openUrl||"").trim().length>0,Ie=!Ae&&W.id!==vt,{key:Pe,tabId:De,sessionId:Ge}=await be(ne,{revealTerminal:Ie});let de=Ge;if(!de){y(H,De,!0);try{de=(await o.createSession({cwd:H,sessionId:De,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,b(H,De,de)}finally{y(H,De,!1)}}if(!de)throw new Error("Failed to create terminal session");K.current[Pe]?.(),y(H,De,!0);const ze=o.connect(de,{onEvent:J=>{J.type==="snapshot"&&(he.getState().replaceBuffer(H,De,J.data??"",J.sequence??0),he.getState().setConnecting(H,De,!1)),J.type==="data"&&typeof J.data=="string"&&J.data.length>0&&he.getState().appendToBuffer(H,De,J.data,J.sequence,J.replayData),J.type==="exit"&&(he.getState().setTabLifecycle(H,De,"exited"),he.getState().setConnecting(H,De,!1),he.getState().removeProjectActionRun(Pe),delete $.current[Pe],K.current[Pe]?.(),delete K.current[Pe],window.clearTimeout(P.current[Pe]),delete P.current[Pe])},onError:(J,Be)=>{he.getState().setConnecting(H,De,!1),Be&&(he.getState().setTabLifecycle(H,De,"exited"),he.getState().setTabSessionId(H,De,null),he.getState().removeProjectActionRun(Pe))}});K.current[Pe]=ze.close;const Ne=ne.autoOpenUrl?yg(ne.openUrl):null;C({key:Pe,directory:H,actionId:ne.id,tabId:De,sessionId:de,status:ne.id===vt&&!Ne?"waiting-for-preview":"running"}),window.clearTimeout(P.current[Pe]),delete P.current[Pe],ne.id===vt&&!Ne&&(P.current[Pe]=window.setTimeout(()=>{const J=he.getState(),Be=J.projectActionRuns[Pe];J.updateProjectActionRunStatus(Pe,"running"),Be&&(J.setActiveTab(Be.directory,Be.tabId),se.getState().openContextPanelTab(Be.directory,{mode:"terminal"})),delete P.current[Pe]},xg)),$.current[Pe]={lastSeenChunkId:null,openedUrl:!!Ne||Ae,tail:"",openInPreview:ne.id===vt};const Ye=bg(ne.command.trim().replace(/\r\n|\r/g,`
|
|
54
|
-
`));await o.sendInput(de,`${Ye}\r`),Ne?(A(H,De,Ne,{locked:!0,autoOpened:!0}),h(H,Ne),ie.success("Opened action URL")):Ae?(A(H,De,null,{locked:!0}),ie.error("Invalid custom URL format")):A(H,De,null,{locked:!1,autoOpened:!1})}catch(ne){I(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X],ie.error(ne instanceof Error?ne.message:"Failed to run action")}finally{B.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,be,n,a,H,c,l,h,v,I,y,C,A,b,G?.id,o]),Se=i.useCallback(async W=>{const X=ns(H,W.id),te=v[X];if(!te)return;S(X,"stopping");const ne=Rg(o,te.sessionId,1e3);try{await o.sendInput(te.sessionId,"")}catch{}const Ae=await ne;if(he.getState().getDirectoryState(te.directory)?.tabs.find(De=>De.id===te.tabId)?.terminalSessionId===te.sessionId&&!Ae){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:te.sessionId})}catch{}else try{await o.close(te.sessionId)}catch{}b(te.directory,te.tabId,null)}I(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X]},[H,v,I,b,o,S]),je=i.useCallback(()=>{const W=we??xe[0];if(!W)return;const X=ns(H,W.id),te=v[X];if(te?.status!=="stopping"){if(te){Se(W);return}ge(W)}},[xe,H,ge,v,we,Se]),ke=i.useCallback((W,X=!1)=>{if(E(W.id),!X){ge(W);return}const te=ns(H,W.id),ne=v[te];if(ne?.status!=="stopping"){if(ne){Se(W);return}ge(W)}},[H,ge,v,Se]),Ce=i.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),Z=we??xe[0]??null,ue=Z?v[ns(H,Z.id)]:null,L=he(W=>ue?W.sessions.get(ue.directory)?.tabs.find(X=>X.id===ue.tabId)?.previewUrl??null:null),Y=!!((n||!a)&&G&&H),le=we??xe[0]??null;return{shouldRender:Y,isLoading:T,normalizedDirectory:H,resolvedSelected:le,displayActions:xe,projectActionRuns:v,selectedRunPreviewUrl:L,handlePrimaryClick:je,handleSelectAction:ke,openProjectActionsSettings:Ce,openContextPreview:h}}const ki=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:h,handlePrimaryClick:x,handleSelectAction:g,openProjectActionsSettings:m,openContextPreview:p}=Eg({projectRef:e,directory:s,allowMobile:o});if(!a||!d)return null;const y=d.icon||"play",b=d.id===vt?"scan-2":on[y]||"play",A=ns(c,d.id),v=f[A],C=v?.status==="stopping",S=v?.status==="waiting-for-preview",I=!!(v&&h),k=()=>{!v||!h||p(v.directory,h)},w=d.id===vt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||C,className:z("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:C||S?t.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?t.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(D,{name:b,className:"h-5 w-5"})})}),w?t.jsx(Oe,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),I?t.jsxs(Fe,{children:[t.jsx(Le,{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:k,children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(Oe,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Pt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ls,{}),u.map(j=>{const E=j.icon||"play",T=j.id===vt?"scan-2":on[E]||"play",U=ns(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(D,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]}):t.jsxs("div",{className:z("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(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:x,disabled:l||C,className:z("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":v?`Stop ${d.name}`:`Run ${d.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:C||S?t.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?t.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(D,{name:b,className:"h-4 w-4"})})})}),w?t.jsx(Oe,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:k,className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(Oe,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Pt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ls,{}),u.map(j=>{const E=j.icon||"play",T=j.id===vt?"scan-2":on[E]||"play",U=ns(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(D,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]})},qn="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Pg="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Mg=i.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:o,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:z(a??qn,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:n})})]}):null}),Tg=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(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z(qn,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Pt,{align:"end",className:"w-64",children:[t.jsx(fd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ls,{}),r.map(d=>{const u=d.user,f=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(Xe,{className:"gap-2",disabled:l,onSelect:()=>{f||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(D,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:h})]}):null]}),f?t.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Fg=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:f,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(Rt,{open:a,onOpenChange:g=>{l(g),g&&c()},children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:z(qn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(D,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Pt,{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:u?.available?`Version ${u.version||""} is available for this instance.`:f?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(hd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Lg=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Kt,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(fs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ns,{children:[t.jsx(Re,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Re,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Og=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},Js=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Bg=i.lazy(()=>vs(()=>import("./SessionSwitcherDropdown-_k4P32o9.js"),__vite__mapDeps([115,24,3,4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),Ox=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Ft("ui.header.render");const l=se(O=>O.setSessionSwitcherOpen),c=se(O=>O.toggleSidebar),d=se(O=>O.isSidebarOpen),u=se(O=>O.activeMainTab),f=se(O=>O.setActiveMainTab),h=se(O=>O.shortcutOverrides);se(O=>O.timeFormatPreference),Gs();const x=ve(O=>!!O.newSessionDraft?.open),g=ve(O=>O.currentSessionId),m=_i(g??""),p=pd(g),y=i.useMemo(()=>{if(!p)return null;const O=p;return{title:p.title??null,directory:O.directory??null,created:p.time?.created??null,slug:O.slug??null,shareUrl:p.share?.url??null,parentId:p.parentID??null}},[p]),b=dt(Lr(O=>{if(!O.activeProjectId)return null;const re=O.projects.find(fe=>fe.id===O.activeProjectId);return re?{id:re.id,path:re.path,label:re.label}:null})),A=Bs(O=>O.homeDirectory),v=i.useMemo(()=>{if(!b)return null;const O=b.label?.trim();if(O)return O;const re=b.path.split(/[\\/]/).filter(Boolean);return re[re.length-1]??null},[b]),{isMobile:C}=ks(),{enabled:S}=Vr(),I=!!(S&&a&&o!==void 0),k=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[w,j]=i.useState(!1),E=null,T=i.useRef(null),[U,_]=i.useState(()=>typeof window>"u"?!1:Os()),$=i.useMemo(()=>Wi(),[]),K=md(),[P,B]=i.useState(!1),R=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:F,side:V}=$i(),G=i.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const re=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!re)return null;const fe=Number.parseInt(re[1],10),He=Number.parseInt(re[2],10);return Number.isNaN(fe)?null:fe===10?He:fe},[]);Me.useEffect(()=>{typeof window>"u"||_(Os())},[]);const M=se(O=>O.isSessionSwitcherOpen),ee=null,H=null,we=[],[ce,ae]=i.useState(!1),[xe,be]=i.useState(!1),[ge,Se]=i.useState("Local"),[je,ke]=i.useState(!0),[Ce,Z]=i.useState(!1),[ue,L]=i.useState(null),[Y,le]=i.useState(!1),[W,X]=i.useState(null),te=i.useMemo(()=>Og(ge),[ge]),ne=i.useCallback(async()=>{if(!(typeof window>"u"||!U))try{if(dn()){Se("Local"),ke(!0);return}ke(!1);const O=await Xd(),re=Zd(),fe=eu([tu(re),...O.hosts]);if(fe.id===su){Se("Local"),ke(!0);return}Se(nu(fe.label.trim()||"Instance"))}catch{Se("Local"),ke(!0)}},[U]);Me.useEffect(()=>(ne(),ru(()=>{ne()})),[ne]);const Ae=i.useCallback(async()=>{if(je){L(null),X(null);return}le(!0),X(null);try{const O=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await Mt(`/api/pi/update-check?${O.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const fe=await re.json();L({available:fe.available??!1,version:fe.version,currentVersion:fe.currentVersion??"unknown",body:fe.body,nextSuggestedCheckInSec:typeof fe.nextSuggestedCheckInSec=="number"?fe.nextSuggestedCheckInSec:void 0,packageManager:fe.packageManager,updateCommand:fe.updateCommand})}catch(O){L(null),X(O instanceof Error?O.message:"Failed to check remote instance updates")}finally{le(!1)}},[je]);i.useEffect(()=>{L(null),X(null),Z(!1)},[je,ge]),i.useEffect(()=>{if(!U||je)return;const O=3e3,re=3600*1e3;let fe=!1,He=null;const es=at=>{He=window.setTimeout(()=>{if(fe||typeof document<"u"&&document.visibilityState!=="visible"){es(re);return}Ae().finally(()=>{fe||es(re)})},at)};return es(O),()=>{fe=!0,He!==null&&window.clearTimeout(He)}},[Ae,je,ge,U]);const Ie=i.useCallback(()=>{if(ue?.available){Z(!0);return}Ae()},[Ae,ue?.available]),Pe=g?y??null:null,De=i.useRef(null),[Ge,de]=i.useState(0);i.useEffect(()=>{if(!g){De.current&&(De.current=null,de(He=>He+1));return}if(Pe){De.current={sessionId:g,session:Pe,expiresAt:Date.now()+2e3};return}const O=De.current;if(!O||O.sessionId!==g)return;const re=O.expiresAt-Date.now();if(re<=0){De.current=null,de(He=>He+1);return}const fe=window.setTimeout(()=>{De.current?.sessionId===g&&(De.current=null),de(He=>He+1)},re);return()=>{window.clearTimeout(fe)}},[g,Pe]);const ze=(()=>{if(Pe)return Pe;if(!g)return null;const O=De.current;return O&&O.sessionId===g&&O.expiresAt>Date.now()?O.session:null})(),Ne=i.useMemo(()=>{const O=typeof ze?.directory=="string"?ze.directory:"";return Js(O||"")},[ze?.directory]),Ye=ve(O=>O.newSessionDraft?.open?Js(O.newSessionDraft.directoryOverride??""):""),J=i.useMemo(()=>lg({sessionDirectory:Ne,draftDirectory:Ye,isNewSessionDraftOpen:x}),[Ye,x,Ne]),We=Bi(J||null),Ue=i.useMemo(()=>cg({activeProjectLabel:v,openDirectory:J,homeDirectory:A}),[v,A,J]),Ve=!!(Ue||We),gt=i.useMemo(()=>g?ds(ze):Ue??"PiChamber",[ze,g,Ue]),Wt=Oi(),ot=zi(),Je=ve(O=>O.updateSessionTitle),xt=ve(O=>O.archiveSessions),tt=ve(O=>O.deleteSessions),[st,St]=i.useState(!1),[Yt,ut]=i.useState(!1),qe=i.useRef(!1),[bt,jt]=i.useState(""),[Lt,ft]=i.useState(null),qt=i.useRef(null);i.useEffect(()=>{qe.current=!1,ut(!1),St(!1),jt(""),ft(null)},[g]);const Ot=i.useCallback(()=>{g&&(jt(ze?.title?.trim()||gt),St(!0))},[ze?.title,g,gt]),Ct=i.useCallback(async()=>{if(!g)return;const O=bt.trim();O&&O!==ze?.title?.trim()&&await Je(g,O),St(!1)},[ze?.title,g,bt,Je]);i.useEffect(()=>{if(!st)return;const O=re=>{const fe=re.target;(!fe||!qt.current?.contains(fe))&&Ct()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[st,Ct]);const Vt=i.useCallback(()=>{g&&cn(g).then(O=>{ie[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[g]),Bt=i.useCallback(async()=>{if(!g||!J){ie.error("Nothing to export");return}try{await ot.syncSession(g)}catch{ie.error("Failed to load the complete session history");return}const O=Ir(Wt.getState()).list;if(O.length===0){ie.error("Nothing to export");return}const re=Ha(O,ze?.title??null),fe=qa(ze?.title??null);await Ya(re,fe)||Wa(re,fe),ie.success("Session exported")},[ze?.title,g,Wt,J,ot]);m?.type==="busy"||m?.type;const is=i.useCallback(async()=>{if(!g||!Lt)return;const O=gd(),re=[g];for(let at=0;at<re.length;at+=1){const gs=re[at];for(const Ut of O)Ut.parentID===gs&&!re.includes(Ut.id)&&re.push(Ut.id)}const fe=Lt;if(ft(null),(fe==="archive"?await xt(re):await tt(re)).failedIds.length>0){ie.error(fe==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(fe==="archive"?"Session archived":"Session deleted")},[xt,g,tt,Lt]),pe=se(O=>O.isArchivePageOpen),_e=i.useMemo(()=>pe?{title:"Archive",subtitle:null}:null,[pe]),me=i.useMemo(()=>Js(J||b?.path||""),[b?.path,J]),Te=i.useMemo(()=>b?{id:b.id,path:b.path}:null,[b]),$e=i.useRef(null);i.useEffect(()=>{!Te||!me||($e.current={projectRef:Te,directory:me})},[me,Te]);const Ze=i.useMemo(()=>Te&&me?{projectRef:Te,directory:me}:$e.current,[me,Te]),Qt=i.useCallback(async O=>{},[]),nt=i.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const re=O.tagName;(re==="INPUT"||re==="TEXTAREA"||re==="SELECT"||O.isContentEditable)&&O.blur()},[]),Jt=i.useCallback(()=>{if(C){nt(),l(!M);return}c()},[nt,C,M,l,c]),kt=i.useCallback(()=>{nn("desktop_open_draft_mini_chat_window",{directory:Js(J||b?.path||""),projectId:b?.id??null,apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[b?.id,b?.path,J]),it=i.useCallback(()=>{if(x){kt();return}g&&nn("desktop_open_session_mini_chat_window",{sessionId:g,directory:Js(J||b?.path||""),apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[b?.path,g,kt,x,J]),Xt=qn,_t=Pg,ps=i.useMemo(()=>n?"sessions":I?r&&o?o:null:r?"git":u,[u,I,n,r,o]),Zt=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&M&&l(!1)},[M,n,e,s,r,l]),zt=i.useCallback(()=>{e?.()},[e]),ms=i.useCallback(()=>{s?.()},[s]),ht=i.useMemo(()=>U&&R&&!P?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!U||F?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[U,P,R,K,F]);Me.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ht)},[ht]);const As=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",oe=d?"0px":U&&F?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":S?"2.75rem":"2.5rem";Me.useEffect(()=>{if(!U||!R){B(!1);return}let O=!1;const re=async()=>{try{const He=await nn("desktop_is_window_fullscreen");O||B(He===!0)}catch{O||B(!1)}},fe=()=>{re()};return re(),window.addEventListener("pichamber:window-resized",fe),()=>{O=!0,window.removeEventListener("pichamber:window-resized",fe)}},[U,R]);const et=i.useMemo(()=>!U||!R||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[U,R,G]),pt=i.useMemo(()=>{if(!(U&&!F))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[U,F]),Nt=i.useCallback(()=>{if(typeof document>"u")return;const O=T.current?.getBoundingClientRect().height;O&&document.documentElement.style.setProperty("--oc-header-height",`${O}px`)},[]);Me.useEffect(()=>{if(typeof window>"u")return;Nt();const O=T.current;if(!O||typeof ResizeObserver>"u")return()=>{};let re=0;const fe=()=>{re||(re=requestAnimationFrame(()=>{re=0,Nt()}))},He=new ResizeObserver(fe);return He.observe(O),window.addEventListener("resize",fe),window.addEventListener("orientationchange",fe),()=>{re&&cancelAnimationFrame(re),He.disconnect(),window.removeEventListener("resize",fe),window.removeEventListener("orientationchange",fe)}},[Nt]),Me.useEffect(()=>{Nt()},[Nt,C,et]);const yt=i.useCallback(async O=>{const re=O.target;re.closest(".app-region-no-drag")||re.closest("button, a, input, select, textarea")||O.button===0&&U&&await xd()},[U]),wt=i.useMemo(()=>C?[{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"}]:[],[C]),gn=i.useCallback(O=>eo(sn(O,h)),[h]);Me.useEffect(()=>{!C&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&f("chat")},[u,C,f]);const xn=i.useMemo(()=>{const O=[];return U&&O.push({value:"instance",label:"Instance",icon:t.jsx(D,{name:"server",className:"h-3.5 w-3.5"})}),O},[U]);Me.useEffect(()=>{const O=re=>{if(ou(re)&&!re.shiftKey&&!re.altKey){const fe=parseInt(re.key,10);fe>=1&&fe<=wt.length&&(re.preventDefault(),C&&(nt(),Zt()),f(wt[fe-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[nt,Zt,C,f,wt]),Me.useEffect(()=>{const O=re=>{const fe=sn("toggle_services_menu",h);if(zo(re,fe)){re.preventDefault(),xe?be(!1):(be(!0),ne());return}const He=sn("cycle_services_tab",h);if(zo(re,He)){if(re.preventDefault(),xn.length===0)return;be(!0),ne();return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[h,xe,xn,ne]);const Ks=O=>{const re=u===O.id,fe=O.icon==="diff",He=fe?null:O.icon,es=O.id==="chat",at=Ut=>fe?t.jsx(Si,{size:Ut}):He?t.jsx(D,{name:He,className:`h-${Ut/4} w-${Ut/4}`}):null,gs=t.jsxs("button",{type:"button",onClick:()=>f(O.id),className:z("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",re?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",es&&!C&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":re,role:"tab",children:[C?at(20):t.jsxs(t.Fragment,{children:[at(16),t.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return t.jsx(i.Fragment,{children:gs},O.id)},Vn=t.jsxs(t.Fragment,{children:[t.jsx(hg,{directory:me,className:"mr-1"}),U?t.jsx(Fg,{isDesktopApp:U,currentInstanceLabel:ge,compactCurrentInstanceLabel:te,currentInstanceIsLocal:je,isDesktopServicesOpen:xe,setIsDesktopServicesOpen:be,refreshCurrentInstanceLabel:ne,shortcutLabel:gn,remoteUpdateInfo:ue,remoteUpdateChecking:Y,remoteUpdateError:W,onOpenRemoteUpdate:Ie}):null,t.jsx(Tg,{isMobile:C,githubAuthStatus:E,githubAccounts:we,githubAvatarUrl:ee,githubLogin:H,isSwitchingGitHubAccount:ce,handleGitHubAccountSwitch:Qt})]}),Qn=$&&(x||!!g),bn=()=>t.jsxs("div",{onMouseDown:yt,className:z("app-region-drag relative flex h-12 select-none items-center pr-3",et),style:pt,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:As}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:oe}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[_e?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:_e.title}),_e.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:_e.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Xt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Bg,{align:"start",children:t.jsx("button",{type:"button",className:Xt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[st?t.jsxs("form",{ref:qt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),Ct()},children:[t.jsx("input",{value:bt,onChange:O=>jt(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&St(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>St(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:x?"New session":gt}),Ve?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:[Ue?t.jsx("span",{className:"truncate",children:Ue}):null,We?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:We})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:g&&!x&&!st?t.jsxs(Rt,{open:Yt,onOpenChange:ut,onOpenChangeComplete:O=>{!O&&qe.current&&(qe.current=!1,Ot())},children:[t.jsx(Et,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(D,{name:"more",className:"size-4"})})}),t.jsxs(Pt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(Xe,{onClick:()=>{qe.current=!0},children:[t.jsx(D,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(Xe,{onClick:Vt,children:[t.jsx(D,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Ls,{}),t.jsxs(Xe,{onClick:()=>{Bt()},children:[t.jsx(D,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ls,{}),t.jsxs(Xe,{onClick:()=>ft("archive"),children:[t.jsx(D,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(Xe,{className:"text-destructive focus:text-destructive",onClick:()=>ft("delete"),children:[t.jsx(D,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),wt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:wt.map(O=>Ks(O))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ze?t.jsx(ki,{projectRef:Ze.projectRef,directory:Ze.directory,className:"mr-1"}):null,t.jsx(Mg,{visible:Qn,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:it,className:z(Xt,"mr-1"),Icon:"picture-in-picture-2"}),Vn,t.jsx(Gi,{visible:F&&V==="right",position:"right"})]})]})]}),Hs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[S&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:As}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:oe}})]}),!S&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:zt,className:z(_t,ps==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(D,{name:"layout-left",className:"h-5 w-5"})}):M?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(D,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Jt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(D,{name:"play-list-add",className:"h-5 w-5"})}),!e&&M&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!M||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!I&&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:wt.map(O=>{const re=u===O.id,fe=O.icon==="diff",He=fe?null:O.icon;return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{C&&(nt(),Zt()),f(O.id)},"aria-label":O.label,"aria-selected":re,role:"tab",className:z(_t,"relative rounded-lg",ps===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[fe?t.jsx(Si,{className:"h-5 w-5"}):He?t.jsx(D,{name:He,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.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(Oe,{children:t.jsx("p",{children:O.label})})]},O.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[I&&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:k.map(O=>{const re=r&&o===O.id;return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{C&&(nt(),Zt()),j(!1),a?.(O.id)},"aria-label":O.label,"aria-selected":re,role:"tab",className:z(_t,"relative rounded-lg",re&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:O.icon,className:"h-5 w-5"})})}),t.jsx(Oe,{children:t.jsx("p",{children:O.label})})]},O.id)})}),t.jsx(oh,{open:w,onOpenChange:j,currentSessionId:g,effectiveDirectory:J||null,isNewSessionDraftOpen:x})]}),Ze&&t.jsx(ki,{projectRef:Ze.projectRef,directory:Ze.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ms,className:z(_t,"relative",ps==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Oe,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Is=z("header-safe-area relative z-10 bg-background",C&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:T,className:Is,style:{"--padding-scale":"1"},children:C?Hs():bn()}),t.jsx(Lg,{action:Lt,onClose:()=>ft(null),sessionTitle:gt,onConfirm:()=>{is()}}),t.jsx(Sa,{open:Ce,onOpenChange:Z,info:ue,downloading:!1,downloaded:!1,progress:null,error:W,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ni="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",_g="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",Bx=()=>{const e=se(p=>p.isSidebarOpen),s=se(p=>p.toggleSidebar),n=se(p=>p.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=eo(sn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=$i(),{enabled:d}=Vr(),u=!e,f=l&&c==="left",h=l,x=u||f||h,g=f||h,m=i.useCallback(()=>{nn("desktop_show_app_menu").catch(p=>{console.warn("[titlebar] failed to open app menu",p)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const p=S=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(S)}px`)},y=S=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(S)}px`)};if(!g)return;const b=o.current,A=r.current;if(!b||!A){p(0),y(0);return}const v=()=>{const S=Math.max(b.getBoundingClientRect().width,b.scrollWidth);p(S),y(A.getBoundingClientRect().width)};if(v(),typeof ResizeObserver>"u")return;const C=new ResizeObserver(v);return C.observe(b),C.observe(A),()=>{C.disconnect()}},[g]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[f?t.jsx(Gi,{visible:!0,position:"left"}):null,h?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:m,"aria-label":"Open PiChamber menu",className:z(Ni,"shrink-0"),children:t.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:z(d?_g:Ni,"shrink-0"),children:t.jsx(D,{name:"layout-left",className:d?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Ai=200,zg="cubic-bezier(0.22, 1, 0.36, 1)",_x=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 d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),Ai);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${Ai}ms ${zg}`}},Ug=hs(()=>({statusById:new Map})),zx=()=>{qi(),Ki()},Ux=e=>{ve.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),se.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),qi(),he.getState().clearAll(),Bs.getState().resetForRuntimeSwitch(),bd.getState().resetForRuntimeSwitch(),yd.getState().resetForRuntimeSwitch(),wd(),vd.getState().resetForRuntimeSwitch(),Gt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),dt.getState().resetForRuntimeSwitch(),Sd.getState().resetForRuntimeSwitch(),Ug.setState({statusById:new Map}),jd(),Cd(),Mu.getState().reset(),iu.getState().resetForRuntimeSwitch(),Ti.getState().resetForRuntimeSwitch(e.runtimeKey),Dr.getState().resetForRuntimeSwitch(e.runtimeKey),Xs.getState().resetForRuntimeSwitch(e.runtimeKey),Wh.getState().resetForRuntimeSwitch(),lt.getState().resetForRuntimeSwitch(e.runtimeKey),au.getState().resetForRuntimeSwitch(e.runtimeKey),ve.getState().restoreForRuntimeSwitch(e.runtimeKey),se.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=se.getState();Or({sessionId:ve.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),Ki()};export{pn as $,Dx as A,Ex as B,Da as C,Lx as D,Fn as E,dx as F,ix as G,Ox as H,Mx as I,zx as J,Qu as K,bs as L,Pa as M,ux as N,rx as O,wx as P,Ff as Q,io as R,Um as S,Tx as T,Sa as U,bx as V,Tf as W,ka as X,eh as Y,Df as Z,Lf as _,Ra as a,ja as a0,mn as a1,rn as a2,Ef as a3,px as a4,jx as a5,Rf as a6,hx as a7,Pf as a8,Sx as a9,Nx as aa,kx as ab,Of as ac,vx as ad,Cx as ae,Ax as af,fx as ag,mx as ah,gx as ai,xx as aj,Vf as ak,yx as al,pf as am,Mf as an,mf as ao,Ea as b,Gr as c,th as d,xs as e,_x as f,ff as g,ax as h,Fx as i,sx as j,cx as k,ox as l,Ix as m,Rx as n,Bx as o,lx as p,Mn as q,Ux as r,nh as s,oh as t,nx as u,xm as v,pi as w,Zs as x,pm as y,Px as z};
|
|
54
|
+
`));await o.sendInput(de,`${Ye}\r`),Ne?(A(H,De,Ne,{locked:!0,autoOpened:!0}),h(H,Ne),ie.success("Opened action URL")):Ae?(A(H,De,null,{locked:!0}),ie.error("Invalid custom URL format")):A(H,De,null,{locked:!1,autoOpened:!1})}catch(ne){I(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X],ie.error(ne instanceof Error?ne.message:"Failed to run action")}finally{B.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,be,n,a,H,c,l,h,v,I,y,C,A,b,G?.id,o]),Se=i.useCallback(async W=>{const X=ns(H,W.id),te=v[X];if(!te)return;S(X,"stopping");const ne=Rg(o,te.sessionId,1e3);try{await o.sendInput(te.sessionId,"")}catch{}const Ae=await ne;if(he.getState().getDirectoryState(te.directory)?.tabs.find(De=>De.id===te.tabId)?.terminalSessionId===te.sessionId&&!Ae){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:te.sessionId})}catch{}else try{await o.close(te.sessionId)}catch{}b(te.directory,te.tabId,null)}I(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X]},[H,v,I,b,o,S]),je=i.useCallback(()=>{const W=we??xe[0];if(!W)return;const X=ns(H,W.id),te=v[X];if(te?.status!=="stopping"){if(te){Se(W);return}ge(W)}},[xe,H,ge,v,we,Se]),ke=i.useCallback((W,X=!1)=>{if(E(W.id),!X){ge(W);return}const te=ns(H,W.id),ne=v[te];if(ne?.status!=="stopping"){if(ne){Se(W);return}ge(W)}},[H,ge,v,Se]),Ce=i.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),Z=we??xe[0]??null,ue=Z?v[ns(H,Z.id)]:null,L=he(W=>ue?W.sessions.get(ue.directory)?.tabs.find(X=>X.id===ue.tabId)?.previewUrl??null:null),Y=!!((n||!a)&&G&&H),le=we??xe[0]??null;return{shouldRender:Y,isLoading:T,normalizedDirectory:H,resolvedSelected:le,displayActions:xe,projectActionRuns:v,selectedRunPreviewUrl:L,handlePrimaryClick:je,handleSelectAction:ke,openProjectActionsSettings:Ce,openContextPreview:h}}const ki=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:h,handlePrimaryClick:x,handleSelectAction:g,openProjectActionsSettings:m,openContextPreview:p}=Eg({projectRef:e,directory:s,allowMobile:o});if(!a||!d)return null;const y=d.icon||"play",b=d.id===vt?"scan-2":on[y]||"play",A=ns(c,d.id),v=f[A],C=v?.status==="stopping",S=v?.status==="waiting-for-preview",I=!!(v&&h),k=()=>{!v||!h||p(v.directory,h)},w=d.id===vt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||C,className:z("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:C||S?t.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?t.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(D,{name:b,className:"h-5 w-5"})})}),w?t.jsx(Oe,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),I?t.jsxs(Fe,{children:[t.jsx(Le,{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:k,children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(Oe,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Pt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ls,{}),u.map(j=>{const E=j.icon||"play",T=j.id===vt?"scan-2":on[E]||"play",U=ns(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(D,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]}):t.jsxs("div",{className:z("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(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:x,disabled:l||C,className:z("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":v?`Stop ${d.name}`:`Run ${d.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:C||S?t.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?t.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(D,{name:b,className:"h-4 w-4"})})})}),w?t.jsx(Oe,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:k,className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(Oe,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Pt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ls,{}),u.map(j=>{const E=j.icon||"play",T=j.id===vt?"scan-2":on[E]||"play",U=ns(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(D,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]})},qn="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Pg="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Mg=i.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:o,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:z(a??qn,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:n})})]}):null}),Tg=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(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z(qn,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Pt,{align:"end",className:"w-64",children:[t.jsx(fd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ls,{}),r.map(d=>{const u=d.user,f=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(Xe,{className:"gap-2",disabled:l,onSelect:()=>{f||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(D,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:h})]}):null]}),f?t.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Fg=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:f,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(Rt,{open:a,onOpenChange:g=>{l(g),g&&c()},children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:z(qn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(D,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Pt,{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:u?.available?`Version ${u.version||""} is available for this instance.`:f?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(hd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Lg=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Kt,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(fs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ns,{children:[t.jsx(Re,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Re,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Og=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},Js=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Bg=i.lazy(()=>vs(()=>import("./SessionSwitcherDropdown-v_8TaIZm.js"),__vite__mapDeps([115,24,3,4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),Ox=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Ft("ui.header.render");const l=se(O=>O.setSessionSwitcherOpen),c=se(O=>O.toggleSidebar),d=se(O=>O.isSidebarOpen),u=se(O=>O.activeMainTab),f=se(O=>O.setActiveMainTab),h=se(O=>O.shortcutOverrides);se(O=>O.timeFormatPreference),Gs();const x=ve(O=>!!O.newSessionDraft?.open),g=ve(O=>O.currentSessionId),m=_i(g??""),p=pd(g),y=i.useMemo(()=>{if(!p)return null;const O=p;return{title:p.title??null,directory:O.directory??null,created:p.time?.created??null,slug:O.slug??null,shareUrl:p.share?.url??null,parentId:p.parentID??null}},[p]),b=dt(Lr(O=>{if(!O.activeProjectId)return null;const re=O.projects.find(fe=>fe.id===O.activeProjectId);return re?{id:re.id,path:re.path,label:re.label}:null})),A=Bs(O=>O.homeDirectory),v=i.useMemo(()=>{if(!b)return null;const O=b.label?.trim();if(O)return O;const re=b.path.split(/[\\/]/).filter(Boolean);return re[re.length-1]??null},[b]),{isMobile:C}=ks(),{enabled:S}=Vr(),I=!!(S&&a&&o!==void 0),k=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[w,j]=i.useState(!1),E=null,T=i.useRef(null),[U,_]=i.useState(()=>typeof window>"u"?!1:Os()),$=i.useMemo(()=>Wi(),[]),K=md(),[P,B]=i.useState(!1),R=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:F,side:V}=$i(),G=i.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const re=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!re)return null;const fe=Number.parseInt(re[1],10),He=Number.parseInt(re[2],10);return Number.isNaN(fe)?null:fe===10?He:fe},[]);Me.useEffect(()=>{typeof window>"u"||_(Os())},[]);const M=se(O=>O.isSessionSwitcherOpen),ee=null,H=null,we=[],[ce,ae]=i.useState(!1),[xe,be]=i.useState(!1),[ge,Se]=i.useState("Local"),[je,ke]=i.useState(!0),[Ce,Z]=i.useState(!1),[ue,L]=i.useState(null),[Y,le]=i.useState(!1),[W,X]=i.useState(null),te=i.useMemo(()=>Og(ge),[ge]),ne=i.useCallback(async()=>{if(!(typeof window>"u"||!U))try{if(dn()){Se("Local"),ke(!0);return}ke(!1);const O=await Xd(),re=Zd(),fe=eu([tu(re),...O.hosts]);if(fe.id===su){Se("Local"),ke(!0);return}Se(nu(fe.label.trim()||"Instance"))}catch{Se("Local"),ke(!0)}},[U]);Me.useEffect(()=>(ne(),ru(()=>{ne()})),[ne]);const Ae=i.useCallback(async()=>{if(je){L(null),X(null);return}le(!0),X(null);try{const O=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await Mt(`/api/pi/update-check?${O.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const fe=await re.json();L({available:fe.available??!1,version:fe.version,currentVersion:fe.currentVersion??"unknown",body:fe.body,nextSuggestedCheckInSec:typeof fe.nextSuggestedCheckInSec=="number"?fe.nextSuggestedCheckInSec:void 0,packageManager:fe.packageManager,updateCommand:fe.updateCommand})}catch(O){L(null),X(O instanceof Error?O.message:"Failed to check remote instance updates")}finally{le(!1)}},[je]);i.useEffect(()=>{L(null),X(null),Z(!1)},[je,ge]),i.useEffect(()=>{if(!U||je)return;const O=3e3,re=3600*1e3;let fe=!1,He=null;const es=at=>{He=window.setTimeout(()=>{if(fe||typeof document<"u"&&document.visibilityState!=="visible"){es(re);return}Ae().finally(()=>{fe||es(re)})},at)};return es(O),()=>{fe=!0,He!==null&&window.clearTimeout(He)}},[Ae,je,ge,U]);const Ie=i.useCallback(()=>{if(ue?.available){Z(!0);return}Ae()},[Ae,ue?.available]),Pe=g?y??null:null,De=i.useRef(null),[Ge,de]=i.useState(0);i.useEffect(()=>{if(!g){De.current&&(De.current=null,de(He=>He+1));return}if(Pe){De.current={sessionId:g,session:Pe,expiresAt:Date.now()+2e3};return}const O=De.current;if(!O||O.sessionId!==g)return;const re=O.expiresAt-Date.now();if(re<=0){De.current=null,de(He=>He+1);return}const fe=window.setTimeout(()=>{De.current?.sessionId===g&&(De.current=null),de(He=>He+1)},re);return()=>{window.clearTimeout(fe)}},[g,Pe]);const ze=(()=>{if(Pe)return Pe;if(!g)return null;const O=De.current;return O&&O.sessionId===g&&O.expiresAt>Date.now()?O.session:null})(),Ne=i.useMemo(()=>{const O=typeof ze?.directory=="string"?ze.directory:"";return Js(O||"")},[ze?.directory]),Ye=ve(O=>O.newSessionDraft?.open?Js(O.newSessionDraft.directoryOverride??""):""),J=i.useMemo(()=>lg({sessionDirectory:Ne,draftDirectory:Ye,isNewSessionDraftOpen:x}),[Ye,x,Ne]),We=Bi(J||null),Ue=i.useMemo(()=>cg({activeProjectLabel:v,openDirectory:J,homeDirectory:A}),[v,A,J]),Ve=!!(Ue||We),gt=i.useMemo(()=>g?ds(ze):Ue??"PiChamber",[ze,g,Ue]),Wt=Oi(),ot=zi(),Je=ve(O=>O.updateSessionTitle),xt=ve(O=>O.archiveSessions),tt=ve(O=>O.deleteSessions),[st,St]=i.useState(!1),[Yt,ut]=i.useState(!1),qe=i.useRef(!1),[bt,jt]=i.useState(""),[Lt,ft]=i.useState(null),qt=i.useRef(null);i.useEffect(()=>{qe.current=!1,ut(!1),St(!1),jt(""),ft(null)},[g]);const Ot=i.useCallback(()=>{g&&(jt(ze?.title?.trim()||gt),St(!0))},[ze?.title,g,gt]),Ct=i.useCallback(async()=>{if(!g)return;const O=bt.trim();O&&O!==ze?.title?.trim()&&await Je(g,O),St(!1)},[ze?.title,g,bt,Je]);i.useEffect(()=>{if(!st)return;const O=re=>{const fe=re.target;(!fe||!qt.current?.contains(fe))&&Ct()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[st,Ct]);const Vt=i.useCallback(()=>{g&&cn(g).then(O=>{ie[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[g]),Bt=i.useCallback(async()=>{if(!g||!J){ie.error("Nothing to export");return}try{await ot.syncSession(g)}catch{ie.error("Failed to load the complete session history");return}const O=Ir(Wt.getState()).list;if(O.length===0){ie.error("Nothing to export");return}const re=Ha(O,ze?.title??null),fe=qa(ze?.title??null);await Ya(re,fe)||Wa(re,fe),ie.success("Session exported")},[ze?.title,g,Wt,J,ot]);m?.type==="busy"||m?.type;const is=i.useCallback(async()=>{if(!g||!Lt)return;const O=gd(),re=[g];for(let at=0;at<re.length;at+=1){const gs=re[at];for(const Ut of O)Ut.parentID===gs&&!re.includes(Ut.id)&&re.push(Ut.id)}const fe=Lt;if(ft(null),(fe==="archive"?await xt(re):await tt(re)).failedIds.length>0){ie.error(fe==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(fe==="archive"?"Session archived":"Session deleted")},[xt,g,tt,Lt]),pe=se(O=>O.isArchivePageOpen),_e=i.useMemo(()=>pe?{title:"Archive",subtitle:null}:null,[pe]),me=i.useMemo(()=>Js(J||b?.path||""),[b?.path,J]),Te=i.useMemo(()=>b?{id:b.id,path:b.path}:null,[b]),$e=i.useRef(null);i.useEffect(()=>{!Te||!me||($e.current={projectRef:Te,directory:me})},[me,Te]);const Ze=i.useMemo(()=>Te&&me?{projectRef:Te,directory:me}:$e.current,[me,Te]),Qt=i.useCallback(async O=>{},[]),nt=i.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const re=O.tagName;(re==="INPUT"||re==="TEXTAREA"||re==="SELECT"||O.isContentEditable)&&O.blur()},[]),Jt=i.useCallback(()=>{if(C){nt(),l(!M);return}c()},[nt,C,M,l,c]),kt=i.useCallback(()=>{nn("desktop_open_draft_mini_chat_window",{directory:Js(J||b?.path||""),projectId:b?.id??null,apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[b?.id,b?.path,J]),it=i.useCallback(()=>{if(x){kt();return}g&&nn("desktop_open_session_mini_chat_window",{sessionId:g,directory:Js(J||b?.path||""),apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[b?.path,g,kt,x,J]),Xt=qn,_t=Pg,ps=i.useMemo(()=>n?"sessions":I?r&&o?o:null:r?"git":u,[u,I,n,r,o]),Zt=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&M&&l(!1)},[M,n,e,s,r,l]),zt=i.useCallback(()=>{e?.()},[e]),ms=i.useCallback(()=>{s?.()},[s]),ht=i.useMemo(()=>U&&R&&!P?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!U||F?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[U,P,R,K,F]);Me.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ht)},[ht]);const As=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",oe=d?"0px":U&&F?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":S?"2.75rem":"2.5rem";Me.useEffect(()=>{if(!U||!R){B(!1);return}let O=!1;const re=async()=>{try{const He=await nn("desktop_is_window_fullscreen");O||B(He===!0)}catch{O||B(!1)}},fe=()=>{re()};return re(),window.addEventListener("pichamber:window-resized",fe),()=>{O=!0,window.removeEventListener("pichamber:window-resized",fe)}},[U,R]);const et=i.useMemo(()=>!U||!R||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[U,R,G]),pt=i.useMemo(()=>{if(!(U&&!F))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[U,F]),Nt=i.useCallback(()=>{if(typeof document>"u")return;const O=T.current?.getBoundingClientRect().height;O&&document.documentElement.style.setProperty("--oc-header-height",`${O}px`)},[]);Me.useEffect(()=>{if(typeof window>"u")return;Nt();const O=T.current;if(!O||typeof ResizeObserver>"u")return()=>{};let re=0;const fe=()=>{re||(re=requestAnimationFrame(()=>{re=0,Nt()}))},He=new ResizeObserver(fe);return He.observe(O),window.addEventListener("resize",fe),window.addEventListener("orientationchange",fe),()=>{re&&cancelAnimationFrame(re),He.disconnect(),window.removeEventListener("resize",fe),window.removeEventListener("orientationchange",fe)}},[Nt]),Me.useEffect(()=>{Nt()},[Nt,C,et]);const yt=i.useCallback(async O=>{const re=O.target;re.closest(".app-region-no-drag")||re.closest("button, a, input, select, textarea")||O.button===0&&U&&await xd()},[U]),wt=i.useMemo(()=>C?[{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"}]:[],[C]),gn=i.useCallback(O=>eo(sn(O,h)),[h]);Me.useEffect(()=>{!C&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&f("chat")},[u,C,f]);const xn=i.useMemo(()=>{const O=[];return U&&O.push({value:"instance",label:"Instance",icon:t.jsx(D,{name:"server",className:"h-3.5 w-3.5"})}),O},[U]);Me.useEffect(()=>{const O=re=>{if(ou(re)&&!re.shiftKey&&!re.altKey){const fe=parseInt(re.key,10);fe>=1&&fe<=wt.length&&(re.preventDefault(),C&&(nt(),Zt()),f(wt[fe-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[nt,Zt,C,f,wt]),Me.useEffect(()=>{const O=re=>{const fe=sn("toggle_services_menu",h);if(zo(re,fe)){re.preventDefault(),xe?be(!1):(be(!0),ne());return}const He=sn("cycle_services_tab",h);if(zo(re,He)){if(re.preventDefault(),xn.length===0)return;be(!0),ne();return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[h,xe,xn,ne]);const Ks=O=>{const re=u===O.id,fe=O.icon==="diff",He=fe?null:O.icon,es=O.id==="chat",at=Ut=>fe?t.jsx(Si,{size:Ut}):He?t.jsx(D,{name:He,className:`h-${Ut/4} w-${Ut/4}`}):null,gs=t.jsxs("button",{type:"button",onClick:()=>f(O.id),className:z("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",re?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",es&&!C&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":re,role:"tab",children:[C?at(20):t.jsxs(t.Fragment,{children:[at(16),t.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return t.jsx(i.Fragment,{children:gs},O.id)},Vn=t.jsxs(t.Fragment,{children:[t.jsx(hg,{directory:me,className:"mr-1"}),U?t.jsx(Fg,{isDesktopApp:U,currentInstanceLabel:ge,compactCurrentInstanceLabel:te,currentInstanceIsLocal:je,isDesktopServicesOpen:xe,setIsDesktopServicesOpen:be,refreshCurrentInstanceLabel:ne,shortcutLabel:gn,remoteUpdateInfo:ue,remoteUpdateChecking:Y,remoteUpdateError:W,onOpenRemoteUpdate:Ie}):null,t.jsx(Tg,{isMobile:C,githubAuthStatus:E,githubAccounts:we,githubAvatarUrl:ee,githubLogin:H,isSwitchingGitHubAccount:ce,handleGitHubAccountSwitch:Qt})]}),Qn=$&&(x||!!g),bn=()=>t.jsxs("div",{onMouseDown:yt,className:z("app-region-drag relative flex h-12 select-none items-center pr-3",et),style:pt,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:As}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:oe}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[_e?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:_e.title}),_e.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:_e.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Xt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Bg,{align:"start",children:t.jsx("button",{type:"button",className:Xt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[st?t.jsxs("form",{ref:qt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),Ct()},children:[t.jsx("input",{value:bt,onChange:O=>jt(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&St(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>St(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:x?"New session":gt}),Ve?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:[Ue?t.jsx("span",{className:"truncate",children:Ue}):null,We?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:We})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:g&&!x&&!st?t.jsxs(Rt,{open:Yt,onOpenChange:ut,onOpenChangeComplete:O=>{!O&&qe.current&&(qe.current=!1,Ot())},children:[t.jsx(Et,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(D,{name:"more",className:"size-4"})})}),t.jsxs(Pt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(Xe,{onClick:()=>{qe.current=!0},children:[t.jsx(D,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(Xe,{onClick:Vt,children:[t.jsx(D,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Ls,{}),t.jsxs(Xe,{onClick:()=>{Bt()},children:[t.jsx(D,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ls,{}),t.jsxs(Xe,{onClick:()=>ft("archive"),children:[t.jsx(D,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(Xe,{className:"text-destructive focus:text-destructive",onClick:()=>ft("delete"),children:[t.jsx(D,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),wt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:wt.map(O=>Ks(O))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ze?t.jsx(ki,{projectRef:Ze.projectRef,directory:Ze.directory,className:"mr-1"}):null,t.jsx(Mg,{visible:Qn,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:it,className:z(Xt,"mr-1"),Icon:"picture-in-picture-2"}),Vn,t.jsx(Gi,{visible:F&&V==="right",position:"right"})]})]})]}),Hs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[S&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:As}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:oe}})]}),!S&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:zt,className:z(_t,ps==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(D,{name:"layout-left",className:"h-5 w-5"})}):M?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(D,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Jt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(D,{name:"play-list-add",className:"h-5 w-5"})}),!e&&M&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!M||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!I&&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:wt.map(O=>{const re=u===O.id,fe=O.icon==="diff",He=fe?null:O.icon;return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{C&&(nt(),Zt()),f(O.id)},"aria-label":O.label,"aria-selected":re,role:"tab",className:z(_t,"relative rounded-lg",ps===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[fe?t.jsx(Si,{className:"h-5 w-5"}):He?t.jsx(D,{name:He,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.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(Oe,{children:t.jsx("p",{children:O.label})})]},O.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[I&&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:k.map(O=>{const re=r&&o===O.id;return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{C&&(nt(),Zt()),j(!1),a?.(O.id)},"aria-label":O.label,"aria-selected":re,role:"tab",className:z(_t,"relative rounded-lg",re&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:O.icon,className:"h-5 w-5"})})}),t.jsx(Oe,{children:t.jsx("p",{children:O.label})})]},O.id)})}),t.jsx(oh,{open:w,onOpenChange:j,currentSessionId:g,effectiveDirectory:J||null,isNewSessionDraftOpen:x})]}),Ze&&t.jsx(ki,{projectRef:Ze.projectRef,directory:Ze.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ms,className:z(_t,"relative",ps==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Oe,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Is=z("header-safe-area relative z-10 bg-background",C&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:T,className:Is,style:{"--padding-scale":"1"},children:C?Hs():bn()}),t.jsx(Lg,{action:Lt,onClose:()=>ft(null),sessionTitle:gt,onConfirm:()=>{is()}}),t.jsx(Sa,{open:Ce,onOpenChange:Z,info:ue,downloading:!1,downloaded:!1,progress:null,error:W,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ni="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",_g="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",Bx=()=>{const e=se(p=>p.isSidebarOpen),s=se(p=>p.toggleSidebar),n=se(p=>p.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=eo(sn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=$i(),{enabled:d}=Vr(),u=!e,f=l&&c==="left",h=l,x=u||f||h,g=f||h,m=i.useCallback(()=>{nn("desktop_show_app_menu").catch(p=>{console.warn("[titlebar] failed to open app menu",p)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const p=S=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(S)}px`)},y=S=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(S)}px`)};if(!g)return;const b=o.current,A=r.current;if(!b||!A){p(0),y(0);return}const v=()=>{const S=Math.max(b.getBoundingClientRect().width,b.scrollWidth);p(S),y(A.getBoundingClientRect().width)};if(v(),typeof ResizeObserver>"u")return;const C=new ResizeObserver(v);return C.observe(b),C.observe(A),()=>{C.disconnect()}},[g]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[f?t.jsx(Gi,{visible:!0,position:"left"}):null,h?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:m,"aria-label":"Open PiChamber menu",className:z(Ni,"shrink-0"),children:t.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:z(d?_g:Ni,"shrink-0"),children:t.jsx(D,{name:"layout-left",className:d?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Ai=200,zg="cubic-bezier(0.22, 1, 0.36, 1)",_x=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 d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),Ai);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${Ai}ms ${zg}`}},Ug=hs(()=>({statusById:new Map})),zx=()=>{qi(),Ki()},Ux=e=>{ve.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),se.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),qi(),he.getState().clearAll(),Bs.getState().resetForRuntimeSwitch(),bd.getState().resetForRuntimeSwitch(),yd.getState().resetForRuntimeSwitch(),wd(),vd.getState().resetForRuntimeSwitch(),Gt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),dt.getState().resetForRuntimeSwitch(),Sd.getState().resetForRuntimeSwitch(),Ug.setState({statusById:new Map}),jd(),Cd(),Mu.getState().reset(),iu.getState().resetForRuntimeSwitch(),Ti.getState().resetForRuntimeSwitch(e.runtimeKey),Dr.getState().resetForRuntimeSwitch(e.runtimeKey),Xs.getState().resetForRuntimeSwitch(e.runtimeKey),Wh.getState().resetForRuntimeSwitch(),lt.getState().resetForRuntimeSwitch(e.runtimeKey),au.getState().resetForRuntimeSwitch(e.runtimeKey),ve.getState().restoreForRuntimeSwitch(e.runtimeKey),se.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=se.getState();Or({sessionId:ve.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),Ki()};export{pn as $,Dx as A,Ex as B,Da as C,Lx as D,Fn as E,dx as F,ix as G,Ox as H,Mx as I,zx as J,Qu as K,bs as L,Pa as M,ux as N,rx as O,wx as P,Ff as Q,io as R,Um as S,Tx as T,Sa as U,bx as V,Tf as W,ka as X,eh as Y,Df as Z,Lf as _,Ra as a,ja as a0,mn as a1,rn as a2,Ef as a3,px as a4,jx as a5,Rf as a6,hx as a7,Pf as a8,Sx as a9,Nx as aa,kx as ab,Of as ac,vx as ad,Cx as ae,Ax as af,fx as ag,mx as ah,gx as ai,xx as aj,Vf as ak,yx as al,pf as am,Mf as an,mf as ao,Ea as b,Gr as c,th as d,xs as e,_x as f,ff as g,ax as h,Fx as i,sx as j,cx as k,ox as l,Ix as m,Rx as n,Bx as o,lx as p,Mn as q,Ux as r,nh as s,oh as t,nx as u,xm as v,pi as w,Zs as x,pm as y,Px as z};
|