@openchamber/web 1.8.6 → 1.8.7

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-9lzLHWe8.js","assets/vendor--DbVqbJpV.css","assets/ToolOutputDialog-BDB_7hZd.js","assets/index-xEiu5N1g.js","assets/index-JYxeZFeM.css"])))=>i.map(i=>d[i]);
2
- import{t as iy,c as ly,F as cy,a as Ce,j as s,R as dy,T as uy,P as fy,C as my,b as hy,A as py,L as gy,d as yy,S as by,e as xy,f as vy,g as wy,i as jy,k as Sy,I as ky,l as Ny,m as Cy,n as My,o as Ay,s as vs,r as Un,p as xn,q as In,u as hr,v as xr,w as f,x as Ic,y as li,z as Tc,B as Pc,D as Rc,E as _s,G as s2,H as Fy,J as m4,K as Lc,M as zc,N as S3,_ as cr,X as Dy,O as uo,Q as ep,U as tp,V as _y,W as n2,Y as r2,Z as gc,$ as By,a0 as tu,a1 as h4,a2 as Aa,a3 as Ey,a4 as sp,a5 as Iy,a6 as Ty,a7 as Py,a8 as o2,a9 as p4,aa as Lo,ab as np,ac as Ry,ad as Ne,ae as Ly,af as rp,ag as Wn,ah as zy,ai as Hy,aj as Oy,ak as g4,al as op,am as ap,an as $y,ao as ip,ap as lp,aq as Vy,ar as cp,as as Uy,at as Wy,au as qy,av as kl,aw as ta,ax as mo,ay as y4,az as Ln,aA as os,aB as b4,aC as To,aD as ei,aE as V1,aF as Xs,aG as dp,aH as Gy,aI as Zy,aJ as Ls,aK as Jn,aL as ka,aM as Ky,aN as Yi,aO as Hc,aP as Qy,aQ as ci,aR as cn,aS as ur,aT as $o,aU as oa,aV as $r,aW as Ba,aX as yc,aY as Po,aZ as a2,a_ as ya,a$ as su,b0 as bc,b1 as h0,b2 as Yy,b3 as ti,b4 as Na,b5 as p0,b6 as i2,b7 as Co,b8 as jr,b9 as Jy,ba as Xy,bb as up,bc as eb,bd as tb,be as aa,bf as sb,bg as U1,bh as nb,bi as il,bj as yr,bk as di,bl as rb,bm as ob,bn as x4,bo as bl,bp as _n,bq as v4,br as w4,bs as fp,bt as mp,bu as ab,bv as ib,bw as Jl,bx as g0,by as ui,bz as fi,bA as lb,bB as sa,bC as cb,bD as db,bE as Qr,bF as ub,bG as mi,bH as Yo,bI as fb,bJ as ao,bK as xc,bL as mb,bM as hb,bN as hp,bO as Fa,bP as l2,bQ as pb,bR as gb,bS as Ya,bT as pp,bU as gp,bV as W1,bW as yb,bX as ll,bY as hi,bZ as go,b_ as zo,b$ as Ho,c0 as Jo,c1 as nu,c2 as yp,c3 as xa,c4 as Fo,c5 as bb,c6 as xb,c7 as Xl,c8 as vb,c9 as wb,ca as bp,cb as jb,cc as xp,cd as Sb,ce as kb,cf as Nb,cg as Cb,ch as vp,ci as si,cj as j4,ck as ru,cl as Mb,cm as Ab,cn as Fb,co as Db,cp as k3,cq as N3,cr as C3,cs as c2,ct as _b,cu as Bb,cv as oo,cw as Eb,cx as xl,cy as M3,cz as Ib,cA as Tb,cB as R2,cC as Pb,cD as Rb,cE as Lb,cF as A3,cG as zb,cH as wp,cI as jp,cJ as Hb,cK as F3,cL as Ob,cM as $b,cN as Vb,cO as Ub,cP as S4,cQ as k4,cR as Wb,cS as ou,cT as kt,cU as Gl,cV as qb,cW as Gb,cX as ji,cY as Zb,cZ as Kb,c_ as Qb,c$ as Yb,d0 as Jb,d1 as Xb,d2 as ex,d3 as tx,d4 as y0,d5 as Sp,d6 as kp,d7 as Np,d8 as Cp,d9 as Mp,da as Ap,db as Fp,dc as sx,dd as Dp,de as _p,df as Hi,dg as Bp,dh as Ep,di as au,dj as Si,dk as Ip,dl as iu,dm as nx,dn as N4,dp as rx,dq as ox,dr as ec,ds as d2,dt as ax,du as ix,dv as lx,dw as cx,dx,dy as ux,dz as fx,dA as mx,dB as hx,dC as px,dD as gx,dE as yx,dF as bx,dG as xx,dH as ni,dI as vx,dJ as wx,dK as jx,dL as Sx,dM as kx,dN as Nx,dO as Cx,dP as lu,dQ as Mx,dR as Ax,dS as Fx,dT as b0,dU as D3,dV as _3,dW as u2,dX as Dx,dY as Tp,dZ as Pp,d_ as Rp,d$ as Lp,e0 as Tr,e1 as _x,e2 as Bx,e3 as x0,e4 as zp,e5 as cu,e6 as Ex,e7 as Ix,e8 as q1,e9 as Tx,ea as Px,eb as Rx,ec as Lx,ed as Hp,ee as du,ef as zx,eg as Hx,eh as Ox,ei as Op,ej as $x,ek as Vx,el as Ux,em as Wx,en as qx,eo as Gx,ep as Zx,eq as Kx,er as Qx,es as Yx,et as Jx,eu as Xx,ev,ew as tv,ex as uu,ey as sv,ez as B3,eA as E3,eB as nv,eC as t1,eD as G1,eE as rv,eF as ov,eG as L2,eH as I3,eI as av,eJ as iv,eK as lv,eL as cv,eM as dv}from"./vendor-.bun-9lzLHWe8.js";import{c as uv,l as fv,d as mv,a as hv,v as pv,g as gv,b as yv,e as bv,u as xv,f as vv,h as wv,i as jv,j as Sv,k as kv,m as Nv,n as Cv,o as Mv,p as Av,q as Fv}from"./index-xEiu5N1g.js";const Gs=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",T3=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}}},P3=t=>{const e=t.trim();if(!e)return null;try{return new URL(e)}catch{try{return new URL(e.endsWith("/")?e:`${e}/`)}catch{return null}}},Dv=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),R3=t=>{const e=Dv(t);return e==="localhost"||e==="127.0.0.1"||e==="::1"},ar=()=>{if(typeof window>"u")return!1;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=P3(t),n=P3(window.location.origin);if(e&&n){if(e.origin===n.origin)return!0;const a=e.port||(e.protocol==="https:"?"443":"80"),i=n.port||(n.protocol==="https:"?"443":"80");return e.protocol===n.protocol&&a===i&&R3(e.hostname)&&R3(n.hostname)}const r=T3(t),o=T3(window.location.origin)||window.location.origin;return!!(r&&o&&r===o)},Xn=()=>typeof window>"u"?!1:typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"&&window.__OPENCHAMBER_LOCAL_ORIGIN__.length>0?!0:Gs(),ln=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Uo=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!ln()},f2=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Oc=async t=>{if(Gs()&&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}},$p=async t=>{if(Gs()&&ar())try{const n=await window.__TAURI__?.dialog?.open?.({directory:!1,multiple:!1,title:"Select File",...t?.filters?{filters:t.filters}:{}});return!n||typeof n!="string"?{success:!1,error:"File selection cancelled"}:{success:!0,path:n}}catch(e){return console.warn("Failed to request file access (tauri)",e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:"Native file picker not available"}},Vp=async t=>({success:!0}),Up=async t=>({success:!0}),Wp=async()=>{if(!Gs()||!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}},qp=async t=>{if(!Gs()||!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 u=d?.downloaded,m=d?.total;typeof u=="number"&&(r=u),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{}}},Gp=async()=>{if(!Gs()||!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}},tc=async(t,e)=>{if(!Gs()||!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}},C4=async(t,e,n,r)=>{if(!Gs()||!ar())return!1;const o=t?.trim(),a=e?.trim(),i=n?.trim(),l=typeof r=="string"?r.trim():"";if(!o||!a||!i)return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_open_in_app",{projectPath:o,appId:a,appName:i,filePath:l.length>0?l:void 0}),!0}catch(c){return console.warn("Failed to open project in app (tauri)",c),!1}},fu=async(t,e)=>{if(!Gs()||!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}}},_v=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Wp,downloadDesktopUpdate:qp,fetchDesktopInstalledApps:fu,getDesktopHomeDirectory:f2,isDesktopLocalOriginActive:ar,isDesktopShell:Xn,isTauriShell:Gs,isVSCodeRuntime:ln,isWebRuntime:Uo,openDesktopPath:tc,openDesktopProjectInApp:C4,requestDirectoryAccess:Oc,requestFileAccess:$p,restartToApplyUpdate:Gp,startAccessingDirectory:Vp,stopAccessingDirectory:Up},Symbol.toStringTag,{value:"Module"}));function J(...t){return iy(ly(t))}const pi=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),m2=t=>pi()&&Gs()?t.metaKey:t.ctrlKey,Oi=()=>pi()&&Gs()?"⌘":"Ctrl",L3=(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}`},v0=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function na(t,e){if(!t)return"";const n=v0(t);if(n==="/")return"/";const r=e?v0(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 fo(t,e){if(!t)return"/";const n=v0(t);if(!n||n==="/")return"/";const r=e?v0(e):void 0;return r&&r!=="/"&&n===r?"~":n.split("/").pop()||n||"/"}function Ja(t,e){return e?t?t.toLowerCase().includes(e.toLowerCase())?!0:new cy([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(e).length>0:!1:!0}function $i(t){const e=Ce.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(hy,{"data-slot":"tooltip-provider",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Vt(t){const e=Ce.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(dy,{"data-slot":"tooltip",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Ut(t){const e=Ce.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(uy,{"data-slot":"tooltip-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function $t(t){const e=Ce.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=J("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(py,{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(fy,{children:s.jsxs(my,{"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 zs(t){const e=Ce.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(vy,{"data-slot":"dropdown-menu",...n}),e[2]=n,e[3]=r):r=e[3],r}function Hs(t){const e=Ce.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(wy,{"data-slot":"dropdown-menu-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function Os(t){const e=Ce.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=J("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(jy,{children:s.jsx(Sy,{"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 Qt(t){const e=Ce.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=J("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-pointer 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(ky,{"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 w0(t){const e=Ce.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(yy,{"data-slot":"dropdown-menu-radio-group",...n}),e[2]=n,e[3]=r):r=e[3],r}function h2(t){const e=Ce.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=J("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-pointer 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(Ay,{children:s.jsx(vs,{className:"size-3"})})}),e[6]=i):i=e[6];let l;return e[7]!==n||e[8]!==o||e[9]!==a?(l=s.jsxs(xy,{"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=Ce.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=J("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(gy,{"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 Rn(t){const e=Ce.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=J("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(by,{"data-slot":"dropdown-menu-separator",className:o,...r}),e[5]=r,e[6]=o,e[7]=a):a=e[7],a}function Bv(t){const e=Ce.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(Ny,{"data-slot":"dropdown-menu-sub",...n}),e[2]=n,e[3]=r):r=e[3],r}function Ev(t){const e=Ce.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=J("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer 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(Un,{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(Cy,{"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 Iv(t){const e=Ce.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=J("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(My,{"data-slot":"dropdown-menu-sub-content",style:o,className:a,...r}),e[6]=r,e[7]=a,e[8]=i):i=e[8],i}let z2=null,H2=null;const j0=()=>{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}}},Tv=()=>{if(typeof window>"u"||!window.localStorage)return j0();const t=window.localStorage,e=j0();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const u=t.getItem(d);if(u!==null)return u}catch{r()}return e.getItem(d)},setItem:(d,u)=>{if(n)try{t.setItem(d,u),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,u)},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}}},Bn=()=>(z2||(z2=Tv()),z2),Pv=()=>{if(typeof window>"u"||!window.sessionStorage)return j0();const t=window.sessionStorage,e=j0();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const u=t.getItem(d);if(u!==null)return u}catch{r()}return e.getItem(d)},setItem:(d,u)=>{if(n)try{t.setItem(d,u),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,u)},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}}},Rv=()=>(H2||(H2=Pv()),H2),M4={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Lv={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function z3(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Xo={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)"}}},Z1={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Xo.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Z1.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Xo.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Z1.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Xo.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Z1.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Xo.tool.inline})},s1={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}"}},da={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},n1=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,zv=t=>{if(!t||typeof t!="object")return!1;const e=t;return n1(e.completion,s1.completion)&&n1(e.error,s1.error)&&n1(e.question,s1.question)&&n1(e.subtask,s1.subtask)},A4=600,Hv=360,Ov=1400,Zp=12,H3=120,Nl=300,Cl=400,Wr=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},Kp=t=>Number.isFinite(t)?Math.min(Ov,Math.max(Hv,Math.round(t))):A4,S0=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.replace(/\\/g,"/"):null},Qp=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.length>H3?e.slice(0,H3):e:null},$v=(t,e)=>t==="file"&&e||t,Yp=(t,e,n)=>{if(typeof n=="string"){const r=n.trim();if(r)return r}return $v(t,e)},Jp=(t,e)=>e===t?t:`${t}:${e}`,Xp=t=>{const e=S0(t.targetPath),n=Yp(t.mode,e,t.dedupeKey);return{id:Jp(t.mode,n),mode:t.mode,targetPath:e,dedupeKey:n,label:Qp(t.label),touchedAt:Date.now()}},e8=(t,e,n)=>{if(t.length<=e)return t;const o=[...t].sort((l,c)=>l.touchedAt-c.touchedAt).filter(l=>l.id!==n),a=t.length-e;if(a<=0||o.length===0)return t.slice(-e);const i=new Set(o.slice(0,a).map(l=>l.id));return t.filter(l=>!i.has(l.id))},t8=t=>{if(!Array.isArray(t))return[];const e=[],n=new Set;for(const r of t){if(!r||typeof r!="object")continue;const o=r;if(o.mode!=="diff"&&o.mode!=="file"&&o.mode!=="context"&&o.mode!=="plan"&&o.mode!=="chat")continue;const a=S0(typeof o.targetPath=="string"?o.targetPath:null),i=Yp(o.mode,a,typeof o.dedupeKey=="string"?o.dedupeKey:null),l=Jp(o.mode,i);!l||n.has(l)||(n.add(l),e.push({id:l,mode:o.mode,targetPath:a,dedupeKey:i,label:Qp(typeof o.label=="string"?o.label:null),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return e},vc=(t,e)=>e&&t.some(n=>n.id===e)?e:t.length===0?null:t[t.length-1].id,Ra=t=>{if(t){const e=t8(t.tabs),n=vc(e,t.activeTabId);return{...t,tabs:e,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:A4,touchedAt:Date.now()}},Vv=(t,e)=>{const n=Xp(e),r=t.tabs.findIndex(l=>l.id===n.id),o=r===-1?[...t.tabs,n]:t.tabs.map((l,c)=>c===r?{...l,mode:n.mode,targetPath:n.targetPath,dedupeKey:n.dedupeKey,label:n.label,touchedAt:Date.now()}:l),a=n.id,i=e8(o,Zp,a);return{...t,isOpen:!0,tabs:i,activeTabId:vc(i,a),touchedAt:Date.now()}},Uv=(t,e)=>{const n=t.tabs.filter(o=>o.id!==e),r=t.activeTabId===e?n[n.length-1]?.id??null:vc(n,t.activeTabId);return{...t,tabs:n,activeTabId:r,isOpen:n.length>0?t.isOpen:!1,touchedAt:Date.now()}},Wv=(t,e,n)=>{if(e===n)return t;const r=t.tabs.findIndex(l=>l.id===e),o=t.tabs.findIndex(l=>l.id===n);if(r===-1||o===-1)return t;const a=[...t.tabs],[i]=a.splice(r,1);return i?(a.splice(o,0,i),{...t,tabs:a,touchedAt:Date.now()}):t},O2=t=>{if(!t||typeof t!="object")return{};const e=t,n={};for(const[r,o]of Object.entries(e)){const a=Wr(r);if(!a||!o||typeof o!="object")continue;const i=o;let l=t8(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;l.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat")&&(l=[Xp({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=l[0]?.id??null);const d=vc(l,c),u=e8(l,Zp,d);n[a]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:vc(u,d),width:Kp(typeof i.width=="number"?i.width:A4),touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},La=(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},De=xn()(In(hr((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:Nl,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:Cl,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,pendingFileNavigation:null,pendingFileFocusPath: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,chatRenderMode:"sorted",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,terminalFontSize:13,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],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:{...da.completion},error:{...da.error},question:{...da.question},subtask:{...da.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,inputSpellcheckEnabled:!1,showToolFileIcons:!0,showExpandedBashTools:!1,showExpandedEditTools:!1,mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",stickyUserHeader:!0,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:Nl}:{isSidebarOpen:r}})},setSidebarOpen:n=>{t(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==Nl?{isSidebarOpen:n,sidebarWidth:Nl}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:Nl}:{isSidebarOpen:n})},setSidebarWidth:n=>{t({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(n=>{const r=!n.isRightSidebarOpen;return r&&!n.hasManuallyResizedRightSidebar?{isRightSidebarOpen:r,rightSidebarWidth:Cl}:{isRightSidebarOpen:r}})},setRightSidebarOpen:n=>{t(r=>r.isRightSidebarOpen===n?n&&!r.hasManuallyResizedRightSidebar&&r.rightSidebarWidth!==Cl?{isRightSidebarOpen:n,rightSidebarWidth:Cl}:r:n&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:Cl}:{isRightSidebarOpen:n})},setRightSidebarWidth:n=>{t({rightSidebarWidth:n,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:n=>{t({rightSidebarTab:n})},openContextPanelTab:(n,r)=>{const o=Wr((n||"").trim());o&&t(a=>{const i=a.contextPanelByDirectory[o],l=Ra(i),c={...a.contextPanelByDirectory,[o]:Vv(l,r)};return{contextPanelByDirectory:La(c,20)}})},openContextDiff:(n,r)=>{const o=Wr((n||"").trim()),a=(r||"").trim();!o||!a||(e().openContextPanelTab(o,{mode:"diff",targetPath:a}),e().setPendingDiffFile(a))},openContextFile:(n,r)=>{const o=Wr((n||"").trim()),a=S0(r);!o||!a||(e().openContextPanelTab(o,{mode:"file",targetPath:a}),e().setPendingFileFocusPath(a),e().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,a)=>{const i=Wr((n||"").trim()),l=S0(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,d=Number.isFinite(a)?Math.max(1,Math.trunc(a)):1;!i||!l||(e().openContextPanelTab(i,{mode:"file",targetPath:l}),e().setPendingFileFocusPath(null),e().setPendingFileNavigation({path:l,line:c,column:d}))},openContextOverview:n=>{const r=Wr((n||"").trim());r&&e().openContextPanelTab(r,{mode:"context"})},openContextPlan:n=>{const r=Wr((n||"").trim());r&&e().openContextPanelTab(r,{mode:"plan"})},setActiveContextPanelTab:(n,r)=>{const o=Wr((n||"").trim()),a=(r||"").trim();!o||!a||t(i=>{const l=i.contextPanelByDirectory[o],c=Ra(l);if(!c.tabs.some(u=>u.id===a)||c.activeTabId===a&&c.isOpen)return i;const d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:a,touchedAt:Date.now(),tabs:c.tabs.map(u=>u.id===a?{...u,touchedAt:Date.now()}:u)}};return{contextPanelByDirectory:La(d,20)}})},reorderContextPanelTabs:(n,r,o)=>{const a=Wr((n||"").trim()),i=(r||"").trim(),l=(o||"").trim();!a||!i||!l||t(c=>{const d=c.contextPanelByDirectory[a],u=Ra(d);if(!u.tabs.some(p=>p.id===i)||!u.tabs.some(p=>p.id===l))return c;const m=Wv(u,i,l);if(m.tabs===u.tabs)return c;const h={...c.contextPanelByDirectory,[a]:m};return{contextPanelByDirectory:La(h,20)}})},closeContextPanelTab:(n,r)=>{const o=Wr((n||"").trim()),a=(r||"").trim();!o||!a||t(i=>{const l=i.contextPanelByDirectory[o],c=Ra(l);if(!c.tabs.some(u=>u.id===a))return i;const d={...i.contextPanelByDirectory,[o]:Uv(c,a)};return{contextPanelByDirectory:La(d,20)}})},closeContextPanel:n=>{const r=Wr((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r];if(!a||!a.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Ra(a),isOpen:!1}};return{contextPanelByDirectory:La(i,20)}})},toggleContextPanelExpanded:n=>{const r=Wr((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=Ra(a),l={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:La(l,20)}})},setContextPanelWidth:(n,r)=>{const o=Wr((n||"").trim());o&&t(a=>{const i=a.contextPanelByDirectory[o],l=Ra(i),c={...a.contextPanelByDirectory,[o]:{...l,width:Kp(r)}};return{contextPanelByDirectory:La(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})},setPendingFileNavigation:n=>{t({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{t({pendingFileFocusPath: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})},setChatRenderMode:n=>{t({chatRenderMode:n})},setActivityRenderMode:n=>{t({activityRenderMode: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})},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(M4);if(o===1){for(const[i]of a)r.style.removeProperty(z3(i));return}for(const[i,l]of a){const c=parseFloat(l);Number.isFinite(c)&&r.style.setProperty(z3(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)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&t(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},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 u=d.recentEfforts[l]??[];if(u.includes(c))return d;const m=u;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})},setInputSpellcheckEnabled:n=>{t({inputSpellcheckEnabled:n})},setShowToolFileIcons:n=>{t({showToolFileIcons:n})},setShowExpandedBashTools:n=>{t({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{t({showExpandedEditTools:n})},setMermaidRenderingMode:n=>{t({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{t({userMessageRenderingMode:n})},setStickyUserHeader:n=>{t({stickyUserHeader: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:xr(()=>Bn()),version:7,migrate:(t,e)=>{if(!t||typeof t!="object")return t;const n=t;if(e<1&&zv(n.notificationTemplates)&&(n.notificationTemplates={completion:{...da.completion},error:{...da.error},question:{...da.question},subtask:{...da.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=O2(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 e<6&&(n.contextPanelByDirectory=O2(n.contextPanelByDirectory)),e<7&&(n.contextPanelByDirectory=O2(n.contextPanelByDirectory)),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,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,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,inputSpellcheckEnabled:t.inputSpellcheckEnabled,showToolFileIcons:t.showToolFileIcons,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,stickyUserHeader:t.stickyUserHeader,showMobileSessionStatusBar:t.showMobileSessionStatusBar,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,shortcutOverrides:t.shortcutOverrides})}),{name:"ui-store"})),qv=({transform:t})=>({...t,y:0}),Gv=t=>{const e=Ce.c(18),{id:n,children:r,className:o}=t;let a;e[0]!==n?(a={id:n},e[0]=n,e[1]=a):a=e[1];const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:u,isDragging:m}=Tc(a);let h;e[2]!==d?(h=Pc.Transform.toString(d),e[2]=d,e[3]=h):h=e[3];let p;e[4]!==h||e[5]!==u?(p={transform:h,transition:u},e[4]=h,e[5]=u,e[6]=p):p=e[6];const g=m&&"opacity-50";let y;e[7]!==o||e[8]!==g?(y=J("h-full rounded-md",o,g),e[7]=o,e[8]=g,e[9]=y):y=e[9];let b;return e[10]!==i||e[11]!==r||e[12]!==n||e[13]!==l||e[14]!==c||e[15]!==p||e[16]!==y?(b=s.jsx("div",{ref:c,"data-sortable-tab-id":n,style:p,className:y,...i,...l,children:r}),e[10]=i,e[11]=r,e[12]=n,e[13]=l,e[14]=c,e[15]=p,e[16]=y,e[17]=b):b=e[17],b},Zv=t=>{const e=Ce.c(6),{id:n,children:r,className:o}=t;let a;e[0]!==o?(a=J("h-full",o),e[0]=o,e[1]=a):a=e[1];let i;return e[2]!==r||e[3]!==n||e[4]!==a?(i=s.jsx("div",{className:a,"data-sortable-tab-id":n,children:r}),e[2]=r,e[3]=n,e[4]=a,e[5]=i):i=e[5],i},Mo=t=>{const e=Ce.c(107),{items:n,activeId:r,onSelect:o,onClose:a,onReorder:i,layoutMode:l,variant:c,activePillInsetClassName:d,activePillButtonClassName:u,inactiveTabsIconOnly:m,animateActivePill:h,className:p}=t,g=l===void 0?"scrollable":l,y=c===void 0?"default":c,b=m===void 0?!1:m,x=De(Kv),v=f.useRef(null);let w;e[0]===Symbol.for("react.memo_cache_sentinel")?(w={left:!1,right:!1},e[0]=w):w=e[0];const[C,k]=f.useState(w);let N;e[1]!==n?(N=n.map(Qv),e[1]=n,e[2]=N):N=e[2];const S=N,j=g==="scrollable",A=y==="active-pill",M=y==="animated",F=A||M,B=A&&j,D=M,E=h??M,I=typeof i=="function",T=I?Gv:Zv;let H;e[3]===Symbol.for("react.memo_cache_sentinel")?(H=new Map,e[3]=H):H=e[3];const P=f.useRef(H),[_,R]=f.useState(null);let z;e[4]===Symbol.for("react.memo_cache_sentinel")?(z={activationConstraint:{distance:8}},e[4]=z):z=e[4];const O=Ic(li(Rc,z)),Q=Yv;let te;e[5]===Symbol.for("react.memo_cache_sentinel")?(te=(ke,Ze)=>{if(Ze){P.current.set(ke,Ze);return}P.current.delete(ke)},e[5]=te):te=e[5];const W=te;let U;e[6]!==r||e[7]!==F?(U=()=>{if(!F||!r){R(Jv);return}const ke=v.current,Ze=P.current.get(r);if(!ke||!Ze){R(Xv);return}const Je=ke.getBoundingClientRect(),Ye=Ze.getBoundingClientRect(),Re={left:Ye.left-Je.left+ke.scrollLeft,top:Ye.top-Je.top+ke.scrollTop,width:Ye.width,height:Ye.height};R(Ue=>Q(Ue,Re)?Ue:Re)},e[6]=r,e[7]=F,e[8]=U):U=e[8];const K=U;let q;e[9]!==j?(q=()=>{if(!j){k({left:!1,right:!1});return}const ke=v.current;if(!ke){k({left:!1,right:!1});return}k({left:ke.scrollLeft>2,right:ke.scrollLeft+ke.clientWidth<ke.scrollWidth-2})},e[9]=j,e[10]=q):q=e[10];const ee=q;let V;e[11]!==j||e[12]!==ee?(V=()=>{if(!j){k({left:!1,right:!1});return}const ke=v.current;if(!ke)return;ee(),ke.addEventListener("scroll",ee,{passive:!0});const Ze=new ResizeObserver(ee);return Ze.observe(ke),()=>{ke.removeEventListener("scroll",ee),Ze.disconnect()}},e[11]=j,e[12]=ee,e[13]=V):V=e[13];let G;e[14]!==j||e[15]!==n.length||e[16]!==ee?(G=[j,n.length,ee],e[14]=j,e[15]=n.length,e[16]=ee,e[17]=G):G=e[17],f.useEffect(V,G);let Y;e[18]!==r||e[19]!==K||e[20]!==F?(Y=()=>{if(!F){R(null);return}K();const ke=v.current;if(!ke)return;const Ze=new ResizeObserver(K);if(Ze.observe(ke),r){const Je=P.current.get(r);Je&&Ze.observe(Je)}return()=>{Ze.disconnect()}},e[18]=r,e[19]=K,e[20]=F,e[21]=Y):Y=e[21];let oe;e[22]!==r||e[23]!==n.length||e[24]!==K||e[25]!==F?(oe=[r,n.length,K,F],e[22]=r,e[23]=n.length,e[24]=K,e[25]=F,e[26]=oe):oe=e[26],f.useEffect(Y,oe);let re;e[27]!==K?(re=()=>{K()},e[27]=K,e[28]=re):re=e[28],f.useLayoutEffect(re);let fe;e[29]!==r||e[30]!==j||e[31]!==ee?(fe=()=>{if(!j||!r)return;const ke=v.current;if(!ke)return;const Ze=window.requestAnimationFrame(()=>{const Je=typeof window.CSS?.escape=="function"?window.CSS.escape(r):r.replace(/"/g,'\\"'),Ye=ke.querySelector(`[data-sortable-tab-id="${Je}"]`);Ye&&(Ye.scrollIntoView({block:"nearest",inline:"nearest"}),ee())});return()=>{window.cancelAnimationFrame(Ze)}},e[29]=r,e[30]=j,e[31]=ee,e[32]=fe):fe=e[32];let ie;e[33]!==r||e[34]!==j||e[35]!==n.length||e[36]!==ee?(ie=[r,j,n.length,ee],e[33]=r,e[34]=j,e[35]=n.length,e[36]=ee,e[37]=ie):ie=e[37],f.useEffect(fe,ie);let de;e[38]!==i?(de=ke=>{if(!i)return;const{active:Ze,over:Je}=ke;!Je||Ze.id===Je.id||i(String(Ze.id),String(Je.id))},e[38]=i,e[39]=de):de=e[39];const $=de;let L;e[40]!==p?(L=J("relative flex h-full min-w-0 flex-1",p),e[40]=p,e[41]=L):L=e[41];let X;e[42]!==j||e[43]!==C||e[44]!==F?(X=j&&!F&&C.left?s.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-6 bg-gradient-to-r from-background to-transparent"}):null,e[42]=j,e[43]=C,e[44]=F,e[45]=X):X=e[45];let ne;e[46]!==j||e[47]!==C||e[48]!==F?(ne=j&&!F&&C.right?s.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-6 bg-gradient-to-l from-background to-transparent"}):null,e[46]=j,e[47]=C,e[48]=F,e[49]=ne):ne=e[49];const se=F?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",pe=F&&"@container/pill-tabs",ae=F&&"pill-tabs__track",ve=F&&(d??"gap-0.5 py-0.5"),ce=D&&"rounded-lg bg-[var(--surface-muted)]/50",Z=j?"overflow-x-auto scrollbar-none":"overflow-x-hidden";let me;e[50]!==se||e[51]!==pe||e[52]!==ae||e[53]!==ve||e[54]!==ce||e[55]!==Z?(me=J("relative flex h-full min-w-0 flex-1",se,pe,ae,ve,ce,Z),e[50]=se,e[51]=pe,e[52]=ae,e[53]=ve,e[54]=ce,e[55]=Z,e[56]=me):me=e[56];let be;e[57]!==j?(be=j?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,e[57]=j,e[58]=be):be=e[58];let we;e[59]!==_||e[60]!==E||e[61]!==F?(we=F&&_?s.jsx("div",{className:J("pointer-events-none absolute left-0 top-0 z-0 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)]",E&&"transition-[transform,width,height] duration-200 ease-out"),style:{transform:`translate(${_.left}px, ${_.top}px)`,width:`${_.width}px`,height:`${_.height}px`}}):null,e[59]=_,e[60]=E,e[61]=F,e[62]=we):we=e[62];let Ae;if(e[63]!==T||e[64]!==r||e[65]!==u||e[66]!==b||e[67]!==A||e[68]!==x||e[69]!==j||e[70]!==n||e[71]!==a||e[72]!==o||e[73]!==B||e[74]!==F){let ke;e[76]!==T||e[77]!==r||e[78]!==u||e[79]!==b||e[80]!==A||e[81]!==x||e[82]!==j||e[83]!==a||e[84]!==o||e[85]!==B||e[86]!==F?(ke=Ze=>{const Je=Ze.id===r,Ye=b&&F&&!Je&&!!Ze.icon,Re=!Ye,Ue=b&&F&&Je&&!j&&!B,Ve=Ze.closable!==!1&&!!a,st=j||B?void 0:F?Ue?"flex-none basis-auto":x?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0";return s.jsx(T,{id:Ze.id,className:st,children:s.jsxs("div",{className:J("group flex h-full items-center",j||B?"shrink-0":F?"w-full":"w-full min-w-0",F?"relative z-10 bg-transparent":Je?"border-r border-border/40 bg-[var(--surface-elevated)] text-foreground":"border-r border-border/40 bg-[var(--surface-elevated)]/25 text-muted-foreground hover:bg-[var(--surface-elevated)]/65 hover:text-foreground"),children:[s.jsx("button",{ref:at=>W(Ze.id,at),type:"button",role:"tab","aria-selected":Je,"aria-label":Ye?Ze.title??Ze.label:void 0,onClick:()=>o(Ze.id),className:J(F?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 items-center justify-center rounded-lg text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 items-center typography-micro",F&&(Ye?"gap-0":"gap-1.5"),F?B?"shrink-0 whitespace-nowrap px-3 text-center":j?"max-w-56 shrink-0 px-3 text-center":Ye?"px-2 !min-w-0 text-center":Ue?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":j?"max-w-56 justify-start truncate pl-3 pr-2 text-left":"w-full justify-center truncate px-2.5 text-center",F?u??(A?x?"h-[34px]":"h-[27px]":"h-7"):null,F?Je?"text-foreground":"text-muted-foreground hover:text-foreground":null,F?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:Ze.title??Ze.label,children:F?s.jsxs(s.Fragment,{children:[Ze.icon?s.jsx("span",{className:"flex shrink-0 items-center justify-center",children:Ze.icon}):null,Re?s.jsx("span",{className:"animated-tabs__label truncate",children:Ze.label}):null]}):s.jsxs("span",{className:J("flex min-w-0 items-center gap-1.5",!j&&"justify-center"),children:[Ze.icon?s.jsx("span",{className:"flex shrink-0 items-center justify-center",children:Ze.icon}):null,s.jsx("span",{className:"truncate leading-[1.2]",children:Ze.label})]})}),Ve?s.jsx("button",{type:"button",onClick:at=>{at.stopPropagation(),a?.(Ze.id)},className:J("mr-1 inline-flex aspect-square h-[65%] min-h-4 max-h-5 !min-h-0 !min-w-0 items-center justify-center rounded-sm transition-opacity",Je?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":Ze.closeLabel??`Close ${Ze.label} tab`,title:Ze.closeLabel??`Close ${Ze.label} tab`,children:s.jsx(_s,{className:"h-3 w-3"})}):null]})},Ze.id)},e[76]=T,e[77]=r,e[78]=u,e[79]=b,e[80]=A,e[81]=x,e[82]=j,e[83]=a,e[84]=o,e[85]=B,e[86]=F,e[87]=ke):ke=e[87],Ae=n.map(ke),e[63]=T,e[64]=r,e[65]=u,e[66]=b,e[67]=A,e[68]=x,e[69]=j,e[70]=n,e[71]=a,e[72]=o,e[73]=B,e[74]=F,e[75]=Ae}else Ae=e[75];let Pe;e[88]!==me||e[89]!==be||e[90]!==we||e[91]!==Ae?(Pe=s.jsxs("div",{ref:v,className:me,style:be,role:"tablist","aria-label":"Tabs",children:[we,Ae]}),e[88]=me,e[89]=be,e[90]=we,e[91]=Ae,e[92]=Pe):Pe=e[92];let xe;e[93]!==L||e[94]!==X||e[95]!==ne||e[96]!==Pe?(xe=s.jsxs("div",{className:L,children:[X,ne,Pe]}),e[93]=L,e[94]=X,e[95]=ne,e[96]=Pe,e[97]=xe):xe=e[97];const _e=xe;if(!I)return _e;let ze;e[98]===Symbol.for("react.memo_cache_sentinel")?(ze=[qv],e[98]=ze):ze=e[98];let le;e[99]!==S||e[100]!==_e?(le=s.jsx(s2,{items:S,strategy:Fy,children:_e}),e[99]=S,e[100]=_e,e[101]=le):le=e[101];let ge;e[102]===Symbol.for("react.memo_cache_sentinel")?(ge=s.jsx(m4,{dropAnimation:null}),e[102]=ge):ge=e[102];let Fe;return e[103]!==$||e[104]!==O||e[105]!==le?(Fe=s.jsxs(Lc,{sensors:O,collisionDetection:zc,onDragEnd:$,modifiers:ze,children:[le,ge]}),e[103]=$,e[104]=O,e[105]=le,e[106]=Fe):Fe=e[106],Fe};function Kv(t){return t.isMobile}function Qv(t){return t.id}function Yv(t,e){return!t||!e?t===e:Math.abs(t.left-e.left)<.5&&Math.abs(t.top-e.top)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5}function Jv(t){return t===null?t:null}function Xv(t){return t===null?t:null}function O3(t){const e=Ce.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 u;return e[10]!==n||e[11]!==r||e[12]!==c?(u=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]=u):u=e[13],u}const ew="/api",tw=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,sw=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(tw.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}},nw=()=>{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},Ml=t=>t.replace(/\\/g,"/"),$3=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class rw{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();globalSseAbortController=null;globalSseTask=null;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;globalSseQueue=[];globalSseBuffer=[];globalSseCoalesced=new Map;globalSseStaleDeltas=new Set;globalSseFlushTimer=null;globalSseLastFlushAt=0;constructor(e=ew){const r=nw()||e;this.baseUrl=sw(r),this.client=S3({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=S3({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 cr(async()=>{const{default:m}=await import("./vendor-.bun-9lzLHWe8.js").then(h=>h.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,h)=>{const p=new FileReader;p.onload=()=>m(p.result),p.onerror=h,p.readAsDataURL(c)});let u=e.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,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 u=await this.toNormalizedFilePartInput(d);o.push(u)}}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 u=d&&d.trim().length>0?`: ${d.trim()}`:"";throw new Error(`Failed to run command (${c.status})${u}`)}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 u=d.id;typeof u!="string"||u.length===0||l.has(u)||(l.add(u),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 u=d.id;typeof u!="string"||u.length===0||l.has(u)||(l.add(u),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[]}}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(),this.globalSseStaleDeltas.clear()}getGlobalSseDeltaKey(e){const n=e.payload;if((typeof n.type=="string"?n.type:null)!=="message.part.delta")return null;const o=typeof n.properties=="object"&&n.properties!==null?n.properties:null,a=typeof o?.messageID=="string"?o.messageID:typeof o?.messageId=="string"?o.messageId:null,i=typeof o?.partID=="string"?o.partID:typeof o?.partId=="string"?o.partId:null;return!a||!i?null:`${e.directory}:${a}:${i}`}getGlobalSseUpdatedPartKey(e){const n=e.payload;if((typeof n.type=="string"?n.type:null)!=="message.part.updated")return null;const o=typeof n.properties=="object"&&n.properties!==null?n.properties:null,a=o?.part&&typeof o.part=="object"?o.part:null,i=typeof a?.messageID=="string"?a.messageID:typeof a?.messageId=="string"?a.messageId:null,l=typeof a?.id=="string"?a.id:typeof a?.partID=="string"?a.partID:typeof a?.partId=="string"?a.partId:null;return!i||!l?null:`${e.directory}:${i}:${l}`}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}if(r==="message.part.updated"){const a=this.getGlobalSseUpdatedPartKey(e);return a?`message.part.updated:${a}`:null}return null}flushGlobalSseQueue=()=>{if(this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length===0)return;const e=this.globalSseQueue,n=this.globalSseStaleDeltas.size>0?new Set(this.globalSseStaleDeltas):void 0;this.globalSseQueue=this.globalSseBuffer,this.globalSseBuffer=e,this.globalSseQueue.length=0,this.globalSseCoalesced.clear(),this.globalSseStaleDeltas.clear(),this.globalSseLastFlushAt=Date.now();for(const r of e)if(r){if(n){const o=this.getGlobalSseDeltaKey(r);if(o&&n.has(o))continue}for(const o of this.globalSseListeners)try{o(r)}catch(a){console.warn("[OpencodeClient] Global SSE listener error:",a)}}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);if(r!==void 0){this.globalSseQueue[r]=void 0;const o=this.getGlobalSseUpdatedPartKey(e);o&&this.globalSseStaleDeltas.add(o)}this.globalSseCoalesced.set(n,this.globalSseQueue.length)}this.globalSseQueue.push(e),this.scheduleGlobalSseFlush()}async runGlobalSseLoop(e){let n=0;const r=250,o=8,a=i=>new Promise(l=>setTimeout(l,i));for(;!e.signal.aborted;){try{const i=await this.client.global.event({signal:e.signal,onSseError:c=>{c?.name==="AbortError"||e.signal.aborted||this.notifyGlobalSseError(c)}});n=0,this.globalSseIsConnected=!0,e.signal.aborted||this.notifyGlobalSseOpen();let l=Date.now();for await(const c of i.stream){if(e.signal.aborted)break;const d=typeof c.directory=="string"&&c.directory.length>0?c.directory:"global",u=this.normalizeRoutedSsePayload({directory:d,payload:c.payload});u&&(this.emitGlobalSseEvent(u),Date.now()-l>=o&&(l=Date.now(),await a(0)))}this.globalSseIsConnected=!1}catch(i){if(this.globalSseIsConnected=!1,i?.name==="AbortError"||e.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",i),this.notifyGlobalSseError(i)}if(e.signal.aborted)break;n+=1,await a(Math.min(r*Math.max(n,1),2e3))}this.flushGlobalSseQueue()}subscribeToGlobalEvents(e,n,r,o){const a=this.normalizeCandidatePath(o?.directory??null),i=l=>{a&&l.directory!==a||e(l)};return this.globalSseListeners.add(i),r&&(this.globalSseOpenListeners.add(r),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(r))try{r()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),n&&this.globalSseErrorListeners.add(n),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),r&&this.globalSseOpenListeners.delete(r),n&&this.globalSseErrorListeners.delete(n),this.maybeStopGlobalSse()}}subscribeToEvents(e,n,r,o,a){const i=a?.key??"default",l=a?.scope??"directory",c=this.sseAbortControllers.get(i);c&&c.abort();const d=new AbortController;this.sseAbortControllers.set(i,d);let u;if(l==="global"){let h=null;const p=y=>{if(y.directory==="global")return y.payload;const b=y.payload,x=typeof b.properties=="object"&&b.properties!==null?b.properties:{};return x.directory===y.directory?y.payload:{...b,properties:{...x,directory:y.directory}}},g=()=>{if(h){try{h()}catch{}h=null}this.sseAbortControllers.get(i)===d&&this.sseAbortControllers.delete(i)};return d.signal.addEventListener("abort",g,{once:!0}),h=this.subscribeToGlobalEvents(y=>{d.signal.aborted||e(p(y))},n?y=>{d.signal.aborted||n(y)}:void 0,r?()=>{d.signal.aborted||r()}:void 0),()=>{g(),d.abort()}}const m=h=>{if(!h||typeof h!="object")return null;const p=h;if(typeof p.type=="string")return p;const g=p.payload;if(g&&typeof g=="object"){const y=g;if(typeof y.type=="string"){if(typeof p.directory=="string"&&p.directory.length>0){const x={...(typeof y.properties=="object"&&y.properties!==null?y.properties:null)??{},directory:p.directory};return{...y,properties:x}}return y}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const h=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",h??"default");const p=async g=>{try{const y=h?{directory:h}:void 0,b={signal:d.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),n&&!d.signal.aborted&&n(v))},onSseEvent:v=>{if(d.signal.aborted)return;v.id&&typeof v.id=="string"&&(u=v.id);const w=v.data,C=m(w);C&&e(C)}};u&&(b.headers={...b.headers||{},"Last-Event-ID":u});const x=await this.client.event.subscribe(y,b);r&&!d.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),r());for await(const v of x.stream)if(d.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(y){if(y?.name==="AbortError"||d.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",y),n&&n(y);const b=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(x=>setTimeout(x,b)),d.signal.aborted||await p(g+1);return}if(!d.signal.aborted){const y=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(b=>setTimeout(b,y)),await p(g+1)}};try{await p(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===d&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===d&&this.sseAbortControllers.delete(i),d.abort()}}async readFile(e){try{const n=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,directory:this.currentDirectory})});if(!n.ok)throw new Error(`Failed to read file: ${n.statusText}`);return await n.text()}catch{return`// Content of ${e}
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-9lzLHWe8.js","assets/vendor--DbVqbJpV.css","assets/ToolOutputDialog-CM2Xnf7u.js","assets/index-TlwNP07y.js","assets/index-JYxeZFeM.css"])))=>i.map(i=>d[i]);
2
+ import{t as iy,c as ly,F as cy,a as Ce,j as s,R as dy,T as uy,P as fy,C as my,b as hy,A as py,L as gy,d as yy,S as by,e as xy,f as vy,g as wy,i as jy,k as Sy,I as ky,l as Ny,m as Cy,n as My,o as Ay,s as vs,r as Un,p as xn,q as In,u as hr,v as xr,w as f,x as Ic,y as li,z as Tc,B as Pc,D as Rc,E as _s,G as s2,H as Fy,J as m4,K as Lc,M as zc,N as S3,_ as cr,X as Dy,O as uo,Q as ep,U as tp,V as _y,W as n2,Y as r2,Z as gc,$ as By,a0 as tu,a1 as h4,a2 as Aa,a3 as Ey,a4 as sp,a5 as Iy,a6 as Ty,a7 as Py,a8 as o2,a9 as p4,aa as Lo,ab as np,ac as Ry,ad as Ne,ae as Ly,af as rp,ag as Wn,ah as zy,ai as Hy,aj as Oy,ak as g4,al as op,am as ap,an as $y,ao as ip,ap as lp,aq as Vy,ar as cp,as as Uy,at as Wy,au as qy,av as kl,aw as ta,ax as mo,ay as y4,az as Ln,aA as os,aB as b4,aC as To,aD as ei,aE as V1,aF as Xs,aG as dp,aH as Gy,aI as Zy,aJ as Ls,aK as Jn,aL as ka,aM as Ky,aN as Yi,aO as Hc,aP as Qy,aQ as ci,aR as cn,aS as ur,aT as $o,aU as oa,aV as $r,aW as Ba,aX as yc,aY as Po,aZ as a2,a_ as ya,a$ as su,b0 as bc,b1 as h0,b2 as Yy,b3 as ti,b4 as Na,b5 as p0,b6 as i2,b7 as Co,b8 as jr,b9 as Jy,ba as Xy,bb as up,bc as eb,bd as tb,be as aa,bf as sb,bg as U1,bh as nb,bi as il,bj as yr,bk as di,bl as rb,bm as ob,bn as x4,bo as bl,bp as _n,bq as v4,br as w4,bs as fp,bt as mp,bu as ab,bv as ib,bw as Jl,bx as g0,by as ui,bz as fi,bA as lb,bB as sa,bC as cb,bD as db,bE as Qr,bF as ub,bG as mi,bH as Yo,bI as fb,bJ as ao,bK as xc,bL as mb,bM as hb,bN as hp,bO as Fa,bP as l2,bQ as pb,bR as gb,bS as Ya,bT as pp,bU as gp,bV as W1,bW as yb,bX as ll,bY as hi,bZ as go,b_ as zo,b$ as Ho,c0 as Jo,c1 as nu,c2 as yp,c3 as xa,c4 as Fo,c5 as bb,c6 as xb,c7 as Xl,c8 as vb,c9 as wb,ca as bp,cb as jb,cc as xp,cd as Sb,ce as kb,cf as Nb,cg as Cb,ch as vp,ci as si,cj as j4,ck as ru,cl as Mb,cm as Ab,cn as Fb,co as Db,cp as k3,cq as N3,cr as C3,cs as c2,ct as _b,cu as Bb,cv as oo,cw as Eb,cx as xl,cy as M3,cz as Ib,cA as Tb,cB as R2,cC as Pb,cD as Rb,cE as Lb,cF as A3,cG as zb,cH as wp,cI as jp,cJ as Hb,cK as F3,cL as Ob,cM as $b,cN as Vb,cO as Ub,cP as S4,cQ as k4,cR as Wb,cS as ou,cT as kt,cU as Gl,cV as qb,cW as Gb,cX as ji,cY as Zb,cZ as Kb,c_ as Qb,c$ as Yb,d0 as Jb,d1 as Xb,d2 as ex,d3 as tx,d4 as y0,d5 as Sp,d6 as kp,d7 as Np,d8 as Cp,d9 as Mp,da as Ap,db as Fp,dc as sx,dd as Dp,de as _p,df as Hi,dg as Bp,dh as Ep,di as au,dj as Si,dk as Ip,dl as iu,dm as nx,dn as N4,dp as rx,dq as ox,dr as ec,ds as d2,dt as ax,du as ix,dv as lx,dw as cx,dx,dy as ux,dz as fx,dA as mx,dB as hx,dC as px,dD as gx,dE as yx,dF as bx,dG as xx,dH as ni,dI as vx,dJ as wx,dK as jx,dL as Sx,dM as kx,dN as Nx,dO as Cx,dP as lu,dQ as Mx,dR as Ax,dS as Fx,dT as b0,dU as D3,dV as _3,dW as u2,dX as Dx,dY as Tp,dZ as Pp,d_ as Rp,d$ as Lp,e0 as Tr,e1 as _x,e2 as Bx,e3 as x0,e4 as zp,e5 as cu,e6 as Ex,e7 as Ix,e8 as q1,e9 as Tx,ea as Px,eb as Rx,ec as Lx,ed as Hp,ee as du,ef as zx,eg as Hx,eh as Ox,ei as Op,ej as $x,ek as Vx,el as Ux,em as Wx,en as qx,eo as Gx,ep as Zx,eq as Kx,er as Qx,es as Yx,et as Jx,eu as Xx,ev,ew as tv,ex as uu,ey as sv,ez as B3,eA as E3,eB as nv,eC as t1,eD as G1,eE as rv,eF as ov,eG as L2,eH as I3,eI as av,eJ as iv,eK as lv,eL as cv,eM as dv}from"./vendor-.bun-9lzLHWe8.js";import{c as uv,l as fv,d as mv,a as hv,v as pv,g as gv,b as yv,e as bv,u as xv,f as vv,h as wv,i as jv,j as Sv,k as kv,m as Nv,n as Cv,o as Mv,p as Av,q as Fv}from"./index-TlwNP07y.js";const Gs=()=>typeof window>"u"?!1:typeof window.__TAURI__?.core?.invoke=="function",T3=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}}},P3=t=>{const e=t.trim();if(!e)return null;try{return new URL(e)}catch{try{return new URL(e.endsWith("/")?e:`${e}/`)}catch{return null}}},Dv=t=>t.replace(/^\[|\]$/g,"").toLowerCase(),R3=t=>{const e=Dv(t);return e==="localhost"||e==="127.0.0.1"||e==="::1"},ar=()=>{if(typeof window>"u")return!1;const t=typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"?window.__OPENCHAMBER_LOCAL_ORIGIN__:"",e=P3(t),n=P3(window.location.origin);if(e&&n){if(e.origin===n.origin)return!0;const a=e.port||(e.protocol==="https:"?"443":"80"),i=n.port||(n.protocol==="https:"?"443":"80");return e.protocol===n.protocol&&a===i&&R3(e.hostname)&&R3(n.hostname)}const r=T3(t),o=T3(window.location.origin)||window.location.origin;return!!(r&&o&&r===o)},Xn=()=>typeof window>"u"?!1:typeof window.__OPENCHAMBER_LOCAL_ORIGIN__=="string"&&window.__OPENCHAMBER_LOCAL_ORIGIN__.length>0?!0:Gs(),ln=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Uo=()=>{if(typeof window>"u")return!1;const e=window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.platform;return e==="web"?!0:e==="desktop"||e==="vscode"?!1:!ln()},f2=async()=>{if(typeof window<"u"){const t=window.__OPENCHAMBER_HOME__;if(t&&t.length>0)return t}return null},Oc=async t=>{if(Gs()&&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}},$p=async t=>{if(Gs()&&ar())try{const n=await window.__TAURI__?.dialog?.open?.({directory:!1,multiple:!1,title:"Select File",...t?.filters?{filters:t.filters}:{}});return!n||typeof n!="string"?{success:!1,error:"File selection cancelled"}:{success:!0,path:n}}catch(e){return console.warn("Failed to request file access (tauri)",e),{success:!1,error:e instanceof Error?e.message:String(e)}}return{success:!1,error:"Native file picker not available"}},Vp=async t=>({success:!0}),Up=async t=>({success:!0}),Wp=async()=>{if(!Gs()||!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}},qp=async t=>{if(!Gs()||!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 u=d?.downloaded,m=d?.total;typeof u=="number"&&(r=u),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{}}},Gp=async()=>{if(!Gs()||!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}},tc=async(t,e)=>{if(!Gs()||!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}},C4=async(t,e,n,r)=>{if(!Gs()||!ar())return!1;const o=t?.trim(),a=e?.trim(),i=n?.trim(),l=typeof r=="string"?r.trim():"";if(!o||!a||!i)return!1;try{return await window.__TAURI__?.core?.invoke?.("desktop_open_in_app",{projectPath:o,appId:a,appName:i,filePath:l.length>0?l:void 0}),!0}catch(c){return console.warn("Failed to open project in app (tauri)",c),!1}},fu=async(t,e)=>{if(!Gs()||!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}}},_v=Object.freeze(Object.defineProperty({__proto__:null,checkForDesktopUpdates:Wp,downloadDesktopUpdate:qp,fetchDesktopInstalledApps:fu,getDesktopHomeDirectory:f2,isDesktopLocalOriginActive:ar,isDesktopShell:Xn,isTauriShell:Gs,isVSCodeRuntime:ln,isWebRuntime:Uo,openDesktopPath:tc,openDesktopProjectInApp:C4,requestDirectoryAccess:Oc,requestFileAccess:$p,restartToApplyUpdate:Gp,startAccessingDirectory:Vp,stopAccessingDirectory:Up},Symbol.toStringTag,{value:"Module"}));function J(...t){return iy(ly(t))}const pi=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),m2=t=>pi()&&Gs()?t.metaKey:t.ctrlKey,Oi=()=>pi()&&Gs()?"⌘":"Ctrl",L3=(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}`},v0=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function na(t,e){if(!t)return"";const n=v0(t);if(n==="/")return"/";const r=e?v0(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 fo(t,e){if(!t)return"/";const n=v0(t);if(!n||n==="/")return"/";const r=e?v0(e):void 0;return r&&r!=="/"&&n===r?"~":n.split("/").pop()||n||"/"}function Ja(t,e){return e?t?t.toLowerCase().includes(e.toLowerCase())?!0:new cy([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(e).length>0:!1:!0}function $i(t){const e=Ce.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(hy,{"data-slot":"tooltip-provider",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Vt(t){const e=Ce.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(dy,{"data-slot":"tooltip",delayDuration:o,...n}),e[3]=o,e[4]=n,e[5]=a):a=e[5],a}function Ut(t){const e=Ce.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(uy,{"data-slot":"tooltip-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function $t(t){const e=Ce.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=J("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(py,{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(fy,{children:s.jsxs(my,{"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 zs(t){const e=Ce.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(vy,{"data-slot":"dropdown-menu",...n}),e[2]=n,e[3]=r):r=e[3],r}function Hs(t){const e=Ce.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(wy,{"data-slot":"dropdown-menu-trigger",...n}),e[2]=n,e[3]=r):r=e[3],r}function Os(t){const e=Ce.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=J("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(jy,{children:s.jsx(Sy,{"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 Qt(t){const e=Ce.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=J("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-pointer 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(ky,{"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 w0(t){const e=Ce.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(yy,{"data-slot":"dropdown-menu-radio-group",...n}),e[2]=n,e[3]=r):r=e[3],r}function h2(t){const e=Ce.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=J("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-pointer 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(Ay,{children:s.jsx(vs,{className:"size-3"})})}),e[6]=i):i=e[6];let l;return e[7]!==n||e[8]!==o||e[9]!==a?(l=s.jsxs(xy,{"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=Ce.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=J("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(gy,{"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 Rn(t){const e=Ce.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=J("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(by,{"data-slot":"dropdown-menu-separator",className:o,...r}),e[5]=r,e[6]=o,e[7]=a):a=e[7],a}function Bv(t){const e=Ce.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(Ny,{"data-slot":"dropdown-menu-sub",...n}),e[2]=n,e[3]=r):r=e[3],r}function Ev(t){const e=Ce.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=J("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer 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(Un,{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(Cy,{"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 Iv(t){const e=Ce.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=J("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(My,{"data-slot":"dropdown-menu-sub-content",style:o,className:a,...r}),e[6]=r,e[7]=a,e[8]=i):i=e[8],i}let z2=null,H2=null;const j0=()=>{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}}},Tv=()=>{if(typeof window>"u"||!window.localStorage)return j0();const t=window.localStorage,e=j0();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const u=t.getItem(d);if(u!==null)return u}catch{r()}return e.getItem(d)},setItem:(d,u)=>{if(n)try{t.setItem(d,u),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,u)},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}}},Bn=()=>(z2||(z2=Tv()),z2),Pv=()=>{if(typeof window>"u"||!window.sessionStorage)return j0();const t=window.sessionStorage,e=j0();let n=!0;const r=()=>{n=!1};return{getItem:d=>{if(n)try{const u=t.getItem(d);if(u!==null)return u}catch{r()}return e.getItem(d)},setItem:(d,u)=>{if(n)try{t.setItem(d,u),e.removeItem(d);return}catch{r();try{t.removeItem(d)}catch{}}e.setItem(d,u)},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}}},Rv=()=>(H2||(H2=Pv()),H2),M4={markdown:"0.9375rem",code:"0.8125rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Lv={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function z3(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Xo={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)"}}},Z1={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Xo.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Z1.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Xo.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Z1.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Xo.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Z1.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Xo.tool.inline})},s1={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}"}},da={completion:{title:"",message:""},error:{title:"",message:""},question:{title:"",message:""},subtask:{title:"",message:""}},n1=(t,e)=>t?t.title===e.title&&t.message===e.message:!1,zv=t=>{if(!t||typeof t!="object")return!1;const e=t;return n1(e.completion,s1.completion)&&n1(e.error,s1.error)&&n1(e.question,s1.question)&&n1(e.subtask,s1.subtask)},A4=600,Hv=360,Ov=1400,Zp=12,H3=120,Nl=300,Cl=400,Wr=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},Kp=t=>Number.isFinite(t)?Math.min(Ov,Math.max(Hv,Math.round(t))):A4,S0=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.replace(/\\/g,"/"):null},Qp=t=>{if(typeof t!="string")return null;const e=t.trim();return e?e.length>H3?e.slice(0,H3):e:null},$v=(t,e)=>t==="file"&&e||t,Yp=(t,e,n)=>{if(typeof n=="string"){const r=n.trim();if(r)return r}return $v(t,e)},Jp=(t,e)=>e===t?t:`${t}:${e}`,Xp=t=>{const e=S0(t.targetPath),n=Yp(t.mode,e,t.dedupeKey);return{id:Jp(t.mode,n),mode:t.mode,targetPath:e,dedupeKey:n,label:Qp(t.label),touchedAt:Date.now()}},e8=(t,e,n)=>{if(t.length<=e)return t;const o=[...t].sort((l,c)=>l.touchedAt-c.touchedAt).filter(l=>l.id!==n),a=t.length-e;if(a<=0||o.length===0)return t.slice(-e);const i=new Set(o.slice(0,a).map(l=>l.id));return t.filter(l=>!i.has(l.id))},t8=t=>{if(!Array.isArray(t))return[];const e=[],n=new Set;for(const r of t){if(!r||typeof r!="object")continue;const o=r;if(o.mode!=="diff"&&o.mode!=="file"&&o.mode!=="context"&&o.mode!=="plan"&&o.mode!=="chat")continue;const a=S0(typeof o.targetPath=="string"?o.targetPath:null),i=Yp(o.mode,a,typeof o.dedupeKey=="string"?o.dedupeKey:null),l=Jp(o.mode,i);!l||n.has(l)||(n.add(l),e.push({id:l,mode:o.mode,targetPath:a,dedupeKey:i,label:Qp(typeof o.label=="string"?o.label:null),touchedAt:typeof o.touchedAt=="number"&&Number.isFinite(o.touchedAt)?o.touchedAt:Date.now()}))}return e},vc=(t,e)=>e&&t.some(n=>n.id===e)?e:t.length===0?null:t[t.length-1].id,Ra=t=>{if(t){const e=t8(t.tabs),n=vc(e,t.activeTabId);return{...t,tabs:e,activeTabId:n,touchedAt:Date.now()}}return{isOpen:!1,expanded:!1,tabs:[],activeTabId:null,width:A4,touchedAt:Date.now()}},Vv=(t,e)=>{const n=Xp(e),r=t.tabs.findIndex(l=>l.id===n.id),o=r===-1?[...t.tabs,n]:t.tabs.map((l,c)=>c===r?{...l,mode:n.mode,targetPath:n.targetPath,dedupeKey:n.dedupeKey,label:n.label,touchedAt:Date.now()}:l),a=n.id,i=e8(o,Zp,a);return{...t,isOpen:!0,tabs:i,activeTabId:vc(i,a),touchedAt:Date.now()}},Uv=(t,e)=>{const n=t.tabs.filter(o=>o.id!==e),r=t.activeTabId===e?n[n.length-1]?.id??null:vc(n,t.activeTabId);return{...t,tabs:n,activeTabId:r,isOpen:n.length>0?t.isOpen:!1,touchedAt:Date.now()}},Wv=(t,e,n)=>{if(e===n)return t;const r=t.tabs.findIndex(l=>l.id===e),o=t.tabs.findIndex(l=>l.id===n);if(r===-1||o===-1)return t;const a=[...t.tabs],[i]=a.splice(r,1);return i?(a.splice(o,0,i),{...t,tabs:a,touchedAt:Date.now()}):t},O2=t=>{if(!t||typeof t!="object")return{};const e=t,n={};for(const[r,o]of Object.entries(e)){const a=Wr(r);if(!a||!o||typeof o!="object")continue;const i=o;let l=t8(i.tabs),c=typeof i.activeTabId=="string"?i.activeTabId:null;l.length===0&&(i.mode==="diff"||i.mode==="file"||i.mode==="context"||i.mode==="plan"||i.mode==="chat")&&(l=[Xp({mode:i.mode,targetPath:typeof i.targetPath=="string"?i.targetPath:null,dedupeKey:typeof i.dedupeKey=="string"?i.dedupeKey:null,label:typeof i.label=="string"?i.label:null})],c=l[0]?.id??null);const d=vc(l,c),u=e8(l,Zp,d);n[a]={isOpen:i.isOpen===!0,expanded:i.expanded===!0,tabs:u,activeTabId:vc(u,d),width:Kp(typeof i.width=="number"?i.width:A4),touchedAt:typeof i.touchedAt=="number"&&Number.isFinite(i.touchedAt)?i.touchedAt:Date.now()}}return n},La=(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},De=xn()(In(hr((t,e)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:Nl,hasManuallyResizedLeftSidebar:!1,isRightSidebarOpen:!1,rightSidebarWidth:Cl,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,pendingFileNavigation:null,pendingFileFocusPath: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,chatRenderMode:"sorted",activityRenderMode:"summary",showDeletionDialog:!0,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,messageLimit:200,fontSize:100,terminalFontSize:13,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],hiddenModels:[],collapsedModelProviders:[],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:{...da.completion},error:{...da.error},question:{...da.question},subtask:{...da.subtask}},summarizeLastMessage:!1,summaryThreshold:200,summaryLength:100,maxLastMessageLength:250,showTerminalQuickKeysOnDesktop:!1,persistChatDraft:!0,inputSpellcheckEnabled:!1,showToolFileIcons:!0,showExpandedBashTools:!1,showExpandedEditTools:!1,mermaidRenderingMode:"svg",userMessageRenderingMode:"markdown",stickyUserHeader:!0,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:Nl}:{isSidebarOpen:r}})},setSidebarOpen:n=>{t(r=>r.isSidebarOpen===n?n&&!r.hasManuallyResizedLeftSidebar&&r.sidebarWidth!==Nl?{isSidebarOpen:n,sidebarWidth:Nl}:r:n&&!r.hasManuallyResizedLeftSidebar?{isSidebarOpen:n,sidebarWidth:Nl}:{isSidebarOpen:n})},setSidebarWidth:n=>{t({sidebarWidth:n,hasManuallyResizedLeftSidebar:!0})},toggleRightSidebar:()=>{t(n=>{const r=!n.isRightSidebarOpen;return r&&!n.hasManuallyResizedRightSidebar?{isRightSidebarOpen:r,rightSidebarWidth:Cl}:{isRightSidebarOpen:r}})},setRightSidebarOpen:n=>{t(r=>r.isRightSidebarOpen===n?n&&!r.hasManuallyResizedRightSidebar&&r.rightSidebarWidth!==Cl?{isRightSidebarOpen:n,rightSidebarWidth:Cl}:r:n&&!r.hasManuallyResizedRightSidebar?{isRightSidebarOpen:n,rightSidebarWidth:Cl}:{isRightSidebarOpen:n})},setRightSidebarWidth:n=>{t({rightSidebarWidth:n,hasManuallyResizedRightSidebar:!0})},setRightSidebarTab:n=>{t({rightSidebarTab:n})},openContextPanelTab:(n,r)=>{const o=Wr((n||"").trim());o&&t(a=>{const i=a.contextPanelByDirectory[o],l=Ra(i),c={...a.contextPanelByDirectory,[o]:Vv(l,r)};return{contextPanelByDirectory:La(c,20)}})},openContextDiff:(n,r)=>{const o=Wr((n||"").trim()),a=(r||"").trim();!o||!a||(e().openContextPanelTab(o,{mode:"diff",targetPath:a}),e().setPendingDiffFile(a))},openContextFile:(n,r)=>{const o=Wr((n||"").trim()),a=S0(r);!o||!a||(e().openContextPanelTab(o,{mode:"file",targetPath:a}),e().setPendingFileFocusPath(a),e().setPendingFileNavigation(null))},openContextFileAtLine:(n,r,o,a)=>{const i=Wr((n||"").trim()),l=S0(r),c=Number.isFinite(o)?Math.max(1,Math.trunc(o)):1,d=Number.isFinite(a)?Math.max(1,Math.trunc(a)):1;!i||!l||(e().openContextPanelTab(i,{mode:"file",targetPath:l}),e().setPendingFileFocusPath(null),e().setPendingFileNavigation({path:l,line:c,column:d}))},openContextOverview:n=>{const r=Wr((n||"").trim());r&&e().openContextPanelTab(r,{mode:"context"})},openContextPlan:n=>{const r=Wr((n||"").trim());r&&e().openContextPanelTab(r,{mode:"plan"})},setActiveContextPanelTab:(n,r)=>{const o=Wr((n||"").trim()),a=(r||"").trim();!o||!a||t(i=>{const l=i.contextPanelByDirectory[o],c=Ra(l);if(!c.tabs.some(u=>u.id===a)||c.activeTabId===a&&c.isOpen)return i;const d={...i.contextPanelByDirectory,[o]:{...c,isOpen:!0,activeTabId:a,touchedAt:Date.now(),tabs:c.tabs.map(u=>u.id===a?{...u,touchedAt:Date.now()}:u)}};return{contextPanelByDirectory:La(d,20)}})},reorderContextPanelTabs:(n,r,o)=>{const a=Wr((n||"").trim()),i=(r||"").trim(),l=(o||"").trim();!a||!i||!l||t(c=>{const d=c.contextPanelByDirectory[a],u=Ra(d);if(!u.tabs.some(p=>p.id===i)||!u.tabs.some(p=>p.id===l))return c;const m=Wv(u,i,l);if(m.tabs===u.tabs)return c;const h={...c.contextPanelByDirectory,[a]:m};return{contextPanelByDirectory:La(h,20)}})},closeContextPanelTab:(n,r)=>{const o=Wr((n||"").trim()),a=(r||"").trim();!o||!a||t(i=>{const l=i.contextPanelByDirectory[o],c=Ra(l);if(!c.tabs.some(u=>u.id===a))return i;const d={...i.contextPanelByDirectory,[o]:Uv(c,a)};return{contextPanelByDirectory:La(d,20)}})},closeContextPanel:n=>{const r=Wr((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r];if(!a||!a.isOpen)return o;const i={...o.contextPanelByDirectory,[r]:{...Ra(a),isOpen:!1}};return{contextPanelByDirectory:La(i,20)}})},toggleContextPanelExpanded:n=>{const r=Wr((n||"").trim());r&&t(o=>{const a=o.contextPanelByDirectory[r],i=Ra(a),l={...o.contextPanelByDirectory,[r]:{...i,expanded:!i.expanded}};return{contextPanelByDirectory:La(l,20)}})},setContextPanelWidth:(n,r)=>{const o=Wr((n||"").trim());o&&t(a=>{const i=a.contextPanelByDirectory[o],l=Ra(i),c={...a.contextPanelByDirectory,[o]:{...l,width:Kp(r)}};return{contextPanelByDirectory:La(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})},setPendingFileNavigation:n=>{t({pendingFileNavigation:n})},setPendingFileFocusPath:n=>{t({pendingFileFocusPath: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})},setChatRenderMode:n=>{t({chatRenderMode:n})},setActivityRenderMode:n=>{t({activityRenderMode: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})},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(M4);if(o===1){for(const[i]of a)r.style.removeProperty(z3(i));return}for(const[i,l]of a){const c=parseFloat(l);Number.isFinite(c)&&r.style.setProperty(z3(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)}))},toggleModelProviderCollapsed:n=>{const r=typeof n=="string"?n.trim():"";r&&t(o=>o.collapsedModelProviders.includes(r)?{collapsedModelProviders:o.collapsedModelProviders.filter(i=>i!==r)}:{collapsedModelProviders:[...o.collapsedModelProviders,r]})},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 u=d.recentEfforts[l]??[];if(u.includes(c))return d;const m=u;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})},setInputSpellcheckEnabled:n=>{t({inputSpellcheckEnabled:n})},setShowToolFileIcons:n=>{t({showToolFileIcons:n})},setShowExpandedBashTools:n=>{t({showExpandedBashTools:n})},setShowExpandedEditTools:n=>{t({showExpandedEditTools:n})},setMermaidRenderingMode:n=>{t({mermaidRenderingMode:n})},setUserMessageRenderingMode:n=>{t({userMessageRenderingMode:n})},setStickyUserHeader:n=>{t({stickyUserHeader: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:xr(()=>Bn()),version:7,migrate:(t,e)=>{if(!t||typeof t!="object")return t;const n=t;if(e<1&&zv(n.notificationTemplates)&&(n.notificationTemplates={completion:{...da.completion},error:{...da.error},question:{...da.question},subtask:{...da.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=O2(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 e<6&&(n.contextPanelByDirectory=O2(n.contextPanelByDirectory)),e<7&&(n.contextPanelByDirectory=O2(n.contextPanelByDirectory)),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,chatRenderMode:t.chatRenderMode,activityRenderMode:t.activityRenderMode,showDeletionDialog:t.showDeletionDialog,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,messageLimit:t.messageLimit,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,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,inputSpellcheckEnabled:t.inputSpellcheckEnabled,showToolFileIcons:t.showToolFileIcons,showExpandedBashTools:t.showExpandedBashTools,showExpandedEditTools:t.showExpandedEditTools,mermaidRenderingMode:t.mermaidRenderingMode,userMessageRenderingMode:t.userMessageRenderingMode,stickyUserHeader:t.stickyUserHeader,showMobileSessionStatusBar:t.showMobileSessionStatusBar,isMobileSessionStatusBarCollapsed:t.isMobileSessionStatusBarCollapsed,shortcutOverrides:t.shortcutOverrides})}),{name:"ui-store"})),qv=({transform:t})=>({...t,y:0}),Gv=t=>{const e=Ce.c(18),{id:n,children:r,className:o}=t;let a;e[0]!==n?(a={id:n},e[0]=n,e[1]=a):a=e[1];const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:u,isDragging:m}=Tc(a);let h;e[2]!==d?(h=Pc.Transform.toString(d),e[2]=d,e[3]=h):h=e[3];let p;e[4]!==h||e[5]!==u?(p={transform:h,transition:u},e[4]=h,e[5]=u,e[6]=p):p=e[6];const g=m&&"opacity-50";let y;e[7]!==o||e[8]!==g?(y=J("h-full rounded-md",o,g),e[7]=o,e[8]=g,e[9]=y):y=e[9];let b;return e[10]!==i||e[11]!==r||e[12]!==n||e[13]!==l||e[14]!==c||e[15]!==p||e[16]!==y?(b=s.jsx("div",{ref:c,"data-sortable-tab-id":n,style:p,className:y,...i,...l,children:r}),e[10]=i,e[11]=r,e[12]=n,e[13]=l,e[14]=c,e[15]=p,e[16]=y,e[17]=b):b=e[17],b},Zv=t=>{const e=Ce.c(6),{id:n,children:r,className:o}=t;let a;e[0]!==o?(a=J("h-full",o),e[0]=o,e[1]=a):a=e[1];let i;return e[2]!==r||e[3]!==n||e[4]!==a?(i=s.jsx("div",{className:a,"data-sortable-tab-id":n,children:r}),e[2]=r,e[3]=n,e[4]=a,e[5]=i):i=e[5],i},Mo=t=>{const e=Ce.c(107),{items:n,activeId:r,onSelect:o,onClose:a,onReorder:i,layoutMode:l,variant:c,activePillInsetClassName:d,activePillButtonClassName:u,inactiveTabsIconOnly:m,animateActivePill:h,className:p}=t,g=l===void 0?"scrollable":l,y=c===void 0?"default":c,b=m===void 0?!1:m,x=De(Kv),v=f.useRef(null);let w;e[0]===Symbol.for("react.memo_cache_sentinel")?(w={left:!1,right:!1},e[0]=w):w=e[0];const[C,k]=f.useState(w);let N;e[1]!==n?(N=n.map(Qv),e[1]=n,e[2]=N):N=e[2];const S=N,j=g==="scrollable",A=y==="active-pill",M=y==="animated",F=A||M,B=A&&j,D=M,E=h??M,I=typeof i=="function",T=I?Gv:Zv;let H;e[3]===Symbol.for("react.memo_cache_sentinel")?(H=new Map,e[3]=H):H=e[3];const P=f.useRef(H),[_,R]=f.useState(null);let z;e[4]===Symbol.for("react.memo_cache_sentinel")?(z={activationConstraint:{distance:8}},e[4]=z):z=e[4];const O=Ic(li(Rc,z)),Q=Yv;let te;e[5]===Symbol.for("react.memo_cache_sentinel")?(te=(ke,Ze)=>{if(Ze){P.current.set(ke,Ze);return}P.current.delete(ke)},e[5]=te):te=e[5];const W=te;let U;e[6]!==r||e[7]!==F?(U=()=>{if(!F||!r){R(Jv);return}const ke=v.current,Ze=P.current.get(r);if(!ke||!Ze){R(Xv);return}const Je=ke.getBoundingClientRect(),Ye=Ze.getBoundingClientRect(),Re={left:Ye.left-Je.left+ke.scrollLeft,top:Ye.top-Je.top+ke.scrollTop,width:Ye.width,height:Ye.height};R(Ue=>Q(Ue,Re)?Ue:Re)},e[6]=r,e[7]=F,e[8]=U):U=e[8];const K=U;let q;e[9]!==j?(q=()=>{if(!j){k({left:!1,right:!1});return}const ke=v.current;if(!ke){k({left:!1,right:!1});return}k({left:ke.scrollLeft>2,right:ke.scrollLeft+ke.clientWidth<ke.scrollWidth-2})},e[9]=j,e[10]=q):q=e[10];const ee=q;let V;e[11]!==j||e[12]!==ee?(V=()=>{if(!j){k({left:!1,right:!1});return}const ke=v.current;if(!ke)return;ee(),ke.addEventListener("scroll",ee,{passive:!0});const Ze=new ResizeObserver(ee);return Ze.observe(ke),()=>{ke.removeEventListener("scroll",ee),Ze.disconnect()}},e[11]=j,e[12]=ee,e[13]=V):V=e[13];let G;e[14]!==j||e[15]!==n.length||e[16]!==ee?(G=[j,n.length,ee],e[14]=j,e[15]=n.length,e[16]=ee,e[17]=G):G=e[17],f.useEffect(V,G);let Y;e[18]!==r||e[19]!==K||e[20]!==F?(Y=()=>{if(!F){R(null);return}K();const ke=v.current;if(!ke)return;const Ze=new ResizeObserver(K);if(Ze.observe(ke),r){const Je=P.current.get(r);Je&&Ze.observe(Je)}return()=>{Ze.disconnect()}},e[18]=r,e[19]=K,e[20]=F,e[21]=Y):Y=e[21];let oe;e[22]!==r||e[23]!==n.length||e[24]!==K||e[25]!==F?(oe=[r,n.length,K,F],e[22]=r,e[23]=n.length,e[24]=K,e[25]=F,e[26]=oe):oe=e[26],f.useEffect(Y,oe);let re;e[27]!==K?(re=()=>{K()},e[27]=K,e[28]=re):re=e[28],f.useLayoutEffect(re);let fe;e[29]!==r||e[30]!==j||e[31]!==ee?(fe=()=>{if(!j||!r)return;const ke=v.current;if(!ke)return;const Ze=window.requestAnimationFrame(()=>{const Je=typeof window.CSS?.escape=="function"?window.CSS.escape(r):r.replace(/"/g,'\\"'),Ye=ke.querySelector(`[data-sortable-tab-id="${Je}"]`);Ye&&(Ye.scrollIntoView({block:"nearest",inline:"nearest"}),ee())});return()=>{window.cancelAnimationFrame(Ze)}},e[29]=r,e[30]=j,e[31]=ee,e[32]=fe):fe=e[32];let ie;e[33]!==r||e[34]!==j||e[35]!==n.length||e[36]!==ee?(ie=[r,j,n.length,ee],e[33]=r,e[34]=j,e[35]=n.length,e[36]=ee,e[37]=ie):ie=e[37],f.useEffect(fe,ie);let de;e[38]!==i?(de=ke=>{if(!i)return;const{active:Ze,over:Je}=ke;!Je||Ze.id===Je.id||i(String(Ze.id),String(Je.id))},e[38]=i,e[39]=de):de=e[39];const $=de;let L;e[40]!==p?(L=J("relative flex h-full min-w-0 flex-1",p),e[40]=p,e[41]=L):L=e[41];let X;e[42]!==j||e[43]!==C||e[44]!==F?(X=j&&!F&&C.left?s.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-6 bg-gradient-to-r from-background to-transparent"}):null,e[42]=j,e[43]=C,e[44]=F,e[45]=X):X=e[45];let ne;e[46]!==j||e[47]!==C||e[48]!==F?(ne=j&&!F&&C.right?s.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-6 bg-gradient-to-l from-background to-transparent"}):null,e[46]=j,e[47]=C,e[48]=F,e[49]=ne):ne=e[49];const se=F?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",pe=F&&"@container/pill-tabs",ae=F&&"pill-tabs__track",ve=F&&(d??"gap-0.5 py-0.5"),ce=D&&"rounded-lg bg-[var(--surface-muted)]/50",Z=j?"overflow-x-auto scrollbar-none":"overflow-x-hidden";let me;e[50]!==se||e[51]!==pe||e[52]!==ae||e[53]!==ve||e[54]!==ce||e[55]!==Z?(me=J("relative flex h-full min-w-0 flex-1",se,pe,ae,ve,ce,Z),e[50]=se,e[51]=pe,e[52]=ae,e[53]=ve,e[54]=ce,e[55]=Z,e[56]=me):me=e[56];let be;e[57]!==j?(be=j?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,e[57]=j,e[58]=be):be=e[58];let we;e[59]!==_||e[60]!==E||e[61]!==F?(we=F&&_?s.jsx("div",{className:J("pointer-events-none absolute left-0 top-0 z-0 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)]",E&&"transition-[transform,width,height] duration-200 ease-out"),style:{transform:`translate(${_.left}px, ${_.top}px)`,width:`${_.width}px`,height:`${_.height}px`}}):null,e[59]=_,e[60]=E,e[61]=F,e[62]=we):we=e[62];let Ae;if(e[63]!==T||e[64]!==r||e[65]!==u||e[66]!==b||e[67]!==A||e[68]!==x||e[69]!==j||e[70]!==n||e[71]!==a||e[72]!==o||e[73]!==B||e[74]!==F){let ke;e[76]!==T||e[77]!==r||e[78]!==u||e[79]!==b||e[80]!==A||e[81]!==x||e[82]!==j||e[83]!==a||e[84]!==o||e[85]!==B||e[86]!==F?(ke=Ze=>{const Je=Ze.id===r,Ye=b&&F&&!Je&&!!Ze.icon,Re=!Ye,Ue=b&&F&&Je&&!j&&!B,Ve=Ze.closable!==!1&&!!a,st=j||B?void 0:F?Ue?"flex-none basis-auto":x?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0";return s.jsx(T,{id:Ze.id,className:st,children:s.jsxs("div",{className:J("group flex h-full items-center",j||B?"shrink-0":F?"w-full":"w-full min-w-0",F?"relative z-10 bg-transparent":Je?"border-r border-border/40 bg-[var(--surface-elevated)] text-foreground":"border-r border-border/40 bg-[var(--surface-elevated)]/25 text-muted-foreground hover:bg-[var(--surface-elevated)]/65 hover:text-foreground"),children:[s.jsx("button",{ref:at=>W(Ze.id,at),type:"button",role:"tab","aria-selected":Je,"aria-label":Ye?Ze.title??Ze.label:void 0,onClick:()=>o(Ze.id),className:J(F?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 items-center justify-center rounded-lg text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 items-center typography-micro",F&&(Ye?"gap-0":"gap-1.5"),F?B?"shrink-0 whitespace-nowrap px-3 text-center":j?"max-w-56 shrink-0 px-3 text-center":Ye?"px-2 !min-w-0 text-center":Ue?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":j?"max-w-56 justify-start truncate pl-3 pr-2 text-left":"w-full justify-center truncate px-2.5 text-center",F?u??(A?x?"h-[34px]":"h-[27px]":"h-7"):null,F?Je?"text-foreground":"text-muted-foreground hover:text-foreground":null,F?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:Ze.title??Ze.label,children:F?s.jsxs(s.Fragment,{children:[Ze.icon?s.jsx("span",{className:"flex shrink-0 items-center justify-center",children:Ze.icon}):null,Re?s.jsx("span",{className:"animated-tabs__label truncate",children:Ze.label}):null]}):s.jsxs("span",{className:J("flex min-w-0 items-center gap-1.5",!j&&"justify-center"),children:[Ze.icon?s.jsx("span",{className:"flex shrink-0 items-center justify-center",children:Ze.icon}):null,s.jsx("span",{className:"truncate leading-[1.2]",children:Ze.label})]})}),Ve?s.jsx("button",{type:"button",onClick:at=>{at.stopPropagation(),a?.(Ze.id)},className:J("mr-1 inline-flex aspect-square h-[65%] min-h-4 max-h-5 !min-h-0 !min-w-0 items-center justify-center rounded-sm transition-opacity",Je?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":Ze.closeLabel??`Close ${Ze.label} tab`,title:Ze.closeLabel??`Close ${Ze.label} tab`,children:s.jsx(_s,{className:"h-3 w-3"})}):null]})},Ze.id)},e[76]=T,e[77]=r,e[78]=u,e[79]=b,e[80]=A,e[81]=x,e[82]=j,e[83]=a,e[84]=o,e[85]=B,e[86]=F,e[87]=ke):ke=e[87],Ae=n.map(ke),e[63]=T,e[64]=r,e[65]=u,e[66]=b,e[67]=A,e[68]=x,e[69]=j,e[70]=n,e[71]=a,e[72]=o,e[73]=B,e[74]=F,e[75]=Ae}else Ae=e[75];let Pe;e[88]!==me||e[89]!==be||e[90]!==we||e[91]!==Ae?(Pe=s.jsxs("div",{ref:v,className:me,style:be,role:"tablist","aria-label":"Tabs",children:[we,Ae]}),e[88]=me,e[89]=be,e[90]=we,e[91]=Ae,e[92]=Pe):Pe=e[92];let xe;e[93]!==L||e[94]!==X||e[95]!==ne||e[96]!==Pe?(xe=s.jsxs("div",{className:L,children:[X,ne,Pe]}),e[93]=L,e[94]=X,e[95]=ne,e[96]=Pe,e[97]=xe):xe=e[97];const _e=xe;if(!I)return _e;let ze;e[98]===Symbol.for("react.memo_cache_sentinel")?(ze=[qv],e[98]=ze):ze=e[98];let le;e[99]!==S||e[100]!==_e?(le=s.jsx(s2,{items:S,strategy:Fy,children:_e}),e[99]=S,e[100]=_e,e[101]=le):le=e[101];let ge;e[102]===Symbol.for("react.memo_cache_sentinel")?(ge=s.jsx(m4,{dropAnimation:null}),e[102]=ge):ge=e[102];let Fe;return e[103]!==$||e[104]!==O||e[105]!==le?(Fe=s.jsxs(Lc,{sensors:O,collisionDetection:zc,onDragEnd:$,modifiers:ze,children:[le,ge]}),e[103]=$,e[104]=O,e[105]=le,e[106]=Fe):Fe=e[106],Fe};function Kv(t){return t.isMobile}function Qv(t){return t.id}function Yv(t,e){return!t||!e?t===e:Math.abs(t.left-e.left)<.5&&Math.abs(t.top-e.top)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5}function Jv(t){return t===null?t:null}function Xv(t){return t===null?t:null}function O3(t){const e=Ce.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 u;return e[10]!==n||e[11]!==r||e[12]!==c?(u=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]=u):u=e[13],u}const ew="/api",tw=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,sw=t=>{const e=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(tw.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}},nw=()=>{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},Ml=t=>t.replace(/\\/g,"/"),$3=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class rw{client;baseUrl;scopedClients=new Map;sseAbortControllers=new Map;currentDirectory=void 0;directoryContextQueue=Promise.resolve();globalSseAbortController=null;globalSseTask=null;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;globalSseQueue=[];globalSseBuffer=[];globalSseCoalesced=new Map;globalSseStaleDeltas=new Set;globalSseFlushTimer=null;globalSseLastFlushAt=0;constructor(e=ew){const r=nw()||e;this.baseUrl=sw(r),this.client=S3({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=S3({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 cr(async()=>{const{default:m}=await import("./vendor-.bun-9lzLHWe8.js").then(h=>h.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,h)=>{const p=new FileReader;p.onload=()=>m(p.result),p.onerror=h,p.readAsDataURL(c)});let u=e.filename;return u&&(u=u.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:u,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 u=await this.toNormalizedFilePartInput(d);o.push(u)}}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 u=d&&d.trim().length>0?`: ${d.trim()}`:"";throw new Error(`Failed to run command (${c.status})${u}`)}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 u=d.id;typeof u!="string"||u.length===0||l.has(u)||(l.add(u),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 u=d.id;typeof u!="string"||u.length===0||l.has(u)||(l.add(u),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[]}}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(),this.globalSseStaleDeltas.clear()}getGlobalSseDeltaKey(e){const n=e.payload;if((typeof n.type=="string"?n.type:null)!=="message.part.delta")return null;const o=typeof n.properties=="object"&&n.properties!==null?n.properties:null,a=typeof o?.messageID=="string"?o.messageID:typeof o?.messageId=="string"?o.messageId:null,i=typeof o?.partID=="string"?o.partID:typeof o?.partId=="string"?o.partId:null;return!a||!i?null:`${e.directory}:${a}:${i}`}getGlobalSseUpdatedPartKey(e){const n=e.payload;if((typeof n.type=="string"?n.type:null)!=="message.part.updated")return null;const o=typeof n.properties=="object"&&n.properties!==null?n.properties:null,a=o?.part&&typeof o.part=="object"?o.part:null,i=typeof a?.messageID=="string"?a.messageID:typeof a?.messageId=="string"?a.messageId:null,l=typeof a?.id=="string"?a.id:typeof a?.partID=="string"?a.partID:typeof a?.partId=="string"?a.partId:null;return!i||!l?null:`${e.directory}:${i}:${l}`}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}if(r==="message.part.updated"){const a=this.getGlobalSseUpdatedPartKey(e);return a?`message.part.updated:${a}`:null}return null}flushGlobalSseQueue=()=>{if(this.globalSseFlushTimer&&(clearTimeout(this.globalSseFlushTimer),this.globalSseFlushTimer=null),this.globalSseQueue.length===0)return;const e=this.globalSseQueue,n=this.globalSseStaleDeltas.size>0?new Set(this.globalSseStaleDeltas):void 0;this.globalSseQueue=this.globalSseBuffer,this.globalSseBuffer=e,this.globalSseQueue.length=0,this.globalSseCoalesced.clear(),this.globalSseStaleDeltas.clear(),this.globalSseLastFlushAt=Date.now();for(const r of e)if(r){if(n){const o=this.getGlobalSseDeltaKey(r);if(o&&n.has(o))continue}for(const o of this.globalSseListeners)try{o(r)}catch(a){console.warn("[OpencodeClient] Global SSE listener error:",a)}}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);if(r!==void 0){this.globalSseQueue[r]=void 0;const o=this.getGlobalSseUpdatedPartKey(e);o&&this.globalSseStaleDeltas.add(o)}this.globalSseCoalesced.set(n,this.globalSseQueue.length)}this.globalSseQueue.push(e),this.scheduleGlobalSseFlush()}async runGlobalSseLoop(e){let n=0;const r=250,o=8,a=i=>new Promise(l=>setTimeout(l,i));for(;!e.signal.aborted;){try{const i=await this.client.global.event({signal:e.signal,onSseError:c=>{c?.name==="AbortError"||e.signal.aborted||this.notifyGlobalSseError(c)}});n=0,this.globalSseIsConnected=!0,e.signal.aborted||this.notifyGlobalSseOpen();let l=Date.now();for await(const c of i.stream){if(e.signal.aborted)break;const d=typeof c.directory=="string"&&c.directory.length>0?c.directory:"global",u=this.normalizeRoutedSsePayload({directory:d,payload:c.payload});u&&(this.emitGlobalSseEvent(u),Date.now()-l>=o&&(l=Date.now(),await a(0)))}this.globalSseIsConnected=!1}catch(i){if(this.globalSseIsConnected=!1,i?.name==="AbortError"||e.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",i),this.notifyGlobalSseError(i)}if(e.signal.aborted)break;n+=1,await a(Math.min(r*Math.max(n,1),2e3))}this.flushGlobalSseQueue()}subscribeToGlobalEvents(e,n,r,o){const a=this.normalizeCandidatePath(o?.directory??null),i=l=>{a&&l.directory!==a||e(l)};return this.globalSseListeners.add(i),r&&(this.globalSseOpenListeners.add(r),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(r))try{r()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),n&&this.globalSseErrorListeners.add(n),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),r&&this.globalSseOpenListeners.delete(r),n&&this.globalSseErrorListeners.delete(n),this.maybeStopGlobalSse()}}subscribeToEvents(e,n,r,o,a){const i=a?.key??"default",l=a?.scope??"directory",c=this.sseAbortControllers.get(i);c&&c.abort();const d=new AbortController;this.sseAbortControllers.set(i,d);let u;if(l==="global"){let h=null;const p=y=>{if(y.directory==="global")return y.payload;const b=y.payload,x=typeof b.properties=="object"&&b.properties!==null?b.properties:{};return x.directory===y.directory?y.payload:{...b,properties:{...x,directory:y.directory}}},g=()=>{if(h){try{h()}catch{}h=null}this.sseAbortControllers.get(i)===d&&this.sseAbortControllers.delete(i)};return d.signal.addEventListener("abort",g,{once:!0}),h=this.subscribeToGlobalEvents(y=>{d.signal.aborted||e(p(y))},n?y=>{d.signal.aborted||n(y)}:void 0,r?()=>{d.signal.aborted||r()}:void 0),()=>{g(),d.abort()}}const m=h=>{if(!h||typeof h!="object")return null;const p=h;if(typeof p.type=="string")return p;const g=p.payload;if(g&&typeof g=="object"){const y=g;if(typeof y.type=="string"){if(typeof p.directory=="string"&&p.directory.length>0){const x={...(typeof y.properties=="object"&&y.properties!==null?y.properties:null)??{},directory:p.directory};return{...y,properties:x}}return y}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const h=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",h??"default");const p=async g=>{try{const y=h?{directory:h}:void 0,b={signal:d.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),n&&!d.signal.aborted&&n(v))},onSseEvent:v=>{if(d.signal.aborted)return;v.id&&typeof v.id=="string"&&(u=v.id);const w=v.data,C=m(w);C&&e(C)}};u&&(b.headers={...b.headers||{},"Last-Event-ID":u});const x=await this.client.event.subscribe(y,b);r&&!d.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),r());for await(const v of x.stream)if(d.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(y){if(y?.name==="AbortError"||d.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",y),n&&n(y);const b=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(x=>setTimeout(x,b)),d.signal.aborted||await p(g+1);return}if(!d.signal.aborted){const y=Math.min(3e3*Math.pow(2,g),3e4);await new Promise(b=>setTimeout(b,y)),await p(g+1)}};try{await p(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===d&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===d&&this.sseAbortControllers.delete(i),d.abort()}}async readFile(e){try{const n=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e,directory:this.currentDirectory})});if(!n.ok)throw new Error(`Failed to read file: ${n.statusText}`);return await n.text()}catch{return`// Content of ${e}
3
3
  // This would be loaded from the server`}}async listFiles(e){try{const n=e||this.currentDirectory||"/",r=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:n})});if(!r.ok)throw new Error(`Failed to list files: ${r.statusText}`);return await r.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(n=>({name:n.name,description:n.description,agent:n.agent,model:n.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(n=>({name:n.name,description:n.description,agent:n.agent,model:n.model,template:n.template}))}catch{return[]}}async getCommandDetails(e){try{const n=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(n.data){const r=n.data.find(o=>o.name===e);if(r)return{name:r.name,template:r.template,description:r.description,agent:r.agent,model:r.model}}return null}catch{return null}}async checkHealth(){try{let e;const n=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;n==="/api"?e="/health":n.endsWith("/api")?e=`${n.slice(0,-4)}/health`:e=`${n}/health`;const r=await fetch(e);return!(!r.ok||(await r.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(e,n){const r=$3();if(r?.createDirectory)try{return await r.createDirectory(e)}catch(l){const c=l instanceof Error?l.message:String(l);throw new Error(c||"Failed to create directory")}const o={path:e,...n?.allowOutsideWorkspace?{allowOutsideWorkspace:!0}:{}},a=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){const l=await a.json().catch(()=>({error:"Failed to create directory"}));throw new Error(l.error||"Failed to create directory")}return await a.json()}async listLocalDirectory(e,n){const r=$3();if(r)try{const o=await r.listDirectory(e||"",n);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:Ml(a.path),isDirectory:!!a.isDirectory,isFile:!a.isDirectory,isSymbolicLink:!1}))}catch(o){throw console.error("Failed to list directory contents:",o),o}try{const o=new URLSearchParams;e&&e.trim().length>0&&o.set("path",e),n?.respectGitignore&&o.set("respectGitignore","true");const a=o.toString(),i=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!i.ok){const c=await i.json().catch(()=>({})),d=typeof c.error=="string"?c.error:"Failed to list directory";throw new Error(d)}const l=await i.json();return!l||!Array.isArray(l.entries)?[]:l.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(e,n){const r=typeof n?.directory=="string"&&n.directory.trim().length>0?n.directory.trim():this.currentDirectory,o=r?Ml(r):null,a=r?this.getScopedApiClient(r):this.client;try{const i=await a.find.files({query:e,limit:typeof n?.limit=="number"&&Number.isFinite(n.limit)?n.limit:void 0,dirs:n?.dirs===!1||n?.type==="file"?"false":"true",type:n?.type});return(Array.isArray(i?.data)?i.data:[]).map(c=>{const d=Ml(c),u=d.split("/").filter(Boolean).pop()||d,m=Ml(o?`${o}/${d}`:d);return{name:u,path:m,relativePath:d,extension:u.includes(".")?u.split(".").pop()?.toLowerCase():void 0}})}catch(i){throw console.error("Failed to search files:",i),i}}async getFilesystemHome(){const e=await f2();if(e)return e;try{const n=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!n.ok){const o=await n.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const r=await n.json();return r&&typeof r.home=="string"&&r.home.length>0?r.home:null}catch(n){return console.warn("Failed to resolve filesystem home directory:",n),null}}async setOpenCodeWorkingDirectory(e){if(!e||typeof e!="string"||!e.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",e),null;const n=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",n,"with path:",e);try{const r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})}),o=await r.json().catch(()=>null);if(!r.ok){const a=o??{},i=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:e}}catch(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const zt=new rw,mu=new Set;function p2(t){return mu.add(t),()=>{mu.delete(t)}}function Ao(t,e){const n=Array.isArray(t)?t:[t],r=Array.from(new Set(n));if(r.length===0)return;r.includes("all")&&r.splice(0,r.length,"all");const o={scopes:r,source:e?.source,timestamp:Date.now()};for(const a of mu)try{const i=a(o);i instanceof Promise&&i.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function wc(t,e){return t.scopes.includes("all")||t.scopes.includes(e)}const F4="Updating OpenCode configuration...";let Oo=0,Da=F4;const hu=new Set;function k0(){const t={isUpdating:Oo>0,message:Da};hu.forEach(e=>e(t))}function kr(t){Oo+=1,Oo===1?(Da=t||F4,k0()):t&&(Da=t,k0())}function fr(){Oo!==0&&(Oo-=1,Oo===0&&(Da=F4,k0()))}function Sr(t){Da===t&&Oo>0||(Da=t,Oo>0&&k0())}function ow(t){return hu.add(t),t({isUpdating:Oo>0,message:Da}),()=>{hu.delete(t)}}function aw(){return{isUpdating:Oo>0,message:Da}}const io=xn()(In(hr((t,e)=>({queuedMessages:{},queueModeEnabled:!0,addToQueue:(n,r)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:r.content,attachments:r.attachments,createdAt:Date.now()};t(i=>{const l=i.queuedMessages[n]??[];return{queuedMessages:{...i.queuedMessages,[n]:[...l,a]}}})},removeFromQueue:(n,r)=>{t(o=>{const i=(o.queuedMessages[n]??[]).filter(l=>l.id!==r);if(i.length===0){const{[n]:l,...c}=o.queuedMessages;return{queuedMessages:c}}return{queuedMessages:{...o.queuedMessages,[n]:i}}})},popToInput:(n,r)=>{const i=(e().queuedMessages[n]??[]).find(l=>l.id===r);return i?(t(l=>{const d=(l.queuedMessages[n]??[]).filter(u=>u.id!==r);if(d.length===0){const{[n]:u,...m}=l.queuedMessages;return{queuedMessages:m}}return{queuedMessages:{...l.queuedMessages,[n]:d}}}),i):null},clearQueue:n=>{t(r=>{const{[n]:o,...a}=r.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:n=>{t({queueModeEnabled:n}),Rs({queueModeEnabled:n})},getQueueForSession:n=>e().queuedMessages[n]??[]}),{name:"message-queue-store",storage:xr(()=>Bn()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),s8="directoryTreeShowHidden",pu="directory-show-hidden-change",V3=()=>{if(typeof window>"u")return!0;try{const t=Bn().getItem(s8);return t===null?!0:t==="true"}catch{return!0}},iw=()=>{typeof window>"u"||window.dispatchEvent(new Event(pu))},sc=(t,e={})=>{if(!(typeof window>"u")){try{Bn().setItem(s8,t?"true":"false"),iw()}catch{}e.persist!==!1&&Rs({directoryShowHidden:t})}},$c=()=>{const t=Ce.c(2),[e,n]=f.useState(V3);let r,o;return t[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const a=()=>{n(V3())};return window.addEventListener("storage",a),window.addEventListener(pu,a),()=>{window.removeEventListener("storage",a),window.removeEventListener(pu,a)}},o=[],t[0]=r,t[1]=o):(r=t[0],o=t[1]),f.useEffect(r,o),e},n8="filesViewShowGitignored",gu="files-view-show-gitignored-change",U3=()=>{if(typeof window>"u")return!1;try{return Bn().getItem(n8)==="true"}catch{return!1}},lw=()=>{typeof window>"u"||window.dispatchEvent(new Event(gu))},K1=(t,e={})=>{if(!(typeof window>"u")){try{Bn().setItem(n8,t?"true":"false"),lw()}catch{}e.persist!==!1&&Rs({filesViewShowGitignored:t})}},g2=()=>{const t=Ce.c(2),[e,n]=f.useState(U3);let r,o;return t[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{if(typeof window>"u")return;const a=()=>{n(U3())};return window.addEventListener("storage",a),window.addEventListener(gu,a),()=>{window.removeEventListener("storage",a),window.removeEventListener(gu,a)}},o=[],t[0]=r,t[1]=o):(r=t[0],o=t[1]),f.useEffect(r,o),e},cw=t=>{if(!t||typeof t!="object")return null;const e={};return typeof t.showReasoningTraces=="boolean"&&(e.showReasoningTraces=t.showReasoningTraces),Object.keys(e).length>0?e:null},dw=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},uw=t=>{const e=De.getState();typeof t.showReasoningTraces=="boolean"&&e.setShowReasoningTraces(t.showReasoningTraces)},fw=async()=>{if(typeof window>"u")return null;const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const e=JSON.parse(t),n=dw(e);return cw(n)}catch(e){return console.warn("Failed to parse stored appearance preferences:",e),null}};let r8=null;const W3=t=>{r8=t},gr=()=>r8,yu=t=>{if(!(typeof window>"u")){if(t.themeId&&localStorage.setItem("selectedThemeId",t.themeId),t.themeVariant&&localStorage.setItem("selectedThemeVariant",t.themeVariant),t.lightThemeId&&localStorage.setItem("lightThemeId",t.lightThemeId),t.darkThemeId&&localStorage.setItem("darkThemeId",t.darkThemeId),typeof t.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(t.useSystemTheme)),t.lastDirectory&&localStorage.setItem("lastDirectory",t.lastDirectory),t.homeDirectory&&(localStorage.setItem("homeDirectory",t.homeDirectory),window.__OPENCHAMBER_HOME__=t.homeDirectory),Array.isArray(t.projects)&&t.projects.length>0?localStorage.setItem("projects",JSON.stringify(t.projects)):localStorage.removeItem("projects"),t.activeProjectId?localStorage.setItem("activeProjectId",t.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(t.pinnedDirectories)&&t.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(t.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),Array.isArray(t.projects)&&t.projects.length>0){const e=t.projects.filter(n=>n.sidebarCollapsed===!0).map(n=>n.id).filter(n=>typeof n=="string"&&n.length>0);e.length>0?localStorage.setItem("oc.sessions.projectCollapse",JSON.stringify(e)):localStorage.removeItem("oc.sessions.projectCollapse")}if(typeof t.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(t.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"),typeof t.directoryShowHidden=="boolean"&&localStorage.setItem("directoryTreeShowHidden",t.directoryShowHidden?"true":"false"),typeof t.filesViewShowGitignored=="boolean"&&localStorage.setItem("filesViewShowGitignored",t.filesViewShowGitignored?"true":"false"),typeof t.openInAppId=="string"&&t.openInAppId.length>0&&localStorage.setItem("openInAppId",t.openInAppId),typeof t.pwaAppName=="string"){const e=t.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);e.length>0?localStorage.setItem("openchamber.pwaName",e):localStorage.removeItem("openchamber.pwaName")}}},mw=t=>{if(!Array.isArray(t))return;const e=[],n=new Set;for(const r of t){if(!r||typeof r!="object")continue;const o=r,a=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",c=typeof o.subpath=="string"?o.subpath.trim():"",d=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!i||!l||n.has(a)||(n.add(a),e.push({id:a,label:i,source:l,...c?{subpath:c}:{},...d?{gitIdentityId:d}:{}}))}return e},hw=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,pw=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&hw.test(e)?e.toLowerCase():null},gw=t=>{if(!Array.isArray(t))return;const e=[],n=new Set,r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const c=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!c||n.has(i)||r.has(c))continue;n.add(i),r.add(c);const d={id:i,path:c};if(typeof a.label=="string"&&a.label.trim().length>0&&(d.label=a.label.trim()),typeof a.icon=="string"&&a.icon.trim().length>0&&(d.icon=a.icon.trim()),a.iconImage===null)d.iconImage=null;else if(a.iconImage&&typeof a.iconImage=="object"){const u=a.iconImage,m=typeof u.mime=="string"?u.mime.trim():"",h=typeof u.updatedAt=="number"&&Number.isFinite(u.updatedAt)?Math.max(0,Math.round(u.updatedAt)):0,p=u.source==="custom"||u.source==="auto"?u.source:null;m&&h>0&&p&&(d.iconImage={mime:m,updatedAt:h,source:p})}if(typeof a.color=="string"&&a.color.trim().length>0&&(d.color=a.color.trim()),a.iconBackground===null)d.iconBackground=null;else{const u=pw(a.iconBackground);u&&(d.iconBackground=u)}typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(d.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(d.lastOpenedAt=a.lastOpenedAt),typeof a.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=a.sidebarCollapsed),e.push(d)}return e.length>0?e:void 0},yw=t=>{if(!Array.isArray(t))return;const e=[],n=new Set,r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.name=="string"?a.name.trim():"",c=typeof a.hostname=="string"?a.hostname.trim().toLowerCase():"";!i||!l||!c||n.has(i)||r.has(c)||(n.add(i),r.add(c),e.push({id:i,name:l,hostname:c}))}return e},bw=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const e=t,n={};for(const[r,o]of Object.entries(e)){const a=r.trim(),i=typeof o=="string"?o.trim():"";!a||!i||(n[a]=i)}return Object.keys(n).length>0?n:void 0},q3=(t,e)=>{if(!Array.isArray(t))return;const n=[],r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,i=typeof a.providerID=="string"?a.providerID.trim():"",l=typeof a.modelID=="string"?a.modelID.trim():"";if(!i||!l)continue;const c=`${i}/${l}`;if(!r.has(c)&&(r.add(c),n.push({providerID:i,modelID:l}),n.length>=e))break}return n},o8=()=>{const t=De.persist;if(t&&typeof t=="object")return t},a8=()=>gr()?.settings??null,bu=t=>{const e=De.getState(),n=io.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==e.showReasoningTraces&&e.setShowReasoningTraces(t.showReasoningTraces),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==e.autoDeleteEnabled&&e.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const r=Math.max(1,Math.min(365,t.autoDeleteAfterDays));r!==e.autoDeleteAfterDays&&e.setAutoDeleteAfterDays(r)}if(typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==n.queueModeEnabled&&n.setQueueMode(t.queueModeEnabled),typeof t.showDeletionDialog=="boolean"&&t.showDeletionDialog!==e.showDeletionDialog&&e.setShowDeletionDialog(t.showDeletionDialog),typeof t.nativeNotificationsEnabled=="boolean"&&t.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&e.setNativeNotificationsEnabled(t.nativeNotificationsEnabled),typeof t.notificationMode=="string"&&(t.notificationMode==="always"||t.notificationMode==="hidden-only")&&t.notificationMode!==e.notificationMode&&e.setNotificationMode(t.notificationMode),typeof t.notifyOnSubtasks=="boolean"&&t.notifyOnSubtasks!==e.notifyOnSubtasks&&e.setNotifyOnSubtasks(t.notifyOnSubtasks),typeof t.notifyOnCompletion=="boolean"&&t.notifyOnCompletion!==e.notifyOnCompletion&&e.setNotifyOnCompletion(t.notifyOnCompletion),typeof t.notifyOnError=="boolean"&&t.notifyOnError!==e.notifyOnError&&e.setNotifyOnError(t.notifyOnError),typeof t.notifyOnQuestion=="boolean"&&t.notifyOnQuestion!==e.notifyOnQuestion&&e.setNotifyOnQuestion(t.notifyOnQuestion),t.notificationTemplates&&typeof t.notificationTemplates=="object"&&e.setNotificationTemplates(t.notificationTemplates),typeof t.summarizeLastMessage=="boolean"&&t.summarizeLastMessage!==e.summarizeLastMessage&&e.setSummarizeLastMessage(t.summarizeLastMessage),typeof t.summaryThreshold=="number"&&Number.isFinite(t.summaryThreshold)&&e.setSummaryThreshold(t.summaryThreshold),typeof t.summaryLength=="number"&&Number.isFinite(t.summaryLength)&&e.setSummaryLength(t.summaryLength),typeof t.maxLastMessageLength=="number"&&Number.isFinite(t.maxLastMessageLength)&&e.setMaxLastMessageLength(t.maxLastMessageLength),typeof t.inputSpellcheckEnabled=="boolean"&&t.inputSpellcheckEnabled!==e.inputSpellcheckEnabled&&e.setInputSpellcheckEnabled(t.inputSpellcheckEnabled),typeof t.showToolFileIcons=="boolean"&&t.showToolFileIcons!==e.showToolFileIcons&&e.setShowToolFileIcons(t.showToolFileIcons),typeof t.showExpandedBashTools=="boolean"&&t.showExpandedBashTools!==e.showExpandedBashTools&&e.setShowExpandedBashTools(t.showExpandedBashTools),typeof t.showExpandedEditTools=="boolean"&&t.showExpandedEditTools!==e.showExpandedEditTools&&e.setShowExpandedEditTools(t.showExpandedEditTools),typeof t.chatRenderMode=="string"&&(t.chatRenderMode==="sorted"||t.chatRenderMode==="live")&&t.chatRenderMode!==e.chatRenderMode&&e.setChatRenderMode(t.chatRenderMode),typeof t.activityRenderMode=="string"&&(t.activityRenderMode==="collapsed"||t.activityRenderMode==="summary")&&t.activityRenderMode!==e.activityRenderMode&&e.setActivityRenderMode(t.activityRenderMode),typeof t.mermaidRenderingMode=="string"&&(t.mermaidRenderingMode==="svg"||t.mermaidRenderingMode==="ascii")&&t.mermaidRenderingMode!==e.mermaidRenderingMode&&e.setMermaidRenderingMode(t.mermaidRenderingMode),typeof t.userMessageRenderingMode=="string"&&(t.userMessageRenderingMode==="markdown"||t.userMessageRenderingMode==="plain")&&t.userMessageRenderingMode!==e.userMessageRenderingMode&&e.setUserMessageRenderingMode(t.userMessageRenderingMode),typeof t.stickyUserHeader=="boolean"&&t.stickyUserHeader!==e.stickyUserHeader&&e.setStickyUserHeader(t.stickyUserHeader),typeof t.fontSize=="number"&&Number.isFinite(t.fontSize)&&t.fontSize!==e.fontSize&&e.setFontSize(t.fontSize),typeof t.terminalFontSize=="number"&&Number.isFinite(t.terminalFontSize)&&t.terminalFontSize!==e.terminalFontSize&&e.setTerminalFontSize(t.terminalFontSize),typeof t.padding=="number"&&Number.isFinite(t.padding)&&t.padding!==e.padding&&e.setPadding(t.padding),typeof t.cornerRadius=="number"&&Number.isFinite(t.cornerRadius)&&t.cornerRadius!==e.cornerRadius&&e.setCornerRadius(t.cornerRadius),typeof t.inputBarOffset=="number"&&Number.isFinite(t.inputBarOffset)&&t.inputBarOffset!==e.inputBarOffset&&e.setInputBarOffset(t.inputBarOffset),Array.isArray(t.favoriteModels)){const r=e.favoriteModels,o=t.favoriteModels;r.length===o.length&&r.every((i,l)=>i.providerID===o[l]?.providerID&&i.modelID===o[l]?.modelID)||De.setState({favoriteModels:o})}if(Array.isArray(t.recentModels)){const r=e.recentModels,o=t.recentModels;r.length===o.length&&r.every((i,l)=>i.providerID===o[l]?.providerID&&i.modelID===o[l]?.modelID)||De.setState({recentModels:o})}typeof t.diffLayoutPreference=="string"&&(t.diffLayoutPreference==="dynamic"||t.diffLayoutPreference==="inline"||t.diffLayoutPreference==="side-by-side")&&t.diffLayoutPreference!==e.diffLayoutPreference&&e.setDiffLayoutPreference(t.diffLayoutPreference),typeof t.diffViewMode=="string"&&(t.diffViewMode==="single"||t.diffViewMode==="stacked")&&t.diffViewMode!==e.diffViewMode&&e.setDiffViewMode(t.diffViewMode),typeof t.directoryShowHidden=="boolean"&&sc(t.directoryShowHidden,{persist:!1}),typeof t.filesViewShowGitignored=="boolean"&&K1(t.filesViewShowGitignored,{persist:!1})},G3=t=>{if(!t||typeof t!="object")return null;const e=t,n={};if(typeof e.themeId=="string"&&e.themeId.length>0&&(n.themeId=e.themeId),(e.useSystemTheme===!0||e.useSystemTheme===!1)&&(n.useSystemTheme=e.useSystemTheme),typeof e.themeVariant=="string"&&(e.themeVariant==="light"||e.themeVariant==="dark")&&(n.themeVariant=e.themeVariant),typeof e.lightThemeId=="string"&&e.lightThemeId.length>0&&(n.lightThemeId=e.lightThemeId),typeof e.darkThemeId=="string"&&e.darkThemeId.length>0&&(n.darkThemeId=e.darkThemeId),typeof e.lastDirectory=="string"&&e.lastDirectory.length>0&&(n.lastDirectory=e.lastDirectory),typeof e.homeDirectory=="string"&&e.homeDirectory.length>0&&(n.homeDirectory=e.homeDirectory),typeof e.opencodeBinary=="string"){const d=e.opencodeBinary.trim();n.opencodeBinary=d.length>0?d:void 0}const r=gw(e.projects);if(r&&(n.projects=r),typeof e.activeProjectId=="string"&&e.activeProjectId.length>0&&(n.activeProjectId=e.activeProjectId),Array.isArray(e.approvedDirectories)&&(n.approvedDirectories=e.approvedDirectories.filter(d=>typeof d=="string"&&d.length>0)),Array.isArray(e.securityScopedBookmarks)&&(n.securityScopedBookmarks=e.securityScopedBookmarks.filter(d=>typeof d=="string"&&d.length>0)),Array.isArray(e.pinnedDirectories)&&(n.pinnedDirectories=Array.from(new Set(e.pinnedDirectories.filter(d=>typeof d=="string"&&d.length>0)))),typeof e.showReasoningTraces=="boolean"&&(n.showReasoningTraces=e.showReasoningTraces),typeof e.autoDeleteEnabled=="boolean"&&(n.autoDeleteEnabled=e.autoDeleteEnabled),typeof e.autoDeleteAfterDays=="number"&&Number.isFinite(e.autoDeleteAfterDays)&&(n.autoDeleteAfterDays=e.autoDeleteAfterDays),typeof e.tunnelProvider=="string"){const d=e.tunnelProvider.trim().toLowerCase();d.length>0&&(n.tunnelProvider=d)}if(typeof e.tunnelMode=="string"){const d=e.tunnelMode.trim().toLowerCase();(d==="quick"||d==="managed-remote"||d==="managed-local")&&(n.tunnelMode=d)}if(e.tunnelBootstrapTtlMs===null?n.tunnelBootstrapTtlMs=null:typeof e.tunnelBootstrapTtlMs=="number"&&Number.isFinite(e.tunnelBootstrapTtlMs)&&(n.tunnelBootstrapTtlMs=e.tunnelBootstrapTtlMs),typeof e.tunnelSessionTtlMs=="number"&&Number.isFinite(e.tunnelSessionTtlMs)&&(n.tunnelSessionTtlMs=e.tunnelSessionTtlMs),e.managedLocalTunnelConfigPath===null)n.managedLocalTunnelConfigPath=null;else if(typeof e.managedLocalTunnelConfigPath=="string"){const d=e.managedLocalTunnelConfigPath.trim();n.managedLocalTunnelConfigPath=d.length>0?d:null}typeof e.managedRemoteTunnelHostname=="string"&&(n.managedRemoteTunnelHostname=e.managedRemoteTunnelHostname.trim()),e.managedRemoteTunnelToken===null?n.managedRemoteTunnelToken=null:typeof e.managedRemoteTunnelToken=="string"&&(n.managedRemoteTunnelToken=e.managedRemoteTunnelToken.trim());const o=yw(e.managedRemoteTunnelPresets);if(o&&(n.managedRemoteTunnelPresets=o),typeof e.managedRemoteTunnelSelectedPresetId=="string"){const d=e.managedRemoteTunnelSelectedPresetId.trim();n.managedRemoteTunnelSelectedPresetId=d.length>0?d:void 0}const a=bw(e.managedRemoteTunnelPresetTokens);if(a&&(n.managedRemoteTunnelPresetTokens=a),typeof e.defaultModel=="string"&&e.defaultModel.length>0&&(n.defaultModel=e.defaultModel),typeof e.defaultVariant=="string"&&e.defaultVariant.length>0&&(n.defaultVariant=e.defaultVariant),typeof e.defaultAgent=="string"&&e.defaultAgent.length>0&&(n.defaultAgent=e.defaultAgent),typeof e.autoCreateWorktree=="boolean"&&(n.autoCreateWorktree=e.autoCreateWorktree),typeof e.gitmojiEnabled=="boolean"&&(n.gitmojiEnabled=e.gitmojiEnabled),typeof e.queueModeEnabled=="boolean"&&(n.queueModeEnabled=e.queueModeEnabled),typeof e.showDeletionDialog=="boolean"&&(n.showDeletionDialog=e.showDeletionDialog),typeof e.nativeNotificationsEnabled=="boolean"&&(n.nativeNotificationsEnabled=e.nativeNotificationsEnabled),typeof e.notificationMode=="string"&&(e.notificationMode==="always"||e.notificationMode==="hidden-only")&&(n.notificationMode=e.notificationMode),typeof e.notifyOnSubtasks=="boolean"&&(n.notifyOnSubtasks=e.notifyOnSubtasks),typeof e.notifyOnCompletion=="boolean"&&(n.notifyOnCompletion=e.notifyOnCompletion),typeof e.notifyOnError=="boolean"&&(n.notifyOnError=e.notifyOnError),typeof e.notifyOnQuestion=="boolean"&&(n.notifyOnQuestion=e.notifyOnQuestion),e.notificationTemplates&&typeof e.notificationTemplates=="object"){const d=e.notificationTemplates,u=y=>{const b=d[y];if(!b||typeof b!="object")return;const x=b,v=typeof x.title=="string"?x.title:"",w=typeof x.message=="string"?x.message:"";return{title:v,message:w}},m=u("completion"),h=u("error"),p=u("question"),g=u("subtask");(m||h||p||g)&&(n.notificationTemplates={completion:m??{title:"Task Complete",message:"Your task has finished."},error:h??{title:"Error Occurred",message:"An error occurred while processing your task."},question:p??{title:"Input Needed",message:"Please provide input to continue."},subtask:g??{title:"Subtask Complete",message:"A subtask has finished."}})}if(typeof e.summarizeLastMessage=="boolean"&&(n.summarizeLastMessage=e.summarizeLastMessage),typeof e.summaryThreshold=="number"&&Number.isFinite(e.summaryThreshold)&&(n.summaryThreshold=Math.max(0,Math.round(e.summaryThreshold))),typeof e.summaryLength=="number"&&Number.isFinite(e.summaryLength)&&(n.summaryLength=Math.max(10,Math.round(e.summaryLength))),typeof e.maxLastMessageLength=="number"&&Number.isFinite(e.maxLastMessageLength)&&(n.maxLastMessageLength=Math.max(10,Math.round(e.maxLastMessageLength))),typeof e.usageAutoRefresh=="boolean"&&(n.usageAutoRefresh=e.usageAutoRefresh),typeof e.usageRefreshIntervalMs=="number"&&Number.isFinite(e.usageRefreshIntervalMs)&&(n.usageRefreshIntervalMs=e.usageRefreshIntervalMs),(e.usageDisplayMode==="usage"||e.usageDisplayMode==="remaining")&&(n.usageDisplayMode=e.usageDisplayMode),Array.isArray(e.usageDropdownProviders)&&(n.usageDropdownProviders=e.usageDropdownProviders.filter(d=>typeof d=="string"&&d.length>0)),e.usageSelectedModels&&typeof e.usageSelectedModels=="object"){const d={};for(const[u,m]of Object.entries(e.usageSelectedModels))Array.isArray(m)&&(d[u]=m.filter(h=>typeof h=="string"));Object.keys(d).length>0&&(n.usageSelectedModels=d)}if(e.usageCollapsedFamilies&&typeof e.usageCollapsedFamilies=="object"){const d={};for(const[u,m]of Object.entries(e.usageCollapsedFamilies))Array.isArray(m)&&(d[u]=m.filter(h=>typeof h=="string"));Object.keys(d).length>0&&(n.usageCollapsedFamilies=d)}if(e.usageExpandedFamilies&&typeof e.usageExpandedFamilies=="object"){const d={};for(const[u,m]of Object.entries(e.usageExpandedFamilies))Array.isArray(m)&&(d[u]=m.filter(h=>typeof h=="string"));Object.keys(d).length>0&&(n.usageExpandedFamilies=d)}if(e.usageModelGroups&&typeof e.usageModelGroups=="object"){const d={};for(const[u,m]of Object.entries(e.usageModelGroups))if(m&&typeof m=="object"){const h=m,p={};Array.isArray(h.customGroups)&&(p.customGroups=h.customGroups.filter(g=>g&&typeof g=="object").map(g=>({id:String(g.id??""),label:String(g.label??""),models:Array.isArray(g.models)?g.models.filter(y=>typeof y=="string"):[],order:typeof g.order=="number"?g.order:0}))),h.modelAssignments&&typeof h.modelAssignments=="object"&&(p.modelAssignments=Object.fromEntries(Object.entries(h.modelAssignments).filter(([,g])=>typeof g=="string").map(([g,y])=>[g,String(y)]))),h.renamedGroups&&typeof h.renamedGroups=="object"&&(p.renamedGroups=Object.fromEntries(Object.entries(h.renamedGroups).filter(([,g])=>typeof g=="string").map(([g,y])=>[g,String(y)]))),Object.keys(p).length>0&&(d[u]=p)}Object.keys(d).length>0&&(n.usageModelGroups=d)}typeof e.inputSpellcheckEnabled=="boolean"&&(n.inputSpellcheckEnabled=e.inputSpellcheckEnabled),typeof e.showToolFileIcons=="boolean"&&(n.showToolFileIcons=e.showToolFileIcons),typeof e.showExpandedBashTools=="boolean"&&(n.showExpandedBashTools=e.showExpandedBashTools),typeof e.showExpandedEditTools=="boolean"&&(n.showExpandedEditTools=e.showExpandedEditTools),typeof e.chatRenderMode=="string"&&(e.chatRenderMode==="sorted"||e.chatRenderMode==="live")&&(n.chatRenderMode=e.chatRenderMode),typeof e.activityRenderMode=="string"&&(e.activityRenderMode==="collapsed"||e.activityRenderMode==="summary")&&(n.activityRenderMode=e.activityRenderMode),typeof e.mermaidRenderingMode=="string"&&(e.mermaidRenderingMode==="svg"||e.mermaidRenderingMode==="ascii")&&(n.mermaidRenderingMode=e.mermaidRenderingMode),typeof e.userMessageRenderingMode=="string"&&(e.userMessageRenderingMode==="markdown"||e.userMessageRenderingMode==="plain")&&(n.userMessageRenderingMode=e.userMessageRenderingMode),typeof e.stickyUserHeader=="boolean"&&(n.stickyUserHeader=e.stickyUserHeader),typeof e.fontSize=="number"&&Number.isFinite(e.fontSize)&&(n.fontSize=e.fontSize),typeof e.terminalFontSize=="number"&&Number.isFinite(e.terminalFontSize)&&(n.terminalFontSize=e.terminalFontSize),typeof e.padding=="number"&&Number.isFinite(e.padding)&&(n.padding=e.padding),typeof e.cornerRadius=="number"&&Number.isFinite(e.cornerRadius)&&(n.cornerRadius=e.cornerRadius),typeof e.inputBarOffset=="number"&&Number.isFinite(e.inputBarOffset)&&(n.inputBarOffset=e.inputBarOffset);const i=q3(e.favoriteModels,64);i&&(n.favoriteModels=i);const l=q3(e.recentModels,16);if(l&&(n.recentModels=l),typeof e.diffLayoutPreference=="string"&&(e.diffLayoutPreference==="dynamic"||e.diffLayoutPreference==="inline"||e.diffLayoutPreference==="side-by-side")&&(n.diffLayoutPreference=e.diffLayoutPreference),typeof e.diffViewMode=="string"&&(e.diffViewMode==="single"||e.diffViewMode==="stacked")&&(n.diffViewMode=e.diffViewMode),typeof e.directoryShowHidden=="boolean"&&(n.directoryShowHidden=e.directoryShowHidden),typeof e.filesViewShowGitignored=="boolean"&&(n.filesViewShowGitignored=e.filesViewShowGitignored),typeof e.openInAppId=="string"&&e.openInAppId.length>0&&(n.openInAppId=e.openInAppId),typeof e.pwaAppName=="string"){const d=e.pwaAppName.trim().replace(/\s+/g," ").slice(0,64);n.pwaAppName=d.length>0?d:""}const c=mw(e.skillCatalogs);return c&&(n.skillCatalogs=c),n},xw=async()=>{const t=a8();if(t)try{const e=await t.load();return G3(e.settings)}catch(e){console.warn("Failed to load shared settings from runtime settings API:",e)}try{const e=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return null;const n=await e.json().catch(()=>null);return G3(n)}catch(e){return console.warn("Failed to load shared settings from server:",e),null}},i8=async()=>{if(typeof window>"u")return;const t=o8(),e=n=>{yu(n);const r=()=>bu(n);if(t?.hasHydrated?.())r();else if(r(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),r()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:n}))};try{const n=await xw();n&&e(n)}catch(n){console.warn("Failed to synchronise settings:",n)}},Rs=async t=>{if(typeof window>"u")return;const e=a8();if(e)try{const n=await e.save(t);n&&(yu(n),bu(n));return}catch(n){console.warn("Failed to update settings via runtime settings API:",n)}try{const n=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok){console.warn("Failed to update shared settings via API:",n.status,n.statusText);return}const r=await n.json().catch(()=>null);r&&(yu(r),bu(r))}catch(n){console.warn("Failed to update shared settings via API:",n)}},l8=async()=>{if(typeof window>"u")return;const t=o8();try{const e=await fw();if(!e)return;const n=()=>uw(e);if(t?.hasHydrated?.()){n();return}if(n(),t?.onFinishHydration){const r=t.onFinishHydration(()=>{r?.(),n()})}}catch(e){console.warn("Failed to load appearance preferences:",e)}},vw=3e4,ww=40,jw=60,Sw=(t,e,n,r,o,a)=>{const i=t.trim(),l=e.trim().toLowerCase();return`${i}::${l}::${n}::${r?"1":"0"}::${o?"1":"0"}::${a}`},y2=xn()(In((t,e)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(n,r,o=jw,a){if(!n||n.trim().length===0)return[];const i=n.trim(),l=typeof r=="string"?r.trim():"",c=!!a?.includeHidden,d=a?.respectGitignore??!0,u=a?.type==="directory"?"directory":"file",m=Sw(i,l,o,c,d,u),h=Date.now(),p=e().cache[m];if(p&&h-p.timestamp<vw)return p.files;const g=e().inFlight[m];if(g)return g;const y=zt.searchFiles(l,{directory:i,limit:o,includeHidden:c,respectGitignore:d,dirs:u!=="file",type:u}).then(b=>(t(x=>{const v={...x.cache,[m]:{files:b,timestamp:Date.now()}},w=x.cacheKeys.filter(C=>C!==m);for(w.push(m);w.length>ww;){const C=w.shift();C&&delete v[C]}return{cache:v,cacheKeys:w}}),b)).finally(()=>{t(b=>{const x={...b.inFlight};return delete x[m],{inFlight:x}})});return t(b=>({inFlight:{...b.inFlight,[m]:y}})),y},invalidateDirectory(n){if(!n||n.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${n.trim()}::`;t(a=>{const i={...a.cache},l=a.cacheKeys.filter(u=>u.startsWith(o)?(delete i[u],!1):!0),c=Object.entries(a.inFlight).filter(([u])=>!u.startsWith(o)),d=Object.fromEntries(c);return{cache:i,cacheKeys:l,inFlight:d}})}}),{name:"file-search-store"})),Kn=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var kw={};let Io=null;const So=Bn(),Z3=So.getItem("lastDirectory"),Nw=typeof Z3=="string"&&Z3.length>0,r1=t=>{try{y2.getState().invalidateDirectory(t)}catch(e){console.warn("Failed to invalidate file search cache:",e)}},cl=t=>{const e=t.trim();if(!e)return e;const n=e.replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n},Cw=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},Q1=(t,e)=>{const n=Cw(t,e);return cl(n)},Mw=()=>{const t=So.getItem("homeDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=cl(t);return e.length>0?e:null},Aw=()=>{const t=So.getItem("lastDirectory");if(typeof t!="string"||t.trim().length===0)return null;const e=cl(t);return e.length>0?e:null},Fw=()=>{if(typeof process>"u")return null;const t=kw,e=t?.HOME||t?.USERPROFILE||(t?.HOMEDRIVE&&t?.HOMEPATH?`${t.HOMEDRIVE}${t.HOMEPATH}`:void 0);if(typeof e=="string"&&e.trim().length>0){const r=cl(e);return r.length>0?r:null}const n=process?.cwd?.();if(typeof n=="string"&&n.trim().length>0){const r=cl(n);return r.length>0?r:null}return null},N0=()=>{if(typeof window<"u"){if(Io)return Io;const e=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:null;if(e&&e.length>0)return Io=e,So.setItem("homeDirectory",e),e;const n=Mw();if(n&&!ln())return Io=n,n}const t=Fw();return t||"/"},Dw=t=>{if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const n=e.replace(/\\/g,"/");if(n.length>1){const r=n.replace(/\/+$/,"");if(r&&r.length>0)return r==="/"?null:r}return n==="/"||n.length===0?null:n},_w=t=>(Io=t,typeof window<"u"&&So.setItem("homeDirectory",t),Rs({homeDirectory:t}),t),c8=async()=>{const t=r=>{const o=Dw(r);return o?_w(o):null};try{const r=await zt.getFilesystemHome(),o=t(r);if(o)return o}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await zt.getSystemInfo(),o=t(r?.homeDirectory);if(o)return o}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await f2(),o=t(r);if(o)return o}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const e=N0(),n=t(e);return n||e},Bw=()=>{if(!ln())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const e=cl(t);return e.length>0?e:null},jc=Bw()||N0(),C0=(()=>{const t=Aw();return t&&!ln()?Q1(t,jc):jc})();C0&&zt.setDirectory(C0);const Ew=!!(jc&&jc!=="/"),Ds=xn()(In((t,e)=>({currentDirectory:C0,directoryHistory:[C0],historyIndex:0,homeDirectory:jc,hasPersistedDirectory:Nw,isHomeReady:Ew,isSwitchingDirectory:!1,setDirectory:(n,r)=>{const o=Io||e().homeDirectory||So.getItem("homeDirectory"),a=Q1(n,o);Kn()&&console.log("[DirectoryStore] setDirectory called with path:",a),zt.setDirectory(a),r1(),t(i=>{const l=[...i.directoryHistory.slice(0,i.historyIndex+1),a];return So.setItem("lastDirectory",a),Rs({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const n=e();if(n.historyIndex>0){const r=n.historyIndex-1,o=n.directoryHistory[r];zt.setDirectory(o),r1(),So.setItem("lastDirectory",o),Rs({lastDirectory:o}),t({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const n=e();if(n.historyIndex<n.directoryHistory.length-1){const r=n.historyIndex+1,o=n.directoryHistory[r];zt.setDirectory(o),r1(),So.setItem("lastDirectory",o),Rs({lastDirectory:o}),t({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:n,setDirectory:r}=e(),o=Io||e().homeDirectory||N0();if(n===o||n==="/")return;const a=n.endsWith("/")?n.slice(0,-1):n,i=a.lastIndexOf("/");if(i===-1){const l=Io||N0();r(l)}else r(i===0?"/":a.substring(0,i))},goHome:async()=>{const n=Io||e().homeDirectory||await c8();e().setDirectory(n)},synchronizeHomeDirectory:n=>{const r=e(),o=n;Io=o;const a=r.homeDirectory!==o,i=So.getItem("lastDirectory"),l=typeof i=="string"&&i.length>0,c=!l&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!c){r.isHomeReady||t({isHomeReady:!0});return}const d=typeof o=="string"&&o!==""&&o!=="/",u=r.currentDirectory?Q1(r.currentDirectory,o):r.currentDirectory,m=r.directoryHistory.map(y=>Q1(y,o)),h=m.some((y,b)=>y!==r.directoryHistory[b]),p=!!(u&&u!==r.currentDirectory),g={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:d};if(c?(g.currentDirectory=o,g.directoryHistory=[o],g.historyIndex=0,g.isSwitchingDirectory=!1):(p||h)&&(g.currentDirectory=u,g.directoryHistory=m,g.historyIndex=Math.min(r.historyIndex,m.length-1),g.isSwitchingDirectory=!1),t(()=>g),(c||p)&&d){const y=c?o:u;zt.setDirectory(y),r1(),So.setItem("lastDirectory",y),Rs({lastDirectory:y})}Rs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&c8().then(t=>{Ds.getState().synchronizeHomeDirectory(t)});const D4=[{key:"code",Icon:Dy,label:"Code"},{key:"terminal",Icon:uo,label:"Terminal"},{key:"rocket",Icon:ep,label:"Rocket"},{key:"flask",Icon:tp,label:"Lab"},{key:"gamepad",Icon:_y,label:"Game"},{key:"briefcase",Icon:n2,label:"Work"},{key:"home",Icon:r2,label:"Home"},{key:"globe",Icon:gc,label:"Web"},{key:"leaf",Icon:By,label:"Nature"},{key:"shield",Icon:tu,label:"Security"},{key:"palette",Icon:h4,label:"Design"},{key:"server",Icon:Aa,label:"Server"},{key:"phone",Icon:Ey,label:"Mobile"},{key:"database",Icon:sp,label:"Data"},{key:"lightbulb",Icon:Iy,label:"Idea"},{key:"music",Icon:Ty,label:"Music"},{key:"camera",Icon:Py,label:"Media"},{key:"book",Icon:o2,label:"Docs"},{key:"heart",Icon:p4,label:"Favorite"}],Vc=Object.fromEntries(D4.map(t=>[t.key,t.Icon])),b2=[{key:"keyword",label:"Purple",cssVar:"var(--syntax-keyword)"},{key:"string",label:"Green",cssVar:"var(--syntax-string)"},{key:"number",label:"Pink",cssVar:"var(--syntax-number)"},{key:"type",label:"Gold",cssVar:"var(--syntax-type)"},{key:"constant",label:"Cyan",cssVar:"var(--syntax-constant)"},{key:"comment",label:"Muted",cssVar:"var(--syntax-comment)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"primary",label:"Blue",cssVar:"var(--primary)"},{key:"success",label:"Green",cssVar:"var(--status-success)"}],Ea=Object.fromEntries(b2.map(t=>[t.key,t.cssVar])),ki=(t,e)=>{if(!t.iconImage||typeof t.iconImage.updatedAt!="number"||t.iconImage.updatedAt<=0)return null;const n=new URLSearchParams({v:String(t.iconImage.updatedAt)});return typeof e?.iconColor=="string"&&e.iconColor.trim()&&n.set("iconColor",e.iconColor.trim()),(e?.themeVariant==="light"||e?.themeVariant==="dark")&&n.set("theme",e.themeVariant),`/api/projects/${encodeURIComponent(t.id)}/icon?${n.toString()}`},Iw=t=>{const e=b2.map(a=>a.key),n=new Map;for(const a of e)n.set(a,0);for(const a of t)a.color&&n.has(a.color)&&n.set(a.color,(n.get(a.color)??0)+1);const r=Math.min(...n.values()),o=e.filter(a=>n.get(a)===r);return o[Math.floor(Math.random()*o.length)]},Ji=Bn(),d8="projects",xu="activeProjectId",Tw=(t,e)=>{const n=t.trim();return!n.startsWith("~")||!e?n:n==="~"?e:n.startsWith("~/")||n.startsWith("~\\")?`${e}${n.slice(1)}`:n},Pw=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,u8=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&Pw.test(e)?e.toLowerCase():null},x2=t=>{const e=t.trim();if(!e)return"";const n=Ji.getItem("homeDirectory")||Ds.getState().homeDirectory||"",o=Tw(e,n).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},f8=t=>{const e=x2(t);if(!e||e==="/")return"Root";const n=e.split("/").filter(Boolean);return(n[n.length-1]||e).replace(/[-_]/g," ").replace(/\b\w/g,o=>o.toUpperCase())},Rw=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Lw=t=>{if(!t||typeof t!="object")return;const e=t,n=typeof e.mime=="string"?e.mime.trim():"",r=typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?Math.max(0,Math.round(e.updatedAt)):0,o=e.source==="custom"||e.source==="auto"?e.source:null;if(!(!n||!r||!o))return{mime:n,updatedAt:r,source:o}},zw=t=>{const e=typeof t.type=="string"?t.type.trim().toLowerCase():"";if(e==="image/png"||e==="image/jpeg"||e==="image/svg+xml")return e;const n=t.name.toLowerCase();return n.endsWith(".png")?"image/png":n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".svg")?"image/svg+xml":null},Hw=async t=>await new Promise((e,n)=>{const r=new FileReader;r.onerror=()=>{n(new Error("Failed to read icon file"))},r.onload=()=>{const o=typeof r.result=="string"?r.result:"";if(!o){n(new Error("Failed to read icon file"));return}e(o)},r.readAsDataURL(t)}),m8=t=>{if(!Array.isArray(t))return[];const e=[],n=new Set,r=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const c=x2(l);if(!c||n.has(i)||r.has(c))continue;n.add(i),r.add(c);const d={id:i,path:c};if(typeof a.label=="string"&&a.label.trim().length>0&&(d.label=a.label.trim()),typeof a.icon=="string"&&a.icon.trim().length>0&&(d.icon=a.icon.trim()),a.iconImage===null)d.iconImage=null;else{const u=Lw(a.iconImage);u&&(d.iconImage=u)}if(typeof a.color=="string"&&a.color.trim().length>0&&(d.color=a.color.trim()),a.iconBackground===null)d.iconBackground=null;else{const u=u8(a.iconBackground);u&&(d.iconBackground=u)}typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(d.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(d.lastOpenedAt=a.lastOpenedAt),typeof a.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=a.sidebarCollapsed),e.push(d)}return e},Ow=()=>{try{const t=Ji.getItem(d8);return t?m8(JSON.parse(t)):[]}catch{return[]}},$w=()=>{try{const t=Ji.getItem(xu);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},_4=(t,e)=>{try{Ji.setItem(d8,JSON.stringify(t))}catch{}try{e?Ji.setItem(xu,e):Ji.removeItem(xu)}catch{}},Mi=(t,e)=>{_4(t,e),Rs({projects:t,activeProjectId:e??void 0})},Vw=Ow(),Uw=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const e=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof e!="string"||e.trim().length===0)return null;const n=x2(e);if(!n)return null;const r=`vscode:${n}`,o={id:r,path:n,label:f8(n),addedAt:Date.now(),lastOpenedAt:Date.now()};return Kn()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:r}},zr=Uw(),B4=zr?.projects??Vw,h8=zr?.activeProjectId??$w()??B4[0]?.id??null;zr&&_4(B4,h8);const ls=xn()(In((t,e)=>({projects:B4,activeProjectId:h8,validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const r=x2(n);return r?{ok:!0,normalizedPath:r}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(n,r)=>{if(zr)return null;const{validateProjectPath:o}=e(),a=o(n);if(!a.ok||!a.normalizedPath)return null;const i=a.normalizedPath,l=e().projects.find(g=>g.path===i);if(l)return e().setActiveProject(l.id),l;const c=Date.now(),d=r?.label?.trim()||f8(i),u=r?.id?.trim(),h={id:u&&!e().projects.some(g=>g.id===u)?u:Rw(),path:i,label:d,color:Iw(e().projects),addedAt:c,lastOpenedAt:c},p=[...e().projects,h];return t({projects:p}),Kn()&&console.info("[ProjectsStore] Added project",h),e().setActiveProject(h.id),e().discoverProjectIcon(h.id),h},removeProject:n=>{if(zr)return;const r=e(),o=r.projects.filter(i=>i.id!==n);let a=r.activeProjectId;if(r.activeProjectId===n&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),Mi(o,a),a){const i=o.find(l=>l.id===a);i&&(zt.setDirectory(i.path),Ds.getState().setDirectory(i.path,{showOverlay:!1}))}else Ds.getState().goHome()},setActiveProject:n=>{if(zr)return;const{projects:r,activeProjectId:o}=e();if(o===n)return;const a=r.find(c=>c.id===n);if(!a)return;const i=Date.now(),l=r.map(c=>c.id===n?{...c,lastOpenedAt:i}:c);t({projects:l,activeProjectId:n}),Mi(l,n),zt.setDirectory(a.path),Ds.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:n=>{if(zr)return;const{projects:r,activeProjectId:o}=e();if(o===n||!r.find(c=>c.id===n))return;const i=Date.now(),l=r.map(c=>c.id===n?{...c,lastOpenedAt:i}:c);t({projects:l,activeProjectId:n}),Mi(l,n)},renameProject:(n,r)=>{if(zr)return;const o=r.trim();if(!o)return;const{projects:a,activeProjectId:i}=e(),l=a.map(c=>c.id===n?{...c,label:o}:c);t({projects:l}),Mi(l,i)},updateProjectMeta:(n,r)=>{if(zr)return;const{projects:o,activeProjectId:a}=e(),i=o.map(l=>{if(l.id!==n)return l;const c={...l};if(r.label!==void 0){const d=r.label.trim();d&&(c.label=d)}return r.icon!==void 0&&(c.icon=r.icon),r.color!==void 0&&(c.color=r.color),r.iconBackground!==void 0&&(c.iconBackground=u8(r.iconBackground)),c});t({projects:i}),Mi(i,a)},uploadProjectIcon:async(n,r)=>{if(zr)return{ok:!1,error:"Custom icons are not supported in this runtime"};const o=zw(r);if(!o)return{ok:!1,error:"Only PNG, JPEG, and SVG are supported"};if(!Number.isFinite(r.size)||r.size<=0)return{ok:!1,error:"Icon file is empty"};if(r.size>5*1024*1024)return{ok:!1,error:"Icon exceeds size limit (5 MB)"};try{const i=(await Hw(r)).replace(/^data:[^;]+;/i,`data:${o};`),l=await fetch(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:i})});if(!l.ok)return{ok:!1,error:(await l.json().catch(()=>null))?.error||"Failed to upload project icon"};const c=await l.json().catch(()=>null);return c?.settings&&e().synchronizeFromSettings(c.settings),{ok:!0}}catch(a){return{ok:!1,error:(a instanceof Error?a.message:String(a))||"Failed to upload project icon"}}},removeProjectIcon:async n=>{if(zr)return{ok:!1,error:"Custom icons are not supported in this runtime"};try{const r=await fetch(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"DELETE",headers:{Accept:"application/json"}});if(!r.ok)return{ok:!1,error:(await r.json().catch(()=>null))?.error||"Failed to remove project icon"};const o=await r.json().catch(()=>null);return o?.settings&&e().synchronizeFromSettings(o.settings),{ok:!0}}catch(r){return{ok:!1,error:(r instanceof Error?r.message:String(r))||"Failed to remove project icon"}}},discoverProjectIcon:async(n,r)=>{if(zr)return{ok:!1,error:"Custom icons are not supported in this runtime"};try{const o=await fetch(`/api/projects/${encodeURIComponent(n)}/icon/discover`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({force:r?.force===!0})}),a=await o.json().catch(()=>null);return o.ok?(a?.settings&&e().synchronizeFromSettings(a.settings),{ok:!0,skipped:a?.skipped===!0,reason:typeof a?.reason=="string"?a.reason:void 0}):{ok:!1,error:a?.error||"Failed to discover project icon"}}catch(o){return{ok:!1,error:(o instanceof Error?o.message:String(o))||"Failed to discover project icon"}}},reorderProjects:(n,r)=>{if(zr)return;const{projects:o,activeProjectId:a}=e();if(n<0||n>=o.length||r<0||r>=o.length||n===r)return;const i=[...o],[l]=i.splice(n,1);i.splice(r,0,l),t({projects:i}),Mi(i,a)},synchronizeFromSettings:n=>{if(zr)return;const r=m8(n.projects??[]),o=typeof n.activeProjectId=="string"&&n.activeProjectId.trim()?n.activeProjectId.trim():null,a=e(),i=JSON.stringify(a.projects)!==JSON.stringify(r),l=a.activeProjectId!==o;if(!(!i&&!l)&&(t({projects:r,activeProjectId:o}),_4(r,o),o)){const c=r.find(d=>d.id===o);c&&(zt.setDirectory(c.path),Ds.getState().setDirectory(c.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:n,activeProjectId:r}=e();return r?n.find(o=>o.id===r)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const e=t.detail;e&&typeof e=="object"&&ls.getState().synchronizeFromSettings(e)});const Ww=new Set(["init","review"]),Xi=t=>Ww.has(t.name),nc="useCommandsStore",vu=t=>new Promise(e=>setTimeout(e,t)),o1=()=>{try{const e=ls.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=zt.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},qw=2e4,K3=300,Q3=4,Gw=800,Zw=200,Kw=2e3,Ia=xn()(In(hr((t,e)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:n=>{t({selectedCommandName:n})},setCommandDraft:n=>{t({commandDraft:n})},loadCommands:async()=>{t({isLoading:!0});const n=e().commands;let r=null;for(let o=0;o<3;o++)try{const a=o1(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await zt.withDirectory(a,()=>zt.listCommandsWithDetails()),c=await Promise.all(l.map(async d=>{try{const u=await fetch(`/api/config/commands/${encodeURIComponent(d.name)}${i}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(u.ok){const m=await u.json();let h=m.scope;if(!h&&m.sources){const p=m.sources;h=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return h==="project"||h==="user"?{...d,scope:h}:{...d,scope:void 0}}}catch(u){console.warn(`[CommandsStore] Failed to fetch config for command ${d.name}:`,u)}return d}));return JSON.stringify(n)!==JSON.stringify(c)?t({commands:c,isLoading:!1}):t({isLoading:!1}),!0}catch(a){r=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load commands:",r),t({commands:n,isLoading:!1}),!1},createCommand:async n=>{kr("Creating command configuration…");let r=!1;try{console.log("[CommandsStore] Creating command:",n.name);const o={template:n.template||""};n.description&&(o.description=n.description),n.agent&&(o.agent=n.agent),n.model&&(o.model=n.model),n.scope&&(o.scope=n.scope),console.log("[CommandsStore] Command config to save:",o);const a=o1(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(n.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to create command";throw new Error(m)}if(console.log("[CommandsStore] Command created successfully"),c?.requiresReload??!0)return r=!0,await $2({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await e().loadCommands();return u&&Ao("commands",{source:nc}),u}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{r||fr()}},updateCommand:async(n,r)=>{kr("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",n),console.log("[CommandsStore] Config received:",r);const a={};r.description!==void 0&&(a.description=r.description),r.agent!==void 0&&(a.agent=r.agent),r.model!==void 0&&(a.model=r.model),r.template!==void 0&&(a.template=r.template),console.log("[CommandsStore] Command config to update:",a);const i=o1(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(n)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),d=await c.json().catch(()=>null);if(!c.ok){const h=d?.error||"Failed to update command";throw new Error(h)}if(console.log("[CommandsStore] Command updated successfully"),d?.requiresReload??!0)return o=!0,await $2({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await e().loadCommands();return m&&Ao("commands",{source:nc}),m}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||fr()}},deleteCommand:async n=>{kr("Deleting command configuration…");let r=!1;try{const o=o1(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(n)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to delete command";throw new Error(u)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return r=!0,await $2({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const d=await e().loadCommands();return d&&Ao("commands",{source:nc}),e().selectedCommandName===n&&t({selectedCommandName:null}),d}catch(o){return console.error("Failed to delete command:",o),!1}finally{r||fr()}},getCommandByName:n=>{const{commands:r}=e();return r.find(o=>o.name===n)}}),{name:"commands-store",storage:xr(()=>Bn()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Ia);async function Qw(t){const e=typeof t=="number"&&t>0?Math.min(t,K3):0;e>0&&await vu(e);const n=Date.now();let r=0,o=null;for(;Date.now()-n<qw;){r+=1,Sr(`Waiting for OpenCode… (attempt ${r})`);try{if(await zt.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-n,i=r<=Q3&&a<1200?K3:Math.min(Gw+Math.max(0,r-Q3)*Zw,Kw);await vu(i)}throw o||new Error("OpenCode did not become ready in time")}async function $2(t={}){const{message:e,delayMs:n}=t;try{Sr(e||"Refreshing commands…")}catch{}try{await Qw(n),Sr("Refreshing commands…"),await Ia.getState().loadCommands(),Ao("commands",{source:nc})}catch(r){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",r),Sr("OpenCode refresh failed. Please retry refreshing configuration manually."),await vu(1500)}finally{fr()}}let Y3=null;Y3||(Y3=p2(t=>{if(t.source!==nc&&wc(t,"commands")){const{loadCommands:e}=Ia.getState();e()}}));const ua=()=>{const t=zt.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const e=window.__zustand_directory_store__;if(e)return e.getState().currentDirectory}catch{}return null};function Yw(t){const e=t.replace(/\\/g,"/"),n=e.lastIndexOf("/skills/");if(n===-1)return;const o=e.substring(n+8).split("/");return o.length>=3?o[0]:void 0}const rc="useSkillsStore",wu=t=>new Promise(e=>setTimeout(e,t)),Jw=2e4,J3=300,X3=4,Xw=800,ej=200,tj=2e3,Hr=xn()(In(hr((t,e)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:n=>{t({selectedSkillName:n})},setSkillDraft:n=>{t({skillDraft:n})},loadSkills:async()=>{t({isLoading:!0});const n=e().skills;let r=null;for(let o=0;o<3;o++)try{const a=ua(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${i}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const u=((await l.json()).skills||[]).map(m=>({name:m.name,path:m.path,scope:m.scope??"user",source:m.source??"opencode",description:m.sources?.md?.description||"",group:Yw(m.path)}));return t({skills:u,isLoading:!1}),!0}catch(a){r=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load skills:",r),t({skills:n,isLoading:!1}),!1},getSkillDetail:async n=>{try{const r=ua(),o=r?`?directory=${encodeURIComponent(r)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(n)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async n=>{kr("Creating skill...");let r=!1;try{const o={name:n.name,description:n.description};n.instructions&&(o.instructions=n.instructions),n.scope&&(o.scope=n.scope),n.source&&(o.source=n.source),n.supportingFiles&&(o.supportingFiles=n.supportingFiles);const a=ua(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(n.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to create skill";throw new Error(m)}if(c?.requiresReload??!1)return r=!0,await Y1({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await e().loadSkills();return u&&Ao("skills",{source:rc}),u}catch{return!1}finally{r||fr()}},updateSkill:async(n,r)=>{kr("Updating skill...");let o=!1;try{const a={};r.description!==void 0&&(a.description=r.description),r.instructions!==void 0&&(a.instructions=r.instructions),r.supportingFiles!==void 0&&(a.supportingFiles=r.supportingFiles);const i=ua(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(n)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),d=await c.json().catch(()=>null);if(!c.ok){const h=d?.error||"Failed to update skill";throw new Error(h)}if(d?.requiresReload??!1)return o=!0,await Y1({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await e().loadSkills();return m&&Ao("skills",{source:rc}),m}catch{return!1}finally{o||fr()}},deleteSkill:async n=>{kr("Deleting skill...");let r=!1;try{const o=ua(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(n)}${a}`,{method:"DELETE"}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to delete skill";throw new Error(u)}if(l?.requiresReload??!1)return r=!0,await Y1({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const d=await e().loadSkills();return d&&Ao("skills",{source:rc}),e().selectedSkillName===n&&t({selectedSkillName:null}),d}catch{return!1}finally{r||fr()}},getSkillByName:n=>{const{skills:r}=e();return r.find(o=>o.name===n)},readSupportingFile:async(n,r)=>{try{const o=ua(),a=o?`&directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(n)}/files/${encodeURIComponent(r)}?${a.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(n,r,o)=>{try{const a=ua(),i=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(n)}/files/${encodeURIComponent(r)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(n,r)=>{try{const o=ua(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(n)}/files/${encodeURIComponent(r)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:xr(()=>Bn()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Hr);async function sj(t){const e=typeof t=="number"&&t>0?Math.min(t,J3):0;e>0&&await wu(e);const n=Date.now();let r=0,o=null;for(;Date.now()-n<Jw;){r+=1,Sr(`Waiting for OpenCode… (attempt ${r})`);try{if(await zt.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-n,i=r<=X3&&a<1200?J3:Math.min(Xw+Math.max(0,r-X3)*ej,tj);await wu(i)}throw o||new Error("OpenCode did not become ready in time")}async function Y1(t){try{Sr(t?.message||"Refreshing skills…")}catch{}try{await sj(t?.delayMs),Sr("Refreshing skills…"),await Hr.getState().loadSkills()&&Ao("skills",{source:rc})}catch{Sr("OpenCode refresh failed. Please retry."),await wu(1500)}finally{fr()}}let ef=null;ef||(ef=p2(t=>{if(t.source!==rc&&wc(t,"skills")){const{loadSkills:e}=Hr.getState();e()}}));const tf=[{id:"anthropic",label:"Anthropic",description:"Anthropic's public skills repository",source:"anthropics/skills",defaultSubpath:"skills",sourceType:"github"},{id:"clawdhub",label:"ClawdHub",description:"Community skill registry with vector search",source:"clawdhub:registry",sourceType:"clawdhub"}],a1=()=>{const t=zt.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const e=window.__zustand_directory_store__;if(e)return e.getState().currentDirectory}catch{}return null},Uc=xn()(In((t,e)=>({sources:tf,itemsBySource:{},selectedSourceId:tf[0]?.id??null,pageInfoBySource:{},loadedSourceIds:{},clawdhubHasMoreBySource:{},isLoadingCatalog:!1,isLoadingSource:!1,isLoadingMore:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:n=>t({selectedSourceId:n}),loadCatalog:async n=>{t({isLoadingCatalog:!0,lastCatalogError:null});const r={sources:e().sources,itemsBySource:e().itemsBySource,pageInfoBySource:e().pageInfoBySource,loadedSourceIds:e().loadedSourceIds,clawdhubHasMoreBySource:e().clawdhubHasMoreBySource};let o=null;try{const a=n?.refresh?"?refresh=true":"",i=new AbortController,l=window.setTimeout(()=>i.abort(),3e3);try{const c=await fetch(`/api/config/skills/catalog${a}`,{method:"GET",headers:{Accept:"application/json"},signal:i.signal}),d=await c.json().catch(()=>null);if(!c.ok||!d?.ok)throw o=d?.error||{kind:"unknown",message:`Failed to load catalog (${c.status})`},new Error(o.message);const u=d.sources&&d.sources.length>0?d.sources:r.sources,m=n?.refresh?{}:e().itemsBySource||{},h=n?.refresh?{}:e().pageInfoBySource||{},p=n?.refresh?{}:e().loadedSourceIds||{},g=n?.refresh?{}:e().clawdhubHasMoreBySource||{},y=e().selectedSourceId,b=y&&u.some(x=>x.id===y)?y:u[0]?.id??null;return t({sources:u,itemsBySource:m,pageInfoBySource:h,loadedSourceIds:p,clawdhubHasMoreBySource:g,selectedSourceId:b}),!0}finally{window.clearTimeout(l)}}catch(a){return o=o||{kind:"unknown",message:a instanceof Error?a.message:String(a)},t({sources:r.sources,itemsBySource:r.itemsBySource,pageInfoBySource:r.pageInfoBySource,loadedSourceIds:r.loadedSourceIds,clawdhubHasMoreBySource:r.clawdhubHasMoreBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}},loadSource:async(n,r)=>{if(!n)return!1;t({isLoadingSource:!0,lastCatalogError:null});try{const o=a1(),a=r?.refresh?"&refresh=true":"",i=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(n)}${a}`:`?sourceId=${encodeURIComponent(n)}${a}`,l=await fetch(`/api/config/skills/catalog/source${i}`,{method:"GET",headers:{Accept:"application/json"}}),c=await l.json().catch(()=>null),d=Array.isArray(c?.items);if(!l.ok||!c?.ok&&!d){const h=await fetch(`/api/config/skills/catalog${i}`,{method:"GET",headers:{Accept:"application/json"}}),p=await h.json().catch(()=>null),g=p?.itemsBySource?.[n];return h.ok&&p?.ok&&Array.isArray(g)?(t(y=>({itemsBySource:{...y.itemsBySource,[n]:g},pageInfoBySource:{...y.pageInfoBySource,[n]:{nextCursor:null}},loadedSourceIds:{...y.loadedSourceIds,[n]:!0},clawdhubHasMoreBySource:{...y.clawdhubHasMoreBySource,[n]:!1}})),!0):(t({lastCatalogError:c?.error||{kind:"unknown",message:`Failed to load source (${l.status})`}}),!1)}const u=c?.items||[],m=c?.nextCursor??null;return t(h=>({itemsBySource:{...h.itemsBySource,[n]:u},pageInfoBySource:{...h.pageInfoBySource,[n]:{nextCursor:m}},loadedSourceIds:{...h.loadedSourceIds,[n]:!0},clawdhubHasMoreBySource:{...h.clawdhubHasMoreBySource,[n]:u.length>0}})),!0}catch(o){return t({lastCatalogError:{kind:"unknown",message:o instanceof Error?o.message:String(o)}}),!1}finally{t({isLoadingSource:!1})}},loadMoreClawdHub:async()=>{const n=e().selectedSourceId;if(!n)return!1;const o=e().pageInfoBySource[n]?.nextCursor||null;t({isLoadingMore:!0});try{const a=a1(),i=[`sourceId=${encodeURIComponent(n)}`];a&&i.push(`directory=${encodeURIComponent(a)}`),o&&i.push(`cursor=${encodeURIComponent(o)}`);const l=`?${i.join("&")}`,c=await fetch(`/api/config/skills/catalog/source${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await c.json().catch(()=>null);if(!c.ok||!d?.ok)return!1;const u=d.nextCursor??null,m=e().itemsBySource[n]||[],h=d.items||[],p=new Map(m.map(b=>[`${b.sourceId}:${b.skillDir}`,b]));let g=0;for(const b of h){const x=`${b.sourceId}:${b.skillDir}`;p.has(x)||(g+=1),p.set(x,b)}const y=h.length===0||g===0;return t(b=>({itemsBySource:{...b.itemsBySource,[n]:Array.from(p.values())},pageInfoBySource:{...b.pageInfoBySource,[n]:{nextCursor:u}},clawdhubHasMoreBySource:{...b.clawdhubHasMoreBySource,[n]:!y}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async n=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const r=a1(),o=r?`?directory=${encodeURIComponent(r)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)}),i=await a.json().catch(()=>null);if(!a.ok||!i){const l=i?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:l}),{ok:!1,error:l}}return i.ok?(t({scanResults:i.items||[]}),i):(t({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{t({isScanning:!1})}},installSkills:async(n,r)=>{kr("Installing skills…"),t({isInstalling:!0,lastInstallError:null});let o=!1;try{const i=(typeof r?.directory=="string"&&r.directory.trim().length>0?r.directory.trim():null)??a1(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await fetch(`/api/config/skills/install${l}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)}),d=await c.json().catch(()=>null);if(!d){const u={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:u}),Sr("Failed to install skills. Please retry."),{ok:!1,error:u}}if(!c.ok||!d.ok){const u=d.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:u}),Sr(u.message||"Failed to install skills. Please retry."),{ok:!1,error:u}}return d.requiresReload?(o=!0,await Y1({message:d.message,delayMs:d.reloadDelayMs})):(Sr(d.message||"Refreshing skills…"),Hr.getState().loadSkills()),d}catch(a){const i={kind:"unknown",message:a instanceof Error?a.message:String(a)};return t({lastInstallError:i}),Sr("Failed to install skills. Please retry."),{ok:!1,error:i}}finally{t({isInstalling:!1}),o||fr()}}}),{name:"skills-catalog-store"})),nj=()=>{const t=zt.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const e=window.__zustand_directory_store__;if(e)return e.getState().currentDirectory}catch{}return null},i1=()=>{try{const e=ls.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=zt.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null};function rj(t){if(!t)return;const e=t.replace(/\\/g,"/"),n=e.lastIndexOf("/agents/");if(n===-1)return;const o=e.substring(n+8).split("/");return o.length>1?o[0]:void 0}const Vi=t=>{const e=t;return e.native===!0||e.builtIn===!0},p8=t=>{const e=t;return e.hidden===!0||e.options?.hidden===!0},g8=t=>t.filter(e=>!p8(e)),J1="useAgentsStore",M0=t=>new Promise(e=>setTimeout(e,t)),oj=2e4,sf=300,nf=4,aj=800,ij=200,lj=2e3,Ni=xn()(In(hr((t,e)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:n=>{t({selectedAgentName:n})},setAgentDraft:n=>{t({agentDraft:n})},loadAgents:async()=>{t({isLoading:!0});const n=e().agents;for(let r=0;r<3;r++)try{const o=i1(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await zt.withDirectory(o,()=>zt.listAgents()),l=await Promise.all(i.map(async c=>{try{const d=await fetch(`/api/config/agents/${encodeURIComponent(c.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(d.ok){const u=await d.json();let m=u.scope;if(!m&&u.sources){const g=u.sources;m=(g.md?.exists?g.md.scope:void 0)??(g.json?.exists?g.json.scope:void 0)??g.md?.scope??g.json?.scope}const h=u.sources?.md?.path,p=rj(h);return m==="project"||m==="user"?{...c,scope:m,group:p}:{...c,scope:void 0,group:p}}}catch(d){console.warn(`[AgentsStore] Failed to fetch config for agent ${c.name}:`,d)}return c}));return JSON.stringify(n)!==JSON.stringify(l)?t({agents:l,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async n=>{kr("Creating agent configuration…");let r=!1;try{console.log("[AgentsStore] Creating agent:",n.name);const o={mode:n.mode||"subagent"};n.description&&(o.description=n.description),n.model&&(o.model=n.model),n.temperature!==void 0&&(o.temperature=n.temperature),n.top_p!==void 0&&(o.top_p=n.top_p),n.prompt&&(o.prompt=n.prompt),n.permission&&(o.permission=n.permission),n.disable!==void 0&&(o.disable=n.disable),n.scope&&(o.scope=n.scope),console.log("[AgentsStore] Agent config to save:",o);const a=i1(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(n.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to create agent";throw new Error(m)}if(c?.requiresReload??!0)return r=!0,await Ca({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await e().loadAgents();return u&&Ao("agents",{source:J1}),u}catch(o){return console.error("Failed to create agent:",o),!1}finally{r||fr()}},updateAgent:async(n,r)=>{kr("Updating agent configuration…");let o=!1;try{const a={};r.mode!==void 0&&(a.mode=r.mode),r.description!==void 0&&(a.description=r.description),r.model!==void 0&&(a.model=r.model),r.temperature!==void 0&&(a.temperature=r.temperature),r.top_p!==void 0&&(a.top_p=r.top_p),r.prompt!==void 0&&(a.prompt=r.prompt),r.permission!==void 0&&(a.permission=r.permission),r.disable!==void 0&&(a.disable=r.disable);const i=i1(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(n)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),d=await c.json().catch(()=>null);if(!c.ok){const h=d?.error||"Failed to update agent";throw new Error(h)}if(d?.requiresReload??!0)return o=!0,await Ca({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await e().loadAgents();return m&&Ao("agents",{source:J1}),m}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||fr()}},deleteAgent:async n=>{kr("Deleting agent configuration…");let r=!1;try{const o=i1(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(n)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to delete agent";throw new Error(u)}if(l?.requiresReload??!0)return r=!0,await Ca({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const d=await e().loadAgents();return d&&Ao("agents",{source:J1}),e().selectedAgentName===n&&t({selectedAgentName:null}),d}catch{return!1}finally{r||fr()}},getAgentByName:n=>{const{agents:r}=e();return r.find(o=>o.name===n)},getVisibleAgents:()=>{const{agents:n}=e();return g8(n)}}),{name:"agents-store",storage:xr(()=>Bn()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Ni);async function cj(t){const e=typeof t=="number"&&t>0?Math.min(t,sf):0;e>0&&await M0(e);const n=Date.now();let r=0,o=null;for(;Date.now()-n<oj;){r+=1,Sr(`Waiting for OpenCode… (attempt ${r})`);try{if(await zt.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-n,i=r<=nf&&a<1200?sf:Math.min(aj+Math.max(0,r-nf)*ij,lj);await M0(i)}throw o||new Error("OpenCode did not become ready in time")}const dj=t=>{if(!t||t.length===0)return["all"];const e=Array.from(new Set(t));return e.includes("all")?["all"]:e};async function uj(t={}){const{message:e,delayMs:n}=t,r=dj(t.scopes),o=t.mode??(r.includes("all")?"projects":"active");try{Sr(e||"Refreshing configuration…")}catch{}try{await cj(n);const a=Yt.getState(),i=Ni.getState(),l=Ia.getState(),c=Hr.getState(),d=Uc.getState(),u=r.includes("all")||r.includes("providers"),m=r.includes("all")||r.includes("agents"),h=r.includes("all")||r.includes("agents"),p=r.includes("all")||r.includes("commands"),g=r.includes("all")||r.includes("skills"),y=nj(),b=o==="projects"?ls.getState().projects:[],x=Array.from(new Set([...y?[y]:[],...b.map(C=>C.path).filter(Boolean)]));r.includes("all")&&o==="projects"&&Yt.setState({directoryScoped:{}});const v=[];for(const C of x)u&&v.push(a.loadProviders({directory:C}).then(()=>{})),m&&v.push(a.loadAgents({directory:C}).then(()=>{}));const w=[];h&&w.push(i.loadAgents().then(()=>{})),p&&w.push(l.loadCommands().then(()=>{})),g&&(w.push(c.loadSkills().then(()=>{})),w.push(d.loadCatalog().then(()=>{}))),Sr("Refreshing configuration…"),await Promise.all([...v,...w])}catch{Sr("OpenCode refresh failed. Please retry."),await M0(1500)}finally{fr()}}async function Ca(t){await uj(t)}async function oc(t){kr(t?.message||"Reloading OpenCode configuration…");try{const e=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),n=await e.json().catch(()=>null);if(!e.ok){const o=n?.error||"Failed to reload configuration";throw new Error(o)}const r={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};n?.requiresReload?await Ca({...r,message:n.message,delayMs:n.reloadDelayMs}):await Ca(r)}catch(e){throw console.error("[reloadOpenCodeConfiguration] Failed:",e),Sr("Failed to reload configuration. Please try again."),await M0(2e3),fr(),e}}let rf=null;rf||(rf=p2(t=>{if(t.source!==J1&&wc(t,"agents")){const{loadAgents:e}=Ni.getState();e()}}));const fj="https://models.dev/api.json",mj="/api/openchamber/models-metadata",of="opencode",af="big-pickle",za="zen",lf="big-pickle",hj=async()=>{try{const t=gr()?.settings;if(t)try{const d=(await t.load())?.settings;if(d){const u=typeof d?.defaultModel=="string"?d.defaultModel.trim():"",m=typeof d?.defaultVariant=="string"?d.defaultVariant.trim():"",h=typeof d?.defaultAgent=="string"?d.defaultAgent.trim():"",p=typeof d?.gitmojiEnabled=="boolean"?d.gitmojiEnabled:void 0,g=typeof d?.zenModel=="string"?d.zenModel.trim():"";return{defaultModel:u.length>0?u:void 0,defaultVariant:m.length>0?m:void 0,defaultAgent:h.length>0?h:void 0,autoCreateWorktree:typeof d?.autoCreateWorktree=="boolean"?d.autoCreateWorktree:void 0,gitmojiEnabled:p,zenModel:g.length>0?g:void 0}}}catch{}const e=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return{};const n=await e.json(),r=typeof n?.defaultModel=="string"?n.defaultModel.trim():"",o=typeof n?.defaultVariant=="string"?n.defaultVariant.trim():"",a=typeof n?.defaultAgent=="string"?n.defaultAgent.trim():"",i=typeof n?.gitmojiEnabled=="boolean"?n.gitmojiEnabled:void 0,l=typeof n?.zenModel=="string"?n.zenModel.trim():"";return{defaultModel:r.length>0?r:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof n?.autoCreateWorktree=="boolean"?n.autoCreateWorktree:void 0,gitmojiEnabled:i,zenModel:l.length>0?l:void 0}}catch{return{}}},l1=t=>{if(!t||typeof t!="string")return null;const e=t.split("/");return e.length!==2||!e[0]||!e[1]?null:{providerId:e[0],modelId:e[1]}},pj=t=>t?.toLowerCase?.()??"",gj=t=>t==="primary"||t==="all"||t===void 0||t===null,A0=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},cf=(t,e,n)=>{const r=t.find(o=>o.id===e);return r?r.models.some(o=>o.id===n):!1},V2=({providers:t,settingsZenModel:e})=>{const n=A0(e);if(!Array.isArray(t)||t.length===0)return n?{providerId:za,modelId:n}:null;if(n&&cf(t,za,n))return{providerId:za,modelId:n};if(cf(t,za,lf))return{providerId:za,modelId:lf};const r=t.find(o=>o.id===za);if(r?.models.length){const o=Math.floor(Math.random()*r.models.length),a=A0(r.models[o]?.id);if(a)return{providerId:za,modelId:a}}return null},Sc=t=>typeof t=="object"&&t!==null,F0=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),yj=t=>{if(!Sc(t))return!1;const e=t;if(e.modalities){const{input:n,output:r}=e.modalities;if(n&&!F0(n)||r&&!F0(r))return!1}return!0},bj=t=>{if(!Sc(t))return!1;const e=t;return e.models===void 0||Sc(e.models)},y8=(t,e)=>{const n=pj(t);return!n||!e?"":`${n}/${e}`},xj=t=>{const e=new Map;if(!Sc(t))return e;for(const[n,r]of Object.entries(t)){if(!bj(r))continue;const o=typeof r.id=="string"&&r.id.length>0?r.id:n,a=r.models;if(!(!a||!Sc(a)))for(const[i,l]of Object.entries(a)){if(!yj(l))continue;const c=typeof i=="string"&&i.length>0?i:l.id;if(!c||typeof c!="string"||c.length===0)continue;const d={id:typeof l.id=="string"&&l.id.length>0?l.id:c,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:F0(l.modalities.input)?l.modalities.input:void 0,output:F0(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},u=y8(o,c);u&&e.set(u,d)}}return e},vj=async()=>{if(typeof fetch!="function")return new Map;const t=[mj,fj];for(const e of t){const n=typeof AbortController<"u"?new AbortController:void 0,r=n?setTimeout(()=>n.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(e),a={signal:n?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(e,a);if(!i.ok)throw new Error(`Metadata request to ${e} returned status ${i.status}`);const l=await i.json();return xj(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${e})`):console.warn(`Failed to fetch model metadata from ${e}:`,o)}finally{r&&clearTimeout(r)}}return new Map};let U2=null;const wj=(t,e)=>{t().size>0||U2||(U2=vj().then(r=>(r.size>0&&e(r),r)).catch(()=>new Map).finally(()=>{U2=null}))},jj=t=>new Promise(e=>setTimeout(e,t)),E4="__global__",el=t=>{const e=typeof t=="string"?t.trim():"";return e.length>0?e:E4},Ai=t=>t===E4?null:t,Sj=()=>{if(typeof window>"u")return E4;const t=zt.getDirectory()??Ds.getState().currentDirectory;return el(t)},Yt=xn()(In(hr((t,e)=>({activeDirectoryKey:Sj(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,settingsGitmojiEnabled:!1,settingsZenModel:void 0,voiceProvider:(()=>{if(typeof window<"u"){const n=localStorage.getItem("voiceProvider");if(n==="openai"||n==="browser"||n==="say")return n}return"browser"})(),speechRate:(()=>{if(typeof window<"u"){const n=localStorage.getItem("speechRate");if(n){const r=parseFloat(n);if(!isNaN(r)&&r>=.5&&r<=2)return r}}return 1})(),speechPitch:(()=>{if(typeof window<"u"){const n=localStorage.getItem("speechPitch");if(n){const r=parseFloat(n);if(!isNaN(r)&&r>=.5&&r<=2)return r}}return 1})(),speechVolume:(()=>{if(typeof window<"u"){const n=localStorage.getItem("speechVolume");if(n){const r=parseFloat(n);if(!isNaN(r)&&r>=0&&r<=1)return r}}return 1})(),sayVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sayVoice");if(n)return n}return"Samantha"})(),browserVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("browserVoice");if(n)return n}return""})(),openaiVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiVoice");if(n)return n}return"nova"})(),openaiApiKey:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiApiKey");if(n)return n}return""})(),showMessageTTSButtons:typeof window<"u"&&localStorage.getItem("showMessageTTSButtons")==="true",voiceModeEnabled:typeof window<"u"&&localStorage.getItem("voiceModeEnabled")==="true",summarizeMessageTTS:typeof window<"u"&&localStorage.getItem("summarizeMessageTTS")==="true",summarizeVoiceConversation:typeof window<"u"&&localStorage.getItem("summarizeVoiceConversation")==="true",summarizeCharacterThreshold:(()=>{if(typeof window<"u"){const n=localStorage.getItem("summarizeCharacterThreshold");if(n){const r=parseInt(n,10);if(!isNaN(r)&&r>=50&&r<=2e3)return r}}return 200})(),summarizeMaxLength:(()=>{if(typeof window<"u"){const n=localStorage.getItem("summarizeMaxLength");if(n){const r=parseInt(n,10);if(!isNaN(r)&&r>=50&&r<=2e3)return r}}return 500})(),activateDirectory:async n=>{const r=el(n);t(o=>{const a=o.directoryScoped[r];return a?{activeDirectoryKey:r,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:r,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),e().isConnected&&(await e().loadProviders({directory:Ai(r)}),await e().loadAgents({directory:Ai(r)}))},loadProviders:async n=>{const r=el(n?.directory??Ai(e().activeDirectoryKey)),o=e().directoryScoped[r],a=o?.providers??(e().activeDirectoryKey===r?e().providers:[]),i=o?.defaultProviders??(e().activeDirectoryKey===r?e().defaultProviders:{});let l=null;for(let c=0;c<3;c++)try{wj(()=>e().modelsMetadata,p=>t({modelsMetadata:p}));const d=await zt.withDirectory(Ai(r),()=>zt.getProviders()),u=Array.isArray(d?.providers)?d.providers:[],m=d?.default||{},h=u.map(p=>{const g=p.models??{},y=Object.keys(g).map(b=>g[b]);return{...p,models:y}});t(p=>{const y={...p.directoryScoped[r]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:h,defaultProviders:m},b={directoryScoped:{...p.directoryScoped,[r]:y}};if(p.activeDirectoryKey===r&&(b.providers=h,b.defaultProviders=m,!p.currentProviderId&&!p.currentModelId&&p.settingsDefaultModel)){const x=l1(p.settingsDefaultModel);if(x){const v=h.find(w=>w.id===x.providerId);if(v?.models.some(w=>w.id===x.modelId)){const w=v.models.find(k=>k.id===x.modelId),C=p.settingsDefaultVariant&&w?.variants?.[p.settingsDefaultVariant]?p.settingsDefaultVariant:void 0;b.currentProviderId=x.providerId,b.currentModelId=x.modelId,b.currentVariant=C,b.selectedProviderId=x.providerId,y.currentProviderId=x.providerId,y.currentModelId=x.modelId,y.currentVariant=C,y.selectedProviderId=x.providerId}}}return b});return}catch(d){l=d;const u=200*(c+1);await new Promise(m=>setTimeout(m,u))}console.error("Failed to load providers:",l),t(c=>{const u={...c.directoryScoped[r]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:i},m={directoryScoped:{...c.directoryScoped,[r]:u}};if(c.activeDirectoryKey===r&&(m.providers=a,m.defaultProviders=i,!c.currentProviderId&&!c.currentModelId&&c.settingsDefaultModel)){const h=l1(c.settingsDefaultModel);if(h){const p=a.find(g=>g.id===h.providerId);if(p?.models.some(g=>g.id===h.modelId)){const g=p.models.find(b=>b.id===h.modelId),y=c.settingsDefaultVariant&&g?.variants?.[c.settingsDefaultVariant]?c.settingsDefaultVariant:void 0;m.currentProviderId=h.providerId,m.currentModelId=h.modelId,m.currentVariant=y,m.selectedProviderId=h.providerId,u.currentProviderId=h.providerId,u.currentModelId=h.modelId,u.currentVariant=y,u.selectedProviderId=h.providerId}}}return m})},setProvider:n=>{const{providers:r}=e(),o=r.find(l=>l.id===n);if(!o)return;const i=o.models[0]?.id||"";t(l=>{const c=l.activeDirectoryKey,u={...l.directoryScoped[c]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:n,currentModelId:i,selectedProviderId:n};return{currentProviderId:n,currentModelId:i,selectedProviderId:n,directoryScoped:{...l.directoryScoped,[c]:u}}})},setModel:n=>{t(r=>{const o=r.activeDirectoryKey,i={...r.directoryScoped[o]??{providers:r.providers,agents:r.agents,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,currentAgentName:r.currentAgentName,selectedProviderId:r.selectedProviderId,agentModelSelections:r.agentModelSelections,defaultProviders:r.defaultProviders},currentModelId:n};return{currentModelId:n,directoryScoped:{...r.directoryScoped,[o]:i}}})},setCurrentVariant:n=>{t(r=>{if(r.currentVariant===n)return r;const o=r.activeDirectoryKey,i={...r.directoryScoped[o]??{providers:r.providers,agents:r.agents,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentVariant:r.currentVariant,currentAgentName:r.currentAgentName,selectedProviderId:r.selectedProviderId,agentModelSelections:r.agentModelSelections,defaultProviders:r.defaultProviders},currentVariant:n};return{currentVariant:n,directoryScoped:{...r.directoryScoped,[o]:i}}})},getCurrentModelVariants:()=>{const r=e().getCurrentModel()?.variants;return r?Object.keys(r):[]},cycleCurrentVariant:()=>{const n=e().getCurrentModelVariants();if(n.length===0)return;const r=e().currentVariant;if(!r){e().setCurrentVariant(n[0]);return}const o=n.indexOf(r);if(o===-1||o===n.length-1){e().setCurrentVariant(void 0);return}e().setCurrentVariant(n[o+1])},setSelectedProvider:n=>{t(r=>{const o=r.activeDirectoryKey,i={...r.directoryScoped[o]??{providers:r.providers,agents:r.agents,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentAgentName:r.currentAgentName,selectedProviderId:r.selectedProviderId,agentModelSelections:r.agentModelSelections,defaultProviders:r.defaultProviders},selectedProviderId:n};return{selectedProviderId:n,directoryScoped:{...r.directoryScoped,[o]:i}}})},saveAgentModelSelection:(n,r,o)=>{t(a=>{const i=a.activeDirectoryKey,l={...a.agentModelSelections,[n]:{providerId:r,modelId:o}},d={...a.directoryScoped[i]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[i]:d}}})},getAgentModelSelection:n=>{const{agentModelSelections:r}=e();return r[n]||null},loadAgents:async n=>{const r=el(n?.directory??Ai(e().activeDirectoryKey)),a=e().directoryScoped[r]?.agents??(e().activeDirectoryKey===r?e().agents:[]);let i=null;for(let l=0;l<3;l++)try{const[c,d]=await Promise.all([zt.withDirectory(Ai(r),()=>zt.listAgents()),hj()]),u=Array.isArray(c)?c:[],m=e().activeDirectoryKey===r?e().providers:e().directoryScoped[r]?.providers??[],h=A0(e().settingsZenModel),p=A0(d.zenModel),g=V2({providers:m,settingsZenModel:h}),y=V2({providers:m,settingsZenModel:p}),v=(g||y)?.modelId||p||h;if(t(D=>{const I={...D.directoryScoped[r]??{providers:m,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:m,agents:u},T={settingsDefaultModel:d.defaultModel,settingsDefaultVariant:d.defaultVariant,settingsDefaultAgent:d.defaultAgent,settingsAutoCreateWorktree:d.autoCreateWorktree??!1,settingsGitmojiEnabled:d.gitmojiEnabled??!1,settingsZenModel:v,directoryScoped:{...D.directoryScoped,[r]:I}};return D.activeDirectoryKey===r&&(T.agents=u),T}),v&&v!==p&&v&&Rs({zenModel:v,gitProviderId:"",gitModelId:""}).catch(()=>{}),u.length===0)return t(D=>{const I={...D.directoryScoped[r]??{providers:m,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:m,agents:[],currentAgentName:void 0},T={directoryScoped:{...D.directoryScoped,[r]:I}};return D.activeDirectoryKey===r&&(T.currentAgentName=void 0),T}),!0;const C=(D,E)=>{const I=m.find(T=>T.id===D);return I?I.models.some(T=>T.id===E):!1},k=u.filter(D=>gj(D.mode));let j=k.find(D=>D.name==="build")||k[0]||u[0];const A={};if(d.defaultAgent){const D=u.find(E=>E.name===d.defaultAgent);D?j=D:A.defaultAgent=""}let M,F,B;if(d.defaultModel){const D=l1(d.defaultModel);if(D&&C(D.providerId,D.modelId)){if(M=D.providerId,F=D.modelId,d.defaultVariant){const T=m.find(H=>H.id===D.providerId)?.models.find(H=>H.id===D.modelId)?.variants;T&&Object.prototype.hasOwnProperty.call(T,d.defaultVariant)?B=d.defaultVariant:A.defaultVariant=""}}else A.defaultModel=""}if(!M&&j?.model?.providerID&&j?.model?.modelID){const{providerID:D,modelID:E}=j.model;C(D,E)&&(M=D,F=E)}if(!M)if(C(of,af))M=of,F=af;else{const D=m[0],E=D?.models[0];D&&E&&(M=D.id,F=E.id)}return t(D=>{const E=D.directoryScoped[r]??{providers:m,agents:u,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},I={...E,providers:m,agents:u,currentAgentName:j.name,currentProviderId:M??E.currentProviderId,currentModelId:F??E.currentModelId,currentVariant:B},T={directoryScoped:{...D.directoryScoped,[r]:I}};return D.activeDirectoryKey===r&&(T.currentAgentName=j.name,M&&F&&(T.currentProviderId=M,T.currentModelId=F,T.currentVariant=B)),T}),Object.keys(A).length>0&&(t({settingsDefaultModel:A.defaultModel!==void 0?void 0:e().settingsDefaultModel,settingsDefaultVariant:A.defaultVariant!==void 0?void 0:e().settingsDefaultVariant,settingsDefaultAgent:A.defaultAgent!==void 0?void 0:e().settingsDefaultAgent}),Rs(A).catch(()=>{})),!0}catch(c){i=c;const d=200*(l+1);await new Promise(u=>setTimeout(u,d))}return console.error("Failed to load agents:",i),t(l=>{const c=l.activeDirectoryKey===r?l.providers:l.directoryScoped[r]?.providers??[],u={...l.directoryScoped[r]??{providers:c,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:c,agents:a},m={directoryScoped:{...l.directoryScoped,[r]:u}};return l.activeDirectoryKey===r&&(m.agents=a),m}),!1},setAgent:n=>{const{agents:r,providers:o,settingsDefaultModel:a,settingsDefaultVariant:i}=e();if(t(l=>{const c=l.activeDirectoryKey,u={...l.directoryScoped[c]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentAgentName:n};return{currentAgentName:n,directoryScoped:{...l.directoryScoped,[c]:u}}}),n&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const c=l.getState(),{currentSessionId:d,isOpenChamberCreatedSession:u,initializeNewOpenChamberSession:m,getAgentModelForSession:h}=c;d&&l.setState(p=>{const g=new Map(p.currentAgentContext);return g.set(d,n),{currentAgentContext:g}}),d&&u(d)&&(h(d,n)||m(d,r))}}if(n&&typeof window<"u"){const l=window.__zustand_session_store__;if(l?.getState){const{currentSessionId:u,getAgentModelForSession:m}=l.getState();if(u&&m(u,n))return}if(a){const u=l1(a);if(u&&o.find(h=>h.id===u.providerId)?.models.some(h=>h.id===u.modelId)){t(h=>{const p=h.activeDirectoryKey,g=h.directoryScoped[p]??{providers:h.providers,agents:h.agents,currentProviderId:h.currentProviderId,currentModelId:h.currentModelId,currentVariant:h.currentVariant,currentAgentName:h.currentAgentName,selectedProviderId:h.selectedProviderId,agentModelSelections:h.agentModelSelections,defaultProviders:h.defaultProviders};let y;if(i){const w=o.find(C=>C.id===u.providerId)?.models.find(C=>C.id===u.modelId)?.variants;w&&Object.prototype.hasOwnProperty.call(w,i)&&(y=i)}const b={...g,currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:y};return{currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:y,directoryScoped:{...h.directoryScoped,[p]:b}}});return}}const d=r.find(u=>u.name===n)?.model;if(d?.providerID&&d?.modelID){const{providerID:u,modelID:m}=d;o.find(g=>g.id===u)?.models.find(g=>g.id===m)&&t(g=>{const y=g.activeDirectoryKey,x={...g.directoryScoped[y]??{providers:g.providers,agents:g.agents,currentProviderId:g.currentProviderId,currentModelId:g.currentModelId,currentAgentName:g.currentAgentName,selectedProviderId:g.selectedProviderId,agentModelSelections:g.agentModelSelections,defaultProviders:g.defaultProviders},currentProviderId:u,currentModelId:m,selectedProviderId:u};return{currentProviderId:u,currentModelId:m,selectedProviderId:u,directoryScoped:{...g.directoryScoped,[y]:x}}})}}},setSettingsDefaultModel:n=>{t({settingsDefaultModel:n})},setSettingsDefaultVariant:n=>{t({settingsDefaultVariant:n})},setSettingsDefaultAgent:n=>{t({settingsDefaultAgent:n})},setSettingsAutoCreateWorktree:n=>{t({settingsAutoCreateWorktree:n})},setSettingsGitmojiEnabled:n=>{t({settingsGitmojiEnabled:n})},setSettingsZenModel:n=>{t({settingsZenModel:n})},getResolvedGitGenerationModel:()=>{const n=e();return V2({providers:n.providers,settingsZenModel:n.settingsZenModel})},setVoiceProvider:n=>{t({voiceProvider:n}),typeof window<"u"&&localStorage.setItem("voiceProvider",n)},setSpeechRate:n=>{const r=Math.max(.5,Math.min(2,n));t({speechRate:r}),typeof window<"u"&&localStorage.setItem("speechRate",String(r))},setSpeechPitch:n=>{const r=Math.max(.5,Math.min(2,n));t({speechPitch:r}),typeof window<"u"&&localStorage.setItem("speechPitch",String(r))},setSpeechVolume:n=>{const r=Math.max(0,Math.min(1,n));t({speechVolume:r}),typeof window<"u"&&localStorage.setItem("speechVolume",String(r))},setSayVoice:n=>{t({sayVoice:n}),typeof window<"u"&&localStorage.setItem("sayVoice",n)},setBrowserVoice:n=>{t({browserVoice:n}),typeof window<"u"&&localStorage.setItem("browserVoice",n)},setOpenaiVoice:n=>{t({openaiVoice:n}),typeof window<"u"&&localStorage.setItem("openaiVoice",n)},setOpenaiApiKey:n=>{t({openaiApiKey:n}),typeof window<"u"&&localStorage.setItem("openaiApiKey",n)},setShowMessageTTSButtons:n=>{t({showMessageTTSButtons:n}),typeof window<"u"&&localStorage.setItem("showMessageTTSButtons",String(n))},setVoiceModeEnabled:n=>{t({voiceModeEnabled:n}),typeof window<"u"&&localStorage.setItem("voiceModeEnabled",String(n))},setSummarizeMessageTTS:n=>{t({summarizeMessageTTS:n}),typeof window<"u"&&localStorage.setItem("summarizeMessageTTS",String(n))},setSummarizeVoiceConversation:n=>{t({summarizeVoiceConversation:n}),typeof window<"u"&&localStorage.setItem("summarizeVoiceConversation",String(n))},setSummarizeCharacterThreshold:n=>{const r=Math.max(50,Math.min(2e3,n));t({summarizeCharacterThreshold:r}),typeof window<"u"&&localStorage.setItem("summarizeCharacterThreshold",String(r))},setSummarizeMaxLength:n=>{const r=Math.max(50,Math.min(2e3,n));t({summarizeMaxLength:r}),typeof window<"u"&&localStorage.setItem("summarizeMaxLength",String(r))},checkConnection:async()=>{let r=0,o=null;for(;r<5;)try{const a=await zt.checkHealth();return t({isConnected:a}),a}catch(a){o=a,r+=1;const i=400*r;await jj(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const n=Kn();n&&console.log("Starting app initialization...");const r=await e().checkConnection();if(n&&console.log("Connection check result:",r),!r){n&&console.log("Server not connected"),t({isConnected:!1});return}n&&console.log("Initializing app..."),await zt.initApp(),n&&console.log("Loading providers..."),await e().loadProviders(),n&&console.log("Loading agents..."),await e().loadAgents(),t({isInitialized:!0,isConnected:!0}),n&&console.log("App initialized successfully")}catch(n){console.error("Failed to initialize app:",n),t({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:n,currentProviderId:r}=e();return n.find(o=>o.id===r)},getCurrentModel:()=>{const n=e().getCurrentProvider(),{currentModelId:r}=e();if(n)return n.models.find(o=>o.id===r)},getCurrentAgent:()=>{const{agents:n,currentAgentName:r}=e();if(r)return n.find(o=>o.name===r)},getModelMetadata:(n,r)=>{const o=y8(n,r);if(!o)return;const{modelsMetadata:a}=e();return a.get(o)},getVisibleAgents:()=>{const{agents:n}=e();return g8(n)}}),{name:"config-store",storage:xr(()=>Bn()),partialize:t=>({activeDirectoryKey:t.activeDirectoryKey,directoryScoped:t.directoryScoped,currentProviderId:t.currentProviderId,currentModelId:t.currentModelId,currentVariant:t.currentVariant,currentAgentName:t.currentAgentName,selectedProviderId:t.selectedProviderId,agentModelSelections:t.agentModelSelections,defaultProviders:t.defaultProviders,settingsDefaultModel:t.settingsDefaultModel,settingsDefaultVariant:t.settingsDefaultVariant,settingsDefaultAgent:t.settingsDefaultAgent,settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,settingsGitmojiEnabled:t.settingsGitmojiEnabled,settingsZenModel:t.settingsZenModel,speechRate:t.speechRate,speechPitch:t.speechPitch,speechVolume:t.speechVolume})})));typeof window<"u"&&(window.__zustand_config_store__=Yt);let df=null;df||(df=p2(async t=>{const e=[];if(wc(t,"agents")){const{loadAgents:n}=Yt.getState();e.push(n().then(()=>{}))}if(wc(t,"providers")){const{loadProviders:n}=Yt.getState();e.push(n())}e.length>0&&await Promise.all(e)}));let uf=null;typeof window<"u"&&!uf&&(uf=Ds.subscribe((t,e)=>{const n=el(t.currentDirectory),r=el(e.currentDirectory);n!==r&&Yt.getState().activateDirectory(t.currentDirectory)}));const kj=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Nj=t=>t?kj.has(t.toLowerCase()):!1,Cj=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Mj=t=>{if(t)try{const e=Cj();if(e?.getState)return e.getState().agents?.find?.(r=>r.name===t)}catch{}},Aj=(t,e)=>{if(!t||t.length===0)return"ask";for(let n=t.length-1;n>=0;n-=1){const r=t[n];if(r.permission===e&&r.pattern==="*")return r.action}for(let n=t.length-1;n>=0;n-=1){const r=t[n];if(r.permission==="*"&&r.pattern==="*")return r.action}return"ask"},X1=t=>{const e=Mj(t);return e?Aj(e.permission,"edit"):"ask"},ff=t=>{if(!t||typeof t!="object")return 0;const e=t.input??0,n=t.output??0,r=t.reasoning??0,o=t.cache&&typeof t.cache=="object"?t.cache.read??0:0,a=t.cache&&typeof t.cache=="object"?t.cache.write??0:0;return e+n+r+o+a},W2=t=>{const e=t.info.tokens;if(typeof e=="number")return e;if(e&&typeof e=="object")return ff(e);const n=t.parts.find(r=>typeof r.tokens<"u");return!n||typeof n.tokens>"u"?0:typeof n.tokens=="number"?n.tokens:ff(n.tokens)},q2=(t,e,n)=>{const r=Number.isFinite(e)?Math.max(e,0):0,o=Number.isFinite(n)&&n>0,a=o?Math.max(n,0):0,i=Math.min(o?a:32e3,32e3),l=Math.min(i,r),c=r>0?Math.max(r-l,1):0,d=c>0?t/c*100:0;return{percentage:Math.min(d,100),contextLimit:r,outputLimit:a,thresholdLimit:c||1,normalizedOutput:l}},Al=["ask","allow","full"],mf="__global__",bs=xn()(In(hr((t,e)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(n,r,o)=>{t(a=>{const i=new Map(a.sessionModelSelections);return i.set(n,{providerId:r,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:n=>{const{sessionModelSelections:r}=e();return r.get(n)||null},saveSessionAgentSelection:(n,r)=>{t(o=>{const a=new Map(o.sessionAgentSelections);a.set(n,r);const i=new Map(o.currentAgentContext);return i.set(n,r),{sessionAgentSelections:a,currentAgentContext:i}})},getSessionAgentSelection:n=>{const{sessionAgentSelections:r}=e();return r.get(n)||null},saveAgentModelForSession:(n,r,o,a)=>{t(i=>{const l=new Map(i.sessionAgentModelSelections);let c=l.get(n);return c?c=new Map(c):c=new Map,c.set(r,{providerId:o,modelId:a}),l.set(n,c),{sessionAgentModelSelections:l}})},getAgentModelForSession:(n,r)=>{const{sessionAgentModelSelections:o}=e(),a=o.get(n);return a&&a.get(r)||null},saveAgentModelVariantForSession:(n,r,o,a,i)=>{t(l=>{const c=new Map(l.sessionAgentModelVariantSelections);let d=c.get(n);d?d=new Map(d):d=new Map;let u=d.get(r);u?u=new Map(u):u=new Map;const m=`${o}/${a}`;return i===void 0?(u.delete(m),u.size===0?(d.delete(r),d.size===0?c.delete(n):c.set(n,d)):(d.set(r,u),c.set(n,d))):(u.set(m,i),d.set(r,u),c.set(n,d)),{sessionAgentModelVariantSelections:c}})},getAgentModelVariantForSession:(n,r,o,a)=>{const{sessionAgentModelVariantSelections:i}=e(),l=i.get(n);if(!l)return;const c=l.get(r);if(c)return c.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(n,r,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:i}=e(),l=new Map,c=(g,y)=>{if("mode"in g&&g.mode&&typeof g.mode=="string"&&r.find(w=>w.name===g.mode))return g.mode;if("agent"in g&&g.agent&&typeof g.agent=="string"&&r.find(w=>w.name===g.agent))return g.agent;if(g.providerID&&g.modelID){const v=r.find(w=>w.model?.providerID===g.providerID&&w.model?.modelID===g.modelID);if(v)return v.name}const{currentAgentContext:b}=e(),x=b.get(n);if(x&&r.find(v=>v.name===x))return x;if(y>0&&g.providerID&&g.modelID){const w=(o.get(n)||[]).filter(C=>C.info.role==="assistant").sort((C,k)=>C.info.time.created-k.info.time.created);for(let C=y-1;C>=0;C--){const N=w[C].info;if(N.providerID===g.providerID&&N.modelID===g.modelID){if(N.mode&&typeof N.mode=="string"&&r.find(A=>A.name===N.mode))return N.mode;const S=r.find(j=>j.model?.providerID===N.providerID&&j.model?.modelID===N.modelID);if(S)return S.name}}}return g.providerID&&g.modelID&&r.find(w=>w.name==="build")?"build":null},d=o.get(n)||[],u=d.filter(g=>g.info.role==="assistant"||g.info.role==="user").sort((g,y)=>g.info.time.created-y.info.time.created),m=d.filter(g=>g.info.role==="assistant").sort((g,y)=>g.info.time.created-y.info.time.created);let h,p;for(let g=0;g<u.length;g++){const y=u[g],{info:b}=y,x=b;if(x.role==="user"){const v=typeof x.mode=="string"&&x.mode.trim().length>0?x.mode:typeof x.agent=="string"&&x.agent.trim().length>0?x.agent:void 0,w=typeof x.model?.providerID=="string"&&x.model.providerID.trim().length>0?x.model.providerID:typeof x.providerID=="string"&&x.providerID.trim().length>0?x.providerID:void 0,C=typeof x.model?.modelID=="string"&&x.model.modelID.trim().length>0?x.model.modelID:typeof x.modelID=="string"&&x.modelID.trim().length>0?x.modelID:void 0,k=typeof x.variant=="string"&&x.variant.trim().length>0?x.variant:void 0;if(v&&w&&C&&r.find(N=>N.name===v)){const N={providerId:w,modelId:C,timestamp:b.time.created},S=l.get(v);(!S||N.timestamp>S.timestamp)&&l.set(v,N),i(n,v,w,C,k)}h=k,p=x.model?.providerID&&x.model?.modelID?{providerID:x.model.providerID,modelID:x.model.modelID}:void 0;continue}if(x.providerID&&x.modelID){const v=c(x,m.indexOf(y));if(v&&r.find(w=>w.name===v)){p&&p.providerID===x.providerID&&p.modelID===x.modelID&&i(n,v,x.providerID,x.modelID,h);const w={providerId:x.providerID,modelId:x.modelID,timestamp:b.time.created},C=l.get(v);(!C||w.timestamp>C.timestamp)&&l.set(v,w)}}h=void 0,p=void 0}for(const[g,y]of l)a(n,g,y.providerId,y.modelId);return l},getContextUsage:(n,r,o,a)=>{if(!n)return null;const i=q2(0,r,o),l=i.contextLimit,c=i.normalizedOutput??0,d=i.thresholdLimit;if(l===0||d===0)return null;const m=(a.get(n)||[]).filter(w=>w.info.role==="assistant");if(m.length===0)return null;const h=m[m.length-1],p=h.info.id,g=w=>{const C=()=>{t(k=>{const N=k.sessionContextUsage.get(n);if(N&&N.totalTokens===w.totalTokens&&N.percentage===w.percentage&&N.contextLimit===w.contextLimit&&(N.outputLimit??0)===(w.outputLimit??0)&&(N.normalizedOutput??0)===(w.normalizedOutput??0)&&N.thresholdLimit===w.thresholdLimit&&N.lastMessageId===w.lastMessageId)return k;const S=new Map(k.sessionContextUsage);return S.set(n,w),{sessionContextUsage:S}})};typeof queueMicrotask=="function"?queueMicrotask(C):typeof window<"u"?window.setTimeout(C,0):setTimeout(C,0)},y=e().sessionContextUsage.get(n);if(y&&y.lastMessageId===p){const w=y.normalizedOutput??y.outputLimit??0,C=y.contextLimit!==l||w!==c||y.thresholdLimit!==d;if(C&&y.totalTokens>0){const k=y.totalTokens/d*100,N={totalTokens:y.totalTokens,percentage:Math.min(k,100),contextLimit:l,outputLimit:i.outputLimit,normalizedOutput:c,thresholdLimit:d,lastMessageId:p};return g(N),N}if(!C&&y.totalTokens>0)return y}const b=W2(h);if(b===0)return y||null;const x=q2(b,r,o),v={totalTokens:b,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit,normalizedOutput:x.normalizedOutput,thresholdLimit:x.thresholdLimit,lastMessageId:p};return g(v),v},updateSessionContextUsage:(n,r,o,a)=>{const l=(a.get(n)||[]).filter(m=>m.info.role==="assistant");if(l.length===0)return;const c=l[l.length-1],d=W2(c);if(d===0)return;const u=q2(d,r,o);t(m=>{const h=new Map(m.sessionContextUsage);return h.set(n,{totalTokens:d,percentage:u.percentage,contextLimit:u.contextLimit,outputLimit:u.outputLimit,normalizedOutput:u.normalizedOutput,thresholdLimit:u.thresholdLimit,lastMessageId:c.info.id}),{sessionContextUsage:h}})},initializeSessionContextUsage:(n,r,o,a)=>{const l=e().sessionContextUsage.get(n);(!l||l.totalTokens===0)&&e().updateSessionContextUsage(n,r,o,a)},pollForTokenUpdates:(n,r,o,a=10)=>{let i=0;const l=()=>{i++;const d=(o.get(n)||[]).find(u=>u.info.id===r);if(d&&d.info.role==="assistant"&&W2(d)>0){e().updateSessionContextUsage(n,0,0,o);return}i<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:n=>{const{currentAgentContext:r}=e();return r.get(n)},getSessionAgentEditMode:(n,r,o=X1(r))=>{if(!n||!r)return o;const i=e().sessionAgentEditModes.get(n)?.get(r);if(i!==void 0)return i;if(n!==mf){const c=e().sessionAgentEditModes.get(mf)?.get(r);if(c!==void 0)return c}return o},setSessionAgentEditMode:(n,r,o,a=X1(r))=>{if(!n||!r)return;const i=a??"ask";i==="deny"||o==="deny"||Al.includes(o)&&t(l=>{const c=new Map(l.sessionAgentEditModes),d=new Map(c.get(n)??new Map);return o===i?(d.delete(r),d.size===0?c.delete(n):c.set(n,d)):(d.set(r,o),c.set(n,d)),{sessionAgentEditModes:c}})},toggleSessionAgentEditMode:(n,r,o=X1(r))=>{if(!n||!r)return;const a=o??"ask";if(a==="deny")return;const i=e().getSessionAgentEditMode(n,r,a),l=Al.indexOf(i),c=Al.indexOf(a),u=((l>=0?l:c>=0?c:0)+1)%Al.length,m=Al[u];e().setSessionAgentEditMode(n,r,m,a)}}),{name:"context-store",storage:xr(()=>Bn()),partialize:t=>({sessionModelSelections:Array.from(t.sessionModelSelections.entries()),sessionAgentSelections:Array.from(t.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(t.sessionAgentModelSelections.entries()).map(([e,n])=>[e,Array.from(n.entries())]),sessionAgentModelVariantSelections:Array.from(t.sessionAgentModelVariantSelections.entries()).map(([e,n])=>[e,Array.from(n.entries()).map(([r,o])=>[r,Array.from(o.entries())])]),currentAgentContext:Array.from(t.currentAgentContext.entries()),sessionContextUsage:Array.from(t.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(t.sessionAgentEditModes.entries()).map(([e,n])=>[e,Array.from(n.entries())])}),merge:(t,e)=>{const n=new Map;t?.sessionAgentModelSelections&&t.sessionAgentModelSelections.forEach(([a,i])=>{n.set(a,new Map(i))});const r=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([a,i])=>{const l=new Map;i.forEach(([c,d])=>{l.set(c,new Map(d))}),r.set(a,l)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([a,i])=>{o.set(a,new Map(i))}),{...e,...t,sessionModelSelections:new Map(t?.sessionModelSelections||[]),sessionAgentSelections:new Map(t?.sessionAgentSelections||[]),sessionAgentModelSelections:n,sessionAgentModelVariantSelections:r,currentAgentContext:new Map(t?.currentAgentContext||[]),sessionContextUsage:new Map(t?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),Nr=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function la(t){const e=Nr();return e?e.checkIsGitRepository(t):uv(t)}async function I4(t){const e=Nr();return e?e.getGitStatus(t):gv(t)}async function b8(t){const e=Nr();return e?e.getGitBranches(t):kv(t)}async function Fj(t,e){const n=Nr();return n?n.deleteRemoteBranch(t,e):yv(t,e)}async function Dj(t,e,n){const r=Date.now(),o=x8();if(!o)throw new Error("Select existing session for generation");console.info("[git-generation][browser] request",{transport:"session",kind:"commit",directory:t,selectedFiles:e.length,sessionId:o.sessionId,providerId:o.providerID,modelId:o.modelID,agent:o.agent});const a=`You are generating a Conventional Commits subject line using session context and selected file paths.
4
4
 
5
5
  Return JSON with exactly this shape:
@@ -6714,7 +6714,7 @@ ${Ge}`;q(Ee)},[U,q]),Ue=f.useCallback(ye=>{if(ye.stopPropagation(),ye.preventDef
6714
6714
  ${$e.cssText}
6715
6715
  transform: none;
6716
6716
  contain: none;
6717
- `;const At=Xe.querySelectorAll('[aria-label^="Message time:"]'),yt=new Set;At.forEach(Zt=>{const is=Zt.getAttribute("aria-label")?.replace("Message time:","").trim();if(!is||Zt.textContent?.includes(is))return;const as=document.createElement("span");as.style.marginLeft="4px",as.textContent=is,Zt.appendChild(as);const ps=Zt.parentElement,xs=ps?.parentElement,mt=xs?.firstElementChild;!xs||!mt||mt===ps||yt.has(xs)||(mt.style.display="none",xs.style.justifyContent="flex-start",yt.add(xs))}),Ge.appendChild(Xe),document.body.appendChild(Ge);const dt=await Mb(Ge,{quality:1,pixelRatio:2,backgroundColor:jt}),Tt=`message-${t}.png`;if(ln()){const Zt=await fetch("/api/vscode/save-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:Tt,dataUrl:dt})});if(!Zt.ok)throw new Error("Failed to save image in VS Code");const rs=await Zt.json();if(rs.saved!==!0){if(rs.canceled)return;throw new Error(rs.error||"Failed to save image in VS Code")}}else{const Zt=document.createElement("a");Zt.download=Tt,Zt.href=dt,document.body.appendChild(Zt),Zt.click(),document.body.removeChild(Zt)}ue.success("Image saved")}catch(Ee){console.error("Failed to generate image:",Ee),ue.error("Failed to generate image")}finally{Ge&&Ge.parentNode&&Ge.parentNode.removeChild(Ge),st(!1)}},[t,Ve]);f.useEffect(()=>()=>{ke()},[ke]);const nt=f.useMemo(()=>{const ye=C?.activityParts;return!G||!ye?[]:ye},[G,C?.activityParts]),he=f.useMemo(()=>{const ye=C?.activityGroupSegments;return!G||!ye?[]:ye.filter(Ge=>Ge.anchorMessageId===t)},[G,t,C?.activityGroupSegments]),je=f.useMemo(()=>{const ye=new Map,Ge=new Map;return nt.forEach(Ee=>{ye.set(Ee.part,Ee);const $e=Ee.part.id;typeof $e=="string"&&$e.length>0&&Ge.set($e,Ee)}),{get:Ee=>{const $e=ye.get(Ee);if($e)return $e;const tt=Ee.id;if(typeof tt=="string"&&tt.length>0)return Ge.get(tt)}}},[nt]),We=C?.toggleGroup,lt=G&&he.length>0&&!!We,rt=f.useMemo(()=>{const ye=[];lt&&We&&he.forEach(Ee=>{const $e=w?Ee.parts:Ee.parts.filter(tt=>tt.kind!=="reasoning");$e.length!==0&&ye.push(s.jsx(hP,{parts:$e,isExpanded:C.isGroupExpanded===!0,collapsedPreviewCount:Y,onToggle:We,syntaxTheme:i,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:g,streamPhase:N,showHeader:!0,animateRows:T,animatedToolIds:W,diffStats:C.diffStats},`progressive-group-${Ee.id}`))});let Ge=0;for(;Ge<H.length;){const Ee=H[Ge];if(Ee.type==="text"){const $e=je.get(Ee);if(G&&!re){Ge+=1;continue}if($e?.kind==="justification"){Ge+=1;continue}ye.push(s.jsx(hT,{part:Ee,messageId:t,streamPhase:N,chatRenderMode:ee,onContentChange:g},`assistant-text-${t}-${Ge}`)),Ge++;continue}if(Ee.type==="reasoning"){const $e=je.get(Ee);if(G&&!re){Ge+=1;continue}if($e?.kind==="reasoning"){Ge+=1;continue}if(w)if(G)ye.push(s.jsx(Mg,{part:Ee,messageId:t,onContentChange:g},`reasoning-${t}-${Ge}`));else{const tt=Ee.text;tt&&tt.trim().length>0&&ye.push(s.jsx(ea,{children:s.jsx("div",{className:"text-sm text-muted-foreground/60 italic leading-relaxed whitespace-pre-wrap",children:tt})},`reasoning-${t}-${Ge}`))}Ge++;continue}if(Ee.type==="tool"){const $e=Ee,tt=$e.tool?.toLowerCase()??"";if(je.get(Ee)?.kind==="tool"&&!l3(tt)){Ge+=1;continue}if(!ve($e)){Ge++;continue}if(i3(tt)){ye.push(s.jsx(ea,{children:s.jsx(H0,{animate:W.has($e.id),wipe:!0,children:s.jsx(qu,{part:$e,isExpanded:d.has($e.id),onToggle:u,syntaxTheme:i,isMobile:l,onContentChange:g,onShowPopup:m,animateTailText:W.has($e.id)})})},`tool-${$e.id}`)),Ge++;continue}const ct=O0(tt),Xe=[$e];let At=Ge+1;for(;At<H.length;){const yt=H[At];if(yt.type!=="tool")break;const dt=yt;if(!ve(dt)){At++;continue}const Tt=dt.tool?.toLowerCase()??"";if(O0(Tt)!==ct)break;Xe.push(dt),At++}ye.push(s.jsx(ea,{children:s.jsx(H0,{animate:Xe.some(yt=>W.has(yt.id)),wipe:!0,children:s.jsx(_g,{toolName:ct,activities:Xe.map(yt=>({id:yt.id,turnId:"",messageId:t,partIndex:0,part:yt,kind:"tool"})),animateTailText:Xe.some(yt=>W.has(yt.id))})})},`static-tools-${$e.id}`)),Ge=At;continue}Ge++}return ye},[je,he,W,T,ee,Y,d,re,l,G,t,g,m,u,lt,ve,N,w,i,We,C,H]),Te=!!k,Qe=oe&&y&&(re||!!k),pt=f.useMemo(()=>{if(!oe||!re)return;const ye=C?.userMessageCreatedAt;if(!(typeof ye!="number"||typeof o!="number")&&!(o<=ye))return bP(o-ye)},[oe,re,C?.userMessageCreatedAt,o]),St=f.useMemo(()=>{const ye=typeof o=="number"&&o>0?o:typeof a=="number"&&a>0?a:null;if(ye===null)return null;const Ge=IT(ye);return Ge.length>0?Ge:null},[o,a]),Ht="text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",Ke=s.jsxs(s.Fragment,{children:[b&&s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon","data-visible":S||D?"true":void 0,className:J("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",!Fe&&"opacity-50"),disabled:!Fe,"aria-label":"Copy message text","aria-hidden":!Fe,onPointerDown:ye=>ye.stopPropagation(),onClick:Je,onFocus:()=>{Fe&&j(!0)},onBlur:()=>{D||j(!1)},children:D?s.jsx(vs,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):s.jsx(Jn,{className:"h-3.5 w-3.5"})})}),s.jsx($t,{sideOffset:6,children:"Copy answer"})]}),s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{type:"button",size:"icon",variant:"ghost",disabled:Ve||!Fe,className:J("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",(!Fe||Ve)&&"opacity-50"),onPointerDown:ye=>ye.stopPropagation(),onClick:at,children:Ve?s.jsx(os,{className:"h-4 w-4 animate-spin"}):s.jsx(Ab,{className:"h-4 w-4"})})}),s.jsx($t,{sideOffset:6,children:Ve?"Saving image...":"Save as image"})]}),s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{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:ye=>ye.stopPropagation(),onClick:Ye,children:s.jsx(ru,{className:"h-4 w-4"})})}),s.jsx($t,{sideOffset:6,children:"Start new session from this answer"})]}),s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{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:ye=>ye.stopPropagation(),onClick:Re,children:s.jsx(o3,{className:"h-4 w-4"})})}),s.jsx($t,{sideOffset:6,children:"Start new multi-run from this answer"})]}),$&&Fe&&s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon",className:J("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",fe?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":fe?"Stop speaking":"Read aloud",onPointerDown:ye=>ye.stopPropagation(),onClick:Ue,children:fe?s.jsx(Po,{className:"h-3.5 w-3.5"}):s.jsx(w4,{className:"h-3.5 w-3.5"})})}),s.jsx($t,{sideOffset:6,children:X})]})]});return s.jsxs("div",{ref:M,className:J("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:E&&B&&Fe?Ze:void 0,children:[s.jsx(MT,{containerRef:M}),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:[rt,Te&&s.jsx(ea,{children:s.jsx("div",{className:"group/assistant-text relative break-words",children:s.jsx(po,{content:k??"",onShowPopup:m})})},"assistant-error")]}),s.jsx(K4,{files:e,onShowPopup:m}),Qe&&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:Ke}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[pt?s.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[s.jsx(Fb,{className:"h-3.5 w-3.5"}),pt]}):null,St?s.jsxs("span",{className:Ht,"aria-label":`Message time: ${St}`,children:[s.jsx(Qr,{className:"h-3.5 w-3.5"}),St]}):null]})]})]})]})},SP=t=>{const e=Ce.c(19);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||e[14]!==r.stickyUserHeaderEnabled||e[15]!==r.userActionsMode?(a=s.jsx(wP,{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,userActionsMode:r.userActionsMode,stickyUserHeaderEnabled:r.stickyUserHeaderEnabled}),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]=r.stickyUserHeaderEnabled,e[15]=r.userActionsMode,e[16]=a):a=e[16],a}let o;return e[17]!==r?(o=s.jsx(jP,{...r}),e[17]=r,e[18]=o):o=e[18],o},Md=f.memo(SP);function kP(t){return t.setCurrentSession}function NP(t){return!t}function CP(t){return!t}const xi=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}},MP=t=>{const e=t.trim();return!!(e.startsWith("User has requested to enter plan mode")||e.startsWith("The plan at ")||e.startsWith("The following tool was executed by the user"))},AP=t=>t.filter(e=>{if(!(e.synthetic===!0))return!0;if(e.type!=="text")return!1;const r=e.text;return typeof r=="string"?MP(r):!1}).map(e=>{const n=e;return n.type==="compaction"?{type:"text",text:"/compact"}:n.type==="text"&&(typeof n.text=="string"?n.text.trim():"").startsWith("The following tool was executed by the user")?{type:"text",text:"/shell"}:e}),FP=f.lazy(()=>cr(()=>import("./ToolOutputDialog-BDB_7hZd.js"),__vite__mapDeps([2,0,1,3,4]))),Bg=4e3,Ri=new Map,Li=new Map,DP=new Set(["bash","shell","cmd","terminal"]),_P=new Set(["apply_patch","edit","write","multiedit","str_replace","str_replace_based_edit_tool","create","file_write"]),BP=t=>{if(typeof t!="string")return"";const e=t.trim().toLowerCase();if(!e)return"";const n=e.replace(/:\d+$/,"");if(!n.includes("."))return n;const r=n.split(".").filter(Boolean);return r[r.length-1]??n},Rh=t=>{const e=Ri.get(t);return e?new Set(e):new Set},Lh=(t,e)=>{if(Ri.size>=Bg&&!Ri.has(t)){const n=Ri.keys().next().value;typeof n=="string"&&Ri.delete(n)}Ri.set(t,new Set(e))},zh=t=>{const e=Li.get(t);return e?new Set(e):new Set},Hh=(t,e)=>{if(Li.size>=Bg&&!Li.has(t)){const n=Li.keys().next().value;typeof n=="string"&&Li.delete(n)}Li.set(t,new Set(e))};function Ad(t){const e=Ce.c(3),[n,r]=f.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]),f.useEffect(o,a),t??n}const to=(t,e)=>{if(typeof t=="object"&&t!==null)return t[e]},EP=({message:t,previousMessage:e,nextMessage:n,onContentChange:r,animationHandlers:o,turnGroupingContext:a,animateUserOnMount:i=!1,onUserAnimationConsumed:l})=>{const{isMobile:c,hasTouchInput:d}=wn(),{currentTheme:u}=ir(),m=f.useRef(null),h=Le(sa(mt=>({lifecyclePhase:mt.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const It=t.info.sessionID??mt.currentSessionId??null;return It?(mt.streamingMessageIds.get(It)??null)===t.info.id:!1})(),currentSessionId:mt.currentSessionId,getAgentModelForSession:mt.getAgentModelForSession,getSessionModelSelection:mt.getSessionModelSelection,revertToMessage:mt.revertToMessage,forkFromMessage:mt.forkFromMessage}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:y,getAgentModelForSession:b,getSessionModelSelection:x,revertToMessage:v,forkFromMessage:w}=h,C=Yt(mt=>mt.providers),{showReasoningTraces:k,stickyUserHeader:N,chatRenderMode:S,showExpandedBashTools:j,showExpandedEditTools:A}=De(sa(mt=>({showReasoningTraces:mt.showReasoningTraces,stickyUserHeader:mt.stickyUserHeader,chatRenderMode:mt.chatRenderMode,showExpandedBashTools:mt.showExpandedBashTools,showExpandedEditTools:mt.showExpandedEditTools})));f.useEffect(()=>{y&&ja.getInstance().recordSessionStart(y)},[y]);const[M,F]=f.useState(null),[B,D]=f.useState(!1),[E,I]=f.useState(()=>Rh(t.info.id)),[T,H]=f.useState(()=>zh(t.info.id)),[P,_]=f.useState({open:!1,title:"",content:""});f.useEffect(()=>{I(Rh(t.info.id)),H(zh(t.info.id))},[t.info.id]);const z=f.useMemo(()=>xi(t.info),[t.info]).isUser,O=z&&(c||!N),Q=z&&!c&&N&&!O,te=t.info.sessionID,{currentContextAgent:W,savedSessionAgentSelection:U}=bs(sa(mt=>({currentContextAgent:te?mt.currentAgentContext.get(te):void 0,savedSessionAgentSelection:te?mt.sessionAgentSelections.get(te):void 0}))),K=f.useMemo(()=>z?AP(t.parts):t.parts,[z,t.parts]),q=f.useMemo(()=>{if(z||!e)return null;const mt=to(e.info,"clientRole"),It=to(e.info,"role");if((typeof mt=="string"?mt:typeof It=="string"?It:void 0)!=="user")return null;const et=to(e.info,"mode"),qe=to(e.info,"agent"),bt=to(e.info,"providerID"),Rt=to(e.info,"modelID"),Nt=to(e.info,"variant"),Pt=typeof et=="string"&&et.trim().length>0?et:typeof qe=="string"&&qe.trim().length>0?qe:void 0,Jt=typeof bt=="string"&&bt.trim().length>0?bt:void 0,Wt=typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,Ie=typeof Nt=="string"&&Nt.trim().length>0?Nt:void 0;return!Pt&&!Jt&&!Wt&&!Ie?null:{agentName:Pt,providerId:Jt,modelId:Wt,variant:Ie}},[z,e]),ee=f.useMemo(()=>{if(z||!e)return!1;const mt=Array.isArray(e.parts)?e.parts:[];for(let It=0;It<mt.length;It++){const Se=mt[It];if(Se?.type!=="text"||Se?.synthetic!==!0)continue;const et=typeof Se.text=="string"?Se.text.trim():"";if(et.startsWith("User has requested to enter plan mode")||et.startsWith("The plan at "))return!0}return!1},[z,e]),V=f.useMemo(()=>{if(z)return;const mt=t.info.time;if(!(typeof mt?.completed=="number"&&mt.completed>0)&&ee&&q?.agentName)return q.agentName;const Se=to(t.info,"mode");if(typeof Se=="string"&&Se.trim().length>0)return Se;const et=to(t.info,"agent");if(typeof et=="string"&&et.trim().length>0)return et;if(q?.agentName)return q.agentName;if(te)return W||(U??void 0)},[z,t.info,ee,q,te,W,U]),G=z?null:to(t.info,"providerID"),Y=z?null:to(t.info,"modelID"),oe=f.useMemo(()=>{if(z||!te)return null;if(q?.providerId&&q?.modelId)return{providerId:q.providerId,modelId:q.modelId};if(V){const It=b(te,V);if(It?.providerId&&It?.modelId)return It}const mt=x(te);return mt?.providerId&&mt?.modelId?mt:null},[z,te,V,q,b,x]),re=f.useMemo(()=>z?null:typeof G=="string"&&G.trim().length>0?G:oe?.providerId??null,[z,G,oe]),fe=f.useMemo(()=>z?null:typeof Y=="string"&&Y.trim().length>0?Y:oe?.modelId??null,[z,Y,oe]),ie=f.useMemo(()=>{if(!z&&re&&fe&&C.length>0){const mt=C.find(It=>It.id===re);if(mt?.models&&Array.isArray(mt.models)){const et=mt.models.find(qe=>qe.id===fe)?.name;return typeof et=="string"?et:void 0}}},[z,re,fe,C]),de=f.useMemo(()=>{if(z||!re||!fe)return!1;const mt=C.find(et=>et.id===re);if(!mt?.models||!Array.isArray(mt.models))return!1;const Se=mt.models.find(et=>et.id===fe)?.variants;return!!(Se&&Object.keys(Se).length>0)},[z,fe,re,C]),$=Ad(V),L=Ad(re??void 0),X=Ad(ie),ne=$??void 0,se=L??null,pe=X??void 0,ae=f.useMemo(()=>{const mt=t.info.time;return typeof mt?.completed=="number"?mt.completed:null},[t.info.time]),ve=f.useMemo(()=>{const mt=t.info.time;return typeof mt?.created=="number"?mt.created:null},[t.info.time]),ce=f.useMemo(()=>z?!0:!!(ae&&ae>0),[z,ae]),Z=f.useMemo(()=>{const mt=t.info.finish;return typeof mt=="string"?mt:void 0},[t.info]),me=f.useMemo(()=>kT(K,{includeReasoning:k}),[K,k]),be=f.useMemo(()=>z?me:!ce&&S==="sorted"?[]:me,[S,ce,z,me]),we=f.useMemo(()=>z?[]:me.filter(mt=>mt.type==="text"),[z,me]),Ae=f.useMemo(()=>z?[]:me.filter(It=>It.type==="tool"),[z,me]),Pe=f.useMemo(()=>z?[]:(a?.activityParts??[]).filter(It=>It.kind==="tool").map(It=>It.part).filter(It=>It.type==="tool"),[z,a?.activityParts]),xe=f.useMemo(()=>{if(!j&&!A)return new Set;const mt=new Set;for(const It of[...Ae,...Pe]){const Se=typeof It?.id=="string"?It.id:"";if(!Se)continue;const et=BP(It.tool);if(et){if(j&&DP.has(et)){mt.add(Se);continue}A&&_P.has(et)&&mt.add(Se)}}return mt},[j,A,Ae,Pe]),_e=f.useMemo(()=>{if(xe.size===0&&T.size===0)return E;const mt=new Set(E);return xe.forEach(It=>{T.has(It)||mt.add(It)}),T.forEach(It=>{mt.delete(It)}),mt},[T,xe,E]),ze=f.useMemo(()=>{if(!z)return;const mt=t.parts.find(qe=>qe.type==="agent");if(!mt)return;const It=mt,Se=typeof It.name=="string"?It.name:void 0;if(!Se)return;const et=It.source&&typeof It.source.value=="string"&&It.source.value.trim().length>0?It.source.value:`@${Se}`;return{name:Se,token:et}},[z,t.parts]),le=z&&be.length===0,ge=typeof Z!="string",Fe=f.useMemo(()=>z?!1:we.length===0||Ae.length===0?ge:!0,[we.length,Ae.length,ge,z]),ke=u?.metadata.variant,Ze=f.useMemo(()=>ke?ke==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ke]),Je=f.useMemo(()=>u?E2(u):Ze?gI:yI,[u,Ze]),Ye=f.useMemo(()=>z?!1:ja.getInstance().shouldAnimateMessage(t.info,y||t.info.sessionID),[t.info,y,z]),[Re,Ue]=f.useState(!1),Ve=f.useMemo(()=>n?xi(n.info):null,[n]),st=!!a,at=a?.isLastAssistantInTurn??!1,nt=f.useMemo(()=>z?!1:st?!at:Ve?!Ve.isUser&&Ve.role==="assistant":!1,[st,at,z,Ve]),he=f.useMemo(()=>ce?"completed":p||(g?"streaming":"completed"),[ce,p,g]);f.useEffect(()=>{!z||!i||l?.(t.info.id)},[i,z,t.info.id,l]),f.useEffect(()=>{Ue(!1)},[t.info.id]),f.useEffect(()=>{const mt=a?.headerMessageId;if(z||!mt||mt!==t.info.id)return;(he==="streaming"||he==="cooldown")&&Ue(!0)},[z,t.info.id,he,a?.headerMessageId]);const je=f.useMemo(()=>{if(z)return!0;const mt=a?.headerMessageId;return mt?t.info.id===mt?he==="completed"?!0:Re||(he==="streaming"||he==="cooldown"):!1:!0},[Re,z,a,he,t.info.id]),We=f.useCallback(mt=>{Cn(mt).then(It=>{It.ok&&(F(mt),setTimeout(()=>F(null),2e3))})},[]),lt=z?void 0:a?.userMessageVariant??q?.variant,rt=!z&&de?lt??"Default":void 0,Te=f.useMemo(()=>{if(z)return;const mt=t.info?.error;if(!mt)return;const It=typeof mt.data?.message=="string"?mt.data.message:void 0,Se=typeof mt.message=="string"?mt.message:void 0,et=typeof mt.name=="string"?mt.name:void 0,qe=It||Se||et;if(qe)return et==="SessionRetry"?`Opencode failed to send a message. Retry attempt info:
6717
+ `;const At=Xe.querySelectorAll('[aria-label^="Message time:"]'),yt=new Set;At.forEach(Zt=>{const is=Zt.getAttribute("aria-label")?.replace("Message time:","").trim();if(!is||Zt.textContent?.includes(is))return;const as=document.createElement("span");as.style.marginLeft="4px",as.textContent=is,Zt.appendChild(as);const ps=Zt.parentElement,xs=ps?.parentElement,mt=xs?.firstElementChild;!xs||!mt||mt===ps||yt.has(xs)||(mt.style.display="none",xs.style.justifyContent="flex-start",yt.add(xs))}),Ge.appendChild(Xe),document.body.appendChild(Ge);const dt=await Mb(Ge,{quality:1,pixelRatio:2,backgroundColor:jt}),Tt=`message-${t}.png`;if(ln()){const Zt=await fetch("/api/vscode/save-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileName:Tt,dataUrl:dt})});if(!Zt.ok)throw new Error("Failed to save image in VS Code");const rs=await Zt.json();if(rs.saved!==!0){if(rs.canceled)return;throw new Error(rs.error||"Failed to save image in VS Code")}}else{const Zt=document.createElement("a");Zt.download=Tt,Zt.href=dt,document.body.appendChild(Zt),Zt.click(),document.body.removeChild(Zt)}ue.success("Image saved")}catch(Ee){console.error("Failed to generate image:",Ee),ue.error("Failed to generate image")}finally{Ge&&Ge.parentNode&&Ge.parentNode.removeChild(Ge),st(!1)}},[t,Ve]);f.useEffect(()=>()=>{ke()},[ke]);const nt=f.useMemo(()=>{const ye=C?.activityParts;return!G||!ye?[]:ye},[G,C?.activityParts]),he=f.useMemo(()=>{const ye=C?.activityGroupSegments;return!G||!ye?[]:ye.filter(Ge=>Ge.anchorMessageId===t)},[G,t,C?.activityGroupSegments]),je=f.useMemo(()=>{const ye=new Map,Ge=new Map;return nt.forEach(Ee=>{ye.set(Ee.part,Ee);const $e=Ee.part.id;typeof $e=="string"&&$e.length>0&&Ge.set($e,Ee)}),{get:Ee=>{const $e=ye.get(Ee);if($e)return $e;const tt=Ee.id;if(typeof tt=="string"&&tt.length>0)return Ge.get(tt)}}},[nt]),We=C?.toggleGroup,lt=G&&he.length>0&&!!We,rt=f.useMemo(()=>{const ye=[];lt&&We&&he.forEach(Ee=>{const $e=w?Ee.parts:Ee.parts.filter(tt=>tt.kind!=="reasoning");$e.length!==0&&ye.push(s.jsx(hP,{parts:$e,isExpanded:C.isGroupExpanded===!0,collapsedPreviewCount:Y,onToggle:We,syntaxTheme:i,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:g,streamPhase:N,showHeader:!0,animateRows:T,animatedToolIds:W,diffStats:C.diffStats},`progressive-group-${Ee.id}`))});let Ge=0;for(;Ge<H.length;){const Ee=H[Ge];if(Ee.type==="text"){const $e=je.get(Ee);if(G&&!re){Ge+=1;continue}if($e?.kind==="justification"){Ge+=1;continue}ye.push(s.jsx(hT,{part:Ee,messageId:t,streamPhase:N,chatRenderMode:ee,onContentChange:g},`assistant-text-${t}-${Ge}`)),Ge++;continue}if(Ee.type==="reasoning"){const $e=je.get(Ee);if(G&&!re){Ge+=1;continue}if($e?.kind==="reasoning"){Ge+=1;continue}if(w)if(G)ye.push(s.jsx(Mg,{part:Ee,messageId:t,onContentChange:g},`reasoning-${t}-${Ge}`));else{const tt=Ee.text;tt&&tt.trim().length>0&&ye.push(s.jsx(ea,{children:s.jsx("div",{className:"text-sm text-muted-foreground/60 italic leading-relaxed whitespace-pre-wrap",children:tt})},`reasoning-${t}-${Ge}`))}Ge++;continue}if(Ee.type==="tool"){const $e=Ee,tt=$e.tool?.toLowerCase()??"";if(je.get(Ee)?.kind==="tool"&&!l3(tt)){Ge+=1;continue}if(!ve($e)){Ge++;continue}if(i3(tt)){ye.push(s.jsx(ea,{children:s.jsx(H0,{animate:W.has($e.id),wipe:!0,children:s.jsx(qu,{part:$e,isExpanded:d.has($e.id),onToggle:u,syntaxTheme:i,isMobile:l,onContentChange:g,onShowPopup:m,animateTailText:W.has($e.id)})})},`tool-${$e.id}`)),Ge++;continue}const ct=O0(tt),Xe=[$e];let At=Ge+1;for(;At<H.length;){const yt=H[At];if(yt.type!=="tool")break;const dt=yt;if(!ve(dt)){At++;continue}const Tt=dt.tool?.toLowerCase()??"";if(O0(Tt)!==ct)break;Xe.push(dt),At++}ye.push(s.jsx(ea,{children:s.jsx(H0,{animate:Xe.some(yt=>W.has(yt.id)),wipe:!0,children:s.jsx(_g,{toolName:ct,activities:Xe.map(yt=>({id:yt.id,turnId:"",messageId:t,partIndex:0,part:yt,kind:"tool"})),animateTailText:Xe.some(yt=>W.has(yt.id))})})},`static-tools-${$e.id}`)),Ge=At;continue}Ge++}return ye},[je,he,W,T,ee,Y,d,re,l,G,t,g,m,u,lt,ve,N,w,i,We,C,H]),Te=!!k,Qe=oe&&y&&(re||!!k),pt=f.useMemo(()=>{if(!oe||!re)return;const ye=C?.userMessageCreatedAt;if(!(typeof ye!="number"||typeof o!="number")&&!(o<=ye))return bP(o-ye)},[oe,re,C?.userMessageCreatedAt,o]),St=f.useMemo(()=>{const ye=typeof o=="number"&&o>0?o:typeof a=="number"&&a>0?a:null;if(ye===null)return null;const Ge=IT(ye);return Ge.length>0?Ge:null},[o,a]),Ht="text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",Ke=s.jsxs(s.Fragment,{children:[b&&s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon","data-visible":S||D?"true":void 0,className:J("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",!Fe&&"opacity-50"),disabled:!Fe,"aria-label":"Copy message text","aria-hidden":!Fe,onPointerDown:ye=>ye.stopPropagation(),onClick:Je,onFocus:()=>{Fe&&j(!0)},onBlur:()=>{D||j(!1)},children:D?s.jsx(vs,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):s.jsx(Jn,{className:"h-3.5 w-3.5"})})}),s.jsx($t,{sideOffset:6,children:"Copy answer"})]}),s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{type:"button",size:"icon",variant:"ghost",disabled:Ve||!Fe,className:J("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",(!Fe||Ve)&&"opacity-50"),onPointerDown:ye=>ye.stopPropagation(),onClick:at,children:Ve?s.jsx(os,{className:"h-4 w-4 animate-spin"}):s.jsx(Ab,{className:"h-4 w-4"})})}),s.jsx($t,{sideOffset:6,children:Ve?"Saving image...":"Save as image"})]}),s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{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:ye=>ye.stopPropagation(),onClick:Ye,children:s.jsx(ru,{className:"h-4 w-4"})})}),s.jsx($t,{sideOffset:6,children:"Start new session from this answer"})]}),s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{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:ye=>ye.stopPropagation(),onClick:Re,children:s.jsx(o3,{className:"h-4 w-4"})})}),s.jsx($t,{sideOffset:6,children:"Start new multi-run from this answer"})]}),$&&Fe&&s.jsxs(Vt,{delayDuration:1e3,children:[s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{type:"button",variant:"ghost",size:"icon",className:J("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",fe?"text-green-500":"text-muted-foreground hover:text-foreground"),"aria-label":fe?"Stop speaking":"Read aloud",onPointerDown:ye=>ye.stopPropagation(),onClick:Ue,children:fe?s.jsx(Po,{className:"h-3.5 w-3.5"}):s.jsx(w4,{className:"h-3.5 w-3.5"})})}),s.jsx($t,{sideOffset:6,children:X})]})]});return s.jsxs("div",{ref:M,className:J("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:E&&B&&Fe?Ze:void 0,children:[s.jsx(MT,{containerRef:M}),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:[rt,Te&&s.jsx(ea,{children:s.jsx("div",{className:"group/assistant-text relative break-words",children:s.jsx(po,{content:k??"",onShowPopup:m})})},"assistant-error")]}),s.jsx(K4,{files:e,onShowPopup:m}),Qe&&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:Ke}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[pt?s.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[s.jsx(Fb,{className:"h-3.5 w-3.5"}),pt]}):null,St?s.jsxs("span",{className:Ht,"aria-label":`Message time: ${St}`,children:[s.jsx(Qr,{className:"h-3.5 w-3.5"}),St]}):null]})]})]})]})},SP=t=>{const e=Ce.c(19);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||e[14]!==r.stickyUserHeaderEnabled||e[15]!==r.userActionsMode?(a=s.jsx(wP,{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,userActionsMode:r.userActionsMode,stickyUserHeaderEnabled:r.stickyUserHeaderEnabled}),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]=r.stickyUserHeaderEnabled,e[15]=r.userActionsMode,e[16]=a):a=e[16],a}let o;return e[17]!==r?(o=s.jsx(jP,{...r}),e[17]=r,e[18]=o):o=e[18],o},Md=f.memo(SP);function kP(t){return t.setCurrentSession}function NP(t){return!t}function CP(t){return!t}const xi=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}},MP=t=>{const e=t.trim();return!!(e.startsWith("User has requested to enter plan mode")||e.startsWith("The plan at ")||e.startsWith("The following tool was executed by the user"))},AP=t=>t.filter(e=>{if(!(e.synthetic===!0))return!0;if(e.type!=="text")return!1;const r=e.text;return typeof r=="string"?MP(r):!1}).map(e=>{const n=e;return n.type==="compaction"?{type:"text",text:"/compact"}:n.type==="text"&&(typeof n.text=="string"?n.text.trim():"").startsWith("The following tool was executed by the user")?{type:"text",text:"/shell"}:e}),FP=f.lazy(()=>cr(()=>import("./ToolOutputDialog-CM2Xnf7u.js"),__vite__mapDeps([2,0,1,3,4]))),Bg=4e3,Ri=new Map,Li=new Map,DP=new Set(["bash","shell","cmd","terminal"]),_P=new Set(["apply_patch","edit","write","multiedit","str_replace","str_replace_based_edit_tool","create","file_write"]),BP=t=>{if(typeof t!="string")return"";const e=t.trim().toLowerCase();if(!e)return"";const n=e.replace(/:\d+$/,"");if(!n.includes("."))return n;const r=n.split(".").filter(Boolean);return r[r.length-1]??n},Rh=t=>{const e=Ri.get(t);return e?new Set(e):new Set},Lh=(t,e)=>{if(Ri.size>=Bg&&!Ri.has(t)){const n=Ri.keys().next().value;typeof n=="string"&&Ri.delete(n)}Ri.set(t,new Set(e))},zh=t=>{const e=Li.get(t);return e?new Set(e):new Set},Hh=(t,e)=>{if(Li.size>=Bg&&!Li.has(t)){const n=Li.keys().next().value;typeof n=="string"&&Li.delete(n)}Li.set(t,new Set(e))};function Ad(t){const e=Ce.c(3),[n,r]=f.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]),f.useEffect(o,a),t??n}const to=(t,e)=>{if(typeof t=="object"&&t!==null)return t[e]},EP=({message:t,previousMessage:e,nextMessage:n,onContentChange:r,animationHandlers:o,turnGroupingContext:a,animateUserOnMount:i=!1,onUserAnimationConsumed:l})=>{const{isMobile:c,hasTouchInput:d}=wn(),{currentTheme:u}=ir(),m=f.useRef(null),h=Le(sa(mt=>({lifecyclePhase:mt.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const It=t.info.sessionID??mt.currentSessionId??null;return It?(mt.streamingMessageIds.get(It)??null)===t.info.id:!1})(),currentSessionId:mt.currentSessionId,getAgentModelForSession:mt.getAgentModelForSession,getSessionModelSelection:mt.getSessionModelSelection,revertToMessage:mt.revertToMessage,forkFromMessage:mt.forkFromMessage}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:y,getAgentModelForSession:b,getSessionModelSelection:x,revertToMessage:v,forkFromMessage:w}=h,C=Yt(mt=>mt.providers),{showReasoningTraces:k,stickyUserHeader:N,chatRenderMode:S,showExpandedBashTools:j,showExpandedEditTools:A}=De(sa(mt=>({showReasoningTraces:mt.showReasoningTraces,stickyUserHeader:mt.stickyUserHeader,chatRenderMode:mt.chatRenderMode,showExpandedBashTools:mt.showExpandedBashTools,showExpandedEditTools:mt.showExpandedEditTools})));f.useEffect(()=>{y&&ja.getInstance().recordSessionStart(y)},[y]);const[M,F]=f.useState(null),[B,D]=f.useState(!1),[E,I]=f.useState(()=>Rh(t.info.id)),[T,H]=f.useState(()=>zh(t.info.id)),[P,_]=f.useState({open:!1,title:"",content:""});f.useEffect(()=>{I(Rh(t.info.id)),H(zh(t.info.id))},[t.info.id]);const z=f.useMemo(()=>xi(t.info),[t.info]).isUser,O=z&&(c||!N),Q=z&&!c&&N&&!O,te=t.info.sessionID,{currentContextAgent:W,savedSessionAgentSelection:U}=bs(sa(mt=>({currentContextAgent:te?mt.currentAgentContext.get(te):void 0,savedSessionAgentSelection:te?mt.sessionAgentSelections.get(te):void 0}))),K=f.useMemo(()=>z?AP(t.parts):t.parts,[z,t.parts]),q=f.useMemo(()=>{if(z||!e)return null;const mt=to(e.info,"clientRole"),It=to(e.info,"role");if((typeof mt=="string"?mt:typeof It=="string"?It:void 0)!=="user")return null;const et=to(e.info,"mode"),qe=to(e.info,"agent"),bt=to(e.info,"providerID"),Rt=to(e.info,"modelID"),Nt=to(e.info,"variant"),Pt=typeof et=="string"&&et.trim().length>0?et:typeof qe=="string"&&qe.trim().length>0?qe:void 0,Jt=typeof bt=="string"&&bt.trim().length>0?bt:void 0,Wt=typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,Ie=typeof Nt=="string"&&Nt.trim().length>0?Nt:void 0;return!Pt&&!Jt&&!Wt&&!Ie?null:{agentName:Pt,providerId:Jt,modelId:Wt,variant:Ie}},[z,e]),ee=f.useMemo(()=>{if(z||!e)return!1;const mt=Array.isArray(e.parts)?e.parts:[];for(let It=0;It<mt.length;It++){const Se=mt[It];if(Se?.type!=="text"||Se?.synthetic!==!0)continue;const et=typeof Se.text=="string"?Se.text.trim():"";if(et.startsWith("User has requested to enter plan mode")||et.startsWith("The plan at "))return!0}return!1},[z,e]),V=f.useMemo(()=>{if(z)return;const mt=t.info.time;if(!(typeof mt?.completed=="number"&&mt.completed>0)&&ee&&q?.agentName)return q.agentName;const Se=to(t.info,"mode");if(typeof Se=="string"&&Se.trim().length>0)return Se;const et=to(t.info,"agent");if(typeof et=="string"&&et.trim().length>0)return et;if(q?.agentName)return q.agentName;if(te)return W||(U??void 0)},[z,t.info,ee,q,te,W,U]),G=z?null:to(t.info,"providerID"),Y=z?null:to(t.info,"modelID"),oe=f.useMemo(()=>{if(z||!te)return null;if(q?.providerId&&q?.modelId)return{providerId:q.providerId,modelId:q.modelId};if(V){const It=b(te,V);if(It?.providerId&&It?.modelId)return It}const mt=x(te);return mt?.providerId&&mt?.modelId?mt:null},[z,te,V,q,b,x]),re=f.useMemo(()=>z?null:typeof G=="string"&&G.trim().length>0?G:oe?.providerId??null,[z,G,oe]),fe=f.useMemo(()=>z?null:typeof Y=="string"&&Y.trim().length>0?Y:oe?.modelId??null,[z,Y,oe]),ie=f.useMemo(()=>{if(!z&&re&&fe&&C.length>0){const mt=C.find(It=>It.id===re);if(mt?.models&&Array.isArray(mt.models)){const et=mt.models.find(qe=>qe.id===fe)?.name;return typeof et=="string"?et:void 0}}},[z,re,fe,C]),de=f.useMemo(()=>{if(z||!re||!fe)return!1;const mt=C.find(et=>et.id===re);if(!mt?.models||!Array.isArray(mt.models))return!1;const Se=mt.models.find(et=>et.id===fe)?.variants;return!!(Se&&Object.keys(Se).length>0)},[z,fe,re,C]),$=Ad(V),L=Ad(re??void 0),X=Ad(ie),ne=$??void 0,se=L??null,pe=X??void 0,ae=f.useMemo(()=>{const mt=t.info.time;return typeof mt?.completed=="number"?mt.completed:null},[t.info.time]),ve=f.useMemo(()=>{const mt=t.info.time;return typeof mt?.created=="number"?mt.created:null},[t.info.time]),ce=f.useMemo(()=>z?!0:!!(ae&&ae>0),[z,ae]),Z=f.useMemo(()=>{const mt=t.info.finish;return typeof mt=="string"?mt:void 0},[t.info]),me=f.useMemo(()=>kT(K,{includeReasoning:k}),[K,k]),be=f.useMemo(()=>z?me:!ce&&S==="sorted"?[]:me,[S,ce,z,me]),we=f.useMemo(()=>z?[]:me.filter(mt=>mt.type==="text"),[z,me]),Ae=f.useMemo(()=>z?[]:me.filter(It=>It.type==="tool"),[z,me]),Pe=f.useMemo(()=>z?[]:(a?.activityParts??[]).filter(It=>It.kind==="tool").map(It=>It.part).filter(It=>It.type==="tool"),[z,a?.activityParts]),xe=f.useMemo(()=>{if(!j&&!A)return new Set;const mt=new Set;for(const It of[...Ae,...Pe]){const Se=typeof It?.id=="string"?It.id:"";if(!Se)continue;const et=BP(It.tool);if(et){if(j&&DP.has(et)){mt.add(Se);continue}A&&_P.has(et)&&mt.add(Se)}}return mt},[j,A,Ae,Pe]),_e=f.useMemo(()=>{if(xe.size===0&&T.size===0)return E;const mt=new Set(E);return xe.forEach(It=>{T.has(It)||mt.add(It)}),T.forEach(It=>{mt.delete(It)}),mt},[T,xe,E]),ze=f.useMemo(()=>{if(!z)return;const mt=t.parts.find(qe=>qe.type==="agent");if(!mt)return;const It=mt,Se=typeof It.name=="string"?It.name:void 0;if(!Se)return;const et=It.source&&typeof It.source.value=="string"&&It.source.value.trim().length>0?It.source.value:`@${Se}`;return{name:Se,token:et}},[z,t.parts]),le=z&&be.length===0,ge=typeof Z!="string",Fe=f.useMemo(()=>z?!1:we.length===0||Ae.length===0?ge:!0,[we.length,Ae.length,ge,z]),ke=u?.metadata.variant,Ze=f.useMemo(()=>ke?ke==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ke]),Je=f.useMemo(()=>u?E2(u):Ze?gI:yI,[u,Ze]),Ye=f.useMemo(()=>z?!1:ja.getInstance().shouldAnimateMessage(t.info,y||t.info.sessionID),[t.info,y,z]),[Re,Ue]=f.useState(!1),Ve=f.useMemo(()=>n?xi(n.info):null,[n]),st=!!a,at=a?.isLastAssistantInTurn??!1,nt=f.useMemo(()=>z?!1:st?!at:Ve?!Ve.isUser&&Ve.role==="assistant":!1,[st,at,z,Ve]),he=f.useMemo(()=>ce?"completed":p||(g?"streaming":"completed"),[ce,p,g]);f.useEffect(()=>{!z||!i||l?.(t.info.id)},[i,z,t.info.id,l]),f.useEffect(()=>{Ue(!1)},[t.info.id]),f.useEffect(()=>{const mt=a?.headerMessageId;if(z||!mt||mt!==t.info.id)return;(he==="streaming"||he==="cooldown")&&Ue(!0)},[z,t.info.id,he,a?.headerMessageId]);const je=f.useMemo(()=>{if(z)return!0;const mt=a?.headerMessageId;return mt?t.info.id===mt?he==="completed"?!0:Re||(he==="streaming"||he==="cooldown"):!1:!0},[Re,z,a,he,t.info.id]),We=f.useCallback(mt=>{Cn(mt).then(It=>{It.ok&&(F(mt),setTimeout(()=>F(null),2e3))})},[]),lt=z?void 0:a?.userMessageVariant??q?.variant,rt=!z&&de?lt??"Default":void 0,Te=f.useMemo(()=>{if(z)return;const mt=t.info?.error;if(!mt)return;const It=typeof mt.data?.message=="string"?mt.data.message:void 0,Se=typeof mt.message=="string"?mt.message:void 0,et=typeof mt.name=="string"?mt.name:void 0,qe=It||Se||et;if(qe)return et==="SessionRetry"?`Opencode failed to send a message. Retry attempt info:
6718
6718
  \`${qe}\``:Nu(qe)?ku:`Opencode failed to send message with error:
6719
6719
  \`${qe}\``},[z,t.info]),Qe=f.useMemo(()=>{if(z){const mt=be.filter(qe=>qe.type==="text").map(qe=>{const bt=qe.shellAction?.output;return typeof bt=="string"?bt.trim():""}).filter(qe=>qe.length>0);if(mt.length>0)return mt.join(`
6720
6720
 
@@ -6924,12 +6924,12 @@ Must-fix:
6924
6924
  - None
6925
6925
  Nice-to-have:
6926
6926
  - None`,be=cG(ce);await zt.sendMessage({id:$.sessionId,providerID:se,modelID:pe,agent:ae,variant:ve,text:Z,additionalParts:[{text:me,synthetic:!0},{text:be,synthetic:!0}]}),ue.success("Session created from PR")}},[W,r,d,O,Q,te]),K=m==="new-branch"?p:y;Ne.useEffect(()=>{if(!x?.all||!d||p.sourceBranch)return;(async()=>{try{const L=await Ta(d).catch(()=>null),X=localStorage.getItem(S6),ne=X&&x.all?.includes(X)?X:L&&x.all?.includes(L)?L:x.all?.includes("main")?"main":x.all?.includes("master")?"master":x.all?.[0]||"";ne&&g(se=>({...se,sourceBranch:ne}))}catch{}})()},[x,d,p.sourceBranch]),Ne.useEffect(()=>{if(!t){h("new-branch"),g({branchName:"",worktreeName:"",isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1}),b({selectedBranch:"",worktreeName:""}),H({isValidating:!1,branchError:null,worktreeError:null,touched:!1});return}const $=A();g(L=>({...L,branchName:$,worktreeName:$,isSyncingWorktreeName:!0}))},[t,A]),Ne.useEffect(()=>{if(m!=="new-branch"||!p.isSyncingWorktreeName)return;const $=Yl(p.branchName),L=Lr($);g(X=>({...X,worktreeName:L}))},[m,p.branchName,p.isSyncingWorktreeName]);const q=Ne.useCallback(async()=>{if(!u||!T.touched||P)return;R&&R.abort();const $=new AbortController;z($),H(L=>({...L,isValidating:!0}));try{const L=m==="new-branch"?p.branchName:y.selectedBranch,X=K.worktreeName,ne=Yl(L),se=Lr(X);let pe=null,ae=null;if(ne||(pe="Branch name is required"),se||(ae="Worktree directory is required"),ne&&se){const ve=await E8(u,{mode:m==="existing-branch"?"existing":"new",branchName:ne,worktreeName:se,existingBranch:m==="existing-branch"?ne:void 0});if($.signal.aborted)return;ve.ok||ve.errors.forEach(ce=>{if(ce.code==="worktree_exists"){ae=ae??ce.message;return}ce.code.startsWith("branch_")&&(pe=pe??ce.message)})}$.signal.aborted||H(ve=>({...ve,isValidating:!1,branchError:pe,worktreeError:ae}))}catch{$.signal.aborted||H(L=>({...L,isValidating:!1}))}},[u,m,p.branchName,y.selectedBranch,K.worktreeName,T.touched,R,P]),ee=m==="new-branch"?p.branchName:y.selectedBranch;Ne.useEffect(()=>{if(!t||!u||!T.touched||P)return;const $=setTimeout(()=>{q()},300);return()=>clearTimeout($)},[K.worktreeName,ee,t,u,q,T.touched,P]);const V=async()=>{if(!u||!d){ue.error("No active project");return}H(se=>({...se,touched:!0}));const $=m==="new-branch"?p.branchName:y.selectedBranch,L=K.worktreeName,X=Yl($),ne=Lr(L);if(!X){ue.error("Branch name is required");return}if(!ne){ue.error("Worktree directory is required");return}R&&(R.abort(),z(null)),H(se=>({...se,isValidating:!1,branchError:null,worktreeError:null})),_(!0);try{const se=await Ci(u),pe=m==="new-branch"?p.linkedPr:null,ae=p.sourceBranch;let ve="";const ce=(()=>{if(pe){const xe=iG(pe,k);return ve=xe.sourceLabel,{preferredName:X||ne,mode:"existing",branchName:X,worktreeName:ne,existingBranch:xe.existingBranch,setupCommands:se,setUpstream:xe.setUpstream,upstreamRemote:xe.upstreamRemote,upstreamBranch:xe.upstreamBranch,...xe.ensureRemoteName?{ensureRemoteName:xe.ensureRemoteName}:{},...xe.ensureRemoteUrl?{ensureRemoteUrl:xe.ensureRemoteUrl}:{}}}return ve=m==="new-branch"?ae:"",{preferredName:X||ne,mode:m==="existing-branch"?"existing":"new",branchName:m==="existing-branch"?void 0:X,worktreeName:ne,existingBranch:m==="existing-branch"?X:void 0,setupCommands:se,...ae&&m==="new-branch"?{startRef:ae}:{}}})(),Z=await ug(d,ce),me=await B8(u,Z),be=m==="new-branch"?p.linkedIssue:null,we=m==="new-branch"?p.linkedPr:null,Ae=m==="new-branch"?p.includePrDiff:!1;let Pe=null;if(be||we){const xe=be?`#${be.number} ${be.title}`.trim():we?`#${we.number} ${we.title}`.trim():"New session",_e=await Le.getState().createSession(xe,me.path,null);if(!_e?.id)throw new Error("Failed to create session");Pe=_e.id,Le.getState().updateSessionTitle(_e.id,xe).catch(()=>{});try{Le.getState().initializeNewOpenChamberSession(_e.id,Yt.getState().agents)}catch{}}p.sourceBranch&&m==="new-branch"&&!p.linkedPr&&localStorage.setItem(S6,p.sourceBranch),ue.success("Worktree created",{description:`${me.branch||me.name}${ve?` from ${ve}`:""}`});try{await S()}catch{}e(!1),Pe?(n?.(me.path,{sessionId:Pe}),U({sessionId:Pe,issue:be,pr:we,includeDiff:Ae}).catch(xe=>{const _e=xe instanceof Error?xe.message:"Failed to send GitHub context";ue.error("Failed to send GitHub context",{description:_e})})):n?.(me.path)}catch(se){const pe=se instanceof Error?se.message:"Failed to create worktree";ue.error("Failed to create worktree",{description:pe})}finally{_(!1)}},G=$=>{h($),H(L=>({...L,touched:!1,branchError:null,worktreeError:null}))},Y=$=>{if(!$){g(L=>({...L,linkedIssue:null,linkedPr:null,includePrDiff:!1,branchName:""}));return}if($.type==="issue"){const L=$.item,X=`issue-${L.number}-${mc()}`;g(ne=>({...ne,linkedIssue:L,linkedPr:null,includePrDiff:!1,branchName:X,worktreeName:Lr(X),isSyncingWorktreeName:!0}))}else if($.type==="pr"){const L=$.item;g(X=>({...X,linkedPr:L,linkedIssue:null,includePrDiff:$.includeDiff??!1,branchName:L.head,worktreeName:Lr(L.head),isSyncingWorktreeName:!0}))}},oe=l&&i?.connected===!0,fe=(m==="existing-branch"?!!y.selectedBranch&&!!y.worktreeName&&!T.branchError&&!T.worktreeError:!!Yl(p.branchName)&&!!p.worktreeName&&!T.branchError&&!T.worktreeError)&&!P,ie=()=>{g($=>({...$,linkedIssue:null,linkedPr:null,branchName:"",includePrDiff:!1,isSyncingWorktreeName:!0}))},de=s.jsxs("div",{className:J("flex gap-2",a?"flex-col w-full":"flex-row items-center"),children:[s.jsx("div",{className:J("flex items-center gap-1.5 text-destructive",a?"w-full justify-center order-first":"mr-auto"),children:T.touched&&(T.branchError||T.worktreeError)&&s.jsxs(s.Fragment,{children:[s.jsx(Co,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"typography-micro",children:T.branchError||T.worktreeError})]})}),s.jsxs("div",{className:J("flex gap-2",a&&"w-full"),children:[s.jsx(ot,{variant:"outline",size:"sm",onClick:()=>e(!1),disabled:P,className:J(a&&"flex-1"),children:"Cancel"}),s.jsxs(ot,{size:"sm",onClick:V,disabled:!fe||P,className:J("gap-1.5",a&&"flex-1"),children:[P&&s.jsx(os,{className:"h-3.5 w-3.5 animate-spin"}),P?"Creating...":"Create Worktree"]})]})]});return s.jsxs(s.Fragment,{children:[a?s.jsxs(rr,{open:t,title:"New Worktree",onClose:()=>e(!1),footer:de,children:[s.jsx("div",{className:"w-full mb-4",children:s.jsx(Mo,{items:[{id:"new-branch",label:"New Branch",icon:s.jsx(cn,{className:"h-3.5 w-3.5"})},{id:"existing-branch",label:"Existing Branch",icon:s.jsx(cu,{className:"h-3.5 w-3.5"})}],activeId:m,onSelect:$=>G($),variant:"active-pill",layoutMode:"fit",className:"w-full"})}),s.jsxs("div",{className:"space-y-6",children:[m==="existing-branch"?s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:"Select Branch"}),s.jsxs(ot,{variant:"outline",size:"sm",onClick:()=>D(!0),className:"w-full justify-between h-9",children:[s.jsx("span",{className:y.selectedBranch?"text-foreground":"text-muted-foreground",children:y.selectedBranch||"Choose a branch..."}),s.jsx(cn,{className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(rr,{open:B,title:"Select Branch",onClose:()=>D(!1),children:s.jsx("div",{className:"space-y-4",children:v?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:"Loading branches..."}):C.length===0&&k.length===0?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:"No branches found"}):s.jsxs(s.Fragment,{children:[C.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:"Local branches"}),s.jsx("div",{className:"space-y-1",children:C.map($=>s.jsx("button",{onClick:()=>{b(L=>({...L,selectedBranch:$,worktreeName:Lr($)})),H(L=>({...L,touched:!0})),D(!1)},className:J("w-full text-left px-3 py-2.5 rounded-md transition-colors",y.selectedBranch===$?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:$})},$))})]}),k.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:"Remote branches"}),s.jsx("div",{className:"space-y-1",children:k.map($=>s.jsx("button",{onClick:()=>{b(L=>({...L,selectedBranch:`remotes/${$}`,worktreeName:Lr($)})),H(L=>({...L,touched:!0})),D(!1)},className:J("w-full text-left px-3 py-2.5 rounded-md transition-colors",y.selectedBranch===`remotes/${$}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:$})},`remotes/${$}`))})]})]})})})]}):s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:"Branch Name"}),m==="new-branch"&&oe&&s.jsxs(ot,{variant:"outline",size:"sm",onClick:()=>F(!0),className:"gap-1.5 h-7",children:[s.jsx(Jo,{className:"size-4 text-status-success"}),p.linkedIssue||p.linkedPr?"Change":"Start from GitHub Issue/PR"]})]}),s.jsx(ts,{value:p.branchName,onChange:$=>{g(L=>({...L,branchName:$.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>H($=>({...$,touched:!0})),placeholder:"feature/my-awesome-feature",disabled:!!p.linkedPr,className:J("h-8",T.touched&&T.branchError&&"border-destructive",p.linkedPr&&"bg-muted text-muted-foreground")}),p.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(vs,{className:"h-3.5 w-3.5 text-status-success"}),s.jsxs("span",{className:"typography-micro",children:["Using PR branch: ",p.linkedPr.head]})]}),p.linkedIssue&&!p.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(vs,{className:"h-3.5 w-3.5 text-status-success"}),s.jsxs("span",{className:"typography-micro",children:["From issue #",p.linkedIssue.number,": ",p.linkedIssue.title]})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"typography-ui-label text-foreground font-semibold",children:"Worktree Directory"}),m!=="existing-branch"&&s.jsxs("button",{onClick:()=>{const $=Lr(m==="new-branch"?p.branchName:"");g(L=>({...L,worktreeName:$,isSyncingWorktreeName:!0}))},disabled:!p.branchName||p.worktreeName===Lr(p.branchName),className:J("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",p.worktreeName===Lr(p.branchName)||!p.branchName?"text-muted-foreground/40 cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-muted"),title:"Reset to match branch name",children:[s.jsx(Wn,{className:"h-3 w-3"}),s.jsx("span",{children:"Reset"})]})]}),s.jsx(ts,{value:K.worktreeName,onChange:$=>{m==="new-branch"?g(L=>({...L,worktreeName:$.target.value,isSyncingWorktreeName:!1})):b(L=>({...L,worktreeName:$.target.value}))},onBlur:()=>H($=>({...$,touched:!0})),placeholder:"my-worktree-directory",className:J("h-8",T.touched&&T.worktreeError&&"border-destructive")})]}),m==="new-branch"&&!p.linkedPr&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:"Source Branch"}),s.jsxs(ot,{variant:"outline",size:"sm",onClick:()=>I(!0),className:"w-full justify-between h-9",children:[s.jsx("span",{className:p.sourceBranch?"text-foreground":"text-muted-foreground",children:p.sourceBranch||"Select source branch..."}),s.jsx(cn,{className:"h-4 w-4 text-muted-foreground"})]}),p.sourceBranch&&s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["New branch will be created from ",p.sourceBranch]}),s.jsx(rr,{open:E,title:"Select Source Branch",onClose:()=>I(!1),children:s.jsx("div",{className:"space-y-4",children:v?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:"Loading branches..."}):C.length===0&&k.length===0?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:"No branches found"}):s.jsxs(s.Fragment,{children:[C.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:"Local branches"}),s.jsx("div",{className:"space-y-1",children:C.map($=>s.jsx("button",{onClick:()=>{g(L=>({...L,sourceBranch:$})),I(!1)},className:J("w-full text-left px-3 py-2.5 rounded-md transition-colors",p.sourceBranch===$?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:$})},$))})]}),k.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:"Remote branches"}),s.jsx("div",{className:"space-y-1",children:k.map($=>s.jsx("button",{onClick:()=>{g(L=>({...L,sourceBranch:`remotes/${$}`})),I(!1)},className:J("w-full text-left px-3 py-2.5 rounded-md transition-colors",p.sourceBranch===`remotes/${$}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:$})},`remotes/${$}`))})]})]})})})]}),(p.linkedIssue||p.linkedPr)&&m==="new-branch"&&s.jsxs("div",{className:"mt-2 px-2 py-1.5 rounded bg-muted/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Jo,{className:"h-3.5 w-3.5 text-status-success shrink-0"}),p.linkedIssue&&s.jsxs("span",{className:"typography-micro text-muted-foreground shrink-0",children:["Issue #",p.linkedIssue.number]}),p.linkedPr&&s.jsxs("span",{className:"typography-micro text-muted-foreground shrink-0",children:["PR #",p.linkedPr.number]}),s.jsx("span",{className:"typography-micro text-foreground truncate flex-1",children:p.linkedIssue?.title||p.linkedPr?.title}),s.jsx("a",{href:p.linkedIssue?.url||p.linkedPr?.url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",onClick:$=>$.stopPropagation(),children:s.jsx(yr,{className:"h-3 w-3"})}),s.jsx("button",{onClick:ie,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(_s,{className:"h-3.5 w-3.5"})})]}),p.linkedPr&&s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 pl-5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[p.linkedPr.head," → ",p.linkedPr.base]}),p.includePrDiff&&s.jsx("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success",children:"+diff"})]})]})]})]}):s.jsx($s,{open:t,onOpenChange:e,children:s.jsxs(Vs,{className:"max-w-lg max-h-[80vh] flex flex-col",children:[s.jsx(Zs,{className:"flex flex-row items-center justify-between",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs(Us,{className:"flex items-center gap-2 shrink-0",children:[s.jsx(cn,{className:"h-5 w-5"}),"New Worktree"]}),s.jsx("div",{className:"w-[280px] shrink-0",children:s.jsx(Mo,{items:[{id:"new-branch",label:"New Branch",icon:s.jsx(cn,{className:"h-3.5 w-3.5"})},{id:"existing-branch",label:"Existing Branch",icon:s.jsx(cu,{className:"h-3.5 w-3.5"})}],activeId:m,onSelect:$=>G($),variant:"active-pill",layoutMode:"fit",className:"w-full"})})]})}),s.jsxs("div",{className:"flex-1 overflow-y-auto mt-2 space-y-6",children:[m==="existing-branch"?s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:"Select Branch"}),s.jsxs(dn,{value:y.selectedBranch,onValueChange:$=>{b(L=>({...L,selectedBranch:$,worktreeName:Lr($)})),H(L=>({...L,touched:!0}))},children:[s.jsx(un,{size:"lg",className:"w-fit",children:s.jsx(bn,{placeholder:"Choose a branch..."})}),s.jsx(fn,{className:"max-h-[280px] max-w-[320px]",children:v?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:"Loading branches..."}):C.length===0&&k.length===0?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:"No branches found"}):s.jsxs(s.Fragment,{children:[C.length>0&&s.jsxs(Sa,{children:[s.jsx(Xa,{className:"typography-small font-semibold text-foreground",children:"Local branches"}),C.map($=>s.jsx(fs,{value:$,className:"whitespace-normal break-all",children:$},$))]}),C.length>0&&k.length>0&&s.jsx(G0,{}),k.length>0&&s.jsxs(Sa,{children:[s.jsx(Xa,{className:"typography-small font-semibold text-foreground",children:"Remote branches"}),k.map($=>s.jsx(fs,{value:`remotes/${$}`,className:"whitespace-normal break-all",children:$},`remotes/${$}`))]})]})})]})]}):s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:"Branch Name"}),m==="new-branch"&&oe&&s.jsxs(ot,{variant:"outline",size:"sm",onClick:()=>F(!0),className:"gap-1.5 h-7",children:[s.jsx(Jo,{className:"size-4 text-status-success"}),p.linkedIssue||p.linkedPr?"Change":"Start from GitHub Issue/PR"]})]}),s.jsx(ts,{value:p.branchName,onChange:$=>{g(L=>({...L,branchName:$.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>H($=>({...$,touched:!0})),placeholder:"feature/my-awesome-feature",disabled:!!p.linkedPr,className:J("h-8",T.touched&&T.branchError&&"border-destructive",p.linkedPr&&"bg-muted text-muted-foreground")}),p.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(vs,{className:"h-3.5 w-3.5 text-status-success"}),s.jsxs("span",{className:"typography-micro",children:["Using PR branch: ",p.linkedPr.head]})]}),p.linkedIssue&&!p.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(vs,{className:"h-3.5 w-3.5 text-status-success"}),s.jsxs("span",{className:"typography-micro",children:["From issue #",p.linkedIssue.number,": ",p.linkedIssue.title]})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"typography-ui-label text-foreground font-semibold",children:"Worktree Directory"}),m!=="existing-branch"&&s.jsxs("button",{onClick:()=>{const $=Lr(m==="new-branch"?p.branchName:"");g(L=>({...L,worktreeName:$,isSyncingWorktreeName:!0}))},disabled:!p.branchName||p.worktreeName===Lr(p.branchName),className:J("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",p.worktreeName===Lr(p.branchName)||!p.branchName?"text-muted-foreground/40 cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-muted"),title:"Reset to match branch name",children:[s.jsx(Wn,{className:"h-3 w-3"}),s.jsx("span",{children:"Reset"})]})]}),s.jsx(ts,{value:K.worktreeName,onChange:$=>{m==="new-branch"?g(L=>({...L,worktreeName:$.target.value,isSyncingWorktreeName:!1})):b(L=>({...L,worktreeName:$.target.value}))},onBlur:()=>H($=>({...$,touched:!0})),placeholder:"my-worktree-directory",className:J("h-8",T.touched&&T.worktreeError&&"border-destructive")})]}),m==="new-branch"&&!p.linkedPr&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:"Source Branch"}),s.jsxs(dn,{value:p.sourceBranch,onValueChange:$=>g(L=>({...L,sourceBranch:$})),children:[s.jsx(un,{size:"lg",className:"w-fit",children:s.jsx(bn,{placeholder:"Select source branch..."})}),s.jsx(fn,{className:"max-h-[280px] max-w-[320px]",children:v?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:"Loading branches..."}):C.length===0&&k.length===0?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:"No branches found"}):s.jsxs(s.Fragment,{children:[C.length>0&&s.jsxs(Sa,{children:[s.jsx(Xa,{className:"typography-small font-semibold text-foreground",children:"Local branches"}),C.map($=>s.jsx(fs,{value:$,className:"whitespace-normal break-all",children:$},$))]}),C.length>0&&k.length>0&&s.jsx(G0,{}),k.length>0&&s.jsxs(Sa,{children:[s.jsx(Xa,{className:"typography-small font-semibold text-foreground",children:"Remote branches"}),k.map($=>s.jsx(fs,{value:`remotes/${$}`,className:"whitespace-normal break-all",children:$},`remotes/${$}`))]})]})})]}),p.sourceBranch&&s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["New branch will be created from ",p.sourceBranch]})]}),(p.linkedIssue||p.linkedPr)&&m==="new-branch"&&s.jsxs("div",{className:"mt-2 px-2 py-1.5 rounded bg-muted/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Jo,{className:"h-3.5 w-3.5 text-status-success shrink-0"}),p.linkedIssue&&s.jsxs("span",{className:"typography-micro text-muted-foreground shrink-0",children:["Issue #",p.linkedIssue.number]}),p.linkedPr&&s.jsxs("span",{className:"typography-micro text-muted-foreground shrink-0",children:["PR #",p.linkedPr.number]}),s.jsx("span",{className:"typography-micro text-foreground truncate flex-1",children:p.linkedIssue?.title||p.linkedPr?.title}),s.jsx("a",{href:p.linkedIssue?.url||p.linkedPr?.url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",onClick:$=>$.stopPropagation(),children:s.jsx(yr,{className:"h-3 w-3"})}),s.jsx("button",{onClick:ie,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(_s,{className:"h-3.5 w-3.5"})})]}),p.linkedPr&&s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 pl-5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[p.linkedPr.head," → ",p.linkedPr.base]}),p.includePrDiff&&s.jsx("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success",children:"+diff"})]})]})]}),s.jsxs(vn,{className:"mt-1 flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center gap-1.5 text-destructive",children:T.touched&&(T.branchError||T.worktreeError)&&s.jsxs(s.Fragment,{children:[s.jsx(Co,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"typography-micro",children:T.branchError||T.worktreeError})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ot,{variant:"outline",size:"sm",onClick:()=>e(!1),disabled:P,children:"Cancel"}),s.jsxs(ot,{size:"sm",onClick:V,disabled:!fe||P,className:"gap-1.5",children:[P&&s.jsx(os,{className:"h-3.5 w-3.5 animate-spin"}),P?"Creating...":"Create Worktree"]})]})]})]})}),s.jsx(oG,{open:M,onOpenChange:F,onSelect:Y})]})}const uG=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,O9=({projectRef:t,canCreateWorktree:e=!1,onActionComplete:n,className:r})=>{const[o,a]=f.useState(!1),[i,l]=f.useState(""),[c,d]=f.useState([]),[u,m]=f.useState(""),[h,p]=f.useState(null),g=Le(I=>I.currentSessionId),y=Le(I=>I.openNewSessionDraft),b=Le(I=>I.setPendingInputText),x=De(I=>I.setActiveMainTab),v=De(I=>I.setSessionSwitcherOpen),w=f.useCallback(async(I,T)=>{if(!t)return!1;const H=await yS(t,{notes:I,todos:T});return H||ue.error("Failed to save project notes"),H},[t]);f.useEffect(()=>{if(!t){l(""),d([]),m("");return}let I=!1;return a(!0),(async()=>{try{const T=await gS(t);if(I)return;l(T.notes),d(T.todos),m("")}catch{I||(ue.error("Failed to load project notes"),l(""),d([]))}finally{I||a(!1)}})(),()=>{I=!0}},[t]);const C=f.useCallback(()=>{w(i,c)},[i,w,c]),k=f.useCallback(()=>{const I=u.trim();if(!I)return;const T=[...c,{id:uG(),text:I.slice(0,e0),completed:!1,createdAt:Date.now()}];d(T),m(""),w(i,T)},[u,i,w,c]),N=f.useCallback((I,T)=>{const H=c.map(P=>P.id===I?{...P,completed:T}:P);d(H),w(i,H)},[i,w,c]),S=f.useCallback(I=>{const T=c.filter(H=>H.id!==I);d(T),w(i,T)},[i,w,c]),j=f.useCallback(()=>{const I=c.filter(T=>!T.completed);I.length!==c.length&&(d(I),w(i,I))},[i,w,c]),A=u.slice(0,e0),M=c.reduce((I,T)=>I+(T.completed?1:0),0),F=f.useCallback(()=>{x("chat"),v(!1)},[x,v]),B=f.useCallback(I=>{t&&(F(),y({directoryOverride:t.path,initialPrompt:I}),ue.success("Todo sent to new session"),n?.())},[n,y,t,F]),D=f.useCallback(I=>{if(!g){ue.error("No active session selected");return}F(),b(I,"append"),ue.success("Todo sent to current session"),n?.()},[g,n,F,b]),E=f.useCallback(async(I,T)=>{if(t){if(!e){ue.error("Worktree actions are only available for Git repositories");return}p(I);try{const H=await VE();if(!H)return;F(),y({directoryOverride:H,initialPrompt:T}),ue.success("Todo sent to new worktree session"),n?.()}finally{p(null)}}},[e,n,y,t,F]);return t?s.jsxs("div",{className:J("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,"/",ju]})]}),s.jsx(dr,{value:i,onChange:I=>l(I.target.value.slice(0,ju)),onBlur:C,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:j,disabled:o||M===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(ts,{value:A,onChange:I=>m(I.target.value.slice(0,e0)),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),k())},placeholder:"Add a todo",disabled:o,className:"h-8"}),s.jsx("button",{type:"button",onClick:k,disabled:o||A.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(Xs,{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(I=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsx(mn,{checked:I.completed,onChange:T=>N(I.id,T),ariaLabel:`Mark "${I.text}" complete`}),s.jsx("span",{className:J("min-w-0 flex-1 typography-ui-label text-foreground",I.completed&&"text-muted-foreground line-through"),title:I.text,children:I.text}),s.jsx("button",{type:"button",onClick:()=>S(I.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 "${I.text}"`,children:s.jsx(Ln,{className:"h-3.5 w-3.5"})}),s.jsxs(zs,{children:[s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",disabled:h===I.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 "${I.text}"`,children:s.jsx(Jx,{className:"h-3.5 w-3.5"})})}),s.jsxs(Os,{align:"end",className:"w-56",children:[s.jsx(Qt,{onClick:()=>D(I.text),children:"Send to current session"}),s.jsx(Qt,{onClick:()=>B(I.text),children:"Send to new session"}),s.jsx(Qt,{onClick:()=>{E(I.id,I.text)},disabled:!e,children:"Send to new worktree session"})]})]})]},I.id))})})]})]}):s.jsx("div",{className:J("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."})})},fG=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(",","")},Kd=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 fG(t)},rn=t=>{if(!t)return null;const e=t.replace(/\\/g,"/").replace(/\/+$/,"");return e.length===0?"/":e},Y0=t=>t.toLowerCase().replace(/^opencode[/-]?/i,"").replace(/[-_]/g,"").trim(),mG=(t,e)=>t?Y0(t)!==Y0(e):!1,l4=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}},k6=t=>l4(t.time?.created)??0,N6=t=>l4(t.time?.updated)??l4(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?k6(e)-k6(t):N6(e)-N6(t)},yl=t=>{const e=new Map;return t.forEach(n=>{e.set(n.id,n)}),Array.from(e.values())},b3=t=>`__archived__:${t}`,hG=(t,e)=>{const n=rn(t.directory??null),r=rn(t.project?.worktree??null),o=n??r;if(!o)return"unassigned";if(e&&o===e)return"project root";const i=(e&&o.startsWith(`${e}/`)?o.slice(e.length+1):o).split("/").filter(Boolean);return i[i.length-1]??"unassigned"},Ec=(t,e,n)=>{const r=rn(t.directory??null),o=rn(t.project?.worktree??null);return o&&(o===e||o.startsWith(`${e}/`))?!0:r?n&&n.has(r)?!0:r===e||r.startsWith(`${e}/`):!1},R1=t=>{if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){const e=Number(t);if(Number.isFinite(e))return e}return null},pG=t=>{if(!t)return null;const e=R1(t.additions),n=R1(t.deletions);if(e!==null||n!==null){const i={additions:Math.max(0,e??0),deletions:Math.max(0,n??0)};return i.additions===0&&i.deletions===0?null:i}const r=Array.isArray(t.diffs)?t.diffs:[];if(r.length===0)return null;let o=0,a=0;return r.forEach(i=>{o+=Math.max(0,R1(i.additions)??0),a+=Math.max(0,R1(i.deletions)??0)}),o===0&&a===0?null:{additions:o,deletions:a}},J0=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),c4=(t,e)=>{if(!e)return t;const n=t.toLowerCase(),r=e.toLowerCase(),o=r.length;if(o===0)return t;const a=[];let i=0,l=n.indexOf(r,i);for(;l!==-1;){l>i&&a.push(t.slice(i,l));const c=t.slice(l,l+o);a.push(s.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:c},`${l}-${c}`)),i=l+o,l=n.indexOf(r,i)}return i<t.length&&a.push(t.slice(i)),a.length>0?a:t},gG=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>rn(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(c=>Ec(c,t.normalizedPath,r)))(e.archivedSessions),i=e.sessions.filter(l=>l.time?.archived||rn(l.directory??null)?!1:Ec(l,t.normalizedPath,r));return yl([...a,...i])},yG=t=>{const e=Ce.c(12),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:i,isSessionsLoading:l,foldersMap:c,createFolder:d,addSessionToFolder:u,cleanupSessions:m}=t;let h,p;e[0]!==u||e[1]!==o||e[2]!==a||e[3]!==m||e[4]!==d||e[5]!==c||e[6]!==l||e[7]!==i||e[8]!==n||e[9]!==r?(h=()=>{l||n.forEach(g=>{const y=b3(g.normalizedPath),b=gG(g,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:i}),x=new Set(b.map(bG)),v=c[y]??[],w=new Map(v.map(xG));b.forEach(C=>{const k=hG(C,g.normalizedPath),N=k.toLowerCase();let S=w.get(N);S||(S=d(y,k),w.set(N,S)),S.sessionIds.includes(C.id)||u(y,S.id,C.id)}),m(y,x)})},p=[n,r,o,a,i,l,c,d,u,m],e[0]=u,e[1]=o,e[2]=a,e[3]=m,e[4]=d,e[5]=c,e[6]=l,e[7]=i,e[8]=n,e[9]=r,e[10]=h,e[11]=p):(h=e[10],p=e[11]),f.useEffect(h,p)};function bG(t){return t.id}function xG(t){return[t.name.toLowerCase(),t]}const vG=t=>{const e=Ce.c(49),{normalizedProjects:n,activeProjectId:r,getSessionsForProject:o,getArchivedSessionsForProject:a,availableWorktreesByProject:i,projectRepoStatus:l,projectRootBranches:c,lastRepoStatus:d,buildGroupedSessions:u,hasSessionSearchQuery:m,normalizedSessionSearchQuery:h,filterSessionNodesForSearch:p,buildGroupSearchText:g,getFoldersForScope:y}=t;let b;if(e[0]!==i||e[1]!==u||e[2]!==a||e[3]!==o||e[4]!==d||e[5]!==n||e[6]!==l||e[7]!==c){let B;e[9]!==i||e[10]!==u||e[11]!==a||e[12]!==o||e[13]!==d||e[14]!==l||e[15]!==c?(B=D=>{const E=yl([...o(D),...a(D)]),I=i.get(D.normalizedPath)??[],T=l.has(D.id)?!!l.get(D.id):d,H=u(E,D.normalizedPath,I,c.get(D.id)??null,T);return{project:D,groups:H}},e[9]=i,e[10]=u,e[11]=a,e[12]=o,e[13]=d,e[14]=l,e[15]=c,e[16]=B):B=e[16],b=n.map(B),e[0]=i,e[1]=u,e[2]=a,e[3]=o,e[4]=d,e[5]=n,e[6]=l,e[7]=c,e[8]=b}else b=e[8];const x=b;let v;e:{if(x.length===0){v=x;break e}let B;if(e[17]!==r||e[18]!==x){let I;e[20]!==r?(I=T=>T.project.id===r,e[20]=r,e[21]=I):I=e[21],B=x.find(I),e[17]=r,e[18]=x,e[19]=B}else B=e[19];const D=B;let E;e[22]!==D||e[23]!==x[0]?(E=D?[D]:[x[0]],e[22]=D,e[23]=x[0],e[24]=E):E=e[24],v=E}const w=v;let C;if(e[25]!==g||e[26]!==p||e[27]!==y||e[28]!==m||e[29]!==h||e[30]!==w){e:{const B=new WeakMap;if(!m){C=B;break e}const D=E=>E.reduce((I,T)=>I+1+D(T.children),0);w.forEach(E=>{E.groups.forEach(I=>{const T=p(I.sessions,h),H=D(T),P=g(I).includes(h),_=rn(I.directory??null),R=_?y(_).filter(z=>z.name.toLowerCase().includes(h)).length:0;B.set(I,{filteredNodes:T,matchedSessionCount:H,folderNameMatchCount:R,groupMatches:P,hasMatch:P||H>0||R>0})})}),C=B}e[25]=g,e[26]=p,e[27]=y,e[28]=m,e[29]=h,e[30]=w,e[31]=C}else C=e[31];const k=C;let N;e:{if(!m){N=w;break e}let B;if(e[32]!==k||e[33]!==w){let D;e[35]!==k?(D=E=>({...E,groups:E.groups.filter(I=>k.get(I)?.hasMatch===!0)}),e[35]=k,e[36]=D):D=e[36],B=w.map(D).filter(wG),e[32]=k,e[33]=w,e[34]=B}else B=e[34];N=B}const S=N,j=m?S:w;let A;e:{if(!m){A=0;break e}let B;if(e[37]!==k||e[38]!==j){let D;e[40]!==k?(D=(E,I)=>E+I.groups.reduce((T,H)=>{const P=k.get(H);if(!P)return T;const _=P.folderNameMatchCount+(P.groupMatches?1:0);return T+P.matchedSessionCount+_},0),e[40]=k,e[41]=D):D=e[41],B=j.reduce(D,0),e[37]=k,e[38]=j,e[39]=B}else B=e[39];A=B}const M=A;let F;return e[42]!==k||e[43]!==x||e[44]!==M||e[45]!==S||e[46]!==j||e[47]!==w?(F={projectSections:x,visibleProjectSections:w,groupSearchDataByGroup:k,searchableProjectSections:S,sectionsForRender:j,searchMatchCount:M},e[42]=k,e[43]=x,e[44]=M,e[45]=S,e[46]=j,e[47]=w,e[48]=F):F=e[48],F};function wG(t){return t.groups.length>0}const jG=t=>{const e=Ce.c(35),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:i,handleSessionSelect:l,isVSCode:c,newSessionDraftOpen:d,mobileVariant:u,openNewSessionDraft:m,setActiveMainTab:h,setSessionSwitcherOpen:p,sessions:g,worktreeMetadata:y}=t;let b,x;if(e[0]!==n){x=new Map,b=new Map;const D=(E,I,T,H)=>{x.has(E)||x.set(E,new Map);const P=x.get(E);H.forEach(_=>{const R=rn(_.worktree?.path??_.session.directory??T??I);P.set(_.session.id,{directory:R}),b.has(E)||b.set(E,{id:_.session.id,directory:R}),_.children.length>0&&D(E,I,R,_.children)})};n.forEach(E=>{E.groups.forEach(I=>{D(E.project.id,E.project.normalizedPath,I.directory,I.sessions)})}),e[0]=n,e[1]=b,e[2]=x}else b=e[1],x=e[2];let v;e[3]!==b||e[4]!==x?(v={metaByProject:x,firstSessionByProject:b},e[3]=b,e[4]=x,e[5]=v):v=e[5];const w=v,C=f.useRef(null),k=f.useRef(null);let N,S;e[6]!==r||e[7]!==o||e[8]!==i||e[9]!==l||e[10]!==c||e[11]!==u||e[12]!==d||e[13]!==m||e[14]!==n||e[15]!==w||e[16]!==h||e[17]!==a||e[18]!==p?(N=()=>{if(!r)return;const D=k.current,E=!!(D&&D!==r);if(k.current=r,d&&(c||!E)||C.current===r)return;const I=n.find(O=>O.project.id===r);if(!I)return;C.current=r;const T=w.metaByProject.get(r);if(i&&T&&T.has(i)){a(O=>{if(O.get(r)===i)return O;const Q=new Map(O);return Q.set(r,i),Q});return}if(!T||T.size===0){h("chat"),u&&p(!1),m({directoryOverride:I.project.normalizedPath});return}const H=o.get(r),P=H&&T.has(H)?H:null,_=w.firstSessionByProject.get(r)?.id??null,R=P??_;if(!R||R===i)return;const z=T.get(R)?.directory??null;l(R,z,!1,r)},S=[r,o,i,l,c,d,u,m,n,w,h,p,a],e[6]=r,e[7]=o,e[8]=i,e[9]=l,e[10]=c,e[11]=u,e[12]=d,e[13]=m,e[14]=n,e[15]=w,e[16]=h,e[17]=a,e[18]=p,e[19]=N,e[20]=S):(N=e[19],S=e[20]),f.useLayoutEffect(N,S);let j,A;e[21]!==r||e[22]!==i||e[23]!==w||e[24]!==a?(j=()=>{if(!r||!i)return;const D=w.metaByProject.get(r);!D||!D.has(i)||a(E=>{if(E.get(r)===i)return E;const I=new Map(E);return I.set(r,i),I})},A=[r,i,w,a],e[21]=r,e[22]=i,e[23]=w,e[24]=a,e[25]=j,e[26]=A):(j=e[25],A=e[26]),f.useEffect(j,A);let M;if(e[27]!==i||e[28]!==g||e[29]!==y){e:{if(!i){M=null;break e}const D=y.get(i)?.path;if(D){M=rn(D)??D;break e}let E;e[31]!==i?(E=T=>T.id===i,e[31]=i,e[32]=E):E=e[32];const I=g.find(E);if(!I){M=null;break e}M=rn(I.directory??null)}e[27]=i,e[28]=g,e[29]=y,e[30]=M}else M=e[30];const F=M;let B;return e[33]!==F?(B={currentSessionDirectory:F},e[33]=F,e[34]=B):B=e[34],B},SG=t=>{const e=Ce.c(4);let n;e[0]!==t?(n=(a,i)=>{const l=i.find(kG)??null,c=l?i.filter(h=>h!==l):i,d=t.get(a);if(!d||d.length===0)return l?[...c,l]:c;const u=new Map(c.map(NG)),m=[];return d.forEach(h=>{const p=u.get(h);p&&(m.push(p),u.delete(h))}),c.forEach(h=>{u.has(h.id)&&m.push(h)}),l?[...m,l]:m},e[0]=t,e[1]=n):n=e[1];const r=n;let o;return e[2]!==r?(o={getOrderedGroups:r},e[2]=r,e[3]=o):o=e[3],o};function kG(t){return t.isArchivedBucket===!0}function NG(t){return[t.id,t]}const CG=t=>{const e=f.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=f.useCallback(a=>{const i=rn(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${i}`.toLowerCase()},[]),r=f.useCallback((a,i)=>i?a.flatMap(l=>{if(n(l.session).includes(i))return[l];const d=r(l.children,i);return d.length===0?[]:[{...l,children:d}]}):a,[n]),o=f.useCallback((a,i,l,c,d)=>{const u=rn(i??null),m=yl(a).sort((A,M)=>Bc(A,M,t.pinnedSessionIds)),h=new Map(m.map(A=>[A.id,A])),p=new Map;m.forEach(A=>{const M=A.parentID;if(!M)return;const F=p.get(M)??[];F.push(A),p.set(M,F)}),p.forEach(A=>A.sort((M,F)=>Bc(M,F,t.pinnedSessionIds)));const g=new Map;l.forEach(A=>{if(A.path){const M=rn(A.path)??A.path;g.set(M,A)}});const y=A=>{const M=rn(A.directory??null),F=t.worktreeMetadata.get(A.id)??null;if(F)return F;if(M){const B=g.get(M)??null;if(B&&M!==u)return B}return null},b=A=>{const M=p.get(A.id)??[];return{session:A,children:M.map(F=>b(F)),worktree:y(A)}},x=m.filter(A=>{const M=A.parentID;return M?!h.has(M):!0}),v=new Map,w="__archived__",C=A=>{if(A.time?.archived)return w;const M=rn(t.worktreeMetadata.get(A.id)?.path??null),F=rn(A.directory??null);if(!M&&!F)return w;const B=rn(A.project?.worktree??null),D=M??F??B;return D?D!==u&&g.has(D)?D:D===u?u??"__project_root__":w:w};x.forEach(A=>{const M=b(A),F=C(A);v.has(F)||v.set(F,[]),v.get(F)?.push(M)});const k=u??"__project_root__",N=[{id:"root",label:d&&c&&c!=="HEAD"?`project root: ${c}`:"project root",branch:c??null,description:u?na(u,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:u,folderScopeKey:u,sessions:v.get(k)??[]}],S=new Map;return l.forEach(A=>{const M=rn(A.path)??A.path,F=v.get(M)??[],B=F.length>0,D=F.reduce((E,I)=>{const T=Number(I.session.time?.updated??I.session.time?.created??0);return Number.isFinite(T)?Math.max(E,T):E},0);S.set(M,{hasActiveSession:B,lastUpdatedAt:D})}),[...l].sort((A,M)=>{const F=rn(A.path)??A.path,B=rn(M.path)??M.path,D=S.get(F)??{hasActiveSession:!1,lastUpdatedAt:0},E=S.get(B)??{hasActiveSession:!1,lastUpdatedAt:0};if(D.hasActiveSession!==E.hasActiveSession)return D.hasActiveSession?-1:1;if(D.hasActiveSession&&E.hasActiveSession)return E.lastUpdatedAt-D.lastUpdatedAt;const I=(A.label||A.branch||A.name||A.path||"").toLowerCase(),T=(M.label||M.branch||M.name||M.path||"").toLowerCase();return I.localeCompare(T)}).forEach(A=>{const M=rn(A.path)??A.path,F=t.gitDirectories.get(M)?.status?.current?.trim()||null,B=A.branch?.trim()||null,E=!!(F&&B&&A.label&&Y0(A.label)===Y0(B))?F:A.label||A.name||fo(M,t.homeDirectory)||M;N.push({id:`worktree:${M}`,label:E,branch:F||B,description:na(M,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:A,directory:M,folderScopeKey:M,sessions:v.get(M)??[]})}),N.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:!t.isVSCode&&u?b3(u):null,sessions:v.get(w)??[]}),N},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitDirectories,t.isVSCode]);return{buildGroupSearchText:e,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},MG=t=>{const e=Ce.c(9),{isSessionSearchOpen:n,setIsSessionSearchOpen:r,sessionSearchInputRef:o,sessionSearchContainerRef:a}=t;let i,l;e[0]!==n||e[1]!==o?(i=()=>{if(!n||typeof window>"u")return;const u=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(u)},l=[n,o],e[0]=n,e[1]=o,e[2]=i,e[3]=l):(i=e[2],l=e[3]),f.useEffect(i,l);let c,d;e[4]!==n||e[5]!==a||e[6]!==r?(c=()=>{if(!n||typeof document>"u")return;const u=m=>{a.current&&(a.current.contains(m.target)||r(!1))};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},d=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=c,e[8]=d):(c=e[7],d=e[8]),f.useEffect(c,d)},AG=180,FG=1,DG=6,_G=({currentSessionId:t,sortedSessions:e,loadMessages:n})=>{const r=f.useRef(new Map),o=f.useRef([]),a=f.useRef(new Set),i=f.useCallback(()=>{if(!(typeof window>"u"))for(;a.current.size<FG&&o.current.length>0;){const c=o.current.shift();if(!c)break;const d=Le.getState();if(d.currentSessionId===c)continue;const u=d.messages.has(c),m=d.sessionHistoryMeta.get(c);u&&typeof m?.complete=="boolean"||(a.current.add(c),n(c).catch(()=>{}).finally(()=>{a.current.delete(c),i()}))}},[n]),l=f.useCallback(c=>{if(!c||c===t||typeof window>"u")return;const d=Le.getState(),u=d.messages.has(c),m=d.sessionHistoryMeta.get(c);if(u&&typeof m?.complete=="boolean"||a.current.has(c)||o.current.includes(c))return;o.current.length>=DG&&o.current.shift();const p=r.current.get(c);p!==void 0&&window.clearTimeout(p);const g=window.setTimeout(()=>{r.current.delete(c),o.current.push(c),i()},AG);r.current.set(c,g)},[t,i]);f.useEffect(()=>{if(!t||e.length===0)return;const c=e.findIndex(d=>d.id===t);c<0||(l(e[c-1]?.id),l(e[c+1]?.id))},[t,l,e]),f.useEffect(()=>{const c=r.current;return()=>{c.forEach(d=>{clearTimeout(d)}),c.clear(),o.current=[]}},[])},BG=t=>{const e=Ce.c(10),{sortedSessions:n,projects:r,directoryStatus:o,setDirectoryStatus:a}=t;let i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i=new Map,e[0]=i):i=e[0];const l=f.useRef(i);let c;e[1]===Symbol.for("react.memo_cache_sentinel")?(c=new Set,e[1]=c):c=e[1];const d=f.useRef(c);let u,m;e[2]!==o?(u=()=>{l.current=o},m=[o],e[2]=o,e[3]=u,e[4]=m):(u=e[3],m=e[4]),f.useEffect(u,m);let h,p;e[5]!==r||e[6]!==a||e[7]!==n?(h=()=>{const g=new Set;n.forEach(y=>{const b=rn(y.directory??null);b&&g.add(b)}),r.forEach(y=>{const b=rn(y.path);b&&g.add(b)}),g.forEach(y=>{const b=l.current.get(y);b&&b!=="unknown"||d.current.has(y)||(d.current.add(y),zt.listLocalDirectory(y).then(()=>{a(x=>{const v=new Map(x);return v.get(y)==="exists"?x:(v.set(y,"exists"),v)})}).catch(async()=>{if((y.includes("/opencode/worktree/")||y.includes("/.opencode/data/worktree/")||y.includes("/.local/share/opencode/worktree/"))&&await zt.probeDirectory(y).catch(EG)){a(w=>{const C=new Map(w);return C.get(y)==="exists"?w:(C.set(y,"exists"),C)});return}a(v=>{const w=new Map(v);return w.get(y)==="missing"?v:(w.set(y,"missing"),w)})}).finally(()=>{d.current.delete(y)}))})},p=[n,r,a],e[5]=r,e[6]=a,e[7]=n,e[8]=h,e[9]=p):(h=e[8],p=e[9]),f.useEffect(h,p)};function EG(){return!1}const IG=t=>{const e=Ce.c(37),[n,r]=f.useState(null),o=f.useRef(null);let a,i;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>()=>{o.current&&clearTimeout(o.current)},i=[],e[0]=a,e[1]=i):(a=e[0],i=e[1]),f.useEffect(a,i);let l;e[2]!==t?(l=(E,I,T,H)=>{if(T)return;const P=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(H&&H!==t.activeProjectId&&t.setActiveProjectIdOnly(H),I&&I!==t.currentDirectory&&t.setDirectory(I,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),E===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(E),P();return}t.setCurrentSession(E),t.onSessionSelected?.(E),P()},e[2]=t,e[3]=l):l=e[3];const c=l;let d;e[4]!==t?(d=()=>{t.setActiveMainTab("chat")},e[4]=t,e[5]=d):d=e[5];const u=d;let m;e[6]!==t?(m=async()=>{t.editingId&&t.editTitle.trim()&&(await t.updateSessionTitle(t.editingId,t.editTitle.trim()),t.setEditingId(null),t.setEditTitle(""))},e[6]=t,e[7]=m):m=e[7];const h=m;let p;e[8]!==t?(p=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=p):p=e[9];const g=p;let y;e[10]!==t?(y=async E=>{const I=await t.shareSession(E.id);I&&I.share?.url?ue.success("Session shared",{description:"You can copy the link from the menu."}):ue.error("Unable to share session")},e[10]=t,e[11]=y):y=e[11];const b=y;let x;e[12]===Symbol.for("react.memo_cache_sentinel")?(x=(E,I)=>{Cn(E).then(T=>{if(!T.ok){ue.error("Failed to copy URL");return}r(I),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{r(null),o.current=null},2e3)}).catch(TG)},e[12]=x):x=e[12];const v=x;let w;e[13]!==t?(w=async E=>{await t.unshareSession(E)?ue.success("Session unshared"):ue.error("Unable to unshare session")},e[13]=t,e[14]=w):w=e[14];const C=w;let k;e[15]!==t.childrenMap?(k=E=>{const I=[],T=H=>{(t.childrenMap.get(H)??[]).forEach(_=>{I.push(_),T(_.id)})};return T(E),I},e[15]=t.childrenMap,e[16]=k):k=e[16];const N=k;let S;e[17]!==t||e[18]!==N?(S=async(E,I)=>{const T=N(E.id),H=I?.archivedBucket===!0;if(T.length===0){(H?await t.deleteSession(E.id):await t.archiveSession(E.id))?ue.success(H?"Session deleted":"Session archived"):ue.error(H?"Failed to delete session":"Failed to archive session");return}const P=[E.id,...T.map(PG)];if(H){const{deletedIds:z,failedIds:O}=await t.deleteSessions(P);z.length>0&&ue.success(`Deleted ${z.length} session${z.length===1?"":"s"}`),O.length>0&&ue.error(`Failed to delete ${O.length} session${O.length===1?"":"s"}`);return}const{archivedIds:_,failedIds:R}=await t.archiveSessions(P);_.length>0&&ue.success(`Archived ${_.length} session${_.length===1?"":"s"}`),R.length>0&&ue.error(`Failed to archive ${R.length} session${R.length===1?"":"s"}`)},e[17]=t,e[18]=N,e[19]=S):S=e[19];const j=S;let A;e[20]!==t||e[21]!==N||e[22]!==j?(A=(E,I)=>{const T=N(E.id);if(!t.showDeletionDialog){j(E,I);return}t.setDeleteSessionConfirm({session:E,descendantCount:T.length,archivedBucket:I?.archivedBucket===!0})},e[20]=t,e[21]=N,e[22]=j,e[23]=A):A=e[23];const M=A;let F;e[24]!==t||e[25]!==j?(F=async()=>{if(!t.deleteSessionConfirm)return;const{session:E,archivedBucket:I}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await j(E,{archivedBucket:I})},e[24]=t,e[25]=j,e[26]=F):F=e[26];const B=F;let D;return e[27]!==B||e[28]!==n||e[29]!==g||e[30]!==M||e[31]!==h||e[32]!==u||e[33]!==c||e[34]!==b||e[35]!==C?(D={copiedSessionId:n,handleSessionSelect:c,handleSessionDoubleClick:u,handleSaveEdit:h,handleCancelEdit:g,handleShareSession:b,handleCopyShareUrl:v,handleUnshareSession:C,handleDeleteSession:M,confirmDeleteSession:B},e[27]=B,e[28]=n,e[29]=g,e[30]=M,e[31]=h,e[32]=u,e[33]=c,e[34]=b,e[35]=C,e[36]=D):D=e[36],D};function TG(){ue.error("Failed to copy URL")}function PG(t){return t.id}const RG=t=>{const e=Ce.c(40),{isVSCode:n,safeStorage:r,keys:o,sessions:a,pinnedSessionIds:i,setPinnedSessionIds:l,groupOrderByProject:c,activeSessionByProject:d,collapsedGroups:u,setExpandedParents:m,setCollapsedProjects:h}=t,p=f.useRef(null),g=f.useRef(null);let y;e[0]!==n?(y=()=>{if(n)return;const P=g.current;if(g.current=null,p.current=null,!P)return;const{projects:_}=ls.getState(),R=_.map(z=>({...z,sidebarCollapsed:P.has(z.id)}));Rs({projects:R}).catch(LG)},e[0]=n,e[1]=y):y=e[1];const b=y;let x;e[2]!==b||e[3]!==n?(x=P=>{typeof window>"u"||n||(g.current=P,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{b()},700))},e[2]=b,e[3]=n,e[4]=x):x=e[4];const v=x;let w,C;e[5]===Symbol.for("react.memo_cache_sentinel")?(w=()=>()=>{typeof window<"u"&&p.current!==null&&window.clearTimeout(p.current),p.current=null,g.current=null},C=[],e[5]=w,e[6]=C):(w=e[5],C=e[6]),f.useEffect(w,C);let k,N;e[7]!==o.projectCollapse||e[8]!==o.sessionExpanded||e[9]!==r||e[10]!==h||e[11]!==m?(k=()=>{try{const P=r.getItem(o.sessionExpanded);if(P){const R=JSON.parse(P);Array.isArray(R)&&m(new Set(R.filter(zG)))}const _=r.getItem(o.projectCollapse);if(_){const R=JSON.parse(_);Array.isArray(R)&&h(new Set(R.filter(HG)))}}catch{}},N=[o.projectCollapse,o.sessionExpanded,r,h,m],e[7]=o.projectCollapse,e[8]=o.sessionExpanded,e[9]=r,e[10]=h,e[11]=m,e[12]=k,e[13]=N):(k=e[12],N=e[13]),f.useEffect(k,N);let S,j;e[14]!==a||e[15]!==l?(S=()=>{const P=new Set(a.map(OG));l(_=>{let R=!1;const z=new Set;return _.forEach(O=>{P.has(O)?z.add(O):R=!0}),R?z:_})},j=[a,l],e[14]=a,e[15]=l,e[16]=S,e[17]=j):(S=e[16],j=e[17]),f.useEffect(S,j);let A,M;e[18]!==o.sessionPinned||e[19]!==i||e[20]!==r?(A=()=>{try{r.setItem(o.sessionPinned,JSON.stringify(Array.from(i)))}catch{}},M=[o.sessionPinned,i,r],e[18]=o.sessionPinned,e[19]=i,e[20]=r,e[21]=A,e[22]=M):(A=e[21],M=e[22]),f.useEffect(A,M);let F,B;e[23]!==c||e[24]!==o.groupOrder||e[25]!==r?(F=()=>{try{const P=Object.fromEntries(c.entries());r.setItem(o.groupOrder,JSON.stringify(P))}catch{}},B=[c,o.groupOrder,r],e[23]=c,e[24]=o.groupOrder,e[25]=r,e[26]=F,e[27]=B):(F=e[26],B=e[27]),f.useEffect(F,B);let D,E;e[28]!==d||e[29]!==o.projectActiveSession||e[30]!==r?(D=()=>{try{const P=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(P))}catch{}},E=[d,o.projectActiveSession,r],e[28]=d,e[29]=o.projectActiveSession,e[30]=r,e[31]=D,e[32]=E):(D=e[31],E=e[32]),f.useEffect(D,E);let I,T;e[33]!==u||e[34]!==o.groupCollapse||e[35]!==r?(I=()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(u)))}catch{}},T=[u,o.groupCollapse,r],e[33]=u,e[34]=o.groupCollapse,e[35]=r,e[36]=I,e[37]=T):(I=e[36],T=e[37]),f.useEffect(I,T);let H;return e[38]!==v?(H={scheduleCollapsedProjectsPersist:v},e[38]=v,e[39]=H):H=e[39],H};function LG(){}function zG(t){return typeof t=="string"}function HG(t){return typeof t=="string"}function OG(t){return t.id}const $G=t=>{const e=Ce.c(17),{projects:n,normalizedProjects:r,normalizePath:o,gitDirectories:a,setProjectRepoStatus:i,setProjectRootBranches:l}=t;let c,d;e[0]!==o||e[1]!==n||e[2]!==i?(c=()=>{let g=!1;const y=n.map(b=>({id:b.id,path:o(b.path)})).filter(VG);return i(new Map),y.length===0?()=>{g=!0}:(y.forEach(b=>{la(b.path).then(x=>{g||i(v=>{const w=new Map(v);return w.set(b.id,x),w})}).catch(()=>{g||i(x=>{const v=new Map(x);return v.set(b.id,null),v})})}),()=>{g=!0})},d=[o,n,i],e[0]=o,e[1]=n,e[2]=i,e[3]=c,e[4]=d):(c=e[3],d=e[4]),f.useEffect(c,d);let u;if(e[5]!==a||e[6]!==r){let g;e[8]!==a?(g=y=>{const b=a.get(y.normalizedPath);return`${y.id}:${b?.status?.current??""}`},e[8]=a,e[9]=g):g=e[9],u=r.map(g).join("|"),e[5]=a,e[6]=r,e[7]=u}else u=e[7];const m=u;let h;e[10]!==r||e[11]!==l?(h=()=>{let g=!1;return(async()=>{const b=await Promise.all(r.map(WG));g||l(x=>{const v=new Map(x);return b.forEach(w=>{const{id:C,branch:k}=w;k&&v.set(C,k)}),v})})(),()=>{g=!0}},e[10]=r,e[11]=l,e[12]=h):h=e[12];let p;e[13]!==r||e[14]!==m||e[15]!==l?(p=[r,m,l],e[13]=r,e[14]=m,e[15]=l,e[16]=p):p=e[16],f.useEffect(h,p)};function VG(t){return!!t.path}function UG(){return null}async function WG(t){const e=await Ta(t.normalizedPath).catch(UG);return{id:t.id,branch:e}}const qG=t=>{const e=Ce.c(13),{isVSCode:n,sessions:r,archivedSessions:o,sessionsByDirectory:a,getSessionsByDirectory:i,availableWorktreesByProject:l}=t;let c;e[0]!==l||e[1]!==i||e[2]!==n||e[3]!==a?(c=p=>{const g=n?[]:l.get(p.normalizedPath)??[],y=[p.normalizedPath,...g.map(GG).filter(ZG)],b=new Set,x=[];return y.forEach(v=>{(a.get(v)??i(v)).forEach(C=>{b.has(C.id)||(b.add(C.id),x.push(C))})}),x},e[0]=l,e[1]=i,e[2]=n,e[3]=a,e[4]=c):c=e[4];const d=c;let u;e[5]!==o||e[6]!==l||e[7]!==n||e[8]!==r?(u=p=>{if(n){const w=o.filter(k=>{const N=rn(k.directory??null),S=rn(k.project?.worktree??null);return N?N===p.normalizedPath:S===p.normalizedPath}),C=r.filter(k=>k.time?.archived||rn(k.directory??null)?!1:rn(k.project?.worktree??null)===p.normalizedPath);return yl([...w,...C])}const g=n?[]:l.get(p.normalizedPath)??[],y=new Set([p.normalizedPath,...g.map(KG).filter(QG)]),x=(w=>w.filter(C=>Ec(C,p.normalizedPath,y)))(o),v=r.filter(w=>{if(w.time?.archived||rn(w.directory??null))return!1;const k=rn(w.project?.worktree??null);return k?k===p.normalizedPath||k.startsWith(`${p.normalizedPath}/`):!1});return yl([...x,...v])},e[5]=o,e[6]=l,e[7]=n,e[8]=r,e[9]=u):u=e[9];const m=u;let h;return e[10]!==m||e[11]!==d?(h={getSessionsForProject:d,getArchivedSessionsForProject:m},e[10]=m,e[11]=d,e[12]=h):h=e[12],h};function GG(t){return rn(t.path)??t.path}function ZG(t){return!!t}function KG(t){return rn(t.path)??t.path}function QG(t){return!!t}const YG=t=>{const e=Ce.c(9),{isSessionsLoading:n,sessions:r,archivedSessions:o,normalizedProjects:a,isVSCode:i,availableWorktreesByProject:l,cleanupSessions:c}=t;let d,u;e[0]!==o||e[1]!==l||e[2]!==c||e[3]!==n||e[4]!==i||e[5]!==a||e[6]!==r?(d=()=>{if(n)return;const m=new Map;r.forEach(g=>{const y=rn(g.directory??null);if(!y)return;const b=m.get(y);if(b){b.add(g.id);return}m.set(y,new Set([g.id]))}),a.forEach(g=>{const y=b3(g.normalizedPath),b=i?[]:l.get(g.normalizedPath)??[],x=new Set([g.normalizedPath,...b.map(JG).filter(XG)]),v=yl([...o,...r.filter(w=>w.time?.archived||rn(w.directory??null)?!1:Ec(w,g.normalizedPath,x))]).filter(w=>Ec(w,g.normalizedPath,x));m.set(y,new Set(v.map(eZ)))});const h=Er.getState().foldersMap;new Set([...Object.keys(h),...m.keys()]).forEach(g=>{c(g,m.get(g)??new Set)})},u=[o,l,c,n,i,a,r],e[0]=o,e[1]=l,e[2]=c,e[3]=n,e[4]=i,e[5]=a,e[6]=r,e[7]=d,e[8]=u):(d=e[7],u=e[8]),f.useEffect(d,u)};function JG(t){return rn(t.path)??t.path}function XG(t){return!!t}function eZ(t){return t.id}const tZ=t=>{const e=Ce.c(8),{isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=t;let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=new Set,e[0]=a):a=e[0];const[i,l]=f.useState(a);let c;e[1]!==n||e[2]!==o?(c=()=>{if(!n)return;const u=new IntersectionObserver(m=>{m.forEach(h=>{const p=h.target.dataset.projectId;p&&l(g=>{const y=new Set(g);return h.isIntersecting?y.delete(p):y.add(p),y})})},{threshold:0});return o.current.forEach(m=>{m&&u.observe(m)}),()=>u.disconnect()},e[1]=n,e[2]=o,e[3]=c):c=e[3];let d;return e[4]!==n||e[5]!==o||e[6]!==r?(d=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=d):d=e[7],f.useEffect(c,d),i},sZ=t=>{const e=Ce.c(74),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:i,onRename:l,onDelete:c,renderSessionNode:d,groupDirectory:u,projectId:m,mobileVariant:h,isRenaming:p,renameDraft:g,onRenameDraftChange:y,onRenameSave:b,onRenameCancel:x,droppableRef:v,isDropTarget:w,onNewSession:C,onNewSubFolder:k,depth:N,hideActions:S,archivedBucket:j}=t,A=h===void 0?!1:h,M=p===void 0?!1:p,F=g===void 0?"":g,B=w===void 0?!1:w,D=N===void 0?0:N,E=S===void 0?!1:S,I=j===void 0?!1:j,[T,H]=f.useState(!1),[P,_]=f.useState(""),R=f.useRef(null),z=M||T,O=M?F:P;let Q;e[0]!==n.name?(Q=()=>{_(n.name),H(!0)},e[0]=n.name,e[1]=Q):Q=e[1];const te=Q;let W;e[2]!==O||e[3]!==n.name||e[4]!==M||e[5]!==l||e[6]!==b?(W=()=>{const xe=O.trim();xe&&xe!==n.name&&l(xe),M&&b&&b(),H(!1),_("")},e[2]=O,e[3]=n.name,e[4]=M,e[5]=l,e[6]=b,e[7]=W):W=e[7];const U=W;let K;e[8]!==M||e[9]!==x?(K=()=>{M&&x&&x(),H(!1),_("")},e[8]=M,e[9]=x,e[10]=K):K=e[10];const q=K;let ee;e[11]!==M||e[12]!==y?(ee=xe=>{M&&y?y(xe):_(xe)},e[11]=M,e[12]=y,e[13]=ee):ee=e[13];const V=ee;let G,Y;e[14]!==M?(G=()=>{if(!M)return;const xe=()=>{const le=R.current;le&&(le.focus(),le.select())},_e=requestAnimationFrame(xe),ze=window.setTimeout(xe,0);return()=>{cancelAnimationFrame(_e),window.clearTimeout(ze)}},Y=[M],e[14]=M,e[15]=G,e[16]=Y):(G=e[15],Y=e[16]),f.useEffect(G,Y);const oe=a?Tr:Xx,fe=D>0&&"ml-3";let ie;e[17]!==fe?(ie=J("oc-folder",fe),e[17]=fe,e[18]=ie):ie=e[18];const de=B&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let $;e[19]!==de?($=J("group/folder flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-sm","hover:bg-interactive-hover/50 cursor-pointer",de),e[19]=de,e[20]=$):$=e[20];const L=z?void 0:i,X=z?void 0:"button",ne=z?void 0:0;let se;e[21]!==i||e[22]!==z?(se=z?void 0:xe=>{(xe.key==="Enter"||xe.key===" ")&&(xe.preventDefault(),i())},e[21]=i,e[22]=z,e[23]=se):se=e[23];const pe=a?`Expand folder ${n.name}`:`Collapse folder ${n.name}`,ae=B?"text-primary":"text-muted-foreground";let ve;e[24]!==ae?(ve=J("h-3.5 w-3.5 flex-shrink-0",ae),e[24]=ae,e[25]=ve):ve=e[25];let ce;e[26]!==oe||e[27]!==ve?(ce=s.jsx(oe,{className:ve}),e[26]=oe,e[27]=ve,e[28]=ce):ce=e[28];let Z;e[29]!==O||e[30]!==n.name||e[31]!==q||e[32]!==V||e[33]!==U||e[34]!==a||e[35]!==B||e[36]!==z||e[37]!==r?(Z=z?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1","data-keyboard-avoid":"true",onSubmit:xe=>{xe.preventDefault(),U()},children:[s.jsx("input",{ref:R,value:O,onChange:xe=>V(xe.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:rZ,onKeyDown:xe=>{if(xe.key==="Escape"){xe.stopPropagation(),q();return}(xe.key===" "||xe.key==="Enter")&&xe.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:oZ,children:s.jsx(vs,{className:"size-4"})}),s.jsx("button",{type:"button",onClick:xe=>{xe.stopPropagation(),q()},className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(_s,{className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:J("typography-ui-label font-semibold truncate",B?"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(Un,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(Ls,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[29]=O,e[30]=n.name,e[31]=q,e[32]=V,e[33]=U,e[34]=a,e[35]=B,e[36]=z,e[37]=r,e[38]=Z):Z=e[38];let me;e[39]!==ce||e[40]!==Z?(me=s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 pl-1.5 flex-1",children:[ce,Z]}),e[39]=ce,e[40]=Z,e[41]=me):me=e[41];let be;e[42]!==D||e[43]!==n.name||e[44]!==te||e[45]!==E||e[46]!==A||e[47]!==c||e[48]!==C||e[49]!==k||e[50]!==z?(be=!z&&!E?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:J("flex items-center gap-0.5 transition-opacity",A?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100"),children:[C?s.jsx("button",{type:"button",onClick:xe=>{xe.stopPropagation(),C()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${n.name}`,title:"New session",children:s.jsx(Xs,{className:"h-3.5 w-3.5"})}):null,k&&D===0?s.jsx("button",{type:"button",onClick:xe=>{xe.stopPropagation(),k()},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(bl,{className:"h-3.5 w-3.5"})}):null,s.jsx("button",{type:"button",onClick:xe=>{xe.stopPropagation(),te()},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(ao,{className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:xe=>{xe.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(Ln,{className:"h-3.5 w-3.5"})})]})}):null,e[42]=D,e[43]=n.name,e[44]=te,e[45]=E,e[46]=A,e[47]=c,e[48]=C,e[49]=k,e[50]=z,e[51]=be):be=e[51];let we;e[52]!==v||e[53]!==$||e[54]!==L||e[55]!==X||e[56]!==ne||e[57]!==se||e[58]!==pe||e[59]!==me||e[60]!==be?(we=s.jsxs("div",{ref:v,className:$,onClick:L,role:X,tabIndex:ne,onKeyDown:se,"aria-label":pe,children:[me,be]}),e[52]=v,e[53]=$,e[54]=L,e[55]=X,e[56]=ne,e[57]=se,e[58]=pe,e[59]=me,e[60]=be,e[61]=we):we=e[61];let Ae;e[62]!==I||e[63]!==u||e[64]!==a||e[65]!==m||e[66]!==d||e[67]!==r||e[68]!==o?(Ae=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(xe=>d(xe,0,u??null,m??null,I)):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]}),e[62]=I,e[63]=u,e[64]=a,e[65]=m,e[66]=d,e[67]=r,e[68]=o,e[69]=Ae):Ae=e[69];let Pe;return e[70]!==ie||e[71]!==we||e[72]!==Ae?(Pe=s.jsxs("div",{className:ie,children:[we,Ae]}),e[70]=ie,e[71]=we,e[72]=Ae,e[73]=Pe):Pe=e[73],Pe},nZ=f.memo(sZ);function rZ(t){return t.stopPropagation()}function oZ(t){return t.stopPropagation()}const aZ=t=>{const e=Ce.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:u,setNodeRef:m,isDragging:h}=tv(c);let p;e[7]!==u?(p=x=>{x.stopPropagation(),u?.onPointerDown&&u.onPointerDown(x)},e[7]=u,e[8]=p):p=e[8];const g=p,y=h?"opacity-30":void 0;let b;return e[9]!==d||e[10]!==a||e[11]!==g||e[12]!==m||e[13]!==y?(b=s.jsx("div",{ref:m,...d,onPointerDown:g,className:y,children:a}),e[9]=d,e[10]=a,e[11]=g,e[12]=m,e[13]=y,e[14]=b):b=e[14],b},iZ=t=>{const e=Ce.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}=ev(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 u;return e[9]!==d?(u=s.jsx(s.Fragment,{children:d}),e[9]=d,e[10]=u):u=e[10],u},lZ=t=>{const e=Ce.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=Ic(li(Rc,i)),[c,d]=f.useState(null),[u,m]=f.useState("Session"),[h,p]=f.useState(null),[g,y]=f.useState(null);if(!n){let S;return e[1]!==a?(S=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=S):S=e[2],S}let b;e[3]!==o?(b=S=>{d(null),p(null),y(null);const{active:j,over:A}=S;if(!A)return;const M=j.data.current,F=A.data.current;M?.type==="session"&&M.sessionId&&F?.type==="folder"&&F.folderId&&o(M.sessionId,F.folderId)},e[3]=o,e[4]=b):b=e[4];const x=b;let v,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(v=S=>{const j=S.active.data.current;if(j?.type==="session"&&j.sessionId){d(j.sessionId),m(j.sessionTitle??"Session");const A=S.active.rect.current.initial?.width,M=S.active.rect.current.initial?.height;p(typeof A=="number"?A:null),y(typeof M=="number"?M:null)}},w=()=>{d(null),p(null),y(null)},e[5]=v,e[6]=w):(v=e[5],w=e[6]);let C;e[7]!==g||e[8]!==c||e[9]!==u||e[10]!==h||e[11]!==r?(C=c&&r?s.jsxs("div",{style:{width:h?`${h}px`:"auto",height:g?`${g}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(uu,{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:u})]}):null,e[7]=g,e[8]=c,e[9]=u,e[10]=h,e[11]=r,e[12]=C):C=e[12];let k;e[13]!==C?(k=s.jsx(m4,{children:C}),e[13]=C,e[14]=k):k=e[14];let N;return e[15]!==a||e[16]!==x||e[17]!==l||e[18]!==k?(N=s.jsxs(Lc,{sensors:l,collisionDetection:zc,onDragStart:v,onDragCancel:w,onDragEnd:x,children:[a,k]}),e[15]=a,e[16]=x,e[17]=l,e[18]=k,e[19]=N):N=e[19],N};function cZ(t){const e=Ce.c(207),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,expandedSessionGroups:d,collapsedGroups:u,hideDirectoryControls:m,getFoldersForScope:h,collapsedFolderIds:p,toggleFolderCollapse:g,renameFolder:y,deleteFolder:b,showDeletionDialog:x,setDeleteFolderConfirm:v,renderSessionNode:w,currentSessionDirectory:C,projectRepoStatus:k,lastRepoStatus:N,toggleGroupSessionLimit:S,mobileVariant:j,activeProjectId:A,setActiveProjectIdOnly:M,setActiveMainTab:F,setSessionSwitcherOpen:B,openNewSessionDraft:D,addSessionToFolder:E,createFolderAndStartRename:I,renamingFolderId:T,renameFolderDraft:H,setRenameFolderDraft:P,setRenamingFolderId:_,pinnedSessionIds:R,prVisualStateByDirectoryBranch:z,onToggleCollapsedGroup:O}=t;let Q,te,W,U,K,q,ee,V,G,Y,oe,re,fe,ie,de,$,L,X,ne,se,pe,ae,ve,ce,Z,me,be;if(e[0]!==A||e[1]!==E||e[2]!==p||e[3]!==u||e[4]!==I||e[5]!==C||e[6]!==b||e[7]!==d||e[8]!==h||e[9]!==n||e[10]!==r||e[11]!==c||e[12]!==i||e[13]!==m||e[14]!==N||e[15]!==j||e[16]!==l||e[17]!==D||e[18]!==R||e[19]!==z||e[20]!==o||e[21]!==k||e[22]!==y||e[23]!==H||e[24]!==T||e[25]!==w||e[26]!==F||e[27]!==M||e[28]!==v||e[29]!==P||e[30]!==_||e[31]!==B||e[32]!==x||e[33]!==g){me=Symbol.for("react.early_return_sentinel");e:{const Qe=i?c.get(n):null;let pt;e[61]!==d||e[62]!==r?(pt=d.has(r),e[61]=d,e[62]=r,e[63]=pt):pt=e[63],re=pt;let St;e[64]!==u||e[65]!==r||e[66]!==i?(St=i?!1:u.has(r),e[64]=u,e[65]=r,e[66]=i,e[67]=St):St=e[67],oe=St,ie=m?10:5;const Ht=i?Qe?.groupMatches===!0:!1,ye=i?Qe?.filteredNodes??[]:n.sessions,Ge=n.folderScopeKey??rn(n.directory??null),Ee=Ge?h(Ge):[],$e=new Map,tt=Wt=>{Wt.forEach(Ie=>{$e.set(Ie.session.id,Ie),Ie.children.length>0&&tt(Ie.children)})};tt(ye);const jt=Ee.map(Wt=>{const Ie=Wt.sessionIds.map(wt=>$e.get(wt)).filter(yZ).sort((wt,Ot)=>Bc(wt.session,Ot.session,R));return{folder:Wt,nodes:Ie}}),ct=new Map(jt.map(gZ)),Xe=Wt=>{const Ie=ct.get(Wt);return Ie?!i||Ie.folder.name.toLowerCase().includes(l)||Ie.nodes.length>0?!0:jt.filter(Ot=>{const{folder:Lt}=Ot;return Lt.parentId===Wt}).some(Ot=>{const{folder:Lt}=Ot;return Xe(Lt.id)}):!1};te=i?jt.filter(Wt=>{const{folder:Ie}=Wt;return Xe(Ie.id)}):jt;const At=new Set(te.flatMap(pZ)),yt=ye.filter(Wt=>!At.has(Wt.session.id)),dt=te.filter(hZ);if(i&&!Ht&&dt.length===0&&yt.length===0){me=null;break e}be=yt.length;const Tt=n.isArchivedBucket||i||re?yt:yt.slice(0,ie);X=be-Tt.length,W=mZ(ye);const rs=rn(n.directory??null);let is;e[68]!==N||e[69]!==o||e[70]!==k?(is=o&&k.has(o)?!!k.get(o):N,e[68]=N,e[69]=o,e[70]=k,e[71]=is):is=e[71],fe=is,Y=!!(rs&&C&&rs===C);const as=n.directory??null;let ps;e[72]!==as?(ps=rn(as),e[72]=as,e[73]=ps):ps=e[73];const xs=ps;let mt;e[74]!==n.branch?(mt=n.branch?.trim()??null,e[74]=n.branch,e[75]=mt):mt=e[75];const It=mt;let Se;e[76]!==It||e[77]!==xs||e[78]!==z?(Se=xs&&It?z.get(`${xs}::${It}`)??null:null,e[76]=It,e[77]=xs,e[78]=z,e[79]=Se):Se=e[79],L=Se,se=!!(L&&n.branch);let et;e[80]!==n.branch||e[81]!==n.isMain||e[82]!==n.label||e[83]!==L?(et=!n.isMain&&(mG(n.branch,n.label)||!!L),e[80]=n.branch,e[81]=n.isMain,e[82]=n.label,e[83]=L,e[84]=et):et=e[84],ne=et;const qe=L?.visualState??null;K=qe?`var(--pr-${qe})`:void 0,q=L&&L.state==="open"&&L.checks?`${L.checks.success}/${L.checks.total} checks passed`:null;let bt;e[85]!==L?(bt=L&&L.state==="open"&&L.checks?[L.checks.failure>0?`${L.checks.failure} failing`:null,L.checks.pending>0?`${L.checks.pending} pending`:null].filter(fZ).join(", "):null,e[85]=L,e[86]=bt):bt=e[86],ee=bt,$=L&&L.state==="open"?L.mergeableState==="blocked"||L.mergeableState==="dirty"?"Conflicts or blocked":L.mergeableState==="clean"||L.canMerge===!0?"Mergeable":null:null,de=L&&L.state==="open"&&L.mergeableState?`Merge state: ${L.mergeableState}`:null,U=L?.base??null,G=L?.head??null;let Rt;e[87]!==L?.url?(Rt=Wt=>{Wt.preventDefault(),Wt.stopPropagation();const Ie=L?.url;if(!Ie||typeof window>"u")return;const wt=window.__TAURI__;if(wt?.shell?.open){wt.shell.open(Ie).catch(()=>{window.open(Ie,"_blank","noopener,noreferrer")});return}window.open(Ie,"_blank","noopener,noreferrer")},e[87]=L?.url,e[88]=Rt):Rt=e[88],V=Rt;const Nt=(Wt,Ie,wt)=>{const Ot=te.filter(Kt=>{const{folder:Ct}=Kt;return Ct.parentId===Wt.id}),Lt=Ot.length>0?s.jsx(s.Fragment,{children:Ot.map(Kt=>{const{folder:Ct,nodes:Xt}=Kt;return Nt(Ct,Xt,wt+1)})}):void 0;return s.jsx(iZ,{folderId:Wt.id,children:(Kt,Ct)=>s.jsx(nZ,{folder:Wt,sessions:Ie,subFolderItems:Lt,isCollapsed:i?!1:p.has(Wt.id),onToggle:()=>g(Wt.id),onRename:Xt=>{Ge&&y(Ge,Wt.id,Xt)},onDelete:()=>{if(!Ge)return;if(!x){b(Ge,Wt.id);return}const Xt=te.filter(cs=>{const{folder:en}=cs;return en.parentId===Wt.id}).length,Ss=Ie.length;v({scopeKey:Ge,folderId:Wt.id,folderName:Wt.name,subFolderCount:Xt,sessionCount:Ss})},renderSessionNode:w,groupDirectory:n.directory,projectId:o,mobileVariant:j,isRenaming:T===Wt.id,renameDraft:T===Wt.id?H:void 0,onRenameDraftChange:Xt=>P(Xt),onRenameSave:()=>{const Xt=H.trim();Xt&&Ge&&y(Ge,Wt.id,Xt),_(null),P("")},onRenameCancel:()=>{_(null),P("")},droppableRef:Kt,isDropTarget:Ct,depth:wt,onNewSession:()=>{o&&o!==A&&M(o),F("chat"),j&&B(!1),D({directoryOverride:n.directory,targetFolderId:Wt.id})},onNewSubFolder:wt===0?()=>{Ge&&I(Ge,Wt.id)}:void 0,hideActions:n.isArchivedBucket===!0,archivedBucket:n.isArchivedBucket===!0})},Wt.id)},Pt=()=>dt.map(Wt=>{const{folder:Ie,nodes:wt}=Wt;return Nt(Ie,wt,0)});Q=lZ,pe=Ge,ae=te.length>0,ve=(Wt,Ie)=>{Ge&&E(Ge,Ie,Wt)},ce=Pt();let Jt;e[89]!==n.directory||e[90]!==n.isArchivedBucket||e[91]!==o||e[92]!==w?(Jt=Wt=>w(Wt,0,n.directory,o,n.isArchivedBucket===!0),e[89]=n.directory,e[90]=n.isArchivedBucket,e[91]=o,e[92]=w,e[93]=Jt):Jt=e[93],Z=Tt.map(Jt)}e[0]=A,e[1]=E,e[2]=p,e[3]=u,e[4]=I,e[5]=C,e[6]=b,e[7]=d,e[8]=h,e[9]=n,e[10]=r,e[11]=c,e[12]=i,e[13]=m,e[14]=N,e[15]=j,e[16]=l,e[17]=D,e[18]=R,e[19]=z,e[20]=o,e[21]=k,e[22]=y,e[23]=H,e[24]=T,e[25]=w,e[26]=F,e[27]=M,e[28]=v,e[29]=P,e[30]=_,e[31]=B,e[32]=x,e[33]=g,e[34]=Q,e[35]=te,e[36]=W,e[37]=U,e[38]=K,e[39]=q,e[40]=ee,e[41]=V,e[42]=G,e[43]=Y,e[44]=oe,e[45]=re,e[46]=fe,e[47]=ie,e[48]=de,e[49]=$,e[50]=L,e[51]=X,e[52]=ne,e[53]=se,e[54]=pe,e[55]=ae,e[56]=ve,e[57]=ce,e[58]=Z,e[59]=me,e[60]=be}else Q=e[34],te=e[35],W=e[36],U=e[37],K=e[38],q=e[39],ee=e[40],V=e[41],G=e[42],Y=e[43],oe=e[44],re=e[45],fe=e[46],ie=e[47],de=e[48],$=e[49],L=e[50],X=e[51],ne=e[52],se=e[53],pe=e[54],ae=e[55],ve=e[56],ce=e[57],Z=e[58],me=e[59],be=e[60];if(me!==Symbol.for("react.early_return_sentinel"))return me;let we;e[94]!==te||e[95]!==n.isArchivedBucket||e[96]!==be?(we=be===0&&te.length===0?s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:n.isArchivedBucket?"No archived sessions yet.":"No sessions in this workspace yet."}):null,e[94]=te,e[95]=n.isArchivedBucket,e[96]=be,e[97]=we):we=e[97];let Ae;e[98]!==r||e[99]!==re||e[100]!==X||e[101]!==S?(Ae=X>0&&!re?s.jsxs("button",{type:"button",onClick:()=>S(r),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 ",X," more ",X===1?"session":"sessions"]}):null,e[98]=r,e[99]=re,e[100]=X,e[101]=S,e[102]=Ae):Ae=e[102];let Pe;e[103]!==r||e[104]!==re||e[105]!==ie||e[106]!==S||e[107]!==be?(Pe=re&&be>ie?s.jsx("button",{type:"button",onClick:()=>S(r),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,e[103]=r,e[104]=re,e[105]=ie,e[106]=S,e[107]=be,e[108]=Pe):Pe=e[108];let xe;e[109]!==Q||e[110]!==pe||e[111]!==ae||e[112]!==ve||e[113]!==ce||e[114]!==Z||e[115]!==we||e[116]!==Ae||e[117]!==Pe?(xe=s.jsxs(Q,{scopeKey:pe,hasFolders:ae,onSessionDroppedOnFolder:ve,children:[ce,Z,we,Ae,Pe]}),e[109]=Q,e[110]=pe,e[111]=ae,e[112]=ve,e[113]=ce,e[114]=Z,e[115]=we,e[116]=Ae,e[117]=Pe,e[118]=xe):xe=e[118];const _e=xe;if(a){let Qe;return e[119]!==_e?(Qe=s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body pb-3",children:_e})}),e[119]=_e,e[120]=Qe):Qe=e[120],Qe}let ze;e[121]===Symbol.for("react.memo_cache_sentinel")?(ze=J("group/gh relative flex items-center justify-between gap-1 py-1 min-w-0 rounded-sm","hover:bg-interactive-hover/50 cursor-pointer"),e[121]=ze):ze=e[121];let le;e[122]!==r||e[123]!==O?(le=()=>O(r),e[122]=r,e[123]=O,e[124]=le):le=e[124];let ge;e[125]!==r||e[126]!==O?(ge=Qe=>{(Qe.key==="Enter"||Qe.key===" ")&&(Qe.preventDefault(),O(r))},e[125]=r,e[126]=O,e[127]=ge):ge=e[127];const Fe=oe?`Expand ${n.label}`:`Collapse ${n.label}`,ke=j?!n.isMain&&n.worktree?"pr-14":"pr-7":!n.isMain&&n.worktree?"group-hover/gh:pr-14 group-focus-within/gh:pr-14":"group-hover/gh:pr-7 group-focus-within/gh:pr-7";let Ze;e[128]!==ke?(Ze=J("min-w-0 flex items-center gap-1.5 pl-1.5 transition-[padding]",ke),e[128]=ke,e[129]=Ze):Ze=e[129];let Je;e[130]!==U||e[131]!==K||e[132]!==q||e[133]!==ee||e[134]!==n.isArchivedBucket||e[135]!==n.isMain||e[136]!==G||e[137]!==fe||e[138]!==de||e[139]!==$||e[140]!==L||e[141]!==se?(Je=n.isArchivedBucket?s.jsx(sv,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||fe?se&&L?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(cn,{className:"h-3.5 w-3.5 flex-shrink-0 translate-y-[0.5px] text-muted-foreground",style:K?{color:K}:void 0})})}),s.jsx($t,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[U||G?s.jsx("div",{className:"text-muted-foreground truncate",children:U&&G?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:U}),s.jsx(B3,{className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:G})]}):s.jsx("span",{children:U??G??""})}):null,de?s.jsx("div",{className:"text-muted-foreground truncate",children:de}):null,$||q?s.jsxs("div",{className:"text-muted-foreground truncate",children:[$??"",$&&q?" • ":"",q??"",ee?` (${ee})`:""]}):null]})})]}):s.jsx(cn,{className:"h-3.5 w-3.5 flex-shrink-0 translate-y-[0.5px] text-muted-foreground",style:K?{color:K}:void 0}):null,e[130]=U,e[131]=K,e[132]=q,e[133]=ee,e[134]=n.isArchivedBucket,e[135]=n.isMain,e[136]=G,e[137]=fe,e[138]=de,e[139]=$,e[140]=L,e[141]=se,e[142]=Je):Je=e[142];const Ye=Y?"text-primary":"text-muted-foreground";let Re;e[143]!==Ye?(Re=J("text-[14px] font-semibold truncate",Ye),e[143]=Ye,e[144]=Re):Re=e[144];let Ue;e[145]!==U||e[146]!==q||e[147]!==ee||e[148]!==n.branch||e[149]!==n.label||e[150]!==V||e[151]!==G||e[152]!==de||e[153]!==$||e[154]!==l||e[155]!==L||e[156]!==se?(Ue=se&&L?s.jsxs(s.Fragment,{children:[s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("span",{className:"inline-flex items-baseline gap-1",children:L.url?s.jsxs("button",{type:"button",className:"inline-flex items-baseline leading-none underline hover:no-underline",onMouseDown:uZ,onClick:V,children:["#",L.number]}):s.jsxs("span",{className:"leading-none",children:["#",L.number]})})}),s.jsx($t,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[U||G?s.jsx("div",{className:"text-muted-foreground truncate",children:U&&G?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:U}),s.jsx(B3,{className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:G})]}):s.jsx("span",{children:U??G??""})}):null,de?s.jsx("div",{className:"text-muted-foreground truncate",children:de}):null,$||q?s.jsxs("div",{className:"text-muted-foreground truncate",children:[$??"",$&&q?" • ":"",q??"",ee?` (${ee})`:""]}):null]})})]}),s.jsx("span",{children:` ${n.branch}`})]}):c4(n.label,l),e[145]=U,e[146]=q,e[147]=ee,e[148]=n.branch,e[149]=n.label,e[150]=V,e[151]=G,e[152]=de,e[153]=$,e[154]=l,e[155]=L,e[156]=se,e[157]=Ue):Ue=e[157];let Ve;e[158]!==Re||e[159]!==Ue?(Ve=s.jsx("p",{className:Re,children:Ue}),e[158]=Re,e[159]=Ue,e[160]=Ve):Ve=e[160];let st;e[161]!==n.branch||e[162]!==V||e[163]!==L||e[164]!==ne||e[165]!==se?(st=!se&&ne?s.jsx("span",{className:"text-[10px] sm:text-[11px] text-muted-foreground/80 truncate leading-tight",children:L?s.jsxs(s.Fragment,{children:[L.url?s.jsxs("button",{type:"button",className:"underline hover:no-underline",onMouseDown:dZ,onClick:V,children:["#",L.number]}):s.jsxs("span",{children:["#",L.number]}),n.branch?s.jsx("span",{children:` ${n.branch}`}):null]}):n.branch}):null,e[161]=n.branch,e[162]=V,e[163]=L,e[164]=ne,e[165]=se,e[166]=st):st=e[166];let at;e[167]!==Ve||e[168]!==st?(at=s.jsxs("div",{className:"min-w-0 flex flex-col justify-center",children:[Ve,st]}),e[167]=Ve,e[168]=st,e[169]=at):at=e[169];let nt;e[170]!==oe?(nt=oe?s.jsx(Un,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(Ls,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}),e[170]=oe,e[171]=nt):nt=e[171];let he;e[172]!==Ze||e[173]!==Je||e[174]!==at||e[175]!==nt?(he=s.jsxs("div",{className:Ze,children:[Je,at,nt]}),e[172]=Ze,e[173]=Je,e[174]=at,e[175]=nt,e[176]=he):he=e[176];let je;e[177]!==W||e[178]!==n.directory||e[179]!==n.isMain||e[180]!==n.label||e[181]!==n.worktree||e[182]!==j?(je=n.directory&&!n.isMain&&n.worktree?s.jsx("div",{className:J("absolute right-7 top-1/2 -translate-y-1/2 z-10 transition-opacity",j?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Qe=>{Qe.stopPropagation(),ia.requestDelete({sessions:W,mode:"worktree",worktree:n.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 ${n.label}`,children:s.jsx(Ln,{className:"h-4 w-4"})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete worktree"})})]})}):null,e[177]=W,e[178]=n.directory,e[179]=n.isMain,e[180]=n.label,e[181]=n.worktree,e[182]=j,e[183]=je):je=e[183];let We;e[184]!==A||e[185]!==n.directory||e[186]!==n.label||e[187]!==j||e[188]!==D||e[189]!==o||e[190]!==F||e[191]!==M||e[192]!==B?(We=n.directory?s.jsx("div",{className:J("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",j?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Qe=>{Qe.stopPropagation(),o&&o!==A&&M(o),F("chat"),j&&B(!1),D({directoryOverride:n.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 ${n.label}`,children:s.jsx(Xs,{className:"h-4 w-4"})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null,e[184]=A,e[185]=n.directory,e[186]=n.label,e[187]=j,e[188]=D,e[189]=o,e[190]=F,e[191]=M,e[192]=B,e[193]=We):We=e[193];let lt;e[194]!==le||e[195]!==ge||e[196]!==Fe||e[197]!==he||e[198]!==je||e[199]!==We?(lt=s.jsxs("div",{className:ze,onClick:le,role:"button",tabIndex:0,onKeyDown:ge,"aria-label":Fe,children:[he,je,We]}),e[194]=le,e[195]=ge,e[196]=Fe,e[197]=he,e[198]=je,e[199]=We,e[200]=lt):lt=e[200];let rt;e[201]!==_e||e[202]!==oe?(rt=oe?null:s.jsx("div",{className:"oc-group-body pb-3",children:_e}),e[201]=_e,e[202]=oe,e[203]=rt):rt=e[203];let Te;return e[204]!==lt||e[205]!==rt?(Te=s.jsxs("div",{className:"oc-group",children:[lt,rt]}),e[204]=lt,e[205]=rt,e[206]=Te):Te=e[206],Te}function dZ(t){return t.stopPropagation()}function uZ(t){return t.stopPropagation()}function fZ(t){return!!t}function mZ(t){const e=[],n=r=>{r.forEach(o=>{e.push(o.session),o.children.length>0&&n(o.children)})};return n(t),e}function hZ(t){const{folder:e}=t;return!e.parentId}function pZ(t){return t.folder.sessionIds}function gZ(t){return[t.folder.id,t]}function yZ(t){return!!t}const d4=xn()(hr(t=>({displayMode:"default",setDisplayMode:e=>t({displayMode:e})}),{name:"session-display-mode"}));function bZ(t){const e=Ce.c(46),{hideDirectoryControls:n,hideProjectSelector:r,activeProjectForHeader:o,homeDirectory:a,normalizedProjects:i,activeProjectId:l,setActiveProjectIdOnly:c,isProjectRenameInline:d,setIsProjectRenameInline:u,handleStartInlineProjectRename:m,handleSaveInlineProjectRename:h,projectRenameDraft:p,setProjectRenameDraft:g,removeProject:y,addProjectButtonClass:b,headerActionIconClass:x,reserveHeaderActionsSpace:v,stableActiveProjectIsRepo:w,useMobileNotesPanel:C,projectNotesPanelOpen:k,setProjectNotesPanelOpen:N,activeProjectRefForHeader:S,openMultiRunLauncher:j,headerActionButtonClass:A,setNewWorktreeDialogOpen:M,setActiveMainTab:F,isSessionSearchOpen:B,setIsSessionSearchOpen:D,sessionSearchInputRef:E,sessionSearchQuery:I,setSessionSearchQuery:T,hasSessionSearchQuery:H,searchMatchCount:P}=t,_=d4(wZ),R=d4(vZ);if(n)return null;const z=`select-none pl-3.5 pr-2 flex-shrink-0 border-b border-border/60 ${r?"py-1":"py-1.5"}`;let O;e[0]!==o||e[1]!==l||e[2]!==b||e[3]!==_||e[4]!==h||e[5]!==m||e[6]!==x||e[7]!==r||e[8]!==a||e[9]!==d||e[10]!==i||e[11]!==p||e[12]!==y||e[13]!==c||e[14]!==R||e[15]!==u||e[16]!==g?(O=!r&&s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[s.jsxs(zs,{onOpenChange:W=>{W||u(!1)},children:[s.jsx(Hs,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex h-8 min-w-0 max-w-[calc(100%-2.5rem)] cursor-pointer 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:o?J0(o.label?.trim()||fo(o.normalizedPath,a)||o.normalizedPath):"Projects"}),s.jsx(Ls,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsxs(Os,{align:"start",className:"min-w-[220px] max-w-[320px]",children:[i.map(W=>{const U=J0(W.label?.trim()||fo(W.normalizedPath,a)||W.normalizedPath);return s.jsx(Qt,{onClick:()=>c(W.id),className:`truncate ${W.id===l?"text-primary":""}`,children:s.jsx("span",{className:"truncate",children:U})},W.id)}),s.jsx("div",{className:"my-1 h-px bg-border/70"}),d?s.jsx("div",{className:"px-2 py-1.5",children:s.jsxs("form",{className:"flex items-center gap-1",onSubmit:W=>{W.preventDefault(),h()},children:[s.jsx("input",{value:p,onChange:W=>g(W.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:W=>{if(W.key==="Escape"){W.stopPropagation(),u(!1);return}(W.key===" "||W.key==="Enter")&&W.stopPropagation()}}),s.jsx("button",{type:"submit",className:"inline-flex h-7 w-7 cursor-pointer items-center justify-center rounded text-muted-foreground hover:text-foreground",children:s.jsx(vs,{className:"h-4 w-4"})}),s.jsx("button",{type:"button",onClick:()=>u(!1),className:"inline-flex h-7 w-7 cursor-pointer items-center justify-center rounded text-muted-foreground hover:text-foreground",children:s.jsx(_s,{className:"h-4 w-4"})})]})}):s.jsxs(Qt,{onClick:W=>{W.preventDefault(),m()},className:"gap-2",children:[s.jsx(ao,{className:"h-4 w-4"}),"Rename project"]}),s.jsxs(Qt,{onClick:()=>{o&&y(o.id)},className:"text-destructive focus:text-destructive gap-2",children:[s.jsx(_s,{className:"h-4 w-4"}),"Close project"]})]})]}),s.jsxs(zs,{children:[s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",className:b,"aria-label":"Session display mode",children:s.jsx(E3,{className:x})})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Display mode"})})]}),s.jsxs(Os,{align:"end",className:"min-w-[160px]",children:[s.jsxs(Qt,{onClick:()=>R("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:"Default"}),_==="default"?s.jsx(vs,{className:"h-4 w-4 text-primary"}):null]}),s.jsxs(Qt,{onClick:()=>R("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:"Minimal"}),_==="minimal"?s.jsx(vs,{className:"h-4 w-4 text-primary"}):null]})]})]})]}),e[0]=o,e[1]=l,e[2]=b,e[3]=_,e[4]=h,e[5]=m,e[6]=x,e[7]=r,e[8]=a,e[9]=d,e[10]=i,e[11]=p,e[12]=y,e[13]=c,e[14]=R,e[15]=u,e[16]=g,e[17]=O):O=e[17];let Q;e[18]!==o||e[19]!==l||e[20]!==S||e[21]!==_||e[22]!==H||e[23]!==A||e[24]!==x||e[25]!==B||e[26]!==j||e[27]!==k||e[28]!==v||e[29]!==P||e[30]!==E||e[31]!==I||e[32]!==F||e[33]!==c||e[34]!==R||e[35]!==D||e[36]!==M||e[37]!==N||e[38]!==T||e[39]!==w||e[40]!==C?(Q=v?s.jsx("div",{className:"-ml-1 flex h-auto min-h-8 flex-col gap-1",children:o?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex h-8 -translate-y-px items-center justify-between gap-1.5 rounded-md pl-0 pr-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[w?s.jsxs(s.Fragment,{children:[s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:async()=>{o&&(o.id!==l&&c(o.id),F("chat"),M(!0))},className:A,"aria-label":"New worktree",children:s.jsx(nv,{className:x})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New worktree"})})]}),s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j,className:A,"aria-label":"New multi-run",children:s.jsx(o3,{className:x})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New multi-run"})})]})]}):null,C?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>N(!0),className:A,"aria-label":"Project notes and todos",children:s.jsx(uu,{className:x})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Project notes"})})]}):s.jsxs(zs,{open:k,onOpenChange:N,modal:!1,children:[s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",className:A,"aria-label":"Project notes and todos",children:s.jsx(uu,{className:x})})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Project notes"})})]}),s.jsx(Os,{align:"start",className:"w-[340px] p-0",children:s.jsx(O9,{projectRef:S,canCreateWorktree:w,onActionComplete:()=>N(!1)})})]}),s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>D(xZ),className:A,"aria-label":"Search sessions","aria-expanded":B,children:s.jsx(ur,{className:x})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]})]}),s.jsxs(zs,{children:[s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",className:A,"aria-label":"Session display mode",children:s.jsx(E3,{className:x})})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Display mode"})})]}),s.jsxs(Os,{align:"end",className:"min-w-[160px]",children:[s.jsxs(Qt,{onClick:()=>R("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:"Default"}),_==="default"?s.jsx(vs,{className:"h-4 w-4 text-primary"}):null]}),s.jsxs(Qt,{onClick:()=>R("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:"Minimal"}),_==="minimal"?s.jsx(vs,{className:"h-4 w-4 text-primary"}):null]})]})]})]}),B?s.jsxs("div",{className:"px-1 pb-1",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:[H?s.jsxs("span",{children:[P," ",P===1?"match":"matches"]}):s.jsx("span",{}),s.jsx("span",{children:"Esc to clear"})]}),s.jsxs("div",{className:"relative",children:[s.jsx(ur,{className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:E,value:I,onChange:W=>T(W.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:W=>{W.key==="Escape"&&(W.stopPropagation(),H?T(""):D(!1))}}),I.length>0?s.jsx("button",{type:"button",onClick:()=>T(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:s.jsx(_s,{className:"h-3.5 w-3.5"})}):null]})]}):null]}):null}):null,e[18]=o,e[19]=l,e[20]=S,e[21]=_,e[22]=H,e[23]=A,e[24]=x,e[25]=B,e[26]=j,e[27]=k,e[28]=v,e[29]=P,e[30]=E,e[31]=I,e[32]=F,e[33]=c,e[34]=R,e[35]=D,e[36]=M,e[37]=N,e[38]=T,e[39]=w,e[40]=C,e[41]=Q):Q=e[41];let te;return e[42]!==z||e[43]!==O||e[44]!==Q?(te=s.jsxs("div",{className:z,children:[O,Q]}),e[42]=z,e[43]=O,e[44]=Q,e[45]=te):te=e[45],te}function xZ(t){return!t}function vZ(t){return t.setDisplayMode}function wZ(t){return t.displayMode}const jZ=t=>{const e=Ce.c(46),{id:n,projectLabel:r,projectDescription:o,isCollapsed:a,isActiveProject:i,isRepo:l,isHovered:c,isDesktopShell:d,isStuck:u,hideDirectoryControls:m,mobileVariant:h,onToggle:p,onHoverChange:g,onNewSession:y,onNewWorktreeSession:b,onOpenMultiRunLauncher:x,onRenameStart:v,onRenameSave:w,onRenameCancel:C,onRenameValueChange:k,renameValue:N,isRenaming:S,onClose:j,sentinelRef:A,children:M,settingsAutoCreateWorktree:F,showCreateButtons:B,hideHeader:D}=t,E=B===void 0?!0:B,I=D===void 0?!1:D;let T;e[0]!==n?(T={id:n},e[0]=n,e[1]=T):T=e[1];const{attributes:H,listeners:P,setNodeRef:_,transform:R,transition:z,isDragging:O}=Tc(T),[Q,te]=f.useState(!1);let W;e[2]!==R?(W=Pc.Transform.toString(R),e[2]=R,e[3]=W):W=e[3];let U;e[4]!==W||e[5]!==z?(U={transform:W,transition:z},e[4]=W,e[5]=z,e[6]=U):U=e[6];const K=O&&"opacity-30";let q;e[7]!==K?(q=J("relative",K),e[7]=K,e[8]=q):q=e[8];let ee;e[9]!==H||e[10]!==m||e[11]!==I||e[12]!==n||e[13]!==i||e[14]!==a||e[15]!==d||e[16]!==c||e[17]!==Q||e[18]!==S||e[19]!==l||e[20]!==u||e[21]!==P||e[22]!==h||e[23]!==j||e[24]!==g||e[25]!==y||e[26]!==b||e[27]!==x||e[28]!==C||e[29]!==w||e[30]!==v||e[31]!==k||e[32]!==p||e[33]!==o||e[34]!==r||e[35]!==N||e[36]!==A||e[37]!==F||e[38]!==E?(ee=I?null:s.jsxs(s.Fragment,{children:[d&&s.jsx("div",{ref:A,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsx("div",{className:J("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:()=>g(!0),onMouseLeave:()=>g(!1),onContextMenu:G=>{G.preventDefault(),S||te(!0)},children:s.jsxs("div",{className:"relative flex items-center gap-1 px-1",...H,children:[S?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-2","data-keyboard-avoid":"true",onSubmit:G=>{G.preventDefault(),w()},children:[s.jsx("input",{value:N,onChange:G=>k(G.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:G=>{if(G.key==="Escape"){G.stopPropagation(),C();return}(G.key===" "||G.key==="Enter")&&G.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(vs,{className:"size-4"})}),s.jsx("button",{type:"button",onClick:C,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(_s,{className:"size-4"})})]}):s.jsxs(Vt,{delayDuration:1500,children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:p,...P,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:J("typography-ui font-semibold truncate",i?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),s.jsx($t,{side:"right",sideOffset:8,children:o})]}),S?null:s.jsxs(zs,{open:Q,onOpenChange:te,children:[s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",className:J("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",h?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:NZ,children:s.jsx(mo,{className:"h-3.5 w-3.5"})})}),s.jsxs(Os,{align:"end",className:"min-w-[180px]",children:[E&&l&&!m&&F&&y&&s.jsxs(Qt,{onClick:y,children:[s.jsx(Xs,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),E&&l&&!m&&!F&&b&&s.jsxs(Qt,{onClick:b,children:[s.jsx(cn,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),E&&l&&!m&&s.jsxs(Qt,{onClick:x,children:[s.jsx(o3,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),s.jsxs(Qt,{onClick:v,children:[s.jsx(ao,{className:"mr-1.5 h-4 w-4"}),"Rename"]}),s.jsxs(Qt,{onClick:j,className:"text-destructive focus:text-destructive",children:[s.jsx(_s,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),E&&l&&!m&&b&&F&&!S&&s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),b()},className:J("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",h?"opacity-70":"opacity-100"),"aria-label":"New session in worktree",children:s.jsx(cn,{className:"h-4 w-4"})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session in worktree"})})]}),E&&(!F||!l)&&!S&&s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),y()},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(Xs,{className:"h-4 w-4"})})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})]})})]}),e[9]=H,e[10]=m,e[11]=I,e[12]=n,e[13]=i,e[14]=a,e[15]=d,e[16]=c,e[17]=Q,e[18]=S,e[19]=l,e[20]=u,e[21]=P,e[22]=h,e[23]=j,e[24]=g,e[25]=y,e[26]=b,e[27]=x,e[28]=C,e[29]=w,e[30]=v,e[31]=k,e[32]=p,e[33]=o,e[34]=r,e[35]=N,e[36]=A,e[37]=F,e[38]=E,e[39]=ee):ee=e[39];let V;return e[40]!==M||e[41]!==_||e[42]!==U||e[43]!==q||e[44]!==ee?(V=s.jsxs("div",{ref:_,style:U,className:q,children:[ee,M]}),e[40]=M,e[41]=_,e[42]=U,e[43]=q,e[44]=ee,e[45]=V):V=e[45],V},SZ=t=>{const e=Ce.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:u}=Tc(o);let m;e[2]!==c?(m=Pc.Transform.toString(c),e[2]=c,e[3]=m):m=e[3];let h;e[4]!==m||e[5]!==d?(h={transform:m,transition:d},e[4]=m,e[5]=d,e[6]=h):h=e[6];const p=u&&"opacity-50";let g;e[7]!==p?(g=J("space-y-0.5 rounded-md",p),e[7]=p,e[8]=g):g=e[8];let y;return e[9]!==a||e[10]!==r||e[11]!==i||e[12]!==l||e[13]!==h||e[14]!==g?(y=s.jsx("div",{ref:l,style:h,className:g,...a,...i,children:r}),e[9]=a,e[10]=r,e[11]=i,e[12]=l,e[13]=h,e[14]=g,e[15]=y):y=e[15],y},kZ=f.memo(SZ);function NZ(t){return t.stopPropagation()}function CZ(t){const e=Ce.c(20);let n;e[0]===Symbol.for("react.memo_cache_sentinel")?(n={activationConstraint:{distance:8}},e[0]=n):n=e[0];let r;e[1]===Symbol.for("react.memo_cache_sentinel")?(r={coordinateGetter:gp},e[1]=r):r=e[1];const o=Ic(li(Rc,n),li(pp,r));if(t.projectSections.length===0){const d=(t.mobileVariant,"");let u;e[2]!==d?(u=J("space-y-1 pb-1 pl-2.5 pr-1",d),e[2]=d,e[3]=u):u=e[3];let m;return e[4]!==t.emptyState||e[5]!==u?(m=s.jsx(Ns,{outerClassName:"flex-1 min-h-0",className:u,children:t.emptyState}),e[4]=t.emptyState,e[5]=u,e[6]=m):m=e[6],m}if(t.sectionsForRender.length===0){const d=(t.mobileVariant,"");let u;e[7]!==d?(u=J("space-y-1 pb-1 pl-2.5 pr-1",d),e[7]=d,e[8]=u):u=e[8];let m;return e[9]!==t.searchEmptyState||e[10]!==u?(m=s.jsx(Ns,{outerClassName:"flex-1 min-h-0",className:u,children:t.searchEmptyState}),e[9]=t.searchEmptyState,e[10]=u,e[11]=m):m=e[11],m}const a=(t.mobileVariant,"");let i;e[12]!==a?(i=J("space-y-1 pb-1 pl-2.5 pr-1",a),e[12]=a,e[13]=i):i=e[13];let l;e[14]!==t||e[15]!==o?(l=t.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const d=t.sectionsForRender.find(p=>p.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!d)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const u=d.groups.find(BZ)??d.groups.find(_Z)??d.groups.find(DZ)??d.groups[0];if(!u)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const m=d.groups.find(FZ);return[u,...m&&m.id!==u.id?[m]:[]].map(p=>{const g=`${d.project.id}:${p.id}`,y=p.id===u.id;return s.jsx(f.Fragment,{children:t.renderGroupSessions(p,g,d.project.id,y)},g)})})()}):s.jsx(s.Fragment,{children:t.sectionsForRender.map(d=>{const u=d.project,m=u.id,h=J0(u.label?.trim()||fo(u.normalizedPath,t.homeDirectory)||u.normalizedPath),p=na(u.normalizedPath,t.homeDirectory),g=t.collapsedProjects.has(m)&&t.hideDirectoryControls,y=m===t.activeProjectId,b=t.projectRepoStatus.get(m),x=t.hoveredProjectId===m,v=t.getOrderedGroups(m,d.groups);return s.jsx(jZ,{id:m,projectLabel:h,projectDescription:p,isCollapsed:g,isActiveProject:y,isRepo:!!b,isHovered:x,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(m),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,onToggle:()=>t.toggleProject(m),onHoverChange:w=>t.setHoveredProjectId(w?m:null),onNewSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:u.normalizedPath})},onNewWorktreeSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.createWorktreeSession()},onOpenMultiRunLauncher:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.openMultiRunLauncher()},onRenameStart:()=>{t.setEditingProjectId(m),t.setEditProjectTitle(u.label?.trim()||fo(u.normalizedPath,t.homeDirectory)||u.normalizedPath)},onRenameSave:t.handleSaveProjectEdit,onRenameCancel:t.handleCancelProjectEdit,onRenameValueChange:t.setEditProjectTitle,renameValue:t.editingProjectId===m?t.editProjectTitle:"",isRenaming:t.editingProjectId===m,onClose:()=>t.removeProject(m),sentinelRef:w=>{t.projectHeaderSentinelRefs.current.set(m,w)},settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,showCreateButtons:!1,hideHeader:!0,children:g?null:s.jsx("div",{className:"space-y-[0.6rem] py-1",children:d.groups.length>0?s.jsxs(Lc,{sensors:o,collisionDetection:zc,onDragEnd:w=>{const{active:C,over:k}=w;if(!k||C.id===k.id)return;const N=v.findIndex(A=>A.id===C.id),S=v.findIndex(A=>A.id===k.id);if(N===-1||S===-1||N===S)return;const j=W1(v,N,S).map(AZ);t.setGroupOrderByProject(A=>{const M=new Map(A);return M.set(m,j),M})},children:[s.jsx(s2,{items:v.map(MZ),strategy:x4,children:v.map(w=>{const C=`${m}:${w.id}`;return s.jsx(kZ,{id:w.id,children:t.renderGroupSessions(w,C,m)},w.id)})}),s.jsx(m4,{dropAnimation:null})]}):s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},m)})}),e[14]=t,e[15]=o,e[16]=l):l=e[16];let c;return e[17]!==i||e[18]!==l?(c=s.jsx(Ns,{outerClassName:"flex-1 min-h-0",className:i,children:l}),e[17]=i,e[18]=l,e[19]=c):c=e[19],c}function MZ(t){return t.id}function AZ(t){return t.id}function FZ(t){return t.isArchivedBucket}function DZ(t){return t.isMain}function _Z(t){return t.sessions.length>0}function BZ(t){return t.isMain&&t.sessions.length>0}const $9=new Set([1,3,4,5,7]),V9=t=>t===4?"0ms":"130ms";function EZ(t){const e=Ce.c(189),{node:n,depth:r,groupDirectory:o,projectId:a,archivedBucket:i,directoryStatus:l,sessionMemoryState:c,currentSessionId:d,pinnedSessionIds:u,expandedParents:m,hasSessionSearchQuery:h,normalizedSessionSearchQuery:p,sessionAttentionStates:g,notifyOnSubtasks:y,sessionStatus:b,permissions:x,editingId:v,setEditingId:w,editTitle:C,setEditTitle:k,handleSaveEdit:N,handleCancelEdit:S,toggleParent:j,handleSessionSelect:A,handleSessionDoubleClick:M,togglePinnedSession:F,handleShareSession:B,copiedSessionId:D,handleCopyShareUrl:E,handleUnshareSession:I,openMenuSessionId:T,setOpenMenuSessionId:H,renamingFolderId:P,getFoldersForScope:_,getSessionFolderId:R,removeSessionFromFolder:z,addSessionToFolder:O,createFolderAndStartRename:Q,openContextPanelTab:te,handleDeleteSession:W,mobileVariant:U,renderSessionNode:K}=t,q=r===void 0?0:r,ee=i===void 0?!1:i,G=d4(LZ)==="minimal";let Y;e[0]===Symbol.for("react.memo_cache_sentinel")?(Y=ln(),e[0]=Y):Y=e[0];const oe=Y,re=n.session;let fe,ie;e[1]!==l||e[2]!==o||e[3]!==re?(fe=rn(re.directory??null)??rn(o??null),ie=fe?l.get(fe):null,e[1]=l,e[2]=o,e[3]=re,e[4]=fe,e[5]=ie):(fe=e[4],ie=e[5]);const $=ie==="missing";let L;e[6]!==re.id||e[7]!==c?(L=c.get(re.id),e[6]=re.id,e[7]=c,e[8]=L):L=e[8];const X=L,ne=d===re.id,se=re.title||"Untitled Session",pe=n.children.length>0;let ae;e[9]!==u||e[10]!==re.id?(ae=u.has(re.id),e[9]=u,e[10]=re.id,e[11]=ae):ae=e[11];const ve=ae;let ce;e[12]!==m||e[13]!==h||e[14]!==re.id?(ce=h?!0:m.has(re.id),e[12]=m,e[13]=h,e[14]=re.id,e[15]=ce):ce=e[15];const Z=ce,me=!!re.parentID,we=g.get(re.id)?.needsAttention===!0&&(!me||y),Ae=re.summary;let Pe;e[16]!==Ae?(Pe=pG(Ae),e[16]=Ae,e[17]=Pe):Pe=e[17];const xe=Pe;if(v===re.id){const Se=re.id,et=q>0&&"pl-[20px]";let qe;e[18]!==et?(qe=J("group relative flex items-center rounded-md px-1.5 py-1","bg-interactive-selection",et),e[18]=et,e[19]=qe):qe=e[19];let bt;e[20]!==N?(bt=Ct=>{Ct.preventDefault(),N()},e[20]=N,e[21]=bt):bt=e[21];let Rt;e[22]!==k?(Rt=Ct=>k(Ct.target.value),e[22]=k,e[23]=Rt):Rt=e[23];let Nt;e[24]!==S?(Nt=Ct=>{if(Ct.key==="Escape"){Ct.stopPropagation(),S();return}(Ct.key===" "||Ct.key==="Enter")&&Ct.stopPropagation()},e[24]=S,e[25]=Nt):Nt=e[25];let Pt;e[26]!==C||e[27]!==Rt||e[28]!==Nt?(Pt=s.jsx("input",{value:C,onChange:Rt,className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:Nt}),e[26]=C,e[27]=Rt,e[28]=Nt,e[29]=Pt):Pt=e[29];let Jt;e[30]===Symbol.for("react.memo_cache_sentinel")?(Jt=s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(vs,{className:"size-4"})}),e[30]=Jt):Jt=e[30];let Wt;e[31]===Symbol.for("react.memo_cache_sentinel")?(Wt=s.jsx(_s,{className:"size-4"}),e[31]=Wt):Wt=e[31];let Ie;e[32]!==S?(Ie=s.jsx("button",{type:"button",onClick:S,className:"shrink-0 text-muted-foreground hover:text-foreground",children:Wt}),e[32]=S,e[33]=Ie):Ie=e[33];let wt;e[34]!==bt||e[35]!==Pt||e[36]!==Ie?(wt=s.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:bt,children:[Pt,Jt,Ie]}),e[34]=bt,e[35]=Pt,e[36]=Ie,e[37]=wt):wt=e[37];let Ot;e[38]!==pe||e[39]!==Z||e[40]!==G||e[41]!==n.children.length||e[42]!==re.share||e[43]!==re.time?.created||e[44]!==re.time?.updated||e[45]!==xe||e[46]!==Ae?(Ot=G?null:s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:[pe?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Z?s.jsx(Ls,{className:"h-3 w-3"}):s.jsx(Un,{className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:Kd(re.time?.updated||re.time?.created||Date.now())}),xe?s.jsxs("span",{className:"flex-shrink-0",children:[s.jsxs("span",{className:"text-status-success/80",children:["+",xe.additions]}),s.jsx("span",{className:"text-muted-foreground/60",children:"/"}),s.jsxs("span",{className:"text-status-error/80",children:["-",xe.deletions]})]}):null,re.share?s.jsx(t1,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,(Ae?.files??0)>0||pe?s.jsxs("span",{className:"flex items-center gap-2 flex-shrink-0",children:[(Ae?.files??0)>0?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[s.jsx(Xl,{className:"h-3 w-3 text-muted-foreground/70"}),s.jsx("span",{children:Ae.files})]})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsxs("p",{children:[Ae.files," changed ",Ae.files===1?"file":"files"]})})]}):null,pe?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[s.jsx($r,{className:"h-3 w-3 text-muted-foreground/70"}),s.jsx("span",{children:n.children.length})]})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsxs("p",{children:[n.children.length," ",n.children.length===1?"sub-session":"sub-sessions"]})})]}):null]}):null]}),e[38]=pe,e[39]=Z,e[40]=G,e[41]=n.children.length,e[42]=re.share,e[43]=re.time?.created,e[44]=re.time?.updated,e[45]=xe,e[46]=Ae,e[47]=Ot):Ot=e[47];let Lt;e[48]!==wt||e[49]!==Ot?(Lt=s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[wt,Ot]}),e[48]=wt,e[49]=Ot,e[50]=Lt):Lt=e[50];let Kt;return e[51]!==re.id||e[52]!==qe||e[53]!==Lt?(Kt=s.jsx("div",{className:qe,children:Lt},Se),e[51]=re.id,e[52]=qe,e[53]=Lt,e[54]=Kt):Kt=e[54],Kt}let _e;e[55]!==re.id||e[56]!==b?(_e=b?.get(re.id)?.type??"idle",e[55]=re.id,e[56]=b,e[57]=_e):_e=e[57];const ze=_e,le=ze==="busy"||ze==="retry",ge=x.get(re.id)?.length??0,ke=le||!le&&we&&!ne;let Ze;e[58]!==X?.isZombie?(Ze=X?.isZombie?s.jsx(Co,{className:"h-4 w-4 text-status-warning"}):null,e[58]=X?.isZombie,e[59]=Ze):Ze=e[59];const Je=Ze,Ye=re.id,Re=re.id,Ue=fe??null,Ve=ne?"bg-interactive-selection":"hover:bg-interactive-hover",st=$?"opacity-75":"",at=q>0&&"pl-[20px]";let nt;e[60]!==Ve||e[61]!==st||e[62]!==at?(nt=J("group relative flex items-center rounded-md px-1.5 py-1",Ve,st,at),e[60]=Ve,e[61]=st,e[62]=at,e[63]=nt):nt=e[63];let he;e[64]!==re.id||e[65]!==H?(he=Se=>{Se.preventDefault(),H(re.id)},e[64]=re.id,e[65]=H,e[66]=he):he=e[66];let je;e[67]!==M||e[68]!==A||e[69]!==pe||e[70]!==Z||e[71]!==G||e[72]!==$||e[73]!==ve||e[74]!==le||e[75]!==U||e[76]!==n.children.length||e[77]!==p||e[78]!==ge||e[79]!==a||e[80]!==re.id||e[81]!==re.share||e[82]!==re.time?.created||e[83]!==re.time?.updated||e[84]!==xe||e[85]!==fe||e[86]!==Ae||e[87]!==se||e[88]!==ke||e[89]!==j?(je=s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:G?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsx("button",{type:"button",disabled:$,onClick:()=>A(re.id,fe,$,a),onDoubleClick:Se=>{Se.stopPropagation(),M()},className:J("flex min-w-0 flex-1 cursor-pointer 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 disabled:cursor-not-allowed transition-[padding]",U?"pr-7":"group-hover:pr-5 group-focus-within:pr-5"),children:s.jsxs("div",{className:J("flex w-full items-center min-w-0 flex-1 overflow-hidden",G?"gap-1":"gap-2"),children:[G&&pe?s.jsx("span",{role:"button",tabIndex:0,onClick:Se=>{Se.stopPropagation(),j(re.id)},onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),Se.stopPropagation(),j(re.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":Z?"Collapse subsessions":"Expand subsessions",children:Z?s.jsx(Ls,{className:"h-3 w-3"}):s.jsx(Un,{className:"h-3 w-3"})}):null,ke?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:le?s.jsx(Q0,{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},RZ)})}):null,ve?s.jsx(G1,{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:c4(se,p)}),ge>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(tu,{className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:ge})]}):null]})})}),s.jsx($t,{side:"right",sideOffset:8,className:"max-w-xs",children:s.jsxs("div",{className:"flex flex-col gap-1 text-xs",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-muted-foreground",children:Kd(re.time?.updated||re.time?.created||Date.now())}),xe?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsxs("span",{className:"text-status-success",children:["+",xe.additions]}),s.jsx("span",{className:"text-muted-foreground",children:"/"}),s.jsxs("span",{className:"text-status-error",children:["-",xe.deletions]})]}):null]}),re.share?s.jsxs("div",{className:"flex items-center gap-1 text-[color:var(--status-info)]",children:[s.jsx(t1,{className:"h-3 w-3"}),s.jsx("span",{children:"Shared session"})]}):null,(Ae?.files??0)>0?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Xl,{className:"h-3 w-3 text-muted-foreground"}),s.jsxs("span",{className:"text-muted-foreground",children:[Ae.files," changed ",Ae.files===1?"file":"files"]})]}):null,pe?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx($r,{className:"h-3 w-3 text-muted-foreground"}),s.jsxs("span",{className:"text-muted-foreground",children:[n.children.length," ",n.children.length===1?"sub-session":"sub-sessions"]})]}):null,$?s.jsxs("div",{className:"flex items-center gap-1 text-status-warning",children:[s.jsx(Co,{className:"h-3 w-3"}),s.jsx("span",{children:"Directory missing"})]}):null]})})]}):s.jsxs("button",{type:"button",disabled:$,onClick:()=>A(re.id,fe,$,a),onDoubleClick:Se=>{Se.stopPropagation(),M()},className:J("flex min-w-0 flex-1 cursor-pointer 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 disabled:cursor-not-allowed transition-[padding]",U?"pr-7":"group-hover:pr-5 group-focus-within:pr-5"),children:[s.jsxs("div",{className:J("flex w-full items-center min-w-0 flex-1 overflow-hidden",G?"gap-1":"gap-2"),children:[ke?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:le?s.jsx(Q0,{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},PZ)})}):null,ve?s.jsx(G1,{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:c4(se,p)}),ge>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(tu,{className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:ge})]}):null]}),G?null:s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:[pe?s.jsx("span",{role:"button",tabIndex:0,onClick:Se=>{Se.stopPropagation(),j(re.id)},onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),Se.stopPropagation(),j(re.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":Z?"Collapse subsessions":"Expand subsessions",children:Z?s.jsx(Ls,{className:"h-3 w-3"}):s.jsx(Un,{className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:Kd(re.time?.updated||re.time?.created||Date.now())}),xe?s.jsxs("span",{className:"flex-shrink-0",children:[s.jsxs("span",{className:"text-status-success/80",children:["+",xe.additions]}),s.jsx("span",{className:"text-muted-foreground/60",children:"/"}),s.jsxs("span",{className:"text-status-error/80",children:["-",xe.deletions]})]}):null,re.share?s.jsx(t1,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,(Ae?.files??0)>0||pe?s.jsxs("span",{className:"flex items-center gap-2 flex-shrink-0",children:[(Ae?.files??0)>0?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[s.jsx(Xl,{className:"h-3 w-3 text-muted-foreground/70"}),s.jsx("span",{children:Ae.files})]})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsxs("p",{children:[Ae.files," changed ",Ae.files===1?"file":"files"]})})]}):null,pe?s.jsxs(Vt,{children:[s.jsx(Ut,{asChild:!0,children:s.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[s.jsx($r,{className:"h-3 w-3 text-muted-foreground/70"}),s.jsx("span",{children:n.children.length})]})}),s.jsx($t,{side:"bottom",sideOffset:4,children:s.jsxs("p",{children:[n.children.length," ",n.children.length===1?"sub-session":"sub-sessions"]})})]}):null]}):null,$?s.jsxs("span",{className:"inline-flex items-center gap-0.5 text-status-warning flex-shrink-0",children:[s.jsx(Co,{className:"h-3 w-3"}),"Missing"]}):null]})]})}),e[67]=M,e[68]=A,e[69]=pe,e[70]=Z,e[71]=G,e[72]=$,e[73]=ve,e[74]=le,e[75]=U,e[76]=n.children.length,e[77]=p,e[78]=ge,e[79]=a,e[80]=re.id,e[81]=re.share,e[82]=re.time?.created,e[83]=re.time?.updated,e[84]=xe,e[85]=fe,e[86]=Ae,e[87]=se,e[88]=ke,e[89]=j,e[90]=je):je=e[90];let We;e[91]!==G||e[92]!==U||e[93]!==Je?(We=Je&&!U?s.jsx("div",{className:J("absolute top-1/2 -translate-y-1/2 z-10",G?"right-7":"right-[30px]"),children:Je}):null,e[91]=G,e[92]=U,e[93]=Je,e[94]=We):We=e[94];const lt=U?"opacity-100":"opacity-0 group-hover:opacity-100 group-focus-within:opacity-100";let rt;e[95]!==lt?(rt=J("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",lt),e[95]=lt,e[96]=rt):rt=e[96];const Te=T===re.id;let Qe;e[97]!==re.id||e[98]!==H?(Qe=Se=>H(Se?re.id:null),e[97]=re.id,e[98]=H,e[99]=Qe):Qe=e[99];let pt;e[100]===Symbol.for("react.memo_cache_sentinel")?(pt=s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Session menu",onClick:TZ,onKeyDown:IZ,children:s.jsx(mo,{className:"h-3.5 w-3.5"})})}),e[100]=pt):pt=e[100];let St;e[101]!==P?(St=Se=>{P&&Se.preventDefault()},e[101]=P,e[102]=St):St=e[102];let Ht;e[103]!==re.id||e[104]!==se||e[105]!==k||e[106]!==w?(Ht=()=>{w(re.id),k(se)},e[103]=re.id,e[104]=se,e[105]=k,e[106]=w,e[107]=Ht):Ht=e[107];let Ke;e[108]===Symbol.for("react.memo_cache_sentinel")?(Ke=s.jsx(ao,{className:"mr-1 h-4 w-4"}),e[108]=Ke):Ke=e[108];let ye;e[109]!==Ht?(ye=s.jsxs(Qt,{onClick:Ht,className:"[&>svg]:mr-1",children:[Ke,"Rename"]}),e[109]=Ht,e[110]=ye):ye=e[110];let Ge;e[111]!==re.id||e[112]!==F?(Ge=()=>F(re.id),e[111]=re.id,e[112]=F,e[113]=Ge):Ge=e[113];let Ee;e[114]!==ve?(Ee=ve?s.jsx(ov,{className:"mr-1 h-4 w-4"}):s.jsx(G1,{className:"mr-1 h-4 w-4"}),e[114]=ve,e[115]=Ee):Ee=e[115];const $e=ve?"Unpin session":"Pin session";let tt;e[116]!==Ge||e[117]!==Ee||e[118]!==$e?(tt=s.jsxs(Qt,{onClick:Ge,className:"[&>svg]:mr-1",children:[Ee,$e]}),e[116]=Ge,e[117]=Ee,e[118]=$e,e[119]=tt):tt=e[119];let jt;e[120]!==D||e[121]!==E||e[122]!==B||e[123]!==I||e[124]!==re?(jt=re.share?s.jsxs(s.Fragment,{children:[s.jsx(Qt,{onClick:()=>{re.share?.url&&E(re.share.url,re.id)},className:"[&>svg]:mr-1",children:D===re.id?s.jsxs(s.Fragment,{children:[s.jsx(vs,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):s.jsxs(s.Fragment,{children:[s.jsx(Jn,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),s.jsxs(Qt,{onClick:()=>I(re.id),className:"[&>svg]:mr-1",children:[s.jsx(rv,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):s.jsxs(Qt,{onClick:()=>B(re),className:"[&>svg]:mr-1",children:[s.jsx(t1,{className:"mr-1 h-4 w-4"}),"Share"]}),e[120]=D,e[121]=E,e[122]=B,e[123]=I,e[124]=re,e[125]=jt):jt=e[125];let ct;e[126]!==O||e[127]!==ee||e[128]!==Q||e[129]!==_||e[130]!==R||e[131]!==z||e[132]!==re.id||e[133]!==fe?(ct=fe&&!ee?(()=>{const Se=_(fe),et=R(fe,re.id);return s.jsxs(s.Fragment,{children:[s.jsx(Rn,{}),s.jsxs(Bv,{children:[s.jsxs(Ev,{className:"[&>svg]:mr-1",children:[s.jsx(Tr,{className:"h-4 w-4"}),"Move to folder"]}),s.jsxs(Iv,{className:"min-w-[180px]",children:[Se.length===0?s.jsx(Qt,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):Se.map(qe=>s.jsxs(Qt,{onClick:()=>{et===qe.id?z(fe,re.id):O(fe,qe.id,re.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:qe.name}),et===qe.id?s.jsx(vs,{className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},qe.id)),s.jsx(Rn,{}),s.jsxs(Qt,{onClick:()=>{const qe=Q(fe);qe&&O(fe,qe.id,re.id)},children:[s.jsx(Xs,{className:"mr-1 h-4 w-4"}),"New folder..."]}),et?s.jsxs(Qt,{onClick:()=>{z(fe,re.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(_s,{className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]})]})})():null,e[126]=O,e[127]=ee,e[128]=Q,e[129]=_,e[130]=R,e[131]=z,e[132]=re.id,e[133]=fe,e[134]=ct):ct=e[134];let Xe;e[135]!==te||e[136]!==re.id||e[137]!==fe||e[138]!==se?(Xe=oe?null:s.jsxs(Qt,{disabled:!fe,onClick:()=>{fe&&te(fe,{mode:"chat",dedupeKey:`session:${re.id}`,label:se})},className:"[&>svg]:mr-1",children:[s.jsx(a2,{className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Side Panel"}),s.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:"beta"})]}),e[135]=te,e[136]=re.id,e[137]=fe,e[138]=se,e[139]=Xe):Xe=e[139];let At;e[140]===Symbol.for("react.memo_cache_sentinel")?(At=s.jsx(Rn,{}),e[140]=At):At=e[140];let yt;e[141]!==ee||e[142]!==W||e[143]!==re?(yt=()=>W(re,{archivedBucket:ee}),e[141]=ee,e[142]=W,e[143]=re,e[144]=yt):yt=e[144];let dt;e[145]===Symbol.for("react.memo_cache_sentinel")?(dt=s.jsx(Ln,{className:"mr-1 h-4 w-4"}),e[145]=dt):dt=e[145];const Tt=ee?"Delete":"Archive";let Zt;e[146]!==yt||e[147]!==Tt?(Zt=s.jsxs(Qt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:yt,children:[dt,Tt]}),e[146]=yt,e[147]=Tt,e[148]=Zt):Zt=e[148];let rs;e[149]!==St||e[150]!==ye||e[151]!==tt||e[152]!==jt||e[153]!==ct||e[154]!==Xe||e[155]!==Zt?(rs=s.jsxs(Os,{align:"end",className:"min-w-[180px]",onCloseAutoFocus:St,children:[ye,tt,jt,ct,Xe,At,Zt]}),e[149]=St,e[150]=ye,e[151]=tt,e[152]=jt,e[153]=ct,e[154]=Xe,e[155]=Zt,e[156]=rs):rs=e[156];let is;e[157]!==Te||e[158]!==Qe||e[159]!==rs?(is=s.jsxs(zs,{open:Te,onOpenChange:Qe,children:[pt,rs]}),e[157]=Te,e[158]=Qe,e[159]=rs,e[160]=is):is=e[160];let as;e[161]!==rt||e[162]!==is?(as=s.jsx("div",{className:rt,children:is}),e[161]=rt,e[162]=is,e[163]=as):as=e[163];let ps;e[164]!==nt||e[165]!==he||e[166]!==je||e[167]!==We||e[168]!==as?(ps=s.jsxs("div",{className:nt,onContextMenu:he,children:[je,We,as]}),e[164]=nt,e[165]=he,e[166]=je,e[167]=We,e[168]=as,e[169]=ps):ps=e[169];let xs;e[170]!==re.id||e[171]!==se||e[172]!==Ue||e[173]!==ps?(xs=s.jsx(aZ,{sessionId:Re,sessionDirectory:Ue,sessionTitle:se,children:ps}),e[170]=re.id,e[171]=se,e[172]=Ue,e[173]=ps,e[174]=xs):xs=e[174];let mt;e[175]!==ee||e[176]!==q||e[177]!==o||e[178]!==pe||e[179]!==Z||e[180]!==n.children||e[181]!==a||e[182]!==K||e[183]!==fe?(mt=pe&&Z?n.children.map(Se=>K(Se,q+1,fe??o,a,ee)):null,e[175]=ee,e[176]=q,e[177]=o,e[178]=pe,e[179]=Z,e[180]=n.children,e[181]=a,e[182]=K,e[183]=fe,e[184]=mt):mt=e[184];let It;return e[185]!==re.id||e[186]!==xs||e[187]!==mt?(It=s.jsxs(f.Fragment,{children:[xs,mt]},Ye),e[185]=re.id,e[186]=xs,e[187]=mt,e[188]=It):It=e[188],It}function IZ(t){return t.stopPropagation()}function TZ(t){return t.stopPropagation()}function PZ(t,e){return $9.has(e)?s.jsx("span",{className:"h-[3px] w-[3px] rounded-full bg-current animate-attention-diamond-pulse",style:{animationDelay:V9(e)}},e):s.jsx("span",{className:"h-[3px] w-[3px]"},e)}function RZ(t,e){return $9.has(e)?s.jsx("span",{className:"h-[3px] w-[3px] rounded-full bg-current animate-attention-diamond-pulse",style:{animationDelay:V9(e)}},e):s.jsx("span",{className:"h-[3px] w-[3px]"},e)}function LZ(t){return t.displayMode}function zZ(t){const e=Ce.c(38),{value:n,setValue:r,showDeletionDialog:o,setShowDeletionDialog:a,onConfirm:i}=t,l=!!n;let c;e[0]!==r?(c=M=>{M||r(null)},e[0]=r,e[1]=c):c=e[1];const d=n?.archivedBucket?"Delete session?":"Archive session?";let u;e[2]!==d?(u=s.jsx(Us,{children:d}),e[2]=d,e[3]=u):u=e[3];const m=n&&n.descendantCount>0?n.archivedBucket?`"${n.session.title||"Untitled Session"}" and its ${n.descendantCount} sub-task${n.descendantCount===1?"":"s"} will be permanently deleted.`:`"${n.session.title||"Untitled Session"}" and its ${n.descendantCount} sub-task${n.descendantCount===1?"":"s"} will be archived.`:n?.archivedBucket?`"${n?.session.title||"Untitled Session"}" will be permanently deleted.`:`"${n?.session.title||"Untitled Session"}" will be archived.`;let h;e[4]!==m?(h=s.jsx(tn,{children:m}),e[4]=m,e[5]=h):h=e[5];let p;e[6]!==u||e[7]!==h?(p=s.jsxs(Zs,{children:[u,h]}),e[6]=u,e[7]=h,e[8]=p):p=e[8];let g;e[9]!==a||e[10]!==o?(g=()=>a(!o),e[9]=a,e[10]=o,e[11]=g):g=e[11];const y=!o;let b;e[12]!==o?(b=o?s.jsx(Ho,{className:"h-4 w-4"}):s.jsx(zo,{className:"h-4 w-4 text-primary"}),e[12]=o,e[13]=b):b=e[13];let x;e[14]!==g||e[15]!==y||e[16]!==b?(x=s.jsxs("button",{type:"button",onClick:g,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":y,children:[b,"Never ask"]}),e[14]=g,e[15]=y,e[16]=b,e[17]=x):x=e[17];let v;e[18]!==r?(v=s.jsx("button",{type:"button",onClick:()=>r(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),e[18]=r,e[19]=v):v=e[19];let w;e[20]!==i?(w=()=>{i()},e[20]=i,e[21]=w):w=e[21];const C=n?.archivedBucket?"Delete":"Archive";let k;e[22]!==w||e[23]!==C?(k=s.jsx("button",{type:"button",onClick:w,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:C}),e[22]=w,e[23]=C,e[24]=k):k=e[24];let N;e[25]!==v||e[26]!==k?(N=s.jsxs("div",{className:"flex items-center gap-2",children:[v,k]}),e[25]=v,e[26]=k,e[27]=N):N=e[27];let S;e[28]!==x||e[29]!==N?(S=s.jsxs(vn,{className:"w-full sm:items-center sm:justify-between",children:[x,N]}),e[28]=x,e[29]=N,e[30]=S):S=e[30];let j;e[31]!==S||e[32]!==p?(j=s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[p,S]}),e[31]=S,e[32]=p,e[33]=j):j=e[33];let A;return e[34]!==l||e[35]!==c||e[36]!==j?(A=s.jsx($s,{open:l,onOpenChange:c,children:j}),e[34]=l,e[35]=c,e[36]=j,e[37]=A):A=e[37],A}function HZ(t){const e=Ce.c(19),{value:n,setValue:r,onConfirm:o}=t,a=!!n;let i;e[0]!==r?(i=y=>{y||r(null)},e[0]=r,e[1]=i):i=e[1];let l;e[2]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(Us,{children:"Delete folder?"}),e[2]=l):l=e[2];const c=n&&(n.subFolderCount>0||n.sessionCount>0)?`"${n.folderName}" will be deleted${n.subFolderCount>0?` along with ${n.subFolderCount} sub-folder${n.subFolderCount===1?"":"s"}`:""}. Sessions inside will not be deleted.`:`"${n?.folderName}" will be permanently deleted.`;let d;e[3]!==c?(d=s.jsxs(Zs,{children:[l,s.jsx(tn,{children:c})]}),e[3]=c,e[4]=d):d=e[4];let u;e[5]!==r?(u=s.jsx("button",{type:"button",onClick:()=>r(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),e[5]=r,e[6]=u):u=e[6];let m;e[7]!==o?(m=s.jsx("button",{type:"button",onClick:o,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"}),e[7]=o,e[8]=m):m=e[8];let h;e[9]!==u||e[10]!==m?(h=s.jsxs(vn,{children:[u,m]}),e[9]=u,e[10]=m,e[11]=h):h=e[11];let p;e[12]!==d||e[13]!==h?(p=s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[d,h]}),e[12]=d,e[13]=h,e[14]=p):p=e[14];let g;return e[15]!==a||e[16]!==i||e[17]!==p?(g=s.jsx($s,{open:a,onOpenChange:i,children:p}),e[15]=a,e[16]=i,e[17]=p,e[18]=g):g=e[18],g}const C6="oc.sessions.projectCollapse",M6="oc.sessions.groupOrder",A6="oc.sessions.groupCollapse",F6="oc.sessions.activeSessionByProject",D6="oc.sessions.expandedParents",_6="oc.sessions.pinned",OZ=t=>{const e=t?.pr;if(!e)return null;if(e.state==="merged")return"merged";if(e.state==="closed")return"closed";if(e.draft)return"draft";const n=t?.checks?.state==="failure",r=typeof e.mergeableState=="string"?e.mergeableState:"",o=e.mergeable===!1||r==="blocked"||r==="dirty";return n||o?"blocked":"open"},B6=t=>{switch(t){case"open":return 5;case"blocked":return 4;case"draft":return 3;case"merged":return 2;case"closed":return 1;default:return 0}},X0=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,hideProjectSelector:o=!0,showOnlyMainWorkspace:a=!1})=>{const[i,l]=f.useState(!1),[c,d]=f.useState(""),u=f.useRef(null),m=f.useRef(null),[h,p]=f.useState(null),[g,y]=f.useState(""),[b,x]=f.useState(null),[v,w]=f.useState(""),[C,k]=f.useState(new Set),[N,S]=f.useState(()=>new Map),j=f.useMemo(()=>Bn(),[]),[A,M]=f.useState(new Set),[F,B]=f.useState(new Map),[D,E]=f.useState(new Set),[I,T]=f.useState(null),[H,P]=f.useState(!1),[_,R]=f.useState(!1),[z,O]=f.useState(null),[Q,te]=f.useState(null),[W,U]=f.useState(""),[K,q]=f.useState(null),[ee,V]=f.useState(null),[G,Y]=f.useState(()=>{try{const He=Bn().getItem(_6);if(!He)return new Set;const gt=JSON.parse(He);return new Set(Array.isArray(gt)?gt.filter(ht=>typeof ht=="string"):[])}catch{return new Set}}),[oe,re]=f.useState(()=>{try{const He=Bn().getItem(A6);if(!He)return new Set;const gt=JSON.parse(He);return new Set(Array.isArray(gt)?gt.filter(ht=>typeof ht=="string"):[])}catch{return new Set}}),[fe,ie]=f.useState(()=>{try{const He=Bn().getItem(M6);if(!He)return new Map;const gt=JSON.parse(He),ht=new Map;return Object.entries(gt).forEach(([ms,Is])=>{Array.isArray(Is)&&ht.set(ms,Is.filter(Ps=>typeof Ps=="string"))}),ht}catch{return new Map}}),[de,$]=f.useState(()=>{try{const He=Bn().getItem(F6);if(!He)return new Map;const gt=JSON.parse(He),ht=new Map;return Object.entries(gt).forEach(([ms,Is])=>{typeof Is=="string"&&Is.length>0&&ht.set(ms,Is)}),ht}catch{return new Map}}),[L,X]=f.useState(!1),[ne,se]=f.useState(""),[pe,ae]=f.useState(new Map),ve=f.useRef(new Map),ce=f.useRef(0),Z=Ds(He=>He.homeDirectory),me=Ds(He=>He.currentDirectory),be=Ds(He=>He.setDirectory),we=ls(He=>He.projects),Ae=ls(He=>He.activeProjectId),Pe=ls(He=>He.addProject),xe=ls(He=>He.removeProject),_e=ls(He=>He.setActiveProjectIdOnly),ze=ls(He=>He.renameProject),le=De(He=>He.setActiveMainTab),ge=De(He=>He.openContextPanelTab),Fe=wn(),ke=De(He=>He.setSessionSwitcherOpen),Ze=De(He=>He.openMultiRunLauncher),Je=De(He=>He.notifyOnSubtasks),Ye=De(He=>He.showDeletionDialog),Re=De(He=>He.setShowDeletionDialog),Ue=Yt(He=>He.settingsAutoCreateWorktree),Ve=Kc(c,120),st=f.useMemo(()=>Ve.trim().toLowerCase(),[Ve]),at=st.length>0,nt=Er(He=>He.collapsedFolderIds),he=Er(He=>He.foldersMap),je=Er(He=>He.getFoldersForScope),We=Er(He=>He.createFolder),lt=Er(He=>He.renameFolder),rt=Er(He=>He.deleteFolder),Te=Er(He=>He.addSessionToFolder),Qe=Er(He=>He.removeSessionFromFolder),pt=Er(He=>He.toggleFolderCollapse),St=Er(He=>He.cleanupSessions),Ht=Er(He=>He.getSessionFolderId);MG({isSessionSearchOpen:i,setIsSessionSearchOpen:l,sessionSearchInputRef:m,sessionSearchContainerRef:u});const Ke=or(He=>He.directories),ye=Le(He=>He.sessions),Ge=Le(He=>He.archivedSessions),Ee=Le(He=>He.sessionsByDirectory),$e=Le(He=>He.currentSessionId),tt=Le(He=>!!He.newSessionDraft?.open),jt=Le(He=>He.setCurrentSession),ct=Le(He=>He.loadMessages),Xe=Le(He=>He.updateSessionTitle),At=Le(He=>He.shareSession),yt=Le(He=>He.unshareSession),dt=Le(He=>He.sessionMemoryState),Tt=Le(He=>He.sessionStatus),Zt=Le(He=>He.sessionAttentionStates),rs=Le(He=>He.permissions),is=Le(He=>He.worktreeMetadata),as=Le(He=>He.availableWorktreesByProject),ps=Le(He=>He.getSessionsByDirectory),xs=Le(He=>He.openNewSessionDraft),mt=jo(He=>He.entries),It=f.useMemo(()=>Gs(),[]),Se=f.useMemo(()=>Xn(),[]),et=f.useMemo(()=>ln(),[]),{buildGroupSearchText:qe,filterSessionNodesForSearch:bt,buildGroupedSessions:Rt}=CG({homeDirectory:Z,worktreeMetadata:is,pinnedSessionIds:G,gitDirectories:Ke,isVSCode:et}),{scheduleCollapsedProjectsPersist:Nt}=RG({isVSCode:et,safeStorage:j,keys:{sessionExpanded:D6,projectCollapse:C6,sessionPinned:_6,groupOrder:M6,projectActiveSession:F6,groupCollapse:A6},sessions:ye,pinnedSessionIds:G,setPinnedSessionIds:Y,groupOrderByProject:fe,activeSessionByProject:de,collapsedGroups:oe,setExpandedParents:k,setCollapsedProjects:M}),Pt=f.useCallback(He=>{Y(gt=>{const ht=new Set(gt);return ht.has(He)?ht.delete(He):ht.add(He),ht})},[]),Jt=f.useMemo(()=>[...ye].sort((He,gt)=>Bc(He,gt,G)),[ye,G]);_G({currentSessionId:$e,sortedSessions:Jt,loadMessages:ct});const Wt=f.useMemo(()=>{const He=new Map;return Jt.forEach(gt=>{const ht=gt.parentID;if(!ht)return;const ms=He.get(ht)??[];ms.push(gt),He.set(ht,ms)}),He.forEach(gt=>gt.sort((ht,ms)=>Bc(ht,ms,G))),He},[Jt,G]);BG({sortedSessions:Jt,projects:we,directoryStatus:N,setDirectoryStatus:S});const Ie=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."})]}),wt=f.useCallback(()=>{b&&v.trim()&&(ze(b,v.trim()),x(null),w(""))},[b,v,ze]),Ot=f.useCallback(()=>{x(null),w("")},[]),Lt=Le(He=>He.deleteSession),Kt=Le(He=>He.deleteSessions),Ct=Le(He=>He.archiveSession),Xt=Le(He=>He.archiveSessions),{copiedSessionId:Ss,handleSessionSelect:cs,handleSessionDoubleClick:en,handleSaveEdit:Ys,handleCancelEdit:kn,handleShareSession:on,handleCopyShareUrl:Ks,handleUnshareSession:Ws,handleDeleteSession:hn,confirmDeleteSession:Tn}=IG({activeProjectId:Ae,currentDirectory:me,currentSessionId:$e,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:i,sessionSearchQuery:c,setSessionSearchQuery:d,setIsSessionSearchOpen:l,setActiveProjectIdOnly:_e,setDirectory:be,setActiveMainTab:le,setSessionSwitcherOpen:ke,setCurrentSession:jt,updateSessionTitle:Xe,shareSession:At,unshareSession:yt,deleteSession:Lt,deleteSessions:Kt,archiveSession:Ct,archiveSessions:Xt,childrenMap:Wt,showDeletionDialog:Ye,setDeleteSessionConfirm:q,deleteSessionConfirm:K,setEditingId:p,setEditTitle:y,editingId:h,editTitle:g}),yn=f.useCallback(()=>{if(!ee)return;const{scopeKey:He,folderId:gt}=ee;V(null),rt(He,gt)},[ee,rt]),Zn=f.useCallback(()=>{if(!It||!ar()){ia.requestDirectoryDialog();return}cr(async()=>{const{requestDirectoryAccess:He}=await Promise.resolve().then(()=>_v);return{requestDirectoryAccess:He}},void 0).then(({requestDirectoryAccess:He})=>He("")).then(He=>{He.success&&He.path?Pe(He.path,{id:He.projectId})||ue.error("Failed to add project",{description:"Please select a valid directory."}):He.error&&He.error!=="Directory selection cancelled"&&ue.error("Failed to select directory",{description:He.error})}).catch(He=>{console.error("Desktop: Error selecting directory:",He),ue.error("Failed to select directory")})},[Pe,It]),lr=f.useCallback(He=>{k(gt=>{const ht=new Set(gt);ht.has(He)?ht.delete(He):ht.add(He);try{j.setItem(D6,JSON.stringify(Array.from(ht)))}catch{}return ht})},[j]),qn=f.useCallback((He,gt)=>{if(!He)return null;gt&&nt.has(gt)&&pt(gt);const ht=We(He,"New folder",gt);return te(ht.id),U(ht.name),ht},[nt,pt,We]),Pn=f.useCallback(He=>{E(gt=>{const ht=new Set(gt);return ht.has(He)?ht.delete(He):ht.add(He),ht})},[]),er=f.useCallback(He=>{ce.current=Date.now()+150,M(gt=>{const ht=new Set(gt);ht.has(He)?ht.delete(He):ht.add(He);try{j.setItem(C6,JSON.stringify(Array.from(ht)))}catch{}return et||Nt(ht),ht})},[et,j,Nt]),On=f.useMemo(()=>we.map(He=>({...He,normalizedPath:rn(He.path)})).filter(He=>!!He.normalizedPath),[we]);$G({projects:we,normalizedProjects:On,normalizePath:rn,gitDirectories:Ke,setProjectRepoStatus:B,setProjectRootBranches:ae});const ut=Le(He=>He.isLoading);YG({isSessionsLoading:ut,sessions:ye,archivedSessions:Ge,normalizedProjects:On,isVSCode:et,availableWorktreesByProject:as,cleanupSessions:St});const{getSessionsForProject:Dt,getArchivedSessionsForProject:vt}=qG({isVSCode:et,sessions:ye,archivedSessions:Ge,sessionsByDirectory:Ee,getSessionsByDirectory:ps,availableWorktreesByProject:as});yG({normalizedProjects:On,sessions:ye,archivedSessions:Ge,availableWorktreesByProject:as,isVSCode:et,isSessionsLoading:ut,foldersMap:he,createFolder:We,addSessionToFolder:Te,cleanupSessions:St});const qt=f.useRef(!1);Ae&&F.has(Ae)&&(qt.current=!!F.get(Ae));const{projectSections:ds,groupSearchDataByGroup:js,sectionsForRender:ss,searchMatchCount:Cs}=vG({normalizedProjects:On,activeProjectId:Ae,getSessionsForProject:Dt,getArchivedSessionsForProject:vt,availableWorktreesByProject:as,projectRepoStatus:F,projectRootBranches:pe,lastRepoStatus:qt.current,buildGroupedSessions:Rt,hasSessionSearchQuery:at,normalizedSessionSearchQuery:st,filterSessionNodesForSearch:bt,buildGroupSearchText:qe,getFoldersForScope:je}),gs=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),s.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),ks=f.useMemo(()=>On.find(He=>He.id===Ae)??On[0]??null,[On,Ae]),Ms=f.useMemo(()=>ks?{id:ks.id,path:ks.normalizedPath}:null,[ks]),ns=f.useMemo(()=>ks?!!F.get(ks.id):!1,[ks,F]),ys=ks&&F.has(ks.id)?ns:qt.current,an=!!ks,sn=t||Fe.isMobile;f.useEffect(()=>{ks||R(!1)},[ks]);const{currentSessionDirectory:Oe}=jG({projectSections:ds,activeProjectId:Ae,activeSessionByProject:de,setActiveSessionByProject:$,currentSessionId:$e,handleSessionSelect:cs,isVSCode:et,newSessionDraftOpen:tt,mobileVariant:t,openNewSessionDraft:xs,setActiveMainTab:le,setSessionSwitcherOpen:ke,sessions:ye,worktreeMetadata:is}),{getOrderedGroups:it}=SG(fe),xt=f.useCallback(()=>{ks&&(se(J0(ks.label?.trim()||fo(ks.normalizedPath,Z)||ks.normalizedPath)),X(!0))},[ks,Z]),Ft=f.useCallback(()=>{if(!ks)return;const He=ne.trim();He&&(ze(ks.id,He),X(!1))},[ks,ne,ze]),pn=t?"inline-flex h-6 w-6 cursor-pointer 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 disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Gn="h-4.5 w-4.5",jn=J("inline-flex cursor-pointer items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",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",!Se&&"bg-transparent hover:bg-sidebar/40"),Cr=tZ({isDesktopShellRuntime:Se,projectSections:ds,projectHeaderSentinelRefs:ve}),Me=f.useCallback((He,gt=0,ht,ms,Is=!1)=>s.jsx(EZ,{node:He,depth:gt,groupDirectory:ht,projectId:ms,archivedBucket:Is,directoryStatus:N,sessionMemoryState:dt,currentSessionId:$e,pinnedSessionIds:G,expandedParents:C,hasSessionSearchQuery:at,normalizedSessionSearchQuery:st,sessionAttentionStates:Zt,notifyOnSubtasks:Je,sessionStatus:Tt,permissions:rs,editingId:h,setEditingId:p,editTitle:g,setEditTitle:y,handleSaveEdit:Ys,handleCancelEdit:kn,toggleParent:lr,handleSessionSelect:cs,handleSessionDoubleClick:en,togglePinnedSession:Pt,handleShareSession:on,copiedSessionId:Ss,handleCopyShareUrl:Ks,handleUnshareSession:Ws,openMenuSessionId:z,setOpenMenuSessionId:O,renamingFolderId:Q,getFoldersForScope:je,getSessionFolderId:Ht,removeSessionFromFolder:Qe,addSessionToFolder:Te,createFolderAndStartRename:qn,openContextPanelTab:ge,handleDeleteSession:hn,mobileVariant:t,renderSessionNode:Me}),[N,dt,$e,G,C,at,st,Zt,Je,Tt,rs,h,p,g,y,Ys,kn,lr,cs,en,Pt,on,Ss,Ks,Ws,z,O,Q,je,Ht,Qe,Te,qn,ge,hn,t]),ft=f.useCallback(He=>{re(gt=>{const ht=new Set(gt);return ht.has(He)?ht.delete(He):ht.add(He),ht})},[]),Bt=f.useMemo(()=>{const He=new Map;return Object.values(mt).forEach(gt=>{const ht=rn(gt.params?.directory??gt.identity?.directory??null),ms=gt.params?.branch?.trim()??gt.identity?.branch?.trim();if(!ht||!ms)return;const Is=OZ(gt.status??null),Ps=gt.status?.pr;if(!Is||!Ps?.number)return;const nn=`${ht}::${ms}`,As={visualState:Is,number:Ps.number,url:typeof Ps.url=="string"&&Ps.url.trim().length>0?Ps.url:null,state:Ps.state,draft:!!Ps.draft,title:typeof Ps.title=="string"&&Ps.title.trim().length>0?Ps.title:null,base:typeof Ps.base=="string"&&Ps.base.trim().length>0?Ps.base:null,head:typeof Ps.head=="string"&&Ps.head.trim().length>0?Ps.head:null,checks:gt.status?.checks?{state:gt.status.checks.state,total:gt.status.checks.total,success:gt.status.checks.success,failure:gt.status.checks.failure,pending:gt.status.checks.pending}:null,canMerge:typeof gt.status?.canMerge=="boolean"?gt.status.canMerge:null,mergeableState:typeof Ps.mergeableState=="string"?Ps.mergeableState:null,repo:gt.status?.repo?{owner:gt.status.repo.owner,repo:gt.status.repo.repo}:null},Fs=He.get(nn);(!Fs||B6(As.visualState)>B6(Fs.visualState))&&He.set(nn,As)}),He},[mt]),es=f.useCallback((He,gt,ht,ms)=>s.jsx(cZ,{group:He,groupKey:gt,projectId:ht,hideGroupLabel:ms,hasSessionSearchQuery:at,normalizedSessionSearchQuery:st,groupSearchDataByGroup:js,expandedSessionGroups:D,collapsedGroups:oe,hideDirectoryControls:r,getFoldersForScope:je,collapsedFolderIds:nt,toggleFolderCollapse:pt,renameFolder:lt,deleteFolder:rt,showDeletionDialog:Ye,setDeleteFolderConfirm:V,renderSessionNode:Me,currentSessionDirectory:Oe,projectRepoStatus:F,lastRepoStatus:qt.current,toggleGroupSessionLimit:Pn,mobileVariant:t,activeProjectId:Ae,setActiveProjectIdOnly:_e,setActiveMainTab:le,setSessionSwitcherOpen:ke,openNewSessionDraft:xs,addSessionToFolder:Te,createFolderAndStartRename:qn,renamingFolderId:Q,renameFolderDraft:W,setRenameFolderDraft:U,setRenamingFolderId:te,pinnedSessionIds:G,prVisualStateByDirectoryBranch:Bt,onToggleCollapsedGroup:ft}),[at,st,js,D,oe,r,je,nt,pt,lt,rt,Ye,Me,Oe,F,Pn,t,Ae,_e,le,ke,xs,Te,qn,Q,W,G,Bt,ft]);return s.jsxs("div",{ref:u,className:J("flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(bZ,{hideDirectoryControls:r,hideProjectSelector:o,activeProjectForHeader:ks,homeDirectory:Z,normalizedProjects:On,activeProjectId:Ae,setActiveProjectIdOnly:_e,isProjectRenameInline:L,setIsProjectRenameInline:X,handleStartInlineProjectRename:xt,handleSaveInlineProjectRename:Ft,projectRenameDraft:ne,setProjectRenameDraft:se,removeProject:xe,handleOpenDirectoryDialog:Zn,addProjectButtonClass:jn,headerActionIconClass:Gn,reserveHeaderActionsSpace:an,stableActiveProjectIsRepo:ys,useMobileNotesPanel:sn,projectNotesPanelOpen:_,setProjectNotesPanelOpen:R,activeProjectRefForHeader:Ms,openMultiRunLauncher:Ze,headerActionButtonClass:pn,setNewWorktreeDialogOpen:P,setActiveMainTab:le,isSessionSearchOpen:i,setIsSessionSearchOpen:l,sessionSearchInputRef:m,sessionSearchQuery:c,setSessionSearchQuery:d,hasSessionSearchQuery:at,searchMatchCount:Cs}),s.jsx(CZ,{sectionsForRender:ss,projectSections:ds,activeProjectId:Ae,showOnlyMainWorkspace:a,hasSessionSearchQuery:at,emptyState:Ie,searchEmptyState:gs,renderGroupSessions:es,homeDirectory:Z,collapsedProjects:A,hideDirectoryControls:r,projectRepoStatus:F,hoveredProjectId:I,setHoveredProjectId:T,isDesktopShellRuntime:Se,stuckProjectHeaders:Cr,mobileVariant:t,toggleProject:er,setActiveProjectIdOnly:_e,setActiveMainTab:le,setSessionSwitcherOpen:ke,openNewSessionDraft:xs,createWorktreeSession:_2,openMultiRunLauncher:Ze,setEditingProjectId:x,setEditProjectTitle:w,editingProjectId:b,editProjectTitle:v,handleSaveProjectEdit:wt,handleCancelProjectEdit:Ot,removeProject:xe,projectHeaderSentinelRefs:ve,settingsAutoCreateWorktree:Ue,getOrderedGroups:it,setGroupOrderByProject:ie}),s.jsx(dG,{open:H,onOpenChange:P,onWorktreeCreated:(He,gt)=>{if(le("chat"),t&&ke(!1),gt?.sessionId){jt(gt.sessionId);return}xs({directoryOverride:He})}}),sn?s.jsx(rr,{open:_,onClose:()=>R(!1),title:"Project notes",children:s.jsx(O9,{projectRef:Ms,canCreateWorktree:ys,onActionComplete:()=>R(!1),className:"p-0"})}):null,s.jsx(zZ,{value:K,setValue:q,showDeletionDialog:Ye,setShowDeletionDialog:Re,onConfirm:Tn}),s.jsx(HZ,{value:ee,setValue:V,onConfirm:yn})]})},T2=()=>{const t=Ce.c(13),[e,n]=Ne.useState(!1);let r,o;t[0]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{n(Gs())},o=[],t[0]=r,t[1]=o):(r=t[0],o=t[1]),Ne.useEffect(r,o);let a;t[2]!==e?(a=async h=>e?await Oc(h):{success:!0,path:h},t[2]=e,t[3]=a):a=t[3];const i=a;let l;t[4]!==e?(l=async h=>e?await Vp():{success:!0},t[4]=e,t[5]=l):l=t[5];const c=l;let d;t[6]!==e?(d=async h=>e?await Up():{success:!0},t[6]=e,t[7]=d):d=t[7];const u=d;let m;return t[8]!==e||t[9]!==i||t[10]!==c||t[11]!==u?(m={isDesktop:e,requestAccess:i,startAccessing:c,stopAccessing:u},t[8]=e,t[9]=i,t[10]=c,t[11]=u,t[12]=m):m=t[12],m},E6=({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:u=!1})=>{const{isMobile:m}=wn(),[h,p]=f.useState([]),[g,y]=f.useState(new Set),[b,x]=f.useState(!0),[v,w]=f.useState(!1),[C,k]=f.useState(""),[N,S]=f.useState(new Set),[j,A]=f.useState(null),[M,F]=f.useState(""),[B,D]=f.useState(!0),E=f.useRef(null),{requestAccess:I,startAccessing:T,isDesktop:H}=T2(),P=f.useRef(l),_=f.useCallback(L=>{if(!L)return L;if(L==="/"||L.length===0)return"/";let X=L;for(;X.length>1&&X.endsWith("/");)X=X.slice(0,-1);return X.length===0?"/":X},[]),R=f.useMemo(()=>{if(!C)return null;const L=C.replace(/\\/g,"/");return _(L)},[C,_]),z=f.useMemo(()=>{if(typeof c=="string"&&c.length>0){const L=c.replace(/\\/g,"/"),X=_(L);if(X&&X!=="/")return X}return R&&R!=="/"?R:null},[c,R,_]),O=f.useMemo(()=>typeof d=="boolean"?!!(d&&z):!!z,[d,z]);f.useEffect(()=>{O||(x(!0),p([]))},[O]);const Q=f.useCallback(L=>{if(!L||!O||!z)return!1;const X=L.replace(/\\/g,"/"),ne=_(X)??X;if(ne===z)return!0;const se=`${z}/`;return ne.startsWith(se)},[O,z,_]),te=async L=>{if(O){if(a==="deferred"){e(L);return}if(H){const X=await I(L);X.success&&X.path?(await T(X.path),e(X.path)):(console.error("Failed to get directory access:",X.error),e(L))}else e(L)}};f.useEffect(()=>{let L=!1;const X=pe=>{if(!pe)return!1;const ae=_(pe.replace(/\\/g,"/"));return!ae||ae==="/"?!1:(k(typeof ae=="string"?ae:pe.replace(/\\/g,"/")),!0)};return c&&X(c)||(async()=>{try{const pe=await zt.getFilesystemHome();if(!L&&X(pe))return}catch(pe){console.warn("Failed to resolve filesystem home directory:",pe)}try{const pe=await zt.getSystemInfo();if(!L&&X(pe?.homeDirectory))return}catch(pe){console.warn("Failed to resolve home directory from system info:",pe)}})(),()=>{L=!0}},[c,_]),f.useEffect(()=>{let L=!1;const X=ae=>{if(L)return;const ve=ae.filter(ce=>typeof ce=="string"&&ce.length>0).map(ce=>{const Z=ce.replace(/\\/g,"/");return _(Z)??Z});S(new Set(ve))},ne=()=>{try{const ae=localStorage.getItem("pinnedDirectories");if(!ae)return;const ve=JSON.parse(ae);Array.isArray(ve)&&X(ve)}catch(ae){console.warn("Failed to load pinned directories from local storage:",ae)}},se=async()=>{try{let ae=[];const ve=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(ve.ok){const ce=await ve.json();ae=Array.isArray(ce?.pinnedDirectories)?ce.pinnedDirectories:[]}if(L)return;X(ae)}catch(ae){console.warn("Failed to load pinned directories:",ae)}};ne();const pe=ae=>{const ve=ae.detail;ve&&Array.isArray(ve.pinnedDirectories)&&X(ve.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",pe),se(),()=>{L=!0,window.removeEventListener("openchamber:settings-synced",pe)}},[_]);const W=f.useRef(!0);f.useEffect(()=>{if(W.current){W.current=!1;return}const L={pinnedDirectories:Array.from(N)};Rs(L)},[N]),f.useEffect(()=>{z&&S(L=>{const X=Array.from(L).map(ne=>_(ne.replace(/\\/g,"/"))??ne).filter(ne=>Q(ne));return new Set(X)})},[z,Q,_]),f.useEffect(()=>{P.current!==l&&(P.current=l)},[l]);const U=L=>{S(X=>{if(!Q(L))return X;const ne=_(L.replace(/\\/g,"/"))??L.replace(/\\/g,"/"),se=new Set(X);return se.has(ne)?se.delete(ne):se.add(ne),se})},K=f.useMemo(()=>Array.from(N).map(L=>_(L.replace(/\\/g,"/"))??L).filter(L=>Q(L)).map(L=>({path:L,name:L.split("/").pop()||L})).sort((L,X)=>L.name.localeCompare(X.name)),[N,Q,_]),q=f.useCallback(async L=>{const X=ve=>l||!ve.startsWith("."),ne=z;if(!O||!ne)return[];const se=L&&L.length>0?L:ne,pe=se?se.replace(/\\/g,"/"):null,ae=pe?_(pe)??pe:null;if(ae){const ve=`${ne}/`;if(!(ae===ne||ae.startsWith(ve)))return[]}try{return(await zt.listLocalDirectory(L)).filter(ce=>{if(!ce.isDirectory||!X(ce.name))return!1;const Z=ce.path.replace(/\\/g,"/"),me=_(Z)??Z,be=me===ne?ne:`${ne}/`;return me===ne||me.startsWith(be)}).map(ce=>({name:ce.name,path:ce.path.replace(/\\/g,"/"),isDirectory:!0})).sort((ce,Z)=>ce.name.localeCompare(Z.name))}catch{try{const ce=await zt.getApiClient().file.list({path:".",directory:L});return ce.data?ce.data.filter(Z=>{if(Z.type!=="directory"||!Z.name||!X(Z.name))return!1;const me=String(Z.absolute||Z.path||Z.name).replace(/\\/g,"/"),be=_(me)??me,we=be===ne?ne:`${ne}/`;return be===ne||be.startsWith(we)}).map(Z=>({name:Z.name||"",path:String(Z.absolute||Z.path||Z.name).replace(/\\/g,"/"),isDirectory:!0})).filter(Z=>Z.name!=="").sort((Z,me)=>Z.name.localeCompare(me.name)):[]}catch{return[]}}},[l,z,_,O]),ee=f.useRef(!1),V=f.useCallback(async()=>{if(!O||!z){x(!0),p([]);return}ee.current||x(!0);try{const L=await q(z);p(L),ee.current=!0}catch{}finally{x(!1)}},[O,z,q]);f.useEffect(()=>{O&&(r==="inline"||v)&&V()},[r,v,O,V]);const G=async L=>{if(!O)return;const X=g.has(L.path),ne=new Set(g);if(X){ne.delete(L.path),y(ne);return}ne.add(L.path),y(ne);const se=await q(L.path),pe=ae=>ae.map(ve=>ve.path===L.path?{...ve,children:se}:ve.children?{...ve,children:pe(ve.children)}:ve);p(ae=>pe(ae))};f.useEffect(()=>{j&&E.current&&(E.current.focus(),E.current.select())},[j]);const Y=(L,X=[])=>{const ne="new_directory",se=X.map(ce=>ce.name);if(!se.includes(ne))return ne;let pe=1;const ae=new RegExp(`^${ne}(\\d+)$`);for(const ce of se){const Z=ce.match(ae);if(Z){const me=parseInt(Z[1],10);me>pe&&(pe=me)}}let ve=2;for(;se.includes(`${ne}${ve}`);)ve++;return`${ne}${Math.max(ve,pe+1)}`},oe=async L=>{if(O){if(g.has(L.path)){const X=Y(L.path,L.children);F(X)}else{const X=new Set(g);if(X.add(L.path),y(X),L.children){const ne=Y(L.path,L.children);F(ne)}else{const ne=await q(L.path),se=ae=>ae.map(ve=>ve.path===L.path?{...ve,children:ne}:ve.children?{...ve,children:se(ve.children)}:ve);p(ae=>se(ae));const pe=Y(L.path,ne);F(pe)}}A(L.path)}},re=async()=>{if(!j||!O)return;const L=M.trim()||"new_directory",X=`${j}/${L}`;try{await zt.createDirectory(X,{allowOutsideWorkspace:!0});const ne=await q(j),se=pe=>pe.map(ae=>ae.path===j?{...ae,children:ne}:ae.children?{...ae,children:se(ae.children)}:ae);p(pe=>se(pe)),A(null),F("")}catch(ne){console.error("Failed to create directory:",ne)}},fe=()=>{A(null),F("")},ie=(L,X=0)=>{const ne=g.has(L.path),se=L.isDirectory,pe=N.has(L.path),ae=t===L.path,ve=r==="inline",ce=s.jsxs(s.Fragment,{children:[se&&s.jsx("button",{onClick:Z=>{Z.stopPropagation(),G(L)},className:J("hover:bg-interactive-hover rounded","p-0.5"),children:ne?s.jsx(Ls,{className:m?"h-3.5 w-3.5":"h-3 w-3"}):s.jsx(Un,{className:m?"h-3.5 w-3.5":"h-3 w-3"})}),!se&&s.jsx("div",{className:m?"w-4.5":"w-4"}),s.jsxs("button",{onClick:Z=>{Z.stopPropagation(),te(L.path),r==="dropdown"&&a==="immediate"&&w(!1)},onDoubleClick:Z=>{Z.stopPropagation(),i&&i(L.path)},className:J("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",ve&&ae?"text-primary":"text-foreground"),children:[s.jsx(ya,{className:J("text-muted-foreground flex-shrink-0",m?"h-4 w-4":"h-3.5 w-3.5",ve&&ae&&"text-primary")}),s.jsx("span",{className:J("font-medium truncate","typography-ui-label",ve&&ae?"text-primary":"text-foreground"),children:L.name})]}),s.jsx("button",{onClick:Z=>{Z.stopPropagation(),oe(L)},className:J("hover:bg-interactive-hover rounded transition-opacity",m?"p-1.5":"p-1",u?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:s.jsx(Xs,{className:J("text-muted-foreground",m?"h-3.5 w-3.5":"h-3 w-3")})}),s.jsx("button",{onClick:Z=>{Z.stopPropagation(),U(L.path)},className:J("hover:bg-interactive-hover rounded transition-opacity",m?"p-1.5":"p-1",u?"opacity-60":"opacity-0 group-hover:opacity-100"),title:pe?"Unpin directory":"Pin directory",children:pe?s.jsx(L2,{className:J("text-primary",m?"h-3.5 w-3.5":"h-3 w-3")}):s.jsx(G1,{className:J("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:J("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",ae?"bg-primary/10 text-primary":"hover:bg-interactive-hover/50 text-foreground"),style:{paddingLeft:`${X*(m?12:14)+(m?4:6)}px`},children:ce}),ne&&s.jsxs(s.Fragment,{children:[j===L.path&&s.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(X+1)*14+6}px`},children:[s.jsx("div",{className:"w-4"}),s.jsx(ya,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(ts,{ref:E,value:M,onChange:Z=>F(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"?(Z.preventDefault(),Z.stopPropagation(),re()):Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),fe())},onBlur:re,className:"h-6 typography-meta flex-1 selection:bg-interactive-selection selection:text-interactive-selection-foreground",placeholder:"new_directory"}),s.jsx("button",{onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),re()},className:"p-1 hover:bg-interactive-hover rounded",title:"Create directory",children:s.jsx(vs,{className:"h-3 w-3 text-green-600"})}),s.jsx("button",{onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),fe()},className:"p-1 hover:bg-interactive-hover rounded",title:"Cancel",children:s.jsx(_s,{className:"h-3 w-3 text-muted-foreground"})})]}),L.children&&L.children.map(Z=>ie(Z,X+1))]})]},L.path):s.jsxs("div",{children:[s.jsxs(Qt,{className:J("flex items-center gap-1 cursor-pointer group",t===L.path&&"bg-interactive-selection"),style:{paddingLeft:`${X*12+8}px`},onSelect:Z=>{Z.preventDefault()},children:[se&&s.jsx("button",{onClick:Z=>{Z.stopPropagation(),G(L)},className:"p-0.5 hover:bg-interactive-hover rounded",children:ne?s.jsx(Ls,{className:"h-3 w-3"}):s.jsx(Un,{className:"h-3 w-3"})}),!se&&s.jsx("div",{className:"w-4"}),ce]}),ne&&s.jsxs("div",{children:[j===L.path&&s.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(X+1)*12+8}px`},children:[s.jsx("div",{className:"w-4"}),s.jsx(ya,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(ts,{ref:E,value:M,onChange:Z=>F(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"?(Z.preventDefault(),Z.stopPropagation(),re()):Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),fe())},onBlur:re,className:"h-6 typography-meta flex-1 selection:bg-interactive-selection selection:text-interactive-selection-foreground",placeholder:"new_directory"}),s.jsx("button",{onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),re()},className:"p-1 hover:bg-interactive-hover rounded",title:"Create directory",children:s.jsx(vs,{className:"h-3 w-3 text-green-600"})}),s.jsx("button",{onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),fe()},className:"p-1 hover:bg-interactive-hover rounded",title:"Cancel",children:s.jsx(_s,{className:"h-3 w-3 text-muted-foreground"})})]}),L.children&&L.children.map(Z=>ie(Z,X+1))]})]},L.path)},de=(L,X)=>{if(r==="inline"){const ne=t===X;return s.jsxs("div",{className:J("group flex items-center gap-2 mx-1 rounded-lg transition-colors",m?"px-1.5 py-1":"px-2 py-1.5",ne?"bg-primary/10":"hover:bg-interactive-hover/50"),children:[s.jsxs("button",{onClick:()=>te(X),onDoubleClick:se=>{se.stopPropagation(),i&&i(X)},className:J("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",ne?"text-primary":"text-foreground"),children:[s.jsx(ya,{className:J("flex-shrink-0",m?"h-4 w-4":"h-3.5 w-3.5",ne?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:J("typography-ui-label font-medium truncate flex-shrink-0",ne?"text-primary":"text-foreground"),children:L}),s.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:na(X,C)})]}),s.jsx("button",{onClick:()=>U(X),className:J("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(L2,{className:J("text-primary","h-3.5 w-3.5")})})]},X)}return s.jsxs(Qt,{onSelect:ne=>{ne.preventDefault(),te(X),a==="immediate"&&w(!1)},className:J("flex items-start gap-2 cursor-pointer group py-2",t===X&&"bg-interactive-selection"),children:[s.jsx(ya,{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:L}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:na(X,C)})]}),s.jsx("button",{onClick:ne=>{ne.stopPropagation(),ne.preventDefault(),U(X)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-interactive-hover rounded transition-opacity",title:"Unpin directory",children:s.jsx(L2,{className:"h-3 w-3 text-primary"})})]},X)},$=s.jsx(s.Fragment,{children:O?s.jsxs(s.Fragment,{children:[K.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>D(L=>!L),className:J("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:[B?s.jsx(Ls,{className:m?"h-3.5 w-3.5":"h-3 w-3"}):s.jsx(Un,{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:K.length})]}),B&&K.map(({name:L,path:X})=>de(L,X)),r==="dropdown"&&s.jsx(Rn,{}),r==="inline"&&B&&s.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),s.jsx("div",{className:J("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"}),b?s.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):h.map(L=>ie(L)),!b&&h.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:J("overflow-hidden flex flex-col",o),children:s.jsx(Ns,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:$})}):s.jsxs(zs,{open:v,onOpenChange:w,children:[s.jsx(Hs,{asChild:!0,children:s.jsxs(ot,{variant:"ghost",className:J("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(ya,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"truncate",title:t,children:na(t,C)})]}),s.jsx(Ls,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(Os,{align:"start",className:"w-[350px]",children:s.jsx(Ns,{outerClassName:"h-full",className:"w-full",children:$})})]})},U9=f.forwardRef((t,e)=>{const n=Ce.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[u,m]=f.useState(d),[h,p]=f.useState(!1),[g,y]=f.useState(0),b=f.useRef(null);let x;n[1]===Symbol.for("react.memo_cache_sentinel")?(x=[],n[1]=x):x=n[1];const v=f.useRef(x),w=$Z;let C;n[2]!==o?(C=te=>te.startsWith("~")&&o?te.replace(/^~/,o):te,n[2]=o,n[3]=C):C=n[3];const k=C;let N;n[4]!==k?(N=te=>{const W=k(te);if(W.endsWith("/"))return W;const U=W.lastIndexOf("/");return U===-1?"":U===0?"/":W.substring(0,U+1)},n[4]=k,n[5]=N):N=n[5];const S=N;let j;n[6]!==k?(j=te=>{const W=k(te);if(W.endsWith("/"))return"";const U=W.lastIndexOf("/");return U===-1?W:W.substring(U+1)},n[6]=k,n[7]=j):j=n[7];const A=j,M=Kc(r,150);let F,B;n[8]!==M||n[9]!==S||n[10]!==A||n[11]!==c||n[12]!==i?(F=()=>{if(!i||!M){m([]);return}const te=S(M),W=A(M).toLowerCase();if(!te){m([]);return}let U=!1;return p(!0),zt.listLocalDirectory(te).then(K=>{if(U)return;const q=K.filter(V=>!(!V.isDirectory||!c&&V.name.startsWith("."))),ee=W?q.map(V=>{const G=w(W,V.name);return G!==null?{entry:V,score:G}:null}).filter(VZ).sort(UZ).map(WZ):q.sort(qZ);m(ee.slice(0,10)),y(0)}).catch(()=>{U||m([])}).finally(()=>{U||p(!1)}),()=>{U=!0}},B=[i,M,S,A,c,w],n[8]=M,n[9]=S,n[10]=A,n[11]=c,n[12]=i,n[13]=F,n[14]=B):(F=n[13],B=n[14]),f.useEffect(F,B);let D,E;n[15]!==g?(D=()=>{v.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},E=[g],n[15]=g,n[16]=D,n[17]=E):(D=n[16],E=n[17]),f.useEffect(D,E);let I,T;n[18]!==l||n[19]!==i?(I=()=>{if(!i)return;const te=W=>{const U=W.target;!U||!b.current||b.current.contains(U)||l()};return document.addEventListener("pointerdown",te,!0),()=>{document.removeEventListener("pointerdown",te,!0)}},T=[i,l],n[18]=l,n[19]=i,n[20]=I,n[21]=T):(I=n[20],T=n[21]),f.useEffect(I,T);let H;n[22]!==a?(H=te=>{const W=te.path.endsWith("/")?te.path:te.path+"/";a(W)},n[22]=a,n[23]=H):H=n[23];const P=H;let _,R;if(n[24]!==P||n[25]!==l||n[26]!==g||n[27]!==u||n[28]!==i?(_=()=>({handleKeyDown:te=>{if(!i||u.length===0)return!1;const W=u.length;if(te.key==="Tab"){if(te.preventDefault(),te.shiftKey)y(U=>(U-1+W)%W);else if(W===1){const U=u[0];U&&P(U)}else y(U=>(U+1)%W);return!0}if(te.key==="ArrowDown")return te.preventDefault(),y(U=>(U+1)%W),!0;if(te.key==="ArrowUp")return te.preventDefault(),y(U=>(U-1+W)%W),!0;if(te.key==="Enter"){te.preventDefault();const U=(g%W+W)%W,K=u[U];return K&&P(K),l(),!0}return te.key==="Escape"?(te.preventDefault(),l(),!0):!1}}),R=[i,u,g,P,l],n[24]=P,n[25]=l,n[26]=g,n[27]=u,n[28]=i,n[29]=_,n[30]=R):(_=n[29],R=n[30]),f.useImperativeHandle(e,_,R),!i||u.length===0&&!h)return null;let z;n[31]!==P||n[32]!==h||n[33]!==l||n[34]!==g||n[35]!==u?(z=h?s.jsx("div",{className:"flex items-center justify-center py-3",children:s.jsx(Wn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):s.jsx("div",{className:"overflow-y-auto py-1",children:u.map((te,W)=>{const U=g===W;return s.jsxs("div",{ref:K=>{v.current[W]=K},className:J("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",U&&"bg-interactive-selection"),onClick:()=>{P(te),l()},onMouseEnter:()=>y(W),children:[s.jsx(Tr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),s.jsx("span",{className:"truncate",children:te.name})]},te.path)})}),n[31]=P,n[32]=h,n[33]=l,n[34]=g,n[35]=u,n[36]=z):z=n[36];let O;n[37]===Symbol.for("react.memo_cache_sentinel")?(O=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]=O):O=n[37];let Q;return n[38]!==z?(Q=s.jsxs("div",{ref:b,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,O]}),n[38]=z,n[39]=Q):Q=n[39],Q});U9.displayName="DirectoryAutocomplete";function $Z(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 u=d-a-1;if(u===0?i=i+1:i=0,o=o+10,o=o+Math.max(0,18-d),o=o-Math.max(0,u),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 VZ(t){return t!==null}function UZ(t,e){return e.score-t.score||t.entry.name.localeCompare(e.entry.name)}function WZ(t){return t.entry}function qZ(t,e){return t.name.localeCompare(e.name)}const GZ=({open:t,onOpenChange:e})=>{const{currentDirectory:n,homeDirectory:r,isHomeReady:o}=Ds(),{addProject:a,getActiveProject:i}=ls(),[l,c]=f.useState(null),[d,u]=f.useState(""),[m,h]=f.useState(!1),[p,g]=f.useState(!1),y=$c(),{isDesktop:b,requestAccess:x,startAccessing:v}=T2(),{isMobile:w}=wn(),[C,k]=f.useState(!1),N=f.useRef(null),S=f.useCallback(W=>W?na(W,r):"",[r]);f.useEffect(()=>{if(t){h(!1),g(!1),k(!1);const U=i()?.path||n||r||"";c(U),u(S(U))}},[t,n,r,S,i]),f.useEffect(()=>{!t||m||l||r&&o&&(c(r),h(!0),u("~"))},[t,m,l,r,o]);const j=f.useCallback(()=>{e(!1)},[e]),A=f.useCallback(async W=>{if(!(!W||p)){g(!0);try{let U=W,K;if(b){const ee=await x(W);if(!ee.success){ue.error("Unable to access directory",{description:ee.error||"Desktop denied directory access."});return}U=ee.path??W,K=ee.projectId;const V=await v(U);if(!V.success){ue.error("Failed to open directory",{description:V.error||"Desktop could not grant file access."});return}}if(!a(U,{id:K})){ue.error("Failed to add project",{description:"Please select a valid directory path."});return}j()}catch(U){ue.error("Failed to select directory",{description:U instanceof Error?U.message:"Unknown error occurred."})}finally{g(!1)}}},[a,j,b,x,v,p]),M=f.useCallback(async()=>{const W=d.trim()||l;W&&await A(W)},[A,d,l]),F=f.useCallback(W=>{c(W),h(!0),u(S(W))},[S]),B=f.useCallback(async W=>{c(W),h(!0),u(S(W)),await A(W)},[A,S]),D=f.useCallback(W=>{const U=W.target.value;if(u(U),h(!0),k(U.startsWith("/")||U.startsWith("~")),U.startsWith("/")||U.startsWith("~")){const K=U.startsWith("~")&&r?U.replace(/^~/,r):U;c(K)}},[r]),E=f.useCallback(W=>{N.current?.handleKeyDown(W)||W.key==="Enter"&&(W.preventDefault(),M())},[M]),I=f.useCallback(W=>{c(W),h(!0),u(S(W))},[S]),T=f.useCallback(()=>{k(!1)},[]),H=f.useCallback(()=>{sc(!y)},[y]),P=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:[y?s.jsx(zo,{className:"h-4 w-4 text-primary"}):s.jsx(Ho,{className:"h-4 w-4"}),"Show hidden"]}),_=s.jsxs(Zs,{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(Us,{children:"Add project directory"}),s.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[s.jsx(tn,{className:"flex-1",children:"Choose a folder to add as a project."}),P]})]}),R=s.jsxs("div",{className:"relative",children:[s.jsx(ts,{value:d,onChange:D,onKeyDown:E,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),s.jsx(U9,{ref:N,inputValue:d,homeDirectory:r,onSelectSuggestion:I,visible:C,onClose:T,showHidden:y})]}),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(E6,{variant:"inline",currentPath:l??n,onSelectPath:F,onDoubleClickPath:B,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:y,rootDirectory:o?r:null,isRootReady:o})}),O=s.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[s.jsx("div",{className:"flex-shrink-0",children:R}),s.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:P}),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(E6,{variant:"inline",currentPath:l??n,onSelectPath:F,onDoubleClickPath:B,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:y,rootDirectory:o?r:null,isRootReady:o,alwaysShowActions:!0})})]}),Q=s.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[R,z]}),te=()=>s.jsxs(s.Fragment,{children:[s.jsx(ot,{variant:"ghost",onClick:j,disabled:p,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),s.jsx(ot,{onClick:M,disabled:p||!m||!l&&!d.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:p?"Adding...":"Add Project"})]});return w?s.jsx(rr,{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:te()}),children:O}):s.jsx($s,{open:t,onOpenChange:e,children:s.jsxs(Vs,{className:J("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:W=>{W.preventDefault()},children:[_,Q,s.jsx(vn,{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:te()})]})})},Wa=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,qa=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},ZZ=()=>{const[t,e]=f.useState(!1),[n,r]=f.useState(!1),[o,a]=f.useState(null),[i,l]=f.useState([]),[c,d]=f.useState(!1),[u,m]=f.useState(!1),[h,p]=f.useState(!1),[g,y]=f.useState(!1),[b,x]=f.useState(new Set),{deleteSession:v,deleteSessions:w,archiveSession:C,archiveSessions:k,loadSessions:N,getWorktreeMetadata:S}=Le(),j=De(ae=>ae.showDeletionDialog),A=De(ae=>ae.setShowDeletionDialog),{currentDirectory:M,homeDirectory:F,isHomeReady:B}=Ds(),{projects:D,addProject:E,activeProjectId:I}=ls(),{requestAccess:T,startAccessing:H}=T2(),{isMobile:P,isTablet:_,hasTouchInput:R}=wn(),z=P||_||R,O=f.useMemo(()=>{const ve=(I?D.find(ce=>ce.id===I)??null:null)?.path??M;return qa(ve)},[I,M,D]),Q=f.useCallback(ae=>{const ce=qa(ae.projectDirectory)||O;return{id:(D.find(me=>qa(me.path)===ce)??null)?.id??`path:${ce}`,path:ce}},[O,D]),te=g&&b.size>0,W=f.useMemo(()=>{const ae=o?.worktree;return ae&&typeof ae.branch=="string"&&ae.branch.trim().length>0?!0:i.length>0&&i.every(({metadata:ve})=>typeof ve.branch=="string"&&ve.branch.trim().length>0)},[o?.worktree,i]),U=o?.mode==="worktree",K=U,q=h||!U||!W,ee=h||!U;f.useEffect(()=>{N()},[N,M]);const V=f.useMemo(()=>D.map(ae=>`${ae.id}:${ae.path}`).join("|"),[D]),G=f.useRef(V);f.useEffect(()=>{V!==G.current&&(G.current=V,N())},[N,V]),f.useEffect(()=>{if(!(n||!B||D.length>0)){if(r(!0),Gs()&&ar()){T("").then(async ae=>{if(!ae.success||!ae.path){ae.error&&ae.error!=="Directory selection cancelled"&&ue.error("Failed to select directory",{description:ae.error});return}const ve=await H(ae.path);if(!ve.success){ue.error("Failed to open directory",{description:ve.error||"Desktop could not grant file access."});return}E(ae.path,{id:ae.projectId})||ue.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(ae=>{console.error("Desktop: Error selecting directory:",ae),ue.error("Failed to select directory")});return}e(!0)}},[E,n,B,D.length,T,H]);const Y=f.useCallback(ae=>{a({sessions:ae.sessions,dateLabel:ae.dateLabel,mode:ae.mode??"session",worktree:ae.worktree??null})},[]),oe=f.useCallback(()=>{a(null),l([]),d(!1),m(!1),p(!1),y(!1),x(new Set)},[]),re=f.useCallback(async ae=>{if(ae.sessions.length===0)return;if(ae.sessions.length===1){const me=ae.sessions[0];await v(me.id)?ue.success("Session deleted"):ue.error("Failed to delete session");return}const ve=ae.sessions.map(me=>me.id),{deletedIds:ce,failedIds:Z}=await w(ve);if(ce.length>0){const me=Z.length>0?`${Z.length} session${Z.length===1?"":"s"} could not be deleted.`:ae.dateLabel?`Removed all sessions from ${ae.dateLabel}.`:void 0;ue.success(`Deleted ${ce.length} session${ce.length===1?"":"s"}`,{description:Wa(me)})}Z.length>0&&ue.error(`Failed to delete ${Z.length} session${Z.length===1?"":"s"}`,{description:Wa("Please try again in a moment.")})},[v,w]);f.useEffect(()=>ia.onDeleteRequest(ae=>{if(!j&&(ae.mode??"session")==="session"){re(ae);return}Y(ae)}),[Y,j,re]),f.useEffect(()=>ia.onDirectoryRequest(()=>{e(!0)}),[]),f.useEffect(()=>{if(!o){l([]),d(!1),m(!1),y(!1),x(new Set);return}const ae=o.sessions.map(Z=>{const me=S(Z.id);return me?{session:Z,metadata:me}:null}).filter(Z=>!!Z);l(ae),d(!1),y(!1),x(new Set);const ve=new Map;if(o.worktree?.path&&ve.set(qa(o.worktree.path),o.worktree),ae.forEach(({metadata:Z})=>{Z.path&&ve.set(qa(Z.path),Z)}),ve.size===0){y(!0);return}let ce=!1;return(async()=>{const Z=new Map,me=new Set;await Promise.all(Array.from(ve.entries()).map(async([be,we])=>{try{const Ae=await Wc(we.path);Z.set(be,Ae),Ae?.isDirty&&me.add(be)}catch{we.status&&(Z.set(be,we.status),we.status.isDirty&&me.add(be))}})).catch(be=>{console.warn("Failed to inspect worktree status before deletion:",be)}),!ce&&(x(me),y(!0),a(be=>{if(!be?.worktree?.path)return be;const we=qa(be.worktree.path),Ae=Z.get(we);if(!Ae)return be;const Pe=be.worktree.status;return Pe?.isDirty===Ae.isDirty&&Pe?.ahead===Ae.ahead&&Pe?.behind===Ae.behind&&Pe?.upstream===Ae.upstream?be:{...be,worktree:{...be.worktree,status:Ae}}}),l(be=>be.map(we=>{const Ae=qa(we.metadata.path),Pe=Z.get(Ae);return Pe?{session:we.session,metadata:{...we.metadata,status:Pe}}:we})))})(),()=>{ce=!0}},[o,S]),f.useEffect(()=>{W||d(!1)},[W]);const fe=f.useCallback(async(ae,ve)=>{const ce=c&&W;try{return await S2(Q(ae),ae,{deleteRemoteBranch:ce,deleteLocalBranch:ve}),!0}catch(Z){return ue.error("Failed to remove worktree",{description:Wa(Z instanceof Error?Z.message:"Please try again.")}),!1}},[W,c,Q]),ie=f.useCallback(async()=>{if(o){p(!0);try{const ae=K,ve=ae&&c,ce=ae&&u;if(o.sessions.length===0&&U&&o.worktree){if(!await fe(o.worktree,ce)){oe();return}const be=c&&W?"Worktree and remote branch removed.":"Worktree removed.";ue.success("Worktree removed",{description:Wa(be)}),oe(),N();return}if(o.sessions.length===1){const Z=o.sessions[0];if(!(U?await C(Z.id):await v(Z.id,{archiveWorktree:!1,deleteRemoteBranch:ve,deleteLocalBranch:ce}))){ue.error(U?"Failed to archive session":"Failed to delete session"),p(!1);return}const be=!U&&ae?ve?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;ue.success(U?"Session archived":"Session deleted",{description:Wa(be),action:{label:"OK",onClick:()=>{}}})}else{const Z=o.sessions.map(we=>we.id);let me=[],be=[];if(U){const we=await k(Z);me=we.archivedIds,be=we.failedIds}else{const we=await w(Z,{archiveWorktree:!1,deleteRemoteBranch:ve,deleteLocalBranch:ce});me=we.deletedIds,be=we.failedIds}if(U&&o.worktree&&be.length===0&&await fe(o.worktree,ce)&&await N(),me.length>0){const we=!U&&ae?ve?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Pe=[be.length>0?`${be.length} session${be.length===1?"":"s"} could not be ${U?"archived":"deleted"}.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0,we].filter(Boolean).join(" ");ue.success(`${U?"Archived":"Deleted"} ${me.length} session${me.length===1?"":"s"}`,{description:Wa(Pe||void 0),action:{label:"OK",onClick:()=>{}}})}if(be.length>0&&(ue.error(`Failed to ${U?"archive":"delete"} ${be.length} session${be.length===1?"":"s"}`,{description:Wa("Please try again in a moment.")}),me.length===0)){p(!1);return}}U&&o.sessions.length===1&&o.worktree&&await fe(o.worktree,ce)&&await N(),oe()}finally{p(!1)}}},[o,c,u,v,w,C,k,oe,K,U,W,fe,N]),de=o?.worktree??i[0]?.metadata??null,$=o?o.mode==="worktree"?o.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and archives ${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}`:""}.`:"",L=o?s.jsxs("div",{className:J(U?"space-y-3":"space-y-2"),children:[o.sessions.length>0&&s.jsxs("div",{className:J(U?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[U&&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:J(U?"mt-2 space-y-1":"space-y-0.5"),children:[o.sessions.slice(0,5).map(ae=>s.jsxs("li",{className:J(U?"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:J(!U&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:ae.title||"Untitled Session"})]},ae.id)),o.sessions.length>5&&s.jsxs("li",{className:J(U?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",o.sessions.length-5," more"]})]})]}),U?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(cn,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),de?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:de.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:de?na(de.path,F):"Worktree path unavailable."}),te&&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,X=U?W?s.jsxs("button",{type:"button",onClick:()=>{q||d(ae=>!ae)},disabled:q,className:J("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",q?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[c?s.jsx(zo,{className:"size-4 text-primary"}):s.jsx(Ho,{className:"size-4"}),"Delete remote branch"]}):s.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,ne=U?s.jsxs("button",{type:"button",onClick:()=>{ee||m(ae=>!ae)},disabled:ee,className:J("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ee?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(zo,{className:"size-4 text-primary"}):s.jsx(Ho,{className:"size-4"}),"Delete local branch"]}):null,se=U?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:[ne,X]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ot,{variant:"ghost",onClick:oe,disabled:h,children:"Cancel"}),s.jsx(ot,{variant:"destructive",onClick:ie,disabled:h,children:h?"Deleting…":"Delete worktree"})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>A(!j),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":!j,children:[j?s.jsx(Ho,{className:"size-4"}):s.jsx(zo,{className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ot,{variant:"ghost",onClick:oe,disabled:h,children:"Cancel"}),s.jsx(ot,{variant:"destructive",onClick:ie,disabled:h,children:h?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),pe=U?"Delete worktree":o?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[z?s.jsx(rr,{open:!!o,onClose:()=>{h||oe()},title:pe,footer:s.jsx("div",{className:"flex justify-end gap-2",children:se}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[$&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:$}),L]})}):s.jsx($s,{open:!!o,onOpenChange:ae=>{if(!ae){if(h)return;oe()}},children:s.jsxs(Vs,{className:J(U?"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(Zs,{children:[s.jsxs(Us,{className:J(U&&"flex items-center gap-2"),children:[U&&s.jsx(Ln,{className:"h-5 w-5"}),pe]}),$&&s.jsx(tn,{children:$})]}),s.jsx("div",{className:J(U&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:L}),s.jsx(vn,{className:"mt-2 gap-2 pt-1 pb-1",children:se})]})}),s.jsx(GZ,{open:t,onOpenChange:e})]})},u4=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),KZ=(t,e)=>{const n=u4(t),r=u4(e);return`${n}-${r}`.substring(0,60)},I6=(t,e)=>`${t}/${e}`,QZ=()=>{const t=ls.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=Ds.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},pc=xn()(In(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=QZ();if(!c)return t({error:"Select a project",isLoading:!1}),null;const d=c.path;if(!await la(d))return t({error:"Not in a git repository",isLoading:!1}),null;const m=u4(n),h=await Ta(d),p=await X4(d),g=[],y=l?.filter(N=>N.trim().length>0)??[],b=new Map;for(const N of o){const S=`${N.providerID}:${N.modelID}`;b.set(S,(b.get(S)||0)+1)}const x=new Map;for(const N of o){const S=`${N.providerID}:${N.modelID}`,j=b.get(S)||1,A=(x.get(S)||0)+1;x.set(S,A);const M=KZ(N.providerID,N.modelID),F=j>1?I6(m,`${M}/${A}`):I6(m,M);try{const B=await D2(c,{preferredName:F,mode:"new",branchName:F,worktreeName:F,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:y},{resolvedRootTrackingRemote:p}),D={...B,createdFromBranch:h,kind:"standard"},E=j>1?`${m}/${N.providerID}/${N.modelID}/${A}`:`${m}/${N.providerID}/${N.modelID}`,I=await zt.withDirectory(B.path,()=>zt.createSession({title:E}));Es.getState().setWorktreeMetadata(I.id,D),g.push({sessionId:I.id,worktreePath:B.path,providerID:N.providerID,modelID:N.modelID,variant:N.variant})}catch(B){console.warn("[MultiRun] Failed to create session:",B)}}const v=l?.filter(N=>N.trim().length>0)??[];v.length>0&&F8(c,v).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const w=g.map(N=>N.sessionId),C=g[0]?.sessionId??null;if(w.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const k=i?.map(N=>({type:"file",mime:N.mime,filename:N.filename,url:N.url}));try{await Es.getState().loadSessions()}catch{}return(async()=>{try{await Promise.allSettled(g.map(async N=>{try{await zt.withDirectory(N.worktreePath,()=>zt.sendMessage({id:N.sessionId,providerID:N.providerID,modelID:N.modelID,variant:N.variant,text:r,agent:a,files:k}))}catch(S){console.warn("[MultiRun] Failed to start run:",S)}}))}catch(N){console.warn("[MultiRun] Failed to start runs:",N)}})(),t({isLoading:!1}),{groupSlug:m,sessionIds:w,firstSessionId:C}}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"})),W9="h-7",e2=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,YZ=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),JZ=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const e=YZ.format(t);return e.endsWith(".0")?e.slice(0,-2):e},XZ=t=>{const e=Ce.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=J("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",W9),e[0]=c):c=e[0];let d;e[1]!==n.providerID?(d=s.jsx(Dn,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=d):d=e[2];let u;e[3]!==l?(u=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=u):u=e[4];let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=s.jsx(_s,{className:"h-3.5 w-3.5"}),e[5]=m):m=e[5];let h;e[6]!==a?(h=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:m}),e[6]=a,e[7]=h):h=e[7];let p;return e[8]!==d||e[9]!==u||e[10]!==h?(p=s.jsxs("div",{className:c,children:[d,u,h]}),e[8]=d,e[9]=u,e[10]=h,e[11]=p):p=e[11],p},q9=({selectedModels:t,onAdd:e,onRemove:n,onUpdate:r,minModels:o,addButtonLabel:a="Add model",showChips:i=!0,maxModels:l})=>{const{providers:c,modelsMetadata:d}=Yt(),{favoriteModelsList:u,recentModelsList:m}=F2(),[h,p]=f.useState(!1),[g,y]=f.useState(""),[b,x]=f.useState(0),[v,w]=f.useState(null),C=f.useRef(null),k=f.useRef(null),N=f.useRef(null),S=f.useRef([]),j=f.useMemo(()=>{const P=new Map;for(const _ of t){const R=`${_.providerID}:${_.modelID}`;P.set(R,(P.get(R)||0)+1)}return P},[t]),A=f.useCallback(P=>t.filter(R=>R.providerID===P.providerID&&R.modelID===P.modelID).findIndex(R=>R.instanceId===P.instanceId)+1,[t]),M=(P,_)=>{const R=`${P}/${_}`;return d.get(R)},F=P=>{const _=P?.name||P?.id||"",R=String(_);return R.length>40?R.substring(0,37)+"...":R},B=f.useCallback((P,_)=>{if(!g.trim())return!0;const R=g.toLowerCase();return P.toLowerCase().includes(R)||_.toLowerCase().includes(R)},[g]),D=f.useMemo(()=>u.filter(({model:P,providerID:_})=>{const z=c.find(Q=>Q.id===_)?.name||_,O=F(P);return B(O,z)}),[u,c,B]),E=f.useMemo(()=>m.filter(({model:P,providerID:_})=>{const z=c.find(Q=>Q.id===_)?.name||_,O=F(P);return B(O,z)}),[m,c,B]),I=f.useMemo(()=>c.map(P=>{const R=(Array.isArray(P.models)?P.models:[]).filter(z=>{const O=F(z);return B(O,P.name||P.id||"")});return{...P,models:R}}).filter(P=>P.models.length>0),[c,B]),T=D.length>0||E.length>0||I.length>0;f.useEffect(()=>{if(h&&N.current){const _=N.current.getBoundingClientRect().top-100;w(Math.max(150,Math.min(400,_)))}},[h]),f.useEffect(()=>{h&&C.current&&C.current.focus()},[h]),f.useEffect(()=>{if(!h)return;const P=_=>{k.current&&!k.current.contains(_.target)&&(p(!1),y(""),x(0))};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[h]),f.useEffect(()=>{x(0)},[g]);const H=(P,_,R,z,O,Q)=>{const te=`${_}:${R}`,W=j.get(te)||0,U=M(_,R),K=JZ(U?.limit?.context),q=z==="fav"||z==="recent";return s.jsxs("button",{ref:ee=>{S.current[O]=ee},type:"button",onClick:()=>{e({providerID:_,modelID:R,displayName:P.name||R,instanceId:e2()})},onMouseEnter:()=>x(O),className:J("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",Q?"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:[q&&s.jsx(Dn,{providerId:_,className:"h-3.5 w-3.5 flex-shrink-0"}),s.jsx("span",{className:"font-medium truncate",children:F(P)}),K&&s.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:K})]}),W>0&&s.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",W]})]},`${z}-${te}`)};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:k,children:[s.jsxs(ot,{ref:N,type:"button",variant:"outline",size:"sm",className:W9,onClick:()=>p(!h),children:[s.jsx(Xs,{className:"h-3.5 w-3.5 mr-1"}),a]}),h&&(()=>{const P=[];D.forEach(({model:O,providerID:Q,modelID:te})=>{P.push({model:O,providerID:Q,modelID:te,section:"fav"})}),E.forEach(({model:O,providerID:Q,modelID:te})=>{P.push({model:O,providerID:Q,modelID:te,section:"recent"})}),I.forEach(O=>{O.models.forEach(Q=>{P.push({model:Q,providerID:O.id,modelID:Q.id,section:"provider"})})});const _=P.length,R=O=>{if(!J4(O))if(O.key==="ArrowDown"){O.preventDefault(),O.stopPropagation();const Q=(b+1)%Math.max(1,_);x(Q),setTimeout(()=>{S.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(O.key==="ArrowUp"){O.preventDefault(),O.stopPropagation();const Q=(b-1+Math.max(1,_))%Math.max(1,_);x(Q),setTimeout(()=>{S.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(O.key==="Enter"){O.preventDefault(),O.stopPropagation();const Q=P[b];Q&&e({providerID:Q.providerID,modelID:Q.modelID,displayName:Q.model.name||Q.modelID,instanceId:e2()})}else O.key==="Escape"&&(O.preventDefault(),O.stopPropagation(),p(!1),y(""),x(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(ur,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),s.jsx(ts,{ref:C,type:"text",placeholder:"Search models",value:g,onChange:O=>y(O.target.value),onKeyDown:R,className:"h-8 pl-8 typography-meta"})]})}),s.jsx(Ns,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:s.jsxs("div",{className:"p-1",children:[!T&&s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),D.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(To,{className:"h-4 w-4 text-primary"}),"Favorites"]}),D.map(({model:O,providerID:Q,modelID:te})=>{const W=z++;return H(O,Q,te,"fav",W,b===W)})]}),E.length>0&&s.jsxs(s.Fragment,{children:[D.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(Qr,{className:"h-4 w-4"}),"Recent"]}),E.map(({model:O,providerID:Q,modelID:te})=>{const W=z++;return H(O,Q,te,"recent",W,b===W)})]}),(D.length>0||E.length>0)&&I.length>0&&s.jsx("div",{className:"h-px bg-border/40 my-1"}),I.map((O,Q)=>s.jsxs(f.Fragment,{children:[Q>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(Dn,{providerId:O.id,className:"h-4 w-4 flex-shrink-0"}),O.name]}),O.models.map(te=>{const W=z++;return H(te,O.id,te.id,"provider",W,b===W)})]},O.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((P,_)=>{const R=`${P.providerID}:${P.modelID}`,z=j.get(R)||1,O=A(P),te=c.find(ee=>ee.id===P.providerID)?.models.find(ee=>ee.id===P.modelID),W=te?.variants?Object.keys(te.variants):[],U=W.length>0,K="__default__",q=P.variant??K;return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(XZ,{model:P,instanceIndex:O,totalSameModel:z,onRemove:()=>n(_)}),U&&s.jsxs(dn,{value:q,onValueChange:ee=>{if(!r)return;r(_,{...P,variant:ee===K?void 0:ee})},children:[s.jsxs(un,{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($o,{className:J("h-3.5 w-3.5 flex-shrink-0",q===K?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(bn,{placeholder:"Thinking"})]}),s.jsxs(fn,{fitContent:!0,children:[s.jsx(fs,{value:K,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),W.map(ee=>s.jsx(fs,{value:ee,className:"pr-2 [&>span:first-child]:hidden",children:ee},ee))]})]})]},P.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`:"","."]})]})},eK=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 x3(t){const[e,n]=f.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[r,o]=f.useState(!1),[a,i]=f.useState(null);return f.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 la(t);if(l)return;if(i(c),!c){n([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const d=await b8(t).catch(()=>null);if(l)return;const u=await X4(t).catch(()=>null);if(l)return;const m=[],h=d?.current?`Current (HEAD: ${d.current})`:"Current (HEAD)";m.push({value:"HEAD",label:h,group:"special"}),d&&(d.all.filter(y=>!y.startsWith("remotes/")).filter(y=>{if(!u)return!0;const b=d.branches?.[y]?.tracking,x=eK(b);return x?x===u:!0}).sort((y,b)=>y.localeCompare(b)).forEach(y=>{m.push({value:y,label:y,group:"local"})}),d.all.filter(y=>y.startsWith("remotes/")).map(y=>y.replace(/^remotes\//,"")).filter(y=>{if(!u)return!0;const b=y.indexOf("/");return b<=0?!1:y.slice(0,b)===u}).sort((y,b)=>y.localeCompare(b)).forEach(y=>{m.push({value:y,label:y,group:"remote"})})),n(m)}finally{l||o(!1)}})(),()=>{l=!0}},[t]),{branches:e,isLoading:r,isGitRepository:a}}const G9=t=>{const e=Ce.c(39),{directory:n,value:r,onChange:o,className:a,disabled:i,id:l}=t,{branches:c,isLoading:d,isGitRepository:u}=x3(n);let m;e[0]!==c||e[1]!==r?(m=c.find(B=>B.value===r)?.label??null,e[0]=c,e[1]=r,e[2]=m):m=e[2];const h=m;let p,g;e[3]!==c||e[4]!==o||e[5]!==r?(p=()=>{!c.some(D=>D.value===r)&&c.length>0&&o("HEAD")},g=[c,r,o],e[3]=c,e[4]=o,e[5]=r,e[6]=p,e[7]=g):(p=e[6],g=e[7]),f.useEffect(p,g);const y=i||!u||d,b=a??"max-w-full typography-meta text-foreground";let x;e[8]!==d||e[9]!==h?(x=h?s.jsx(bn,{children:h}):s.jsx(bn,{placeholder:d?"Loading branches…":"Select a branch"}),e[8]=d,e[9]=h,e[10]=x):x=e[10];let v;e[11]!==l||e[12]!==b||e[13]!==x?(v=s.jsx(un,{id:l,size:"lg",className:b,children:x}),e[11]=l,e[12]=b,e[13]=x,e[14]=v):v=e[14];let w;e[15]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx(Xa,{children:"Default"}),e[15]=w):w=e[15];let C;e[16]!==c?(C=c.filter(tK).map(sK),e[16]=c,e[17]=C):C=e[17];let k;e[18]!==C?(k=s.jsxs(Sa,{children:[w,C]}),e[18]=C,e[19]=k):k=e[19];let N;e[20]!==c?(N=c.some(nK)?s.jsxs(s.Fragment,{children:[s.jsx(G0,{}),s.jsxs(Sa,{children:[s.jsx(Xa,{children:"Local branches"}),c.filter(rK).map(oK)]})]}):null,e[20]=c,e[21]=N):N=e[21];let S;e[22]!==c?(S=c.some(aK)?s.jsxs(s.Fragment,{children:[s.jsx(G0,{}),s.jsxs(Sa,{children:[s.jsx(Xa,{children:"Remote branches"}),c.filter(iK).map(lK)]})]}):null,e[22]=c,e[23]=S):S=e[23];let j;e[24]!==N||e[25]!==S||e[26]!==k?(j=s.jsxs(fn,{fitContent:!0,children:[k,N,S]}),e[24]=N,e[25]=S,e[26]=k,e[27]=j):j=e[27];let A;e[28]!==y||e[29]!==o||e[30]!==j||e[31]!==v||e[32]!==r?(A=s.jsxs(dn,{value:r,onValueChange:o,disabled:y,children:[v,j]}),e[28]=y,e[29]=o,e[30]=j,e[31]=v,e[32]=r,e[33]=A):A=e[33];let M;e[34]!==u?(M=u===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."}),e[34]=u,e[35]=M):M=e[35];let F;return e[36]!==A||e[37]!==M?(F=s.jsxs("div",{className:"space-y-2",children:[A,M]}),e[36]=A,e[37]=M,e[38]=F):F=e[38],F};function tK(t){return t.group==="special"}function sK(t){return s.jsx(fs,{value:t.value,className:"w-auto whitespace-nowrap",children:t.label},t.value)}function nK(t){return t.group==="local"}function rK(t){return t.group==="local"}function oK(t){return s.jsx(fs,{value:t.value,className:"w-auto whitespace-nowrap",children:t.label},t.value)}function aK(t){return t.group==="remote"}function iK(t){return t.group==="remote"}function lK(t){return s.jsx(fs,{value:t.value,className:"w-auto whitespace-nowrap",children:t.label},t.value)}const Z9=t=>{const e=Ce.c(28),{value:n,onChange:r,className:o,disabled:a,id:i}=t,l=Yt(cK),c=Yt(dK),d=Yt(uK);let u;e[0]!==l?(u=l(),e[0]=l,e[1]=u):u=e[1];const m=u;let h;e[2]!==m?(h=m.filter(fK),e[2]=m,e[3]=h):h=e[3];const p=h;let g,y;e[4]!==c?(g=()=>{c()},y=[c],e[4]=c,e[5]=g,e[6]=y):(g=e[5],y=e[6]),f.useEffect(g,y);let b,x;e[7]!==d||e[8]!==a||e[9]!==r||e[10]!==p||e[11]!==n?(b=()=>{if(a)return;const A=n.trim();if(A.length>0&&p.some(B=>B.name===A))return;const M=typeof d=="string"&&d.trim().length>0?d.trim():null;if(M&&p.some(B=>B.name===M)){r(M);return}const F=p[0]?.name;F&&r(F)},x=[d,a,r,p,n],e[7]=d,e[8]=a,e[9]=r,e[10]=p,e[11]=n,e[12]=b,e[13]=x):(b=e[12],x=e[13]),f.useEffect(b,x);const v=n.trim().length>0?n:void 0,w=o??"max-w-full typography-meta text-foreground";let C;e[14]===Symbol.for("react.memo_cache_sentinel")?(C=s.jsx(bn,{placeholder:"Select an agent"}),e[14]=C):C=e[14];let k;e[15]!==i||e[16]!==w?(k=s.jsx(un,{id:i,size:"lg",className:w,children:C}),e[15]=i,e[16]=w,e[17]=k):k=e[17];let N;e[18]!==p?(N=p.length>0&&s.jsx(Sa,{children:p.map(mK)}),e[18]=p,e[19]=N):N=e[19];let S;e[20]!==N?(S=s.jsx(fn,{fitContent:!0,children:N}),e[20]=N,e[21]=S):S=e[21];let j;return e[22]!==a||e[23]!==r||e[24]!==v||e[25]!==S||e[26]!==k?(j=s.jsxs(dn,{value:v,onValueChange:r,disabled:a,children:[k,S]}),e[22]=a,e[23]=r,e[24]=v,e[25]=S,e[26]=k,e[27]=j):j=e[27],j};function cK(t){return t.getVisibleAgents}function dK(t){return t.loadAgents}function uK(t){return t.currentAgentName}function fK(t){return t.mode!=="subagent"}function mK(t){return s.jsx(fs,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const hK=10*1024*1024,T6=5,P6=({initialPrompt:t,onCreated:e,onCancel:n})=>{const[r,o]=f.useState(""),[a,i]=f.useState(()=>t??""),[l,c]=f.useState([]),[d,u]=f.useState(""),[m,h]=f.useState([]),[p,g]=f.useState(!1),[y,b]=f.useState([]),[x,v]=f.useState(!1),[w,C]=f.useState(!1),k=f.useRef(null),N=Ds(Y=>Y.currentDirectory??null),S=f.useMemo(()=>{if(typeof window>"u")return null;const Y=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof Y=="string"&&Y.trim().length>0?Y.trim():null},[]),j=ls(Y=>Y.activeProjectId),A=ls(Y=>Y.projects),M=f.useMemo(()=>{if(j){const oe=A.find(re=>re.id===j);if(oe?.path)return{id:oe.id,path:oe.path}}const Y=N??S;return Y?{id:`path:${Y}`,path:Y}:null},[j,A,N,S]),[F,B]=f.useState(()=>typeof window>"u"?!1:Xn()),D=f.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);f.useEffect(()=>{typeof window>"u"||B(Xn())},[]);const E=f.useMemo(()=>{if(typeof window>"u")return null;const Y=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof Y=="number"&&Number.isFinite(Y)&&Y>0)return Y;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const re=Number.parseInt(oe[1],10),fe=Number.parseInt(oe[2],10);return Number.isNaN(re)?null:re===10?fe:re},[]),I=f.useMemo(()=>F&&D?"pl-[5.5rem]":"pl-3",[F,D]),T=f.useMemo(()=>!F||!D||E===null?"":E>=26?"h-12":E<=15?"h-14":"",[F,D,E]),H=f.useCallback(async Y=>{if(!Y.target.closest("button, a, input, select, textarea")&&Y.button===0&&F)try{const{getCurrentWindow:oe}=await cr(async()=>{const{getCurrentWindow:fe}=await import("./vendor-.bun-9lzLHWe8.js").then(ie=>ie.eR);return{getCurrentWindow:fe}},__vite__mapDeps([0,1]));await oe().startDragging()}catch{}},[F]);f.useEffect(()=>{if(!n)return;const Y=oe=>{oe.key==="Escape"&&(oe.preventDefault(),oe.stopPropagation(),n())};return window.addEventListener("keydown",Y,!0),()=>window.removeEventListener("keydown",Y,!0)},[n]);const[P,_]=f.useState("HEAD"),{isLoading:R,isGitRepository:z}=x3(N),O=pc(Y=>Y.createMultiRun),Q=pc(Y=>Y.error),te=pc(Y=>Y.clearError);f.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&i(Y=>Y.trim().length>0?Y:t)},[t]),f.useEffect(()=>{if(!M)return;let Y=!1;return C(!0),(async()=>{try{const oe=await Ci(M);Y||b(oe)}catch{}finally{Y||C(!1)}})(),()=>{Y=!0}},[M]);const W=Y=>{l.length>=T6||(c(oe=>[...oe,Y]),te())},U=Y=>{c(oe=>oe.filter((re,fe)=>fe!==Y)),te()},K=f.useCallback((Y,oe)=>{c(re=>re.map((fe,ie)=>ie===Y?oe:fe))},[]),q=async Y=>{const oe=Y.target.files;if(!oe)return;let re=0;for(let fe=0;fe<oe.length;fe++){const ie=oe[fe];if(ie.size>hK){ue.error(`File "${ie.name}" is too large (max 10MB)`);continue}try{const de=await new Promise((L,X)=>{const ne=new FileReader;ne.onload=()=>L(ne.result),ne.onerror=X,ne.readAsDataURL(ie)}),$={id:e2(),filename:ie.name,mimeType:ie.type||"application/octet-stream",size:ie.size,dataUrl:de};h(L=>[...L,$]),re++}catch(de){console.error("File attach failed",de),ue.error(`Failed to attach "${ie.name}"`)}}re>0&&ue.success(`Attached ${re} file${re>1?"s":""}`),k.current&&(k.current.value="")},ee=Y=>{h(oe=>oe.filter(re=>re.id!==Y))},V=async Y=>{if(Y.preventDefault(),!!a.trim()&&!(l.length<2)){g(!0),te();try{const oe=l.map(({instanceId:$,...L})=>L),re=m.map($=>({mime:$.mimeType,filename:$.filename,url:$.dataUrl})),fe=y.filter($=>$.trim().length>0),ie={name:r.trim(),prompt:a.trim(),models:oe,agent:d||void 0,worktreeBaseBranch:P,files:re.length>0?re:void 0,setupCommands:fe.length>0?fe:void 0},de=await O(ie);de&&(de.firstSessionId&&Le.getState().setCurrentSession(de.firstSessionId),e?.())}finally{g(!1)}}},G=!!(r.trim()&&a.trim()&&l.length>=2&&z&&!R);return s.jsxs("div",{className:"flex flex-col h-full bg-background",children:[s.jsxs("header",{onMouseDown:H,className:J("relative flex h-12 items-center justify-center border-b app-region-drag select-none",I,T),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(Vt,{delayDuration:500,children:[s.jsx(Ut,{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(_s,{className:"h-5 w-5"})})}),s.jsx($t,{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:V,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(ts,{id:"group-name",value:r,onChange:Y=>o(Y.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(G9,{directory:N,value:P,onChange:_,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:P||"HEAD"}),"."]})]}),s.jsxs(Vr,{open:x,onOpenChange:v,children:[s.jsxs(ho,{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",y.filter(Y=>Y.trim()).length>0&&s.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(Y=>Y.trim()).length," configured)"]})]}),s.jsx(Ls,{className:J("h-4 w-4 text-muted-foreground transition-transform duration-200",x&&"rotate-180")})]}),s.jsx(Ur,{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:[y.map((Y,oe)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx(ts,{value:Y,onChange:re=>{const fe=[...y];fe[oe]=re.target.value,b(fe)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>{const re=y.filter((fe,ie)=>ie!==oe);b(re)},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(_s,{className:"h-4 w-4"})})]},oe)),s.jsxs("button",{type:"button",onClick:()=>b([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(Xs,{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(Z9,{value:d,onChange:u,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(dr,{id:"prompt",value:a,onChange:Y=>i(Y.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:k,type:"file",multiple:!0,className:"hidden",onChange:q,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:()=>k.current?.click(),children:[s.jsx(Jl,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),m.map(Y=>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:[Y.mimeType.startsWith("image/")?s.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground"}):s.jsx(ui,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[120px]",title:Y.filename,children:Y.filename}),s.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",Y.size<1024?`${Y.size}B`:Y.size<1024*1024?`${(Y.size/1024).toFixed(1)}KB`:`${(Y.size/(1024*1024)).toFixed(1)}MB`,")"]}),s.jsx("button",{type:"button",onClick:()=>ee(Y.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:s.jsx(_s,{className:"h-3.5 w-3.5"})})]},Y.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(q9,{selectedModels:l,onAdd:W,onRemove:U,onUpdate:K,minModels:2,maxModels:T6})]}),Q&&s.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:Q}),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:!G||p,children:p?"Creating...":s.jsxs(s.Fragment,{children:["Start (",l.length," models)"]})})]})]})})})]})},L1=85,pK=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},gK=()=>{const{isSidebarOpen:o,isRightSidebarOpen:a,isBottomTerminalOpen:i,setRightSidebarOpen:l,setBottomTerminalOpen:c,activeMainTab:d,setIsMobile:u,isSessionSwitcherOpen:m,isSettingsDialogOpen:h,setSettingsDialogOpen:p,isMultiRunLauncherOpen:g,setMultiRunLauncherOpen:y,multiRunLauncherPrefillPrompt:b}=De(),{isMobile:x}=wn(),v=Wo()??"",w=f.useMemo(()=>pK(v),[v]),C=De(_=>{if(!w)return!1;const R=_.contextPanelByDirectory[w],z=R?.tabs??[],O=z.find(Q=>Q.id===R?.activeTabId)??z[z.length-1];return!!(R?.isOpen&&O)}),k=De(_=>_.setSidebarOpen),N=f.useRef(!1),S=f.useRef(!1),j=f.useRef(!1),[A,M]=f.useState(!1),F=f.useRef(!1),B=I3(0),D=Ne.useRef(0),E=I3(0),I=Ne.useRef(0);Ne.useEffect(()=>{x&&(D.current=window.innerWidth*(L1/100),I.current=window.innerWidth*(L1/100))},[x]),Ne.useEffect(()=>{if(!x)return;const _=A?0:-D.current;Ya(B,_,{type:"spring",stiffness:400,damping:35,mass:.8})},[A,x,B]),Ne.useEffect(()=>{if(!x)return;F.current=a;const _=a?0:I.current;Ya(E,_,{type:"spring",stiffness:400,damping:35,mass:.8})},[x,a,E]),Ne.useEffect(()=>{x&&M(m)},[m,x]),Ne.useEffect(()=>{x&&(F.current=a)},[a,x]);const T=Ac(_=>_.checkForUpdates);f.useEffect(()=>{const z=window.setTimeout(()=>{T()},3e3),O=window.setInterval(()=>{T()},36e5);return()=>{window.clearTimeout(z),window.clearInterval(O)}},[T]),f.useEffect(()=>{De.getState().isMobile!==x&&u(x)},[x,u]),f.useEffect(()=>{if(typeof window>"u")return;let _;const R=()=>{_!==void 0&&window.clearTimeout(_),_=window.setTimeout(()=>{De.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",R),()=>{window.removeEventListener("resize",R),_!==void 0&&window.clearTimeout(_)}},[]),f.useEffect(()=>{if(C){De.getState().isSidebarOpen&&(k(!1),j.current=!0);return}j.current&&(k(!0),j.current=!1)},[C,k]),f.useEffect(()=>{if(typeof window>"u")return;let _;const R=()=>{const O=De.getState(),Q=window.innerWidth,te=window.innerHeight,W=Q<1140,U=Q>=1220;W?O.isRightSidebarOpen&&(l(!1),N.current=!0):U&&N.current&&(l(!0),N.current=!1);const K=te<640,q=te>=700;K?O.isBottomTerminalOpen&&(c(!1),S.current=!0):q&&S.current&&(c(!0),S.current=!1)},z=()=>{_!==void 0&&window.clearTimeout(_),_=window.setTimeout(()=>{R()},100)};return R(),window.addEventListener("resize",z),()=>{window.removeEventListener("resize",z),_!==void 0&&window.clearTimeout(_)}},[c,l]),f.useEffect(()=>{if(typeof window>"u")return;const _=De.subscribe((R,z)=>{const O=window.innerWidth,Q=window.innerHeight,te=O>=1220,W=Q>=700;R.isRightSidebarOpen!==z.isRightSidebarOpen&&te&&(N.current=!1),R.isBottomTerminalOpen!==z.isBottomTerminalOpen&&W&&(S.current=!1)});return()=>{_()}},[]),f.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const _=document.documentElement;let R=0,z=!1,O=0,Q=null;const te=De.getState().setKeyboardOpen,W=()=>{Q&&(Q.style.setProperty("--oc-keyboard-avoid-offset","0px"),Q.removeAttribute("data-keyboard-avoid-active"),Q=null)},U=oe=>{if(!oe)return null;const re=oe.getAttribute("data-keyboard-avoid-target-id");if(re){const ie=document.getElementById(re);if(ie instanceof HTMLElement)return ie}const fe=oe.closest("[data-keyboard-avoid]");if(fe)return fe.getAttribute("data-keyboard-avoid")==="none"?null:fe;if(oe.classList.contains("overlay-scrollbar-container")){const ie=oe.parentElement;if(ie instanceof HTMLElement)return ie}return oe},K=()=>{R=0,z=!0,_.style.setProperty("--oc-keyboard-inset","0px"),te(!1)},q=()=>{const oe=window.visualViewport,re=oe?Math.round(oe.height):window.innerHeight,fe=oe?Math.max(0,Math.round(oe.offsetTop)):0;_.style.setProperty("--oc-visual-viewport-offset-top",`${fe}px`);const ie=document.activeElement,de=ie?.tagName,L=de==="INPUT"||de==="TEXTAREA"||de==="SELECT"||!!ie?.isContentEditable,X=Math.round(_.clientHeight||window.innerHeight),ne=re+fe,se=Math.max(0,X-ne),ae=se>=(L?120:180)?se:0;if(z)ae===0&&(z=!1),R=0;else if(R===0)ae>0&&L&&(R=ae);else{const me=!L&&re>O+6;ae===0?(R=0,te(!1)):me?K():(ae>0&&L||ae>R)&&(R=ae,te(!0))}_.style.setProperty("--oc-keyboard-inset",`${R}px`),O=re;const ce=/iPad|iPhone|iPod/.test(navigator.userAgent)&&R>0?34:0;_.style.setProperty("--oc-keyboard-home-indicator",`${ce}px`);const Z=L?U(ie):null;if(!x||!Z||!ie)W();else{Z!==Q&&(W(),Q=Z);const me=fe+re,we=ie.getBoundingClientRect().bottom-me,Ae=8,Pe=Math.max(R,ae),xe=we>Ae&&Pe>0?Math.min(we,Pe):0,_e=Q;_e&&(_e.style.setProperty("--oc-keyboard-avoid-offset",`${xe}px`),_e.setAttribute("data-keyboard-avoid-active","true"))}if(x&&L){const me=document.scrollingElement;me&&me.scrollTop!==0&&(me.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};q();const ee=window.visualViewport;ee?.addEventListener("resize",q),ee?.addEventListener("scroll",q),window.addEventListener("resize",q),window.addEventListener("orientationchange",q);const V=oe=>{if(!oe)return!1;const re=oe.tagName;return re==="INPUT"||re==="TEXTAREA"||re==="SELECT"||oe.isContentEditable},G=oe=>{const re=oe.target;V(re)&&(z=!1),q()};document.addEventListener("focusin",G,!0);const Y=oe=>{const re=oe.target;if(!V(re))return;const fe=oe.relatedTarget;V(fe)||window.requestAnimationFrame(()=>{if(V(document.activeElement))return;const ie=window.visualViewport,de=ie?Math.round(ie.height):window.innerHeight,$=ie?Math.max(0,Math.round(ie.offsetTop)):0,L=Math.round(_.clientHeight||window.innerHeight),X=de+$;if(Math.max(0,L-X)>0){q();return}K(),q()})};return document.addEventListener("focusout",Y,!0),()=>{ee?.removeEventListener("resize",q),ee?.removeEventListener("scroll",q),window.removeEventListener("resize",q),window.removeEventListener("orientationchange",q),document.removeEventListener("focusin",G,!0),document.removeEventListener("focusout",Y,!0),W()}},[x]);const H=f.useMemo(()=>{switch(d){case"plan":return s.jsx(Qg,{});case"git":return s.jsx(Xu,{});case"diff":return s.jsx(m9,{});case"terminal":return s.jsx(E5,{});case"files":return s.jsx(x9,{});default:return null}},[d]),P=d==="chat";return s.jsx(JH,{children:s.jsxs("div",{className:J("main-content-safe-area h-[100dvh]",x?"flex flex-col":"flex","bg-background"),children:[s.jsx(Xq,{}),s.jsx(sG,{}),s.jsx(rG,{}),s.jsx(ZZ,{}),x?s.jsxs(RB,{value:{leftDrawerOpen:A,rightDrawerOpen:a,toggleLeftDrawer:()=>{a&&l(!1),M(!A)},toggleRightDrawer:()=>{A&&M(!1),l(!a)},leftDrawerX:B,rightDrawerX:E,leftDrawerWidth:D,rightDrawerWidth:I,setMobileLeftDrawerOpen:M,setRightSidebarOpen:l},children:[!(h||g)&&s.jsx(fm,{onToggleLeftDrawer:()=>{a&&l(!1),M(!A)},onToggleRightDrawer:()=>{A&&M(!1),l(!a)},leftDrawerOpen:A,rightDrawerOpen:a}),s.jsx(Yo.button,{type:"button",initial:!1,animate:{opacity:A||a?1:0,pointerEvents:A||a?"auto":"none"},className:"fixed inset-0 z-40 bg-black/50 cursor-default",onClick:()=>{M(!1),l(!1)},"aria-label":"Close drawer"}),s.jsx(Yo.aside,{drag:"x",dragElastic:.08,dragMomentum:!1,dragConstraints:{left:-(D.current||window.innerWidth*.85),right:0},style:{width:`${L1}%`,x:B},onDragEnd:(_,R)=>{const z=D.current||window.innerWidth*.85,O=z*.3,Q=500,te=B.get(),W=R.offset.x<-O||R.velocity.x<-Q,U=R.offset.x>O||R.velocity.x>Q;W?(B.set(-z),M(!1)):U?(B.set(0),M(!0)):te>-z/2?B.set(0):B.set(-z)},className:J("fixed left-0 top-0 z-50 h-full bg-transparent","cursor-grab active:cursor-grabbing"),"aria-hidden":!A,children:s.jsxs("div",{className:"h-full overflow-hidden flex bg-sidebar shadow-none drawer-safe-area",children:[s.jsx("div",{onPointerDownCapture:_=>_.stopPropagation(),children:s.jsx(Fm,{className:"shrink-0",mobile:!0})}),s.jsx("div",{className:"flex-1 min-w-0 overflow-hidden flex flex-col",children:s.jsx(Nn,{children:s.jsx(X0,{mobileVariant:!0})})})]})}),s.jsx(Yo.aside,{drag:"x",dragElastic:.08,dragMomentum:!1,dragConstraints:{left:0,right:I.current||window.innerWidth*.85},style:{width:`${L1}%`,x:E},onDragEnd:(_,R)=>{const z=I.current||window.innerWidth*.85,O=z*.3,Q=500,te=E.get(),W=R.offset.x>O||R.velocity.x>Q,U=R.offset.x<-O||R.velocity.x<-Q;W?(E.set(z),l(!1)):U?(E.set(0),l(!0)):te<z/2?E.set(0):E.set(z)},className:J("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(Nn,{children:s.jsx(Xu,{})})})}),s.jsx("div",{className:J("flex flex-1 overflow-hidden relative",(h||g)&&"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:J("absolute inset-0",!P&&"invisible"),children:s.jsx(Nn,{children:s.jsx(al,{})})}),H&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Nn,{children:H})})]})}),g&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:s.jsx(Nn,{children:s.jsx(P6,{initialPrompt:b,onCreated:()=>y(!1),onCancel:()=>y(!1)})})}),h&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:s.jsx(Nn,{children:s.jsx(y3,{onClose:()=>p(!1)})})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[s.jsxs("div",{className:J("absolute inset-0 flex flex-col",g&&"invisible"),children:[s.jsx(fm,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[s.jsx(Fm,{}),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(bC,{isOpen:o,isMobile:x,children:s.jsx(X0,{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:J("absolute inset-0",!P&&"invisible"),children:s.jsx(Nn,{children:s.jsx(al,{})})}),H&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Nn,{children:H})})]}),s.jsx(Jq,{})]}),s.jsx(TD,{isOpen:a,children:s.jsx(Nn,{children:s.jsx(gq,{})})})]}),s.jsx(fC,{isOpen:i,isMobile:x,children:s.jsx(Nn,{children:s.jsx(E5,{})})})]})]})]})]}),g&&s.jsx("div",{className:J("absolute inset-0 z-10 bg-background"),children:s.jsx(Nn,{children:s.jsx(P6,{initialPrompt:b,onCreated:()=>y(!1),onCancel:()=>y(!1)})})})]}),s.jsx(PW,{open:h,onOpenChange:p})]})]})})},yK=t=>{if(!t)return"-";try{return new Date(t).toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}catch{return"-"}},bK=550,xK=1400,vK=280,wK=()=>{const t=mr(),e=f.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),n=f.useMemo(()=>{const T=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof T=="string"&&T.trim().length>0?T.trim():null},[]),r=f.useRef(!1),o=f.useMemo(()=>{try{return!!Le.getState().newSessionDraft?.open}catch{return!1}},[]),[a,i]=f.useState(()=>o?"chat":"sessions"),[l,c]=f.useState(0),d=f.useRef(null),u=Le(T=>T.currentSessionId),m=Le(T=>T.sessions),h=f.useMemo(()=>u?m.find(T=>T.id===u)?.title||"Session":null,[u,m]),p=Le(T=>!!T.newSessionDraft?.open),g=Le(T=>T.isSyncing),y=Le(T=>{const H=T.sessionStatus;if(!H||H.size===0)return!1;for(const P of H.values())if(P?.type==="busy"||P?.type==="retry")return!0;return!1}),b=Le(T=>T.openNewSessionDraft),[x,v]=f.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),w=Yt(T=>T.isInitialized),C=Yt(T=>T.initializeApp),k=Le(T=>T.loadSessions),N=Le(T=>T.loadMessages),S=Le(T=>T.messages),[j,A]=f.useState(()=>w),[M,F]=f.useState(!1),B=f.useRef(0);f.useEffect(()=>{u&&i("chat")},[u]),f.useEffect(()=>{const T=t.vscode;T&&T.executeCommand("openchamber.setActiveSession",u,h)},[h,u,t.vscode]),f.useEffect(()=>{if(e==="editor"||a!=="chat"||u||p||g||y)return;const T=window.setTimeout(()=>{const H=Le.getState(),P=!H.currentSessionId,_=!H.newSessionDraft?.open,R=H.isSyncing,z=(()=>{const O=H.sessionStatus;if(!O||O.size===0)return!1;for(const Q of O.values())if(Q?.type==="busy"||Q?.type==="retry")return!0;return!1})();P&&_&&!R&&!z&&i("sessions")},900);return()=>{window.clearTimeout(T)}},[u,p,a,e,g,y]);const D=f.useCallback(()=>{i("sessions")},[]);f.useEffect(()=>{const T=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(T==="connected"||T==="connecting"||T==="error"||T==="disconnected")&&v(T);const H=P=>{const R=P.detail?.status;(R==="connected"||R==="connecting"||R==="error"||R==="disconnected")&&v(R)};return window.addEventListener("openchamber:connection-status",H),()=>window.removeEventListener("openchamber:connection-status",H)},[]),f.useEffect(()=>{const T=H=>{const _=H.detail?.view;_==="settings"?i("settings"):_==="chat"?i("chat"):_==="sessions"&&i("sessions")};return window.addEventListener("openchamber:navigate",T),()=>window.removeEventListener("openchamber:navigate",T)},[]),f.useEffect(()=>{(async()=>{if(M||j||x!=="connected")return;const H=Date.now();if(!(H-B.current<750)){B.current=H,F(!0);try{const P=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();P&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:w}),w||await C();const _=Yt.getState();_.isConnected&&(_.providers.length===0&&await _.loadProviders(),_.agents.length===0&&await _.loadAgents());const R=Yt.getState();if(!R.isInitialized||!R.isConnected||R.providers.length===0||R.agents.length===0)return;await k();const z=Le.getState().error;if(P&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:R.providers.length,agents:R.agents.length,sessions:Le.getState().sessions.length,sessionsError:z}),typeof z=="string"&&z.length>0)return;A(!0)}catch{}finally{F(!1)}}})()},[x,w,j,C,M,k]),f.useEffect(()=>{if(e==="editor"&&!r.current&&!(!j||x!=="connected")){if(!n){r.current=!0,b();return}m.some(T=>T.id===n)&&(r.current=!0,Le.getState().setCurrentSession(n))}},[x,j,n,b,m,e]),f.useEffect(()=>{(async()=>{if(!(!j||x!=="connected"||a!=="chat"||p||!u||S.has(u)))try{await N(u)}catch{}})()},[x,u,a,j,N,S,p]),f.useEffect(()=>{const T=d.current;if(!T)return;const H=new ResizeObserver(P=>{for(const _ of P)c(_.contentRect.width)});return H.observe(T),c(T.clientWidth),()=>H.disconnect()},[]);const E=l>0&&l<bK,I=l>=xK;return f.useEffect(()=>{I&&a==="sessions"&&e==="sidebar"&&i("chat")},[I,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(z1,{title:m.find(T=>T.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Nn,{children:s.jsx(al,{})})})]}):a==="settings"?s.jsx(y3,{onClose:()=>i(I?"chat":"sessions"),forceMobile:E}):I?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:vK},children:s.jsx(X0,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),s.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[s.jsx(z1,{title:p&&!u?"New session":m.find(T=>T.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Nn,{children:s.jsx(al,{})})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:J("flex flex-col h-full",a!=="sessions"&&"hidden"),children:[s.jsx(z1,{title:"Sessions"}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(X0,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>i("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}),s.jsxs("div",{className:J("flex flex-col h-full",a!=="chat"&&"hidden"),children:[s.jsx(z1,{title:p&&!u?"New session":m.find(T=>T.id===u)?.title||"Chat",showBack:!0,onBack:D,showMcp:!0,showContextUsage:!0,showRateLimits:!0}),s.jsx("div",{className:"flex-1 overflow-hidden",children:s.jsx(Nn,{children:s.jsx(al,{})})})]})]})})},z1=t=>{const e=Ce.c(46),{title:n,showBack:r,onBack:o,onNewSession:a,onSettings:i,onAgentManager:l,showMcp:c,showContextUsage:d,showRateLimits:u}=t,{getCurrentModel:m}=Yt(),h=Le(jK),p=Qs(SK),g=Qs(kK),y=Qs(NK),b=Qs(CK),x=Qs(MK),v=Qs(AK),w=Qs(FK),C=Qs(DK);z4();let k,N;e[0]!==w?(k=()=>{w()},N=[w],e[0]=w,e[1]=k,e[2]=N):(k=e[1],N=e[2]),f.useEffect(k,N);let S;if(e[3]!==h||e[4]!==m){const Q=m(),te=Q?.limit&&typeof Q.limit=="object"?Q.limit:null,W=typeof te?.context=="number"?te.context:0,U=typeof te?.output=="number"?te.output:0;S=h(W,U),e[3]=h,e[4]=m,e[5]=S}else S=e[5];const j=S;let A;if(e[6]!==v||e[7]!==p){A=[];for(const Q of Do){if(!v.includes(Q.id))continue;const te=p.find(q=>q.providerId===Q.id),W=te?.usage?.windows??{},U=Object.entries(W),K=te&&!te.ok&&te.configured?te.error:void 0;(U.length>0||K)&&A.push({providerId:Q.id,providerName:Q.name,entries:U,error:K})}e[6]=v,e[7]=p,e[8]=A}else A=e[8];const M=A,F=M.length>0;let B;e[9]!==C?(B=async Q=>{C(Q);try{await Rs({usageDisplayMode:Q})}catch(te){console.warn("Failed to update usage display mode:",te)}},e[9]=C,e[10]=B):B=e[10];const D=B;let E;e[11]!==o||e[12]!==r?(E=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(c2,{className:"h-5 w-5"})}),e[11]=o,e[12]=r,e[13]=E):E=e[13];let I;e[14]!==n?(I=s.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:n,children:n}),e[14]=n,e[15]=I):I=e[15];let T;e[16]!==a?(T=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(Xs,{className:"h-5 w-5"})}),e[16]=a,e[17]=T):T=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($r,{className:"h-5 w-5"})}),e[18]=l,e[19]=H):H=e[19];let P;e[20]!==c?(P=c&&s.jsx(Wk,{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]=P):P=e[21];let _;e[22]!==g||e[23]!==D||e[24]!==F||e[25]!==y||e[26]!==x||e[27]!==b||e[28]!==p||e[29]!==M||e[30]!==u?(_=u&&s.jsxs(zs,{onOpenChange:Q=>{Q&&p.length===0&&g()},children:[s.jsx(Hs,{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:y,children:s.jsx(su,{className:"h-5 w-5"})})}),s.jsxs(Os,{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 ${x==="usage"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>{D("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 ${x==="remaining"?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:text-foreground"}`,onClick:()=>{D("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:()=>g(),disabled:y,"aria-label":"Refresh rate limits",children:s.jsx(Wn,{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 ",yK(b)]}),!F&&s.jsx(Qt,{className:"cursor-default",onSelect:_K,children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"No rate limits available."})}),M.map((Q,te)=>s.jsxs(f.Fragment,{children:[s.jsxs(Zr,{className:"flex items-center gap-2 bg-[var(--surface-elevated)] typography-ui-label text-foreground",children:[s.jsx(Dn,{providerId:Q.providerId,className:"h-4 w-4"}),Q.providerName]}),Q.entries.length===0?s.jsx(Qt,{className:"cursor-default",onSelect:BK,children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Q.error??"No rate limits reported."})},`${Q.providerId}-empty`):Q.entries.map(W=>{const[U,K]=W,q=x==="remaining"?K.remainingPercent:K.usedPercent,ee=qi(K.usedPercent,K.resetAt,K.windowSeconds,U),V=ee?.dailyAllocationPercent!=null?x==="remaining"?100-vo(ee.elapsedRatio):vo(ee.elapsedRatio):null;return s.jsx(Qt,{className:"cursor-default items-start",onSelect:EK,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:E0(U)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:xo(q)==="-"?"":xo(q)})]}),s.jsx(Gi,{percent:q,tonePercent:K.usedPercent,className:"h-1",expectedMarkerPercent:V}),ee&&s.jsx("div",{className:"mt-0.5",children:s.jsx(Zi,{paceInfo:ee,compact:!0})}),s.jsx("span",{className:"flex items-center justify-between typography-micro text-muted-foreground text-[10px]",children:s.jsx("span",{children:K.resetAfterFormatted??K.resetAtFormatted??""})})]})},`${Q.providerId}-${U}`)}),te<M.length-1&&s.jsx(Rn,{})]},Q.providerId))]})]}),e[22]=g,e[23]=D,e[24]=F,e[25]=y,e[26]=x,e[27]=b,e[28]=p,e[29]=M,e[30]=u,e[31]=_):_=e[31];let R;e[32]!==i?(R=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(ta,{className:"h-5 w-5"})}),e[32]=i,e[33]=R):R=e[33];let z;e[34]!==j||e[35]!==d?(z=d&&j&&j.totalTokens>0&&s.jsx(n7,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact"}),e[34]=j,e[35]=d,e[36]=z):z=e[36];let O;return e[37]!==_||e[38]!==R||e[39]!==z||e[40]!==E||e[41]!==I||e[42]!==T||e[43]!==H||e[44]!==P?(O=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:[E,I,T,H,P,_,R,z]}),e[37]=_,e[38]=R,e[39]=z,e[40]=E,e[41]=I,e[42]=T,e[43]=H,e[44]=P,e[45]=O):O=e[45],O};function jK(t){return t.getContextUsage}function SK(t){return t.results}function kK(t){return t.fetchAllQuotas}function NK(t){return t.isLoading}function CK(t){return t.lastUpdated}function MK(t){return t.displayMode}function AK(t){return t.dropdownProviderIds}function FK(t){return t.loadSettings}function DK(t){return t.setDisplayMode}function _K(t){return t.preventDefault()}function BK(t){return t.preventDefault()}function EK(t){return t.preventDefault()}const H1=t=>{const e=ls.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?Hn(t):null},Hn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},R6=(t,e)=>{const n=Hn(t),r=Hn(e);if(!n||!r)return!1;if(n===r)return!0;const o=r==="/"?"/":`${r}/`;return n.startsWith(o)},K9=async(t,e)=>{const n=Hn(e);if(!n)return n;try{const r=await t.path.get({directory:n});return Hn(r.data?.directory??"")||n}catch{return n}},Q9=async(t,e)=>{const n=Hn(e);if(!n)return[];const r=await K9(t,n),o=i=>i.filter(l=>{const c=Hn(l.directory??"");return c?R6(c,n)||r!==n&&R6(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[]}},IK=async(t,e)=>{const n=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&n.set(Hn(o.path),o.worktreeMetadata)});const r=Array.from(new Set(t.sessions.map(o=>Hn(o.path)))).filter(Boolean).filter(o=>!n.has(o));if(r.length===0)return n;try{const o=await gi({id:`path:${e}`,path:e}),a=new Map(o.map(i=>[Hn(i.path),i]));r.forEach(i=>{const l=a.get(i);l&&n.set(i,l)})}catch{}return n},TK=async t=>{const{apiClient:e,group:n,projectDirectory:r,worktreePaths:o}=t,a=await IK(n,r),i=Le.getState(),l=Array.from(new Set(o.map(h=>Hn(h)).filter(Boolean))),c=5;let d=0;const u=[],m=async()=>{for(;d<l.length;){const h=l[d];d+=1;const p=n.sessions.filter(v=>Hn(v.path)===h).map(v=>v.id),g=i.getSessionsByDirectory(h),y=Array.isArray(g)?g.map(v=>v.id):[];let b=[];if(y.length===0)try{b=(await Q9(e,h)).map(w=>w.id)}catch{b=[]}const x=Array.from(new Set([...y,...b,...p].filter(Boolean)));u.push({worktreePath:h,sessionIds:x,metadata:a.get(h)})}};return await Promise.all(Array.from({length:Math.min(c,l.length)},m)),u},Qd=async t=>{const e=zt.getApiClient(),n=await TK({apiClient:e,group:t.group,projectDirectory:t.projectDirectory,worktreePaths:t.worktreePaths}),r=Le.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 PK(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 Ma=xn()(In((t,e)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const n=Ds.getState().currentDirectory,r=H1(n);if(!r){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Hn(r),l={id:ls.getState().projects.find(d=>Hn(d.path)===o)?.id??`path:${o}`,path:o},c=e().groups;t({isLoading:!0,error:null});try{const d=zt.getApiClient(),u=await K9(d,o),m=u&&u!==o?{...l,path:u}:null,h=await gi(l).catch(()=>[]),p=m?await gi(m).catch(()=>[]):[],g=new Set,y=new Map;[...h,...p].forEach(S=>{if(S?.path){const j=Hn(S.path);g.add(j),y.has(j)||y.set(j,S)}});const b=async()=>{try{const j=await d.session.list({directory:o}),A=Array.isArray(j.data)?j.data:[];if(A.some(M=>{const F=Hn(M.directory??"");return F?g.has(F):!1}))return A}catch{}const S=await d.session.list(void 0);return Array.isArray(S.data)?S.data:[]},x=async S=>{const j=new Map,A=5;let M=0;const F=async()=>{for(;M<S.length;){const B=S[M];M+=1;const D=Hn(B);if(D)try{(await Q9(d,D)).forEach(I=>j.set(I.id,I))}catch(E){console.debug("Failed to fetch sessions from worktree:",D,E)}}};return await Promise.all(Array.from({length:Math.min(A,S.length)},F)),Array.from(j.values())};let w=(await b()).filter(S=>{const j=Hn(S.directory??"");return j?g.has(j):!1});if(w.length===0){const S=new Set;g.forEach(j=>S.add(j)),S.size>0&&(w=await x(Array.from(S)))}const C=new Map;for(const S of w){const j=S.time?.updated??0;C.set(S.id,typeof j=="number"?j:0)}const k=new Map;for(const S of w){const j=PK(S.title);if(!j)continue;const A=Hn(S.directory),M=y.get(A),F={id:S.id,path:A,providerId:j.provider,modelId:j.model,instanceNumber:j.index,branch:M?.branch??"",displayLabel:`${j.provider}/${j.model}`,worktreeMetadata:M},B=k.get(j.groupSlug);B?B.push(F):k.set(j.groupSlug,[F])}const N=Array.from(k.entries()).map(([S,j])=>{const A=j.reduce((M,F)=>{const B=C.get(F.id)??0;return Math.max(M,B)},0);return{name:S,sessions:j.sort((M,F)=>{const B=M.providerId.localeCompare(F.providerId);if(B!==0)return B;const D=M.modelId.localeCompare(F.modelId);return D!==0?D:M.instanceNumber-F.instanceNumber}),lastActive:A||Date.now(),sessionCount:j.length}});N.sort((S,j)=>S.name.localeCompare(j.name)),t({groups:N,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=Ds.getState().currentDirectory,a=H1(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:i}=await Qd({group:r,projectDirectory:Hn(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=Hn(r);if(!a)return!1;const i=Ds.getState().currentDirectory,l=H1(i);if(!l)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:c}=await Qd({group:o,projectDirectory:Hn(l),worktreePaths:[a]});c.length>0&&t({error:"Failed to delete some sessions"}),await e().loadGroups();const d=e().groups.find(u=>u.name===n);if(!d)return e().selectedGroupName===n&&t({selectedGroupName:null,selectedSessionId:null}),c.length===0;if(e().selectedGroupName===n){const u=e().selectedSessionId,m=new Set(d.sessions.map(h=>h.id));(!u||!m.has(u))&&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(u=>u.name===n);if(!o)return!1;const a=Hn(r);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(u=>Hn(u.path)).filter(Boolean))).filter(u=>u!==a);if(l.length===0)return!0;const c=Ds.getState().currentDirectory,d=H1(c);if(!d)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const{failedIds:u}=await Qd({group:o,projectDirectory:Hn(d),worktreePaths:l});if(u.length>0&&t({error:"Failed to delete some sessions"}),await e().loadGroups(),e().selectedGroupName===n){const m=e().groups.find(p=>p.name===n),h=m?.sessions.find(p=>Hn(p.path)===a)??m?.sessions[0]??null;t({selectedSessionId:h?.id??null})}return u.length===0}catch(u){return t({error:u instanceof Error?u.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"})),RK=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`},LK=t=>{const e=Ce.c(62),{group:n,isSelected:r,onSelect:o}=t,[a,i]=f.useState(!1),[l,c]=f.useState(!1),[d,u]=f.useState(!1),m=Ma(HK);let h;e[0]!==m||e[1]!==n.name||e[2]!==d?(h=async()=>{if(d)return;if(u(!0),ue.info(`Deleting "${n.name}"...`),await m(n.name))ue.success(`Deleted "${n.name}"`);else{const q=Ma.getState().error;ue.error(q||`Failed to delete "${n.name}"`)}u(!1),c(!1)},e[0]=m,e[1]=n.name,e[2]=d,e[3]=h):h=e[3];const p=h,g=r?"bg-interactive-selection":"hover:bg-interactive-hover";let y;e[4]!==g?(y=J("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",g),e[4]=g,e[5]=y):y=e[5];let b;e[6]!==n.name?(b=s.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:n.name}),e[6]=n.name,e[7]=b):b=e[7];let x;e[8]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx(cn,{className:"h-3 w-3"}),e[8]=x):x=e[8];const v=n.sessionCount!==1?"s":"";let w;e[9]!==n.sessionCount||e[10]!==v?(w=s.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[x,n.sessionCount," model",v]}),e[9]=n.sessionCount,e[10]=v,e[11]=w):w=e[11];let C;e[12]!==n.lastActive?(C=RK(n.lastActive),e[12]=n.lastActive,e[13]=C):C=e[13];let k;e[14]!==C?(k=s.jsx("span",{className:"typography-micro text-muted-foreground/60",children:C}),e[14]=C,e[15]=k):k=e[15];let N;e[16]!==w||e[17]!==k?(N=s.jsxs("div",{className:"flex items-center gap-2",children:[w,k]}),e[16]=w,e[17]=k,e[18]=N):N=e[18];let S;e[19]!==N||e[20]!==b?(S=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:[b,N]}),e[19]=N,e[20]=b,e[21]=S):S=e[21];const j=a&&"opacity-100";let A;e[22]!==j?(A=J("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",j),e[22]=j,e[23]=A):A=e[23];let M;e[24]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(mo,{className:"h-3.5 w-3.5"}),e[24]=M):M=e[24];let F;e[25]!==A?(F=s.jsx(Hs,{asChild:!0,children:s.jsx("button",{type:"button",className:A,"aria-label":"Group menu",onClick:OK,children:M})}),e[25]=A,e[26]=F):F=e[26];let B;e[27]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(Os,{align:"end",className:"min-w-[140px]",children:s.jsx(Qt,{variant:"destructive",onSelect:K=>{K.stopPropagation(),i(!1),c(!0)},children:"Delete"})}),e[27]=B):B=e[27];let D;e[28]!==a||e[29]!==F?(D=s.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:s.jsxs(zs,{open:a,onOpenChange:i,children:[F,B]})}),e[28]=a,e[29]=F,e[30]=D):D=e[30];let E;e[31]!==S||e[32]!==D?(E=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[S,D]}),e[31]=S,e[32]=D,e[33]=E):E=e[33];let I;e[34]!==o||e[35]!==E||e[36]!==y?(I=s.jsx("div",{className:y,onClick:o,children:E}),e[34]=o,e[35]=E,e[36]=y,e[37]=I):I=e[37];let T;e[38]===Symbol.for("react.memo_cache_sentinel")?(T=s.jsx(Us,{children:"Delete agent group"}),e[38]=T):T=e[38];let H;e[39]!==n.name?(H=s.jsxs(Zs,{children:[T,s.jsxs(tn,{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 P;e[41]===Symbol.for("react.memo_cache_sentinel")?(P=()=>c(!1),e[41]=P):P=e[41];let _;e[42]!==d?(_=s.jsx(ot,{variant:"outline",onClick:P,disabled:d,children:"Cancel"}),e[42]=d,e[43]=_):_=e[43];let R;e[44]!==p?(R=()=>{p()},e[44]=p,e[45]=R):R=e[45];const z=d?"Deleting…":"Delete";let O;e[46]!==d||e[47]!==R||e[48]!==z?(O=s.jsx(ot,{variant:"destructive",onClick:R,disabled:d,children:z}),e[46]=d,e[47]=R,e[48]=z,e[49]=O):O=e[49];let Q;e[50]!==_||e[51]!==O?(Q=s.jsxs(vn,{children:[_,O]}),e[50]=_,e[51]=O,e[52]=Q):Q=e[52];let te;e[53]!==H||e[54]!==Q?(te=s.jsxs(Vs,{className:"max-w-md",keyboardAvoid:!0,children:[H,Q]}),e[53]=H,e[54]=Q,e[55]=te):te=e[55];let W;e[56]!==l||e[57]!==te?(W=s.jsx($s,{open:l,onOpenChange:c,children:te}),e[56]=l,e[57]=te,e[58]=W):W=e[58];let U;return e[59]!==I||e[60]!==W?(U=s.jsxs(s.Fragment,{children:[I,W]}),e[59]=I,e[60]=W,e[61]=U):U=e[61],U},zK=t=>{const e=Ce.c(54),{className:n,selectedGroupName:r,onGroupSelect:o,onNewAgent:a}=t,[i,l]=f.useState(""),[c,d]=f.useState(!1),{groups:u,isLoading:m,loadGroups:h}=Ma(),p=Ds($K);let g,y;e[0]!==p||e[1]!==h?(g=()=>{p&&h()},y=[p,h],e[0]=p,e[1]=h,e[2]=g,e[3]=y):(g=e[2],y=e[3]),f.useEffect(g,y);let b;e:{if(!i.trim()){b=u;break e}let O;if(e[4]!==u||e[5]!==i){const Q=i.toLowerCase();O=u.filter(te=>te.name.toLowerCase().includes(Q)),e[4]=u,e[5]=i,e[6]=O}else O=e[6];b=O}const x=b;let v;e[7]!==x||e[8]!==c?(v=c?x:x.slice(0,5),e[7]=x,e[8]=c,e[9]=v):v=e[9];const w=v,C=x.length-5;let k;e[10]!==n?(k=J("flex h-full flex-col text-foreground border-r border-border/30",n),e[10]=n,e[11]=k):k=e[11];let N;e[12]===Symbol.for("react.memo_cache_sentinel")?(N=s.jsx(ur,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e[12]=N):N=e[12];let S;e[13]===Symbol.for("react.memo_cache_sentinel")?(S=O=>l(O.target.value),e[13]=S):S=e[13];let j;e[14]!==i?(j=s.jsx("div",{className:"px-2.5 pt-3 pb-2",children:s.jsxs("div",{className:"relative",children:[N,s.jsx(ts,{value:i,onChange:S,placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e[14]=i,e[15]=j):j=e[15];let A,M;e[16]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(Xs,{className:"h-4 w-4"}),A=s.jsx("span",{className:"typography-ui-label",children:"New Agent Group"}),e[16]=A,e[17]=M):(A=e[16],M=e[17]);let F;e[18]!==a?(F=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:[M,A]})}),e[18]=a,e[19]=F):F=e[19];let B,D;e[20]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(Ls,{className:"h-4 w-4 text-muted-foreground"}),D=s.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),e[20]=B,e[21]=D):(B=e[20],D=e[21]);let E;e[22]!==m?(E=m&&s.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."}),e[22]=m,e[23]=E):E=e[23];let I;e[24]!==E?(I=s.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[B,D,E]}),e[24]=E,e[25]=I):I=e[25];let T;if(e[26]!==o||e[27]!==r||e[28]!==w){let O;e[30]!==o||e[31]!==r?(O=Q=>s.jsx(LK,{group:Q,isSelected:r===Q.name,onSelect:()=>o?.(Q.name)},Q.name),e[30]=o,e[31]=r,e[32]=O):O=e[32],T=w.map(O),e[26]=o,e[27]=r,e[28]=w,e[29]=T}else T=e[29];let H;e[33]!==C||e[34]!==c?(H=!c&&C>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 (",C,")"]}),e[33]=C,e[34]=c,e[35]=H):H=e[35];let P;e[36]!==x.length||e[37]!==c?(P=c&&x.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]=x.length,e[37]=c,e[38]=P):P=e[38];let _;e[39]!==x.length||e[40]!==m||e[41]!==i?(_=!m&&x.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]=x.length,e[40]=m,e[41]=i,e[42]=_):_=e[42];let R;e[43]!==T||e[44]!==H||e[45]!==P||e[46]!==_?(R=s.jsxs(Ns,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[T,H,P,_]}),e[43]=T,e[44]=H,e[45]=P,e[46]=_,e[47]=R):R=e[47];let z;return e[48]!==F||e[49]!==I||e[50]!==R||e[51]!==k||e[52]!==j?(z=s.jsxs("div",{className:k,children:[j,F,I,R]}),e[48]=F,e[49]=I,e[50]=R,e[51]=k,e[52]=j,e[53]=z):z=e[53],z};function HK(t){return t.deleteGroup}function OK(t){return t.stopPropagation()}function $K(t){return t.currentDirectory}const VK=10*1024*1024,UK=5,WK=({className:t,onCreateGroup:e,isCreating:n=!1})=>{const[r,o]=f.useState(""),[a,i]=f.useState(""),[l,c]=f.useState([]),[d,u]=f.useState(""),[m,h]=f.useState("HEAD"),[p,g]=f.useState([]),[y,b]=f.useState(!1),[x,v]=f.useState([]),[w,C]=f.useState(!1),[k,N]=f.useState(!1),S=f.useRef(null),j=f.useRef(null),{currentTheme:A}=ir(),M=Ds(K=>K.currentDirectory??null),{isGitRepository:F,isLoading:B}=x3(M),D=f.useMemo(()=>{if(typeof window>"u")return null;const K=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof K=="string"&&K.trim().length>0?K.trim():null},[]),E=f.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),I=ls(K=>K.activeProjectId),T=ls(K=>K.projects),H=f.useMemo(()=>{if(E&&D)return{id:`vscode:${D}`,path:D};if(I){const K=T.find(q=>q.id===I);if(K?.path)return{id:K.id,path:K.path}}return M?{id:`path:${M}`,path:M}:null},[I,T,M,D,E]);f.useEffect(()=>{if(!H)return;let K=!1;return N(!0),(async()=>{try{const q=await Ci(H);K||v(q)}catch{}finally{K||N(!1)}})(),()=>{K=!0}},[H]);const P=f.useCallback(K=>{l.length>=UK||c(q=>[...q,K])},[l.length]),_=f.useCallback(K=>{c(q=>q.filter((ee,V)=>V!==K))},[]),R=f.useCallback((K,q)=>{c(ee=>ee.map((V,G)=>G===K?q:V))},[]),z=async K=>{const q=K.target.files;if(!q)return;let ee=0;for(let V=0;V<q.length;V++){const G=q[V];if(G.size>VK){ue.error(`File "${G.name}" is too large (max 10MB)`);continue}try{const Y=await new Promise((re,fe)=>{const ie=new FileReader;ie.onload=()=>re(ie.result),ie.onerror=fe,ie.readAsDataURL(G)}),oe={id:e2(),filename:G.name,mimeType:G.type||"application/octet-stream",size:G.size,dataUrl:Y};g(re=>[...re,oe]),ee++}catch(Y){console.error("File attach failed",Y),ue.error(`Failed to attach "${G.name}"`)}}ee>0&&ue.success(`Attached ${ee} file${ee>1?"s":""}`),S.current&&(S.current.value="")},O=K=>{g(q=>q.filter(ee=>ee.id!==K))},Q=y||n,te=!!(r.trim()&&a.trim()&&l.length>=1&&F&&!B),W=async K=>{if(K.preventDefault(),!(!te||Q)){b(!0);try{const q=l.map(({providerID:G,modelID:Y,displayName:oe,variant:re})=>({providerID:G,modelID:Y,displayName:oe,variant:re})),ee=p.length>0?p.map(G=>({mime:G.mimeType,filename:G.filename,url:G.dataUrl})):void 0,V=x.filter(G=>G.trim().length>0);await e?.({name:r.trim(),prompt:a.trim(),models:q,agent:d||void 0,worktreeBaseBranch:m,files:ee,setupCommands:V.length>0?V:void 0}),o(""),i(""),c([]),u(""),g([]),h("HEAD")}catch(q){console.error("Failed to create agent group:",q),ue.error("Failed to create agent group")}finally{b(!1)}}},U=K=>{J4(K)||K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),te&&!Q&&W(K))};return s.jsx("div",{className:J("flex flex-col items-center justify-center h-full w-full p-4",t),children:s.jsxs("form",{onSubmit:W,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(ts,{id:"group-name",value:r,onChange:K=>o(K.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(cn,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),s.jsx(G9,{directory:M,value:m,onChange:h}),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(Vr,{open:w,onOpenChange:C,children:[s.jsxs(ho,{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(K=>K.trim()).length>0&&s.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(K=>K.trim()).length," configured)"]})]}),s.jsx(Ls,{className:J("h-4 w-4 text-muted-foreground transition-transform duration-200",w&&"rotate-180")})]}),s.jsx(Ur,{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."]}),k?s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):s.jsxs("div",{className:"space-y-1.5",children:[x.map((K,q)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx(ts,{value:K,onChange:ee=>{const V=[...x];V[q]=ee.target.value,v(V)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>{const ee=x.filter((V,G)=>G!==q);v(ee)},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(_s,{className:"h-4 w-4"})})]},q)),s.jsxs("button",{type:"button",onClick:()=>v([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(Xs,{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(Z9,{value:d,onChange:u}),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(q9,{selectedModels:l,onAdd:P,onRemove:_,onUpdate:R,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:A?.colors?.surface?.subtle},children:[s.jsx(dr,{ref:j,id:"prompt",value:a,onChange:K=>i(K.target.value),onKeyDown:U,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"}),p.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:p.map(K=>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:[K.mimeType.startsWith("image/")?s.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground"}):s.jsx(ui,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[120px]",title:K.filename,children:K.filename}),s.jsx("button",{type:"button",onClick:()=>O(K.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:s.jsx(_s,{className:"h-3.5 w-3.5"})})]},K.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:S,type:"file",multiple:!0,className:"hidden",onChange:z,accept:"*/*"}),s.jsx("button",{type:"button",onClick:()=>S.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(yp,{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:!te||Q,className:J("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",te?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:Q?s.jsx(av,{className:"h-[18px] w-[18px] animate-spin"}):s.jsx(nu,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},qK=({group:t,className:e})=>{const{selectedSessionId:n,selectSession:r,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Ma(),{setCurrentSession:i,currentSessionId:l}=Le(),[c,d]=f.useState(null),[u,m]=f.useState(!1),h=f.useMemo(()=>n?t.sessions.find(w=>w.id===n)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,n]),p=f.useCallback(w=>{r(w.id),i(w.id)},[r,i]);f.useEffect(()=>{if(t.sessions.length>0){const w=n?t.sessions.find(C=>C.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 g=h?.id===l,y=f.useCallback(()=>{if(!h?.path){ue.error("No worktree path available");return}Cn(h.path).then(w=>{if(w.ok){ue.success("Worktree path copied");return}ue.error("Failed to copy path")})},[h?.path]),b=f.useCallback(async()=>{h&&d({kind:"remove",path:h.path,label:h.displayLabel})},[h]),x=f.useCallback(async()=>{h&&d({kind:"keepOnly",path:h.path,label:h.displayLabel})},[h]),v=f.useCallback(async()=>{if(!(!c||u)){m(!0);try{if(c.kind==="remove")if(ue.info("Removing worktree..."),await o(t.name,c.path))ue.success("Worktree removed");else{const C=Ma.getState().error;ue.error(C||"Failed to remove worktree");return}else if(ue.info("Removing other worktrees..."),await a(t.name,c.path))ue.success("Removed other worktrees");else{const C=Ma.getState().error;ue.error(C||"Failed to remove other worktrees");return}d(null)}finally{m(!1)}}},[o,t.name,u,a,c]);return s.jsxs("div",{className:J("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(cn,{className:"h-3.5 w-3.5"}),h?.worktreeMetadata?.label||h?.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(zs,{children:[s.jsx(Hs,{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:h&&s.jsxs(s.Fragment,{children:[s.jsx(Dn,{providerId:h.providerId,className:"h-5 w-5 flex-shrink-0"}),s.jsx("span",{className:"truncate typography-body",children:h.modelId}),h.instanceNumber>1&&s.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",h.instanceNumber]})]})}),s.jsx(Ls,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(Os,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(w=>s.jsxs(Qt,{onClick:()=>p(w),className:"flex items-center gap-2 py-2",children:[s.jsx(Dn,{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(cn,{className:"h-3 w-3"}),s.jsx("span",{className:"truncate",children:w.worktreeMetadata?.label||w.branch})]})]}),h?.id===w.id&&s.jsx(vs,{className:"h-4 w-4 text-primary flex-shrink-0"})]},w.id))})]})}),s.jsxs(zs,{children:[s.jsx(Hs,{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(mo,{className:"h-4 w-4"})})}),s.jsxs(Os,{align:"end",className:"min-w-[220px]",children:[s.jsx(Qt,{onSelect:w=>{w.preventDefault(),b()},variant:"destructive",children:"Remove this worktree"}),s.jsx(Qt,{onSelect:w=>{w.preventDefault(),x()},children:"Leave this one, remove others"}),s.jsxs(Qt,{onClick:w=>{w.stopPropagation(),y()},disabled:!h?.path,children:[s.jsx(Jn,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),s.jsx($s,{open:!!c,onOpenChange:w=>{w||d(null)},children:s.jsxs(Vs,{className:"max-w-md",keyboardAvoid:!0,children:[s.jsxs(Zs,{children:[s.jsx(Us,{children:c?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),s.jsx(tn,{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(vn,{children:[s.jsx(ot,{variant:"outline",onClick:()=>d(null),disabled:u,children:"Cancel"}),s.jsx(ot,{variant:c?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:u,children:u?"Working…":c?.kind==="remove"?"Remove":"Remove others"})]})]})}),s.jsx("div",{className:"flex-1 min-h-0",children:h?g?s.jsx($g,{sessionId:h.id,children:s.jsx(Og,{})}):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(Dn,{providerId:h.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"font-medium text-foreground",children:h.displayLabel}),s.jsx("span",{children:"·"}),s.jsx("span",{className:"font-mono text-xs truncate",children:h.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:h.displayLabel})]}),s.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",h.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"})})})]})},GK=({className:t})=>{const e=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[n,r]=f.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=Yt(w=>w.isInitialized),a=Yt(w=>w.initializeApp),i=Le(w=>w.loadSessions),l=Ds(w=>w.setDirectory),c=f.useRef(0),{selectedGroupName:d,selectGroup:u,getSelectedGroup:m,loadGroups:h}=Ma(),{createMultiRun:p,isLoading:g}=pc();f.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 C=k=>{const S=k.detail?.status;(S==="connected"||S==="connecting"||S==="error"||S==="disconnected")&&r(S)};return window.addEventListener("openchamber:connection-status",C),()=>window.removeEventListener("openchamber:connection-status",C)},[e]),f.useEffect(()=>{if(!e||n!=="connected")return;const w=Date.now();if(w-c.current<750)return;c.current=w;const C=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof C=="string"&&C.trim().length>0)try{l(C,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const N=Yt.getState();if(!N.isInitialized||!N.isConnected||N.providers.length===0||N.agents.length===0)return;await i(),Kn()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:N.providers.length,agents:N.agents.length,sessions:Le.getState().sessions.length})}catch{}})()},[n,o,a,e,i,l]);const y=f.useCallback(w=>{u(w)},[u]),b=f.useCallback(()=>{u(null)},[u]),x=f.useCallback(async w=>{ue.info(`Creating agent group "${w.name}" with ${w.models.length} model(s)...`);const C=await p(w);if(C){ue.success(`Agent group "${w.name}" created with ${C.sessionIds.length} session(s)`);const k=C.groupSlug,N=async(S=6)=>{for(let j=0;j<S;j+=1){if(await h(),Ma.getState().groups.some(M=>M.name===k))return!0;await new Promise(M=>setTimeout(M,500))}return!1};try{await Le.getState().loadSessions()}catch{}await N(),u(k)}else{const k=pc.getState().error;ue.error(k||"Failed to create agent group")}},[p,h,u]),v=m();return s.jsxs("div",{className:J("flex h-full w-full bg-background",t),children:[s.jsx("div",{className:"w-64 flex-shrink-0",children:s.jsx(zK,{selectedGroupName:d,onGroupSelect:y,onNewAgent:b})}),s.jsx("div",{className:"flex-1 min-w-0",children:v?s.jsx(qK,{group:v}):s.jsx(WK,{onCreateGroup:x,isCreating:g})})]})},ZK=t=>{const e=Ce.c(51),{onClose:n}=t,{sessions:r,messages:o,sessionMemoryState:a,currentSessionId:i}=Le(),l=jo(KK);let c;e[0]!==o?(c=0,o.forEach(H=>{c=c+H.length}),e[0]=o,e[1]=c):c=e[1];const d=c;let u;if(e[2]!==i||e[3]!==o||e[4]!==a||e[5]!==r){let H;e[7]!==i||e[8]!==o||e[9]!==a?(H=P=>{const _=o.get(P.id)?.length||0,R=a.get(P.id);return{id:P.id,title:P.title||"Untitled",messageCount:_,isStreaming:R?.isStreaming||!1,isZombie:R?.isZombie||!1,backgroundCount:R?.backgroundMessageCount||0,lastAccessed:R?.lastAccessedAt||0,isCurrent:P.id===i}},e[7]=i,e[8]=o,e[9]=a,e[10]=H):H=e[10],u=r.map(H).sort(QK),e[2]=i,e[3]=o,e[4]=a,e[5]=r,e[6]=u}else u=e[6];const m=u,h=o.size;let p;e[11]===Symbol.for("react.memo_cache_sentinel")?(p=s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(sp,{className:"h-4 w-4"}),s.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),e[11]=p):p=e[11];let g;e[12]!==n?(g=n&&s.jsx(ot,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(_s,{className:"h-4 w-4"})}),e[12]=n,e[13]=g):g=e[13];let y;e[14]!==g?(y=s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[p,g]}),e[14]=g,e[15]=y):y=e[15];let b;e[16]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e[16]=b):b=e[16];let x;e[17]!==d?(x=s.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[b,s.jsx("div",{className:"typography-markdown font-semibold",children:d})]}),e[17]=d,e[18]=x):x=e[18];let v;e[19]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e[19]=v):v=e[19];let w;e[20]!==h?(w=s.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[v,s.jsxs("div",{className:"typography-markdown font-semibold",children:[h," / ",Cu.MAX_SESSIONS]})]}),e[20]=h,e[21]=w):w=e[21];let C;e[22]!==x||e[23]!==w?(C=s.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[x,w]}),e[22]=x,e[23]=w,e[24]=C):C=e[24];let k;e[25]===Symbol.for("react.memo_cache_sentinel")?(k=s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),s.jsxs("span",{children:[H8()," messages"]})]}),e[25]=k):k=e[25];let N;e[26]===Symbol.for("react.memo_cache_sentinel")?(N=s.jsxs("div",{className:"flex justify-between",children:[s.jsx("span",{className:"text-muted-foreground",children:"Zombie Timeout:"}),s.jsxs("span",{children:[Cu.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]}),e[26]=N):N=e[26];let S;e[27]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx("span",{className:"text-muted-foreground",children:"GitHub Total Requests:"}),e[27]=S):S=e[27];let j;e[28]!==l?(j=s.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[k,N,s.jsxs("div",{className:"flex justify-between",children:[S,s.jsx("span",{children:l})]})]}),e[28]=l,e[29]=j):j=e[29];let A;e[30]===Symbol.for("react.memo_cache_sentinel")?(A=s.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e[30]=A):A=e[30];let M;e[31]!==m?(M=m.map(YK),e[31]=m,e[32]=M):M=e[32];let F;e[33]!==M?(F=s.jsxs("div",{className:"border-t pt-2",children:[A,s.jsx(Ns,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:M})]}),e[33]=M,e[34]=F):F=e[34];let B;e[35]!==i||e[36]!==o||e[37]!==a||e[38]!==r?(B=s.jsx(Ut,{asChild:!0,children:s.jsx(ot,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(JK),currentSessionId:i,cachedSessions:Array.from(o.keys()),memoryStates:Object.fromEntries(a)})},children:"Log State"})}),e[35]=i,e[36]=o,e[37]=a,e[38]=r,e[39]=B):B=e[39];let D;e[40]===Symbol.for("react.memo_cache_sentinel")?(D=s.jsx($t,{side:"top",children:"Log current memory state to browser console"}),e[40]=D):D=e[40];let E;e[41]!==B?(E=s.jsx("div",{className:"flex gap-2 pt-2 border-t",children:s.jsxs(Vt,{delayDuration:1e3,children:[B,D]})}),e[41]=B,e[42]=E):E=e[42];let I;e[43]!==j||e[44]!==F||e[45]!==E||e[46]!==C?(I=s.jsxs("div",{className:"space-y-3",children:[C,null,j,F,E]}),e[43]=j,e[44]=F,e[45]=E,e[46]=C,e[47]=I):I=e[47];let T;return e[48]!==I||e[49]!==y?(T=s.jsxs(U4,{className:"fixed bottom-4 right-4 w-96 p-4 shadow-none z-50 bg-background/95 backdrop-blur bottom-safe-area",children:[y,I]}),e[48]=I,e[49]=y,e[50]=T):T=e[50],T};function KK(t){return t.totalRequestCount}function QK(t,e){return e.lastAccessed-t.lastAccessed}function YK(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(iv,{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>Eo()?"text-status-warning":""}`,children:[t.messageCount," msgs"]}),t.backgroundCount>0&&s.jsxs("span",{className:"text-primary",children:["+",t.backgroundCount]})]})]},t.id)}function JK(t){return{id:t.id,title:t.title}}const XK="openchamber-message-cursors",t2="cursors",eQ=1,Y9="openchamber.messageCursors",v3=()=>typeof window<"u",J9=()=>v3()&&typeof indexedDB<"u",tQ=()=>J9()?new Promise((t,e)=>{const n=indexedDB.open(XK,eQ);n.onupgradeneeded=()=>{const r=n.result;r.objectStoreNames.contains(t2)||r.createObjectStore(t2)},n.onerror=()=>{e(n.error??new Error("Failed to open IndexedDB"))},n.onsuccess=()=>{t(n.result)}}):Promise.reject(new Error("IndexedDB not supported")),sQ=()=>{if(!v3())return{};try{const t=window.localStorage.getItem(Y9);if(!t)return{};const e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}},nQ=t=>{if(v3())try{window.localStorage.setItem(Y9,JSON.stringify(t))}catch{}},rQ=async(t,e,n)=>{if(!t||!e)return;if(J9())try{const o=await tQ();await new Promise((a,i)=>{const l=o.transaction(t2,"readwrite");l.objectStore(t2).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=sQ();r[t]={messageId:e,completedAt:n},nQ(r)},L6=(t,e)=>{const n=t.trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-3))}...`},oQ=({sessionTitle:t,permissionBody:e,disabled:n=!1,onOnce:r,onAlways:o,onDeny:a})=>{const[i,l]=f.useState(!1),c=t.trim().length>0?` for ${t}`:"",d=L6(t,64)||"Session",u=L6(e,120)||"Permission details unavailable",m=async h=>{if(!(i||n)){l(!0);try{await h()}finally{l(!1)}}};return s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"mb-1.5 min-w-0 space-y-0.5",children:[s.jsxs("p",{className:"typography-meta text-muted-foreground",title:t,children:["Session:"," ",s.jsx("span",{className:"inline-block max-w-[280px] align-bottom truncate text-foreground",children:d})]}),s.jsxs("p",{className:"typography-meta text-muted-foreground",title:e,children:["Permission:"," ",s.jsx("span",{className:"inline-block max-w-[280px] align-bottom truncate",children:u})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>m(r),disabled:n||i,"aria-label":`Approve once${c}`,className:J("px-2 py-1 typography-meta font-medium rounded transition-colors h-6","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:"Once"}),s.jsx("button",{onClick:()=>m(o),disabled:n||i,"aria-label":`Approve always${c}`,className:J("px-2 py-1 typography-meta font-medium rounded transition-colors h-6","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:"Always"}),s.jsx("button",{onClick:()=>m(a),disabled:n||i,"aria-label":`Deny permission${c}`,className:J("px-2 py-1 typography-meta font-medium rounded transition-colors h-6","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:"Deny"})]})]})},Vn=(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},z6=t=>Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(e=>e.length>0):[],H6=t=>{if(!t||typeof t!="object")return null;const e=t,n=Vn(e,["id"]),r=Vn(e,["sessionID"]);if(!n||!r)return null;const o=typeof e.permission=="string"?e.permission:"",a=z6(e.patterns),i=typeof e.metadata=="object"&&e.metadata!==null?e.metadata:{},l=z6(e.always),c=e.tool,d=c&&typeof c=="object"?{messageID:Vn(c,["messageID"])??"",callID:Vn(c,["callID"])??""}:void 0;return{id:n,sessionID:r,permission:o,patterns:a,metadata:i,always:l,tool:d&&d.messageID.length>0&&d.callID.length>0?d:void 0}},aQ=t=>{const e=["command","cmd","script","path","filePath","filepath","file_path","directory","working_directory","cwd","url","uri","endpoint","description","action","operation"];for(let r=0;r<e.length;r++){const o=t[e[r]];if(typeof o=="string"){const a=o.trim();if(a.length>0)return a;continue}if(typeof o=="number"||typeof o=="boolean")return String(o);if(Array.isArray(o)){const a=o.filter(i=>typeof i=="string"&&i.trim().length>0).slice(0,3).join(", ").trim();if(a.length>0)return a}}if(Object.entries(t).length===0)return"";try{return JSON.stringify(t)}catch{return""}},iQ=t=>{const n=(Array.isArray(t.patterns)?t.patterns:[]).filter(i=>typeof i=="string"&&i.trim().length>0).join(", ").trim(),r=typeof t.metadata=="object"&&t.metadata!==null?t.metadata:{},o=aQ(r);if(n.length>0&&o.length>0)return`${n} | ${o}`;if(n.length>0)return n;if(o.length>0)return o;const a=typeof t.permission=="string"?t.permission.trim():"";return a.length>0?a:"Permission details unavailable"},lQ=750,cQ=1500,dQ=1500,Yd=t=>Vn(t,["directory"])??"global",uQ=500,fQ=100,Qa=new Map,O6=(t,e)=>{const n=`${t}:${e}`,r=Qa.get(n);if(r&&r.sessionId===t)return r.message;const i=(Le.getState().messages.get(t)||[]).find(l=>l.info.id===e)||null;if(Qa.size>=uQ){let l=0;for(const c of Qa.keys()){if(l++>=fQ)break;Qa.delete(c)}}return Qa.set(n,{sessionId:t,message:i}),i},$6=(t,e)=>(Le.getState().messages.get(t)||[]).find(o=>o.info.id===e)||null,mQ=t=>{const e=t?.enabled??!0,{addStreamingPart:n,applyPartDelta:r,completeStreamingMessage:o,updateMessageInfo:a,updateSessionCompaction:i,addPermission:l,dismissPermission:c,addQuestion:d,dismissQuestion:u,currentSessionId:m,applySessionMetadata:h,getWorktreeMetadata:p,loadMessages:g,loadSessions:y,updateSession:b,removeSessionFromStore:x}=Le(),{checkConnection:v}=Yt(),w=Ds(Ke=>Ke.currentDirectory),C=f.useMemo(()=>{if(!m)return;try{const Ge=p?.(m);if(Ge?.path)return Ge.path}catch(Ge){console.warn("Failed to inspect worktree metadata for session directory:",Ge)}const ye=Le.getState().sessions.find(Ge=>Ge.id===m);if(ye&&typeof ye.directory=="string"&&ye.directory.trim().length>0)return ye.directory.trim()},[m,p]),k=f.useMemo(()=>{if(C&&C.length>0)return C;if(typeof w=="string"&&w.trim().length>0)return w.trim()},[C,w]),N=f.useCallback(async()=>{try{const ye=ls.getState().projects.map(jt=>jt.path),Ee=Le.getState().sessions.map(jt=>jt.directory),$e=[k,...ye,...Ee],tt=await zt.listPendingQuestions({directories:$e});if(tt.length===0)return;for(const jt of tt)d(jt)}catch{}},[d,k]),S=f.useRef(0),j=f.useCallback((Ke=!1)=>{const ye=Date.now();!Ke&&ye-S.current<cQ||(S.current=ye,N())},[N]),A=f.useCallback(async()=>{try{const ye=ls.getState().projects.map(jt=>jt.path),Ee=Le.getState().sessions.map(jt=>jt.directory),$e=[k,...ye,...Ee],tt=await zt.listPendingPermissions({directories:$e});if(tt.length===0)return;for(const jt of tt){const ct=H6(jt);ct&&l(ct)}}catch{}},[l,k]),M=f.useRef(0),F=f.useCallback((Ke=!1)=>{const ye=Date.now();!Ke&&ye-M.current<dQ||(M.current=ye,A())},[A]),B=f.useRef(F);f.useEffect(()=>{B.current=F},[F]),f.useEffect(()=>{e&&(F(!0),j(!0))},[e,F,j]);const D=f.useCallback(Ke=>{if(typeof Ke!="string")return null;const ye=Ke.trim();if(!ye)return null;const Ge=ye.replace(/\\/g,"/");return Ge.length>1?Ge.replace(/\/+$/,""):Ge},[]),E=f.useCallback(Ke=>{if(!Ke)return null;try{const Ee=p?.(Ke),$e=D(Ee?.path??null);if($e)return $e}catch{}const Ge=Le.getState().sessions.find(Ee=>Ee.id===Ke);return D(Ge?.directory??null)},[p,D]),I=De(Ke=>Ke.setEventStreamStatus),T=f.useRef(null),H=f.useCallback((Ke,ye)=>{const Ge=ye??null,Ee=T.current;if(!(Ee&&Ee.status===Ke&&Ee.hint===Ge)){if(T.current={status:Ke,hint:Ge},Kn()){const tt={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Ke]??"[INFO]",jt=Ge?`${tt} SSE ${Ke}: ${Ge}`:`${tt} SSE ${Ke}`;console.info(jt)}I(Ke,Ge)}},[I]),P=f.useCallback((Ke,ye,Ge)=>{if(!Ke)return Promise.resolve();const Ee=Date.now();if(V.current)return V.current;if(Ee-G.current<lQ)return Promise.resolve();const $e=g(Ke,Ge).catch(tt=>{console.warn(`[useEventStream] Failed to resync messages (${ye}):`,tt)}).finally(()=>{V.current=null,G.current=Date.now()});return V.current=$e,$e},[g]),_=f.useCallback(async Ke=>{Kn()&&console.info("[useEventStream] Bootstrapping state:",Ke);try{const ye=Eo();await Promise.all([y(),m?P(m,Ke,ye):Promise.resolve()])}catch(ye){console.warn("[useEventStream] Bootstrap failed:",Ke,ye)}},[m,y,P]),R=f.useCallback((Ke,ye,Ge=Eo())=>{if(!Ke)return Promise.resolve();const $e=Le.getState().sessionMemoryState.get(Ke)?.streamingCooldownUntil,tt=Date.now();if(typeof $e=="number"&&$e>tt){const jt=Math.min(3e3,Math.max(0,$e-tt));return new Promise(ct=>{setTimeout(()=>{P(Ke,ye,Ge).finally(ct)},jt)})}return P(Ke,ye,Ge)},[P]);f.useEffect(()=>{_e.current=R},[R]);const z=f.useCallback((Ke,ye,Ge)=>{Kn()&&console.debug(`[MessageTracker] ${Ke}: ${ye}`,Ge)},[]),O=f.useCallback(Ke=>{Kn()&&console.debug(`[MessageTracker] ${Ke}: reported`)},[]),Q=f.useRef(null),te=f.useRef(null),W=f.useRef(0),U=f.useRef(new Set),K=f.useRef(new Map),q=f.useRef(null),ee=f.useRef(!1),V=f.useRef(null),G=f.useRef(0),Y=f.useRef(new Set),oe=f.useRef(new Set),re=f.useRef(new Set),fe=f.useRef(new Set),ie=f.useRef(!1),de=f.useRef(new Set),$=f.useRef(new Map),L=f.useCallback(()=>{if(typeof document>"u")return"visible";const Ke=document.visibilityState;return Ke==="hidden"&&document.hasFocus()?"visible":Ke},[]),X=f.useRef(L()),ne=f.useRef(typeof navigator>"u"?!0:navigator.onLine),se=f.useRef(!1),pe=f.useRef(null),ae=f.useRef(null),ve=f.useRef(Date.now()),ce=f.useRef(new Map),Z=f.useRef(new Map),me=f.useRef(new Map),be=f.useRef(new Map),we=f.useRef(new Map),Ae=f.useRef(new Map),Pe=f.useRef(0),xe=f.useRef(null),_e=f.useRef(()=>Promise.resolve()),ze=f.useRef(()=>{}),le=f.useCallback((Ke,ye)=>{const Ge=be.current;if(Ge.set(Ke,ye),Ge.size>4e3){const Ee=Ge.keys().next().value;typeof Ee=="string"&&Ge.delete(Ee)}},[]),ge=f.useCallback(Ke=>X.current==="hidden"?!0:Ke&&typeof document<"u"?!document.hasFocus():!1,[]),Fe=f.useCallback(Ke=>{const ye=gr();if(!ye?.notifications)return;const Ge=typeof Ke.title=="string"?Ke.title.trim():"";if(!Ge)return;const Ee=De.getState();if(!Ee.nativeNotificationsEnabled)return;const $e=!!ye.runtime?.isVSCode;(Ke.requireHidden||Ee.notificationMode==="hidden-only")&&!ge($e)||ye.notifications.notifyAgentCompletion({title:Ge,body:typeof Ke.body=="string"?Ke.body:"",tag:typeof Ke.tag=="string"?Ke.tag:void 0})},[ge]),ke=f.useCallback(Ke=>{const ye=Date.now();ye-ve.current>25e3&&(_(Ke),ve.current=ye)},[_]),Ze=f.useRef(m),Je=f.useRef(null),Ye=f.useRef(null);f.useEffect(()=>{Ze.current=m},[m]);const Re=f.useCallback((Ke,ye)=>{if(!Ke)return;const Ge=Date.now(),Ee=K.current,$e=Ee.get(Ke);if($e&&Ge-$e<3e3)return;Ee.set(Ke,Ge);const tt=jt=>{if(typeof ye=="string"&&ye.trim().length>0)return ye.trim();try{const At=p?.(jt);if(At?.path)return At.path}catch{}const Xe=Le.getState().sessions.find(At=>At.id===jt);return Xe&&typeof Xe.directory=="string"&&Xe.directory.trim().length>0?Xe.directory.trim():null};setTimeout(async()=>{try{const jt=tt(Ke),ct=jt?await zt.withDirectory(jt,()=>zt.getSession(Ke)):await zt.getSession(Ke);if(ct){const Xe={};typeof ct.title=="string"&&ct.title.length>0&&(Xe.title=ct.title),ct.summary!==void 0&&(Xe.summary=ct.summary),Object.keys(Xe).length>0&&h(Ke,Xe)}}catch(jt){console.warn("Failed to refresh session metadata:",jt)}},100)},[h,p]),Ue=f.useCallback((Ke,ye,Ge="unknown")=>{if(!Ke)return;const $e=Le.getState().sessionStatus?.get(Ke)?.type??"idle",tt=ye?.type??"idle",jt=$e==="idle"&&(tt==="busy"||tt==="retry");if(tt==="idle"){const At=Z.current.get(Ke);At&&(clearTimeout(At),Z.current.delete(Ke))}if(jt){const At=Z.current.get(Ke);At&&(clearTimeout(At),Z.current.delete(Ke));const yt=Date.now(),dt=setTimeout(()=>{const Tt=Le.getState().sessionStatus?.get(Ke);if(Tt?.type!=="busy"&&Tt?.type!=="retry")return;const Zt=me.current.get(Ke)??0;Date.now()-Zt<15e3||(ce.current.get(Ke)??0)>=yt||(me.current.set(Ke,Date.now()),_e.current(Ke,"status_busy_no_message",Eo()).finally(()=>{ze.current("No message events after busy status")}))},2e3);Z.current.set(Ke,dt)}const Xe=new Map(Le.getState().sessionStatus??new Map);if(tt==="idle")Xe.set(Ke,{...ye,confirmedAt:Date.now()});else{const At=Xe.get(Ke);At?.confirmedAt?Xe.set(Ke,{...ye,confirmedAt:At.confirmedAt}):Xe.set(Ke,ye)}Le.setState({sessionStatus:Xe})},[]),Ve=f.useCallback((Ke,ye,Ge="unknown",Ee)=>{if(!Ke)return;const $e=Ee?.syncStatus!==!1;if(Ae.current.get(Ke)===ye)return;const jt=we.current.get(Ke);jt&&(clearTimeout(jt),we.current.delete(Ke));const ct=new Map(Ae.current);if(ct.set(Ke,ye),Ae.current=ct,!!$e){if(ye==="idle"){Ue(Ke,{type:"idle"},`${Ge}:idle`);return}if(Ue(Ke,{type:"busy"},`${Ge}:${ye}`),ye==="cooldown"){const Xe=setTimeout(()=>{if(we.current.delete(Ke),Ae.current.get(Ke)!=="cooldown")return;const At=new Map(Ae.current);At.set(Ke,"idle"),Ae.current=At,Ue(Ke,{type:"idle"},`${Ge}:cooldown_timeout`)},2e3);we.current.set(Ke,Xe)}}},[Ue]),st=f.useCallback(async()=>{const Ke=Date.now();if(xe.current)return xe.current;if(Ke-Pe.current<1500)return;Pe.current=Ke;const ye=Ee=>{const $e=new Set,tt=Le.getState().sessions,jt=new Set(tt.map(ct=>ct.id));for(const[ct,Xe]of Object.entries(Ee)){if(!ct||!Xe)continue;$e.add(ct);const At=Xe.type==="cooldown"?"cooldown":Xe.type==="busy"||Xe.type==="retry"?"busy":"idle";Ve(ct,At,"snapshot")}for(const[ct,Xe]of Ae.current.entries())jt.has(ct)&&(Xe==="busy"||Xe==="cooldown")&&!$e.has(ct)&&Ve(ct,"idle","snapshot_missing")},Ge=(async()=>{try{const Ee=await zt.getWebServerSessionActivity();if(Ee&&Object.keys(Ee).length>0){ye(Ee);return}const $e=await zt.getGlobalSessionStatus();$e&&Object.keys($e).length>0&&ye($e)}catch{}})().finally(()=>{xe.current=null});return xe.current=Ge,Ge},[Ve]),at=f.useCallback(()=>{const Ke=we.current;for(const ye of Ke.values())clearTimeout(ye);Ke.clear(),Ae.current.clear()},[]),nt=f.useCallback((Ke,ye)=>{const Ge=ye?.refreshActivity!==!1,Ee=ye?.pollStatus!==!1;Kn()&&console.debug("[useEventStream] Repairing derived session state",{reason:Ke,refreshActivity:Ge,pollStatus:Ee}),Ge&&st(),Ee&&I8()},[st]);f.useEffect(()=>{const Ke=m??null,ye=Je.current,Ge=E(Ke),Ee=Ye.current;ye&&Ke&&ye!==Ke&&(Qa.clear(),Ee&&Ge&&Ee!==Ge&&nt("session_switch_directory")),Je.current=Ke,Ye.current=Ge},[m,nt,E]);const he=f.useCallback(Ke=>{if(ve.current=Date.now(),Kn()&&console.debug("[useEventStream] Received event:",Ke.type,Ke.properties),!Ke.properties)return;const ye=Ke.properties;if(!new Set(["session.abort","session.error"]).has(Ke.type)){const Ee=(typeof ye.session=="object"&&ye.session!==null?ye.session:null)||(typeof ye.sessionInfo=="object"&&ye.sessionInfo!==null?ye.sessionInfo:null);if(Ee){const $e=Ee,tt=typeof $e.id=="string"&&$e.id.length>0?$e.id:typeof $e.sessionID=="string"&&$e.sessionID.length>0?$e.sessionID:typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof ye.id=="string"&&ye.id.length>0?ye.id:void 0;if(tt){const jt=typeof $e.title=="string"?$e.title:typeof ye.title=="string"?ye.title:void 0,ct=typeof $e.summary=="object"&&$e.summary!==null?$e.summary:typeof ye.summary=="object"&&ye.summary!==null?ye.summary:void 0;if(jt!==void 0||ct!==void 0){const Xe={};jt!==void 0&&(Xe.title=jt),ct!==void 0&&(Xe.summary=ct),h(tt,Xe)}}}}switch(Ke.type){case"server.connected":v();break;case"global.disposed":case"server.instance.disposed":{_("server_disposed_event");break}case"mcp.tools.changed":{const Ee=typeof ye.directory=="string"?ye.directory:k;Or.getState().refresh({directory:Ee??null,silent:!0});break}case"session.status":{const Ee=Vn(ye,["sessionID","sessionId"]),$e=ye.status,tt=typeof $e=="object"&&$e!==null?$e:null,jt=typeof $e=="string"?$e:typeof tt?.type=="string"?tt.type:typeof tt?.status=="string"?tt.status:typeof ye.type=="string"?ye.type:typeof ye.phase=="string"?ye.phase:typeof ye.state=="string"?ye.state:null,ct=tt??{},Xe=ye.metadata,At=typeof Xe=="object"&&Xe!==null?Xe:null;Ee&&jt&&(jt==="busy"?(Ue(Ee,{type:"busy"},"sse:session.status"),Ve(Ee,"busy","sse:session.status",{syncStatus:!1})):jt==="retry"?(Ue(Ee,{type:"retry",attempt:typeof ct.attempt=="number"?ct.attempt:typeof ye.attempt=="number"?ye.attempt:typeof At?.attempt=="number"?At.attempt:void 0,message:typeof ct.message=="string"?ct.message:typeof ye.message=="string"?ye.message:typeof At?.message=="string"?At.message:void 0,next:typeof ct.next=="number"?ct.next:typeof ye.next=="number"?ye.next:typeof At?.next=="number"?At.next:void 0},"sse:session.status"),Ve(Ee,"busy","sse:session.status",{syncStatus:!1})):(Ue(Ee,{type:"idle"},"sse:session.status"),Ve(Ee,"idle","sse:session.status",{syncStatus:!1}),nt("session.status_idle",{refreshActivity:!1})),Re(Ee,typeof ye.directory=="string"?ye.directory:null))}break;case"openchamber:session-activity":{const Ee=Vn(ye,["sessionId","sessionID"]),$e=typeof ye.phase=="string"?ye.phase:null;Ee&&($e==="idle"||$e==="busy"||$e==="cooldown")&&(Ve(Ee,$e,"sse:openchamber:session-activity"),Re(Ee,typeof ye.directory=="string"?ye.directory:null))}break;case"openchamber:session-status":{const Ee=Vn(ye,["sessionId","sessionID"]),$e=typeof ye.status=="string"?ye.status:null,tt=typeof ye.needsAttention=="boolean"?ye.needsAttention:!1,jt=typeof ye.timestamp=="number"?ye.timestamp:Date.now();if(Ee&&$e){if($e==="busy")Ue(Ee,{type:"busy"},"sse:openchamber:session-status"),Ve(Ee,"busy","sse:openchamber:session-status",{syncStatus:!1});else if($e==="retry"){const yt=typeof ye.metadata=="object"&&ye.metadata!==null?ye.metadata:{};Ue(Ee,{type:"retry",attempt:typeof yt.attempt=="number"?yt.attempt:void 0,message:typeof yt.message=="string"?yt.message:void 0,next:typeof yt.next=="number"?yt.next:void 0},"sse:openchamber:session-status"),Ve(Ee,"busy","sse:openchamber:session-status",{syncStatus:!1})}else Ue(Ee,{type:"idle"},"sse:openchamber:session-status"),Ve(Ee,"idle","sse:openchamber:session-status",{syncStatus:!1}),tt&&nt("openchamber.session-status_attention_idle",{refreshActivity:!1});const ct=Le.getState().sessionAttentionStates||new Map,Xe=new Map(ct),At=Xe.get(Ee);Xe.set(Ee,{needsAttention:tt,lastStatusChangeAt:jt,lastUserMessageAt:At?.lastUserMessageAt??null,status:$e,isViewed:At?.isViewed??!1}),Le.setState({sessionAttentionStates:Xe})}}break;case"message.part.updated":{const Ee=typeof ye.part=="object"&&ye.part!==null?ye.part:null;if(!Ee)break;const $e=Ee,tt=typeof ye.info=="object"&&ye.info!==null?ye.info:ye,jt=Vn(tt,["sessionID","sessionId"]),ct=Vn($e,["sessionID","sessionId"])||jt||Vn(ye,["sessionID","sessionId"]),Xe=Vn(tt,["messageID","messageId","id"]),At=Vn($e,["messageID","messageId"])||Xe||Vn(ye,["messageID","messageId"]);if(!ct||!At){Kn()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:$e.sessionID??jt??ye.sessionID,messageID:$e.messageID??Xe??ye.messageID});break}const yt=ct,dt=At;ce.current.set(yt,Date.now());const Tt=Z.current.get(yt);Tt&&(clearTimeout(Tt),Z.current.delete(yt));const Zt=Nt=>{const Pt=typeof Nt=="string"?Nt.trim():"";return Pt?Pt.startsWith("User has requested to enter plan mode")||Pt.startsWith("The plan at ")||Pt.startsWith("The following tool was executed by the user"):!1},rs=()=>{const Nt=typeof $e.type=="string"?$e.type:"";if(Nt==="subtask"||Nt==="agent"||Nt==="file")return!0;if(Nt==="text"&&$e.synthetic===!0){const Pt=$e.text;return Zt(Pt)}return!1};let is="assistant";const as=$6(yt,dt),ps=as?.parts?.find(Nt=>Nt?.id===$e.id),xs=typeof ps?.type=="string"?ps.type:void 0;if(tt&&typeof tt.role=="string")is=tt.role;else if(as){const Nt=as.info.role;typeof Nt=="string"&&(is=Nt)}if(is!=="user"&&rs()&&(is="user"),z(dt,"part_received",{role:is}),is==="user"&&$e.synthetic===!0){const Nt=$e.text;if(!Zt(Nt)){z(dt,"skipped_synthetic_user_part");break}}const mt=Vn($e,["id","partID","partId"]),It=Yd(ye),Se=mt?`${It}:${dt}:${mt}`:null,et=Se?be.current.get(Se):void 0,qe=Ee.type||xs||et||"text",Rt={...{...Ee,type:qe}};if(Se&&typeof qe=="string"&&qe.length>0&&le(Se,qe),is==="assistant"){const Nt=Rt.type,Jt=typeof Rt.time?.end=="number",Wt=Rt.state?.status,Ie=typeof Rt.tool=="string"?Rt.tool.toLowerCase():null,wt=Rt.text;if(Nt==="tool"&&Ie==="question"&&j(),Nt==="tool"?Wt==="running"||Wt==="pending":Nt==="reasoning"?!Jt:Nt==="text"?typeof wt=="string"&&wt.trim().length>0&&!Jt:Nt==="step-start"){const Lt=Le.getState().sessionStatus?.get(yt),Kt=Lt?.type==="idle"&&typeof Lt.confirmedAt=="number"&&Date.now()-Lt.confirmedAt<1200;(!Lt||Lt.type==="idle")&&(Kt||Ue(yt,{type:"busy"},"sse:message.part.updated"))}}z(dt,"addStreamingPart_called"),n(yt,dt,Rt,is);break}case"message.part.delta":{const Ee=Vn(ye,["sessionID","sessionId"]),$e=Vn(ye,["messageID","messageId"]),tt=Vn(ye,["partID","partId"]),jt=Vn(ye,["field"]),ct=typeof ye.delta=="string"?ye.delta:null;if(!Ee||!$e||!tt||!jt||ct===null){Kn()&&console.debug("[useEventStream] Skipping message.part.delta with missing payload",{sessionID:ye.sessionID,messageID:ye.messageID,partID:ye.partID,field:ye.field});break}ce.current.set(Ee,Date.now());const Xe=Z.current.get(Ee);Xe&&(clearTimeout(Xe),Z.current.delete(Ee));const At=$6(Ee,$e),yt=At?.parts?.find(Zt=>Zt?.id===tt),dt=At?.info?.role,Tt=typeof dt=="string"?dt:"assistant";if(!yt){if(jt==="text"||jt==="content"||jt==="value"){const Zt=Yd(ye),rs=Vn(ye,["partType","type","part_type"])||Vn(ye,["kind"]),is=`${Zt}:${$e}:${tt}`,as=be.current.get(is),ps=typeof rs=="string"&&rs.trim().length>0?rs:typeof as=="string"&&as.trim().length>0?as:"text",xs={id:tt,type:ps,sessionID:Ee,messageID:$e,delta:ct,[jt]:""};typeof ps=="string"&&ps.length>0&&le(is,ps),n(Ee,$e,xs,Tt)}break}if(Tt==="assistant"&&ct.length>0){const Zt=Le.getState().sessionStatus?.get(Ee),rs=Zt?.type==="idle"&&typeof Zt.confirmedAt=="number"&&Date.now()-Zt.confirmedAt<1200;(!Zt||Zt.type==="idle")&&(rs||Ue(Ee,{type:"busy"},"sse:message.part.delta"))}z($e,"part_delta_received",{role:Tt,field:jt}),r(Ee,$e,tt,jt,ct,Tt);break}case"message.updated":{const Ee=typeof ye.info=="object"&&ye.info!==null?ye.info:ye,$e=Ee,tt=Vn($e,["sessionID","sessionId"])||Vn(ye,["sessionID","sessionId"]),jt=Vn($e,["messageID","messageId","id"])||Vn(ye,["messageID","messageId"]);if(!tt||!jt){Kn()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:$e.sessionID??ye.sessionID,messageID:$e.id??ye.messageID});break}const ct=tt,Xe=jt;ce.current.set(ct,Date.now());const At=Z.current.get(ct);if(At&&(clearTimeout(At),Z.current.delete(ct)),Kn())try{const Lt=ye.parts||$e.parts||[],Ct=(Array.isArray(Lt)?Lt.filter(Xt=>Xt?.type==="text"):[]).map(Xt=>{const Ss=Xt;return typeof Ss?.text=="string"?Ss.text:typeof Ss?.content=="string"?Ss.content:""}).join(`
6927
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Xe,role:$e.role,status:$e.status,textLen:Ct.length,textPreview:Ct.slice(0,120),partsCount:Array.isArray(Lt)?Lt.length:0})}catch{}if(z(Xe,"message_updated",{role:$e.role}),$e.role==="user"){const{sessionMemoryState:Lt}=qs.getState(),Kt=Lt.get(ct);if(Kt){const Ks=new Map(Lt);Ks.set(ct,{...Kt,lastUserMessageAt:Date.now()}),qs.setState({sessionMemoryState:Ks})}const Ct=ye.parts||$e.parts,Xt=Array.isArray(Ct)?Ct:[],Ss=O6(ct,Xe),cs=(()=>{const Ks=$e.agent;if(typeof Ks=="string"&&Ks.trim().length>0)return Ks.trim();const Ws=$e.mode;return typeof Ws=="string"&&Ws.trim().length>0?Ws.trim():""})(),en=(()=>{const Ws=$e.time?.created;return typeof Ws=="number"?Ws:null})(),Ys=Xt.length>0&&Xt.every(Ks=>Ks?.synthetic===!0),kn=(()=>{if(!cs)return!1;if(Ys&&(cs==="plan"||cs==="build"))return!0;const Ks=$.current.get(ct);return Ks?en===null?!1:Xe===Ks.messageId?!0:en>=Ks.created:!0})();if(cs&&kn)try{const Ks=Yt.getState().agents;if(Array.isArray(Ks)&&Ks.some(Ws=>Ws?.name===cs)){const Ws=bs.getState();if(Ws.saveSessionAgentSelection(ct,cs),$.current.set(ct,{created:en??Date.now(),messageId:Xe}),Ze.current===ct)try{Yt.getState().setAgent(cs)}catch{}const hn=$e.model,Tn=typeof hn?.providerID=="string"?hn.providerID:null,yn=typeof hn?.modelID=="string"?hn.modelID:null;if(Tn&&yn){Ws.saveSessionModelSelection(ct,Tn,yn),Ws.saveAgentModelForSession(ct,cs,Tn,yn);const Zn=typeof $e.variant=="string"?$e.variant:void 0;if(Ws.saveAgentModelVariantForSession(ct,cs,Tn,yn,Zn),Ze.current===ct)try{Yt.getState().setProvider(Tn),Yt.getState().setModel(yn)}catch{}}}}catch{}if(Ys&&(cs==="plan"||cs==="build")&&Ze.current===ct){const Ks=`${ct}:${Xe}:${cs}`;de.current.has(Ks)||(de.current.add(Ks),cr(async()=>{const{toast:Ws}=await import("./vendor-.bun-9lzLHWe8.js").then(hn=>hn.eP);return{toast:Ws}},__vite__mapDeps([0,1])).then(({toast:Ws})=>{Ws.info(cs==="plan"?"Plan mode active":"Build mode active",{description:cs==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const on={...Ee,userMessageMarker:!0,clientRole:"user",...cs?{mode:cs}:{}};if(a(ct,Xe,on),!Ss&&Xt.length===0){const Ks=`${ct}:${Xe}`;U.current.has(Ks)||(U.current.add(Ks),zt.getSessionMessages(ct).then(Ws=>{Le.getState().syncMessages(ct,Ws)}).catch(()=>{}))}if(Xt.length>0){const Ks=Yd(ye);for(let Ws=0;Ws<Xt.length;Ws++){const hn=Xt[Ws];if(hn.synthetic===!0){const Zn=hn.text,lr=typeof Zn=="string"?Zn.trim():"";if(!(lr.startsWith("User has requested to enter plan mode")||lr.startsWith("The plan at ")||lr.startsWith("The following tool was executed by the user")))continue}const yn={...hn,type:hn?.type||"text",sessionID:hn?.sessionID||ct,messageID:hn?.messageID||Xe};typeof yn.id=="string"&&typeof yn.type=="string"&&le(`${Ks}:${Xe}:${yn.id}`,yn.type),n(ct,Xe,yn,"user")}}z(Xe,"user_message_created_from_event",{partsCount:Xt.length});break}const dt=O6(ct,Xe)?.info?.finish==="stop",Tt=ye.parts||$e.parts,rs=(Array.isArray(Tt)?Tt:[]).length>0,as=typeof($e.time||{})?.completed=="number",ps=Ee.status,xs=typeof ps=="string"?ps.toLowerCase():null,mt=xs==="completed"||xs==="complete",It=Ee.finish,Se=typeof It=="string"?It:null,et=Se==="stop",qe=Se==="error";if(!rs&&!as&&!mt&&!et&&!qe)break;const bt={...$e};delete bt.parts,a(ct,Xe,bt);const Rt=typeof Ee.role=="string"?Ee.role:null;if(!!gr()?.runtime?.isVSCode&&!ie.current&&Rt==="assistant"){const Lt=De.getState(),Kt=Le.getState().sessions.find(Xt=>Xt.id===ct),Ct=typeof Kt?.title=="string"?Kt.title.trim():"";if(et&&Lt.notifyOnCompletion!==!1){const Xt=!!Kt?.parentID;if(!(Lt.notifyOnSubtasks===!1&&Xt)){const Ss=`ready:${ct}:${Xe}`;re.current.has(Ss)||(re.current.add(Ss),Fe({title:"Agent is ready",body:Ct||"Task completed",tag:`ready-${ct}`}))}}if(qe&&Lt.notifyOnError!==!1){const Xt=`error:${ct}:${Xe}`;re.current.has(Xt)||(re.current.add(Xt),Fe({title:"Tool error",body:Ct||"An error occurred",tag:`error-${ct}`}))}}const Jt=Ee.time,Wt=Jt?.completed,Ie=typeof Wt=="number"&&Number.isFinite(Wt),wt=Se==="stop"||dt;if(Ee.role==="assistant"&&(Ie||mt||wt)&&Ee.role==="assistant"){const Kt=Le.getState().messages.get(ct)||[];let Ct=null,Xt="";for(let on=0;on<Kt.length;on++){const Ks=Kt[on];Ks.info.role==="assistant"&&Ks.info.id>Xt&&(Xt=Ks.info.id,Ct=Ks.info.id)}if(m===ct&&Xe!==Ct)break;const cs=Ie?Wt:Date.now();Ie||a(ct,Xe,{...Ee,time:{...Jt??{},completed:cs}}),z(Xe,"completed",{timeCompleted:cs}),O(Xe),rQ(ct,Xe,cs),o(ct,Xe),nt("assistant_message_completed");const en=Ee.sessionID,Ys=typeof en=="string"&&en.length>0?en:ct;Re(Ys,typeof ye.directory=="string"?ye.directory:null),Ee.summary&&typeof Ys=="string"&&i(Ys,null)}break}case"session.created":case"session.updated":{const Ee=typeof ye.info=="object"&&ye.info!==null?ye.info:typeof ye.sessionInfo=="object"&&ye.sessionInfo!==null?ye.sessionInfo:typeof ye.session=="object"&&ye.session!==null?ye.session:ye,$e=typeof Ee.id=="string"&&Ee.id.length>0?Ee.id:typeof Ee.sessionID=="string"&&Ee.sessionID.length>0?Ee.sessionID:typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof ye.id=="string"&&ye.id.length>0?ye.id:void 0;if($e){const tt=typeof Ee.time=="object"&&Ee.time!==null?Ee.time:typeof ye.time=="object"&&ye.time!==null?ye.time:null,jt=tt&&typeof tt.compacting=="number"?tt.compacting:null;i($e,jt);const ct=typeof Ee.directory=="string"?Ee.directory:typeof ye.directory=="string"?ye.directory:null,Xe={...Ee,id:$e,...ct?{directory:ct}:{}};b(Xe)}break}case"session.deleted":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:typeof ye.id=="string"?ye.id:null;Ee&&x(Ee);break}case"session.abort":{const Ee=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:null,$e=typeof ye.messageID=="string"&&ye.messageID.length>0?ye.messageID:null;Ee&&Ue(Ee,{type:"idle"},"sse:session.abort"),Ee&&$e&&o(Ee,$e);break}case"permission.asked":{const Ee=H6(ye);if(!Ee)break;if(l(Ee),gr()?.runtime?.isVSCode&&!ie.current&&De.getState().notifyOnQuestion!==!1){const ct=`permission:${Ee.sessionID}:${Ee.id}`;if(!fe.current.has(ct)){fe.current.add(ct);const Xe=Le.getState().sessions.find(At=>At.id===Ee.sessionID)?.title||"Agent is waiting for your approval";Fe({title:"Permission required",body:Xe,tag:`permission-${Ee.sessionID}:${Ee.id}`})}}const tt=`${Ee.sessionID}:${Ee.id}`;Y.current.has(tt)||setTimeout(()=>{const jt=Ze.current;if(jt===Ee.sessionID)return;const ct=Le.getState().sessions.find(dt=>dt.id===Ee.sessionID);if(ct?.parentID&&ct.parentID===jt||!Le.getState().permissions.get(Ee.sessionID)?.some(dt=>dt.id===Ee.id))return;Y.current.add(tt);const At=Le.getState().sessions.find(dt=>dt.id===Ee.sessionID)?.title||"Session",yt=iQ(Ee);cr(async()=>{const{toast:dt}=await import("./vendor-.bun-9lzLHWe8.js").then(Tt=>Tt.eP);return{toast:dt}},__vite__mapDeps([0,1])).then(({toast:dt})=>{De.getState().isMobile?dt.warning("Permission required",{id:tt,description:At,duration:3e4,action:{label:"Open",onClick:()=>{De.getState().setActiveMainTab("chat"),Le.getState().setCurrentSession(Ee.sessionID)}}}):dt.warning("Permission required",{id:tt,description:f.createElement(oQ,{sessionTitle:At,permissionBody:yt,onOnce:async()=>{try{await Le.getState().respondToPermission(Ee.sessionID,Ee.id,"once"),dt.dismiss(tt)}catch(Zt){console.error("Failed to respond to permission:",Zt)}},onAlways:async()=>{try{await Le.getState().respondToPermission(Ee.sessionID,Ee.id,"always"),dt.dismiss(tt)}catch(Zt){console.error("Failed to respond to permission:",Zt)}},onDeny:async()=>{try{await Le.getState().respondToPermission(Ee.sessionID,Ee.id,"reject"),dt.dismiss(tt)}catch(Zt){console.error("Failed to respond to permission:",Zt)}}}),duration:3e4})})},0);break}case"permission.replied":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=typeof ye.requestID=="string"?ye.requestID:typeof ye.id=="string"?ye.id:null;Ee&&$e&&c(Ee,$e);break}case"question.asked":{if(!("sessionID"in ye)||typeof ye.sessionID!="string")break;const Ee=ye;if(d(Ee),gr()?.runtime?.isVSCode&&!ie.current&&De.getState().notifyOnQuestion!==!1){const ct=`question:${Ee.sessionID}:${Ee.id}`;if(!fe.current.has(ct)){fe.current.add(ct);const Xe=Array.isArray(Ee.questions)?Ee.questions[0]:void 0,At=typeof Xe?.header=="string"?Xe.header.trim():"",yt=typeof Xe?.question=="string"?Xe.question.trim():"";Fe({title:At||"Input needed",body:yt||"Agent is waiting for your response",tag:`question-${Ee.sessionID}:${Ee.id}`})}}const tt=`${Ee.sessionID}:${Ee.id}`;oe.current.has(tt)||setTimeout(()=>{const jt=Ze.current;if(jt===Ee.sessionID)return;const ct=Le.getState().sessions.find(yt=>yt.id===Ee.sessionID);if(ct?.parentID&&ct.parentID===jt||!Le.getState().questions.get(Ee.sessionID)?.some(yt=>yt.id===Ee.id))return;oe.current.add(tt);const At=Le.getState().sessions.find(yt=>yt.id===Ee.sessionID)?.title||"Session";cr(async()=>{const{toast:yt}=await import("./vendor-.bun-9lzLHWe8.js").then(dt=>dt.eP);return{toast:yt}},__vite__mapDeps([0,1])).then(({toast:yt})=>{yt.info("Input needed",{id:tt,description:At,duration:3e4,action:{label:"Open",onClick:()=>{De.getState().setActiveMainTab("chat"),Le.getState().setCurrentSession(Ee.sessionID)}}})})},0);break}case"question.replied":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=typeof ye.requestID=="string"?ye.requestID:null;Ee&&$e&&u(Ee,$e);break}case"question.rejected":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=typeof ye.requestID=="string"?ye.requestID:null;Ee&&$e&&u(Ee,$e);break}case"openchamber:notification":{ie.current=!0;const Ee=typeof ye.title=="string"?ye.title:"",$e=typeof ye.body=="string"?ye.body:"",tt=typeof ye.tag=="string"?ye.tag:void 0,jt=!!ye.requireHidden;if(ar()&&ye.desktopStdoutActive)break;Fe({title:Ee,body:$e,tag:tt,requireHidden:jt});break}case"todo.updated":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=Array.isArray(ye.todos)?ye.todos:null;Ee&&$e&&lB(Ee,$e);break}}},[m,n,r,o,a,l,c,d,u,v,Re,i,h,z,O,j,b,x,_,k,Ue,Ve,nt,Fe,le]),je=f.useRef(he);f.useEffect(()=>{je.current=he},[he]);const We=f.useRef(_);f.useEffect(()=>{We.current=_},[_]);const lt=f.useCallback(Ke=>{je.current(Ke)},[]),rt=f.useCallback(Ke=>We.current(Ke),[]),Te=f.useCallback(()=>{const Ke=L();return X.current=Ke,Ke==="visible"&&ne.current},[L]),Qe=f.useCallback(()=>{Kn()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!Q.current,currentSessionId:Ze.current,effectiveDirectory:k,onlineStatus:ne.current,visibilityState:X.current,lastEventTimestamp:ve.current,reconnectAttempts:W.current})},[k]),pt=f.useCallback(()=>{if(ee.current){Kn()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(ee.current=!0,te.current&&(clearTimeout(te.current),te.current=null),Q.current){const Ke=Q.current;Q.current=null;try{Ke()}catch(ye){console.warn("[useEventStream] Error during unsubscribe:",ye)}}ee.current=!1},[]),St=f.useCallback(async Ke=>{if(Qe(),!Te()){se.current=!0,ne.current?H("paused","Paused while hidden"):H("offline","Waiting for network");return}Ke?.resetAttempts&&(W.current=0),pt(),ve.current=Date.now(),H("connecting",null),Kn()&&console.info("[useEventStream] Starting event stream...");const ye=Ee=>{console.warn("Event stream error:",Ee)},Ge=()=>{const Ee=se.current;if(W.current=0,se.current=!1,ve.current=Date.now(),H("connected",null),v(),nt("stream_open"),B.current(Ee),Ee)rt("sse_reconnected");else{const $e=Ze.current;$e&&setTimeout(()=>{_e.current($e,"sse_reconnected",Eo()).then(()=>Re($e)).catch(tt=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",tt)})},0)}};if(Kn()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:k,isCleaningUp:ee.current}),ee.current){Kn()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ee=zt.subscribeToGlobalEvents(tt=>{const jt=tt.payload,ct=tt.payload,Xe=typeof ct.properties=="object"&&ct.properties!==null?ct.properties:{},At=tt.directory&&tt.directory!=="global"?{...Xe,directory:tt.directory}:Xe;lt({type:typeof jt.type=="string"?jt.type:"",properties:At})},ye,Ge),$e=()=>{try{Ee()}catch(tt){console.warn("[useEventStream] Error during unsubscribe:",tt)}};ee.current?$e():Q.current=$e}catch(Ee){console.error("[useEventStream] Error during subscription:",Ee),ye(Ee)}},[Te,pt,H,v,Re,lt,rt,nt,k,Qe]),Ht=f.useCallback(Ke=>{if(!Te()){se.current=!0,pt(),ne.current?H("paused","Paused while hidden"):H("offline","Waiting for network");return}if(te.current)return;const ye=W.current+1;W.current=ye;const Ge=Ke??`Retrying (${ye})`;H("reconnecting",Ge);const Ee=ye<=3?Math.min(1e3*Math.pow(2,ye-1),8e3):Math.min(2e3*Math.pow(2,ye-3),32e3),$e=Math.floor(Math.random()*250),tt=Ee+$e;te.current&&clearTimeout(te.current),te.current=setTimeout(()=>{St({resetAttempts:!1})},tt)},[Te,pt,H,St]);f.useEffect(()=>{ze.current=Ht},[Ht]),f.useEffect(()=>{if(!e){pt(),H("idle",null);return}typeof window<"u"&&(window.__messageTracker=z);const Ke=()=>{pe.current&&(clearTimeout(pe.current),pe.current=null)},ye=()=>{if(X.current=L(),X.current!=="visible")return;if(Ke(),ke("visibility_restore"),nt("visibility_restore"),Date.now()-ve.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),se.current=!0),se.current||!Q.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const yt=Ze.current;yt&&(R(yt,"visibility_restore",Eo()),Re(yt)),B.current(!1),nt("visibility_restore_resume"),H("connecting","Resuming stream"),St({resetAttempts:!0})}},Ge=()=>{if(X.current=L(),X.current==="visible"&&(Ke(),ke("window_focus"),nt("window_focus"),Date.now()-ve.current>45e3&&(se.current=!0),se.current||!Q.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const yt=Ze.current;yt&&(Re(yt),R(yt,"window_focus",Eo())),B.current(!1),nt("window_focus_resume"),H("connecting","Resuming stream"),St({resetAttempts:!0})}},Ee=()=>{ne.current=!0,ke("network_restored"),nt("network_restored"),B.current(!1),(se.current||!Q.current)&&(H("connecting","Network restored"),St({resetAttempts:!0}))},$e=()=>{ne.current=!1,se.current=!0,H("offline","Waiting for network"),pt()},tt=()=>{se.current=!0,pt(),H("paused","Paused while hidden")},jt=At=>{if(se.current=se.current||!!At.persisted,X.current=L(),X.current==="visible"){const yt=Ze.current;yt&&(R(yt,"page_show",Eo()),Re(yt)),B.current(!1),nt("page_show"),St({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",Ee),window.addEventListener("offline",$e),window.addEventListener("focus",Ge),window.addEventListener("pagehide",tt),window.addEventListener("pageshow",jt));const ct=setTimeout(()=>{St({resetAttempts:!0})},100);ae.current&&clearInterval(ae.current),ae.current=setInterval(()=>{if(!Te())return;const At=Date.now();Array.from(Le.getState().sessionStatus?.values?.()??[]).some(dt=>dt?.type==="busy"||dt?.type==="retry")&&nt("stale_check_busy_sessions"),At-ve.current>45e3&&Promise.resolve().then(async()=>{try{if(!await zt.checkHealth()){Ht("Refreshing stalled stream");return}Ht("Refreshing stalled stream")}catch(dt){console.warn("Health check after stale stream failed:",dt),Ht("Refreshing stalled stream")}})},1e4);const Xe=setInterval(()=>{const At=Le.getState().sessionStatus;if(!At)return;const yt=Date.now();At.forEach((dt,Tt)=>{if(dt.type!=="busy"&&dt.type!=="retry")return;const Zt=ce.current.get(Tt)??0,rs=yt-Zt>zS,is=yt-Zt>6e4;rs&&is&&(console.warn("[useEventStream] Session stuck in busy state, forcing idle:",Tt),Ue(Tt,{type:"idle"},"timeout_recovery"))})},3e4);return()=>{clearTimeout(ct),clearInterval(Xe),typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",Ee),window.removeEventListener("offline",$e),window.removeEventListener("focus",Ge),window.removeEventListener("pagehide",tt),window.removeEventListener("pageshow",jt)),Ke(),ae.current&&(clearInterval(ae.current),ae.current=null),at(),Qa.clear(),re.current.clear(),fe.current.clear(),ie.current=!1,se.current=!1,X.current=L(),ne.current=typeof navigator>"u"?!0:navigator.onLine,pt(),q.current&&(clearTimeout(q.current),q.current=null),H("idle",null)}},[e,k,z,L,pt,H,St,Ht,g,Re,st,at,nt,Te,y,ke,P,R,Ue])},hQ=()=>{const t=Le.getState(),e=t.currentSessionId;if(!e)return"";const n=t.sessions.find(r=>r.id===e);return typeof n?.directory=="string"?n.directory:""},pQ=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 u="";if(d){const m=await a.json().catch(()=>null);if(Array.isArray(m))u=`json[array] len=${m.length}`;else if(m&&typeof m=="object"){const h=Object.keys(m).slice(0,8);u=`json[object] keys=${h.join(",")}${Object.keys(m).length>h.length?",…":""}`}else u=`json[${typeof m}]`}else u=l?`content-type=${l}`:"no content-type";return{ok:a.ok&&d,status:a.status,elapsedMs:i,summary:u}}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)}},gQ=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},yQ=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},bQ=async()=>{const t=new Date,e="1.8.6",n=typeof navigator<"u"?navigator.userAgent:"(no navigator)",r=hQ(),o=De.getState().eventStreamStatus,a=typeof window<"u"?window.location.origin:"",i=a?`${a.replace(/\/+$/,"")}/api/`:"",l=await(async()=>{if(!a)return null;const y=new AbortController,b=setTimeout(()=>y.abort(),5e3);try{const x=await fetch(`${a.replace(/\/+$/,"")}/health`,{method:"GET",headers:{Accept:"application/json"},signal:y.signal});if(!x.ok)return null;const v=await x.json().catch(()=>null);return!v||typeof v!="object"||Array.isArray(v)?null:v}catch{return null}finally{clearTimeout(b)}})(),c=await(async()=>{if(!a)return null;const y=new AbortController,b=setTimeout(()=>y.abort(),7e3);try{const x=await fetch(`${a.replace(/\/+$/,"")}/api/config/opencode-resolution`,{method:"GET",headers:{Accept:"application/json"},signal:y.signal}),v=x.headers.get("content-type")||"(none)";if(!x.ok)return{data:null,status:x.status,error:`http ${x.status} content-type=${v}`};const w=await x.text();let C=null;try{C=JSON.parse(w)}catch{const k=w.replace(/\s+/g," ").slice(0,120);return{data:null,status:x.status,error:`invalid json content-type=${v} body=${k||"(empty)"}`}}return!C||typeof C!="object"||Array.isArray(C)?{data:null,status:x.status,error:`invalid json-shape content-type=${v}`}:{data:C,status:x.status,error:null}}catch(x){return{data:null,status:null,error:x instanceof Error?x.message:String(x)}}finally{clearTimeout(b)}})()||{data:null,error:null},d=(y,b=!0)=>{if(!i)return null;const x=new URL(y.replace(/^\/+/,""),i);return b&&r&&x.searchParams.set("directory",r),x.toString()},u=[{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(u.map(async y=>{const b=d(y.path,y.includeDirectory!==!1);if(!b)return{label:y.label,url:"(none)",result:null};const x=await pQ(b,typeof y.timeoutMs=="number"?y.timeoutMs:void 0);return{label:y.label,url:b,result:x}})):[],h=[];h.push(`Time: ${t.toISOString()}`),h.push(`OpenChamber version: ${e}`),h.push(`Runtime: ${a||"(unknown)"} (api=${a?a+"/api":"(unknown)"})`),h.push(`Event stream: ${o}`),h.push(`Directory: ${r||"(none)"}`),h.push(`Platform: ${n}`);const p=yQ(l?.openCodePort);if(h.push(`OpenCode runtime port: ${p??"(unknown)"}`),typeof l?.openCodeRunning=="boolean"&&h.push(`OpenCode runtime running: ${l.openCodeRunning?"yes":"no"}`),typeof l?.openCodeSecureConnection=="boolean"&&h.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?"true":"false"}`),typeof l?.openCodeAuthSource=="string"&&l.openCodeAuthSource.trim()&&h.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<"u"){const y=window.__OPENCHAMBER_MACOS_MAJOR__;typeof y=="number"&&Number.isFinite(y)&&y>0&&h.push(`macOS major: ${y}`)}if(/Mac OS X|Macintosh/.test(n)){h.push(""),h.push("OpenCode CLI resolution:");const y=c.data,b=y&&typeof y.configured=="string"?y.configured:null,x=y&&typeof y.resolved=="string"?y.resolved:l&&typeof l.opencodeBinaryResolved=="string"?l.opencodeBinaryResolved:"",v=y&&typeof y.resolvedDir=="string"?y.resolvedDir:"",w=y&&typeof y.source=="string"?y.source:l&&typeof l.opencodeBinarySource=="string"?l.opencodeBinarySource:"",C=y&&typeof y.shim=="string"?y.shim:l&&typeof l.opencodeShimInterpreter=="string"?l.opencodeShimInterpreter:"",k=y&&typeof y.node=="string"?y.node:l&&typeof l.nodeBinaryResolved=="string"?l.nodeBinaryResolved:"",N=y&&typeof y.bun=="string"?y.bun:l&&typeof l.bunBinaryResolved=="string"?l.bunBinaryResolved:"",S=y&&typeof y.detectedNow=="string"?y.detectedNow:"",j=y&&typeof y.detectedSourceNow=="string"?y.detectedSourceNow:"";if(b!==null&&h.push(`- configured: ${b.trim().length===0?"(cleared)":b}`),x){const A=v||(x.includes("/")?x.split("/").slice(0,-1).join("/")||"/":"");h.push(`- opencode: ${x}${A?` (dir=${A})`:""}`)}else h.push("- opencode: (n/a)");h.push(`- source: ${w||"(n/a)"}`),S&&(h.push(`- detected-now: ${S}`),h.push(`- detected-source: ${j||"(n/a)"}`)),h.push(`- shim: ${C||"(n/a)"}`),h.push(`- node: ${k||"(n/a)"}`),h.push(`- bun: ${N||"(n/a)"}`),!y&&c.error&&h.push(`- resolution-endpoint: ${c.error}`)}if(h.push(""),m.length){h.push("OpenCode API probes:");for(const y of m){if(!y.result){h.push(`- ${y.label}: (no url)`);continue}const{ok:b,status:x,elapsedMs:v,summary:w}=y.result,C=b?"":` url=${y.url}`;h.push(`- ${y.label}: ${b?"ok":"fail"} status=${x} time=${v}ms ${w}${C}`)}}else h.push("OpenCode API probes: (skipped)");return h.push(""),h.push(`Generated: ${gQ(Date.now())}`),h.join(`
6927
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:Xe,role:$e.role,status:$e.status,textLen:Ct.length,textPreview:Ct.slice(0,120),partsCount:Array.isArray(Lt)?Lt.length:0})}catch{}if(z(Xe,"message_updated",{role:$e.role}),$e.role==="user"){const{sessionMemoryState:Lt}=qs.getState(),Kt=Lt.get(ct);if(Kt){const Ks=new Map(Lt);Ks.set(ct,{...Kt,lastUserMessageAt:Date.now()}),qs.setState({sessionMemoryState:Ks})}const Ct=ye.parts||$e.parts,Xt=Array.isArray(Ct)?Ct:[],Ss=O6(ct,Xe),cs=(()=>{const Ks=$e.agent;if(typeof Ks=="string"&&Ks.trim().length>0)return Ks.trim();const Ws=$e.mode;return typeof Ws=="string"&&Ws.trim().length>0?Ws.trim():""})(),en=(()=>{const Ws=$e.time?.created;return typeof Ws=="number"?Ws:null})(),Ys=Xt.length>0&&Xt.every(Ks=>Ks?.synthetic===!0),kn=(()=>{if(!cs)return!1;if(Ys&&(cs==="plan"||cs==="build"))return!0;const Ks=$.current.get(ct);return Ks?en===null?!1:Xe===Ks.messageId?!0:en>=Ks.created:!0})();if(cs&&kn)try{const Ks=Yt.getState().agents;if(Array.isArray(Ks)&&Ks.some(Ws=>Ws?.name===cs)){const Ws=bs.getState();if(Ws.saveSessionAgentSelection(ct,cs),$.current.set(ct,{created:en??Date.now(),messageId:Xe}),Ze.current===ct)try{Yt.getState().setAgent(cs)}catch{}const hn=$e.model,Tn=typeof hn?.providerID=="string"?hn.providerID:null,yn=typeof hn?.modelID=="string"?hn.modelID:null;if(Tn&&yn){Ws.saveSessionModelSelection(ct,Tn,yn),Ws.saveAgentModelForSession(ct,cs,Tn,yn);const Zn=typeof $e.variant=="string"?$e.variant:void 0;if(Ws.saveAgentModelVariantForSession(ct,cs,Tn,yn,Zn),Ze.current===ct)try{Yt.getState().setProvider(Tn),Yt.getState().setModel(yn)}catch{}}}}catch{}if(Ys&&(cs==="plan"||cs==="build")&&Ze.current===ct){const Ks=`${ct}:${Xe}:${cs}`;de.current.has(Ks)||(de.current.add(Ks),cr(async()=>{const{toast:Ws}=await import("./vendor-.bun-9lzLHWe8.js").then(hn=>hn.eP);return{toast:Ws}},__vite__mapDeps([0,1])).then(({toast:Ws})=>{Ws.info(cs==="plan"?"Plan mode active":"Build mode active",{description:cs==="plan"?"Edits restricted to plan file":"You can now edit files",duration:5e3})}))}const on={...Ee,userMessageMarker:!0,clientRole:"user",...cs?{mode:cs}:{}};if(a(ct,Xe,on),!Ss&&Xt.length===0){const Ks=`${ct}:${Xe}`;U.current.has(Ks)||(U.current.add(Ks),zt.getSessionMessages(ct).then(Ws=>{Le.getState().syncMessages(ct,Ws)}).catch(()=>{}))}if(Xt.length>0){const Ks=Yd(ye);for(let Ws=0;Ws<Xt.length;Ws++){const hn=Xt[Ws];if(hn.synthetic===!0){const Zn=hn.text,lr=typeof Zn=="string"?Zn.trim():"";if(!(lr.startsWith("User has requested to enter plan mode")||lr.startsWith("The plan at ")||lr.startsWith("The following tool was executed by the user")))continue}const yn={...hn,type:hn?.type||"text",sessionID:hn?.sessionID||ct,messageID:hn?.messageID||Xe};typeof yn.id=="string"&&typeof yn.type=="string"&&le(`${Ks}:${Xe}:${yn.id}`,yn.type),n(ct,Xe,yn,"user")}}z(Xe,"user_message_created_from_event",{partsCount:Xt.length});break}const dt=O6(ct,Xe)?.info?.finish==="stop",Tt=ye.parts||$e.parts,rs=(Array.isArray(Tt)?Tt:[]).length>0,as=typeof($e.time||{})?.completed=="number",ps=Ee.status,xs=typeof ps=="string"?ps.toLowerCase():null,mt=xs==="completed"||xs==="complete",It=Ee.finish,Se=typeof It=="string"?It:null,et=Se==="stop",qe=Se==="error";if(!rs&&!as&&!mt&&!et&&!qe)break;const bt={...$e};delete bt.parts,a(ct,Xe,bt);const Rt=typeof Ee.role=="string"?Ee.role:null;if(!!gr()?.runtime?.isVSCode&&!ie.current&&Rt==="assistant"){const Lt=De.getState(),Kt=Le.getState().sessions.find(Xt=>Xt.id===ct),Ct=typeof Kt?.title=="string"?Kt.title.trim():"";if(et&&Lt.notifyOnCompletion!==!1){const Xt=!!Kt?.parentID;if(!(Lt.notifyOnSubtasks===!1&&Xt)){const Ss=`ready:${ct}:${Xe}`;re.current.has(Ss)||(re.current.add(Ss),Fe({title:"Agent is ready",body:Ct||"Task completed",tag:`ready-${ct}`}))}}if(qe&&Lt.notifyOnError!==!1){const Xt=`error:${ct}:${Xe}`;re.current.has(Xt)||(re.current.add(Xt),Fe({title:"Tool error",body:Ct||"An error occurred",tag:`error-${ct}`}))}}const Jt=Ee.time,Wt=Jt?.completed,Ie=typeof Wt=="number"&&Number.isFinite(Wt),wt=Se==="stop"||dt;if(Ee.role==="assistant"&&(Ie||mt||wt)&&Ee.role==="assistant"){const Kt=Le.getState().messages.get(ct)||[];let Ct=null,Xt="";for(let on=0;on<Kt.length;on++){const Ks=Kt[on];Ks.info.role==="assistant"&&Ks.info.id>Xt&&(Xt=Ks.info.id,Ct=Ks.info.id)}if(m===ct&&Xe!==Ct)break;const cs=Ie?Wt:Date.now();Ie||a(ct,Xe,{...Ee,time:{...Jt??{},completed:cs}}),z(Xe,"completed",{timeCompleted:cs}),O(Xe),rQ(ct,Xe,cs),o(ct,Xe),nt("assistant_message_completed");const en=Ee.sessionID,Ys=typeof en=="string"&&en.length>0?en:ct;Re(Ys,typeof ye.directory=="string"?ye.directory:null),Ee.summary&&typeof Ys=="string"&&i(Ys,null)}break}case"session.created":case"session.updated":{const Ee=typeof ye.info=="object"&&ye.info!==null?ye.info:typeof ye.sessionInfo=="object"&&ye.sessionInfo!==null?ye.sessionInfo:typeof ye.session=="object"&&ye.session!==null?ye.session:ye,$e=typeof Ee.id=="string"&&Ee.id.length>0?Ee.id:typeof Ee.sessionID=="string"&&Ee.sessionID.length>0?Ee.sessionID:typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof ye.id=="string"&&ye.id.length>0?ye.id:void 0;if($e){const tt=typeof Ee.time=="object"&&Ee.time!==null?Ee.time:typeof ye.time=="object"&&ye.time!==null?ye.time:null,jt=tt&&typeof tt.compacting=="number"?tt.compacting:null;i($e,jt);const ct=typeof Ee.directory=="string"?Ee.directory:typeof ye.directory=="string"?ye.directory:null,Xe={...Ee,id:$e,...ct?{directory:ct}:{}};b(Xe)}break}case"session.deleted":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:typeof ye.id=="string"?ye.id:null;Ee&&x(Ee);break}case"session.abort":{const Ee=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:null,$e=typeof ye.messageID=="string"&&ye.messageID.length>0?ye.messageID:null;Ee&&Ue(Ee,{type:"idle"},"sse:session.abort"),Ee&&$e&&o(Ee,$e);break}case"permission.asked":{const Ee=H6(ye);if(!Ee)break;if(l(Ee),gr()?.runtime?.isVSCode&&!ie.current&&De.getState().notifyOnQuestion!==!1){const ct=`permission:${Ee.sessionID}:${Ee.id}`;if(!fe.current.has(ct)){fe.current.add(ct);const Xe=Le.getState().sessions.find(At=>At.id===Ee.sessionID)?.title||"Agent is waiting for your approval";Fe({title:"Permission required",body:Xe,tag:`permission-${Ee.sessionID}:${Ee.id}`})}}const tt=`${Ee.sessionID}:${Ee.id}`;Y.current.has(tt)||setTimeout(()=>{const jt=Ze.current;if(jt===Ee.sessionID)return;const ct=Le.getState().sessions.find(dt=>dt.id===Ee.sessionID);if(ct?.parentID&&ct.parentID===jt||!Le.getState().permissions.get(Ee.sessionID)?.some(dt=>dt.id===Ee.id))return;Y.current.add(tt);const At=Le.getState().sessions.find(dt=>dt.id===Ee.sessionID)?.title||"Session",yt=iQ(Ee);cr(async()=>{const{toast:dt}=await import("./vendor-.bun-9lzLHWe8.js").then(Tt=>Tt.eP);return{toast:dt}},__vite__mapDeps([0,1])).then(({toast:dt})=>{De.getState().isMobile?dt.warning("Permission required",{id:tt,description:At,duration:3e4,action:{label:"Open",onClick:()=>{De.getState().setActiveMainTab("chat"),Le.getState().setCurrentSession(Ee.sessionID)}}}):dt.warning("Permission required",{id:tt,description:f.createElement(oQ,{sessionTitle:At,permissionBody:yt,onOnce:async()=>{try{await Le.getState().respondToPermission(Ee.sessionID,Ee.id,"once"),dt.dismiss(tt)}catch(Zt){console.error("Failed to respond to permission:",Zt)}},onAlways:async()=>{try{await Le.getState().respondToPermission(Ee.sessionID,Ee.id,"always"),dt.dismiss(tt)}catch(Zt){console.error("Failed to respond to permission:",Zt)}},onDeny:async()=>{try{await Le.getState().respondToPermission(Ee.sessionID,Ee.id,"reject"),dt.dismiss(tt)}catch(Zt){console.error("Failed to respond to permission:",Zt)}}}),duration:3e4})})},0);break}case"permission.replied":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=typeof ye.requestID=="string"?ye.requestID:typeof ye.id=="string"?ye.id:null;Ee&&$e&&c(Ee,$e);break}case"question.asked":{if(!("sessionID"in ye)||typeof ye.sessionID!="string")break;const Ee=ye;if(d(Ee),gr()?.runtime?.isVSCode&&!ie.current&&De.getState().notifyOnQuestion!==!1){const ct=`question:${Ee.sessionID}:${Ee.id}`;if(!fe.current.has(ct)){fe.current.add(ct);const Xe=Array.isArray(Ee.questions)?Ee.questions[0]:void 0,At=typeof Xe?.header=="string"?Xe.header.trim():"",yt=typeof Xe?.question=="string"?Xe.question.trim():"";Fe({title:At||"Input needed",body:yt||"Agent is waiting for your response",tag:`question-${Ee.sessionID}:${Ee.id}`})}}const tt=`${Ee.sessionID}:${Ee.id}`;oe.current.has(tt)||setTimeout(()=>{const jt=Ze.current;if(jt===Ee.sessionID)return;const ct=Le.getState().sessions.find(yt=>yt.id===Ee.sessionID);if(ct?.parentID&&ct.parentID===jt||!Le.getState().questions.get(Ee.sessionID)?.some(yt=>yt.id===Ee.id))return;oe.current.add(tt);const At=Le.getState().sessions.find(yt=>yt.id===Ee.sessionID)?.title||"Session";cr(async()=>{const{toast:yt}=await import("./vendor-.bun-9lzLHWe8.js").then(dt=>dt.eP);return{toast:yt}},__vite__mapDeps([0,1])).then(({toast:yt})=>{yt.info("Input needed",{id:tt,description:At,duration:3e4,action:{label:"Open",onClick:()=>{De.getState().setActiveMainTab("chat"),Le.getState().setCurrentSession(Ee.sessionID)}}})})},0);break}case"question.replied":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=typeof ye.requestID=="string"?ye.requestID:null;Ee&&$e&&u(Ee,$e);break}case"question.rejected":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=typeof ye.requestID=="string"?ye.requestID:null;Ee&&$e&&u(Ee,$e);break}case"openchamber:notification":{ie.current=!0;const Ee=typeof ye.title=="string"?ye.title:"",$e=typeof ye.body=="string"?ye.body:"",tt=typeof ye.tag=="string"?ye.tag:void 0,jt=!!ye.requireHidden;if(ar()&&ye.desktopStdoutActive)break;Fe({title:Ee,body:$e,tag:tt,requireHidden:jt});break}case"todo.updated":{const Ee=typeof ye.sessionID=="string"?ye.sessionID:null,$e=Array.isArray(ye.todos)?ye.todos:null;Ee&&$e&&lB(Ee,$e);break}}},[m,n,r,o,a,l,c,d,u,v,Re,i,h,z,O,j,b,x,_,k,Ue,Ve,nt,Fe,le]),je=f.useRef(he);f.useEffect(()=>{je.current=he},[he]);const We=f.useRef(_);f.useEffect(()=>{We.current=_},[_]);const lt=f.useCallback(Ke=>{je.current(Ke)},[]),rt=f.useCallback(Ke=>We.current(Ke),[]),Te=f.useCallback(()=>{const Ke=L();return X.current=Ke,Ke==="visible"&&ne.current},[L]),Qe=f.useCallback(()=>{Kn()&&console.debug("[useEventStream] Connection state:",{hasUnsubscribe:!!Q.current,currentSessionId:Ze.current,effectiveDirectory:k,onlineStatus:ne.current,visibilityState:X.current,lastEventTimestamp:ve.current,reconnectAttempts:W.current})},[k]),pt=f.useCallback(()=>{if(ee.current){Kn()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(ee.current=!0,te.current&&(clearTimeout(te.current),te.current=null),Q.current){const Ke=Q.current;Q.current=null;try{Ke()}catch(ye){console.warn("[useEventStream] Error during unsubscribe:",ye)}}ee.current=!1},[]),St=f.useCallback(async Ke=>{if(Qe(),!Te()){se.current=!0,ne.current?H("paused","Paused while hidden"):H("offline","Waiting for network");return}Ke?.resetAttempts&&(W.current=0),pt(),ve.current=Date.now(),H("connecting",null),Kn()&&console.info("[useEventStream] Starting event stream...");const ye=Ee=>{console.warn("Event stream error:",Ee)},Ge=()=>{const Ee=se.current;if(W.current=0,se.current=!1,ve.current=Date.now(),H("connected",null),v(),nt("stream_open"),B.current(Ee),Ee)rt("sse_reconnected");else{const $e=Ze.current;$e&&setTimeout(()=>{_e.current($e,"sse_reconnected",Eo()).then(()=>Re($e)).catch(tt=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",tt)})},0)}};if(Kn()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:k,isCleaningUp:ee.current}),ee.current){Kn()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ee=zt.subscribeToGlobalEvents(tt=>{const jt=tt.payload,ct=tt.payload,Xe=typeof ct.properties=="object"&&ct.properties!==null?ct.properties:{},At=tt.directory&&tt.directory!=="global"?{...Xe,directory:tt.directory}:Xe;lt({type:typeof jt.type=="string"?jt.type:"",properties:At})},ye,Ge),$e=()=>{try{Ee()}catch(tt){console.warn("[useEventStream] Error during unsubscribe:",tt)}};ee.current?$e():Q.current=$e}catch(Ee){console.error("[useEventStream] Error during subscription:",Ee),ye(Ee)}},[Te,pt,H,v,Re,lt,rt,nt,k,Qe]),Ht=f.useCallback(Ke=>{if(!Te()){se.current=!0,pt(),ne.current?H("paused","Paused while hidden"):H("offline","Waiting for network");return}if(te.current)return;const ye=W.current+1;W.current=ye;const Ge=Ke??`Retrying (${ye})`;H("reconnecting",Ge);const Ee=ye<=3?Math.min(1e3*Math.pow(2,ye-1),8e3):Math.min(2e3*Math.pow(2,ye-3),32e3),$e=Math.floor(Math.random()*250),tt=Ee+$e;te.current&&clearTimeout(te.current),te.current=setTimeout(()=>{St({resetAttempts:!1})},tt)},[Te,pt,H,St]);f.useEffect(()=>{ze.current=Ht},[Ht]),f.useEffect(()=>{if(!e){pt(),H("idle",null);return}typeof window<"u"&&(window.__messageTracker=z);const Ke=()=>{pe.current&&(clearTimeout(pe.current),pe.current=null)},ye=()=>{if(X.current=L(),X.current!=="visible")return;if(Ke(),ke("visibility_restore"),nt("visibility_restore"),Date.now()-ve.current>45e3&&(console.info("[useEventStream] Visibility restored with stalled stream, reconnecting..."),se.current=!0),se.current||!Q.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const yt=Ze.current;yt&&(R(yt,"visibility_restore",Eo()),Re(yt)),B.current(!1),nt("visibility_restore_resume"),H("connecting","Resuming stream"),St({resetAttempts:!0})}},Ge=()=>{if(X.current=L(),X.current==="visible"&&(Ke(),ke("window_focus"),nt("window_focus"),Date.now()-ve.current>45e3&&(se.current=!0),se.current||!Q.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const yt=Ze.current;yt&&(Re(yt),R(yt,"window_focus",Eo())),B.current(!1),nt("window_focus_resume"),H("connecting","Resuming stream"),St({resetAttempts:!0})}},Ee=()=>{ne.current=!0,ke("network_restored"),nt("network_restored"),B.current(!1),(se.current||!Q.current)&&(H("connecting","Network restored"),St({resetAttempts:!0}))},$e=()=>{ne.current=!1,se.current=!0,H("offline","Waiting for network"),pt()},tt=()=>{se.current=!0,pt(),H("paused","Paused while hidden")},jt=At=>{if(se.current=se.current||!!At.persisted,X.current=L(),X.current==="visible"){const yt=Ze.current;yt&&(R(yt,"page_show",Eo()),Re(yt)),B.current(!1),nt("page_show"),St({resetAttempts:!0})}};typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",Ee),window.addEventListener("offline",$e),window.addEventListener("focus",Ge),window.addEventListener("pagehide",tt),window.addEventListener("pageshow",jt));const ct=setTimeout(()=>{St({resetAttempts:!0})},100);ae.current&&clearInterval(ae.current),ae.current=setInterval(()=>{if(!Te())return;const At=Date.now();Array.from(Le.getState().sessionStatus?.values?.()??[]).some(dt=>dt?.type==="busy"||dt?.type==="retry")&&nt("stale_check_busy_sessions"),At-ve.current>45e3&&Promise.resolve().then(async()=>{try{if(!await zt.checkHealth()){Ht("Refreshing stalled stream");return}Ht("Refreshing stalled stream")}catch(dt){console.warn("Health check after stale stream failed:",dt),Ht("Refreshing stalled stream")}})},1e4);const Xe=setInterval(()=>{const At=Le.getState().sessionStatus;if(!At)return;const yt=Date.now();At.forEach((dt,Tt)=>{if(dt.type!=="busy"&&dt.type!=="retry")return;const Zt=ce.current.get(Tt)??0,rs=yt-Zt>zS,is=yt-Zt>6e4;rs&&is&&(console.warn("[useEventStream] Session stuck in busy state, forcing idle:",Tt),Ue(Tt,{type:"idle"},"timeout_recovery"))})},3e4);return()=>{clearTimeout(ct),clearInterval(Xe),typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",Ee),window.removeEventListener("offline",$e),window.removeEventListener("focus",Ge),window.removeEventListener("pagehide",tt),window.removeEventListener("pageshow",jt)),Ke(),ae.current&&(clearInterval(ae.current),ae.current=null),at(),Qa.clear(),re.current.clear(),fe.current.clear(),ie.current=!1,se.current=!1,X.current=L(),ne.current=typeof navigator>"u"?!0:navigator.onLine,pt(),q.current&&(clearTimeout(q.current),q.current=null),H("idle",null)}},[e,k,z,L,pt,H,St,Ht,g,Re,st,at,nt,Te,y,ke,P,R,Ue])},hQ=()=>{const t=Le.getState(),e=t.currentSessionId;if(!e)return"";const n=t.sessions.find(r=>r.id===e);return typeof n?.directory=="string"?n.directory:""},pQ=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 u="";if(d){const m=await a.json().catch(()=>null);if(Array.isArray(m))u=`json[array] len=${m.length}`;else if(m&&typeof m=="object"){const h=Object.keys(m).slice(0,8);u=`json[object] keys=${h.join(",")}${Object.keys(m).length>h.length?",…":""}`}else u=`json[${typeof m}]`}else u=l?`content-type=${l}`:"no content-type";return{ok:a.ok&&d,status:a.status,elapsedMs:i,summary:u}}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)}},gQ=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},yQ=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},bQ=async()=>{const t=new Date,e="1.8.7",n=typeof navigator<"u"?navigator.userAgent:"(no navigator)",r=hQ(),o=De.getState().eventStreamStatus,a=typeof window<"u"?window.location.origin:"",i=a?`${a.replace(/\/+$/,"")}/api/`:"",l=await(async()=>{if(!a)return null;const y=new AbortController,b=setTimeout(()=>y.abort(),5e3);try{const x=await fetch(`${a.replace(/\/+$/,"")}/health`,{method:"GET",headers:{Accept:"application/json"},signal:y.signal});if(!x.ok)return null;const v=await x.json().catch(()=>null);return!v||typeof v!="object"||Array.isArray(v)?null:v}catch{return null}finally{clearTimeout(b)}})(),c=await(async()=>{if(!a)return null;const y=new AbortController,b=setTimeout(()=>y.abort(),7e3);try{const x=await fetch(`${a.replace(/\/+$/,"")}/api/config/opencode-resolution`,{method:"GET",headers:{Accept:"application/json"},signal:y.signal}),v=x.headers.get("content-type")||"(none)";if(!x.ok)return{data:null,status:x.status,error:`http ${x.status} content-type=${v}`};const w=await x.text();let C=null;try{C=JSON.parse(w)}catch{const k=w.replace(/\s+/g," ").slice(0,120);return{data:null,status:x.status,error:`invalid json content-type=${v} body=${k||"(empty)"}`}}return!C||typeof C!="object"||Array.isArray(C)?{data:null,status:x.status,error:`invalid json-shape content-type=${v}`}:{data:C,status:x.status,error:null}}catch(x){return{data:null,status:null,error:x instanceof Error?x.message:String(x)}}finally{clearTimeout(b)}})()||{data:null,error:null},d=(y,b=!0)=>{if(!i)return null;const x=new URL(y.replace(/^\/+/,""),i);return b&&r&&x.searchParams.set("directory",r),x.toString()},u=[{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(u.map(async y=>{const b=d(y.path,y.includeDirectory!==!1);if(!b)return{label:y.label,url:"(none)",result:null};const x=await pQ(b,typeof y.timeoutMs=="number"?y.timeoutMs:void 0);return{label:y.label,url:b,result:x}})):[],h=[];h.push(`Time: ${t.toISOString()}`),h.push(`OpenChamber version: ${e}`),h.push(`Runtime: ${a||"(unknown)"} (api=${a?a+"/api":"(unknown)"})`),h.push(`Event stream: ${o}`),h.push(`Directory: ${r||"(none)"}`),h.push(`Platform: ${n}`);const p=yQ(l?.openCodePort);if(h.push(`OpenCode runtime port: ${p??"(unknown)"}`),typeof l?.openCodeRunning=="boolean"&&h.push(`OpenCode runtime running: ${l.openCodeRunning?"yes":"no"}`),typeof l?.openCodeSecureConnection=="boolean"&&h.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?"true":"false"}`),typeof l?.openCodeAuthSource=="string"&&l.openCodeAuthSource.trim()&&h.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<"u"){const y=window.__OPENCHAMBER_MACOS_MAJOR__;typeof y=="number"&&Number.isFinite(y)&&y>0&&h.push(`macOS major: ${y}`)}if(/Mac OS X|Macintosh/.test(n)){h.push(""),h.push("OpenCode CLI resolution:");const y=c.data,b=y&&typeof y.configured=="string"?y.configured:null,x=y&&typeof y.resolved=="string"?y.resolved:l&&typeof l.opencodeBinaryResolved=="string"?l.opencodeBinaryResolved:"",v=y&&typeof y.resolvedDir=="string"?y.resolvedDir:"",w=y&&typeof y.source=="string"?y.source:l&&typeof l.opencodeBinarySource=="string"?l.opencodeBinarySource:"",C=y&&typeof y.shim=="string"?y.shim:l&&typeof l.opencodeShimInterpreter=="string"?l.opencodeShimInterpreter:"",k=y&&typeof y.node=="string"?y.node:l&&typeof l.nodeBinaryResolved=="string"?l.nodeBinaryResolved:"",N=y&&typeof y.bun=="string"?y.bun:l&&typeof l.bunBinaryResolved=="string"?l.bunBinaryResolved:"",S=y&&typeof y.detectedNow=="string"?y.detectedNow:"",j=y&&typeof y.detectedSourceNow=="string"?y.detectedSourceNow:"";if(b!==null&&h.push(`- configured: ${b.trim().length===0?"(cleared)":b}`),x){const A=v||(x.includes("/")?x.split("/").slice(0,-1).join("/")||"/":"");h.push(`- opencode: ${x}${A?` (dir=${A})`:""}`)}else h.push("- opencode: (n/a)");h.push(`- source: ${w||"(n/a)"}`),S&&(h.push(`- detected-now: ${S}`),h.push(`- detected-source: ${j||"(n/a)"}`)),h.push(`- shim: ${C||"(n/a)"}`),h.push(`- node: ${k||"(n/a)"}`),h.push(`- bun: ${N||"(n/a)"}`),!y&&c.error&&h.push(`- resolution-endpoint: ${c.error}`)}if(h.push(""),m.length){h.push("OpenCode API probes:");for(const y of m){if(!y.result){h.push(`- ${y.label}: (no url)`);continue}const{ok:b,status:x,elapsedMs:v,summary:w}=y.result,C=b?"":` url=${y.url}`;h.push(`- ${y.label}: ${b?"ok":"fail"} status=${x} time=${v}ms ${w}${C}`)}}else h.push("OpenCode API probes: (skipped)");return h.push(""),h.push(`Generated: ${gQ(Date.now())}`),h.join(`
6928
6928
  `)},X9=async()=>{const t=await bQ(),e=De.getState();e.setOpenCodeStatusText(t),e.setOpenCodeStatusDialogOpen(!0)},xQ=()=>{const t=Ce.c(33),{openNewSessionDraft:e,abortCurrentOperation:n,armAbortPrompt:r,clearAbortPrompt:o,currentSessionId:a}=Le(),{toggleCommandPalette:i,toggleHelpDialog:l,toggleSidebar:c,toggleNavRail:d,toggleRightSidebar:u,setRightSidebarOpen:m,setRightSidebarTab:h,toggleBottomTerminal:p,setBottomTerminalExpanded:g,isMobile:y,setSessionSwitcherOpen:b,setActiveMainTab:x,setSettingsDialogOpen:v,setModelSelectorOpen:w,toggleExpandedInput:C,shortcutOverrides:k}=De(),{themeMode:N,setThemeMode:S}=ir(),{working:j}=Y4(),A=f.useRef(null),M=f.useRef(null),F=f.useRef(N);let B,D;t[0]!==N?(B=()=>{F.current=N},D=[N],t[0]=N,t[1]=B,t[2]=D):(B=t[1],D=t[2]),f.useEffect(B,D);let E;t[3]!==o?(E=()=>{M.current&&(clearTimeout(M.current),M.current=null),A.current=null,o()},t[3]=o,t[4]=E):E=t[4];const I=E;let T,H;t[5]!==n||t[6]!==r||t[7]!==a||t[8]!==y||t[9]!==e||t[10]!==I||t[11]!==x||t[12]!==g||t[13]!==w||t[14]!==m||t[15]!==h||t[16]!==b||t[17]!==v||t[18]!==S||t[19]!==k||t[20]!==p||t[21]!==i||t[22]!==C||t[23]!==l||t[24]!==d||t[25]!==u||t[26]!==c||t[27]!==j?(T=()=>{const R=O=>Ro(O,k),z=O=>{if(zn(O,R("open_command_palette"))){O.preventDefault(),i();return}if(zn(O,R("open_status"))){O.preventDefault(),X9();return}if(zn(O,R("open_help"))){O.preventDefault(),l();return}const Q=zn(O,R("new_chat")),te=zn(O,R("new_chat_worktree"));if(Q||te){if(O.preventDefault(),x("chat"),b(!1),!ln()&&te){_2();return}e();return}if(zn(O,R("cycle_theme"))){O.preventDefault();const W=["light","dark","system"],U=document.activeElement,q=(W.indexOf(F.current)+1)%W.length;S(W[q]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),U&&document.contains(U)&&U.focus({preventScroll:!0}))});return}if(zn(O,R("open_timeline"))){O.preventDefault();const{isTimelineDialogOpen:W,setTimelineDialogOpen:U}=De.getState();U(!W);return}if(zn(O,R("open_settings"))){O.preventDefault();const{isSettingsDialogOpen:W}=De.getState();v(!W);return}if(zn(O,R("toggle_sidebar"))){O.preventDefault();const{isMobile:W,isSessionSwitcherOpen:U}=De.getState();W?b(!U):c();return}if(zn(O,R("toggle_nav_rail"))){O.preventDefault(),d();return}if(zn(O,R("focus_input"))){O.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(zn(O,R("toggle_right_sidebar"))){const{isMobile:W}=De.getState();if(W)return;O.preventDefault(),u();return}if(zn(O,R("open_right_sidebar_git"))){const{isMobile:W}=De.getState();if(W)return;O.preventDefault(),m(!0),h("git");return}if(zn(O,R("open_right_sidebar_files"))){const{isMobile:W}=De.getState();if(W)return;O.preventDefault(),m(!0),h("files");return}if(zn(O,R("cycle_right_sidebar_tab"))){const{isMobile:W,rightSidebarTab:U}=De.getState();if(W)return;const K=["git","files"],q=K.indexOf(U),ee=K[(q+1)%K.length];O.preventDefault(),m(!0),h(ee);return}if(zn(O,R("toggle_terminal"))){const{isMobile:W}=De.getState();if(W)return;O.preventDefault(),p();return}if(zn(O,R("toggle_terminal_expanded"))){const{isMobile:W,isBottomTerminalExpanded:U}=De.getState();if(W)return;O.preventDefault(),g(!U);return}if(zn(O,R("open_model_selector"))){const{isSettingsDialogOpen:W,isCommandPaletteOpen:U,isHelpDialogOpen:K,isSessionSwitcherOpen:q,isAboutDialogOpen:ee,activeMainTab:V,isModelSelectorOpen:G}=De.getState();if(W||U||K||q||ee||!(V==="chat"))return;O.preventDefault(),w(!G);return}if(zn(O,R("cycle_thinking_variant"))){const{isSettingsDialogOpen:W,isCommandPaletteOpen:U,isHelpDialogOpen:K,isSessionSwitcherOpen:q,isAboutDialogOpen:ee,activeMainTab:V}=De.getState();if(W||U||K||q||ee||!(V==="chat"))return;const oe=Yt.getState();if(oe.getCurrentModelVariants().length===0)return;O.preventDefault(),oe.cycleCurrentVariant();const fe=Yt.getState().currentVariant,ie=Le.getState(),de=ie.currentSessionId,$=Yt.getState().currentAgentName,L=Yt.getState().currentProviderId,X=Yt.getState().currentModelId;de&&$&&L&&X&&ie.saveAgentModelVariantForSession(de,$,L,X,fe);return}if(zn(O,R("cycle_favorite_model_forward"))||zn(O,R("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:W,isCommandPaletteOpen:U,isHelpDialogOpen:K,isSessionSwitcherOpen:q,isAboutDialogOpen:ee,activeMainTab:V,favoriteModels:G,addRecentModel:Y}=De.getState();if(W||U||K||q||ee||!(V==="chat")||G.length===0)return;O.preventDefault();const{currentProviderId:fe,currentModelId:ie,setProvider:de,setModel:$}=Yt.getState(),L=G.length,X=G.findIndex(pe=>pe.providerID===fe&&pe.modelID===ie),ne=zn(O,R("cycle_favorite_model_forward"))?1:-1,se=G[(X+ne+L)%L];de(se.providerID),$(se.modelID),Y(se.providerID,se.modelID);return}if(zn(O,R("expand_input"))){if(y)return;O.preventDefault(),C();return}if(O.key==="Escape"){const U=!!O.target?.closest('[role="dialog"]'),K=!!document.querySelector('[data-settings-view="true"]');if(U||K){I();return}const{isSettingsDialogOpen:q,isCommandPaletteOpen:ee,isHelpDialogOpen:V,isSessionSwitcherOpen:G,isAboutDialogOpen:Y,isMultiRunLauncherOpen:oe,isImagePreviewOpen:re,activeMainTab:fe}=De.getState();if(q){O.preventDefault(),v(!1),I();return}if(ee||V||G||Y||oe||re||!(fe==="chat")){I();return}const $=a;if(!(j.canAbort&&!!$)){I();return}const X=Date.now(),ne=A.current;if(ne&&X<ne){O.preventDefault(),I(),n($||void 0);return}O.preventDefault();const se=r(3e3)??X+3e3;A.current=se,M.current&&clearTimeout(M.current);const pe=Math.max(se-X,0);M.current=setTimeout(()=>{A.current&&Date.now()>=A.current&&I()},pe||0);return}};return window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",z)}},H=[e,n,i,l,c,d,u,m,h,p,g,y,b,x,v,w,C,S,j,r,I,a,k],t[5]=n,t[6]=r,t[7]=a,t[8]=y,t[9]=e,t[10]=I,t[11]=x,t[12]=g,t[13]=w,t[14]=m,t[15]=h,t[16]=b,t[17]=v,t[18]=S,t[19]=k,t[20]=p,t[21]=i,t[22]=C,t[23]=l,t[24]=d,t[25]=u,t[26]=c,t[27]=j,t[28]=T,t[29]=H):(T=t[28],H=t[29]),f.useEffect(T,H);let P,_;t[30]!==I?(P=()=>()=>{I()},_=[I],t[30]=I,t[31]=P,t[32]=_):(P=t[31],_=t[32]),f.useEffect(P,_)},V6="openchamber:menu-action",Jd="openchamber:check-for-updates",vQ=t=>{const{openNewSessionDraft:e}=Le(),{toggleCommandPalette:n,toggleHelpDialog:r,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:i,setSettingsDialogOpen:l,setAboutDialogOpen:c}=De(),{addProject:d}=ls(),u=Ac(v=>v.checkForUpdates),{requestAccess:m,startAccessing:h}=T2(),{setThemeMode:p}=ir(),g=f.useRef(!1),y=f.useCallback(()=>{g.current||(g.current=!0,u().then(()=>{const{available:v,error:w}=Ac.getState();if(w){ue.error("Failed to check for updates",{description:w});return}v||ue.success("You are on the latest version")}).finally(()=>{g.current=!1}))},[u]),b=f.useCallback(()=>{Gs()&&m("").then(async v=>{if(!v.success||!v.path){v.error&&v.error!=="Directory selection cancelled"&&ue.error("Failed to select directory",{description:v.error});return}const w=await h(v.path);if(!w.success){ue.error("Failed to open directory",{description:w.error||"Desktop could not grant file access."});return}d(v.path,{id:v.projectId})||ue.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(v=>{console.error("Desktop: Error selecting directory:",v),ue.error("Failed to select directory")}),ia.requestDirectoryDialog()},[d,m,h]),x=f.useCallback(v=>{switch(v){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),_2();break;case"change-workspace":b();break;case"open-git-tab":{const{activeMainTab:w}=De.getState();i(w==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:w}=De.getState();i(w==="diff"?"chat":"diff");break}case"open-files-tab":{const{activeMainTab:w}=De.getState();i(w==="files"?"chat":"files");break}case"open-terminal-tab":{const{activeMainTab:w}=De.getState();i(w==="terminal"?"chat":"terminal");break}case"copy":{const w=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(w)||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":{X9().catch(()=>{ue.error("Failed to collect OpenCode status")});break}}},[b,t,e,c,i,a,l,p,n,r,o]);f.useEffect(()=>{const v=C=>{const k=C.detail;k&&x(k)},w=()=>{y()};return window.addEventListener(V6,v),window.addEventListener(Jd,w),()=>{window.removeEventListener(V6,v),window.removeEventListener(Jd,w)}},[x,y]),f.useEffect(()=>{if(typeof window>"u")return;const w=window.__TAURI__?.event?.listen;if(typeof w!="function")return;let C=null,k=null;return w("openchamber:menu-action",N=>{const S=N?.payload;typeof S=="string"&&x(S)}).then(N=>{C=N}).catch(()=>{}),w("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Jd))}).then(N=>{k=N}).catch(()=>{}),()=>{(async()=>{try{const S=C?.();S instanceof Promise&&await S}catch{}try{const S=k?.();S instanceof Promise&&await S}catch{}})()}},[x])},wQ=t=>{const e=t?.enabled??!0;f.useEffect(()=>{if(!e)return;let n=!1;return(async()=>{try{const o=await zt.getGlobalSessionStatus();if(n||!o)return;const a=new Map;Object.entries(o).forEach(([i,l])=>{if(!i||!l)return;const c=l;a.set(i,c)}),a.size>0&&Le.setState({sessionStatus:a})}catch{}})(),()=>{n=!0}},[e])},jQ=2e3,SQ=t=>{const e=Le.getState().sessionAbortFlags.get(t);return e?Date.now()-e.timestamp<jQ:!1},U6=(t,e)=>{Le.setState(n=>{const r=new Map(n.sessionStatus??new Map);return r.set(t,{type:e}),{sessionStatus:r}})},kQ=t=>{const e=Yt.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}=Ou(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}},NQ=t=>{const e=bs.getState(),n=Yt.getState(),r=qs.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 CQ(t){const e=t?.enabled??!0,n=io(i=>i.queuedMessages),r=Le(i=>i.sessionStatus),o=f.useRef(new Set),a=f.useRef(new Map);f.useEffect(()=>{if(!e)return;const i=async(u,m)=>{if(m.length===0||o.current.has(u)||SQ(u)||(Le.getState().sessionStatus?.get(u)?.type??"idle")!=="idle")return;const p=kQ(m);if(!p.primaryText&&!p.additionalParts?.length)return;const g=NQ(u);if(!(!g.providerID||!g.modelID)){o.current.add(u),U6(u,"busy");try{await qs.getState().sendMessage(p.primaryText,g.providerID,g.modelID,g.agent,u,p.primaryAttachments,p.agentMentionName,p.additionalParts,g.variant,"normal");const y=io.getState().removeFromQueue;m.forEach(b=>{y(u,b.id)})}catch(y){U6(u,"idle"),console.warn("[queue] queued auto-send failed:",y)}finally{o.current.delete(u)}}},l=new Map(a.current);(r?Array.from(r.entries()):[]).forEach(([u,m])=>{l.set(u,m.type)}),Object.entries(n).forEach(([u,m])=>{const h=r?.get(u)?.type??"idle",p=a.current.get(u),g=(p==="busy"||p==="retry")&&h==="idle",y=p===void 0&&h==="idle";m.length>0&&(g||y)&&i(u,m),l.set(u,h)}),a.current=l},[e,n,r])}const MQ=["chat","git","diff","terminal","files"],AQ=["settings","agents","commands","skills","providers","usage","git-identities"],co={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function W6(t){const e=FQ();return{sessionId:DQ(e),tab:_Q(e),settingsPath:BQ(e),diffFile:EQ(e)}}function FQ(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function DQ(t){const e=t.get(co.SESSION);return!e||e.trim().length===0?null:e.trim()}function _Q(t){const e=t.get(co.TAB);if(!e)return null;const n=e.toLowerCase().trim();return MQ.includes(n)?n:null}function BQ(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":(AQ.includes(n),n)}function EQ(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 q6(){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 IQ="chat";function ey(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!==IQ&&e.set(co.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&e.set(co.FILE,t.diffFile),e}function TQ(t,e){const n=typeof window<"u"?window.location.pathname:"/",r=t.toString();return r?`${n}?${r}`:n}function PQ(t){if(typeof window>"u")return!0;try{const e=new URLSearchParams(window.location.search),n=ey(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 RQ(t,e={}){if(!(typeof window>"u")&&!LQ()&&!(!e.force&&PQ(t)))try{const n=ey(t),r=TQ(n);e.replace?window.history.replaceState({...window.history.state,route:t},"",r):window.history.pushState({route:t},"",r)}catch{}}function LQ(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function zQ(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function HQ(){const t=f.useMemo(()=>zQ(),[]),e=f.useRef(!1),n=f.useRef(!1),r=Le(m=>m.setCurrentSession),o=De(m=>m.setActiveMainTab),a=De(m=>m.setSettingsDialogOpen),i=De(m=>m.setSettingsPage),l=De(m=>m.navigateToDiff),c=f.useCallback(async m=>{if(!n.current){n.current=!0;try{if(m.sessionId){const h=Le.getState().currentSessionId;m.sessionId!==h&&await r(m.sessionId)}if(m.settingsPath){i(L9(m.settingsPath)),a(!0);return}De.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=f.useCallback(()=>{const m=Le.getState(),h=De.getState();return{sessionId:m.currentSessionId,tab:h.activeMainTab,isSettingsOpen:h.isSettingsDialogOpen,settingsPath:h.settingsPage,diffFile:h.pendingDiffFile}},[]),u=f.useCallback((m={})=>{if(t||n.current)return;const h=d();RQ(h,m)},[t,d]);f.useEffect(()=>{if(e.current||(e.current=!0,!q6()))return;const m=W6();(async()=>(await c(m),t||u({replace:!0})))()},[c,t,u]),f.useEffect(()=>{if(t)return;let m=Le.getState().currentSessionId;return Le.subscribe(p=>{const g=p.currentSessionId;g===m||n.current||(m=g,u())})},[t,u]),f.useEffect(()=>{if(t)return;let m=De.getState().activeMainTab,h=De.getState().isSettingsDialogOpen,p=De.getState().settingsPage,g=De.getState().pendingDiffFile;return De.subscribe(b=>{if(n.current)return;const x=b.activeMainTab!==m,v=b.isSettingsDialogOpen!==h,w=b.settingsPage!==p,C=b.pendingDiffFile!==g&&b.activeMainTab==="diff";m=b.activeMainTab,h=b.isSettingsDialogOpen,p=b.settingsPage,g=b.pendingDiffFile,(x||v||w||C)&&u()})},[t,u]),f.useEffect(()=>{if(typeof window>"u"||t)return;const m=()=>{const h=W6();if(q6())c(h);else{const p=De.getState();p.isSettingsDialogOpen&&a(!1),p.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[c,t,o,a])}const OQ=1e4,ty=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},sy=t=>{if(!Uo())return;const e=gr();e?.push?.setVisibility&&e.push.setVisibility({visible:t})},$Q=t=>{const e=Ce.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||!Uo()||typeof document>"u")return;const a=VQ,i=UQ;a();const l=window.setInterval(i,OQ);return document.addEventListener("visibilitychange",a),window.addEventListener("pagehide",a),window.addEventListener("pageshow",a),window.addEventListener("focus",a),window.addEventListener("blur",a),()=>{window.clearInterval(l),document.removeEventListener("visibilitychange",a),window.removeEventListener("pagehide",a),window.removeEventListener("pageshow",a),window.removeEventListener("focus",a),window.removeEventListener("blur",a)}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),f.useEffect(r,o)};function VQ(){sy(ty()==="visible")}function UQ(){ty()==="visible"&&sy(!0)}const WQ=3,qQ=(t,e)=>{if(typeof t!="string")return e;const n=t.trim().replace(/\s+/g," ");return n?n.slice(0,48):e},GQ=(t,e)=>{const n=e?[...t.filter(a=>a.id===e),...t.filter(a=>a.id!==e)]:t,r=[],o=new Set;for(const a of n){const i=typeof a.id=="string"?a.id.trim():"";if(!(!i||o.has(i))&&(o.add(i),r.push({sessionId:i,title:qQ(a.title,`Session ${r.length+1}`)}),r.length>=WQ))break}return r},ZQ=()=>{const t=Ce.c(9),e=Le(KQ),n=Le(QQ);let r;t[0]!==n||t[1]!==e?(r=GQ(e,n),t[0]=n,t[1]=e,t[2]=r):r=t[2];const o=r;let a;t[3]!==o?(a=JSON.stringify(o),t[3]=o,t[4]=a):a=t[4];const i=a;let l,c;t[5]!==o||t[6]!==i?(l=()=>{if(typeof window>"u"||!Uo())return;try{o.length===0?localStorage.removeItem(t6):localStorage.setItem(t6,i)}catch{return}window.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},c=[o,i],t[5]=o,t[6]=i,t[7]=l,t[8]=c):(l=t[7],c=t[8]),f.useEffect(l,c)};function KQ(t){return t.sessions}function QQ(t){return t.currentSessionId}const YQ=()=>{const t=Ce.c(3),{browserTab:e}=D9();let n,r;t[0]!==e?(n=()=>{if(typeof window>"u"||!Uo()||!e)return;let o=null,a=null;const i=()=>{a!==null&&(ue.dismiss(a),a=null)},l=async()=>{if(!o)return;const u=o;o=null,i(),await u.prompt();const{outcome:m}=await u.userChoice;m==="accepted"&&ue.success("Install started")},c=u=>{const m=u;typeof m.prompt=="function"&&(m.preventDefault(),o=m,a===null&&(a=ue.info("Install OpenChamber for quicker access",{duration:1/0,action:{label:"Install",onClick:()=>{l()}}})))},d=()=>{o=null,i(),ue.success("OpenChamber installed")};return window.addEventListener("beforeinstallprompt",c),window.addEventListener("appinstalled",d),()=>{i(),window.removeEventListener("beforeinstallprompt",c),window.removeEventListener("appinstalled",d)}},r=[e],t[0]=e,t[1]=n,t[2]=r):(n=t[1],r=t[2]),f.useEffect(n,r)},JQ="OpenChamber",G6=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),XQ=t=>{const n=t.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},eY=(t,e)=>[t,e,JQ].filter(r=>typeof r=="string"&&r.trim().length>0).join(" | "),tY=()=>{const t=ls(a=>a.activeProjectId?a.projects.find(i=>i.id===a.activeProjectId)??null:null),e=f.useMemo(()=>{if(!t)return null;const a=t.label?.trim();if(a)return G6(a);const i=XQ(t.path);return i?G6(i):null},[t]),[n,r]=f.useState(null);f.useEffect(()=>{if(typeof window>"u"||!Xn()){r(null);return}let a=!1;const i=async()=>{try{const c=window.location.href,d=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin;if(fl(c,d)){a||r(null);return}const m=(await V4()).hosts.find(p=>fl(c,p.url)),h=m?.label?.trim()?Fr(m.label.trim()):"Instance";a||r(h)}catch{a||r("Instance")}};i();const l=()=>{i()};return window.addEventListener("focus",l),()=>{a=!0,window.removeEventListener("focus",l)}},[]);const o=f.useMemo(()=>eY(e,n),[e,n]);f.useEffect(()=>{if(typeof document<"u"&&(document.title=o),!Gs())return;let a=!1;return(async()=>{try{const{getCurrentWindow:l}=await cr(async()=>{const{getCurrentWindow:u}=await import("./vendor-.bun-9lzLHWe8.js").then(m=>m.eR);return{getCurrentWindow:u}},__vite__mapDeps([0,1]));if(a||typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await l().setTitle(o)}catch{return}})(),()=>{a=!0}},[o])},sY=50,nY=15e3,rY=2*6e4,oY=15e3,aY=5e3,iY=t=>{if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const n=e.replace(/\\/g,"/");return n==="/"?"/":n.replace(/\/+$/,"")},lY=(t,e)=>t===e?nY:rY,cY=(t,e)=>t?t.branch!==e.branch||t.tracking!==e.tracking||t.ahead!==e.ahead||t.behind!==e.behind:!!e.branch,Xd=(t,e)=>{const n=[];return e.forEach(r=>{const o=t.get(r);o?.branch&&n.push({directory:r,branch:o.branch,remoteName:null})}),n},dY=(t,e)=>{const n=Ds(k=>k.currentDirectory),r=ls(k=>k.projects),o=Le(k=>k.sessions),a=Le(k=>k.archivedSessions),i=Le(k=>k.availableWorktreesByProject),l=Le(k=>k.worktreeMetadata),c=nr(k=>k.status),d=nr(k=>k.hasChecked),u=nr(k=>k.refreshStatus),m=jo(k=>k.syncBackgroundTargets),h=jo(k=>k.refreshTargets),[p,g]=f.useState(new Map),y=f.useRef(new Map),b=f.useRef([]),x=f.useRef(new Map);f.useEffect(()=>{y.current=p},[p]);const v=f.useCallback(k=>{if(k.length===0)return;const N=new Map;k.forEach(S=>{const j=`${S.directory}::${S.branch}`;N.set(j,S)}),N.forEach((S,j)=>{const A=x.current.get(j);typeof A=="number"&&window.clearTimeout(A);const M=window.setTimeout(()=>{x.current.delete(j),h([S],{force:!0,silent:!0,markInitialResolved:!0})},aY);x.current.set(j,M)})},[h]);f.useEffect(()=>{!t||d||u(t)},[t,d,u]);const w=f.useMemo(()=>{const k=new Map,N=S=>{const j=iY(S);!j||k.has(j)||k.set(j,j)};return N(n),r.forEach(S=>{N(S.path)}),i.forEach(S=>{S.forEach(j=>{N(j.path)})}),l.forEach(S=>{N(S.path)}),[...o,...a].sort((S,j)=>(j.time?.updated??0)-(S.time?.updated??0)).forEach(S=>{const j=S;N(j.directory??null),N(j.project?.worktree??null)}),Array.from(k.values()).slice(0,sY)},[a,i,n,r,o,l]);f.useEffect(()=>{let k=!1;const N=async(A=!1)=>{const M=Date.now(),F=w.filter(I=>{const T=y.current.get(I);return!T||A?!0:M-T.fetchedAt>lY(I,n)});if(F.length===0)return Xd(y.current,w);const B=await Promise.all(F.map(async I=>{try{const T=await e.getGitStatus(I),H=typeof T.current=="string"?T.current.trim():"";return{directory:I,branch:H&&H!=="HEAD"?H:null,tracking:typeof T.tracking=="string"?T.tracking:null,ahead:typeof T.ahead=="number"?T.ahead:0,behind:typeof T.behind=="number"?T.behind:0}}catch{return{directory:I,branch:null,tracking:null,ahead:0,behind:0}}}));if(k)return[];const D=new Map(y.current),E=[];return B.forEach(({directory:I,branch:T,tracking:H,ahead:P,behind:_})=>{const R=D.get(I),z={branch:T,tracking:H,ahead:P,behind:_,fetchedAt:Date.now()};D.set(I,z),T&&cY(R,z)&&E.push({directory:I,branch:T,remoteName:null})}),g(I=>{let T=!1;if(I.size!==D.size)T=!0;else for(const[H,P]of D.entries()){const _=I.get(H);if(!_||_.branch!==P.branch||_.tracking!==P.tracking||_.ahead!==P.ahead||_.behind!==P.behind){T=!0;break}}return y.current=D,T?D:I}),E.length>0&&(h(E,{force:!0,silent:!0,markInitialResolved:!0}),v(E)),Xd(D,w)};N();const S=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||N()},oY),j=()=>{typeof document<"u"&&document.visibilityState!=="visible"||N(!0).then(A=>{const M=A.length>0?A:b.current;if(M.length===0)return;const F=n?M.filter(B=>B.directory===n):[];F.length>0&&h(F,{force:!0,silent:!0,markInitialResolved:!0}),h(M,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})})};return window.addEventListener("focus",j),document.addEventListener("visibilitychange",j),()=>{k=!0,window.clearInterval(S),window.removeEventListener("focus",j),document.removeEventListener("visibilitychange",j)}},[w,n,e,h,v]),f.useEffect(()=>{const k=new Set(w);g(N=>{let S=!1;const j=new Map;return N.forEach((A,M)=>{if(!k.has(M)){S=!0;return}j.set(M,A)}),S?(y.current=j,j):N})},[w]);const C=f.useMemo(()=>Xd(p,w),[p,w]);f.useEffect(()=>{b.current=C},[C]),f.useEffect(()=>{const k=x.current;return()=>{k.forEach(N=>{window.clearTimeout(N)}),k.clear()}},[]),f.useEffect(()=>{m({targets:C,github:t,githubAuthChecked:d,githubConnected:c?.connected??null})},[t,d,c?.connected,m,C])};function uY(){const t=Ce.c(16),{git:e}=mr(),n=Ds(fY),{currentSessionId:r,sessions:o,worktreeMetadata:a}=Le(),{setActiveDirectory:i,startPolling:l,stopPolling:c,fetchAll:d}=or();let u;t[0]!==r||t[1]!==a?(u=r?a.get(r)??void 0:void 0,t[0]=r,t[1]=a,t[2]=u):u=t[2];const m=u;let h;if(t[3]!==r||t[4]!==o){let v;t[6]!==r?(v=w=>w.id===r,t[6]=r,t[7]=v):v=t[7],h=o.find(v),t[3]=r,t[4]=o,t[5]=h}else h=t[5];const g=h?.directory??null,y=m?.path??g??n??null;let b,x;t[8]!==y||t[9]!==d||t[10]!==e||t[11]!==i||t[12]!==l||t[13]!==c?(b=()=>{if(!y||!e){c();return}return i(y),d(y,e,{silentIfCached:!0}),l(e),()=>{c()}},x=[y,e,i,l,c,d],t[8]=y,t[9]=d,t[10]=e,t[11]=i,t[12]=l,t[13]=c,t[14]=b,t[15]=x):(b=t[14],x=t[15]),f.useEffect(b,x)}function fY(t){return t.currentDirectory}function mY(t){const e=Ce.c(2),{children:n}=t;uY();let r;return e[0]!==n?(r=s.jsx(s.Fragment,{children:n}),e[0]=n,e[1]=r):r=e[1],r}const hY="curl -fsSL https://opencode.ai/install | bash",pY=3e3,gY="https://opencode.ai/docs",yY="https://opencode.ai/docs/windows-wsl";function bY(t){const e=Ce.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(Jn,{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 xY=3e4;function vY({onCliAvailable:t}){const[e,n]=f.useState(!1),[r,o]=f.useState(!1),[a,i]=f.useState(!1),[l,c]=f.useState(!1),[d,u]=f.useState(""),[m,h]=f.useState("unknown");f.useEffect(()=>{const k=setTimeout(()=>o(!0),xY);return()=>clearTimeout(k)},[]),f.useEffect(()=>{i(Xn())},[]),f.useEffect(()=>{if(typeof navigator>"u"){h("unknown");return}const k=navigator.userAgent||"";if(/Windows/i.test(k)){h("windows");return}if(/Macintosh|Mac OS X/i.test(k)){h("macos");return}if(/Linux/i.test(k)){h("linux");return}h("unknown")},[]),f.useEffect(()=>{let k=!1;return(async()=>{try{const N=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!N.ok)return;const S=await N.json().catch(()=>null);if(!S||k)return;const j=typeof S.opencodeBinary=="string"?S.opencodeBinary.trim():"";j&&u(j)}catch{}})(),()=>{k=!0}},[]);const p=f.useCallback(async k=>{if(!k.target.closest("button, a, input, select, textarea, code")&&k.button===0&&a&&Gs())try{const{getCurrentWindow:N}=await cr(async()=>{const{getCurrentWindow:j}=await import("./vendor-.bun-9lzLHWe8.js").then(A=>A.eR);return{getCurrentWindow:j}},__vite__mapDeps([0,1]));await N().startDragging()}catch(N){console.error("Failed to start window dragging:",N)}},[a]),g=f.useCallback(async()=>{try{const k=await fetch("/health");if(!k.ok)return!1;const N=await k.json();return N.openCodeRunning===!0||N.isOpenCodeReady===!0}catch{return!1}},[]),y=f.useCallback(async()=>{c(!0);try{await fetch("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>c(!1),1e3)}},[]),b=f.useCallback(async()=>{if(typeof window>"u"||!a||!Gs())return;const k=window.__TAURI__;if(k?.dialog?.open)try{const N=await k.dialog.open({title:"Select opencode binary",multiple:!1,directory:!1});typeof N=="string"&&N.trim().length>0&&u(N.trim())}catch{}},[a]),x=f.useCallback(async()=>{c(!0);try{await Rs({opencodeBinary:d.trim()}),await fetch("/api/config/reload",{method:"POST"})}finally{setTimeout(()=>c(!1),1e3)}},[d]),v=f.useCallback(async()=>{const k=await Cn(hY);k.ok?(n(!0),setTimeout(()=>n(!1),2e3)):console.error("Failed to copy:",k.error)},[]);f.useEffect(()=>{const k=async()=>{await g()&&t?.()},N=setInterval(k,pY);return k(),()=>clearInterval(N)},[g,t]);const w=m==="windows"?yY:gY,C=m==="windows"?"C:\\Users\\you\\AppData\\Roaming\\npm\\opencode.cmd":m==="linux"?"/home/you/.bun/bin/opencode":"/Users/you/.bun/bin/opencode";return s.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:p,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(yr,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),m==="windows"&&s.jsxs("div",{className:"mx-auto max-w-2xl rounded-lg border border-border bg-background/50 p-4 text-left",children:[s.jsx("div",{className:"text-sm text-foreground",children:"Windows setup (WSL recommended)"}),s.jsxs("ol",{className:"mt-2 list-decimal space-y-1 pl-5 text-sm text-muted-foreground",children:[s.jsxs("li",{children:["Install WSL (if needed) with ",s.jsx("code",{className:"text-foreground/80",children:"wsl --install"})," in PowerShell."]}),s.jsx("li",{children:"Run the install command below inside your WSL terminal."}),s.jsx("li",{children:"If OpenChamber does not detect OpenCode automatically, set the binary path below."})]})]}),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(vs,{className:"h-4 w-4"}),"Copied to clipboard"]}):s.jsx(bY,{onCopy:v})})}),s.jsxs("a",{href:w,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:[m==="windows"?"View Windows + WSL documentation":"View documentation",s.jsx(yr,{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:y,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(ts,{value:d,onChange:k=>u(k.target.value),placeholder:C,disabled:l,className:"flex-1 font-mono text-xs"}),s.jsx(ot,{type:"button",variant:"secondary",onClick:b,disabled:l||!a||!Gs(),children:"Browse"}),s.jsx(ot,{type:"button",onClick:x,disabled:l,children:"Apply"})]}),s.jsx("div",{className:"text-xs text-muted-foreground/70",children:"Saves to OpenChamber settings and reloads OpenCode configuration."})]})})]}),r&&s.jsx("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:m==="windows"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-muted-foreground/70",children:"On Windows, install and run OpenCode in WSL for best compatibility."}),s.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["If detection fails, set a native path (",s.jsx("code",{className:"text-foreground/70",children:"opencode.cmd"}),"/",s.jsx("code",{className:"text-foreground/70",children:"opencode.exe"}),"), ",s.jsx("code",{className:"text-foreground/70",children:"wsl.exe"}),", or ",s.jsx("code",{className:"text-foreground/70",children:"wsl:/usr/local/bin/opencode"}),"."]})]}):s.jsxs(s.Fragment,{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 wY=()=>{const t=Ce.c(5),[e,n]=f.useState(jY),{isUpdating:r,message:o}=e;let a,i;if(t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>ow(n),i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),f.useEffect(a,i),!r)return null;let l;t[2]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(B2,{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 jY(){return aw()}const f4={getLastAssistantMessage(){const t=Le.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(h=>{const p={id:h.id,type:h.type};return h.type==="text"?(p.text=h.text,p.textLength=h.text?.length||0):h.type==="tool"?(p.tool=h.tool,p.state=h.state?.status):(h.type==="step-start"||h.type==="step-finish")&&(p.isStepMarker=!0),p}),i=a.some(h=>h.type==="text"&&h.text&&h.text.trim().length>0),l=a.some(h=>h.type==="tool"),c=a.some(h=>h.type==="step-start"||h.type==="step-finish"),d=a.length===0,u=!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:u,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=Le.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=Ds.getState(),e=Le.getState(),n=ls.getState(),r=t.currentDirectory||null,o=zt.getDirectory()??null,a=e.sessions||[],i=new Set,l={};a.forEach(S=>{const j=S.directory;typeof j=="string"&&j.trim().length>0?(i.add(j),l[j]=(l[j]??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(S){return{available:!1,error:S instanceof Error?S.message:String(S)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,u=typeof window<"u"&&!!window.__TAURI__,m=async S=>{try{return await S.json()}catch{return null}},h=async S=>{try{return await S.text()}catch{return null}},p=async S=>{try{const j=await fetch(S);return j.ok?await m(j):{status:j.status}}catch(j){return{error:j instanceof Error?j.message:String(j)}}};let g=null,y=null,b=null,x=null;const v=r?`/api/path?directory=${encodeURIComponent(r)}`:"/api/path";g=await p(v);const w=r?`/api/project/current?directory=${encodeURIComponent(r)}`:"/api/project/current";y=await p(w),b=await p("/api/config/settings");try{const S=await fetch("/api/health"),j=S.headers.get("content-type")||"",A=await h(S),M=j.toLowerCase().includes("application/json");let F=null;if(M&&A)try{const B=JSON.parse(A);B&&typeof B=="object"&&!Array.isArray(B)&&(F=B)}catch{F=null}x={status:S.status,ok:S.ok,contentType:j,type:M?"json":"html",openCodePort:F?.openCodePort??null,openCodeRunning:F?.openCodeRunning??null,openCodeSecureConnection:F?.openCodeSecureConnection??null,openCodeAuthSource:F?.openCodeAuthSource??null,isOpenCodeReady:F?.isOpenCodeReady??null,lastOpenCodeError:F?.lastOpenCodeError??null,preview:A?A.slice(0,120):null}}catch(S){x={error:S instanceof Error?S.message:String(S)}}let C={isGitRepo:null};if(r)try{C.isGitRepo=await la(r)}catch(S){C={isGitRepo:null,error:S instanceof Error?S.message:String(S)}}const k=n.projects.map(S=>({id:S.id,path:S.path,label:S.label})),N={runtime:{platform:d?.runtime?.platform??null,isDesktop:u,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:g?.directory||g?.worktree||o,homeDirectory:t.homeDirectory||null,isHomeReady:t.isHomeReady,hasPersistedDirectory:t.hasPersistedDirectory,isSwitchingDirectory:t.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:k},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:C,localStorage:c,opencode:{pathInfo:g,projectInfo:y,health:x},openchamber:{settingsInfo:b}};return console.log("[DEBUG] App status snapshot:",N),N},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=Le.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=Le.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:
6929
6929
  `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
6930
6930
  `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
6931
6931
  `),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)
6932
- `),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=Le.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(h=>h.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=h=>typeof h=="number"&&Number.isFinite(h)?h:null,u=h=>{const p=h.filter(g=>typeof g=="number");return p.length>0?Math.max(...p):null},m=l.map((h,p)=>{const g=h.info??{},y=Array.isArray(h.parts)?h.parts:[],b=g.time??{},x=d(b.completed),v=x!==null,w=y.filter(B=>B.type==="tool"),C=y.filter(B=>B.type==="reasoning"),k=u(w.map(B=>d(B.state?.time?.end??B.state?.time?.start))),N=u(C.map(B=>d(B.time?.end??B.time?.start))),S=u([k,N].filter(B=>B!==null)),j=w.some(B=>["pending","running","started"].includes(B.state?.status)),A=C.some(B=>typeof B.time?.end!="number");w.length>0&&(c.withTools+=1),C.length>0&&(c.withReasoning+=1),v||(c.completedMissing+=1);const M=!!(v&&typeof k=="number"&&x<k);M&&(c.completedBeforeTool+=1);const F=!!(v&&typeof N=="number"&&x<N);return F&&(c.completedBeforeReasoning+=1),v&&j&&(c.runningToolsWhenCompleted+=1),v&&A&&(c.reasoningOpenWhenCompleted+=1),{index:p,messageId:g.id,role:g.role,completedAt:x,latestToolTimestamp:k,latestReasoningTimestamp:N,latestPartTimestamp:S,completed_missing:!v,completed_before_tool:M,completed_before_reasoning:F,running_tools_when_completed:!!(v&&j),reasoning_open_when_completed:!!(v&&A),has_tools:w.length>0,has_reasoning:C.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=Le.getState(),e=t.currentSessionId;if(!e)return console.log("[ERROR] No active session"),null;const r=(t.messages.get(e)||[]).filter(b=>b.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(b=>b.type==="step-finish"),i=o.info.finish==="stop",c=o.info.time?.completed,d=o.info.status,u=typeof c=="number"&&c>0||d==="completed",m=!!(u&&i),h=t.messageStreamStates,p=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,g=h.get(o.info.id),y=o.info.id===p;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:",u),console.log("hasStopReason:",i),console.log("messageIsComplete:",m),console.log("lifecycle phase:",g?.phase),console.log("isStreamingCandidate:",y),console.log("streamingMessageId:",p),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:c,status:d,hasCompletedFlag:u,hasStopReason:i,messageIsComplete:m,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=f4,Kn()&&(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 SY=({open:t,onOpenChange:e})=>{const[n,r]=f.useState(null),[o,a]=f.useState(!1),[i,l]=f.useState(!1),[c,d]=f.useState(null),[u,m]=f.useState(!1),h=f.useCallback(async()=>{if(!o){a(!0),l(!1);try{if(!c){ue.error("Copy failed",{description:"Diagnostics not ready yet. Wait a second and retry."});return}const g=await f4.copyTextToClipboard(c);g.ok?(l(!0),ue.success("Diagnostics copied")):ue.error("Copy failed",{description:g.error})}catch(g){ue.error("Copy failed"),console.error("Failed to copy diagnostics:",g)}finally{a(!1)}}},[c,o]);f.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.__TAURI__?(async()=>{try{const{getVersion:b}=await cr(async()=>{const{getVersion:v}=await import("./vendor-.bun-9lzLHWe8.js").then(w=>w.eT);return{getVersion:v}},__vite__mapDeps([0,1])),x=await b();r(x)}catch{r("1.8.6")}})():r("1.8.6")},[t]),f.useEffect(()=>{if(!t){d(null),m(!1);return}let g=!1;return m(!0),f4.buildDiagnosticsReport().then(y=>{g||d(y)}).catch(y=>{g||(console.error("Failed to prepare diagnostics:",y),d(null))}).finally(()=>{g||m(!1)}),()=>{g=!0}},[t]);const p=n;return s.jsx($s,{open:t,onOpenChange:e,children:s.jsx(Vs,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(B2,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),p&&s.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",p]})]}),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:h,disabled:o||u||!c,className:J("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:i?"Diagnostics copied":u?"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(Na,{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(Hp,{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(du,{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 O1(t){const e=Ce.c(3),{apis:n,children:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(k2.Provider,{value:n,children:r}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o}const kY=/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|opencode(\.exe)?:\s*command\s+not\s+found|not\s+recognized\s+as\s+an\s+internal\s+or\s+external\s+command|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,NY=1500,CY=()=>{const t=Ce.c(3),{isAboutDialogOpen:e,setAboutDialogOpen:n}=De();let r;return t[0]!==e||t[1]!==n?(r=s.jsx(SY,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},MY=()=>{if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search);if(t.get("ocPanel")!=="session-chat")return null;const e=t.get("sessionId"),n=typeof e=="string"?e.trim():"";if(!n)return null;const r=t.get("directory"),o=typeof r=="string"&&r.trim().length>0?r.trim():null;return{sessionId:n,directory:o}};function AY({apis:t}){const{initializeApp:e,isInitialized:n,isConnected:r}=Yt(),o=Yt(_=>_.providers.length),a=Yt(_=>_.agents.length),i=Yt(_=>_.loadProviders),l=Yt(_=>_.loadAgents),{error:c,clearError:d,loadSessions:u}=Le(),m=Le(_=>_.currentSessionId),h=Le(_=>_.setCurrentSession),p=Le(_=>_.sessions),g=Ds(_=>_.currentDirectory),y=Ds(_=>_.setDirectory),b=Ds(_=>_.isSwitchingDirectory),[x,v]=f.useState(!1),{uiFont:w,monoFont:C}=h9(),k=nr(_=>_.refreshStatus),[N,S]=f.useState(()=>t.runtime.isVSCode),[j,A]=f.useState(!1),[M,F]=f.useState(!0),B=f.useRef(!1),D=f.useMemo(()=>MY(),[]),E=!D||M;f.useEffect(()=>{S(t.runtime.isVSCode)},[t.runtime.isVSCode]),f.useEffect(()=>(W3(t),()=>W3(null)),[t]),f.useEffect(()=>{D||k(t.github,{force:!0})},[t.github,D,k]),dY(E?t.github:void 0,t.git),f.useEffect(()=>{if(typeof document>"u")return;const _=document.documentElement,R=_5[w]?.stack??_5[IO].stack,z=Za[C]?.stack??Za[d0].stack;_.style.setProperty("--font-sans",R),_.style.setProperty("--font-heading",R),_.style.setProperty("--font-family-sans",R),_.style.setProperty("--font-mono",z),_.style.setProperty("--font-family-mono",z),_.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=R)},[w,C]),f.useEffect(()=>{if(n){const R=setTimeout(()=>{const z=document.getElementById("initial-loading");z&&(z.classList.add("fade-out"),setTimeout(()=>{z.remove()},300))},150);return()=>clearTimeout(R)}},[n]),f.useEffect(()=>{const _=setTimeout(()=>{const R=document.getElementById("initial-loading");R&&!n&&(R.classList.add("fade-out"),setTimeout(()=>{R.remove()},300))},5e3);return()=>clearTimeout(_)},[n]),f.useEffect(()=>{(async()=>N||await e())()},[e,N]);const I=f.useRef(!1),T=f.useRef(0);f.useEffect(()=>{if(N||!r||o>0&&a>0||I.current)return;const _=Date.now();if(_-T.current<750)return;T.current=_,I.current=!0,(async()=>{try{o===0&&await i(),a===0&&await l()}catch{}finally{I.current=!1}})()},[a,r,N,l,i,o]),f.useEffect(()=>{if(b)return;(async()=>N||r&&(zt.setDirectory(g),await u()))()},[g,b,u,r,N]),f.useEffect(()=>{if(!D||typeof window>"u")return;const _=O=>{const Q=O?.visible===!0;F(Q)},R=O=>{if(O.origin!==window.location.origin)return;const Q=O.data;Q?.type==="openchamber:embedded-visibility"&&_(Q.payload)},z=window;return z.__openchamberSetEmbeddedVisibility=_,window.addEventListener("message",R),()=>{window.removeEventListener("message",R),z.__openchamberSetEmbeddedVisibility===_&&delete z.__openchamberSetEmbeddedVisibility}},[D]),f.useEffect(()=>{!D?.directory||N||g!==D.directory&&y(D.directory,{showOverlay:!1})},[g,D,N,y]),f.useEffect(()=>{!D||N||m!==D.sessionId&&p.some(_=>_.id===D.sessionId)&&h(D.sessionId)},[m,D,N,p,h]),f.useEffect(()=>{if(!D||typeof window>"u")return;const _=R=>{R.storageArea===window.localStorage&&R.key==="ui-store"&&De.persist.rehydrate()};return window.addEventListener("storage",_),()=>{window.removeEventListener("storage",_)}},[D]),f.useEffect(()=>{typeof window>"u"||!n||b||B.current||(B.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,b]),mQ({enabled:E}),NS({enabled:E}),$Q({enabled:E}),ZQ(),YQ(),tY(),HQ(),xQ();const H=f.useCallback(()=>{v(_=>!_)},[]);vQ(H),wQ({enabled:E}),E9({enabled:E}),CQ({enabled:E}),f.useEffect(()=>{if(D)return;const _=R=>{m2(R)&&R.shiftKey&&R.key==="D"&&(R.preventDefault(),v(z=>!z))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[D]),f.useEffect(()=>{D||c&&setTimeout(()=>d(),5e3)},[d,D,c]),f.useEffect(()=>{if(D||!Xn()||!ar())return;let _=!1;const R=async()=>{const O=await fetch("/health",{method:"GET"}).catch(()=>null);if(!O||!O.ok||_)return;const Q=await O.json().catch(()=>null);if(!Q||_)return;const te=Q.openCodeRunning===!0,W=Q.isOpenCodeReady===!0,K=(typeof Q.opencodeBinaryResolved=="string"?Q.opencodeBinaryResolved.trim():"").length>0,q=typeof Q.lastOpenCodeError=="string"?Q.lastOpenCodeError:"",ee=!te&&(kY.test(q)||!K&&!W);A(ee)};R();const z=window.setInterval(()=>{R()},NY);return()=>{_=!0,window.clearInterval(z)}},[D]);const P=f.useCallback(()=>{A(!1),window.location.reload()},[]);return j?s.jsx(Nn,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(vY,{onCliAvailable:P})})}):D?s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(al,{}),s.jsx(b1,{})]})})})}):N?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(GK,{}),s.jsx(b1,{})]})})})}):s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx(y5,{children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(wK,{}),s.jsx(b1,{})]})})})})}):s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx(mY,{children:s.jsx(y5,{children:s.jsx(LD,{children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(gK,{}),s.jsx(b1,{}),s.jsx(wY,{}),s.jsx(CY,{}),x&&s.jsx(ZK,{onClose:()=>v(!1)})]})})})})})})})}const ny=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=Ds.getState();t&&n.homeDirectory!==t&&n.synchronizeHomeDirectory(t),e&&!ln()&&n.setDirectory(e,{showOverlay:!1})},ry="/auth/session",FY=async()=>{console.log("[Frontend Auth] Checking session status...");const t=await fetch(ry,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});return console.log("[Frontend Auth] Session status response:",t.status,t.statusText),t},DY=async t=>{console.log("[Frontend Auth] Submitting password...");const e=await fetch(ry,{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},oy=t=>{const e=Ce.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},_Y=()=>{const t=Ce.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background text-foreground",children:s.jsx(B2,{width:120,height:120,isAnimated:!0})}),t[0]=e):e=t[0],e},Z6=t=>{const e=Ce.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 u=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]!==u?(m=s.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:u}),e[2]=u,e[3]=m):m=e[3];let h;e[4]!==d||e[5]!==m?(h=s.jsxs("div",{className:"space-y-2",children:[d,m]}),e[4]=d,e[5]=m,e[6]=h):h=e[6];let p;e[7]!==n?(p=s.jsx(ot,{type:"button",onClick:n,className:"w-full max-w-xs",children:"Retry"}),e[7]=n,e[8]=p):p=e[8];let g;return e[9]!==h||e[10]!==p?(g=s.jsx(oy,{children:s.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[h,p]})}),e[9]=h,e[10]=p,e[11]=g):g=e[11],g},BY=({children:t})=>{const e=f.useMemo(()=>ln(),[]),n=e,r=f.useMemo(()=>Xn()&&!e,[e]),[o,a]=f.useState(()=>n?"authenticated":"pending"),[i,l]=f.useState(""),[c,d]=f.useState(!1),[u,m]=f.useState(""),[h,p]=f.useState(void 0),[g,y]=f.useState(!1),b=f.useRef(null),x=f.useRef(n),v=f.useCallback(async()=>{if(n){console.log("[Frontend Auth] VSCode runtime, skipping auth"),a("authenticated");return}const C=document.cookie,k=C.includes("oc_ui_session="),N=C.includes("oc_ui_refresh=");console.log("[Frontend Auth] Cookies check - access:",k,"refresh:",N),console.log("[Frontend Auth] All cookies:",C.split(";").map(S=>S.trim().split("=")[0])),a(S=>S==="authenticated"?S:"pending");try{const S=await FY(),j=await S.text();if(console.log("[Frontend Auth] Raw response:",S.status,j),S.ok){console.log("[Frontend Auth] Session is authenticated"),a("authenticated"),y(!1),m(""),p(void 0);return}if(S.status===401){let A={};try{A=JSON.parse(j)}catch{A={}}console.warn("[Frontend Auth] Session is locked (401)",A),A.debug&&console.warn("[Frontend Auth] Debug info:",A.debug),y(A.tunnelLocked===!0),a("locked"),p(void 0);return}if(S.status===429){let A={};try{A=JSON.parse(j)}catch{A={}}p(A.retryAfter),y(!1),a("rate-limited");return}console.error("[Frontend Auth] Unexpected response status:",S.status),a("error"),y(!1)}catch(S){console.warn("Failed to check session status:",S),a("error"),y(!1)}},[n]);f.useEffect(()=>{n||v()},[v,n]),f.useEffect(()=>{!n&&o==="locked"&&(x.current=!1)},[n,o]),f.useEffect(()=>{o==="locked"&&b.current&&(b.current.focus(),b.current.select())},[o]),f.useEffect(()=>{n||o==="authenticated"&&!x.current&&(x.current=!0,(async()=>(await i8(),await l8(),await ny()))())},[n,o]);const w=async C=>{if(C.preventDefault(),!g&&!(!i||c)){d(!0),m("");try{const k=await DY(i);if(k.ok){console.log("[Frontend Auth] Login successful");const N=document.cookie,S=N.includes("oc_ui_session="),j=N.includes("oc_ui_refresh=");console.log("[Frontend Auth] After login - access:",S,"refresh:",j),console.log("[Frontend Auth] All cookies after login:",N.split(";").map(A=>A.trim().split("=")[0]).filter(Boolean)),l(""),y(!1),a("authenticated");return}if(k.status===401){console.warn("[Frontend Auth] Login failed: Invalid password"),m("Incorrect password. Try again."),y(!1),a("locked");return}if(k.status===429){console.warn("[Frontend Auth] Login failed: Rate limited");const N=await k.json().catch(()=>({}));p(N.retryAfter),y(!1),a("rate-limited");return}console.error("[Frontend Auth] Login failed: Unexpected response",k.status),m("Unexpected response from server."),y(!1),a("error")}catch(k){console.warn("Failed to submit UI password:",k),m("Network error. Check connection and retry."),y(!1),a("error")}finally{d(!1)}}};return o==="pending"?s.jsx(_Y,{}):o==="error"?s.jsx(Z6,{onRetry:()=>{v()},errorType:"network"}):o==="rate-limited"?s.jsx(Z6,{onRetry:()=>{v()},errorType:"rate-limit",retryAfter:h}):o==="locked"?s.jsx(oy,{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:g?"Tunnel access required":"Unlock OpenChamber"}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:g?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!g&&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(lv,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),s.jsx(ts,{id:"openchamber-ui-password",ref:b,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:C=>{l(C.target.value),u&&m("")},className:"pl-10","aria-invalid":!!u||void 0,"aria-describedby":u?"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(os,{className:"h-4 w-4 animate-spin"}):s.jsx(cv,{className:"h-4 w-4"})})]}),u&&s.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:u})]}),r&&s.jsxs("div",{className:"w-full",children:[s.jsx(IN,{}),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})},eu=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 EY{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(`
6932
+ `),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=Le.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(h=>h.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=h=>typeof h=="number"&&Number.isFinite(h)?h:null,u=h=>{const p=h.filter(g=>typeof g=="number");return p.length>0?Math.max(...p):null},m=l.map((h,p)=>{const g=h.info??{},y=Array.isArray(h.parts)?h.parts:[],b=g.time??{},x=d(b.completed),v=x!==null,w=y.filter(B=>B.type==="tool"),C=y.filter(B=>B.type==="reasoning"),k=u(w.map(B=>d(B.state?.time?.end??B.state?.time?.start))),N=u(C.map(B=>d(B.time?.end??B.time?.start))),S=u([k,N].filter(B=>B!==null)),j=w.some(B=>["pending","running","started"].includes(B.state?.status)),A=C.some(B=>typeof B.time?.end!="number");w.length>0&&(c.withTools+=1),C.length>0&&(c.withReasoning+=1),v||(c.completedMissing+=1);const M=!!(v&&typeof k=="number"&&x<k);M&&(c.completedBeforeTool+=1);const F=!!(v&&typeof N=="number"&&x<N);return F&&(c.completedBeforeReasoning+=1),v&&j&&(c.runningToolsWhenCompleted+=1),v&&A&&(c.reasoningOpenWhenCompleted+=1),{index:p,messageId:g.id,role:g.role,completedAt:x,latestToolTimestamp:k,latestReasoningTimestamp:N,latestPartTimestamp:S,completed_missing:!v,completed_before_tool:M,completed_before_reasoning:F,running_tools_when_completed:!!(v&&j),reasoning_open_when_completed:!!(v&&A),has_tools:w.length>0,has_reasoning:C.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=Le.getState(),e=t.currentSessionId;if(!e)return console.log("[ERROR] No active session"),null;const r=(t.messages.get(e)||[]).filter(b=>b.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(b=>b.type==="step-finish"),i=o.info.finish==="stop",c=o.info.time?.completed,d=o.info.status,u=typeof c=="number"&&c>0||d==="completed",m=!!(u&&i),h=t.messageStreamStates,p=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,g=h.get(o.info.id),y=o.info.id===p;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:",u),console.log("hasStopReason:",i),console.log("messageIsComplete:",m),console.log("lifecycle phase:",g?.phase),console.log("isStreamingCandidate:",y),console.log("streamingMessageId:",p),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:c,status:d,hasCompletedFlag:u,hasStopReason:i,messageIsComplete:m,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=f4,Kn()&&(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 SY=({open:t,onOpenChange:e})=>{const[n,r]=f.useState(null),[o,a]=f.useState(!1),[i,l]=f.useState(!1),[c,d]=f.useState(null),[u,m]=f.useState(!1),h=f.useCallback(async()=>{if(!o){a(!0),l(!1);try{if(!c){ue.error("Copy failed",{description:"Diagnostics not ready yet. Wait a second and retry."});return}const g=await f4.copyTextToClipboard(c);g.ok?(l(!0),ue.success("Diagnostics copied")):ue.error("Copy failed",{description:g.error})}catch(g){ue.error("Copy failed"),console.error("Failed to copy diagnostics:",g)}finally{a(!1)}}},[c,o]);f.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.__TAURI__?(async()=>{try{const{getVersion:b}=await cr(async()=>{const{getVersion:v}=await import("./vendor-.bun-9lzLHWe8.js").then(w=>w.eT);return{getVersion:v}},__vite__mapDeps([0,1])),x=await b();r(x)}catch{r("1.8.7")}})():r("1.8.7")},[t]),f.useEffect(()=>{if(!t){d(null),m(!1);return}let g=!1;return m(!0),f4.buildDiagnosticsReport().then(y=>{g||d(y)}).catch(y=>{g||(console.error("Failed to prepare diagnostics:",y),d(null))}).finally(()=>{g||m(!1)}),()=>{g=!0}},[t]);const p=n;return s.jsx($s,{open:t,onOpenChange:e,children:s.jsx(Vs,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(B2,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),p&&s.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",p]})]}),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:h,disabled:o||u||!c,className:J("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:i?"Diagnostics copied":u?"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(Na,{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(Hp,{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(du,{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 O1(t){const e=Ce.c(3),{apis:n,children:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(k2.Provider,{value:n,children:r}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o}const kY=/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|opencode(\.exe)?:\s*command\s+not\s+found|not\s+recognized\s+as\s+an\s+internal\s+or\s+external\s+command|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,NY=1500,CY=()=>{const t=Ce.c(3),{isAboutDialogOpen:e,setAboutDialogOpen:n}=De();let r;return t[0]!==e||t[1]!==n?(r=s.jsx(SY,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},MY=()=>{if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search);if(t.get("ocPanel")!=="session-chat")return null;const e=t.get("sessionId"),n=typeof e=="string"?e.trim():"";if(!n)return null;const r=t.get("directory"),o=typeof r=="string"&&r.trim().length>0?r.trim():null;return{sessionId:n,directory:o}};function AY({apis:t}){const{initializeApp:e,isInitialized:n,isConnected:r}=Yt(),o=Yt(_=>_.providers.length),a=Yt(_=>_.agents.length),i=Yt(_=>_.loadProviders),l=Yt(_=>_.loadAgents),{error:c,clearError:d,loadSessions:u}=Le(),m=Le(_=>_.currentSessionId),h=Le(_=>_.setCurrentSession),p=Le(_=>_.sessions),g=Ds(_=>_.currentDirectory),y=Ds(_=>_.setDirectory),b=Ds(_=>_.isSwitchingDirectory),[x,v]=f.useState(!1),{uiFont:w,monoFont:C}=h9(),k=nr(_=>_.refreshStatus),[N,S]=f.useState(()=>t.runtime.isVSCode),[j,A]=f.useState(!1),[M,F]=f.useState(!0),B=f.useRef(!1),D=f.useMemo(()=>MY(),[]),E=!D||M;f.useEffect(()=>{S(t.runtime.isVSCode)},[t.runtime.isVSCode]),f.useEffect(()=>(W3(t),()=>W3(null)),[t]),f.useEffect(()=>{D||k(t.github,{force:!0})},[t.github,D,k]),dY(E?t.github:void 0,t.git),f.useEffect(()=>{if(typeof document>"u")return;const _=document.documentElement,R=_5[w]?.stack??_5[IO].stack,z=Za[C]?.stack??Za[d0].stack;_.style.setProperty("--font-sans",R),_.style.setProperty("--font-heading",R),_.style.setProperty("--font-family-sans",R),_.style.setProperty("--font-mono",z),_.style.setProperty("--font-family-mono",z),_.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=R)},[w,C]),f.useEffect(()=>{if(n){const R=setTimeout(()=>{const z=document.getElementById("initial-loading");z&&(z.classList.add("fade-out"),setTimeout(()=>{z.remove()},300))},150);return()=>clearTimeout(R)}},[n]),f.useEffect(()=>{const _=setTimeout(()=>{const R=document.getElementById("initial-loading");R&&!n&&(R.classList.add("fade-out"),setTimeout(()=>{R.remove()},300))},5e3);return()=>clearTimeout(_)},[n]),f.useEffect(()=>{(async()=>N||await e())()},[e,N]);const I=f.useRef(!1),T=f.useRef(0);f.useEffect(()=>{if(N||!r||o>0&&a>0||I.current)return;const _=Date.now();if(_-T.current<750)return;T.current=_,I.current=!0,(async()=>{try{o===0&&await i(),a===0&&await l()}catch{}finally{I.current=!1}})()},[a,r,N,l,i,o]),f.useEffect(()=>{if(b)return;(async()=>N||r&&(zt.setDirectory(g),await u()))()},[g,b,u,r,N]),f.useEffect(()=>{if(!D||typeof window>"u")return;const _=O=>{const Q=O?.visible===!0;F(Q)},R=O=>{if(O.origin!==window.location.origin)return;const Q=O.data;Q?.type==="openchamber:embedded-visibility"&&_(Q.payload)},z=window;return z.__openchamberSetEmbeddedVisibility=_,window.addEventListener("message",R),()=>{window.removeEventListener("message",R),z.__openchamberSetEmbeddedVisibility===_&&delete z.__openchamberSetEmbeddedVisibility}},[D]),f.useEffect(()=>{!D?.directory||N||g!==D.directory&&y(D.directory,{showOverlay:!1})},[g,D,N,y]),f.useEffect(()=>{!D||N||m!==D.sessionId&&p.some(_=>_.id===D.sessionId)&&h(D.sessionId)},[m,D,N,p,h]),f.useEffect(()=>{if(!D||typeof window>"u")return;const _=R=>{R.storageArea===window.localStorage&&R.key==="ui-store"&&De.persist.rehydrate()};return window.addEventListener("storage",_),()=>{window.removeEventListener("storage",_)}},[D]),f.useEffect(()=>{typeof window>"u"||!n||b||B.current||(B.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,b]),mQ({enabled:E}),NS({enabled:E}),$Q({enabled:E}),ZQ(),YQ(),tY(),HQ(),xQ();const H=f.useCallback(()=>{v(_=>!_)},[]);vQ(H),wQ({enabled:E}),E9({enabled:E}),CQ({enabled:E}),f.useEffect(()=>{if(D)return;const _=R=>{m2(R)&&R.shiftKey&&R.key==="D"&&(R.preventDefault(),v(z=>!z))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[D]),f.useEffect(()=>{D||c&&setTimeout(()=>d(),5e3)},[d,D,c]),f.useEffect(()=>{if(D||!Xn()||!ar())return;let _=!1;const R=async()=>{const O=await fetch("/health",{method:"GET"}).catch(()=>null);if(!O||!O.ok||_)return;const Q=await O.json().catch(()=>null);if(!Q||_)return;const te=Q.openCodeRunning===!0,W=Q.isOpenCodeReady===!0,K=(typeof Q.opencodeBinaryResolved=="string"?Q.opencodeBinaryResolved.trim():"").length>0,q=typeof Q.lastOpenCodeError=="string"?Q.lastOpenCodeError:"",ee=!te&&(kY.test(q)||!K&&!W);A(ee)};R();const z=window.setInterval(()=>{R()},NY);return()=>{_=!0,window.clearInterval(z)}},[D]);const P=f.useCallback(()=>{A(!1),window.location.reload()},[]);return j?s.jsx(Nn,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(vY,{onCliAvailable:P})})}):D?s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(al,{}),s.jsx(b1,{})]})})})}):N?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(GK,{}),s.jsx(b1,{})]})})})}):s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx(y5,{children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(wK,{}),s.jsx(b1,{})]})})})})}):s.jsx(Nn,{children:s.jsx(O1,{apis:t,children:s.jsx(mY,{children:s.jsx(y5,{children:s.jsx(LD,{children:s.jsx($i,{delayDuration:700,skipDelayDuration:150,children:s.jsxs("div",{className:"h-full text-foreground bg-background",children:[s.jsx(gK,{}),s.jsx(b1,{}),s.jsx(wY,{}),s.jsx(CY,{}),x&&s.jsx(ZK,{onClose:()=>v(!1)})]})})})})})})})}const ny=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=Ds.getState();t&&n.homeDirectory!==t&&n.synchronizeHomeDirectory(t),e&&!ln()&&n.setDirectory(e,{showOverlay:!1})},ry="/auth/session",FY=async()=>{console.log("[Frontend Auth] Checking session status...");const t=await fetch(ry,{method:"GET",credentials:"include",headers:{Accept:"application/json"}});return console.log("[Frontend Auth] Session status response:",t.status,t.statusText),t},DY=async t=>{console.log("[Frontend Auth] Submitting password...");const e=await fetch(ry,{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},oy=t=>{const e=Ce.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},_Y=()=>{const t=Ce.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background text-foreground",children:s.jsx(B2,{width:120,height:120,isAnimated:!0})}),t[0]=e):e=t[0],e},Z6=t=>{const e=Ce.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 u=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]!==u?(m=s.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:u}),e[2]=u,e[3]=m):m=e[3];let h;e[4]!==d||e[5]!==m?(h=s.jsxs("div",{className:"space-y-2",children:[d,m]}),e[4]=d,e[5]=m,e[6]=h):h=e[6];let p;e[7]!==n?(p=s.jsx(ot,{type:"button",onClick:n,className:"w-full max-w-xs",children:"Retry"}),e[7]=n,e[8]=p):p=e[8];let g;return e[9]!==h||e[10]!==p?(g=s.jsx(oy,{children:s.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[h,p]})}),e[9]=h,e[10]=p,e[11]=g):g=e[11],g},BY=({children:t})=>{const e=f.useMemo(()=>ln(),[]),n=e,r=f.useMemo(()=>Xn()&&!e,[e]),[o,a]=f.useState(()=>n?"authenticated":"pending"),[i,l]=f.useState(""),[c,d]=f.useState(!1),[u,m]=f.useState(""),[h,p]=f.useState(void 0),[g,y]=f.useState(!1),b=f.useRef(null),x=f.useRef(n),v=f.useCallback(async()=>{if(n){console.log("[Frontend Auth] VSCode runtime, skipping auth"),a("authenticated");return}const C=document.cookie,k=C.includes("oc_ui_session="),N=C.includes("oc_ui_refresh=");console.log("[Frontend Auth] Cookies check - access:",k,"refresh:",N),console.log("[Frontend Auth] All cookies:",C.split(";").map(S=>S.trim().split("=")[0])),a(S=>S==="authenticated"?S:"pending");try{const S=await FY(),j=await S.text();if(console.log("[Frontend Auth] Raw response:",S.status,j),S.ok){console.log("[Frontend Auth] Session is authenticated"),a("authenticated"),y(!1),m(""),p(void 0);return}if(S.status===401){let A={};try{A=JSON.parse(j)}catch{A={}}console.warn("[Frontend Auth] Session is locked (401)",A),A.debug&&console.warn("[Frontend Auth] Debug info:",A.debug),y(A.tunnelLocked===!0),a("locked"),p(void 0);return}if(S.status===429){let A={};try{A=JSON.parse(j)}catch{A={}}p(A.retryAfter),y(!1),a("rate-limited");return}console.error("[Frontend Auth] Unexpected response status:",S.status),a("error"),y(!1)}catch(S){console.warn("Failed to check session status:",S),a("error"),y(!1)}},[n]);f.useEffect(()=>{n||v()},[v,n]),f.useEffect(()=>{!n&&o==="locked"&&(x.current=!1)},[n,o]),f.useEffect(()=>{o==="locked"&&b.current&&(b.current.focus(),b.current.select())},[o]),f.useEffect(()=>{n||o==="authenticated"&&!x.current&&(x.current=!0,(async()=>(await i8(),await l8(),await ny()))())},[n,o]);const w=async C=>{if(C.preventDefault(),!g&&!(!i||c)){d(!0),m("");try{const k=await DY(i);if(k.ok){console.log("[Frontend Auth] Login successful");const N=document.cookie,S=N.includes("oc_ui_session="),j=N.includes("oc_ui_refresh=");console.log("[Frontend Auth] After login - access:",S,"refresh:",j),console.log("[Frontend Auth] All cookies after login:",N.split(";").map(A=>A.trim().split("=")[0]).filter(Boolean)),l(""),y(!1),a("authenticated");return}if(k.status===401){console.warn("[Frontend Auth] Login failed: Invalid password"),m("Incorrect password. Try again."),y(!1),a("locked");return}if(k.status===429){console.warn("[Frontend Auth] Login failed: Rate limited");const N=await k.json().catch(()=>({}));p(N.retryAfter),y(!1),a("rate-limited");return}console.error("[Frontend Auth] Login failed: Unexpected response",k.status),m("Unexpected response from server."),y(!1),a("error")}catch(k){console.warn("Failed to submit UI password:",k),m("Network error. Check connection and retry."),y(!1),a("error")}finally{d(!1)}}};return o==="pending"?s.jsx(_Y,{}):o==="error"?s.jsx(Z6,{onRetry:()=>{v()},errorType:"network"}):o==="rate-limited"?s.jsx(Z6,{onRetry:()=>{v()},errorType:"rate-limit",retryAfter:h}):o==="locked"?s.jsx(oy,{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:g?"Tunnel access required":"Unlock OpenChamber"}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:g?"Open this tunnel using the one-time connect link from the desktop app.":"This session is password-protected."})]}),!g&&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(lv,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),s.jsx(ts,{id:"openchamber-ui-password",ref:b,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:C=>{l(C.target.value),u&&m("")},className:"pl-10","aria-invalid":!!u||void 0,"aria-describedby":u?"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(os,{className:"h-4 w-4 animate-spin"}):s.jsx(cv,{className:"h-4 w-4"})})]}),u&&s.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:u})]}),r&&s.jsxs("div",{className:"w-full",children:[s.jsx(IN,{}),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})},eu=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 EY{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(`
6933
6933
  `)}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=eu(e.colors.surface.muted),o=eu(e.colors.surface.subtle),a=eu(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,u)=>{n.push(` --chart-${u+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 {
6934
6934
  ${n}
6935
6935
  }