@openchamber/web 1.8.0 → 1.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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-Byc0cUD3.js","assets/vendor--DbVqbJpV.css","assets/ToolOutputDialog-BoRPV5fw.js","assets/index-BvZjrpc0.js","assets/index-DGX6jOFq.css"])))=>i.map(i=>d[i]);
2
- import{t as ES,c as IS,F as _S,a as Me,j as s,R as PS,T as TS,P as RS,C as BS,A as OS,b as $S,L as LS,d as zS,S as HS,e as US,I as VS,s as Ts,f as WS,g as GS,i as qS,k as KS,l as QS,m as YS,n as JS,o as XS,r as ar,p as u,q as Fn,u as Gn,v as Br,w as Or,x as Dx,_ as gr,X as ZS,K as Ao,M as ov,N as av,y as ek,z as im,B as lm,D as od,E as tk,G as iv,H as hg,J as Ya,O as sk,Q as lv,U as nk,V as rk,W as ok,Y as cm,Z as gg,$ as Na,a0 as zs,a1 as ak,a2 as ik,a3 as De,a4 as lk,a5 as cv,a6 as br,a7 as ck,a8 as dk,a9 as uk,aa as xg,ab as dv,ac as uv,ad as fv,ae as fk,af as mk,ag as mv,ah as pv,ai as pk,aj as hk,ak as gk,al as bc,am as Ca,an as Fo,ao as dm,ap as Qn,aq as ps,ar as yg,as as na,at as Si,au as Zu,av as sn,aw as hv,ax as xk,ay as yk,az as Us,aA as ir,aB as Wa,aC as bk,aD as zc,aE as jd,aF as vk,aG as Mi,aH as bn,aI as Cr,aJ as ua,aK as fa,aL as Uo,aM as ti,aN as wf,aO as ra,aP as gv,aQ as ea,aR as hh,aS as ad,aT as jf,aU as wk,aV as ki,aW as Ga,aX as Sf,aY as um,aZ as tc,a_ as _r,a$ as jk,b0 as Sk,b1 as kk,b2 as Nk,b3 as Ck,b4 as Fa,b5 as Ak,b6 as ef,b7 as Fk,b8 as sc,b9 as so,ba as bg,bb as kf,bc as Ei,bd as Dk,be as Mk,bf as vg,bg as xv,bh as yv,bi as wg,bj as jg,bk as Oi,bl as Nn,bm as Sg,bn as kg,bo as Ng,bp as Cg,bq as bv,br as vv,bs as Ek,bt as Ik,bu as Nf,bv as _k,bw as Hc,bx as Ja,by as ca,bz as fm,bA as Pk,bB as oa,bC as Tk,bD as Rk,bE as Vo,bF as Bk,bG as Ii,bH as Ok,bI as $k,bJ as Lk,bK as zk,bL as Hk,bM as ja,bN as Uk,bO as So,bP as id,bQ as Vk,bR as Wk,bS as wv,bT as Xa,bU as Ag,bV as Tl,bW as gh,bX as jv,bY as Gk,bZ as Wo,b_ as qk,b$ as Kk,c0 as Sv,c1 as ep,c2 as Qk,c3 as Fg,c4 as Ni,c5 as kv,c6 as Yk,c7 as Jk,c8 as Nv,c9 as Xk,ca as Cv,cb as Zk,cc as e3,cd as t3,ce as Dg,cf as xh,cg as Mx,ch as $o,ci as Lo,cj as Go,ck as s3,cl as Ex,cm as Ix,cn as _x,co as mm,cp as nc,cq as n3,cr as r3,cs as ta,ct as o3,cu as fc,cv as Px,cw as a3,cx as i3,cy as tp,cz as l3,cA as c3,cB as d3,cC as Tx,cD as u3,cE as Av,cF as Fv,cG as f3,cH as Rx,cI as m3,cJ as p3,cK as h3,cL as g3,cM as ld,cN as Mg,cO as x3,cP as yh,cQ as yt,cR as Oc,cS as y3,cT as b3,cU as $i,cV as v3,cW as w3,cX as j3,cY as S3,cZ as k3,c_ as N3,c$ as C3,d0 as A3,d1 as Cf,d2 as Dv,d3 as Mv,d4 as Ev,d5 as Iv,d6 as _v,d7 as Pv,d8 as Tv,d9 as F3,da as Rv,db as Bv,dc as Rl,dd as Ov,de as $v,df as bh,dg as Li,dh as cd,di as Eg,dj as vh,dk as Ig,dl as D3,dm as _g,dn as M3,dp as Uc,dq as pm,dr as E3,ds as I3,dt as _3,du as P3,dv as T3,dw as R3,dx as B3,dy as O3,dz as $3,dA as L3,dB as z3,dC as H3,dD as U3,dE as V3,dF as Ci,dG as W3,dH as Ha,dI as G3,dJ as q3,dK as K3,dL as Q3,dM as Y3,dN as J3,dO as wh,dP as X3,dQ as Z3,dR as e5,dS as Af,dT as Bx,dU as Lv,dV as zv,dW as Hv,dX as Uv,dY as hm,dZ as t5,d_ as no,d$ as s5,e0 as n5,e1 as Ff,e2 as Vv,e3 as r5,e4 as o5,e5 as a5,e6 as i5,e7 as l5,e8 as c5,e9 as Wv,ea as jh,eb as d5,ec as u5,ed as f5,ee as m5,ef as p5,eg as h5,eh as g5,ei as x5,ej as y5,ek as b5,el as v5,em as w5,en as j5,eo as Pg,ep as S5,eq as k5,er as sp,es as Sh,et as N5,eu as C5,ev as A5,ew as kh,ex as Gv,ey as F5,ez as D5,eA as M5,eB as E5,eC as I5,eD as np,eE as Ox,eF as _5,eG as P5,eH as T5,eI as R5,eJ as B5}from"./vendor-.bun-Byc0cUD3.js";import{c as O5,l as $5,d as L5,a as z5,v as H5,g as U5,b as V5,e as W5,u as G5,f as q5,h as K5,i as Q5,j as Y5,k as J5,m as X5,r as Z5,n as eN,o as tN,p as sN,q as nN,s as rN,t as oN}from"./index-BvZjrpc0.js";const tn=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",$x=t=>{const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{try{return new URL(e.endsWith("/")?e:`${e}/`).origin}catch{return null}}},Ar=()=>{if(typeof window>"u")return!1;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=$x(t),n=$x(window.location.origin)||window.location.origin;return!!(e&&n&&e===n)},fr=()=>typeof window>"u"?!1:typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"&&window.__OPENCHAMBER_LOCAL_ORIGIN__.length>0?!0:tn(),ln=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,zi=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!ln()},gm=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Sd=async t=>{if(tn()&&Ar())try{const n=await window.__TAURI__?.dialog?.open?.({directory:!0,multiple:!1,title:"Select Working Directory"});return!n||typeof n!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:n}}catch(e){return console.warn("Failed to request directory access (tauri)",e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:t}},qv=async t=>({success:!0}),Kv=async t=>({success:!0}),Qv=async()=>{if(!tn()||!Ar())return null;try{return await window.__TAURI__?.core?.invoke?.("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates (tauri)",t),null}},Yv=async t=>{if(!tn()||!Ar())return!1;const e=window.__TAURI__;let n=null,r=0,o;try{return typeof t=="function"&&e?.event?.listen&&(n=await e.event.listen("openchamber:update-progress",a=>{const i=a?.payload;if(!i||typeof i!="object")return;const l=i,c=typeof l.event=="string"?l.event:null,d=l.data&&typeof l.data=="object"?l.data:null;if(c==="Started"){r=0,o=typeof d?.contentLength=="number"?d.contentLength:void 0,t({downloaded:r,total:o});return}if(c==="Progress"){const f=d?.downloaded,m=d?.total;typeof f=="number"&&(r=f),typeof m=="number"&&(o=m),t({downloaded:r,total:o});return}c==="Finished"&&t({downloaded:r,total:o})})),await e?.core?.invoke?.("desktop_download_and_install_update"),!0}catch(a){return console.warn("Failed to download update (tauri)",a),!1}finally{if(n)try{const a=n();a instanceof Promise&&await a}catch{}}},Jv=async()=>{if(!tn()||!Ar())return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_restart"),!0}catch(t){return console.warn("Failed to restart for update (tauri)",t),!1}},Xv=async(t,e)=>{if(!tn()||!Ar())return!1;const n=t?.trim();if(!n)return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_open_path",{path:n,app:typeof e=="string"&&e.trim().length>0?e.trim():void 0}),!0}catch(r){return console.warn("Failed to open path (tauri)",r),!1}},Zv=async(t,e)=>{if(!tn()||!Ar())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(t)?t.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await window.__TAURI__?.core?.invoke?.("desktop_get_installed_apps",{apps:n,force:e===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const a=o;return Array.isArray(a.apps)?{apps:a.apps.filter(l=>l&&typeof l=="object").map(l=>{const c=l;return{name:typeof c.name=="string"?c.name:"",iconDataUrl:typeof c.iconDataUrl=="string"?c.iconDataUrl:null}}).filter(l=>l.name.length>0),success:!0,hasCache:a.hasCache===!0,isCacheStale:a.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps (tauri)",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},aN=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Qv,downloadDesktopUpdate:Yv,fetchDesktopInstalledApps:Zv,getDesktopHomeDirectory:gm,isDesktopLocalOriginActive:Ar,isDesktopShell:fr,isTauriShell:tn,isVSCodeRuntime:ln,isWebRuntime:zi,openDesktopPath:Xv,requestDirectoryAccess:Sd,restartToApplyUpdate:Jv,startAccessingDirectory:qv,stopAccessingDirectory:Kv},Symbol.toStringTag,{value:"Module"}));function Z(...t){return ES(IS(t))}const _i=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),xm=t=>_i()&&tn()?t.metaKey:t.ctrlKey,aa=()=>_i()&&tn()?"⌘":"Ctrl",ew=(t,e)=>{const n=t??"",r=Math.max(16,e?.maxLength??45);if(n.length<=r)return n;const o=n.split("/");if(o.length<=1)return n;const a=o.pop()??"";if(!a)return n;const i=Math.max(0,r-(a.length+2));if(i<=0)return`…/${a}`;let l="";for(const c of o){if(!c)continue;const d=l?`${l}/${c}`:c;if(d.length>i)break;l=d}if(!l){const c=o[0]??"";l=c?c.slice(0,i):""}return l?`${l}…/${a}`:`…/${a}`},Df=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function ia(t,e){if(!t)return"";const n=Df(t);if(n==="/")return"/";const r=e?Df(e):void 0;if(r&&r!=="/"){if(n===r)return"~";if(n.startsWith(`${r}/`)){const o=n.slice(r.length+1);return o?`~/${o}`:"~"}}return n}function To(t,e){if(!t)return"/";const n=Df(t);if(!n||n==="/")return"/";const r=e?Df(e):void 0;return r&&r!=="/"&&n===r?"~":n.split("/").pop()||n||"/"}function ji(t,e){return e?t?t.toLowerCase().includes(e.toLowerCase())?!0:new _S([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(e).length>0:!1:!0}function Vc(t){const e=Me.c(6);let n,r;e[0]!==t?({delayDuration:r,...n}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);const o=r===void 0?0:r;let a;return e[3]!==o||e[4]!==n?(a=s.jsx($S,{"data-slot":"tooltip-provider",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Yt(t){const e=Me.c(6);let n,r;e[0]!==t?({delayDuration:r,...n}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);const o=r===void 0?0:r;let a;return e[3]!==o||e[4]!==n?(a=s.jsx(PS,{"data-slot":"tooltip",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Jt(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(TS,{"data-slot":"tooltip-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function Kt(t){const e=Me.c(13);let n,r,o,a;e[0]!==t?({className:r,sideOffset:a,children:n,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=a===void 0?0:a;let l;e[5]!==r?(l=Z("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",r),e[5]=r,e[6]=l):l=e[6];let c;e[7]===Symbol.for("react.memo_cache_sentinel")?(c=s.jsx(OS,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"}),e[7]=c):c=e[7];let d;return e[8]!==n||e[9]!==o||e[10]!==i||e[11]!==l?(d=s.jsx(RS,{children:s.jsxs(BS,{"data-slot":"tooltip-content",sideOffset:i,className:l,...o,children:[n,c]})}),e[8]=n,e[9]=o,e[10]=i,e[11]=l,e[12]=d):d=e[12],d}function Ys(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(WS,{"data-slot":"dropdown-menu",...n}),e[2]=n,e[3]=r):r=e[3],r}function Js(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(GS,{"data-slot":"dropdown-menu-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function Xs(t){const e=Me.c(14);let n,r,o,a;e[0]!==t?({className:n,sideOffset:a,style:o,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=a===void 0?4:a;let l;e[5]!==o?(l={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)",...o},e[5]=o,e[6]=l):l=e[6];let c;e[7]!==n?(c=Z("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border-2 border-border/60 p-1 shadow-none",n),e[7]=n,e[8]=c):c=e[8];let d;return e[9]!==r||e[10]!==i||e[11]!==l||e[12]!==c?(d=s.jsx(qS,{children:s.jsx(KS,{"data-slot":"dropdown-menu-content",sideOffset:i,style:l,className:c,...r})}),e[9]=r,e[10]=i,e[11]=l,e[12]=c,e[13]=d):d=e[13],d}function is(t){const e=Me.c(12);let n,r,o,a;e[0]!==t?({className:n,inset:r,variant:a,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=a===void 0?"default":a;let l;e[5]!==n?(l=Z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",n),e[5]=n,e[6]=l):l=e[6];let c;return e[7]!==r||e[8]!==o||e[9]!==l||e[10]!==i?(c=s.jsx(QS,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":i,className:l,...o}),e[7]=r,e[8]=o,e[9]=l,e[10]=i,e[11]=c):c=e[11],c}function Mf(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(zS,{"data-slot":"dropdown-menu-radio-group",...n}),e[2]=n,e[3]=r):r=e[3],r}function ym(t){const e=Me.c(11);let n,r,o;e[0]!==t?({className:r,children:n,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o):(n=e[1],r=e[2],o=e[3]);let a;e[4]!==r?(a=Z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[state=checked]:bg-interactive-selection data-[state=checked]:text-interactive-selection-foreground relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),e[4]=r,e[5]=a):a=e[5];let i;e[6]===Symbol.for("react.memo_cache_sentinel")?(i=s.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:s.jsx(VS,{children:s.jsx(Ts,{className:"size-3"})})}),e[6]=i):i=e[6];let l;return e[7]!==n||e[8]!==o||e[9]!==a?(l=s.jsxs(US,{"data-slot":"dropdown-menu-radio-item",className:a,...o,children:[i,n]}),e[7]=n,e[8]=o,e[9]=a,e[10]=l):l=e[10],l}function Zr(t){const e=Me.c(10);let n,r,o;e[0]!==t?({className:n,inset:r,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o):(n=e[1],r=e[2],o=e[3]);let a;e[4]!==n?(a=Z("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",n),e[4]=n,e[5]=a):a=e[5];let i;return e[6]!==r||e[7]!==o||e[8]!==a?(i=s.jsx(LS,{"data-slot":"dropdown-menu-label","data-inset":r,className:a,...o}),e[6]=r,e[7]=o,e[8]=a,e[9]=i):i=e[9],i}function Kn(t){const e=Me.c(8);let n,r;e[0]!==t?({className:n,...r}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);let o;e[3]!==n?(o=Z("bg-border -mx-1 my-0.5 h-px",n),e[3]=n,e[4]=o):o=e[4];let a;return e[5]!==r||e[6]!==o?(a=s.jsx(HS,{"data-slot":"dropdown-menu-separator",className:o,...r}),e[5]=r,e[6]=o,e[7]=a):a=e[7],a}function iN(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(YS,{"data-slot":"dropdown-menu-sub",...n}),e[2]=n,e[3]=r):r=e[3],r}function lN(t){const e=Me.c(13);let n,r,o,a;e[0]!==t?({className:r,inset:o,children:n,...a}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);let i;e[5]!==r?(i=Z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),e[5]=r,e[6]=i):i=e[6];let l;e[7]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(ar,{className:"ml-auto size-3.5"}),e[7]=l):l=e[7];let c;return e[8]!==n||e[9]!==o||e[10]!==a||e[11]!==i?(c=s.jsxs(JS,{"data-slot":"dropdown-menu-sub-trigger","data-inset":o,className:i,...a,children:[n,l]}),e[8]=n,e[9]=o,e[10]=a,e[11]=i,e[12]=c):c=e[12],c}function cN(t){const e=Me.c(9);let n,r;e[0]!==t?({className:n,...r}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);let o;e[3]===Symbol.for("react.memo_cache_sentinel")?(o={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},e[3]=o):o=e[3];let a;e[4]!==n?(a=Z("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border-2 border-border/60 p-1 shadow-none",n),e[4]=n,e[5]=a):a=e[5];let i;return e[6]!==r||e[7]!==a?(i=s.jsx(XS,{"data-slot":"dropdown-menu-sub-content",style:o,className:a,...r}),e[6]=r,e[7]=a,e[8]=i):i=e[8],i}function Gl(t){const e=Me.c(45),{tabs:n,value:r,onValueChange:o,className:a,isInteractive:i,animate:l,collapseLabelsOnSmall:c,collapseLabelsOnNarrow:d,size:f}=t,m=i===void 0?!0:i,p=l===void 0?!0:l,g=c===void 0?!1:c,y=d===void 0?!1:d,x=f===void 0?"default":f,h=u.useRef(null),v=u.useRef(null);let b;e[0]===Symbol.for("react.memo_cache_sentinel")?(b=new Map,e[0]=b):b=e[0];const w=u.useRef(b),[j,F]=u.useState(!1);let A;e[1]!==r?(A=()=>{const q=h.current,$=v.current,G=w.current.get(r);if(!q||!$||!G)return;const W=q.getBoundingClientRect(),J=G.getBoundingClientRect(),te=J.left-W.left,le=J.width;$.style.transform=`translateX(${te}px)`,$.style.width=`${le}px`},e[1]=r,e[2]=A):A=e[2];const C=A;let S;e[3]!==j||e[4]!==C?(S=()=>{C(),j||F(!0)},e[3]=j,e[4]=C,e[5]=S):S=e[5];let N;e[6]!==j||e[7]!==n.length||e[8]!==C||e[9]!==r?(N=[j,C,r,n.length],e[6]=j,e[7]=n.length,e[8]=C,e[9]=r,e[10]=N):N=e[10],u.useLayoutEffect(S,N);let k,D;e[11]!==C?(k=()=>{const q=h.current;if(!q)return;const $=new ResizeObserver(()=>C());return $.observe(q),()=>$.disconnect()},D=[C],e[11]=C,e[12]=k,e[13]=D):(k=e[12],D=e[13]),u.useEffect(k,D);let M;e[14]===Symbol.for("react.memo_cache_sentinel")?(M=(q,$)=>{q?w.current.set($,q):w.current.delete($)},e[14]=M):M=e[14];const E=M,_=y&&"@container/animated-tabs";let T;e[15]!==a||e[16]!==_?(T=Z("relative w-full",_,a),e[15]=a,e[16]=_,e[17]=T):T=e[17];const P=x==="sm"?"h-8 rounded-lg py-0.5 px-px gap-0.5":"h-10 rounded-lg py-0.5 px-px gap-0.5";let H;e[18]!==P?(H=Z("relative flex items-center overflow-hidden bg-[var(--surface-muted)]/50",P),e[18]=P,e[19]=H):H=e[19];const R=p&&j?"transition-[transform,width] duration-200 ease-out":null;let I;e[20]!==R?(I=Z("absolute top-0.5 bottom-0.5 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] shadow-none",R),e[20]=R,e[21]=I):I=e[21];let B;e[22]===Symbol.for("react.memo_cache_sentinel")?(B={width:0,transform:"translateX(0)"},e[22]=B):B=e[22];let z;e[23]!==I?(z=s.jsx("div",{ref:v,className:I,style:B}),e[23]=I,e[24]=z):z=e[24];let U;if(e[25]!==g||e[26]!==m||e[27]!==o||e[28]!==x||e[29]!==n||e[30]!==r){let q;e[32]!==g||e[33]!==m||e[34]!==o||e[35]!==x||e[36]!==r?(q=$=>{const G=r===$.value,W=$.icon;return s.jsxs("button",{ref:J=>E(J,$.value),type:"button",onClick:()=>{m&&o($.value)},className:Z("animated-tabs__button relative z-10 flex flex-1 items-center justify-center font-medium transition-colors duration-150",x==="sm"?"h-6 rounded-lg px-2.5 text-sm":"h-7 rounded-lg px-3 text-sm",g?"gap-0 sm:gap-1.5":"gap-1.5",G?"text-foreground":"text-muted-foreground hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":G,"aria-label":$.label,"aria-disabled":!m,tabIndex:m?0:-1,children:[W?s.jsx(W,{className:Z(x==="sm"?"h-3.5 w-3.5":"h-4 w-4",G?"text-foreground":"text-muted-foreground")}):null,s.jsx("span",{className:Z("animated-tabs__label truncate",g?"hidden sm:inline":null),children:$.label})]},$.value)},e[32]=g,e[33]=m,e[34]=o,e[35]=x,e[36]=r,e[37]=q):q=e[37],U=n.map(q),e[25]=g,e[26]=m,e[27]=o,e[28]=x,e[29]=n,e[30]=r,e[31]=U}else U=e[31];let K;e[38]!==H||e[39]!==z||e[40]!==U?(K=s.jsxs("div",{ref:h,className:H,children:[z,U]}),e[38]=H,e[39]=z,e[40]=U,e[41]=K):K=e[41];let V;return e[42]!==T||e[43]!==K?(V=s.jsx("div",{className:T,children:K}),e[42]=T,e[43]=K,e[44]=V):V=e[44],V}function Lx(t){const e=Me.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let c;e[5]!==a||e[6]!==i||e[7]!==l?(c={width:i,height:l,...a},e[5]=a,e[6]=i,e[7]=l,e[8]=c):c=e[8];let d;e[9]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"}),e[9]=d):d=e[9];let f;return e[10]!==n||e[11]!==r||e[12]!==c?(f=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:c,...r,children:d}),e[10]=n,e[11]=r,e[12]=c,e[13]=f):f=e[13],f}let rp=null,op=null;const Ef=()=>{const t=new Map;return{getItem:e=>t.get(e)??null,setItem:(e,n)=>{t.set(e,n)},removeItem:e=>{t.delete(e)},clear:()=>{t.clear()},key:e=>Array.from(t.keys())[e]??null,get length(){return t.size}}},dN=()=>{if(typeof window>"u"||!window.localStorage)return Ef();const t=window.localStorage,e=Ef();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const f=t.getItem(d);if(f!==null)return f}catch{r()}return e.getItem(d)},setItem:(d,f)=>{if(n)try{t.setItem(d,f),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,f)},removeItem:d=>{try{t.removeItem(d)}catch{r()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{r()}e.clear()},key:d=>{if(n)try{return t.key(d)}catch{r()}return e.key(d)},get length(){if(n)try{return t.length+e.length}catch{r()}return e.length}}},Wn=()=>(rp||(rp=dN()),rp),uN=()=>{if(typeof window>"u"||!window.sessionStorage)return Ef();const t=window.sessionStorage,e=Ef();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const f=t.getItem(d);if(f!==null)return f}catch{r()}return e.getItem(d)},setItem:(d,f)=>{if(n)try{t.setItem(d,f),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,f)},removeItem:d=>{try{t.removeItem(d)}catch{r()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{r()}e.clear()},key:d=>{if(n)try{return t.key(d)}catch{r()}return e.key(d)},get length(){if(n)try{return t.length+e.length}catch{r()}return e.length}}},fN=()=>(op||(op=uN()),op),Tg={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},mN={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function zx(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const ka={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},tf={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ka.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:tf.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ka.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:tf.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ka.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:tf.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ka.tool.inline})},vu={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Pa={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},wu=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,pN=t=>{if(!t||typeof t!="object")return!1;const e=t;return wu(e.completion,vu.completion)&&wu(e.error,vu.error)&&wu(e.question,vu.question)&&wu(e.subtask,vu.subtask)},tw=600,hN=360,gN=1400,vc=300,wc=400,ii=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},xN=t=>Number.isFinite(t)?Math.min(gN,Math.max(hN,Math.round(t))):tw,li=t=>t?{...t,touchedAt:Date.now()}:{isOpen:!1,expanded:!1,mode:null,targetPath:null,width:tw,touchedAt:Date.now()},ci=(t,e)=>{const n=Object.entries(t);if(n.length<=e)return t;n.sort((o,a)=>(a[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,a]of n.slice(0,e))r[o]=a;return r},Te=Fn()(Gn(Br((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:vc,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:wc,hasManuallyResizedRightSidebar:!1,rightSidebarTab:"git",contextPanelByDirectory:{},isBottomTerminalOpen:!1,isBottomTerminalExpanded:!1,bottomTerminalHeight:300,hasManuallyResizedBottomTerminal:!1,isNavRailExpanded:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,showTextJustificationActivity:!1,showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,messageLimit:200,toolCallExpansion:"collapsed",fontSize:100,terminalFontSize:13,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],hiddenModels:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"stacked",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Pa.completion},error:{...Pa.error},question:{...Pa.question},subtask:{...Pa.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,mermaidRenderingMode:"svg",showMobileSessionStatusBar:!0,isMobileSessionStatusBarCollapsed:!1,isExpandedInput:!1,shortcutOverrides:{},setTheme:n=>{t({theme:n}),e().applyTheme()},toggleSidebar:()=>{t(n=>{const r=!n.isSidebarOpen;return r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:vc}:{isSidebarOpen:r}})},setSidebarOpen:n=>{t(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==vc?{isSidebarOpen:n,sidebarWidth:vc}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:vc}:{isSidebarOpen:n})},setSidebarWidth:n=>{t({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(n=>{const r=!n.isRightSidebarOpen;return r&&!n.hasManuallyResizedRightSidebar?{isRightSidebarOpen:r,rightSidebarWidth:wc}:{isRightSidebarOpen:r}})},setRightSidebarOpen:n=>{t(r=>r.isRightSidebarOpen===n?n&&!r.hasManuallyResizedRightSidebar&&r.rightSidebarWidth!==wc?{isRightSidebarOpen:n,rightSidebarWidth:wc}:r:n&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:wc}:{isRightSidebarOpen:n})},setRightSidebarWidth:n=>{t({rightSidebarWidth:n,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:n=>{t({rightSidebarTab:n})},openContextDiff:(n,r)=>{const o=ii((n||"").trim()),a=(r||"").trim();!o||!a||(t(i=>{const l=i.contextPanelByDirectory[o],c=li(l),d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,mode:"diff",targetPath:a}};return{contextPanelByDirectory:ci(d,20)}}),e().setPendingDiffFile(a))},openContextFile:(n,r)=>{const o=ii((n||"").trim()),a=(r||"").trim();!o||!a||t(i=>{const l=i.contextPanelByDirectory[o],c=li(l),d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,mode:"file",targetPath:a}};return{contextPanelByDirectory:ci(d,20)}})},openContextOverview:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=li(a),l={...o.contextPanelByDirectory,[r]:{...i,isOpen:!0,mode:"context",targetPath:null}};return{contextPanelByDirectory:ci(l,20)}})},openContextPlan:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=li(a),l={...o.contextPanelByDirectory,[r]:{...i,isOpen:!0,mode:"plan",targetPath:null}};return{contextPanelByDirectory:ci(l,20)}})},closeContextPanel:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r];if(!a||!a.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...li(a),isOpen:!1}};return{contextPanelByDirectory:ci(i,20)}})},toggleContextPanelExpanded:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=li(a),l={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:ci(l,20)}})},setContextPanelWidth:(n,r)=>{const o=ii((n||"").trim());o&&t(a=>{const i=a.contextPanelByDirectory[o],l=li(i),c={...a.contextPanelByDirectory,[o]:{...l,width:xN(r)}};return{contextPanelByDirectory:ci(c,20)}})},toggleBottomTerminal:()=>{t(n=>{const r=!n.isBottomTerminalOpen;if(r&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalOpen:n=>{t(r=>{if(r.isBottomTerminalOpen===n){if(!n)return r;if(!r.hasManuallyResizedBottomTerminal&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return r.bottomTerminalHeight===o&&r.hasManuallyResizedBottomTerminal===!1?r:{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return r}if(n&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:n}})},setBottomTerminalExpanded:n=>{t({isBottomTerminalExpanded:n})},setBottomTerminalHeight:n=>{t({bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!0})},setNavRailExpanded:n=>{t({isNavRailExpanded:n})},toggleNavRail:()=>{t({isNavRailExpanded:!e().isNavRailExpanded})},setSessionSwitcherOpen:n=>{t({isSessionSwitcherOpen:n})},setMainTabGuard:n=>{e().mainTabGuard!==n&&t({mainTabGuard:n})},setActiveMainTab:n=>{const r=e().mainTabGuard;r&&!r(n)||t({activeMainTab:n})},setPendingDiffFile:n=>{t({pendingDiffFile:n})},navigateToDiff:n=>{const r=e().mainTabGuard;r&&!r("diff")||t({pendingDiffFile:n,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=e();return n&&t({pendingDiffFile:null}),n},setIsMobile:n=>{t({isMobile:n})},toggleCommandPalette:()=>{t(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{t({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{t(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{t({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{t({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{t({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{t({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{t({isSessionCreateDialogOpen:n})},setSettingsDialogOpen:n=>{t(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:n=>{t({isModelSelectorOpen:n})},setSidebarSection:n=>{t({sidebarSection:n})},setSettingsPage:n=>{t({settingsPage:n})},setSettingsProjectsSelectedId:n=>{t({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{t({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{t({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{t({showReasoningTraces:n})},setShowTextJustificationActivity:n=>{t({showTextJustificationActivity:n})},setShowDeletionDialog:n=>{t({showDeletionDialog:n})},setAutoDeleteEnabled:n=>{t({autoDeleteEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));t({autoDeleteAfterDays:r})},setAutoDeleteLastRunAt:n=>{t({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));t({messageLimit:r})},setToolCallExpansion:n=>{t({toolCallExpansion:n})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));t({fontSize:r}),e().applyTypography()},setTerminalFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(52,r));t({terminalFontSize:o})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));t({padding:r}),e().applyPadding()},setCornerRadius:n=>{t({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=e(),r=document.documentElement,o=n/100,a=Object.entries(Tg);if(o===1){for(const[i]of a)r.style.removeProperty(zx(i));return}for(const[i,l]of a){const c=parseFloat(l);Number.isFinite(c)&&r.style.setProperty(zx(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:n}=e(),r=document.documentElement,o=n/100;if(o===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);r.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{t({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},setDiffWrapLines:n=>{t({diffWrapLines:n})},setDiffViewMode:n=>{t({diffViewMode:n})},setInputBarOffset:n=>{t({inputBarOffset:n})},setKeyboardOpen:n=>{t({isKeyboardOpen:n})},toggleFavoriteModel:(n,r)=>{t(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},toggleHiddenModel:(n,r)=>{t(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=e();return o.some(a=>a.providerID===n&&a.modelID===r)},hideAllModels:(n,r)=>{t(o=>{const a=o.hiddenModels.filter(l=>l.providerID!==n);return{hiddenModels:[...r.filter(l=>typeof l=="string"&&l.length>0).map(l=>({providerID:n,modelID:l})),...a]}})},showAllModels:n=>{t(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=e();return o.some(a=>a.providerID===n&&a.modelID===r)},addRecentModel:(n,r)=>{t(o=>{const a=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...a].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&t(o=>{if(o.recentAgents.includes(r))return o;const a=o.recentAgents;return{recentAgents:[r,...a].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const a=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!a||!i)return;const l=`${a}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";t(d=>{const f=d.recentEfforts[l]??[];if(f.includes(c))return d;const m=f;return{recentEfforts:{...d.recentEfforts,[l]:[c,...m].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(n=>{const r={};return n.isBottomTerminalOpen&&!n.hasManuallyResizedBottomTerminal&&(r.bottomTerminalHeight=Math.floor(window.innerHeight*.32)),r})},applyTheme:()=>{const{theme:n}=e(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{t(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:n=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:n=>{t({isTimelineDialogOpen:n})},setImagePreviewOpen:n=>{t({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{t({nativeNotificationsEnabled:n})},setNotificationMode:n=>{t({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{t({showTerminalQuickKeysOnDesktop:n})},setNotifyOnSubtasks:n=>{t({notifyOnSubtasks:n})},setNotifyOnCompletion:n=>{t({notifyOnCompletion:n})},setNotifyOnError:n=>{t({notifyOnError:n})},setNotifyOnQuestion:n=>{t({notifyOnQuestion:n})},setNotificationTemplates:n=>{t({notificationTemplates:n})},setSummarizeLastMessage:n=>{t({summarizeLastMessage:n})},setSummaryThreshold:n=>{t({summaryThreshold:n})},setSummaryLength:n=>{t({summaryLength:n})},setMaxLastMessageLength:n=>{t({maxLastMessageLength:n})},setPersistChatDraft:n=>{t({persistChatDraft:n})},setMermaidRenderingMode:n=>{t({mermaidRenderingMode:n})},setShowMobileSessionStatusBar:n=>{t({showMobileSessionStatusBar:n})},setIsMobileSessionStatusBarCollapsed:n=>{t({isMobileSessionStatusBarCollapsed:n})},viewPagerPage:"center",setViewPagerPage:n=>{t({viewPagerPage:n}),t(n==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:n==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(n,r)=>{t(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{t(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{t({shortcutOverrides:{}})},toggleExpandedInput:()=>{t(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{t({isExpandedInput:n})}}),{name:"ui-store",storage:Or(()=>Wn()),version:5,migrate:(t,e)=>{if(!t||typeof t!="object")return t;const n=t;if(e<1&&pN(n.notificationTemplates)&&(n.notificationTemplates={completion:{...Pa.completion},error:{...Pa.error},question:{...Pa.question},subtask:{...Pa.subtask}}),e<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,a=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof a=="number"&&!r.has(a)&&(n.messageLimit=a),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if((typeof n.rightSidebarTab!="string"||n.rightSidebarTab!=="git"&&n.rightSidebarTab!=="files")&&(n.rightSidebarTab="git"),(!n.contextPanelByDirectory||typeof n.contextPanelByDirectory!="object")&&(n.contextPanelByDirectory={}),e<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[a,i]of Object.entries(r))typeof a=="string"&&typeof i=="string"&&(o[a]=i);n.shortcutOverrides=o}return n},partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isRightSidebarOpen:t.isRightSidebarOpen,rightSidebarWidth:t.rightSidebarWidth,rightSidebarTab:t.rightSidebarTab,contextPanelByDirectory:t.contextPanelByDirectory,isBottomTerminalOpen:t.isBottomTerminalOpen,isBottomTerminalExpanded:t.isBottomTerminalExpanded,bottomTerminalHeight:t.bottomTerminalHeight,isNavRailExpanded:t.isNavRailExpanded,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,settingsPage:t.settingsPage,settingsHasOpenedOnce:t.settingsHasOpenedOnce,settingsProjectsSelectedId:t.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:t.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,showReasoningTraces:t.showReasoningTraces,showTextJustificationActivity:t.showTextJustificationActivity,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,toolCallExpansion:t.toolCallExpansion,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,persistChatDraft:t.persistChatDraft,mermaidRenderingMode:t.mermaidRenderingMode,showMobileSessionStatusBar:t.showMobileSessionStatusBar,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,shortcutOverrides:t.shortcutOverrides})}),{name:"ui-store"})),yN="/api",bN=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,vN=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(bN.test(e)||typeof window>"u")return e;const n=window.location?.href||window.location?.origin;if(!n)return e;try{return new URL(e,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),e}},wN=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_DESKTOP_SERVER__,e=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!e)return null;const n=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return n?`${n}/api`:null},ju=t=>t.replace(/\\/g,"/"),ap=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class jN{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;globalSseQueue=[];globalSseBuffer=[];globalSseCoalesced=new Map;globalSseFlushTimer=null;globalSseLastFlushAt=0;constructor(e=yN){const r=wN()||e;this.baseUrl=vN(r),this.client=Dx({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}getScopedApiClient(e){const n=this.normalizeCandidatePath(e)??e,r=n||"",o=this.scopedClients.get(r);if(o)return o;const a=Dx({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,a),a}normalizeCandidatePath(e){if(typeof e!="string")return null;const n=e.trim();if(!n)return null;const r=n.replace(/\\/g,"/");return(r.length>1?r.replace(/\/+$/,""):r)||null}deriveHomeDirectory(e){const n=e.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const a=n[1],l=e.slice(a.length+(e.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const r=e.startsWith("/"),o=e.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(e){this.currentDirectory=e}getDirectory(){return this.currentDirectory}async withDirectory(e,n){const r=async()=>{if(e==null)return n();const a=this.currentDirectory;this.currentDirectory=e;try{return await n()}finally{this.currentDirectory=a}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const e=new Set,n=o=>{const a=this.normalizeCandidatePath(o);a&&e.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(n(a.directory),n(a.worktree),n(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!e.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!e.size)try{(await this.listSessions()).forEach(a=>n(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!e.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!e.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(e);return this.deriveHomeDirectory(r)}async probeDirectory(e){const n=this.normalizeCandidatePath(e);if(!n)return!1;try{const o=(await this.client.path.get({directory:n})).data,a=typeof o?.directory=="string"?o.directory:null;return!!(a&&a.trim().length>0)}catch{return!1}}async listSessions(){const e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data:[]}async createSession(e){const n=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:e?.parentID,title:e?.title});if(!n.data)throw new Error("Failed to create session");return n.data}async getSession(e){const n=await this.client.session.get({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!n.data)throw new Error("Session not found");return n.data}async deleteSession(e){return(await this.client.session.delete({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(e,n){const r=await this.client.session.update({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},title:n});if(!r.data)throw new Error("Failed to update session");return r.data}async getSessionMessages(e,n){return(await this.client.session.messages({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof n=="number"?{limit:n}:{}})).data||[]}async getSessionTodos(e){try{const n=this.baseUrl.replace(/\/$/,""),r=new URL(`${n}/session/${encodeURIComponent(e)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&r.searchParams.set("directory",this.currentDirectory);const o=await fetch(r.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(e){if(!e)return!1;const n=e.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(e){if(!e)return!1;const n=e.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(e){try{const n=(await gr(async()=>{const{default:m}=await import("./vendor-.bun-Byc0cUD3.js").then(p=>p.h);return{default:m}},__vite__mapDeps([0,1]))).default,r=e.url.indexOf(",");if(r===-1)return e;const o=e.url.substring(r+1),a=atob(o),i=new Uint8Array(a.length);for(let m=0;m<a.length;m++)i[m]=a.charCodeAt(m);const l=new Blob([i],{type:e.mime}),c=await n({blob:l,toType:"image/jpeg",quality:.9}),d=await new Promise((m,p)=>{const g=new FileReader;g.onload=()=>m(g.result),g.onerror=p,g.readAsDataURL(c)});let f=e.filename;return f&&(f=f.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:f,url:d}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),e}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let n=e.url;if(e.url.startsWith("data:")){const r=e.url.indexOf(",");if(r!==-1){const o=e.url.substring(5,r),a=e.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:e.filename,url:n}}async toNormalizedFilePartInput(e){const n=await this.normalizeFilePart(e);return{...e.id?{id:e.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(e){const n=Date.now(),r=e.messageId??`temp_${n}_${Math.random().toString(36).substring(2,9)}`,o=[];if(e.prefaceText&&e.prefaceText.trim()&&o.push({type:"text",text:e.prefaceText,synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()){const c={type:"text",text:e.text};o.push(c)}if(e.files&&e.files.length>0)for(const c of e.files){const d=await this.toNormalizedFilePartInput(c);o.push(d)}if(e.additionalParts&&e.additionalParts.length>0){for(const c of e.additionalParts)if(c.text&&c.text.trim()&&o.push({type:"text",text:c.text,...c.synthetic?{synthetic:!0}:{}}),c.files&&c.files.length>0)for(const d of c.files){const f=await this.toNormalizedFilePartInput(d);o.push(f)}}if(e.agentMentions&&e.agentMentions.length>0)for(const c of e.agentMentions)c?.name&&o.push({type:"agent",name:c.name,...c.source?{source:c.source}:{}});if(o.length===0)throw new Error("Message must have at least one part (text or file)");const a=this.baseUrl.replace(/\/+$/,"");let i;try{i=new URL(`${a}/session/${encodeURIComponent(e.id)}/prompt_async`),this.currentDirectory&&i.searchParams.set("directory",this.currentDirectory)}catch(c){throw console.error("[git-generation][browser] failed to build prompt_async URL",{baseUrl:this.baseUrl,normalizedBase:a,sessionId:e.id,directory:this.currentDirectory,message:c instanceof Error?c.message:String(c),error:c}),c}e.format&&console.info("[git-generation][browser] send structured message",{sessionId:e.id,providerID:e.providerID,modelID:e.modelID,agent:e.agent,variant:e.variant,directory:this.currentDirectory,baseUrl:this.baseUrl,formatType:e.format.type});let l;try{l=await fetch(i.toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,...e.format?{format:e.format}:{},parts:o})})}catch(c){throw console.error("[git-generation][browser] prompt_async request failed before response",{sessionId:e.id,url:i.toString(),directory:this.currentDirectory,hasFormat:!!e.format,message:c instanceof Error?c.message:String(c),error:c}),c}if(!l.ok){let c="";try{c=await l.text()}catch{}const d=c&&c.trim().length>0?`: ${c.trim()}`:"";throw new Error(`Failed to send message (${l.status})${d}`)}return r}async sendCommand(e){const n=Date.now(),r=e.messageId??`temp_${n}_${Math.random().toString(36).substring(2,9)}`,o=[];if(e.files&&e.files.length>0)for(const d of e.files)o.push(await this.toNormalizedFilePartInput(d));const a=this.baseUrl.replace(/\/+$/,""),i=new URL(`${a}/session/${encodeURIComponent(e.id)}/command`);this.currentDirectory&&i.searchParams.set("directory",this.currentDirectory);const l={command:e.command,arguments:e.arguments??"",model:`${e.providerID}/${e.modelID}`,...e.agent?{agent:e.agent}:{},...e.variant?{variant:e.variant}:{},...o.length>0?{parts:o}:{},...e.messageId?{messageID:e.messageId}:{}},c=await fetch(i.toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(l)});if(!c.ok){let d="";try{d=await c.text()}catch{}const f=d&&d.trim().length>0?`: ${d.trim()}`:"";throw new Error(`Failed to run command (${c.status})${f}`)}return r}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(e,n,r){const o=await this.client.session.revert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:n,partID:r});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(e){const n=await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!n.data)throw new Error("Failed to unrevert session");return n.data}async forkSession(e,n){const r=await this.client.session.fork({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:n});if(!r.data)throw new Error("Failed to fork session");return r.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(e){try{const n=this.baseUrl.replace(/\/$/,""),r=new URL(`${n}/session/status`),o=typeof e=="string"?e.trim():"";o.length>0&&r.searchParams.set("directory",o);const a=await fetch(r.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async getWebServerSessionActivity(){try{const e=await fetch("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const n=await e.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async listToolIds(e){try{const n=typeof e?.directory=="string"?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(e,n,r){return(await this.client.permission.reply({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:n,...r?.message?{message:r.message}:{}})).data||!1}async listPendingPermissions(e){const n=[],r=async c=>{try{const d=typeof c=="string"?c.trim():"";return(await this.client.permission.list(d?{directory:d}:void 0)).data||[]}catch{return[]}};n.push(r(null));const o=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&o.add(d)}for(const c of o)n.push(r(c));const a=await Promise.all(n),i=[],l=new Set;for(const c of a)for(const d of c){if(!d||typeof d!="object")continue;const f=d.id;typeof f!="string"||f.length===0||l.has(f)||(l.add(f),i.push(d))}return i}async replyToQuestion(e,n){const r=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n];return(await this.client.question.reply({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:r})).data||!1}async rejectQuestion(e){return(await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(e){const n=[],r=async c=>{try{const d=typeof c=="string"?c.trim():"";return(await this.client.question.list(d?{directory:d}:void 0)).data||[]}catch{return[]}};n.push(r(null));const o=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&o.add(d)}for(const c of o)n.push(r(c));const a=await Promise.all(n),i=[],l=new Set;for(const c of a)for(const d of c){if(!d||typeof d!="object")continue;const f=d.id;typeof f!="string"||f.length===0||l.has(f)||(l.add(f),i.push(d))}return i}async getConfig(){const e=await this.client.config.get();if(!e.data)throw new Error("Failed to get config");return e.data}async updateConfig(e){const n=`${this.baseUrl}/config`,r=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const a=await r.text();throw console.error("[OpencodeClient] Failed to update config:",r.status,a),new Error(`Failed to update config: ${r.status} ${r.statusText}`)}return await r.json()}async updateConfigPartial(e){const n=await this.getConfig(),r=e(n);return await this.updateConfig(r)}async getProviders(){const e=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!e.data)throw new Error("Failed to get providers");return e.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(e){if(!e)return null;const n=e.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-Byc0cUD3.js","assets/vendor--DbVqbJpV.css","assets/ToolOutputDialog-DORFnwJC.js","assets/index-BcefsbYU.js","assets/index-DGX6jOFq.css"])))=>i.map(i=>d[i]);
2
+ import{t as ES,c as IS,F as _S,a as Me,j as s,R as PS,T as TS,P as RS,C as BS,A as OS,b as $S,L as LS,d as zS,S as HS,e as US,I as VS,s as Ts,f as WS,g as GS,i as qS,k as KS,l as QS,m as YS,n as JS,o as XS,r as ar,p as u,q as Fn,u as Gn,v as Br,w as Or,x as Dx,_ as gr,X as ZS,K as Ao,M as ov,N as av,y as ek,z as im,B as lm,D as od,E as tk,G as iv,H as hg,J as Ya,O as sk,Q as lv,U as nk,V as rk,W as ok,Y as cm,Z as gg,$ as Na,a0 as zs,a1 as ak,a2 as ik,a3 as De,a4 as lk,a5 as cv,a6 as br,a7 as ck,a8 as dk,a9 as uk,aa as xg,ab as dv,ac as uv,ad as fv,ae as fk,af as mk,ag as mv,ah as pv,ai as pk,aj as hk,ak as gk,al as bc,am as Ca,an as Fo,ao as dm,ap as Qn,aq as ps,ar as yg,as as na,at as Si,au as Zu,av as sn,aw as hv,ax as xk,ay as yk,az as Us,aA as ir,aB as Wa,aC as bk,aD as zc,aE as jd,aF as vk,aG as Mi,aH as bn,aI as Cr,aJ as ua,aK as fa,aL as Uo,aM as ti,aN as wf,aO as ra,aP as gv,aQ as ea,aR as hh,aS as ad,aT as jf,aU as wk,aV as ki,aW as Ga,aX as Sf,aY as um,aZ as tc,a_ as _r,a$ as jk,b0 as Sk,b1 as kk,b2 as Nk,b3 as Ck,b4 as Fa,b5 as Ak,b6 as ef,b7 as Fk,b8 as sc,b9 as so,ba as bg,bb as kf,bc as Ei,bd as Dk,be as Mk,bf as vg,bg as xv,bh as yv,bi as wg,bj as jg,bk as Oi,bl as Nn,bm as Sg,bn as kg,bo as Ng,bp as Cg,bq as bv,br as vv,bs as Ek,bt as Ik,bu as Nf,bv as _k,bw as Hc,bx as Ja,by as ca,bz as fm,bA as Pk,bB as oa,bC as Tk,bD as Rk,bE as Vo,bF as Bk,bG as Ii,bH as Ok,bI as $k,bJ as Lk,bK as zk,bL as Hk,bM as ja,bN as Uk,bO as So,bP as id,bQ as Vk,bR as Wk,bS as wv,bT as Xa,bU as Ag,bV as Tl,bW as gh,bX as jv,bY as Gk,bZ as Wo,b_ as qk,b$ as Kk,c0 as Sv,c1 as ep,c2 as Qk,c3 as Fg,c4 as Ni,c5 as kv,c6 as Yk,c7 as Jk,c8 as Nv,c9 as Xk,ca as Cv,cb as Zk,cc as e3,cd as t3,ce as Dg,cf as xh,cg as Mx,ch as $o,ci as Lo,cj as Go,ck as s3,cl as Ex,cm as Ix,cn as _x,co as mm,cp as nc,cq as n3,cr as r3,cs as ta,ct as o3,cu as fc,cv as Px,cw as a3,cx as i3,cy as tp,cz as l3,cA as c3,cB as d3,cC as Tx,cD as u3,cE as Av,cF as Fv,cG as f3,cH as Rx,cI as m3,cJ as p3,cK as h3,cL as g3,cM as ld,cN as Mg,cO as x3,cP as yh,cQ as yt,cR as Oc,cS as y3,cT as b3,cU as $i,cV as v3,cW as w3,cX as j3,cY as S3,cZ as k3,c_ as N3,c$ as C3,d0 as A3,d1 as Cf,d2 as Dv,d3 as Mv,d4 as Ev,d5 as Iv,d6 as _v,d7 as Pv,d8 as Tv,d9 as F3,da as Rv,db as Bv,dc as Rl,dd as Ov,de as $v,df as bh,dg as Li,dh as cd,di as Eg,dj as vh,dk as Ig,dl as D3,dm as _g,dn as M3,dp as Uc,dq as pm,dr as E3,ds as I3,dt as _3,du as P3,dv as T3,dw as R3,dx as B3,dy as O3,dz as $3,dA as L3,dB as z3,dC as H3,dD as U3,dE as V3,dF as Ci,dG as W3,dH as Ha,dI as G3,dJ as q3,dK as K3,dL as Q3,dM as Y3,dN as J3,dO as wh,dP as X3,dQ as Z3,dR as e5,dS as Af,dT as Bx,dU as Lv,dV as zv,dW as Hv,dX as Uv,dY as hm,dZ as t5,d_ as no,d$ as s5,e0 as n5,e1 as Ff,e2 as Vv,e3 as r5,e4 as o5,e5 as a5,e6 as i5,e7 as l5,e8 as c5,e9 as Wv,ea as jh,eb as d5,ec as u5,ed as f5,ee as m5,ef as p5,eg as h5,eh as g5,ei as x5,ej as y5,ek as b5,el as v5,em as w5,en as j5,eo as Pg,ep as S5,eq as k5,er as sp,es as Sh,et as N5,eu as C5,ev as A5,ew as kh,ex as Gv,ey as F5,ez as D5,eA as M5,eB as E5,eC as I5,eD as np,eE as Ox,eF as _5,eG as P5,eH as T5,eI as R5,eJ as B5}from"./vendor-.bun-Byc0cUD3.js";import{c as O5,l as $5,d as L5,a as z5,v as H5,g as U5,b as V5,e as W5,u as G5,f as q5,h as K5,i as Q5,j as Y5,k as J5,m as X5,r as Z5,n as eN,o as tN,p as sN,q as nN,s as rN,t as oN}from"./index-BcefsbYU.js";const tn=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",$x=t=>{const e=t.trim();if(!e)return null;try{return new URL(e).origin}catch{try{return new URL(e.endsWith("/")?e:`${e}/`).origin}catch{return null}}},Ar=()=>{if(typeof window>"u")return!1;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=$x(t),n=$x(window.location.origin)||window.location.origin;return!!(e&&n&&e===n)},fr=()=>typeof window>"u"?!1:typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"&&window.__OPENCHAMBER_LOCAL_ORIGIN__.length>0?!0:tn(),ln=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,zi=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!ln()},gm=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Sd=async t=>{if(tn()&&Ar())try{const n=await window.__TAURI__?.dialog?.open?.({directory:!0,multiple:!1,title:"Select Working Directory"});return!n||typeof n!="string"?{success:!1,error:"Directory selection cancelled"}:{success:!0,path:n}}catch(e){return console.warn("Failed to request directory access (tauri)",e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!0,path:t}},qv=async t=>({success:!0}),Kv=async t=>({success:!0}),Qv=async()=>{if(!tn()||!Ar())return null;try{return await window.__TAURI__?.core?.invoke?.("desktop_check_for_updates")}catch(t){return console.warn("Failed to check for updates (tauri)",t),null}},Yv=async t=>{if(!tn()||!Ar())return!1;const e=window.__TAURI__;let n=null,r=0,o;try{return typeof t=="function"&&e?.event?.listen&&(n=await e.event.listen("openchamber:update-progress",a=>{const i=a?.payload;if(!i||typeof i!="object")return;const l=i,c=typeof l.event=="string"?l.event:null,d=l.data&&typeof l.data=="object"?l.data:null;if(c==="Started"){r=0,o=typeof d?.contentLength=="number"?d.contentLength:void 0,t({downloaded:r,total:o});return}if(c==="Progress"){const f=d?.downloaded,m=d?.total;typeof f=="number"&&(r=f),typeof m=="number"&&(o=m),t({downloaded:r,total:o});return}c==="Finished"&&t({downloaded:r,total:o})})),await e?.core?.invoke?.("desktop_download_and_install_update"),!0}catch(a){return console.warn("Failed to download update (tauri)",a),!1}finally{if(n)try{const a=n();a instanceof Promise&&await a}catch{}}},Jv=async()=>{if(!tn()||!Ar())return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_restart"),!0}catch(t){return console.warn("Failed to restart for update (tauri)",t),!1}},Xv=async(t,e)=>{if(!tn()||!Ar())return!1;const n=t?.trim();if(!n)return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_open_path",{path:n,app:typeof e=="string"&&e.trim().length>0?e.trim():void 0}),!0}catch(r){return console.warn("Failed to open path (tauri)",r),!1}},Zv=async(t,e)=>{if(!tn()||!Ar())return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const n=Array.isArray(t)?t.filter(r=>typeof r=="string"):[];if(n.length===0)return{apps:[],success:!0,hasCache:!1,isCacheStale:!1};try{const o=await window.__TAURI__?.core?.invoke?.("desktop_get_installed_apps",{apps:n,force:e===!0?!0:void 0});if(!o||typeof o!="object")return{apps:[],success:!1,hasCache:!1,isCacheStale:!1};const a=o;return Array.isArray(a.apps)?{apps:a.apps.filter(l=>l&&typeof l=="object").map(l=>{const c=l;return{name:typeof c.name=="string"?c.name:"",iconDataUrl:typeof c.iconDataUrl=="string"?c.iconDataUrl:null}}).filter(l=>l.name.length>0),success:!0,hasCache:a.hasCache===!0,isCacheStale:a.isCacheStale===!0}:{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}catch(r){return console.warn("Failed to fetch installed apps (tauri)",r),{apps:[],success:!1,hasCache:!1,isCacheStale:!1}}},aN=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Qv,downloadDesktopUpdate:Yv,fetchDesktopInstalledApps:Zv,getDesktopHomeDirectory:gm,isDesktopLocalOriginActive:Ar,isDesktopShell:fr,isTauriShell:tn,isVSCodeRuntime:ln,isWebRuntime:zi,openDesktopPath:Xv,requestDirectoryAccess:Sd,restartToApplyUpdate:Jv,startAccessingDirectory:qv,stopAccessingDirectory:Kv},Symbol.toStringTag,{value:"Module"}));function Z(...t){return ES(IS(t))}const _i=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),xm=t=>_i()&&tn()?t.metaKey:t.ctrlKey,aa=()=>_i()&&tn()?"⌘":"Ctrl",ew=(t,e)=>{const n=t??"",r=Math.max(16,e?.maxLength??45);if(n.length<=r)return n;const o=n.split("/");if(o.length<=1)return n;const a=o.pop()??"";if(!a)return n;const i=Math.max(0,r-(a.length+2));if(i<=0)return`…/${a}`;let l="";for(const c of o){if(!c)continue;const d=l?`${l}/${c}`:c;if(d.length>i)break;l=d}if(!l){const c=o[0]??"";l=c?c.slice(0,i):""}return l?`${l}…/${a}`:`…/${a}`},Df=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function ia(t,e){if(!t)return"";const n=Df(t);if(n==="/")return"/";const r=e?Df(e):void 0;if(r&&r!=="/"){if(n===r)return"~";if(n.startsWith(`${r}/`)){const o=n.slice(r.length+1);return o?`~/${o}`:"~"}}return n}function To(t,e){if(!t)return"/";const n=Df(t);if(!n||n==="/")return"/";const r=e?Df(e):void 0;return r&&r!=="/"&&n===r?"~":n.split("/").pop()||n||"/"}function ji(t,e){return e?t?t.toLowerCase().includes(e.toLowerCase())?!0:new _S([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(e).length>0:!1:!0}function Vc(t){const e=Me.c(6);let n,r;e[0]!==t?({delayDuration:r,...n}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);const o=r===void 0?0:r;let a;return e[3]!==o||e[4]!==n?(a=s.jsx($S,{"data-slot":"tooltip-provider",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Yt(t){const e=Me.c(6);let n,r;e[0]!==t?({delayDuration:r,...n}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);const o=r===void 0?0:r;let a;return e[3]!==o||e[4]!==n?(a=s.jsx(PS,{"data-slot":"tooltip",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Jt(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(TS,{"data-slot":"tooltip-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function Kt(t){const e=Me.c(13);let n,r,o,a;e[0]!==t?({className:r,sideOffset:a,children:n,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=a===void 0?0:a;let l;e[5]!==r?(l=Z("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",r),e[5]=r,e[6]=l):l=e[6];let c;e[7]===Symbol.for("react.memo_cache_sentinel")?(c=s.jsx(OS,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"}),e[7]=c):c=e[7];let d;return e[8]!==n||e[9]!==o||e[10]!==i||e[11]!==l?(d=s.jsx(RS,{children:s.jsxs(BS,{"data-slot":"tooltip-content",sideOffset:i,className:l,...o,children:[n,c]})}),e[8]=n,e[9]=o,e[10]=i,e[11]=l,e[12]=d):d=e[12],d}function Ys(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(WS,{"data-slot":"dropdown-menu",...n}),e[2]=n,e[3]=r):r=e[3],r}function Js(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(GS,{"data-slot":"dropdown-menu-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function Xs(t){const e=Me.c(14);let n,r,o,a;e[0]!==t?({className:n,sideOffset:a,style:o,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=a===void 0?4:a;let l;e[5]!==o?(l={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)",...o},e[5]=o,e[6]=l):l=e[6];let c;e[7]!==n?(c=Z("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border-2 border-border/60 p-1 shadow-none",n),e[7]=n,e[8]=c):c=e[8];let d;return e[9]!==r||e[10]!==i||e[11]!==l||e[12]!==c?(d=s.jsx(qS,{children:s.jsx(KS,{"data-slot":"dropdown-menu-content",sideOffset:i,style:l,className:c,...r})}),e[9]=r,e[10]=i,e[11]=l,e[12]=c,e[13]=d):d=e[13],d}function is(t){const e=Me.c(12);let n,r,o,a;e[0]!==t?({className:n,inset:r,variant:a,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=a===void 0?"default":a;let l;e[5]!==n?(l=Z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",n),e[5]=n,e[6]=l):l=e[6];let c;return e[7]!==r||e[8]!==o||e[9]!==l||e[10]!==i?(c=s.jsx(QS,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":i,className:l,...o}),e[7]=r,e[8]=o,e[9]=l,e[10]=i,e[11]=c):c=e[11],c}function Mf(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(zS,{"data-slot":"dropdown-menu-radio-group",...n}),e[2]=n,e[3]=r):r=e[3],r}function ym(t){const e=Me.c(11);let n,r,o;e[0]!==t?({className:r,children:n,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o):(n=e[1],r=e[2],o=e[3]);let a;e[4]!==r?(a=Z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[state=checked]:bg-interactive-selection data-[state=checked]:text-interactive-selection-foreground relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),e[4]=r,e[5]=a):a=e[5];let i;e[6]===Symbol.for("react.memo_cache_sentinel")?(i=s.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:s.jsx(VS,{children:s.jsx(Ts,{className:"size-3"})})}),e[6]=i):i=e[6];let l;return e[7]!==n||e[8]!==o||e[9]!==a?(l=s.jsxs(US,{"data-slot":"dropdown-menu-radio-item",className:a,...o,children:[i,n]}),e[7]=n,e[8]=o,e[9]=a,e[10]=l):l=e[10],l}function Zr(t){const e=Me.c(10);let n,r,o;e[0]!==t?({className:n,inset:r,...o}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o):(n=e[1],r=e[2],o=e[3]);let a;e[4]!==n?(a=Z("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",n),e[4]=n,e[5]=a):a=e[5];let i;return e[6]!==r||e[7]!==o||e[8]!==a?(i=s.jsx(LS,{"data-slot":"dropdown-menu-label","data-inset":r,className:a,...o}),e[6]=r,e[7]=o,e[8]=a,e[9]=i):i=e[9],i}function Kn(t){const e=Me.c(8);let n,r;e[0]!==t?({className:n,...r}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);let o;e[3]!==n?(o=Z("bg-border -mx-1 my-0.5 h-px",n),e[3]=n,e[4]=o):o=e[4];let a;return e[5]!==r||e[6]!==o?(a=s.jsx(HS,{"data-slot":"dropdown-menu-separator",className:o,...r}),e[5]=r,e[6]=o,e[7]=a):a=e[7],a}function iN(t){const e=Me.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let r;return e[2]!==n?(r=s.jsx(YS,{"data-slot":"dropdown-menu-sub",...n}),e[2]=n,e[3]=r):r=e[3],r}function lN(t){const e=Me.c(13);let n,r,o,a;e[0]!==t?({className:r,inset:o,children:n,...a}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);let i;e[5]!==r?(i=Z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),e[5]=r,e[6]=i):i=e[6];let l;e[7]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(ar,{className:"ml-auto size-3.5"}),e[7]=l):l=e[7];let c;return e[8]!==n||e[9]!==o||e[10]!==a||e[11]!==i?(c=s.jsxs(JS,{"data-slot":"dropdown-menu-sub-trigger","data-inset":o,className:i,...a,children:[n,l]}),e[8]=n,e[9]=o,e[10]=a,e[11]=i,e[12]=c):c=e[12],c}function cN(t){const e=Me.c(9);let n,r;e[0]!==t?({className:n,...r}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]);let o;e[3]===Symbol.for("react.memo_cache_sentinel")?(o={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},e[3]=o):o=e[3];let a;e[4]!==n?(a=Z("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border-2 border-border/60 p-1 shadow-none",n),e[4]=n,e[5]=a):a=e[5];let i;return e[6]!==r||e[7]!==a?(i=s.jsx(XS,{"data-slot":"dropdown-menu-sub-content",style:o,className:a,...r}),e[6]=r,e[7]=a,e[8]=i):i=e[8],i}function Gl(t){const e=Me.c(45),{tabs:n,value:r,onValueChange:o,className:a,isInteractive:i,animate:l,collapseLabelsOnSmall:c,collapseLabelsOnNarrow:d,size:f}=t,m=i===void 0?!0:i,p=l===void 0?!0:l,g=c===void 0?!1:c,y=d===void 0?!1:d,x=f===void 0?"default":f,h=u.useRef(null),v=u.useRef(null);let b;e[0]===Symbol.for("react.memo_cache_sentinel")?(b=new Map,e[0]=b):b=e[0];const w=u.useRef(b),[j,F]=u.useState(!1);let A;e[1]!==r?(A=()=>{const q=h.current,$=v.current,G=w.current.get(r);if(!q||!$||!G)return;const W=q.getBoundingClientRect(),J=G.getBoundingClientRect(),te=J.left-W.left,le=J.width;$.style.transform=`translateX(${te}px)`,$.style.width=`${le}px`},e[1]=r,e[2]=A):A=e[2];const C=A;let S;e[3]!==j||e[4]!==C?(S=()=>{C(),j||F(!0)},e[3]=j,e[4]=C,e[5]=S):S=e[5];let N;e[6]!==j||e[7]!==n.length||e[8]!==C||e[9]!==r?(N=[j,C,r,n.length],e[6]=j,e[7]=n.length,e[8]=C,e[9]=r,e[10]=N):N=e[10],u.useLayoutEffect(S,N);let k,D;e[11]!==C?(k=()=>{const q=h.current;if(!q)return;const $=new ResizeObserver(()=>C());return $.observe(q),()=>$.disconnect()},D=[C],e[11]=C,e[12]=k,e[13]=D):(k=e[12],D=e[13]),u.useEffect(k,D);let M;e[14]===Symbol.for("react.memo_cache_sentinel")?(M=(q,$)=>{q?w.current.set($,q):w.current.delete($)},e[14]=M):M=e[14];const E=M,_=y&&"@container/animated-tabs";let T;e[15]!==a||e[16]!==_?(T=Z("relative w-full",_,a),e[15]=a,e[16]=_,e[17]=T):T=e[17];const P=x==="sm"?"h-8 rounded-lg py-0.5 px-px gap-0.5":"h-10 rounded-lg py-0.5 px-px gap-0.5";let H;e[18]!==P?(H=Z("relative flex items-center overflow-hidden bg-[var(--surface-muted)]/50",P),e[18]=P,e[19]=H):H=e[19];const R=p&&j?"transition-[transform,width] duration-200 ease-out":null;let I;e[20]!==R?(I=Z("absolute top-0.5 bottom-0.5 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] shadow-none",R),e[20]=R,e[21]=I):I=e[21];let B;e[22]===Symbol.for("react.memo_cache_sentinel")?(B={width:0,transform:"translateX(0)"},e[22]=B):B=e[22];let z;e[23]!==I?(z=s.jsx("div",{ref:v,className:I,style:B}),e[23]=I,e[24]=z):z=e[24];let U;if(e[25]!==g||e[26]!==m||e[27]!==o||e[28]!==x||e[29]!==n||e[30]!==r){let q;e[32]!==g||e[33]!==m||e[34]!==o||e[35]!==x||e[36]!==r?(q=$=>{const G=r===$.value,W=$.icon;return s.jsxs("button",{ref:J=>E(J,$.value),type:"button",onClick:()=>{m&&o($.value)},className:Z("animated-tabs__button relative z-10 flex flex-1 items-center justify-center font-medium transition-colors duration-150",x==="sm"?"h-6 rounded-lg px-2.5 text-sm":"h-7 rounded-lg px-3 text-sm",g?"gap-0 sm:gap-1.5":"gap-1.5",G?"text-foreground":"text-muted-foreground hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":G,"aria-label":$.label,"aria-disabled":!m,tabIndex:m?0:-1,children:[W?s.jsx(W,{className:Z(x==="sm"?"h-3.5 w-3.5":"h-4 w-4",G?"text-foreground":"text-muted-foreground")}):null,s.jsx("span",{className:Z("animated-tabs__label truncate",g?"hidden sm:inline":null),children:$.label})]},$.value)},e[32]=g,e[33]=m,e[34]=o,e[35]=x,e[36]=r,e[37]=q):q=e[37],U=n.map(q),e[25]=g,e[26]=m,e[27]=o,e[28]=x,e[29]=n,e[30]=r,e[31]=U}else U=e[31];let K;e[38]!==H||e[39]!==z||e[40]!==U?(K=s.jsxs("div",{ref:h,className:H,children:[z,U]}),e[38]=H,e[39]=z,e[40]=U,e[41]=K):K=e[41];let V;return e[42]!==T||e[43]!==K?(V=s.jsx("div",{className:T,children:K}),e[42]=T,e[43]=K,e[44]=V):V=e[44],V}function Lx(t){const e=Me.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const i=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let c;e[5]!==a||e[6]!==i||e[7]!==l?(c={width:i,height:l,...a},e[5]=a,e[6]=i,e[7]=l,e[8]=c):c=e[8];let d;e[9]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"}),e[9]=d):d=e[9];let f;return e[10]!==n||e[11]!==r||e[12]!==c?(f=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:c,...r,children:d}),e[10]=n,e[11]=r,e[12]=c,e[13]=f):f=e[13],f}let rp=null,op=null;const Ef=()=>{const t=new Map;return{getItem:e=>t.get(e)??null,setItem:(e,n)=>{t.set(e,n)},removeItem:e=>{t.delete(e)},clear:()=>{t.clear()},key:e=>Array.from(t.keys())[e]??null,get length(){return t.size}}},dN=()=>{if(typeof window>"u"||!window.localStorage)return Ef();const t=window.localStorage,e=Ef();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const f=t.getItem(d);if(f!==null)return f}catch{r()}return e.getItem(d)},setItem:(d,f)=>{if(n)try{t.setItem(d,f),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,f)},removeItem:d=>{try{t.removeItem(d)}catch{r()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{r()}e.clear()},key:d=>{if(n)try{return t.key(d)}catch{r()}return e.key(d)},get length(){if(n)try{return t.length+e.length}catch{r()}return e.length}}},Wn=()=>(rp||(rp=dN()),rp),uN=()=>{if(typeof window>"u"||!window.sessionStorage)return Ef();const t=window.sessionStorage,e=Ef();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const f=t.getItem(d);if(f!==null)return f}catch{r()}return e.getItem(d)},setItem:(d,f)=>{if(n)try{t.setItem(d,f),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,f)},removeItem:d=>{try{t.removeItem(d)}catch{r()}e.removeItem(d)},clear:()=>{try{t.clear()}catch{r()}e.clear()},key:d=>{if(n)try{return t.key(d)}catch{r()}return e.key(d)},get length(){if(n)try{return t.length+e.length}catch{r()}return e.length}}},fN=()=>(op||(op=uN()),op),Tg={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},mN={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function zx(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const ka={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},tf={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ka.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:tf.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ka.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:tf.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ka.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:tf.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ka.tool.inline})},vu={completion:{title:"{agent_name} is ready",message:"{last_message}"},error:{title:"Tool error",message:"{last_message}"},question:{title:"{agent_name} needs input",message:"{last_message}"},subtask:{title:"Subtask complete",message:"{last_message}"}},Pa={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},wu=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,pN=t=>{if(!t||typeof t!="object")return!1;const e=t;return wu(e.completion,vu.completion)&&wu(e.error,vu.error)&&wu(e.question,vu.question)&&wu(e.subtask,vu.subtask)},tw=600,hN=360,gN=1400,vc=300,wc=400,ii=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},xN=t=>Number.isFinite(t)?Math.min(gN,Math.max(hN,Math.round(t))):tw,li=t=>t?{...t,touchedAt:Date.now()}:{isOpen:!1,expanded:!1,mode:null,targetPath:null,width:tw,touchedAt:Date.now()},ci=(t,e)=>{const n=Object.entries(t);if(n.length<=e)return t;n.sort((o,a)=>(a[1]?.touchedAt??0)-(o[1]?.touchedAt??0));const r={};for(const[o,a]of n.slice(0,e))r[o]=a;return r},Te=Fn()(Gn(Br((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:vc,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:wc,hasManuallyResizedRightSidebar:!1,rightSidebarTab:"git",contextPanelByDirectory:{},isBottomTerminalOpen:!1,isBottomTerminalExpanded:!1,bottomTerminalHeight:300,hasManuallyResizedBottomTerminal:!1,isNavRailExpanded:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,sidebarOpenBeforeFullscreenTab:null,pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isOpenCodeStatusDialogOpen:!1,openCodeStatusText:"",isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",settingsPage:"home",settingsHasOpenedOnce:!1,settingsProjectsSelectedId:null,settingsRemoteInstancesSelectedId:null,eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!0,showTextJustificationActivity:!1,showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,messageLimit:200,toolCallExpansion:"collapsed",fontSize:100,terminalFontSize:13,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],hiddenModels:[],recentModels:[],recentAgents:[],recentEfforts:{},diffLayoutPreference:"inline",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"stacked",isTimelineDialogOpen:!1,isImagePreviewOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",notifyOnSubtasks:!0,notifyOnCompletion:!0,notifyOnError:!0,notifyOnQuestion:!0,notificationTemplates:{completion:{...Pa.completion},error:{...Pa.error},question:{...Pa.question},subtask:{...Pa.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,mermaidRenderingMode:"svg",showMobileSessionStatusBar:!0,isMobileSessionStatusBarCollapsed:!1,isExpandedInput:!1,shortcutOverrides:{},setTheme:n=>{t({theme:n}),e().applyTheme()},toggleSidebar:()=>{t(n=>{const r=!n.isSidebarOpen;return r&&!n.hasManuallyResizedLeftSidebar?{isSidebarOpen:r,sidebarWidth:vc}:{isSidebarOpen:r}})},setSidebarOpen:n=>{t(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==vc?{isSidebarOpen:n,sidebarWidth:vc}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:vc}:{isSidebarOpen:n})},setSidebarWidth:n=>{t({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(n=>{const r=!n.isRightSidebarOpen;return r&&!n.hasManuallyResizedRightSidebar?{isRightSidebarOpen:r,rightSidebarWidth:wc}:{isRightSidebarOpen:r}})},setRightSidebarOpen:n=>{t(r=>r.isRightSidebarOpen===n?n&&!r.hasManuallyResizedRightSidebar&&r.rightSidebarWidth!==wc?{isRightSidebarOpen:n,rightSidebarWidth:wc}:r:n&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:wc}:{isRightSidebarOpen:n})},setRightSidebarWidth:n=>{t({rightSidebarWidth:n,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:n=>{t({rightSidebarTab:n})},openContextDiff:(n,r)=>{const o=ii((n||"").trim()),a=(r||"").trim();!o||!a||(t(i=>{const l=i.contextPanelByDirectory[o],c=li(l),d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,mode:"diff",targetPath:a}};return{contextPanelByDirectory:ci(d,20)}}),e().setPendingDiffFile(a))},openContextFile:(n,r)=>{const o=ii((n||"").trim()),a=(r||"").trim();!o||!a||t(i=>{const l=i.contextPanelByDirectory[o],c=li(l),d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,mode:"file",targetPath:a}};return{contextPanelByDirectory:ci(d,20)}})},openContextOverview:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=li(a),l={...o.contextPanelByDirectory,[r]:{...i,isOpen:!0,mode:"context",targetPath:null}};return{contextPanelByDirectory:ci(l,20)}})},openContextPlan:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=li(a),l={...o.contextPanelByDirectory,[r]:{...i,isOpen:!0,mode:"plan",targetPath:null}};return{contextPanelByDirectory:ci(l,20)}})},closeContextPanel:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r];if(!a||!a.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...li(a),isOpen:!1}};return{contextPanelByDirectory:ci(i,20)}})},toggleContextPanelExpanded:n=>{const r=ii((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=li(a),l={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:ci(l,20)}})},setContextPanelWidth:(n,r)=>{const o=ii((n||"").trim());o&&t(a=>{const i=a.contextPanelByDirectory[o],l=li(i),c={...a.contextPanelByDirectory,[o]:{...l,width:xN(r)}};return{contextPanelByDirectory:ci(c,20)}})},toggleBottomTerminal:()=>{t(n=>{const r=!n.isBottomTerminalOpen;if(r&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:r,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:r}})},setBottomTerminalOpen:n=>{t(r=>{if(r.isBottomTerminalOpen===n){if(!n)return r;if(!r.hasManuallyResizedBottomTerminal&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return r.bottomTerminalHeight===o&&r.hasManuallyResizedBottomTerminal===!1?r:{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return r}if(n&&typeof window<"u"){const o=Math.floor(window.innerHeight*.32);return{isBottomTerminalOpen:n,bottomTerminalHeight:o,hasManuallyResizedBottomTerminal:!1}}return{isBottomTerminalOpen:n}})},setBottomTerminalExpanded:n=>{t({isBottomTerminalExpanded:n})},setBottomTerminalHeight:n=>{t({bottomTerminalHeight:n,hasManuallyResizedBottomTerminal:!0})},setNavRailExpanded:n=>{t({isNavRailExpanded:n})},toggleNavRail:()=>{t({isNavRailExpanded:!e().isNavRailExpanded})},setSessionSwitcherOpen:n=>{t({isSessionSwitcherOpen:n})},setMainTabGuard:n=>{e().mainTabGuard!==n&&t({mainTabGuard:n})},setActiveMainTab:n=>{const r=e().mainTabGuard;r&&!r(n)||t({activeMainTab:n})},setPendingDiffFile:n=>{t({pendingDiffFile:n})},navigateToDiff:n=>{const r=e().mainTabGuard;r&&!r("diff")||t({pendingDiffFile:n,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:n}=e();return n&&t({pendingDiffFile:null}),n},setIsMobile:n=>{t({isMobile:n})},toggleCommandPalette:()=>{t(n=>({isCommandPaletteOpen:!n.isCommandPaletteOpen}))},setCommandPaletteOpen:n=>{t({isCommandPaletteOpen:n})},toggleHelpDialog:()=>{t(n=>({isHelpDialogOpen:!n.isHelpDialogOpen}))},setHelpDialogOpen:n=>{t({isHelpDialogOpen:n})},setAboutDialogOpen:n=>{t({isAboutDialogOpen:n})},setOpenCodeStatusDialogOpen:n=>{t({isOpenCodeStatusDialogOpen:n})},setOpenCodeStatusText:n=>{t({openCodeStatusText:n})},setSessionCreateDialogOpen:n=>{t({isSessionCreateDialogOpen:n})},setSettingsDialogOpen:n=>{t(r=>n?r.settingsHasOpenedOnce?{isSettingsDialogOpen:!0}:{isSettingsDialogOpen:!0,settingsHasOpenedOnce:!0}:{isSettingsDialogOpen:!1})},setModelSelectorOpen:n=>{t({isModelSelectorOpen:n})},setSidebarSection:n=>{t({sidebarSection:n})},setSettingsPage:n=>{t({settingsPage:n})},setSettingsProjectsSelectedId:n=>{t({settingsProjectsSelectedId:n})},setSettingsRemoteInstancesSelectedId:n=>{t({settingsRemoteInstancesSelectedId:n})},setEventStreamStatus:(n,r)=>{t({eventStreamStatus:n,eventStreamHint:r??null})},setShowReasoningTraces:n=>{t({showReasoningTraces:n})},setShowTextJustificationActivity:n=>{t({showTextJustificationActivity:n})},setShowDeletionDialog:n=>{t({showDeletionDialog:n})},setAutoDeleteEnabled:n=>{t({autoDeleteEnabled:n})},setAutoDeleteAfterDays:n=>{const r=Math.max(1,Math.min(365,n));t({autoDeleteAfterDays:r})},setAutoDeleteLastRunAt:n=>{t({autoDeleteLastRunAt:n})},setMessageLimit:n=>{const r=Math.max(10,Math.min(500,Math.round(n)));t({messageLimit:r})},setToolCallExpansion:n=>{t({toolCallExpansion:n})},setFontSize:n=>{const r=Math.max(50,Math.min(200,n));t({fontSize:r}),e().applyTypography()},setTerminalFontSize:n=>{const r=Math.round(n),o=Math.max(9,Math.min(52,r));t({terminalFontSize:o})},setPadding:n=>{const r=Math.max(50,Math.min(200,n));t({padding:r}),e().applyPadding()},setCornerRadius:n=>{t({cornerRadius:n})},applyTypography:()=>{const{fontSize:n}=e(),r=document.documentElement,o=n/100,a=Object.entries(Tg);if(o===1){for(const[i]of a)r.style.removeProperty(zx(i));return}for(const[i,l]of a){const c=parseFloat(l);Number.isFinite(c)&&r.style.setProperty(zx(i),`${c*o}rem`)}},applyPadding:()=>{const{padding:n}=e(),r=document.documentElement,o=n/100;if(o===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);r.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:n=>{t({diffLayoutPreference:n})},setDiffFileLayout:(n,r)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[n]:r}}))},setDiffWrapLines:n=>{t({diffWrapLines:n})},setDiffViewMode:n=>{t({diffViewMode:n})},setInputBarOffset:n=>{t({inputBarOffset:n})},setKeyboardOpen:n=>{t({isKeyboardOpen:n})},toggleFavoriteModel:(n,r)=>{t(o=>o.favoriteModels.some(i=>i.providerID===n&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{favoriteModels:[{providerID:n,modelID:r},...o.favoriteModels]})},toggleHiddenModel:(n,r)=>{t(o=>o.hiddenModels.some(i=>i.providerID===n&&i.modelID===r)?{hiddenModels:o.hiddenModels.filter(i=>!(i.providerID===n&&i.modelID===r))}:{hiddenModels:[{providerID:n,modelID:r},...o.hiddenModels]})},isHiddenModel:(n,r)=>{const{hiddenModels:o}=e();return o.some(a=>a.providerID===n&&a.modelID===r)},hideAllModels:(n,r)=>{t(o=>{const a=o.hiddenModels.filter(l=>l.providerID!==n);return{hiddenModels:[...r.filter(l=>typeof l=="string"&&l.length>0).map(l=>({providerID:n,modelID:l})),...a]}})},showAllModels:n=>{t(r=>({hiddenModels:r.hiddenModels.filter(o=>o.providerID!==n)}))},isFavoriteModel:(n,r)=>{const{favoriteModels:o}=e();return o.some(a=>a.providerID===n&&a.modelID===r)},addRecentModel:(n,r)=>{t(o=>{const a=o.recentModels.filter(i=>!(i.providerID===n&&i.modelID===r));return{recentModels:[{providerID:n,modelID:r},...a].slice(0,5)}})},addRecentAgent:n=>{const r=typeof n=="string"?n.trim():"";r&&t(o=>{if(o.recentAgents.includes(r))return o;const a=o.recentAgents;return{recentAgents:[r,...a].slice(0,5)}})},addRecentEffort:(n,r,o)=>{const a=typeof n=="string"?n.trim():"",i=typeof r=="string"?r.trim():"";if(!a||!i)return;const l=`${a}/${i}`,c=typeof o=="string"&&o.trim().length>0?o.trim():"default";t(d=>{const f=d.recentEfforts[l]??[];if(f.includes(c))return d;const m=f;return{recentEfforts:{...d.recentEfforts,[l]:[c,...m].slice(0,5)}}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(n=>{const r={};return n.isBottomTerminalOpen&&!n.hasManuallyResizedBottomTerminal&&(r.bottomTerminalHeight=Math.floor(window.innerHeight*.32)),r})},applyTheme:()=>{const{theme:n}=e(),r=document.documentElement;if(r.classList.remove("light","dark"),n==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(n)},setMultiRunLauncherOpen:n=>{t(r=>({isMultiRunLauncherOpen:n,multiRunLauncherPrefillPrompt:n?r.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:n=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:n,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:n=>{t({isTimelineDialogOpen:n})},setImagePreviewOpen:n=>{t({isImagePreviewOpen:n})},setNativeNotificationsEnabled:n=>{t({nativeNotificationsEnabled:n})},setNotificationMode:n=>{t({notificationMode:n})},setShowTerminalQuickKeysOnDesktop:n=>{t({showTerminalQuickKeysOnDesktop:n})},setNotifyOnSubtasks:n=>{t({notifyOnSubtasks:n})},setNotifyOnCompletion:n=>{t({notifyOnCompletion:n})},setNotifyOnError:n=>{t({notifyOnError:n})},setNotifyOnQuestion:n=>{t({notifyOnQuestion:n})},setNotificationTemplates:n=>{t({notificationTemplates:n})},setSummarizeLastMessage:n=>{t({summarizeLastMessage:n})},setSummaryThreshold:n=>{t({summaryThreshold:n})},setSummaryLength:n=>{t({summaryLength:n})},setMaxLastMessageLength:n=>{t({maxLastMessageLength:n})},setPersistChatDraft:n=>{t({persistChatDraft:n})},setMermaidRenderingMode:n=>{t({mermaidRenderingMode:n})},setShowMobileSessionStatusBar:n=>{t({showMobileSessionStatusBar:n})},setIsMobileSessionStatusBarCollapsed:n=>{t({isMobileSessionStatusBarCollapsed:n})},viewPagerPage:"center",setViewPagerPage:n=>{t({viewPagerPage:n}),t(n==="left"?{isSessionSwitcherOpen:!0,isRightSidebarOpen:!1}:n==="right"?{isRightSidebarOpen:!0,isSessionSwitcherOpen:!1}:{isSessionSwitcherOpen:!1,isRightSidebarOpen:!1})},setShortcutOverride:(n,r)=>{t(o=>({shortcutOverrides:{...o.shortcutOverrides,[n]:r}}))},clearShortcutOverride:n=>{t(r=>{const o={...r.shortcutOverrides};return delete o[n],{shortcutOverrides:o}})},resetAllShortcutOverrides:()=>{t({shortcutOverrides:{}})},toggleExpandedInput:()=>{t(n=>({isExpandedInput:!n.isExpandedInput}))},setExpandedInput:n=>{t({isExpandedInput:n})}}),{name:"ui-store",storage:Or(()=>Wn()),version:5,migrate:(t,e)=>{if(!t||typeof t!="object")return t;const n=t;if(e<1&&pN(n.notificationTemplates)&&(n.notificationTemplates={completion:{...Pa.completion},error:{...Pa.error},question:{...Pa.question},subtask:{...Pa.subtask}}),e<3){const r=new Set([90,120,180,220]),o=n.memoryLimitHistorical,a=n.memoryLimitActiveSession;typeof o=="number"&&!r.has(o)?n.messageLimit=o:typeof a=="number"&&!r.has(a)&&(n.messageLimit=a),delete n.memoryLimitHistorical,delete n.memoryLimitViewport,delete n.memoryLimitActiveSession}if((typeof n.rightSidebarTab!="string"||n.rightSidebarTab!=="git"&&n.rightSidebarTab!=="files")&&(n.rightSidebarTab="git"),(!n.contextPanelByDirectory||typeof n.contextPanelByDirectory!="object")&&(n.contextPanelByDirectory={}),e<5)if(!n.shortcutOverrides||typeof n.shortcutOverrides!="object")n.shortcutOverrides={};else{const r=n.shortcutOverrides,o={};for(const[a,i]of Object.entries(r))typeof a=="string"&&typeof i=="string"&&(o[a]=i);n.shortcutOverrides=o}return n},partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isRightSidebarOpen:t.isRightSidebarOpen,rightSidebarWidth:t.rightSidebarWidth,rightSidebarTab:t.rightSidebarTab,contextPanelByDirectory:t.contextPanelByDirectory,isBottomTerminalOpen:t.isBottomTerminalOpen,isBottomTerminalExpanded:t.isBottomTerminalExpanded,bottomTerminalHeight:t.bottomTerminalHeight,isNavRailExpanded:t.isNavRailExpanded,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,settingsPage:t.settingsPage,settingsHasOpenedOnce:t.settingsHasOpenedOnce,settingsProjectsSelectedId:t.settingsProjectsSelectedId,settingsRemoteInstancesSelectedId:t.settingsRemoteInstancesSelectedId,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,showReasoningTraces:t.showReasoningTraces,showTextJustificationActivity:t.showTextJustificationActivity,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,toolCallExpansion:t.toolCallExpansion,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,showTerminalQuickKeysOnDesktop:t.showTerminalQuickKeysOnDesktop,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,persistChatDraft:t.persistChatDraft,mermaidRenderingMode:t.mermaidRenderingMode,showMobileSessionStatusBar:t.showMobileSessionStatusBar,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,shortcutOverrides:t.shortcutOverrides})}),{name:"ui-store"})),yN="/api",bN=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,vN=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(bN.test(e)||typeof window>"u")return e;const n=window.location?.href||window.location?.origin;if(!n)return e;try{return new URL(e,n).toString()}catch(r){return console.warn("Failed to normalize OpenCode base URL:",r),e}},wN=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_DESKTOP_SERVER__,e=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!e)return null;const n=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return n?`${n}/api`:null},ju=t=>t.replace(/\\/g,"/"),ap=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class jN{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;globalSseQueue=[];globalSseBuffer=[];globalSseCoalesced=new Map;globalSseFlushTimer=null;globalSseLastFlushAt=0;constructor(e=yN){const r=wN()||e;this.baseUrl=vN(r),this.client=Dx({baseUrl:this.baseUrl})}getBaseUrl(){return this.baseUrl}getScopedApiClient(e){const n=this.normalizeCandidatePath(e)??e,r=n||"",o=this.scopedClients.get(r);if(o)return o;const a=Dx({baseUrl:this.baseUrl,directory:n});return this.scopedClients.set(r,a),a}normalizeCandidatePath(e){if(typeof e!="string")return null;const n=e.trim();if(!n)return null;const r=n.replace(/\\/g,"/");return(r.length>1?r.replace(/\/+$/,""):r)||null}deriveHomeDirectory(e){const n=e.match(/^([A-Za-z]:)(?:\/|$)/);if(n){const a=n[1],l=e.slice(a.length+(e.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const r=e.startsWith("/"),o=e.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(e){this.currentDirectory=e}getDirectory(){return this.currentDirectory}async withDirectory(e,n){const r=async()=>{if(e==null)return n();const a=this.currentDirectory;this.currentDirectory=e;try{return await n()}finally{this.currentDirectory=a}},o=this.directoryContextQueue.then(r,r);return this.directoryContextQueue=o.then(()=>{},()=>{}),o}getApiClient(){return this.client}async getSystemInfo(){const e=new Set,n=o=>{const a=this.normalizeCandidatePath(o);a&&e.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(n(a.directory),n(a.worktree),n(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!e.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);n(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!e.size)try{(await this.listSessions()).forEach(a=>n(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(n(this.currentDirectory),typeof window<"u")try{n(window.localStorage.getItem("lastDirectory")),n(window.localStorage.getItem("homeDirectory"))}catch{}if(!e.size&&typeof process<"u"&&typeof process.cwd=="function"&&n(process.cwd()),!e.size)return{homeDirectory:"/",username:void 0};const[r]=Array.from(e);return this.deriveHomeDirectory(r)}async probeDirectory(e){const n=this.normalizeCandidatePath(e);if(!n)return!1;try{const o=(await this.client.path.get({directory:n})).data,a=typeof o?.directory=="string"?o.directory:null;return!!(a&&a.trim().length>0)}catch{return!1}}async listSessions(){const e=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(e.data)?e.data:[]}async createSession(e){const n=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:e?.parentID,title:e?.title});if(!n.data)throw new Error("Failed to create session");return n.data}async getSession(e){const n=await this.client.session.get({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!n.data)throw new Error("Session not found");return n.data}async deleteSession(e){return(await this.client.session.delete({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(e,n){const r=await this.client.session.update({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},title:n});if(!r.data)throw new Error("Failed to update session");return r.data}async getSessionMessages(e,n){return(await this.client.session.messages({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof n=="number"?{limit:n}:{}})).data||[]}async getSessionTodos(e){try{const n=this.baseUrl.replace(/\/$/,""),r=new URL(`${n}/session/${encodeURIComponent(e)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&r.searchParams.set("directory",this.currentDirectory);const o=await fetch(r.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(e){if(!e)return!1;const n=e.toLowerCase();return n.startsWith("text/")&&n!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript","application/octet-stream","image/svg+xml"].includes(n)}isHeicMime(e){if(!e)return!1;const n=e.toLowerCase();return n==="image/heic"||n==="image/heif"}async convertHeicToJpeg(e){try{const n=(await gr(async()=>{const{default:m}=await import("./vendor-.bun-Byc0cUD3.js").then(p=>p.h);return{default:m}},__vite__mapDeps([0,1]))).default,r=e.url.indexOf(",");if(r===-1)return e;const o=e.url.substring(r+1),a=atob(o),i=new Uint8Array(a.length);for(let m=0;m<a.length;m++)i[m]=a.charCodeAt(m);const l=new Blob([i],{type:e.mime}),c=await n({blob:l,toType:"image/jpeg",quality:.9}),d=await new Promise((m,p)=>{const g=new FileReader;g.onload=()=>m(g.result),g.onerror=p,g.readAsDataURL(c)});let f=e.filename;return f&&(f=f.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:f,url:d}}catch(n){return console.warn("Failed to convert HEIC to JPEG:",n),e}}async normalizeFilePart(e){if(this.isHeicMime(e.mime))return this.convertHeicToJpeg(e);if(!this.shouldNormalizeToTextPlain(e.mime))return e;let n=e.url;if(e.url.startsWith("data:")){const r=e.url.indexOf(",");if(r!==-1){const o=e.url.substring(5,r),a=e.url.substring(r);n=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:e.filename,url:n}}async toNormalizedFilePartInput(e){const n=await this.normalizeFilePart(e);return{...e.id?{id:e.id}:{},type:"file",mime:n.mime,filename:n.filename,url:n.url}}async sendMessage(e){const n=Date.now(),r=e.messageId??`temp_${n}_${Math.random().toString(36).substring(2,9)}`,o=[];if(e.prefaceText&&e.prefaceText.trim()&&o.push({type:"text",text:e.prefaceText,synthetic:e.prefaceTextSynthetic!==!1}),e.text&&e.text.trim()){const c={type:"text",text:e.text};o.push(c)}if(e.files&&e.files.length>0)for(const c of e.files){const d=await this.toNormalizedFilePartInput(c);o.push(d)}if(e.additionalParts&&e.additionalParts.length>0){for(const c of e.additionalParts)if(c.text&&c.text.trim()&&o.push({type:"text",text:c.text,...c.synthetic?{synthetic:!0}:{}}),c.files&&c.files.length>0)for(const d of c.files){const f=await this.toNormalizedFilePartInput(d);o.push(f)}}if(e.agentMentions&&e.agentMentions.length>0)for(const c of e.agentMentions)c?.name&&o.push({type:"agent",name:c.name,...c.source?{source:c.source}:{}});if(o.length===0)throw new Error("Message must have at least one part (text or file)");const a=this.baseUrl.replace(/\/+$/,"");let i;try{i=new URL(`${a}/session/${encodeURIComponent(e.id)}/prompt_async`),this.currentDirectory&&i.searchParams.set("directory",this.currentDirectory)}catch(c){throw console.error("[git-generation][browser] failed to build prompt_async URL",{baseUrl:this.baseUrl,normalizedBase:a,sessionId:e.id,directory:this.currentDirectory,message:c instanceof Error?c.message:String(c),error:c}),c}e.format&&console.info("[git-generation][browser] send structured message",{sessionId:e.id,providerID:e.providerID,modelID:e.modelID,agent:e.agent,variant:e.variant,directory:this.currentDirectory,baseUrl:this.baseUrl,formatType:e.format.type});let l;try{l=await fetch(i.toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({model:{providerID:e.providerID,modelID:e.modelID},agent:e.agent,variant:e.variant,...e.format?{format:e.format}:{},parts:o})})}catch(c){throw console.error("[git-generation][browser] prompt_async request failed before response",{sessionId:e.id,url:i.toString(),directory:this.currentDirectory,hasFormat:!!e.format,message:c instanceof Error?c.message:String(c),error:c}),c}if(!l.ok){let c="";try{c=await l.text()}catch{}const d=c&&c.trim().length>0?`: ${c.trim()}`:"";throw new Error(`Failed to send message (${l.status})${d}`)}return r}async sendCommand(e){const n=Date.now(),r=e.messageId??`temp_${n}_${Math.random().toString(36).substring(2,9)}`,o=[];if(e.files&&e.files.length>0)for(const d of e.files)o.push(await this.toNormalizedFilePartInput(d));const a=this.baseUrl.replace(/\/+$/,""),i=new URL(`${a}/session/${encodeURIComponent(e.id)}/command`);this.currentDirectory&&i.searchParams.set("directory",this.currentDirectory);const l={command:e.command,arguments:e.arguments??"",model:`${e.providerID}/${e.modelID}`,...e.agent?{agent:e.agent}:{},...e.variant?{variant:e.variant}:{},...o.length>0?{parts:o}:{},...e.messageId?{messageID:e.messageId}:{}},c=await fetch(i.toString(),{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(l)});if(!c.ok){let d="";try{d=await c.text()}catch{}const f=d&&d.trim().length>0?`: ${d.trim()}`:"";throw new Error(`Failed to run command (${c.status})${f}`)}return r}async abortSession(e){return!!(await this.client.session.abort({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(e,n,r){const o=await this.client.session.revert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:n,partID:r});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(e){const n=await this.client.session.unrevert({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!n.data)throw new Error("Failed to unrevert session");return n.data}async forkSession(e,n){const r=await this.client.session.fork({sessionID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:n});if(!r.data)throw new Error("Failed to fork session");return r.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(e){try{const n=this.baseUrl.replace(/\/$/,""),r=new URL(`${n}/session/status`),o=typeof e=="string"?e.trim():"";o.length>0&&r.searchParams.set("directory",o);const a=await fetch(r.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async getWebServerSessionActivity(){try{const e=await fetch("/api/session-activity",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const n=await e.json().catch(()=>null);return!n||typeof n!="object"?null:n}catch{return null}}async listToolIds(e){try{const n=typeof e?.directory=="string"?e.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(n?{directory:n}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(e,n,r){return(await this.client.permission.reply({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:n,...r?.message?{message:r.message}:{}})).data||!1}async listPendingPermissions(e){const n=[],r=async c=>{try{const d=typeof c=="string"?c.trim():"";return(await this.client.permission.list(d?{directory:d}:void 0)).data||[]}catch{return[]}};n.push(r(null));const o=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&o.add(d)}for(const c of o)n.push(r(c));const a=await Promise.all(n),i=[],l=new Set;for(const c of a)for(const d of c){if(!d||typeof d!="object")continue;const f=d.id;typeof f!="string"||f.length===0||l.has(f)||(l.add(f),i.push(d))}return i}async replyToQuestion(e,n){const r=!Array.isArray(n)||n.length===0?[]:Array.isArray(n[0])?n:[n];return(await this.client.question.reply({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:r})).data||!1}async rejectQuestion(e){return(await this.client.question.reject({requestID:e,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(e){const n=[],r=async c=>{try{const d=typeof c=="string"?c.trim():"";return(await this.client.question.list(d?{directory:d}:void 0)).data||[]}catch{return[]}};n.push(r(null));const o=new Set;for(const c of e?.directories??[]){const d=this.normalizeCandidatePath(c??null);d&&o.add(d)}for(const c of o)n.push(r(c));const a=await Promise.all(n),i=[],l=new Set;for(const c of a)for(const d of c){if(!d||typeof d!="object")continue;const f=d.id;typeof f!="string"||f.length===0||l.has(f)||(l.add(f),i.push(d))}return i}async getConfig(){const e=await this.client.config.get();if(!e.data)throw new Error("Failed to get config");return e.data}async updateConfig(e){const n=`${this.baseUrl}/config`,r=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){const a=await r.text();throw console.error("[OpencodeClient] Failed to update config:",r.status,a),new Error(`Failed to update config: ${r.status} ${r.statusText}`)}return await r.json()}async updateConfigPartial(e){const n=await this.getConfig(),r=e(n);return await this.updateConfig(r)}async getProviders(){const e=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!e.data)throw new Error("Failed to get providers");return e.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(e){if(!e)return null;const n=e.split(`
3
3
  `),r=[];let o;for(const i of n)if(i.startsWith("data:"))r.push(i.slice(5).replace(/^\s/,""));else if(i.startsWith("id:")){const l=i.slice(3).trim();l&&(o=l)}if(r.length===0)return null;const a=r.join(`
4
4
  `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(e){if(!e||typeof e!="object")return null;const n=e,r=typeof n.directory=="string"?n.directory:typeof n.properties=="object"&&n.properties!==null?n.properties.directory:null,o=typeof r=="string"?this.normalizeCandidatePath(r)??r.trim():null;if(typeof n.type=="string")return{directory:o&&o.length>0?o:"global",payload:n};const a=n.payload;if(a&&typeof a=="object"){const i=a;if(typeof i.type=="string")return{directory:o&&o.length>0?o:"global",payload:i}}return null}emitGlobalSseEvent(e){this.enqueueGlobalSseEvent(e)}notifyGlobalSseOpen(){for(const e of this.globalSseOpenListeners)try{e()}catch(n){console.warn("[OpencodeClient] Global SSE open handler error:",n)}}notifyGlobalSseError(e){for(const n of this.globalSseErrorListeners)try{n(e)}catch(r){console.warn("[OpencodeClient] Global SSE error handler failed:",r)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const e=new AbortController;this.globalSseAbortController=e,this.globalSseTask=this.runGlobalSseLoop(e).catch(n=>{n?.name==="AbortError"||e.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",n)}).finally(()=>{this.globalSseAbortController===e&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null,this.clearGlobalSseQueue())}clearGlobalSseQueue(){this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length=0,this.globalSseBuffer.length=0,this.globalSseCoalesced.clear()}getGlobalSseCoalesceKey(e){const n=e.payload,r=typeof n.type=="string"?n.type:null;if(!r)return null;const o=typeof n.properties=="object"&&n.properties!==null?n.properties:null;if(r==="session.status"){const a=typeof o?.sessionID=="string"?o.sessionID:typeof o?.sessionId=="string"?o.sessionId:null;return a?`session.status:${e.directory}:${a}`:null}if(r==="openchamber:session-status"){const a=typeof o?.sessionId=="string"?o.sessionId:typeof o?.sessionID=="string"?o.sessionID:null;return a?`openchamber:session-status:${a}`:null}return null}flushGlobalSseQueue=()=>{if(this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length===0)return;const e=this.globalSseQueue;this.globalSseQueue=this.globalSseBuffer,this.globalSseBuffer=e,this.globalSseQueue.length=0,this.globalSseCoalesced.clear(),this.globalSseLastFlushAt=Date.now();for(const n of e)if(n)for(const r of this.globalSseListeners)try{r(n)}catch(o){console.warn("[OpencodeClient] Global SSE listener error:",o)}this.globalSseBuffer.length=0};scheduleGlobalSseFlush(){if(this.globalSseFlushTimer)return;const e=Date.now()-this.globalSseLastFlushAt,n=Math.max(0,16-e);this.globalSseFlushTimer=setTimeout(this.flushGlobalSseQueue,n)}enqueueGlobalSseEvent(e){const n=this.getGlobalSseCoalesceKey(e);if(n){const r=this.globalSseCoalesced.get(n);r!==void 0&&(this.globalSseQueue[r]=void 0),this.globalSseCoalesced.set(n,this.globalSseQueue.length)}this.globalSseQueue.push(e),this.scheduleGlobalSseFlush()}async runGlobalSseLoop(e){const n=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let r=0;for(;!e.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const i=await fetch(n,{method:"GET",headers:a,signal:e.signal});if(!i.ok||!i.body)throw new Error(`Global SSE connect failed with status ${i.status}`);r=0,this.globalSseIsConnected=!0,e.signal.aborted||this.notifyGlobalSseOpen();const l=i.body.getReader(),c=new TextDecoder;let d="";for(;;){const{done:m,value:p}=await l.read();if(m||e.signal.aborted)break;if(!p||p.length===0)continue;d+=c.decode(p,{stream:!0}).replace(/\r\n/g,`
5
5
  `);const g=d.split(`
@@ -126,7 +126,7 @@ ${t}`,o=mi.get(r);if(o!==void 0)return o;const a=ep.languages[n]??ep.languages.t
126
126
  `).map(e=>e.replace(/^>\s?/,"").trimEnd()).filter(e=>e.trim().length>0).join(`
127
127
  `).trim(),W_=t=>{const e=Me.c(6),{part:n,messageId:r,onContentChange:o}=t,a=n,i=a.text||a.content||"";let l;e[0]!==i?(l=V_(i),e[0]=i,e[1]=l):l=e[1];const c=l;if(!c||c.trim().length===0)return null;const d=n.id||`${r}-justification`;let f;return e[2]!==o||e[3]!==d||e[4]!==c?(f=s.jsx(ej,{text:c,variant:"justification",onContentChange:o,blockId:d}),e[2]=o,e[3]=d,e[4]=c,e[5]=f):f=e[5],f},G_=u.memo(W_),Zb=6,q_=t=>[...t].sort((e,n)=>{const r=typeof e.endedAt=="number"?e.endedAt:void 0,o=typeof n.endedAt=="number"?n.endedAt:void 0;return r===void 0&&o===void 0?0:r===void 0?1:o===void 0?-1:r-o}),e0=t=>{const e={},n=t.filter(r=>r.kind==="tool");return n.forEach((r,o)=>{const a=r.id;e[a]={hasPrev:o>0,hasNext:o<n.length-1}}),e},K_=({parts:t,isExpanded:e,onToggle:n,syntaxTheme:r,isMobile:o,expandedTools:a,onToggleTool:i,onShowPopup:l,onContentChange:c,diffStats:d})=>{const f=u.useRef(e),[m,p]=u.useState(!1),[g,y]=u.useState(0),x=u.useRef(new Set);u.useEffect(()=>{if(f.current===e)return;const N=f.current===!1;if(f.current=e,c?.("structural"),e&&N){y(D=>D+1),p(!0),x.current.clear();const k=setTimeout(()=>p(!1),50);return()=>clearTimeout(k)}else p(!1)},[e,c]);const h=u.useMemo(()=>q_(t),[t]),v=e0(h),b=u.useMemo(()=>h.slice(-Zb),[h]),w=u.useMemo(()=>{const N=new Set;return b.forEach(k=>{N.add(k.id)}),N},[b]),j=u.useMemo(()=>e0(b),[b]),F=Math.max(0,h.length-Zb);if(h.length===0)return null;const A=e?h:b,C=e?v:j,S=F>0;return s.jsx(Xr,{children:s.jsxs("div",{className:"my-1",children:[s.jsxs("div",{className:Z("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl",S&&"cursor-pointer"),onClick:S?n:void 0,children:[s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[s.jsx("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:S?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:Z("absolute inset-0 transition-opacity",e&&"opacity-0",!e&&!o&&"group-hover/tool:opacity-0"),style:{color:"var(--tools-icon)"},children:s.jsx(fa,{className:"h-3.5 w-3.5"})}),s.jsx("div",{className:Z("absolute inset-0 transition-opacity flex items-center justify-center",e&&"opacity-100",!e&&o&&"opacity-0",!e&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:e?s.jsx(Us,{className:"h-3.5 w-3.5"}):s.jsx(ar,{className:"h-3.5 w-3.5"})})]}):s.jsx(fa,{className:"h-3.5 w-3.5",style:{color:"var(--tools-icon)"}})}),s.jsx("span",{className:"typography-meta font-medium",style:{color:"var(--tools-title)"},children:"Activity"})]}),d&&(d.additions>0||d.deletions>0)&&s.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:s.jsxs("span",{className:"flex-shrink-0 leading-none",children:[s.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,d.additions)]}),s.jsx("span",{className:"text-muted-foreground/50",children:"/"}),s.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,d.deletions)]})]})})]}),s.jsxs("div",{className:Z("relative pr-2 pb-1 pt-1 pl-[1.4375rem]"),children:[s.jsx("div",{className:"absolute left-[0.4375rem] w-px top-[-0.25rem] bottom-0",style:{backgroundColor:"var(--tools-border)",borderWidth:"0",width:"1px"}}),!e&&F>0&&s.jsxs("div",{className:"typography-micro text-muted-foreground/70 mb-1 cursor-pointer hover:text-muted-foreground",onClick:n,children:["+",F," more..."]}),A.map(N=>{const k=N.id,D=C[k],M=`${k}-exp${g}`,E=w.has(N.id);let _=!1;switch(m&&E?_=!0:e||(x.current.has(N.id)?_=!0:x.current.add(N.id)),N.kind){case"tool":return s.jsx(Xr,{skipAnimation:_,children:s.jsx(Zh,{part:N.part,isExpanded:a.has(k),onToggle:()=>i(k),syntaxTheme:r,isMobile:o,onContentChange:c,onShowPopup:l,hasPrevTool:D?.hasPrev??!1,hasNextTool:D?.hasNext??!1})},M);case"reasoning":return s.jsx(Xr,{skipAnimation:_,children:s.jsx(tj,{part:N.part,messageId:N.messageId,onContentChange:c})},M);case"justification":return s.jsx(Xr,{skipAnimation:_,children:s.jsx(G_,{part:N.part,messageId:N.messageId,onContentChange:c})},M);default:return null}})]})]})})},Q_=u.memo(K_),ux=t=>{const e=t,n=e.text;return typeof n=="string"?n:e.content||e.value||""},sj=t=>{if(t.type!=="text")return!1;const e=ux(t);return!e||e.trim().length===0},Y_=(t,e={})=>{const{includeReasoning:n=!0}=e,r=t.some(o=>!o.synthetic);return t.filter(o=>{const i=!!o.synthetic;return i&&o.type==="text"&&ux(o).includes("<system-reminder>")||i&&r||!n&&o.type==="reasoning"?!1:!(o.type==="patch")})};function fx(t){const e=Me.c(3);let n;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"}),e[0]=n):n=e[0];let r;return e[1]!==t?(r=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...t,children:n}),e[1]=t,e[2]=r):r=e[2],r}function J_(){const[t,e]=De.useState(!1),{voiceProvider:n,speechRate:r,speechPitch:o,speechVolume:a,sayVoice:i,browserVoice:l,openaiVoice:c,summarizeMessageTTS:d,summarizeCharacterThreshold:f}=rs(),{speak:m,stop:p,isAvailable:g}=w2(),{speak:y,stop:x,isAvailable:h}=j2(),v=De.useCallback(()=>{e(!1),p(),x(),pn.cancelSpeech()},[p,x]),b=De.useCallback(async w=>{if(w.trim()){v(),e(!0);try{let j=w;if(d&&k2(w,"message")?j=await S2(w,{threshold:f}):j=N2(w),n==="openai"&&g)await m(j,{voice:c,speed:r,summarize:!1,onEnd:()=>e(!1),onError:()=>e(!1)});else if(n==="say"&&h){const F=Math.round(100+(r-.5)*200);await y(j,{voice:i,rate:F,onEnd:()=>e(!1),onError:()=>e(!1)})}else await pn.waitForVoices(),await pn.resumeAudioContext(),await pn.speakText(j,navigator.language||"en-US",()=>e(!1),{rate:r,pitch:o,volume:a,voiceName:l||void 0})}catch(j){console.error("[useMessageTTS] Playback error:",j),e(!1)}}},[n,r,o,a,i,l,c,d,f,g,h,m,y,v]);return{isPlaying:t,play:b,stop:v}}const X_=200,Z_=t=>{const e=Me.c(70),{containerRef:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={x:0,y:0,show:!1},e[0]=r):r=e[0];const[o,a]=u.useState(r),[i,l]=u.useState(""),[c,d]=u.useState(!1),[f,m]=u.useState(!1),[p,g]=u.useState(!1),y=u.useRef(null),x=u.useRef(null),h=u.useRef(null),v=u.useRef(null),b=Re(eP),w=Re(tP),j=Te(sP);let F,A;e[1]===Symbol.for("react.memo_cache_sentinel")?(F=()=>()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),v.current!==null&&(window.cancelAnimationFrame(v.current),v.current=null)},A=[],e[1]=F,e[2]=A):(F=e[1],A=e[2]),u.useEffect(F,A);let C;e[3]===Symbol.for("react.memo_cache_sentinel")?(C=()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),v.current!==null&&(window.cancelAnimationFrame(v.current),v.current=null),g(!1),m(!0),h.current=window.setTimeout(()=>{a(nP),l(""),x.current=null,m(!1),h.current=null},X_)},e[3]=C):C=e[3];const S=C;let N;e[4]!==o.show?(N=()=>{if(!x.current)return;h.current!==null&&(window.clearTimeout(h.current),h.current=null),m(!1);const{text:Y,rect:re}=x.current,ue=!o.show,Q=re.left+re.width/2,O=re.top-10;l(Y),a({x:Q,y:O,show:!0}),ue&&(g(!0),v.current!==null&&window.cancelAnimationFrame(v.current),v.current=window.requestAnimationFrame(()=>{g(!1),v.current=null}))},e[4]=o.show,e[5]=N):N=e[5];const k=N;let D;e[6]!==n||e[7]!==c||e[8]!==k?(D=()=>{const Y=window.getSelection(),re=n.current;if(!Y||!re){c||S();return}const ue=Y.toString().trim();if(!ue){c||S();return}const Q=Y.getRangeAt(0);if(!re.contains(Q.commonAncestorContainer)){c||S();return}const O=Q.getBoundingClientRect();x.current={text:ue,rect:O},c||k()},e[6]=n,e[7]=c,e[8]=k,e[9]=D):D=e[9];const M=D;let E,_;e[10]!==n||e[11]!==M||e[12]!==k?(E=()=>{const Y=n.current;if(!Y)return;const re=()=>{d(!0),S()},ue=()=>{d(!1),x.current&&setTimeout(()=>{const O=window.getSelection();O&&O.toString().trim()?k():S()},10)};document.addEventListener("selectionchange",M),Y.addEventListener("mousedown",re),document.addEventListener("mouseup",ue);const Q=O=>{y.current&&!y.current.contains(O.target)&&!window.getSelection()?.toString().trim()&&S()};return document.addEventListener("mousedown",Q),()=>{document.removeEventListener("selectionchange",M),Y.removeEventListener("mousedown",re),document.removeEventListener("mouseup",ue),document.removeEventListener("mousedown",Q)}},_=[n,M,S,k],e[10]=n,e[11]=M,e[12]=k,e[13]=E,e[14]=_):(E=e[13],_=e[14]),u.useEffect(E,_);let T;e[15]!==i||e[16]!==w?(T=()=>{i&&(w(i,"append"),S(),window.getSelection()?.removeAllRanges())},e[15]=i,e[16]=w,e[17]=T):T=e[17];const P=T;let H;e[18]!==b||e[19]!==i||e[20]!==w?(H=async()=>{if(!i)return;await b(void 0,null,null)&&w(i,"replace"),S(),window.getSelection()?.removeAllRanges()},e[18]=b,e[19]=i,e[20]=w,e[21]=H):H=e[21];const R=H;let I;e[22]!==i?(I=async()=>{if(!i)return;const Y=await Cn(i);Y.ok||console.error("Failed to copy:",Y.error),S(),window.getSelection()?.removeAllRanges()},e[22]=i,e[23]=I):I=e[23];const B=I;if(!o.show)return null;if(j){const Y=f?"opacity-0 translate-y-[4px] pointer-events-none":p?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0";let re;e[24]!==Y?(re=Z("fixed left-0 right-0 bottom-0 z-50","flex items-center justify-center gap-4","bg-[var(--surface-elevated)] border-t border-[var(--interactive-border)]","px-3 py-2","safe-area-bottom","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",Y),e[24]=Y,e[25]=re):re=e[25];let ue;e[26]===Symbol.for("react.memo_cache_sentinel")?(ue={paddingBottom:"calc(0.5rem + env(safe-area-inset-bottom, 0px))"},e[26]=ue):ue=e[26];let Q;e[27]===Symbol.for("react.memo_cache_sentinel")?(Q=Z("flex items-center gap-2 px-3 py-2 rounded-lg","text-sm font-medium","bg-[var(--primary-base)] text-[var(--primary-foreground)]","active:opacity-80","transition-opacity duration-150"),e[27]=Q):Q=e[27];let O,se;e[28]===Symbol.for("react.memo_cache_sentinel")?(O=s.jsx(sn,{className:"h-5 w-5"}),se=s.jsx("span",{children:"Add to chat"}),e[28]=O,e[29]=se):(O=e[28],se=e[29]);let X;e[30]!==P?(X=s.jsxs("button",{onClick:P,className:Q,type:"button",children:[O,se]}),e[30]=P,e[31]=X):X=e[31];let L;e[32]===Symbol.for("react.memo_cache_sentinel")?(L=Z("flex items-center gap-2 px-3 py-2 rounded-lg","text-sm font-medium","bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]","active:opacity-80","transition-opacity duration-150"),e[32]=L):L=e[32];let me,fe;e[33]===Symbol.for("react.memo_cache_sentinel")?(me=s.jsx(xh,{className:"h-5 w-5"}),fe=s.jsx("span",{children:"New session"}),e[33]=me,e[34]=fe):(me=e[33],fe=e[34]);let pe;e[35]!==R?(pe=s.jsxs("button",{onClick:R,className:L,type:"button",children:[me,fe]}),e[35]=R,e[36]=pe):pe=e[36];let de;e[37]===Symbol.for("react.memo_cache_sentinel")?(de=Z("flex items-center gap-2 px-3 py-2 rounded-lg","text-sm font-medium","bg-[var(--surface-muted)] text-[var(--surface-foreground)]","active:opacity-80","transition-opacity duration-150"),e[37]=de):de=e[37];let ne,ge;e[38]===Symbol.for("react.memo_cache_sentinel")?(ne=s.jsx(ir,{className:"h-5 w-5"}),ge=s.jsx("span",{children:"Copy"}),e[38]=ne,e[39]=ge):(ne=e[38],ge=e[39]);let we;e[40]!==B?(we=s.jsxs("button",{onClick:B,className:de,type:"button",children:[ne,ge]}),e[40]=B,e[41]=we):we=e[41];let Oe;return e[42]!==re||e[43]!==X||e[44]!==pe||e[45]!==we?(Oe=Na.createPortal(s.jsxs("div",{ref:y,className:re,style:ue,children:[X,pe,we]}),document.body),e[42]=re,e[43]=X,e[44]=pe,e[45]=we,e[46]=Oe):Oe=e[46],Oe}let z;e[47]!==o.x||e[48]!==o.y?(z={left:o.x,top:o.y,transform:"translate(-50%, -100%)"},e[47]=o.x,e[48]=o.y,e[49]=z):z=e[49];const U=f?"opacity-0 translate-y-[4px] pointer-events-none":p?"opacity-0 translate-y-[4px]":"opacity-100 translate-y-0";let K;e[50]!==U?(K=Z("flex items-center gap-1","rounded-lg border border-[var(--interactive-border)]","bg-[var(--surface-elevated)] shadow-none","px-1.5 py-1","transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]",U),e[50]=U,e[51]=K):K=e[51];let V;e[52]===Symbol.for("react.memo_cache_sentinel")?(V=Z("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),e[52]=V):V=e[52];let q,$;e[53]===Symbol.for("react.memo_cache_sentinel")?(q=s.jsx(sn,{className:"h-4 w-4"}),$=s.jsx("span",{children:"Add to chat"}),e[53]=q,e[54]=$):(q=e[53],$=e[54]);let G;e[55]!==P?(G=s.jsxs("button",{onClick:P,className:V,title:"Add to current chat",type:"button",children:[q,$]}),e[55]=P,e[56]=G):G=e[56];let W;e[57]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx("div",{className:"w-px h-4 bg-[var(--interactive-border)]"}),e[57]=W):W=e[57];let J;e[58]===Symbol.for("react.memo_cache_sentinel")?(J=Z("flex items-center gap-1.5 px-2 py-1 rounded-md","text-sm font-medium","text-[var(--surface-foreground)]","hover:bg-[var(--interactive-hover)]","transition-colors duration-150"),e[58]=J):J=e[58];let te,le;e[59]===Symbol.for("react.memo_cache_sentinel")?(te=s.jsx(xh,{className:"h-4 w-4"}),le=s.jsx("span",{children:"New session"}),e[59]=te,e[60]=le):(te=e[59],le=e[60]);let ae;e[61]!==R?(ae=s.jsxs("button",{onClick:R,className:J,title:"Create new session with selection",type:"button",children:[te,le]}),e[61]=R,e[62]=ae):ae=e[62];let ie;e[63]!==K||e[64]!==G||e[65]!==ae?(ie=s.jsxs("div",{className:K,children:[G,W,ae]}),e[63]=K,e[64]=G,e[65]=ae,e[66]=ie):ie=e[66];let oe;return e[67]!==z||e[68]!==ie?(oe=Na.createPortal(s.jsx("div",{ref:y,className:"fixed z-50",style:z,children:ie}),document.body),e[67]=z,e[68]=ie,e[69]=oe):oe=e[69],oe};function eP(t){return t.createSession}function tP(t){return t.setPendingInputText}function sP(t){return t.isMobile}function nP(t){return{...t,show:!1}}const t0=t=>t.type==="subtask",s0=t=>{const e=t;return e.type==="text"&&typeof e.shellAction=="object"&&e.shellAction!==null},rP=t=>{if(!t||typeof t!="object")return null;const e=typeof t.providerID=="string"?t.providerID.trim():"",n=typeof t.modelID=="string"?t.modelID.trim():"";return!e||!n?null:`${e}/${n}`},oP=t=>{const e=Me.c(36),{part:n}=t,[r,o]=u.useState(!1),a=Re(fP);let i;e[0]!==n.description?(i=typeof n.description=="string"?n.description.trim():"",e[0]=n.description,e[1]=i):i=e[1];const l=i;let c;e[2]!==n.command?(c=typeof n.command=="string"?n.command.trim():"",e[2]=n.command,e[3]=c):c=e[3];const d=c;let f;e[4]!==n.agent?(f=typeof n.agent=="string"?n.agent.trim():"",e[4]=n.agent,e[5]=f):f=e[5];const m=f;let p;e[6]!==n.prompt?(p=typeof n.prompt=="string"?n.prompt.trim():"",e[6]=n.prompt,e[7]=p):p=e[7];const g=p;let y;e[8]!==n.taskSessionID?(y=typeof n.taskSessionID=="string"?n.taskSessionID.trim():"",e[8]=n.taskSessionID,e[9]=y):y=e[9];const x=y;let h;e[10]!==n.model?(h=rP(n.model),e[10]=n.model,e[11]=h):h=e[11];const v=h;let b;e[12]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Delegated task"}),e[12]=b):b=e[12];let w;e[13]!==d?(w=d?s.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:["/",d]}):null,e[13]=d,e[14]=w):w=e[14];let j;e[15]!==m?(j=m?s.jsxs("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:["@",m]}):null,e[15]=m,e[16]=j):j=e[16];let F;e[17]!==v?(F=v?s.jsx("span",{className:"inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground",children:v}):null,e[17]=v,e[18]=F):F=e[18];let A;e[19]!==F||e[20]!==w||e[21]!==j?(A=s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[b,w,j,F]}),e[19]=F,e[20]=w,e[21]=j,e[22]=A):A=e[22];let C;e[23]!==l?(C=l?s.jsx("div",{className:"typography-ui-label text-foreground/90 mt-1.5",children:l}):null,e[23]=l,e[24]=C):C=e[24];let S;e[25]!==r||e[26]!==g?(S=g?s.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[s.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>o(mP),children:r?"Hide prompt":"Show prompt"}),r?s.jsx("pre",{className:"typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/85",children:g}):null]}):null,e[25]=r,e[26]=g,e[27]=S):S=e[27];let N;e[28]!==a||e[29]!==x?(N=x?s.jsx("div",{className:"mt-1.5",children:s.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>{a(x)},children:"Open subtask session"})}):null,e[28]=a,e[29]=x,e[30]=N):N=e[30];let k;return e[31]!==A||e[32]!==C||e[33]!==S||e[34]!==N?(k=s.jsxs("div",{className:"mt-2",children:[A,C,S,N]}),e[31]=A,e[32]=C,e[33]=S,e[34]=N,e[35]=k):k=e[35],k},aP=t=>{const e=Me.c(29),{part:n}=t,[r,o]=u.useState(!1),[a,i]=u.useState(!1),l=u.useRef(null);let c;e[0]!==n.shellAction?(c=typeof n.shellAction?.command=="string"?n.shellAction.command.trim():"",e[0]=n.shellAction,e[1]=c):c=e[1];const d=c,f=typeof n.shellAction?.output=="string"?n.shellAction.output:"";let m;e[2]!==n.shellAction?(m=typeof n.shellAction?.status=="string"?n.shellAction.status.trim().toLowerCase():"",e[2]=n.shellAction,e[3]=m):m=e[3];const p=m;let g;e[4]!==f?(g=f.trim(),e[4]=f,e[5]=g):g=e[5];const y=g.length>0;let x;e[6]===Symbol.for("react.memo_cache_sentinel")?(x=()=>{l.current!==null&&typeof window<"u"&&(window.clearTimeout(l.current),l.current=null)},e[6]=x):x=e[6];const h=x;let v,b;e[7]===Symbol.for("react.memo_cache_sentinel")?(v=()=>()=>{h()},b=[h],e[7]=v,e[8]=b):(v=e[7],b=e[8]),u.useEffect(v,b);let w;e[9]!==y||e[10]!==f?(w=async()=>{!y||!(await Cn(f)).ok||(h(),i(!0),typeof window<"u"&&(l.current=window.setTimeout(()=>{i(!1),l.current=null},2e3)))},e[9]=y,e[10]=f,e[11]=w):w=e[11];const j=w;let F;e[12]===Symbol.for("react.memo_cache_sentinel")?(F=s.jsx("span",{className:"typography-meta font-semibold text-foreground",children:"Shell command"}),e[12]=F):F=e[12];let A;e[13]!==p?(A=p?s.jsx("span",{className:Z("inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none",p==="error"?"bg-[var(--status-error-background)] text-[var(--status-error)]":"bg-foreground/5 text-muted-foreground"),children:p}):null,e[13]=p,e[14]=A):A=e[14];let C;e[15]!==A?(C=s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[F,A]}),e[15]=A,e[16]=C):C=e[16];let S;e[17]!==d?(S=d?s.jsx("pre",{className:"typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/90 font-mono",children:d}):null,e[17]=d,e[18]=S):S=e[18];let N;e[19]!==a||e[20]!==j||e[21]!==r||e[22]!==y||e[23]!==f?(N=y?s.jsxs("div",{className:"mt-2 border-t border-border/60 pt-1.5",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx("button",{type:"button",className:"typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2",onClick:()=>o(pP),children:r?"Hide output":"Show output"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:()=>{j()},"aria-label":a?"Copied":"Copy output",title:a?"Copied":"Copy output",children:a?s.jsx(Ts,{className:"h-3.5 w-3.5"}):s.jsx(ir,{className:"h-3.5 w-3.5"})})]}),r?s.jsx("pre",{className:"typography-meta mt-1.5 max-h-56 overflow-auto whitespace-pre-wrap break-words text-foreground/85 font-mono",children:f}):null]}):null,e[19]=a,e[20]=j,e[21]=r,e[22]=y,e[23]=f,e[24]=N):N=e[24];let k;return e[25]!==C||e[26]!==S||e[27]!==N?(k=s.jsxs("div",{className:"mt-2",children:[C,S,N]}),e[25]=C,e[26]=S,e[27]=N,e[28]=k):k=e[28],k},iP=t=>{const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e/60),r=Math.round(e%60);return`${n}m ${r}s`},lP=new Set(["task"]),$u=t=>typeof t=="string"&&lP.has(t.toLowerCase()),cP=({messageId:t,parts:e,isMobile:n,hasTouchInput:r,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:l,agentMention:c,onRevert:d,onFork:f})=>{const[m,p]=u.useState(!1),g=u.useRef(null),y=u.useMemo(()=>e.filter(S=>S.type==="text"?!sj(S):!!(t0(S)||s0(S))),[e]),x=c?.token;let h=!1;const v=!!a,b=!!i,w=!!(r??n),j=!!o,F=u.useCallback(()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),A=u.useCallback(()=>{!w||!v||!j||typeof window>"u"||(F(),p(!0),g.current=window.setTimeout(()=>{p(!1),g.current=null},1800))},[v,F,j,w]);u.useEffect(()=>{j||(p(!1),F())},[F,j]);const C=u.useCallback(S=>{!a||!j||(S.stopPropagation(),S.preventDefault(),a(),w&&A())},[j,w,a,A]);return s.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&v&&j?A:void 0,children:[s.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:y.map((S,N)=>{if(t0(S))return s.jsx(Xr,{children:s.jsx(oP,{part:S})},S.id??`user-subtask-${N}`);if(s0(S))return s.jsx(Xr,{children:s.jsx(aP,{part:S})},S.id??`user-shell-${N}`);let k;return c&&x&&!h&&ux(S).includes(x)&&(k=c,h=!0),s.jsx(Xr,{children:s.jsx(H9,{part:S,messageId:t,isMobile:n,agentMention:k})},S.id??`user-text-${N}`)})}),s.jsx(A2,{files:e,onShowPopup:l,compact:!0}),v&&j||d||f?s.jsx("div",{className:Z("absolute top-full left-0 right-0 z-10 group/user-actions",n?"pt-2 pb-3":"pt-5"),children:s.jsxs("div",{className:Z("flex translate-x-5 items-center justify-end gap-1",n?"pointer-events-auto opacity-100":"pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100"),children:[d&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Revert to this message",onPointerDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),d()},children:s.jsx(Ii,{className:"h-3 w-3"})})}),s.jsx(Kt,{sideOffset:6,children:"Revert from here"})]}),f&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),f()},children:s.jsx(bn,{className:"h-3 w-3"})})}),s.jsx(Kt,{sideOffset:6,children:"Fork from here"})]}),v&&j&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon","data-visible":m||b?"true":void 0,className:"h-6 w-6 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:S=>S.stopPropagation(),onClick:C,onFocus:()=>p(!0),onBlur:()=>{b||p(!1)},children:b?s.jsx(Ts,{className:"h-3 w-3 text-[color:var(--status-success)]"}):s.jsx(ir,{className:"h-3 w-3"})})}),s.jsx(Kt,{sideOffset:6,children:"Copy message"})]})]})}):null]})},dP=({messageId:t,parts:e,isMessageCompleted:n,messageFinish:r,messageCompletedAt:o,syntaxTheme:a,isMobile:i,hasTouchInput:l,expandedTools:c,onToggleTool:d,onShowPopup:f,streamPhase:m,allowAnimation:p,onContentChange:g,hasTextContent:y=!1,onCopyMessage:x,copiedMessage:h=!1,onAuxiliaryContentComplete:v,showReasoningTraces:b=!1,turnGroupingContext:w,errorMessage:j})=>{const[F,A]=u.useState(!1),C=u.useRef(null),S=u.useRef(null),N=!!x,k=!!h,D=!!(l??i),M=!n,E=u.useMemo(()=>e.filter(Se=>!sj(Se)).filter(Se=>Se.type!=="compaction"),[e]),_=u.useMemo(()=>E.filter(Se=>Se.type==="tool"),[E]),T=u.useMemo(()=>E.filter(Se=>Se.type==="text"),[E]),P=Re(Se=>Se.createSessionFromAssistantMessage),H=Te(Se=>Se.openMultiRunLauncherWithPrompt),R=w?.isLastAssistantInTurn??!1,I=r==="stop",{isPlaying:B,play:z,stop:U}=J_(),K=rs(Se=>Se.showMessageTTSButtons),V=rs(Se=>Se.voiceProvider),q=u.useMemo(()=>B?"Stop speaking":`Read aloud (${V==="browser"?"Browser":V==="openai"?"OpenAI":"Say"} voice)`,[B,V]),$=_.length>0,G=u.useMemo(()=>_.some(Se=>{const st=(Se.state??{})?.status;return st==="pending"||st==="running"||st==="started"}),[_]),W=u.useCallback(Se=>{const Le=Se.state??{},st=Le?.status;if(st==="pending"||st==="running"||st==="started")return!1;const Ke=Le?.time??{},it=typeof Ke?.end=="number"?Ke.end:void 0,pt=typeof Ke?.start=="number"?Ke.start:void 0;return!(typeof it!="number"||typeof pt=="number"&&it<pt)},[]),J=u.useMemo(()=>_.length===0?!0:G?!1:_.every(Se=>W(Se)),[_,G,W]),te=u.useMemo(()=>E.filter(Se=>Se.type==="reasoning"),[E]),le=u.useMemo(()=>te.length===0?!0:te.every(Se=>typeof Se.time?.end=="number"),[te]),ae=typeof r!="string",ie=te.length>0&&$&&(G||ae||!J),oe=M||$&&(G||ae||!J),Y=M||ie,re=$||te.length>0,ue=T.length===0,Q=re&&ue&&!oe&&!Y&&J&&le,O=u.useRef(!1),se=u.useRef(!1);u.useEffect(()=>{se.current=!1},[t]),u.useEffect(()=>{if(!Q){O.current=!1;return}O.current||(O.current=!0,v?.())},[Q,v]),u.useEffect(()=>{if(M){se.current=!1;return}if($){se.current=!1;return}te.length!==0&&(Y||!le||se.current||(se.current=!0,g?.("structural")))},[M,$,g,le,te.length,Y]);const X=!!y&&!M,L=u.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),me=u.useCallback(()=>{!D||!N||!X||typeof window>"u"||(L(),A(!0),C.current=window.setTimeout(()=>{A(!1),C.current=null},1800))},[N,L,X,D]);u.useEffect(()=>{X||(A(!1),L())},[L,X]);const fe=u.useCallback(Se=>{!x||!X||(Se.stopPropagation(),Se.preventDefault(),x(),D&&me())},[X,D,x,me]),pe=u.useCallback(Se=>{Se.stopPropagation(),Se.preventDefault(),P&&P(t)},[P,t]),de=u.useCallback(Se=>{Se.stopPropagation(),Se.preventDefault();const Le=Vf(T);if(!Le.trim())return;const st=`${rA}
128
128
 
129
- ${Le}`;H(st)},[T,H]),ne=u.useCallback(Se=>{if(Se.stopPropagation(),Se.preventDefault(),B){U();return}const Le=Vf(T);Le.trim()&&z(Le)},[T,B,z,U]);u.useEffect(()=>()=>{L()},[L]);const ge=u.useMemo(()=>{const Se={},Le=_.filter(st=>$u(st.tool)||oe?!1:W(st));return Le.forEach((st,Ke)=>{Se[st.id]={hasPrev:Ke>0,hasNext:Ke<Le.length-1}}),Se},[_,oe,W]),we=u.useMemo(()=>w?.activityParts??[],[w]),Oe=u.useMemo(()=>w?we.filter(Se=>Se.messageId===t):[],[we,t,w]),et=u.useMemo(()=>w?w.activityGroupSegments.filter(Se=>Se.anchorMessageId===t):[],[t,w]),$e=u.useMemo(()=>{const Se=new Map;return Oe.forEach(Le=>{Se.set(Le.part,Le)}),Se},[Oe]),Ae=u.useMemo(()=>w?(b?we:we.filter(Le=>Le.kind!=="reasoning")).filter(Le=>{if(Le.kind!=="tool")return!0;const st=Le.part.tool;return!$u(st)}):[],[we,b,w]),[Ie,be]=u.useState(!1);u.useEffect(()=>{if(!w)return;const Se=w.activityGroupSegments.some(st=>st.afterToolPartId!==null),Le=Ae.some(st=>st.kind==="reasoning");(Ae.length>1||Se&&Ae.length>0||Le)&&be(!0)},[w,Ae]);const ee=!!(w&&Ie),he=!!(w&&ee&&Ae.length>0&&et.length>0),ye=u.useMemo(()=>_.filter(Se=>$u(Se.tool)),[_]),We=u.useMemo(()=>{const Se=[],Le=Ke=>{!w||!he||et.filter(it=>(it.afterToolPartId??null)===Ke).forEach(it=>{const pt=b?it.parts:it.parts.filter(Ut=>Ut.kind!=="reasoning");pt.length!==0&&Se.push(s.jsx(Q_,{parts:pt,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:a,isMobile:i,expandedTools:c,onToggleTool:d,onShowPopup:f,onContentChange:g,diffStats:w.diffStats},`progressive-group-${it.id}`))})};Le(null),ye.forEach(Ke=>{Se.push(s.jsx(Xr,{children:s.jsx(Zh,{part:Ke,isExpanded:c.has(Ke.id),onToggle:d,syntaxTheme:a,isMobile:i,onContentChange:g,onShowPopup:f,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ke.id}`)),Le(Ke.id)});const st=[];return E.forEach((Ke,it)=>{const pt=$e.get(Ke);if(!pt||!w)return;let Ut=null,ss=null;if(!ee){if(pt.kind==="tool"){const Wt=Ke;if($u(Wt.tool))return;const kt=Wt.state?.time,ht=W(Wt);if(!(!oe&&ht))return;const gt=ge[Wt.id];ss=s.jsx(Xr,{children:s.jsx(Zh,{part:Wt,isExpanded:c.has(Wt.id),onToggle:d,syntaxTheme:a,isMobile:i,onContentChange:g,onShowPopup:f,hasPrevTool:gt?.hasPrev??!1,hasNextTool:gt?.hasNext??!1})},`tool-${Wt.id}`),Ut=ht&&typeof kt?.end=="number"?kt.end:null}else if(pt.kind==="reasoning"&&b){const Wt=Ke.time,dt=typeof Wt?.end=="number"?Wt.end:null;ss=s.jsx(Xr,{children:s.jsx(tj,{part:Ke,messageId:t,onContentChange:g})},`reasoning-${pt.id}`),Ut=dt}ss&&st.push({part:Ke,index:it,endTime:Ut,element:ss})}}),st.sort((Ke,it)=>Ke.endTime===null&&it.endTime===null?Ke.index-it.index:Ke.endTime===null?1:it.endTime===null?-1:Ke.endTime-it.endTime),st.forEach(({element:Ke})=>{Se.push(Ke)}),Se},[$e,et,c,i,W,t,g,f,d,oe,ee,b,a,ge,w,E,ye,he]),Ee=w?.turnId,ze=Re(Se=>Se.currentSessionId),Ze=Os(Se=>{if(!Ee||!ze)return;const Le=Se.messages.get(ze);if(!Le)return;const st=Le.find(pt=>pt.info?.id===Ee);if(!st)return;const it=st.info.summary?.body;return typeof it=="string"&&it.trim().length>0?it:void 0}),Fe=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:Ze,tt=u.useRef(void 0);Fe&&Fe.trim().length>0&&(tt.current=Fe);const He=u.useRef(Ee);He.current!==Ee&&(He.current=Ee,tt.current=void 0);const _e=tt.current,je=w?.isLastAssistantInTurn&&_e&&_e.trim().length>0,Ye=!!j,Ne=R&&y&&(I||!!j),Pe=u.useMemo(()=>{if(!R||!I)return;const Se=w?.userMessageCreatedAt;if(!(typeof Se!="number"||typeof o!="number")&&!(o<=Se))return iP(o-Se)},[R,I,w?.userMessageCreatedAt,o]),Qe=s.jsxs(s.Fragment,{children:[x&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon","data-visible":F||k?"true":void 0,className:Z("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!X&&"opacity-50"),disabled:!X,"aria-label":"Copy message text","aria-hidden":!X,onPointerDown:Se=>Se.stopPropagation(),onClick:fe,onFocus:()=>{X&&A(!0)},onBlur:()=>{k||A(!1)},children:k?s.jsx(Ts,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):s.jsx(ir,{className:"h-3.5 w-3.5"})})}),s.jsx(Kt,{sideOffset:6,children:"Copy answer"})]}),s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:Se=>Se.stopPropagation(),onClick:pe,children:s.jsx(xh,{className:"h-4 w-4"})})}),s.jsx(Kt,{sideOffset:6,children:"Start new session from this answer"})]}),s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:Se=>Se.stopPropagation(),onClick:de,children:s.jsx(fx,{className:"h-4 w-4"})})}),s.jsx(Kt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),K&&X&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon",className:Z("h-8 w-8 bg-transparent hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",B?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":B?"Stop speaking":"Read aloud",onPointerDown:Se=>Se.stopPropagation(),onClick:ne,children:B?s.jsx(ra,{className:"h-3.5 w-3.5"}):s.jsx(Cg,{className:"h-3.5 w-3.5"})})}),s.jsx(Kt,{sideOffset:6,children:q})]})]});return s.jsxs("div",{ref:S,className:Z("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:D&&N&&X?me:void 0,children:[s.jsx(Z_,{containerRef:S}),s.jsxs("div",{children:[s.jsxs("div",{className:"message-content-text leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[We,Ye&&s.jsx(Xr,{children:s.jsx("div",{className:"group/assistant-text relative break-words",children:s.jsx(Kr,{content:j??"",onShowPopup:f})})},"assistant-error"),je&&s.jsx(Xr,{children:s.jsxs("div",{className:"group/assistant-text relative break-words",children:[s.jsx(Kr,{content:_e,onShowPopup:f}),Ne&&s.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5",children:[s.jsx("div",{className:"flex items-center gap-1.5",children:Qe}),Pe?s.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[s.jsx(Mx,{className:"h-3.5 w-3.5"}),Pe]}):null]})]})},"summary-body")]}),s.jsx(A2,{files:e,onShowPopup:f}),!je&&Ne&&s.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5",children:[s.jsx("div",{className:"flex items-center gap-1.5",children:Qe}),Pe?s.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[s.jsx(Mx,{className:"h-3.5 w-3.5"}),Pe]}):null]})]})]})},uP=t=>{const e=Me.c(17);let n,r;if(e[0]!==t?({isUser:n,...r}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]),n){let a;return e[3]!==r.agentMention||e[4]!==r.copiedMessage||e[5]!==r.hasTextContent||e[6]!==r.hasTouchInput||e[7]!==r.isMobile||e[8]!==r.messageId||e[9]!==r.onCopyMessage||e[10]!==r.onFork||e[11]!==r.onRevert||e[12]!==r.onShowPopup||e[13]!==r.parts?(a=s.jsx(cP,{messageId:r.messageId,parts:r.parts,isMobile:r.isMobile,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onRevert:r.onRevert,onFork:r.onFork}),e[3]=r.agentMention,e[4]=r.copiedMessage,e[5]=r.hasTextContent,e[6]=r.hasTouchInput,e[7]=r.isMobile,e[8]=r.messageId,e[9]=r.onCopyMessage,e[10]=r.onFork,e[11]=r.onRevert,e[12]=r.onShowPopup,e[13]=r.parts,e[14]=a):a=e[14],a}let o;return e[15]!==r?(o=s.jsx(dP,{...r}),e[15]=r,e[16]=o):o=e[16],o},n0=u.memo(uP);function fP(t){return t.setCurrentSession}function mP(t){return!t}function pP(t){return!t}const Ka=t=>{const e=t,n=e?.clientRole,r=e?.role;return e?.userMessageMarker===!0||n==="user"||r==="user"||e?.origin==="user"||e?.source==="user"?{role:"user",isUser:!0}:{role:n||r||"assistant",isUser:!1}},hP=u.lazy(()=>gr(()=>import("./ToolOutputDialog-BoRPV5fw.js"),__vite__mapDeps([2,0,1,3,4]))),gP=new Set(["task","edit","multiedit","write","apply_patch","bash","todowrite"]),xP=4e3,yi=new Map,r0=t=>{const e=yi.get(t);return e?new Set(e):new Set},yP=(t,e)=>{if(yi.size>=xP&&!yi.has(t)){const n=yi.keys().next().value;typeof n=="string"&&yi.delete(n)}yi.set(t,new Set(e))},o0=t=>typeof t=="string"&&gP.has(t.toLowerCase());function zp(t){const e=Me.c(3),[n,r]=u.useState(t);let o,a;return e[0]!==t?(o=()=>{t!=null&&r(t)},a=[t],e[0]=t,e[1]=o,e[2]=a):(o=e[1],a=e[2]),u.useEffect(o,a),t??n}const bo=(t,e)=>{if(typeof t=="object"&&t!==null)return t[e]},bP=t=>{const e=Me.c(227),{message:n,previousMessage:r,nextMessage:o,onContentChange:a,animationHandlers:i,turnGroupingContext:l}=t,{isMobile:c,hasTouchInput:d}=hn(),{currentTheme:f}=mo(),m=u.useRef(null);let p;e[0]!==n.info?(p=Xe=>({lifecyclePhase:Xe.messageStreamStates.get(n.info.id)?.phase??null,isStreamingMessage:(()=>{const os=n.info.sessionID??Xe.currentSessionId??null;return os?(Xe.streamingMessageIds.get(os)??null)===n.info.id:!1})(),currentSessionId:Xe.currentSessionId,getAgentModelForSession:Xe.getAgentModelForSession,getSessionModelSelection:Xe.getSessionModelSelection,revertToMessage:Xe.revertToMessage,forkFromMessage:Xe.forkFromMessage}),e[0]=n.info,e[1]=p):p=e[1];const g=Re(oa(p)),{lifecyclePhase:y,isStreamingMessage:x,currentSessionId:h,getAgentModelForSession:v,getSessionModelSelection:b,revertToMessage:w,forkFromMessage:j}=g,F=rs(vP),{showReasoningTraces:A,toolCallExpansion:C}=Te(oa(wP));let S,N;e[2]!==h?(S=()=>{h&&Va.getInstance().recordSessionStart(h)},N=[h],e[2]=h,e[3]=S,e[4]=N):(S=e[3],N=e[4]),u.useEffect(S,N);const[k,D]=u.useState(null),[M,E]=u.useState(!1);let _;e[5]!==n.info.id?(_=()=>r0(n.info.id),e[5]=n.info.id,e[6]=_):_=e[6];const[T,P]=u.useState(_);let H;e[7]===Symbol.for("react.memo_cache_sentinel")?(H={open:!1,title:"",content:""},e[7]=H):H=e[7];const[R,I]=u.useState(H);let B,z;e[8]!==n.info.id?(B=()=>{P(r0(n.info.id))},z=[n.info.id],e[8]=n.info.id,e[9]=B,e[10]=z):(B=e[9],z=e[10]),u.useEffect(B,z);let U;e[11]===Symbol.for("react.memo_cache_sentinel")?(U=()=>{yi.clear(),P(new Set)},e[11]=U):U=e[11];let K;e[12]!==C?(K=[C],e[12]=C,e[13]=K):K=e[13],u.useEffect(U,K);let V;e[14]!==n.info?(V=Ka(n.info),e[14]=n.info,e[15]=V):V=e[15];const $=V.isUser,G=n.info.sessionID;let W;e[16]!==G?(W=Xe=>({currentContextAgent:G?Xe.currentAgentContext.get(G):void 0,savedSessionAgentSelection:G?Xe.sessionAgentSelections.get(G):void 0}),e[16]=G,e[17]=W):W=e[17];const{currentContextAgent:J,savedSessionAgentSelection:te}=Ss(oa(W));let le;e:{if(!$){le=n.parts;break e}const Xe=jP;let os;if(e[18]!==n.parts){let Nt;e[20]===Symbol.for("react.memo_cache_sentinel")?(Nt=ms=>{if(!(ms?.synthetic===!0))return!0;if(ms.type!=="text")return!1;const Is=ms?.text;return typeof Is=="string"?Xe(Is):!1},e[20]=Nt):Nt=e[20],os=n.parts.filter(Nt).map(SP),e[18]=n.parts,e[19]=os}else os=e[19];le=os}const ae=le;let ie;e:{if($||!r){ie=null;break e}const Xe=bo(r.info,"clientRole"),os=bo(r.info,"role");if((typeof Xe=="string"?Xe:typeof os=="string"?os:void 0)!=="user"){ie=null;break e}let ms,hs,Is,rn;if(e[21]!==r.info){const lr=bo(r.info,"mode"),pr=bo(r.info,"agent"),cr=bo(r.info,"providerID"),_n=bo(r.info,"modelID"),ho=bo(r.info,"variant");ms=typeof lr=="string"&&lr.trim().length>0?lr:typeof pr=="string"&&pr.trim().length>0?pr:void 0,Is=typeof cr=="string"&&cr.trim().length>0?cr:void 0,hs=typeof _n=="string"&&_n.trim().length>0?_n:void 0,rn=typeof ho=="string"&&ho.trim().length>0?ho:void 0,e[21]=r.info,e[22]=ms,e[23]=hs,e[24]=Is,e[25]=rn}else ms=e[22],hs=e[23],Is=e[24],rn=e[25];const tr=rn;if(!ms&&!Is&&!hs&&!tr){ie=null;break e}let kn;e[26]!==ms||e[27]!==hs||e[28]!==Is||e[29]!==tr?(kn={agentName:ms,providerId:Is,modelId:hs,variant:tr},e[26]=ms,e[27]=hs,e[28]=Is,e[29]=tr,e[30]=kn):kn=e[30],ie=kn}const oe=ie;let Y;e:{if($||!r){Y=!1;break e}const Xe=Array.isArray(r.parts)?r.parts:[];for(let os=0;os<Xe.length;os++){const Nt=Xe[os];if(Nt?.type!=="text"||Nt?.synthetic!==!0)continue;const ms=typeof Nt.text=="string"?Nt.text.trim():"";if(ms.startsWith("User has requested to enter plan mode")||ms.startsWith("The plan at ")){Y=!0;break e}}Y=!1}const re=Y;let ue;e:{if($){ue=void 0;break e}const Xe=n.info.time;if(!(typeof Xe?.completed=="number"&&Xe.completed>0)&&re&&oe?.agentName){ue=oe.agentName;break e}let Nt,ms;if(e[31]!==n.info?(Nt=bo(n.info,"mode"),ms=typeof Nt=="string"&&Nt.trim().length>0,e[31]=n.info,e[32]=Nt,e[33]=ms):(Nt=e[32],ms=e[33]),ms){ue=Nt;break e}let hs,Is;if(e[34]!==n.info?(hs=bo(n.info,"agent"),Is=typeof hs=="string"&&hs.trim().length>0,e[34]=n.info,e[35]=hs,e[36]=Is):(hs=e[35],Is=e[36]),Is){ue=hs;break e}if(oe?.agentName){ue=oe.agentName;break e}if(!G){ue=void 0;break e}if(J){ue=J;break e}ue=te??void 0}const Q=ue;let O;e[37]!==$||e[38]!==n.info?(O=$?null:bo(n.info,"providerID"),e[37]=$,e[38]=n.info,e[39]=O):O=e[39];const se=O;let X;e[40]!==$||e[41]!==n.info?(X=$?null:bo(n.info,"modelID"),e[40]=$,e[41]=n.info,e[42]=X):X=e[42];const L=X;let me;e:{if($||!G){me=null;break e}if(oe?.providerId&&oe?.modelId){let Nt;e[43]!==oe.modelId||e[44]!==oe.providerId?(Nt={providerId:oe.providerId,modelId:oe.modelId},e[43]=oe.modelId,e[44]=oe.providerId,e[45]=Nt):Nt=e[45],me=Nt;break e}if(Q){let Nt;e[46]!==Q||e[47]!==v||e[48]!==G?(Nt=v(G,Q),e[46]=Q,e[47]=v,e[48]=G,e[49]=Nt):Nt=e[49];const ms=Nt;if(ms?.providerId&&ms?.modelId){me=ms;break e}}let Xe;e[50]!==b||e[51]!==G?(Xe=b(G),e[50]=b,e[51]=G,e[52]=Xe):Xe=e[52];const os=Xe;if(os?.providerId&&os?.modelId){me=os;break e}me=null}const fe=me;let pe;e:{if($){pe=null;break e}if(typeof se=="string"&&se.trim().length>0){pe=se;break e}pe=fe?.providerId??null}const de=pe;let ne;e:{if($){ne=null;break e}if(typeof L=="string"&&L.trim().length>0){ne=L;break e}ne=fe?.modelId??null}const ge=ne;let we;if(e[53]!==$||e[54]!==ge||e[55]!==de||e[56]!==F){e:{if($){we=void 0;break e}if(de&&ge&&F.length>0){let Xe;e[58]!==de?(Xe=Nt=>Nt.id===de,e[58]=de,e[59]=Xe):Xe=e[59];const os=F.find(Xe);if(os?.models&&Array.isArray(os.models)){let Nt;e[60]!==ge?(Nt=rn=>rn.id===ge,e[60]=ge,e[61]=Nt):Nt=e[61];const Is=os.models.find(Nt)?.name;we=typeof Is=="string"?Is:void 0;break e}}we=void 0}e[53]=$,e[54]=ge,e[55]=de,e[56]=F,e[57]=we}else we=e[57];const Oe=we;let et;e:{if($){et=!1;break e}if(!de||!ge){et=!1;break e}const Xe=F.find(ms=>ms.id===de);if(!Xe?.models||!Array.isArray(Xe.models)){et=!1;break e}const Nt=Xe.models.find(ms=>ms.id===ge)?.variants;et=!!(Nt&&Object.keys(Nt).length>0)}const $e=et,Ae=zp(Q),Ie=zp(de??void 0),be=zp(Oe),ee=Ae??void 0,he=Ie??null,ye=be??void 0,We=n.info.time,Ee=typeof We?.completed=="number"?We.completed:null;let ze;e:{if($){ze=!0;break e}ze=!!(Ee&&Ee>0)}const Ze=ze,Fe=n.info.finish,tt=typeof Fe=="string"?Fe:void 0;let He;e[62]!==ae||e[63]!==A?(He=Y_(ae,{includeReasoning:A}),e[62]=ae,e[63]=A,e[64]=He):He=e[64];const _e=He;let je;e:{if($){je=_e;break e}let Xe;e[65]!==Ze||e[66]!==_e?(Xe=Ze?_e:[],e[65]=Ze,e[66]=_e,e[67]=Xe):Xe=e[67],je=Xe}const Ye=je;let Ne;e:{if($){let os;e[68]===Symbol.for("react.memo_cache_sentinel")?(os=[],e[68]=os):os=e[68],Ne=os;break e}let Xe;e[69]!==_e?(Xe=_e.filter(kP),e[69]=_e,e[70]=Xe):Xe=e[70],Ne=Xe}const Pe=Ne;let Qe;e:{if($){let Nt;e[71]===Symbol.for("react.memo_cache_sentinel")?(Nt=[],e[71]=Nt):Nt=e[71],Qe=Nt;break e}let Xe;e[72]!==_e?(Xe=_e.filter(NP),e[72]=_e,e[73]=Xe):Xe=e[73],Qe=Xe}const Se=Qe;let Le;e:{if(C==="collapsed"||C==="activity"){Le=T;break e}let Xe;if(e[74]!==Se||e[75]!==l){Xe=new Set;for(const Nt of Se){const ms=Nt.tool;Nt.id&&o0(ms)&&Xe.add(Nt.id)}if(l?.isFirstAssistantInTurn)for(const Nt of l.activityParts){if(Nt.kind!=="tool")continue;const ms=Nt.part;o0(ms.tool)&&(ms.id&&Xe.add(ms.id),Nt.id&&Xe.add(Nt.id))}e[74]=Se,e[75]=l,e[76]=Xe}else Xe=e[76];let os;if(e[77]!==Xe||e[78]!==T){os=new Set(Xe);for(const Nt of T)os.has(Nt)?os.delete(Nt):os.add(Nt);e[77]=Xe,e[78]=T,e[79]=os}else os=e[79];Le=os}const st=Le;let Ke;if(e[80]!==$||e[81]!==n.parts){e:{if(!$){Ke=void 0;break e}const Xe=n.parts.find(CP);if(!Xe){Ke=void 0;break e}const os=Xe,Nt=typeof os.name=="string"?os.name:void 0;if(!Nt){Ke=void 0;break e}const ms=os.source&&typeof os.source.value=="string"&&os.source.value.trim().length>0?os.source.value:`@${Nt}`;let hs;e[83]!==Nt||e[84]!==ms?(hs={name:Nt,token:ms},e[83]=Nt,e[84]=ms,e[85]=hs):hs=e[85],Ke=hs}e[80]=$,e[81]=n.parts,e[82]=Ke}else Ke=e[82];const it=Ke,pt=$&&Ye.length===0,Ut=typeof tt!="string";let ss;e:{if($){ss=!1;break e}if(Pe.length===0||Se.length===0){ss=Ut;break e}ss=!0}const Wt=ss,dt=f?.metadata.variant;let kt;e:{if(dt){kt=dt==="dark";break e}if(typeof document<"u"){let Xe;e[86]===Symbol.for("react.memo_cache_sentinel")?(Xe=document.documentElement.classList.contains("dark"),e[86]=Xe):Xe=e[86],kt=Xe;break e}kt=!1}const ht=kt;let vt;e:{if(f){let Xe;e[87]!==f?(Xe=Im(f),e[87]=f,e[88]=Xe):Xe=e[88],vt=Xe;break e}vt=ht?R9:B9}const gt=vt;let Dt;e:{if($){Dt=!1;break e}let Xe;e[89]!==h||e[90]!==n.info?(Xe=Va.getInstance().shouldAnimateMessage(n.info,h||n.info.sessionID),e[89]=h,e[90]=n.info,e[91]=Xe):Xe=e[91],Dt=Xe}const Et=Dt,[Pt,St]=u.useState(!1);let Ot;e:{if(!r){Ot=null;break e}let Xe;e[92]!==r.info?(Xe=Ka(r.info),e[92]=r.info,e[93]=Xe):Xe=e[93],Ot=Xe}const qt=Ot;let Ge;e:{if(!o){Ge=null;break e}Ge=Ka(o.info)}const xe=Ge;let qe;e:{if($){qe=!1;break e}if(!xe){qe=!1;break e}qe=!xe.isUser&&xe.role==="assistant"}const at=qe;let bt;e:{if(Ze){bt="completed";break e}if(y){bt=y;break e}bt=x?"streaming":"completed"}const wt=bt;let Rt;e[94]===Symbol.for("react.memo_cache_sentinel")?(Rt=()=>{St(!1)},e[94]=Rt):Rt=e[94];let Ft;e[95]!==n.info.id?(Ft=[n.info.id],e[95]=n.info.id,e[96]=Ft):Ft=e[96],u.useEffect(Rt,Ft);let At;e[97]!==$||e[98]!==n.info.id||e[99]!==wt||e[100]!==l?.headerMessageId?(At=()=>{const Xe=l?.headerMessageId;if($||!Xe||Xe!==n.info.id)return;(wt==="streaming"||wt==="cooldown")&&St(!0)},e[97]=$,e[98]=n.info.id,e[99]=wt,e[100]=l?.headerMessageId,e[101]=At):At=e[101];const It=l?.headerMessageId;let Bt;e[102]!==$||e[103]!==n.info.id||e[104]!==wt||e[105]!==It?(Bt=[$,n.info.id,wt,It],e[102]=$,e[103]=n.info.id,e[104]=wt,e[105]=It,e[106]=Bt):Bt=e[106],u.useEffect(At,Bt);let ts;e:{if($){ts=!0;break e}const Xe=l?.headerMessageId;if(Xe){if(n.info.id===Xe){if(wt==="completed"){ts=!0;break e}ts=Pt||(wt==="streaming"||wt==="cooldown");break e}ts=!1;break e}if(!qt){ts=!0;break e}ts=qt.isUser}const as=ts;let ds;e[107]===Symbol.for("react.memo_cache_sentinel")?(ds=Xe=>{Cn(Xe).then(os=>{os.ok&&(D(Xe),setTimeout(()=>D(null),2e3))})},e[107]=ds):ds=e[107];const Be=ds,ft=l?.turnId;let Qt;e[108]!==n.info.sessionID||e[109]!==ft?(Qt=Xe=>{if(!ft||!n.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const os=Xe.messages.get(n.info.sessionID);if(!os)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Nt=os.find(rn=>rn.info?.id===ft);if(!Nt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const hs=Nt.info.summary?.body,Is=Nt.info.variant;return{assistantSummaryFromStore:typeof hs=="string"&&hs.trim().length>0?hs:void 0,variantFromTurnStore:typeof Is=="string"&&Is.trim().length>0?Is:void 0}},e[108]=n.info.sessionID,e[109]=ft,e[110]=Qt):Qt=e[110];const{assistantSummaryFromStore:Gt,variantFromTurnStore:zt}=Os(oa(Qt)),Mt=$?void 0:zt??oe?.variant,cs=!$&&$e?Mt??"Default":void 0;let Cs;e[111]!==Gt||e[112]!==l?(Cs=typeof l?.summaryBody=="string"&&l.summaryBody.trim().length>0?l.summaryBody:Gt,e[111]=Gt,e[112]=l,e[113]=Cs):Cs=e[113];const Ns=Cs,[$s,an]=u.useState(void 0);let vn;e[114]===Symbol.for("react.memo_cache_sentinel")?(vn=()=>{an(void 0)},e[114]=vn):vn=e[114];let Gs;e[115]!==ft?(Gs=[ft],e[115]=ft,e[116]=Gs):Gs=e[116],u.useEffect(vn,Gs);let Yn,er;e[117]!==Ns?(Yn=()=>{Ns&&Ns.trim().length>0&&an(Ns)},er=[Ns],e[117]=Ns,e[118]=Yn,e[119]=er):(Yn=e[118],er=e[119]),u.useEffect(Yn,er);let On;e:{if($){On=void 0;break e}const Xe=n.info?.error;if(!Xe){On=void 0;break e}const os=typeof Xe.data?.message=="string"?Xe.data.message:void 0,Nt=typeof Xe.message=="string"?Xe.message:void 0,ms=typeof Xe.name=="string"?Xe.name:void 0,hs=os||Nt||ms;if(!hs){On=void 0;break e}if(ms==="SessionRetry"){On=`Opencode failed to send a message. Retry attempt info:
129
+ ${Le}`;H(st)},[T,H]),ne=u.useCallback(Se=>{if(Se.stopPropagation(),Se.preventDefault(),B){U();return}const Le=Vf(T);Le.trim()&&z(Le)},[T,B,z,U]);u.useEffect(()=>()=>{L()},[L]);const ge=u.useMemo(()=>{const Se={},Le=_.filter(st=>$u(st.tool)||oe?!1:W(st));return Le.forEach((st,Ke)=>{Se[st.id]={hasPrev:Ke>0,hasNext:Ke<Le.length-1}}),Se},[_,oe,W]),we=u.useMemo(()=>w?.activityParts??[],[w]),Oe=u.useMemo(()=>w?we.filter(Se=>Se.messageId===t):[],[we,t,w]),et=u.useMemo(()=>w?w.activityGroupSegments.filter(Se=>Se.anchorMessageId===t):[],[t,w]),$e=u.useMemo(()=>{const Se=new Map;return Oe.forEach(Le=>{Se.set(Le.part,Le)}),Se},[Oe]),Ae=u.useMemo(()=>w?(b?we:we.filter(Le=>Le.kind!=="reasoning")).filter(Le=>{if(Le.kind!=="tool")return!0;const st=Le.part.tool;return!$u(st)}):[],[we,b,w]),[Ie,be]=u.useState(!1);u.useEffect(()=>{if(!w)return;const Se=w.activityGroupSegments.some(st=>st.afterToolPartId!==null),Le=Ae.some(st=>st.kind==="reasoning");(Ae.length>1||Se&&Ae.length>0||Le)&&be(!0)},[w,Ae]);const ee=!!(w&&Ie),he=!!(w&&ee&&Ae.length>0&&et.length>0),ye=u.useMemo(()=>_.filter(Se=>$u(Se.tool)),[_]),We=u.useMemo(()=>{const Se=[],Le=Ke=>{!w||!he||et.filter(it=>(it.afterToolPartId??null)===Ke).forEach(it=>{const pt=b?it.parts:it.parts.filter(Ut=>Ut.kind!=="reasoning");pt.length!==0&&Se.push(s.jsx(Q_,{parts:pt,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:a,isMobile:i,expandedTools:c,onToggleTool:d,onShowPopup:f,onContentChange:g,diffStats:w.diffStats},`progressive-group-${it.id}`))})};Le(null),ye.forEach(Ke=>{Se.push(s.jsx(Xr,{children:s.jsx(Zh,{part:Ke,isExpanded:c.has(Ke.id),onToggle:d,syntaxTheme:a,isMobile:i,onContentChange:g,onShowPopup:f,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ke.id}`)),Le(Ke.id)});const st=[];return E.forEach((Ke,it)=>{const pt=$e.get(Ke);if(!pt||!w)return;let Ut=null,ss=null;if(!ee){if(pt.kind==="tool"){const Wt=Ke;if($u(Wt.tool))return;const kt=Wt.state?.time,ht=W(Wt);if(!(!oe&&ht))return;const gt=ge[Wt.id];ss=s.jsx(Xr,{children:s.jsx(Zh,{part:Wt,isExpanded:c.has(Wt.id),onToggle:d,syntaxTheme:a,isMobile:i,onContentChange:g,onShowPopup:f,hasPrevTool:gt?.hasPrev??!1,hasNextTool:gt?.hasNext??!1})},`tool-${Wt.id}`),Ut=ht&&typeof kt?.end=="number"?kt.end:null}else if(pt.kind==="reasoning"&&b){const Wt=Ke.time,dt=typeof Wt?.end=="number"?Wt.end:null;ss=s.jsx(Xr,{children:s.jsx(tj,{part:Ke,messageId:t,onContentChange:g})},`reasoning-${pt.id}`),Ut=dt}ss&&st.push({part:Ke,index:it,endTime:Ut,element:ss})}}),st.sort((Ke,it)=>Ke.endTime===null&&it.endTime===null?Ke.index-it.index:Ke.endTime===null?1:it.endTime===null?-1:Ke.endTime-it.endTime),st.forEach(({element:Ke})=>{Se.push(Ke)}),Se},[$e,et,c,i,W,t,g,f,d,oe,ee,b,a,ge,w,E,ye,he]),Ee=w?.turnId,ze=Re(Se=>Se.currentSessionId),Ze=Os(Se=>{if(!Ee||!ze)return;const Le=Se.messages.get(ze);if(!Le)return;const st=Le.find(pt=>pt.info?.id===Ee);if(!st)return;const it=st.info.summary?.body;return typeof it=="string"&&it.trim().length>0?it:void 0}),Fe=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:Ze,tt=u.useRef(void 0);Fe&&Fe.trim().length>0&&(tt.current=Fe);const He=u.useRef(Ee);He.current!==Ee&&(He.current=Ee,tt.current=void 0);const _e=tt.current,je=w?.isLastAssistantInTurn&&_e&&_e.trim().length>0,Ye=!!j,Ne=R&&y&&(I||!!j),Pe=u.useMemo(()=>{if(!R||!I)return;const Se=w?.userMessageCreatedAt;if(!(typeof Se!="number"||typeof o!="number")&&!(o<=Se))return iP(o-Se)},[R,I,w?.userMessageCreatedAt,o]),Qe=s.jsxs(s.Fragment,{children:[x&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon","data-visible":F||k?"true":void 0,className:Z("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!X&&"opacity-50"),disabled:!X,"aria-label":"Copy message text","aria-hidden":!X,onPointerDown:Se=>Se.stopPropagation(),onClick:fe,onFocus:()=>{X&&A(!0)},onBlur:()=>{k||A(!1)},children:k?s.jsx(Ts,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):s.jsx(ir,{className:"h-3.5 w-3.5"})})}),s.jsx(Kt,{sideOffset:6,children:"Copy answer"})]}),s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:Se=>Se.stopPropagation(),onClick:pe,children:s.jsx(xh,{className:"h-4 w-4"})})}),s.jsx(Kt,{sideOffset:6,children:"Start new session from this answer"})]}),s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:Se=>Se.stopPropagation(),onClick:de,children:s.jsx(fx,{className:"h-4 w-4"})})}),s.jsx(Kt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),K&&X&&s.jsxs(Yt,{delayDuration:1e3,children:[s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon",className:Z("h-8 w-8 bg-transparent hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",B?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":B?"Stop speaking":"Read aloud",onPointerDown:Se=>Se.stopPropagation(),onClick:ne,children:B?s.jsx(ra,{className:"h-3.5 w-3.5"}):s.jsx(Cg,{className:"h-3.5 w-3.5"})})}),s.jsx(Kt,{sideOffset:6,children:q})]})]});return s.jsxs("div",{ref:S,className:Z("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:D&&N&&X?me:void 0,children:[s.jsx(Z_,{containerRef:S}),s.jsxs("div",{children:[s.jsxs("div",{className:"message-content-text leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[We,Ye&&s.jsx(Xr,{children:s.jsx("div",{className:"group/assistant-text relative break-words",children:s.jsx(Kr,{content:j??"",onShowPopup:f})})},"assistant-error"),je&&s.jsx(Xr,{children:s.jsxs("div",{className:"group/assistant-text relative break-words",children:[s.jsx(Kr,{content:_e,onShowPopup:f}),Ne&&s.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5",children:[s.jsx("div",{className:"flex items-center gap-1.5",children:Qe}),Pe?s.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[s.jsx(Mx,{className:"h-3.5 w-3.5"}),Pe]}):null]})]})},"summary-body")]}),s.jsx(A2,{files:e,onShowPopup:f}),!je&&Ne&&s.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-start gap-1.5",children:[s.jsx("div",{className:"flex items-center gap-1.5",children:Qe}),Pe?s.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[s.jsx(Mx,{className:"h-3.5 w-3.5"}),Pe]}):null]})]})]})},uP=t=>{const e=Me.c(17);let n,r;if(e[0]!==t?({isUser:n,...r}=t,e[0]=t,e[1]=n,e[2]=r):(n=e[1],r=e[2]),n){let a;return e[3]!==r.agentMention||e[4]!==r.copiedMessage||e[5]!==r.hasTextContent||e[6]!==r.hasTouchInput||e[7]!==r.isMobile||e[8]!==r.messageId||e[9]!==r.onCopyMessage||e[10]!==r.onFork||e[11]!==r.onRevert||e[12]!==r.onShowPopup||e[13]!==r.parts?(a=s.jsx(cP,{messageId:r.messageId,parts:r.parts,isMobile:r.isMobile,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onRevert:r.onRevert,onFork:r.onFork}),e[3]=r.agentMention,e[4]=r.copiedMessage,e[5]=r.hasTextContent,e[6]=r.hasTouchInput,e[7]=r.isMobile,e[8]=r.messageId,e[9]=r.onCopyMessage,e[10]=r.onFork,e[11]=r.onRevert,e[12]=r.onShowPopup,e[13]=r.parts,e[14]=a):a=e[14],a}let o;return e[15]!==r?(o=s.jsx(dP,{...r}),e[15]=r,e[16]=o):o=e[16],o},n0=u.memo(uP);function fP(t){return t.setCurrentSession}function mP(t){return!t}function pP(t){return!t}const Ka=t=>{const e=t,n=e?.clientRole,r=e?.role;return e?.userMessageMarker===!0||n==="user"||r==="user"||e?.origin==="user"||e?.source==="user"?{role:"user",isUser:!0}:{role:n||r||"assistant",isUser:!1}},hP=u.lazy(()=>gr(()=>import("./ToolOutputDialog-DORFnwJC.js"),__vite__mapDeps([2,0,1,3,4]))),gP=new Set(["task","edit","multiedit","write","apply_patch","bash","todowrite"]),xP=4e3,yi=new Map,r0=t=>{const e=yi.get(t);return e?new Set(e):new Set},yP=(t,e)=>{if(yi.size>=xP&&!yi.has(t)){const n=yi.keys().next().value;typeof n=="string"&&yi.delete(n)}yi.set(t,new Set(e))},o0=t=>typeof t=="string"&&gP.has(t.toLowerCase());function zp(t){const e=Me.c(3),[n,r]=u.useState(t);let o,a;return e[0]!==t?(o=()=>{t!=null&&r(t)},a=[t],e[0]=t,e[1]=o,e[2]=a):(o=e[1],a=e[2]),u.useEffect(o,a),t??n}const bo=(t,e)=>{if(typeof t=="object"&&t!==null)return t[e]},bP=t=>{const e=Me.c(227),{message:n,previousMessage:r,nextMessage:o,onContentChange:a,animationHandlers:i,turnGroupingContext:l}=t,{isMobile:c,hasTouchInput:d}=hn(),{currentTheme:f}=mo(),m=u.useRef(null);let p;e[0]!==n.info?(p=Xe=>({lifecyclePhase:Xe.messageStreamStates.get(n.info.id)?.phase??null,isStreamingMessage:(()=>{const os=n.info.sessionID??Xe.currentSessionId??null;return os?(Xe.streamingMessageIds.get(os)??null)===n.info.id:!1})(),currentSessionId:Xe.currentSessionId,getAgentModelForSession:Xe.getAgentModelForSession,getSessionModelSelection:Xe.getSessionModelSelection,revertToMessage:Xe.revertToMessage,forkFromMessage:Xe.forkFromMessage}),e[0]=n.info,e[1]=p):p=e[1];const g=Re(oa(p)),{lifecyclePhase:y,isStreamingMessage:x,currentSessionId:h,getAgentModelForSession:v,getSessionModelSelection:b,revertToMessage:w,forkFromMessage:j}=g,F=rs(vP),{showReasoningTraces:A,toolCallExpansion:C}=Te(oa(wP));let S,N;e[2]!==h?(S=()=>{h&&Va.getInstance().recordSessionStart(h)},N=[h],e[2]=h,e[3]=S,e[4]=N):(S=e[3],N=e[4]),u.useEffect(S,N);const[k,D]=u.useState(null),[M,E]=u.useState(!1);let _;e[5]!==n.info.id?(_=()=>r0(n.info.id),e[5]=n.info.id,e[6]=_):_=e[6];const[T,P]=u.useState(_);let H;e[7]===Symbol.for("react.memo_cache_sentinel")?(H={open:!1,title:"",content:""},e[7]=H):H=e[7];const[R,I]=u.useState(H);let B,z;e[8]!==n.info.id?(B=()=>{P(r0(n.info.id))},z=[n.info.id],e[8]=n.info.id,e[9]=B,e[10]=z):(B=e[9],z=e[10]),u.useEffect(B,z);let U;e[11]===Symbol.for("react.memo_cache_sentinel")?(U=()=>{yi.clear(),P(new Set)},e[11]=U):U=e[11];let K;e[12]!==C?(K=[C],e[12]=C,e[13]=K):K=e[13],u.useEffect(U,K);let V;e[14]!==n.info?(V=Ka(n.info),e[14]=n.info,e[15]=V):V=e[15];const $=V.isUser,G=n.info.sessionID;let W;e[16]!==G?(W=Xe=>({currentContextAgent:G?Xe.currentAgentContext.get(G):void 0,savedSessionAgentSelection:G?Xe.sessionAgentSelections.get(G):void 0}),e[16]=G,e[17]=W):W=e[17];const{currentContextAgent:J,savedSessionAgentSelection:te}=Ss(oa(W));let le;e:{if(!$){le=n.parts;break e}const Xe=jP;let os;if(e[18]!==n.parts){let Nt;e[20]===Symbol.for("react.memo_cache_sentinel")?(Nt=ms=>{if(!(ms?.synthetic===!0))return!0;if(ms.type!=="text")return!1;const Is=ms?.text;return typeof Is=="string"?Xe(Is):!1},e[20]=Nt):Nt=e[20],os=n.parts.filter(Nt).map(SP),e[18]=n.parts,e[19]=os}else os=e[19];le=os}const ae=le;let ie;e:{if($||!r){ie=null;break e}const Xe=bo(r.info,"clientRole"),os=bo(r.info,"role");if((typeof Xe=="string"?Xe:typeof os=="string"?os:void 0)!=="user"){ie=null;break e}let ms,hs,Is,rn;if(e[21]!==r.info){const lr=bo(r.info,"mode"),pr=bo(r.info,"agent"),cr=bo(r.info,"providerID"),_n=bo(r.info,"modelID"),ho=bo(r.info,"variant");ms=typeof lr=="string"&&lr.trim().length>0?lr:typeof pr=="string"&&pr.trim().length>0?pr:void 0,Is=typeof cr=="string"&&cr.trim().length>0?cr:void 0,hs=typeof _n=="string"&&_n.trim().length>0?_n:void 0,rn=typeof ho=="string"&&ho.trim().length>0?ho:void 0,e[21]=r.info,e[22]=ms,e[23]=hs,e[24]=Is,e[25]=rn}else ms=e[22],hs=e[23],Is=e[24],rn=e[25];const tr=rn;if(!ms&&!Is&&!hs&&!tr){ie=null;break e}let kn;e[26]!==ms||e[27]!==hs||e[28]!==Is||e[29]!==tr?(kn={agentName:ms,providerId:Is,modelId:hs,variant:tr},e[26]=ms,e[27]=hs,e[28]=Is,e[29]=tr,e[30]=kn):kn=e[30],ie=kn}const oe=ie;let Y;e:{if($||!r){Y=!1;break e}const Xe=Array.isArray(r.parts)?r.parts:[];for(let os=0;os<Xe.length;os++){const Nt=Xe[os];if(Nt?.type!=="text"||Nt?.synthetic!==!0)continue;const ms=typeof Nt.text=="string"?Nt.text.trim():"";if(ms.startsWith("User has requested to enter plan mode")||ms.startsWith("The plan at ")){Y=!0;break e}}Y=!1}const re=Y;let ue;e:{if($){ue=void 0;break e}const Xe=n.info.time;if(!(typeof Xe?.completed=="number"&&Xe.completed>0)&&re&&oe?.agentName){ue=oe.agentName;break e}let Nt,ms;if(e[31]!==n.info?(Nt=bo(n.info,"mode"),ms=typeof Nt=="string"&&Nt.trim().length>0,e[31]=n.info,e[32]=Nt,e[33]=ms):(Nt=e[32],ms=e[33]),ms){ue=Nt;break e}let hs,Is;if(e[34]!==n.info?(hs=bo(n.info,"agent"),Is=typeof hs=="string"&&hs.trim().length>0,e[34]=n.info,e[35]=hs,e[36]=Is):(hs=e[35],Is=e[36]),Is){ue=hs;break e}if(oe?.agentName){ue=oe.agentName;break e}if(!G){ue=void 0;break e}if(J){ue=J;break e}ue=te??void 0}const Q=ue;let O;e[37]!==$||e[38]!==n.info?(O=$?null:bo(n.info,"providerID"),e[37]=$,e[38]=n.info,e[39]=O):O=e[39];const se=O;let X;e[40]!==$||e[41]!==n.info?(X=$?null:bo(n.info,"modelID"),e[40]=$,e[41]=n.info,e[42]=X):X=e[42];const L=X;let me;e:{if($||!G){me=null;break e}if(oe?.providerId&&oe?.modelId){let Nt;e[43]!==oe.modelId||e[44]!==oe.providerId?(Nt={providerId:oe.providerId,modelId:oe.modelId},e[43]=oe.modelId,e[44]=oe.providerId,e[45]=Nt):Nt=e[45],me=Nt;break e}if(Q){let Nt;e[46]!==Q||e[47]!==v||e[48]!==G?(Nt=v(G,Q),e[46]=Q,e[47]=v,e[48]=G,e[49]=Nt):Nt=e[49];const ms=Nt;if(ms?.providerId&&ms?.modelId){me=ms;break e}}let Xe;e[50]!==b||e[51]!==G?(Xe=b(G),e[50]=b,e[51]=G,e[52]=Xe):Xe=e[52];const os=Xe;if(os?.providerId&&os?.modelId){me=os;break e}me=null}const fe=me;let pe;e:{if($){pe=null;break e}if(typeof se=="string"&&se.trim().length>0){pe=se;break e}pe=fe?.providerId??null}const de=pe;let ne;e:{if($){ne=null;break e}if(typeof L=="string"&&L.trim().length>0){ne=L;break e}ne=fe?.modelId??null}const ge=ne;let we;if(e[53]!==$||e[54]!==ge||e[55]!==de||e[56]!==F){e:{if($){we=void 0;break e}if(de&&ge&&F.length>0){let Xe;e[58]!==de?(Xe=Nt=>Nt.id===de,e[58]=de,e[59]=Xe):Xe=e[59];const os=F.find(Xe);if(os?.models&&Array.isArray(os.models)){let Nt;e[60]!==ge?(Nt=rn=>rn.id===ge,e[60]=ge,e[61]=Nt):Nt=e[61];const Is=os.models.find(Nt)?.name;we=typeof Is=="string"?Is:void 0;break e}}we=void 0}e[53]=$,e[54]=ge,e[55]=de,e[56]=F,e[57]=we}else we=e[57];const Oe=we;let et;e:{if($){et=!1;break e}if(!de||!ge){et=!1;break e}const Xe=F.find(ms=>ms.id===de);if(!Xe?.models||!Array.isArray(Xe.models)){et=!1;break e}const Nt=Xe.models.find(ms=>ms.id===ge)?.variants;et=!!(Nt&&Object.keys(Nt).length>0)}const $e=et,Ae=zp(Q),Ie=zp(de??void 0),be=zp(Oe),ee=Ae??void 0,he=Ie??null,ye=be??void 0,We=n.info.time,Ee=typeof We?.completed=="number"?We.completed:null;let ze;e:{if($){ze=!0;break e}ze=!!(Ee&&Ee>0)}const Ze=ze,Fe=n.info.finish,tt=typeof Fe=="string"?Fe:void 0;let He;e[62]!==ae||e[63]!==A?(He=Y_(ae,{includeReasoning:A}),e[62]=ae,e[63]=A,e[64]=He):He=e[64];const _e=He;let je;e:{if($){je=_e;break e}let Xe;e[65]!==Ze||e[66]!==_e?(Xe=Ze?_e:[],e[65]=Ze,e[66]=_e,e[67]=Xe):Xe=e[67],je=Xe}const Ye=je;let Ne;e:{if($){let os;e[68]===Symbol.for("react.memo_cache_sentinel")?(os=[],e[68]=os):os=e[68],Ne=os;break e}let Xe;e[69]!==_e?(Xe=_e.filter(kP),e[69]=_e,e[70]=Xe):Xe=e[70],Ne=Xe}const Pe=Ne;let Qe;e:{if($){let Nt;e[71]===Symbol.for("react.memo_cache_sentinel")?(Nt=[],e[71]=Nt):Nt=e[71],Qe=Nt;break e}let Xe;e[72]!==_e?(Xe=_e.filter(NP),e[72]=_e,e[73]=Xe):Xe=e[73],Qe=Xe}const Se=Qe;let Le;e:{if(C==="collapsed"||C==="activity"){Le=T;break e}let Xe;if(e[74]!==Se||e[75]!==l){Xe=new Set;for(const Nt of Se){const ms=Nt.tool;Nt.id&&o0(ms)&&Xe.add(Nt.id)}if(l?.isFirstAssistantInTurn)for(const Nt of l.activityParts){if(Nt.kind!=="tool")continue;const ms=Nt.part;o0(ms.tool)&&(ms.id&&Xe.add(ms.id),Nt.id&&Xe.add(Nt.id))}e[74]=Se,e[75]=l,e[76]=Xe}else Xe=e[76];let os;if(e[77]!==Xe||e[78]!==T){os=new Set(Xe);for(const Nt of T)os.has(Nt)?os.delete(Nt):os.add(Nt);e[77]=Xe,e[78]=T,e[79]=os}else os=e[79];Le=os}const st=Le;let Ke;if(e[80]!==$||e[81]!==n.parts){e:{if(!$){Ke=void 0;break e}const Xe=n.parts.find(CP);if(!Xe){Ke=void 0;break e}const os=Xe,Nt=typeof os.name=="string"?os.name:void 0;if(!Nt){Ke=void 0;break e}const ms=os.source&&typeof os.source.value=="string"&&os.source.value.trim().length>0?os.source.value:`@${Nt}`;let hs;e[83]!==Nt||e[84]!==ms?(hs={name:Nt,token:ms},e[83]=Nt,e[84]=ms,e[85]=hs):hs=e[85],Ke=hs}e[80]=$,e[81]=n.parts,e[82]=Ke}else Ke=e[82];const it=Ke,pt=$&&Ye.length===0,Ut=typeof tt!="string";let ss;e:{if($){ss=!1;break e}if(Pe.length===0||Se.length===0){ss=Ut;break e}ss=!0}const Wt=ss,dt=f?.metadata.variant;let kt;e:{if(dt){kt=dt==="dark";break e}if(typeof document<"u"){let Xe;e[86]===Symbol.for("react.memo_cache_sentinel")?(Xe=document.documentElement.classList.contains("dark"),e[86]=Xe):Xe=e[86],kt=Xe;break e}kt=!1}const ht=kt;let vt;e:{if(f){let Xe;e[87]!==f?(Xe=Im(f),e[87]=f,e[88]=Xe):Xe=e[88],vt=Xe;break e}vt=ht?R9:B9}const gt=vt;let Dt;e:{if($){Dt=!1;break e}let Xe;e[89]!==h||e[90]!==n.info?(Xe=Va.getInstance().shouldAnimateMessage(n.info,h||n.info.sessionID),e[89]=h,e[90]=n.info,e[91]=Xe):Xe=e[91],Dt=Xe}const Et=Dt,[Pt,St]=u.useState(!1);let Ot;e:{if(!r){Ot=null;break e}let Xe;e[92]!==r.info?(Xe=Ka(r.info),e[92]=r.info,e[93]=Xe):Xe=e[93],Ot=Xe}const qt=Ot;let Ge;e:{if(!o){Ge=null;break e}Ge=Ka(o.info)}const xe=Ge;let qe;e:{if($){qe=!1;break e}if(!xe){qe=!1;break e}qe=!xe.isUser&&xe.role==="assistant"}const at=qe;let bt;e:{if(Ze){bt="completed";break e}if(y){bt=y;break e}bt=x?"streaming":"completed"}const wt=bt;let Rt;e[94]===Symbol.for("react.memo_cache_sentinel")?(Rt=()=>{St(!1)},e[94]=Rt):Rt=e[94];let Ft;e[95]!==n.info.id?(Ft=[n.info.id],e[95]=n.info.id,e[96]=Ft):Ft=e[96],u.useEffect(Rt,Ft);let At;e[97]!==$||e[98]!==n.info.id||e[99]!==wt||e[100]!==l?.headerMessageId?(At=()=>{const Xe=l?.headerMessageId;if($||!Xe||Xe!==n.info.id)return;(wt==="streaming"||wt==="cooldown")&&St(!0)},e[97]=$,e[98]=n.info.id,e[99]=wt,e[100]=l?.headerMessageId,e[101]=At):At=e[101];const It=l?.headerMessageId;let Bt;e[102]!==$||e[103]!==n.info.id||e[104]!==wt||e[105]!==It?(Bt=[$,n.info.id,wt,It],e[102]=$,e[103]=n.info.id,e[104]=wt,e[105]=It,e[106]=Bt):Bt=e[106],u.useEffect(At,Bt);let ts;e:{if($){ts=!0;break e}const Xe=l?.headerMessageId;if(Xe){if(n.info.id===Xe){if(wt==="completed"){ts=!0;break e}ts=Pt||(wt==="streaming"||wt==="cooldown");break e}ts=!1;break e}if(!qt){ts=!0;break e}ts=qt.isUser}const as=ts;let ds;e[107]===Symbol.for("react.memo_cache_sentinel")?(ds=Xe=>{Cn(Xe).then(os=>{os.ok&&(D(Xe),setTimeout(()=>D(null),2e3))})},e[107]=ds):ds=e[107];const Be=ds,ft=l?.turnId;let Qt;e[108]!==n.info.sessionID||e[109]!==ft?(Qt=Xe=>{if(!ft||!n.info.sessionID)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const os=Xe.messages.get(n.info.sessionID);if(!os)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const Nt=os.find(rn=>rn.info?.id===ft);if(!Nt)return{assistantSummaryFromStore:void 0,variantFromTurnStore:void 0};const hs=Nt.info.summary?.body,Is=Nt.info.variant;return{assistantSummaryFromStore:typeof hs=="string"&&hs.trim().length>0?hs:void 0,variantFromTurnStore:typeof Is=="string"&&Is.trim().length>0?Is:void 0}},e[108]=n.info.sessionID,e[109]=ft,e[110]=Qt):Qt=e[110];const{assistantSummaryFromStore:Gt,variantFromTurnStore:zt}=Os(oa(Qt)),Mt=$?void 0:zt??oe?.variant,cs=!$&&$e?Mt??"Default":void 0;let Cs;e[111]!==Gt||e[112]!==l?(Cs=typeof l?.summaryBody=="string"&&l.summaryBody.trim().length>0?l.summaryBody:Gt,e[111]=Gt,e[112]=l,e[113]=Cs):Cs=e[113];const Ns=Cs,[$s,an]=u.useState(void 0);let vn;e[114]===Symbol.for("react.memo_cache_sentinel")?(vn=()=>{an(void 0)},e[114]=vn):vn=e[114];let Gs;e[115]!==ft?(Gs=[ft],e[115]=ft,e[116]=Gs):Gs=e[116],u.useEffect(vn,Gs);let Yn,er;e[117]!==Ns?(Yn=()=>{Ns&&Ns.trim().length>0&&an(Ns)},er=[Ns],e[117]=Ns,e[118]=Yn,e[119]=er):(Yn=e[118],er=e[119]),u.useEffect(Yn,er);let On;e:{if($){On=void 0;break e}const Xe=n.info?.error;if(!Xe){On=void 0;break e}const os=typeof Xe.data?.message=="string"?Xe.data.message:void 0,Nt=typeof Xe.message=="string"?Xe.message:void 0,ms=typeof Xe.name=="string"?Xe.name:void 0,hs=os||Nt||ms;if(!hs){On=void 0;break e}if(ms==="SessionRetry"){On=`Opencode failed to send a message. Retry attempt info:
130
130
  \`${hs}\``;break e}if(Rh(hs)){On=Th;break e}On=`Opencode failed to send message with error:
131
131
  \`${hs}\``}const gn=On;let Dn;if(e[120]!==gn||e[121]!==$s||e[122]!==Ye||e[123]!==$){e:{if($){const os=Ye.filter(AP).map(FP).filter(DP);if(os.length>0){Dn=os.join(`
132
132
 
@@ -336,12 +336,12 @@ Must-fix:
336
336
  - None
337
337
  Nice-to-have:
338
338
  - None`,we=MW(re);Lt.sendMessage({id:O,providerID:me,modelID:fe,agent:pe,variant:de,text:ne,additionalParts:[{text:ge,synthetic:!0},{text:we,synthetic:!0}]}).catch(Oe=>{const et=Oe instanceof Error?Oe.message:String(Oe);ce.error("Failed to send PR context",{description:et})}),ce.success("Session created from PR")}catch(re){const ue=re instanceof Error?re.message:String(re);ce.error(p?"PR worktree failed":"Failed to start session",{description:ue})}finally{N(null)}}},[p,ie,n,y,e,c,te,le,ae,S]);return s.jsx(Vs,{open:t,onOpenChange:e,children:s.jsxs(Ws,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(en,{className:"flex-shrink-0",children:[s.jsxs(Zs,{className:"flex items-center gap-2",children:[s.jsx(Ha,{className:"h-5 w-5"}),"New Session From GitHub PR"]}),s.jsx(nn,{children:"Seeds a new session with hidden PR context (title/body/comments/files/checks)."})]}),s.jsxs("div",{className:"relative mt-2",children:[s.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(fs,{placeholder:"Search by title or #123, or paste PR URL",value:f,onChange:Y=>m(Y.target.value),className:"pl-9 w-full"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[c?null:s.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),n?null:s.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),k?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(ps,{className:"h-4 w-4 animate-spin"}),"Loading pull requests..."]}):null,V===!1?s.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[s.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),s.jsx("div",{className:"flex justify-center",children:s.jsx(ot,{variant:"outline",size:"sm",onClick:$,children:"Open settings"})})]}):null,R?s.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:R}):null,J&&c&&n&&V?s.jsxs("div",{className:Z("group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer",S===J&&"bg-interactive-selection/30"),onClick:()=>{oe(J)},children:[s.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),s.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use PR #",J]}),s.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:S===J?s.jsx(ps,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,G.length===0&&!k&&V&&n&&c?s.jsx("div",{className:"text-center text-muted-foreground py-8",children:f?"No PRs found":"No open PRs found"}):null,G.map(Y=>{const re=W(Y);return s.jsxs("div",{className:Z("group flex items-start gap-2 py-1.5 rounded transition-colors",S===Y.number&&"bg-interactive-selection/30",re?"opacity-50 cursor-not-allowed":"hover:bg-interactive-hover/30 cursor-pointer"),onClick:()=>{re||oe(Y.number)},children:[s.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0 pt-0.5",children:["#",Y.number]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"typography-small text-foreground truncate ml-0.5",children:Y.title}),p&&re?s.jsxs("p",{className:"typography-micro text-muted-foreground mt-0.5 ml-0.5",children:["PR worktree disabled: branch already exists or is in use (",Y.head,")"]}):null]}),s.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2 pt-0.5",children:S===Y.number?s.jsx(ps,{className:"h-4 w-4 animate-spin text-muted-foreground"}):s.jsx("a",{href:Y.url,target:"_blank",rel:"noopener noreferrer",className:Z("hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",re&&"pointer-events-none"),onClick:ue=>ue.stopPropagation(),"aria-label":"Open in GitHub",children:s.jsx(so,{className:"h-4 w-4"})})})]},Y.number)}),A&&V&&c&&n?s.jsx("div",{className:"py-2 flex justify-center",children:s.jsx("button",{type:"button",onClick:()=>{U()},disabled:M||!!S,className:Z("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(M||!!S)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:M?s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(ps,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),s.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[s.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-4 sm:gap-y-2",children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:gap-4",children:[s.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":p,onClick:()=>g(Y=>!Y),onKeyDown:Y=>{(Y.key===" "||Y.key==="Enter")&&(Y.preventDefault(),g(re=>!re))},children:[s.jsx("button",{type:"button",onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),g(re=>!re)},"aria-label":"Toggle worktree",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:p?s.jsx($o,{className:"h-4 w-4 text-primary"}):s.jsx(Lo,{className:"h-4 w-4"})}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create in PR worktree"})]}),s.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":y,onClick:()=>x(Y=>!Y),onKeyDown:Y=>{(Y.key===" "||Y.key==="Enter")&&(Y.preventDefault(),x(re=>!re))},children:[s.jsx("button",{type:"button",onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),x(re=>!re)},"aria-label":"Toggle diff",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:y?s.jsx($o,{className:"h-4 w-4 text-primary"}):s.jsx(Lo,{className:"h-4 w-4"})}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:"Include full diff"})]})]}),s.jsx("div",{className:"hidden sm:block sm:flex-1"}),s.jsxs("div",{className:"flex items-center gap-2",children:[q?s.jsx(ot,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:q,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(so,{className:"size-4"}),"Open Repo"]})}):null,s.jsx(ot,{variant:"outline",size:"sm",onClick:z,disabled:k||!!S,children:"Refresh"})]})]})]})]})})}const RW=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,M1=({projectRef:t,canCreateWorktree:e=!1,onActionComplete:n,className:r})=>{const[o,a]=u.useState(!1),[i,l]=u.useState(""),[c,d]=u.useState([]),[f,m]=u.useState(""),[p,g]=u.useState(null),y=Re(T=>T.currentSessionId),x=Re(T=>T.openNewSessionDraft),h=Re(T=>T.setPendingInputText),v=Te(T=>T.setActiveMainTab),b=Te(T=>T.setSessionSwitcherOpen),w=u.useCallback(async(T,P)=>{if(!t)return!1;const H=await $4(t,{notes:T,todos:P});return H||ce.error("Failed to save project notes"),H},[t]);u.useEffect(()=>{if(!t){l(""),d([]),m("");return}let T=!1;return a(!0),(async()=>{try{const P=await O4(t);if(T)return;l(P.notes),d(P.todos),m("")}catch{T||(ce.error("Failed to load project notes"),l(""),d([]))}finally{T||a(!1)}})(),()=>{T=!0}},[t]);const j=u.useCallback(()=>{w(i,c)},[i,w,c]),F=u.useCallback(()=>{const T=f.trim();if(!T)return;const P=[...c,{id:RW(),text:T.slice(0,lf),completed:!1,createdAt:Date.now()}];d(P),m(""),w(i,P)},[f,i,w,c]),A=u.useCallback((T,P)=>{const H=c.map(R=>R.id===T?{...R,completed:P}:R);d(H),w(i,H)},[i,w,c]),C=u.useCallback(T=>{const P=c.filter(H=>H.id!==T);d(P),w(i,P)},[i,w,c]),S=u.useCallback(()=>{const T=c.filter(P=>!P.completed);T.length!==c.length&&(d(T),w(i,T))},[i,w,c]),N=f.slice(0,lf),k=c.reduce((T,P)=>T+(P.completed?1:0),0),D=u.useCallback(()=>{v("chat"),b(!1)},[v,b]),M=u.useCallback(T=>{t&&(D(),x({directoryOverride:t.path,initialPrompt:T}),ce.success("Todo sent to new session"),n?.())},[n,x,t,D]),E=u.useCallback(T=>{if(!y){ce.error("No active session selected");return}D(),h(T,"append"),ce.success("Todo sent to current session"),n?.()},[y,n,D,h]),_=u.useCallback(async(T,P)=>{if(t){if(!e){ce.error("Worktree actions are only available for Git repositories");return}g(T);try{const H=await lS();if(!H)return;D(),x({directoryOverride:H,initialPrompt:P}),ce.success("Todo sent to new worktree session"),n?.()}finally{g(null)}}},[e,n,x,t,D]);return t?s.jsxs("div",{className:Z("w-full min-w-0 space-y-3 p-3",r),children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Quick notes"}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[i.length,"/",Ph]})]}),s.jsx(xr,{value:i,onChange:T=>l(T.target.value.slice(0,Ph)),onBlur:j,placeholder:"Capture context, reminders, or links",className:"min-h-24 resize-none",disabled:o})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Todo"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[c.length," item",c.length===1?"":"s"]}),s.jsx("button",{type:"button",onClick:S,disabled:o||k===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:"Clear completed"})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(fs,{value:N,onChange:T=>m(T.target.value.slice(0,lf)),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),F())},placeholder:"Add a todo",disabled:o,className:"h-8"}),s.jsx("button",{type:"button",onClick:F,disabled:o||N.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Add todo",children:s.jsx(sn,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:c.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No todos yet. Add a small checklist for this project."}):s.jsx("ul",{className:"divide-y divide-border/50",children:c.map(T=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsx(jn,{checked:T.completed,onChange:P=>A(T.id,P),ariaLabel:`Mark "${T.text}" complete`}),s.jsx("span",{className:Z("min-w-0 flex-1 typography-ui-label text-foreground",T.completed&&"text-muted-foreground line-through"),title:T.text,children:T.text}),s.jsx("button",{type:"button",onClick:()=>C(T.id),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete "${T.text}"`,children:s.jsx(Qn,{className:"h-3.5 w-3.5"})}),s.jsxs(Ys,{children:[s.jsx(Js,{asChild:!0,children:s.jsx("button",{type:"button",disabled:p===T.id,className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Send "${T.text}"`,children:s.jsx(S5,{className:"h-3.5 w-3.5"})})}),s.jsxs(Xs,{align:"end",className:"w-56",children:[s.jsx(is,{onClick:()=>E(T.text),children:"Send to current session"}),s.jsx(is,{onClick:()=>M(T.text),children:"Send to new session"}),s.jsx(is,{onClick:()=>{_(T.id,T.text)},disabled:!e,children:"Send to new worktree session"})]})]})]},T.id))})})]})]}):s.jsx("div",{className:Z("w-full min-w-0 p-3",r),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to add notes and todos."})})},BW=t=>{const e=Me.c(72),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:i,onRename:l,onDelete:c,renderSessionNode:d,groupDirectory:f,projectId:m,mobileVariant:p,isRenaming:g,renameDraft:y,onRenameDraftChange:x,onRenameSave:h,onRenameCancel:v,droppableRef:b,isDropTarget:w,onNewSession:j,onNewSubFolder:F,depth:A}=t,C=p===void 0?!1:p,S=g===void 0?!1:g,N=y===void 0?"":y,k=w===void 0?!1:w,D=A===void 0?0:A,[M,E]=u.useState(!1),[_,T]=u.useState(""),P=u.useRef(null),H=S||M,R=S?N:_;let I;e[0]!==n.name?(I=()=>{T(n.name),E(!0)},e[0]=n.name,e[1]=I):I=e[1];const B=I;let z;e[2]!==R||e[3]!==n.name||e[4]!==S||e[5]!==l||e[6]!==h?(z=()=>{const we=R.trim();we&&we!==n.name&&l(we),S&&h&&h(),E(!1),T("")},e[2]=R,e[3]=n.name,e[4]=S,e[5]=l,e[6]=h,e[7]=z):z=e[7];const U=z;let K;e[8]!==S||e[9]!==v?(K=()=>{S&&v&&v(),E(!1),T("")},e[8]=S,e[9]=v,e[10]=K):K=e[10];const V=K;let q;e[11]!==S||e[12]!==x?(q=we=>{S&&x?x(we):T(we)},e[11]=S,e[12]=x,e[13]=q):q=e[13];const $=q;let G,W;e[14]!==S?(G=()=>{if(!S)return;const we=()=>{const $e=P.current;$e&&($e.focus(),$e.select())},Oe=requestAnimationFrame(we),et=window.setTimeout(we,0);return()=>{cancelAnimationFrame(Oe),window.clearTimeout(et)}},W=[S],e[14]=S,e[15]=G,e[16]=W):(G=e[15],W=e[16]),u.useEffect(G,W);const J=a?no:k5,le=D>0&&"ml-3";let ae;e[17]!==le?(ae=Z("oc-folder",le),e[17]=le,e[18]=ae):ae=e[18];const ie=k&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let oe;e[19]!==ie?(oe=Z("group/folder flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-sm","hover:bg-interactive-hover/50 cursor-pointer",ie),e[19]=ie,e[20]=oe):oe=e[20];const Y=H?void 0:i,re=H?void 0:"button",ue=H?void 0:0;let Q;e[21]!==i||e[22]!==H?(Q=H?void 0:we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),i())},e[21]=i,e[22]=H,e[23]=Q):Q=e[23];const O=a?`Expand folder ${n.name}`:`Collapse folder ${n.name}`,se=k?"text-primary":"text-muted-foreground";let X;e[24]!==se?(X=Z("h-3.5 w-3.5 flex-shrink-0",se),e[24]=se,e[25]=X):X=e[25];let L;e[26]!==J||e[27]!==X?(L=s.jsx(J,{className:X}),e[26]=J,e[27]=X,e[28]=L):L=e[28];let me;e[29]!==R||e[30]!==n.name||e[31]!==V||e[32]!==$||e[33]!==U||e[34]!==a||e[35]!==k||e[36]!==H||e[37]!==r?(me=H?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1","data-keyboard-avoid":"true",onSubmit:we=>{we.preventDefault(),U()},children:[s.jsx("input",{ref:P,value:R,onChange:we=>$(we.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:$W,onKeyDown:we=>{if(we.key==="Escape"){we.stopPropagation(),V();return}(we.key===" "||we.key==="Enter")&&we.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:LW,children:s.jsx(Ts,{className:"size-4"})}),s.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),V()},className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(zs,{className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:Z("typography-ui-label font-semibold truncate",k?"text-primary":"text-muted-foreground"),children:n.name}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",r.length]}),a?s.jsx(ar,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(Us,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[29]=R,e[30]=n.name,e[31]=V,e[32]=$,e[33]=U,e[34]=a,e[35]=k,e[36]=H,e[37]=r,e[38]=me):me=e[38];let fe;e[39]!==L||e[40]!==me?(fe=s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 pl-1.5 flex-1",children:[L,me]}),e[39]=L,e[40]=me,e[41]=fe):fe=e[41];let pe;e[42]!==D||e[43]!==n.name||e[44]!==B||e[45]!==C||e[46]!==c||e[47]!==j||e[48]!==F||e[49]!==H?(pe=H?null:s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:Z("flex items-center gap-0.5 transition-opacity",C?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100"),children:[j?s.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),j()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${n.name}`,title:"New session",children:s.jsx(sn,{className:"h-3.5 w-3.5"})}):null,F&&D===0?s.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),F()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New sub-folder in ${n.name}`,title:"New sub-folder",children:s.jsx(Oi,{className:"h-3.5 w-3.5"})}):null,s.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),B()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${n.name}`,children:s.jsx(So,{className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:we=>{we.stopPropagation(),c()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete folder ${n.name}`,children:s.jsx(Qn,{className:"h-3.5 w-3.5"})})]})}),e[42]=D,e[43]=n.name,e[44]=B,e[45]=C,e[46]=c,e[47]=j,e[48]=F,e[49]=H,e[50]=pe):pe=e[50];let de;e[51]!==b||e[52]!==oe||e[53]!==Y||e[54]!==re||e[55]!==ue||e[56]!==Q||e[57]!==O||e[58]!==fe||e[59]!==pe?(de=s.jsxs("div",{ref:b,className:oe,onClick:Y,role:re,tabIndex:ue,onKeyDown:Q,"aria-label":O,children:[fe,pe]}),e[51]=b,e[52]=oe,e[53]=Y,e[54]=re,e[55]=ue,e[56]=Q,e[57]=O,e[58]=fe,e[59]=pe,e[60]=de):de=e[60];let ne;e[61]!==f||e[62]!==a||e[63]!==m||e[64]!==d||e[65]!==r||e[66]!==o?(ne=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(we=>d(we,0,f??null,m??null)):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]}),e[61]=f,e[62]=a,e[63]=m,e[64]=d,e[65]=r,e[66]=o,e[67]=ne):ne=e[67];let ge;return e[68]!==ae||e[69]!==de||e[70]!==ne?(ge=s.jsxs("div",{className:ae,children:[de,ne]}),e[68]=ae,e[69]=de,e[70]=ne,e[71]=ge):ge=e[71],ge},OW=u.memo(BW);function $W(t){return t.stopPropagation()}function LW(t){return t.stopPropagation()}const zW=new Set([1,3,4,5,7]),HW=t=>t===4?"0ms":"130ms",E1="oc.sessions.projectCollapse",I1="oc.sessions.groupOrder",_1="oc.sessions.groupCollapse",P1="oc.sessions.activeSessionByProject",T1="oc.sessions.expandedParents",R1="oc.sessions.pinned",UW=180,VW=1,WW=6,GW=t=>{const e=new Date(t),n=new Date,r=(i,l)=>i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate(),o=new Date(n);return o.setDate(n.getDate()-1),r(e,n)?"Today":r(e,o)?"Yesterday":e.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},B1=t=>{const e=new Date,n=new Date(t);if(((o,a)=>o.getFullYear()===a.getFullYear()&&o.getMonth()===a.getMonth()&&o.getDate()===a.getDate())(n,e)){const o=Date.now()-t;return o<6e4?"Just now":o<36e5?`${Math.floor(o/6e4)}min ago`:`${Math.floor(o/36e5)}h ago`}return GW(t)},kr=t=>{if(!t)return null;const e=t.replace(/\\/g,"/").replace(/\/+$/,"");return e.length===0?"/":e},nm=t=>t.toLowerCase().replace(/^opencode[/-]?/i,"").replace(/[-_]/g,"").trim(),qW=(t,e)=>t?nm(t)!==nm(e):!1,fg=t=>{if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){const e=Number(t);if(Number.isFinite(e))return e}},O1=t=>fg(t.time?.created)??0,$1=t=>fg(t.time?.updated)??fg(t.time?.created)??0,Bc=(t,e,n)=>{const r=n.has(t.id),o=n.has(e.id);return r!==o?r?-1:1:r&&o?O1(e)-O1(t):$1(e)-$1(t)},qu=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),KW=t=>{const e=Me.c(15),{sessionId:n,sessionDirectory:r,sessionTitle:o,children:a}=t,i=`session-drag:${n}`;let l;e[0]!==r||e[1]!==n||e[2]!==o?(l={type:"session",sessionId:n,sessionDirectory:r,sessionTitle:o},e[0]=r,e[1]=n,e[2]=o,e[3]=l):l=e[3];let c;e[4]!==i||e[5]!==l?(c={id:i,data:l},e[4]=i,e[5]=l,e[6]=c):c=e[6];const{attributes:d,listeners:f,setNodeRef:m,isDragging:p}=D5(c);let g;e[7]!==f?(g=v=>{v.stopPropagation(),f?.onPointerDown&&f.onPointerDown(v)},e[7]=f,e[8]=g):g=e[8];const y=g,x=p?"opacity-30":void 0;let h;return e[9]!==d||e[10]!==a||e[11]!==y||e[12]!==m||e[13]!==x?(h=s.jsx("div",{ref:m,...d,onPointerDown:y,className:x,children:a}),e[9]=d,e[10]=a,e[11]=y,e[12]=m,e[13]=x,e[14]=h):h=e[14],h},QW=t=>{const e=Me.c(11),{folderId:n,children:r}=t,o=`folder-drop:${n}`;let a;e[0]!==n?(a={type:"folder",folderId:n},e[0]=n,e[1]=a):a=e[1];let i;e[2]!==o||e[3]!==a?(i={id:o,data:a},e[2]=o,e[3]=a,e[4]=i):i=e[4];const{setNodeRef:l,isOver:c}=I5(i);let d;e[5]!==r||e[6]!==c||e[7]!==l?(d=r(l,c),e[5]=r,e[6]=c,e[7]=l,e[8]=d):d=e[8];let f;return e[9]!==d?(f=s.jsx(s.Fragment,{children:d}),e[9]=d,e[10]=f):f=e[10],f},L1=t=>{const e=Me.c(20),{scopeKey:n,hasFolders:r,onSessionDroppedOnFolder:o,children:a}=t;let i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={activationConstraint:{distance:8}},e[0]=i):i=e[0];const l=bg(kf(vg,i)),[c,d]=u.useState(null),[f,m]=u.useState("Session"),[p,g]=u.useState(null),[y,x]=u.useState(null);if(!n){let C;return e[1]!==a?(C=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=C):C=e[2],C}let h;e[3]!==o?(h=C=>{d(null),g(null),x(null);const{active:S,over:N}=C;if(!N)return;const k=S.data.current,D=N.data.current;k?.type==="session"&&k.sessionId&&D?.type==="folder"&&D.folderId&&o(k.sessionId,D.folderId)},e[3]=o,e[4]=h):h=e[4];const v=h;let b,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(b=C=>{const S=C.active.data.current;if(S?.type==="session"&&S.sessionId){d(S.sessionId),m(S.sessionTitle??"Session");const N=C.active.rect.current.initial?.width,k=C.active.rect.current.initial?.height;g(typeof N=="number"?N:null),x(typeof k=="number"?k:null)}},w=()=>{d(null),g(null),x(null)},e[5]=b,e[6]=w):(b=e[5],w=e[6]);let j;e[7]!==y||e[8]!==c||e[9]!==f||e[10]!==p||e[11]!==r?(j=c&&r?s.jsxs("div",{style:{width:p?`${p}px`:"auto",height:y?`${y}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2.5 py-1 shadow-none pointer-events-none",children:[s.jsx(kh,{className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:f})]}):null,e[7]=y,e[8]=c,e[9]=f,e[10]=p,e[11]=r,e[12]=j):j=e[12];let F;e[13]!==j?(F=s.jsx(Gv,{children:j}),e[13]=j,e[14]=F):F=e[14];let A;return e[15]!==a||e[16]!==v||e[17]!==l||e[18]!==F?(A=s.jsxs(wg,{sensors:l,collisionDetection:jg,onDragStart:b,onDragCancel:w,onDragEnd:v,children:[a,F]}),e[15]=a,e[16]=v,e[17]=l,e[18]=F,e[19]=A):A=e[19],A},YW=t=>{const e=Me.c(48),{id:n,projectLabel:r,projectDescription:o,isCollapsed:a,isActiveProject:i,isRepo:l,isHovered:c,isDesktopShell:d,isStuck:f,hideDirectoryControls:m,mobileVariant:p,onToggle:g,onHoverChange:y,onNewSession:x,onNewWorktreeSession:h,onNewSessionFromGitHubIssue:v,onNewSessionFromGitHubPR:b,onOpenMultiRunLauncher:w,onRenameStart:j,onRenameSave:F,onRenameCancel:A,onRenameValueChange:C,renameValue:S,isRenaming:N,onClose:k,sentinelRef:D,children:M,settingsAutoCreateWorktree:E,showCreateButtons:_,hideHeader:T}=t,P=_===void 0?!0:_,H=T===void 0?!1:T;let R;e[0]!==n?(R={id:n},e[0]=n,e[1]=R):R=e[1];const{attributes:I,listeners:B,setNodeRef:z,transform:U,transition:K,isDragging:V}=Sg(R),[q,$]=u.useState(!1);let G;e[2]!==U?(G=kg.Transform.toString(U),e[2]=U,e[3]=G):G=e[3];let W;e[4]!==G||e[5]!==K?(W={transform:G,transition:K},e[4]=G,e[5]=K,e[6]=W):W=e[6];const J=V&&"opacity-30";let te;e[7]!==J?(te=Z("relative",J),e[7]=J,e[8]=te):te=e[8];let le;e[9]!==I||e[10]!==m||e[11]!==H||e[12]!==n||e[13]!==i||e[14]!==a||e[15]!==d||e[16]!==c||e[17]!==q||e[18]!==N||e[19]!==l||e[20]!==f||e[21]!==B||e[22]!==p||e[23]!==k||e[24]!==y||e[25]!==x||e[26]!==v||e[27]!==b||e[28]!==h||e[29]!==w||e[30]!==A||e[31]!==F||e[32]!==j||e[33]!==C||e[34]!==g||e[35]!==o||e[36]!==r||e[37]!==S||e[38]!==D||e[39]!==E||e[40]!==P?(le=H?null:s.jsxs(s.Fragment,{children:[d&&s.jsx("div",{ref:D,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsx("div",{className:Z("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b select-none",!d&&"bg-transparent"),style:{backgroundColor:d?"transparent":void 0,borderColor:c?"var(--color-border-hover)":a?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>y(!0),onMouseLeave:()=>y(!1),onContextMenu:ie=>{ie.preventDefault(),N||$(!0)},children:s.jsxs("div",{className:"relative flex items-center gap-1 px-1",...I,children:[N?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-2","data-keyboard-avoid":"true",onSubmit:ie=>{ie.preventDefault(),F()},children:[s.jsx("input",{value:S,onChange:ie=>C(ie.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename project",onKeyDown:ie=>{if(ie.key==="Escape"){ie.stopPropagation(),A();return}(ie.key===" "||ie.key==="Enter")&&ie.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(Ts,{className:"size-4"})}),s.jsx("button",{type:"button",onClick:A,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(zs,{className:"size-4"})})]}):s.jsxs(Yt,{delayDuration:1500,children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:g,...B,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:s.jsx("span",{className:Z("typography-ui font-semibold truncate",i?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),s.jsx(Kt,{side:"right",sideOffset:8,children:o})]}),N?null:s.jsxs(Ys,{open:q,onOpenChange:$,children:[s.jsx(Js,{asChild:!0,children:s.jsx("button",{type:"button",className:Z("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",p?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:ZW,children:s.jsx(Fo,{className:"h-3.5 w-3.5"})})}),s.jsxs(Xs,{align:"end",className:"min-w-[180px]",children:[P&&l&&!m&&E&&x&&s.jsxs(is,{onClick:x,children:[s.jsx(sn,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),P&&l&&!m&&!E&&h&&s.jsxs(is,{onClick:h,children:[s.jsx(bn,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),P&&l&&!m&&v&&s.jsxs(is,{onClick:v,children:[s.jsx(Pg,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub issue"]}),P&&l&&!m&&b&&s.jsxs(is,{onClick:b,children:[s.jsx(Ha,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub PR"]}),P&&l&&!m&&s.jsxs(is,{onClick:w,children:[s.jsx(fx,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),s.jsxs(is,{onClick:j,children:[s.jsx(So,{className:"mr-1.5 h-4 w-4"}),"Rename"]}),s.jsxs(is,{onClick:k,className:"text-destructive focus:text-destructive",children:[s.jsx(zs,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),P&&l&&!m&&h&&E&&!N&&s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),h()},className:Z("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground hover:bg-interactive-hover/50 flex-shrink-0",p?"opacity-70":"opacity-100"),"aria-label":"New session in worktree",children:s.jsx(bn,{className:"h-4 w-4"})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session in worktree"})})]}),P&&(!E||!l)&&!N&&s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),x()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:s.jsx(sn,{className:"h-4 w-4"})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})]})})]}),e[9]=I,e[10]=m,e[11]=H,e[12]=n,e[13]=i,e[14]=a,e[15]=d,e[16]=c,e[17]=q,e[18]=N,e[19]=l,e[20]=f,e[21]=B,e[22]=p,e[23]=k,e[24]=y,e[25]=x,e[26]=v,e[27]=b,e[28]=h,e[29]=w,e[30]=A,e[31]=F,e[32]=j,e[33]=C,e[34]=g,e[35]=o,e[36]=r,e[37]=S,e[38]=D,e[39]=E,e[40]=P,e[41]=le):le=e[41];let ae;return e[42]!==M||e[43]!==z||e[44]!==W||e[45]!==te||e[46]!==le?(ae=s.jsxs("div",{ref:z,style:W,className:te,children:[le,M]}),e[42]=M,e[43]=z,e[44]=W,e[45]=te,e[46]=le,e[47]=ae):ae=e[47],ae},JW=t=>{const e=Me.c(16),{id:n,children:r}=t;let o;e[0]!==n?(o={id:n},e[0]=n,e[1]=o):o=e[1];const{attributes:a,listeners:i,setNodeRef:l,transform:c,transition:d,isDragging:f}=Sg(o);let m;e[2]!==c?(m=kg.Transform.toString(c),e[2]=c,e[3]=m):m=e[3];let p;e[4]!==m||e[5]!==d?(p={transform:m,transition:d},e[4]=m,e[5]=d,e[6]=p):p=e[6];const g=f&&"opacity-50";let y;e[7]!==g?(y=Z("space-y-0.5 rounded-md",g),e[7]=g,e[8]=y):y=e[8];let x;return e[9]!==a||e[10]!==r||e[11]!==i||e[12]!==l||e[13]!==p||e[14]!==y?(x=s.jsx("div",{ref:l,style:p,className:y,...a,...i,children:r}),e[9]=a,e[10]=r,e[11]=i,e[12]=l,e[13]=p,e[14]=y,e[15]=x):x=e[15],x},XW=u.memo(JW),rm=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,hideProjectSelector:o=!0,showOnlyMainWorkspace:a=!1})=>{const[i,l]=u.useState(null),[c,d]=u.useState(""),[f,m]=u.useState(null),[p,g]=u.useState(""),[y,x]=u.useState(null),h=u.useRef(null),[v,b]=u.useState(new Set),[w,j]=u.useState(()=>new Map),F=u.useRef(new Map),A=u.useRef(new Set),C=u.useMemo(()=>Wn(),[]),[S,N]=u.useState(new Set),[k,D]=u.useState(new Map),[M,E]=u.useState(new Set),[_,T]=u.useState(null),[P,H]=u.useState(!1),[R,I]=u.useState(!1),[B,z]=u.useState(!1),[U,K]=u.useState(!1),[V,q]=u.useState(new Set),[$,G]=u.useState(null),[W,J]=u.useState(null),[te,le]=u.useState(""),[ae,ie]=u.useState(null),[oe,Y]=u.useState(null),[re,ue]=u.useState(()=>{try{const ve=Wn().getItem(R1);if(!ve)return new Set;const lt=JSON.parse(ve);return new Set(Array.isArray(lt)?lt.filter(ct=>typeof ct=="string"):[])}catch{return new Set}}),[Q,O]=u.useState(()=>{try{const ve=Wn().getItem(_1);if(!ve)return new Set;const lt=JSON.parse(ve);return new Set(Array.isArray(lt)?lt.filter(ct=>typeof ct=="string"):[])}catch{return new Set}}),[se,X]=u.useState(()=>{try{const ve=Wn().getItem(I1);if(!ve)return new Map;const lt=JSON.parse(ve),ct=new Map;return Object.entries(lt).forEach(([_t,Tt])=>{Array.isArray(Tt)&&ct.set(_t,Tt.filter(Xe=>typeof Xe=="string"))}),ct}catch{return new Map}}),[L,me]=u.useState(()=>{try{const ve=Wn().getItem(P1);if(!ve)return new Map;const lt=JSON.parse(ve),ct=new Map;return Object.entries(lt).forEach(([_t,Tt])=>{typeof Tt=="string"&&Tt.length>0&&ct.set(_t,Tt)}),ct}catch{return new Map}}),[fe,pe]=u.useState(!1),[de,ne]=u.useState(""),[ge,we]=u.useState(new Map),Oe=u.useRef(new Map),et=u.useRef(0),$e=u.useRef(null),Ae=u.useRef(null),Ie=Rs(ve=>ve.homeDirectory),be=Rs(ve=>ve.currentDirectory),ee=Rs(ve=>ve.setDirectory),he=bs(ve=>ve.projects),ye=bs(ve=>ve.activeProjectId),We=bs(ve=>ve.addProject),Ee=bs(ve=>ve.removeProject),ze=bs(ve=>ve.setActiveProjectIdOnly),Ze=bs(ve=>ve.renameProject),Fe=Te(ve=>ve.setActiveMainTab),tt=hn(),He=Te(ve=>ve.setSessionSwitcherOpen),_e=Te(ve=>ve.openMultiRunLauncher),je=Te(ve=>ve.notifyOnSubtasks),Ye=Te(ve=>ve.showDeletionDialog),Ne=Te(ve=>ve.setShowDeletionDialog),Pe=rs(ve=>ve.settingsAutoCreateWorktree),Qe=co(ve=>ve.collapsedFolderIds),Se=co(ve=>ve.getFoldersForScope),Le=co(ve=>ve.createFolder),st=co(ve=>ve.renameFolder),Ke=co(ve=>ve.deleteFolder),it=co(ve=>ve.addSessionToFolder),pt=co(ve=>ve.removeSessionFromFolder),Ut=co(ve=>ve.toggleFolderCollapse),ss=co(ve=>ve.cleanupSessions),Wt=co(ve=>ve.getSessionFolderId),dt=Nr(ve=>ve.directories),kt=Re(ve=>ve.sessions),ht=Re(ve=>ve.sessionsByDirectory),vt=Re(ve=>ve.currentSessionId),gt=Re(ve=>!!ve.newSessionDraft?.open),Dt=Re(ve=>ve.setCurrentSession),Et=Re(ve=>ve.loadMessages),Pt=Re(ve=>ve.updateSessionTitle),St=Re(ve=>ve.shareSession),Ot=Re(ve=>ve.unshareSession),qt=Re(ve=>ve.sessionMemoryState),Ge=Re(ve=>ve.sessionStatus),xe=Re(ve=>ve.sessionAttentionStates),qe=Re(ve=>ve.permissions),at=Re(ve=>ve.worktreeMetadata),bt=Re(ve=>ve.availableWorktreesByProject),wt=Re(ve=>ve.getSessionsByDirectory),Rt=Re(ve=>ve.openNewSessionDraft),Ft=u.useMemo(()=>tn(),[]),At=u.useMemo(()=>fr(),[]),It=u.useMemo(()=>ln(),[]),Bt=u.useCallback(()=>{if(It)return;const ve=Ae.current;if(Ae.current=null,$e.current=null,!ve)return;const{projects:lt}=bs.getState(),ct=lt.map(_t=>({..._t,sidebarCollapsed:ve.has(_t.id)}));on({projects:ct}).catch(()=>{})},[It]),ts=u.useCallback(ve=>{typeof window>"u"||It||(Ae.current=ve,$e.current!==null&&window.clearTimeout($e.current),$e.current=window.setTimeout(()=>{Bt()},700))},[Bt,It]);u.useEffect(()=>()=>{typeof window<"u"&&$e.current!==null&&window.clearTimeout($e.current),$e.current=null,Ae.current=null},[]),u.useEffect(()=>{try{const ve=C.getItem(T1);if(ve){const ct=JSON.parse(ve);Array.isArray(ct)&&b(new Set(ct.filter(_t=>typeof _t=="string")))}const lt=C.getItem(E1);if(lt){const ct=JSON.parse(lt);Array.isArray(ct)&&N(new Set(ct.filter(_t=>typeof _t=="string")))}}catch{}},[C]),u.useEffect(()=>{const ve=new Set(kt.map(lt=>lt.id));ue(lt=>{let ct=!1;const _t=new Set;return lt.forEach(Tt=>{ve.has(Tt)?_t.add(Tt):ct=!0}),ct?_t:lt})},[kt]),u.useEffect(()=>{try{C.setItem(R1,JSON.stringify(Array.from(re)))}catch{}},[re,C]);const as=u.useCallback(ve=>{ue(lt=>{const ct=new Set(lt);return ct.has(ve)?ct.delete(ve):ct.add(ve),ct})},[]),ds=u.useMemo(()=>[...kt].sort((ve,lt)=>Bc(ve,lt,re)),[kt,re]);u.useEffect(()=>{F.current=w},[w]);const Be=u.useRef(new Map),ft=u.useRef([]),Qt=u.useRef(new Set),Gt=u.useCallback(()=>{if(!(typeof window>"u"))for(;Qt.current.size<VW&&ft.current.length>0;){const ve=ft.current.shift();if(!ve)break;const lt=Re.getState();if(lt.currentSessionId===ve)continue;const ct=lt.messages.has(ve),_t=lt.sessionMemoryState.get(ve);ct&&_t?.historyComplete!==void 0||(Qt.current.add(ve),Et(ve).catch(()=>{}).finally(()=>{Qt.current.delete(ve),Gt()}))}},[Et]),zt=u.useCallback(ve=>{if(!ve||ve===vt||typeof window>"u")return;const lt=Re.getState(),ct=lt.messages.has(ve),_t=lt.sessionMemoryState.get(ve);if(ct&&_t?.historyComplete!==void 0||Qt.current.has(ve)||ft.current.includes(ve))return;ft.current.length>=WW&&ft.current.shift();const Xe=Be.current.get(ve);Xe!==void 0&&window.clearTimeout(Xe);const os=window.setTimeout(()=>{Be.current.delete(ve),ft.current.push(ve),Gt()},UW);Be.current.set(ve,os)},[vt,Gt]);u.useEffect(()=>{if(!vt||ds.length===0)return;const ve=ds.findIndex(lt=>lt.id===vt);ve<0||(zt(ds[ve-1]?.id),zt(ds[ve+1]?.id))},[vt,zt,ds]),u.useEffect(()=>{let ve=!1;const lt=he.map(ct=>({id:ct.id,path:kr(ct.path)})).filter(ct=>!!ct.path);return D(new Map),lt.length===0?()=>{ve=!0}:(lt.forEach(ct=>{Da(ct.path).then(_t=>{ve||D(Tt=>{const Xe=new Map(Tt);return Xe.set(ct.id,_t),Xe})}).catch(()=>{ve||D(_t=>{const Tt=new Map(_t);return Tt.set(ct.id,null),Tt})})}),()=>{ve=!0})},[he]);const Mt=u.useMemo(()=>{const ve=new Map;return ds.forEach(lt=>{const ct=lt.parentID;if(!ct)return;const _t=ve.get(ct)??[];_t.push(lt),ve.set(ct,_t)}),ve.forEach(lt=>lt.sort((ct,_t)=>Bc(ct,_t,re))),ve},[ds,re]);u.useEffect(()=>{const ve=new Set;ds.forEach(lt=>{const ct=kr(lt.directory??null);ct&&ve.add(ct)}),he.forEach(lt=>{const ct=kr(lt.path);ct&&ve.add(ct)}),ve.forEach(lt=>{const ct=F.current.get(lt);ct&&ct!=="unknown"||A.current.has(lt)||(A.current.add(lt),Lt.listLocalDirectory(lt).then(()=>{j(_t=>{const Tt=new Map(_t);return Tt.get(lt)==="exists"?_t:(Tt.set(lt,"exists"),Tt)})}).catch(async()=>{if((lt.includes("/opencode/worktree/")||lt.includes("/.opencode/data/worktree/")||lt.includes("/.local/share/opencode/worktree/"))&&await Lt.probeDirectory(lt).catch(()=>!1)){j(Xe=>{const os=new Map(Xe);return os.get(lt)==="exists"?Xe:(os.set(lt,"exists"),os)});return}j(Tt=>{const Xe=new Map(Tt);return Xe.get(lt)==="missing"?Tt:(Xe.set(lt,"missing"),Xe)})}).finally(()=>{A.current.delete(lt)}))})},[ds,he]),u.useEffect(()=>{const ve=Be.current;return()=>{h.current&&clearTimeout(h.current),ve.forEach(lt=>{clearTimeout(lt)}),ve.clear(),ft.current=[]}},[]);const cs=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:"No sessions yet"}),s.jsx("p",{className:"typography-meta mt-1",children:"Create your first session to start coding."})]}),Cs=u.useCallback((ve,lt,ct,_t)=>{if(!ct){if(_t&&_t!==ye&&ze(_t),lt&&lt!==be&&ee(lt,{showOverlay:!1}),t&&(Fe("chat"),He(!1)),ve===vt){n||e?.(ve);return}Dt(ve),e?.(ve)}},[ye,n,be,vt,t,e,Fe,ze,Dt,ee,He]),Ns=u.useCallback(()=>{Fe("chat")},[Fe]),$s=u.useCallback(async()=>{i&&c.trim()&&(await Pt(i,c.trim()),l(null),d(""))},[i,c,Pt]),an=u.useCallback(()=>{l(null),d("")},[]),vn=u.useCallback(()=>{f&&p.trim()&&(Ze(f,p.trim()),m(null),g(""))},[f,p,Ze]),Gs=u.useCallback(()=>{m(null),g("")},[]),Yn=u.useCallback(async ve=>{const lt=await St(ve.id);lt&&lt.share?.url?ce.success("Session shared",{description:"You can copy the link from the menu."}):ce.error("Unable to share session")},[St]),er=u.useCallback((ve,lt)=>{Cn(ve).then(ct=>{if(!ct.ok){ce.error("Failed to copy URL");return}x(lt),h.current&&clearTimeout(h.current),h.current=window.setTimeout(()=>{x(null),h.current=null},2e3)}).catch(()=>{ce.error("Failed to copy URL")})},[]),On=u.useCallback(async ve=>{await Ot(ve)?ce.success("Session unshared"):ce.error("Unable to unshare session")},[Ot]),gn=u.useCallback(ve=>{const lt=[],ct=_t=>{(Mt.get(_t)??[]).forEach(Xe=>{lt.push(Xe),ct(Xe.id)})};return ct(ve),lt},[Mt]),Dn=Re(ve=>ve.deleteSession),Jn=Re(ve=>ve.deleteSessions),$n=u.useCallback(async ve=>{const lt=gn(ve.id);if(lt.length===0){await Dn(ve.id)?ce.success("Session deleted"):ce.error("Failed to delete session");return}const ct=[ve.id,...lt.map(Xe=>Xe.id)],{deletedIds:_t,failedIds:Tt}=await Jn(ct);_t.length>0&&ce.success(`Deleted ${_t.length} session${_t.length===1?"":"s"}`),Tt.length>0&&ce.error(`Failed to delete ${Tt.length} session${Tt.length===1?"":"s"}`)},[gn,Dn,Jn]),Ln=u.useCallback(ve=>{const lt=gn(ve.id);if(!Ye){$n(ve);return}ie({session:ve,descendantCount:lt.length})},[gn,Ye,$n]),qn=u.useCallback(async()=>{if(!ae)return;const{session:ve}=ae;ie(null),await $n(ve)},[ae,$n]),wr=u.useCallback(()=>{if(!oe)return;const{scopeKey:ve,folderId:lt}=oe;Y(null),Ke(ve,lt)},[oe,Ke]),mr=u.useCallback(()=>{if(!Ft||!Ar()){ma.requestDirectoryDialog();return}gr(async()=>{const{requestDirectoryAccess:ve}=await Promise.resolve().then(()=>aN);return{requestDirectoryAccess:ve}},void 0).then(({requestDirectoryAccess:ve})=>ve("")).then(ve=>{ve.success&&ve.path?We(ve.path,{id:ve.projectId})||ce.error("Failed to add project",{description:"Please select a valid directory."}):ve.error&&ve.error!=="Directory selection cancelled"&&ce.error("Failed to select directory",{description:ve.error})}).catch(ve=>{console.error("Desktop: Error selecting directory:",ve),ce.error("Failed to select directory")})},[We,Ft]),nt=u.useCallback(ve=>{b(lt=>{const ct=new Set(lt);ct.has(ve)?ct.delete(ve):ct.add(ve);try{C.setItem(T1,JSON.stringify(Array.from(ct)))}catch{}return ct})},[C]),jt=u.useCallback((ve,lt)=>{if(!ve)return null;lt&&Qe.has(lt)&&Ut(lt);const ct=Le(ve,"New folder",lt);return J(ct.id),le(ct.name),ct},[Qe,Ut,Le]),mt=u.useCallback(ve=>{const lt=Mt.get(ve.id)??[];return{session:ve,children:lt.map(ct=>mt(ct)),worktree:at.get(ve.id)??null}},[Mt,at]),es=u.useCallback((ve,lt,ct,_t,Tt)=>{const Xe=kr(lt??null),os=[...ve].sort((js,Ks)=>Bc(js,Ks,re)),Nt=new Map(os.map(js=>[js.id,js])),ms=new Map;os.forEach(js=>{const Ks=js.parentID;if(!Ks)return;const Un=ms.get(Ks)??[];Un.push(js),ms.set(Ks,Un)}),ms.forEach(js=>js.sort((Ks,Un)=>Bc(Ks,Un,re)));const hs=new Map;ct.forEach(js=>{if(js.path){const Ks=kr(js.path)??js.path;hs.set(Ks,js)}});const Is=js=>{const Ks=kr(js.directory??null),Un=at.get(js.id)??null;if(Un)return Un;if(Ks){const Zt=hs.get(Ks)??null;if(Zt&&Ks!==Xe)return Zt}return null},rn=js=>{const Ks=ms.get(js.id)??[];return{session:js,children:Ks.map(Un=>rn(Un)),worktree:Is(js)}},tr=os.filter(js=>{const Ks=js.parentID;return Ks?!Nt.has(Ks):!0}),kn=new Map,lr=new Map,pr=js=>{const Ks=kr(at.get(js.id)?.path??null),Un=kr(js.directory??null),Zt=Ks??Un;return Zt&&Zt!==Xe&&hs.has(Zt)?Zt:Xe??"__project_root__"};tr.forEach((js,Ks)=>{const Un=rn(js),Zt=pr(js);kn.has(Zt)||(kn.set(Zt,[]),lr.set(Zt,Ks)),kn.get(Zt)?.push(Un)});const cr=Xe??"__project_root__",_n=[{id:"root",label:Tt&&_t&&_t!=="HEAD"?`project root: ${_t}`:"project root",branch:_t??null,description:Xe?ia(Xe,Ie):null,isMain:!0,worktree:null,directory:Xe,sessions:kn.get(cr)??[]}];[...ct].sort((js,Ks)=>{const Un=(js.label||js.branch||js.name||js.path||"").toLowerCase(),Zt=(Ks.label||Ks.branch||Ks.name||Ks.path||"").toLowerCase();return Un.localeCompare(Zt)}).forEach(js=>{const Ks=kr(js.path)??js.path,Un=dt.get(Ks)?.status?.current?.trim()||null,Zt=js.branch?.trim()||null,wn=!!(Un&&Zt&&js.label&&nm(js.label)===nm(Zt))?Un:js.label||js.name||To(Ks,Ie)||Ks;_n.push({id:`worktree:${Ks}`,label:wn,branch:Un||Zt,description:ia(Ks,Ie),isMain:!1,worktree:js,directory:Ks,sessions:kn.get(Ks)??[]})});const go=new Set(_n.map(js=>js.directory).filter(js=>!!js));return Array.from(kn.keys()).filter(js=>!go.has(js)&&js!==cr).sort((js,Ks)=>(lr.get(js)??0)-(lr.get(Ks)??0)).forEach(js=>{const Ks=dt.get(js)?.status?.current?.trim()||null;_n.push({id:`worktree:orphan:${js}`,label:To(js,Ie)||js,branch:Ks,description:ia(js,Ie),isMain:!1,worktree:null,directory:js,sessions:kn.get(js)??[]})}),_n},[Ie,at,re,dt]),Xt=u.useCallback(ve=>{E(lt=>{const ct=new Set(lt);return ct.has(ve)?ct.delete(ve):ct.add(ve),ct})},[]),vs=u.useCallback(ve=>{et.current=Date.now()+150,N(lt=>{const ct=new Set(lt);ct.has(ve)?ct.delete(ve):ct.add(ve);try{C.setItem(E1,JSON.stringify(Array.from(ct)))}catch{}return It||ts(ct),ct})},[It,C,ts]);u.useEffect(()=>{try{const ve=Object.fromEntries(se.entries());C.setItem(I1,JSON.stringify(ve))}catch{}},[se,C]),u.useEffect(()=>{try{const ve=Object.fromEntries(L.entries());C.setItem(P1,JSON.stringify(ve))}catch{}},[L,C]),u.useEffect(()=>{try{C.setItem(_1,JSON.stringify(Array.from(Q)))}catch{}},[Q,C]);const ns=u.useMemo(()=>he.map(ve=>({...ve,normalizedPath:kr(ve.path)})).filter(ve=>!!ve.normalizedPath),[he]),As=u.useMemo(()=>ns.map(ve=>{const lt=dt.get(ve.normalizedPath);return`${ve.id}:${lt?.status?.current??""}`}).join("|"),[ns,dt]);u.useEffect(()=>{let ve=!1;return(async()=>{const ct=await Promise.all(ns.map(async _t=>{const Tt=await ni(_t.normalizedPath).catch(()=>null);return{id:_t.id,branch:Tt}}));ve||we(_t=>{const Tt=new Map(_t);return ct.forEach(({id:Xe,branch:os})=>{os&&Tt.set(Xe,os)}),Tt})})(),()=>{ve=!0}},[ns,As]);const Ht=Re(ve=>ve.isLoading);u.useEffect(()=>{if(Ht)return;const ve=new Map;kt.forEach(_t=>{const Tt=kr(_t.directory??null);if(!Tt)return;const Xe=ve.get(Tt);if(Xe){Xe.add(_t.id);return}ve.set(Tt,new Set([_t.id]))});const lt=co.getState().foldersMap;new Set([...Object.keys(lt),...ve.keys()]).forEach(_t=>{ss(_t,ve.get(_t)??new Set)})},[kt,Ht,ss]);const xs=u.useCallback(ve=>{const lt=It?[]:bt.get(ve.normalizedPath)??[],ct=[ve.normalizedPath,...lt.map(Xe=>kr(Xe.path)??Xe.path).filter(Xe=>!!Xe)],_t=new Set,Tt=[];return ct.forEach(Xe=>{(ht.get(Xe)??wt(Xe)).forEach(Nt=>{_t.has(Nt.id)||(_t.add(Nt.id),Tt.push(Nt))})}),Tt},[bt,wt,ht,It]),Ms=u.useRef(!1);ye&&k.has(ye)&&(Ms.current=!!k.get(ye));const ys=u.useMemo(()=>ns.map(ve=>{const lt=xs(ve),ct=bt.get(ve.normalizedPath)??[],_t=k.has(ve.id)?!!k.get(ve.id):Ms.current,Tt=es(lt,ve.normalizedPath,ct,ge.get(ve.id)??null,_t);return{project:ve,groups:Tt}}),[ns,xs,es,bt,ge,k]),xn=u.useMemo(()=>{if(ys.length===0)return ys;const ve=ys.find(lt=>lt.project.id===ye);return ve?[ve]:[ys[0]]},[ys,ye]),Ce=u.useMemo(()=>ns.find(ve=>ve.id===ye)??ns[0]??null,[ns,ye]),xt=u.useMemo(()=>Ce?{id:Ce.id,path:Ce.normalizedPath}:null,[Ce]),ke=u.useMemo(()=>Ce?{id:Ce.id,path:Ce.path,normalizedPath:Ce.normalizedPath,label:Ce.label}:null,[Ce]),Ue=u.useMemo(()=>Ce?!!k.get(Ce.id):!1,[Ce,k]),Ve=Ce&&k.has(Ce.id)?Ue:Ms.current,Je=!!Ce,ut=t||tt.isMobile;u.useEffect(()=>{Ce||K(!1)},[Ce]);const $t=u.useMemo(()=>{const ve=new Map,lt=new Map,ct=(_t,Tt,Xe,os)=>{ve.has(_t)||ve.set(_t,new Map);const Nt=ve.get(_t);os.forEach(ms=>{const hs=kr(ms.worktree?.path??ms.session.directory??Xe??Tt);Nt.set(ms.session.id,{directory:hs}),lt.has(_t)||lt.set(_t,{id:ms.session.id,directory:hs}),ms.children.length>0&&ct(_t,Tt,hs,ms.children)})};return ys.forEach(_t=>{_t.groups.forEach(Tt=>{ct(_t.project.id,_t.project.normalizedPath,Tt.directory,Tt.sessions)})}),{metaByProject:ve,firstSessionByProject:lt}},[ys]),gs=u.useRef(null),Ls=u.useRef(null);u.useLayoutEffect(()=>{if(!ye)return;const ve=Ls.current,lt=!!(ve&&ve!==ye);if(Ls.current=ye,gt&&(It||!lt)||gs.current===ye)return;const ct=ys.find(hs=>hs.project.id===ye);if(!ct)return;gs.current=ye;const _t=$t.metaByProject.get(ye);if(vt&&_t&&_t.has(vt)){me(hs=>{if(hs.get(ye)===vt)return hs;const Is=new Map(hs);return Is.set(ye,vt),Is});return}if(!_t||_t.size===0){Fe("chat"),t&&He(!1),Rt({directoryOverride:ct.project.normalizedPath});return}const Tt=L.get(ye),Xe=Tt&&_t.has(Tt)?Tt:null,os=$t.firstSessionByProject.get(ye)?.id??null,Nt=Xe??os;if(!Nt||Nt===vt)return;const ms=_t.get(Nt)?.directory??null;Cs(Nt,ms,!1,ye)},[ye,L,vt,Cs,It,gt,t,Rt,ys,$t,Fe,He]),u.useEffect(()=>{if(!ye||!vt)return;const ve=$t.metaByProject.get(ye);!ve||!ve.has(vt)||me(lt=>{if(lt.get(ye)===vt)return lt;const ct=new Map(lt);return ct.set(ye,vt),ct})},[ye,vt,$t]);const Fs=u.useMemo(()=>{if(!vt)return null;const ve=at.get(vt)?.path;if(ve)return kr(ve)??ve;const lt=kt.find(ct=>ct.id===vt);return lt?kr(lt.directory??null):null},[vt,kt,at]),ws=u.useCallback((ve,lt)=>{const ct=se.get(ve);if(!ct||ct.length===0)return lt;const _t=new Map(lt.map(Xe=>[Xe.id,Xe])),Tt=[];return ct.forEach(Xe=>{const os=_t.get(Xe);os&&(Tt.push(os),_t.delete(Xe))}),lt.forEach(Xe=>{_t.has(Xe.id)&&Tt.push(Xe)}),Tt},[se]),Ds=u.useCallback(()=>{Ce&&(ne(qu(Ce.label?.trim()||To(Ce.normalizedPath,Ie)||Ce.normalizedPath)),pe(!0))},[Ce,Ie]),Es=u.useCallback(()=>{if(!Ce)return;const ve=de.trim();ve&&(Ze(Ce.id,ve),pe(!1))},[Ce,de,Ze]),zn=t?"inline-flex h-6 w-6 items-center justify-center rounded-md leading-none text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50":"inline-flex h-6 w-6 items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",qs="h-4.5 w-4.5",Fr=Z("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t?"h-8 w-8 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50":"h-8 w-8 text-foreground hover:bg-interactive-hover",!At&&"bg-transparent hover:bg-sidebar/40");u.useEffect(()=>{if(!At)return;const ve=new IntersectionObserver(lt=>{lt.forEach(ct=>{const _t=ct.target.dataset.projectId;_t&&q(Tt=>{const Xe=new Set(Tt);return ct.isIntersecting?Xe.delete(_t):Xe.add(_t),Xe})})},{threshold:0});return Oe.current.forEach(lt=>{lt&&ve.observe(lt)}),()=>ve.disconnect()},[At,ys]);const Hn=u.useCallback((ve,lt=0,ct,_t)=>{const Tt=ve.session,Xe=kr(Tt.directory??null)??kr(ct??null),Nt=(Xe?w.get(Xe):null)==="missing",ms=qt.get(Tt.id),hs=vt===Tt.id,Is=Tt.title||"Untitled Session",rn=ve.children.length>0,tr=re.has(Tt.id),kn=v.has(Tt.id),lr=!!Tt.parentID,cr=xe.get(Tt.id)?.needsAttention===!0&&(!lr||je),_n=Tt.summary;if(i===Tt.id)return s.jsx("div",{className:Z("group relative flex items-center rounded-md px-1.5 py-1","bg-interactive-selection",lt>0&&"pl-[20px]"),children:s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[s.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:Zt=>{Zt.preventDefault(),$s()},children:[s.jsx("input",{value:c,onChange:Zt=>d(Zt.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:Zt=>{if(Zt.key==="Escape"){Zt.stopPropagation(),an();return}(Zt.key===" "||Zt.key==="Enter")&&Zt.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(Ts,{className:"size-4"})}),s.jsx("button",{type:"button",onClick:an,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(zs,{className:"size-4"})})]}),s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[rn?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:kn?s.jsx(Us,{className:"h-3 w-3"}):s.jsx(ar,{className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:B1(Tt.time?.updated||Tt.time?.created||Date.now())}),Tt.share?s.jsx(sp,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,(_n?.files??0)>0?s.jsxs("span",{className:"flex-shrink-0",children:["· ",_n.files," ",_n.files===1?"file":"files"," changed"]}):null,rn?s.jsxs("span",{className:"truncate",children:[ve.children.length," ",ve.children.length===1?"task":"tasks"]}):null]})]})},Tt.id);const ho=Ge?.get(Tt.id)?.type??"idle",go=ho==="busy"||ho==="retry",rr=qe.get(Tt.id)?.length??0,Ks=go||!go&&cr&&!hs,Un=ms&&ms.isZombie?s.jsx(tc,{className:"h-4 w-4 text-status-warning"}):null;return s.jsxs(u.Fragment,{children:[s.jsx(KW,{sessionId:Tt.id,sessionDirectory:Xe??null,sessionTitle:Is,children:s.jsx("div",{className:Z("group relative flex items-center rounded-md px-1.5 py-1",hs?"bg-interactive-selection":"hover:bg-interactive-hover",Nt?"opacity-75":"",lt>0&&"pl-[20px]"),onContextMenu:Zt=>{Zt.preventDefault(),G(Tt.id)},children:s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsxs("button",{type:"button",disabled:Nt,onClick:()=>Cs(Tt.id,Xe,Nt,_t),onDoubleClick:Zt=>{Zt.stopPropagation(),Ns()},className:Z("flex min-w-0 flex-1 flex-col gap-0 overflow-hidden rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none"),children:[s.jsxs("div",{className:"flex w-full items-center gap-2 min-w-0 flex-1 overflow-hidden",children:[Ks?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:go?s.jsx(jx,{size:"xs",className:"text-primary"}):s.jsx("span",{className:"grid grid-cols-3 gap-[1px] text-[var(--status-info)]","aria-label":"Unread updates",title:"Unread updates",children:Array.from({length:9},(Zt,yn)=>zW.has(yn)?s.jsx("span",{className:"h-[3px] w-[3px] rounded-full bg-current animate-attention-diamond-pulse",style:{animationDelay:HW(yn)}},yn):s.jsx("span",{className:"h-[3px] w-[3px]"},yn))})}):null,tr?s.jsx(Sh,{className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}):null,s.jsx("div",{className:"block min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:Is}),rr>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:"Permission required","aria-label":"Permission required",children:[s.jsx(iv,{className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:rr})]}):null]}),s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[rn?s.jsx("span",{role:"button",tabIndex:0,onClick:Zt=>{Zt.stopPropagation(),nt(Tt.id)},onKeyDown:Zt=>{(Zt.key==="Enter"||Zt.key===" ")&&(Zt.preventDefault(),Zt.stopPropagation(),nt(Tt.id))},className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 flex-shrink-0 rounded-sm","aria-label":kn?"Collapse subsessions":"Expand subsessions",children:kn?s.jsx(Us,{className:"h-3 w-3"}):s.jsx(ar,{className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:B1(Tt.time?.updated||Tt.time?.created||Date.now())}),Tt.share?s.jsx(sp,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,(_n?.files??0)>0?s.jsxs("span",{className:"flex-shrink-0",children:["· ",_n.files," ",_n.files===1?"file":"files"," changed"]}):null,rn?s.jsxs("span",{className:"truncate",children:[ve.children.length," ",ve.children.length===1?"task":"tasks"]}):null,Nt?s.jsxs("span",{className:"inline-flex items-center gap-0.5 text-status-warning flex-shrink-0",children:[s.jsx(tc,{className:"h-3 w-3"}),"Missing"]}):null]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Un,s.jsxs(Ys,{open:$===Tt.id,onOpenChange:Zt=>G(Zt?Tt.id:null),children:[s.jsx(Js,{asChild:!0,children:s.jsx("button",{type:"button",className:Z("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:Zt=>Zt.stopPropagation(),onKeyDown:Zt=>Zt.stopPropagation(),children:s.jsx(Fo,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),s.jsxs(Xs,{align:"end",className:"min-w-[180px]",onCloseAutoFocus:Zt=>{W&&Zt.preventDefault()},children:[s.jsxs(is,{onClick:()=>{l(Tt.id),d(Is)},className:"[&>svg]:mr-1",children:[s.jsx(So,{className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(is,{onClick:()=>as(Tt.id),className:"[&>svg]:mr-1",children:[tr?s.jsx(N5,{className:"mr-1 h-4 w-4"}):s.jsx(Sh,{className:"mr-1 h-4 w-4"}),tr?"Unpin session":"Pin session"]}),Tt.share?s.jsxs(s.Fragment,{children:[s.jsx(is,{onClick:()=>{Tt.share?.url&&er(Tt.share.url,Tt.id)},className:"[&>svg]:mr-1",children:y===Tt.id?s.jsxs(s.Fragment,{children:[s.jsx(Ts,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):s.jsxs(s.Fragment,{children:[s.jsx(ir,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),s.jsxs(is,{onClick:()=>On(Tt.id),className:"[&>svg]:mr-1",children:[s.jsx(C5,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):s.jsxs(is,{onClick:()=>Yn(Tt),className:"[&>svg]:mr-1",children:[s.jsx(sp,{className:"mr-1 h-4 w-4"}),"Share"]}),Xe?(()=>{const Zt=Se(Xe),yn=Wt(Xe,Tt.id);return s.jsxs(s.Fragment,{children:[s.jsx(Kn,{}),s.jsxs(iN,{children:[s.jsxs(lN,{className:"[&>svg]:mr-1",children:[s.jsx(no,{className:"h-4 w-4"}),"Move to folder"]}),s.jsxs(cN,{className:"min-w-[180px]",children:[Zt.length===0?s.jsx(is,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):Zt.map(wn=>s.jsxs(is,{onClick:()=>{yn===wn.id?pt(Xe,Tt.id):it(Xe,wn.id,Tt.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:wn.name}),yn===wn.id?s.jsx(Ts,{className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},wn.id)),s.jsx(Kn,{}),s.jsxs(is,{onClick:()=>{const wn=jt(Xe);wn&&it(Xe,wn.id,Tt.id)},children:[s.jsx(sn,{className:"mr-1 h-4 w-4"}),"New folder..."]}),yn?s.jsxs(is,{onClick:()=>{pt(Xe,Tt.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(zs,{className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]})]})})():null,s.jsx(Kn,{}),s.jsxs(is,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Ln(Tt),children:[s.jsx(Qn,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})})}),rn&&kn?ve.children.map(Zt=>Hn(Zt,lt+1,Xe??ct,_t)):null]},Tt.id)},[w,qt,Ge,xe,qe,vt,v,i,c,$s,an,nt,Cs,Ns,re,as,Yn,er,On,Ln,y,t,$,W,Se,Wt,it,pt,jt,je]),po=u.useCallback((ve,lt,ct,_t)=>{const Tt=M.has(lt),Xe=Q.has(lt),os=r?10:5,Nt=kr(ve.directory??null),ms=Nt?Se(Nt):[],hs=new Set(ms.flatMap(Zt=>Zt.sessionIds)),Is=ve.sessions.filter(Zt=>!hs.has(Zt.session.id)),rn=ms.map(Zt=>{const yn=Zt.sessionIds.map(wn=>ve.sessions.find(xo=>xo.session.id===wn)).filter(wn=>!!wn).sort((wn,xo)=>Bc(wn.session,xo.session,re));return{folder:Zt,nodes:yn}}),tr=rn.filter(({folder:Zt})=>!Zt.parentId),kn=Is.length,lr=Tt?Is:Is.slice(0,os),pr=kn-lr.length,_n=(Zt=>{const yn=[],wn=xo=>{xo.forEach(Ko=>{yn.push(Ko.session),Ko.children.length>0&&wn(Ko.children)})};return wn(Zt),yn})(ve.sessions),ho=kr(ve.directory??null),go=ct&&k.has(ct)?!!k.get(ct):Ms.current,rr=!ve.isMain&&qW(ve.branch,ve.label),js=!!(ho&&Fs&&ho===Fs),Ks=(Zt,yn,wn)=>{const xo=rn.filter(({folder:ha})=>ha.parentId===Zt.id),Ko=xo.length>0?s.jsx(s.Fragment,{children:xo.map(({folder:ha,nodes:Ea})=>Ks(ha,Ea,wn+1))}):void 0;return s.jsx(QW,{folderId:Zt.id,children:(ha,Ea)=>s.jsx(OW,{folder:Zt,sessions:yn,subFolderItems:Ko,isCollapsed:Qe.has(Zt.id),onToggle:()=>Ut(Zt.id),onRename:ao=>{Nt&&st(Nt,Zt.id,ao)},onDelete:()=>{if(!Nt)return;if(!Ye){Ke(Nt,Zt.id);return}const ao=rn.filter(({folder:Bm})=>Bm.parentId===Zt.id).length,Wi=yn.length;Y({scopeKey:Nt,folderId:Zt.id,folderName:Zt.name,subFolderCount:ao,sessionCount:Wi})},renderSessionNode:Hn,groupDirectory:ve.directory,projectId:ct,mobileVariant:t,isRenaming:W===Zt.id,renameDraft:W===Zt.id?te:void 0,onRenameDraftChange:ao=>le(ao),onRenameSave:()=>{const ao=te.trim();ao&&Nt&&st(Nt,Zt.id,ao),J(null),le("")},onRenameCancel:()=>{J(null),le("")},droppableRef:ha,isDropTarget:Ea,depth:wn,onNewSession:()=>{ct&&ct!==ye&&ze(ct),Fe("chat"),t&&He(!1),Rt({directoryOverride:ve.directory,targetFolderId:Zt.id})},onNewSubFolder:wn===0?()=>{Nt&&jt(Nt,Zt.id)}:void 0})},Zt.id)},Un=()=>tr.map(({folder:Zt,nodes:yn})=>Ks(Zt,yn,0));return _t?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body pb-3",children:s.jsxs(L1,{scopeKey:Nt,hasFolders:rn.length>0,onSessionDroppedOnFolder:(Zt,yn)=>{Nt&&it(Nt,yn,Zt)},children:[Un(),lr.map(Zt=>Hn(Zt,0,ve.directory,ct)),kn===0&&ms.length===0?s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,pr>0&&!Tt?s.jsxs("button",{type:"button",onClick:()=>Xt(lt),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",pr," more ",pr===1?"session":"sessions"]}):null,Tt&&kn>os?s.jsx("button",{type:"button",onClick:()=>Xt(lt),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:Z("group/gh relative flex items-center justify-between gap-1 py-1 min-w-0 rounded-sm",!_t&&"hover:bg-interactive-hover/50 cursor-pointer"),onClick:_t?void 0:()=>{O(Zt=>{const yn=new Set(Zt);return yn.has(lt)?yn.delete(lt):yn.add(lt),yn})},role:_t?void 0:"button",tabIndex:_t?void 0:0,onKeyDown:_t?void 0:Zt=>{(Zt.key==="Enter"||Zt.key===" ")&&(Zt.preventDefault(),O(yn=>{const wn=new Set(yn);return wn.has(lt)?wn.delete(lt):wn.add(lt),wn}))},"aria-label":_t?void 0:Xe?`Expand ${ve.label}`:`Collapse ${ve.label}`,children:[_t?s.jsx("div",{}):s.jsxs("div",{className:Z("min-w-0 flex items-center gap-1.5 pl-1.5 transition-[padding]",t?!ve.isMain&&ve.worktree?"pr-14":"pr-7":!ve.isMain&&ve.worktree?"group-hover/gh:pr-14 group-focus-within/gh:pr-14":"group-hover/gh:pr-7 group-focus-within/gh:pr-7"),children:[!ve.isMain||go?s.jsx(bn,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):null,s.jsxs("div",{className:"min-w-0 flex flex-col justify-center",children:[s.jsx("p",{className:Z("text-[14px] font-semibold truncate",js?"text-primary":"text-muted-foreground"),children:ve.label}),rr?s.jsx("span",{className:"text-[10px] sm:text-[11px] text-muted-foreground/80 truncate leading-tight",children:ve.branch}):null]}),Xe?s.jsx(ar,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(Us,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),ve.directory?s.jsxs(s.Fragment,{children:[!ve.isMain&&ve.worktree?s.jsx("div",{className:Z("absolute right-7 top-1/2 -translate-y-1/2 z-10 transition-opacity",t?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Zt=>{Zt.stopPropagation(),ma.requestDelete({sessions:_n,mode:"worktree",worktree:ve.worktree})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${ve.label}`,children:s.jsx(Qn,{className:"h-4 w-4"})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete worktree"})})]})}):null,s.jsx("div",{className:Z("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",t?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Zt=>{Zt.stopPropagation(),ct&&ct!==ye&&ze(ct),Fe("chat"),t&&He(!1),Rt({directoryOverride:ve.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${ve.label}`,children:s.jsx(sn,{className:"h-4 w-4"})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})})]}):null]}),Xe?null:s.jsx("div",{className:"oc-group-body pb-3",children:s.jsxs(L1,{scopeKey:Nt,hasFolders:rn.length>0,onSessionDroppedOnFolder:(Zt,yn)=>{Nt&&it(Nt,yn,Zt)},children:[Un(),lr.map(Zt=>Hn(Zt,0,ve.directory,ct)),kn===0&&ms.length===0?s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,pr>0&&!Tt?s.jsxs("button",{type:"button",onClick:()=>Xt(lt),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",pr," more ",pr===1?"session":"sessions"]}):null,Tt&&kn>os?s.jsx("button",{type:"button",onClick:()=>Xt(lt),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})})]})},[M,Q,r,Fs,k,Hn,Xt,ye,ze,Fe,t,He,Rt,Se,Qe,Ut,jt,st,Ke,Ye,it,W,te,re]),jr=bg(kf(vg,{activationConstraint:{distance:8}}),kf(E5,{coordinateGetter:M5}));return s.jsxs("div",{className:Z("flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[!r&&s.jsxs("div",{className:Z("select-none pl-3.5 pr-2 flex-shrink-0 border-b border-border/60",o?"py-1":"py-1.5"),children:[!o&&s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[s.jsxs(Ys,{onOpenChange:ve=>{ve||pe(!1)},children:[s.jsx(Js,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex h-8 min-w-0 max-w-[calc(100%-2.5rem)] items-center gap-1 rounded-md px-2 text-left text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("span",{className:"text-base font-semibold truncate",children:Ce?qu(Ce.label?.trim()||To(Ce.normalizedPath,Ie)||Ce.normalizedPath):"Projects"}),s.jsx(Us,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsxs(Xs,{align:"start",className:"min-w-[220px] max-w-[320px]",children:[ns.map(ve=>{const lt=qu(ve.label?.trim()||To(ve.normalizedPath,Ie)||ve.normalizedPath);return s.jsx(is,{onClick:()=>ze(ve.id),className:Z("truncate",ve.id===ye&&"text-primary"),children:s.jsx("span",{className:"truncate",children:lt})},ve.id)}),s.jsx("div",{className:"my-1 h-px bg-border/70"}),fe?s.jsx("div",{className:"px-2 py-1.5",children:s.jsxs("form",{className:"flex items-center gap-1",onSubmit:ve=>{ve.preventDefault(),Es()},children:[s.jsx("input",{value:de,onChange:ve=>ne(ve.target.value),className:"h-7 flex-1 rounded border border-border bg-transparent px-2 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",placeholder:"Rename project",autoFocus:!0,onKeyDown:ve=>{if(ve.key==="Escape"){ve.stopPropagation(),pe(!1);return}(ve.key===" "||ve.key==="Enter")&&ve.stopPropagation()}}),s.jsx("button",{type:"submit",className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:text-foreground",children:s.jsx(Ts,{className:"h-4 w-4"})}),s.jsx("button",{type:"button",onClick:()=>pe(!1),className:"inline-flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:text-foreground",children:s.jsx(zs,{className:"h-4 w-4"})})]})}):s.jsxs(is,{onClick:ve=>{ve.preventDefault(),Ds()},className:"gap-2",children:[s.jsx(So,{className:"h-4 w-4"}),"Rename project"]}),s.jsxs(is,{onClick:()=>{Ce&&Ee(Ce.id)},className:"text-destructive focus:text-destructive gap-2",children:[s.jsx(zs,{className:"h-4 w-4"}),"Close project"]})]})]}),s.jsx("button",{type:"button",onClick:mr,className:Fr,"aria-label":"Add project",title:"Add project",children:s.jsx(Oi,{className:qs})})]}),Je?s.jsx("div",{className:"-ml-1 flex h-8 items-center",children:Ce?s.jsxs("div",{className:"flex h-8 -translate-y-px items-center gap-1.5 rounded-md pl-0 pr-1",children:[Ve?s.jsxs(s.Fragment,{children:[s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:async()=>{if(!Ce)return;Ce.id!==ye&&ze(Ce.id);const ve=await lS();ve&&(Fe("chat"),t&&He(!1),Rt({directoryOverride:ve}))},className:zn,"aria-label":"New worktree",children:s.jsx(A5,{className:qs})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New worktree"})})]}),s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>H(!0),className:zn,"aria-label":"New from issue",children:s.jsx(Pg,{className:qs})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New from issue"})})]}),s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>I(!0),className:zn,"aria-label":"New from PR",children:s.jsx(Ha,{className:qs})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New from PR"})})]}),s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:_e,className:zn,"aria-label":"New multi-run",children:s.jsx(fx,{className:qs})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New multi-run"})})]})]}):null,Ve&&ke?s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>z(!0),className:zn,"aria-label":"Manage branches",children:s.jsx(Ig,{className:qs})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Manage branches"})})]}):null,ut?s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>K(!0),className:zn,"aria-label":"Project notes and todos",children:s.jsx(kh,{className:qs})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Project notes"})})]}):s.jsxs(Ys,{open:U,onOpenChange:K,modal:!1,children:[s.jsxs(Yt,{children:[s.jsx(Jt,{asChild:!0,children:s.jsx(Js,{asChild:!0,children:s.jsx("button",{type:"button",className:zn,"aria-label":"Project notes and todos",children:s.jsx(kh,{className:qs})})})}),s.jsx(Kt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Project notes"})})]}),s.jsx(Xs,{align:"start",className:"w-[340px] p-0",children:s.jsx(M1,{projectRef:xt,canCreateWorktree:Ve,onActionComplete:()=>K(!1)})})]})]}):null}):null]}),s.jsx(Ps,{outerClassName:"flex-1 min-h-0",className:Z("space-y-1 pb-1 pl-2.5 pr-1",""),children:ys.length===0?cs:a?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const ve=ys.find(_t=>_t.project.id===ye)??ys[0];if(!ve)return cs;const lt=ve.groups.find(_t=>_t.isMain&&_t.sessions.length>0)??ve.groups.find(_t=>_t.sessions.length>0)??ve.groups.find(_t=>_t.isMain)??ve.groups[0];if(!lt)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ct=`${ve.project.id}:${lt.id}`;return po(lt,ct,ve.project.id,a)})()}):s.jsx(s.Fragment,{children:xn.map(ve=>{const lt=ve.project,ct=lt.id,_t=qu(lt.label?.trim()||To(lt.normalizedPath,Ie)||lt.normalizedPath),Tt=ia(lt.normalizedPath,Ie),Xe=S.has(ct)&&r,os=ct===ye,Nt=k.get(ct),ms=_===ct,hs=ws(ct,ve.groups);return s.jsx(YW,{id:ct,projectLabel:_t,projectDescription:Tt,isCollapsed:Xe,isActiveProject:os,isRepo:!!Nt,isHovered:ms,isDesktopShell:At,isStuck:V.has(ct),hideDirectoryControls:r,mobileVariant:t,onToggle:()=>vs(ct),onHoverChange:Is=>T(Is?ct:null),onNewSession:()=>{ct!==ye&&ze(ct),Fe("chat"),t&&He(!1),Rt({directoryOverride:lt.normalizedPath})},onNewWorktreeSession:()=>{ct!==ye&&ze(ct),Fe("chat"),t&&He(!1),Tm()},onNewSessionFromGitHubIssue:()=>{ct!==ye&&ze(ct),H(!0)},onNewSessionFromGitHubPR:()=>{ct!==ye&&ze(ct),I(!0)},onOpenMultiRunLauncher:()=>{ct!==ye&&ze(ct),_e()},onRenameStart:()=>{m(ct),g(lt.label?.trim()||To(lt.normalizedPath,Ie)||lt.normalizedPath)},onRenameSave:vn,onRenameCancel:Gs,onRenameValueChange:g,renameValue:f===ct?p:"",isRenaming:f===ct,onClose:()=>Ee(ct),sentinelRef:Is=>{Oe.current.set(ct,Is)},settingsAutoCreateWorktree:Pe,showCreateButtons:!1,hideHeader:!0,children:Xe?null:s.jsx("div",{className:"space-y-[0.6rem] py-1",children:ve.groups.length>0?s.jsxs(wg,{sensors:jr,collisionDetection:jg,onDragEnd:Is=>{const{active:rn,over:tr}=Is;if(!tr||rn.id===tr.id)return;const kn=hs.findIndex(cr=>cr.id===rn.id),lr=hs.findIndex(cr=>cr.id===tr.id);if(kn===-1||lr===-1||kn===lr)return;const pr=F5(hs,kn,lr).map(cr=>cr.id);X(cr=>{const _n=new Map(cr);return _n.set(ct,pr),_n})},children:[s.jsx(xv,{items:hs.map(Is=>Is.id),strategy:yv,children:hs.map(Is=>{const rn=`${ct}:${Is.id}`;return s.jsx(XW,{id:Is.id,children:po(Is,rn,ct)},Is.id)})}),s.jsx(Gv,{dropAnimation:null})]}):s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ct)})})}),s.jsx(FW,{open:P,onOpenChange:ve=>{H(ve),!ve&&t&&(Fe("chat"),He(!1))}}),s.jsx(TW,{open:R,onOpenChange:ve=>{I(ve),!ve&&t&&(Fe("chat"),He(!1))}}),s.jsx(Cj,{open:B,onOpenChange:z,project:ke}),ut?s.jsx(Ur,{open:U,onClose:()=>K(!1),title:"Project notes",children:s.jsx(M1,{projectRef:xt,canCreateWorktree:Ve,onActionComplete:()=>K(!1),className:"p-0"})}):null,s.jsx(Vs,{open:!!ae,onOpenChange:ve=>{ve||ie(null)},children:s.jsxs(Ws,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(en,{children:[s.jsx(Zs,{children:"Delete session?"}),s.jsx(nn,{children:ae&&ae.descendantCount>0?`"${ae.session.title||"Untitled Session"}" and its ${ae.descendantCount} sub-task${ae.descendantCount===1?"":"s"} will be permanently deleted.`:`"${ae?.session.title||"Untitled Session"}" will be permanently deleted.`})]}),s.jsxs(In,{className:"w-full sm:items-center sm:justify-between",children:[s.jsxs("button",{type:"button",onClick:()=>Ne(!Ye),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!Ye,children:[Ye?s.jsx(Lo,{className:"h-4 w-4"}):s.jsx($o,{className:"h-4 w-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>ie(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>{qn()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})]})}),s.jsx(Vs,{open:!!oe,onOpenChange:ve=>{ve||Y(null)},children:s.jsxs(Ws,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(en,{children:[s.jsx(Zs,{children:"Delete folder?"}),s.jsx(nn,{children:oe&&(oe.subFolderCount>0||oe.sessionCount>0)?`"${oe.folderName}" will be deleted${oe.subFolderCount>0?` along with ${oe.subFolderCount} sub-folder${oe.subFolderCount===1?"":"s"}`:""}. Sessions inside will not be deleted.`:`"${oe?.folderName}" will be permanently deleted.`})]}),s.jsxs(In,{children:[s.jsx("button",{type:"button",onClick:()=>Y(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:wr,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})]})};function ZW(t){return t.stopPropagation()}const Rm=()=>{const t=Me.c(13),[e,n]=De.useState(!1);let r,o;t[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{n(tn())},o=[],t[0]=r,t[1]=o):(r=t[0],o=t[1]),De.useEffect(r,o);let a;t[2]!==e?(a=async p=>e?await Sd(p):{success:!0,path:p},t[2]=e,t[3]=a):a=t[3];const i=a;let l;t[4]!==e?(l=async p=>e?await qv():{success:!0},t[4]=e,t[5]=l):l=t[5];const c=l;let d;t[6]!==e?(d=async p=>e?await Kv():{success:!0},t[6]=e,t[7]=d):d=t[7];const f=d;let m;return t[8]!==e||t[9]!==i||t[10]!==c||t[11]!==f?(m={isDesktop:e,requestAccess:i,startAccessing:c,stopAccessing:f},t[8]=e,t[9]=i,t[10]=c,t[11]=f,t[12]=m):m=t[12],m},z1=({currentPath:t,onSelectPath:e,triggerClassName:n,variant:r="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:l=!1,rootDirectory:c=null,isRootReady:d,alwaysShowActions:f=!1})=>{const{isMobile:m}=hn(),[p,g]=u.useState([]),[y,x]=u.useState(new Set),[h,v]=u.useState(!0),[b,w]=u.useState(!1),[j,F]=u.useState(""),[A,C]=u.useState(new Set),[S,N]=u.useState(null),[k,D]=u.useState(""),[M,E]=u.useState(!0),_=u.useRef(null),{requestAccess:T,startAccessing:P,isDesktop:H}=Rm(),R=u.useRef(l),I=u.useCallback(O=>{if(!O)return O;if(O==="/"||O.length===0)return"/";let se=O;for(;se.length>1&&se.endsWith("/");)se=se.slice(0,-1);return se.length===0?"/":se},[]),B=u.useMemo(()=>{if(!j)return null;const O=j.replace(/\\/g,"/");return I(O)},[j,I]),z=u.useMemo(()=>{if(typeof c=="string"&&c.length>0){const O=c.replace(/\\/g,"/"),se=I(O);if(se&&se!=="/")return se}return B&&B!=="/"?B:null},[c,B,I]),U=u.useMemo(()=>typeof d=="boolean"?!!(d&&z):!!z,[d,z]);u.useEffect(()=>{U||(v(!0),g([]))},[U]);const K=u.useCallback(O=>{if(!O||!U||!z)return!1;const se=O.replace(/\\/g,"/"),X=I(se)??se;if(X===z)return!0;const L=`${z}/`;return X.startsWith(L)},[U,z,I]),V=async O=>{if(U){if(a==="deferred"){e(O);return}if(H){const se=await T(O);se.success&&se.path?(await P(se.path),e(se.path)):(console.error("Failed to get directory access:",se.error),e(O))}else e(O)}};u.useEffect(()=>{let O=!1;const se=me=>{if(!me)return!1;const fe=I(me.replace(/\\/g,"/"));return!fe||fe==="/"?!1:(F(typeof fe=="string"?fe:me.replace(/\\/g,"/")),!0)};return c&&se(c)||(async()=>{try{const me=await Lt.getFilesystemHome();if(!O&&se(me))return}catch(me){console.warn("Failed to resolve filesystem home directory:",me)}try{const me=await Lt.getSystemInfo();if(!O&&se(me?.homeDirectory))return}catch(me){console.warn("Failed to resolve home directory from system info:",me)}})(),()=>{O=!0}},[c,I]),u.useEffect(()=>{let O=!1;const se=fe=>{if(O)return;const pe=fe.filter(de=>typeof de=="string"&&de.length>0).map(de=>{const ne=de.replace(/\\/g,"/");return I(ne)??ne});C(new Set(pe))},X=()=>{try{const fe=localStorage.getItem("pinnedDirectories");if(!fe)return;const pe=JSON.parse(fe);Array.isArray(pe)&&se(pe)}catch(fe){console.warn("Failed to load pinned directories from local storage:",fe)}},L=async()=>{try{let fe=[];const pe=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(pe.ok){const de=await pe.json();fe=Array.isArray(de?.pinnedDirectories)?de.pinnedDirectories:[]}if(O)return;se(fe)}catch(fe){console.warn("Failed to load pinned directories:",fe)}};X();const me=fe=>{const pe=fe.detail;pe&&Array.isArray(pe.pinnedDirectories)&&se(pe.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",me),L(),()=>{O=!0,window.removeEventListener("openchamber:settings-synced",me)}},[I]);const q=u.useRef(!0);u.useEffect(()=>{if(q.current){q.current=!1;return}const O={pinnedDirectories:Array.from(A)};on(O)},[A]),u.useEffect(()=>{z&&C(O=>{const se=Array.from(O).map(X=>I(X.replace(/\\/g,"/"))??X).filter(X=>K(X));return new Set(se)})},[z,K,I]),u.useEffect(()=>{R.current!==l&&(R.current=l)},[l]);const $=O=>{C(se=>{if(!K(O))return se;const X=I(O.replace(/\\/g,"/"))??O.replace(/\\/g,"/"),L=new Set(se);return L.has(X)?L.delete(X):L.add(X),L})},G=u.useMemo(()=>Array.from(A).map(O=>I(O.replace(/\\/g,"/"))??O).filter(O=>K(O)).map(O=>({path:O,name:O.split("/").pop()||O})).sort((O,se)=>O.name.localeCompare(se.name)),[A,K,I]),W=u.useCallback(async O=>{const se=pe=>l||!pe.startsWith("."),X=z;if(!U||!X)return[];const L=O&&O.length>0?O:X,me=L?L.replace(/\\/g,"/"):null,fe=me?I(me)??me:null;if(fe){const pe=`${X}/`;if(!(fe===X||fe.startsWith(pe)))return[]}try{return(await Lt.listLocalDirectory(O)).filter(de=>{if(!de.isDirectory||!se(de.name))return!1;const ne=de.path.replace(/\\/g,"/"),ge=I(ne)??ne,we=ge===X?X:`${X}/`;return ge===X||ge.startsWith(we)}).map(de=>({name:de.name,path:de.path.replace(/\\/g,"/"),isDirectory:!0})).sort((de,ne)=>de.name.localeCompare(ne.name))}catch{try{const de=await Lt.getApiClient().file.list({path:".",directory:O});return de.data?de.data.filter(ne=>{if(ne.type!=="directory"||!ne.name||!se(ne.name))return!1;const ge=String(ne.absolute||ne.path||ne.name).replace(/\\/g,"/"),we=I(ge)??ge,Oe=we===X?X:`${X}/`;return we===X||we.startsWith(Oe)}).map(ne=>({name:ne.name||"",path:String(ne.absolute||ne.path||ne.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ne=>ne.name!=="").sort((ne,ge)=>ne.name.localeCompare(ge.name)):[]}catch{return[]}}},[l,z,I,U]),J=u.useRef(!1),te=u.useCallback(async()=>{if(!U||!z){v(!0),g([]);return}J.current||v(!0);try{const O=await W(z);g(O),J.current=!0}catch{}finally{v(!1)}},[U,z,W]);u.useEffect(()=>{U&&(r==="inline"||b)&&te()},[r,b,U,te]);const le=async O=>{if(!U)return;const se=y.has(O.path),X=new Set(y);if(se){X.delete(O.path),x(X);return}X.add(O.path),x(X);const L=await W(O.path),me=fe=>fe.map(pe=>pe.path===O.path?{...pe,children:L}:pe.children?{...pe,children:me(pe.children)}:pe);g(fe=>me(fe))};u.useEffect(()=>{S&&_.current&&(_.current.focus(),_.current.select())},[S]);const ae=(O,se=[])=>{const X="new_directory",L=se.map(de=>de.name);if(!L.includes(X))return X;let me=1;const fe=new RegExp(`^${X}(\\d+)$`);for(const de of L){const ne=de.match(fe);if(ne){const ge=parseInt(ne[1],10);ge>me&&(me=ge)}}let pe=2;for(;L.includes(`${X}${pe}`);)pe++;return`${X}${Math.max(pe,me+1)}`},ie=async O=>{if(U){if(y.has(O.path)){const se=ae(O.path,O.children);D(se)}else{const se=new Set(y);if(se.add(O.path),x(se),O.children){const X=ae(O.path,O.children);D(X)}else{const X=await W(O.path),L=fe=>fe.map(pe=>pe.path===O.path?{...pe,children:X}:pe.children?{...pe,children:L(pe.children)}:pe);g(fe=>L(fe));const me=ae(O.path,X);D(me)}}N(O.path)}},oe=async()=>{if(!S||!U)return;const O=k.trim()||"new_directory",se=`${S}/${O}`;try{await Lt.createDirectory(se,{allowOutsideWorkspace:!0});const X=await W(S),L=me=>me.map(fe=>fe.path===S?{...fe,children:X}:fe.children?{...fe,children:L(fe.children)}:fe);g(me=>L(me)),N(null),D("")}catch(X){console.error("Failed to create directory:",X)}},Y=()=>{N(null),D("")},re=(O,se=0)=>{const X=y.has(O.path),L=O.isDirectory,me=A.has(O.path),fe=t===O.path,pe=r==="inline",de=s.jsxs(s.Fragment,{children:[L&&s.jsx("button",{onClick:ne=>{ne.stopPropagation(),le(O)},className:Z("hover:bg-interactive-hover rounded","p-0.5"),children:X?s.jsx(Us,{className:m?"h-3.5 w-3.5":"h-3 w-3"}):s.jsx(ar,{className:m?"h-3.5 w-3.5":"h-3 w-3"})}),!L&&s.jsx("div",{className:m?"w-4.5":"w-4"}),s.jsxs("button",{onClick:ne=>{ne.stopPropagation(),V(O.path),r==="dropdown"&&a==="immediate"&&w(!1)},onDoubleClick:ne=>{ne.stopPropagation(),i&&i(O.path)},className:Z("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",pe&&fe?"text-primary":"text-foreground"),children:[s.jsx(ea,{className:Z("text-muted-foreground flex-shrink-0",m?"h-4 w-4":"h-3.5 w-3.5",pe&&fe&&"text-primary")}),s.jsx("span",{className:Z("font-medium truncate","typography-ui-label",pe&&fe?"text-primary":"text-foreground"),children:O.name})]}),s.jsx("button",{onClick:ne=>{ne.stopPropagation(),ie(O)},className:Z("hover:bg-interactive-hover rounded transition-opacity",m?"p-1.5":"p-1",f?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:s.jsx(sn,{className:Z("text-muted-foreground",m?"h-3.5 w-3.5":"h-3 w-3")})}),s.jsx("button",{onClick:ne=>{ne.stopPropagation(),$(O.path)},className:Z("hover:bg-interactive-hover rounded transition-opacity",m?"p-1.5":"p-1",f?"opacity-60":"opacity-0 group-hover:opacity-100"),title:me?"Unpin directory":"Pin directory",children:me?s.jsx(np,{className:Z("text-primary",m?"h-3.5 w-3.5":"h-3 w-3")}):s.jsx(Sh,{className:Z("text-muted-foreground",m?"h-3.5 w-3.5":"h-3 w-3")})})]});return r==="inline"?s.jsxs("div",{children:[s.jsx("div",{className:Z("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",m?"px-1.5 py-1":"px-2 py-1.5",fe?"bg-primary/10 text-primary":"hover:bg-interactive-hover/50 text-foreground"),style:{paddingLeft:`${se*(m?12:14)+(m?4:6)}px`},children:de}),X&&s.jsxs(s.Fragment,{children:[S===O.path&&s.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(se+1)*14+6}px`},children:[s.jsx("div",{className:"w-4"}),s.jsx(ea,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(fs,{ref:_,value:k,onChange:ne=>D(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"?(ne.preventDefault(),ne.stopPropagation(),oe()):ne.key==="Escape"&&(ne.preventDefault(),ne.stopPropagation(),Y())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-interactive-selection selection:text-interactive-selection-foreground",placeholder:"new_directory"}),s.jsx("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),oe()},className:"p-1 hover:bg-interactive-hover rounded",title:"Create directory",children:s.jsx(Ts,{className:"h-3 w-3 text-green-600"})}),s.jsx("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),Y()},className:"p-1 hover:bg-interactive-hover rounded",title:"Cancel",children:s.jsx(zs,{className:"h-3 w-3 text-muted-foreground"})})]}),O.children&&O.children.map(ne=>re(ne,se+1))]})]},O.path):s.jsxs("div",{children:[s.jsxs(is,{className:Z("flex items-center gap-1 cursor-pointer group",t===O.path&&"bg-interactive-selection"),style:{paddingLeft:`${se*12+8}px`},onSelect:ne=>{ne.preventDefault()},children:[L&&s.jsx("button",{onClick:ne=>{ne.stopPropagation(),le(O)},className:"p-0.5 hover:bg-interactive-hover rounded",children:X?s.jsx(Us,{className:"h-3 w-3"}):s.jsx(ar,{className:"h-3 w-3"})}),!L&&s.jsx("div",{className:"w-4"}),de]}),X&&s.jsxs("div",{children:[S===O.path&&s.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(se+1)*12+8}px`},children:[s.jsx("div",{className:"w-4"}),s.jsx(ea,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(fs,{ref:_,value:k,onChange:ne=>D(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"?(ne.preventDefault(),ne.stopPropagation(),oe()):ne.key==="Escape"&&(ne.preventDefault(),ne.stopPropagation(),Y())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-interactive-selection selection:text-interactive-selection-foreground",placeholder:"new_directory"}),s.jsx("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),oe()},className:"p-1 hover:bg-interactive-hover rounded",title:"Create directory",children:s.jsx(Ts,{className:"h-3 w-3 text-green-600"})}),s.jsx("button",{onClick:ne=>{ne.preventDefault(),ne.stopPropagation(),Y()},className:"p-1 hover:bg-interactive-hover rounded",title:"Cancel",children:s.jsx(zs,{className:"h-3 w-3 text-muted-foreground"})})]}),O.children&&O.children.map(ne=>re(ne,se+1))]})]},O.path)},ue=(O,se)=>{if(r==="inline"){const X=t===se;return s.jsxs("div",{className:Z("group flex items-center gap-2 mx-1 rounded-lg transition-colors",m?"px-1.5 py-1":"px-2 py-1.5",X?"bg-primary/10":"hover:bg-interactive-hover/50"),children:[s.jsxs("button",{onClick:()=>V(se),onDoubleClick:L=>{L.stopPropagation(),i&&i(se)},className:Z("flex flex-1 items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded min-w-0",X?"text-primary":"text-foreground"),children:[s.jsx(ea,{className:Z("flex-shrink-0",m?"h-4 w-4":"h-3.5 w-3.5",X?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Z("typography-ui-label font-medium truncate flex-shrink-0",X?"text-primary":"text-foreground"),children:O}),s.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:ia(se,j)})]}),s.jsx("button",{onClick:()=>$(se),className:Z("hover:bg-interactive-hover rounded-md transition-opacity",m?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:s.jsx(np,{className:Z("text-primary","h-3.5 w-3.5")})})]},se)}return s.jsxs(is,{onSelect:X=>{X.preventDefault(),V(se),a==="immediate"&&w(!1)},className:Z("flex items-start gap-2 cursor-pointer group py-2",t===se&&"bg-interactive-selection"),children:[s.jsx(ea,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium",children:O}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:ia(se,j)})]}),s.jsx("button",{onClick:X=>{X.stopPropagation(),X.preventDefault(),$(se)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-interactive-hover rounded transition-opacity",title:"Unpin directory",children:s.jsx(np,{className:"h-3 w-3 text-primary"})})]},se)},Q=s.jsx(s.Fragment,{children:U?s.jsxs(s.Fragment,{children:[G.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>E(O=>!O),className:Z("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-interactive-hover/30 rounded transition-colors uppercase tracking-wide",m?"px-1.5 py-1":"px-2 py-1.5"),children:[M?s.jsx(Us,{className:m?"h-3.5 w-3.5":"h-3 w-3"}):s.jsx(ar,{className:m?"h-3.5 w-3.5":"h-3 w-3"}),s.jsx("span",{children:"Pinned"}),s.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/60 normal-case tracking-normal",children:G.length})]}),M&&G.map(({name:O,path:se})=>ue(O,se)),r==="dropdown"&&s.jsx(Kn,{}),r==="inline"&&M&&s.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),s.jsx("div",{className:Z("typography-meta font-medium text-muted-foreground/80 flex items-center gap-1.5 uppercase tracking-wide",m?"px-1.5 py-1":"px-2 py-1.5"),children:"Browse"}),h?s.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):p.map(O=>re(O)),!h&&p.length===0&&s.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):s.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return r==="inline"?s.jsx("div",{className:Z("overflow-hidden flex flex-col",o),children:s.jsx(Ps,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Q})}):s.jsxs(Ys,{open:b,onOpenChange:w,children:[s.jsx(Js,{asChild:!0,children:s.jsxs(ot,{variant:"ghost",className:Z("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",n),"aria-label":"Select working directory",children:[s.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[s.jsx(ea,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"truncate",title:t,children:ia(t,j)})]}),s.jsx(Us,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(Xs,{align:"start",className:"w-[350px]",children:s.jsx(Ps,{outerClassName:"h-full",className:"w-full",children:Q})})]})},dS=u.forwardRef((t,e)=>{const n=Me.c(40),{inputValue:r,homeDirectory:o,onSelectSuggestion:a,visible:i,onClose:l,showHidden:c}=t;let d;n[0]===Symbol.for("react.memo_cache_sentinel")?(d=[],n[0]=d):d=n[0];const[f,m]=u.useState(d),[p,g]=u.useState(!1),[y,x]=u.useState(0),h=u.useRef(null);let v;n[1]===Symbol.for("react.memo_cache_sentinel")?(v=[],n[1]=v):v=n[1];const b=u.useRef(v),w=eG;let j;n[2]!==o?(j=V=>V.startsWith("~")&&o?V.replace(/^~/,o):V,n[2]=o,n[3]=j):j=n[3];const F=j;let A;n[4]!==F?(A=V=>{const q=F(V);if(q.endsWith("/"))return q;const $=q.lastIndexOf("/");return $===-1?"":$===0?"/":q.substring(0,$+1)},n[4]=F,n[5]=A):A=n[5];const C=A;let S;n[6]!==F?(S=V=>{const q=F(V);if(q.endsWith("/"))return"";const $=q.lastIndexOf("/");return $===-1?q:q.substring($+1)},n[6]=F,n[7]=S):S=n[7];const N=S,k=Ed(r,150);let D,M;n[8]!==k||n[9]!==C||n[10]!==N||n[11]!==c||n[12]!==i?(D=()=>{if(!i||!k){m([]);return}const V=C(k),q=N(k).toLowerCase();if(!V){m([]);return}let $=!1;return g(!0),Lt.listLocalDirectory(V).then(G=>{if($)return;const W=G.filter(te=>!(!te.isDirectory||!c&&te.name.startsWith("."))),J=q?W.map(te=>{const le=w(q,te.name);return le!==null?{entry:te,score:le}:null}).filter(tG).sort(sG).map(nG):W.sort(rG);m(J.slice(0,10)),x(0)}).catch(()=>{$||m([])}).finally(()=>{$||g(!1)}),()=>{$=!0}},M=[i,k,C,N,c,w],n[8]=k,n[9]=C,n[10]=N,n[11]=c,n[12]=i,n[13]=D,n[14]=M):(D=n[13],M=n[14]),u.useEffect(D,M);let E,_;n[15]!==y?(E=()=>{b.current[y]?.scrollIntoView({behavior:"smooth",block:"nearest"})},_=[y],n[15]=y,n[16]=E,n[17]=_):(E=n[16],_=n[17]),u.useEffect(E,_);let T,P;n[18]!==l||n[19]!==i?(T=()=>{if(!i)return;const V=q=>{const $=q.target;!$||!h.current||h.current.contains($)||l()};return document.addEventListener("pointerdown",V,!0),()=>{document.removeEventListener("pointerdown",V,!0)}},P=[i,l],n[18]=l,n[19]=i,n[20]=T,n[21]=P):(T=n[20],P=n[21]),u.useEffect(T,P);let H;n[22]!==a?(H=V=>{const q=V.path.endsWith("/")?V.path:V.path+"/";a(q)},n[22]=a,n[23]=H):H=n[23];const R=H;let I,B;if(n[24]!==R||n[25]!==l||n[26]!==y||n[27]!==f||n[28]!==i?(I=()=>({handleKeyDown:V=>{if(!i||f.length===0)return!1;const q=f.length;if(V.key==="Tab"){if(V.preventDefault(),V.shiftKey)x($=>($-1+q)%q);else if(q===1){const $=f[0];$&&R($)}else x($=>($+1)%q);return!0}if(V.key==="ArrowDown")return V.preventDefault(),x($=>($+1)%q),!0;if(V.key==="ArrowUp")return V.preventDefault(),x($=>($-1+q)%q),!0;if(V.key==="Enter"){V.preventDefault();const $=(y%q+q)%q,G=f[$];return G&&R(G),l(),!0}return V.key==="Escape"?(V.preventDefault(),l(),!0):!1}}),B=[i,f,y,R,l],n[24]=R,n[25]=l,n[26]=y,n[27]=f,n[28]=i,n[29]=I,n[30]=B):(I=n[29],B=n[30]),u.useImperativeHandle(e,I,B),!i||f.length===0&&!p)return null;let z;n[31]!==R||n[32]!==p||n[33]!==l||n[34]!==y||n[35]!==f?(z=p?s.jsx("div",{className:"flex items-center justify-center py-3",children:s.jsx(br,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):s.jsx("div",{className:"overflow-y-auto py-1",children:f.map((V,q)=>{const $=y===q;return s.jsxs("div",{ref:G=>{b.current[q]=G},className:Z("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",$&&"bg-interactive-selection"),onClick:()=>{R(V),l()},onMouseEnter:()=>x(q),children:[s.jsx(no,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),s.jsx("span",{className:"truncate",children:V.name})]},V.path)})}),n[31]=R,n[32]=p,n[33]=l,n[34]=y,n[35]=f,n[36]=z):z=n[36];let U;n[37]===Symbol.for("react.memo_cache_sentinel")?(U=s.jsx("div",{className:"px-3 py-1.5 border-t typography-meta text-muted-foreground bg-sidebar/50",children:"Tab cycle • ↑↓ navigate • Enter select"}),n[37]=U):U=n[37];let K;return n[38]!==z?(K=s.jsxs("div",{ref:h,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-none top-full mt-1 left-0 flex flex-col overflow-hidden",children:[z,U]}),n[38]=z,n[39]=K):K=n[39],K});dS.displayName="DirectoryAutocomplete";function eG(t,e){const n=t.trim().toLowerCase();if(!n)return 0;const r=e.toLowerCase();let o=0,a=-1,i=0;for(let l=0;l<n.length;l=l+1,l){const c=n[l];if(!c||c===" ")continue;const d=r.indexOf(c,a+1);if(d===-1)return null;const f=d-a-1;if(f===0?i=i+1:i=0,o=o+10,o=o+Math.max(0,18-d),o=o-Math.max(0,f),d===0)o=o+12;else{const m=r[d-1];(m==="/"||m==="_"||m==="-"||m==="."||m===" ")&&(o=o+10)}o=o+(i>0?12:0),a=d}return o=o+Math.max(0,24-Math.round(r.length/3)),o}function tG(t){return t!==null}function sG(t,e){return e.score-t.score||t.entry.name.localeCompare(e.entry.name)}function nG(t){return t.entry}function rG(t,e){return t.name.localeCompare(e.name)}const oG=({open:t,onOpenChange:e})=>{const{currentDirectory:n,homeDirectory:r,isHomeReady:o}=Rs(),{addProject:a,getActiveProject:i}=bs(),[l,c]=u.useState(null),[d,f]=u.useState(""),[m,p]=u.useState(!1),[g,y]=u.useState(!1),x=mc(),{isDesktop:h,requestAccess:v,startAccessing:b}=Rm(),{isMobile:w}=hn(),[j,F]=u.useState(!1),A=u.useRef(null),C=u.useCallback(q=>q?ia(q,r):"",[r]);u.useEffect(()=>{if(t){p(!1),y(!1),F(!1);const $=i()?.path||n||r||"";c($),f(C($))}},[t,n,r,C,i]),u.useEffect(()=>{!t||m||l||r&&o&&(c(r),p(!0),f("~"))},[t,m,l,r,o]);const S=u.useCallback(()=>{e(!1)},[e]),N=u.useCallback(async q=>{if(!(!q||g)){y(!0);try{let $=q,G;if(h){const J=await v(q);if(!J.success){ce.error("Unable to access directory",{description:J.error||"Desktop denied directory access."});return}$=J.path??q,G=J.projectId;const te=await b($);if(!te.success){ce.error("Failed to open directory",{description:te.error||"Desktop could not grant file access."});return}}if(!a($,{id:G})){ce.error("Failed to add project",{description:"Please select a valid directory path."});return}S()}catch($){ce.error("Failed to select directory",{description:$ instanceof Error?$.message:"Unknown error occurred."})}finally{y(!1)}}},[a,S,h,v,b,g]),k=u.useCallback(async()=>{const q=d.trim()||l;q&&await N(q)},[N,d,l]),D=u.useCallback(q=>{c(q),p(!0),f(C(q))},[C]),M=u.useCallback(async q=>{c(q),p(!0),f(C(q)),await N(q)},[N,C]),E=u.useCallback(q=>{const $=q.target.value;if(f($),p(!0),F($.startsWith("/")||$.startsWith("~")),$.startsWith("/")||$.startsWith("~")){const G=$.startsWith("~")&&r?$.replace(/^~/,r):$;c(G)}},[r]),_=u.useCallback(q=>{A.current?.handleKeyDown(q)||q.key==="Enter"&&(q.preventDefault(),k())},[k]),T=u.useCallback(q=>{c(q),p(!0),f(C(q))},[C]),P=u.useCallback(()=>{F(!1)},[]),H=u.useCallback(()=>{Wc(!x)},[x]),R=s.jsxs("button",{type:"button",onClick:H,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-interactive-hover/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[x?s.jsx($o,{className:"h-4 w-4 text-primary"}):s.jsx(Lo,{className:"h-4 w-4"}),"Show hidden"]}),I=s.jsxs(en,{className:"flex-shrink-0 px-4 pb-2 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-3 sm:pt-0",children:[s.jsx(Zs,{children:"Add project directory"}),s.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[s.jsx(nn,{className:"flex-1",children:"Choose a folder to add as a project."}),R]})]}),B=s.jsxs("div",{className:"relative",children:[s.jsx(fs,{value:d,onChange:E,onKeyDown:_,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),s.jsx(dS,{ref:A,inputValue:d,homeDirectory:r,onSelectSuggestion:T,visible:j,onClose:P,showHidden:x})]}),z=s.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:s.jsx(z1,{variant:"inline",currentPath:l??n,onSelectPath:D,onDoubleClickPath:M,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?r:null,isRootReady:o})}),U=s.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[s.jsx("div",{className:"flex-shrink-0",children:B}),s.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:R}),s.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:s.jsx(z1,{variant:"inline",currentPath:l??n,onSelectPath:D,onDoubleClickPath:M,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:x,rootDirectory:o?r:null,isRootReady:o,alwaysShowActions:!0})})]}),K=s.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[B,z]}),V=()=>s.jsxs(s.Fragment,{children:[s.jsx(ot,{variant:"ghost",onClick:S,disabled:g,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),s.jsx(ot,{onClick:k,disabled:g||!m||!l&&!d.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:g?"Adding...":"Add Project"})]});return w?s.jsx(Ur,{open:t,onClose:()=>e(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:s.jsx("div",{className:"flex flex-row gap-2",children:V()}),children:U}):s.jsx(Vs,{open:t,onOpenChange:e,children:s.jsxs(Ws,{className:Z("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:q=>{q.preventDefault()},children:[I,K,s.jsx(In,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-4 sm:pb-0",children:V()})]})})},hi=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,gi=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},aG=()=>{const[t,e]=u.useState(!1),[n,r]=u.useState(!1),[o,a]=u.useState(null),[i,l]=u.useState([]),[c,d]=u.useState(!1),[f,m]=u.useState(!1),[p,g]=u.useState(!1),[y,x]=u.useState(!1),[h,v]=u.useState(new Set),{deleteSession:b,deleteSessions:w,loadSessions:j,getWorktreeMetadata:F}=Re(),A=Te(L=>L.showDeletionDialog),C=Te(L=>L.setShowDeletionDialog),{currentDirectory:S,homeDirectory:N,isHomeReady:k}=Rs(),{projects:D,addProject:M,activeProjectId:E}=bs(),{requestAccess:_,startAccessing:T}=Rm(),{isMobile:P,isTablet:H,hasTouchInput:R}=hn(),I=P||H||R,B=u.useMemo(()=>{const me=(E?D.find(fe=>fe.id===E)??null:null)?.path??S;return gi(me)},[E,S,D]),z=u.useCallback(L=>{const fe=gi(L.projectDirectory)||B;return{id:(D.find(de=>gi(de.path)===fe)??null)?.id??`path:${fe}`,path:fe}},[B,D]),U=y&&h.size>0,K=u.useMemo(()=>{const L=o?.worktree;return L&&typeof L.branch=="string"&&L.branch.trim().length>0?!0:i.length>0&&i.every(({metadata:me})=>typeof me.branch=="string"&&me.branch.trim().length>0)},[o?.worktree,i]),V=o?.mode==="worktree",q=V,$=p||!V||!K,G=p||!V;u.useEffect(()=>{j()},[j,S]);const W=u.useMemo(()=>D.map(L=>`${L.id}:${L.path}`).join("|"),[D]),J=u.useRef(W);u.useEffect(()=>{W!==J.current&&(J.current=W,j())},[j,W]),u.useEffect(()=>{if(!(n||!k||D.length>0)){if(r(!0),tn()&&Ar()){_("").then(async L=>{if(!L.success||!L.path){L.error&&L.error!=="Directory selection cancelled"&&ce.error("Failed to select directory",{description:L.error});return}const me=await T(L.path);if(!me.success){ce.error("Failed to open directory",{description:me.error||"Desktop could not grant file access."});return}M(L.path,{id:L.projectId})||ce.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(L=>{console.error("Desktop: Error selecting directory:",L),ce.error("Failed to select directory")});return}e(!0)}},[M,n,k,D.length,_,T]);const te=u.useCallback(L=>{a({sessions:L.sessions,dateLabel:L.dateLabel,mode:L.mode??"session",worktree:L.worktree??null})},[]),le=u.useCallback(()=>{a(null),l([]),d(!1),m(!1),g(!1),x(!1),v(new Set)},[]),ae=u.useCallback(async L=>{if(L.sessions.length===0)return;if(L.sessions.length===1){const de=L.sessions[0];await b(de.id)?ce.success("Session deleted"):ce.error("Failed to delete session");return}const me=L.sessions.map(de=>de.id),{deletedIds:fe,failedIds:pe}=await w(me);if(fe.length>0){const de=pe.length>0?`${pe.length} session${pe.length===1?"":"s"} could not be deleted.`:L.dateLabel?`Removed all sessions from ${L.dateLabel}.`:void 0;ce.success(`Deleted ${fe.length} session${fe.length===1?"":"s"}`,{description:hi(de)})}pe.length>0&&ce.error(`Failed to delete ${pe.length} session${pe.length===1?"":"s"}`,{description:hi("Please try again in a moment.")})},[b,w]);u.useEffect(()=>ma.onDeleteRequest(L=>{if(!A&&(L.mode??"session")==="session"){ae(L);return}te(L)}),[te,A,ae]),u.useEffect(()=>ma.onDirectoryRequest(()=>{e(!0)}),[]),u.useEffect(()=>{if(!o){l([]),d(!1),m(!1),x(!1),v(new Set);return}const L=o.sessions.map(pe=>{const de=F(pe.id);return de?{session:pe,metadata:de}:null}).filter(pe=>!!pe);l(L),d(!1),x(!1),v(new Set);const me=new Map;if(o.worktree?.path&&me.set(gi(o.worktree.path),o.worktree),L.forEach(({metadata:pe})=>{pe.path&&me.set(gi(pe.path),pe)}),me.size===0){x(!0);return}let fe=!1;return(async()=>{const pe=new Map,de=new Set;await Promise.all(Array.from(me.entries()).map(async([ne,ge])=>{try{const we=await Fd(ge.path);pe.set(ne,we),we?.isDirty&&de.add(ne)}catch{ge.status&&(pe.set(ne,ge.status),ge.status.isDirty&&de.add(ne))}})).catch(ne=>{console.warn("Failed to inspect worktree status before deletion:",ne)}),!fe&&(v(de),x(!0),a(ne=>{if(!ne?.worktree?.path)return ne;const ge=gi(ne.worktree.path),we=pe.get(ge);if(!we)return ne;const Oe=ne.worktree.status;return Oe?.isDirty===we.isDirty&&Oe?.ahead===we.ahead&&Oe?.behind===we.behind&&Oe?.upstream===we.upstream?ne:{...ne,worktree:{...ne.worktree,status:we}}}),l(ne=>ne.map(ge=>{const we=gi(ge.metadata.path),Oe=pe.get(we);return Oe?{session:ge.session,metadata:{...ge.metadata,status:Oe}}:ge})))})(),()=>{fe=!0}},[o,F]),u.useEffect(()=>{K||d(!1)},[K]);const ie=u.useCallback(async(L,me)=>{const fe=c&&K;try{return await Cm(z(L),L,{deleteRemoteBranch:fe,deleteLocalBranch:me}),!0}catch(pe){return ce.error("Failed to remove worktree",{description:hi(pe instanceof Error?pe.message:"Please try again.")}),!1}},[K,c,z]),oe=u.useCallback(async()=>{if(o){g(!0);try{const L=q,me=L&&c,fe=L&&f;if(o.sessions.length===0&&V&&o.worktree){if(!await ie(o.worktree,fe)){le();return}const ne=c&&K?"Worktree and remote branch removed.":"Worktree removed.";ce.success("Worktree removed",{description:hi(ne)}),le(),j();return}if(o.sessions.length===1){const pe=o.sessions[0];if(!await b(pe.id,{archiveWorktree:V?!1:L,deleteRemoteBranch:me,deleteLocalBranch:fe})){ce.error("Failed to delete session"),g(!1);return}const ne=!V&&L?me?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;ce.success("Session deleted",{description:hi(ne),action:{label:"OK",onClick:()=>{}}})}else{const pe=o.sessions.map(ge=>ge.id),{deletedIds:de,failedIds:ne}=await w(pe,{archiveWorktree:V?!1:L,deleteRemoteBranch:me,deleteLocalBranch:fe});if(V&&o.worktree&&ne.length===0&&await ie(o.worktree,fe)&&await j(),de.length>0){const ge=!V&&L?me?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Oe=[ne.length>0?`${ne.length} session${ne.length===1?"":"s"} could not be deleted.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0,ge].filter(Boolean).join(" ");ce.success(`Deleted ${de.length} session${de.length===1?"":"s"}`,{description:hi(Oe||void 0),action:{label:"OK",onClick:()=>{}}})}if(ne.length>0&&(ce.error(`Failed to delete ${ne.length} session${ne.length===1?"":"s"}`,{description:hi("Please try again in a moment.")}),de.length===0)){g(!1);return}}V&&o.sessions.length===1&&o.worktree&&await ie(o.worktree,fe)&&await j(),le()}finally{g(!1)}}},[o,c,f,b,w,le,q,V,K,ie,j]),Y=o?.worktree??i[0]?.metadata??null,re=o?o.mode==="worktree"?o.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${o.sessions.length===1?"1 linked session":`${o.sessions.length} linked sessions`}.`:`This action permanently removes ${o.sessions.length===1?"1 session":`${o.sessions.length} sessions`}${o.dateLabel?` from ${o.dateLabel}`:""}.`:"",ue=o?s.jsxs("div",{className:Z(V?"space-y-3":"space-y-2"),children:[o.sessions.length>0&&s.jsxs("div",{className:Z(V?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[V&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-meta font-medium text-foreground",children:o.sessions.length===1?"Linked session":"Linked sessions"}),s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:o.sessions.length})]}),s.jsxs("ul",{className:Z(V?"mt-2 space-y-1":"space-y-0.5"),children:[o.sessions.slice(0,5).map(L=>s.jsxs("li",{className:Z(V?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[s.jsx("span",{className:Z(!V&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:L.title||"Untitled Session"})]},L.id)),o.sessions.length>5&&s.jsxs("li",{className:Z(V?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",o.sessions.length-5," more"]})]})]}),V?s.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(bn,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),Y?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Y.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Y?ia(Y.path,N):"Worktree path unavailable."}),U&&s.jsx("p",{className:"typography-micro text-status-warning",children:"Uncommitted changes will be discarded."})]}):s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.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,Q=V?K?s.jsxs("button",{type:"button",onClick:()=>{$||d(L=>!L)},disabled:$,className:Z("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",$?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[c?s.jsx($o,{className:"size-4 text-primary"}):s.jsx(Lo,{className:"size-4"}),"Delete remote branch"]}):s.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,O=V?s.jsxs("button",{type:"button",onClick:()=>{G||m(L=>!L)},disabled:G,className:Z("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",G?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[f?s.jsx($o,{className:"size-4 text-primary"}):s.jsx(Lo,{className:"size-4"}),"Delete local branch"]}):null,se=V?s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[O,Q]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ot,{variant:"ghost",onClick:le,disabled:p,children:"Cancel"}),s.jsx(ot,{variant:"destructive",onClick:oe,disabled:p,children:p?"Deleting…":"Delete worktree"})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>C(!A),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":!A,children:[A?s.jsx(Lo,{className:"size-4"}):s.jsx($o,{className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ot,{variant:"ghost",onClick:le,disabled:p,children:"Cancel"}),s.jsx(ot,{variant:"destructive",onClick:oe,disabled:p,children:p?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),X=V?"Delete worktree":o?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[I?s.jsx(Ur,{open:!!o,onClose:()=>{p||le()},title:X,footer:s.jsx("div",{className:"flex justify-end gap-2",children:se}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[re&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:re}),ue]})}):s.jsx(Vs,{open:!!o,onOpenChange:L=>{if(!L){if(p)return;le()}},children:s.jsxs(Ws,{className:Z(V?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[s.jsxs(en,{children:[s.jsxs(Zs,{className:Z(V&&"flex items-center gap-2"),children:[V&&s.jsx(Qn,{className:"h-5 w-5"}),X]}),re&&s.jsx(nn,{children:re})]}),s.jsx("div",{className:Z(V&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:ue}),s.jsx(In,{className:"mt-2 gap-2 pt-1 pb-1",children:se})]})}),s.jsx(oG,{open:t,onOpenChange:e})]})},mg=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),iG=(t,e)=>{const n=mg(t),r=mg(e);return`${n}-${r}`.substring(0,60)},H1=(t,e)=>`${t}/${e}`,lG=()=>{const t=bs.getState(),e=t.activeProjectId;if(!e)return null;const n=t.projects.find(o=>o.id===e);if(n?.path)return{id:n.id,path:n.path};const r=Rs.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},rd=Fn()(Gn(t=>({isLoading:!1,error:null,createMultiRun:async e=>{const n=e.name.trim(),r=e.prompt.trim(),{models:o,agent:a,files:i,setupCommands:l}=e;if(!n)return t({error:"Group name is required"}),null;if(!r)return t({error:"Prompt is required"}),null;if(o.length<1)return t({error:"Select at least 1 model"}),null;if(o.length>5)return t({error:"Maximum 5 models allowed"}),null;t({isLoading:!0,error:null});try{const c=lG();if(!c)return t({error:"Select a project",isLoading:!1}),null;const d=c.path;if(!await Da(d))return t({error:"Not in a git repository",isLoading:!1}),null;const m=mg(n),p=await ni(d),g=await yx(d),y=[],x=l?.filter(A=>A.trim().length>0)??[],h=new Map;for(const A of o){const C=`${A.providerID}:${A.modelID}`;h.set(C,(h.get(C)||0)+1)}const v=new Map;for(const A of o){const C=`${A.providerID}:${A.modelID}`,S=h.get(C)||1,N=(v.get(C)||0)+1;v.set(C,N);const k=iG(A.providerID,A.modelID),D=S>1?H1(m,`${k}/${N}`):H1(m,k);try{const M=await Bd(c,{preferredName:D,mode:"new",branchName:D,worktreeName:D,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:x},{resolvedRootTrackingRemote:g}),E={...M,createdFromBranch:p,kind:"standard"},_=S>1?`${m}/${A.providerID}/${A.modelID}/${N}`:`${m}/${A.providerID}/${A.modelID}`,T=await Lt.withDirectory(M.path,()=>Lt.createSession({title:_}));Bs.getState().setWorktreeMetadata(T.id,E),y.push({sessionId:T.id,worktreePath:M.path,providerID:A.providerID,modelID:A.modelID,variant:A.variant})}catch(M){console.warn("[MultiRun] Failed to create session:",M)}}const b=l?.filter(A=>A.trim().length>0)??[];b.length>0&&Mw(c,b).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const w=y.map(A=>A.sessionId),j=y[0]?.sessionId??null;if(w.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const F=i?.map(A=>({type:"file",mime:A.mime,filename:A.filename,url:A.url}));try{await Bs.getState().loadSessions()}catch{}return(async()=>{try{await Promise.allSettled(y.map(async A=>{try{await Lt.withDirectory(A.worktreePath,()=>Lt.sendMessage({id:A.sessionId,providerID:A.providerID,modelID:A.modelID,variant:A.variant,text:r,agent:a,files:F}))}catch(C){console.warn("[MultiRun] Failed to start run:",C)}}))}catch(A){console.warn("[MultiRun] Failed to start runs:",A)}})(),t({isLoading:!1}),{groupSlug:m,sessionIds:w,firstSessionId:j}}catch(c){return t({error:c instanceof Error?c.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"})),uS="h-7",om=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,cG=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),dG=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const e=cG.format(t);return e.endsWith(".0")?e.slice(0,-2):e},uG=t=>{const e=Me.c(12),{model:n,instanceIndex:r,totalSameModel:o,onRemove:a}=t,i=n.displayName||`${n.providerID}/${n.modelID}`,l=o>1?`${i} (${r})`:i;let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=Z("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",uS),e[0]=c):c=e[0];let d;e[1]!==n.providerID?(d=s.jsx(Bn,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=d):d=e[2];let f;e[3]!==l?(f=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=f):f=e[4];let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=s.jsx(zs,{className:"h-3.5 w-3.5"}),e[5]=m):m=e[5];let p;e[6]!==a?(p=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:m}),e[6]=a,e[7]=p):p=e[7];let g;return e[8]!==d||e[9]!==f||e[10]!==p?(g=s.jsxs("div",{className:c,children:[d,f,p]}),e[8]=d,e[9]=f,e[10]=p,e[11]=g):g=e[11],g},fS=({selectedModels:t,onAdd:e,onRemove:n,onUpdate:r,minModels:o,addButtonLabel:a="Add model",showChips:i=!0,maxModels:l})=>{const{providers:c,modelsMetadata:d}=rs(),{favoriteModelsList:f,recentModelsList:m}=Em(),[p,g]=u.useState(!1),[y,x]=u.useState(""),[h,v]=u.useState(0),[b,w]=u.useState(null),j=u.useRef(null),F=u.useRef(null),A=u.useRef(null),C=u.useRef([]),S=u.useMemo(()=>{const R=new Map;for(const I of t){const B=`${I.providerID}:${I.modelID}`;R.set(B,(R.get(B)||0)+1)}return R},[t]),N=u.useCallback(R=>t.filter(B=>B.providerID===R.providerID&&B.modelID===R.modelID).findIndex(B=>B.instanceId===R.instanceId)+1,[t]),k=(R,I)=>{const B=`${R}/${I}`;return d.get(B)},D=R=>{const I=R?.name||R?.id||"",B=String(I);return B.length>40?B.substring(0,37)+"...":B},M=u.useCallback((R,I)=>{if(!y.trim())return!0;const B=y.toLowerCase();return R.toLowerCase().includes(B)||I.toLowerCase().includes(B)},[y]),E=u.useMemo(()=>f.filter(({model:R,providerID:I})=>{const z=c.find(K=>K.id===I)?.name||I,U=D(R);return M(U,z)}),[f,c,M]),_=u.useMemo(()=>m.filter(({model:R,providerID:I})=>{const z=c.find(K=>K.id===I)?.name||I,U=D(R);return M(U,z)}),[m,c,M]),T=u.useMemo(()=>c.map(R=>{const B=(Array.isArray(R.models)?R.models:[]).filter(z=>{const U=D(z);return M(U,R.name||R.id||"")});return{...R,models:B}}).filter(R=>R.models.length>0),[c,M]),P=E.length>0||_.length>0||T.length>0;u.useEffect(()=>{if(p&&A.current){const I=A.current.getBoundingClientRect().top-100;w(Math.max(150,Math.min(400,I)))}},[p]),u.useEffect(()=>{p&&j.current&&j.current.focus()},[p]),u.useEffect(()=>{if(!p)return;const R=I=>{F.current&&!F.current.contains(I.target)&&(g(!1),x(""),v(0))};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[p]),u.useEffect(()=>{v(0)},[y]);const H=(R,I,B,z,U,K)=>{const V=`${I}:${B}`,q=S.get(V)||0,$=k(I,B),G=dG($?.limit?.context),W=z==="fav"||z==="recent";return s.jsxs("button",{ref:J=>{C.current[U]=J},type:"button",onClick:()=>{e({providerID:I,modelID:B,displayName:R.name||B,instanceId:om()})},onMouseEnter:()=>v(U),className:Z("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",K?"bg-interactive-selection":"hover:bg-interactive-hover/50"),children:[s.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[W&&s.jsx(Bn,{providerId:I,className:"h-3.5 w-3.5 flex-shrink-0"}),s.jsx("span",{className:"font-medium truncate",children:D(R)}),G&&s.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:G})]}),q>0&&s.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",q]})]},`${z}-${V}`)};return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[s.jsxs("div",{className:"relative",ref:F,children:[s.jsxs(ot,{ref:A,type:"button",variant:"outline",size:"sm",className:uS,onClick:()=>g(!p),children:[s.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const R=[];E.forEach(({model:U,providerID:K,modelID:V})=>{R.push({model:U,providerID:K,modelID:V,section:"fav"})}),_.forEach(({model:U,providerID:K,modelID:V})=>{R.push({model:U,providerID:K,modelID:V,section:"recent"})}),T.forEach(U=>{U.models.forEach(K=>{R.push({model:K,providerID:U.id,modelID:K.id,section:"provider"})})});const I=R.length,B=U=>{if(!ax(U))if(U.key==="ArrowDown"){U.preventDefault(),U.stopPropagation();const K=(h+1)%Math.max(1,I);v(K),setTimeout(()=>{C.current[K]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(U.key==="ArrowUp"){U.preventDefault(),U.stopPropagation();const K=(h-1+Math.max(1,I))%Math.max(1,I);v(K),setTimeout(()=>{C.current[K]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(U.key==="Enter"){U.preventDefault(),U.stopPropagation();const K=R[h];K&&e({providerID:K.providerID,modelID:K.modelID,displayName:K.model.name||K.modelID,instanceId:om()})}else U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),g(!1),x(""),v(0))};let z=0;return s.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden shadow-none w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[s.jsx("div",{className:"p-2 border-b border-border/40",children:s.jsxs("div",{className:"relative",children:[s.jsx(Cr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),s.jsx(fs,{ref:j,type:"text",placeholder:"Search models",value:y,onChange:U=>x(U.target.value),onKeyDown:B,className:"h-8 pl-8 typography-meta"})]})}),s.jsx(Ps,{outerClassName:"flex-1",style:{maxHeight:b?`${b}px`:"300px"},children:s.jsxs("div",{className:"p-1",children:[!P&&s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),E.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[s.jsx(na,{className:"h-4 w-4 text-primary"}),"Favorites"]}),E.map(({model:U,providerID:K,modelID:V})=>{const q=z++;return H(U,K,V,"fav",q,h===q)})]}),_.length>0&&s.jsxs(s.Fragment,{children:[E.length>0&&s.jsx("div",{className:"h-px bg-border/40 my-1"}),s.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[s.jsx(Vo,{className:"h-4 w-4"}),"Recent"]}),_.map(({model:U,providerID:K,modelID:V})=>{const q=z++;return H(U,K,V,"recent",q,h===q)})]}),(E.length>0||_.length>0)&&T.length>0&&s.jsx("div",{className:"h-px bg-border/40 my-1"}),T.map((U,K)=>s.jsxs(u.Fragment,{children:[K>0&&s.jsx("div",{className:"h-px bg-border/40 my-1"}),s.jsxs("div",{style:{backgroundColor:"var(--surface-elevated)"},className:"typography-micro font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2 -mx-1 px-3 py-1.5 sticky top-0 z-10 border-b border-border/30",children:[s.jsx(Bn,{providerId:U.id,className:"h-4 w-4 flex-shrink-0"}),U.name]}),U.models.map(V=>{const q=z++;return H(V,U.id,V.id,"provider",q,h===q)})]},U.id))]})}),s.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),i&&t.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:t.map((R,I)=>{const B=`${R.providerID}:${R.modelID}`,z=S.get(B)||1,U=N(R),V=c.find(J=>J.id===R.providerID)?.models.find(J=>J.id===R.modelID),q=V?.variants?Object.keys(V.variants):[],$=q.length>0,G="__default__",W=R.variant??G;return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(uG,{model:R,instanceIndex:U,totalSameModel:z,onRemove:()=>n(I)}),$&&s.jsxs(un,{value:W,onValueChange:J=>{if(!r)return;r(I,{...R,variant:J===G?void 0:J})},children:[s.jsxs(fn,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-interactive-selection/20 border-border/30 hover:bg-interactive-hover/30 typography-meta font-medium text-foreground",children:[s.jsx(ua,{className:Z("h-3.5 w-3.5 flex-shrink-0",W===G?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(An,{placeholder:"Thinking"})]}),s.jsxs(mn,{fitContent:!0,children:[s.jsx(ks,{value:G,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),q.map(J=>s.jsx(ks,{value:J,className:"pr-2 [&>span:first-child]:hidden",children:J},J))]})]})]},R.instanceId)})})]}),o!==void 0&&t.length<o&&s.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",l!==void 0?`to ${l} models`:"","."]})]})},fG=t=>{const e=String(t||"").trim().replace(/^remotes\//,"");if(!e)return null;const n=e.indexOf("/");return n<=0?null:e.slice(0,n)};function Nx(t){const[e,n]=u.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[r,o]=u.useState(!1),[a,i]=u.useState(null);return u.useEffect(()=>{let l=!1;if(!t){i(null),o(!1),n([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),i(null),(async()=>{try{const c=await Da(t);if(l)return;if(i(c),!c){n([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const d=await Hg(t).catch(()=>null);if(l)return;const f=await yx(t).catch(()=>null);if(l)return;const m=[],p=d?.current?`Current (HEAD: ${d.current})`:"Current (HEAD)";m.push({value:"HEAD",label:p,group:"special"}),d&&(d.all.filter(x=>!x.startsWith("remotes/")).filter(x=>{if(!f)return!0;const h=d.branches?.[x]?.tracking,v=fG(h);return v?v===f:!0}).sort((x,h)=>x.localeCompare(h)).forEach(x=>{m.push({value:x,label:x,group:"local"})}),d.all.filter(x=>x.startsWith("remotes/")).map(x=>x.replace(/^remotes\//,"")).filter(x=>{if(!f)return!0;const h=x.indexOf("/");return h<=0?!1:x.slice(0,h)===f}).sort((x,h)=>x.localeCompare(h)).forEach(x=>{m.push({value:x,label:x,group:"remote"})})),n(m)}finally{l||o(!1)}})(),()=>{l=!0}},[t]),{branches:e,isLoading:r,isGitRepository:a}}const mS=t=>{const e=Me.c(39),{directory:n,value:r,onChange:o,className:a,disabled:i,id:l}=t,{branches:c,isLoading:d,isGitRepository:f}=Nx(n);let m;e[0]!==c||e[1]!==r?(m=c.find(M=>M.value===r)?.label??null,e[0]=c,e[1]=r,e[2]=m):m=e[2];const p=m;let g,y;e[3]!==c||e[4]!==o||e[5]!==r?(g=()=>{!c.some(E=>E.value===r)&&c.length>0&&o("HEAD")},y=[c,r,o],e[3]=c,e[4]=o,e[5]=r,e[6]=g,e[7]=y):(g=e[6],y=e[7]),u.useEffect(g,y);const x=i||!f||d,h=a??"max-w-full typography-meta text-foreground";let v;e[8]!==d||e[9]!==p?(v=p?s.jsx(An,{children:p}):s.jsx(An,{placeholder:d?"Loading branches…":"Select a branch"}),e[8]=d,e[9]=p,e[10]=v):v=e[10];let b;e[11]!==l||e[12]!==h||e[13]!==v?(b=s.jsx(fn,{id:l,size:"lg",className:h,children:v}),e[11]=l,e[12]=h,e[13]=v,e[14]=b):b=e[14];let w;e[15]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx(Kp,{children:"Default"}),e[15]=w):w=e[15];let j;e[16]!==c?(j=c.filter(mG).map(pG),e[16]=c,e[17]=j):j=e[17];let F;e[18]!==j?(F=s.jsxs(gf,{children:[w,j]}),e[18]=j,e[19]=F):F=e[19];let A;e[20]!==c?(A=c.some(hG)?s.jsxs(s.Fragment,{children:[s.jsx(A0,{}),s.jsxs(gf,{children:[s.jsx(Kp,{children:"Local branches"}),c.filter(gG).map(xG)]})]}):null,e[20]=c,e[21]=A):A=e[21];let C;e[22]!==c?(C=c.some(yG)?s.jsxs(s.Fragment,{children:[s.jsx(A0,{}),s.jsxs(gf,{children:[s.jsx(Kp,{children:"Remote branches"}),c.filter(bG).map(vG)]})]}):null,e[22]=c,e[23]=C):C=e[23];let S;e[24]!==A||e[25]!==C||e[26]!==F?(S=s.jsxs(mn,{fitContent:!0,children:[F,A,C]}),e[24]=A,e[25]=C,e[26]=F,e[27]=S):S=e[27];let N;e[28]!==x||e[29]!==o||e[30]!==S||e[31]!==b||e[32]!==r?(N=s.jsxs(un,{value:r,onValueChange:o,disabled:x,children:[b,S]}),e[28]=x,e[29]=o,e[30]=S,e[31]=b,e[32]=r,e[33]=N):N=e[33];let k;e[34]!==f?(k=f===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."}),e[34]=f,e[35]=k):k=e[35];let D;return e[36]!==N||e[37]!==k?(D=s.jsxs("div",{className:"space-y-2",children:[N,k]}),e[36]=N,e[37]=k,e[38]=D):D=e[38],D};function mG(t){return t.group==="special"}function pG(t){return s.jsx(ks,{value:t.value,className:"w-auto whitespace-nowrap",children:t.label},t.value)}function hG(t){return t.group==="local"}function gG(t){return t.group==="local"}function xG(t){return s.jsx(ks,{value:t.value,className:"w-auto whitespace-nowrap",children:t.label},t.value)}function yG(t){return t.group==="remote"}function bG(t){return t.group==="remote"}function vG(t){return s.jsx(ks,{value:t.value,className:"w-auto whitespace-nowrap",children:t.label},t.value)}const pS=t=>{const e=Me.c(28),{value:n,onChange:r,className:o,disabled:a,id:i}=t,l=rs(wG),c=rs(jG),d=rs(SG);let f;e[0]!==l?(f=l(),e[0]=l,e[1]=f):f=e[1];const m=f;let p;e[2]!==m?(p=m.filter(kG),e[2]=m,e[3]=p):p=e[3];const g=p;let y,x;e[4]!==c?(y=()=>{c()},x=[c],e[4]=c,e[5]=y,e[6]=x):(y=e[5],x=e[6]),u.useEffect(y,x);let h,v;e[7]!==d||e[8]!==a||e[9]!==r||e[10]!==g||e[11]!==n?(h=()=>{if(a)return;const N=n.trim();if(N.length>0&&g.some(M=>M.name===N))return;const k=typeof d=="string"&&d.trim().length>0?d.trim():null;if(k&&g.some(M=>M.name===k)){r(k);return}const D=g[0]?.name;D&&r(D)},v=[d,a,r,g,n],e[7]=d,e[8]=a,e[9]=r,e[10]=g,e[11]=n,e[12]=h,e[13]=v):(h=e[12],v=e[13]),u.useEffect(h,v);const b=n.trim().length>0?n:void 0,w=o??"max-w-full typography-meta text-foreground";let j;e[14]===Symbol.for("react.memo_cache_sentinel")?(j=s.jsx(An,{placeholder:"Select an agent"}),e[14]=j):j=e[14];let F;e[15]!==i||e[16]!==w?(F=s.jsx(fn,{id:i,size:"lg",className:w,children:j}),e[15]=i,e[16]=w,e[17]=F):F=e[17];let A;e[18]!==g?(A=g.length>0&&s.jsx(gf,{children:g.map(NG)}),e[18]=g,e[19]=A):A=e[19];let C;e[20]!==A?(C=s.jsx(mn,{fitContent:!0,children:A}),e[20]=A,e[21]=C):C=e[21];let S;return e[22]!==a||e[23]!==r||e[24]!==b||e[25]!==C||e[26]!==F?(S=s.jsxs(un,{value:b,onValueChange:r,disabled:a,children:[F,C]}),e[22]=a,e[23]=r,e[24]=b,e[25]=C,e[26]=F,e[27]=S):S=e[27],S};function wG(t){return t.getVisibleAgents}function jG(t){return t.loadAgents}function SG(t){return t.currentAgentName}function kG(t){return t.mode!=="subagent"}function NG(t){return s.jsx(ks,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const CG=10*1024*1024,U1=5,V1=({initialPrompt:t,onCreated:e,onCancel:n})=>{const[r,o]=u.useState(""),[a,i]=u.useState(()=>t??""),[l,c]=u.useState([]),[d,f]=u.useState(""),[m,p]=u.useState([]),[g,y]=u.useState(!1),[x,h]=u.useState([]),[v,b]=u.useState(!1),[w,j]=u.useState(!1),F=u.useRef(null),A=Rs(ae=>ae.currentDirectory??null),C=u.useMemo(()=>{if(typeof window>"u")return null;const ae=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof ae=="string"&&ae.trim().length>0?ae.trim():null},[]),S=bs(ae=>ae.activeProjectId),N=bs(ae=>ae.projects),k=u.useMemo(()=>{if(S){const ie=N.find(oe=>oe.id===S);if(ie?.path)return{id:ie.id,path:ie.path}}const ae=A??C;return ae?{id:`path:${ae}`,path:ae}:null},[S,N,A,C]),[D,M]=u.useState(()=>typeof window>"u"?!1:fr()),E=u.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);u.useEffect(()=>{typeof window>"u"||M(fr())},[]);const _=u.useMemo(()=>{if(typeof window>"u")return null;const ae=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof ae=="number"&&Number.isFinite(ae)&&ae>0)return ae;if(typeof navigator>"u")return null;const ie=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ie)return null;const oe=Number.parseInt(ie[1],10),Y=Number.parseInt(ie[2],10);return Number.isNaN(oe)?null:oe===10?Y:oe},[]),T=u.useMemo(()=>D&&E?"pl-[5.5rem]":"pl-3",[D,E]),P=u.useMemo(()=>!D||!E||_===null?"":_>=26?"h-12":_<=15?"h-14":"",[D,E,_]),H=u.useCallback(async ae=>{if(!ae.target.closest("button, a, input, select, textarea")&&ae.button===0&&D)try{const{getCurrentWindow:ie}=await gr(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-Byc0cUD3.js").then(re=>re.eN);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await ie().startDragging()}catch{}},[D]);u.useEffect(()=>{if(!n)return;const ae=ie=>{ie.key==="Escape"&&(ie.preventDefault(),ie.stopPropagation(),n())};return window.addEventListener("keydown",ae,!0),()=>window.removeEventListener("keydown",ae,!0)},[n]);const[R,I]=u.useState("HEAD"),{isLoading:B,isGitRepository:z}=Nx(A),U=rd(ae=>ae.createMultiRun),K=rd(ae=>ae.error),V=rd(ae=>ae.clearError);u.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&i(ae=>ae.trim().length>0?ae:t)},[t]),u.useEffect(()=>{if(!k)return;let ae=!1;return j(!0),(async()=>{try{const ie=await Vi(k);ae||h(ie)}catch{}finally{ae||j(!1)}})(),()=>{ae=!0}},[k]);const q=ae=>{l.length>=U1||(c(ie=>[...ie,ae]),V())},$=ae=>{c(ie=>ie.filter((oe,Y)=>Y!==ae)),V()},G=u.useCallback((ae,ie)=>{c(oe=>oe.map((Y,re)=>re===ae?ie:Y))},[]),W=async ae=>{const ie=ae.target.files;if(!ie)return;let oe=0;for(let Y=0;Y<ie.length;Y++){const re=ie[Y];if(re.size>CG){ce.error(`File "${re.name}" is too large (max 10MB)`);continue}try{const ue=await new Promise((O,se)=>{const X=new FileReader;X.onload=()=>O(X.result),X.onerror=se,X.readAsDataURL(re)}),Q={id:om(),filename:re.name,mimeType:re.type||"application/octet-stream",size:re.size,dataUrl:ue};p(O=>[...O,Q]),oe++}catch(ue){console.error("File attach failed",ue),ce.error(`Failed to attach "${re.name}"`)}}oe>0&&ce.success(`Attached ${oe} file${oe>1?"s":""}`),F.current&&(F.current.value="")},J=ae=>{p(ie=>ie.filter(oe=>oe.id!==ae))},te=async ae=>{if(ae.preventDefault(),!!a.trim()&&!(l.length<2)){y(!0),V();try{const ie=l.map(({instanceId:Q,...O})=>O),oe=m.map(Q=>({mime:Q.mimeType,filename:Q.filename,url:Q.dataUrl})),Y=x.filter(Q=>Q.trim().length>0),re={name:r.trim(),prompt:a.trim(),models:ie,agent:d||void 0,worktreeBaseBranch:R,files:oe.length>0?oe:void 0,setupCommands:Y.length>0?Y:void 0},ue=await U(re);ue&&(ue.firstSessionId&&Re.getState().setCurrentSession(ue.firstSessionId),e?.())}finally{y(!1)}}},le=!!(r.trim()&&a.trim()&&l.length>=2&&z&&!B);return s.jsxs("div",{className:"flex flex-col h-full bg-background",children:[s.jsxs("header",{onMouseDown:H,className:Z("relative flex h-12 items-center justify-center border-b app-region-drag select-none",T,P),style:{borderColor:"var(--interactive-border)"},children:[s.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"}),n&&s.jsx("div",{className:"absolute right-0 flex items-center pr-3",children:s.jsxs(Yt,{delayDuration:500,children:[s.jsx(Jt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":"Close (Esc)",className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:s.jsx(zs,{className:"h-5 w-5"})})}),s.jsx(Kt,{children:s.jsx("p",{children:"Close (Esc)"})})]})})]}),s.jsx("div",{className:"flex-1 overflow-auto",children:s.jsx("div",{className:"chat-column py-6",children:s.jsxs("form",{onSubmit:te,className:"space-y-6","data-keyboard-avoid":"true",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(fs,{id:"group-name",value:r,onChange:ae=>o(ae.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),s.jsx(mS,{directory:A,value:R,onChange:I,id:"multirun-worktree-base-branch"}),s.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",s.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:R||"HEAD"}),"."]})]}),s.jsxs(ro,{open:v,onOpenChange:b,children:[s.jsxs(Do,{className:"w-full flex items-center justify-between py-1 hover:bg-[var(--interactive-hover)] rounded-md px-1 -mx-1 transition-colors",children:[s.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",x.filter(ae=>ae.trim()).length>0&&s.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(ae=>ae.trim()).length," configured)"]})]}),s.jsx(Us,{className:Z("h-4 w-4 text-muted-foreground transition-transform duration-200",v&&"rotate-180")})]}),s.jsx(oo,{children:s.jsxs("div",{className:"pt-2 space-y-2",children:[s.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",s.jsx("code",{className:"font-mono text-xs",children:"$ROOT_PROJECT_PATH"})," for project root."]}),w?s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):s.jsxs("div",{className:"space-y-1.5",children:[x.map((ae,ie)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx(fs,{value:ae,onChange:oe=>{const Y=[...x];Y[ie]=oe.target.value,h(Y)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>{const oe=x.filter((Y,re)=>re!==ie);h(oe)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:s.jsx(zs,{className:"h-4 w-4"})})]},ie)),s.jsxs("button",{type:"button",onClick:()=>h([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(sn,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),s.jsx(pS,{value:d,onChange:f,id:"multirun-agent"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:["Prompt ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(xr,{id:"prompt",value:a,onChange:ae=>i(ae.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),s.jsx("input",{ref:F,type:"file",multiple:!0,className:"hidden",onChange:W,accept:"*/*"}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsxs(ot,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>F.current?.click(),children:[s.jsx(Nf,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),m.map(ae=>s.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[ae.mimeType.startsWith("image/")?s.jsx(Ja,{className:"h-3.5 w-3.5 text-muted-foreground"}):s.jsx(ca,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[120px]",title:ae.filename,children:ae.filename}),s.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",ae.size<1024?`${ae.size}B`:ae.size<1024*1024?`${(ae.size/1024).toFixed(1)}KB`:`${(ae.size/(1024*1024)).toFixed(1)}MB`,")"]}),s.jsx("button",{type:"button",onClick:()=>J(ae.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:s.jsx(zs,{className:"h-3.5 w-3.5"})})]},ae.id))]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Models ",s.jsx("span",{className:"text-destructive",children:"*"})]}),s.jsx(fS,{selectedModels:l,onAdd:q,onRemove:$,onUpdate:G,minModels:2,maxModels:U1})]}),K&&s.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:K}),s.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[s.jsx(ot,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),s.jsx(ot,{type:"submit",disabled:!le||g,children:g?"Creating...":s.jsxs(s.Fragment,{children:["Start (",l.length," models)"]})})]})]})})})]})},Ku=85,AG=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},FG=()=>{const{isSidebarOpen:o,isRightSidebarOpen:a,isBottomTerminalOpen:i,setRightSidebarOpen:l,setBottomTerminalOpen:c,activeMainTab:d,setIsMobile:f,isSessionSwitcherOpen:m,isSettingsDialogOpen:p,setSettingsDialogOpen:g,isMultiRunLauncherOpen:y,setMultiRunLauncherOpen:x,multiRunLauncherPrefillPrompt:h}=Te(),{isMobile:v}=hn(),b=oi()??"",w=u.useMemo(()=>AG(b),[b]),j=Te(I=>{if(!w)return!1;const B=I.contextPanelByDirectory[w];return!!(B?.isOpen&&B?.mode)}),F=Te(I=>I.setSidebarOpen),A=u.useRef(!1),C=u.useRef(!1),S=u.useRef(!1),[N,k]=u.useState(!1),D=u.useRef(!1),M=Ox(0),E=De.useRef(0),_=Ox(0),T=De.useRef(0);De.useEffect(()=>{v&&(E.current=window.innerWidth*(Ku/100),T.current=window.innerWidth*(Ku/100))},[v]),De.useEffect(()=>{if(!v)return;const I=N?0:-E.current;Tl(M,I,{type:"spring",stiffness:400,damping:35,mass:.8})},[N,v,M]),De.useEffect(()=>{if(!v)return;D.current=a;const I=a?0:T.current;Tl(_,I,{type:"spring",stiffness:400,damping:35,mass:.8})},[v,a,_]),De.useEffect(()=>{v&&k(m)},[m,v]),De.useEffect(()=>{v&&(D.current=a)},[a,v]);const P=sx(I=>I.checkForUpdates);u.useEffect(()=>{const I=setTimeout(()=>{P()},3e3);return()=>clearTimeout(I)},[P]),u.useEffect(()=>{Te.getState().isMobile!==v&&f(v)},[v,f]),u.useEffect(()=>{if(typeof window>"u")return;let I;const B=()=>{I!==void 0&&window.clearTimeout(I),I=window.setTimeout(()=>{Te.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",B),()=>{window.removeEventListener("resize",B),I!==void 0&&window.clearTimeout(I)}},[]),u.useEffect(()=>{if(j){Te.getState().isSidebarOpen&&(F(!1),S.current=!0);return}S.current&&(F(!0),S.current=!1)},[j,F]),u.useEffect(()=>{if(typeof window>"u")return;let I;const B=()=>{const U=Te.getState(),K=window.innerWidth,V=window.innerHeight,q=K<1140,$=K>=1220;q?U.isRightSidebarOpen&&(l(!1),A.current=!0):$&&A.current&&(l(!0),A.current=!1);const G=V<640,W=V>=700;G?U.isBottomTerminalOpen&&(c(!1),C.current=!0):W&&C.current&&(c(!0),C.current=!1)},z=()=>{I!==void 0&&window.clearTimeout(I),I=window.setTimeout(()=>{B()},100)};return B(),window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),I!==void 0&&window.clearTimeout(I)}},[c,l]),u.useEffect(()=>{if(typeof window>"u")return;const I=Te.subscribe((B,z)=>{const U=window.innerWidth,K=window.innerHeight,V=U>=1220,q=K>=700;B.isRightSidebarOpen!==z.isRightSidebarOpen&&V&&(A.current=!1),B.isBottomTerminalOpen!==z.isBottomTerminalOpen&&q&&(C.current=!1)});return()=>{I()}},[]),u.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const I=document.documentElement;let B=0,z=!1,U=0,K=null;const V=Te.getState().setKeyboardOpen,q=()=>{K&&(K.style.setProperty("--oc-keyboard-avoid-offset","0px"),K.removeAttribute("data-keyboard-avoid-active"),K=null)},$=ie=>{if(!ie)return null;const oe=ie.getAttribute("data-keyboard-avoid-target-id");if(oe){const re=document.getElementById(oe);if(re instanceof HTMLElement)return re}const Y=ie.closest("[data-keyboard-avoid]");if(Y)return Y.getAttribute("data-keyboard-avoid")==="none"?null:Y;if(ie.classList.contains("overlay-scrollbar-container")){const re=ie.parentElement;if(re instanceof HTMLElement)return re}return ie},G=()=>{B=0,z=!0,I.style.setProperty("--oc-keyboard-inset","0px"),V(!1)},W=()=>{const ie=window.visualViewport,oe=ie?Math.round(ie.height):window.innerHeight,Y=ie?Math.max(0,Math.round(ie.offsetTop)):0;I.style.setProperty("--oc-visual-viewport-offset-top",`${Y}px`);const re=document.activeElement,ue=re?.tagName,O=ue==="INPUT"||ue==="TEXTAREA"||ue==="SELECT"||!!re?.isContentEditable,se=Math.round(I.clientHeight||window.innerHeight),X=oe+Y,L=Math.max(0,se-X),fe=L>=(O?120:180)?L:0;if(z)fe===0&&(z=!1),B=0;else if(B===0)fe>0&&O&&(B=fe);else{const ge=!O&&oe>U+6;fe===0?(B=0,V(!1)):ge?G():(fe>0&&O||fe>B)&&(B=fe,V(!0))}I.style.setProperty("--oc-keyboard-inset",`${B}px`),U=oe;const de=/iPad|iPhone|iPod/.test(navigator.userAgent)&&B>0?34:0;I.style.setProperty("--oc-keyboard-home-indicator",`${de}px`);const ne=O?$(re):null;if(!v||!ne||!re)q();else{ne!==K&&(q(),K=ne);const ge=Y+oe,Oe=re.getBoundingClientRect().bottom-ge,et=8,$e=Math.max(B,fe),Ae=Oe>et&&$e>0?Math.min(Oe,$e):0,Ie=K;Ie&&(Ie.style.setProperty("--oc-keyboard-avoid-offset",`${Ae}px`),Ie.setAttribute("data-keyboard-avoid-active","true"))}if(v&&O){const ge=document.scrollingElement;ge&&ge.scrollTop!==0&&(ge.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};W();const J=window.visualViewport;J?.addEventListener("resize",W),J?.addEventListener("scroll",W),window.addEventListener("resize",W),window.addEventListener("orientationchange",W);const te=ie=>{if(!ie)return!1;const oe=ie.tagName;return oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||ie.isContentEditable},le=ie=>{const oe=ie.target;te(oe)&&(z=!1),W()};document.addEventListener("focusin",le,!0);const ae=ie=>{const oe=ie.target;if(!te(oe))return;const Y=ie.relatedTarget;te(Y)||window.requestAnimationFrame(()=>{if(te(document.activeElement))return;const re=window.visualViewport,ue=re?Math.round(re.height):window.innerHeight,Q=re?Math.max(0,Math.round(re.offsetTop)):0,O=Math.round(I.clientHeight||window.innerHeight),se=ue+Q;if(Math.max(0,O-se)>0){W();return}G(),W()})};return document.addEventListener("focusout",ae,!0),()=>{J?.removeEventListener("resize",W),J?.removeEventListener("scroll",W),window.removeEventListener("resize",W),window.removeEventListener("orientationchange",W),document.removeEventListener("focusin",le,!0),document.removeEventListener("focusout",ae,!0),q()}},[v]);const H=u.useMemo(()=>{switch(d){case"plan":return s.jsx(vj,{});case"git":return s.jsx(rg,{});case"diff":return s.jsx(Pj,{});case"terminal":return s.jsx(z0,{});case"files":return s.jsx(Lj,{});default:return null}},[d]),R=d==="chat";return s.jsx(aO,{children:s.jsxs("div",{className:Z("main-content-safe-area h-[100dvh]",v?"flex flex-col":"flex","bg-background"),children:[s.jsx(yW,{}),s.jsx(jW,{}),s.jsx(NW,{}),s.jsx(aG,{}),v?s.jsxs(wI,{value:{leftDrawerOpen:N,rightDrawerOpen:a,toggleLeftDrawer:()=>{a&&l(!1),k(!N)},toggleRightDrawer:()=>{N&&k(!1),l(!a)},leftDrawerX:M,rightDrawerX:_,leftDrawerWidth:E,rightDrawerWidth:T,setMobileLeftDrawerOpen:k,setRightSidebarOpen:l},children:[!(p||y)&&s.jsx(tb,{onToggleLeftDrawer:()=>{a&&l(!1),k(!N)},onToggleRightDrawer:()=>{N&&k(!1),l(!a)},leftDrawerOpen:N,rightDrawerOpen:a}),s.jsx(ja.button,{type:"button",initial:!1,animate:{opacity:N||a?1:0,pointerEvents:N||a?"auto":"none"},className:"fixed inset-0 z-40 bg-black/50 cursor-default",onClick:()=>{k(!1),l(!1)},"aria-label":"Close drawer"}),s.jsx(ja.aside,{drag:"x",dragElastic:.08,dragMomentum:!1,dragConstraints:{left:-(E.current||window.innerWidth*.85),right:0},style:{width:`${Ku}%`,x:M},onDragEnd:(I,B)=>{const z=E.current||window.innerWidth*.85,U=z*.3,K=500,V=M.get(),q=B.offset.x<-U||B.velocity.x<-K,$=B.offset.x>U||B.velocity.x>K;q?(M.set(-z),k(!1)):$?(M.set(0),k(!0)):V>-z/2?M.set(0):M.set(-z)},className:Z("fixed left-0 top-0 z-50 h-full bg-transparent","cursor-grab active:cursor-grabbing"),"aria-hidden":!N,children:s.jsxs("div",{className:"h-full overflow-hidden flex bg-sidebar shadow-none drawer-safe-area",children:[s.jsx("div",{onPointerDownCapture:I=>I.stopPropagation(),children:s.jsx(pb,{className:"shrink-0",mobile:!0})}),s.jsx("div",{className:"flex-1 min-w-0 overflow-hidden flex flex-col",children:s.jsx(Tn,{children:s.jsx(rm,{mobileVariant:!0})})})]})}),s.jsx(ja.aside,{drag:"x",dragElastic:.08,dragMomentum:!1,dragConstraints:{left:0,right:T.current||window.innerWidth*.85},style:{width:`${Ku}%`,x:_},onDragEnd:(I,B)=>{const z=T.current||window.innerWidth*.85,U=z*.3,K=500,V=_.get(),q=B.offset.x>U||B.velocity.x>K,$=B.offset.x<-U||B.velocity.x<-K;q?(_.set(z),l(!1)):$?(_.set(0),l(!0)):V<z/2?_.set(0):_.set(z)},className:Z("fixed right-0 top-0 z-50 h-full bg-transparent","cursor-grab active:cursor-grabbing"),"aria-hidden":!a,children:s.jsx("div",{className:"h-full overflow-hidden flex flex-col bg-background shadow-none drawer-safe-area",children:s.jsx(Tn,{children:s.jsx(rg,{mode:"sidebar"})})})}),s.jsx("div",{className:Z("flex flex-1 overflow-hidden relative",(p||y)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:s.jsxs("main",{className:"w-full h-full overflow-hidden bg-background relative",children:[s.jsx("div",{className:Z("absolute inset-0",!R&&"invisible"),children:s.jsx(Tn,{children:s.jsx(sd,{})})}),H&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Tn,{children:H})})]})}),y&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:s.jsx(Tn,{children:s.jsx(V1,{initialPrompt:h,onCreated:()=>x(!1),onCancel:()=>x(!1)})})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:s.jsx(Tn,{children:s.jsx(kx,{onClose:()=>g(!1)})})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[s.jsxs("div",{className:Z("absolute inset-0 flex flex-col",y&&"invisible"),children:[s.jsx(tb,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[s.jsx(pb,{}),s.jsxs("div",{className:"flex flex-1 min-w-0 overflow-hidden border-t border-l border-border/50 rounded-tl-xl",children:[s.jsx(h6,{isOpen:o,isMobile:v,children:s.jsx(rm,{hideProjectSelector:!0})}),s.jsxs("div",{className:"flex flex-1 min-w-0 flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[s.jsxs("div",{className:"relative flex flex-1 min-h-0 min-w-0 overflow-hidden",children:[s.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[s.jsx("div",{className:Z("absolute inset-0",!R&&"invisible"),children:s.jsx(Tn,{children:s.jsx(sd,{})})}),H&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Tn,{children:H})})]}),s.jsx(hW,{})]}),s.jsx(ME,{isOpen:a,children:s.jsx(Tn,{children:s.jsx(LV,{})})})]}),s.jsx(c6,{isOpen:i,isMobile:v,children:s.jsx(Tn,{children:s.jsx(z0,{})})})]})]})]})]}),y&&s.jsx("div",{className:Z("absolute inset-0 z-10 bg-background"),children:s.jsx(Tn,{children:s.jsx(V1,{initialPrompt:h,onCreated:()=>x(!1),onCancel:()=>x(!1)})})})]}),s.jsx(iV,{open:p,onOpenChange:g})]})]})})},DG=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},MG=550,EG=1400,IG=280,_G=()=>{const t=Vr(),e=u.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),n=u.useMemo(()=>{const P=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof P=="string"&&P.trim().length>0?P.trim():null},[]),r=u.useRef(!1),o=u.useMemo(()=>{try{return!!Re.getState().newSessionDraft?.open}catch{return!1}},[]),[a,i]=u.useState(()=>o?"chat":"sessions"),[l,c]=u.useState(0),d=u.useRef(null),f=Re(P=>P.currentSessionId),m=Re(P=>P.sessions),p=u.useMemo(()=>f?m.find(P=>P.id===f)?.title||"Session":null,[f,m]),g=Re(P=>!!P.newSessionDraft?.open),y=Re(P=>P.isSyncing),x=Re(P=>{const H=P.sessionStatus;if(!H||H.size===0)return!1;for(const R of H.values())if(R?.type==="busy"||R?.type==="retry")return!0;return!1}),h=Re(P=>P.openNewSessionDraft),[v,b]=u.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),w=rs(P=>P.isInitialized),j=rs(P=>P.initializeApp),F=Re(P=>P.loadSessions),A=Re(P=>P.loadMessages),C=Re(P=>P.messages),[S,N]=u.useState(()=>w),[k,D]=u.useState(!1),M=u.useRef(0);u.useEffect(()=>{f&&i("chat")},[f]),u.useEffect(()=>{const P=t.vscode;P&&P.executeCommand("openchamber.setActiveSession",f,p)},[p,f,t.vscode]),u.useEffect(()=>{if(e==="editor"||a!=="chat"||f||g||y||x)return;const P=window.setTimeout(()=>{const H=Re.getState(),R=!H.currentSessionId,I=!H.newSessionDraft?.open,B=H.isSyncing,z=(()=>{const U=H.sessionStatus;if(!U||U.size===0)return!1;for(const K of U.values())if(K?.type==="busy"||K?.type==="retry")return!0;return!1})();R&&I&&!B&&!z&&i("sessions")},900);return()=>{window.clearTimeout(P)}},[f,g,a,e,y,x]);const E=u.useCallback(()=>{i("sessions")},[]);u.useEffect(()=>{const P=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(P==="connected"||P==="connecting"||P==="error"||P==="disconnected")&&b(P);const H=R=>{const B=R.detail?.status;(B==="connected"||B==="connecting"||B==="error"||B==="disconnected")&&b(B)};return window.addEventListener("openchamber:connection-status",H),()=>window.removeEventListener("openchamber:connection-status",H)},[]),u.useEffect(()=>{const P=H=>{const I=H.detail?.view;I==="settings"?i("settings"):I==="chat"?i("chat"):I==="sessions"&&i("sessions")};return window.addEventListener("openchamber:navigate",P),()=>window.removeEventListener("openchamber:navigate",P)},[]),u.useEffect(()=>{(async()=>{if(k||S||v!=="connected")return;const H=Date.now();if(!(H-M.current<750)){M.current=H,D(!0);try{const R=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();R&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:w}),w||await j();const I=rs.getState();I.isConnected&&(I.providers.length===0&&await I.loadProviders(),I.agents.length===0&&await I.loadAgents());const B=rs.getState();if(!B.isInitialized||!B.isConnected||B.providers.length===0||B.agents.length===0)return;await F();const z=Re.getState().error;if(R&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:B.providers.length,agents:B.agents.length,sessions:Re.getState().sessions.length,sessionsError:z}),typeof z=="string"&&z.length>0)return;N(!0)}catch{}finally{D(!1)}}})()},[v,w,S,j,k,F]),u.useEffect(()=>{if(e==="editor"&&!r.current&&!(!S||v!=="connected")){if(!n){r.current=!0,h();return}m.some(P=>P.id===n)&&(r.current=!0,Re.getState().setCurrentSession(n))}},[v,S,n,h,m,e]),u.useEffect(()=>{(async()=>{if(!(!S||v!=="connected"||a!=="chat"||g||!f||C.has(f)))try{await A(f)}catch{}})()},[v,f,a,S,A,C,g]),u.useEffect(()=>{const P=d.current;if(!P)return;const H=new ResizeObserver(R=>{for(const I of R)c(I.contentRect.width)});return H.observe(P),c(P.clientWidth),()=>H.disconnect()},[]);const _=l>0&&l<MG,T=l>=EG;return u.useEffect(()=>{T&&a==="sessions"&&e==="sidebar"&&i("chat")},[T,a,e]),s.jsx("div",{ref:d,className:"h-full w-full bg-background text-foreground flex flex-col",children:e==="editor"?s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Qu,{title:m.find(P=>P.id===f)?.title||"Chat",showMcp:!0,showContextUsage:!0}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Tn,{children:s.jsx(sd,{})})})]}):a==="settings"?s.jsx(kx,{onClose:()=>i(T?"chat":"sessions"),forceMobile:_}):T?s.jsxs("div",{className:"flex h-full",children:[s.jsx("div",{className:"h-full border-r border-border overflow-hidden flex-shrink-0",style:{width:IG},children:s.jsx(rm,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),s.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[s.jsx(Qu,{title:g&&!f?"New session":m.find(P=>P.id===f)?.title||"Chat",showMcp:!0,showContextUsage:!0}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Tn,{children:s.jsx(sd,{})})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:Z("flex flex-col h-full",a!=="sessions"&&"hidden"),children:[s.jsx(Qu,{title:"Sessions"}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(rm,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>i("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}),s.jsxs("div",{className:Z("flex flex-col h-full",a!=="chat"&&"hidden"),children:[s.jsx(Qu,{title:g&&!f?"New session":m.find(P=>P.id===f)?.title||"Chat",showBack:!0,onBack:E,showMcp:!0,showContextUsage:!0,showRateLimits:!0}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Tn,{children:s.jsx(sd,{})})})]})]})})},Qu=t=>{const e=Me.c(46),{title:n,showBack:r,onBack:o,onNewSession:a,onSettings:i,onAgentManager:l,showMcp:c,showContextUsage:d,showRateLimits:f}=t,{getCurrentModel:m}=rs(),p=Re(PG),g=Qs(TG),y=Qs(RG),x=Qs(BG),h=Qs(OG),v=Qs($G),b=Qs(LG),w=Qs(zG),j=Qs(HG);qg();let F,A;e[0]!==w?(F=()=>{w()},A=[w],e[0]=w,e[1]=F,e[2]=A):(F=e[1],A=e[2]),u.useEffect(F,A);let C;if(e[3]!==p||e[4]!==m){const K=m(),V=K?.limit&&typeof K.limit=="object"?K.limit:null,q=typeof V?.context=="number"?V.context:0,$=typeof V?.output=="number"?V.output:0;C=p(q,$),e[3]=p,e[4]=m,e[5]=C}else C=e[5];const S=C;let N;if(e[6]!==b||e[7]!==g){N=[];for(const K of qo){if(!b.includes(K.id))continue;const V=g.find(W=>W.providerId===K.id),q=V?.usage?.windows??{},$=Object.entries(q),G=V&&!V.ok&&V.configured?V.error:void 0;($.length>0||G)&&N.push({providerId:K.id,providerName:K.name,entries:$,error:G})}e[6]=b,e[7]=g,e[8]=N}else N=e[8];const k=N,D=k.length>0;let M;e[9]!==j?(M=async K=>{j(K);try{await on({usageDisplayMode:K})}catch(V){console.warn("Failed to update usage display mode:",V)}},e[9]=j,e[10]=M):M=e[10];const E=M;let _;e[11]!==o||e[12]!==r?(_=r&&o&&s.jsx("button",{onClick:o,className:"inline-flex h-7 w-7 items-center justify-center text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:s.jsx(mm,{className:"h-5 w-5"})}),e[11]=o,e[12]=r,e[13]=_):_=e[13];let T;e[14]!==n?(T=s.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:n,children:n}),e[14]=n,e[15]=T):T=e[15];let P;e[16]!==a?(P=a&&s.jsx("button",{onClick:a,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:s.jsx(sn,{className:"h-5 w-5"})}),e[16]=a,e[17]=P):P=e[17];let H;e[18]!==l?(H=l&&s.jsx("button",{onClick:l,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Agent Manager",children:s.jsx(Uo,{className:"h-5 w-5"})}),e[18]=l,e[19]=H):H=e[19];let R;e[20]!==c?(R=c&&s.jsx(XA,{headerIconButtonClass:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"}),e[20]=c,e[21]=R):R=e[21];let I;e[22]!==y||e[23]!==E||e[24]!==D||e[25]!==x||e[26]!==v||e[27]!==h||e[28]!==g||e[29]!==k||e[30]!==f?(I=f&&s.jsxs(Ys,{onOpenChange:K=>{K&&g.length===0&&y()},children:[s.jsx(Js,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":"Rate limits",className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",disabled:x,children:s.jsx(hh,{className:"h-5 w-5"})})}),s.jsxs(Xs,{align:"end",className:"w-80 max-h-[70vh] overflow-y-auto overflow-x-hidden bg-[var(--surface-elevated)] p-0",children:[s.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)]",children:s.jsxs(Zr,{className:"flex items-center justify-between gap-3 typography-ui-header font-semibold text-foreground",children:[s.jsx("span",{children:"Rate limits"}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("div",{className:"flex items-center rounded-md border border-[var(--interactive-border)] p-0.5",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 rounded-sm typography-micro text-[10px] transition-colors ${v==="usage"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>{E("usage")},"aria-label":"Show used quota",children:"Used"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 rounded-sm typography-micro text-[10px] transition-colors ${v==="remaining"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>{E("remaining")},"aria-label":"Show remaining quota",children:"Remaining"})]}),s.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>y(),disabled:x,"aria-label":"Refresh rate limits",children:s.jsx(br,{className:"h-4 w-4"})})]})]})}),s.jsxs("div",{className:"border-b border-[var(--interactive-border)] px-2 pb-2 typography-micro text-muted-foreground text-[10px]",children:["Last updated ",DG(h)]}),!D&&s.jsx(is,{className:"cursor-default",onSelect:UG,children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"No rate limits available."})}),k.map((K,V)=>s.jsxs(u.Fragment,{children:[s.jsxs(Zr,{className:"flex items-center gap-2 bg-[var(--surface-elevated)] typography-ui-label text-foreground",children:[s.jsx(Bn,{providerId:K.providerId,className:"h-4 w-4"}),K.providerName]}),K.entries.length===0?s.jsx(is,{className:"cursor-default",onSelect:VG,children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:K.error??"No rate limits reported."})},`${K.providerId}-empty`):K.entries.map(q=>{const[$,G]=q,W=v==="remaining"?G.remainingPercent:G.usedPercent,J=zl(G.usedPercent,G.resetAt,G.windowSeconds,$),te=J?.dailyAllocationPercent!=null?v==="remaining"?100-Po(J.elapsedRatio):Po(J.elapsedRatio):null;return s.jsx(is,{className:"cursor-default items-start",onSelect:WG,children:s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-2",children:[s.jsxs("span",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Wf($)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:_o(W)==="-"?"":_o(W)})]}),s.jsx(Hl,{percent:W,tonePercent:G.usedPercent,className:"h-1",expectedMarkerPercent:te}),J&&s.jsx("div",{className:"mt-0.5",children:s.jsx(Ul,{paceInfo:J,compact:!0})}),s.jsx("span",{className:"flex items-center justify-between typography-micro text-muted-foreground text-[10px]",children:s.jsx("span",{children:G.resetAfterFormatted??G.resetAtFormatted??""})})]})},`${K.providerId}-${$}`)}),V<k.length-1&&s.jsx(Kn,{})]},K.providerId))]})]}),e[22]=y,e[23]=E,e[24]=D,e[25]=x,e[26]=v,e[27]=h,e[28]=g,e[29]=k,e[30]=f,e[31]=I):I=e[31];let B;e[32]!==i?(B=i&&s.jsx("button",{onClick:i,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Settings",children:s.jsx(Ca,{className:"h-5 w-5"})}),e[32]=i,e[33]=B):B=e[33];let z;e[34]!==S||e[35]!==d?(z=d&&S&&S.totalTokens>0&&s.jsx(Kw,{totalTokens:S.totalTokens,percentage:S.percentage,contextLimit:S.contextLimit,outputLimit:S.outputLimit??0,size:"compact"}),e[34]=S,e[35]=d,e[36]=z):z=e[36];let U;return e[37]!==I||e[38]!==B||e[39]!==z||e[40]!==_||e[41]!==T||e[42]!==P||e[43]!==H||e[44]!==R?(U=s.jsxs("div",{className:"flex items-center gap-1.5 pl-1 pr-2 py-1 border-b border-border bg-background shrink-0",children:[_,T,P,H,R,I,B,z]}),e[37]=I,e[38]=B,e[39]=z,e[40]=_,e[41]=T,e[42]=P,e[43]=H,e[44]=R,e[45]=U):U=e[45],U};function PG(t){return t.getContextUsage}function TG(t){return t.results}function RG(t){return t.fetchAllQuotas}function BG(t){return t.isLoading}function OG(t){return t.lastUpdated}function $G(t){return t.displayMode}function LG(t){return t.dropdownProviderIds}function zG(t){return t.loadSettings}function HG(t){return t.setDisplayMode}function UG(t){return t.preventDefault()}function VG(t){return t.preventDefault()}function WG(t){return t.preventDefault()}const Yu=t=>{const e=bs.getState(),n=e.activeProjectId,r=n?e.projects.find(o=>o.id===n)?.path:void 0;return typeof r=="string"&&r.trim().length>0?r:t?Zn(t):null},Zn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},W1=(t,e)=>{const n=Zn(t),r=Zn(e);if(!n||!r)return!1;if(n===r)return!0;const o=r==="/"?"/":`${r}/`;return n.startsWith(o)},hS=async(t,e)=>{const n=Zn(e);if(!n)return n;try{const r=await t.path.get({directory:n});return Zn(r.data?.directory??"")||n}catch{return n}},gS=async(t,e)=>{const n=Zn(e);if(!n)return[];const r=await hS(t,n),o=i=>i.filter(l=>{const c=Zn(l.directory??"");return c?W1(c,n)||r!==n&&W1(c,r):!1}),a=async i=>{const l=await t.session.list({directory:i});return Array.isArray(l.data)?l.data:[]};try{const i=o(await a(n));if(i.length>0)return i}catch{}if(r&&r!==n)try{const i=o(await a(r));if(i.length>0)return i}catch{}try{const i=await t.session.list(void 0),l=Array.isArray(i.data)?i.data:[];return o(l)}catch{return[]}},GG=async(t,e)=>{const n=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&n.set(Zn(o.path),o.worktreeMetadata)});const r=Array.from(new Set(t.sessions.map(o=>Zn(o.path)))).filter(Boolean).filter(o=>!n.has(o));if(r.length===0)return n;try{const o=await Pi({id:`path:${e}`,path:e}),a=new Map(o.map(i=>[Zn(i.path),i]));r.forEach(i=>{const l=a.get(i);l&&n.set(i,l)})}catch{}return n},qG=async t=>{const{apiClient:e,group:n,projectDirectory:r,worktreePaths:o}=t,a=await GG(n,r),i=Re.getState(),l=Array.from(new Set(o.map(p=>Zn(p)).filter(Boolean))),c=5;let d=0;const f=[],m=async()=>{for(;d<l.length;){const p=l[d];d+=1;const g=n.sessions.filter(b=>Zn(b.path)===p).map(b=>b.id),y=i.getSessionsByDirectory(p),x=Array.isArray(y)?y.map(b=>b.id):[];let h=[];if(x.length===0)try{h=(await gS(e,p)).map(w=>w.id)}catch{h=[]}const v=Array.from(new Set([...x,...h,...g].filter(Boolean)));f.push({worktreePath:p,sessionIds:v,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(c,l.length)},m)),f},uh=async t=>{const e=Lt.getApiClient(),n=await qG({apiClient:e,group:t.group,projectDirectory:t.projectDirectory,worktreePaths:t.worktreePaths}),r=Re.getState(),o=new Set;return n.forEach(({worktreePath:a,sessionIds:i,metadata:l})=>{i.forEach(c=>{o.add(c),l&&(r.setWorktreeMetadata(c,l),r.setSessionDirectory(c,a))})}),o.size===0?{failedIds:[]}:r.deleteSessions(Array.from(o),{archiveWorktree:!0,silent:!0})};function KG(t){if(!t)return null;const e=t.split("/");if(e.length<3)return null;const n=e[0];if(!n||n.includes(" "))return null;const r=e[1];if(!r)return null;const o=e[e.length-1],a=parseInt(o,10),i=e.length>=4&&!isNaN(a)&&String(a)===o,l=i?e.slice(2,-1):e.slice(2);if(l.length===0)return null;const c=l.join("/");return{groupSlug:n,provider:r,model:c,index:i?a:1}}const Qa=Fn()(Gn((t,e)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const n=Rs.getState().currentDirectory,r=Yu(n);if(!r){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Zn(r),l={id:bs.getState().projects.find(d=>Zn(d.path)===o)?.id??`path:${o}`,path:o},c=e().groups;t({isLoading:!0,error:null});try{const d=Lt.getApiClient(),f=await hS(d,o),m=f&&f!==o?{...l,path:f}:null,p=await Pi(l).catch(()=>[]),g=m?await Pi(m).catch(()=>[]):[],y=new Set,x=new Map;[...p,...g].forEach(C=>{if(C?.path){const S=Zn(C.path);y.add(S),x.has(S)||x.set(S,C)}});const h=async()=>{try{const S=await d.session.list({directory:o}),N=Array.isArray(S.data)?S.data:[];if(N.some(k=>{const D=Zn(k.directory??"");return D?y.has(D):!1}))return N}catch{}const C=await d.session.list(void 0);return Array.isArray(C.data)?C.data:[]},v=async C=>{const S=new Map,N=5;let k=0;const D=async()=>{for(;k<C.length;){const M=C[k];k+=1;const E=Zn(M);if(E)try{(await gS(d,E)).forEach(T=>S.set(T.id,T))}catch(_){console.debug("Failed to fetch sessions from worktree:",E,_)}}};return await Promise.all(Array.from({length:Math.min(N,C.length)},D)),Array.from(S.values())};let w=(await h()).filter(C=>{const S=Zn(C.directory??"");return S?y.has(S):!1});if(w.length===0){const C=new Set;y.forEach(S=>C.add(S)),C.size>0&&(w=await v(Array.from(C)))}const j=new Map;for(const C of w){const S=C.time?.updated??0;j.set(C.id,typeof S=="number"?S:0)}const F=new Map;for(const C of w){const S=KG(C.title);if(!S)continue;const N=Zn(C.directory),k=x.get(N),D={id:C.id,path:N,providerId:S.provider,modelId:S.model,instanceNumber:S.index,branch:k?.branch??"",displayLabel:`${S.provider}/${S.model}`,worktreeMetadata:k},M=F.get(S.groupSlug);M?M.push(D):F.set(S.groupSlug,[D])}const A=Array.from(F.entries()).map(([C,S])=>{const N=S.reduce((k,D)=>{const M=j.get(D.id)??0;return Math.max(k,M)},0);return{name:C,sessions:S.sort((k,D)=>{const M=k.providerId.localeCompare(D.providerId);if(M!==0)return M;const E=k.modelId.localeCompare(D.modelId);return E!==0?E:k.instanceNumber-D.instanceNumber}),lastActive:N||Date.now(),sessionCount:S.length}});A.sort((C,S)=>C.name.localeCompare(S.name)),t({groups:A,isLoading:!1,error:null})}catch(d){console.error("Failed to load agent groups:",d),t({groups:c.length>0?c:[],isLoading:!1,error:d instanceof Error?d.message:"Failed to load agent groups"})}},selectGroup:n=>{const{groups:r}=e(),o=r.find(a=>a.name===n);t({selectedGroupName:n,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:n=>{t({selectedSessionId:n})},deleteGroup:async n=>{const r=e().groups.find(i=>i.name===n);if(!r)return!1;const o=Rs.getState().currentDirectory,a=Yu(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:i}=await uh({group:r,projectDirectory:Zn(a),worktreePaths:r.sessions.map(l=>l.path)});return i.length>0&&t({error:"Failed to delete some sessions"}),e().selectedGroupName===n&&t({selectedGroupName:null,selectedSessionId:null}),await e().loadGroups(),i.length===0}catch(i){return t({error:i instanceof Error?i.message:"Failed to delete group"}),!1}finally{t({isLoading:!1})}},deleteGroupWorktree:async(n,r)=>{const o=e().groups.find(c=>c.name===n);if(!o)return!1;const a=Zn(r);if(!a)return!1;const i=Rs.getState().currentDirectory,l=Yu(i);if(!l)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:c}=await uh({group:o,projectDirectory:Zn(l),worktreePaths:[a]});c.length>0&&t({error:"Failed to delete some sessions"}),await e().loadGroups();const d=e().groups.find(f=>f.name===n);if(!d)return e().selectedGroupName===n&&t({selectedGroupName:null,selectedSessionId:null}),c.length===0;if(e().selectedGroupName===n){const f=e().selectedSessionId,m=new Set(d.sessions.map(p=>p.id));(!f||!m.has(f))&&t({selectedSessionId:d.sessions[0]?.id??null})}return c.length===0}catch(c){return t({error:c instanceof Error?c.message:"Failed to delete worktree"}),!1}finally{t({isLoading:!1})}},keepOnlyGroupWorktree:async(n,r)=>{const o=e().groups.find(f=>f.name===n);if(!o)return!1;const a=Zn(r);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(f=>Zn(f.path)).filter(Boolean))).filter(f=>f!==a);if(l.length===0)return!0;const c=Rs.getState().currentDirectory,d=Yu(c);if(!d)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:f}=await uh({group:o,projectDirectory:Zn(d),worktreePaths:l});if(f.length>0&&t({error:"Failed to delete some sessions"}),await e().loadGroups(),e().selectedGroupName===n){const m=e().groups.find(g=>g.name===n),p=m?.sessions.find(g=>Zn(g.path)===a)??m?.sessions[0]??null;t({selectedSessionId:p?.id??null})}return f.length===0}catch(f){return t({error:f instanceof Error?f.message:"Failed to remove other worktrees"}),!1}finally{t({isLoading:!1})}},getSelectedGroup:()=>{const{groups:n,selectedGroupName:r}=e();return r?n.find(o=>o.name===r)??null:null},getSelectedSession:()=>{const{selectedSessionId:n}=e(),r=e().getSelectedGroup();return!r||!n?null:r.sessions.find(o=>o.id===n)??null},clearError:()=>{t({error:null})}}),{name:"agent-groups-store"})),QG=t=>{const n=Date.now()-t,r=Math.floor(n/(60*1e3)),o=Math.floor(n/(3600*1e3)),a=Math.floor(n/(1440*60*1e3));return r<1?"now":r<60?`${r}m`:o<24?`${o}h`:`${a}d`},YG=t=>{const e=Me.c(62),{group:n,isSelected:r,onSelect:o}=t,[a,i]=u.useState(!1),[l,c]=u.useState(!1),[d,f]=u.useState(!1),m=Qa(XG);let p;e[0]!==m||e[1]!==n.name||e[2]!==d?(p=async()=>{if(d)return;if(f(!0),ce.info(`Deleting "${n.name}"...`),await m(n.name))ce.success(`Deleted "${n.name}"`);else{const W=Qa.getState().error;ce.error(W||`Failed to delete "${n.name}"`)}f(!1),c(!1)},e[0]=m,e[1]=n.name,e[2]=d,e[3]=p):p=e[3];const g=p,y=r?"bg-interactive-selection":"hover:bg-interactive-hover";let x;e[4]!==y?(x=Z("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",y),e[4]=y,e[5]=x):x=e[5];let h;e[6]!==n.name?(h=s.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:n.name}),e[6]=n.name,e[7]=h):h=e[7];let v;e[8]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx(bn,{className:"h-3 w-3"}),e[8]=v):v=e[8];const b=n.sessionCount!==1?"s":"";let w;e[9]!==n.sessionCount||e[10]!==b?(w=s.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[v,n.sessionCount," model",b]}),e[9]=n.sessionCount,e[10]=b,e[11]=w):w=e[11];let j;e[12]!==n.lastActive?(j=QG(n.lastActive),e[12]=n.lastActive,e[13]=j):j=e[13];let F;e[14]!==j?(F=s.jsx("span",{className:"typography-micro text-muted-foreground/60",children:j}),e[14]=j,e[15]=F):F=e[15];let A;e[16]!==w||e[17]!==F?(A=s.jsxs("div",{className:"flex items-center gap-2",children:[w,F]}),e[16]=w,e[17]=F,e[18]=A):A=e[18];let C;e[19]!==A||e[20]!==h?(C=s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[h,A]}),e[19]=A,e[20]=h,e[21]=C):C=e[21];const S=a&&"opacity-100";let N;e[22]!==S?(N=Z("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",S),e[22]=S,e[23]=N):N=e[23];let k;e[24]===Symbol.for("react.memo_cache_sentinel")?(k=s.jsx(Fo,{className:"h-3.5 w-3.5"}),e[24]=k):k=e[24];let D;e[25]!==N?(D=s.jsx(Js,{asChild:!0,children:s.jsx("button",{type:"button",className:N,"aria-label":"Group menu",onClick:ZG,children:k})}),e[25]=N,e[26]=D):D=e[26];let M;e[27]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(Xs,{align:"end",className:"min-w-[140px]",children:s.jsx(is,{variant:"destructive",onSelect:G=>{G.stopPropagation(),i(!1),c(!0)},children:"Delete"})}),e[27]=M):M=e[27];let E;e[28]!==a||e[29]!==D?(E=s.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:s.jsxs(Ys,{open:a,onOpenChange:i,children:[D,M]})}),e[28]=a,e[29]=D,e[30]=E):E=e[30];let _;e[31]!==C||e[32]!==E?(_=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[C,E]}),e[31]=C,e[32]=E,e[33]=_):_=e[33];let T;e[34]!==o||e[35]!==_||e[36]!==x?(T=s.jsx("div",{className:x,onClick:o,children:_}),e[34]=o,e[35]=_,e[36]=x,e[37]=T):T=e[37];let P;e[38]===Symbol.for("react.memo_cache_sentinel")?(P=s.jsx(Zs,{children:"Delete agent group"}),e[38]=P):P=e[38];let H;e[39]!==n.name?(H=s.jsxs(en,{children:[P,s.jsxs(nn,{children:["Delete ",s.jsx("span",{className:"text-foreground font-medium",children:n.name}),"? This removes all worktrees and sessions in this group."]})]}),e[39]=n.name,e[40]=H):H=e[40];let R;e[41]===Symbol.for("react.memo_cache_sentinel")?(R=()=>c(!1),e[41]=R):R=e[41];let I;e[42]!==d?(I=s.jsx(ot,{variant:"outline",onClick:R,disabled:d,children:"Cancel"}),e[42]=d,e[43]=I):I=e[43];let B;e[44]!==g?(B=()=>{g()},e[44]=g,e[45]=B):B=e[45];const z=d?"Deleting…":"Delete";let U;e[46]!==d||e[47]!==B||e[48]!==z?(U=s.jsx(ot,{variant:"destructive",onClick:B,disabled:d,children:z}),e[46]=d,e[47]=B,e[48]=z,e[49]=U):U=e[49];let K;e[50]!==I||e[51]!==U?(K=s.jsxs(In,{children:[I,U]}),e[50]=I,e[51]=U,e[52]=K):K=e[52];let V;e[53]!==H||e[54]!==K?(V=s.jsxs(Ws,{className:"max-w-md",keyboardAvoid:!0,children:[H,K]}),e[53]=H,e[54]=K,e[55]=V):V=e[55];let q;e[56]!==l||e[57]!==V?(q=s.jsx(Vs,{open:l,onOpenChange:c,children:V}),e[56]=l,e[57]=V,e[58]=q):q=e[58];let $;return e[59]!==T||e[60]!==q?($=s.jsxs(s.Fragment,{children:[T,q]}),e[59]=T,e[60]=q,e[61]=$):$=e[61],$},JG=t=>{const e=Me.c(54),{className:n,selectedGroupName:r,onGroupSelect:o,onNewAgent:a}=t,[i,l]=u.useState(""),[c,d]=u.useState(!1),{groups:f,isLoading:m,loadGroups:p}=Qa(),g=Rs(eq);let y,x;e[0]!==g||e[1]!==p?(y=()=>{g&&p()},x=[g,p],e[0]=g,e[1]=p,e[2]=y,e[3]=x):(y=e[2],x=e[3]),u.useEffect(y,x);let h;e:{if(!i.trim()){h=f;break e}let U;if(e[4]!==f||e[5]!==i){const K=i.toLowerCase();U=f.filter(V=>V.name.toLowerCase().includes(K)),e[4]=f,e[5]=i,e[6]=U}else U=e[6];h=U}const v=h;let b;e[7]!==v||e[8]!==c?(b=c?v:v.slice(0,5),e[7]=v,e[8]=c,e[9]=b):b=e[9];const w=b,j=v.length-5;let F;e[10]!==n?(F=Z("flex h-full flex-col text-foreground border-r border-border/30",n),e[10]=n,e[11]=F):F=e[11];let A;e[12]===Symbol.for("react.memo_cache_sentinel")?(A=s.jsx(Cr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e[12]=A):A=e[12];let C;e[13]===Symbol.for("react.memo_cache_sentinel")?(C=U=>l(U.target.value),e[13]=C):C=e[13];let S;e[14]!==i?(S=s.jsx("div",{className:"px-2.5 pt-3 pb-2",children:s.jsxs("div",{className:"relative",children:[A,s.jsx(fs,{value:i,onChange:C,placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e[14]=i,e[15]=S):S=e[15];let N,k;e[16]===Symbol.for("react.memo_cache_sentinel")?(k=s.jsx(sn,{className:"h-4 w-4"}),N=s.jsx("span",{className:"typography-ui-label",children:"New Agent Group"}),e[16]=N,e[17]=k):(N=e[16],k=e[17]);let D;e[18]!==a?(D=s.jsx("div",{className:"px-2.5 pb-2",children:s.jsxs(ot,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:a,children:[k,N]})}),e[18]=a,e[19]=D):D=e[19];let M,E;e[20]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(Us,{className:"h-4 w-4 text-muted-foreground"}),E=s.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),e[20]=M,e[21]=E):(M=e[20],E=e[21]);let _;e[22]!==m?(_=m&&s.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."}),e[22]=m,e[23]=_):_=e[23];let T;e[24]!==_?(T=s.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[M,E,_]}),e[24]=_,e[25]=T):T=e[25];let P;if(e[26]!==o||e[27]!==r||e[28]!==w){let U;e[30]!==o||e[31]!==r?(U=K=>s.jsx(YG,{group:K,isSelected:r===K.name,onSelect:()=>o?.(K.name)},K.name),e[30]=o,e[31]=r,e[32]=U):U=e[32],P=w.map(U),e[26]=o,e[27]=r,e[28]=w,e[29]=P}else P=e[29];let H;e[33]!==j||e[34]!==c?(H=!c&&j>0&&s.jsxs("button",{type:"button",onClick:()=>d(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",j,")"]}),e[33]=j,e[34]=c,e[35]=H):H=e[35];let R;e[36]!==v.length||e[37]!==c?(R=c&&v.length>5&&s.jsx("button",{type:"button",onClick:()=>d(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),e[36]=v.length,e[37]=c,e[38]=R):R=e[38];let I;e[39]!==v.length||e[40]!==m||e[41]!==i?(I=!m&&v.length===0&&s.jsxs("div",{className:"py-4 text-center",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:i.trim()?"No groups found":"No agent groups yet"}),!i.trim()&&s.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]}),e[39]=v.length,e[40]=m,e[41]=i,e[42]=I):I=e[42];let B;e[43]!==P||e[44]!==H||e[45]!==R||e[46]!==I?(B=s.jsxs(Ps,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[P,H,R,I]}),e[43]=P,e[44]=H,e[45]=R,e[46]=I,e[47]=B):B=e[47];let z;return e[48]!==D||e[49]!==T||e[50]!==B||e[51]!==F||e[52]!==S?(z=s.jsxs("div",{className:F,children:[S,D,T,B]}),e[48]=D,e[49]=T,e[50]=B,e[51]=F,e[52]=S,e[53]=z):z=e[53],z};function XG(t){return t.deleteGroup}function ZG(t){return t.stopPropagation()}function eq(t){return t.currentDirectory}const tq=10*1024*1024,sq=5,nq=({className:t,onCreateGroup:e,isCreating:n=!1})=>{const[r,o]=u.useState(""),[a,i]=u.useState(""),[l,c]=u.useState([]),[d,f]=u.useState(""),[m,p]=u.useState("HEAD"),[g,y]=u.useState([]),[x,h]=u.useState(!1),[v,b]=u.useState([]),[w,j]=u.useState(!1),[F,A]=u.useState(!1),C=u.useRef(null),S=u.useRef(null),{currentTheme:N}=mo(),k=Rs(G=>G.currentDirectory??null),{isGitRepository:D,isLoading:M}=Nx(k),E=u.useMemo(()=>{if(typeof window>"u")return null;const G=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof G=="string"&&G.trim().length>0?G.trim():null},[]),_=u.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),T=bs(G=>G.activeProjectId),P=bs(G=>G.projects),H=u.useMemo(()=>{if(_&&E)return{id:`vscode:${E}`,path:E};if(T){const G=P.find(W=>W.id===T);if(G?.path)return{id:G.id,path:G.path}}return k?{id:`path:${k}`,path:k}:null},[T,P,k,E,_]);u.useEffect(()=>{if(!H)return;let G=!1;return A(!0),(async()=>{try{const W=await Vi(H);G||b(W)}catch{}finally{G||A(!1)}})(),()=>{G=!0}},[H]);const R=u.useCallback(G=>{l.length>=sq||c(W=>[...W,G])},[l.length]),I=u.useCallback(G=>{c(W=>W.filter((J,te)=>te!==G))},[]),B=u.useCallback((G,W)=>{c(J=>J.map((te,le)=>le===G?W:te))},[]),z=async G=>{const W=G.target.files;if(!W)return;let J=0;for(let te=0;te<W.length;te++){const le=W[te];if(le.size>tq){ce.error(`File "${le.name}" is too large (max 10MB)`);continue}try{const ae=await new Promise((oe,Y)=>{const re=new FileReader;re.onload=()=>oe(re.result),re.onerror=Y,re.readAsDataURL(le)}),ie={id:om(),filename:le.name,mimeType:le.type||"application/octet-stream",size:le.size,dataUrl:ae};y(oe=>[...oe,ie]),J++}catch(ae){console.error("File attach failed",ae),ce.error(`Failed to attach "${le.name}"`)}}J>0&&ce.success(`Attached ${J} file${J>1?"s":""}`),C.current&&(C.current.value="")},U=G=>{y(W=>W.filter(J=>J.id!==G))},K=x||n,V=!!(r.trim()&&a.trim()&&l.length>=1&&D&&!M),q=async G=>{if(G.preventDefault(),!(!V||K)){h(!0);try{const W=l.map(({providerID:le,modelID:ae,displayName:ie,variant:oe})=>({providerID:le,modelID:ae,displayName:ie,variant:oe})),J=g.length>0?g.map(le=>({mime:le.mimeType,filename:le.filename,url:le.dataUrl})):void 0,te=v.filter(le=>le.trim().length>0);await e?.({name:r.trim(),prompt:a.trim(),models:W,agent:d||void 0,worktreeBaseBranch:m,files:J,setupCommands:te.length>0?te:void 0}),o(""),i(""),c([]),f(""),y([]),p("HEAD")}catch(W){console.error("Failed to create agent group:",W),ce.error("Failed to create agent group")}finally{h(!1)}}},$=G=>{ax(G)||G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),V&&!K&&q(G))};return s.jsx("div",{className:Z("flex flex-col items-center justify-center h-full w-full p-4",t),children:s.jsxs("form",{onSubmit:q,className:"w-full max-w-2xl space-y-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:"Group Name"}),s.jsx(fs,{id:"group-name",value:r,onChange:G=>o(G.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[s.jsx(bn,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),s.jsx(mS,{directory:k,value:m,onChange:p}),s.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",s.jsx("code",{className:"font-mono text-xs",children:m})]})]}),s.jsxs(ro,{open:w,onOpenChange:j,children:[s.jsxs(Do,{className:"w-full flex items-center justify-between py-1 hover:bg-[var(--interactive-hover)] rounded-md px-1 -mx-1 transition-colors",children:[s.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",v.filter(G=>G.trim()).length>0&&s.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",v.filter(G=>G.trim()).length," configured)"]})]}),s.jsx(Us,{className:Z("h-4 w-4 text-muted-foreground transition-transform duration-200",w&&"rotate-180")})]}),s.jsx(oo,{children:s.jsxs("div",{className:"pt-2 space-y-2",children:[s.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",s.jsx("code",{className:"font-mono text-xs",children:"$ROOT_PROJECT_PATH"})," for project root."]}),F?s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):s.jsxs("div",{className:"space-y-1.5",children:[v.map((G,W)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx(fs,{value:G,onChange:J=>{const te=[...v];te[W]=J.target.value,b(te)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>{const J=v.filter((te,le)=>le!==W);b(J)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:s.jsx(zs,{className:"h-4 w-4"})})]},W)),s.jsxs("button",{type:"button",onClick:()=>b([...v,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(sn,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),s.jsx(pS,{value:d,onChange:f}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Models"}),s.jsx(fS,{selectedModels:l,onAdd:R,onRemove:I,onUpdate:B,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),s.jsxs("div",{className:"rounded-xl border border-border/80 overflow-hidden focus-within:ring-1 focus-within:ring-primary/50",style:{backgroundColor:N?.colors?.surface?.subtle},children:[s.jsx(xr,{ref:S,id:"prompt",value:a,onChange:G=>i(G.target.value),onKeyDown:$,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent dark:bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),g.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:g.map(G=>s.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[G.mimeType.startsWith("image/")?s.jsx(Ja,{className:"h-3.5 w-3.5 text-muted-foreground"}):s.jsx(ca,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[120px]",title:G.filename,children:G.filename}),s.jsx("button",{type:"button",onClick:()=>U(G.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:s.jsx(zs,{className:"h-3.5 w-3.5"})})]},G.id))}),s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40 bg-transparent",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{ref:C,type:"file",multiple:!0,className:"hidden",onChange:z,accept:"*/*"}),s.jsx("button",{type:"button",onClick:()=>C.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:s.jsx(jv,{className:"h-[18px] w-[18px]"})})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),s.jsx("button",{type:"submit",disabled:!V||K,className:Z("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",V?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:K?s.jsx(_5,{className:"h-[18px] w-[18px] animate-spin"}):s.jsx(gh,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},rq=({group:t,className:e})=>{const{selectedSessionId:n,selectSession:r,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Qa(),{setCurrentSession:i,currentSessionId:l}=Re(),[c,d]=u.useState(null),[f,m]=u.useState(!1),p=u.useMemo(()=>n?t.sessions.find(w=>w.id===n)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,n]),g=u.useCallback(w=>{r(w.id),i(w.id)},[r,i]);u.useEffect(()=>{if(t.sessions.length>0){const w=n?t.sessions.find(j=>j.id===n)??t.sessions[0]:t.sessions[0];w&&(w.id!==l&&i(w.id),n||r(w.id))}},[t.name,t.sessions,n,l,r,i]);const y=p?.id===l,x=u.useCallback(()=>{if(!p?.path){ce.error("No worktree path available");return}Cn(p.path).then(w=>{if(w.ok){ce.success("Worktree path copied");return}ce.error("Failed to copy path")})},[p?.path]),h=u.useCallback(async()=>{p&&d({kind:"remove",path:p.path,label:p.displayLabel})},[p]),v=u.useCallback(async()=>{p&&d({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),b=u.useCallback(async()=>{if(!(!c||f)){m(!0);try{if(c.kind==="remove")if(ce.info("Removing worktree..."),await o(t.name,c.path))ce.success("Worktree removed");else{const j=Qa.getState().error;ce.error(j||"Failed to remove worktree");return}else if(ce.info("Removing other worktrees..."),await a(t.name,c.path))ce.success("Removed other worktrees");else{const j=Qa.getState().error;ce.error(j||"Failed to remove other worktrees");return}d(null)}finally{m(!1)}}},[o,t.name,f,a,c]);return s.jsxs("div",{className:Z("flex h-full flex-col bg-background",e),children:[s.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[s.jsx("div",{className:"flex items-start justify-between gap-4",children:s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:t.name}),s.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[s.jsxs("span",{children:[t.sessionCount," model",t.sessionCount!==1?"s":""]}),s.jsx("span",{children:"·"}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(bn,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),t.sessions.length>0&&s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("div",{className:"flex-1 min-w-0",children:s.jsxs(Ys,{children:[s.jsx(Js,{asChild:!0,children:s.jsxs(ot,{variant:"outline",className:"w-full justify-between h-10 px-3",children:[s.jsx("div",{className:"flex items-center gap-2 min-w-0",children:p&&s.jsxs(s.Fragment,{children:[s.jsx(Bn,{providerId:p.providerId,className:"h-5 w-5 flex-shrink-0"}),s.jsx("span",{className:"truncate typography-body",children:p.modelId}),p.instanceNumber>1&&s.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",p.instanceNumber]})]})}),s.jsx(Us,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(Xs,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(w=>s.jsxs(is,{onClick:()=>g(w),className:"flex items-center gap-2 py-2",children:[s.jsx(Bn,{providerId:w.providerId,className:"h-5 w-5 flex-shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-body",children:w.modelId}),w.instanceNumber>1&&s.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",w.instanceNumber]})]}),w.branch&&s.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[s.jsx(bn,{className:"h-3 w-3"}),s.jsx("span",{className:"truncate",children:w.worktreeMetadata?.label||w.branch})]})]}),p?.id===w.id&&s.jsx(Ts,{className:"h-4 w-4 text-primary flex-shrink-0"})]},w.id))})]})}),s.jsxs(Ys,{children:[s.jsx(Js,{asChild:!0,children:s.jsx(ot,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:s.jsx(Fo,{className:"h-4 w-4"})})}),s.jsxs(Xs,{align:"end",className:"min-w-[220px]",children:[s.jsx(is,{onSelect:w=>{w.preventDefault(),h()},variant:"destructive",children:"Remove this worktree"}),s.jsx(is,{onSelect:w=>{w.preventDefault(),v()},children:"Leave this one, remove others"}),s.jsxs(is,{onClick:w=>{w.stopPropagation(),x()},disabled:!p?.path,children:[s.jsx(ir,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),s.jsx(Vs,{open:!!c,onOpenChange:w=>{w||d(null)},children:s.jsxs(Ws,{className:"max-w-md",keyboardAvoid:!0,children:[s.jsxs(en,{children:[s.jsx(Zs,{children:c?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),s.jsx(nn,{children:c?.kind==="remove"?s.jsxs(s.Fragment,{children:["Remove ",s.jsx("span",{className:"text-foreground font-medium",children:c?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):s.jsxs(s.Fragment,{children:["Keep ",s.jsx("span",{className:"text-foreground font-medium",children:c?.label})," and remove the other worktrees in ",s.jsx("span",{className:"text-foreground font-medium",children:t.name}),"."]})})]}),s.jsxs(In,{children:[s.jsx(ot,{variant:"outline",onClick:()=>d(null),disabled:f,children:"Cancel"}),s.jsx(ot,{variant:c?.kind==="remove"?"destructive":"default",onClick:()=>{b()},disabled:f,children:f?"Working…":c?.kind==="remove"?"Remove":"Remove others"})]})]})}),s.jsx("div",{className:"flex-1 min-h-0",children:p?y?s.jsx(fj,{sessionId:p.id,children:s.jsx(uj,{})}):s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsx("div",{className:"px-4 py-2 bg-muted/30 border-b border-border/30",children:s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(Bn,{providerId:p.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel}),s.jsx("span",{children:"·"}),s.jsx("span",{className:"font-mono text-xs truncate",children:p.path})]})}),s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsxs("div",{className:"text-center p-8",children:[s.jsxs("p",{className:"typography-body text-muted-foreground mb-2",children:["Loading session for ",s.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel})]}),s.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",p.id]})]})})]}):s.jsx("div",{className:"h-full flex items-center justify-center",children:s.jsx("p",{className:"typography-body text-muted-foreground",children:"No sessions in this group"})})})]})},oq=({className:t})=>{const e=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[n,r]=u.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=rs(w=>w.isInitialized),a=rs(w=>w.initializeApp),i=Re(w=>w.loadSessions),l=Rs(w=>w.setDirectory),c=u.useRef(0),{selectedGroupName:d,selectGroup:f,getSelectedGroup:m,loadGroups:p}=Qa(),{createMultiRun:g,isLoading:y}=rd();u.useEffect(()=>{if(!e)return;const w=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(w==="connected"||w==="connecting"||w==="error"||w==="disconnected")&&r(w);const j=F=>{const C=F.detail?.status;(C==="connected"||C==="connecting"||C==="error"||C==="disconnected")&&r(C)};return window.addEventListener("openchamber:connection-status",j),()=>window.removeEventListener("openchamber:connection-status",j)},[e]),u.useEffect(()=>{if(!e||n!=="connected")return;const w=Date.now();if(w-c.current<750)return;c.current=w;const j=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof j=="string"&&j.trim().length>0)try{l(j,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const A=rs.getState();if(!A.isInitialized||!A.isConnected||A.providers.length===0||A.agents.length===0)return;await i(),nr()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:A.providers.length,agents:A.agents.length,sessions:Re.getState().sessions.length})}catch{}})()},[n,o,a,e,i,l]);const x=u.useCallback(w=>{f(w)},[f]),h=u.useCallback(()=>{f(null)},[f]),v=u.useCallback(async w=>{ce.info(`Creating agent group "${w.name}" with ${w.models.length} model(s)...`);const j=await g(w);if(j){ce.success(`Agent group "${w.name}" created with ${j.sessionIds.length} session(s)`);const F=j.groupSlug,A=async(C=6)=>{for(let S=0;S<C;S+=1){if(await p(),Qa.getState().groups.some(k=>k.name===F))return!0;await new Promise(k=>setTimeout(k,500))}return!1};try{await Re.getState().loadSessions()}catch{}await A(),f(F)}else{const F=rd.getState().error;ce.error(F||"Failed to create agent group")}},[g,p,f]),b=m();return s.jsxs("div",{className:Z("flex h-full w-full bg-background",t),children:[s.jsx("div",{className:"w-64 flex-shrink-0",children:s.jsx(JG,{selectedGroupName:d,onGroupSelect:x,onNewAgent:h})}),s.jsx("div",{className:"flex-1 min-w-0",children:b?s.jsx(rq,{group:b}):s.jsx(nq,{onCreateGroup:v,isCreating:y})})]})},aq=t=>{const e=Me.c(66),{onClose:n}=t,{sessions:r,messages:o,sessionMemoryState:a,currentSessionId:i,trimToViewportWindow:l,evictLeastRecentlyUsed:c}=Re();let d;e[0]!==o?(d=0,o.forEach($=>{d=d+$.length}),e[0]=o,e[1]=d):d=e[1];const f=d;let m;if(e[2]!==i||e[3]!==o||e[4]!==a||e[5]!==r){let $;e[7]!==i||e[8]!==o||e[9]!==a?($=G=>{const W=o.get(G.id)?.length||0,J=a.get(G.id);return{id:G.id,title:G.title||"Untitled",messageCount:W,isStreaming:J?.isStreaming||!1,isZombie:J?.isZombie||!1,backgroundCount:J?.backgroundMessageCount||0,lastAccessed:J?.lastAccessedAt||0,isCurrent:G.id===i}},e[7]=i,e[8]=o,e[9]=a,e[10]=$):$=e[10],m=r.map($).sort(iq),e[2]=i,e[3]=o,e[4]=a,e[5]=r,e[6]=m}else m=e[6];const p=m,g=o.size;let y;e[11]===Symbol.for("react.memo_cache_sentinel")?(y=s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(lv,{className:"h-4 w-4"}),s.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),e[11]=y):y=e[11];let x;e[12]!==n?(x=n&&s.jsx(ot,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(zs,{className:"h-4 w-4"})}),e[12]=n,e[13]=x):x=e[13];let h;e[14]!==x?(h=s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[y,x]}),e[14]=x,e[15]=h):h=e[15];let v;e[16]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e[16]=v):v=e[16];let b;e[17]!==f?(b=s.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[v,s.jsx("div",{className:"typography-markdown font-semibold",children:f})]}),e[17]=f,e[18]=b):b=e[18];let w;e[19]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e[19]=w):w=e[19];let j;e[20]!==g?(j=s.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[w,s.jsxs("div",{className:"typography-markdown font-semibold",children:[g," / ",Jl.MAX_SESSIONS]})]}),e[20]=g,e[21]=j):j=e[21];let F;e[22]!==b||e[23]!==j?(F=s.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[b,j]}),e[22]=b,e[23]=j,e[24]=F):F=e[24];let A;e[25]===Symbol.for("react.memo_cache_sentinel")?(A=s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),s.jsxs("span",{children:[Sm()," messages"]})]}),e[25]=A):A=e[25];let C;e[26]===Symbol.for("react.memo_cache_sentinel")?(C=s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Background Stream Limit:"}),s.jsxs("span",{children:[Jl.BACKGROUND_STREAMING_BUFFER," messages"]})]}),e[26]=C):C=e[26];let S;e[27]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[A,C,s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Zombie Timeout:"}),s.jsxs("span",{children:[Jl.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e[27]=S):S=e[27];let N;e[28]===Symbol.for("react.memo_cache_sentinel")?(N=s.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e[28]=N):N=e[28];let k;e[29]!==p?(k=p.map(lq),e[29]=p,e[30]=k):k=e[30];let D;e[31]!==k?(D=s.jsxs("div",{className:"border-t pt-2",children:[N,s.jsx(Ps,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:k})]}),e[31]=k,e[32]=D):D=e[32];let M;e[33]!==i||e[34]!==l?(M=()=>{i&&l(i,10)},e[33]=i,e[34]=l,e[35]=M):M=e[35];let E;e[36]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Qn,{className:"h-3 w-3 mr-1"}),e[36]=E):E=e[36];let _;e[37]!==M?(_=s.jsx(Jt,{asChild:!0,children:s.jsxs(ot,{size:"sm",variant:"outline",className:"typography-meta",onClick:M,children:[E,"Force Trim (10)"]})}),e[37]=M,e[38]=_):_=e[38];let T;e[39]===Symbol.for("react.memo_cache_sentinel")?(T=s.jsx(Kt,{side:"top",children:"Trim current session to only 10 most recent messages"}),e[39]=T):T=e[39];let P;e[40]!==_?(P=s.jsxs(Yt,{delayDuration:1e3,children:[_,T]}),e[40]=_,e[41]=P):P=e[41];let H;e[42]!==c?(H=s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{c()},children:"Evict LRU"})}),e[42]=c,e[43]=H):H=e[43];let R;e[44]===Symbol.for("react.memo_cache_sentinel")?(R=s.jsx(Kt,{side:"top",children:"Remove least recently used sessions from memory cache"}),e[44]=R):R=e[44];let I;e[45]!==H?(I=s.jsxs(Yt,{delayDuration:1e3,children:[H,R]}),e[45]=H,e[46]=I):I=e[46];let B;e[47]!==i||e[48]!==o||e[49]!==a||e[50]!==r?(B=s.jsx(Jt,{asChild:!0,children:s.jsx(ot,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(cq),currentSessionId:i,cachedSessions:Array.from(o.keys()),memoryStates:Object.fromEntries(a)})},children:"Log State"})}),e[47]=i,e[48]=o,e[49]=a,e[50]=r,e[51]=B):B=e[51];let z;e[52]===Symbol.for("react.memo_cache_sentinel")?(z=s.jsx(Kt,{side:"top",children:"Log current memory state to browser console"}),e[52]=z):z=e[52];let U;e[53]!==B?(U=s.jsxs(Yt,{delayDuration:1e3,children:[B,z]}),e[53]=B,e[54]=U):U=e[54];let K;e[55]!==P||e[56]!==I||e[57]!==U?(K=s.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[P,I,U]}),e[55]=P,e[56]=I,e[57]=U,e[58]=K):K=e[58];let V;e[59]!==D||e[60]!==K||e[61]!==F?(V=s.jsxs("div",{className:"space-y-3",children:[F,null,S,D,K]}),e[59]=D,e[60]=K,e[61]=F,e[62]=V):V=e[62];let q;return e[63]!==V||e[64]!==h?(q=s.jsxs(Zg,{className:"fixed bottom-4 right-4 w-96 p-4 shadow-none z-50 bg-background/95 backdrop-blur bottom-safe-area",children:[h,V]}),e[63]=V,e[64]=h,e[65]=q):q=e[65],q};function iq(t,e){return e.lastAccessed-t.lastAccessed}function lq(t){return s.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${t.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[s.jsx("span",{className:"truncate",children:t.title}),t.isStreaming&&s.jsx(P5,{className:"h-3 w-3 text-primary animate-pulse"}),t.isZombie&&s.jsx("span",{className:"text-status-warning",children:"!"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`font-mono ${t.messageCount>Zo()?"text-status-warning":""}`,children:[t.messageCount," msgs"]}),t.backgroundCount>0&&s.jsxs("span",{className:"text-primary",children:["+",t.backgroundCount]})]})]},t.id)}function cq(t){return{id:t.id,title:t.title}}const dq="openchamber-message-cursors",am="cursors",uq=1,xS="openchamber.messageCursors",Cx=()=>typeof window<"u",yS=()=>Cx()&&typeof indexedDB<"u",fq=()=>yS()?new Promise((t,e)=>{const n=indexedDB.open(dq,uq);n.onupgradeneeded=()=>{const r=n.result;r.objectStoreNames.contains(am)||r.createObjectStore(am)},n.onerror=()=>{e(n.error??new Error("Failed to open IndexedDB"))},n.onsuccess=()=>{t(n.result)}}):Promise.reject(new Error("IndexedDB not supported")),mq=()=>{if(!Cx())return{};try{const t=window.localStorage.getItem(xS);if(!t)return{};const e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}},pq=t=>{if(Cx())try{window.localStorage.setItem(xS,JSON.stringify(t))}catch{}},hq=async(t,e,n)=>{if(!t||!e)return;if(yS())try{const o=await fq();await new Promise((a,i)=>{const l=o.transaction(am,"readwrite");l.objectStore(am).put({messageId:e,completedAt:n},t),l.oncomplete=()=>a(),l.onerror=()=>i(l.error??new Error("Cursor write failed")),l.onabort=()=>i(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const r=mq();r[t]={messageId:e,completedAt:n},pq(r)},Lr=(t,e)=>{if(!t||typeof t!="object")return null;const n=t;for(let r=0;r<e.length;r++){const o=n[e[r]];if(typeof o=="string"&&o.length>0)return o}return null},gq=50,xq=750,yq=1500,bq=1500,G1=new WeakMap,q1=t=>{if(!t||!Array.isArray(t))return 0;const e=G1.get(t);if(e!==void 0)return e;let n=0;for(let r=0;r<t.length;r++){const o=t[r];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(n+=a.length)}}return G1.set(t,n),n},vq=10,K1=t=>{if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const n=e.indexOf("_"),r=n>=0?e.slice(n+1):e;return!r||r.length<vq?null:r},fh=(t,e)=>{const n=K1(t),r=K1(e);return!n||!r||n.length!==r.length?!0:n>r},wq=500,jq=100,wi=new Map,Ju=(t,e)=>{const n=`${t}:${e}`,r=wi.get(n);if(r&&r.sessionId===t)return r.message;const i=(Re.getState().messages.get(t)||[]).find(l=>l.info.id===e)||null;if(wi.size>=wq){let l=0;for(const c of wi.keys()){if(l++>=jq)break;wi.delete(c)}}return wi.set(n,{sessionId:t,message:i}),i},Sq=()=>{const{addStreamingPart:t,completeStreamingMessage:e,updateMessageInfo:n,updateSessionCompaction:r,addPermission:o,dismissPermission:a,addQuestion:i,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,getWorktreeMetadata:f,loadMessages:m,loadSessions:p,updateSession:g,removeSessionFromStore:y}=Re(),{checkConnection:x}=rs(),h=Rs(_e=>_e.currentDirectory),v=u.useMemo(()=>{if(!c)return;try{const Ye=f?.(c);if(Ye?.path)return Ye.path}catch(Ye){console.warn("Failed to inspect worktree metadata for session directory:",Ye)}const je=Re.getState().sessions.find(Ye=>Ye.id===c);if(je&&typeof je.directory=="string"&&je.directory.trim().length>0)return je.directory.trim()},[c,f]),b=u.useMemo(()=>{if(v&&v.length>0)return v;if(typeof h=="string"&&h.trim().length>0)return h.trim()},[v,h]),w=u.useCallback(async()=>{try{const je=bs.getState().projects.map(Se=>Se.path),Ne=Re.getState().sessions.map(Se=>Se.directory),Pe=[b,...je,...Ne],Qe=await Lt.listPendingQuestions({directories:Pe});if(Qe.length===0)return;for(const Se of Qe)i(Se)}catch{}},[i,b]),j=u.useRef(0),F=u.useCallback((_e=!1)=>{const je=Date.now();!_e&&je-j.current<yq||(j.current=je,w())},[w]),A=u.useCallback(async()=>{try{const je=bs.getState().projects.map(Se=>Se.path),Ne=Re.getState().sessions.map(Se=>Se.directory),Pe=[b,...je,...Ne],Qe=await Lt.listPendingPermissions({directories:Pe});if(Qe.length===0)return;for(const Se of Qe)o(Se)}catch{}},[o,b]),C=u.useRef(0),S=u.useCallback((_e=!1)=>{const je=Date.now();!_e&&je-C.current<bq||(C.current=je,A())},[A]),N=u.useRef(S);u.useEffect(()=>{N.current=S},[S]),u.useEffect(()=>{S(!0),F(!0)},[S,F]);const k=u.useCallback(_e=>{if(typeof _e!="string")return null;const je=_e.trim();if(!je)return null;const Ye=je.replace(/\\/g,"/");return Ye.length>1?Ye.replace(/\/+$/,""):Ye},[]),D=u.useCallback(_e=>{if(!_e)return null;try{const Ne=f?.(_e),Pe=k(Ne?.path??null);if(Pe)return Pe}catch{}const Ye=Re.getState().sessions.find(Ne=>Ne.id===_e);return k(Ye?.directory??null)},[f,k]),M=Te(_e=>_e.setEventStreamStatus),E=u.useRef(null),_=u.useCallback((_e,je)=>{const Ye=je??null,Ne=E.current;if(!(Ne&&Ne.status===_e&&Ne.hint===Ye)){if(E.current={status:_e,hint:Ye},nr()){const Qe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[_e]??"[INFO]",Se=Ye?`${Qe} SSE ${_e}: ${Ye}`:`${Qe} SSE ${_e}`;console.info(Se)}M(_e,Ye)}},[M]),T=u.useCallback((_e,je,Ye)=>{if(!_e)return Promise.resolve();const Ne=Date.now();if(G.current)return G.current;if(Ne-W.current<xq)return Promise.resolve();const Pe=m(_e,Ye).catch(Qe=>{console.warn(`[useEventStream] Failed to resync messages (${je}):`,Qe)}).finally(()=>{G.current=null,W.current=Date.now()});return G.current=Pe,Pe},[m]),P=u.useCallback(async _e=>{nr()&&console.info("[useEventStream] Bootstrapping state:",_e);try{const je=Zo();await Promise.all([p(),c?T(c,_e,je):Promise.resolve()])}catch(je){console.warn("[useEventStream] Bootstrap failed:",_e,je)}},[c,p,T]),H=u.useCallback((_e,je,Ye=Zo())=>{if(!_e)return Promise.resolve();const Pe=Re.getState().sessionMemoryState.get(_e)?.streamingCooldownUntil,Qe=Date.now();if(typeof Pe=="number"&&Pe>Qe){const Se=Math.min(3e3,Math.max(0,Pe-Qe));return new Promise(Le=>{setTimeout(()=>{T(_e,je,Ye).finally(Le)},Se)})}return T(_e,je,Ye)},[T]);u.useEffect(()=>{de.current=H},[H]);const R=u.useCallback((_e,je,Ye)=>{nr()&&console.debug(`[MessageTracker] ${_e}: ${je}`,Ye)},[]),I=u.useCallback(_e=>{nr()&&console.debug(`[MessageTracker] ${_e}: reported`)},[]),B=u.useRef(null),z=u.useRef(null),U=u.useRef(0),K=u.useRef(new Set),V=u.useRef(new Map),q=u.useRef(null),$=u.useRef(!1),G=u.useRef(null),W=u.useRef(0),J=u.useRef(new Set),te=u.useRef(new Set),le=u.useRef(new Set),ae=u.useRef(new Set),ie=u.useRef(!1),oe=u.useRef(new Set),Y=u.useRef(new Map),re=u.useCallback(()=>{if(typeof document>"u")return"visible";const _e=document.visibilityState;return _e==="hidden"&&document.hasFocus()?"visible":_e},[]),ue=u.useRef(re()),Q=u.useRef(typeof navigator>"u"?!0:navigator.onLine),O=u.useRef(!1),se=u.useRef(null),X=u.useRef(null),L=u.useRef(Date.now()),me=u.useRef(new Map),fe=u.useRef(new Map),pe=u.useRef(new Map),de=u.useRef(()=>Promise.resolve()),ne=u.useRef(()=>{}),ge=u.useCallback(_e=>ue.current==="hidden"?!0:_e&&typeof document<"u"?!document.hasFocus():!1,[]),we=u.useCallback(_e=>{const je=Tr();if(!je?.notifications)return;const Ye=typeof _e.title=="string"?_e.title.trim():"";if(!Ye)return;const Ne=Te.getState();if(!Ne.nativeNotificationsEnabled)return;const Pe=!!je.runtime?.isVSCode;(_e.requireHidden||Ne.notificationMode==="hidden-only")&&!ge(Pe)||je.notifications.notifyAgentCompletion({title:Ye,body:typeof _e.body=="string"?_e.body:"",tag:typeof _e.tag=="string"?_e.tag:void 0})},[ge]),Oe=u.useCallback(_e=>{const je=Date.now();je-L.current>25e3&&(P(_e),L.current=je)},[P]),et=u.useRef(c),$e=u.useRef(null),Ae=u.useRef(null);u.useEffect(()=>{et.current=c},[c]);const Ie=u.useCallback((_e,je)=>{if(!_e)return;const Ye=Date.now(),Ne=V.current,Pe=Ne.get(_e);if(Pe&&Ye-Pe<3e3)return;Ne.set(_e,Ye);const Qe=Se=>{if(typeof je=="string"&&je.trim().length>0)return je.trim();try{const Ke=f?.(Se);if(Ke?.path)return Ke.path}catch{}const st=Re.getState().sessions.find(Ke=>Ke.id===Se);return st&&typeof st.directory=="string"&&st.directory.trim().length>0?st.directory.trim():null};setTimeout(async()=>{try{const Se=Qe(_e),Le=Se?await Lt.withDirectory(Se,()=>Lt.getSession(_e)):await Lt.getSession(_e);if(Le){const st={};typeof Le.title=="string"&&Le.title.length>0&&(st.title=Le.title),Le.summary!==void 0&&(st.summary=Le.summary),Object.keys(st).length>0&&d(_e,st)}}catch(Se){console.warn("Failed to refresh session metadata:",Se)}},100)},[d,f]),be=u.useCallback((_e,je,Ye="unknown")=>{if(!_e)return;const Pe=Re.getState().sessionStatus?.get(_e)?.type??"idle",Qe=je?.type??"idle",Se=Pe==="idle"&&(Qe==="busy"||Qe==="retry");if(Qe==="idle"){const Ke=fe.current.get(_e);Ke&&(clearTimeout(Ke),fe.current.delete(_e))}if(Se){const Ke=fe.current.get(_e);Ke&&(clearTimeout(Ke),fe.current.delete(_e));const it=Date.now(),pt=setTimeout(()=>{const Ut=Re.getState().sessionStatus?.get(_e);if(Ut?.type!=="busy"&&Ut?.type!=="retry")return;const ss=pe.current.get(_e)??0;Date.now()-ss<15e3||(me.current.get(_e)??0)>=it||(pe.current.set(_e,Date.now()),de.current(_e,"status_busy_no_message",Zo()).finally(()=>{ne.current("No message events after busy status")}))},2e3);fe.current.set(_e,pt)}const st=new Map(Re.getState().sessionStatus??new Map);if(Qe==="idle")st.set(_e,{...je,confirmedAt:Date.now()});else{const Ke=st.get(_e);Ke?.confirmedAt?st.set(_e,{...je,confirmedAt:Ke.confirmedAt}):st.set(_e,je)}Re.setState({sessionStatus:st})},[]);u.useEffect(()=>{const _e=c??null,je=$e.current,Ye=D(_e);Ae.current,je&&_e&&je!==_e&&wi.clear(),$e.current=_e,Ae.current=Ye},[c,D]);const ee=u.useCallback(_e=>{if(L.current=Date.now(),nr()&&console.debug("[useEventStream] Received event:",_e.type,_e.properties),!_e.properties)return;const je=_e.properties;if(!new Set(["session.abort","session.error"]).has(_e.type)){const Ne=(typeof je.session=="object"&&je.session!==null?je.session:null)||(typeof je.sessionInfo=="object"&&je.sessionInfo!==null?je.sessionInfo:null);if(Ne){const Pe=Ne,Qe=typeof Pe.id=="string"&&Pe.id.length>0?Pe.id:typeof Pe.sessionID=="string"&&Pe.sessionID.length>0?Pe.sessionID:typeof je.sessionID=="string"&&je.sessionID.length>0?je.sessionID:typeof je.id=="string"&&je.id.length>0?je.id:void 0;if(Qe){const Se=typeof Pe.title=="string"?Pe.title:typeof je.title=="string"?je.title:void 0,Le=typeof Pe.summary=="object"&&Pe.summary!==null?Pe.summary:typeof je.summary=="object"&&je.summary!==null?je.summary:void 0;if(Se!==void 0||Le!==void 0){const st={};Se!==void 0&&(st.title=Se),Le!==void 0&&(st.summary=Le),d(Qe,st)}}}}switch(_e.type){case"server.connected":x();break;case"global.disposed":case"server.instance.disposed":{P("server_disposed_event");break}case"mcp.tools.changed":{const Ne=typeof je.directory=="string"?je.directory:b;to.getState().refresh({directory:Ne??null,silent:!0});break}case"session.status":{const Ne=Lr(je,["sessionID","sessionId"]),Pe=je.status,Qe=typeof Pe=="object"&&Pe!==null?Pe:null,Se=typeof Pe=="string"?Pe:typeof Qe?.type=="string"?Qe.type:typeof Qe?.status=="string"?Qe.status:typeof je.type=="string"?je.type:typeof je.phase=="string"?je.phase:typeof je.state=="string"?je.state:null,Le=Qe??{},st=je.metadata,Ke=typeof st=="object"&&st!==null?st:null;Ne&&Se&&(Se==="busy"?be(Ne,{type:"busy"},"sse:session.status"):Se==="retry"?be(Ne,{type:"retry",attempt:typeof Le.attempt=="number"?Le.attempt:typeof je.attempt=="number"?je.attempt:typeof Ke?.attempt=="number"?Ke.attempt:void 0,message:typeof Le.message=="string"?Le.message:typeof je.message=="string"?je.message:typeof Ke?.message=="string"?Ke.message:void 0,next:typeof Le.next=="number"?Le.next:typeof je.next=="number"?je.next:typeof Ke?.next=="number"?Ke.next:void 0},"sse:session.status"):be(Ne,{type:"idle"},"sse:session.status"),Ie(Ne,typeof je.directory=="string"?je.directory:null))}break;case"openchamber:session-status":{const Ne=Lr(je,["sessionId","sessionID"]),Pe=typeof je.status=="string"?je.status:null,Qe=typeof je.needsAttention=="boolean"?je.needsAttention:!1,Se=typeof je.timestamp=="number"?je.timestamp:Date.now();if(Ne&&Pe){if(Pe==="busy")be(Ne,{type:"busy"},"sse:openchamber:session-status");else if(Pe==="retry"){const it=typeof je.metadata=="object"&&je.metadata!==null?je.metadata:{};be(Ne,{type:"retry",attempt:typeof it.attempt=="number"?it.attempt:void 0,message:typeof it.message=="string"?it.message:void 0,next:typeof it.next=="number"?it.next:void 0},"sse:openchamber:session-status")}else be(Ne,{type:"idle"},"sse:openchamber:session-status");const Le=Re.getState().sessionAttentionStates||new Map,st=new Map(Le),Ke=st.get(Ne);st.set(Ne,{needsAttention:Qe,lastStatusChangeAt:Se,lastUserMessageAt:Ke?.lastUserMessageAt??null,status:Pe,isViewed:Ke?.isViewed??!1}),Re.setState({sessionAttentionStates:st})}}break;case"message.part.updated":{const Ne=typeof je.part=="object"&&je.part!==null?je.part:null;if(!Ne)break;const Pe=Ne,Qe=typeof je.info=="object"&&je.info!==null?je.info:je,Se=Lr(Qe,["sessionID","sessionId"]),Le=Lr(Pe,["sessionID","sessionId"])||Se||Lr(je,["sessionID","sessionId"]),st=Lr(Qe,["messageID","messageId","id"]),Ke=Lr(Pe,["messageID","messageId"])||st||Lr(je,["messageID","messageId"]);if(!Le||!Ke){nr()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Pe.sessionID??Se??je.sessionID,messageID:Pe.messageID??st??je.messageID});break}const it=Le,pt=Ke;me.current.set(it,Date.now());const Ut=fe.current.get(it);Ut&&(clearTimeout(Ut),fe.current.delete(it));const ss=Re.getState().sessionMemoryState.get(it)?.trimmedHeadMaxId;if(ss&&!fh(pt,ss)){nr()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:it,messageId:pt,trimmedHeadMaxId:ss});break}const Wt=vt=>{const gt=typeof vt=="string"?vt.trim():"";return gt?gt.startsWith("User has requested to enter plan mode")||gt.startsWith("The plan at ")||gt.startsWith("The following tool was executed by the user"):!1},dt=()=>{const vt=typeof Pe.type=="string"?Pe.type:"";if(vt==="subtask"||vt==="agent"||vt==="file")return!0;if(vt==="text"&&Pe.synthetic===!0){const gt=Pe.text;return Wt(gt)}return!1};let kt="assistant";if(Qe&&typeof Qe.role=="string")kt=Qe.role;else{const vt=Ju(it,pt);if(vt){const gt=vt.info.role;typeof gt=="string"&&(kt=gt)}}if(kt!=="user"&&dt()&&(kt="user"),R(pt,"part_received",{role:kt}),kt==="user"&&Pe.synthetic===!0){const vt=Pe.text;if(!Wt(vt)){R(pt,"skipped_synthetic_user_part");break}}const ht={...Ne,type:Ne.type||"text"};if(kt==="assistant"){const vt=ht.type,Dt=typeof ht.time?.end=="number",Et=ht.state?.status,Pt=typeof ht.tool=="string"?ht.tool.toLowerCase():null,St=ht.text;if(vt==="tool"&&Pt==="question"&&F(),vt==="tool"?Et==="running"||Et==="pending":vt==="reasoning"?!Dt:vt==="text"?typeof St=="string"&&St.trim().length>0&&!Dt:vt==="step-start"){const qt=Re.getState().sessionStatus?.get(it),Ge=qt?.type==="idle"&&typeof qt.confirmedAt=="number"&&Date.now()-qt.confirmedAt<1200;if(!qt||qt.type==="idle"){if(Ge)break;be(it,{type:"busy"},"sse:message.part.updated")}}}R(pt,"addStreamingPart_called"),t(it,pt,ht,kt);break}case"message.part.delta":{const Ne=Lr(je,["sessionID","sessionId"]),Pe=Lr(je,["messageID","messageId"]),Qe=Lr(je,["partID","partId"]),Se=Lr(je,["field"]),Le=typeof je.delta=="string"?je.delta:null;if(!Ne||!Pe||!Qe||!Se||Le===null){nr()&&console.debug("[useEventStream] Skipping message.part.delta with missing payload",{sessionID:je.sessionID,messageID:je.messageID,partID:je.partID,field:je.field});break}me.current.set(Ne,Date.now());const st=fe.current.get(Ne);st&&(clearTimeout(st),fe.current.delete(Ne));const Ke=Re.getState().sessionMemoryState.get(Ne)?.trimmedHeadMaxId;if(Ke&&!fh(Pe,Ke)){nr()&&console.debug("[useEventStream] Skipping message.part.delta for trimmed message",{sessionId:Ne,messageId:Pe,trimmedHeadMaxId:Ke});break}const it=Ju(Ne,Pe),pt=it?.parts?.find(ht=>ht?.id===Qe);if(!pt)break;const ss=pt[Se],Wt={...pt,[Se]:`${typeof ss=="string"?ss:""}${Le}`};let dt="assistant";const kt=it?.info?.role;if(typeof kt=="string"&&(dt=kt),dt==="assistant"&&Le.length>0){const ht=Re.getState().sessionStatus?.get(Ne),vt=ht?.type==="idle"&&typeof ht.confirmedAt=="number"&&Date.now()-ht.confirmedAt<1200;(!ht||ht.type==="idle")&&(vt||be(Ne,{type:"busy"},"sse:message.part.delta"))}R(Pe,"part_delta_received",{role:dt,field:Se}),t(Ne,Pe,Wt,dt);break}case"message.updated":{const Ne=typeof je.info=="object"&&je.info!==null?je.info:je,Pe=Ne,Qe=Lr(Pe,["sessionID","sessionId"])||Lr(je,["sessionID","sessionId"]),Se=Lr(Pe,["messageID","messageId","id"])||Lr(je,["messageID","messageId"]);if(!Qe||!Se){nr()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Pe.sessionID??je.sessionID,messageID:Pe.id??je.messageID});break}const Le=Qe,st=Se;me.current.set(Le,Date.now());const Ke=fe.current.get(Le);Ke&&(clearTimeout(Ke),fe.current.delete(Le));const it=Re.getState().sessionMemoryState.get(Le)?.trimmedHeadMaxId;if(it&&!fh(st,it)){nr()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Le,messageId:st,trimmedHeadMaxId:it});break}if(nr())try{const At=je.parts||Pe.parts||[],Bt=(Array.isArray(At)?At.filter(ts=>ts?.type==="text"):[]).map(ts=>{const as=ts;return typeof as?.text=="string"?as.text:typeof as?.content=="string"?as.content:""}).join(`
339
- `);console.info("[STREAM-TRACE] message.updated",{messageId:st,role:Pe.role,status:Pe.status,textLen:Bt.length,textPreview:Bt.slice(0,120),partsCount:Array.isArray(At)?At.length:0})}catch{}if(R(st,"message_updated",{role:Pe.role}),Pe.role==="user"){const{sessionMemoryState:At}=Os.getState(),It=At.get(Le);if(It){const zt=new Map(At);zt.set(Le,{...It,lastUserMessageAt:Date.now()}),Os.setState({sessionMemoryState:zt})}const Bt=je.parts||Pe.parts,ts=Array.isArray(Bt)?Bt:[],as=Ju(Le,st),ds=(()=>{const zt=Pe.agent;if(typeof zt=="string"&&zt.trim().length>0)return zt.trim();const Mt=Pe.mode;return typeof Mt=="string"&&Mt.trim().length>0?Mt.trim():""})(),Be=(()=>{const Mt=Pe.time?.created;return typeof Mt=="number"?Mt:null})(),ft=ts.length>0&&ts.every(zt=>zt?.synthetic===!0),Qt=(()=>{if(!ds)return!1;if(ft&&(ds==="plan"||ds==="build"))return!0;const zt=Y.current.get(Le);return zt?Be===null?!1:st===zt.messageId?!0:Be>=zt.created:!0})();if(ds&&Qt)try{const zt=rs.getState().agents;if(Array.isArray(zt)&&zt.some(Mt=>Mt?.name===ds)){const Mt=Ss.getState();if(Mt.saveSessionAgentSelection(Le,ds),Y.current.set(Le,{created:Be??Date.now(),messageId:st}),et.current===Le)try{rs.getState().setAgent(ds)}catch{}const cs=Pe.model,Cs=typeof cs?.providerID=="string"?cs.providerID:null,Ns=typeof cs?.modelID=="string"?cs.modelID:null;if(Cs&&Ns){Mt.saveSessionModelSelection(Le,Cs,Ns),Mt.saveAgentModelForSession(Le,ds,Cs,Ns);const $s=typeof Pe.variant=="string"?Pe.variant:void 0;if(Mt.saveAgentModelVariantForSession(Le,ds,Cs,Ns,$s),et.current===Le)try{rs.getState().setProvider(Cs),rs.getState().setModel(Ns)}catch{}}}}catch{}if(ft&&(ds==="plan"||ds==="build")&&et.current===Le){const zt=`${Le}:${st}:${ds}`;oe.current.has(zt)||(oe.current.add(zt),gr(async()=>{const{toast:Mt}=await import("./vendor-.bun-Byc0cUD3.js").then(cs=>cs.eL);return{toast:Mt}},__vite__mapDeps([0,1])).then(({toast:Mt})=>{Mt.info(ds==="plan"?"Plan mode active":"Build mode active",{description:ds==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const Gt={...Ne,userMessageMarker:!0,clientRole:"user",...ds?{mode:ds}:{}};if(n(Le,st,Gt),!as&&ts.length===0){const zt=`${Le}:${st}`;K.current.has(zt)||(K.current.add(zt),Lt.getSessionMessages(Le,50).then(Mt=>{Re.getState().syncMessages(Le,Mt)}).catch(()=>{}))}if(ts.length>0)for(let zt=0;zt<ts.length;zt++){const Mt=ts[zt];if(Mt.synthetic===!0){const Ns=Mt.text,$s=typeof Ns=="string"?Ns.trim():"";if(!($s.startsWith("User has requested to enter plan mode")||$s.startsWith("The plan at ")||$s.startsWith("The following tool was executed by the user")))continue}const Cs={...Mt,type:Mt?.type||"text",sessionID:Mt?.sessionID||Le,messageID:Mt?.messageID||st};t(Le,st,Cs,"user")}R(st,"user_message_created_from_event",{partsCount:ts.length});break}const pt=Ju(Le,st),Ut=q1(pt?.parts||[]),ss=pt?.info?.finish==="stop",Wt=je.parts||Pe.parts,dt=Array.isArray(Wt)?Wt:[],kt=dt.length>0,vt=typeof(Pe.time||{})?.completed=="number",gt=Ne.status,Dt=typeof gt=="string"?gt.toLowerCase():null,Et=Dt==="completed"||Dt==="complete",Pt=Ne.finish,St=typeof Pt=="string"?Pt:null,Ot=St==="stop",qt=St==="error";if(!kt&&!vt&&!Et&&!Ot&&!qt)break;if(Pe.role==="assistant"&&kt){dt.some(ts=>ts?.type==="tool"&&typeof ts.tool=="string"&&ts.tool.toLowerCase()==="question")&&F();const It=q1(dt);if(Ut>0&&It+gq<Ut&&!Ot){R(st,"skipped_shrinking_update",{incomingLen:It,existingLen:Ut});break}}n(Le,st,Ne);const Ge=typeof Ne.role=="string"?Ne.role:null;if(!!Tr()?.runtime?.isVSCode&&!ie.current&&Ge==="assistant"){const At=Te.getState(),It=Re.getState().sessions.find(ts=>ts.id===Le),Bt=typeof It?.title=="string"?It.title.trim():"";if(Ot&&At.notifyOnCompletion!==!1){const ts=!!It?.parentID;if(!(At.notifyOnSubtasks===!1&&ts)){const as=`ready:${Le}:${st}`;le.current.has(as)||(le.current.add(as),we({title:"Agent is ready",body:Bt||"Task completed",tag:`ready-${Le}`}))}}if(qt&&At.notifyOnError!==!1){const ts=`error:${Le}:${st}`;le.current.has(ts)||(le.current.add(ts),we({title:"Tool error",body:Bt||"An error occurred",tag:`error-${Le}`}))}}if(kt&&Pe.role!=="user"){const Bt=(Re.getState().messages.get(Le)||[]).find(ds=>ds.info.id===st),ts=!Bt||Bt.parts.length===0;R(st,ts?"server_parts_injected":"server_parts_refreshed",{count:dt.length});const as=dt;for(let ds=0;ds<as.length;ds++){const Be=as[ds],ft={...Be,type:Be?.type||"text",sessionID:Be?.sessionID||Le,messageID:Be?.messageID||st};t(Le,st,ft,Pe.role),R(st,`server_part_${ds}`)}}const at=Ne.time,bt=at?.completed,wt=typeof bt=="number"&&Number.isFinite(bt),Rt=St==="stop"||ss;if(Ne.role==="assistant"&&(wt||Et||Rt)&&Ne.role==="assistant"){const It=Re.getState().messages.get(Le)||[];let Bt=null,ts="";for(let Gt=0;Gt<It.length;Gt++){const zt=It[Gt];zt.info.role==="assistant"&&zt.info.id>ts&&(ts=zt.info.id,Bt=zt.info.id)}if(c===Le&&st!==Bt)break;const ds=wt?bt:Date.now();wt||n(Le,st,{...Ne,time:{...at??{},completed:ds}}),R(st,"completed",{timeCompleted:ds}),I(st),hq(Le,st,ds),e(Le,st);const Be=Ne.sessionID,ft=typeof Be=="string"&&Be.length>0?Be:Le;Ie(ft,typeof je.directory=="string"?je.directory:null),Ne.summary&&typeof ft=="string"&&r(ft,null)}break}case"session.created":case"session.updated":{const Ne=typeof je.info=="object"&&je.info!==null?je.info:typeof je.sessionInfo=="object"&&je.sessionInfo!==null?je.sessionInfo:typeof je.session=="object"&&je.session!==null?je.session:je,Pe=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof je.sessionID=="string"&&je.sessionID.length>0?je.sessionID:typeof je.id=="string"&&je.id.length>0?je.id:void 0;if(Pe){const Qe=typeof Ne.time=="object"&&Ne.time!==null?Ne.time:typeof je.time=="object"&&je.time!==null?je.time:null,Se=Qe&&typeof Qe.compacting=="number"?Qe.compacting:null;r(Pe,Se);const Le=typeof Ne.directory=="string"?Ne.directory:typeof je.directory=="string"?je.directory:null,st={...Ne,id:Pe,...Le?{directory:Le}:{}};g(st)}break}case"session.deleted":{const Ne=typeof je.sessionID=="string"?je.sessionID:typeof je.id=="string"?je.id:null;Ne&&y(Ne);break}case"session.abort":{const Ne=typeof je.sessionID=="string"&&je.sessionID.length>0?je.sessionID:null,Pe=typeof je.messageID=="string"&&je.messageID.length>0?je.messageID:null;Ne&&be(Ne,{type:"idle"},"sse:session.abort"),Ne&&Pe&&e(Ne,Pe);break}case"permission.asked":{if(!("sessionID"in je)||typeof je.sessionID!="string")break;const Ne=je;if(o(Ne),Tr()?.runtime?.isVSCode&&!ie.current&&Te.getState().notifyOnQuestion!==!1){const Le=`permission:${Ne.sessionID}:${Ne.id}`;if(!ae.current.has(Le)){ae.current.add(Le);const st=Re.getState().sessions.find(Ke=>Ke.id===Ne.sessionID)?.title||"Agent is waiting for your approval";we({title:"Permission required",body:st,tag:`permission-${Ne.sessionID}:${Ne.id}`})}}const Qe=`${Ne.sessionID}:${Ne.id}`;J.current.has(Qe)||setTimeout(()=>{const Se=et.current;if(Se===Ne.sessionID)return;const Le=Re.getState().sessions.find(it=>it.id===Ne.sessionID);if(Le?.parentID&&Le.parentID===Se||!Re.getState().permissions.get(Ne.sessionID)?.some(it=>it.id===Ne.id))return;J.current.add(Qe);const Ke=Re.getState().sessions.find(it=>it.id===Ne.sessionID)?.title||"Session";gr(async()=>{const{toast:it}=await import("./vendor-.bun-Byc0cUD3.js").then(pt=>pt.eL);return{toast:it}},__vite__mapDeps([0,1])).then(({toast:it})=>{it.warning("Permission required",{id:Qe,description:Ke,duration:3e4,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),Re.getState().setCurrentSession(Ne.sessionID)}}})})},0);break}case"permission.replied":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=typeof je.requestID=="string"?je.requestID:typeof je.id=="string"?je.id:null;Ne&&Pe&&a(Ne,Pe);break}case"question.asked":{if(!("sessionID"in je)||typeof je.sessionID!="string")break;const Ne=je;if(i(Ne),Tr()?.runtime?.isVSCode&&!ie.current&&Te.getState().notifyOnQuestion!==!1){const Le=`question:${Ne.sessionID}:${Ne.id}`;if(!ae.current.has(Le)){ae.current.add(Le);const st=Array.isArray(Ne.questions)?Ne.questions[0]:void 0,Ke=typeof st?.header=="string"?st.header.trim():"",it=typeof st?.question=="string"?st.question.trim():"";we({title:Ke||"Input needed",body:it||"Agent is waiting for your response",tag:`question-${Ne.sessionID}:${Ne.id}`})}}const Qe=`${Ne.sessionID}:${Ne.id}`;te.current.has(Qe)||setTimeout(()=>{const Se=et.current;if(Se===Ne.sessionID)return;const Le=Re.getState().sessions.find(it=>it.id===Ne.sessionID);if(Le?.parentID&&Le.parentID===Se||!Re.getState().questions.get(Ne.sessionID)?.some(it=>it.id===Ne.id))return;te.current.add(Qe);const Ke=Re.getState().sessions.find(it=>it.id===Ne.sessionID)?.title||"Session";gr(async()=>{const{toast:it}=await import("./vendor-.bun-Byc0cUD3.js").then(pt=>pt.eL);return{toast:it}},__vite__mapDeps([0,1])).then(({toast:it})=>{it.info("Input needed",{id:Qe,description:Ke,duration:3e4,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),Re.getState().setCurrentSession(Ne.sessionID)}}})})},0);break}case"question.replied":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=typeof je.requestID=="string"?je.requestID:null;Ne&&Pe&&l(Ne,Pe);break}case"question.rejected":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=typeof je.requestID=="string"?je.requestID:null;Ne&&Pe&&l(Ne,Pe);break}case"openchamber:notification":{ie.current=!0;const Ne=typeof je.title=="string"?je.title:"",Pe=typeof je.body=="string"?je.body:"",Qe=typeof je.tag=="string"?je.tag:void 0,Se=!!je.requireHidden;if(Ar()&&je.desktopStdoutActive)break;we({title:Ne,body:Pe,tag:Qe,requireHidden:Se});break}case"todo.updated":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=Array.isArray(je.todos)?je.todos:null;Ne&&Pe&&X7(Ne,Pe);break}}},[c,t,e,n,o,a,i,l,x,Ie,r,d,R,I,F,g,y,P,b,be,we]),he=u.useRef(ee);u.useEffect(()=>{he.current=ee},[ee]);const ye=u.useRef(P);u.useEffect(()=>{ye.current=P},[P]);const We=u.useCallback(_e=>{he.current(_e)},[]),Ee=u.useCallback(_e=>ye.current(_e),[]),ze=u.useCallback(()=>{const _e=re();return ue.current=_e,_e==="visible"&&Q.current},[re]),Ze=u.useCallback(()=>{nr()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!B.current,currentSessionId:et.current,effectiveDirectory:b,onlineStatus:Q.current,visibilityState:ue.current,lastEventTimestamp:L.current,reconnectAttempts:U.current})},[b]),Fe=u.useCallback(()=>{if($.current){nr()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if($.current=!0,z.current&&(clearTimeout(z.current),z.current=null),B.current){const _e=B.current;B.current=null;try{_e()}catch(je){console.warn("[useEventStream] Error during unsubscribe:",je)}}$.current=!1},[]),tt=u.useCallback(async _e=>{if(Ze(),!ze()){O.current=!0,Q.current?_("paused","Paused while hidden"):_("offline","Waiting for network");return}_e?.resetAttempts&&(U.current=0),Fe(),L.current=Date.now(),_("connecting",null),nr()&&console.info("[useEventStream] Starting event stream...");const je=Ne=>{console.warn("Event stream error:",Ne)},Ye=()=>{const Ne=O.current;if(U.current=0,O.current=!1,L.current=Date.now(),_("connected",null),x(),va(),N.current(Ne),Ne)Ee("sse_reconnected");else{const Pe=et.current;Pe&&setTimeout(()=>{de.current(Pe,"sse_reconnected",Zo()).then(()=>Ie(Pe)).catch(Qe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Qe)})},0)}};if(nr()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:b,isCleaningUp:$.current}),$.current){nr()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ne=Lt.subscribeToGlobalEvents(Qe=>{const Se=Qe.payload,Le=Qe.payload,st=typeof Le.properties=="object"&&Le.properties!==null?Le.properties:{},Ke=Qe.directory&&Qe.directory!=="global"?{...st,directory:Qe.directory}:st;We({type:typeof Se.type=="string"?Se.type:"",properties:Ke})},je,Ye),Pe=()=>{try{Ne()}catch(Qe){console.warn("[useEventStream] Error during unsubscribe:",Qe)}};$.current?Pe():B.current=Pe}catch(Ne){console.error("[useEventStream] Error during subscription:",Ne),je(Ne)}},[ze,Fe,_,x,Ie,We,Ee,b,Ze]),He=u.useCallback(_e=>{if(!ze()){O.current=!0,Fe(),Q.current?_("paused","Paused while hidden"):_("offline","Waiting for network");return}if(z.current)return;const je=U.current+1;U.current=je;const Ye=_e??`Retrying (${je})`;_("reconnecting",Ye);const Ne=je<=3?Math.min(1e3*Math.pow(2,je-1),8e3):Math.min(2e3*Math.pow(2,je-3),32e3),Pe=Math.floor(Math.random()*250),Qe=Ne+Pe;z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{tt({resetAttempts:!1})},Qe)},[ze,Fe,_,tt]);u.useEffect(()=>{ne.current=He},[He]),u.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=R);const _e=()=>{se.current&&(clearTimeout(se.current),se.current=null)},je=()=>{if(ue.current=re(),ue.current!=="visible")return;if(_e(),Oe("visibility_restore"),va(),Date.now()-L.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),O.current=!0),O.current||!B.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const it=et.current;it&&(H(it,"visibility_restore",Zo()),Ie(it)),N.current(!1),va(),_("connecting","Resuming stream"),tt({resetAttempts:!0})}},Ye=()=>{if(ue.current=re(),ue.current==="visible"&&(_e(),Oe("window_focus"),va(),Date.now()-L.current>45e3&&(O.current=!0),O.current||!B.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const it=et.current;it&&(Ie(it),H(it,"window_focus",Zo())),N.current(!1),va(),_("connecting","Resuming stream"),tt({resetAttempts:!0})}},Ne=()=>{Q.current=!0,Oe("network_restored"),N.current(!1),(O.current||!B.current)&&(va(),_("connecting","Network restored"),tt({resetAttempts:!0}))},Pe=()=>{Q.current=!1,O.current=!0,_("offline","Waiting for network"),Fe()},Qe=()=>{O.current=!0,Fe(),_("paused","Paused while hidden")},Se=Ke=>{if(O.current=O.current||!!Ke.persisted,ue.current=re(),ue.current==="visible"){const it=et.current;it&&(H(it,"page_show",Zo()),Ie(it)),N.current(!1),va(),tt({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",je),typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("offline",Pe),window.addEventListener("focus",Ye),window.addEventListener("pagehide",Qe),window.addEventListener("pageshow",Se));const Le=setTimeout(()=>{tt({resetAttempts:!0})},100);X.current&&clearInterval(X.current),X.current=setInterval(()=>{if(!ze())return;const Ke=Date.now();Array.from(Re.getState().sessionStatus?.values?.()??[]).some(pt=>pt?.type==="busy"||pt?.type==="retry")&&va(),Ke-L.current>45e3&&Promise.resolve().then(async()=>{try{if(!await Lt.checkHealth()){He("Refreshing stalled stream");return}He("Refreshing stalled stream")}catch(pt){console.warn("Health check after stale stream failed:",pt),He("Refreshing stalled stream")}})},1e4);const st=setInterval(()=>{const Ke=Re.getState().sessionStatus;if(!Ke)return;const it=Date.now();Ke.forEach((pt,Ut)=>{if(pt.type!=="busy"&&pt.type!=="retry")return;const ss=me.current.get(Ut)??0,Wt=it-ss>HC,dt=it-ss>6e4;Wt&&dt&&(console.warn("[useEventStream] Session stuck in busy state, forcing idle:",Ut),be(Ut,{type:"idle"},"timeout_recovery"))})},3e4);return()=>{clearTimeout(Le),clearInterval(st),typeof document<"u"&&document.removeEventListener("visibilitychange",je),typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("offline",Pe),window.removeEventListener("focus",Ye),window.removeEventListener("pagehide",Qe),window.removeEventListener("pageshow",Se)),_e(),X.current&&(clearInterval(X.current),X.current=null),wi.clear(),le.current.clear(),ae.current.clear(),ie.current=!1,O.current=!1,ue.current=re(),Q.current=typeof navigator>"u"?!0:navigator.onLine,Fe(),q.current&&(clearTimeout(q.current),q.current=null),_("idle",null)}},[b,R,re,Fe,_,tt,He,m,Ie,ze,p,Oe,T,H,be])},kq=()=>{const t=Re.getState(),e=t.currentSessionId;if(!e)return"";const n=t.sessions.find(r=>r.id===e);return typeof n?.directory=="string"?n.directory:""},Nq=async(t,e=6e3)=>{const n=new AbortController,r=setTimeout(()=>n.abort(),e),o=Date.now();try{const a=await fetch(t,{method:"GET",headers:{Accept:"application/json"},signal:n.signal}),i=Date.now()-o,l=a.headers.get("content-type")||"",c=l.toLowerCase(),d=c.includes("json")&&!c.includes("text/html");let f="";if(d){const m=await a.json().catch(()=>null);if(Array.isArray(m))f=`json[array] len=${m.length}`;else if(m&&typeof m=="object"){const p=Object.keys(m).slice(0,8);f=`json[object] keys=${p.join(",")}${Object.keys(m).length>p.length?",…":""}`}else f=`json[${typeof m}]`}else f=l?`content-type=${l}`:"no content-type";return{ok:a.ok&&d,status:a.status,elapsedMs:i,summary:f}}catch(a){const i=Date.now()-o,c=n.signal.aborted||a instanceof Error&&(a.name==="AbortError"||a.message.toLowerCase().includes("aborted"))?`timeout after ${e}ms`:a instanceof Error?a.message:String(a);return{ok:!1,status:0,elapsedMs:i,summary:`error=${c}`}}finally{clearTimeout(r)}},Cq=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},Aq=t=>{if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.trunc(t);if(typeof t=="string"){const e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return null},Fq=async()=>{const t=new Date,e="1.8.0",n=typeof navigator<"u"?navigator.userAgent:"(no navigator)",r=kq(),o=Te.getState().eventStreamStatus,a=typeof window<"u"?window.location.origin:"",i=a?`${a.replace(/\/+$/,"")}/api/`:"",l=await(async()=>{if(!a)return null;const x=new AbortController,h=setTimeout(()=>x.abort(),5e3);try{const v=await fetch(`${a.replace(/\/+$/,"")}/health`,{method:"GET",headers:{Accept:"application/json"},signal:x.signal});if(!v.ok)return null;const b=await v.json().catch(()=>null);return!b||typeof b!="object"||Array.isArray(b)?null:b}catch{return null}finally{clearTimeout(h)}})(),c=await(async()=>{if(!a)return null;const x=new AbortController,h=setTimeout(()=>x.abort(),7e3);try{const v=await fetch(`${a.replace(/\/+$/,"")}/api/config/opencode-resolution`,{method:"GET",headers:{Accept:"application/json"},signal:x.signal}),b=v.headers.get("content-type")||"(none)";if(!v.ok)return{data:null,status:v.status,error:`http ${v.status} content-type=${b}`};const w=await v.text();let j=null;try{j=JSON.parse(w)}catch{const F=w.replace(/\s+/g," ").slice(0,120);return{data:null,status:v.status,error:`invalid json content-type=${b} body=${F||"(empty)"}`}}return!j||typeof j!="object"||Array.isArray(j)?{data:null,status:v.status,error:`invalid json-shape content-type=${b}`}:{data:j,status:v.status,error:null}}catch(v){return{data:null,status:null,error:v instanceof Error?v.message:String(v)}}finally{clearTimeout(h)}})()||{data:null,error:null},d=(x,h=!0)=>{if(!i)return null;const v=new URL(x.replace(/^\/+/,""),i);return h&&r&&v.searchParams.set("directory",r),v.toString()},f=[{label:"health",path:"/global/health",includeDirectory:!1},{label:"config",path:"/config",includeDirectory:!0},{label:"providers",path:"/config/providers",includeDirectory:!0},{label:"agents",path:"/agent",includeDirectory:!0,timeoutMs:12e3},{label:"commands",path:"/command",includeDirectory:!0,timeoutMs:1e4},{label:"project",path:"/project/current",includeDirectory:!0},{label:"path",path:"/path",includeDirectory:!0},{label:"sessions",path:"/session",includeDirectory:!0,timeoutMs:12e3},{label:"sessionStatus",path:"/session/status",includeDirectory:!0}],m=i?await Promise.all(f.map(async x=>{const h=d(x.path,x.includeDirectory!==!1);if(!h)return{label:x.label,url:"(none)",result:null};const v=await Nq(h,typeof x.timeoutMs=="number"?x.timeoutMs:void 0);return{label:x.label,url:h,result:v}})):[],p=[];p.push(`Time: ${t.toISOString()}`),p.push(`OpenChamber version: ${e}`),p.push(`Runtime: ${a||"(unknown)"} (api=${a?a+"/api":"(unknown)"})`),p.push(`Event stream: ${o}`),p.push(`Directory: ${r||"(none)"}`),p.push(`Platform: ${n}`);const g=Aq(l?.openCodePort);if(p.push(`OpenCode runtime port: ${g??"(unknown)"}`),typeof l?.openCodeRunning=="boolean"&&p.push(`OpenCode runtime running: ${l.openCodeRunning?"yes":"no"}`),typeof l?.openCodeSecureConnection=="boolean"&&p.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?"true":"false"}`),typeof l?.openCodeAuthSource=="string"&&l.openCodeAuthSource.trim()&&p.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<"u"){const x=window.__OPENCHAMBER_MACOS_MAJOR__;typeof x=="number"&&Number.isFinite(x)&&x>0&&p.push(`macOS major: ${x}`)}if(/Mac OS X|Macintosh/.test(n)){p.push(""),p.push("OpenCode CLI resolution:");const x=c.data,h=x&&typeof x.configured=="string"?x.configured:null,v=x&&typeof x.resolved=="string"?x.resolved:l&&typeof l.opencodeBinaryResolved=="string"?l.opencodeBinaryResolved:"",b=x&&typeof x.resolvedDir=="string"?x.resolvedDir:"",w=x&&typeof x.source=="string"?x.source:l&&typeof l.opencodeBinarySource=="string"?l.opencodeBinarySource:"",j=x&&typeof x.shim=="string"?x.shim:l&&typeof l.opencodeShimInterpreter=="string"?l.opencodeShimInterpreter:"",F=x&&typeof x.node=="string"?x.node:l&&typeof l.nodeBinaryResolved=="string"?l.nodeBinaryResolved:"",A=x&&typeof x.bun=="string"?x.bun:l&&typeof l.bunBinaryResolved=="string"?l.bunBinaryResolved:"",C=x&&typeof x.detectedNow=="string"?x.detectedNow:"",S=x&&typeof x.detectedSourceNow=="string"?x.detectedSourceNow:"";if(h!==null&&p.push(`- configured: ${h.trim().length===0?"(cleared)":h}`),v){const N=b||(v.includes("/")?v.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${v}${N?` (dir=${N})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${w||"(n/a)"}`),C&&(p.push(`- detected-now: ${C}`),p.push(`- detected-source: ${S||"(n/a)"}`)),p.push(`- shim: ${j||"(n/a)"}`),p.push(`- node: ${F||"(n/a)"}`),p.push(`- bun: ${A||"(n/a)"}`),!x&&c.error&&p.push(`- resolution-endpoint: ${c.error}`)}if(p.push(""),m.length){p.push("OpenCode API probes:");for(const x of m){if(!x.result){p.push(`- ${x.label}: (no url)`);continue}const{ok:h,status:v,elapsedMs:b,summary:w}=x.result,j=h?"":` url=${x.url}`;p.push(`- ${x.label}: ${h?"ok":"fail"} status=${v} time=${b}ms ${w}${j}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${Cq(Date.now())}`),p.join(`
339
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:st,role:Pe.role,status:Pe.status,textLen:Bt.length,textPreview:Bt.slice(0,120),partsCount:Array.isArray(At)?At.length:0})}catch{}if(R(st,"message_updated",{role:Pe.role}),Pe.role==="user"){const{sessionMemoryState:At}=Os.getState(),It=At.get(Le);if(It){const zt=new Map(At);zt.set(Le,{...It,lastUserMessageAt:Date.now()}),Os.setState({sessionMemoryState:zt})}const Bt=je.parts||Pe.parts,ts=Array.isArray(Bt)?Bt:[],as=Ju(Le,st),ds=(()=>{const zt=Pe.agent;if(typeof zt=="string"&&zt.trim().length>0)return zt.trim();const Mt=Pe.mode;return typeof Mt=="string"&&Mt.trim().length>0?Mt.trim():""})(),Be=(()=>{const Mt=Pe.time?.created;return typeof Mt=="number"?Mt:null})(),ft=ts.length>0&&ts.every(zt=>zt?.synthetic===!0),Qt=(()=>{if(!ds)return!1;if(ft&&(ds==="plan"||ds==="build"))return!0;const zt=Y.current.get(Le);return zt?Be===null?!1:st===zt.messageId?!0:Be>=zt.created:!0})();if(ds&&Qt)try{const zt=rs.getState().agents;if(Array.isArray(zt)&&zt.some(Mt=>Mt?.name===ds)){const Mt=Ss.getState();if(Mt.saveSessionAgentSelection(Le,ds),Y.current.set(Le,{created:Be??Date.now(),messageId:st}),et.current===Le)try{rs.getState().setAgent(ds)}catch{}const cs=Pe.model,Cs=typeof cs?.providerID=="string"?cs.providerID:null,Ns=typeof cs?.modelID=="string"?cs.modelID:null;if(Cs&&Ns){Mt.saveSessionModelSelection(Le,Cs,Ns),Mt.saveAgentModelForSession(Le,ds,Cs,Ns);const $s=typeof Pe.variant=="string"?Pe.variant:void 0;if(Mt.saveAgentModelVariantForSession(Le,ds,Cs,Ns,$s),et.current===Le)try{rs.getState().setProvider(Cs),rs.getState().setModel(Ns)}catch{}}}}catch{}if(ft&&(ds==="plan"||ds==="build")&&et.current===Le){const zt=`${Le}:${st}:${ds}`;oe.current.has(zt)||(oe.current.add(zt),gr(async()=>{const{toast:Mt}=await import("./vendor-.bun-Byc0cUD3.js").then(cs=>cs.eL);return{toast:Mt}},__vite__mapDeps([0,1])).then(({toast:Mt})=>{Mt.info(ds==="plan"?"Plan mode active":"Build mode active",{description:ds==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const Gt={...Ne,userMessageMarker:!0,clientRole:"user",...ds?{mode:ds}:{}};if(n(Le,st,Gt),!as&&ts.length===0){const zt=`${Le}:${st}`;K.current.has(zt)||(K.current.add(zt),Lt.getSessionMessages(Le,50).then(Mt=>{Re.getState().syncMessages(Le,Mt)}).catch(()=>{}))}if(ts.length>0)for(let zt=0;zt<ts.length;zt++){const Mt=ts[zt];if(Mt.synthetic===!0){const Ns=Mt.text,$s=typeof Ns=="string"?Ns.trim():"";if(!($s.startsWith("User has requested to enter plan mode")||$s.startsWith("The plan at ")||$s.startsWith("The following tool was executed by the user")))continue}const Cs={...Mt,type:Mt?.type||"text",sessionID:Mt?.sessionID||Le,messageID:Mt?.messageID||st};t(Le,st,Cs,"user")}R(st,"user_message_created_from_event",{partsCount:ts.length});break}const pt=Ju(Le,st),Ut=q1(pt?.parts||[]),ss=pt?.info?.finish==="stop",Wt=je.parts||Pe.parts,dt=Array.isArray(Wt)?Wt:[],kt=dt.length>0,vt=typeof(Pe.time||{})?.completed=="number",gt=Ne.status,Dt=typeof gt=="string"?gt.toLowerCase():null,Et=Dt==="completed"||Dt==="complete",Pt=Ne.finish,St=typeof Pt=="string"?Pt:null,Ot=St==="stop",qt=St==="error";if(!kt&&!vt&&!Et&&!Ot&&!qt)break;if(Pe.role==="assistant"&&kt){dt.some(ts=>ts?.type==="tool"&&typeof ts.tool=="string"&&ts.tool.toLowerCase()==="question")&&F();const It=q1(dt);if(Ut>0&&It+gq<Ut&&!Ot){R(st,"skipped_shrinking_update",{incomingLen:It,existingLen:Ut});break}}n(Le,st,Ne);const Ge=typeof Ne.role=="string"?Ne.role:null;if(!!Tr()?.runtime?.isVSCode&&!ie.current&&Ge==="assistant"){const At=Te.getState(),It=Re.getState().sessions.find(ts=>ts.id===Le),Bt=typeof It?.title=="string"?It.title.trim():"";if(Ot&&At.notifyOnCompletion!==!1){const ts=!!It?.parentID;if(!(At.notifyOnSubtasks===!1&&ts)){const as=`ready:${Le}:${st}`;le.current.has(as)||(le.current.add(as),we({title:"Agent is ready",body:Bt||"Task completed",tag:`ready-${Le}`}))}}if(qt&&At.notifyOnError!==!1){const ts=`error:${Le}:${st}`;le.current.has(ts)||(le.current.add(ts),we({title:"Tool error",body:Bt||"An error occurred",tag:`error-${Le}`}))}}if(kt&&Pe.role!=="user"){const Bt=(Re.getState().messages.get(Le)||[]).find(ds=>ds.info.id===st),ts=!Bt||Bt.parts.length===0;R(st,ts?"server_parts_injected":"server_parts_refreshed",{count:dt.length});const as=dt;for(let ds=0;ds<as.length;ds++){const Be=as[ds],ft={...Be,type:Be?.type||"text",sessionID:Be?.sessionID||Le,messageID:Be?.messageID||st};t(Le,st,ft,Pe.role),R(st,`server_part_${ds}`)}}const at=Ne.time,bt=at?.completed,wt=typeof bt=="number"&&Number.isFinite(bt),Rt=St==="stop"||ss;if(Ne.role==="assistant"&&(wt||Et||Rt)&&Ne.role==="assistant"){const It=Re.getState().messages.get(Le)||[];let Bt=null,ts="";for(let Gt=0;Gt<It.length;Gt++){const zt=It[Gt];zt.info.role==="assistant"&&zt.info.id>ts&&(ts=zt.info.id,Bt=zt.info.id)}if(c===Le&&st!==Bt)break;const ds=wt?bt:Date.now();wt||n(Le,st,{...Ne,time:{...at??{},completed:ds}}),R(st,"completed",{timeCompleted:ds}),I(st),hq(Le,st,ds),e(Le,st);const Be=Ne.sessionID,ft=typeof Be=="string"&&Be.length>0?Be:Le;Ie(ft,typeof je.directory=="string"?je.directory:null),Ne.summary&&typeof ft=="string"&&r(ft,null)}break}case"session.created":case"session.updated":{const Ne=typeof je.info=="object"&&je.info!==null?je.info:typeof je.sessionInfo=="object"&&je.sessionInfo!==null?je.sessionInfo:typeof je.session=="object"&&je.session!==null?je.session:je,Pe=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof je.sessionID=="string"&&je.sessionID.length>0?je.sessionID:typeof je.id=="string"&&je.id.length>0?je.id:void 0;if(Pe){const Qe=typeof Ne.time=="object"&&Ne.time!==null?Ne.time:typeof je.time=="object"&&je.time!==null?je.time:null,Se=Qe&&typeof Qe.compacting=="number"?Qe.compacting:null;r(Pe,Se);const Le=typeof Ne.directory=="string"?Ne.directory:typeof je.directory=="string"?je.directory:null,st={...Ne,id:Pe,...Le?{directory:Le}:{}};g(st)}break}case"session.deleted":{const Ne=typeof je.sessionID=="string"?je.sessionID:typeof je.id=="string"?je.id:null;Ne&&y(Ne);break}case"session.abort":{const Ne=typeof je.sessionID=="string"&&je.sessionID.length>0?je.sessionID:null,Pe=typeof je.messageID=="string"&&je.messageID.length>0?je.messageID:null;Ne&&be(Ne,{type:"idle"},"sse:session.abort"),Ne&&Pe&&e(Ne,Pe);break}case"permission.asked":{if(!("sessionID"in je)||typeof je.sessionID!="string")break;const Ne=je;if(o(Ne),Tr()?.runtime?.isVSCode&&!ie.current&&Te.getState().notifyOnQuestion!==!1){const Le=`permission:${Ne.sessionID}:${Ne.id}`;if(!ae.current.has(Le)){ae.current.add(Le);const st=Re.getState().sessions.find(Ke=>Ke.id===Ne.sessionID)?.title||"Agent is waiting for your approval";we({title:"Permission required",body:st,tag:`permission-${Ne.sessionID}:${Ne.id}`})}}const Qe=`${Ne.sessionID}:${Ne.id}`;J.current.has(Qe)||setTimeout(()=>{const Se=et.current;if(Se===Ne.sessionID)return;const Le=Re.getState().sessions.find(it=>it.id===Ne.sessionID);if(Le?.parentID&&Le.parentID===Se||!Re.getState().permissions.get(Ne.sessionID)?.some(it=>it.id===Ne.id))return;J.current.add(Qe);const Ke=Re.getState().sessions.find(it=>it.id===Ne.sessionID)?.title||"Session";gr(async()=>{const{toast:it}=await import("./vendor-.bun-Byc0cUD3.js").then(pt=>pt.eL);return{toast:it}},__vite__mapDeps([0,1])).then(({toast:it})=>{it.warning("Permission required",{id:Qe,description:Ke,duration:3e4,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),Re.getState().setCurrentSession(Ne.sessionID)}}})})},0);break}case"permission.replied":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=typeof je.requestID=="string"?je.requestID:typeof je.id=="string"?je.id:null;Ne&&Pe&&a(Ne,Pe);break}case"question.asked":{if(!("sessionID"in je)||typeof je.sessionID!="string")break;const Ne=je;if(i(Ne),Tr()?.runtime?.isVSCode&&!ie.current&&Te.getState().notifyOnQuestion!==!1){const Le=`question:${Ne.sessionID}:${Ne.id}`;if(!ae.current.has(Le)){ae.current.add(Le);const st=Array.isArray(Ne.questions)?Ne.questions[0]:void 0,Ke=typeof st?.header=="string"?st.header.trim():"",it=typeof st?.question=="string"?st.question.trim():"";we({title:Ke||"Input needed",body:it||"Agent is waiting for your response",tag:`question-${Ne.sessionID}:${Ne.id}`})}}const Qe=`${Ne.sessionID}:${Ne.id}`;te.current.has(Qe)||setTimeout(()=>{const Se=et.current;if(Se===Ne.sessionID)return;const Le=Re.getState().sessions.find(it=>it.id===Ne.sessionID);if(Le?.parentID&&Le.parentID===Se||!Re.getState().questions.get(Ne.sessionID)?.some(it=>it.id===Ne.id))return;te.current.add(Qe);const Ke=Re.getState().sessions.find(it=>it.id===Ne.sessionID)?.title||"Session";gr(async()=>{const{toast:it}=await import("./vendor-.bun-Byc0cUD3.js").then(pt=>pt.eL);return{toast:it}},__vite__mapDeps([0,1])).then(({toast:it})=>{it.info("Input needed",{id:Qe,description:Ke,duration:3e4,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),Re.getState().setCurrentSession(Ne.sessionID)}}})})},0);break}case"question.replied":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=typeof je.requestID=="string"?je.requestID:null;Ne&&Pe&&l(Ne,Pe);break}case"question.rejected":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=typeof je.requestID=="string"?je.requestID:null;Ne&&Pe&&l(Ne,Pe);break}case"openchamber:notification":{ie.current=!0;const Ne=typeof je.title=="string"?je.title:"",Pe=typeof je.body=="string"?je.body:"",Qe=typeof je.tag=="string"?je.tag:void 0,Se=!!je.requireHidden;if(Ar()&&je.desktopStdoutActive)break;we({title:Ne,body:Pe,tag:Qe,requireHidden:Se});break}case"todo.updated":{const Ne=typeof je.sessionID=="string"?je.sessionID:null,Pe=Array.isArray(je.todos)?je.todos:null;Ne&&Pe&&X7(Ne,Pe);break}}},[c,t,e,n,o,a,i,l,x,Ie,r,d,R,I,F,g,y,P,b,be,we]),he=u.useRef(ee);u.useEffect(()=>{he.current=ee},[ee]);const ye=u.useRef(P);u.useEffect(()=>{ye.current=P},[P]);const We=u.useCallback(_e=>{he.current(_e)},[]),Ee=u.useCallback(_e=>ye.current(_e),[]),ze=u.useCallback(()=>{const _e=re();return ue.current=_e,_e==="visible"&&Q.current},[re]),Ze=u.useCallback(()=>{nr()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!B.current,currentSessionId:et.current,effectiveDirectory:b,onlineStatus:Q.current,visibilityState:ue.current,lastEventTimestamp:L.current,reconnectAttempts:U.current})},[b]),Fe=u.useCallback(()=>{if($.current){nr()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if($.current=!0,z.current&&(clearTimeout(z.current),z.current=null),B.current){const _e=B.current;B.current=null;try{_e()}catch(je){console.warn("[useEventStream] Error during unsubscribe:",je)}}$.current=!1},[]),tt=u.useCallback(async _e=>{if(Ze(),!ze()){O.current=!0,Q.current?_("paused","Paused while hidden"):_("offline","Waiting for network");return}_e?.resetAttempts&&(U.current=0),Fe(),L.current=Date.now(),_("connecting",null),nr()&&console.info("[useEventStream] Starting event stream...");const je=Ne=>{console.warn("Event stream error:",Ne)},Ye=()=>{const Ne=O.current;if(U.current=0,O.current=!1,L.current=Date.now(),_("connected",null),x(),va(),N.current(Ne),Ne)Ee("sse_reconnected");else{const Pe=et.current;Pe&&setTimeout(()=>{de.current(Pe,"sse_reconnected",Zo()).then(()=>Ie(Pe)).catch(Qe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Qe)})},0)}};if(nr()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:b,isCleaningUp:$.current}),$.current){nr()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ne=Lt.subscribeToGlobalEvents(Qe=>{const Se=Qe.payload,Le=Qe.payload,st=typeof Le.properties=="object"&&Le.properties!==null?Le.properties:{},Ke=Qe.directory&&Qe.directory!=="global"?{...st,directory:Qe.directory}:st;We({type:typeof Se.type=="string"?Se.type:"",properties:Ke})},je,Ye),Pe=()=>{try{Ne()}catch(Qe){console.warn("[useEventStream] Error during unsubscribe:",Qe)}};$.current?Pe():B.current=Pe}catch(Ne){console.error("[useEventStream] Error during subscription:",Ne),je(Ne)}},[ze,Fe,_,x,Ie,We,Ee,b,Ze]),He=u.useCallback(_e=>{if(!ze()){O.current=!0,Fe(),Q.current?_("paused","Paused while hidden"):_("offline","Waiting for network");return}if(z.current)return;const je=U.current+1;U.current=je;const Ye=_e??`Retrying (${je})`;_("reconnecting",Ye);const Ne=je<=3?Math.min(1e3*Math.pow(2,je-1),8e3):Math.min(2e3*Math.pow(2,je-3),32e3),Pe=Math.floor(Math.random()*250),Qe=Ne+Pe;z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{tt({resetAttempts:!1})},Qe)},[ze,Fe,_,tt]);u.useEffect(()=>{ne.current=He},[He]),u.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=R);const _e=()=>{se.current&&(clearTimeout(se.current),se.current=null)},je=()=>{if(ue.current=re(),ue.current!=="visible")return;if(_e(),Oe("visibility_restore"),va(),Date.now()-L.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),O.current=!0),O.current||!B.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const it=et.current;it&&(H(it,"visibility_restore",Zo()),Ie(it)),N.current(!1),va(),_("connecting","Resuming stream"),tt({resetAttempts:!0})}},Ye=()=>{if(ue.current=re(),ue.current==="visible"&&(_e(),Oe("window_focus"),va(),Date.now()-L.current>45e3&&(O.current=!0),O.current||!B.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const it=et.current;it&&(Ie(it),H(it,"window_focus",Zo())),N.current(!1),va(),_("connecting","Resuming stream"),tt({resetAttempts:!0})}},Ne=()=>{Q.current=!0,Oe("network_restored"),N.current(!1),(O.current||!B.current)&&(va(),_("connecting","Network restored"),tt({resetAttempts:!0}))},Pe=()=>{Q.current=!1,O.current=!0,_("offline","Waiting for network"),Fe()},Qe=()=>{O.current=!0,Fe(),_("paused","Paused while hidden")},Se=Ke=>{if(O.current=O.current||!!Ke.persisted,ue.current=re(),ue.current==="visible"){const it=et.current;it&&(H(it,"page_show",Zo()),Ie(it)),N.current(!1),va(),tt({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",je),typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("offline",Pe),window.addEventListener("focus",Ye),window.addEventListener("pagehide",Qe),window.addEventListener("pageshow",Se));const Le=setTimeout(()=>{tt({resetAttempts:!0})},100);X.current&&clearInterval(X.current),X.current=setInterval(()=>{if(!ze())return;const Ke=Date.now();Array.from(Re.getState().sessionStatus?.values?.()??[]).some(pt=>pt?.type==="busy"||pt?.type==="retry")&&va(),Ke-L.current>45e3&&Promise.resolve().then(async()=>{try{if(!await Lt.checkHealth()){He("Refreshing stalled stream");return}He("Refreshing stalled stream")}catch(pt){console.warn("Health check after stale stream failed:",pt),He("Refreshing stalled stream")}})},1e4);const st=setInterval(()=>{const Ke=Re.getState().sessionStatus;if(!Ke)return;const it=Date.now();Ke.forEach((pt,Ut)=>{if(pt.type!=="busy"&&pt.type!=="retry")return;const ss=me.current.get(Ut)??0,Wt=it-ss>HC,dt=it-ss>6e4;Wt&&dt&&(console.warn("[useEventStream] Session stuck in busy state, forcing idle:",Ut),be(Ut,{type:"idle"},"timeout_recovery"))})},3e4);return()=>{clearTimeout(Le),clearInterval(st),typeof document<"u"&&document.removeEventListener("visibilitychange",je),typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("offline",Pe),window.removeEventListener("focus",Ye),window.removeEventListener("pagehide",Qe),window.removeEventListener("pageshow",Se)),_e(),X.current&&(clearInterval(X.current),X.current=null),wi.clear(),le.current.clear(),ae.current.clear(),ie.current=!1,O.current=!1,ue.current=re(),Q.current=typeof navigator>"u"?!0:navigator.onLine,Fe(),q.current&&(clearTimeout(q.current),q.current=null),_("idle",null)}},[b,R,re,Fe,_,tt,He,m,Ie,ze,p,Oe,T,H,be])},kq=()=>{const t=Re.getState(),e=t.currentSessionId;if(!e)return"";const n=t.sessions.find(r=>r.id===e);return typeof n?.directory=="string"?n.directory:""},Nq=async(t,e=6e3)=>{const n=new AbortController,r=setTimeout(()=>n.abort(),e),o=Date.now();try{const a=await fetch(t,{method:"GET",headers:{Accept:"application/json"},signal:n.signal}),i=Date.now()-o,l=a.headers.get("content-type")||"",c=l.toLowerCase(),d=c.includes("json")&&!c.includes("text/html");let f="";if(d){const m=await a.json().catch(()=>null);if(Array.isArray(m))f=`json[array] len=${m.length}`;else if(m&&typeof m=="object"){const p=Object.keys(m).slice(0,8);f=`json[object] keys=${p.join(",")}${Object.keys(m).length>p.length?",…":""}`}else f=`json[${typeof m}]`}else f=l?`content-type=${l}`:"no content-type";return{ok:a.ok&&d,status:a.status,elapsedMs:i,summary:f}}catch(a){const i=Date.now()-o,c=n.signal.aborted||a instanceof Error&&(a.name==="AbortError"||a.message.toLowerCase().includes("aborted"))?`timeout after ${e}ms`:a instanceof Error?a.message:String(a);return{ok:!1,status:0,elapsedMs:i,summary:`error=${c}`}}finally{clearTimeout(r)}},Cq=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},Aq=t=>{if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.trunc(t);if(typeof t=="string"){const e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return null},Fq=async()=>{const t=new Date,e="1.8.1",n=typeof navigator<"u"?navigator.userAgent:"(no navigator)",r=kq(),o=Te.getState().eventStreamStatus,a=typeof window<"u"?window.location.origin:"",i=a?`${a.replace(/\/+$/,"")}/api/`:"",l=await(async()=>{if(!a)return null;const x=new AbortController,h=setTimeout(()=>x.abort(),5e3);try{const v=await fetch(`${a.replace(/\/+$/,"")}/health`,{method:"GET",headers:{Accept:"application/json"},signal:x.signal});if(!v.ok)return null;const b=await v.json().catch(()=>null);return!b||typeof b!="object"||Array.isArray(b)?null:b}catch{return null}finally{clearTimeout(h)}})(),c=await(async()=>{if(!a)return null;const x=new AbortController,h=setTimeout(()=>x.abort(),7e3);try{const v=await fetch(`${a.replace(/\/+$/,"")}/api/config/opencode-resolution`,{method:"GET",headers:{Accept:"application/json"},signal:x.signal}),b=v.headers.get("content-type")||"(none)";if(!v.ok)return{data:null,status:v.status,error:`http ${v.status} content-type=${b}`};const w=await v.text();let j=null;try{j=JSON.parse(w)}catch{const F=w.replace(/\s+/g," ").slice(0,120);return{data:null,status:v.status,error:`invalid json content-type=${b} body=${F||"(empty)"}`}}return!j||typeof j!="object"||Array.isArray(j)?{data:null,status:v.status,error:`invalid json-shape content-type=${b}`}:{data:j,status:v.status,error:null}}catch(v){return{data:null,status:null,error:v instanceof Error?v.message:String(v)}}finally{clearTimeout(h)}})()||{data:null,error:null},d=(x,h=!0)=>{if(!i)return null;const v=new URL(x.replace(/^\/+/,""),i);return h&&r&&v.searchParams.set("directory",r),v.toString()},f=[{label:"health",path:"/global/health",includeDirectory:!1},{label:"config",path:"/config",includeDirectory:!0},{label:"providers",path:"/config/providers",includeDirectory:!0},{label:"agents",path:"/agent",includeDirectory:!0,timeoutMs:12e3},{label:"commands",path:"/command",includeDirectory:!0,timeoutMs:1e4},{label:"project",path:"/project/current",includeDirectory:!0},{label:"path",path:"/path",includeDirectory:!0},{label:"sessions",path:"/session",includeDirectory:!0,timeoutMs:12e3},{label:"sessionStatus",path:"/session/status",includeDirectory:!0}],m=i?await Promise.all(f.map(async x=>{const h=d(x.path,x.includeDirectory!==!1);if(!h)return{label:x.label,url:"(none)",result:null};const v=await Nq(h,typeof x.timeoutMs=="number"?x.timeoutMs:void 0);return{label:x.label,url:h,result:v}})):[],p=[];p.push(`Time: ${t.toISOString()}`),p.push(`OpenChamber version: ${e}`),p.push(`Runtime: ${a||"(unknown)"} (api=${a?a+"/api":"(unknown)"})`),p.push(`Event stream: ${o}`),p.push(`Directory: ${r||"(none)"}`),p.push(`Platform: ${n}`);const g=Aq(l?.openCodePort);if(p.push(`OpenCode runtime port: ${g??"(unknown)"}`),typeof l?.openCodeRunning=="boolean"&&p.push(`OpenCode runtime running: ${l.openCodeRunning?"yes":"no"}`),typeof l?.openCodeSecureConnection=="boolean"&&p.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?"true":"false"}`),typeof l?.openCodeAuthSource=="string"&&l.openCodeAuthSource.trim()&&p.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<"u"){const x=window.__OPENCHAMBER_MACOS_MAJOR__;typeof x=="number"&&Number.isFinite(x)&&x>0&&p.push(`macOS major: ${x}`)}if(/Mac OS X|Macintosh/.test(n)){p.push(""),p.push("OpenCode CLI resolution:");const x=c.data,h=x&&typeof x.configured=="string"?x.configured:null,v=x&&typeof x.resolved=="string"?x.resolved:l&&typeof l.opencodeBinaryResolved=="string"?l.opencodeBinaryResolved:"",b=x&&typeof x.resolvedDir=="string"?x.resolvedDir:"",w=x&&typeof x.source=="string"?x.source:l&&typeof l.opencodeBinarySource=="string"?l.opencodeBinarySource:"",j=x&&typeof x.shim=="string"?x.shim:l&&typeof l.opencodeShimInterpreter=="string"?l.opencodeShimInterpreter:"",F=x&&typeof x.node=="string"?x.node:l&&typeof l.nodeBinaryResolved=="string"?l.nodeBinaryResolved:"",A=x&&typeof x.bun=="string"?x.bun:l&&typeof l.bunBinaryResolved=="string"?l.bunBinaryResolved:"",C=x&&typeof x.detectedNow=="string"?x.detectedNow:"",S=x&&typeof x.detectedSourceNow=="string"?x.detectedSourceNow:"";if(h!==null&&p.push(`- configured: ${h.trim().length===0?"(cleared)":h}`),v){const N=b||(v.includes("/")?v.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${v}${N?` (dir=${N})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${w||"(n/a)"}`),C&&(p.push(`- detected-now: ${C}`),p.push(`- detected-source: ${S||"(n/a)"}`)),p.push(`- shim: ${j||"(n/a)"}`),p.push(`- node: ${F||"(n/a)"}`),p.push(`- bun: ${A||"(n/a)"}`),!x&&c.error&&p.push(`- resolution-endpoint: ${c.error}`)}if(p.push(""),m.length){p.push("OpenCode API probes:");for(const x of m){if(!x.result){p.push(`- ${x.label}: (no url)`);continue}const{ok:h,status:v,elapsedMs:b,summary:w}=x.result,j=h?"":` url=${x.url}`;p.push(`- ${x.label}: ${h?"ok":"fail"} status=${v} time=${b}ms ${w}${j}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${Cq(Date.now())}`),p.join(`
340
340
  `)},bS=async()=>{const t=await Fq(),e=Te.getState();e.setOpenCodeStatusText(t),e.setOpenCodeStatusDialogOpen(!0)},Dq=()=>{const t=Me.c(33),{openNewSessionDraft:e,abortCurrentOperation:n,armAbortPrompt:r,clearAbortPrompt:o,currentSessionId:a}=Re(),{toggleCommandPalette:i,toggleHelpDialog:l,toggleSidebar:c,toggleNavRail:d,toggleRightSidebar:f,setRightSidebarOpen:m,setRightSidebarTab:p,toggleBottomTerminal:g,setBottomTerminalExpanded:y,isMobile:x,setSessionSwitcherOpen:h,setActiveMainTab:v,setSettingsDialogOpen:b,setModelSelectorOpen:w,toggleExpandedInput:j,shortcutOverrides:F}=Te(),{themeMode:A,setThemeMode:C}=mo(),{working:S}=z2(),N=u.useRef(null),k=u.useRef(null),D=u.useRef(A);let M,E;t[0]!==A?(M=()=>{D.current=A},E=[A],t[0]=A,t[1]=M,t[2]=E):(M=t[1],E=t[2]),u.useEffect(M,E);let _;t[3]!==o?(_=()=>{k.current&&(clearTimeout(k.current),k.current=null),N.current=null,o()},t[3]=o,t[4]=_):_=t[4];const T=_;let P,H;t[5]!==n||t[6]!==r||t[7]!==a||t[8]!==x||t[9]!==e||t[10]!==T||t[11]!==v||t[12]!==y||t[13]!==w||t[14]!==m||t[15]!==p||t[16]!==h||t[17]!==b||t[18]!==C||t[19]!==F||t[20]!==g||t[21]!==i||t[22]!==j||t[23]!==l||t[24]!==d||t[25]!==f||t[26]!==c||t[27]!==S?(P=()=>{const B=U=>la(U,F),z=U=>{if(sr(U,B("open_command_palette"))){U.preventDefault(),i();return}if(sr(U,B("open_status"))){U.preventDefault(),bS();return}if(sr(U,B("open_help"))){U.preventDefault(),l();return}if(sr(U,B("new_chat"))||sr(U,B("new_chat_worktree"))){U.preventDefault();const K=ln(),V=rs.getState().settingsAutoCreateWorktree,q=sr(U,B("new_chat"));if(K?!1:q?V:!V){v("chat"),h(!1),Tm();return}v("chat"),h(!1),e();return}if(sr(U,B("cycle_theme"))){U.preventDefault();const K=["light","dark","system"],V=document.activeElement,$=(K.indexOf(D.current)+1)%K.length;C(K[$]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),V&&document.contains(V)&&V.focus({preventScroll:!0}))});return}if(sr(U,B("open_timeline"))){U.preventDefault();const{isTimelineDialogOpen:K,setTimelineDialogOpen:V}=Te.getState();V(!K);return}if(sr(U,B("open_settings"))){U.preventDefault();const{isSettingsDialogOpen:K}=Te.getState();b(!K);return}if(sr(U,B("toggle_sidebar"))){U.preventDefault();const{isMobile:K,isSessionSwitcherOpen:V}=Te.getState();K?h(!V):c();return}if(sr(U,B("toggle_nav_rail"))){U.preventDefault(),d();return}if(sr(U,B("focus_input"))){U.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(sr(U,B("toggle_right_sidebar"))){const{isMobile:K}=Te.getState();if(K)return;U.preventDefault(),f();return}if(sr(U,B("open_right_sidebar_git"))){const{isMobile:K}=Te.getState();if(K)return;U.preventDefault(),m(!0),p("git");return}if(sr(U,B("open_right_sidebar_files"))){const{isMobile:K}=Te.getState();if(K)return;U.preventDefault(),m(!0),p("files");return}if(sr(U,B("cycle_right_sidebar_tab"))){const{isMobile:K,rightSidebarTab:V}=Te.getState();if(K)return;const q=["git","files"],$=q.indexOf(V),G=q[($+1)%q.length];U.preventDefault(),m(!0),p(G);return}if(sr(U,B("toggle_terminal"))){const{isMobile:K}=Te.getState();if(K)return;U.preventDefault(),g();return}if(sr(U,B("toggle_terminal_expanded"))){const{isMobile:K,isBottomTerminalExpanded:V}=Te.getState();if(K)return;U.preventDefault(),y(!V);return}if(sr(U,B("open_model_selector"))){const{isSettingsDialogOpen:K,isCommandPaletteOpen:V,isHelpDialogOpen:q,isSessionSwitcherOpen:$,isAboutDialogOpen:G,activeMainTab:W,isModelSelectorOpen:J}=Te.getState();if(K||V||q||$||G||!(W==="chat"))return;U.preventDefault(),w(!J);return}if(sr(U,B("cycle_thinking_variant"))){const{isSettingsDialogOpen:K,isCommandPaletteOpen:V,isHelpDialogOpen:q,isSessionSwitcherOpen:$,isAboutDialogOpen:G,activeMainTab:W}=Te.getState();if(K||V||q||$||G||!(W==="chat"))return;const le=rs.getState();if(le.getCurrentModelVariants().length===0)return;U.preventDefault(),le.cycleCurrentVariant();const ie=rs.getState().currentVariant,oe=Re.getState(),Y=oe.currentSessionId,re=rs.getState().currentAgentName,ue=rs.getState().currentProviderId,Q=rs.getState().currentModelId;Y&&re&&ue&&Q&&oe.saveAgentModelVariantForSession(Y,re,ue,Q,ie);return}if(sr(U,B("expand_input"))){if(x)return;U.preventDefault(),j();return}if(U.key==="Escape"){const V=!!U.target?.closest('[role="dialog"]'),q=!!document.querySelector('[data-settings-view="true"]');if(V||q){T();return}const{isSettingsDialogOpen:$,isCommandPaletteOpen:G,isHelpDialogOpen:W,isSessionSwitcherOpen:J,isAboutDialogOpen:te,isMultiRunLauncherOpen:le,isImagePreviewOpen:ae,activeMainTab:ie}=Te.getState();if($){U.preventDefault(),b(!1),T();return}if(G||W||J||te||le||ae||!(ie==="chat")){T();return}const re=a;if(!(S.canAbort&&!!re)){T();return}const Q=Date.now(),O=N.current;if(O&&Q<O){U.preventDefault(),T(),n();return}U.preventDefault();const se=r(3e3)??Q+3e3;N.current=se,k.current&&clearTimeout(k.current);const X=Math.max(se-Q,0);k.current=setTimeout(()=>{N.current&&Date.now()>=N.current&&T()},X||0);return}};return window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",z)}},H=[e,n,i,l,c,d,f,m,p,g,y,x,h,v,b,w,j,C,S,r,T,a,F],t[5]=n,t[6]=r,t[7]=a,t[8]=x,t[9]=e,t[10]=T,t[11]=v,t[12]=y,t[13]=w,t[14]=m,t[15]=p,t[16]=h,t[17]=b,t[18]=C,t[19]=F,t[20]=g,t[21]=i,t[22]=j,t[23]=l,t[24]=d,t[25]=f,t[26]=c,t[27]=S,t[28]=P,t[29]=H):(P=t[28],H=t[29]),u.useEffect(P,H);let R,I;t[30]!==T?(R=()=>()=>{T()},I=[T],t[30]=T,t[31]=R,t[32]=I):(R=t[31],I=t[32]),u.useEffect(R,I)},Q1="openchamber:menu-action",Mq="openchamber:check-for-updates",Eq=t=>{const{openNewSessionDraft:e}=Re(),{toggleCommandPalette:n,toggleHelpDialog:r,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:i,setSettingsDialogOpen:l,setAboutDialogOpen:c}=Te(),{addProject:d}=bs(),{requestAccess:f,startAccessing:m}=Rm(),{setThemeMode:p}=mo(),g=u.useCallback(()=>{tn()&&f("").then(async x=>{if(!x.success||!x.path){x.error&&x.error!=="Directory selection cancelled"&&ce.error("Failed to select directory",{description:x.error});return}const h=await m(x.path);if(!h.success){ce.error("Failed to open directory",{description:h.error||"Desktop could not grant file access."});return}d(x.path,{id:x.projectId})||ce.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(x=>{console.error("Desktop: Error selecting directory:",x),ce.error("Failed to select directory")}),ma.requestDirectoryDialog()},[d,f,m]),y=u.useCallback(x=>{switch(x){case"about":c(!0);break;case"settings":l(!0);break;case"command-palette":n();break;case"new-session":i("chat"),a(!1),e();break;case"new-worktree-session":i("chat"),a(!1),Tm();break;case"change-workspace":g();break;case"open-git-tab":{const{activeMainTab:h}=Te.getState();i(h==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:h}=Te.getState();i(h==="diff"?"chat":"diff");break}case"open-files-tab":{const{activeMainTab:h}=Te.getState();i(h==="files"?"chat":"files");break}case"open-terminal-tab":{const{activeMainTab:h}=Te.getState();i(h==="terminal"?"chat":"terminal");break}case"copy":{const h=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(h)||document.execCommand("copy");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":t?.();break;case"help-dialog":r();break;case"download-logs":{bS().catch(()=>{ce.error("Failed to collect OpenCode status")});break}}},[g,t,e,c,i,a,l,p,n,r,o]);u.useEffect(()=>{const x=h=>{const v=h.detail;v&&y(v)};return window.addEventListener(Q1,x),()=>window.removeEventListener(Q1,x)},[y]),u.useEffect(()=>{if(typeof window>"u")return;const h=window.__TAURI__?.event?.listen;if(typeof h!="function")return;let v=null,b=null;return h("openchamber:menu-action",w=>{const j=w?.payload;typeof j=="string"&&y(j)}).then(w=>{v=w}).catch(()=>{}),h("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Mq))}).then(w=>{b=w}).catch(()=>{}),()=>{(async()=>{try{const j=v?.();j instanceof Promise&&await j}catch{}try{const j=b?.();j instanceof Promise&&await j}catch{}})()}},[y])},Iq=()=>{u.useEffect(()=>{let t=!1;return(async()=>{try{const n=await Lt.getGlobalSessionStatus();if(t||!n)return;const r=new Map;Object.entries(n).forEach(([o,a])=>{if(!o||!a)return;const i=a;r.set(o,i)}),r.size>0&&Re.setState({sessionStatus:r})}catch{}})(),()=>{t=!0}},[])},_q=2e3,Pq=t=>{const e=Re.getState().sessionAbortFlags.get(t);return e?Date.now()-e.timestamp<_q:!1},Y1=(t,e)=>{Re.setState(n=>{const r=new Map(n.sessionStatus??new Map);return r.set(t,{type:e}),{sessionStatus:r}})},Tq=t=>{const e=rs.getState().getVisibleAgents();let n="",r=[],o;const a=[];for(let i=0;i<t.length;i+=1){const l=t[i],{sanitizedText:c,mention:d}=Yh(l.content,e);!o&&d?.name&&(o=d.name),i===0?(n=c,r=l.attachments??[]):a.push({text:c,attachments:l.attachments})}return{primaryText:n,primaryAttachments:r,agentMentionName:o,additionalParts:a.length>0?a:void 0}},Rq=t=>{const e=Ss.getState(),n=rs.getState(),r=Os.getState(),o=e.getSessionAgentSelection(t)??e.getCurrentAgent(t)??n.currentAgentName??void 0,a=e.getSessionModelSelection(t),i=o?e.getAgentModelForSession(t,o):null,l=i?.providerId??a?.providerId??n.currentProviderId??r.lastUsedProvider?.providerID,c=i?.modelId??a?.modelId??n.currentModelId??r.lastUsedProvider?.modelID,d=o&&l&&c?e.getAgentModelVariantForSession(t,o,l,c):void 0;return{providerID:l,modelID:c,agent:o,variant:d}};function Bq(){const t=ko(o=>o.queuedMessages),e=Re(o=>o.sessionStatus),n=u.useRef(new Set),r=u.useRef(new Map);u.useEffect(()=>{const o=async(c,d)=>{if(d.length===0||n.current.has(c)||Pq(c)||(Re.getState().sessionStatus?.get(c)?.type??"idle")!=="idle")return;const m=Tq(d);if(!m.primaryText&&!m.additionalParts?.length)return;const p=Rq(c);if(!(!p.providerID||!p.modelID)){n.current.add(c),Y1(c,"busy");try{await Os.getState().sendMessage(m.primaryText,p.providerID,p.modelID,p.agent,c,m.primaryAttachments,m.agentMentionName,m.additionalParts,p.variant,"normal");const g=ko.getState().removeFromQueue;d.forEach(y=>{g(c,y.id)})}catch(g){Y1(c,"idle"),console.warn("[queue] queued auto-send failed:",g)}finally{n.current.delete(c)}}},a=new Map(r.current);(e?Array.from(e.entries()):[]).forEach(([c,d])=>{a.set(c,d.type)}),Object.entries(t).forEach(([c,d])=>{const f=e?.get(c)?.type??"idle",m=r.current.get(c),p=(m==="busy"||m==="retry")&&f==="idle",g=m===void 0&&f==="idle";d.length>0&&(p||g)&&o(c,d),a.set(c,f)}),r.current=a},[t,e])}const Oq=["chat","git","diff","terminal","files"],$q=["settings","agents","commands","skills","providers","usage","git-identities"],Co={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function J1(t){const e=Lq();return{sessionId:zq(e),tab:Hq(e),settingsPath:Uq(e),diffFile:Vq(e)}}function Lq(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function zq(t){const e=t.get(Co.SESSION);return!e||e.trim().length===0?null:e.trim()}function Hq(t){const e=t.get(Co.TAB);if(!e)return null;const n=e.toLowerCase().trim();return Oq.includes(n)?n:null}function Uq(t){const e=t.get(Co.SETTINGS);if(!e)return null;const n=e.toLowerCase().trim();return n.length===0?null:n==="openchamber"||n==="general"||n==="preferences"?"home":($q.includes(n),n)}function Vq(t){const e=t.get(Co.FILE);if(!e||e.trim().length===0)return null;try{return decodeURIComponent(e.trim())}catch{return e.trim()}}function X1(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Co.SESSION)||t.has(Co.TAB)||t.has(Co.SETTINGS)||t.has(Co.FILE)}catch{return!1}}const Wq="chat";function vS(t){const e=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&e.set(Co.SESSION,t.sessionId),t.isSettingsOpen){const n=t.settingsPath.trim().length>0?t.settingsPath:"home";return e.set(Co.SETTINGS,n),e}return t.tab!==Wq&&e.set(Co.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&e.set(Co.FILE,t.diffFile),e}function Gq(t,e){const n=typeof window<"u"?window.location.pathname:"/",r=t.toString();return r?`${n}?${r}`:n}function qq(t){if(typeof window>"u")return!0;try{const e=new URLSearchParams(window.location.search),n=vS(t),r=[...e.entries()].sort((a,i)=>a[0].localeCompare(i[0])),o=[...n.entries()].sort((a,i)=>a[0].localeCompare(i[0]));if(r.length!==o.length)return!1;for(let a=0;a<r.length;a++)if(r[a][0]!==o[a][0]||r[a][1]!==o[a][1])return!1;return!0}catch{return!0}}function Kq(t,e={}){if(!(typeof window>"u")&&!Qq()&&!(!e.force&&qq(t)))try{const n=vS(t),r=Gq(n);e.replace?window.history.replaceState({...window.history.state,route:t},"",r):window.history.pushState({route:t},"",r)}catch{}}function Qq(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function Yq(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function Jq(){const t=u.useMemo(()=>Yq(),[]),e=u.useRef(!1),n=u.useRef(!1),r=Re(m=>m.setCurrentSession),o=Te(m=>m.setActiveMainTab),a=Te(m=>m.setSettingsDialogOpen),i=Te(m=>m.setSettingsPage),l=Te(m=>m.navigateToDiff),c=u.useCallback(async m=>{if(!n.current){n.current=!0;try{if(m.sessionId){const p=Re.getState().currentSessionId;m.sessionId!==p&&await r(m.sessionId)}if(m.settingsPath){i(nS(m.settingsPath)),a(!0);return}Te.getState().isSettingsDialogOpen&&a(!1),m.tab&&o(m.tab),m.diffFile&&(m.tab==="diff"||!m.tab)&&l(m.diffFile)}finally{n.current=!1}}},[r,o,a,i,l]),d=u.useCallback(()=>{const m=Re.getState(),p=Te.getState();return{sessionId:m.currentSessionId,tab:p.activeMainTab,isSettingsOpen:p.isSettingsDialogOpen,settingsPath:p.settingsPage,diffFile:p.pendingDiffFile}},[]),f=u.useCallback((m={})=>{if(t||n.current)return;const p=d();Kq(p,m)},[t,d]);u.useEffect(()=>{if(e.current||(e.current=!0,!X1()))return;const m=J1();(async()=>(await c(m),t||f({replace:!0})))()},[c,t,f]),u.useEffect(()=>{if(t)return;let m=Re.getState().currentSessionId;return Re.subscribe(g=>{const y=g.currentSessionId;y===m||n.current||(m=y,f())})},[t,f]),u.useEffect(()=>{if(t)return;let m=Te.getState().activeMainTab,p=Te.getState().isSettingsDialogOpen,g=Te.getState().settingsPage,y=Te.getState().pendingDiffFile;return Te.subscribe(h=>{if(n.current)return;const v=h.activeMainTab!==m,b=h.isSettingsDialogOpen!==p,w=h.settingsPage!==g,j=h.pendingDiffFile!==y&&h.activeMainTab==="diff";m=h.activeMainTab,p=h.isSettingsDialogOpen,g=h.settingsPage,y=h.pendingDiffFile,(v||b||w||j)&&f()})},[t,f]),u.useEffect(()=>{if(typeof window>"u"||t)return;const m=()=>{const p=J1();if(X1())c(p);else{const g=Te.getState();g.isSettingsDialogOpen&&a(!1),g.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[c,t,o,a])}const Xq=1e4,wS=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},jS=t=>{if(!zi())return;const e=Tr();e?.push?.setVisibility&&e.push.setVisibility({visible:t})},Zq=()=>{const t=Me.c(1);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=[],t[0]=e):e=t[0],u.useEffect(sK,e)};function eK(){jS(wS()==="visible")}function tK(){wS()==="visible"&&jS(!0)}function sK(){if(!zi()||typeof document>"u")return;const t=eK,e=tK;t();const n=window.setInterval(e,Xq);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),window.addEventListener("blur",t),()=>{window.clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t),window.removeEventListener("blur",t)}}const nK="OpenChamber",Z1=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),rK=t=>{const n=t.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},oK=(t,e)=>[t,e,nK].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),aK=()=>{const t=bs(a=>a.activeProjectId?a.projects.find(i=>i.id===a.activeProjectId)??null:null),e=u.useMemo(()=>{if(!t)return null;const a=t.label?.trim();if(a)return Z1(a);const i=rK(t.path);return i?Z1(i):null},[t]),[n,r]=u.useState(null);u.useEffect(()=>{if(typeof window>"u"||!fr()){r(null);return}let a=!1;const i=async()=>{try{const c=window.location.href,d=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin;if(ic(c,d)){a||r(null);return}const m=(await Xg()).hosts.find(g=>ic(c,g.url)),p=m?.label?.trim()?zr(m.label.trim()):"Instance";a||r(p)}catch{a||r("Instance")}};i();const l=()=>{i()};return window.addEventListener("focus",l),()=>{a=!0,window.removeEventListener("focus",l)}},[]);const o=u.useMemo(()=>oK(e,n),[e,n]);u.useEffect(()=>{if(typeof document<"u"&&(document.title=o),!tn())return;let a=!1;return(async()=>{try{const{getCurrentWindow:l}=await gr(async()=>{const{getCurrentWindow:d}=await import("./vendor-.bun-Byc0cUD3.js").then(f=>f.eN);return{getCurrentWindow:d}},__vite__mapDeps([0,1]));if(a)return;await l().setTitle(o)}catch{return}})(),()=>{a=!0}},[o])};function iK(){const t=Me.c(16),{git:e}=Vr(),n=Rs(lK),{currentSessionId:r,sessions:o,worktreeMetadata:a}=Re(),{setActiveDirectory:i,startPolling:l,stopPolling:c,fetchAll:d}=Nr();let f;t[0]!==r||t[1]!==a?(f=r?a.get(r)??void 0:void 0,t[0]=r,t[1]=a,t[2]=f):f=t[2];const m=f;let p;if(t[3]!==r||t[4]!==o){let b;t[6]!==r?(b=w=>w.id===r,t[6]=r,t[7]=b):b=t[7],p=o.find(b),t[3]=r,t[4]=o,t[5]=p}else p=t[5];const y=p?.directory??null,x=m?.path??y??n??null;let h,v;t[8]!==x||t[9]!==d||t[10]!==e||t[11]!==i||t[12]!==l||t[13]!==c?(h=()=>{if(!x||!e){c();return}return i(x),d(x,e,{silentIfCached:!0}),l(e),()=>{c()}},v=[x,e,i,l,c,d],t[8]=x,t[9]=d,t[10]=e,t[11]=i,t[12]=l,t[13]=c,t[14]=h,t[15]=v):(h=t[14],v=t[15]),u.useEffect(h,v)}function lK(t){return t.currentDirectory}function cK(t){const e=Me.c(2),{children:n}=t;iK();let r;return e[0]!==n?(r=s.jsx(s.Fragment,{children:n}),e[0]=n,e[1]=r):r=e[1],r}const dK="curl -fsSL https://opencode.ai/install | bash",uK=3e3;function fK(t){const e=Me.c(4),{onCopy:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsxs("code",{children:[s.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),s.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),s.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),s.jsx("span",{className:"text-muted-foreground",children:" | "}),s.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e[0]=r):r=e[0];let o;e[1]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(ir,{className:"h-4 w-4"}),e[1]=o):o=e[1];let a;return e[2]!==n?(a=s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[r,s.jsx("button",{onClick:n,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:o})]}),e[2]=n,e[3]=a):a=e[3],a}const mK=3e4;function pK({onCliAvailable:t}){const[e,n]=u.useState(!1),[r,o]=u.useState(!1),[a,i]=u.useState(!1),[l,c]=u.useState(!1),[d,f]=u.useState("");u.useEffect(()=>{const v=setTimeout(()=>o(!0),mK);return()=>clearTimeout(v)},[]),u.useEffect(()=>{i(fr())},[]),u.useEffect(()=>{let v=!1;return(async()=>{try{const b=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!b.ok)return;const w=await b.json().catch(()=>null);if(!w||v)return;const j=typeof w.opencodeBinary=="string"?w.opencodeBinary.trim():"";j&&f(j)}catch{}})(),()=>{v=!0}},[]);const m=u.useCallback(async v=>{if(!v.target.closest("button, a, input, select, textarea, code")&&v.button===0&&a&&tn())try{const{getCurrentWindow:b}=await gr(async()=>{const{getCurrentWindow:j}=await import("./vendor-.bun-Byc0cUD3.js").then(F=>F.eN);return{getCurrentWindow:j}},__vite__mapDeps([0,1]));await b().startDragging()}catch(b){console.error("Failed to start window dragging:",b)}},[a]),p=u.useCallback(async()=>{try{const v=await fetch("/health");if(!v.ok)return!1;const b=await v.json();return b.openCodeRunning===!0||b.isOpenCodeReady===!0}catch{return!1}},[]),g=u.useCallback(async()=>{c(!0);try{await fetch("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>c(!1),1e3)}},[]),y=u.useCallback(async()=>{if(typeof window>"u"||!a||!tn())return;const v=window.__TAURI__;if(v?.dialog?.open)try{const b=await v.dialog.open({title:"Select opencode binary",multiple:!1,directory:!1});typeof b=="string"&&b.trim().length>0&&f(b.trim())}catch{}},[a]),x=u.useCallback(async()=>{c(!0);try{await on({opencodeBinary:d.trim()}),await fetch("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>c(!1),1e3)}},[d]),h=u.useCallback(async()=>{const v=await Cn(dK);v.ok?(n(!0),setTimeout(()=>n(!1),2e3)):console.error("Failed to copy:",v.error)},[]);return u.useEffect(()=>{const v=async()=>{await p()&&t?.()},b=setInterval(v,uK);return v(),()=>clearInterval(b)},[p,t]),s.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:m,children:[s.jsxs("div",{className:"w-full space-y-4 text-center",children:[s.jsxs("div",{className:"space-y-4",children:[s.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),s.jsxs("p",{className:"text-muted-foreground",children:[s.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",s.jsx(so,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),s.jsx("div",{className:"flex justify-center",children:s.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:e?s.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[s.jsx(Ts,{className:"h-4 w-4"}),"Copied to clipboard"]}):s.jsx(fK,{onCopy:h})})}),s.jsxs("a",{href:"https://opencode.ai/docs",target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 justify-center",children:["View documentation",s.jsx(so,{className:"h-3 w-3"})]}),s.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."}),s.jsx("div",{className:"flex justify-center",children:s.jsx("button",{type:"button",onClick:g,disabled:l,className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:l?"Retrying…":"Retry"})}),s.jsx("div",{className:"mx-auto w-full max-w-xl pt-4",children:s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-sm text-muted-foreground",children:"Already installed? Set the OpenCode CLI path:"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(fs,{value:d,onChange:v=>f(v.target.value),placeholder:"/Users/you/.bun/bin/opencode",disabled:l,className:"flex-1 font-mono text-xs"}),s.jsx(ot,{type:"button",variant:"secondary",onClick:y,disabled:l||!a||!tn(),children:"Browse"}),s.jsx(ot,{type:"button",onClick:x,disabled:l,children:"Apply"})]}),s.jsxs("div",{className:"text-xs text-muted-foreground/70",children:["Saves to ",s.jsx("code",{className:"text-foreground/70",children:"~/.config/openchamber/settings.json"})," and reloads OpenCode configuration."]})]})})]}),r&&s.jsxs("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:[s.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["Already installed? Make sure ",s.jsx("code",{className:"text-foreground/70",children:"opencode"})," is in your PATH"]}),s.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["or set ",s.jsx("code",{className:"text-foreground/70",children:"OPENCODE_BINARY"})," environment variable."]}),s.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["If you see ",s.jsx("code",{className:"text-foreground/70",children:"env: node: No such file or directory"})," or ",s.jsx("code",{className:"text-foreground/70",children:"env: bun: No such file or directory"}),", install that runtime or ensure it is on PATH."]})]})]})}const hK=()=>{const t=Me.c(5),[e,n]=u.useState(gK),{isUpdating:r,message:o}=e;let a,i;if(t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>SN(n),i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),u.useEffect(a,i),!r)return null;let l;t[2]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(ix,{width:80,height:80,isAnimated:!0}),t[2]=l):l=t[2];let c;return t[3]!==o?(c=s.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[l,s.jsx("p",{className:"typography-body text-muted-foreground",children:o})]}),t[3]=o,t[4]=c):c=t[4],c};function gK(){return kN()}const pg={getLastAssistantMessage(){const t=Re.getState(),e=t.currentSessionId;if(!e)return console.log("[ERROR] No active session"),null;const n=t.messages.get(e);if(!n||n.length===0)return console.log("[ERROR] No messages in current session"),null;for(let r=n.length-1;r>=0;r--){const o=n[r];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const g={id:p.id,type:p.type};return p.type==="text"?(g.text=p.text,g.textLength=p.text?.length||0):p.type==="tool"?(g.tool=p.tool,g.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(g.isStepMarker=!0),g}),i=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),c=a.some(p=>p.type==="step-start"||p.type==="step-finish"),d=a.length===0,f=!i&&!l&&(!d||c),m={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:d,isEmptyResponse:f,raw:o};return console.log("[INSPECT] Last Assistant Message:",m),console.log("[SUMMARY] Summary:",{messageId:m.messageId,partsCount:m.partsCount,isEmpty:m.isEmpty,isEmptyResponse:m.isEmptyResponse,hasText:i,hasTools:l,hasStepMarkers:c,onlyStepMarkers:c&&!i&&!l}),m.isEmpty&&console.warn("[WARNING] Message has NO parts!"),m.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),c&&!i&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),m}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(t,e=80){return!t||typeof t!="string"||t.length<=e?t:t.substring(0,e)+"…"},truncateMessages(t){return t.map(e=>({...e,parts:(e.parts||[]).map(n=>{const r={...n};return"text"in n&&(r.text=this.truncateString(n.text)),"textPreview"in n&&(r.textPreview=this.truncateString(n.textPreview)),n.state&&(r.state={...n.state},"output"in n.state&&(r.state.output=this.truncateString(n.state.output)),"error"in n.state&&(r.state.error=this.truncateString(n.state.error)),n.state.metadata&&"preview"in n.state.metadata&&(r.state.metadata={...n.state.metadata,preview:this.truncateString(n.state.metadata.preview)})),r})}))},getAllMessages(t=!1){const e=Re.getState(),n=e.currentSessionId;if(!n)return console.log("[ERROR] No active session"),[];const r=e.messages.get(n)||[];return console.log(`[MESSAGES] Total messages in session: ${r.length}`),r.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),t?this.truncateMessages(r):r},async getAppStatus(){const t=Rs.getState(),e=Re.getState(),n=bs.getState(),r=t.currentDirectory||null,o=Lt.getDirectory()??null,a=e.sessions||[],i=new Set,l={};a.forEach(C=>{const S=C.directory;typeof S=="string"&&S.trim().length>0?(i.add(S),l[S]=(l[S]??0)+1):l["(none)"]=(l["(none)"]??0)+1});const c=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(C){return{available:!1,error:C instanceof Error?C.message:String(C)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,f=typeof window<"u"&&!!window.__TAURI__,m=async C=>{try{return await C.json()}catch{return null}},p=async C=>{try{return await C.text()}catch{return null}},g=async C=>{try{const S=await fetch(C);return S.ok?await m(S):{status:S.status}}catch(S){return{error:S instanceof Error?S.message:String(S)}}};let y=null,x=null,h=null,v=null;const b=r?`/api/path?directory=${encodeURIComponent(r)}`:"/api/path";y=await g(b);const w=r?`/api/project/current?directory=${encodeURIComponent(r)}`:"/api/project/current";x=await g(w),h=await g("/api/config/settings");try{const C=await fetch("/api/health"),S=C.headers.get("content-type")||"",N=await p(C),k=S.toLowerCase().includes("application/json");let D=null;if(k&&N)try{const M=JSON.parse(N);M&&typeof M=="object"&&!Array.isArray(M)&&(D=M)}catch{D=null}v={status:C.status,ok:C.ok,contentType:S,type:k?"json":"html",openCodePort:D?.openCodePort??null,openCodeRunning:D?.openCodeRunning??null,openCodeSecureConnection:D?.openCodeSecureConnection??null,openCodeAuthSource:D?.openCodeAuthSource??null,isOpenCodeReady:D?.isOpenCodeReady??null,lastOpenCodeError:D?.lastOpenCodeError??null,preview:N?N.slice(0,120):null}}catch(C){v={error:C instanceof Error?C.message:String(C)}}let j={isGitRepo:null};if(r)try{j.isGitRepo=await Da(r)}catch(C){j={isGitRepo:null,error:C instanceof Error?C.message:String(C)}}const F=n.projects.map(C=>({id:C.id,path:C.path,label:C.label})),A={runtime:{platform:d?.runtime?.platform??null,isDesktop:f,isVSCode:!!d?.runtime?.isVSCode,hasRuntimeApis:!!d,desktopServerOrigin:null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:r,opencodeDirectory:y?.directory||y?.worktree||o,homeDirectory:t.homeDirectory||null,isHomeReady:t.isHomeReady,hasPersistedDirectory:t.hasPersistedDirectory,isSwitchingDirectory:t.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:F},sessions:{total:a.length,currentSessionId:e.currentSessionId,lastLoadedDirectory:e.lastLoadedDirectory,uniqueDirectories:i.size,directorySamples:Array.from(i).slice(0,5),directoryCounts:l},worktrees:{available:e.availableWorktrees.length,metadataEntries:e.worktreeMetadata.size},git:j,localStorage:c,opencode:{pathInfo:y,projectInfo:x,health:v},openchamber:{settingsInfo:h}};return console.log("[DEBUG] App status snapshot:",A),A},async buildDiagnosticsReport(){const t=await this.getAppStatus();return JSON.stringify(t,null,2)},async copyTextToClipboard(t){return Cn(t)},async copyDiagnosticsReport(){const t=await this.buildDiagnosticsReport();return{...await this.copyTextToClipboard(t),report:t}},checkLastMessage(){const t=this.getLastAssistantMessage();if(!t)return!1;const e=t.isEmpty||t.isEmptyResponse;return e?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:t.messageId,isEmpty:t.isEmpty,isEmptyResponse:t.isEmptyResponse,partsCount:t.partsCount}),t.parts.length>0&&console.log("Parts:",t.parts)):console.log("[OK] Last message looks good!"),e},getStreamingState(){const t=Re.getState(),e=t.currentSessionId?t.streamingMessageIds.get(t.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:e,streamingMessageIds:Array.from(t.streamingMessageIds.entries()),messageStreamStates:Array.from(t.messageStreamStates.entries())}),{streamingMessageId:e,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){const t=Re.getState(),e=t.currentSessionId;if(!e)return console.log("[ERROR] No active session"),[];const r=(t.messages.get(e)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(c=>c.type==="text"&&c.text&&c.text.trim().length>0),l=a.some(c=>c.type==="tool");return a.length===0||!i&&!l});return console.log(`[INSPECT] Found ${r.length} empty assistant messages`),r.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),r},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
341
341
  `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
342
342
  `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
343
343
  `),console.log("3. To retry, you can:"),console.log(" - Edit your last user message and resend"),console.log(' - Send a follow-up message like "Please provide the response"'),console.log(` - Try a different model (OpenAI models tend to be more reliable)
344
- `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(t={}){const{includeNonAssistant:e=!1,verbose:n=!0,maxTableRows:r=25}=t,o=Re.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],l=e?i:i.filter(p=>p.info.role==="assistant"),c={totalMessages:i.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},d=p=>typeof p=="number"&&Number.isFinite(p)?p:null,f=p=>{const g=p.filter(y=>typeof y=="number");return g.length>0?Math.max(...g):null},m=l.map((p,g)=>{const y=p.info??{},x=Array.isArray(p.parts)?p.parts:[],h=y.time??{},v=d(h.completed),b=v!==null,w=x.filter(M=>M.type==="tool"),j=x.filter(M=>M.type==="reasoning"),F=f(w.map(M=>d(M.state?.time?.end??M.state?.time?.start))),A=f(j.map(M=>d(M.time?.end??M.time?.start))),C=f([F,A].filter(M=>M!==null)),S=w.some(M=>["pending","running","started"].includes(M.state?.status)),N=j.some(M=>typeof M.time?.end!="number");w.length>0&&(c.withTools+=1),j.length>0&&(c.withReasoning+=1),b||(c.completedMissing+=1);const k=!!(b&&typeof F=="number"&&v<F);k&&(c.completedBeforeTool+=1);const D=!!(b&&typeof A=="number"&&v<A);return D&&(c.completedBeforeReasoning+=1),b&&S&&(c.runningToolsWhenCompleted+=1),b&&N&&(c.reasoningOpenWhenCompleted+=1),{index:g,messageId:y.id,role:y.role,completedAt:v,latestToolTimestamp:F,latestReasoningTimestamp:A,latestPartTimestamp:C,completed_missing:!b,completed_before_tool:k,completed_before_reasoning:D,running_tools_when_completed:!!(b&&S),reasoning_open_when_completed:!!(b&&N),has_tools:w.length>0,has_reasoning:j.length>0}});return n&&(console.table(m.slice(0,r)),m.length>r&&console.log(`Displayed first ${r} rows out of ${m.length}.`),console.log("[SUMMARY] Message completion timing:",c)),{summary:c,rows:m}},checkCompletionStatus(){const t=Re.getState(),e=t.currentSessionId;if(!e)return console.log("[ERROR] No active session"),null;const r=(t.messages.get(e)||[]).filter(h=>h.info.role==="assistant");if(r.length===0)return console.log("[ERROR] No assistant messages"),null;const o=r[r.length-1],a=o.parts.filter(h=>h.type==="step-finish"),i=o.info.finish==="stop",c=o.info.time?.completed,d=o.info.status,f=typeof c=="number"&&c>0||d==="completed",m=!!(f&&i),p=t.messageStreamStates,g=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,y=p.get(o.info.id),x=o.info.id===g;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",c,"(type:",typeof c,")"),console.log("status:",d),console.log("hasCompletedFlag:",f),console.log("hasStopReason:",i),console.log("messageIsComplete:",m),console.log("lifecycle phase:",y?.phase),console.log("isStreamingCandidate:",x),console.log("streamingMessageId:",g),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:c,status:d,hasCompletedFlag:f,hasStopReason:i,messageIsComplete:m,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=pg,nr()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",t=>{try{const e=t.message||"",n=t.filename||"";typeof e=="string"&&e.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(n))&&t.preventDefault()}catch{}}));const xK=({open:t,onOpenChange:e})=>{const[n,r]=u.useState(null),[o,a]=u.useState(!1),[i,l]=u.useState(!1),[c,d]=u.useState(null),[f,m]=u.useState(!1),p=u.useCallback(async()=>{if(!o){a(!0),l(!1);try{if(!c){ce.error("Copy failed",{description:"Diagnostics not ready yet. Wait a second and retry."});return}const y=await pg.copyTextToClipboard(c);y.ok?(l(!0),ce.success("Diagnostics copied")):ce.error("Copy failed",{description:y.error})}catch(y){ce.error("Copy failed"),console.error("Failed to copy diagnostics:",y)}finally{a(!1)}}},[c,o]);u.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.__TAURI__?(async()=>{try{const{getVersion:h}=await gr(async()=>{const{getVersion:b}=await import("./vendor-.bun-Byc0cUD3.js").then(w=>w.eP);return{getVersion:b}},__vite__mapDeps([0,1])),v=await h();r(v)}catch{r("1.8.0")}})():r("1.8.0")},[t]),u.useEffect(()=>{if(!t){d(null),m(!1);return}let y=!1;return m(!0),pg.buildDiagnosticsReport().then(x=>{y||d(x)}).catch(x=>{y||(console.error("Failed to prepare diagnostics:",x),d(null))}).finally(()=>{y||m(!1)}),()=>{y=!0}},[t]);const g=n;return s.jsx(Vs,{open:t,onOpenChange:e,children:s.jsx(Ws,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(ix,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),g&&s.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",g]})]}),s.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",s.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsx("button",{onClick:p,disabled:o||f||!c,className:Z("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:i?"Diagnostics copied":f?"Preparing diagnostics...":"Copy diagnostics"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Includes OpenChamber state, OpenCode health, directories, and projects."})]}),s.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(Ga,{className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(Wv,{className:"h-4 w-4"}),s.jsx("span",{children:"Discord"})]}),s.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(jh,{className:"h-4 w-4"}),s.jsx("span",{children:"@btriapitsyn"})]})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function mh(t){const e=Me.c(3),{apis:n,children:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(Kg.Provider,{value:n,children:r}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o}const yK=()=>{const t=Me.c(3),{isAboutDialogOpen:e,setAboutDialogOpen:n}=Te();let r;return t[0]!==e||t[1]!==n?(r=s.jsx(xK,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r};function bK(t){const e=Me.c(68),{apis:n}=t,{initializeApp:r,isInitialized:o,isConnected:a}=rs(),{error:i,clearError:l,loadSessions:c}=Re(),d=Rs(DK),f=Rs(FK),[m,p]=u.useState(!1),{uiFont:g,monoFont:y}=Tj(),x=Jr(AK);let h;e[0]!==n.runtime.isVSCode?(h=()=>n.runtime.isVSCode,e[0]=n.runtime.isVSCode,e[1]=h):h=e[1];const[v,b]=u.useState(h),[w,j]=u.useState(!1),F=u.useRef(!1);let A,C;e[2]!==n.runtime.isVSCode?(A=()=>{b(n.runtime.isVSCode)},C=[n.runtime.isVSCode],e[2]=n.runtime.isVSCode,e[3]=A,e[4]=C):(A=e[3],C=e[4]),u.useEffect(A,C);let S,N;e[5]!==n?(S=()=>(ow(n),CK),N=[n],e[5]=n,e[6]=S,e[7]=N):(S=e[6],N=e[7]),u.useEffect(S,N);let k,D;e[8]!==n.github||e[9]!==x?(k=()=>{x(n.github,{force:!0})},D=[n.github,x],e[8]=n.github,e[9]=x,e[10]=k,e[11]=D):(k=e[10],D=e[11]),u.useEffect(k,D);let M,E;e[12]!==y||e[13]!==g?(M=()=>{if(typeof document>"u")return;const fe=document.documentElement,pe=$0[g]?.stack??$0[YO].stack,de=bi[y]?.stack??bi[yf].stack;fe.style.setProperty("--font-sans",pe),fe.style.setProperty("--font-heading",pe),fe.style.setProperty("--font-family-sans",pe),fe.style.setProperty("--font-mono",de),fe.style.setProperty("--font-family-mono",de),fe.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=pe)},E=[g,y],e[12]=y,e[13]=g,e[14]=M,e[15]=E):(M=e[14],E=e[15]),u.useEffect(M,E);let _,T;e[16]!==o?(_=()=>{if(o){const pe=setTimeout(NK,150);return()=>clearTimeout(pe)}},T=[o],e[16]=o,e[17]=_,e[18]=T):(_=e[17],T=e[18]),u.useEffect(_,T);let P,H;e[19]!==o?(P=()=>{const fe=setTimeout(()=>{const pe=document.getElementById("initial-loading");pe&&!o&&(pe.classList.add("fade-out"),setTimeout(()=>{pe.remove()},300))},5e3);return()=>clearTimeout(fe)},H=[o],e[19]=o,e[20]=P,e[21]=H):(P=e[20],H=e[21]),u.useEffect(P,H);let R,I;e[22]!==r||e[23]!==v?(R=()=>{(async()=>v||await r())()},I=[r,v],e[22]=r,e[23]=v,e[24]=R,e[25]=I):(R=e[24],I=e[25]),u.useEffect(R,I);let B,z;e[26]!==d||e[27]!==a||e[28]!==f||e[29]!==v||e[30]!==c?(B=()=>{if(f)return;(async()=>v||a&&(Lt.setDirectory(d),await c()))()},z=[d,f,c,a,v],e[26]=d,e[27]=a,e[28]=f,e[29]=v,e[30]=c,e[31]=B,e[32]=z):(B=e[31],z=e[32]),u.useEffect(B,z);let U,K;e[33]!==o||e[34]!==f?(U=()=>{typeof window>"u"||!o||f||F.current||(F.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},K=[o,f],e[33]=o,e[34]=f,e[35]=U,e[36]=K):(U=e[35],K=e[36]),u.useEffect(U,K),Sq(),K4(),Zq(),aK(),Jq(),Dq();let V;e[37]===Symbol.for("react.memo_cache_sentinel")?(V=()=>{p(kK)},e[37]=V):V=e[37],Eq(V);const $=rs(SK);let G,W;e[38]!==$?(G=()=>{if(!tn())return;const fe=window.__TAURI__;typeof fe?.core?.invoke=="function"&&fe.core.invoke("desktop_set_auto_worktree_menu",{enabled:$})},W=[$],e[38]=$,e[39]=G,e[40]=W):(G=e[39],W=e[40]),u.useEffect(G,W),Iq(),Xj(),Bq();let J,te;e[41]===Symbol.for("react.memo_cache_sentinel")?(J=()=>{const fe=pe=>{xm(pe)&&pe.shiftKey&&pe.key==="D"&&(pe.preventDefault(),p(jK))};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},te=[],e[41]=J,e[42]=te):(J=e[41],te=e[42]),u.useEffect(J,te);let le,ae;e[43]!==l||e[44]!==i?(le=()=>{i&&setTimeout(()=>l(),5e3)},ae=[i,l],e[43]=l,e[44]=i,e[45]=le,e[46]=ae):(le=e[45],ae=e[46]),u.useEffect(le,ae);let ie,oe;e[47]===Symbol.for("react.memo_cache_sentinel")?(ie=()=>{if(!fr()||!Ar())return;let fe=!1;return(async()=>{const de=await fetch("/health",{method:"GET"}).catch(wK);if(!de||!de.ok)return;const ne=await de.json().catch(vK);if(!ne||fe)return;const ge=ne.openCodeRunning===!0,we=typeof ne.lastOpenCodeError=="string"?ne.lastOpenCodeError:"",Oe=!ge&&/ENOENT|spawn\s+opencode|Unable\s+to\s+locate\s+the\s+opencode\s+CLI|OpenCode\s+CLI\s+not\s+found|opencode(\.exe)?\s+not\s+found|env:\s*(node|bun):\s*No\s+such\s+file\s+or\s+directory|(node|bun):\s*No\s+such\s+file\s+or\s+directory/i.test(we);j(Oe)})(),()=>{fe=!0}},oe=[],e[47]=ie,e[48]=oe):(ie=e[47],oe=e[48]),u.useEffect(ie,oe);let Y;e[49]===Symbol.for("react.memo_cache_sentinel")?(Y=()=>{j(!1),window.location.reload()},e[49]=Y):Y=e[49];const re=Y;if(w){let fe;return e[50]===Symbol.for("react.memo_cache_sentinel")?(fe=s.jsx(Tn,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(pK,{onCliAvailable:re})})}),e[50]=fe):fe=e[50],fe}if(v){if((typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"){let ne;e[51]===Symbol.for("react.memo_cache_sentinel")?(ne=s.jsx(Vc,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(oq,{}),s.jsx(bp,{})]})}),e[51]=ne):ne=e[51];let ge;return e[52]!==n?(ge=s.jsx(Tn,{children:s.jsx(mh,{apis:n,children:ne})}),e[52]=n,e[53]=ge):ge=e[53],ge}let pe;e[54]===Symbol.for("react.memo_cache_sentinel")?(pe=s.jsx(w0,{children:s.jsx(Vc,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(_G,{}),s.jsx(bp,{})]})})}),e[54]=pe):pe=e[54];let de;return e[55]!==n?(de=s.jsx(Tn,{children:s.jsx(mh,{apis:n,children:pe})}),e[55]=n,e[56]=de):de=e[56],de}let ue,Q,O,se;e[57]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(FG,{}),Q=s.jsx(bp,{}),O=s.jsx(hK,{}),se=s.jsx(yK,{}),e[57]=ue,e[58]=Q,e[59]=O,e[60]=se):(ue=e[57],Q=e[58],O=e[59],se=e[60]);let X;e[61]!==m?(X=m&&s.jsx(aq,{onClose:()=>p(!1)}),e[61]=m,e[62]=X):X=e[62];let L;e[63]!==X?(L=s.jsx(cK,{children:s.jsx(w0,{children:s.jsx(TE,{children:s.jsx(Vc,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[ue,Q,O,se,X]})})})})}),e[63]=X,e[64]=L):L=e[64];let me;return e[65]!==n||e[66]!==L?(me=s.jsx(Tn,{children:s.jsx(mh,{apis:n,children:L})}),e[65]=n,e[66]=L,e[67]=me):me=e[67],me}function vK(){return null}function wK(){return null}function jK(t){return!t}function SK(t){return t.settingsAutoCreateWorktree}function kK(t){return!t}function NK(){const t=document.getElementById("initial-loading");t&&(t.classList.add("fade-out"),setTimeout(()=>{t.remove()},300))}function CK(){return ow(null)}function AK(t){return t.refreshStatus}function FK(t){return t.isSwitchingDirectory}function DK(t){return t.currentDirectory}const SS=async()=>{if(typeof window>"u")return;let t=null,e=null;try{t=window.localStorage.getItem("homeDirectory"),e=window.localStorage.getItem("lastDirectory")}catch(r){console.warn("Failed to read saved directory preferences:",r)}const n=Rs.getState();t&&n.homeDirectory!==t&&n.synchronizeHomeDirectory(t),e&&!ln()&&n.setDirectory(e,{showOverlay:!1})},kS="/auth/session",MK=async()=>{console.log("[Frontend Auth] Checking session status...");const t=await fetch(kS,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});return console.log("[Frontend Auth] Session status response:",t.status,t.statusText),t},EK=async t=>{console.log("[Frontend Auth] Submitting password...");const e=await fetch(kS,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})});return console.log("[Frontend Auth] Password submit response:",e.status,e.statusText),e},Ax=t=>{const e=Me.c(5),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},e[0]=r):r=e[0];let o;e[1]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e[1]=o):o=e[1];let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a=s.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e[2]=a):a=e[2];let i;return e[3]!==n?(i=s.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:r,children:[o,a,s.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:n})]}),e[3]=n,e[4]=i):i=e[4],i},IK=t=>{const e=Me.c(2),{message:n}=t,r=n===void 0?"Preparing workspace…":n;let o;return e[0]!==r?(o=s.jsx(Ax,{children:s.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:r})})}),e[0]=r,e[1]=o):o=e[1],o},ev=t=>{const e=Me.c(12),{onRetry:n,errorType:r,retryAfter:o}=t,i=(r===void 0?"network":r)==="rate-limit",l=o?Math.ceil(o/60):1,c=i?"Too many attempts":"Unable to reach server";let d;e[0]!==c?(d=s.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:c}),e[0]=c,e[1]=d):d=e[1];const f=i?`Please wait ${l} minute${l>1?"s":""} before trying again.`:"We couldn't verify the UI session. Check that the service is running and try again.";let m;e[2]!==f?(m=s.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:f}),e[2]=f,e[3]=m):m=e[3];let p;e[4]!==d||e[5]!==m?(p=s.jsxs("div",{className:"space-y-2",children:[d,m]}),e[4]=d,e[5]=m,e[6]=p):p=e[6];let g;e[7]!==n?(g=s.jsx(ot,{type:"button",onClick:n,className:"w-full max-w-xs",children:"Retry"}),e[7]=n,e[8]=g):g=e[8];let y;return e[9]!==p||e[10]!==g?(y=s.jsx(Ax,{children:s.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[p,g]})}),e[9]=p,e[10]=g,e[11]=y):y=e[11],y},_K=({children:t})=>{const e=u.useMemo(()=>ln(),[]),n=e,r=u.useMemo(()=>fr()&&!e,[e]),[o,a]=u.useState(()=>n?"authenticated":"pending"),[i,l]=u.useState(""),[c,d]=u.useState(!1),[f,m]=u.useState(""),[p,g]=u.useState(void 0),[y,x]=u.useState(!1),h=u.useRef(null),v=u.useRef(n),b=u.useCallback(async()=>{if(n){console.log("[Frontend Auth] VSCode runtime, skipping auth"),a("authenticated");return}const j=document.cookie,F=j.includes("oc_ui_session="),A=j.includes("oc_ui_refresh=");console.log("[Frontend Auth] Cookies check - access:",F,"refresh:",A),console.log("[Frontend Auth] All cookies:",j.split(";").map(C=>C.trim().split("=")[0])),a(C=>C==="authenticated"?C:"pending");try{const C=await MK(),S=await C.text();if(console.log("[Frontend Auth] Raw response:",C.status,S),C.ok){console.log("[Frontend Auth] Session is authenticated"),a("authenticated"),x(!1),m(""),g(void 0);return}if(C.status===401){let N={};try{N=JSON.parse(S)}catch{N={}}console.warn("[Frontend Auth] Session is locked (401)",N),N.debug&&console.warn("[Frontend Auth] Debug info:",N.debug),x(N.tunnelLocked===!0),a("locked"),g(void 0);return}if(C.status===429){let N={};try{N=JSON.parse(S)}catch{N={}}g(N.retryAfter),x(!1),a("rate-limited");return}console.error("[Frontend Auth] Unexpected response status:",C.status),a("error"),x(!1)}catch(C){console.warn("Failed to check session status:",C),a("error"),x(!1)}},[n]);u.useEffect(()=>{n||b()},[b,n]),u.useEffect(()=>{!n&&o==="locked"&&(v.current=!1)},[n,o]),u.useEffect(()=>{o==="locked"&&h.current&&(h.current.focus(),h.current.select())},[o]),u.useEffect(()=>{n||o==="authenticated"&&!v.current&&(v.current=!0,(async()=>(await lw(),await cw(),await SS()))())},[n,o]);const w=async j=>{if(j.preventDefault(),!y&&!(!i||c)){d(!0),m("");try{const F=await EK(i);if(F.ok){console.log("[Frontend Auth] Login successful");const A=document.cookie,C=A.includes("oc_ui_session="),S=A.includes("oc_ui_refresh=");console.log("[Frontend Auth] After login - access:",C,"refresh:",S),console.log("[Frontend Auth] All cookies after login:",A.split(";").map(N=>N.trim().split("=")[0]).filter(Boolean)),l(""),x(!1),a("authenticated");return}if(F.status===401){console.warn("[Frontend Auth] Login failed: Invalid password"),m("Incorrect password. Try again."),x(!1),a("locked");return}if(F.status===429){console.warn("[Frontend Auth] Login failed: Rate limited");const A=await F.json().catch(()=>({}));g(A.retryAfter),x(!1),a("rate-limited");return}console.error("[Frontend Auth] Login failed: Unexpected response",F.status),m("Unexpected response from server."),x(!1),a("error")}catch(F){console.warn("Failed to submit UI password:",F),m("Network error. Check connection and retry."),x(!1),a("error")}finally{d(!1)}}};return o==="pending"?s.jsx(IK,{}):o==="error"?s.jsx(ev,{onRetry:()=>{b()},errorType:"network"}):o==="rate-limited"?s.jsx(ev,{onRetry:()=>{b()},errorType:"rate-limit",retryAfter:p}):o==="locked"?s.jsx(Ax,{children:s.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[s.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[s.jsx("h1",{className:"text-xl font-semibold text-foreground",children:y?"Tunnel access required":"Unlock OpenChamber"}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:y?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!y&&s.jsxs("form",{onSubmit:w,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(T5,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),s.jsx(fs,{id:"openchamber-ui-password",ref:h,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:j=>{l(j.target.value),f&&m("")},className:"pl-10","aria-invalid":!!f||void 0,"aria-describedby":f?"oc-ui-auth-error":void 0,disabled:c})]}),s.jsx(ot,{type:"submit",size:"icon",disabled:!i||c,"aria-label":c?"Unlocking":"Unlock",children:c?s.jsx(ps,{className:"h-4 w-4 animate-spin"}):s.jsx(R5,{className:"h-4 w-4"})})]}),f&&s.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:f})]}),r&&s.jsxs("div",{className:"w-full",children:[s.jsx(LF,{}),s.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})}):s.jsx(s.Fragment,{children:t})},ph=t=>{if(!t||typeof t!="string")return null;const e=t.trim();if(!e.startsWith("#"))return null;let n=e.slice(1);if((n.length===3||n.length===4)&&(n=n.split("").map(l=>l+l).join("")),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;const r=Number.parseInt(n,16);if(Number.isNaN(r))return null;const o=r>>16&255,a=r>>8&255,i=r&255;return`${o} ${a} ${i}`};class PK{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(e){const n=[];return n.push(...this.generateTailwindVariables(e)),n.push(...this.generatePrimaryColors(e.colors.primary)),n.push(...this.generateSurfaceColors(e.colors.surface)),n.push(...this.generateInteractiveColors(e.colors.interactive)),n.push(...this.generateStatusColors(e.colors.status)),n.push(...this.generatePullRequestColors(e)),n.push(...this.generateSyntaxColors(e.colors.syntax)),n.push(...this.generateComponentColors(e.colors,e)),n.push(...this.generateTypographyVariables()),e.config&&n.push(...this.generateConfigVariables(e.config)),n.join(`
344
+ `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(t={}){const{includeNonAssistant:e=!1,verbose:n=!0,maxTableRows:r=25}=t,o=Re.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],l=e?i:i.filter(p=>p.info.role==="assistant"),c={totalMessages:i.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},d=p=>typeof p=="number"&&Number.isFinite(p)?p:null,f=p=>{const g=p.filter(y=>typeof y=="number");return g.length>0?Math.max(...g):null},m=l.map((p,g)=>{const y=p.info??{},x=Array.isArray(p.parts)?p.parts:[],h=y.time??{},v=d(h.completed),b=v!==null,w=x.filter(M=>M.type==="tool"),j=x.filter(M=>M.type==="reasoning"),F=f(w.map(M=>d(M.state?.time?.end??M.state?.time?.start))),A=f(j.map(M=>d(M.time?.end??M.time?.start))),C=f([F,A].filter(M=>M!==null)),S=w.some(M=>["pending","running","started"].includes(M.state?.status)),N=j.some(M=>typeof M.time?.end!="number");w.length>0&&(c.withTools+=1),j.length>0&&(c.withReasoning+=1),b||(c.completedMissing+=1);const k=!!(b&&typeof F=="number"&&v<F);k&&(c.completedBeforeTool+=1);const D=!!(b&&typeof A=="number"&&v<A);return D&&(c.completedBeforeReasoning+=1),b&&S&&(c.runningToolsWhenCompleted+=1),b&&N&&(c.reasoningOpenWhenCompleted+=1),{index:g,messageId:y.id,role:y.role,completedAt:v,latestToolTimestamp:F,latestReasoningTimestamp:A,latestPartTimestamp:C,completed_missing:!b,completed_before_tool:k,completed_before_reasoning:D,running_tools_when_completed:!!(b&&S),reasoning_open_when_completed:!!(b&&N),has_tools:w.length>0,has_reasoning:j.length>0}});return n&&(console.table(m.slice(0,r)),m.length>r&&console.log(`Displayed first ${r} rows out of ${m.length}.`),console.log("[SUMMARY] Message completion timing:",c)),{summary:c,rows:m}},checkCompletionStatus(){const t=Re.getState(),e=t.currentSessionId;if(!e)return console.log("[ERROR] No active session"),null;const r=(t.messages.get(e)||[]).filter(h=>h.info.role==="assistant");if(r.length===0)return console.log("[ERROR] No assistant messages"),null;const o=r[r.length-1],a=o.parts.filter(h=>h.type==="step-finish"),i=o.info.finish==="stop",c=o.info.time?.completed,d=o.info.status,f=typeof c=="number"&&c>0||d==="completed",m=!!(f&&i),p=t.messageStreamStates,g=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,y=p.get(o.info.id),x=o.info.id===g;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",c,"(type:",typeof c,")"),console.log("status:",d),console.log("hasCompletedFlag:",f),console.log("hasStopReason:",i),console.log("messageIsComplete:",m),console.log("lifecycle phase:",y?.phase),console.log("isStreamingCandidate:",x),console.log("streamingMessageId:",g),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:c,status:d,hasCompletedFlag:f,hasStopReason:i,messageIsComplete:m,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=pg,nr()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",t=>{try{const e=t.message||"",n=t.filename||"";typeof e=="string"&&e.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(n))&&t.preventDefault()}catch{}}));const xK=({open:t,onOpenChange:e})=>{const[n,r]=u.useState(null),[o,a]=u.useState(!1),[i,l]=u.useState(!1),[c,d]=u.useState(null),[f,m]=u.useState(!1),p=u.useCallback(async()=>{if(!o){a(!0),l(!1);try{if(!c){ce.error("Copy failed",{description:"Diagnostics not ready yet. Wait a second and retry."});return}const y=await pg.copyTextToClipboard(c);y.ok?(l(!0),ce.success("Diagnostics copied")):ce.error("Copy failed",{description:y.error})}catch(y){ce.error("Copy failed"),console.error("Failed to copy diagnostics:",y)}finally{a(!1)}}},[c,o]);u.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.__TAURI__?(async()=>{try{const{getVersion:h}=await gr(async()=>{const{getVersion:b}=await import("./vendor-.bun-Byc0cUD3.js").then(w=>w.eP);return{getVersion:b}},__vite__mapDeps([0,1])),v=await h();r(v)}catch{r("1.8.1")}})():r("1.8.1")},[t]),u.useEffect(()=>{if(!t){d(null),m(!1);return}let y=!1;return m(!0),pg.buildDiagnosticsReport().then(x=>{y||d(x)}).catch(x=>{y||(console.error("Failed to prepare diagnostics:",x),d(null))}).finally(()=>{y||m(!1)}),()=>{y=!0}},[t]);const g=n;return s.jsx(Vs,{open:t,onOpenChange:e,children:s.jsx(Ws,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(ix,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),g&&s.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",g]})]}),s.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",s.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsx("button",{onClick:p,disabled:o||f||!c,className:Z("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:i?"Diagnostics copied":f?"Preparing diagnostics...":"Copy diagnostics"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:"Includes OpenChamber state, OpenCode health, directories, and projects."})]}),s.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(Ga,{className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(Wv,{className:"h-4 w-4"}),s.jsx("span",{children:"Discord"})]}),s.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(jh,{className:"h-4 w-4"}),s.jsx("span",{children:"@btriapitsyn"})]})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function mh(t){const e=Me.c(3),{apis:n,children:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(Kg.Provider,{value:n,children:r}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o}const yK=()=>{const t=Me.c(3),{isAboutDialogOpen:e,setAboutDialogOpen:n}=Te();let r;return t[0]!==e||t[1]!==n?(r=s.jsx(xK,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r};function bK(t){const e=Me.c(68),{apis:n}=t,{initializeApp:r,isInitialized:o,isConnected:a}=rs(),{error:i,clearError:l,loadSessions:c}=Re(),d=Rs(DK),f=Rs(FK),[m,p]=u.useState(!1),{uiFont:g,monoFont:y}=Tj(),x=Jr(AK);let h;e[0]!==n.runtime.isVSCode?(h=()=>n.runtime.isVSCode,e[0]=n.runtime.isVSCode,e[1]=h):h=e[1];const[v,b]=u.useState(h),[w,j]=u.useState(!1),F=u.useRef(!1);let A,C;e[2]!==n.runtime.isVSCode?(A=()=>{b(n.runtime.isVSCode)},C=[n.runtime.isVSCode],e[2]=n.runtime.isVSCode,e[3]=A,e[4]=C):(A=e[3],C=e[4]),u.useEffect(A,C);let S,N;e[5]!==n?(S=()=>(ow(n),CK),N=[n],e[5]=n,e[6]=S,e[7]=N):(S=e[6],N=e[7]),u.useEffect(S,N);let k,D;e[8]!==n.github||e[9]!==x?(k=()=>{x(n.github,{force:!0})},D=[n.github,x],e[8]=n.github,e[9]=x,e[10]=k,e[11]=D):(k=e[10],D=e[11]),u.useEffect(k,D);let M,E;e[12]!==y||e[13]!==g?(M=()=>{if(typeof document>"u")return;const fe=document.documentElement,pe=$0[g]?.stack??$0[YO].stack,de=bi[y]?.stack??bi[yf].stack;fe.style.setProperty("--font-sans",pe),fe.style.setProperty("--font-heading",pe),fe.style.setProperty("--font-family-sans",pe),fe.style.setProperty("--font-mono",de),fe.style.setProperty("--font-family-mono",de),fe.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=pe)},E=[g,y],e[12]=y,e[13]=g,e[14]=M,e[15]=E):(M=e[14],E=e[15]),u.useEffect(M,E);let _,T;e[16]!==o?(_=()=>{if(o){const pe=setTimeout(NK,150);return()=>clearTimeout(pe)}},T=[o],e[16]=o,e[17]=_,e[18]=T):(_=e[17],T=e[18]),u.useEffect(_,T);let P,H;e[19]!==o?(P=()=>{const fe=setTimeout(()=>{const pe=document.getElementById("initial-loading");pe&&!o&&(pe.classList.add("fade-out"),setTimeout(()=>{pe.remove()},300))},5e3);return()=>clearTimeout(fe)},H=[o],e[19]=o,e[20]=P,e[21]=H):(P=e[20],H=e[21]),u.useEffect(P,H);let R,I;e[22]!==r||e[23]!==v?(R=()=>{(async()=>v||await r())()},I=[r,v],e[22]=r,e[23]=v,e[24]=R,e[25]=I):(R=e[24],I=e[25]),u.useEffect(R,I);let B,z;e[26]!==d||e[27]!==a||e[28]!==f||e[29]!==v||e[30]!==c?(B=()=>{if(f)return;(async()=>v||a&&(Lt.setDirectory(d),await c()))()},z=[d,f,c,a,v],e[26]=d,e[27]=a,e[28]=f,e[29]=v,e[30]=c,e[31]=B,e[32]=z):(B=e[31],z=e[32]),u.useEffect(B,z);let U,K;e[33]!==o||e[34]!==f?(U=()=>{typeof window>"u"||!o||f||F.current||(F.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},K=[o,f],e[33]=o,e[34]=f,e[35]=U,e[36]=K):(U=e[35],K=e[36]),u.useEffect(U,K),Sq(),K4(),Zq(),aK(),Jq(),Dq();let V;e[37]===Symbol.for("react.memo_cache_sentinel")?(V=()=>{p(kK)},e[37]=V):V=e[37],Eq(V);const $=rs(SK);let G,W;e[38]!==$?(G=()=>{if(!tn())return;const fe=window.__TAURI__;typeof fe?.core?.invoke=="function"&&fe.core.invoke("desktop_set_auto_worktree_menu",{enabled:$})},W=[$],e[38]=$,e[39]=G,e[40]=W):(G=e[39],W=e[40]),u.useEffect(G,W),Iq(),Xj(),Bq();let J,te;e[41]===Symbol.for("react.memo_cache_sentinel")?(J=()=>{const fe=pe=>{xm(pe)&&pe.shiftKey&&pe.key==="D"&&(pe.preventDefault(),p(jK))};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},te=[],e[41]=J,e[42]=te):(J=e[41],te=e[42]),u.useEffect(J,te);let le,ae;e[43]!==l||e[44]!==i?(le=()=>{i&&setTimeout(()=>l(),5e3)},ae=[i,l],e[43]=l,e[44]=i,e[45]=le,e[46]=ae):(le=e[45],ae=e[46]),u.useEffect(le,ae);let ie,oe;e[47]===Symbol.for("react.memo_cache_sentinel")?(ie=()=>{if(!fr()||!Ar())return;let fe=!1;return(async()=>{const de=await fetch("/health",{method:"GET"}).catch(wK);if(!de||!de.ok)return;const ne=await de.json().catch(vK);if(!ne||fe)return;const ge=ne.openCodeRunning===!0,we=typeof ne.lastOpenCodeError=="string"?ne.lastOpenCodeError:"",Oe=!ge&&/ENOENT|spawn\s+opencode|Unable\s+to\s+locate\s+the\s+opencode\s+CLI|OpenCode\s+CLI\s+not\s+found|opencode(\.exe)?\s+not\s+found|env:\s*(node|bun):\s*No\s+such\s+file\s+or\s+directory|(node|bun):\s*No\s+such\s+file\s+or\s+directory/i.test(we);j(Oe)})(),()=>{fe=!0}},oe=[],e[47]=ie,e[48]=oe):(ie=e[47],oe=e[48]),u.useEffect(ie,oe);let Y;e[49]===Symbol.for("react.memo_cache_sentinel")?(Y=()=>{j(!1),window.location.reload()},e[49]=Y):Y=e[49];const re=Y;if(w){let fe;return e[50]===Symbol.for("react.memo_cache_sentinel")?(fe=s.jsx(Tn,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(pK,{onCliAvailable:re})})}),e[50]=fe):fe=e[50],fe}if(v){if((typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"){let ne;e[51]===Symbol.for("react.memo_cache_sentinel")?(ne=s.jsx(Vc,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(oq,{}),s.jsx(bp,{})]})}),e[51]=ne):ne=e[51];let ge;return e[52]!==n?(ge=s.jsx(Tn,{children:s.jsx(mh,{apis:n,children:ne})}),e[52]=n,e[53]=ge):ge=e[53],ge}let pe;e[54]===Symbol.for("react.memo_cache_sentinel")?(pe=s.jsx(w0,{children:s.jsx(Vc,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(_G,{}),s.jsx(bp,{})]})})}),e[54]=pe):pe=e[54];let de;return e[55]!==n?(de=s.jsx(Tn,{children:s.jsx(mh,{apis:n,children:pe})}),e[55]=n,e[56]=de):de=e[56],de}let ue,Q,O,se;e[57]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(FG,{}),Q=s.jsx(bp,{}),O=s.jsx(hK,{}),se=s.jsx(yK,{}),e[57]=ue,e[58]=Q,e[59]=O,e[60]=se):(ue=e[57],Q=e[58],O=e[59],se=e[60]);let X;e[61]!==m?(X=m&&s.jsx(aq,{onClose:()=>p(!1)}),e[61]=m,e[62]=X):X=e[62];let L;e[63]!==X?(L=s.jsx(cK,{children:s.jsx(w0,{children:s.jsx(TE,{children:s.jsx(Vc,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[ue,Q,O,se,X]})})})})}),e[63]=X,e[64]=L):L=e[64];let me;return e[65]!==n||e[66]!==L?(me=s.jsx(Tn,{children:s.jsx(mh,{apis:n,children:L})}),e[65]=n,e[66]=L,e[67]=me):me=e[67],me}function vK(){return null}function wK(){return null}function jK(t){return!t}function SK(t){return t.settingsAutoCreateWorktree}function kK(t){return!t}function NK(){const t=document.getElementById("initial-loading");t&&(t.classList.add("fade-out"),setTimeout(()=>{t.remove()},300))}function CK(){return ow(null)}function AK(t){return t.refreshStatus}function FK(t){return t.isSwitchingDirectory}function DK(t){return t.currentDirectory}const SS=async()=>{if(typeof window>"u")return;let t=null,e=null;try{t=window.localStorage.getItem("homeDirectory"),e=window.localStorage.getItem("lastDirectory")}catch(r){console.warn("Failed to read saved directory preferences:",r)}const n=Rs.getState();t&&n.homeDirectory!==t&&n.synchronizeHomeDirectory(t),e&&!ln()&&n.setDirectory(e,{showOverlay:!1})},kS="/auth/session",MK=async()=>{console.log("[Frontend Auth] Checking session status...");const t=await fetch(kS,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});return console.log("[Frontend Auth] Session status response:",t.status,t.statusText),t},EK=async t=>{console.log("[Frontend Auth] Submitting password...");const e=await fetch(kS,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})});return console.log("[Frontend Auth] Password submit response:",e.status,e.statusText),e},Ax=t=>{const e=Me.c(5),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},e[0]=r):r=e[0];let o;e[1]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e[1]=o):o=e[1];let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a=s.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e[2]=a):a=e[2];let i;return e[3]!==n?(i=s.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:r,children:[o,a,s.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:n})]}),e[3]=n,e[4]=i):i=e[4],i},IK=t=>{const e=Me.c(2),{message:n}=t,r=n===void 0?"Preparing workspace…":n;let o;return e[0]!==r?(o=s.jsx(Ax,{children:s.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:r})})}),e[0]=r,e[1]=o):o=e[1],o},ev=t=>{const e=Me.c(12),{onRetry:n,errorType:r,retryAfter:o}=t,i=(r===void 0?"network":r)==="rate-limit",l=o?Math.ceil(o/60):1,c=i?"Too many attempts":"Unable to reach server";let d;e[0]!==c?(d=s.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:c}),e[0]=c,e[1]=d):d=e[1];const f=i?`Please wait ${l} minute${l>1?"s":""} before trying again.`:"We couldn't verify the UI session. Check that the service is running and try again.";let m;e[2]!==f?(m=s.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:f}),e[2]=f,e[3]=m):m=e[3];let p;e[4]!==d||e[5]!==m?(p=s.jsxs("div",{className:"space-y-2",children:[d,m]}),e[4]=d,e[5]=m,e[6]=p):p=e[6];let g;e[7]!==n?(g=s.jsx(ot,{type:"button",onClick:n,className:"w-full max-w-xs",children:"Retry"}),e[7]=n,e[8]=g):g=e[8];let y;return e[9]!==p||e[10]!==g?(y=s.jsx(Ax,{children:s.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[p,g]})}),e[9]=p,e[10]=g,e[11]=y):y=e[11],y},_K=({children:t})=>{const e=u.useMemo(()=>ln(),[]),n=e,r=u.useMemo(()=>fr()&&!e,[e]),[o,a]=u.useState(()=>n?"authenticated":"pending"),[i,l]=u.useState(""),[c,d]=u.useState(!1),[f,m]=u.useState(""),[p,g]=u.useState(void 0),[y,x]=u.useState(!1),h=u.useRef(null),v=u.useRef(n),b=u.useCallback(async()=>{if(n){console.log("[Frontend Auth] VSCode runtime, skipping auth"),a("authenticated");return}const j=document.cookie,F=j.includes("oc_ui_session="),A=j.includes("oc_ui_refresh=");console.log("[Frontend Auth] Cookies check - access:",F,"refresh:",A),console.log("[Frontend Auth] All cookies:",j.split(";").map(C=>C.trim().split("=")[0])),a(C=>C==="authenticated"?C:"pending");try{const C=await MK(),S=await C.text();if(console.log("[Frontend Auth] Raw response:",C.status,S),C.ok){console.log("[Frontend Auth] Session is authenticated"),a("authenticated"),x(!1),m(""),g(void 0);return}if(C.status===401){let N={};try{N=JSON.parse(S)}catch{N={}}console.warn("[Frontend Auth] Session is locked (401)",N),N.debug&&console.warn("[Frontend Auth] Debug info:",N.debug),x(N.tunnelLocked===!0),a("locked"),g(void 0);return}if(C.status===429){let N={};try{N=JSON.parse(S)}catch{N={}}g(N.retryAfter),x(!1),a("rate-limited");return}console.error("[Frontend Auth] Unexpected response status:",C.status),a("error"),x(!1)}catch(C){console.warn("Failed to check session status:",C),a("error"),x(!1)}},[n]);u.useEffect(()=>{n||b()},[b,n]),u.useEffect(()=>{!n&&o==="locked"&&(v.current=!1)},[n,o]),u.useEffect(()=>{o==="locked"&&h.current&&(h.current.focus(),h.current.select())},[o]),u.useEffect(()=>{n||o==="authenticated"&&!v.current&&(v.current=!0,(async()=>(await lw(),await cw(),await SS()))())},[n,o]);const w=async j=>{if(j.preventDefault(),!y&&!(!i||c)){d(!0),m("");try{const F=await EK(i);if(F.ok){console.log("[Frontend Auth] Login successful");const A=document.cookie,C=A.includes("oc_ui_session="),S=A.includes("oc_ui_refresh=");console.log("[Frontend Auth] After login - access:",C,"refresh:",S),console.log("[Frontend Auth] All cookies after login:",A.split(";").map(N=>N.trim().split("=")[0]).filter(Boolean)),l(""),x(!1),a("authenticated");return}if(F.status===401){console.warn("[Frontend Auth] Login failed: Invalid password"),m("Incorrect password. Try again."),x(!1),a("locked");return}if(F.status===429){console.warn("[Frontend Auth] Login failed: Rate limited");const A=await F.json().catch(()=>({}));g(A.retryAfter),x(!1),a("rate-limited");return}console.error("[Frontend Auth] Login failed: Unexpected response",F.status),m("Unexpected response from server."),x(!1),a("error")}catch(F){console.warn("Failed to submit UI password:",F),m("Network error. Check connection and retry."),x(!1),a("error")}finally{d(!1)}}};return o==="pending"?s.jsx(IK,{}):o==="error"?s.jsx(ev,{onRetry:()=>{b()},errorType:"network"}):o==="rate-limited"?s.jsx(ev,{onRetry:()=>{b()},errorType:"rate-limit",retryAfter:p}):o==="locked"?s.jsx(Ax,{children:s.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[s.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[s.jsx("h1",{className:"text-xl font-semibold text-foreground",children:y?"Tunnel access required":"Unlock OpenChamber"}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:y?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!y&&s.jsxs("form",{onSubmit:w,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(T5,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),s.jsx(fs,{id:"openchamber-ui-password",ref:h,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:j=>{l(j.target.value),f&&m("")},className:"pl-10","aria-invalid":!!f||void 0,"aria-describedby":f?"oc-ui-auth-error":void 0,disabled:c})]}),s.jsx(ot,{type:"submit",size:"icon",disabled:!i||c,"aria-label":c?"Unlocking":"Unlock",children:c?s.jsx(ps,{className:"h-4 w-4 animate-spin"}):s.jsx(R5,{className:"h-4 w-4"})})]}),f&&s.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:f})]}),r&&s.jsxs("div",{className:"w-full",children:[s.jsx(LF,{}),s.jsx("p",{className:"mt-1 text-center typography-micro text-muted-foreground",children:"Use Local if remote is unreachable."})]})]})}):s.jsx(s.Fragment,{children:t})},ph=t=>{if(!t||typeof t!="string")return null;const e=t.trim();if(!e.startsWith("#"))return null;let n=e.slice(1);if((n.length===3||n.length===4)&&(n=n.split("").map(l=>l+l).join("")),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;const r=Number.parseInt(n,16);if(Number.isNaN(r))return null;const o=r>>16&255,a=r>>8&255,i=r&255;return`${o} ${a} ${i}`};class PK{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(e){const n=[];return n.push(...this.generateTailwindVariables(e)),n.push(...this.generatePrimaryColors(e.colors.primary)),n.push(...this.generateSurfaceColors(e.colors.surface)),n.push(...this.generateInteractiveColors(e.colors.interactive)),n.push(...this.generateStatusColors(e.colors.status)),n.push(...this.generatePullRequestColors(e)),n.push(...this.generateSyntaxColors(e.colors.syntax)),n.push(...this.generateComponentColors(e.colors,e)),n.push(...this.generateTypographyVariables()),e.config&&n.push(...this.generateConfigVariables(e.config)),n.join(`
345
345
  `)}generateTailwindVariables(e){const n=[];n.push(` --background: ${e.colors.surface.background} !important;`),n.push(` --foreground: ${e.colors.surface.foreground} !important;`),n.push(` --muted: ${e.colors.surface.muted} !important;`),n.push(` --muted-foreground: ${e.colors.surface.mutedForeground} !important;`),n.push(` --card: ${e.colors.surface.elevated} !important;`),n.push(` --card-foreground: ${e.colors.surface.elevatedForeground} !important;`),n.push(` --popover: ${e.colors.surface.elevated} !important;`),n.push(` --popover-foreground: ${e.colors.surface.elevatedForeground} !important;`),n.push(` --border: ${e.colors.interactive.border} !important;`),n.push(` --input: ${e.colors.interactive.border} !important;`),n.push(` --primary: ${e.colors.primary.base} !important;`),n.push(` --primary-foreground: ${e.colors.primary.foreground} !important;`),n.push(` --secondary: ${e.colors.surface.muted} !important;`),n.push(` --secondary-foreground: ${e.colors.surface.mutedForeground} !important;`),n.push(` --accent: ${e.colors.surface.subtle} !important;`),n.push(` --accent-foreground: ${e.colors.surface.foreground} !important;`),n.push(` --destructive: ${e.colors.status.error} !important;`),n.push(` --destructive-foreground: ${e.colors.status.errorForeground} !important;`),n.push(` --ring: ${e.colors.interactive.focusRing} !important;`),e.config?.radius?.md&&n.push(` --radius: ${e.config.radius.md} !important;`);const r=ph(e.colors.surface.muted),o=ph(e.colors.surface.subtle),a=ph(e.colors.interactive.border);n.push(` --sidebar-base: ${e.colors.surface.muted} !important;`),r&&n.push(` --sidebar-base-rgb: ${r} !important;`),n.push(" --sidebar: var(--sidebar-base) !important;"),n.push(` --sidebar-foreground: ${e.colors.surface.mutedForeground} !important;`),n.push(` --sidebar-primary: ${e.colors.primary.base} !important;`),n.push(` --sidebar-primary-foreground: ${e.colors.primary.foreground} !important;`),n.push(` --sidebar-accent-base: ${e.colors.surface.subtle} !important;`),o&&n.push(` --sidebar-accent-base-rgb: ${o} !important;`),n.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),n.push(` --sidebar-accent-foreground: ${e.colors.surface.foreground} !important;`),n.push(` --sidebar-border: ${e.colors.interactive.border} !important;`),a&&n.push(` --sidebar-border-rgb: ${a} !important;`),n.push(` --sidebar-ring: ${e.colors.interactive.focusRing} !important;`);const i=e.metadata.variant==="dark",l=i?.8:.95,c=i?.7:.9;if(r)n.push(` --sidebar-overlay-strong: rgb(${r} / ${l}) !important;`),n.push(` --sidebar-overlay-soft: rgb(${r} / ${c}) !important;`);else{const d=e.colors.surface.muted;n.push(` --sidebar-overlay-strong: ${this.opacity(d,l)} !important;`),n.push(` --sidebar-overlay-soft: ${this.opacity(d,c)} !important;`)}return e.colors.charts?.series&&Array.isArray(e.colors.charts.series)&&e.colors.charts.series.forEach((d,f)=>{n.push(` --chart-${f+1}: ${d};`)}),e.colors.loading?(n.push(` --loading-spinner: ${e.colors.loading.spinner||e.colors.primary.base};`),n.push(` --loading-spinner-track: ${e.colors.loading.spinnerTrack||e.colors.surface.muted};`)):(n.push(` --loading-spinner: ${e.colors.primary.base};`),n.push(` --loading-spinner-track: ${e.colors.surface.muted};`)),n}apply(e){const n=this.generate(e),r=document.createElement("style");r.id="opencode-theme-variables";let o="";e.metadata.variant==="dark"?(o=`:root {
346
346
  ${n}
347
347
  }