UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

679 lines • 431 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./session-snapshot-database-BBKeXATO.js","./plugin-contracts-runtime-ByiEPbv_.js","./config-runtime-BecGLziM.js","./markdown-runtime-ORQpioyT.js","./sidebar-update-runtime-DQZboSgD.js","./control-ui-core-DI-Q_yCI.css","./control-ui-boot-shared-styles-DUf4zEvn.css","./control-ui-boot-shared-DIWJGbGi.css","./sidebar-update-runtime-Bpn2ByHA.css","./board-view-DvSYdNVj.js","./chat-transcript-styles-BN-TorbW.js","./control-ui-boot-chat-styles-BcslGtWC.js","./control-ui-disabled-B8wp3jVt.js","./near-viewport-observer-WgGck829.js","./widget-sandbox-host-COBvR0Ux.js","./mcp-app-confirm-BOrRV_eo.js","./sandbox-host-Dm6XHU23.js","./chat-transcript-styles-B0IJwY9P.css","./control-ui-boot-chat-styles-SRk09zDG.css","./control-ui-boot-chat-C2DT0d4M.css","./board-view-CCkz6swN.css","./chat-sidebar-region.runtime-B67R083E.js","./control-ui-boot-new-styles-cChqenO3.js","./panel-tab-strip-CniNZmas.js","./panel-empty-state-Cvj4wChf.js","./control-ui-boot-new-styles-BS7lzENV.css","./control-ui-boot-new-D-SpiTTi.css","./control-ui-boot-chat-DhbON6pC.css","./chat-sidebar-region-BT887V4g.css","./chat-detail-panel-DYod9DCg.js","./terminal-panel-registration-DRAlY3On.js","./scrollbar-styles-z704pTjt.js","./panel-icon-button-BbsY5x_R.js","./dock-destination-controls-BmjaupAr.js","./theme-color-DAo4KRoc.js","./catalog-terminal-start-DmNpGDDP.js","./link-reader-panel-DAzjGGyQ.js","./link-reader-response-2ZxZ1BKy.js","./browser-panel-s0odPIu7.js","./gateway-websocket-url-BW0hi5Wr.js","./desktop-panel-CuBSlrvl.js","./reasoned-disabled-control-BE3CsN4F.js","./desktop-focus-window-DUCI-_oT.js","./portals-page-BKvqjvya.js","./portals-page-DZUgz7YJ.css","./chat-session-rail-J1mIG8Ef.js","./chat-session-rail-BmiGPeTv.css","./chat-processes-panel-CKKlleIX.js","./chat-session-panels-DQzw7cXS.js","./chat-session-panels-BDbvNV8H.css","./chat-processes-panel-wfftEucI.css","./chat-subagents-panel-krANCQ7F.js","./chat-subagents-panel-BX3B7hCl.css","./session-discussion-panel-Da6iwG46.js","./chat-pane-placement.runtime-CoEpFcJk.js","./cloud-worker-stop.runtime-B791S2pQ.js","./session-organizer-operations.runtime-SirMtAXt.js","./session-workspace-recovery.runtime-C0JCx4Ml.js","./input-dialog-CnAqzRxY.js"])))=>i.map(i=>d[i]);
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{$l as t,$n as n,Ac as r,Ct as i,Dl as a,Do as o,El as s,En as c,Eo as l,Et as u,Fc as d,Fl as f,Gi as p,Gl as m,Go as h,Gs as g,Hl as _,Hn as v,Ho as y,Hr as b,I as x,Ic as S,Il as C,Io as w,Jc as T,Jl as E,Jo as D,Jr as O,Js as k,Jt as ee,Kl as A,Lc as j,Lr as te,Lu as ne,Mc as M,Ml as N,Mo as P,Nc as re,Nl as ie,Nu as ae,Ou as oe,Pc as se,Pl as ce,Pu as F,Qc as le,Ql as ue,Qn as de,Rl as fe,Rn as pe,Rr as me,St as he,Tl as ge,Tu as _e,Ui as ve,Ul as ye,Uo as be,Ur as xe,Vn as Se,Vr as Ce,W as we,Wc as Te,Wi as Ee,Wl as I,Wn as De,Xc as Oe,Xl as ke,Xn as Ae,Xt as je,Yc as Me,Yl as Ne,Yn as Pe,Yr as Fe,Ys as Ie,Yt as Le,Zn as Re,Zo as ze,_u as Be,a as Ve,ac as He,br as Ue,bu as We,c as Ge,cl as Ke,cr as qe,dt as Je,du as Ye,ea as Xe,er as Ze,eu as Qe,g as $e,gr as et,h as tt,i as nt,il as L,jc as rt,jl as it,jo as at,ju as ot,k as st,kl as R,ko as ct,ku as lt,l as ut,ll as dt,lt as ft,m as pt,mc as mt,n as ht,nc as gt,nl as _t,on as vt,p as yt,pc as bt,pn as xt,qc as St,qn as Ct,qo as wt,qt as Tt,r as Et,rl as Dt,rr as Ot,s as kt,sn as At,sr as jt,tr as Mt,tu as Nt,u as Pt,un as Ft,uu as It,vu as Lt,wl as z,wn as Rt,xu as zt,yu as B,zl as Bt,zu as V}from"./control-ui-core-CBJ5efDh.js";import{A as Vt,J as Ht,L as Ut,N as Wt,R as Gt,Y as Kt,at as qt,c as Jt,j as Yt,ot as Xt,q as Zt,s as Qt}from"./control-ui-boot-shared-gZIpWrfw.js";import{$n as $t,$r as en,A as tn,Aa as nn,Ai as rn,At as an,Bi as on,Cr as sn,D as cn,Dt as ln,E as un,Ei as dn,Fr as fn,G as pn,J as mn,Jt as hn,K as gn,Ki as _n,La as vn,M as yn,Mi as bn,O as xn,Or as Sn,Ot as Cn,Sr as wn,Ti as Tn,Tr as En,Ui as Dn,Vi as On,Xa as kn,Xi as An,Zi as jn,Zt as Mn,_n as Nn,ai as Pn,at as Fn,bn as In,br as Ln,ca as Rn,ci as zn,ct as Bn,di as Vn,dr as Hn,en as Un,er as Wn,fi as Gn,gn as Kn,go as qn,hn as Jn,ii as Yn,ji as Xn,jr as Zn,jt as Qn,k as $n,ki as er,li as tr,lt as nr,mr as rr,n as ir,ni as ar,oi as or,or as sr,p as cr,pr as lr,qa as ur,qi as dr,qr as fr,qt as pr,r as mr,sa as H,si as hr,sr as gr,st as _r,ui as vr,ur as yr,vo as br,vr as xr,w as Sr,wi as Cr,wn as wr,wr as Tr,yr as Er}from"./control-ui-core-DtLivg_r.js";import{C as Dr,G as U,J as W,T as Or,W as kr,Z as Ar,at as G,c as jr,l as Mr,n as Nr,q as Pr,rt as Fr,t as Ir}from"./lit-runtime-IOnANfcZ.js";import{$t as Lr,Et as Rr,Gt as zr,Lt as Br,Mt as Vr,Nt as Hr,Sr as Ur,Tt as Wr,Ut as Gr,Wt as Kr,cr as qr,dr as Jr,en as Yr,fr as Xr,gr as Zr,lr as Qr,mr as $r,on as ei,sr as ti,ur as ni,vr as ri,xr as ii,yr as ai}from"./control-ui-boot-shared-CkXlyZBY.js";import{D as oi,E as si,d as ci,u as li}from"./control-ui-boot-chat-Ye5j4vAg.js";import{c as ui,d as K,l as di,u as fi}from"./gateway-runtime-C77LeWZN.js";import{$i as pi,$n as mi,A as hi,An as gi,B as _i,Bi as vi,Br as yi,D as bi,Dt as xi,E as Si,Fa as Ci,G as wi,H as Ti,I as Ei,Ii as Di,Ir as Oi,Jr as ki,K as Ai,Kn as ji,L as Mi,Ln as Ni,Lr as Pi,Ma as Fi,Mr as Ii,N as Li,Ni as Ri,Nn as zi,O as Bi,Ot as Vi,Pa as Hi,Pn as Ui,Rn as Wi,Rr as Gi,St as Ki,Tt as qi,U as Ji,Ur as Yi,V as Xi,W as Zi,Wi as Qi,Yn as $i,Yr as ea,Zn as ta,Zr as na,bt as ra,ct as ia,da as aa,di as oa,ea as sa,ei as ca,fi as la,fr as ua,ga as da,ha as fa,ii as pa,ir as ma,j as ha,k as ga,kn as _a,la as va,lt as ya,na as ba,oa as xa,or as Sa,pa as Ca,pr as wa,q as Ta,qn as Ea,sa as Da,si as Oa,st as ka,ta as Aa,ut as ja,wt as Ma,xt as Na,zi as Pa,zn as Fa,zr as Ia}from"./control-ui-boot-shared-UG5ko-VG.js";import{Ei as La,Ft as Ra,Ga as za,It as Ba,Ki as Va,Mo as Ha,Mt as Ua,N as Wa,Ni as Ga,Oi as Ka,Po as qa,Sa as Ja,Sr as Ya,Ta as Xa,Ui as Za,Ur as Qa,Wa as $a,Wr as eo,Xt as to,Ya as no,Yi as ro,Yt as io,Zr as q,_a as ao,ao as oo,bi as so,ci as co,da as lo,ea as uo,io as fo,jo as po,jt as mo,ma as ho,mt as go,pa as _o,ro as vo,uo as yo,wa as bo,xa as xo,xr as So,ya as J,yi as Co}from"./ui-CmSP4d14.js";import{B as wo,V as To}from"./control-ui-boot-shared-VLPz5vN2.js";import{m as Eo,y as Do}from"./control-ui-boot-shared-SQHdJTzb.js";import{Aa as Oo,An as ko,Ca as Ao,Da as jo,Ea as Mo,F as No,Fi as Po,Gn as Fo,I as Io,Jn as Lo,Kn as Ro,Li as zo,M as Bo,Mt as Vo,N as Ho,Nn as Uo,Nt as Wo,Oa as Go,Or as Ko,P as qo,S as Jo,Sa as Yo,Ta as Xo,Vr as Zo,X as Qo,Yn as $o,_t as es,at as ts,cn as ns,gi as rs,gr as is,gt as as,hr as os,ht as ss,it as cs,jn as ls,ka as us,kr as ds,kt as fs,na as ps,on as ms,qn as hs,ta as gs,wa as _s,x as vs,zr as ys}from"./control-ui-boot-shared-XreXSF7h.js";import{$a as bs,$c as xs,$d as Ss,$f as Cs,$i as ws,$n as Ts,$r as Es,$s as Ds,$t as Os,$u as ks,Aa as As,Ad as js,Af as Ms,Ai as Ns,Ao as Ps,Au as Fs,Ba as Is,Bc as Ls,Bd as Rs,Bf as zs,Bi as Bs,Bn as Vs,Bo as Hs,Bp as Us,Br as Ws,Bu as Gs,Ca as Ks,Cd as qs,Cf as Js,Ci as Ys,Cp as Xs,Cr as Zs,Cu as Qs,Da as $s,Dd as ec,Df as tc,Di as nc,Dl as rc,Dn as ic,Dp as ac,Dr as oc,Du as sc,E as cc,Ea as lc,Ed as uc,Ef as dc,Ei as fc,Ep as pc,Er as mc,Eu as hc,Fa as gc,Fd as _c,Ff as vc,Fi as yc,Fo as bc,Fr as xc,Ga as Sc,Gd as Cc,Gi as wc,Gl as Tc,Go as Ec,Gr as Dc,Gt as Oc,Ha as kc,Hd as Ac,Hf as jc,Hi as Mc,Hl as Nc,Ho as Pc,Hr as Fc,Hu as Ic,I as Lc,Ia as Rc,Id as zc,If as Bc,Ii as Vc,In as Hc,Io as Uc,Iu as Wc,Ja as Gc,Jd as Kc,Jf as qc,Ji as Jc,Jn as Yc,Jp as Xc,Js as Zc,Jt as Qc,Ju as $c,Ka as el,Kf as tl,Ki as nl,Kl as rl,Kp as il,Kr as al,Ks as ol,Kt as sl,Ku as cl,L as ll,La as ul,Lc as dl,Ld as fl,Li as pl,Ln as ml,Lp as hl,Lr as gl,Ls as _l,Lu as vl,Ma as yl,Md as bl,Mf as xl,Mi as Sl,Mn as Cl,Mo as wl,Mr as Tl,Mu as El,Na as Dl,Nd as Ol,Nf as kl,Ni as Al,Nn as jl,Ns as Ml,Nu as Nl,O as Pl,Oa as Fl,Od as Il,Of as Ll,Oi as Rl,Op as zl,Or as Bl,Ou as Vl,Pa as Hl,Pd as Ul,Pf as Wl,Pi as Gl,Po as Kl,Pp as ql,Pr as Jl,Qa as Yl,Qc as Xl,Qd as Zl,Qi as Ql,Qn as $l,Qr as eu,Qt as tu,Qu as nu,R as ru,Ra as iu,Rc as au,Rd as ou,Rf as su,Ri as cu,Rn as lu,Ro as uu,Rp as du,Ru as fu,Sa as pu,Sd as mu,Sf as hu,Si as gu,Sn as _u,Sp as vu,Sr as yu,St as bu,T as xu,Ta as Su,Td as Cu,Tf as wu,Ti as Y,Tp as Tu,Tr as Eu,Tu as Du,Ua as Ou,Ui as ku,Ul as Au,Uo as ju,Up as Mu,Ur as Nu,Uu as Pu,Va as Fu,Vd as Iu,Vf as Lu,Vi as Ru,Vl as zu,Vo as Bu,Vu,Wd as Hu,Wi as Uu,Wo as Wu,Wp as Gu,Wr as Ku,Ws as qu,Wt as Ju,Wu as Yu,Xa as Xu,Xd as Zu,Xf as Qu,Xn as $u,Xr as ed,Xs as td,Xt as nd,Xu as rd,Ya as id,Yd as ad,Yf as od,Yi as sd,Yl as cd,Yn as ld,Yp as ud,Yt as dd,Yu as fd,Za as pd,Zc as md,Zd as hd,Zf as gd,Zn as _d,Zr as vd,Zt as yd,Zu as bd,_a as xd,_d as Sd,_f as Cd,_i as wd,_l as Td,_o as Ed,_r as Dd,aa as Od,ac as kd,ad as Ad,ao as jd,ap as Md,ar as Nd,au as Pd,ba as Fd,bd as Id,bf as Ld,bi as Rd,bp as zd,br as Bd,ca as Vd,cd as Hd,cf as Ud,ci as Wd,cl as Gd,cn as Kd,co as qd,cp as Jd,cr as Yd,dc as Xd,dd as Zd,df as Qd,di as $d,do as ef,dp as tf,dr as nf,ea as rf,ed as af,ef as of,ei as sf,em as cf,eo as lf,ep as uf,er as df,fc as ff,fd as pf,ff as mf,fi as hf,fn as gf,fo as _f,fr as vf,ga as yf,gc as bf,gd as xf,gf as Sf,gi as Cf,go as wf,gp as Tf,gr as Ef,gu as Df,ha as Of,hf as kf,hi as Af,hp as jf,hr as Mf,hu as Nf,ia as Pf,ic as Ff,id as If,if as Lf,ii as Rf,il as zf,in as Bf,io as Vf,ir as Hf,ja as Uf,jd as Wf,jf as Gf,ji as Kf,jn as qf,jp as Jf,jr as Yf,ju as Xf,kd as Zf,kf as Qf,ki as $f,kp as ep,ku as tp,la as np,lc as rp,ld as ip,lf as ap,li as op,ln as sp,lo as cp,lr as lp,lu as up,ma as dp,md as fp,mi as pp,ml as mp,mn as hp,mr as gp,na as _p,nc as vp,nd as yp,nf as bp,ni as xp,nl as Sp,nm as Cp,nn as wp,no as Tp,np as Ep,nr as Dp,oa as Op,od as X,oi as kp,ol as Ap,oo as jp,or as Mp,ou as Np,pc as Pp,pd as Fp,pi as Ip,pn as Lp,pp as Rp,pr as zp,qa as Bp,qd as Vp,qf as Hp,qi as Up,qn as Wp,qp as Gp,qr as Kp,qt as qp,qu as Jp,ra as Yp,rc as Xp,rd as Zp,rf as Qp,ri as $p,ro as em,rr as tm,sa as nm,sd as rm,si as im,sl as am,so as om,sp as sm,sr as cm,su as lm,tc as um,td as dm,tf as fm,ti as pm,tm as mm,tn as hm,to as gm,tp as _m,tr as vm,uc as ym,ud as bm,uf as xm,ui as Sm,un as Cm,uo as wm,up as Tm,ur as Em,v as Dm,va as Om,vd as km,vf as Am,vi as jm,vo as Mm,vp as Nm,vr as Pm,w as Fm,wa as Im,wd as Lm,wf as Rm,wi as zm,wl as Bm,wn as Vm,wp as Hm,wr as Um,wu as Wm,xa as Gm,xd as Km,xf as qm,xi as Jm,xn as Ym,xp as Xm,xr as Zm,xt as Qm,y as $m,ya as eh,yd as th,yf as nh,yi as rh,yp as ih,yr as ah,z as oh,za as sh,zc as ch,zd as lh,zf as uh,zi as dh,zn as fh,zo as ph,zp as mh,zu as hh}from"./control-ui-boot-shared-dOnP4mAA.js";import{G as gh,K as _h,W as vh,it as yh}from"./control-ui-boot-shared-Q8KG_noF.js";import"./control-ui-boot-shared-styles-BXPMRytW.js";import{D as bh,J as xh,O as Sh,_ as Ch,b as wh,g as Th,n as Eh,t as Dh,v as Oh,w as kh,x as Ah,y as jh}from"./control-ui-boot-chat-XPUNenUd.js";import{A as Mh,D as Nh,E as Ph,I as Fh,L as Ih,O as Lh,P as Rh,R as zh,T as Bh,X as Vh,Z as Hh,c as Uh,d as Wh,f as Gh,j as Kh,k as qh,l as Jh,s as Yh,u as Xh,v as Zh,w as Qh}from"./control-ui-boot-chat-CGYcTLro.js";import{$ as $h,$t as eg,A as tg,An as ng,At as rg,B as ig,Bn as ag,Bt as og,C as sg,Ct as cg,Dt as lg,E as ug,Et as dg,F as fg,Fn as pg,Ft as mg,G as hg,Gn as gg,Gt as _g,H as vg,Hn as yg,Ht as bg,In as xg,It as Sg,J as Cg,Jn as wg,Jt as Tg,K as Eg,Kn as Dg,Kt as Og,L as kg,Ln as Ag,Lt as jg,M as Mg,Mn as Ng,Mt as Pg,N as Fg,Nn as Ig,Nt as Lg,On as Rg,Ot as zg,P as Bg,Pn as Vg,Pt as Hg,Q as Ug,R as Wg,Rn as Gg,Rt as Kg,S as qg,St as Jg,T as Yg,Tt as Xg,U as Zg,Un as Qg,Ut as $g,V as e_,Vn as t_,Vt as n_,W as r_,Wn as i_,X as a_,Xn as o_,Xt as s_,Y as c_,Yn as l_,Yt as u_,Z as d_,Zn as f_,Zt as p_,_ as m_,_t as h_,an as g_,ar as __,at as v_,br as y_,bt as b_,c as x_,cn as S_,cr as C_,ct as w_,d as T_,dn as E_,dt as D_,en as O_,et as k_,f as A_,fn as j_,ft as M_,g as N_,gn as P_,gt as F_,h as I_,hn as L_,ht as R_,in as z_,ir as B_,it as V_,j as H_,jn as U_,jt as W_,k as G_,kn as K_,kt as q_,l as J_,ln as Y_,lt as X_,m as Z_,mn as Q_,mt as $_,nn as ev,nt as tv,on as nv,or as rv,ot as iv,p as av,pn as ov,pt as sv,q as cv,qn as lv,qt as uv,rn as dv,rr as fv,rt as pv,s as mv,sn as hv,sr as gv,st as _v,tn as vv,tt as yv,u as bv,un as xv,ut as Sv,v as Cv,vn as wv,vt as Tv,w as Ev,wt as Dv,x as Ov,xr as kv,xt as Av,yt as jv,z as Mv,zn as Nv,zt as Pv}from"./control-ui-boot-chat-B-b-JQel.js";import{$ as Fv,B as Iv,C as Lv,F as Rv,G as zv,H as Bv,I as Vv,K as Hv,L as Uv,Lt as Wv,N as Gv,P as Kv,R as qv,S as Jv,St as Yv,U as Xv,V as Zv,W as Qv,X as $v,dt as ey,ft as ty,jt as ny,mt as ry,tt as iy,ut as ay,x as oy,yt as sy,z as cy}from"./control-ui-boot-chat-CmENwCKi.js";import{_ as ly,g as uy,n as dy,o as fy,r as py}from"./control-ui-boot-chat-k_u3nGjS.js";import{bt as my,xt as hy}from"./control-ui-boot-new-CkyIHJ_L.js";function gy(e){let t=by.get(e);return t||(t={panes:new Map,listeners:new Set},by.set(e,t)),t}function _y(e,t,n){let r=gy(e);if(JSON.stringify(r.panes.get(t))!==JSON.stringify(n)){n?r.panes.set(t,n):r.panes.delete(t);for(let e of r.listeners)e()}}function vy(e,t){return uo(gy(e).listeners,t)}function yy(e,n,r,i){if(!br(n)||!r)return{page:n};let a={hello:e.gateway.snapshot.hello,agentsList:e.agents.state.agentsList,assistantAgentId:i},o=I(a,r),s=e.sessions.state.result?.sessions.find(e=>t(a,r,e.key,e.agentId)),c=a.agentsList?.agents.find(e=>e.id===o.agentId),l=xh({session:s,agentWorkspace:c?.workspace}),u=[...gy(e).panes.values()].find(e=>e.sessionKey===o.sessionKey&&e.agentId===o.agentId);return{page:n,title:s?.label||s?.displayName||o.sessionKey,...o,sessionId:s?.sessionId,workspace:l.root??void 0,...u}}var by;function xy(){return(xy=e((()=>{qn(),R(),by=new WeakMap})))()}function Sy(e){let t=J(e),n=typeof t?.stopReason==`string`?t.stopReason.toLowerCase():``;return mf(e)!==null||J(t?.openclawAbort)?.aborted===!0||[`aborted`,`cancelled`,`canceled`,`timeout`,`timed_out`].includes(n)}function Cy(e){if(of(e))return`commentary`;if(vh(e,{phase:`final_answer`}))return`final_answer`;let t=_h(e);if(t)return t;let n=J(e),r=J(n?.__openclaw);return r?.mirrorOrigin===`codex-app-server`&&r.runTerminal===!0&&n?.stopReason===`stop`&&!Sy(e)?`final_answer`:void 0}function wy(){return(wy=e((()=>{gh(),Ss(),ap()})))()}function Ty(e){return e.name===`sessions_yield`&&Object.hasOwn(e,`args`)&&e.completed===!0&&e.isError!==!0&&(J(e.details)?.status===`yielded`||Ka(e.outputText??``)?.status===`yielded`)}function Ey(e){return mi(e).some(e=>e.name===`sessions_yield`)}function Dy(e){return e.kind===`reading-indicator`&&!e.waitingOn}function Oy(e,t){let n=[],r=null,i=!1,a=new Set,o,s=!1,c=new Set,l=[];for(let u=e.length-1;u>=0;u--){let d=e[u],f=d.kind===`message`?J(d.message):null,p=(f?mi(f):[]).filter(e=>e.name===`sessions_yield`),m=p.filter(Ty),h=m.at(-1),g=[];if(h){let e=f?vc(f):null,t=i||[...a].some(e=>h.runId!==void 0&&e!==h.runId)||s&&o!==void 0&&!o.item.runId;if(g.push({kind:`notice`,key:`yield:${d.key}:${h.id}`,handoffBoundary:!0,text:``,timestamp:e??0}),t){let e=h.runId??Lf(f);s&&e&&e!==o?.item.runId&&!l.includes(e)&&l.unshift(e)}else r={timestamp:e!==null&&e>0?e:null,...h.runId?{runId:h.runId}:{}};i=!0}let _=[d];if(f&&p.length>0&&!t&&Gi(f))_=[];else if(f&&p.length>0&&Array.isArray(f.content)){let e=new Set(p.map(e=>e.callId)),n=new Set(m.map(e=>e.callId)),r=f.content.filter(r=>{let i=J(r);if(!i||!Yt(i.type)&&!Wt(i.type))return!0;let a=su(i,f);return!t||Yt(i.type)&&(a?e.has(a):i.name===`sessions_yield`)?!1:a?!n.has(a):!(m.length>0&&i.name===`sessions_yield`)});_=r.length?[{...d,kind:`message`,message:{...f,content:r,activity:wa(f).filter(n=>t&&!e.has(n.toolCallId??n.itemId))}}]:[]}let v=[..._,...g];if(n.push(v),Dy(d))o={slot:v,item:d},s=!0;else if(s&&qc(d)){let e=f?vc(f):null;o&&e!==null&&e>0&&(o.askedAt=e),s=!1}let y=f?Lf(f):d.kind===`stream`||d.kind===`reading-indicator`?d.runId:void 0;y&&(a.add(y),s&&c.add(y)),i||=qc(d)||d.kind===`stream`||f!==null&&yi(Yi(f))===`assistant`&&tc(f)}let u=o;return u?.askedAt!==void 0&&l.length>0&&[...c].every(e=>e===u.item.runId||l.includes(e))&&(u.slot[u.slot.indexOf(u.item)]={...u.item,startedAt:Math.min(u.item.startedAt,u.askedAt),request:{askedAt:u.askedAt,runIds:l}}),{items:n.toReversed().flat(),pending:r}}function ky(e,t=!0,n){let r=Oy(e,t).items,i=n?.find(Dy);return i?r.map(e=>Dy(e)&&e.key===i.key?i:e):r}function Ay(e){if(jy.has(e))return jy.get(e)??null;let{pending:t}=Oy(um(qm(Qt([...e]))),!0);return jy.set(e,t),t}var jy;function My(){return(My=e((()=>{La(),Vt(),Jt(),Pi(),ua(),ma(),Ll(),Ss(),vp(),Qu(),jy=new WeakMap})))()}function Ny(e,t){return t!==`assistant`&&t!==`user`?null:e?.isImported?e.externalSource?`${t}:import:${e.externalSource}`:e.sequence===null?null:`${t}:import-seq:${e.sequence}`:e?.id?`${t}:${e.id}`:null}function Py(e,t){return e.replace(RegExp(`^${yh(t)}(?::|:|-|—)?[ \\t]+`),``)}function Fy(e,t){if(e.content.length===0)return null;let n=[];for(let t of e.content){if(t.type!==`text`||typeof t.text!=`string`)return null;n.push(t.text)}return{role:t,senderLabel:(e.senderLabel??``).trim(),senderKey:Hi(e.sender),senderSession:e.senderSession,clientSourcesKey:Gt(e.sourceClients??[]),text:n.join(`
`)}}function Iy(e,t){if(e?.role!==`assistant`||t?.role!==`assistant`||!e.text.trim()||!t.text.trim()||!!e.senderLabel==!!t.senderLabel)return!1;let n=e.senderLabel?e:t,r=e.senderLabel?t:e;return n.text===r.text||Py(n.text,n.senderLabel)===r.text}function Ly(e){if(!e||!e.role||e.role===`tool`)return null;let t=e.text.trim().replace(/\s+/g,` `);if(!t)return null;let n=[`user`,`assistant`].includes(e.role)?e.senderLabel:``;return JSON.stringify([e.role,n,e.senderKey??``,e.senderSession,e.clientSourcesKey,t])}function Ry(e){let t=[],n=null,r=null,i=!1;for(let a of e){if(a.kind!==`message`){t.push(a),n=null,r=null,i=!1;continue}let e=Ia(a.message),o={kind:`message`,item:a,normalized:e},s=yi(e.role).toLowerCase(),c=Gf(a.message),l=c?null:Fy(e,s),u=Bc(a.message),d=c?null:Ny(u,s),f=d===null&&u?.isImported===!0&&u.externalSource===null&&u.sequence===null,p=t[t.length-1];if(d&&r===d&&p?.kind===`message`&&Iy(n,l)){l?.senderLabel||(t[t.length-1]=o,n=l);continue}if(p?.kind===`message`&&!f&&!i&&d===r&&l?.role===n?.role){let e=Ly(l);if(e&&e===Ly(n)){p.item.duplicateCount=(p.item.duplicateCount??1)+1;continue}}t.push(o),n=l,r=d,i=f}return t}function zy(){return(zy=e((()=>{Ut(),Pi(),Fi(),Ll()})))()}function By(e,t){return Cy(e)??(t===`none`?`activity`:`reply`)}function Vy(e,t,n){if(!e.id)return JSON.stringify([`sender-label`,e.username??e.name??``]);let r=Ci({type:`profile`,id:e.id});return t.has(r)||r===n?r:JSON.stringify([`sender`,e.id])}function Hy(e,t,{people:n,localPerson:r}){let i=new Set(n),a=[],o=new Map,s=new Map,c={};for(let e of t)if(qc(e)&&(e.kind!==`group`||e.role!==`user`)&&(c={}),e.kind===`stream`&&s.set(e.key,c),e.kind===`group`){for(let t of e.messages)s.set(t.key,c);if(e.role===`user`){for(let t of e.messages){let e=jc(t.message);e&&o.set(e,o.has(e)?null:t)}e.sender?.identity?i.add(Ci(e.sender.identity)):e.sender?a.push(e.sender):!e.senderSession&&r&&i.add(r);let t=e.messages.at(-1);c={sender:e.sender,message:e.sender?t:void 0,turnSource:t}}else e.role===`assistant`&&od(e)&&(c={})}for(let e of a)i.add(Vy(e,i,r));let l=i.size>=2,u=[],d=c;for(let t=e.length-1;t>=0;--t){let n=e[t];d=(n.kind===`group`?n.messages.map(e=>s.get(e.key)).find(Boolean):n.kind===`stream`?s.get(n.key):void 0)??d,u[t]=d}for(let[t,n]of e.entries()){let{sender:e,message:r,turnSource:i}=u[t];if(n.kind===`group`){if(l&&(n.replyShared=!0),n.role!==`assistant`||od(n))continue;let e=n.runId&&n.messages.some(e=>e.replyTarget?.kind===`current`)?o.get(n.runId):void 0;i&&(n.replyTurnSource=i),e&&(n.replyCurrentSource=e)}else if(n.kind!==`stream`)continue;l&&(n.kind===`stream`||e)&&(n.replyToSender=e,n.replyToMessage=r)}return e}function Uy(e,t={}){let n=Gy(e,t.items&&Wy(e,t.items));return Hy(n,t.items?Gy(t.items):n,t)}function Wy(e,t){let n=new Set(e.map(e=>e.key)),r=new Set,i=!1;for(let e of t)n.has(e.key)?i&&=(r.add(e.key),!1):i||=Hp(e);return r}function Gy(e,t){let n=[],r=null,i=null,a=null;for(let o of Ry(e)){if(o.kind!==`message`){r&&=(n.push(r),null),n.push(o);continue}let{item:e,normalized:s}=o,c=yi(s.role),l=Ma(e.message,s),u={message:e.message,key:e.key,duplicateCount:e.duplicateCount,...s.replyTarget?{replyTarget:s.replyTarget}:{},hasVisibleContent:l===`non-text`||!!Vi(e.message,s).trim()},d=c===`user`||c===`assistant`?s.senderLabel??null:null,f=c===`user`?s.sender:void 0,p=s.timestamp||Date.now(),m=c===`assistant`||c===`tool`?Lf(e.message):void 0,h=c===`user`?Am(e.message):null,g=c===`user`?h??jc(e.message):null,_=c===`assistant`?JSON.stringify(s.replyTarget??null):null,v=c===`user`||c===`assistant`,y=e.startsTurn===!0||t?.has(e.key)===!0||J(J(e.message)?.__openclaw)?.turnBoundary===!0,b=c===`assistant`&&r?.role===`assistant`&&By(r.messages[0]?.message,r.visibleContent)!==By(e.message,l);!r||y||Cs(e.message)||Cs(r.messages[0]?.message)||gd(e.message)&&!s.senderSession?.sessionKey||r.role!==c||r.runId!==m||gd(r.messages[0]?.message)!==gd(e.message)||i!==g||c===`assistant`&&a!==_||b||Gt(r.sourceClients??[])!==Gt(s.sourceClients??[])||v&&(!f?.identity&&r.senderLabel!==d||r.senderSession?.sessionKey!==s.senderSession?.sessionKey||r.senderSession?.label!==s.senderSession?.label||r.senderSession?.agentId!==s.senderSession?.agentId||Hi(r.sender)!==Hi(f))?(r&&n.push(r),i=g,a=_,r={kind:`group`,key:`group:${c}:${e.key}`,role:c,senderLabel:d,...s.senderSession?{senderSession:s.senderSession}:{},...f?{sender:f}:{},...s.sourceClients?{sourceClients:s.sourceClients}:{},messages:[u],visibleContent:l,timestamp:p,isStreaming:!1,...m?{runId:m}:{}}):((l===`non-text`||r.visibleContent===`none`)&&(r.visibleContent=l),r.messages.push(u))}return r&&n.push(r),n}function Ky(e){let t=[],n=[],r=()=>{let[e]=n;if(e){let{runId:r,boundaryId:i}=e;t.push({kind:`stream-run`,key:`stream-run:${e.key}`,parts:n,replyToSender:n.find(e=>e.kind===`stream`)?.replyToSender,replyToMessage:n.find(e=>e.kind===`stream`)?.replyToMessage,...r?{runId:r}:{},...i?{boundaryId:i}:{}}),n=[]}};for(let i of e){if(i.kind===`stream`||i.kind===`reading-indicator`){let e=n[0];e&&(e.runId!==i.runId||e.boundaryId!==i.boundaryId)&&r(),n.push(i);continue}r(),t.push(i)}return r(),t}function qy(e){return e.kind===`group`&&(e.role===`assistant`||e.role===`tool`)&&!tl(e)}function Jy(e){if(e.kind!==`group`||e.isStreaming||Zy(e,!1))return!1;let t=e.role.toLowerCase();return t===`tool`||t===`assistant`&&!tl(e)&&By(e.messages[0]?.message,e.visibleContent)!==`final_answer`}function Yy(e){return e.messages.some(({message:e})=>mi(e).some(Sa))}function Xy(e){return e.messages.some(({message:e})=>Sy(e)||J(e)?.stopReason===`error`)}function Zy(e,t=!0){return e.visibleContent===`non-text`||t&&e.visibleContent===`text`}function Qy(e){return e.role.toLowerCase()===`assistant`&&!tl(e)&&Zy(e)}function $y(e){return e.kind===`group`&&!e.isStreaming&&Qy(e)&&By(e.messages[0]?.message,e.visibleContent)!==`commentary`}function eb(e){let t=e[0];return!t||t.kind===`stream-run`?[]:t.kind===`group`?t.role.toLowerCase()===`user`?t.messages.map(({message:e})=>e):[]:t.kind===`message`&&qc(t)?[t.message]:[]}function tb(e,t){let[n,r,i,a,...o]=po(t.sessionKey).split(`:`);if(!(n===`agent`&&r&&i===`dashboard`&&a&&o.length===0)||t.searchActive)return e;let s=[],c=[];for(let t of e)t.kind!==`stream-run`&&qc(t)&&c.length>0&&(s.push(c),c=[]),c.push(t);c.length>0&&s.push(c);let l=t.runWorking?eb(s.at(-1)??[]).map(Am).findLast(e=>e!==null):void 0,u=l?s.findIndex(e=>eb(e).some(e=>jc(e)===l)):-1,d=t.runWorking?u>=0?u:s.length-1:-1,f=[];for(let[e,n]of s.entries()){if(e===d||n.some(e=>e.kind===`stream-run`||e.kind===`group`&&e.isStreaming)){f.push(...n);continue}let r=n.findLast($y);if(!r){f.push(...n);continue}let i=n.lastIndexOf(r),a=i,o=a;for(;a>0&&qy(n[a-1]);)--a;if(n.some(e=>e.kind===`notice`&&e.handoffBoundary)){let e=n.slice(i+1),t=r.runId!==void 0&&e.length>0&&e.every(e=>Jy(e)&&e.runId===r.runId&&!Yy(e)&&!Xy(e));f.push(...t?[...n.slice(0,i),...e,r]:n);continue}let s=nb(n);for(;o+1<n.length;){let e=n[o+1];if(!qy(e)||e.runId&&!s.has(e.runId))break;o+=1}let c=[],l=[],u=new Map,p;for(let e=a;e<=o;e+=1){let t=n[e];e!==i&&Jy(t)&&(e<i||!Yy(t))?(c.push(t),p&&u.set(t.key,p)):(l.push(t),p=t.key)}if(c.length===0){f.push(...n);continue}let m=t.session,h=m?.runtimeMs,g=m?.key===t.sessionKey&&r.runId!==void 0&&m.lastRunId===r.runId&&sb.has(m.status??``)&&typeof h==`number`&&Number.isFinite(h)&&h>=0?h:null,_=!od(r)&&!c.some(od)&&l.slice(0,l.indexOf(r)).every(e=>e.kind===`group`&&!od(e)&&e.runId===r.runId)?r.runId:void 0;f.push(...n.slice(0,a)),f.push({kind:`work-group`,key:`work:${r.key}`,groups:c,..._?{replyRunId:_}:{},...u.size>0?{previewAfterGroup:u}:{},durationMs:g}),f.push(...l,...n.slice(o+1))}return f}function nb(e){let t=new Set;for(let n of e){if(n.kind===`stream-run`){n.runId&&t.add(n.runId);continue}if(n.kind!==`group`||n.runId===void 0)continue;let e=n.role.toLowerCase()!==`tool`;(n.isStreaming||Zy(n,e))&&t.add(n.runId)}return t}function rb(e){if(e.isStreaming||e.visibleContent===`non-text`||od(e)||e.messages.some(({message:e,hasVisibleContent:t})=>{let n=J(e);return n?.role===`assistant`&&(t||Cy(e)===`final_answer`||Sy(e)||n.stopReason===`error`)}))return!1;let t=e.role.toLowerCase();return t===`tool`||t===`assistant`&&e.visibleContent===`none`&&e.messages.some(({message:e})=>mi(e).length>0)}function ib(e){return{kind:`activity-run`,key:`activity:${e[0].key}`,groups:e}}function ab(e,t){let n=e=>e.kind===`activity-run`?e.groups:e.kind===`group`&&rb(e)?[e]:void 0,r=n(e),i=n(t);return r&&i?ib([...r,...i]):void 0}function ob(e,t={}){if(t.searchActive)return e;let n=[],r=[],i=()=>{let[e]=r;e&&(n.push(r.length===1?e:ib(r)),r=[])};for(let t of e){if(t.kind===`group`&&rb(t)){r.push(t);continue}i(),n.push(t)}return i(),n}var sb;function cb(){return(cb=e((()=>{Ut(),xi(),Pi(),ra(),Fi(),ma(),wy(),zy(),Ll(),Ss(),Qu(),Cd(),sb=new Set([`done`,`failed`,`timeout`,`killed`])})))()}function lb(e,t,n,r,i){let a=(n.queue??[]).toSorted(Ii),{queue:o,pendingInputs:s}=bl(t,a,n.pendingInputs??[]),c=new Set,l=new Set,u=new Set,d=[],f,p,m=(e,t)=>{if(n.searchOpen&&n.searchQuery?.trim()&&!xl(e,n.searchQuery,n.messageRecovery))for(let e of t)u.add(e.key)};for(let t of s){let r=xf([t],void 0,a,n.workspaceSyncPendingRunIds,n.workerSetupPending,n.messageRecovery),o=r[0];if(o){if(m(t.message,r),t.state===`queued`){d.push({items:r,runId:t.runId}),i&&t.runId===i&&(f=o.key);continue}Qf(e,[{item:o,bounds:{afterKey:p}}]),e.splice(e.indexOf(o)+1,0,...r.slice(1));for(let e of r)c.add(e.key);p=r.at(-1).key}}let h=new Map(d.flatMap(e=>e.runId?[[e.runId,e]]:[])),g=new Map(d.map(e=>[e.items[0].key,e])),_=new Set(e.map(e=>e.key));for(let e of o){if(!Cc(e))continue;let t=Wl(e);if(!t)continue;let i={items:[{kind:`message`,key:e.sendRunId?qm([t])[0].key:`pending-send:${e.id}`,message:t}],runId:e.sendRunId,initial:e.id===n.initialTurnId,local:!0,bypassesQueue:e.queueMode===`steer`||e.queueMode===`interrupt`};m(t,i.items),!f&&!Rs(e)&&(f=i.items[0].key);let o=a.indexOf(e),s=r.keys.indexOf(i.items[0].key),c=s<0||i.initial?void 0:r.keys.slice(s+1).find(e=>g.has(e)||_.has(e));c&&_.has(c)&&(i.beforeKey=c);let l=a.slice(o+1).map(e=>e.sendRunId?h.get(e.sendRunId):void 0).find(e=>e!==void 0)??(c?g.get(c):void 0),u=l?d.indexOf(l):-1;d.splice(u<0?d.length:u,0,i)}let v=e.length;for(let t of d.toReversed()){let n=t.local?e.findIndex(e=>{if(!t.runId||e.kind!==`message`)return!1;let n=Zr(e.message);return xm(e.message,t.runId)||n?.role===`assistant`&&!n.isImported&&n.runId===t.runId}):-1,r=t.beforeKey?e.findIndex(e=>e.key===t.beforeKey):-1,i=t.initial?0:Math.min(v,n<0?e.length:n,r<0?e.length:r);e.splice(i,0,...t.items),v=t.initial||t.bypassesQueue&&n>=0?v+t.items.length:i,l.add(t.items[0].key)}return r.keys=e.filter(e=>e.kind!==`message`||tc(e.message)).map(e=>e.key),{pendingKeys:l,historicalKeys:c,hiddenKeys:u,activeInputKey:f}}function ub(){return(ub=e((()=>{$r(),th(),ou(),Ll(),Cu(),ap()})))()}function db(e,t,n){let r=hu(e,t);return r?`canvas:${r}`:`${n}:canvas`}function fb(e,t={keys:[]}){let n=[],r=e.toolMessages.filter(e=>J(e)!==null),i=qm(r).map(e=>({projection:{item:e},runId:qa(e.message.runId),callId:qa(e.message.toolCallId),preview:Rm(e.message)})),a=e.queue??[],o=e.streamSegments,s=null,c=()=>{if(s)return s;let t=e.runId?void 0:Ay(e.messages)?.runId;return s=Hu(e.sessionKey,e.runId??null,e.streamStartedAt,a,t?o.filter(e=>e.runId!==t):o,t?r.filter(e=>e.runId!==t):r),s},l=e.persistCommentary===!1&&(e.runWorking||e.runActive)?qa(c().runId):void 0,u=Qt(e.messages.filter(t=>!Wi(t)&&(e.persistCommentary!==!1||!of(t)||l!==void 0&&Lf(t)===l))),d=e.searchOpen===!0&&!!e.searchQuery?.trim(),f=new Set,p=new Set,m=u.map(uf),h=qm(u),g={previews:[],lastMatchingAssistantIndex:-1},_=h.map((t,n)=>{let r=m[n],i=r&&yi(r.role);return(i===`user`||i===`system`)&&(g={previews:[],lastMatchingAssistantIndex:-1}),i===`assistant`&&r&&(!d||xl(u[n],e.searchQuery??``,e.messageRecovery))&&(g.lastMatchingAssistantIndex=n,g.previews.push(...r.content.flatMap(e=>e.type===`canvas`?[{preview:e.preview,item:t}]:[]))),g}),v=e.compactionStatus,y=v?`divider:compaction:live:${v.runId}:${v.itemId??`manual`}`:void 0,b=!1;for(let[t,r]of h.entries()){let i=r.message,a=r.key,o=J(i)??{},s=J(o.__openclaw);if(s?.kind===`compaction`||lh(i)){let e=v!=null&&Iu(i,v),r=Ul(s??{},vc(i)??Date.now(),t);n.push({...r,compactionId:r.key,...e&&y?{key:y}:{}}),b||=e;continue}let c=m[t];if(!c)continue;if(s&&s.kind===`reset`){n.push(zc(s,c.timestamp??Date.now(),t));continue}if(yi(c.role)===`system`){let e=ea(i);e?.trim()&&n.push({kind:`notice`,key:a,text:e,timestamp:c.timestamp});continue}let l=c.role.toLowerCase()===`toolresult`,h=l?Rm(i):null;if(h){let e=hu(i,h);e&&p.add(e)}let g=h&&_[t].previews.find(({preview:e})=>Oi(e,h.preview));h&&g&&(g.item.message=Ld(g.item.message,h.preview,h.text));let x=h!=null&&!g&&(!d||_[t].lastMatchingAssistantIndex>t);if(h&&x&&n.push({kind:`message`,key:db(i,h,a),message:Js(h,h.timestamp??Lu(u,t))}),!e.showToolCalls&&l&&!Ey(i))continue;let S=e.searchQuery??``;e.searchOpen&&S.trim()&&!xl(i,S,e.messageRecovery)&&f.add(a),(tc(i,c)||c.role.toLowerCase()===`assistant`)&&n.push(...Kc(r,c))}let x=e.runId??(e.stream!==null||a.some(Cc)?c().runId:null),S=Zl(n),{pendingKeys:C,historicalKeys:w,hiddenKeys:T,activeInputKey:E}=lb(n,u,e,t,x),D=()=>n.filter(e=>!w.has(e.key)),O=Zu(D()),k=(x?O(x):null)??(E?{afterKey:E}:S),ee=(e,t,n)=>(typeof t==`string`&&n?e(t,n):null)??Qp(e,t,x,k)??(!t&&E?k:void 0),A=e=>{let{minimum:t,maximum:r}=Ms(n,e??void 0),i=n.find((e,n)=>n>=t&&n<r&&C.has(e.key));return i?{...e,beforeKey:i.key}:e??void 0};for(let{projection:e,preview:t}of i){if(!t)continue;let r=hu(e.item.message,t);if(r&&p.has(r))continue;let i=A(ee(O,e.item.message.runId,qa(e.item.message.openclawToolStreamAfterSendId))),{minimum:a,maximum:o}=Ms(n,i??void 0),s=dc(n,t.timestamp,a,o);if(s){n[s.index]={...s.item,message:Ld(s.item.message,t.preview,t.text)};continue}if(d)continue;let c=wu(n,t.timestamp,a,o),l=n[c],u=l?.kind===`message`?vc(l.message):null,f=t.timestamp!=null&&u!=null?Math.min(t.timestamp,u):t.timestamp;n.splice(c,0,{kind:`message`,key:db(e.item.message,t,e.item.key),message:Js(t,f)})}n=n.filter(e=>e.kind!==`message`||tc(e.message));let j=[];if(v&&y&&!b){let e=v.startedAt??v.completedAt??Date.now();j.push({item:{...Ul({},e,0,v.phase===`complete`?`complete`:`active`),key:y}})}let te=o.filter($i),ne=o.filter(e=>!$i(e)),M=hd();for(let e of i)M.add(e.runId,e.callId,e.projection);let N=Zu(D()),P=(e,t)=>A(ee(N,e,t));if(!d){e.archiveNotice&&j.push({item:e.archiveNotice});for(let t of e.guardianNotices??[])j.push({item:_c(t),bounds:P(t.runId)})}let re=(e,t,n)=>{j.push({item:{kind:`stream`,key:t,text:n,startedAt:e.ts,isStreaming:!1,...bp(e.runId),...fm(e.runId)},bounds:P(e.runId,e.afterUserSendId)})},ie=null,ae=Math.max(ne.length,i.length);for(let t=0;t<ae;t++){let n=ne[t];if(n){let r=uh(n.text),i=ta(r,ie);if(ie=Ea(ie,r),i.length>0&&n.persisted!==!0){let r=`stream-seg:${e.sessionKey}:${t}`;re(n,r,i);let a=M.get(qa(n.runId),n.toolCallId?.trim());a&&(a.predecessorKey=r)}}let r=i[t];r&&(e.showToolCalls||Ey(r.projection.item.message))&&(r.projection.bounds=P(r.runId,qa(r.projection.item.message.openclawToolStreamAfterSendId)),j.push(r.projection))}for(let t of te){let n=uh(t.text);n.length>0&&re(t,`stream-seg:${e.sessionKey}:${t.itemId}`,n)}for(let t of e.questionPrompts??[]){if(t.status===`pending`)continue;let e={kind:`question`,key:`question:${t.id}`,questionId:t.id,startedAt:t.createdAtMs};j.push({item:e,bounds:t.runId?P(t.runId):void 0})}ad(n,i.map(e=>e.projection)),Qf(n,j);let oe=e.stream===null&&e.loading===!0&&n.length===0,se=e.stream!==null&&e.stream.trim().length===0,ce=(!v||v.phase===`complete`)&&(e.runWorking===!0&&!oe||se||a.some(e=>(e.sendState===`submitting`||e.sendState===`sending`)&&Cc(e)));e.runWorking!==!0&&e.stream===null&&!ce&&fl(e.sessionKey);let F=A((x?Zu(D())(x):null)??(E?{afterKey:E}:null)),le=e=>{if(F){let{maximum:t}=Ms(n,F);n.splice(t,0,e)}else n.push(e)};if(e.stream!==null){let t=uh(e.stream),r=ji(o,uh),i=ta(t,r);if(i.length>0&&!Fa(i).shouldSkip){let t=c(),r=e.runId??t.runId;le({kind:`stream`,key:t.key,text:i,startedAt:zs(n,e.streamStartedAt??Date.now()),isStreaming:!0,...bp(r),...fm(r)})}}if(ce){let t=c(),n=e.runId??t.runId;le({kind:`reading-indicator`,key:t.key,startedAt:t.startedAt,...bp(n),...fm(n)})}else e.subagentWait&&!oe&&le({kind:`reading-indicator`,key:`waiting-subagents:${e.sessionKey}`,startedAt:e.subagentWait.startedAt,waitingOn:`subagents`,runId:e.subagentWait.runId});let ue=f.size>0||T.size>0?new Set([...f,...T]):void 0,de=(t,n)=>ky(t,e.showToolCalls,n),fe=ue?de(um(n)):void 0;return Uy(de(um(n,ue),fe),{items:fe,people:e.replyPeople,localPerson:e.replyLocalPerson})}function pb(){return(pb=e((()=>{Jt(),Ni(),na(),Pi(),ou(),My(),Vp(),cb(),ub(),Ll(),Ss(),vp(),Qu()})))()}function mb(e){return e.kind===`agent-run-frame`?e.parts.flatMap(mb):e.kind===`group`?[e]:e.kind===`work-group`||e.kind===`activity-run`?e.groups:[]}function hb(e){if(e.kind===`work-group`){if(e.replyRunId)return e.replyRunId;if(e.groups.some(od))return}if(e.kind===`stream-run`)return e.runId;let t=mb(e),n=t[0]?.runId;return n&&t.every(e=>e.runId===n)?n:void 0}function gb(e){return e.kind===`stream-run`?e.parts.some(e=>e.kind===`reading-indicator`||e.kind===`stream`&&e.isStreaming):mb(e).some(e=>e.isStreaming)}function _b(e){let t=e.messages[0]?.message,n=Zr(t),r=n?.runId;return r?`send:${r}`:n?.id?`entry:${n.id}`:void 0}function vb(e,t,n){return`agent-run:${JSON.stringify(n?[e,t,n]:[e,t])}`}function yb(e,t){let n=J(e),r=Cy(e),i=n?.stopReason,a=J(n?.__openclaw);return!(ea(e)?.trim()||qu(e))||Sy(e)||r===`commentary`||i===`toolUse`||i===`error`||a?.mirrorOrigin===`codex-app-server`&&a.runTerminal!==!0?!1:!t||r===`final_answer`||i===`stop`}function bb(e){let t=e.flatMap(mb).flatMap(e=>e.role===`assistant`?e.messages:[]).findLast(({message:e})=>yb(e,!0));if(t)return t;let n=e.at(-1);if(n?.kind!==`group`||n.role!==`assistant`)return null;let r=n.messages.at(-1);return r&&yb(r.message,!1)?r:null}function xb(e){if(e.outcome.kind!==`active`)return;let t=e.parts.flatMap(e=>e.kind===`stream-run`?e.parts:[]);return t.length>0&&e.parts.every(e=>e.kind===`stream-run`&&e.parts.every(e=>e.kind===`reading-indicator`))?t:void 0}function Sb(e,t={}){if(t.searchActive)return e;let n=[],r,i,a=new Set,o,s,c=[],l,u=!1,d=!1,f=e=>{let t=c.at(-1),n=d&&t?ab(t,e):void 0;d=!1,n?c[c.length-1]=n:c.push(e)},p=(e=!1)=>{let t=l?.runId??s,f=l?l.boundaryId:r;if(l=void 0,u=!1,d=!1,!s||!t||c.length===0)return;let p=c.some(gb),m=p||e?null:bb(c);if(!f&&!p&&!m){n.push(...c),c=[],s=void 0;return}let h=f??`send:${t}`,g=vb(t,h,o??c.flatMap(e=>e.kind===`stream-run`?e.parts:[]).find(e=>e.kind===`stream`&&e.key.includes(`:after:`))?.key),_=a.has(g)?vb(t,h,JSON.stringify([i,c[0].key])):g;a.add(g),n.push({kind:`agent-run-frame`,key:_,runId:s,boundaryId:h,outcome:e?{kind:`failed`}:p?{kind:`active`}:{kind:`completed`,actionOwner:m},parts:c}),c=[],s=void 0};for(let t of e){if(t.kind===`notice`&&t.handoffBoundary&&s&&c.length>0){l??={runId:s,boundaryId:r},u=!0,d=!0;continue}if(t.kind!==`group`&&t.kind!==`work-group`&&t.kind!==`activity-run`&&t.kind!==`stream-run`){p(),n.push(t),r=t.kind===`notice`&&t.startsTurn?t.boundaryId:void 0,o=r?void 0:t.key;continue}let e=mb(t)[0];if(e&&Hp(e)){p(),i=e.key,o=void 0;let a=_b(e);if(e.role===`user`||od(e)||!a){n.push(t),r=a;continue}r=a}let a=t.kind===`stream-run`?t.boundaryId:void 0,m=hb(t);if(u&&!m&&t.kind===`stream-run`&&!a){f(t);continue}if(u&&m&&m!==s&&(r=a,s=m,u=!1),a&&(a!==(r??(s?`send:${s}`:void 0))&&p(),r=a),!m){if(p(),n.push(t),t.kind===`activity-run`){let e=t.groups.findLast(qc);e?(r=_b(e),i=e.key,o=void 0):t.groups.some(e=>e.runId===void 0)&&(r=void 0,o=t.key)}else r=void 0,o=t.key;continue}let h=!(t.kind===`work-group`&&t.replyRunId)&&mb(t).some(Xy);s&&s!==m&&p(),s=m,f(t),h&&(p(!0),r=void 0,o=t.key)}return p(),n}function Cb(){return(Cb=e((()=>{$r(),na(),wy(),cb(),Qu(),ol()})))()}function wb(e){if(e){Kb.delete(e);return}Kb.clear(),Ac(),Jb.clear(),Yb.clear()}function Tb(e,t){return e?.key===t?.key&&e?.message===t?.message}function Eb(e,t){return e.role===t.role&&e.senderLabel===t.senderLabel&&Db(e.senderSession,t.senderSession,Zb.senderSession)&&Gt(e.sourceClients??[])===Gt(t.sourceClients??[])&&JSON.stringify(e.sender)===JSON.stringify(t.sender)&&JSON.stringify(e.replyToSender)===JSON.stringify(t.replyToSender)&&Tb(e.replyToMessage,t.replyToMessage)&&e.replyShared===t.replyShared&&Tb(e.replyTurnSource,t.replyTurnSource)&&Tb(e.replyCurrentSource,t.replyCurrentSource)&&e.isStreaming===t.isStreaming&&e.visibleContent===t.visibleContent&&e.runId===t.runId&&e.messages.length===t.messages.length&&e.messages.every((e,n)=>{let r=t.messages[n];return r!==void 0&&e.key===r.key&&e.message===r.message&&e.duplicateCount===r.duplicateCount&&JSON.stringify(e.replyTarget)===JSON.stringify(r.replyTarget)&&e.hasVisibleContent===r.hasVisibleContent})}function Db(e,t,n){return n.every(n=>e?.[n]===t?.[n])}function Ob(e,t){if(e.kind!==t.kind||e.key!==t.key)return!1;switch(t.kind){case`group`:return e.kind===`group`&&Eb(e,t);case`message`:return e.kind===`message`&&Db(e,t,Zb.message);case`notice`:return e.kind===`notice`&&Db(e,t,Zb.notice);case`divider`:return e.kind===`divider`&&Db(e,t,Zb.divider);case`stream`:return e.kind===`stream`&&e.text===t.text&&e.startedAt===t.startedAt&&e.isStreaming===t.isStreaming&&JSON.stringify(e.replyToSender)===JSON.stringify(t.replyToSender)&&Tb(e.replyToMessage,t.replyToMessage)&&e.runId===t.runId&&e.boundaryId===t.boundaryId;case`reading-indicator`:return e.kind===`reading-indicator`&&e.startedAt===t.startedAt&&e.waitingOn===t.waitingOn&&e.request?.askedAt===t.request?.askedAt&&e.request?.runIds.join(`
`)===t.request?.runIds.join(`
`)&&e.runId===t.runId&&e.boundaryId===t.boundaryId;case`question`:return e.kind===`question`&&Db(e,t,Zb.question)}return!1}function kb(e,t){if(e.length===0||t.length===0)return t;let n=new WeakMap,r=new Map;for(let t of e)if(t.kind===`group`)for(let e of t.messages)e.message&&typeof e.message==`object`&&n.set(e.message,t),r.set(e.key,t);let i=new Set(t.filter(e=>e.kind===`group`).map(e=>e.key)),a=new Set,o=new Map(e.flatMap(e=>e.kind===`divider`&&e.compactionId?[[e.compactionId,e.key]]:[])),s=t.map(e=>{if(e.kind===`divider`&&e.compactionId){let t=o.get(e.compactionId);return t?{...e,key:t}:e}if(e.kind!==`group`)return e;let t=new Map;for(let[i,o]of e.messages.entries()){let s=o.message&&typeof o.message==`object`?n.get(o.message)??r.get(o.key):r.get(o.key);if(!s||a.has(s.key)||s.role!==e.role||s.runId!==e.runId||s.senderLabel!==e.senderLabel||!Db(s.senderSession,e.senderSession,Zb.senderSession)||Gt(s.sourceClients??[])!==Gt(e.sourceClients??[])||Hi(s.sender)!==Hi(e.sender))continue;let c=t.get(s);t.set(s,{overlap:(c?.overlap??0)+1,lastMatchIndex:i})}let s=null;for(let[e,n]of t)(!s||n.overlap>s.overlap||n.overlap===s.overlap&&n.lastMatchIndex>s.lastMatchIndex)&&(s={group:e,...n});return!s||s.group.key!==e.key&&i.has(s.group.key)?e:(a.add(s.group.key),e.key===s.group.key?e:{...e,key:s.group.key})}),c=new Map(e.map(e=>[`${e.kind}\u0000${e.key}`,e])),l=s.map(e=>{let t=c.get(`${e.kind}\u0000${e.key}`);return t&&Ob(t,e)?t:e});return Ab(l,e)?e:l}function Ab(e,t){return e===t||e!==void 0&&t!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function jb(e,t){return e.sessionKey===t.sessionKey&&e.archiveNotice?.key===t.archiveNotice?.key&&e.archiveNotice?.label===t.archiveNotice?.label&&e.runId===t.runId&&e.compactionStatus===t.compactionStatus&&e.locale===t.locale&&e.messages===t.messages&&e.toolMessages===t.toolMessages&&e.guardianNotices===t.guardianNotices&&e.streamSegments===t.streamSegments&&e.streamStartedAt===t.streamStartedAt&&e.queue===t.queue&&e.initialTurnId===t.initialTurnId&&Ab(e.pendingInputs,t.pendingInputs)&&e.workspaceSyncPendingRunIds===t.workspaceSyncPendingRunIds&&e.workerSetupPending===t.workerSetupPending&&e.showToolCalls===t.showToolCalls&&e.persistCommentary===t.persistCommentary&&e.runWorking===t.runWorking&&e.runActive===t.runActive&&e.subagentWait?.startedAt===t.subagentWait?.startedAt&&e.subagentWait?.runId===t.subagentWait?.runId&&e.subagentWait===void 0==(t.subagentWait===void 0)&&e.questionPrompts===t.questionPrompts&&e.loading===t.loading&&Ab(e.replyPeople,t.replyPeople)&&e.replyLocalPerson===t.replyLocalPerson&&e.searchOpen===t.searchOpen&&e.searchQuery===t.searchQuery&&e.messageRecovery?.messages===t.messageRecovery?.messages&&e.messageRecovery?.revision===t.messageRecovery?.revision&&e.messageRecovery?.agentId===t.messageRecovery?.agentId}function Mb(e){return JSON.stringify([e.sessionKey,e.runId??null,e.streamStartedAt])}function Nb(e,t){let n=e.liveStream,r=n?e.items[n.index]:void 0;if(t.stream===null||!n||r?.kind!==`stream`||!r.isStreaming||n.identity!==Mb(t))return!1;let i=ta(uh(t.stream),n.prefix);return i.length===0||Fa(i).shouldSkip?!1:(e.items[n.index]={...r,text:i},!0)}function Pb(e){return e.findIndex(e=>e.kind===`stream`&&e.isStreaming)}function Fb(e){return qb.get(e)??0}function Ib(e,t=`visible`){let n=Kb.get(e.paneId);n||(n=new Map,Kb.set(e.paneId,n));let r=Yu(n,e.sessionKey,()=>({inputOrder:{keys:[]},initialTurnId:e.initialTurnId}));if(r.initialTurnId!==e.initialTurnId){r.initialTurnId=e.initialTurnId,r.inputOrder.keys=[];for(let e of[r.visible,r.unfiltered])e&&(e.input=null)}let i=r[t]??={generation:0,input:null,items:[],liveStream:null};if(i.input&&jb(i.input,e)){if(i.input.stream===e.stream)return i.items;if(i.input.stream!==null&&Nb(i,e))return i.input=e,i.items}let a=kb(i.items,fb(e,r.inputOrder));qb.set(a,++i.generation),i.input=e,i.items=a;let o=Pb(a);return i.liveStream=o<0?null:{index:o,identity:Mb(e),prefix:ji(e.streamSegments,uh)},a}function Lb(e){return Xb.get(e)??0}function Rb(e,t,n){e.has(t)&&e.get(t)===n||(e.set(t,n),Xb.set(e,Lb(e)+1))}function zb(e,t){e.delete(t)&&Xb.set(e,Lb(e)+1)}function Bb(e,t,n){let r=new Set(n.map(e=>Bc(e)?.id).filter(e=>typeof e==`string`).map(e=>Ep(t,e)));for(let t of e.keys())r.has(t)||zb(e,t)}function Vb(e){return Yu(Jb,e,()=>({expanded:new Map,initialized:new Set}))}function Hb(e){return Vb(e).expanded}function Ub(e){for(let[t,n]of Yb)if(z(t,e))return t!==e&&(Yb.delete(t),Jp(Yb,e,n)),n;return Yu(Yb,e,()=>new Map)}function Wb(e,t,n){if(!t)return;let r=e=>{let t=new Map;for(let[n,r]of e)t.set(r,t.has(r)?null:n);return t},i=r(n);for(let[a,o]of r(t)){let t=i.get(a),r=o?e.get(o):void 0;o&&t&&!n.has(o)&&r!==void 0&&(Rb(e,t,r),o.startsWith(`activity:`)&&zb(e,o))}}function Gb(e,t,n,r=!1){let i=Vb(e),{expanded:a,initialized:o,lastSync:s}=i;if(s?.items.deref()===t&&s.isFilteredProjection===r&&s.autoExpandToolCalls===n)return;let c=new Set,l=new Map,u=(e,t,r)=>{c.add(e),t&&l.set(e,`${r}:${t}`),o.has(e)||(Rb(a,e,n),o.add(e))};for(let e of t){if(e.kind!==`group`)continue;let t;for(let n of e.messages){let e=mi(n.message);for(let r=0;r<e.length;r++)t??=e[r]?.callId,u(`${n.key}:toolcard:${r}`,e[r]?.callId,`card`);Gi(n.message)&&u(`toolmsg:${n.key}`,e[0]?.callId,`message`)}t&&l.set(`activity:${e.key}`,`activity:${t}`)}if(r||(Wb(a,i.calls,l),i.calls=l),n&&!s?.autoExpandToolCalls)for(let e of o)Rb(a,e,!0);if(!r)for(let e of o)c.has(e)||(o.delete(e),zb(a,e));i.lastSync={items:new WeakRef(t),isFilteredProjection:r,autoExpandToolCalls:n}}var Kb,qb,Jb,Yb,Xb,Zb;function Qb(){return(Qb=e((()=>{Ut(),Ni(),Pi(),Fi(),ma(),R(),_m(),ou(),pb(),Ll(),cl(),cb(),Cb(),Kb=new Map,qb=new WeakMap,Jb=new Map,Yb=new Map,Xb=new WeakMap,Zb={message:[`message`,`duplicateCount`],notice:[`text`,`label`,`handoffBoundary`,`startsTurn`,`boundaryId`,`timestamp`],divider:[`compaction`,`compactionId`,`label`,`metric`,`description`,`timestamp`],question:[`questionId`,`startedAt`],senderSession:[`sessionKey`,`agentId`,`label`]}})))()}function $b(e,t){return X(e,t),e.requestUpdate?.(),!1}function ex(e){if(!e.client?.recoveryScopeReady||!e.client.recoveryScope)return null;let t=e.settings?.gatewayUrl??``,n=e.sessionKey,r=h(e,n),i=e.currentSessionId??void 0,a=!!e.selectedChatSessionIncognito,o=`${ee(t,e.client.recoveryScope)}${JSON.stringify([n,r,i,a])}`,s=`${Le(t)}:${o}`,c=ax.get(e)??new Map;ax.set(e,c);let l=a?void 0:globalThis.sessionStorage;if(!a&&!l)throw Error(V(`chat.goals.recoveryUnavailable`));let u=c.get(s);if(!u){let e=l?.getItem(o);if(e){let t;try{t=JSON.parse(e)}catch{t=`invalid`}let a=bo(t)&&`action`in t?Kr:Gr;u=t===`expired`?{retired:`expired`,pending:!1}:bo(t)&&Do(a,t)&&t.sessionKey===n&&t.agentId===r&&t.sessionId===i?{params:t,pending:!1}:{retired:`invalid`,pending:!1},u.retired&&l?.setItem(o,JSON.stringify(u.retired)),c.set(s,u)}}return u&&!u.pending&&u.params&&Tt(u.params.issuedAtMs)&&(u.params=void 0,u.retired=`expired`,l?.setItem(o,JSON.stringify(`expired`))),{sessionKey:n,agentId:r,sessionId:i,signature:s,storageKey:o,storage:l,operations:c,operation:u}}function tx(e){try{let t=ex(e)?.operation;return t?{pending:t.pending,retired:t.retired,onCheck:()=>ix(e,void 0,t)}:void 0}catch{return}}async function nx(e,t,n){return t.objective.trim()?t.sessionId&&t.sessionId!==e.currentSessionId?$b(e,V(`chat.goals.sessionChanged`)):t.action===`edit`?rx(e,{action:`edit`,goalId:t.goalId,objective:t.objective}):e.chatMessage===t.objective&&!!await e.handleSendChat(void 0,{intent:{kind:`session-goal-start`,version:1,issuedAtMs:Date.now()}},n):!1}async function rx(e,t){return ix(e,t)}async function ix(e,t,n){let r=e.client;if(!r||!e.connected||!r.recoveryScopeReady)return $b(e,V(`chat.goals.offline`));if(!r.recoveryScope)return $b(e,V(`chat.goals.recoveryUnavailable`));let i;try{i=ex(e)}catch(t){return $b(e,`${V(`chat.goals.recoveryUnavailable`)} ${B(t)}`)}if(!i)return!1;let{sessionKey:a,agentId:o,sessionId:s,signature:c,storageKey:l,storage:u,operations:d}=i,f=wt(e,a).agentId,{operation:p}=i;if(n&&p!==n)return!1;let m=e.connectionEpoch,h=r.recoveryScope,g=()=>e.client===r&&e.connected&&e.connectionEpoch===m&&r.recoveryScope===h&&(e.currentSessionId??void 0)===s&&ze(e,a,o);if(p?.pending)return $b(e,V(`chat.goals.actionPending`));if(p?.retired){if(t)return!1;let n=e.sessions,i=n.captureConnectionScope(),f=I(e,a);if(!i||!f.agentId)return!1;let m=()=>g()&&e.sessions===n&&n.isConnectionScopeCurrent(i)&&ex(e)?.operation===p,h=JSON.stringify(p.retired),_;p.pending=!0,e.requestUpdate?.();try{let t=await n.reconcileMutation(o);if(!m())return!1;_=n.observeRow({key:f.sessionKey,agentId:f.agentId},()=>{},{onInvalidate:()=>{}});let i=_.captureReconcile(),p=await n.describe({key:a,...o?{agentId:o}:{}},{client:r,refresh:!0,timeoutMs:ox});if(!m())return!1;let g=p.session;if(!g||!z(g.key,f.sessionKey)||s&&g.sessionId!==s)return!1;let v=i(g);return!m()||v.status!==`current`||!v.row||s&&v.row.sessionId!==s?!1:t.status===`refreshed`?u&&u.getItem(l)!==h?!1:(u?.removeItem(l),d.delete(c),X(e,null),!0):(t.status===`failed`&&X(e,t.error),!1)}catch(t){return g()&&X(e,B(t)),!1}finally{_?.dispose(),p.pending=!1,e.requestUpdate?.()}}if(p&&t){let n=p.params;if(!n||n.goalId!==t.goalId||(`action`in n?n.action:`clear`)!==t.action||t.action===`edit`&&(!(`objective`in n)||n.objective!==t.objective))return $b(e,V(`chat.goals.outcomeUnknown`))}if(!p){if(!t)return!1;if(!s||Zp(e))return $b(e,V(`chat.thread.loading`));let n={sessionKey:a,...o?{agentId:o}:{},sessionId:s,goalId:t.goalId,operationId:mo(),issuedAtMs:Date.now()};p={params:t.action===`clear`?n:t.action===`edit`?{...n,action:`edit`,objective:t.objective}:{...n,action:t.action},pending:!1};let r=t.action===`clear`?Gr:Kr;if(!Do(r,p.params))return $b(e,V(`chat.goals.invalidRequest`));try{u?.setItem(l,JSON.stringify(p.params))}catch(t){return $b(e,`${V(`chat.goals.recoveryUnavailable`)} ${B(t)}`)}d.set(c,p)}let _=p.params;if(!_)return!1;let v=e=>{let t=JSON.parse(u?.getItem(l)??`null`);bo(t)&&t.operationId===_.operationId&&(e?u?.setItem(l,JSON.stringify(e)):u?.removeItem(l))};p.pending=!0,X(e,null),e.requestUpdate?.();try{let t=await r.request(`action`in _?`sessions.goal.update`:`sessions.goal.clear`,_,{timeoutMs:ox});d.delete(c);try{v()}catch{}if(g()){if(t.replayed)return jd(e,{sessionKey:a,agentId:o}).catch(t=>{g()&&(X(e,B(t)),e.requestUpdate?.())}),!0;let n=e.sessionsResult?.sessions.find(e=>z(e.key,a)&&e.sessionId===s&&(e.agentId===void 0||e.agentId===f));n?.goal?.id===_.goalId&&(!t.goal||t.goal.updatedAt>=n.goal.updatedAt)&&(f&&s&&e.sessions.patchRowLocal(n.key,{goal:t.goal},{agentId:f,sessionId:s}),t.status===`started`&&t.runId&&Uf(e,t.runId,Date.now()))}return!0}catch(t){let n=t instanceof Wn&&bo(t.details)?t.details:null,r=n?.reason,i=typeof r==`string`&&(n?.code===`GOAL_OPERATION_REJECTED`&&sx.has(r)||r.startsWith(`goal-`)&&sx.has(r.slice(5)));if(i){let e=r===`expired`||r===`goal-expired`?`expired`:void 0;e?(p.params=void 0,p.retired=e):d.delete(c);try{v(e)}catch{}}return g()&&X(e,i?B(t):`${V(`chat.goals.outcomeUnknown`)} ${B(t)}`),!1}finally{p.pending=!1,e.requestUpdate?.()}}var ax,ox,sx;function cx(){return(cx=e((()=>{Eo(),zr(),$t(),F(),ya(),je(),zt(),Ue(),R(),Ua(),af(),Vf(),gc(),ja(),ax=new WeakMap,ox=3e4,sx=new Set([`expired`,`operation-conflict`,`session-rebound`,`goal-rebound`,`capacity`,`invalid`])})))()}var lx,ux;function dx(){return(dx=e((()=>{kr(),lr(),gs(),F(),Lh(),pa(),we(),gt(),R(),ho(),lx=_o(()=>import(`./control-ui-boot-shared-UG5ko-VG.js`).then(e=>(e.i(),e.r)),__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url),ux=class extends lo{constructor(...e){super(...e),this.identity=``,this.messages=[],this.entries=[],this.drafts=[],this.error=``,this.busy=!1,this.generation=0,this.refreshQueued=!1}static{this.properties={host:{attribute:!1},identity:{type:String},messages:{attribute:!1}}}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),this.unsubscribe=la(()=>{this.refreshQueued||(this.refreshQueued=!0,queueMicrotask(()=>{this.refreshQueued=!1,this.isConnected&&this.refresh()}))})}disconnectedCallback(){this.generation++,this.unsubscribe?.(),super.disconnectedCallback()}updated(e){let t=e.has(`messages`)&&this.entries.some(e=>e.session.queue?.some(e=>e.sendRunId));(e.has(`identity`)||e.has(`host`)||t)&&this.refresh()}owner(){let e=this.host;return!e||e.selectedChatSessionIncognito||!rr(e)?null:{gatewayOwner:oa(e.settings.gatewayUrl).gatewayOwner,recoveryScope:rr(e)}}async refresh(){let e=++this.generation,t=this.host,n=this.owner();if(this.drafts=[],!n){this.entries=[],this.error=``,this.requestUpdate();return}try{let r=t?qh(t):null,i=``;if(t&&r?.entries.length){let e=Kh(t,r.entries);e!==`unchanged`&&(r=qh(t)),e===`storage-failed`&&(i=V(`chat.outboxRecoveryStorageFailed`))}this.entries=r?.entries??[],this.error=i||(r?.blocked?V(`chat.outboxRecoveryFull`):``);let a=await(await lx).prepareDurableComposerRecovery(n);if(e!==this.generation||!this.isConnected)return;if(a.status===`storage-failed`)throw Error(`storage-failed`);this.drafts=a.entries}catch{if(e!==this.generation||!this.isConnected)return;this.error=V(`chat.outboxRecoveryStorageFailed`)}this.requestUpdate()}async recover(e){let t=this.host,n=this.owner();if(!t||!n||this.busy)return;let r=this.identity,i=t.client,a=t.currentSessionId,o=t.connectionEpoch,s=()=>this.isConnected&&this.host===t&&this.identity===r&&t.client===i&&t.currentSessionId===a&&t.connectionEpoch===o&&JSON.stringify(this.owner())===JSON.stringify(n)&&!t.chatMessage&&!t.chatGoalDraftMode&&!t.chatReplyTarget&&!t.chatAttachments.length&&!t.chatQueue.length;this.busy=!0,this.error=``,this.requestUpdate();try{if(!s()){this.error=V(`chat.outboxRecoveryConflict`);return}let i=I(t,t.sessionKey),a=Ph(t,i),o={...n,scopeKey:`chat:v3:${mt(i)}`},c=await lx,l=await c.readDurableComposerDraft(o);if(l.status===`storage-failed`){this.error=V(`chat.outboxRecoveryStorageFailed`);return}if(!a||l.status===`found`||!s()){this.error=V(`chat.outboxRecoveryConflict`);return}if(!await ps({title:V(`chat.outboxRecoveryReviewTitle`),message:V(`chat.outboxRecoveryConfirm`,{chat:this.chatName(i.sessionKey)}),details:this.details(e),confirmLabel:V(`chat.outboxRecoveryRestore`)})||!s())return;let u=await c.readDurableComposerDraft(o);if(!s()||JSON.stringify(u)!==JSON.stringify(l)){this.error=V(`chat.outboxRecoveryConflict`);return}let d=`id`in e?Mh(t,e,a,l.revision??0):(await c.restoreDurableComposerRecovery(o,e,l.revision??0,l.writeId,()=>s()&&JSON.stringify(Ph(t,i))===JSON.stringify(a),a.revision)).status;d===`restored`||d===`persisted`?(this.host===t&&this.identity===r&&this.dispatchEvent(new CustomEvent(`outbox-restored`,{bubbles:!0})),await this.refresh()):this.error=V(d===`conflict`?`chat.outboxRecoveryConflict`:`chat.outboxRecoveryStorageFailed`)}catch{this.error=V(`chat.outboxRecoveryStorageFailed`)}finally{this.busy=!1,this.requestUpdate()}}chatName(e){let t=this.host?.sessionsResult?.sessions.find(t=>t.key===e);return He(e,t)}preview(e){let t=`id`in e?e.session.draft||e.session.queue?.find(e=>e.text.trim())?.text:e.text;if(t?.trim())return t.trim();let n=`id`in e?(e.session.queue??[]).flatMap(e=>e.attachments??[]).map(e=>e.fileName??e.mimeType):e.attachmentNames;if(n.length)return V(`chat.outboxRecoveryAttachments`,{files:n.join(`, `)});let{goalMode:r,replyTarget:i}=`id`in e?e.session:e;return r?V(`chat.outboxRecoveryGoal`):i?V(`chat.outboxRecoveryReply`,{text:i.text}):V(`chat.outboxRecoveryQueued`)}unconfirmed(e){return`id`in e&&e.session.queue?.some(e=>(e.sendAttempts??0)>0||e.sendState===`unconfirmed`)}details(e){let t=`id`in e?e.session:null,n=`id`in e?e.session.draft:e.text,{goalMode:r,replyTarget:i}=`id`in e?e.session:e,a=`id`in e?[]:e.attachmentNames;return[n?.trim(),r?V(`chat.outboxRecoveryGoal`):``,i?V(`chat.outboxRecoveryReply`,{text:i.text}):``,a.length?V(`chat.outboxRecoveryAttachments`,{files:a.join(`, `)}):``,...(t?.queue??[]).flatMap(e=>[e.text.trim(),e.attachments?.length?V(`chat.outboxRecoveryAttachments`,{files:e.attachments.map(e=>e.fileName??e.mimeType).join(`, `)}):``,e.attachmentStorageError?V(`chat.outboxRecoveryAttachmentMissing`):``]),this.unconfirmed(e)?V(`chat.outboxRecoveryUnconfirmed`):``].filter(Boolean).join(`

`)}async discard(e){let t=this.host,n=this.owner();if(!t||!n||this.busy)return;let r=this.identity,i=t.client,a=t.connectionEpoch,o=()=>this.isConnected&&this.host===t&&this.identity===r&&t.client===i&&t.connectionEpoch===a&&JSON.stringify(this.owner())===JSON.stringify(n);this.busy=!0,this.error=``,this.requestUpdate();try{if(!await ps({title:V(`chat.outboxRecoveryDeleteTitle`),message:V(`chat.outboxRecoveryDeleteConfirm`),details:this.details(e),confirmLabel:V(`chat.outboxRecoveryDelete`),danger:!0})||!o())return;let r=`id`in e?Nh(t,e,o):(await(await lx).discardDurableComposerRecovery(n,e,o)).status;if(!o())return;r===`discarded`?await this.refresh():this.error=V(r===`conflict`?`chat.outboxRecoveryDeleteConflict`:`chat.outboxRecoveryStorageFailed`)}catch{o()&&(this.error=V(`chat.outboxRecoveryStorageFailed`))}finally{this.busy=!1,this.requestUpdate()}}renderEntry(e){let t=Oa(`id`in e?e.sourceScopeKey:e.scopeKey),n=this.host?I(this.host,this.host.sessionKey):void 0,r=t&&![`global`,`main`].includes(t.sessionKey)&&(!n||mt(t)!==mt(n))?this.host?.sessionsResult?.sessions.find(e=>e.key===t.sessionKey):void 0,i=`id`in e?e.session.updatedAt:e.updatedAt,a=`id`in e&&!!e.session.queue?.length;return W`<div
      class="chat-outbox-recovery-row"
      title=${i>0?V(`chat.outboxRecoveryUpdated`,{time:x(i,{dateStyle:`medium`,timeStyle:`short`})}):``}
    >
      <span class="chat-outbox-recovery__kind"
        >${V(a?`chat.outboxRecoveryQueued`:`chat.outboxRecoveryDraft`)}</span
      >
      <span class="chat-outbox-recovery__preview">${this.preview(e)}</span>
      ${this.unconfirmed(e)?W`<span
              class="chat-outbox-recovery__warning"
              title=${V(`chat.outboxRecoveryUnconfirmed`)}
              >${V(`chat.outboxRecoveryUnconfirmedLabel`)}</span
            >`:U}
      ${r?W`<span class="chat-outbox-recovery__source"
              >${V(`chat.outboxRecoverySource`,{chat:He(r.key,r)})}</span
            >`:U}
      <div class="chat-outbox-recovery__actions">
        ${[[`chat.outboxRecoveryRestore`,()=>void this.recover(e)],[`chat.outboxRecoveryDelete`,()=>void this.discard(e)]].map(([e,t])=>W`
            <button class="btn btn--sm" ?disabled=${this.busy||!this.owner()} @click=${t}>
              ${V(e)}
            </button>
          `)}
      </div>
    </div>`}render(){let e=[...this.entries,...this.drafts];return!e.length&&!this.error?U:W`<div class="chat-outbox-recovery">
      ${this.error?W`<div class="chat-outbox-recovery__error" role="alert" title=${this.error}>${this.error}</div>`:U}
      ${e.map(e=>this.renderEntry(e))}
    </div>`}},customElements.define(`openclaw-chat-outbox-recovery`,ux)})))()}function fx(e,t){let n=1,r=t.length;if(r>mx)return!1;for(let t of e){let e=t.browserAnnotation;if(e&&(n+=1,r+=e.modelContext.length,n>px||r>mx))return!1}return!0}var px,mx;function hx(){return(hx=e((()=>{px=4,mx=8e3})))()}function gx(e,t,n){if(!t.browserAnnotation)return!1;let r=t.browserAnnotation.modelContext,i=e.getOwner(),a=e.getSessionKey(),o=e.getAttachments(),s=o.findIndex(e=>e.id===t.id);if(s<0)return!1;e.setAttachments(o.filter(e=>e.id!==t.id)),e.requestUpdate(),e.focusComposer();let c=!1,l=()=>{c||(c=!0,vt(t.id))};return Lt({message:n.removed,actionLabel:n.undo,onAction:()=>{if(c)return;if(e.getOwner()!==i||e.getSessionKey()!==a){l();return}let o=e.getAttachments();if(o.some(e=>e.id===t.id)){c=!0;return}if(!fx(o,r)){l(),Lt({message:n.undoUnavailable});return}c=!0;let u=[...o];u.splice(Math.min(s,o.length),0,t),e.setAttachments(u),e.requestUpdate(),e.focusRestoredAnnotation(t.id)},onDismiss:e=>{e!==`action`&&l()}})||l(),!0}function _x(){return(_x=e((()=>{Be(),il(),hx()})))()}function vx(e,t){return f(t)?E(e):A(e,t)}function yx(e,t){return bd(e).subscriptionGeneration===t.generation&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&e.connected&&e.sessionKey.trim()===t.requestedKey&&vx(e,t.requestedKey)===(t.requestedAgentId??null)}async function bx(e){let t=bd(e).pendingSubscriptionReleases;t.size!==0&&await Promise.all([...t].map(async n=>{try{await e.sessions.unsubscribeMessages(n),t.delete(n)}catch{}}))}async function xx(e,t,n){for(let r=0;r<Ex;r+=1)try{await e(t);return}catch(e){if(n?.()||r+1===Ex)throw e;await Va(Tx*2**r)}}function Sx(e){let t=bd(e);t.subscriptionGeneration+=1,t.subscriptionRetry?.abort(),delete t.subscriptionRetry,Hd(e,`subscription`,!1),t.subscriptionReady=Promise.resolve(!1);let n=new Set(t.pendingSubscriptionReleases);t.pendingSubscriptionReleases.clear(),e.chatSessionMessageSubscription&&n.add(e.chatSessionMessageSubscription),e.chatSessionMessageSubscriptionRequestedKey=null,e.chatSessionMessageSubscription=null,e.chatSessionApprovalQueue=[];let r=e.sessions;if(!r?.unsubscribeMessages)return;let i=r.unsubscribeMessages.bind(r);for(let e of n)xx(i,e).catch(()=>void 0)}function Cx(e,t){let n=bd(e),r=e.client,i=e.connectionEpoch,a=e.sessionKey.trim(),o=vx(e,a);n.subscriptionRetry?.abort();let s=new AbortController;n.subscriptionRetry=s;let c=wx(e,s.signal,t).finally(()=>{n.subscriptionRetry===s&&(delete n.subscriptionRetry,Hd(e,`subscription`,!1))}),l=n.subscriptionGeneration,u=c.then(t=>t&&r!==null&&yx(e,{generation:l,client:r,connectionEpoch:i,requestedKey:a,requestedAgentId:o})&&e.chatSessionMessageSubscriptionRequestedKey===a&&e.chatSessionMessageSubscription!=null);return n.subscriptionReady=u,u}async function wx(e,t,n){if(!e.client||!e.connected)return!1;let r=e.client,i=e.sessions,a=Date.now()+Yp,o=e.connectionEpoch,s=e.sessionKey.trim();if(!s)return!1;let c=Ha(e.chatSessionMessageSubscriptionRequestedKey),l=e.chatSessionMessageSubscription??null,u=Ha(l?.key),d=c??u,f=vx(e,s),p=f!==null&&d===s&&(l?.agentId??null)!==f;p&&(e.chatSessionApprovalQueue=[],e.requestUpdate?.());let m=bd(e),h=++m.subscriptionGeneration;await bx(e);let g=d!==null&&d!==s,_=n?.force===!0||g||p,v=l!==null&&_,y=_||u===null||c===null,b=()=>!t.aborted&&e.sessions===i&&yx(e,{generation:h,client:r,connectionEpoch:o,requestedKey:s,requestedAgentId:f}),x=()=>{let t=m.subscriptionError;!t||m.pendingSubscriptionReleases.size>0||(m.subscriptionError=void 0,m.historyLoad.phase===`failed`&&m.historyLoad.message===t&&rm(e,{phase:`idle`}),e.requestUpdate?.())},S=t=>{let n=Pf(t);m.subscriptionError=n;let r=m.historyLoad;rm(e,{phase:`failed`,sessionKey:s,requestAgentId:C(e,s)?Ne(e):void 0,startup:r.phase!==`idle`&&`startup`in r?r.startup:!m.acceptedHistory,message:n,retryable:Op(t,`sessions.messages.subscribe`)}),e.requestUpdate?.()},w=async()=>{let n=0;for(;b();)try{return await i.subscribeMessages(s,{agentId:f??void 0,...Ln(e.hello?.auth??null)?{includeApprovals:!0}:{}})}catch(r){if(!b()||!Op(r,`sessions.messages.subscribe`))throw r;let i=a-Date.now();if(i<=0)throw r;if(Hd(e,`subscription`,!0),await Va(Math.min(Ie(r,n++),i),t),!b())return null;if(Date.now()>=a)throw r}return null};if(!v&&!y)return b()&&l&&z(l.key,s)&&(l.agentId??null)===f&&x(),b()&&l!==null;try{let t=v&&l?i.unsubscribeMessages(l):Promise.resolve(),n=y&&b()?w():Promise.resolve(null),[r,a]=await Promise.allSettled([t,n]);if(r.status===`rejected`){if(a.status===`fulfilled`&&a.value)try{await xx(i.unsubscribeMessages.bind(i),a.value,b)}catch(t){return b()?(l&&m.pendingSubscriptionReleases.add(l),e.chatSessionMessageSubscriptionRequestedKey=s,e.chatSessionMessageSubscription=a.value,S(`${B(r.reason)}; replacement release failed: ${B(t)}`),!0):(m.pendingSubscriptionReleases.add(a.value),!1)}return b()&&S(r.reason),!1}let o=a.status===`fulfilled`?a.value:null;if(!o){if(b()&&v&&(e.chatSessionMessageSubscriptionRequestedKey=null,e.chatSessionMessageSubscription=null),a.status===`rejected`)throw a.reason;return!1}if(!b()){try{await xx(i.unsubscribeMessages.bind(i),o)}catch{m.pendingSubscriptionReleases.add(o)}return!1}return e.chatSessionMessageSubscriptionRequestedKey=s,e.chatSessionMessageSubscription=o,e.chatSessionApprovalQueue=o.includeApprovals?o_(o.approvalReplay,o.key,o.agentId??void 0):[],x(),!0}catch(e){return b()&&S(e),!1}}var Tx,Ex;function Dx(){return(Dx=e((()=>{Za(),Tr(),zt(),g(),R(),Od(),af(),l_(),Tx=250,Ex=3})))()}function Ox(e,t,n){return{owner:n,paneId:e,scopeKey:mt(I(t,t.sessionKey))}}function kx(e,t,n,r){let i=e.chatAttachmentHandoff.consume(Ox(t,n,r));if(!i)return;let a=i.draftRevision===void 0||i.draftRevision>=ac(n,n.sessionKey).revisions.latestAttempt;a&&i.draftRevision!==void 0&&(n.chatMessage=i.message??``,n.chatMentions=i.mentions,n.chatGoalDraftMode=i.goalMode??null,n.chatReplyTarget=i.replyTarget??null);let o=new Set(n.chatAttachments.map(e=>e.id));n.chatAttachments=[...n.chatAttachments,...a?i.attachments.filter(e=>!o.has(e.id)):[]];let s=Object.entries(i.fallbacks).filter(([e])=>Object.hasOwn(n.chatComposerFallbackByScope,e)).flatMap(([,e])=>e.attachments);n.chatComposerFallbackByScope={...i.fallbacks,...n.chatComposerFallbackByScope};let c=n.chatComposerFallbackByScope[Ox(t,n,r).scopeKey];a&&c?.storageFailed&&(n.lastError=Hm,n.chatError=Hm),Xc([...s,...a?[]:i.attachments],[n.chatAttachments,...Object.values(n.chatComposerFallbackByScope).map(e=>e.attachments)])}function Ax(e,t,n,r,i,a){if(a&&!mh({...n,connected:!1},a))return;let o=[...n.chatAttachments];e.chatAttachmentHandoff.prepare({reviewPrivateDraft:wd,...Ox(t,n,r),attachments:o,fallbacks:n.chatComposerFallbackByScope,message:n.chatMessage,mentions:n.chatMentions,goalMode:n.chatGoalDraftMode,replyTarget:n.chatReplyTarget,draftRevision:i,incognito:Us(n,I(n,n.sessionKey))})}function jx(e){if(e){At(e.chatAttachments);for(let t of Object.values(e.chatComposerFallbackByScope))At(t.attachments),t.attachments=[];e.chatAttachments=[]}}function Mx(e,t,n,r,i){if(!i||r===i)return r;if(n){let e=e=>(At(e.filter(e=>e.browserAnnotation)),e.filter(e=>!e.browserAnnotation));n.chatAttachments=e(n.chatAttachments);for(let t of Object.values(n.chatComposerFallbackByScope))t.attachments=e(t.attachments);n.requestUpdate?.()}return e.chatAttachmentHandoff.clearPane(t),i}function Nx(e,t,n){let r=new Set(wg(t,n).map(e=>e.id));for(let t of e.querySelectorAll(`openclaw-chat-pane`))r.has(t.paneId)&&t.resumeStagedAttachments?.()}var Px,Fx;function Ix(){return(Ix=e((()=>{pa(),R(),il(),Cf(),du(),pc(),Nv(),Px=new WeakMap,Fx=class{constructor(e,t){this.context=e,this.host=t,this.ownsComposer=!0,this.custody=Symbol(`chat-composer-custody`);let n=Px.get(e);n||(n=new Set,Px.set(e,n)),this.presentations=n,this.scope=this.currentScope(),n.add(this)}claim(){if(!this.host.presented())return;let e=this.currentScope();this.otherRegion(e).find(e=>e.ownsComposer)?.transferTo(this),this.ownsComposer||=(this.host.resume(!0),!0),this.scope=e,this.presentations.delete(this),this.presentations.add(this)}captureOwner(){let e=this.currentScope();if(!e)return;let t=this.custody;return{resolveOwner:()=>{let n=[this,...[...this.presentations].toReversed()];for(let r of n){if(!this.presentations.has(r)||!r.ownsComposer||r.custody!==t)continue;let n=r.currentScope();if(n&&(n.owner===e.owner||n.owner.recoveryScopeReady)&&r.matchesScope({...e,owner:n.owner}))return r.host.state()}},retainedAttachmentIds:e=>this.context.chatAttachmentHandoff.retainedAttachmentIds(e)}}dispose(){if(this.ownsComposer){let e=this.otherRegion(this.currentScope()),t=e.find(e=>e.host.presented())??e[0];t&&this.transferTo(t)}this.presentations.delete(this)}currentScope(){let e=this.host.state(),t=this.host.presentationOwner();if(e&&t?.recoveryScope&&!mh({...e,connected:!1},t))return null;let n=this.host.owner(),r=n?.recoveryScope;return e&&n&&e.client===n&&r?{owner:n,gatewayOwner:oa(e.settings.gatewayUrl).gatewayOwner,recoveryScope:r,scopeKey:mt(I(e,e.sessionKey))}:null}otherRegion(e){return[...this.presentations].toReversed().filter(t=>t.host.region()!==this.host.region()&&t.matchesScope(e))}matchesScope(e){let t=this.scope,n=this.currentScope();return!!(e&&t&&n&&n.owner===e.owner&&t.gatewayOwner===e.gatewayOwner&&t.recoveryScope===e.recoveryScope&&t.scopeKey===e.scopeKey&&(n.owner===t.owner||n.owner.recoveryScopeReady)&&n.gatewayOwner===t.gatewayOwner&&n.recoveryScope===t.recoveryScope&&n.scopeKey===t.scopeKey)}transferTo(e){let t=this.host.state(),n=e.host.state();if(!t||!n||!this.matchesScope(e.currentScope()))return;this.host.pause(),e.host.pause();let r=t.chatAttachments,i=t.chatComposerFallbackByScope;Xc([n.chatAttachments,...Object.values(n.chatComposerFallbackByScope).map(e=>e.attachments)].flat(),[r,...Object.values(i).map(e=>e.attachments)]),n.chatMessage=t.chatMessage,n.chatMentions=t.chatMentions,n.chatGoalDraftMode=t.chatGoalDraftMode,n.chatReplyTarget=t.chatReplyTarget,n.chatQueuedEdit=t.chatQueuedEdit,n.chatAttachments=r,n.chatComposerFallbackByScope=i,t.chatMessage=``,t.chatMentions=[],t.chatGoalDraftMode=null,t.chatReplyTarget=null,t.chatQueuedEdit=null,t.chatAttachments=[],t.chatComposerFallbackByScope={},e.host.adoptAttachmentReads(this.host.takeAttachmentReads()),this.ownsComposer=!1,e.ownsComposer=!0,e.custody=this.custody,e.scope=e.currentScope(),e.host.resume(),t.requestUpdate?.(),n.requestUpdate?.()}}})))()}function Lx(e){e.updateComplete.then(()=>{e.querySelector(pm)?.focus({preventScroll:!0})})}function Rx(e,t,n,r){if(!e||!t||n.defaultPrevented||!(n instanceof CustomEvent))return!1;if(!$e(e.uploadConfig))return Lt({message:tt()}),!1;let i=n.detail;if(!i||typeof i.modelContext!=`string`||typeof i.dataUrl!=`string`||!i.card)return!1;if(!fx(e.chatAttachments,i.modelContext))return n.rejection=`limit`,!1;let a=Jl(i.dataUrl,i.fileName||`annotation`,sf(e.hello?.policy),eu(e.chatAttachments)+r);return a?(n.preventDefault(),e.chatAttachments=[...e.chatAttachments,{...a,browserAnnotation:{modelContext:i.modelContext,title:i.card.title,displayUrl:i.card.displayUrl,markedRegionCount:i.card.markedRegionCount,inspectedElement:i.card.inspectedElement}}],e.requestUpdate?.(),!0):!1}function zx(){return(zx=e((()=>{Be(),pt(),hx(),pp(),Es(),gl()})))()}var Bx;function Vx(){return(Vx=e((()=>{ds(),zv(),sy(),F(),_a(),Ah(),Oh(),pt(),il(),Es(),Dc(),gi(),Bx=class{constructor(e){this.options=e}subscribe(){let e=this.options.element,t=(t,n)=>(e.addEventListener(t,n),()=>e.removeEventListener(t,n)),n=[t(Qv,e=>this.receiveResourceMention(e)),t(ty,e=>this.receiveMessage(e)),t(ey,e=>this.receiveFile(e)),t(ay,e=>this.receiveContext(e)),t(Ko,e=>this.receiveOpen(e)),t(ry,e=>this.receiveWidgetPrompt(e))];return()=>n.forEach(e=>e())}syncLaunch(){let e=this.options.current(),t=e?.launch;e&&t&&this.openedLaunch!==t&&t.owner===e.context.gateway.snapshot.client&&t.sessionKey===e.state.sessionKey&&(this.openedLaunch=t,this.openLaunch(e,t))}openLaunch(e,t,n=``){e.state.handleOpenSidebar({kind:`mcp-app`,title:t.entrypoint.title,launch:t,fileTab:{id:`mcp-app:${t.serverName}/${t.entrypoint.toolName}:${t.settings?`settings`:`app`}${n}`,label:t.entrypoint.title}})}presentedEventOwner(e){if(!(e instanceof CustomEvent)||e.defaultPrevented)return null;let t=this.options.current();return t?.presented&&e.detail.sessionKey===t.state.sessionKey?t:null}receiveWidgetPrompt(e){let t=e.detail,n=typeof t?.text==`string`?t.text.trim():``;n&&this.options.current()?.state.handleSendChat(n)}receiveResourceMention(e){let t=this.presentedEventOwner(e);if(!t||!$e(t.state.uploadConfig))return;let n=e.detail,r=t.state,{resource:i}=n,a=i.title||i.name,o=JSON.stringify({serverName:n.serverName,resource:i},null,2),s=new File([o],`${a.replace(/[\\/]/gu,`-`)}.txt`,{type:`text/plain`});if(!ed([s],sf(r.hello?.policy),eu(r.chatAttachments)).length)return;e.preventDefault();let c=Gp({attachment:{id:Gu(),mimeType:s.type,fileName:s.name,sizeBytes:s.size,origin:`file`},dataUrl:Ku(o),file:s});r.chatAttachments=[...r.chatAttachments,c],r.requestUpdate()}receiveMessage(e){let t=this.presentedEventOwner(e);if(!t)return;let n=e.detail,{state:r,context:i}=t;e.preventDefault(),(async()=>{if(n.target===`new`)return wh(i,r.assistantAgentId||t.agentId||``,n);let e=jh(n.content,i),a=!1;try{return await r.handleSendChat(e.text,{attachmentsOverride:e.attachments,onOutboxAdmitted:()=>{a=!0}}),a}finally{a||At(e.attachments)}})().then(n.respond,()=>n.respond(!1))}receiveFile(e){let t=this.presentedEventOwner(e);if(!t)return;let n=e.detail;e.preventDefault(),t.openFile(n.path),n.respond(!0)}receiveContext(e){if(!(e instanceof CustomEvent))return;let t=e.detail,n=this.options.current(),r=n?.context.gateway.snapshot.client;if(!n||!r||t.sessionKey!==n.state.sessionKey)return;let i=e.composedPath().find(e=>e instanceof HTMLElement&&e.localName===`mcp-app-view`);i&&kh(r,{...t,agentId:n.state.assistantAgentId??void 0,title:i.title||V(`mcpApp.title`)})}receiveOpen(e){let t=this.presentedEventOwner(e),n=e.detail;t&&n.owner===t.context.gateway.snapshot.client&&(e.preventDefault(),this.openLaunch(t,n,`:${n.filePath??``}`))}}})))()}function Hx(e,t,n=()=>!0){return{slot:e,combo:t,available:n}}var Ux;function Wx(){return(Wx=e((()=>{oe(),Ux={terminal:Hx(`terminal`,_e.terminalPanel,e=>e.state?.terminalAvailable===!0),browser:Hx(`browser`,_e.browserPanel,e=>e.state?.browserPanelAvailable===!0),workspace:Hx(`workspace`,_e.workspaceFiles),companion:Hx(`companion`,_e.sideChat),desktop:Hx(`desktop`,_e.desktopPanel,e=>e.desktopAvailable===!0),discussion:Hx(`discussion`,_e.discussionPanel,e=>e.discussion!=null&&e.discussionAvailable===!0),dashboard:Hx(`dashboard`,_e.dashboardPanel,e=>e.dashboardAvailable()),detail:Hx(`detail`,_e.reviewPanel),conversation:void 0,"link-reader":void 0,portal:void 0,subagents:void 0,processes:void 0}})))()}function Gx(e,t,n){let r=Bt(t)?.agentId??n?.trim();if(L(t)){r&&e.agentSelection.set(r,{background:!0});return}let i=be(t,e.gateway.snapshot.hello),a=Nn();(a.sessionKey!==i||a.lastActiveSessionKey!==i)&&wr({sessionKey:i,lastActiveSessionKey:i}),(e.gateway.snapshot.sessionKey!==i||r&&e.agentSelection.state.selectedId!==r)&&dn({selection:e.agentSelection,gateway:e.gateway,sessionKey:i,agentId:r,background:!0})}function Kx(e){return!e.chatLoading&&!e.chatSending&&!e.chatRunId&&e.chatStream===null&&(e.chatQueue.length===0||yp(e))}function Z(e){let t=(e.sessionsResult?.sessions??[]).find(t=>Nt(e,t.key,e.sessionKey,t.agentId));if(!t||!f(t.key))return t;let n=Y(e);if(!(e.sessionsResultAgentId&&yo(e.sessionsResultAgentId)!==n))return t.observerDigest?.agentId&&yo(t.observerDigest.agentId)!==n?{...t,observerDigest:void 0}:t}function qx(e){let t=Y(e);if(e.chatAvatarUrl)return e.chatAvatarUrl;let n=es({agentId:t}).avatar;if(n)return n;let r=(e.chatAvatarStatus??e.assistantAvatarStatus)===`none`&&(e.chatAvatarReason??e.assistantAvatarReason)===`missing`,i=e.assistantAvatar;if(!r&&i&&Ye(i)&&e.assistantAgentId===t)return i;let a=e.agentsList?.agents?.find(e=>e.id===t)?.identity,o=a?.avatarUrl??a?.avatar;return typeof o==`string`&&Ye(o)?o:null}function Q(){return(Q=e((()=>{Tn(),as(),Jn(),It(),_t(),Ue(),R(),zm(),af()})))()}function Jx(e,t,n){if(n!==`dashboard`)return dv(t,n);let r=Nn().sidebarSessionLayouts?.[a(e,e.sessionKey)],i=r?r.dashboardPresentationOverride:null,o={...t,dashboardPresentationOverride:i};return r&&i===void 0?dv(o,n):ev(o,i??Z(e)?.boardPresentation??`split`)}function Yx(e,t){t===`workspace`&&Rg(e)}function Xx(e){let{state:t,sidebarLayout:n}=e,r=e=>Ae(n,e),i=r=>{e.updateSidebarLayout(Jx(t,n,r)),r===`companion`&&e.setObserverVisibility(!0)},a=r=>{r===`companion`&&e.setObserverVisibility(!1),Yx(t,r),e.updateSidebarLayout(O_(n,r))},o=e=>r(e)?a(e):i(e);return{closePanelSlot:a,openPanelSlot:i,sessionWorkspace:{...j_(t,{draftScope:e.presentationId,draftContext:{sessionTitle:e.sessionTitle,paneLabel:e.paneLabel},expanded:Ae(n,`workspace`),presented:e.presented}),collapsed:!r(`workspace`),onToggleCollapsed:()=>o(`workspace`),onToggleTerminal:t.terminalAvailable?()=>o(`terminal`):void 0,onToggleBrowser:t.browserPanelAvailable?()=>o(`browser`):void 0,onToggleDesktop:nr(e.gatewaySnapshot)?()=>o(`desktop`):void 0}}}function Zx(){return(Zx=e((()=>{Fn(),Jn(),R(),Q(),Ng(),ov(),vv()})))()}var Qx,$x,eS,tS;function nS(){return(nS=e((()=>{zf(),R(),pp(),Nv(),Qx=`openclaw:queued-edit-retention-change`,$x=3,eS=5e3,tS=class{constructor(e,t){this.host=e,this.bindings=t,this.sessionsByPane=new Map,this.unbound=new Set,this.pendingAtFocus=new WeakSet,this.preview=null,this.refreshRetention=()=>{this.host.requestUpdate()},this.removeSession=(e,t,n,r=!1)=>{let i=this.bindings.context();if(i&&cr(i,t)){this.host.requestUpdate();return}let a=this.findPane(e,t);r||a?.discardStagedAttachments?.();let o=this.sessionsByPane.get(e),s=o&&[...o.keys()].find(e=>z(e,t));s!==void 0&&o?.delete(s),i&&!r&&op(i,e,t),this.preview?.paneId===e&&z(this.preview.sessionKey,t)&&this.cancelPreview();let c=Gg(this.bindings.layout(),e)?.pane.sessionKey;c&&z(c,t)?this.bindings.selectReplacement(e,t,n):this.host.requestUpdate()},this.handleNavigationIntent=e=>{if(!(e instanceof CustomEvent)||(this.cancelPreview(),!this.bindings.presented()))return;let t=e.detail,n=this.bindings.layout(),r=Gg(n,n.activePaneId)?.pane;if(window.location.href!==this.bindings.routeHref()&&(!r||!this.unbound.has(r.id)))return;if(r&&this.unbound.has(r.id)&&(!f(t.sessionKey)||t.agentId)){e.preventDefault(),t.commit()&&this.bindings.presented()&&this.bindings.layout()===n&&this.bindings.adoptNavigation(r.id,t.sessionKey,t.agentId);return}let i=[...this.sessionsByPane.get(r?.id??``)?.keys()??[]].find(e=>z(e,t.sessionKey));if(!r||!i||this.findPane(r.id,i)?.routeFace!==t.face||z(r.sessionKey,i))return;this.present(r.id,i,!0);let a={...t,href:window.location.href,paneId:r.id,sessionKey:i};this.preview=a,this.previewFrame=requestAnimationFrame(()=>{this.preview===a&&(this.previewFrame=requestAnimationFrame(()=>{this.previewFrame=void 0,this.preview===a&&(window.location.href!==a.href||!a.commit())&&this.cancelPreview()}))}),this.previewTimer=window.setTimeout(this.cancelPreview,eS),e.preventDefault()},this.cancelPreview=()=>{let e=this.bindings.layout(),t=this.preview?.paneId??e.activePaneId;this.previewFrame!==void 0&&(cancelAnimationFrame(this.previewFrame),this.previewFrame=void 0),this.previewTimer!==void 0&&(window.clearTimeout(this.previewTimer),this.previewTimer=void 0),this.preview=null;let n=Gg(e,t)?.pane;n&&this.present(n.id,n.sessionKey)}}get unboundPaneIds(){return this.unbound}restore(e){this.unbound.clear(),this.pendingAtFocus=new WeakSet;for(let t of e)f(t.sessionKey)&&this.unbound.add(t.id);this.unbound.has(this.bindings.layout().activePaneId)&&this.capturePendingNavigation()}bindPane(e){this.unbound.delete(e)}capturePendingNavigation(){let e=this.bindings.context();if(!e)return;let{matches:t,pendingMatches:n}=e.router.getState();this.pendingAtFocus=new WeakSet([...t,...n].filter(e=>e.isFetching||e.status===`pending`).map(e=>e.abortController))}wasPendingAtFocus(){return this.bindings.context()?.router.getState().matches.some(e=>this.pendingAtFocus.has(e.abortController))===!0}connect(){this.host.addEventListener(Qx,this.refreshRetention),window.addEventListener(`popstate`,this.cancelPreview),window.addEventListener(Sp,this.handleNavigationIntent)}disconnect(){this.sessionsByPane.clear(),this.unbound.clear(),this.pendingAtFocus=new WeakSet,this.host.removeEventListener(Qx,this.refreshRetention),window.removeEventListener(`popstate`,this.cancelPreview),window.removeEventListener(Sp,this.handleNavigationIntent),this.cancelPreview()}suspend(){this.cancelPreview()}settleRoute(){this.preview&&this.cancelPreview()}retain(e){for(let t of this.unbound)e.some(e=>e.id===t&&f(e.sessionKey))||this.unbound.delete(t);let t=e.filter(e=>!this.unbound.has(e.id)),n=new Set(t.map(e=>e.id));for(let e of this.sessionsByPane.keys())n.has(e)||this.sessionsByPane.delete(e);return new Map(t.map(e=>[e.id,this.retainPane(e)]))}retainPane(e){let t=this.sessionsByPane.get(e.id);t||(t=new Map,this.sessionsByPane.set(e.id,t));let n=Array.from({length:$x},()=>void 0);for(let[e,r]of t)n[r]=e;let r=[...t.keys()].find(t=>t===e.sessionKey||z(t,e.sessionKey))??e.sessionKey,i=t.get(r);if(i===void 0){if(i=n.indexOf(void 0),i<0){let r=[...t].find(([t])=>!this.findPane(e.id,t)?.hasQueuedMessageEdit);if(r){let[n,a]=r;this.findPane(e.id,n)?.prepareForEviction?.(),t.delete(n),i=a}else i=n.length}n[i]=r}t.delete(r),t.set(r,i);for(let[i,a]of t){if(t.size<=$x)break;i===r||this.findPane(e.id,i)?.hasQueuedMessageEdit||(this.findPane(e.id,i)?.prepareForEviction?.(),t.delete(i),n[a]=void 0)}for(;n.length>$x&&n.at(-1)===void 0;)n.pop();return n}discardPane(e){for(let t of this.host.querySelectorAll(`openclaw-chat-pane`))t.paneId===e&&t.discardStagedAttachments?.();let t=this.bindings.context();t?.chatAttachmentHandoff.clearPane(e),this.unbound.delete(e),t&&Sm(t,e),this.sessionsByPane.delete(e)}findPane(e,t){return[...this.host.querySelectorAll(`openclaw-chat-pane`)].find(n=>n.paneId===e&&z(n.sessionKey??``,t))}present(e,t,n=!1){let r=wg(this.bindings.layout(),this.bindings.narrow()).some(t=>t.id===e);for(let i of this.host.querySelectorAll(`openclaw-chat-pane`)){if(i.paneId!==e)continue;let a=z(i.sessionKey??``,t),o=this.bindings.presented()&&r&&a;if(i.classList.toggle(`chat-pane-cache__pane--visible`,a),i.visuallyPresented=o,n){i.toggleAttribute(`inert`,!0);continue}i.toggleAttribute(`inert`,!o),i.setAttribute(`aria-hidden`,o?`false`:`true`),i.presented=o}}}})))()}function rS(e){if(e.restartingKey===e.row?.key)return{kind:`busy`,message:V(e.row?.repositoryWorkspaceId&&e.row.placement?.state!==`failed`?`sessionsView.dispatchingSession`:`sessionsView.restartingSession`)};if(e.reclaimingKey===e.row?.key)return{kind:`busy`,message:V(`sessionsView.stoppingSession`)};if(e.moving)return{kind:`busy`,message:V(`sessionsView.finishingSessionMove`)};if(e.workspaceResultReconciling)return{kind:`busy`,message:V(`sessionsView.syncingCloudFilesComposer`)};if(aS(e.row))return{kind:`dispatch-required`};switch(e.row?.placement?.state){case`requested`:case`provisioning`:case`syncing`:case`starting`:return{kind:`setup`,startup:{sessionKey:e.row.key,phase:e.row.placement.state,startedAt:e.row.placement.createdAtMs}};case`draining`:case`reconciling`:return{kind:`busy`,message:V(`sessionsView.finishingSessionMove`)};case`failed`:return{kind:`failed`,...e.row.placement.recoveryAction?{recoveryAction:e.row.placement.recoveryAction}:{}};default:return{kind:`ready`}}}function iS(e){let t=cS(e),n=e.workspaceResultReconciling&&e.row?.placement?.state===`active`&&!t.moving&&!t.restarting&&e.reclaimingKey!==e.row.key,r=rS({...e,moving:t.moving,workspaceResultReconciling:n}),i=r.kind===`setup`&&!e.startupPending,a=!e.startupPending&&r.kind===`busy`?r.message:null,o=e.row?.placement,s=!e.startupPending&&r.kind===`failed`&&o?.state===`failed`&&o.retryOnSend===!0,c=o&&`terminalReason`in o?o.terminalReason:void 0,l=o?.state===`failed`?o.recoveryError:c,u={state:r,blocksSend:r.kind!==`ready`&&!n&&!i&&!s,busyMessage:a,startup:r.kind===`setup`?r.startup:null,diskSpace:o?.state===`active`?o.diskSpace:void 0,workerRuntimeInstall:o?.state===`active`||o?.state===`provisioning`?o.workerRuntimeInstall:void 0,runError:l&&!t.restarting?{summary:V(`chat.cloudWorkerFailed`,{error:l})}:null,failedUnavailableMessage:V(`sessionsView.failedSessionUnavailable`)};if(e.startupPending||!e.row||s)return{...u,disabledBanner:void 0};let d=r.kind===`dispatch-required`;if(!d&&(r.kind!==`failed`||!r.recoveryAction))return{...u,disabledBanner:void 0};let f=d||r.recoveryAction===`restart`;return{...u,disabledBanner:{kind:`above-composer`,title:V(d?`sessionsView.repositoryWorkerRequiredTitle`:`sessionsView.failedSessionTitle`),text:V(d?`sessionsView.repositoryWorkerRequiredPrompt`:f?`sessionsView.failedSessionRestartPrompt`:`sessionsView.failedSessionStopPrompt`),icon:`warning`,actionLabel:V(d?`sessionsView.chooseWorker`:f?`sessionsView.restartSession`:`sessionsView.stopCloudWorker`),actionStyle:`primary`,disabledReason:f?t.recoveryDisabledReason:t.reclaimDisabledReason,onAction:f?e.onRecover:e.onReclaim}}}function aS(e){return!(!e?.repositoryWorkspaceId||e.placement&&e.placement.state!==`local`)}function oS(e,t){let n=e.placement,r=t?.phase===`failed`?void 0:t?.targetKind;n?.state===`active`&&(r=n.runner?.kind===`device`?`device`:`profile`);let i,a;if(r===`device`||r===`auto-device`)i=V(`sessionsView.runsOnDevice`),a=`sessionsView.stopDeviceWorker`;else if(r===`profile`){let e=n&&n.state!==`local`&&n.state!==`requested`?n:void 0;i=e?.providerId&&e.profileId?`${e.providerId} · ${e.profileId}`:V(`newSession.runsOn`,{place:V(`newSession.cloud`)}),a=`sessionsView.stopCloudWorker`}else i=V(`sessionsView.runsOnWorker`),a=`sessionsView.stopWorker`;return{label:i,stopLabel:V(a),confirmMessage:V(`${a}Confirm`,{session:e.label||e.key}),confirmLabel:V(`${a}ConfirmAction`)}}function sS(e){if(!e)return null;let t=e.placement;if(t&&t.state!==`local`){if(t.state!==`active`)return null;if(t.runner?.kind===`device`){let e=qa(t.runner.deviceId);return t.runner.status===`available`&&e?`node:${e}`:null}return qa(t.environmentId)??null}let n=qa(e.execNode);return n?`node:${n}`:`gateway`}function cS(e){let t=e.movingKey===e.row?.key||e.row?.placementMove!==void 0&&e.row.placementMove.error===void 0,n=e.reclaimingKey===e.row?.key,r=e.restartingKey===e.row?.key,i=$o(e.row?.placement),a=t=>b(e.gatewaySnapshot,{method:t,requiredScope:`operator.write`}),o=a(`sessions.move`),s=a(`sessions.reclaim`),c=a(`sessions.dispatch`),l=e.row?.placement?.state,u=aS(e.row),d=l===`failed`?e.row?.placement?.recoveryAction:void 0,f=l===`active`?e.row?.placement?.runner:void 0,p=f?.kind===`device`&&f.status===`offline`,m=t?V(`common.loading`):n||l!==`active`?V(`sessionsView.actionUnavailable`):o.allowed?void 0:o.reason,h=r?V(`common.loading`):t||n||!u&&d!==`restart`?V(`sessionsView.actionUnavailable`):e.row?.archived?V(`chat.archivedSessionDisabled`):c.allowed||!u&&s.allowed?void 0:c.reason;return{moving:t,restarting:r,moveDisabledReason:m,reclaimDisabledReason:n?V(`common.loading`):r?V(`sessionsView.actionUnavailable`):p?V(`sessionsView.offlineDeviceStopUnavailable`):i?.blocksActiveRun&&e.row?.hasActiveRun===!0?V(`sessionsView.activeRun`):i?s.allowed?void 0:s.reason:V(`sessionsView.actionUnavailable`),recoveryDisabledReason:h}}function lS(){return(lS=e((()=>{Lo(),F(),fa(),my(),Ce(),da(),hy()})))()}function uS(e){let t=e?.placement,n=t?.state===`active`?t.runner:void 0;return JSON.stringify([e?.sessionId,e?.execNode,e?.archived===!0,t?[t.state,t.generation,`environmentId`in t?t.environmentId:void 0,`activeOwnerEpoch`in t?t.activeOwnerEpoch:void 0,`providerId`in t?t.providerId:void 0,`profileId`in t?t.profileId:void 0,n?.kind,n?.deviceId,n?.status]:null])}function dS(e,t){return e.columns.some(e=>e.panels.some(e=>e.slot===t))}var fS;function pS(){return(pS=e((()=>{Fn(),ny(),Iv(),Vh(),_t(),Ue(),R(),lS(),vv(),fS=class{constructor(){this.owner=null,this.generation=0,this.pendingProbes=0,this.reconciliationFailed=!1}syncPane(e){let t=e.state(),n=t?.client,r=t?.sessionKey,i=t?.connectionEpoch,a=t?D(t,t.sessionKey).agentId:void 0,o=e.observation(),s=o?.row??void 0;this.sync(t&&n&&r&&t.connected&&o?.isCurrent()&&e.isPresented()&&!L(r)?{client:n,sessions:t.sessions,observation:o,sessionKey:r,agentId:a,connectionEpoch:t.connectionEpoch,desktopAvailable:nr(e.gateway),browserAvailable:_r(e.gateway),placement:s?.placement,sessionId:s?.sessionId,execNode:s?.execNode,archived:s?.archived,browserTab:[...Hh(t.chatMessages,t.chatToolMessages).values()].at(-1),layout:()=>t.sidebarLayout,commit:(t,n)=>e.commit(t,n),requestUpdate:()=>e.requestUpdate(),isCurrent:()=>e.isConnected()&&e.state()===t&&t.client===n&&t.sessionKey===r&&D(t,t.sessionKey).agentId===a&&t.connectionEpoch===i&&t.connected&&e.observation()===o&&o.isCurrent()&&uS(o.row??void 0)===uS(s)&&e.isPresented()}:null)}invalidate(){this.generation+=1,this.signature=void 0,this.pendingProbes=0,this.reconciliation=void 0,this.reconciliationFailed=!1,this.probeCurrent=void 0,this.requestProbeUpdate=void 0}reconcileObservation(e){let t=this.owner;if(!t?.isCurrent()||!t.observation.isCurrent())return;let n=t.layout(),r=t.desktopAvailable&&(this.desktop!==void 0||!dS(n,`desktop`)),i=!this.dismissed(n)&&t.browserAvailable&&t.browserTab!==void 0;(r||i)&&this.reconcile(async()=>(await this.readSession(t),e.requestUpdate(),await e.updated(),t.observation.isCurrent()))}readSession(e){let t=this.descriptorRead;if(t?.observation===e.observation&&t.current())return t.promise;let n=this.generation,r=()=>n===this.generation&&e.isCurrent()&&e.observation.isCurrent(),i={observation:e.observation,current:r,promise:Promise.resolve(null)};return i.promise=(async()=>{for(;r();){let t=e.observation.captureReconcile(),{session:n}=await e.sessions.describe({key:e.sessionKey,...e.agentId?{agentId:e.agentId}:{}},{client:e.client});if(!r())return null;let i=t(n??void 0);if(i.status===`current`)return i.row;if(i.status===`retired`)return null}return null})().finally(()=>{this.descriptorRead===i&&(this.descriptorRead=void 0)}),this.descriptorRead=i,i.promise}reconcile(e){let t=this.probeCurrent;if(!t?.())return;let n=this.reconciliationFailed&&this.pendingProbes===0,r=this.requestProbeUpdate,i=Promise.resolve().then(()=>t()?e():!1).catch(()=>!1);this.reconciliation=i,this.reconciliationFailed=!1,i.then(e=>{this.reconciliation===i&&(this.reconciliationFailed=!e,!e&&this.desktop&&(this.desktop.source=null,r?.()),e&&(this.reconciliation=void 0,n&&t()&&this.pendingProbes===0&&(this.signature=void 0,r?.())))})}async afterReconciliation(e,t){let n;for(;e()&&(n=this.reconciliation);){let e=await n;if(this.reconciliation===n&&!e)return}return e()?t():void 0}trackProbe(e,t){this.pendingProbes+=1,e.finally(()=>{this.generation===t&&--this.pendingProbes})}desktopSource(e,t,n,r,i){if(this.desktop?.sessionKey===t&&this.desktop.agentId===n)return this.desktop.client===e&&this.desktop.observation.isCurrent()&&this.desktop.connectionEpoch===r&&this.desktop.resourceIdentity===uS(i)?this.desktop.source:null}sync(e){let t=this.owner;if(this.owner=e,!e){this.invalidate();return}let n=uS(e),r=JSON.stringify([e.sessionKey,e.agentId,e.connectionEpoch,n,e.desktopAvailable,e.browserAvailable,e.browserTab,e.layout().resourceAutoOpenDismissed]);if(this.client===e.client&&this.signature===r&&t?.observation===e.observation)return;(this.reconciliationFailed||this.probeCurrent&&!this.probeCurrent())&&(this.reconciliation=void 0,this.reconciliationFailed=!1),this.client=e.client,this.signature=r;let i=++this.generation;this.pendingProbes=0,this.desktop&&(this.desktop.sessionKey!==e.sessionKey||this.desktop.agentId!==e.agentId?this.desktop=void 0:(this.desktop.client!==e.client||this.desktop.connectionEpoch!==e.connectionEpoch||this.desktop.resourceIdentity!==n)&&(this.desktop={...this.desktop,client:e.client,connectionEpoch:e.connectionEpoch,resourceIdentity:n,source:null}));let a=dS(e.layout(),`desktop`);if(this.dismissed(e.layout())&&(!this.desktop||!a)){this.desktop=void 0;return}let o=()=>i===this.generation&&e.isCurrent()&&(!this.dismissed(e.layout())||this.desktop!==void 0&&dS(e.layout(),`desktop`));this.probeCurrent=o,this.requestProbeUpdate=e.requestUpdate,e.desktopAvailable&&(this.desktop||!a)&&this.trackProbe(this.discoverDesktop(e,o),i),!this.dismissed(e.layout())&&e.browserAvailable&&e.browserTab&&this.trackProbe(this.discoverBrowser(e,e.browserTab,o),i)}dismissed(e){return e.resourceAutoOpenDismissed===!0||e.open===!1&&Ze(e).some(e=>e.slot!==`conversation`)}publishDesktop(e,t){let n=dS(e.layout(),`desktop`);if(this.dismissed(e.layout())&&!n||!this.desktop&&(t===null||n))return;let r=this.desktop?.source!==t;this.desktop={client:e.client,observation:e.observation,sessionKey:e.sessionKey,agentId:e.agentId,connectionEpoch:e.connectionEpoch,resourceIdentity:uS(e),source:t},t!==null&&this.reveal(e,`desktop`),r&&e.requestUpdate()}reveal(e,t){let r=e.layout();if(this.dismissed(r)||dS(r,t))return;let i=dv(r,t);r.open&&Re(r)&&(i.columns[0].activePanelId=r.columns[0].activePanelId),n(r)?.slot!==void 0&&n(r)?.slot!==`conversation`&&(i.open=r.open),i.expanded=r.expanded,i.expandedSide=r.expandedSide,e.commit(i,t)}async discoverDesktop(e,t){try{let n=await this.readSession(e),r=await this.afterReconciliation(t,()=>{if(!n||!z(n.key,e.sessionKey)||n.archived){this.publishDesktop(e,null);return}let t=sS(n);if(!t||t===`gateway`||cy({id:t}).kind===`environment`&&!n.sessionId){this.publishDesktop(e,null);return}return t});if(!r)return;let i=await Zv(e.client,{target:Promise.resolve(r),isCurrent:t,recoverToPicker:!1});await this.afterReconciliation(t,()=>{let t=i?.environments.find(e=>e.id===r);if(!t||t.status!==`available`||t.desktop!==!0||t.type===`worker`&&(t.worker?.state!==`attached`||!n?.sessionId||!t.worker.attachedSessionIds.includes(n.sessionId))){this.publishDesktop(e,null);return}this.publishDesktop(e,r)})}catch{await this.afterReconciliation(t,()=>{this.publishDesktop(e,null)})}}async discoverBrowser(e,t,n){try{let r=await this.readSession(e);if(!r||r.archived)return;let i=await this.afterReconciliation(n,()=>Wv(Yv(e.client,t.tab,n)));await this.afterReconciliation(n,()=>{i?.running&&i.tabs.some(e=>e.targetId===t.tab.targetId&&!e.urlUnavailableReason)&&this.reveal(e,`browser`)})}catch{}}}})))()}async function mS(){return!customElements.get(`openclaw-board-view`)&&(gS??=_o(()=>import(`./board-view-DvSYdNVj.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([9,0,1,2,3,4,10,11,12,13,14,15,16,5,6,7,8,17,18,19,20]),import.meta.url),await gS,!0)}function hS(e){return W`
    <div
      class="board-session-surface"
      ?hidden=${Ge(e.active,!0)}
      ?inert=${Ge(e.active,!0)}
    >
      <div class="board-session-surface__board">
        <openclaw-board-view
          .active=${Ge(e.active)}
          .session=${e.session}
          .snapshot=${e.snapshot}
          .activeTabId=${e.activeTabId}
          .pageWidgetName=${e.pageWidgetName??``}
          .widgetFrameUrl=${e.widgetFrameUrl}
          .callbacks=${e.callbacks}
          .canMutate=${e.canMutate}
          .canGrant=${e.canGrant}
        ></openclaw-board-view>
        ${customElements.get(`openclaw-board-view`)?U:Xv(`board`,V(`common.loading`),!1,!0)}
      </div>
    </div>
  `}var gS;function _S(){return(_S=e((()=>{kr(),Bv(),F(),kt(),ho(),gS=null})))()}function vS(e){let t=J(e)?.messageId;return typeof t==`string`&&t?t:null}function yS(){return(yS=e((()=>{})))()}function bS(e){return(e?.appliedConfigHash??e?.configRevisionHash??e?.hash??null)||JSON.stringify(J(J(e?.runtimeConfig)?.mcp)?.servers??null)}var xS;function SS(){return(SS=e((()=>{kr(),Tr(),Rv(),fr(),Io(),F(),Zi(),Ee(),_i(),zt(),di(),Ce(),Ue(),R(),py(),Vf(),ef(),jl(),p_(),wi(),xS=class{constructor(e){this.notify=e,this.patchTokens=new Map,this.effectiveTools=null,this.effectiveToolsErrorKey=null,this.effectiveToolsRequest=null,this.client=null,this.addDialogOpen=!1,this.addScope=`session`,this.addBusy=!1,this.addError=null,this.skillCatalog=new qf(e),this.library=new s_(e)}effectiveToolsKeys(e,t,n){let r=ve({chatModelCatalog:t.chatModelCatalog,sessions:e.sessions,sessionsResult:t.sessionsResult},{agentId:n,sessionKey:t.sessionKey});return{cacheKey:`${r}\0config=${bS(e.runtimeConfig.state.configSnapshot??null)}`,requestKey:r}}loadEffectiveTools(e,t,n,r=!1){let i=t.client,a=t.sessionKey,{cacheKey:o,requestKey:s}=this.effectiveToolsKeys(e,t,n);if(!t.connected||!i||this.effectiveTools?.key===o||this.effectiveToolsRequest?.key===o||!r&&this.effectiveToolsErrorKey===o)return;let c={key:o},l=t.connectionEpoch;this.effectiveToolsRequest=c;let u={chatModelCatalog:t.chatModelCatalog,client:i,connected:!0,sessions:e.sessions,sessionsResult:t.sessionsResult,toolsEffectiveError:null,toolsEffectiveLoading:!1,toolsEffectiveLoadingKey:null,toolsEffectiveResult:null,toolsEffectiveResultKey:null},d=()=>this.effectiveToolsRequest===c&&this.client===i&&t.client===i&&t.connected&&this.connectionEpoch===l&&t.connectionEpoch===l&&t.sessionKey===a&&this.effectiveToolsKeys(e,t,n).cacheKey===o;this.effectiveToolsErrorKey=null,this.notify(),p(u,{agentId:n,sessionKey:a},{isCurrent:d}).then(()=>{d()&&(u.toolsEffectiveResult&&u.toolsEffectiveResultKey===s?this.effectiveTools={key:o,result:u.toolsEffectiveResult}:u.toolsEffectiveError&&(this.effectiveToolsErrorKey=o))}).catch(()=>{d()&&(this.effectiveToolsErrorKey=o)}).finally(()=>{this.effectiveToolsRequest===c&&(this.effectiveToolsRequest=null,this.client===i&&this.connectionEpoch===l&&this.notify())})}async patch(e,t,n){if(!t.connected||!t.client)return{ok:!1,error:V(`chat.composer.menu.offlineBlocked`)};let r=b(e.gateway.snapshot,{method:`sessions.patch`,params:{key:t.sessionKey,toolOverrides:n}});if(!r.allowed)return{ok:!1,error:r.reason};let i=t.sessionKey;if(this.patchTokens.has(i))return{ok:!1,error:V(`chat.composer.menu.savingBlocked`)};let a=t.client,o=Symbol(i);this.patchTokens.set(i,o);let s=()=>this.client===a&&t.client===a&&t.sessionKey===i&&this.patchTokens.get(i)===o;t.lastError=null,t.chatError=null,this.notify();try{if(!await _f(t,i,{toolOverrides:n},D(t,i)))throw Error(V(`chat.composer.menu.offlineBlocked`));return{ok:!0}}catch(e){let n=B(e);if(s()){try{await jp(t)}catch{}s()&&(t.lastError=n,t.chatError=n,t.requestUpdate?.())}return{ok:!1,error:n}}finally{this.patchTokens.get(i)===o&&(this.patchTokens.delete(i),this.client===a&&this.notify())}}closeAddDialog(){this.addBusy||(this.addDialogOpen=!1,this.addError=null,this.notify())}addServerBlockedReason(e,t,n,r){let i=En(e.gateway.snapshot);return!t.connected||!t.client?V(`chat.composer.menu.offlineBlocked`):i.canAdmin?r===`everywhere`?null:n?this.patchTokens.has(t.sessionKey)?V(`chat.composer.menu.savingBlocked`):null:V(`common.loading`):V(`chat.composer.menu.adminBlocked`)}async loadCurrentSessionOverrides(e,t,n){let r=()=>e.sessionKey===t&&wt(e,t).agentId===n;if(!r())return{ok:!1,error:V(`mcpServers.sessionChanged`)};try{await jp(e)}catch(e){return{ok:!1,error:B(e)}}if(!r())return{ok:!1,error:V(`mcpServers.sessionChanged`)};let i=e.sessions.state;if(i.error)return{ok:!1,error:i.error};let a=i.result?.sessions.find(e=>z(e.key,t));return!a||(i.agentId??void 0)!==n?{ok:!1,error:V(`mcpServers.sessionUnavailable`)}:{ok:!0,overrides:a.toolOverrides}}async submitAddServer(e,t,n,r){if(this.addBusy)return;let i=this.addServerBlockedReason(e,t,n,this.addScope);if(i){this.addError=i,this.notify();return}let a=r.name.trim();if(!Ei.test(a)){this.addError=V(`mcpServers.nameInvalid`),this.notify();return}let o=Xi(r.target,r.transport);if(!o){this.addError=V(`mcpServers.targetInvalid`),this.notify();return}this.addBusy=!0,this.addError=null,this.notify();let s=t.sessionKey,c=wt(t,s).agentId,l=this.addScope,u=l===`session`?{...o,enabled:!1}:o,d=`config`,f;try{let n=await Ti(e.runtimeConfig,{buildPatch:e=>Mi(e,a,u),note:`composer connectors: add MCP server ${a}`});if(!n.ok)f=n.error;else if(l===`session`){d=`session`;let n=await this.loadCurrentSessionOverrides(t,s,c);if(!n.ok)f=n.error;else{let r=Hc(n.overrides,`mcpServers`,a,!0,!1),i=await this.patch(e,t,r);i.ok||(f=i.error)}}}catch(e){f=B(e)}finally{this.addBusy=!1}if(f!==void 0){let e=We(f);this.addError=d===`session`?V(`mcpServers.sessionEnableFailed`,{error:e}):e,this.notify();return}this.addDialogOpen=!1,this.notify()}renderAddServerDialog(e,t,n){if(!this.addDialogOpen)return U;let r=this.addServerBlockedReason(e,t,n,`everywhere`),i=this.addServerBlockedReason(e,t,n,this.addScope),a=V(`chat.composer.menu.addMcpServerTitle`),o=V(`chat.composer.menu.addMcpServerDescription`),s=V(this.addScope===`session`?`chat.composer.menu.scopeSessionHint`:`chat.composer.menu.scopeEverywhereHint`);return W`
      <openclaw-modal-dialog
        label=${a}
        description=${o}
        @modal-cancel=${e=>{if(this.addBusy){e.preventDefault();return}this.closeAddDialog()}}
      >
        <div class="exec-approval-card mcp-server-dialog">
          <div class="exec-approval-header">
            <div>
              <div class="exec-approval-title">${a}</div>
              <div class="exec-approval-sub">${o}</div>
            </div>
          </div>
          <div class="mcp-server-dialog__scope">
            <span>${V(`chat.composer.menu.scopeLabel`)}</span>
            ${Qo({value:this.addScope,options:[{value:`session`,label:V(`chat.composer.menu.scopeSession`)},{value:`everywhere`,label:V(`chat.composer.menu.scopeEverywhere`)}],ariaLabel:V(`chat.composer.menu.scopeLabel`),disabled:this.addBusy||r!==null,onChange:e=>{this.addScope=e,this.addError=null,this.notify()}})}
            <span class="mcp-server-dialog__scope-hint">${s}</span>
          </div>
          ${Vv({busy:this.addBusy,disabled:i!==null,blockedReason:i,autofocus:!0,onSubmit:r=>void this.submitAddServer(e,t,n,r),onCancel:()=>this.closeAddDialog()})}
          ${this.addError?W`<div class="mcp-server-message mcp-server-message--error" role="alert">
                  ${this.addError}
                </div>`:U}
        </div>
      </openclaw-modal-dialog>
    `}props(e,t,n,r,i=!1,a=!1){(this.client!==t.client||this.connectionEpoch!==t.connectionEpoch)&&(this.client=t.client,this.connectionEpoch=t.connectionEpoch,this.skillCatalog.synchronize(t.client,t.connectionEpoch),this.patchTokens.clear(),this.effectiveTools=null,this.effectiveToolsErrorKey=null,this.effectiveToolsRequest=null);let o=t.client,s=t.connectionEpoch,c=t.sessionKey,l=()=>t.connected&&t.client===o&&t.connectionEpoch===s&&t.sessionKey===c;this.library.synchronize(o&&t.connected?{client:o,connectionEpoch:s,sessionKey:c,agentId:r,isCurrent:l}:null),a&&!this.library.result&&!this.library.loading&&!this.library.error&&this.library.load();let u=ui(e.gateway.snapshot,`skills.library.activate`,`operator.write`,{requireAdvertisement:!1}),d=e.runtimeConfig.state.configSnapshot?.runtimeConfig??null,f=En(e.gateway.snapshot),p=t.connected&&!!t.client,m=K(e.gateway.snapshot,`tools.effective`)===!0;m&&i&&this.loadEffectiveTools(e,t,r);let h=m?this.effectiveToolsKeys(e,t,r).cacheKey:null,g=h!==null&&this.effectiveTools?.key===h?this.effectiveTools.result:null,_=h!==null&&this.effectiveToolsRequest?.key===h,v=h!==null&&this.effectiveToolsErrorKey===h,y=p&&n!==void 0&&d!==null,x=b(e.gateway.snapshot,{method:`sessions.patch`,params:{key:t.sessionKey,toolOverrides:null}}),S=p?y?x.allowed?this.patchTokens.has(t.sessionKey)?V(`chat.composer.menu.savingBlocked`):null:x.reason:V(`common.loading`):V(`chat.composer.menu.offlineBlocked`),C=S??(g?null:V(v?`chat.composer.menu.toolAccess.loadFailed`:`common.loading`)),w=p?f.canAdmin?null:V(`chat.composer.menu.adminBlocked`):V(`chat.composer.menu.offlineBlocked`);return{basePath:t.basePath,skills:this.skillCatalog.rows(r,n?.toolOverrides),skillsLoading:this.skillCatalog.isLoading(r),skillsError:this.skillCatalog.hasError(r),mcpServers:Ji(d)??[],toolsEffectiveResult:g,toolsEffectiveLoading:_,toolsEffectiveError:v,toolAccessMutationBlockedReason:C,webSearchBaseEnabled:Cl(d),mutationBlockedReason:S,canAdmin:f.canAdmin&&p,adminBlockedReason:w,addServerDialog:this.renderAddServerDialog(e,t,n),library:{result:this.library.result,loading:this.library.loading,busy:this.library.busy,error:this.library.error,notice:this.library.notice,canWrite:u,onReload:()=>{l()&&this.library.load(!0)},onRead:(e,t)=>{l()&&this.library.openRead(e,t)},onActivate:(e,t,n)=>{l()&&u&&this.library.activate(e,t,n)}},libraryDialog:this.library.read?fy({read:this.library.read,file:this.library.selectedFile,onFile:e=>{this.library.selectedFile=e,this.notify()},onClose:()=>{this.library.closeRead(),this.notify()}}):U,onLoadSkills:()=>{if(!l())return;let n=e.runtimeConfig.state;!n.configSnapshot&&!n.configLoading&&e.runtimeConfig.ensureLoaded().catch(()=>void 0);let i=t.client,a=t.connectionEpoch;this.skillCatalog.load(i,a,r,()=>t.connected&&t.client===i&&t.connectionEpoch===a),this.library.load(!0)},onPatchToolOverrides:n=>void this.patch(e,t,n),onNavigate:(t,n)=>e.navigate(t,n),onAddServer:()=>{f.canAdmin&&p&&(this.addDialogOpen=!0,this.addScope=`session`,this.addError=null,this.notify())},...m?{onOpenToolAccess:()=>this.loadEffectiveTools(e,t,r,!0)}:{}}}}})))()}function CS(e){return e?[e.id,e.identity?.type,e.identity?.id,e.name,e.email,e.avatarUrl]:null}function wS(e,t){let{users:n}=Nf(e),r=Qn({snapshotUser:t.selfUser,presenceEntries:e?.presence,presenceInstanceId:t.selfInstanceId});return JSON.stringify([n.length>=2,CS(r),n.filter(e=>e.watchedSessions.includes(t.sessionKey)).map(CS)])}function TS(e,t,n){return e===t||wS(e,n)===wS(t,n)}function ES(){return(ES=e((()=>{lm()})))()}function DS(e,t){return t?(e.selectedChatSessionArchived=t.archived===!0,e.selectedChatSessionIncognito=t.incognito===!0,e.chatQueueModeOverride=t.queueMode,e.chatEffectiveQueueMode=t.effectiveQueueMode,!0):!1}function OS(e){e.lastError=null,e.chatError=null}function kS(e,t,n){let r=ks(e),i=t&&r.phase===`failed`?r.message:null,a=n?hc(e,e.sessionKey):null,o=sa(e.chatMessage);return{...a&&!o?{canSend:!1}:{},submitDisabledReason:a??(t?i??V(`chat.thread.loading`):null),submitPending:a!==null||t&&r.phase!==`failed`,onDraftChange:(...t)=>{e.handleChatDraftChange(...t),a&&o!==sa(e.chatMessage)&&e.requestUpdate?.()}}}function AS(e,t,n){return Uh(e.settings.chatFollowUpMode,Jh(n.configSnapshot?.runtimeConfig,{configNeedsApply:n.configNeedsApply,effectiveMode:e.chatEffectiveQueueMode,sessionMetadataLoaded:t!==void 0||e.chatEffectiveQueueMode!==void 0,sessionMode:e.chatQueueModeOverride}))}var jS,MS;function NS(){return(NS=e((()=>{F(),pi(),Yh(),af(),tp(),jS=256,MS=class{constructor(){this.lastBlocked=new Map}reset(){this.lastBlocked.clear()}resolve(e){if(e.catalog)return!1;if(e.session){let t=e.session.visibility===`draft`?e.session.sharingRole!==`admin`&&e.session.sharingRole!==`owner`:e.session.visibility!==void 0&&e.session.visibility!==`shared`&&e.session.sharingRole===`viewer`;if(this.lastBlocked.delete(e.sessionKey),this.lastBlocked.set(e.sessionKey,t),this.lastBlocked.size>jS){let e=this.lastBlocked.keys().next().value;e&&this.lastBlocked.delete(e)}return t}return e.listLoading&&this.lastBlocked.get(e.sessionKey)===!0}}})))()}function PS(){return{realtimeTalkActive:!1,realtimeTalkStatus:`idle`,realtimeTalkDetail:null,realtimeTalkInputNotice:null,realtimeTalkUseSystemDefault:null,realtimeTalkInputLevel:new tu,realtimeTalkVideoStream:null,realtimeTalkCameraDevices:[],realtimeTalkVideoCapable:!1,realtimeTalkVideoPending:!1,realtimeTalkCameraError:!1,realtimeTalkSession:null,realtimeTalkVoiceController:null,realtimeTalkConversationState:Og()}}function FS(e,t={}){let n=e.realtimeTalkSession;e.realtimeTalkVoiceController?.dispose(),e.realtimeTalkVoiceController=null,e.realtimeTalkSession=null,e.realtimeTalkUseSystemDefault=null,e.realtimeTalkActive=!1,e.realtimeTalkStatus=`idle`,e.realtimeTalkDetail=null,e.realtimeTalkInputNotice=null,e.realtimeTalkInputLevel.set(0),e.realtimeTalkVideoStream=null,e.realtimeTalkCameraDevices=[],e.realtimeTalkVideoCapable=!1,e.realtimeTalkVideoPending=!1,e.realtimeTalkCameraError=!1,e.realtimeTalkConversationState=t.preserveConversation?_g(e.realtimeTalkConversationState):Og(),n?.stop()}function IS(e){e.realtimeTalkStatus===`error`&&FS(e)}function LS(e,t=()=>!0){let n=0,r=()=>e.realtimeTalkStatus===`error`,i=t=>{e.settings=wr({talkCameraAutoEnable:t})},a=t=>{e.realtimeTalkDetail=B(t),e.realtimeTalkCameraError=!0,e.requestUpdate()},o=async t=>{let n=await wp(()=>!1);e.realtimeTalkSession===t&&(e.realtimeTalkCameraDevices=n.devices,e.requestUpdate())},s=async(t,n={})=>{let o=e.realtimeTalkSession;if(o&&e.realtimeTalkVideoCapable&&!e.realtimeTalkVideoPending&&!r()){e.realtimeTalkVideoPending=!0,e.realtimeTalkCameraError=!1,e.realtimeTalkDetail=null,e.requestUpdate(),t||i(!1);try{t&&await o.switchCamera(Nn().realtimeTalkVideoDeviceId),await o.setVideoEnabled(t)}catch(t){if(e.realtimeTalkSession!==o||r())return;n.disableAutoEnableOnFailure&&i(!1),e.realtimeTalkVideoStream=null,a(t)}finally{e.realtimeTalkSession===o&&(e.realtimeTalkVideoPending=!1,e.requestUpdate())}}};e.resetRealtimeTalkConversation=()=>{e.realtimeTalkConversationState=Og()};let c=async(l=!1,u)=>{if(e.realtimeTalkUseSystemDefault=null,!t())return;if(!e.client||!e.connected){e.lastError=`Gateway not connected`,e.chatError=e.lastError,e.requestUpdate();return}let d=Nn(),f=l?void 0:d.realtimeTalkInputDeviceId?.trim()||void 0,{client:p,sessionKey:m}=e,h=u?e.realtimeTalkSession?.getTransport():void 0;if(u&&!h)throw Error(V(`chat.voice.selectionFailed`));if(u){let r=e.realtimeTalkSession,i=e.realtimeTalkVoiceController;e.realtimeTalkSession=null;let a=r?.stop();if(e.realtimeTalkVideoStream=null,e.realtimeTalkCameraDevices=[],e.realtimeTalkConversationState=_g(e.realtimeTalkConversationState),n+=1,e.requestUpdate(),await a,e.realtimeTalkVoiceController!==i||e.client!==p||e.sessionKey!==m||!e.connected||!t())return}else{n=0,e.realtimeTalkVoiceController?.dispose();let t=new og({client:p,sessionKey:m,isCurrent:()=>e.realtimeTalkVoiceController===t&&e.client===p&&e.sessionKey===m&&e.connected,currentCall:()=>e.realtimeTalkSession,restart:e=>c(l,e),cancel:t=>{FS(e,{preserveConversation:!0}),e.realtimeTalkStatus=`error`,e.realtimeTalkDetail=t,e.requestUpdate()}});e.realtimeTalkVoiceController=t}let g=e.realtimeTalkVoiceController,_=u?`voice-${n}:`:``,v=u?e.realtimeTalkConversationState.entries.length:0,y=d.realtimeTalkVideoDeviceId?.trim()||void 0,b=d.talkCameraAutoEnable===!0,x=!1;e.realtimeTalkActive=!0,e.realtimeTalkStatus=`connecting`,e.realtimeTalkDetail=null,e.realtimeTalkInputNotice=null,e.realtimeTalkVideoCapable=!1,e.realtimeTalkVideoPending=!1,e.realtimeTalkCameraError=!1,e.realtimeTalkInputLevel.set(0),u||e.resetRealtimeTalkConversation();let S=t=>(...n)=>{e.realtimeTalkSession===C&&t(...n)},C=new bg(p,m,{onStatus:S((t,n)=>{e.realtimeTalkStatus=t,e.realtimeTalkDetail=t===`error`&&n?We(n):n??null,e.realtimeTalkCameraError=!1,e.realtimeTalkActive=t!==`idle`,(t===`idle`||t===`error`)&&(e.realtimeTalkInputNotice=null,e.realtimeTalkInputLevel.set(0)),e.requestUpdate(),t===`error`&&g?.failed(C),t===`listening`&&e.realtimeTalkVideoCapable&&b&&!x&&(x=!0,s(!0,{disableAutoEnableOnFailure:!0}))}),onInputNotice:S(t=>{e.realtimeTalkInputNotice=We(t),e.requestUpdate()}),onVideoCapability:S(t=>{e.realtimeTalkVideoCapable=t,e.requestUpdate()}),onInputLevel:S(t=>{e.realtimeTalkInputLevel.set(t)}),onTranscript:S(t=>{e.realtimeTalkConversationState=u_(e.realtimeTalkConversationState,t.itemId===void 0?t:{...t,itemId:`${_}${t.itemId}`,order:t.order===void 0?void 0:v+t.order}),e.requestUpdate()}),onTranscriptOrder:S(t=>{e.realtimeTalkConversationState=Tg(e.realtimeTalkConversationState,t.map(({itemId:e,order:t})=>({itemId:`${_}${e}`,order:v+t}))),e.requestUpdate()}),onVideoStream:S(t=>{if(t&&e.realtimeTalkStatus===`error`){C.setVideoEnabled(!1).catch(()=>void 0);return}e.realtimeTalkVideoStream=t,t&&(i(!0),e.realtimeTalkDetail=null,e.realtimeTalkCameraError=!1,o(C)),e.requestUpdate()}),onVideoError:S(e=>{r()||a(e)}),onTalkEvent:S(t=>{e.client===p&&e.sessionKey===m&&(t.type===`session.ready`?g?.ready(C):t.type===`session.closed`&&g?.failed(C))})},u?{voice:u.voice,voiceChangeId:u.changeId,transport:h}:{},{inputDeviceId:f,videoDeviceId:y});e.realtimeTalkSession=C;try{return await C.start(),e.realtimeTalkSession===C?C:void 0}catch(t){if(e.realtimeTalkSession!==C)return;if(u)throw t;let n=B(t);if(FS(e),e.realtimeTalkStatus=`error`,e.realtimeTalkDetail=n,t instanceof hm){let t=async()=>{if(e.realtimeTalkUseSystemDefault===t){if(e.realtimeTalkUseSystemDefault=null,!e.connected||e.client!==p||e.sessionKey!==m){e.requestUpdate();return}await c(!0)}};e.realtimeTalkUseSystemDefault=t}e.requestUpdate()}};e.toggleRealtimeTalk=async()=>{if(e.realtimeTalkSession||e.realtimeTalkActive){FS(e),e.requestUpdate();return}await c()},e.toggleRealtimeTalkCamera=async()=>s(e.realtimeTalkVideoStream===null),e.switchRealtimeTalkCamera=async()=>{let t=e.realtimeTalkSession,n=e.realtimeTalkVideoStream,i=e.realtimeTalkCameraDevices;if(!t||!n||i.length<2||e.realtimeTalkVideoPending)return;let o=n.getVideoTracks()[0]?.getSettings?.().deviceId?.trim()||Nn().realtimeTalkVideoDeviceId?.trim(),s=i[(i.findIndex(e=>e.deviceId===o)+1)%i.length];if(s){e.realtimeTalkVideoPending=!0,e.realtimeTalkCameraError=!1,e.realtimeTalkDetail=null,e.requestUpdate();try{await t.switchCamera(s.deviceId),e.realtimeTalkSession===t&&(e.settings=wr({realtimeTalkVideoDeviceId:s.deviceId}))}catch(n){e.realtimeTalkSession===t&&!r()&&a(n)}finally{e.realtimeTalkSession===t&&(e.realtimeTalkVideoPending=!1,e.requestUpdate())}}}}function RS(){return(RS=e((()=>{Jn(),F(),zt(),uv(),Bf(),Os(),$g(),n_()})))()}function zS(e,t){return[...t.flatMap(e=>{let t=e.browserAnnotation?.modelContext.trim();return t?[t]:[]}),e].filter(Boolean).join(`

`)}async function BS(e,t,n){let r=null;if(e.client&&e.connected&&(t.trim()||n.attachments?.length)){mc(e,n.recovery)&&X(e,null);try{r=await Dd(e,{message:t.trim(),attachments:n.attachments,runId:mo(),expectedLeafEntryId:Pm(e)})}catch(t){if(mc(e,n.recovery)){let n=Ef(t);X(e,n?V(`chat.sendErrors.activeLeafChanged`):t instanceof io&&t.requestSent?Wm:pd(t)),n&&Promise.all([Rd(e),eh(e)])}}}let i=r?.status===`ok`||r?.status===`started`||r?.status===`in_flight`;Um(e,n.recovery,i,n.attachments),mm(r)&&mc(e,n.recovery)&&X(e,Vl(r,`detached`))}function VS(){return(VS=e((()=>{to(),F(),Ua(),xd(),af(),rh(),cf(),Zs(),Mf(),tp(),Yl()})))()}function HS(){return new Promise(e=>{let t=new MessageChannel;t.port1.addEventListener(`message`,()=>{t.port1.close(),t.port2.close(),e()},{once:!0}),t.port1.start(),t.port2.postMessage(void 0)})}async function US(e,t,n,r){let i=n.yieldToInput&&typeof MessageChannel<`u`,a=i&&n.isCurrent()&&e.connected&&e.client&&!e.chatLoading&&!Zp(e)&&!n.pendingSettings&&t.sendState===`waiting-idle`&&(t.queueMode||n.allowActiveRunSend&&!t.intent||!Rc(e)&&!Hl(e)&&e.chatQueue.find(e=>e.sendState!==`failed`||e.localCommandName)?.id===t.id),o=i&&e.connected&&n.isCurrent()?Tf(e).beginSubmission(e,t.id,{inline:!!a,isCurrent:()=>e.connected&&n.isCurrent()}):void 0;try{let a=t;if(i){await HS();let r=n.isCurrent()&&ze(e,t.sessionKey,t.agentId)?tf(e,t.id):null;if(!r||!Di(t,{...r,sendState:r.sendState===`submitting`?`waiting-idle`:r.sendState,orderKey:t.orderKey}))return`pending`;a=r}return await r(a)}finally{o?.release()}}async function WS(e,t,n,r){let i=t,{action:a,scope:o}=n;if(a){let e=GS.get(a)??mo();GS.set(a,e),i=`${t}\0${e}`}let s=e.chatSubmitGuards??=new Set;if(s.has(i))return;s.add(i);let c=mt(o),l={signatures:new Set(n.attachments?.map(e=>Jf(``,[e]))),isCurrent:()=>n.isCurrent()&&mt(I(e,e.sessionKey))===c},u=KS.get(e);l.signatures.size&&(u??=new Set,u.add(l),KS.set(e,u));let d=()=>{u?.delete(l)&&(u.size||KS.delete(e))};try{return await r({releaseAttachments:d,canRetireAttachment:t=>{let n=Jf(``,[t]);return l.isCurrent()&&l.signatures.has(n)&&![...KS.get(e)??[]].some(e=>e.isCurrent()&&e.signatures.has(n))}})}finally{d(),s.delete(i)}}var GS,KS;function qS(){return(qS=e((()=>{Ri(),bt(),Ue(),R(),Ua(),af(),Nm(),Jd(),ql(),gc(),GS=new WeakMap,KS=new WeakMap})))()}async function JS(e,t){let n=wm(e,t);return n&&!await Dp(e,t,n)?!1:e.sessionKey===t}async function YS(e,t,n,r){if($c(e)?.providerReview&&!ul(t??e.chatMessage)){X(e,V(`chat.providerReview.pausedBody`));return}if(Zp(e)&&(n?.intent||n?.resumeQueuedMessageEditId||!Qi(t??e.chatMessage)))return;if(n?.intent&&$c(e)?.sendDisabledReason){e.requestUpdate?.();return}let i=e.chatMessage,a=e.chatMentions?.map(e=>({...e})),o=e.chatReplyTarget?{...e.chatReplyTarget}:null,s=e.chatGoalDraftMode,c=n?.intent,l=t??e.chatMessage,u=t==null?a:n?.mentionsOverride,d=Ca(l,u),f=c?l:d.text,p=fc(),m=e.sessionKey,g=_d(e,!1),_=ih(e),v=Pm(e),y=Eu(t==null?e.chatAttachments:n?.attachmentsOverride??[]),b={attachments:t==null?y:[],scope:I(e,m),isCurrent:()=>_()&&g()&&e.sessionKey===m},x=(n=`none`)=>t==null?yu(e,i,y,a,o,n):{},S=y.length>0;if(S&&!$e(e.uploadConfig)){X(e,tt());return}if(c){if(u?.length){X(e,V(`chat.mentions.unsupported`));return}if(!e.connected||!e.client){X(e,V(`chat.goals.offline`));return}if(Rc(e)||Hl(e)){X(e,V(`chat.goals.busy`));return}if(y.some(e=>e.browserAnnotation)){X(e,V(`chat.goals.annotationUnsupported`));return}if(!f.trim())return}let C=n?.resumeQueuedMessageEditId,w=C?Nd(e):null;if(C!=null&&w?.id!==C)return;let T=C!=null&&w?.id===C,E=T?w.revision:null,D=c?null:ba(f);if(d.mentions?.length&&(D||/^\/(?:btw|side)(?::|\s|$)/i.test(f))){X(e,V(`chat.mentions.unsupported`));return}if(T&&(D||ul(f))){X(e,`Queued-row edits cannot run commands or stop aliases. Cancel this edit and send the command from the composer.`);return}let O=D||c?f:zS(f,y),k=D?y.filter(e=>!e.browserAnnotation&&!e.selectionAnnotation):y,ee=()=>{let t=vd(k,e.hello?.policy);return t!==void 0&&(Lt({message:t}),!0)};if(!O&&!S)return;if(!c){if(ul(f)&&(f.startsWith(`/`)||Dl(e))){if(e.connected&&!Lp(e,`abort`))return;e.chatRunError=null,t??id(e,f),await yl(e,{scope:`session`});return}let n=D;if(/^\/(?:btw|side)(?::|\s|$)/i.test(f)){e.chatRunError=null;let n=Wh(f);await WS(e,Zm(e,`local`,O,[]),b,async()=>{t??(id(e,f),x(`all`)),await e.openSessionCompanion?.(n)});return}let r=n?.command.clientPresentation,s=e.dispatchClientPresentation;if(e.connected&&n?.args===``&&r?.when===`no-arguments`&&!S&&e.chatReplyTarget==null&&s&&await WS(e,Zm(e,`local`,O,[]),b,async()=>{if(e.sessionKey!==m)return`not-handled`;let n=!1;try{n=await s(r.action)}catch{}return n?e.sessionKey===m?(e.chatRunError=null,t??(x(),id(e,O)),`handled`):`handled`:`not-handled`})!==`not-handled`)return;let c=n?.command.key===`model`&&Rr(n.args);if((!n?.command.executeLocal||c)&&$c(e)?.sendDisabledReason){e.requestUpdate?.();return}if(e.chatRunError=null,n?.command.key===`approve`&&(Rc(e)||Zp(e))){await WS(e,Zm(e,`detached`,O,y),b,async()=>{if(!await JS(e,m)||ee())return;let n=x(`annotations`);t??id(e,f);let r=I(e,m);Wu(e,!0,!1,{source:`manual`}),await BS(e,O,{attachments:k.length?k:void 0,recovery:Bd(e,r,n)})});return}if(n?.command.executeLocal&&!c){if(hp(n.command.key)){if(Du(e,m)){e.requestUpdate?.();return}await WS(e,Zm(e,`local`,O,y),b,async()=>{let r=ca(e,e.sessionKey);t??(id(e,f),x(`all`));let s=sm(e,O,Fs(O),{args:n.args,name:n.command.key},Ta(e.hello,e.client?.instanceId,e.selfUser)??void 0);if(s){if(s.sendState=vm(e),Tf(e).admit(e,r,s)!==`admitted`){Tf(e).remove(e,s.id),t??(e.chatMessage=i,e.chatMentions=a??[],e.chatReplyTarget=o,e.chatAttachments=y),X(e,Qs);return}Wu(e,!0,!1,{source:`manual`}),await nd(e,s,{routingSessionKey:e.sessionKey})}});return}let r=n.command.key===`redirect`,s=async()=>{if(r&&!await JS(e,m))return;let i,a=I(e,m);t??(id(e,f),n.command.key!==`export-session`&&(i=x()));let o=Bd(e,a,i);(n.command.key===`steer`||n.command.key===`redirect`)&&Wu(e,!0,!1,{source:`manual`});let s=await sp(e,n.command.key,n.args);n.command.key===`export-session`&&s===`completed`&&t==null&&mc(e,o)&&x(`all`),s===`failed`||s===`cancelled`?Um(e,o,!1,o.composer?.previousAttachments):s===`completed`&&Um(e,o,!0,o.composer?.previousAttachments)};r?await WS(e,Zm(e,`local`,O,y),b,s):await s();return}}if(ee())return;let{replyTargetOverride:A=o}=n??{},j=T?null:A,te=T?w.replyToId:j?.sourceMessageId?.trim()||void 0,ne=j&&!te&&!c?Xf(O,j):O,M=!c&&!f.startsWith(`/`)&&!f.startsWith(`!`)&&!oi(ne)?T?w.source.workContext:e.getWorkContext?.():void 0,N=M?Zt(M):void 0,P=ne.length-f.length,re=d.mentions?.map(e=>({profileId:e.profileId,start:e.start+P,end:e.end+P})),ie=Zm(e,C?`queued-edit`:c?`goal`:`message`,N?`${ne}\n\n${Ht(N)}`:ne,y,re),ae=!1,oe=async i=>{if(e.chatLoading&&(c||D||T)){if(!await Rd(e))return;v=Pm(e)}if(e.sessionKey!==m)return;let a=h(e,m),o=()=>b.isCurrent()&&ze(e,m,a);if(!ze(e,m,a)){X(e,V(`mcpServers.sessionUnavailable`));return}if(c&&(Rc(e)||Hl(e))){X(e,V(`chat.goals.busy`));return}let l=Nd(e);if(T&&(l!==w||l.revision!==E))return;if(Du(e,m,!1,a)){e.requestUpdate?.();return}let u=wm(e,m),d=Hl(e)||Zp(e),g=C&&l?.id===C?l:null,_=g?g.source.queueMode??`queue`:n?.followUpMode??e.chatFollowUpMode??In(e.settings?.chatFollowUpMode),y=!c&&d&&_!==`queue`?_:void 0,S=!!(c||d&&_!==`queue`),ee=$l(e,ne,k.length?k:void 0,!!c||Fs(O),p,u?`waiting-model`:vm(e),te,g?.orderKey,y,c,v,re,N);if(!ee)return;let A=ee.item;if(A.asyncQuestionItemId=g?.source.asyncQuestionItemId??n?.asyncQuestionItemId,A.attachments?.length){let t=await vu(e,A),n=Nd(e);if(!o()||T&&(n!==w||n.revision!==E)){t.status===`ready`&&Xs(t.update);return}if(t.status===`failed`){X(e,Xm(t.reason));return}A={...A,...t.update};let r=Du(e,m,!1,a);if(r||c&&(Rc(e)||Hl(e))){Xs(A),r?e.requestUpdate?.():X(e,V(`chat.goals.busy`));return}u??=wm(e,m),A.sendState=u?`waiting-model`:vm(e)}let j=x(D?`annotations`:`none`);t??id(e,f),A=df(e,A);let M=Tf(e).admit(e,ee.admission,A,g?{id:g.id,expected:g.source}:void 0),P=M===`admitted`;P&&(i.releaseAttachments(),t==null&&!D&&!c&&o()&&(e.chatAttachments=e.chatAttachments.filter(e=>!i.canRetireAttachment(e)))),g&&Em(e,P,A.attachments,g);let ie=!P&&!A.attachments?.length&&(!g||!g.sourceWasDurable)&&!Nd(e)&&!u&&$u(e,A,m);if(!P&&!ie){Xs(A),ah(e,A,{...j,previousGoalDraftMode:s}),X(e,sc(M,!!g));return}X(e,null),n?.onOutboxAdmitted?.();let oe=await US(e,A,{yieldToInput:P&&!!r,isCurrent:o,allowActiveRunSend:S,pendingSettings:u},t=>nd(e,t,{...j,previousGoalDraftMode:s,...S?{allowActiveRunSend:!0}:{},...v===void 0?{}:{expectedLeafEntryId:v},...u?{pendingSettings:u}:{},restoreOnTerminalFailure:!!(D||c),routingSessionKey:m,storageMode:ie?`memory`:`durable`})),se=tf(e,A.id);ae=oe!==`failed`,oe===`pending`&&se?.sendState===`waiting-idle`&&e.sessionKey===m&&ze(e,m,se.agentId)&&(Rc(e)||Hl(e))&&gp(e,se,`queued-busy`,p)};return await WS(e,ie,{...b,action:r},oe),ae}function XS(){return(XS=e((()=>{Wr(),si(),Kt(),Jn(),F(),ya(),Zi(),pi(),Gh(),Ai(),aa(),pa(),Ue(),R(),Be(),pt(),Cm(),af(),rh(),Nm(),rd(),Jd(),Zs(),yd(),VS(),Ts(),Mf(),tp(),vf(),ef(),qS(),Es(),Gc(),zd(),nc(),Yd(),gc(),Hs(),ja(),wi()})))()}function ZS(e,t){let n=km(e),r=n?.queuedInputs.find(e=>`pending-input:${e.id}`===t&&e.queued&&e.state===`queued`),i=e.client;if(!n||!r?.runId)return!1;if(!i||!e.connected)return!0;let a=e.connectionEpoch,o=()=>km(e)===n&&e.client===i&&e.connected&&e.connectionEpoch===a;return Tp(i,{sessionKey:n.sessionKey,agentId:n.agentId,runId:r.runId,...Us(e,n)?{}:{discardPendingInput:!0}}).then(async t=>{if(o()){if(!t.ok){e.chatError=B(t.error),e.requestUpdate?.();return}await Rd(e,{supersedeInFlight:!0})}}),!0}function QS(e){e.imageLightboxRequestVersion+=1;let t=e.imageLightbox;return e.imageLightbox=null,t?.release?.(),e.imageLightboxRequestVersion}async function $S(e){if(!e.client||!e.connected)return;let t=e.client,n=e.sessionKey.trim(),r=bf({sessionKey:n,assistantAgentId:e.assistantAgentId,agentsList:e.agentsList,hello:e.hello});if(!r)return;let i=++e.assistantIdentityRequestVersion;try{let a=await ss(t,r);if(e.client!==t||!e.connected||e.assistantIdentityRequestVersion!==i||e.sessionKey.trim()!==n||bf(e)!==r||!a)return;e.assistantAgentId!==(a.agentId??null)&&C(e,e.sessionKey)&&om(e),e.assistantName=a.name,e.assistantAvatar=a.avatar,e.assistantAvatarStatus=a.avatarStatus??null,e.assistantAvatarReason=a.avatarReason??null,e.assistantAgentId=a.agentId??null,e.requestUpdate?.()}catch{}}function eC(e,t,n,i=new Map){let o=()=>t.invalidate(),s=Nn(),c=n.sessionKey?.trim()||s.sessionKey,l=a({agentsList:e.agents.state.agentsList,hello:e.gateway?.snapshot.hello},c),u=Kn(),d=e.config.current,f={uploadConfig:e.config,captureComposerRecoveryReload:()=>{let t=pr(e.gateway);return()=>dr({timeoutMs:0,...t})},sessions:e.sessions,hasPendingInitialTurn:t=>e.placementStartup.hasPendingTurn(t),chatSubmissions:e.chatSubmissions,settings:s,assistantName:d.assistantIdentity.name,assistantAvatar:null,assistantAvatarStatus:null,assistantAvatarReason:null,assistantIdentityRequestVersion:0,userName:u.name,userAvatar:u.avatar,embedSandboxMode:d.embedSandboxMode,allowExternalEmbedUrls:d.allowExternalEmbedUrls,automaticallyFetchFavicons:d.automaticallyFetchFavicons,client:null,connected:!1,connectionEpoch:0,mediaPolicyEpoch:0,hello:null,selfUser:null,canvasPluginSurfaceUrl:null,terminalAvailable:!1,browserPanelAvailable:!1,assistantAgentId:e.agentSelection.state.selectedId,sessionKey:c,chatLoading:!1,chatHistoryPagination:{hasMore:!1},chatSending:!1,chatMessage:``,chatMessages:[],chatDisplayedLeafEntryId:void 0,chatBranches:[],chatBranchesSessionKey:null,chatBranchesConnectionEpoch:null,chatToolMessages:[],guardianNotices:[],providerPolicyNotice:null,chatThinkingLevel:null,chatVerboseLevel:null,chatQueueModeOverride:void 0,chatEffectiveQueueMode:void 0,chatAttachments:[],chatRunId:null,chatRunUsageById:new Map,chatStream:null,chatStreamStartedAt:null,chatRunStartup:null,lastError:null,chatError:null,chatRunError:null,agentsError:null,chatStreamSegments:[],chatRunStatus:null,compactionStatus:null,fallbackStatus:null,observerDigest:null,knownAgentRunIds:new Set,waitingApprovalStatuses:new Map,waitingApprovalResolvedIds:new Set,chatAvatarUrl:null,chatAvatarStatus:null,chatAvatarReason:null,chatModelSwitchPromises:{},chatModelPickerOpenSessionKey:null,chatModelsLoading:!1,chatModelCatalog:[],chatModelCatalogInitialized:he(e.gateway.snapshot.client),chatModelSelectionPolicy:void 0,chatModelCatalogRetired:!1,chatModelCatalogError:null,chatAccountSelection:null,modelAuthStatusRequestVersion:0,modelAuthStatusResult:null,modelAuthStatusError:null,sessionsResult:null,sessionsResultAgentId:null,sessionsLoading:!1,sessionsError:null,sessionsArchivedFilter:`active`,selectedChatSessionArchived:!1,selectedChatSessionIncognito:!1,agentsList:e.agents.state.agentsList,agentsSelectedId:e.agentSelection.state.selectedId,refreshSessionsAfterChat:new Map,pendingAbort:null,pendingSessionMessageReloadSessionKey:null,chatSubmitGuards:new Set,chatGoalDraftMode:null,chatSendTimingsByRun:new Map,chatQueue:[],chatComposerFallbackByScope:{},chatSendingScopeKey:null,chatMessagesBySession:i,eventLogBuffer:[],dispatchClientPresentation:t=>Gv(e,t),basePath:e.basePath,resourceBasePath:e.resourceBasePath,chatNewMessagesBelow:!1,chatLocalInputHistoryBySession:{},chatInputHistorySessionKey:null,chatInputHistoryItems:null,chatInputHistoryIndex:-1,chatDraftBeforeHistory:null,chatStreamRenderFrame:null,chatLastScrollTop:0,chatLastScrollHeight:0,chatHasAutoScrolled:!1,chatUserNearBottom:!0,chatFollowLocked:!1,chatReadingHistory:!1,sidebarLayout:De(s.sidebarSessionLayouts?.[l]),sidebarContent:null,sidebarFocusPanelId:s.sidebarSessionActivePanels?.[l]??``,sidebarFocusVersion:0,imageLightbox:null,imageLightboxRequestVersion:0,toolStreamById:new Map,toolStreamOrder:[],activityEventSeqById:new Map,toolStreamSyncTimer:null,...PS(),renderLifecycle:t,requestUpdate:o,transcriptLoadingChanged:()=>n.dispatchEvent(new CustomEvent(se,{bubbles:!0,composed:!0})),historyRecoveryChanged:()=>n.dispatchEvent(new Event(r,{bubbles:!0,composed:!0})),sessionWorkspaceState:void 0,querySelector:n.querySelector.bind(n)};f.resetToolStream=()=>Sc(f),f.resetChatInputHistoryNavigation=()=>Xu(f),f.scrollToBottom=e=>{Pc(f),Wu(f,!0,!!e?.smooth,{source:`manual`})},f.handleChatScroll=e=>uu(f,e),f.handleChatDraftChange=(e,t)=>el(f,e,t),f.handleChatInputHistoryKey=e=>Bp(f,e),f.applySettings=e=>{let n={...f.settings,...e};f.settings=wr({chatShowThinking:n.chatShowThinking,chatShowToolCalls:n.chatShowToolCalls,chatPersistCommentary:n.chatPersistCommentary,chatSendShortcut:n.chatSendShortcut}),t.invalidate()},LS(f,()=>!$c(f)?.providerReview),f.loadAssistantIdentity=()=>$S(f),f.handleSendChat=(t,n,r)=>{let i=t??f.chatMessage,a=ba(i)!==null||ul(i)&&Dl(f);return No({connected:f.connected,directComposerSend:t===void 0&&n===void 0&&Ho(),message:i,hasAttachments:f.chatAttachments.length>0,isCommand:a})&&Bo(e),YS(f,t,n,r)};let p=e=>async n=>{await e(f,n),t.invalidate()};f.handleAbortChat=p(yl),f.removeQueuedMessage=e=>{if(ZS(f,e))return;if(lp(f,e)){X(f,Hf),t.invalidate();return}let n=Rp(f,e,{discard:!0});n===`removed`?(X(f,null),qp(f)):n===`rejected`&&X(f,Qs),t.invalidate()},f.retryQueuedChatMessage=p(Qc),f.steerQueuedChatMessage=p(dd),f.moveQueuedChatMessage=(e,n)=>{sl(f,e,n),t.invalidate()},f.editQueuedChatMessage=e=>{if(Mp(f,e)===`unavailable`)X(f,tm);else for(let e of[`lastError`,`chatError`])f[e]===`A queued message is being edited in another pane. Finish or cancel that edit before editing it here.`&&(f[e]=null);t.invalidate()},f.updateQueuedChatMessageEdit=(e,n)=>{nf(f,e,n),t.invalidate()},f.submitQueuedChatMessageEdit=()=>{let e=Nd(f);e&&f.handleSendChat(e.draftText,{attachmentsOverride:[...e.attachments],mentionsOverride:e.mentions,resumeQueuedMessageEditId:e.id}).then(o,o)},f.cancelQueuedChatMessageEdit=()=>{cm(f)&&qp(f),t.invalidate()};let m=new Set,h=``;return f.updateSidebarLayout=(e,n)=>{let r=a(f,f.sessionKey),i=JSON.stringify([f.settings.gatewayUrl,r]);i!==h&&(m.clear(),h=i);let o=De(e),s=f.sidebarLayout,c=(e,t)=>e.columns.some(e=>e.panels.some(e=>e.slot===t));n?.automaticResource&&!c(s,n.automaticResource)&&c(o,n.automaticResource)&&m.add(n.automaticResource);for(let e of m){let t=o.columns.flatMap(e=>e.panels).find(t=>t.slot===e);(!t||e===`desktop`&&t.environmentId!==void 0)&&m.delete(e)}(s.resourceAutoOpenDismissed||n?.persist!==!1&&(s.open&&!o.open||c(s,`desktop`)&&!c(o,`desktop`)||c(s,`browser`)&&!c(o,`browser`)))&&(o.resourceAutoOpenDismissed=!0);let l=n?.dashboardPresentation===`personal`?xv(o):void 0;if(l){let e=Z(f);o.dashboardPresentationOverride=e&&l===(e.boardPresentation??`split`)?null:l}if((f.sidebarContent?.kind===`loading`||f.sidebarContent?.kind===`unavailable`)&&!o.columns.some(e=>e.panels.some(e=>e.slot===`detail`))&&(f.sidebarContent=null),f.sidebarLayout=o,n?.persist===!1){t.invalidate();return}let u=o;for(let e of m)u=O_(u,e);f.settings=wr({sidebarSessionLayouts:v(Nn().sidebarSessionLayouts,r,u,{geometryOnly:n?.geometryOnly,dashboardPresentationOverride:l?o.dashboardPresentationOverride:void 0})}),o.dashboardPresentationOverride=f.settings.sidebarSessionLayouts?.[r]?.dashboardPresentationOverride,t.invalidate()},f.updateSidebarActivePanel=e=>{let n=e.trim();if(!n)return;f.sidebarFocusPanelId=n,f.sidebarFocusVersion+=1;let r=f.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.id===n)?.slot;if((r===`desktop`||r===`browser`)&&m.has(r)){t.invalidate();return}f.settings=wr({sidebarSessionActivePanels:Se(Nn().sidebarSessionActivePanels,a(f,f.sessionKey),n)}),t.invalidate()},f.handleOpenSidebar=e=>{let t=e?.fileTab??(e?.kind===`attachment`?{id:`attachment:${e.sourceIdentity??e.src??crypto.randomUUID()}`,label:e.title}:e?.kind===`file`?{id:`file:${e.path}`,label:e.name}:null),r=t?`workspace`:`detail`,i=dv(f.sidebarLayout,r),a=i.columns.flatMap(e=>e.panels).find(e=>e.slot===r);a&&(i=eg(i,a.id));let o=n.getBoundingClientRect?.().width??0,s=o>0&&o>=680?Ct(i,o)??i:i;if(t&&e){let n=Ig(f,t.id,t.label,e);if(e.kind===`mcp-app`&&n.content.kind===`mcp-app`){n.content=e,n.label=t.label;let r=U_(f);r.previews=[...r.previews]}}else f.sidebarContent=e;f.updateSidebarLayout(s),a&&f.updateSidebarActivePanel(a.id)},f.handleCloseSidebar=e=>{e===`workspace`&&Rg(f),f.updateSidebarLayout(O_(f.sidebarLayout,e))},f.beginImageOpen=()=>{let e=QS(f);return t.invalidate(),e},f.handleOpenImage=(e,n)=>{if((n??f.beginImageOpen())!==f.imageLightboxRequestVersion){e.release?.();return}let r=e.kind===`video`,i=e=>r?Ds(e,`video`):xt(e,window.location.href,{allowDataImage:!0}),a=i(e.src),o=e.originalSrc?i(e.originalSrc):void 0;if(!a||e.originalSrc&&!o){e.release?.();return}f.imageLightbox={...e,src:a,...o?{originalSrc:o}:{}},t.invalidate()},f.handleCloseImage=()=>{QS(f),t.invalidate()},f}function tC(){return(tC=e((()=>{as(),Kv(),hn(),qo(),Jn(),Dn(),pi(),zt(),i(),Ft(),R(),gm(),ym(),d(),af(),rh(),th(),rd(),Jd(),RS(),Oc(),XS(),tp(),Vf(),Q(),td(),Ng(),du(),Gc(),Yd(),gc(),Hs(),pe(),vv()})))()}function nC(e){let t=e.chatStreamRenderFrame;t!=null&&(e.chatStreamRenderFrame=null,typeof globalThis.cancelAnimationFrame==`function`&&globalThis.cancelAnimationFrame(t))}function rC(e,t=`immediate`){if(globalThis.document?.visibilityState===`hidden`||t===`immediate`||typeof globalThis.requestAnimationFrame!=`function`){nC(e),e.requestUpdate?.();return}if(e.chatStreamRenderFrame!=null)return;let n=0;n=globalThis.requestAnimationFrame(()=>{e.chatStreamRenderFrame===n&&(e.chatStreamRenderFrame=null,e.requestUpdate?.())}),e.chatStreamRenderFrame=n}function iC(e){return[km(e)?.page,e.chatMessages,e.chatToolMessages,e.chatStreamSegments,e.guardianNotices,e.realtimeTalkConversationState.entries]}var aC;function oC(){return(oC=e((()=>{An(),F(),pa(),R(),Be(),il(),Dx(),Nm(),th(),RS(),tC(),Es(),Kp(),ol(),Ng(),Cf(),du(),pc(),Yd(),Hs(),aC=class{constructor(e,t,n){this.host=e,this.onStateChange=t,this.onQueuedMessageDiscarded=n,this.previousChatLoading=!1,this.previousTranscriptSources=[],this.previousChatStream=null,this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1,this.cleanups=[],this.renderLifecycleConnected=!1,this.attachmentReadsValue=new al(()=>this.stateValue?.requestUpdate?.()),this.composerPersistence=new Tu(()=>this.stateValue),e.addController(this)}get attachmentReads(){return this.attachmentReadsValue}takeAttachmentReads(){let e=this.attachmentReadsValue;return this.attachmentReadsValue=new al(()=>this.stateValue?.requestUpdate?.()),e}adoptAttachmentReads(e,t){this.attachmentReadsValue.abortReads(),this.attachmentReadsValue=e,e.retarget(this.attachmentInputProps(t),()=>t.requestUpdate?.())}attachmentInputProps(e){let t=this.attachmentReads,n=t.readSignal;return{uploadConfig:e.uploadConfig,attachmentReads:t,attachments:e.chatAttachments,attachmentLimits:sf(e.hello?.policy),getAttachments:()=>e.chatAttachments,pendingAttachmentReads:t.pendingReads,getPendingAttachmentReads:()=>t.pendingReads,readSignal:n,onPendingReadsChange:r=>{r===1&&n===t.readSignal&&zl(e),t.updatePending(n,r)},onAttachmentsChange:t=>{e.chatAttachments=t,e.requestUpdate?.()}}}createRenderLifecycle(){this.cancelRenderLifecycleScope();let e=new Set;return this.renderLifecycleScope=e,{invalidate:()=>{this.requestUpdateForScope(e)},afterCommit:(t,n)=>this.afterCommit(e,t,n)}}attach(e){this.stateValue&&this.stateValue!==e&&(this.privateDraftReview?.controller.abort(),Sx(this.stateValue),Zc(this.stateValue.requestUpdate),this.attachmentReads.abortReads(),this.composerPersistence.stop(),nC(this.stateValue),bc(this.stateValue),FS(this.stateValue)),this.stateValue=e,this.previousTranscriptSources=iC(e),e.canRestoreComposer=()=>this.stateValue===e&&this.composerPersistence.active,this.previousChatLoading=e.chatLoading,this.previousChatStream=e.chatStream;let t=e.renderLifecycle;e.requestUpdate=()=>t.invalidate(),this.cleanups.push(Tf(e).subscribe(e,t=>{this.stateValue===e&&this.onQueuedMessageDiscarded?.(t)})),this.cleanups.push(jn(()=>this.stateValue!==e||!e.chatQueuedEdit&&!this.hasPrivateDraft(e),()=>{if(!e.chatQueuedEdit&&this.hasPrivateDraft(e)){Lt({message:V(`chat.privateDraftReload.blocked`),actionLabel:V(`chat.privateDraftReload.review`),onAction:()=>void this.reviewPrivateDraft(e)});return}let t=e.chatQueuedEdit,n=e.client;Lt({message:V(`chat.queue.reloadBlocked`),actionLabel:e.reviewQueuedMessageEdit?V(`chat.queue.reviewEdit`):void 0,onAction:()=>{this.stateValue===e&&e.client===n&&t&&Nd(e)===t&&e.reviewQueuedMessageEdit?.()}})}));let n=e.handleSendChat;e.handleSendChat=async(e,r,i)=>{let a=n(e,r,i);t.invalidate();try{return await a}finally{t.invalidate()}};let r=e.handleChatDraftChange;e.handleChatDraftChange=(e,t)=>{r(e,t),this.composerPersistence.schedule()};let i=e.handleChatInputHistoryKey;e.handleChatInputHistoryKey=t=>{let n=i(t);return n.handled&&(this.composerPersistence.schedule(),e.renderLifecycle.invalidate()),n}}hasPrivateComposerInput(e){return Us(e,I(e,e.sessionKey))&&!!(e.chatMessage||e.chatAttachments.length||e.chatGoalDraftMode||e.chatReplyTarget||e.chatMentions?.length||this.attachmentReads.pendingReads)}privateFallback(e){return Object.entries(e.chatComposerFallbackByScope).find(([t,n])=>{let r=Oa(t);return(n.incognito||r&&Us(e,r))&&!!(n.message||n.attachments.length||n.goalMode||n.replyTarget||n.mentions?.length)})}hasPrivateDraft(e){return this.hasPrivateComposerInput(e)||!!this.privateFallback(e)}async reviewPrivateDraft(e){if(this.stateValue!==e||this.privateDraftReview||!this.hasPrivateDraft(e))return;let t=hl(e),n=this.hasPrivateComposerInput(e)?void 0:this.privateFallback(e),{sessionKey:r,connectionEpoch:i}=e,a=n?.[1].message??e.chatMessage,o=n?n[1].mentions:e.chatMentions,s=n?n[1].goalMode:e.chatGoalDraftMode,c=n?n[1].replyTarget:e.chatReplyTarget,l=[...n?.[1].attachments??e.chatAttachments],u=this.attachmentReads,d=n?0:u.pendingReads,f=e.captureComposerRecoveryReload?.(),p={controller:new AbortController,isCurrent:()=>this.stateValue===e&&e.client===t.client&&mh(e,t)&&e.sessionKey===r&&e.connectionEpoch===i&&(n?e.chatComposerFallbackByScope[n[0]]===n[1]:e.chatMessage===a&&e.chatMentions===o&&e.chatGoalDraftMode===s&&e.chatReplyTarget===c&&this.attachmentReads===u&&u.pendingReads===d&&e.chatAttachments.length===l.length&&l.every((t,n)=>e.chatAttachments[n]===t))};this.privateDraftReview=p;try{if(!p.isCurrent()||p.controller.signal.aborted||!await wd({text:a,attachments:l,hasGoal:!!s,pendingReads:d,isCurrent:p.isCurrent,signal:p.controller.signal})||!p.isCurrent())return;if(n){let t={...e.chatComposerFallbackByScope};delete t[n[0]],e.chatComposerFallbackByScope=t}else u.abortReads(),e.chatAttachments=[],e.chatGoalDraftMode=null,e.chatReplyTarget=null,e.handleChatDraftChange(``,[]);let t=e.captureComposerRecoveryOwner?.()?.retainedAttachmentIds(l);Xc(l.filter(e=>!t?.has(e.id)),[e.chatAttachments,...Object.values(e.chatComposerFallbackByScope).map(e=>e.attachments)]),e.requestUpdate?.(),await f?.()}catch{p.isCurrent()&&Lt({message:V(`chat.privateDraftReload.unavailable`)})}finally{this.privateDraftReview===p&&(this.privateDraftReview=void 0),!p.isCurrent()&&this.stateValue===e&&e.client===t.client&&e.sessionKey===r&&this.hasPrivateDraft(e)&&Lt({message:V(`chat.privateDraftReload.changed`),actionLabel:V(`chat.privateDraftReload.review`),onAction:()=>void this.reviewPrivateDraft(e)})}}addCleanup(e){this.cleanups.push(e)}isRenderLifecycleScopeActive(e){return this.renderLifecycleConnected&&this.renderLifecycleScope===e}requestUpdateForScope(e){return this.isRenderLifecycleScopeActive(e)?(this.privateDraftReview&&!this.privateDraftReview.isCurrent()&&this.privateDraftReview.controller.abort(),this.composerPersistence.persistChangedState(),this.captureRenderLifecycleChanges(),this.onStateChange?.(),this.host.requestUpdate(),!0):!1}cancelRenderLifecycleScope(){let e=this.renderLifecycleScope;if(e){this.renderLifecycleScope=void 0;for(let t of e)t()}}afterCommit(e,t,n){if(!this.isRenderLifecycleScopeActive(e))return n?.(),()=>void 0;let r=!1,i,a=()=>{e.has(o)&&(i=void 0,e.delete(o))},o=()=>{if(e.has(o)){e.delete(o);try{i?.()}finally{i=void 0,r||n?.()}}};return e.add(o),this.requestUpdateForScope(e)?(this.host.updateComplete.then(()=>{if(e.has(o)){if(!this.isRenderLifecycleScopeActive(e)){o();return}r=!0;try{let n=t(a);typeof n==`function`?e.has(o)&&this.isRenderLifecycleScopeActive(e)?i=n:n():a()}catch(e){throw a(),e}}},o),o):(o(),o)}captureRenderLifecycleChanges(){let e=this.stateValue;if(!e)return;let t=iC(e),n=t.some((e,t)=>this.previousTranscriptSources[t]!==e),r=this.previousChatStream!==e.chatStream,i=this.previousChatLoading!==e.chatLoading,a=this.previousChatLoading&&!e.chatLoading,o=this.previousChatStream==null&&typeof e.chatStream==`string`;this.previousTranscriptSources=t,this.previousChatLoading=e.chatLoading,this.previousChatStream=e.chatStream,(n||r||i)&&(this.scrollAfterUpdate=!0,this.scrollContentChangedAfterUpdate||=n||r,this.forceScrollAfterUpdate||=a||o||!e.chatHasAutoScrolled)}handleTranscriptResize(){this.stateValue&&this.renderLifecycleConnected&&Ec(this.stateValue,!1,!1,{source:`resize`})}hostConnected(){this.renderLifecycleConnected=!0,this.cancelRenderLifecycleScope()}hostUpdated(){let e=this.stateValue;if(!this.scrollAfterUpdate)return;let t=this.forceScrollAfterUpdate,n=this.scrollContentChangedAfterUpdate;this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1,e&&Ec(e,t,e.chatHasAutoScrolled,{contentChanged:n})}stopChatEffects(){for(this.privateDraftReview?.controller.abort();this.cleanups.length>0;)this.cleanups.pop()?.();let e=this.stateValue;e&&(Sx(e),Zc(e.requestUpdate),nC(e),bc(e),QS(e),(e.sidebarContent?.kind===`loading`||e.sidebarContent?.kind===`unavailable`)&&(e.sidebarContent=null),Rg(e),K_(e.sessionWorkspaceState),FS(e),e.resetToolStream?.())}hostDisconnected(){this.renderLifecycleConnected=!1,this.cancelRenderLifecycleScope(),this.attachmentReads.abortReads(),this.composerPersistence.stop(),this.stopChatEffects(),this.stateValue=void 0,this.previousTranscriptSources=[],this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1}}})))()}function sC(e,t){if(!t||e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||!e.deltaY||Math.abs(e.deltaX)>Math.abs(e.deltaY))return;let n=e.composedPath();if(n.includes(t))return;for(let t of n){if(t===e.currentTarget)break;if(!(t instanceof HTMLElement))continue;let n=getComputedStyle(t),r=e.deltaY<0?t.scrollTop>0:t.scrollTop+t.clientHeight<t.scrollHeight-1;if(/^(auto|scroll)$/.test(n.overflowY)&&(t.scrollHeight>t.clientHeight&&(!t.closest(`.chat-footer__context`)||r)||n.overscrollBehaviorY===`contain`||n.overscrollBehaviorY===`none`))return}let r=new WheelEvent(`wheel`,{deltaX:e.deltaX,deltaY:e.deltaY,deltaMode:e.deltaMode,cancelable:!0});if(!t.dispatchEvent(r))return;e.preventDefault();let i=getComputedStyle(t),a=e.deltaMode===WheelEvent.DOM_DELTA_PAGE?t.clientHeight:e.deltaMode===WheelEvent.DOM_DELTA_LINE?Number.parseFloat(i.lineHeight)||Number.parseFloat(i.fontSize)*1.2:1;t.scrollBy({top:e.deltaY*a,behavior:`instant`})}function cC(e){if(e.defaultPrevented||!lC.has(e.key))return!1;let t=e.key!==` `&&e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&!e.shiftKey&&!e.altKey&&!e.metaKey,n=ro(),r=t&&!e.ctrlKey&&n,i=e.key===`ArrowUp`||e.key===`PageUp`||e.key===`Home`||e.key===` `&&e.shiftKey,a=!1;for(let o of e.composedPath()){if(o===e.currentTarget)break;if(o instanceof HTMLElement){if(o instanceof HTMLMediaElement&&o.controls&&!e.key.startsWith(`Page`))return!1;if(o instanceof HTMLInputElement){if(o.type===`range`){if(e.key!==` `)return!1}else if([`button`,`checkbox`,`color`,`file`,`image`,`reset`,`submit`].includes(o.type)){if(e.key===` `)return!1}else if(!r&&!(t&&!e.ctrlKey&&e.key.startsWith(`Page`)))return!1}if(o instanceof HTMLSelectElement&&(o.multiple||o.size>1||!r&&(!t||!e.ctrlKey||n||e.key.startsWith(`Page`)))||o instanceof HTMLTextAreaElement&&!r||!a&&o.hasAttribute(`contenteditable`)&&(a=!0,!o.matches(`[contenteditable="false" i]`)&&!r)||e.key===` `&&o.matches(`button, summary`)||/^(auto|scroll)$/.test(getComputedStyle(o).overflowY)&&(i?o.scrollTop>0:o.scrollTop<o.scrollHeight-o.clientHeight))return!1}}return!0}var lC;function uC(){return(uC=e((()=>{oe(),lC=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `])})))()}var $;function dC(){return(dC=e((()=>{eo(),Ar(),bn(),rn(),ko(),Mo(),qv(),R(),Ch(),ae(),Gd(),kt(),j(),SS(),d(),af(),ES(),NS(),oC(),Q(),jg(),Qm(),lg(),Dv(),gc(),Hs(),jt(),$=class extends ot{connectedCallback(){this.paneLifecycleRoot=this.closest(`openclaw-app-shell`)??this.parentElement,document.addEventListener(`visibilitychange`,this.handleVisibilityChange),super.connectedCallback(),this.addEventListener(se,this.synchronizeForegroundTranscript),this.paneLifecycleRoot?.dispatchEvent(new Event(rt))}async scheduleUpdate(){for(;this.hasUpdated&&this.isConnected&&(document.visibilityState===`hidden`||!this.presented);)await new Promise(e=>{this.hiddenUpdateResume=e});await super.scheduleUpdate()}disconnectedCallback(){this.removeEventListener(se,this.synchronizeForegroundTranscript),this.context?.connectionBootstrap.setForegroundPane(this,null),this.hiddenUpdateResume?.(),this.hiddenUpdateResume=void 0,document.removeEventListener(`visibilitychange`,this.handleVisibilityChange),super.disconnectedCallback();let e=this.paneLifecycleRoot;this.paneLifecycleRoot=null,this.conversationVisible=!1,e?.dispatchEvent(new Event(rt))}get visuallyPresented(){return this.visuallyPresentedValue}set visuallyPresented(e){let t=this.visuallyPresentedValue;if(e===t)return;let n=this.conversationPresented;this.visuallyPresentedValue=e,this.dispatchEvent(new Event(Ve)),this.requestUpdate(`visuallyPresented`,t),this.notifyConversationPresentation(n)}get conversationPresented(){return this.presented&&this.visuallyPresented&&this.conversationVisible}setConversationVisible(e){let t=this.conversationPresented;this.conversationVisible=e,this.notifyConversationPresentation(t)}notifyConversationPresentation(e){e!==this.conversationPresented&&this.dispatchEvent(new Event(rt,{bubbles:!0,composed:!0}))}get presented(){return this.presentedValue}set presented(e){let t=this.presentedValue;if(e===t)return;let n=this.conversationPresented;this.headerPresentationGeneration+=1,this.presentedValue=e,e&&(this.hiddenUpdateResume?.(),this.hiddenUpdateResume=void 0),this.dispatchEvent(new Event(Ve)),this.progressCard.hostUpdate(),this.requestUpdate(`presented`,t),this.presentedChanged(e),this.notifyConversationPresentation(n),this.synchronizeForegroundTranscript()}presentedChanged(e){}get transcriptLoading(){let e=this.state?ks(this.state).phase:`idle`;return e===`pending-connection`||e===`in-flight`}get historyRecovering(){return!!(this.state&&this.state.client===this.context?.gateway.snapshot.client&&dm(this.state))}get transcriptReady(){if(!this.state?.connected||this.state.client!==this.context?.gateway.snapshot.client)return!1;let e=ks(this.state).phase;return e===`committed`||e===`failed`}get headerOutcomeOwner(){return`${this.connectionGeneration}:${this.headerPresentationGeneration}`}ownsHeaderOutcome(e){return this.presented&&e===this.headerOutcomeOwner}get selected(){return this.activeValue}get active(){return this.activeValue&&(!this.context||Xn(this.context).current===this.inputRegion)}set active(e){let t=this.activeValue;e!==t&&(this.activeValue=e,this.requestUpdate(`active`,t),this.activeChanged(this.active),this.synchronizeForegroundTranscript())}activeChanged(e){}retireHeaderSessionMutations(){this.headerSessionMutationAbortController.abort(),this.headerSessionMutationAbortController=new AbortController}get runActivity(){let e=this.state;return e?.connected?{client:e.client,agentId:Y(e),working:Hl(e),completion:e.chatRunStatus}:null}resolveChatReadTarget(){let e=this.state;if(!e)return;let t=I(e,e.sessionKey);if(t.agentId)return t;let n=nu(e);return n&&Bt(n.key)?I(e,n.key):n?.agentId&&(n.key===`global`||n.key===`unknown`)?{sessionKey:n.key,agentId:n.agentId}:void 0}projectChildRoster(e){let t=e?this.swarmHydrator?.rows:void 0;return{swarm:e&&this.swarmEnabled?{...e,sessions:t??[]}:void 0,subagentSessions:t,subagentSessionsHydrated:!!(e&&this.swarmHydrator?.hydrated),subagentSessionsRead:!!(e&&this.swarmHydrator?.childrenRead),subagentParentKey:e?ue(e.sessionKey,e.agentId):void 0}}isCurrentSessionArchived(e){return e.selectedChatSessionArchived||e.sessionsResult?.sessions.some(t=>t.archived===!0&&z(t.key,e.sessionKey))===!0}get presencePayload(){return this.presencePayloadValue}set presencePayload(e){let t=this.presencePayloadValue;this.presencePayloadValue=e;let n=this.context?.gateway.snapshot;TS(t,e,{sessionKey:this.state?.sessionKey??this.sessionKey,selfUser:n?.selfUser,selfInstanceId:n?.client?.instanceId})||this.requestUpdate(`presencePayload`,t)}constructor(){super(),this.paneLifecycleRoot=null,this.handleVisibilityChange=()=>{if(this.progressCard.hostUpdate(),document.visibilityState!==`hidden`){this.hiddenUpdateResume?.();return}let e=this.state;if(!e)return;let t=mg(this.presentationId).composerTextarea?.value,n=t!==void 0&&t!==e.chatMessage;n&&e.handleChatDraftChange(t),(n||e.chatStreamRenderFrame!=null)&&rC(e)},this.minutePoll=new am(this,6e4,()=>this.requestUpdate(),!0,`visible`),this.paneId=`single`,this.presentationId=`single`,this.sessionKey=``,this.routeLoadingSkeleton=!1,this.inputRegion=`page`,this.compact=!1,this.visuallyPresentedValue=!0,this.conversationVisible=!1,this.activeValue=!1,this.headerPresentationGeneration=0,this.presentedValue=!0,this.synchronizeForegroundTranscript=()=>{this.context?.connectionBootstrap.setForegroundPane(this,this.state&&this.isConnected&&this.selected&&this.presented&&this.inputRegion===`page`?{sessionKey:qe(this.state,{sessionKey:this.state.sessionKey}),client:this.state.client,ready:this.transcriptReady||nu(this.state)!==void 0}:null)},this.focusComposer=!1,this.dashboardExpanded=!1,this.narrow=!1,this.mergedChrome=!1,this.navDrawerOpen=!1,this.onboarding=!1,this.publishedRunActivity=null,this.chatState=new aC(this,()=>{this.syncQueuedEditRetention();let e=this.runActivity;(e?.client!==this.publishedRunActivity?.client||e?.agentId!==this.publishedRunActivity?.agentId||e?.working!==this.publishedRunActivity?.working||e?.completion!==this.publishedRunActivity?.completion)&&(this.publishedRunActivity=e,this.dispatchEvent(new Event(re,{bubbles:!0})))},e=>dg(this.presentationId).transcriptRenderContext.onAsyncQuestionDiscard?.(e)),this.composerCapabilities=new xS(()=>this.requestUpdate()),this.transcript=new cg(this,()=>this.paneId,{visuallyPresented:()=>this.visuallyPresented,onViewportResize:()=>this.chatState.handleTranscriptResize(),canFollowEnd:()=>this.state!==void 0&&Kl(this.state),onReaderScroll:e=>this.state&&ph(this.state,e)}),this.progressCard=new Uv(this,{gateway:()=>this.context?.gateway,target:()=>this.initialProgressCardTarget()}),this.questionPromptState=Ao(()=>{this.questionPrompts=jo(this.questionPromptState),this.requestUpdate()}),this.questionPrompts=[],this.paneWidth=1/0,this.paneResizeObserver=null,this.connectedClient=null,this.boardProviderLifecycleConnected=!1,this.connectionGeneration=0,this.headerSessionMutationAbortController=new AbortController,this.headerRenameValue=``,this.headerPlatform=null,this.headerCopiedAction=null,this.continueInTerminalDialog=null,this.headerPlacementMovingKey=null,this.headerPlacementReclaimingKey=null,this.headerPlacementRestartingKey=null,this.sessionSharingStates=new Map,this.sessionSharingHydrationTargets=new Map,this.sessionParticipationTracker=new MS,this.observedBoardPresence=new Map,this.swarmHydrator=null,this.swarmEnabled=!0,this.sessionDiscussionStates=new Map,this.sessionDiscussionOpenUrls=new Map,this.pendingPanelToggleRequests=new Map,this.sessionDiscussionProbes=new Set,this.sessionDiscussionPanels=new Map,this.headerRenameInitialValue=``,this.headerRenameSession=null,this.headerCopiedTimer=null,this.composerPrefillAttentionTimer=null,this.composerPrefillAttentionTarget=null,this.headerWorktreePaths=new Map,this.headerBranches=new Map,this.nativeDraftCleanup=null,this.unreadPatchGuard=new Th,this.sessionSuggestions=[],this.sessionSuggestionBusyIds=new Set,this.sessionSuggestionsRequestVersion=0,this.sessionSuggestionsRefreshQueued=!1,this.sessionSuggestionTargetSignature=``,this.typingActors=new Map,this.typingTimers=new Map,this.sessionPullRequests=[],this.githubRepo=null,this.sessionPullRequestsStatus=`ready`,this.githubPublication=null,this.dismissedSessionPullRequestIds=new Set,this.dismissedWorkspaceConflictRefs=new Map,this.catalogMessages=[],this.catalogLoading=!1,this.loadingOlder=!1,this.catalogSession=null,this.catalogHost=null,this.catalogLoadGeneration=0,this.catalogRequestedSessionKey=null,this.olderLoadGeneration=0,this.historyObserver=null,this.historyObserverSentinel=null,this.historyObserverBootstrap=!1,this.historyObserverArmed=!1,this.historyAutoLoadBlocked=!1,this.historyIntentTimer=null,this.historyTouchY=null,this.transcriptScrollTop=null,this.olderCursorsSeen=new Set,Uo(this),new S(this).effect(()=>this.ownerDocument,bu).watchStore(()=>this.context&&Xn(this.context),()=>this.activeChanged(this.active)).watch(()=>this.context?.overlays,(e,t)=>e.subscribe(e=>{this.state&&this.reconcileWaitingApprovalSnapshot(e.approvalQueue),t()})).watch(()=>this.context?.runtimeConfig,(e,t)=>e.subscribe(()=>{this.refreshSwarmRoster(),t()})).watchStore(()=>this.context?.theme).watchStore(()=>this.context?.plugins).watch(()=>this.resolveBoardProvider(),(e,t)=>{let n=e.snapshot$.subscribe(t),r=e.loadError$.subscribe(t);return()=>{n(),r()}}).effect(()=>this.resolveBoardProvider(),e=>e.events.subscribe(e=>this.handleBoardCommand(e)))}},q([Qa({context:er,subscribe:!0})],$.prototype,`context`,void 0),q([G({attribute:!1})],$.prototype,`mcpAppLaunch`,void 0),q([G({attribute:!1})],$.prototype,`paneId`,void 0),q([G({attribute:!1})],$.prototype,`paneLabel`,void 0),q([G({attribute:!1})],$.prototype,`presentationId`,void 0),q([G({attribute:!1})],$.prototype,`chatMessagesBySession`,void 0),q([G({attribute:!1})],$.prototype,`sessionSnapshotStore`,void 0),q([G({attribute:!1})],$.prototype,`sessionKey`,void 0),q([G({attribute:!1})],$.prototype,`routeLoadingSkeleton`,void 0),q([G({attribute:!1})],$.prototype,`agentId`,void 0),q([G({attribute:!1})],$.prototype,`inputRegion`,void 0),q([G({attribute:!1})],$.prototype,`compact`,void 0),q([G({attribute:!1})],$.prototype,`onBackToSubagents`,void 0),q([G({attribute:!1})],$.prototype,`workContext`,void 0),q([G({attribute:!1})],$.prototype,`draft`,void 0),q([G({attribute:!1})],$.prototype,`focusComposer`,void 0),q([G({attribute:!1})],$.prototype,`dashboardExpanded`,void 0),q([G({attribute:!1})],$.prototype,`routeFace`,void 0),q([G({attribute:!1})],$.prototype,`onFaceChange`,void 0),q([G({attribute:!1})],$.prototype,`onFocusPane`,void 0),q([G({attribute:!1})],$.prototype,`onSessionDeleted`,void 0),q([G({attribute:!1})],$.prototype,`presentationTitle`,void 0),q([G({attribute:!1})],$.prototype,`narrow`,void 0),q([G({attribute:!1})],$.prototype,`mergedChrome`,void 0),q([G({attribute:!1})],$.prototype,`navDrawerOpen`,void 0),q([G({attribute:!1})],$.prototype,`onboarding`,void 0),q([G({attribute:!1})],$.prototype,`onOpenSplitView`,void 0),q([G({attribute:!1})],$.prototype,`onSplitDown`,void 0),q([G({attribute:!1})],$.prototype,`onSplitRight`,void 0),q([G({attribute:!1})],$.prototype,`onClosePane`,void 0),q([G({attribute:!1})],$.prototype,`boardProvider`,void 0),q([Fr()],$.prototype,`paneWidth`,void 0),q([Fr()],$.prototype,`headerRenameValue`,void 0),q([Fr()],$.prototype,`headerPlatform`,void 0),q([Fr()],$.prototype,`headerCopiedAction`,void 0),q([Fr()],$.prototype,`headerPlacementMovingKey`,void 0),q([Fr()],$.prototype,`headerPlacementReclaimingKey`,void 0),q([Fr()],$.prototype,`headerPlacementRestartingKey`,void 0),q([Fr()],$.prototype,`sessionSharingStates`,void 0),q([Fr()],$.prototype,`resetConfirmation`,void 0),q([Fr({hasChanged:(e,t)=>!!e!=!!t})],$.prototype,`headerRenameSession`,void 0),q([Fr()],$.prototype,`catalogMessages`,void 0),q([Fr()],$.prototype,`catalogLoading`,void 0),q([Fr()],$.prototype,`loadingOlder`,void 0)})))()}function fC(e){return JSON.stringify([e.question,e.answer,e.ts])}function pC(e,t){let n=e.turns.flatMap(e=>e.attachments??[]),r=[...e.responses],i=t.map(e=>({exchange:e,key:fC(e)}));for(;r.length;){let e=0;if(r.every(([,t])=>(e=i.findIndex((n,r)=>r>=e&&n.key===t)+1,e>0)))break;r.shift()}let a=i.map(({exchange:e,key:t},n)=>{let i=r[0]?.[1]===t?r.shift():void 0;return{turn:i?.[0]??{status:`answered`,...e},key:t,position:n,fresh:!i}}),o=[...a],s=new Map,c=new Set(a.filter(({turn:t,fresh:n})=>!n&&!e.turns.includes(t)).map(({turn:e})=>e)),l=[...c,...e.turns].flatMap(e=>{let t=o.findIndex(({turn:t,fresh:n})=>e.status===`answered`?e===t:e.status===`failed`&&e.question===t.question&&n),n=t<0?void 0:o.splice(t,1)[0];return n&&(Object.assign(e,n.turn),delete e.attachments,n.turn=e,s.set(e,n.position)),!n&&e.status===`answered`?[]:[e]});for(let{turn:e,position:t}of o){let n=l.findLastIndex(e=>(s.get(e)??1/0)<t),r=l.findIndex((e,t)=>t>n&&e.status===`answered`);s.set(e,t),l.splice(r<0?l.length:r,0,e)}e.turns=l.filter(e=>!c.has(e)).slice(-24),Xc(n,[e.turns.flatMap(e=>e.attachments??[])]),e.responses=new Map(a.slice(-24).map(({turn:e,key:t})=>[e,t]))}function mC(e,t){return`${t?.trim()??``}\0${e.trim()}`}function hC(e){let t=e.flatMap(e=>e.selectionAnnotation?[Av(e.selectionAnnotation)]:[]);return t.length?t.join(`

`):void 0}function gC(e,t,n,r,i,a){let o=hC(i??[]),s=i?.filter(e=>!e.selectionAnnotation);return s?.length&&yt(a),e.request(`sessions.companion.ask`,{sessionKey:t,...r?{agentId:r}:{},question:n,...o?{selectionContext:o}:{},...s?.length?{attachments:Yf(s)}:{}},{timeoutMs:vC})}var _C,vC,yC,bC;function xC(){return(xC=e((()=>{ei(),Ya(),F(),Be(),pt(),Tl(),il(),Kp(),Jg(),_C=`SESSION_COMPANION_BUSY`,vC=7e4,yC=new Map([[`context-unavailable`,`history-unavailable`],[`session-missing`,`missing`],[`rate-limited`,`rate-limited`],[`image-input-unsupported`,`image-unsupported`],[`utility-model-unavailable`,`model-unavailable`]]),bC=class{constructor(e=()=>{}){this.notify=e,this.threads=new Map,this.hydrationTokens=new Map,this.submissionTokens=new Map}view(e,t){return this.get(mC(e,t))}setDraft(e,t,n){let r=this.get(mC(e,n));r.draft!==t&&(r.draft=t,r.draftRevision+=1,this.notify())}setAttachments(e,t,n){if((hC(t)?.length??0)>16e3)return Lt({message:V(`chat.rail.selectionTooLong`)}),!1;let r=this.get(mC(e,n));return r.attachments=t,this.notify(),!0}async hydrate(e,t,n){let r=e.trim();if(!r)return;let i=mC(r,n),a=this.get(i),o=Symbol(i);this.hydrationTokens.set(i,o),a.loading=!0,this.notify();try{for(;this.submissionTokens.has(i)||a.pendingResets.size;)await Promise.all([this.submissionTokens.get(i)?.promise,...[...a.pendingResets].map(e=>e.promise)]);if(this.hydrationTokens.get(i)!==o)return;let e=a.revision,n=await t(r);for(;a.pendingResets.size;)await Promise.all([...a.pendingResets].map(e=>e.promise));if(this.hydrationTokens.get(i)!==o||a.revision!==e)return;pC(a,n.exchanges),a.revision+=1,this.notify()}catch{}finally{this.hydrationTokens.get(i)===o&&(this.hydrationTokens.delete(i),a.loading=!1,this.notify())}}async submit(e,t,n,r){let i=e.trim(),a=typeof t==`string`?t.trim():t.question;if(!i||!a)return;let o=mC(i,r),s=this.get(o);if(s.turns.some(e=>e.status===`pending`)||s.attachmentReads?.pendingReads||typeof t!=`string`&&(!s.turns.includes(t)||t.status!==`failed`))return;let c=typeof t==`string`?s.attachments:t.attachments,l={question:a,status:`pending`,...c?.length?{attachments:c}:{}};if(typeof t==`string`){let e=[...s.turns,l];for(let t of e.slice(0,-24))At(t.attachments??[]);s.turns=e.slice(-24),s.attachments=[],s.draft=``,s.draftRevision+=1}else s.turns=s.turns.map(e=>e===t?l:e);s.revision+=1;let u=So();this.submissionTokens.set(o,u),this.notify();try{let e=await n(i,a,l.attachments);if(this.submissionTokens.get(o)!==u)return;At(l.attachments??[]),delete l.attachments,Object.assign(l,{status:`answered`,answer:e.answer,ts:e.ts}),s.responses.set(l,fC({question:a,...e})),s.responses=new Map([...s.responses].slice(-24))}catch(e){if(this.submissionTokens.get(o)!==u)return;let t=Ja(Ja(e).details),n=Xa(t,`reason`)??null,r=n===`image-input-unsupported`,i=t.code===_C?`busy`:yC.get(n??``)??`unavailable`;Object.assign(l,{status:`failed`,hint:i,retryable:r||!!Ja(e).retryable||n===null})}finally{u.resolve(),this.submissionTokens.get(o)===u&&(this.submissionTokens.delete(o),s.revision+=1,this.notify())}}async reset(e,t,n){let r=e.trim();if(!r)return;let i=mC(r,n),a=this.get(i),o=new Set([...a.turns,...a.responses.keys()]),s=a.draftRevision,c=a.attachmentReads,l=[...c?.project(a.attachments??[])??[]],u=new Set([...(a.attachments??[]).map(({id:e})=>e),...l.map(({attachment:e})=>e.id)]),d=this.submissionTokens.get(i),f=this.hydrationTokens.get(i),p=So();a.pendingResets.add(p);try{if(await t(r),this.threads.get(i)!==a)return;let e=[...a.attachments??[],...a.turns.flatMap(e=>e.attachments??[])];a.turns=a.turns.filter(e=>!o.has(e)),a.responses=new Map([...a.responses].filter(([e])=>!o.has(e))),a.draftRevision===s&&(a.draft=``,a.draftRevision+=1);for(let e of l)c?.remove(e);a.attachments=(a.attachments??[]).filter(({id:e})=>!u.has(e)),d&&this.submissionTokens.get(i)===d&&(this.submissionTokens.delete(i),d.resolve()),f&&this.hydrationTokens.get(i)===f&&(this.hydrationTokens.delete(i),a.loading=!1),Xc(e,[a.attachments??[],a.turns.flatMap(e=>e.attachments??[])]),a.revision+=1,this.notify()}finally{a.pendingResets.delete(p),p.resolve()}}retire(e,t){let n=e?mC(e,t):null;for(let[e,t]of this.threads)if(!(n&&n!==e)){t.attachmentReads?.abortReads(),At(t.attachments??[]);for(let e of t.turns)At(e.attachments??[])}for(let e of[this.threads,this.hydrationTokens,this.submissionTokens])n?e.delete(n):e.clear();this.notify()}get(e){let t=this.threads.get(e);return t||(t={turns:[],loading:!1,draft:``,attachments:[],attachmentReads:new al(this.notify),revision:0,draftRevision:0,pendingResets:new Set,responses:new Map},this.threads.set(e,t)),t}}})))()}var SC;function CC(){return(CC=e((()=>{ei(),F(),Gh(),_t(),Be(),pt(),dC(),xC(),Q(),jg(),Jg(),vv(),SC=class extends ${constructor(...e){super(...e),this.sessionCompanionHydrationKey=``,this.sessionCompanionFocusGeneration=0,this.sessionCompanionPresented=!1,this.sessionCompanionThreads=new bC(()=>{this.requestUpdate()}),this.setSessionObserverVisibility=e=>{let t=this.state;t?.connected&&t.client&&et(t.client,e).catch(()=>void 0),this.requestUpdate()},this.submitSessionCompanionQuestion=async e=>{let t=this.state;if(!t||!t.sessionKey)return;let{sessionKey:n,client:r,connected:i}=t,a=Y(t);this.requestSessionRail(`open`);let o=typeof e==`string`?e:e.question;if(o.trim()){if(!i||!r){this.sessionCompanionThreads.setDraft(n,o,a);return}if((typeof e==`string`?this.sessionCompanionThreads.view(n,a).attachments:e.attachments)?.some(e=>!e.selectionAnnotation)&&!$e(t.uploadConfig)){Lt({message:tt()});return}await this.sessionCompanionThreads.submit(n,e,(e,n,i)=>gC(r,e,n,a,i,t.uploadConfig),a)}},this.stageSessionCompanionAttachment=(e,t)=>{let n=this.state;if(!n||n.sessionKey!==t||!e.selectionAnnotation)return!1;let r=Y(n),i=this.sessionCompanionThreads.view(t,r),a=[...i.attachments??[],e];if(Av({...e.selectionAnnotation,comment:``}).length>16e3)Lt({message:V(i.draft.trim()?`chat.rail.selectionTooLong`:`chat.rail.selectionQuoteOnly`)});else if(!this.sessionCompanionThreads.setAttachments(t,a,r))return!1;return i.draft.trim()||this.sessionCompanionThreads.setDraft(t,Xh(e.selectionAnnotation.text)??``,r),this.requestSessionRail(`open`),!0}}restorePaneSidebarLayout(e){if(!this.compact)return e;let t=e.columns[0]?.panels.find(e=>e.slot===`conversation`);return{...t?g_(e,t.id):e,open:!1,expanded:!1}}setChatSidePanelOpen(e,t){let r=this.state;if(!r)return;let i=t??r.sidebarLayout,a=Y_(i,e);i.columns[0]?.panels.some(e=>e.slot===`companion`)&&this.setSessionObserverVisibility(Ae(a,`companion`)),this.commitSidebarLayout(a,n(i)?.slot===`dashboard`?{dashboardPresentation:`personal`}:void 0)}requestSessionRail(e){let t=this.state;if(!t)return;let n=e===`toggle`&&Ae(t.sidebarLayout,`companion`),r=n?O_:dv;this.commitSidebarLayout(r(t.sidebarLayout,`companion`)),this.setSessionObserverVisibility(!n)}requestSubagentsPanel(e){this.requestBackgroundPanel(`subagents`,e)}showSubagents(e){let t=this.state?.sessionKey,n=()=>(this.subagentsShowRequest===n&&(this.subagentsShowRequest=void 0,this.requestUpdate()),this.state?.sessionKey===t?e:void 0);this.subagentsShowRequest=n,this.requestUpdate(),this.requestBackgroundPanel(`subagents`,`open`)}presentSidebarLayout(e){return this.paneWidth<680?z_(e):e}isSlotShown(e,t){return Ae(this.presentSidebarLayout(e),t)}requestBackgroundPanel(e,t){let n=this.state;if(!n)return;let r=t===`toggle`&&Ae(n.sidebarLayout,e);if(!r&&this.paneWidth<680){let e=this.ownerDocument.activeElement,t=e instanceof HTMLElement&&this.contains(e)?e:null,n=()=>(this.sideFocusOrigin===n&&(this.sideFocusOrigin=void 0),t);this.sideFocusOrigin=n}this.commitSidebarLayout(r?O_(n.sidebarLayout,e):dv(n.sidebarLayout,e))}syncSessionCompanionPresentation(e){(this.sessionCompanionPresented!==e||!e&&this.sessionCompanionFocusRequest!==void 0)&&(this.sessionCompanionPresented=e,e&&this.state?this.sessionCompanionFocusRequest??=this.captureSessionCompanionFocus(this.state).requestFocus:(this.sessionCompanionFocusGeneration+=1,this.sessionCompanionFocusRequest=void 0))}captureSessionCompanionFocus(e){let t=e.sessionKey,n=Y(e),r=this.connectionGeneration,i=this.sessionCompanionFocusGeneration,a=mg(this.presentationId),o=a.editRevision,s=e.chatMessage,c=()=>this.state===e&&e.sessionKey===t&&Y(e)===n&&this.connectionGeneration===r&&this.sessionCompanionFocusGeneration===i&&a.editRevision===o&&e.chatMessage===s&&this.sessionCompanionPresented&&(this.ownerDocument.activeElement===this.ownerDocument.body||this.contains(this.ownerDocument.activeElement))&&this.isConnected&&this.active&&this.visuallyPresented&&this.presented,l=()=>(this.sessionCompanionFocusRequest===l&&(this.sessionCompanionFocusRequest=void 0,this.requestUpdate()),c());return{ownsFocus:c,requestFocus:l}}async openSessionCompanion(e,t){let{ownsFocus:n,requestFocus:r}=this.captureSessionCompanionFocus(e);this.sessionCompanionFocusRequest=r,this.requestUpdate(),await this.submitSessionCompanionQuestion(t),n()&&(this.sessionCompanionFocusRequest=r,this.requestUpdate())}hydrateSessionCompanion(e){let t=this.state;if(!t?.connected||!t.client||!e||L(e))return;let n=Y(t),r=`${this.connectionGeneration}\0${n}\0${e}`;this.sessionCompanionHydrationKey!==r&&(this.sessionCompanionHydrationKey=r,this.sessionCompanionThreads.hydrate(e,e=>t.client.request(`sessions.companion.state`,{sessionKey:e,...n?{agentId:n}:{}}),n))}}})))()}var wC,TC;function EC(){return(EC=e((()=>{za(),gs(),F(),Fe(),zt(),Ce(),R(),Be(),CC(),Q(),h_(),wC=`session.members.listEvidence`,TC=class extends SC{constructor(...e){super(...e),this.clearSessionCompanion=async()=>{let e=this.captureConnectionScope(),t=e?.state.sessionKey;if(!e||!t)return;let n=Y(e.state);await this.sessionCompanionThreads.reset(t,t=>e.client.request(`sessions.companion.reset`,{sessionKey:t,...n?{agentId:n}:{}}),n).catch(n=>{this.presented&&this.isConnectionScopeCurrent(e)&&e.state.sessionKey===t&&this.publishHeaderError(n)})}}setSessionSharingState(e,t){this.sessionSharingStates=new Map(this.sessionSharingStates).set(e,t)}sessionSharingAgentId(e){return e===`global`?this.state?Y(this.state):void 0:Bt(e)?.agentId}sessionSharingCacheKey(e){return`${this.sessionSharingAgentId(e)??``}\0${e}`}currentSessionSharingRow(e,t){let n=e.state.sessionsResult?.sessions.find(e=>z(e.key,t.key));if(!n||!F_(t)||!F_(n))return null;if(n===t)return n;let r=t.sessionId?.trim(),i=n.sessionId?.trim();return r&&i&&r===i?n:null}ownsSessionSharing(e,t){return this.ownsHeaderOutcomeScope(e)&&this.currentSessionSharingRow(e,t)!==null}async loadSessionSharing(e,t=!1){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null;if(!n||!r||!b(n.context.gateway.snapshot,{method:wC,requiredScope:`operator.read`}).allowed)return;let i=this.sessionSharingCacheKey(r.key),a=this.sessionSharingStates.get(i);if(a?.loading&&!t)return;let o={...a,loading:!0,error:void 0},s=()=>this.sessionSharingStates.get(i)===o;this.setSessionSharingState(i,o);let c;try{c={loading:!1,result:await n.client.request(wC,{sessionKey:r.key,...this.sessionSharingAgentId(r.key)?{agentId:this.sessionSharingAgentId(r.key)}:{}})}}catch(e){c={loading:!1,error:B(e)}}if(!this.ownsSessionSharing(n,r)||!s()){if(this.isConnectionScopeCurrent(n)&&s()){let e=new Map(this.sessionSharingStates);e.delete(i),this.sessionSharingStates=e}return}this.setSessionSharingState(i,c)}failSharing(e,t,n,r){this.ownsHeaderOutcomeScope(e)&&(this.setSessionSharingState(t,{...this.sessionSharingStates.get(t)??{loading:!1},loading:!1,error:B(r)}),z(this.state?.sessionKey,n)&&this.publishHeaderError(r,e.headerOutcomeOwner))}async setSessionPublicShare(e,t){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null,i=r?.sessionId;if(!n||!r||!i)return;let a=()=>b(n.context.gateway.snapshot,{method:`session.publicShare.set`,requiredScope:`operator.write`}).allowed,o=()=>this.ownsHeaderOutcomeScope(n)&&this.currentSessionSharingRow(n,r)?.sessionId===i&&z(n.state.sessionKey,r.key),s=this.sessionSharingCacheKey(r.key),c=this.sessionSharingStates.get(s);if(!a()||!o()||c?.loading)return;let l={...c,loading:!0,error:void 0};this.setSessionSharingState(s,l);try{if(t&&(!o()||!a()||!await ps({title:V(`chat.sessionSharing.publicConfirmTitle`),message:V(`chat.sessionSharing.publicConfirmMessage`),confirmLabel:V(`chat.sessionSharing.publicConfirmEnable`),danger:!0}))||!o()||!a())return;let e=await n.client.request(`session.publicShare.set`,{sessionKey:r.key,agentId:this.sessionSharingAgentId(r.key),expectedSessionId:i,enabled:t});if(!o()){this.sessionSharingHydrationTargets.delete(s);return}this.setSessionSharingState(s,{loading:!1,...c?.result?{result:{...c.result,publicShare:e.publicShare}}:{}}),Lt({message:V(t?`chat.sessionSharing.publicEnabled`:`chat.sessionSharing.publicDisabled`)}),await this.loadSessionSharing(r,!0)}catch(e){o()&&this.failSharing(n,s,r.key,e)}finally{this.sessionSharingStates.get(s)===l&&this.setSessionSharingState(s,{...c,loading:!1})}}async copySessionPublicLink(e){let t=this.captureConnectionScope(),n=t?this.currentSessionSharingRow(t,e):null;if(!t||!n)return;let r=this.sessionSharingStates.get(this.sessionSharingCacheKey(e.key))?.result?.publicShare,i=n.sessionId;if(!r||!i)return;let a=()=>this.ownsHeaderOutcomeScope(t)&&this.currentSessionSharingRow(t,n)?.sessionId===i;try{let e=t.context.gateway,r=e.snapshot.hello?.controlUiUrl,i=r??t.client.gatewayUrl??e.connection.gatewayUrl,o=new URL(i||window.location.href);o.protocol=o.protocol.replace(/^ws/u,`http`);let s=$a({namespace:`chat`,sessionKey:n.key,fallbackAgentId:this.sessionSharingAgentId(n.key),basePath:r?o.pathname:t.context.basePath,displayName:n.label||n.displayName,shortIdLength:32});if(!s)return;let c=await O(new URL(s,o.origin).href,a);a()&&Lt({message:V(c?`common.copied`:`common.copyFailed`)})}catch(e){a()&&this.publishHeaderError(e)}}setSessionVisibility(e,t){return this.mutateSessionSharing(e,{visibility:t})}setSessionMember(e,t,n){return this.mutateSessionSharing(e,{identityId:t,member:n})}async mutateSessionSharing(e,t){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null;if(!n||!r||`visibility`in t&&t.visibility===r.visibility)return;let i=this.sessionSharingAgentId(r.key),a=this.sessionSharingCacheKey(r.key),o=`visibility`in t?`session.visibility.set`:t.member?`session.members.add`:`session.members.remove`,s={sessionKey:r.key,...`visibility`in t?{visibility:t.visibility}:{identityId:t.identityId},...i?{agentId:i}:{}};if(b(n.context.gateway.snapshot,{method:o,requiredScope:`operator.write`}).allowed)try{if(await n.client.request(o,s),!this.ownsSessionSharing(n,r))return;let e=`visibility`in t;if(!e&&(await this.loadSessionSharing(r,!0),!this.ownsSessionSharing(n,r)))return;let c=await n.sessions.reconcileMutation(i),l=this.currentSessionSharingRow(n,r);if(!this.ownsHeaderOutcomeScope(n)||!l)return;if(c.status===`failed`){this.failSharing(n,a,r.key,c.error);return}e&&await this.loadSessionSharing(l,!0)}catch(e){if(!this.ownsSessionSharing(n,r))return;this.failSharing(n,a,r.key,e)}}captureConnectionScope(){let e=this.state;if(!e?.client)return null;let t={context:this.context,state:e,client:e.client,generation:this.connectionGeneration,headerOutcomeOwner:this.headerOutcomeOwner,sessions:this.context.sessions};return this.isConnectionScopeCurrent(t)?t:null}isConnectionScopeCurrent(e){return this.isConnected&&this.context===e.context&&this.state===e.state&&e.state.connected&&e.state.client===e.client&&this.connectedClient===e.client&&e.context.gateway.snapshot.phase===`connected`&&e.context.gateway.snapshot.client===e.client&&this.connectionGeneration===e.generation}ownsHeaderOutcomeScope(e){return this.isConnectionScopeCurrent(e)&&this.ownsHeaderOutcome(e.headerOutcomeOwner)}}})))()}var DC;function OC(){return(OC=e((()=>{Tr(),zt(),di(),_t(),Ue(),R(),EC(),Q(),DC=class extends TC{constructor(...e){super(...e),this.messageReactions=new Map,this.reactionTarget=``,this.reactionGeneration=0,this.reactionRevisions=new Map,this.reactionWrites=new Map,this.handleMessageReaction=(e,t,n)=>{this.setMessageReaction(e,t,n)},this.setMessageReaction=async(e,t,n)=>{let r=this.captureConnectionScope();if(!r||!this.canReactToCurrentSession())return;this.syncSessionReactions();let i=this.reactionGeneration,a=this.reactionRevisions.get(e)??0,o=r.state.sessionKey,s=Z(r.state)?.sessionId??r.state.currentSessionId,c=Symbol(`reaction`);this.reactionWrites.set(e,c);let l=()=>i===this.reactionGeneration&&this.reactionWrites.get(e)===c&&this.isConnectionScopeCurrent(r)&&r.state.sessionKey===o&&(Z(r.state)?.sessionId??r.state.currentSessionId)===s;try{let i=await r.client.request(`session.reactions.set`,{sessionKey:o,messageId:e,emoji:t,remove:n,...D(r.state,o)});if(!l())return;(this.reactionRevisions.get(e)??0)===a&&(this.messageReactions=new Map(this.messageReactions).set(e,i.reactions),this.reactionReadUpdates?.set(e,i.reactions))}catch(e){l()&&(r.state.chatError=B(e),r.state.lastError=r.state.chatError)}finally{i===this.reactionGeneration&&this.reactionWrites.get(e)===c&&(this.reactionWrites.delete(e),this.requestUpdate())}}}resetSessionReactions(){this.reactionGeneration+=1,this.reactionTarget=``,this.messageReactions=new Map,this.reactionReadUpdates=void 0,this.reactionRevisions.clear(),this.reactionWrites.clear()}canReactToCurrentSession(){let e=this.state;return!!(e&&xr(this.context.gateway.snapshot,Z(e),{archived:this.isCurrentSessionArchived(e),catalog:!!L(e.sessionKey)}))}syncSessionReactions(){let e=this.captureConnectionScope(),t=e?.state,n=t&&(Z(t)?.sessionId??t.currentSessionId),r=e&&t&&n&&!L(t.sessionKey)&&K(e.context.gateway.snapshot,`session.reactions.list`),i=r?JSON.stringify([e.generation,t.assistantAgentId,t.sessionKey,n]):``;if(this.reactionTarget===i||(this.resetSessionReactions(),this.reactionTarget=i,!r))return;let a=this.reactionGeneration,o=t.sessionKey,s=new Map;this.reactionReadUpdates=s;let c=()=>a===this.reactionGeneration&&this.isConnectionScopeCurrent(e)&&t.sessionKey===o&&(Z(t)?.sessionId??t.currentSessionId)===n;e.client.request(`session.reactions.list`,{sessionKey:o,...D(t,o)}).then(e=>{c()&&e.sessionId===n&&(this.messageReactions=new Map([...Object.entries(e.reactions),...s]))}).catch(e=>{c()&&(t.chatError=B(e))}).finally(()=>{a===this.reactionGeneration&&(this.reactionReadUpdates=void 0,this.requestUpdate())})}handleSessionReactionEvent(e){let t=this.state;t?.connected&&Qe({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:t.sessionKey},e.sessionKey,e.agentId)&&e.sessionId===(Z(t)?.sessionId??t.currentSessionId)&&(this.syncSessionReactions(),this.reactionRevisions.set(e.messageId,(this.reactionRevisions.get(e.messageId)??0)+1),this.reactionReadUpdates?.set(e.messageId,e.reactions),this.messageReactions=new Map(this.messageReactions).set(e.messageId,e.reactions),this.requestUpdate())}}})))()}function kC(e,t){let n=w(e);if(!n||!Qe(t,n.key,n.agentId??void 0))return;let r=J(J(e)?.message);if(qa(r?.role)?.toLowerCase()!==`user`)return;let i=Xt(J(r?.__openclaw)?.senderIdentity);return i?.type===`profile`?i.id:void 0}function AC(){return(AC=e((()=>{qt(),l(),R()})))()}var jC,MC,NC,PC,FC,IC;function LC(){return(LC=e((()=>{$t(),F(),zt(),di(),lm(),Ue(),R(),OC(),pp(),Q(),AC(),h_(),jC=2500,MC=1e4,NC=3e4,PC=300,FC=250,IC=class extends DC{constructor(...e){super(...e),this.typingActiveIds=new Set,this.typingViews=[]}syncSelectedSessionSharing(e){let t=e?.sessionId?.trim();if(!e||!t||!this.presented||!F_(e))return;let n=this.sessionSharingCacheKey(e.key);if(this.sessionSharingHydrationTargets.get(n)===t&&this.sessionSharingStates.has(n))return;this.sessionSharingHydrationTargets.set(n,t);let r=new Map(this.sessionSharingStates);r.delete(n),this.sessionSharingStates=r,this.loadSessionSharing(e,!0)}suggestionMatchesCurrentSession(e){let t=this.state;return!!(t?.connected&&Qe({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:t.sessionKey},e.sessionKey,e.agentId))}hasMultipleIdentities(){return Pd(this.presencePayload)}resetSessionSuggestions(){this.sessionSuggestionsRequestVersion+=1,this.sessionSuggestionsRefreshQueued=!1,this.sessionSuggestions=[],this.sessionSuggestionRole=void 0,this.sessionSuggestionBusyIds.clear(),this.sessionSuggestionAddOperation=void 0,this.sessionSuggestionEditOperation=void 0}syncSessionSuggestionTarget(e,t){let n=t?`${e}\0${t.key}\0${t.sessionId??``}\0${t.visibility??`shared`}\0${t.sharingRole??`owner`}`:``;n!==this.sessionSuggestionTargetSignature&&(this.sessionSuggestionTargetSignature=n,this.resetSessionSuggestions(),this.clearTypingActors(),this.refreshSessionSuggestions())}refreshSessionSuggestions(){if(this.sessionSuggestionsRefreshPromise)return this.sessionSuggestionsRefreshVersion!==this.sessionSuggestionsRequestVersion&&(this.sessionSuggestionsRefreshQueued=!0),this.sessionSuggestionsRefreshPromise;let e=++this.sessionSuggestionsRequestVersion;this.sessionSuggestionsRefreshVersion=e;let t=this.loadSessionSuggestions(e).finally(()=>{this.sessionSuggestionsRefreshPromise===t&&(this.sessionSuggestionsRefreshPromise=void 0,this.sessionSuggestionsRefreshVersion=void 0,this.sessionSuggestionsRefreshQueued&&(this.sessionSuggestionsRefreshQueued=!1,this.refreshSessionSuggestions()))});return this.sessionSuggestionsRefreshPromise=t,t}async loadSessionSuggestions(e){let t=this.sessionSuggestionTargetSignature,n=this.captureConnectionScope(),r=n?Z(n.state):void 0;if(!n||!r||!this.hasMultipleIdentities()||!K(n.context.gateway.snapshot,`session.suggestions.list`)){this.sessionSuggestions=[],this.sessionSuggestionRole=void 0,this.requestUpdate();return}let i=n.state.sessionKey;try{let r=await n.client.request(`session.suggestions.list`,{sessionKey:i,...D(n.state,i)});if(!this.isConnectionScopeCurrent(n)||n.state.sessionKey!==i||e!==this.sessionSuggestionsRequestVersion||t!==this.sessionSuggestionTargetSignature)return;this.sessionSuggestions=r.suggestions,this.sessionSuggestionRole=r.role,this.requestUpdate()}catch{e===this.sessionSuggestionsRequestVersion&&t===this.sessionSuggestionTargetSignature&&(this.sessionSuggestions=[],this.sessionSuggestionRole=void 0,this.requestUpdate())}}handleSessionSuggestionEvent(e){if(!this.hasMultipleIdentities()||!this.suggestionMatchesCurrentSession(e.suggestion))return;let t=this.sessionSuggestionsRefreshPromise!==void 0||this.sessionSuggestionRole!==void 0;this.sessionSuggestionsRequestVersion+=1;let n=this.context.gateway.snapshot.selfUser?.id;(this.sessionSuggestionRole!==`viewer`||e.suggestion.author.id===n)&&(this.sessionSuggestions=e.action===`added`?[...this.sessionSuggestions.filter(t=>t.id!==e.suggestion.id),e.suggestion].toSorted((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id)):e.suggestion.author.id===n?this.sessionSuggestions.map(t=>t.id===e.suggestion.id?e.suggestion:t):this.sessionSuggestions.filter(t=>t.id!==e.suggestion.id),this.sessionSuggestionBusyIds.delete(e.suggestion.id),this.requestUpdate(),t&&this.refreshSessionSuggestions())}async addCurrentSessionSuggestion(){let e=this.captureConnectionScope(),t=e?.state.chatMessage??``;if(!e||!t.trim()||this.sessionSuggestionAddOperation||!this.hasMultipleIdentities())return;if(e.state.chatMentions?.length||e.state.chatAttachments.length>0){e.state.chatError=V(e.state.chatMentions?.length?`chat.mentions.unsupported`:`chat.sessionSuggestions.attachmentsUnsupported`),e.state.lastError=e.state.chatError,e.state.requestUpdate?.();return}let n=e.state.sessionKey,r=Symbol(`session-suggestion-add`);this.sessionSuggestionAddOperation=r,this.requestUpdate();try{let i=await e.client.request(`session.suggestions.add`,{sessionKey:n,text:t,...D(e.state,n)});if(this.sessionSuggestionAddOperation!==r||!this.isConnectionScopeCurrent(e)||e.state.sessionKey!==n)return;e.state.chatMessage===t&&!e.state.chatMentions?.length&&e.state.handleChatDraftChange(``,[]),this.sessionSuggestions=[...this.sessionSuggestions.filter(e=>e.id!==i.suggestion.id),i.suggestion]}catch(t){this.sessionSuggestionAddOperation===r&&this.isConnectionScopeCurrent(e)&&(e.state.chatError=B(t),e.state.lastError=e.state.chatError)}finally{this.sessionSuggestionAddOperation===r&&(this.sessionSuggestionAddOperation=void 0,this.requestUpdate())}}async resolveCurrentSessionSuggestion(e,t){let n=this.captureConnectionScope();if(!n||this.sessionSuggestionBusyIds.has(e.id)||t===`edit`&&this.sessionSuggestionEditOperation!==void 0||!this.suggestionMatchesCurrentSession(e)||this.isCurrentSessionArchived(n.state)&&t!==`dismiss`)return;let r=n.state.sessionKey,i=this.sessionSuggestionTargetSignature,a=()=>this.isConnectionScopeCurrent(n)&&n.state.sessionKey===r&&this.sessionSuggestionTargetSignature===i,o=t===`edit`?{text:n.state.chatMessage,mentions:n.state.chatMentions?.map(e=>({...e}))}:void 0,s=t===`edit`?Symbol(`session-suggestion-edit`):void 0;s&&(this.sessionSuggestionEditOperation=s),this.sessionSuggestionBusyIds.add(e.id),t===`edit`&&(n.state.handleChatDraftChange(e.text,[]),queueMicrotask(()=>this.querySelector(pm)?.focus({preventScroll:!0}))),this.requestUpdate();try{let i=await n.client.request(`session.suggestions.resolve`,{sessionKey:r,id:e.id,resolution:t,...D(n.state,r)});if(!a())return;let o=this.sessionSuggestions.filter(t=>t.id!==e.id);this.sessionSuggestions=i.suggestion.author.id===this.context.gateway.snapshot.selfUser?.id?[...o,i.suggestion].toSorted((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id)):o}catch(r){a()&&(t===`edit`&&r instanceof Wn&&o!==void 0&&n.state.chatMessage===e.text&&!n.state.chatMentions?.length&&n.state.handleChatDraftChange(o.text,o.mentions??[]),n.state.chatError=B(r),n.state.lastError=n.state.chatError)}finally{a()&&(this.sessionSuggestionEditOperation===s&&(this.sessionSuggestionEditOperation=void 0),this.sessionSuggestionBusyIds.delete(e.id),this.requestUpdate())}}clearTypingActors(){this.clearTypingRequest();for(let e of this.typingTimers.values())window.clearTimeout(e);this.typingTimers.clear(),this.typingActors.clear(),this.typingActiveIds.clear(),this.refreshTypingPresentation()}pruneTypingActors(){let e=this.state;if(!e||this.typingActors.size===0)return;let t=I(e,e.sessionKey),n=ue(t.sessionKey,t.agentId),r=new Set(Nf(this.presencePayload).users.flatMap(e=>e.identity?.type===`profile`&&e.watchedSessions.includes(n)?[e.identity.id]:[])),i=!1;for(let e of this.typingActors.keys())r.has(e)||(this.removeTypingActor(e),i=!0);i&&this.refreshTypingPresentation()}handleSessionTypingEvent(e){let t=this.context.gateway.snapshot.selfUser?.id,n=this.state,r=n?Z(n):void 0;if(!this.hasMultipleIdentities()||e.actor.id===t||!n||r?.sessionId!==e.sessionId||!Qe({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:n.sessionKey},e.sessionKey,e.agentId))return;let i=this.typingTimers.get(e.actor.id);if(i!==void 0&&(window.clearTimeout(i),this.typingTimers.delete(e.actor.id)),!e.typing){this.removeTypingActor(e.actor.id),this.refreshTypingPresentation();return}let a=e.preview?MC:jC,o=Date.now(),s=o+NC,c={label:e.actor.label??e.actor.id,retireAt:e.preview?s:o+a,...e.preview?{preview:e.preview}:{}};this.typingActiveIds.add(e.actor.id),this.typingActors.set(e.actor.id,c);let l=()=>{if(this.typingActors.get(e.actor.id)!==c)return;this.typingTimers.delete(e.actor.id);let t=s-Date.now();if(!c.preview||t<=0){this.removeTypingActor(e.actor.id);let t=Date.now();for(let[e,n]of this.typingActors)n.retireAt<=t&&this.removeTypingActor(e)}else{if(!c.paused)for(let e of this.typingActiveIds){let t=this.typingActors.get(e);t?.preview&&t.retireAt-NC+MC<=Date.now()&&(t.paused=!0,this.typingActiveIds.delete(e))}let n=t-PC;n<=0&&(c.exitDurationMs=t),this.typingTimers.set(e.actor.id,window.setTimeout(l,n>0?n:t))}this.refreshTypingPresentation()};this.typingTimers.set(e.actor.id,window.setTimeout(l,a)),this.refreshTypingPresentation()}clearTypingActorForSessionMessage(e){let t=this.state;if(!t)return;let n=kC(e,{agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:t.sessionKey});n&&this.removeTypingActor(n)&&this.refreshTypingPresentation()}removeTypingActor(e){return this.typingActors.get(e)?(this.typingActiveIds.delete(e),window.clearTimeout(this.typingTimers.get(e)),this.typingTimers.delete(e),this.typingActors.delete(e)):!1}refreshTypingPresentation(){let e=[];for(let[t,n]of this.typingActors)if(e.push({id:t,label:n.label,...n.preview?{preview:n.preview}:{},...n.paused?{paused:!0}:{},...n.exitDurationMs===void 0?{}:{exitDurationMs:n.exitDurationMs}}),e.length===2)break;let t=0;for(let n of this.typingActiveIds){if(n===e[0]?.id||n===e[1]?.id)continue;let r=this.typingActors.get(n);r&&(t+=1,e.length<7&&e.push({id:n,label:r.label}))}let n=t>5?{several:!0}:void 0;e.length===this.typingViews.length&&e.every((e,t)=>{let n=this.typingViews[t];return n?.id===e.id&&n.label===e.label&&n.preview===e.preview&&n.paused===e.paused&&n.exitDurationMs===e.exitDurationMs})&&n?.several===this.typingOverflow?.several||(this.typingViews=e,this.typingOverflow=n,this.requestUpdate())}typingActorViews(){return this.typingViews}sendTypingState(e,t){let n=this.captureConnectionScope(),r=n?Z(n.state):void 0;if(!n||!r?.sessionId||!this.hasMultipleIdentities()){this.clearTypingRequest();return}let i=n.state.sessionKey,{sessionId:a,sharingRole:o,visibility:s}=r,c=()=>{let r=Z(n.state);if(!this.isConnectionScopeCurrent(n)||n.state.sessionKey!==i||r?.sessionId!==a||r.sharingRole!==o||r.visibility!==s||!this.hasMultipleIdentities())return;let c=e?t?.trim():void 0,l=c?Array.from(c).slice(-300).join(``):void 0;this.typingRequestSentAt=e?Date.now():void 0,n.client.request(`session.typing`,{sessionKey:i,sessionId:a,typing:e,...l?{preview:l}:{},...D(n.state,i)}).catch(()=>void 0)},l=e&&this.typingRequestSentAt!==void 0?FC-(Date.now()-this.typingRequestSentAt):0;if(l<=0){this.clearTypingRequest(),c();return}this.pendingTypingRequest=c,this.typingRequestTimer??=window.setTimeout(()=>{let e=this.pendingTypingRequest;this.typingRequestTimer=void 0,this.pendingTypingRequest=void 0,e?.()},l)}clearTypingRequest(){window.clearTimeout(this.typingRequestTimer),this.typingRequestTimer=void 0,this.typingRequestSentAt=void 0,this.pendingTypingRequest=void 0}}})))()}var RC;function zC(){return(zC=e((()=>{Ba(),$t(),Hn(),Tr(),F(),Fe(),zt(),di(),_t(),Te(),LC(),Q(),RC=class extends IC{constructor(...e){super(...e),this.taskSuggestions=[],this.taskSuggestionBusyIds=new Set,this.taskSuggestionCopiedIds=new Set,this.taskSuggestionOperations=new Map,this.taskSuggestionsRequestVersion=0,this.taskSuggestionSwapGeneration=0,this.navigateTaskSuggestion=(e,t)=>{let n=this.taskSuggestions.findIndex(t=>t.id===e);if(n<0||this.taskSuggestions.length<2)return;let r=t===`next`?1:-1,i=this.taskSuggestions[(n+r+this.taskSuggestions.length)%this.taskSuggestions.length];i&&(this.activeTaskSuggestionId=i.id,this.taskSuggestionSwapDirection=t,this.taskSuggestionSwapGeneration+=1,this.requestUpdate(),this.updateComplete.then(()=>{[...this.querySelectorAll(`.task-suggestion`)].find(e=>e.dataset.taskId===i.id)?.querySelector(`[data-task-${t===`next`?`next`:`prev`}]`)?.focus()}))},this.copyTaskSuggestionPrompt=async e=>{let t=await O(e.prompt);if(this.isConnected){if(!t){let e=V(`chat.taskSuggestions.copyPromptFailed`);this.state&&(this.state.lastError=e,this.state.chatError=e),this.requestUpdate();return}this.taskSuggestionCopiedIds.add(e.id),this.requestUpdate(),setTimeout(()=>{this.taskSuggestionCopiedIds.delete(e.id),this.isConnected&&this.requestUpdate()},2e3)}}}setTaskSuggestions(e){let t=e.filter(e=>this.taskSuggestionOperations.get(e.id)?.action!==`dismiss`);for(let e of this.taskSuggestionOperations.values()){if(e.action!==`accept`||!e.canDisplay())continue;let n=t.findIndex(t=>t.id===e.suggestion.id);n<0?t.push(e.suggestion):t[n]=e.suggestion}this.taskSuggestions=t,t.some(e=>e.id===this.activeTaskSuggestionId)||(this.activeTaskSuggestionId=t[0]?.id,this.taskSuggestionSwapDirection=void 0)}reconcileTaskSuggestionConnection(e){let t=new Set;for(let[n,r]of this.taskSuggestionOperations)(r.action===`dismiss`?e:!r.canDisplay())?(this.taskSuggestionOperations.delete(n),this.taskSuggestionBusyIds.delete(n),t.add(n)):r.action===`accept`&&r.outcome.phase===`starting`&&!r.isCurrent()&&(r.outcome={phase:`failed`,error:V(`chat.queue.deliveryUnconfirmed`)},this.taskSuggestionBusyIds.delete(n));this.setTaskSuggestions(e?[]:this.taskSuggestions.filter(e=>!t.has(e.id)))}async refreshTaskSuggestions(e){let t=++this.taskSuggestionsRequestVersion,n=this.captureConnectionScope();if(!n||!K(n.context.gateway.snapshot,`taskSuggestions.list`)||L(n.state.sessionKey)){this.setTaskSuggestions([]),this.requestUpdate();return}let r=n.state.sessionKey,i=Y(n.state),a=JSON.stringify([this.connectionGeneration,r,i]);if(e?.automatic){if(!this.secondarySessionReadsReady(this.explicitReadScope===a))return}else this.explicitReadScope=a;try{let e=await n.client.request(`taskSuggestions.list`,{agentId:i});if(t!==this.taskSuggestionsRequestVersion||!this.isConnectionScopeCurrent(n)||r!==n.state.sessionKey)return;this.setTaskSuggestions(e.suggestions.filter(e=>this.suggestionMatchesCurrentSession(e))),this.requestUpdate()}catch{}}handleTaskSuggestionEvent(e){if(e.action===`created`){if(!this.suggestionMatchesCurrentSession(e.suggestion))return;this.setTaskSuggestions([e.suggestion,...this.taskSuggestions.filter(t=>t.id!==e.suggestion.id)])}else{let t=this.taskSuggestionOperations.get(e.taskId);t?.action===`dismiss`&&(t.resolved=!0),this.setTaskSuggestions(this.taskSuggestions.filter(t=>t.id!==e.taskId)),t?.action!==`accept`&&this.taskSuggestionBusyIds.delete(e.taskId)}this.requestUpdate(),this.refreshTaskSuggestions({automatic:!0})}suggestionChatProps(e,t,n){let r=this.context.gateway.snapshot,i=r.hello?.auth??null,a=e&&sn(i),o=e&&Er(i),s=new Map(this.taskSuggestionOperations),c=e=>{let t=s.get(e.id);return t?.action!==`accept`||this.taskSuggestionOperations.get(e.id)===t&&t.canDisplay()};return{taskSuggestions:this.taskSuggestions.filter(e=>{let t=this.taskSuggestionOperations.get(e.id);return t?.action!==`accept`||t.canDisplay()}),activeTaskSuggestionId:this.activeTaskSuggestionId,taskSuggestionSwapDirection:this.taskSuggestionSwapDirection,taskSuggestionSwapGeneration:this.taskSuggestionSwapGeneration,onNavigateTaskSuggestion:this.navigateTaskSuggestion,taskSuggestionBusyIds:this.taskSuggestionBusyIds,taskSuggestionAcceptance:e=>{let t=this.taskSuggestionOperations.get(e);return t?.action===`accept`&&t.canDisplay()?t.outcome:void 0},canOpenTaskSuggestions:e&&r.phase===`connected`&&wn(i),onOpenTaskSuggestion:this.onPaneSessionChange?e=>{let t=this.taskSuggestionOperations.get(e.id),n=this.context.gateway.snapshot;n.phase===`connected`&&wn(n.hello?.auth??null)&&c(e)&&t?.action===`accept`&&t.canDisplay()&&t.outcome.phase===`started`&&this.onPaneSessionChange?.(this.paneId,t.outcome.sessionKey)}:void 0,sessionSuggestions:n?this.sessionSuggestions:[],sessionSuggestionRole:this.sessionSuggestionRole,sessionSuggestionBusyIds:this.sessionSuggestionBusyIds,sessionSuggestionsArchived:t,canResolveSessionSuggestions:a&&K(r,`session.suggestions.resolve`)===!0,onResolveSessionSuggestion:this.resolveCurrentSessionSuggestion.bind(this),canAcceptTaskSuggestions:o&&K(r,`taskSuggestions.accept`)===!0,canDismissTaskSuggestions:a&&K(r,`taskSuggestions.dismiss`)===!0,taskSuggestionCopiedIds:this.taskSuggestionCopiedIds,onCopyTaskSuggestionPrompt:this.copyTaskSuggestionPrompt,onChangeTaskRepository:(e,t)=>{let n=this.taskSuggestionOperations.get(e.id);c(e)&&n?.action===`accept`&&n.outcome.phase===`failed`&&n.outcome.repository&&(Object.assign(n.outcome.repository,t),this.requestUpdate())},onAcceptTaskSuggestion:(e,t,n)=>c(e)?this.resolveTaskSuggestion(e,`accept`,t,n):void 0,onDismissTaskSuggestion:e=>c(e)?this.resolveTaskSuggestion(e,`dismiss`):void 0}}async resolveTaskSuggestion(e,t,n=`local`,r){let i=this.captureConnectionScope();if(!i||!this.suggestionMatchesCurrentSession(e))return;let a=this.taskSuggestionOperations.get(e.id);if(a?.action===`dismiss`)return;if(a?.action===`accept`){if(!a.canDisplay()||a.outcome.phase===`starting`)return;if(a.outcome.phase===`started`){t===`dismiss`&&(this.taskSuggestionsRequestVersion+=1,this.taskSuggestionOperations.delete(e.id),this.setTaskSuggestions(this.taskSuggestions.filter(t=>t.id!==e.id)),this.requestUpdate());return}}let o=i.context.gateway.snapshot,s=o.hello?.auth??null;if(!K(o,`taskSuggestions.${t}`)||!(t===`accept`?Er(s):sn(s)))return;let c=i.state.sessionKey,l=qa(i.state.currentSessionId),u=!1,d=yr(i.context.gateway),f=o.hello?.auth?.recoveryScope??(i.client.recoveryScopeReady?i.client.recoveryScope:void 0),p=()=>{let e=qa(i.state.currentSessionId);l??=e,u||=!!(l&&e)&&e!==l;let t=i.context.gateway.snapshot,n=t.hello?.auth?.recoveryScope??(t.client?.recoveryScopeReady?t.client.recoveryScope:void 0);return f??=n,this.isConnected&&this.context===i.context&&this.state===i.state&&i.state.sessionKey===c&&!u&&yr(i.context.gateway)===d&&(!n||n===f)},m=()=>this.isConnectionScopeCurrent(i)&&p(),h=t===`accept`?{action:t,suggestion:a?.suggestion??e,mode:a?.mode??n,cwd:r??a?.cwd,canDisplay:p,isCurrent:m,outcome:{phase:`starting`}}:{action:t,resolved:!1},g=this.taskSuggestions.findIndex(t=>t.id===e.id),_=()=>m()&&this.taskSuggestionOperations.get(e.id)===h;this.taskSuggestionOperations.set(e.id,h),t===`accept`&&this.taskSuggestionBusyIds.add(e.id),this.setTaskSuggestions(this.taskSuggestions),this.requestUpdate();let v=!1;try{if(h.action===`accept`){let t=await i.client.request(`taskSuggestions.accept`,{taskId:e.id,mode:h.mode,...h.cwd?{cwd:h.cwd}:{}});if(!_())return;let n=qa(t.key);if(t.taskId!==e.id||!n)throw Error(V(`chat.taskSuggestions.startUnconfirmed`));h.outcome={phase:`started`,sessionKey:n,href:Oe({face:`chat`,sessionKey:n,fallbackAgentId:e.agentId??Y(i.state),basePath:i.context.basePath,exactKey:!0}).href}}else{if(await i.client.request(`taskSuggestions.dismiss`,{taskId:e.id}),!_())return;this.setTaskSuggestions(this.taskSuggestions.filter(t=>t.id!==e.id))}}catch(e){if(!_())return;if(h.action===`dismiss`){if(h.resolved)return;v=g>=0}else{let t=e instanceof Wn?e.details:void 0,n=h.mode===`worktree`&&t&&typeof t==`object`&&`code`in t&&t.code===Ra.TASK_WORKTREE_SOURCE_REQUIRED?{cwd:h.cwd??h.suggestion.cwd,open:!0,projects:[]}:void 0;h.outcome={phase:`failed`,error:B(e),...n?{repository:n}:{}},n&&i.client.request(`projects.list`,{}).then(e=>{_()&&h.outcome.phase===`failed`&&h.outcome.repository===n&&(n.projects=e.projects.filter(e=>!!e.repoRoot),this.requestUpdate())}).catch(()=>{})}i.state.lastError=B(e),i.state.chatError=i.state.lastError}finally{if(this.taskSuggestionOperations.get(e.id)===h&&(h.action===`dismiss`&&this.taskSuggestionOperations.delete(e.id),this.taskSuggestionBusyIds.delete(e.id),h.action===`accept`&&!m()&&(this.reconcileTaskSuggestionConnection(!1),this.requestUpdate()),this.isConnectionScopeCurrent(i)&&i.state.sessionKey===c)){if(v){a?.action===`accept`&&this.taskSuggestionOperations.set(e.id,a);let t=[...this.taskSuggestions];t.splice(g,0,e),this.setTaskSuggestions(t)}this.requestUpdate(),t===`dismiss`&&this.refreshTaskSuggestions()}}}}})))()}var BC;function VC(){return(VC=e((()=>{Co(),Ro(),F(),zt(),we(),g(),di(),Ed(),Ce(),dl(),_t(),Ue(),R(),Ch(),il(),yS(),xd(),af(),pp(),zC(),bm(),Q(),sv(),nc(),Hs(),BC=class extends RC{constructor(...e){super(...e),this.deferredSessionHydration=null,this.hiddenRunReadRequests=new Map,this.dismissSessionPullRequest=e=>{this.dismissSessionPullRequestId(D_(e))},this.dismissSessionPullRequestsBranch=e=>{this.dismissSessionPullRequestId(Sv(e))}}resetSessionReadAcknowledgements(){this.unreadPatchGuard.beginActivation(this.state?.sessionKey??``),this.hiddenRunReadRequests.clear()}secondarySessionReadsReady(e=!1){let t=this.state;return!!(t?.connected&&k(this.context.gateway.snapshot)&&this.presented&&document.visibilityState!==`hidden`&&(e||!this.deferredSessionHydration&&(L(t.sessionKey)||this.transcriptReady||nu(t))))}subscribeSessionRepositoryContext(){this.chatState.addCleanup(Mm(this.context.gateway).subscribe(()=>this.requestUpdate()));let e=ch(this.context.gateway);this.chatState.addCleanup(e.subscribe(()=>{this.refreshSessionPullRequests()})),this.chatState.addCleanup(()=>e.unwatch(this))}get visibleSessionPullRequests(){return this.sessionPullRequests.filter(e=>!this.dismissedSessionPullRequestIds.has(D_(e)))}get sessionPullRequestsBranchDismissed(){let e=this.sessionPullRequestsBranch;return e!==void 0&&this.dismissedSessionPullRequestIds.has(Sv(e))}applyPullRequestPresentation(e,t=this.dismissedSessionPullRequestIds){let n=e?.pullRequests??[],r=au(e),i=e?.status??`ready`,a=this.sessionPullRequests!==n&&(this.sessionPullRequests.length>0||n.length>0)||this.sessionPullRequestsBranch!==e?.branch||this.githubRepo?.owner!==r?.owner||this.githubRepo?.repo!==r?.repo||this.sessionPullRequestsStatus!==i||this.dismissedSessionPullRequestIds.size!==t.size||[...t].some(e=>!this.dismissedSessionPullRequestIds.has(e));this.sessionPullRequests=n,this.sessionPullRequestsBranch=e?.branch,this.githubRepo=r,this.sessionPullRequestsStatus=i,this.dismissedSessionPullRequestIds=t,a&&this.requestUpdate()}refreshSessionPullRequests(e={}){if(!this.presented)return ch(this.context.gateway).unwatch(this),!1;let t=this.captureConnectionScope();if(!t||!ui(t.context.gateway.snapshot,`controlUi.sessionPullRequests.subscribe`,`operator.read`))return t&&ch(t.context.gateway).unwatch(this),this.applyPullRequestPresentation(),!1;let n=t.state.sessionKey;if(!n.trim()||L(n))return ch(t.context.gateway).unwatch(this),this.applyPullRequestPresentation(),!1;let r=t.context.sessions.capturePullRequestEpoch(n),i=ch(t.context.gateway),a=ue(n,D(t.state,n).agentId??Y(t.state));i.watch(this,[a],{foreground:!0});let o=e.refresh===!0&&i.refresh(a,e),s=i.get(a);if(!this.isConnectionScopeCurrent(t)||n!==t.state.sessionKey)return o;if(!s)return(this.sessionPullRequests.length>0||this.sessionPullRequestsBranch!==void 0)&&t.context.sessions.setPullRequestSummary(n,void 0,r),this.applyPullRequestPresentation(void 0,new Set),o;let c=au(s),l=this.githubRepo!=null&&c!==null&&(this.githubRepo.owner!==c.owner||this.githubRepo.repo!==c.repo);if(this.applyPullRequestPresentation(s,$_(n)),!s.rateLimited||s.pullRequests.length>0||l){let e=t.context.sessions.pullRequestSummary(n);t.context.sessions.setPullRequestSummary(n,Ls(s.pullRequests,e),r)}let u=this.githubPublication?.result?.status===`published`?this.githubPublication?.result:void 0,d=u?s.pullRequests.find(e=>e.url===u.url):void 0;return s.branch&&u&&(s.branch.branch!==u.branch||d&&d.state!==`open`&&d.state!==`draft`)&&this.githubPublication?.reset(),o}resetSessionPullRequests(){this.state&&fp(this.state),ch(this.context.gateway).unwatch(this),this.sessionPullRequests=[],this.sessionPullRequestsBranch=void 0,this.githubRepo=null,this.sessionPullRequestsStatus=`ready`,this.githubPublication?.detach(),this.githubPublication=null,this.dismissedSessionPullRequestIds=new Set}dismissSessionPullRequestId(e){let t=this.state?.sessionKey;t&&(this.dismissedSessionPullRequestIds=M_(t,e),this.requestUpdate())}deferSessionHydrationUntilTranscript(e,t){let n=this.state;if(!n)return;let r={};this.deferredSessionHydration=r;let i=this.connectionGeneration,a=n.client,o=()=>{this.deferredSessionHydration===r&&(this.deferredSessionHydration=null)},s=()=>this.deferredSessionHydration===r&&this.connectionGeneration===i&&this.state===n&&n.connected&&n.client===a&&n.sessionKey===e,c=t=>{if(!s()){o();return}if(!this.presented||document.visibilityState===`hidden`){r.resume=()=>c(t);return}r.resume=void 0,Rl(n,()=>{s()&&this.presented&&document.visibilityState!==`hidden`?(this.deferredSessionHydration=null,n.requestUpdate?.(),this.refreshTaskSuggestions({automatic:!0}),t&&this.markSessionRead(Z(n)),a&&this.loadHeaderPlatform(a,i),eh(n),this.probeSessionDiscussion(e),this.hydrateSessionCompanion(e),this.refreshSessionPullRequests()):s()?r.resume=()=>c(t):o()})};t.then(c,()=>c(!1))}resumeDeferredSessionHydration(){let e=this.deferredSessionHydration;if(e){let t=e.resume;e.resume=void 0,t?.()}return this.deferredSessionHydration!==null}retireDeferredSessionHydration(){this.deferredSessionHydration=null}markSessionRead(e){let t=this.state;if(!t?.connected||!e||!k(this.context.gateway.snapshot))return;let n=e.endedAt??e.updatedAt??0,r=(e.status===`failed`||e.status===`timeout`)&&(e.lastReadAt==null||n>e.lastReadAt),i=!!(e.agentStatus&&e.agentStatus.expiresAt>Date.now()),a=e.unread===!0||r||i;a||this.unreadPatchGuard.shouldPatch(t.sessionKey,!1,e.markedUnreadAt);let o=Bt(e.key)?.agentId??Y(t);b(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,unread:!1,agentId:o}}).allowed&&e.sharingRole!==`viewer`&&!this.sessionParticipationTracker.resolve({catalog:L(t.sessionKey)!==null,listLoading:t.sessionsLoading,sessionKey:`${Y(t)??``}\0${t.sessionKey}`,session:e})&&(this.markHiddenRunsRead(e),a&&this.unreadPatchGuard.shouldPatch(t.sessionKey,!0,e.markedUnreadAt)&&this.acknowledgeSessionRead(e,this.unreadPatchGuard,o))}acknowledgeSessionRead(e,t,n){let r=t.settlePatch();this.context.sessions.patch(e.key,{unread:!1},{agentId:n,expectedMarkedUnreadAt:e.markedUnreadAt??null}).then(e=>r(e!==null),e=>r(!1,e))}markHiddenRunsRead(e){let t=this.state;if(!t)return;let n=Fo(t.sessionsResult?.sessions??[],e.key);for(let e of n){let n=e.updatedAt??null;if(e.markedUnreadAt!=null||e.sharingRole===`viewer`)continue;let r=Bt(e.key)?.agentId??Y(t);if(!b(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,unread:!1,agentId:r}}).allowed)continue;let i=this.hiddenRunReadRequests.get(e.key);(!i||i.revision!==n)&&(i={revision:n,guard:new Th},this.hiddenRunReadRequests.set(e.key,i)),i.guard.shouldPatch(e.key,!0)&&this.acknowledgeSessionRead(e,i.guard,r)}}async restoreArchivedSession(e,t){let n=this.captureConnectionScope();if(!n||n.state.sessionKey!==e)return;let r=b(n.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e,archived:!1},sessionScope:!0,session:Z(n.state)});if(!r.allowed){n.state.lastError=r.reason,n.state.chatError=r.reason,n.state.requestUpdate?.();return}let i=Bt(e)?.agentId??Y(n.state),a=null;try{await n.sessions.patch(e,{archived:!1},{agentId:i,expectedSessionId:t})||(a=n.sessions.state.error)}catch(e){a=B(e)}a&&this.isConnectionScopeCurrent(n)&&n.state.sessionKey===e&&(n.state.lastError=a,n.state.chatError=a,n.state.requestUpdate?.())}setPaneSessionKey(e){let t=this.state;if(!t)return null;let n=L(e)?e:be(e,this.context.gateway.snapshot.hello);return n?(t.sessionKey=n,n):null}openCatalogSession(e,t){this.catalogRequestedSessionKey=this.sessionKey,this.catalogMessages=[],this.catalogCursor=void 0,this.catalogSession=null,this.catalogHost=null,At(t.chatAttachments),t.chatAttachments=[],t.chatLoading=!0,t.requestUpdate(),this.loadCatalogSession(e,!1)}catalogItemMessage(e){let t=so(e.timestamp)??null,n=e.text?.trim()?e.text:null;if(e.type===`userMessage`)return n?{role:`user`,senderLabel:e.sender?.label??V(`sessionsView.user`),...e.sender?{__openclaw:{senderIdentity:e.sender.identity,senderId:e.sender.identity.id,senderName:e.sender.label,senderProfileAvatarUrl:e.sender.avatarUrl}}:{},content:n,...t==null?{}:{timestamp:t},messageId:e.id}:null;let r=n,i=e.truncated;if(e.type===`reasoning`)r=n?`Thinking\n\n${n}`:`Thinking`;else if(e.type===`toolCall`){let t=n??Wd(e.raw,[`command`,`name`,`tool`,`title`,`query`]);r=t?`Tool call\n\n${t}`:`Tool call`}else if(e.type===`toolResult`){let t=n??Wd(e.raw,[`aggregatedOutput`])??im(e.raw),a=t?st(t,500):null;i||=!!(t&&a!==t),r=a?`Tool result\n\n${a}`:`Tool result`}return r?(i&&(r=`${r}\n\n${V(`chat.catalogOutputTruncated`)}`),{role:`assistant`,content:[{type:`text`,text:r}],...t==null?{}:{timestamp:t},messageId:e.id}):null}prependUniqueCatalogMessages(e){let t=new Set(this.catalogMessages.map(vS).filter(Boolean));return[...e.filter(e=>{let n=vS(e);return!n||!t.has(n)?(n&&t.add(n),!0):!1}),...this.catalogMessages]}async loadCatalogSession(e,t){let n=this.captureConnectionScope();if(!n)return!1;let{state:r,client:i}=n;if(t&&!this.catalogCursor)return!1;let a=Y(r),o=t?this.catalogLoadGeneration:++this.catalogLoadGeneration,s=this.sessionKey,c=()=>this.isConnectionScopeCurrent(n)&&o===this.catalogLoadGeneration&&this.sessionKey===s&&Y(r)===a;t||(this.catalogLoading=!0,this.catalogCursor=void 0,this.olderCursorsSeen.clear(),this.historyObserverArmed=!1,this.transcriptScrollTop=null,this.historyObserver?.disconnect(),this.historyObserver=null);try{if(!t){let t=await Dt({agentId:a,client:i,key:e,isCurrent:c});if(!t||!c())return!1;this.catalogHost=t.host,this.catalogSession=t.session}let n=t?this.catalogCursor:void 0;n&&this.olderCursorsSeen.add(n);let o=await i.request(`sessions.catalog.read`,{agentId:a,catalogId:e.catalogId,hostId:e.hostId,threadId:e.threadId,...this.catalogSession?.sourceHomeId?{sourceHomeId:this.catalogSession.sourceHomeId}:{},limit:50,...t&&this.catalogCursor?{cursor:this.catalogCursor}:{}});if(!c())return!1;let s=o.items.toReversed().map(e=>this.catalogItemMessage(e)).filter(e=>e!==null),l=t?this.prependUniqueCatalogMessages(s):s,u=l.length>this.catalogMessages.length,d=t&&(!o.nextCursor||o.nextCursor===n||this.olderCursorsSeen.has(o.nextCursor));return this.catalogMessages=l,this.catalogCursor=d?void 0:o.nextCursor,r.lastError=null,Wu(r,!t),!t||u||!d}catch(e){return c()&&(r.lastError=B(e)),!1}finally{c()&&!t&&(this.catalogLoading=!1,r.chatLoading=!1,r.requestUpdate())}}}})))()}var HC;function UC(){return(UC=e((()=>{F(),Pa(),Pi(),_t(),R(),VC(),Qb(),vi(),HC=class extends BC{constructor(...e){super(...e),this.activeReplyNavigation=null,this.replyNavigationSessionKey=null,this.replyNavigationId=null,this.replyMessageRevision=0,this.replyMessages=new Map,this.readReplyMessage=e=>this.currentReplyMessage(e)?.message,this.replyMessageStatus=e=>{let t=this.currentReplyMessage(e);return t?.message?void 0:t?.status??`pending`},this.openReplyMessage=async e=>{let t=this.state;if(!t||L(t.sessionKey))return;let n=t.sessionKey,r=t.currentSessionId?.trim()??``,i=Symbol(`reply-navigation`),a=()=>this.activeReplyNavigation===i&&this.state===t&&z(t.sessionKey,n)&&(!r||t.currentSessionId===r);this.activeReplyNavigation=i,this.replyNavigationSessionKey=n,this.replyNavigationId=e,this.requestUpdate();try{for(;!t.chatMessages.some(t=>kl(t)===e);){if(!a())return;if(!t.chatHistoryPagination.hasMore){t.lastError=V(`chat.messages.originalUnavailable`),t.requestUpdate?.();return}let e=await this.loadOlderMessages();if(!a())return;if(!e){!t.chatHistoryPagination.hasMore&&!t.lastError&&(t.lastError=V(`chat.messages.originalUnavailable`),t.requestUpdate?.());return}}if(!a())return;this.requestUpdate(),await this.updateComplete,a()&&this.transcript.revealMessage(e)}finally{this.activeReplyNavigation===i&&(this.resetReplyNavigation(),this.requestUpdate())}}}synchronizeReplyMessages(){let e=this.state?.chatMessages;if(this.replyMessageSource!==e){this.replyMessageSource=e,this.replyMessages.clear();for(let t of e??[]){let e=Ia(t).replyTarget,n=xo(xo(t)?.__openclaw),r=xo(n?.replyToMessage);e?.kind===`id`&&r&&this.replyMessages.set(e.id,r.ok&&r.message?{message:r.message}:{status:r.unavailableReason===`oversized`?`oversized`:`missing`})}this.replyMessageRevision+=1}}currentReplyMessage(e){return this.synchronizeReplyMessages(),this.replyMessages.get(e)}currentReplyNavigationId(e){return this.replyNavigationSessionKey&&z(this.replyNavigationSessionKey,e)?this.replyNavigationId:null}currentReplyMessageAccess(e){return this.synchronizeReplyMessages(),{revision:this.replyMessageRevision,navigationId:this.currentReplyNavigationId(e),read:this.readReplyMessage,status:this.replyMessageStatus,open:this.openReplyMessage}}retireReplyMessages(){this.replyMessages.clear(),this.replyMessageSource=void 0}resetReplyNavigation(){this.activeReplyNavigation=null,this.replyNavigationSessionKey=null,this.replyNavigationId=null}}})))()}function WC(e){let t=Tf(e).allItems(e);for(let n of t)if(!(!n.sendRunId||n.sendState!==`submitting`&&n.sendState!==`sending`&&n.sendState!==`waiting-idle`)&&!(n.sendState===`waiting-idle`&&n.sendAttempts===0&&n.sendRequestStartedAtMs===void 0&&lp(e,n.id))){if(Tf(e).hasVolatile(e,n.id)){Tf(e).change(e,n.id,e=>({...e,sendState:`unconfirmed`}));continue}jf(e,n.id,e=>({...e,sendState:`waiting-reconnect`}))}}function GC(e,t,n){return z(t,n)?!0:!!(t&&f(t)&&A(e,n))}function KC(e,t,n,r){let i=r&&f(r)?A(e,n):void 0;return t?.sessions.find(t=>z(t.key,n)?!0:i!=null&&A(e,t.key)===i)}function qC(e,t){if(!t||!go(t)||go(e))return!1;let n=typeof e.updatedAt==`number`?e.updatedAt:null;return n==null||(typeof t.updatedAt==`number`?t.updatedAt:0)>=n||(typeof t.startedAt==`number`?t.startedAt:0)>=n}function JC(e,t,n,r,i,a){Promise.allSettled([n,r]).then(n=>{let r=n[0],o=n[1],s=e.sessionsResult,c=r.status===`fulfilled`?r.value?.sessionInfo:null,l=KC(e,s,t,c?.key),u=!(!c||!GC(e,c.key,t)||go(c)||qC(c,l)),d=s?.sessions.find(e=>z(e.key,t)),f=!(!d||go(d));o.status!==`fulfilled`||e.chatQueue.length===0||!z(e.sessionKey,t)||!s&&!u||s===i&&!u||e.sessionsError&&!u||!(u||f)||a()})}function YC(){return(YC=e((()=>{R(),Nm(),Jd(),Yd()})))()}function XC(e){fw.get(e)?.catalogRequest?.controller.abort(),fw.get(e)?.unsubscribe(),fw.delete(e),ow(e),e.chatModelsLoading=!1}function ZC(e){let t=typeof globalThis.requestIdleCallback==`function`?globalThis.requestIdleCallback:null;if(t){t(e,{timeout:750});return}globalThis.setTimeout(e,50)}async function QC(e){return gf({client:e.client,agentId:Y(e),sessionKey:e.sessionKey})}function $C(e,t){e&&C(e,e.sessionKey)&&!Bt(e.sessionKey)?.agentId&&(e.assistantAgentId??null)!==t&&(ew(e,t),jp(e))}function ew(e,t){(e.assistantAgentId??null)!==t&&(om(e),e.assistantIdentityRequestVersion+=1,e.assistantAgentId=t,e.assistantName=``,e.assistantAvatar=null,e.assistantAvatarStatus=null,e.assistantAvatarReason=null,e.chatAvatarUrl=null,e.chatAvatarStatus=null,e.chatAvatarReason=null,e.modelAuthStatusResult=null,e.modelAuthStatusError=null,nw(e,{automatic:!0}),iw(e).finally(()=>e.requestUpdate?.()),e.loadAssistantIdentity(),e.requestUpdate?.())}function tw(e){let t=fw.get(e);if(t?.isCurrent())return t;t&&XC(e);let n=e.client;if(!n||!e.connected)return;let r={agentId:Y(e)??void 0,sessionKey:e.sessionKey},i=e.connectionEpoch,a={client:n,sessions:e.sessions,scope:r,version:0,sessionFactsInvalidated:!1,isCurrent:()=>fw.get(e)===a&&e.connected&&e.client===n&&e.sessions===a.sessions&&e.connectionEpoch===i&&e.sessionKey===r.sessionKey&&(Y(e)??void 0)===r.agentId,unsubscribe:Li(n,r,t=>{if(a.isCurrent()){if((t.type===`invalidated`||t.type===`loading`)&&(a.sessionRefreshPending=t.type===`invalidated`&&t.scope===`session`,a.version+=1,a.sessionFactsRequest&&(a.sessionFactsInvalidated=!0,a.sessionFactsRetryPending=!0)),t.type===`invalidated`){if(t.scope===`full`&&(a.catalogRequest?.controller.abort(),a.catalogRequest=void 0,e.chatModelsLoading=!1,sw(e,a)),a.sessionFactsInvalidated||=t.refreshSessionFacts,t.scope===`session`&&a.catalogRequest)return;nw(e,{automatic:!0});return}t.type!==`loading`&&(t.type===`result`&&Kd(t.result),a.sessionFactsRetryPending&&(a.sessionFactsRetryPending=!1,cw(e))),e.requestUpdate?.()}},()=>a.isCurrent()&&e.chatMetadataIsPresented?.()!==!1)};fw.set(e,a),e.chatModelCatalogInitialized=he(n);let o=hi(n,r);return o&&Kd(o),a}async function nw(e,t){let n=tw(e);if(!n){XC(e);return}if(t?.automatic){if(e.chatMetadataIsPresented?.()===!1)return;let r=ga(n.client,n.scope,{kind:t.startup?`startup`:void 0}),i=cw(e);if(n.refreshPending?.refresh===r)return n.refreshPending.promise;n.catalogRequest=void 0,e.chatModelsLoading=!i&&(!!e.chatModelCatalogError||e.chatModelsLoading||e.chatModelCatalog.length===0),e.chatModelCatalogError=null,e.requestUpdate?.();let a=()=>n.isCurrent()&&r.isCurrent()&&n.refreshPending?.refresh===r,o=!1,s=r.catalog.then(async t=>{o=!r.isCurrent(),t&&n.isCurrent()&&n.refreshPending?.refresh===r&&(o&&Vm(n.client,n.scope,{allowStale:!0})!==t||(o=!1,sw(e,n),a()&&(e.chatModelsLoading=!1,e.requestUpdate?.(),n.sessionFactsInvalidated&&e.chatMetadataIsPresented?.()!==!1&&await rw(e,n))))},t=>{o=!r.isCurrent(),a()&&!cw(e)&&a()&&(e.chatModelCatalogError=B(t),e.chatModelsLoading=!1,e.requestUpdate?.())}).finally(()=>{n.isCurrent()&&n.refreshPending?.refresh===r&&(e.chatModelsLoading=!1,e.requestUpdate?.())}),c=Promise.allSettled([r.completed,s]).then(()=>{if(n.refreshPending?.refresh===r&&(n.refreshPending=void 0,o&&n.isCurrent()))return nw(e,{automatic:!0})});return n.refreshPending={refresh:r,promise:c},c}n.refreshPending=void 0,ha(n.client,n.scope);let r=Bi(n.client,n.scope).catch(()=>void 0),i=n.version,a=aw(e,n).then(async t=>{n.sessionFactsInvalidated&&t&&n.isCurrent()&&n.version===i&&await rw(e,n)});await Promise.all([r,a])}function rw(e,t){t.sessionFactsRetryPending=!1;let n=t.version;if(t.sessionFactsRequest?.version===n)return t.sessionFactsRequest.promise;let r=t.scope.agentId;if(!r||!t.isCurrent())return Promise.resolve();let i=t.sessions.observeRow({key:t.scope.sessionKey,agentId:r},()=>{}),a=i.captureReconcile();t.sessionFactsInvalidated=!1;let o=t.sessions.describe({key:t.scope.sessionKey,agentId:r},{client:t.client,refresh:!0}).then(r=>{if(!t.isCurrent()||t.version!==n)return;let i=a(r.session??void 0);t.isCurrent()&&t.version===n&&(i.status===`invalidated`&&(t.sessionFactsInvalidated=!0,t.sessionFactsRequest=void 0),i.status===`current`&&e.sessionsResult&&(e.sessionsResult={...e.sessionsResult,sessions:t.sessions.projectRows(e.sessionsResult.sessions)},e.requestUpdate?.()))}).catch(()=>{t.isCurrent()&&t.version===n&&(t.sessionFactsInvalidated=!0,t.sessionFactsRequest=void 0)}).finally(()=>{i.dispose(),t.sessionFactsRequest?.promise===o&&(t.sessionFactsRequest=void 0)});return t.sessionFactsRequest={version:n,promise:o},o}async function iw(e){if(!e.client||!e.connected)return;let t=e.client,n=e.connectionEpoch,r=Y(e),i=++e.modelAuthStatusRequestVersion,a=()=>e.client===t&&e.connected&&e.connectionEpoch===n&&e.modelAuthStatusRequestVersion===i&&Y(e)===r;try{let n=await rc(t,{agentId:r});if(!a())return;e.modelAuthStatusResult=n,e.modelAuthStatusError=n.unavailable?.message??null}catch(t){if(!a())return;e.modelAuthStatusResult={ts:0,providers:[]},e.modelAuthStatusError=B(t)}}async function aw(e,t){if(sw(e,t))return!0;if(t.catalogRequest?.version===t.version)return t.catalogRequest.promise;t.catalogRequest?.controller.abort();let n=new AbortController,r=t.version,i=()=>t.isCurrent()&&t.catalogRequest?.controller===n;e.chatModelsLoading=!!e.chatModelCatalogError||e.chatModelsLoading||e.chatModelCatalog.length===0,e.chatModelCatalogError=null,e.requestUpdate?.();let a=_u(t.client,{...t.scope,signal:n.signal}).then(n=>{if(!t.isCurrent())return!1;let r=Vm(t.client,t.scope);if(r||i()){sw(e,t);let a=!!r||Vm(t.client,t.scope,{allowStale:!0})===n;return!a&&i()?(t.catalogRequest=void 0,aw(e,t)):a}return!1},t=>(i()&&(e.chatModelCatalogError=B(t)),!1)).finally(()=>{i()&&(t.catalogRequest=void 0,e.chatModelsLoading=!1,e.requestUpdate?.())});return t.catalogRequest={version:r,controller:n,promise:a},a}function ow(e,t){e.chatModelCatalog=t?.models??[],e.chatModelCatalogInitialized=t!==void 0||he(e.client),e.chatModelSelectionPolicy=t?.modelSelectionPolicy,e.chatModelCatalogRetired=!1,e.chatAccountSelection=t?.accountSelection??null,e.chatModelCatalogError=null,e.chatModelCatalogRefreshFailed=t?.refreshFailed,e.chatModelCatalogPendingProviders=t?.pendingProviders}function sw(e,t){let n=Vm(t.client,t.scope),r=n??Vm(t.client,t.scope,{allowStale:!0});if(!r&&t.isCurrent()&&u(t.client,t.scope)&&(ow(e),e.chatModelCatalogRetired=!0,e.requestUpdate?.()),!r||!t.isCurrent())return!1;n&&(t.catalogRequest?.controller.abort(),t.catalogRequest=void 0);let i=e.chatModelCatalogError,a=e.chatModelsLoading;return ow(e,r),n||(e.chatModelCatalogError=i),e.chatModelsLoading=!n&&a,e.requestUpdate?.(),!!n}function cw(e){let t=fw.get(e),n=!!(t&&sw(e,t));return t&&n&&!t.sessionRefreshPending&&t.sessionFactsInvalidated&&e.chatMetadataIsPresented?.()!==!1&&rw(e,t),n}async function lw(e){let t=tw(e);t&&sw(e,t)||(t&&(t.refreshPending=void 0,ha(t.client,t.scope)),t&&await aw(e,t)&&t.isCurrent()&&await rw(e,t))}async function uw(e,t,n){let r=e.client,i=e.sessions,a=e.connectionEpoch,o=e.sessionKey,s=bf(e),c=()=>e.connected&&e.sessions===i&&e.client===r&&e.connectionEpoch===a&&e.sessionKey===o&&bf(e)===s,l=()=>e.requestUpdate?.(),u=e.sessionsResult,d=t?.historyLoad??Rd(e,{deferBranches:t?.deferBranches===!0,startup:t?.startup===!0}),f=d.finally(()=>{t?.scheduleScroll!==!1&&Wu(e),l()}),p=d.then(t=>{if(!t?.sessionInfo||!c()||t.observation.owner!==i)return;let n=t.observation.reconcile(t.sessionInfo,t.defaults,{resultAgentId:e.sessions.state.agentId??s,selectedGlobalAgentId:s,archivedFilter:t.sessionInfo.archived===!0?`all`:e.sessionsArchivedFilter});if(!n||!c())return;let r=e.sessions.state.agentId!==s&&(C(e,o)||P(t.sessionInfo));if(e.sessionsResult=r?ct(e.sessionsResultAgentId===s?e.sessionsResult:null,n===`defaults-only`?Z(e):t.sessionInfo,t.defaults,{resultAgentId:s,selectedGlobalAgentId:s,archivedFilter:`all`},n===`defaults-only`||e.sessionsResultAgentId===s&&e.sessionsResult!==u):e.sessions.state.result,e.sessionsResultAgentId=r?s:e.sessions.state.agentId,n===`defaults-only`)return;let a=Z(e);a&&(e.selectedChatSessionArchived=a.archived===!0,e.selectedChatSessionIncognito=a.incognito===!0);let l=t.inFlightRun?.runId?.trim(),d=t.sessionInfo.activeRunIds;(!l||e.chatRunId!==l||!go(t.sessionInfo)||Array.isArray(d)&&!d.includes(l))&&a&&!Is(e,a,{publishRunStatus:!0,historyRun:t.observation.run&&t.sessionInfo.hasActiveRun===!1&&!go(t.sessionInfo)&&!t.inFlightRun&&t.sessionInfo.sessionId===t.observation.run.sessionId?t.observation.run:null})&&!e.chatRunId&&e.chatStream==null&&sh(e,{publishRunStatus:!0})}),m=t.startup===!0?d.then(e=>n(e?.metadata),()=>n(void 0)):Promise.resolve();if(JC(e,o,f,p,u,()=>void Ju(e)),Promise.allSettled([p,m]).finally(l),t?.awaitHistory===!0){await f;return}await Promise.resolve()}function dw(e,t){let n=t?.startup?tw(e):void 0,r=n?Si(n.client,n.scope):void 0;n&&nw(e,{automatic:!0,startup:!0});let i=uw(e,{...t},async e=>{n&&r?.isCurrent()&&(e?r.publish(e):await ga(n.client,n.scope,{kind:`metadata`,revalidateMetadata:()=>r.isCurrent()}).completed)}),a=e.sessionKey,o=e.client,s=e.connectionEpoch;return ZC(()=>{e.connected&&e.client===o&&e.connectionEpoch===s&&e.sessionKey===a&&Promise.allSettled([ff(e),...t?.startup?[]:[nw(e,{automatic:!0})]]).finally(()=>e.requestUpdate?.())}),i}var fw;function pw(){return(pw=e((()=>{bi(),zt(),Bm(),i(),Ym(),l(),R(),at(),ym(),Cm(),rh(),YC(),Oc(),Vf(),Q(),gc(),Hs(),fw=new WeakMap})))()}var mw;function hw(){return(hw=e((()=>{$r(),ti(),mn(),Da(),zt(),_t(),Ue(),R(),il(),lu(),Up(),rf(),af(),Dx(),rh(),UC(),pp(),uC(),pw(),Q(),Ps(),pc(),Cu(),Hs(),Gs(),dh(),mw=class extends HC{constructor(...e){super(...e),this.activeCatalogContinuation=null,this.activeOlderLoad=null,this.stagedOlder={page:null,load:null},this.refreshHistory=()=>{let e=this.state;if(!e)return;let t=L(e.sessionKey);if(t){this.loadCatalogSession(t,!1);return}Bs(e,{preserveStreamSegments:e.chatRunId!==null}),this.reconcileWaitingApprovalSnapshot(),bd(e).subscriptionError&&Cx(e);let n=ks(e),r=n.phase===`failed`&&n.startup;dw(e,{historyLoad:Rd(e,{startup:r,supersedeInFlight:!0}),awaitHistory:!0,scheduleScroll:!1,startup:r})},this.handleCommandPaletteSlashCommand=e=>{let t=this.state;t&&(t.handleChatDraftChange(e.endsWith(` `)?e:`${e} `),t.requestUpdate?.())}}hydrateStoredChatSnapshot(e,t){let n=this.sessionSnapshotStore;if(!n)return;let r=qe(e,{sessionKey:t}),i=bd(e),a=this.context.gateway.snapshot.phase!==`connected`,o,s=n.read(r,e=>{a=!0,o=e}),c={sessionKey:t,startedBeforeReady:a,readyAt:o,promise:s.then(n=>{if(i.initialSnapshotHydration!==c||i.acceptedHistory||this.state!==e||!z(e.sessionKey,t)||qe(e,{sessionKey:t})!==r)return c.complete?.();let a=e.chatMessagesBySession,o=Pu(a,e,{sessionKey:t})??n;if(!o)return c.complete?.();vl(e,o);let s={...o,messages:e.chatMessages};fu(a,e,{sessionKey:t},s),c.complete?.(),e.requestUpdate?.()}).catch(()=>c.complete?.()).finally(()=>{i.initialSnapshotHydration===c&&!c.wait&&delete i.initialSnapshotHydration})};i.initialSnapshotHydration=c}hasOlderMessages(){let e=this.state;return e?L(e.sessionKey)?!(!this.catalogCursor||this.catalogLoading):e.chatHistoryPagination.hasMore&&!e.chatLoading:!1}resetOlderMessagesViewport(){this.olderLoadGeneration+=1,this.activeOlderLoad=null,this.stagedOlder={page:null,load:null},this.resetReplyNavigation(),this.loadingOlder=!1,this.historyObserverArmed=!1,this.historyAutoLoadBlocked=!1,this.historyTouchY=null,this.historyIntentTimer!==null&&(window.clearTimeout(this.historyIntentTimer),this.historyIntentTimer=null),this.transcriptScrollTop=null,this.olderCursorsSeen.clear(),this.clearHistoryObserver()}clearHistoryObserver(){this.historyObserver?.disconnect(),this.historyObserver=null,this.historyObserverSentinel=null,this.historyObserverBootstrap=!1}syncHistoryObserver(){if((this.state&&L(this.state.sessionKey)?this.catalogLoading:this.state?.chatLoading)&&(this.historyObserverArmed=!1,this.loadingOlder&&=(this.olderLoadGeneration+=1,!1)),typeof IntersectionObserver!=`function`||!this.presented||!this.state?.connected||this.loadingOlder||!this.hasOlderMessages()){this.clearHistoryObserver();return}let e=this.transcript.scrollElement,t=e?.querySelector(`.chat-history-sentinel`)??null;if(!e||!t){this.clearHistoryObserver();return}this.transcriptScrollTop??=e.scrollTop;let n=!this.historyObserverArmed;if(this.historyAutoLoadBlocked){this.clearHistoryObserver();return}this.historyObserver&&this.historyObserver.root===e&&this.historyObserverSentinel===t&&this.historyObserverBootstrap===n||(this.clearHistoryObserver(),this.historyObserver=new IntersectionObserver((t,r)=>{this.historyObserver===r&&t.some(e=>e.isIntersecting)&&(this.clearHistoryObserver(),!(n&&e.scrollHeight>e.clientHeight)&&(this.historyObserverArmed=!1,this.loadOlderMessages()))},{root:e,rootMargin:`${xp}px 0px 0px`,threshold:0}),this.historyObserverSentinel=t,this.historyObserverBootstrap=n,this.historyObserver.observe(t))}handleTranscriptScroll(e){let t=e.currentTarget instanceof HTMLElement?e.currentTarget:e.target instanceof HTMLElement?e.target:null,n=this.transcriptScrollTop,r=t?wl(t):null;if(r){this.transcriptScrollTop=r.scrollTop;let e=this.transcript.renderedSessionKey,t=this.state?.sessionKey;e&&t&&z(e,t)&&ju(this.paneId,e,Uc(r))}!this.loadingOlder&&!this.transcript.isMaintenanceScroll&&r!==null&&n!==null&&r.scrollTop<n&&r.scrollTop<r.scrollHeight-r.clientHeight&&r.scrollTop<=1200&&this.consumeHistoryIntent()&&(this.historyAutoLoadBlocked||!this.historyObserverArmed)&&(this.historyAutoLoadBlocked=!1,this.historyObserverArmed=!0,this.syncHistoryObserver()),this.state?.handleChatScroll(e)}consumeHistoryIntent(){let e=this.historyIntentTimer!==null;return this.historyIntentTimer!==null&&window.clearTimeout(this.historyIntentTimer),this.historyIntentTimer=window.setTimeout(()=>{this.historyIntentTimer=null},200),!e}handleTranscriptHistoryIntent(e){let t=e.currentTarget instanceof HTMLElement?e.currentTarget:null,n=e instanceof WheelEvent&&e.deltaY<0||e instanceof KeyboardEvent&&$p.has(e.key)&&cC(e);if(typeof TouchEvent<`u`&&e instanceof TouchEvent){let t=e.touches[0]?.clientY??null;if(e.type===`touchstart`){this.historyTouchY=t;return}if(e.type===`touchend`||e.type===`touchcancel`){this.historyTouchY=null;return}let r=this.historyTouchY;t!==null&&r!==null&&(n=t-r>=8,(n||t<r)&&(this.historyTouchY=t))}if(!(!t||!n||t.scrollTop>1200||this.loadingOlder||!this.hasOlderMessages()||!this.consumeHistoryIntent())){if(this.historyAutoLoadBlocked=!1,typeof IntersectionObserver!=`function`){this.loadOlderMessages();return}this.historyObserverArmed=!0,this.syncHistoryObserver()}}async loadOlderMessages(){if(this.activeOlderLoad)return this.activeOlderLoad;let e=this.performOlderMessagesLoad();this.activeOlderLoad=e;try{return await e}finally{this.activeOlderLoad===e&&(this.activeOlderLoad=null)}}async performOlderMessagesLoad(){let e=this.state,t=e?L(e.sessionKey):null;if(!e||this.loadingOlder||!this.hasOlderMessages())return!1;let n=++this.olderLoadGeneration,r=()=>{this.loadingOlder||(this.loadingOlder=!0,e.requestUpdate())},i=!1;try{if(t)r(),i=await this.loadCatalogSession(t,!0);else{let t=e.chatHistoryPagination;if(!t.hasMore)return!1;let a=t.nextOffset,o=typeof e.currentSessionId==`string`?e.currentSessionId.trim():``,s=this.takeStagedOlderPage(e);if(!s&&this.stagedOlder.load){if(r(),await this.stagedOlder.load,n!==this.olderLoadGeneration)return!1;s=this.takeStagedOlderPage(e)}if(s||=(r(),await sd(e,a)??null),!s||n!==this.olderLoadGeneration)return!1;if(s.windowReset)return vl(e,{messages:s.messages??[],pagination:_p(s),sessionId:s.sessionInfo?.sessionId??s.sessionId??null,displayedLeafEntryId:s.sessionInfo?.activeLeafEntryId??null,deltaCursor:s.deltaCursor}),Ql(e),e.lastError=null,i=!0,!0;if(o&&ws(s)!==o)return await Rd(e),i=!0,!0;let c=_p(s),l=!c.hasMore||c.nextOffset<=a,u=Array.isArray(s.messages)?s.messages:[],d=Lm(e),f=d.entries.flatMap(e=>e.pending&&e.identity?.role===`user`&&e.pendingRunId?[e.pendingRunId]:[]);if(f.length){let t=u.filter(e=>{let t=Zr(e);return t?.role===`user`&&!t.isImported&&(t.id!==null||t.sequence!==null)}),n=qr(d,{type:`snapshotLoaded`,messages:t,scope:d.scope}),r=new Set(n.entries.filter(e=>e.pending&&e.identity?.role===`user`).map(e=>e.pendingRunId));Wf(e,new Set(f.filter(e=>!r.has(e))))}let p=va(u,e.chatMessages),m=p.length>e.chatMessages.length;Il(e,p),e.chatHistoryPagination=l?{hasMore:!1,...c.totalMessages===void 0?{}:{totalMessages:c.totalMessages}}:c,e.lastError=null,Ql(e),Wu(e,!1),i=m||!l,l||this.stageNextOlderPage(e)}}catch(t){n===this.olderLoadGeneration&&(e.lastError=B(t),this.transcriptScrollTop=this.transcript.scrollElement?.scrollTop??null)}finally{n===this.olderLoadGeneration&&(i?this.hasOlderMessages()||(this.historyAutoLoadBlocked=!1):this.historyAutoLoadBlocked=this.hasOlderMessages(),this.loadingOlder=!1,e.requestUpdate())}return i}stageNextOlderPage(e){if(this.stagedOlder.page||this.stagedOlder.load)return;let t=e.chatHistoryPagination;if(!t.hasMore||L(e.sessionKey))return;let n=this.stagedOlder;this.stagedOlder.load=(async()=>{try{let r=await nl(e,t.nextOffset);r&&n===this.stagedOlder&&this.state===e&&(this.stagedOlder.page=r)}catch{}finally{n===this.stagedOlder&&(this.stagedOlder.load=null)}})()}takeStagedOlderPage(e){let t=this.stagedOlder.page;return t?(this.stagedOlder.page=null,Jc(e,t)?t.result:null):null}async continueCatalogSession(e){let t=this.captureConnectionScope(),n=t?.state,r=t?.client,i=n?.chatMessage.trim()??``;if(!t||!n||!r||!this.catalogSession?.canContinue)return;let a=Mu(n.chatAttachments);if(!i&&a.length===0)return;let o=n.sessionKey,s=Y(n),c=this.catalogLoadGeneration,l=Symbol(`catalog-continuation`);this.activeCatalogContinuation=l;let u=()=>this.activeCatalogContinuation===l&&this.isConnectionScopeCurrent(t)&&this.catalogLoadGeneration===c&&n.sessionKey===o&&Y(n)===s;n.chatSending=!0,n.requestUpdate();let d=()=>{this.activeCatalogContinuation===l&&(this.activeCatalogContinuation=null,n.chatSendingScopeKey==null&&n.chatSending&&(n.chatSending=!1,n.requestUpdate()))};try{let t=await r.request(`sessions.catalog.continue`,{...e,agentId:s,...this.catalogSession.sourceHomeId?{sourceHomeId:this.catalogSession.sourceHomeId}:{}});if(!u()){d();return}if(Af(this.context,this.paneId,t.sessionKey,{attachments:a,draft:i,send:!0}),this.onPaneSessionChange?.(this.paneId,t.sessionKey)===!1){op(this.context,this.paneId,t.sessionKey),d();return}le({...e,agentId:s,sessionKey:t.sessionKey}),this.activeCatalogContinuation=null,n.chatSending=!1,n.requestUpdate()}catch(e){if(!u()){d();return}this.activeCatalogContinuation=null,n.lastError=B(e),n.chatSending=!1,n.requestUpdate()}}async rewindToMessage(e){let t=this.state;if(!t)return!1;let n=await fh(t,e,this.chatState.attachmentReads);return t.requestUpdate?.(),!!n}async forkFromMessage(e){let t=this.captureConnectionScope();if(!t)return;let n=t.state,r=n.sessionKey,i=D(n,r);try{let a=await n.sessions.forkAtMessage(r,e,i),o=a.editorText??``;if(!this.ownsHeaderOutcomeScope(t)||!ze(n,r,i.agentId)||this.onPaneSessionChange?.(this.paneId,a.sessionKey)===!1)return;ep(n,a.sessionKey,{agentId:Bt(a.sessionKey)?.agentId,draft:o,mentions:[],replyTarget:null}),Af(this.context,this.paneId,a.sessionKey,{attachments:ud([],a.editorAttachments),draft:o})}catch(e){if(!this.ownsHeaderOutcomeScope(t)||!ze(n,r,i.agentId))return;n.lastError=B(e),n.chatError=n.lastError,n.requestUpdate?.()}}async switchToBranch(e){let t=this.state;t&&(await Vs(t,e),t.requestUpdate?.())}announceCommandPaletteTarget(e){this.dispatchEvent(new CustomEvent(gn,{bubbles:!0,composed:!0,detail:{owner:this,onSlashCommand:e}}))}}})))()}var gw;function _w(){return(_w=e((()=>{kr(),wo(),Ur(),Tr(),Jn(),F(),Zh(),zh(),Mt(),zt(),di(),Ce(),Ue(),Te(),R(),Be(),_S(),hw(),Q(),vv(),ho(),gw=class extends mw{get dashboardDefaultWriteOwner(){return JSON.stringify([this.headerOutcomeOwner,this.state?.sessionKey,this.resolveBoardConversation().agentId])}canSaveDashboardDefault(e){return!!(this.state?.connected&&e.sessionId&&!this.sessionParticipationTracker.resolve({catalog:!1,listLoading:this.state.sessionsLoading,sessionKey:e.key,session:e})&&b(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,boardFace:`dashboard`,boardPresentation:`split`}}).allowed)}isDashboardDefault(e,t){return T(e)===`dashboard`&&t===(e.boardPresentation??`split`)}dashboardDefaultMenuAction(e,t){let n=t?xv(t):void 0;if(!e?.sessionId||!this.state?.connected||!n)return;let r=V(`chat.sidePanel.defaultViewDescription`);if(this.isDashboardDefault(e,n))return{kind:`status`,label:V(`chat.sidePanel.currentViewIsDefault`),description:r};if(!this.canSaveDashboardDefault(e))return;let i=this.dashboardDefaultWrite?.owner===this.dashboardDefaultWriteOwner,a=this.resolveBoardConversation().agentId;return{label:V(i?`chat.sidePanel.savingDefault`:`chat.sidePanel.useViewAsDefault`),description:r,disabled:i,onActivate:()=>void this.saveDashboardDefault(e,a)}}async saveDashboardDefault(e,t){let n=this.captureConnectionScope(),r=this.state?Z(this.state):void 0,i=this.state?xv(this.state.sidebarLayout):void 0;if(!n||!r||r.key!==e.key||r.sessionId!==e.sessionId||this.resolveBoardConversation().agentId!==t||!i||!this.canSaveDashboardDefault(r)||this.isDashboardDefault(r,i)||this.dashboardDefaultWrite?.owner===this.dashboardDefaultWriteOwner)return;let a={owner:this.dashboardDefaultWriteOwner};this.dashboardDefaultWrite=a;let o=()=>this.ownsHeaderOutcomeScope(n)&&this.dashboardDefaultWrite===a&&this.context.sessions===n.sessions&&this.dashboardDefaultWriteOwner===a.owner&&Z(n.state)?.sessionId===e.sessionId;this.requestUpdate();try{let r=await n.sessions.patch(e.key,{boardFace:`dashboard`,boardPresentation:i},{agentId:t,expectedSessionId:e.sessionId});if(!o())return;if(!r)throw Error(V(`chat.sidePanel.defaultSaveFailed`));Lt({message:V(`chat.sidePanel.defaultSaved`),anchor:this})}catch(e){o()&&(this.publishHeaderError(e,n.headerOutcomeOwner),Lt({message:V(`chat.sidePanel.defaultSaveError`,{error:B(e)}),anchor:this}))}finally{this.dashboardDefaultWrite===a&&(this.dashboardDefaultWrite=void 0,this.requestUpdate())}}commitSidebarLayout(e,t){let n=this.state;if(!n)return;let r=this.initializeBrowserSidebarLayout(e);n.updateSidebarLayout(this.fitPaneSidebarLayout(r),t)}fitPaneSidebarLayout(e){return this.paneWidth>=680?Ct(e,this.paneWidth)??e:e}initializeBrowserSidebarLayout(e){if(!e.columns[0]?.browserWidthPending||!Ae(e,`browser`))return e;let t=this.querySelector(`.agent-chat__composer-shell`);if(!t)return e;let n=Number.parseFloat(getComputedStyle(t).getPropertyValue(`--chat-composer-side-inset`));return Pe(e,this.querySelector(`.sidebar-region`)?.getBoundingClientRect().width??this.paneWidth,t.getBoundingClientRect().width+(Number.isFinite(n)?n:0))}commitSidebarPanelResize(e,t,n){let r=this.state;if(!r)return;let i=hv(e,t,n),a=this.fitPaneSidebarLayout(i),o=a.columns.find(e=>e.id===t),s=de(a)===`bottom`?o?.height:o?.width;if(s!==void 0&&r.sidebarLayout.columns.some(e=>e.id===t)){r.updateSidebarLayout(hv(r.sidebarLayout,t,s),{geometryOnly:!0});return}this.commitSidebarLayout(a,{geometryOnly:!0})}resolveBoardConversation(){return I({assistantAgentId:this.state?.assistantAgentId,agentsList:this.state?.agentsList,hello:this.context?.gateway.snapshot.hello},this.state?.sessionKey||this.sessionKey)}resolveBoardProvider(){let e=this.resolveBoardConversation();if(this.boardProvider)return this.releaseBoardProviderLease(),this.boardProvider;let t=this.context?.gateway.snapshot,n=!t||K(t,`board.get`)!==!1,r=!t||sn(t.hello?.auth??null),i=!t||Ln(t.hello?.auth??null),a=r&&(!t||fi(t,ii.BOARD_WIDGET_PUT_CANVAS_DOC)===!0),o=r&&(!t||K(t,`board.widget.appView`)===!0&&K(t,`board.widget.put`)===!0),s=t?.client;if(this.boardProviderLifecycleConnected&&s&&n){let n=Fh(e);return this.boardProviderLease?.cacheKey===n?this.boardProviderLease.update(s,t.phase===`connected`,{canPinWidgets:a,canPinMcpApps:o,canMutate:r,canGrant:i}):(this.releaseBoardProviderLease(),this.boardProviderLease={...Rh(e,s,t.phase===`connected`,a,o,r,i),cacheKey:n}),this.boardProviderLease.provider}return this.releaseBoardProviderLease(),Ih(e,n)}releaseBoardProviderLease(){this.boardProviderLease?.release(),this.boardProviderLease=void 0}readSavedDashboardLayout(){return this.state?Nn().sidebarSessionLayouts?.[a(this.state,this.state.sessionKey)]:void 0}captureNavigationFace(){let e=this.state;return e?Ae(e.sidebarLayout,`dashboard`)?(this.retainDashboardPresentation(this.routeFace!==`dashboard`),`dashboard`):this.readSavedDashboardLayout()===void 0?this.routeFace:`chat`:this.routeFace}retainDashboardPresentation(e=!1){this.dashboardPresentationActivation={client:this.state?.client??null,key:Fh(this.resolveBoardConversation()),expanded:this.dashboardExpanded,pendingRoute:e}}syncRetainedBoardSession(e){let t=this.resolveBoardSessionKey(e.snapshot.sessionKey),n=this.routeFace===`dashboard`||this.dashboardExpanded,r=Fh(this.resolveBoardConversation()),i=this.dashboardPresentationActivation,a=this.state?.client??null,o=this.state?Z(this.state):void 0,s=i?.pendingRoute===!0&&i.key===r&&i.client===a;if(i&&n&&(i.pendingRoute=!1),!this.presented||!n&&!s)this.dashboardPresentationActivation=void 0;else if(e.available&&t&&(i?.key!==r||i.client!==a||i.expanded!==this.dashboardExpanded)){let e=this.readSavedDashboardLayout(),t=e!==void 0&&e.dashboardPresentationOverride!==null;if(this.dashboardExpanded||o||t){let t=e?.dashboardPresentationOverride??o?.boardPresentation??`split`,n=e&&(xv(e)??(e.columns.some(e=>e.panels.some(e=>e.slot===`dashboard`))?`split`:void 0));this.dashboardExpanded?this.showDashboard(!0):e&&(e.dashboardPresentationOverride===void 0||n===t)?(this.retainDashboardPresentation(),this.commitSidebarLayout(this.restorePaneSidebarLayout(e),{persist:!1})):this.showDashboard(t===`expanded`)}}if(t&&e.provider.hasLoadedSnapshot){let n=this.observedBoardPresence.get(t);this.observedBoardPresence.set(t,e.hasBoard),this.presented&&n===!1&&e.hasBoard&&e.face===`chat`&&!this.readSavedDashboardLayout()&&this.showDashboard((o?.boardPresentation??`split`)===`expanded`)}e.available&&this.state&&Ae(this.state.sidebarLayout,`dashboard`)&&!customElements.get(`openclaw-board-view`)&&mS().then(e=>{e&&this.requestUpdate()})}resolveBoardSessionKey(e=``){let t=be(e||this.state?.sessionKey||this.sessionKey,this.context?.gateway.snapshot.hello),n=fe(t);return n===`main`?vo({agentId:`main`}):n}refreshSwarmRoster(){let e=this.context,t=!1;e.connectionBootstrap.run(this,async()=>{this.context===e&&(t=await this.hydrateSwarmRoster())},{background:!0}).then(()=>{t&&this.context===e&&this.presented&&this.isConnected&&this.refreshSwarmRoster()})}async hydrateSwarmRoster(){let e=this.state,t=this.context;if(!e||!this.presented||!this.isConnected)return!1;let n=this.resolveChatReadTarget();if(!n)return this.swarmHydrator?.dispose(),this.swarmHydrator=null,!1;let{sessionKey:r,agentId:i}=n,a=e.client;if(!a)return!1;let o=e.connectionEpoch,s=()=>this.context===t&&this.state===e&&this.presented&&this.isConnected&&e.client===a&&e.connectionEpoch===o&&r===this.resolveChatReadTarget()?.sessionKey&&i===this.resolveChatReadTarget()?.agentId,c=!1;return await _o(async()=>{let{isSwarmEnabledInConfig:e,SwarmRosterHydrator:t}=await import(`./control-ui-boot-chat-XPUNenUd.js`).then(e=>(e.r(),e.i));return{isSwarmEnabledInConfig:e,SwarmRosterHydrator:t}},__vite__mapDeps([0,2,1,3,4,10,11,5,6,7,8,17,18,19]),import.meta.url).then(({isSwarmEnabledInConfig:n,SwarmRosterHydrator:l})=>{if(!s()){c=!0;return}let u=n(t.runtimeConfig?.state.configSnapshot?.config,i);if(this.swarmEnabled!==u&&(this.swarmEnabled=u,rC(e,`animation-frame`)),!e.connected){this.swarmHydrator&&(this.swarmHydrator.dispose(),this.swarmHydrator=null,rC(e,`animation-frame`));return}this.swarmHydrator??=new l,this.swarmHydrator.update({sessions:t.sessions,parentKey:r,agentId:i,sourceEpoch:o,readParent:e=>t.sessions.describe({key:r,...Bt(r)?{}:{agentId:i}},{client:a,refresh:e}).then(e=>e.session??null),currentRows:()=>s()?e.sessionsResult?.sessions??[]:[],onRows:()=>{s()&&rC(e,`animation-frame`)}})}),c}resolveBoardView(){let e=this.resolveBoardProvider(),t=e.snapshot$.value,n=t.tabs.length>0||t.widgets.length>0,r=this.resolveBoardSessionKey(t.sessionKey),i=this.context.theme.settings.boardSessionViews?.[r],a=(t.tabs.some(e=>e.tabId===i?.activeTabId)?i?.activeTabId:void 0)??t.tabs[0]?.tabId??t.widgets[0]?.tabId??``;return{provider:e,snapshot:t,available:!!this.boardProvider||K(this.context.gateway.snapshot,`board.get`)!==!1,hasBoard:n,face:this.routeFace??`chat`,activeTabId:a}}selectBoardTab(e){let t=this.resolveBoardView(),n=this.resolveBoardSessionKey(t.snapshot.sessionKey);if(!n)return;let r=this.context.theme.settings.boardSessionViews,i=wr({boardSessionViews:Ot(r,n,{activeTabId:e})});this.state&&(this.state.settings=i),this.requestUpdate()}isBoardPanelAvailable(e=this.resolveBoardView()){return e.available&&!!this.resolveBoardSessionKey(e.snapshot.sessionKey)}pageBoardWidget(e,t){if(!e||!this.state||!Z(this.state)||!this.visuallyPresented||!t.provider.hasLoadedSnapshot||!customElements.get(`openclaw-board-view`)||!Ae(e,`dashboard`))return;let n=t.snapshot.widgets.filter(e=>e.tabId===t.activeTabId),r=n.length===1?n[0]:void 0;return r?.sizeW===12?r:void 0}pageBoardWidgetMenu(e,t=this.resolveBoardView()){let n=this.pageBoardWidget(e,t);if(!n)return;let r=this.resolveBoardConversation();return r.agentId??=Bt(t.snapshot.sessionKey)?.agentId,{widget:n,tabs:t.snapshot.tabs,canMutate:t.provider.canMutate,onSelect:e=>{let i=this.resolveBoardView();if(i.provider!==t.provider||this.pageBoardWidget(this.state?.sidebarLayout,i)!==n)return;let a=this.querySelector(`openclaw-board-view`);a?.snapshot?.sessionKey===t.snapshot.sessionKey&&a.session.agentId===r.agentId&&a.session.sessionKey===r.sessionKey&&a.selectPageWidgetMenuItem(n.name,n.revision,e)}}}renderBoardPanel(e,t){let n=this.resolveBoardConversation(),r=this.resolveBoardSessionKey(e.snapshot.sessionKey);if(!this.isBoardPanelAvailable(e))return U;let i=!e.provider.hasLoadedSnapshot&&e.provider.loadError$.value;if(i)return W`<div
        class="board-session-surface__state board-session-surface__state--error"
        role="alert"
      >
        ${V(`dashboardDocument.loadFailed`,{error:i})}
      </div>`;n.agentId??=Bt(e.snapshot.sessionKey)?.agentId;let a=Ae(t,`dashboard`)&&this.visuallyPresented,o=this.connectionGeneration,s=()=>hS({active:{owner:this,isPresented:()=>Ae(t,`dashboard`)&&this.visuallyPresented,preview:()=>!this.presented&&this.connectionGeneration===o},session:n,snapshot:e.provider.hasLoadedSnapshot?e.snapshot:void 0,activeTabId:e.activeTabId,pageWidgetName:this.pageBoardWidget(t,e)?.name,canMutate:e.provider.canMutate,canGrant:e.provider.canGrant,callbacks:{appViewGeneration:e.provider.appViewGeneration,applyOps:t=>e.provider.applyOps(t),grant:(t,n)=>e.provider.grant(t,n),selectTab:e=>{this.onFaceChange?.(this.paneId,this.sessionKey,`dashboard`),this.selectBoardTab(e)},frameLoadFailed:t=>e.provider.refreshWidgetFrame(t),widgetAppView:(t,n)=>e.provider.widgetAppView(t,n),refreshWidgetAppView:(t,n)=>e.provider.refreshWidgetAppView(t,n)},widgetFrameUrl:(t,n)=>e.provider.widgetFrameUrl(t,n)});return W`${a?s():To([r,n.agentId],s)}`}showDashboard(e){let t=this.state;if(!t)return;let n=ev(t.sidebarLayout,e?`expanded`:`split`);this.retainDashboardPresentation(this.routeFace!==`dashboard`&&!this.dashboardExpanded),this.commitSidebarLayout(n,{persist:!1}),this.onFaceChange?.(this.paneId,this.sessionKey,`dashboard`)}handleBoardCommand(e){if(!this.presented)return;let t=this.resolveBoardView(),n=this.resolveBoardSessionKey(t.snapshot.sessionKey);if(!n||this.resolveBoardSessionKey(e.sessionKey)!==n)return;let r=e.command;if(r.kind===`focus_tab`){t.snapshot.tabs.some(e=>e.tabId===r.tabId)&&(this.selectBoardTab(r.tabId),this.showDashboard(!1));return}t.activeTabId&&this.showDashboard(r.dock===`hidden`)}}})))()}var vw,yw,bw;function xw(){return(xw=e((()=>{kr(),Ya(),Hn(),fr(),F(),zh(),zt(),dl(),_t(),zf(),Te(),R(),Be(),oc(),xd(),af(),rh(),nS(),pS(),_w(),pp(),bm(),RS(),Oc(),Vf(),tC(),pw(),Q(),xy(),jg(),B_(),Ng(),lg(),Yd(),vw=600,yw=`agent-chat__input--prefill-attention`,bw=class extends gw{constructor(...e){super(...e),this.activeSessionResources=new fS,this.archiveFocusOwned=!1,this.retainedQueuedEdit=!1,this.progressPresentationReady=!1,this.hiddenProgressCards=new Map,this.clearSavedProgressCard=e=>{this.progressCard.dismiss(e).catch(()=>Lt({message:V(`sessionProgressCard.clearFailed`)}))}}captureProgressCardRefreshAction(){let e=this.captureConnectionScope();if(!e)return;let{state:t}=e,n=t.sessionKey,r=t.currentSessionId,i=Y(t);return{state:this.progressCard.refreshState,onRefresh:a=>{this.isConnectionScopeCurrent(e)&&t.sessionKey===n&&t.currentSessionId===r&&Y(t)===i&&this.progressCard.refresh(a)}}}captureArchivePresentationFocus(){this.archiveFocusOwned=!!(this.state&&this.isCurrentSessionArchived(this.state)&&this.currentSessionArchived===!1&&zg(this.presentationId,this))}retireArchivedPresentation(){let e=this.state?this.isCurrentSessionArchived(this.state):!1;e&&this.currentSessionArchived===!1&&(Xg(this.presentationId,this),this.archiveFocusOwned&&this.querySelector(`.chat-thread`)?.focus({preventScroll:!0})),this.currentSessionArchived=e}get hasQueuedMessageEdit(){return!!this.state?.chatQueuedEdit}syncQueuedEditRetention(){let e=this.hasQueuedMessageEdit;e!==this.retainedQueuedEdit&&(this.retainedQueuedEdit=e,this.dispatchEvent(new Event(Qx,{bubbles:!0})))}reviewQueuedMessageEdit(e){let t=Nd(e);if(!t||this.state!==e||!this.isConnected)return;let n=e.client,r=Oe({context:this.context,face:`chat`,sessionKey:t.sessionKey,agentId:t.agentId,exactKey:!0});Ap(this,{agentId:t.agentId,face:`chat`,sessionKey:t.sessionKey,commit:()=>this.state!==e||e.client!==n||this.context.gateway.snapshot.client!==n||Nd(e)!==t?!1:(this.onFocusPane?.(this.paneId,`review-edit`),this.context.navigate(`chat`,r.options),!0)})}get progressCardPresentation(){let e=this.state;if(!e||e.settings.chatShowTaskProgress===!1||!this.presented||this.isCurrentSessionArchived(e)||L(e.sessionKey))return this.retainedProgressCard=void 0,null;let t=yr(this.context.gateway);this.hiddenProgressCardScope!==t&&(this.hiddenProgressCardScope=t,this.hiddenProgressCards.clear());let n=Ne(e),r=this.retainedProgressCard;r&&(!bd(e).acceptedHistory||r.gatewayScope!==t||r.client!==e.client||r.sessionKey!==e.sessionKey||r.sessionId!==e.currentSessionId||r.agentId!==n)&&(this.retainedProgressCard=void 0);let i=this.progressCard.card,a=this.resolveChatReadTarget();i&&a?this.retainedProgressCard={gatewayScope:t,client:e.client,sessionKey:e.sessionKey,sessionId:e.currentSessionId,agentId:n,card:i,lifetime:this.progressCard.lifetime,identity:JSON.stringify([a.agentId??null,a.sessionKey])}:this.progressCard.loading||(this.retainedProgressCard=void 0);let o=this.retainedProgressCard;if(!o)return null;let s=this.hiddenProgressCards.get(o.identity);return s?(s.lifetime?s.lifetime===o.lifetime:s.revision===o.card.revision)?null:(this.hiddenProgressCards.delete(o.identity),o):o}hideProgressCard(e){let t=this.progressCardPresentation;t&&t.card===e&&(this.hiddenProgressCards.delete(t.identity),this.hiddenProgressCards.set(t.identity,{lifetime:t.lifetime,revision:e.revision}),this.requestUpdate())}initialProgressCardTarget(){let e=this.state;if(e?.connected&&this.presented&&document.visibilityState!==`hidden`&&!this.isCurrentSessionArchived(e)&&!L(e.sessionKey)&&(this.transcriptReady||nu(e)))return e.settings.chatShowTaskProgress===!1?void 0:this.resolveChatReadTarget()}get progressCardInitialLoading(){let e=this.state;if(!e||e.settings.chatShowTaskProgress===!1||(this.progressPresentationSessionKey!==e.sessionKey&&(this.progressPresentationSessionKey=e.sessionKey,this.progressPresentationReady=!1),this.progressPresentationReady))return!1;let t=this.context.gateway.snapshot.phase;return!this.isCurrentSessionArchived(e)&&!L(e.sessionKey)&&ks(e).phase!==`failed`&&(t===`connecting`||t===`starting`||e.connected&&(!this.presented||document.visibilityState===`hidden`||!this.transcriptReady&&!nu(e)||this.initialProgressCardTarget()&&this.progressCard.loading&&!this.progressCard.error))?!0:(this.progressPresentationReady=!0,!1)}clearComposerPrefillAttention(){this.composerPrefillAttentionTimer!==null&&(window.clearTimeout(this.composerPrefillAttentionTimer),this.composerPrefillAttentionTimer=null),this.composerPrefillAttentionTarget?.classList.remove(yw),this.composerPrefillAttentionTarget=null}showComposerPrefillAttention(e){this.clearComposerPrefillAttention(),e.offsetWidth,e.classList.add(yw),this.composerPrefillAttentionTarget=e,this.composerPrefillAttentionTimer=window.setTimeout(()=>{this.composerPrefillAttentionTarget===e&&this.clearComposerPrefillAttention()},vw)}confirmConversationReset(){let e=this.resolveBoardView(),t=Fh(this.resolveBoardConversation()),n=this.resetConfirmation;if(n&&n.scopeKey!==t&&this.settleResetConfirmation(!1),!e.hasBoard)return Promise.resolve(!0);if(this.resetConfirmation)return this.resetConfirmation.promise;let{promise:r,resolve:i}=So();return this.resetConfirmation={scopeKey:t,promise:r,resolve:i},r}cancelResetConfirmationForSessionChange(){let e=this.resetConfirmation;e&&e.scopeKey!==Fh(this.resolveBoardConversation())&&this.settleResetConfirmation(!1)}settleResetConfirmation(e){let t=this.resetConfirmation;t&&(this.resetConfirmation=void 0,t.resolve(e))}renderResetConfirmation(){if(!this.resetConfirmation)return U;let e=V(`chat.board.resetTitle`),t=V(`chat.board.resetDescription`);return W`
      <openclaw-modal-dialog
        label=${e}
        description=${t}
        @modal-cancel=${()=>this.settleResetConfirmation(!1)}
      >
        <div class="exec-approval-card board-reset-confirmation">
          <div class="exec-approval-header">
            <div>
              <div class="exec-approval-title">${e}</div>
              <div class="exec-approval-sub">${t}</div>
            </div>
          </div>
          <div class="exec-approval-actions">
            <button
              class="btn primary"
              type="button"
              @click=${()=>this.settleResetConfirmation(!0)}
            >
              ${V(`common.confirm`)}
            </button>
            <button
              class="btn"
              type="button"
              autofocus
              @click=${()=>this.settleResetConfirmation(!1)}
            >
              ${V(`common.cancel`)}
            </button>
          </div>
        </div>
      </openclaw-modal-dialog>
    `}activeChanged(e){this.isConnected&&(this.syncActiveBindings(),e&&this.activateComposerPresentation(),e&&this.presented&&this.state?.chatQueue.length&&(jp(this.state).catch(()=>void 0),qp(this.state)),this.querySelector(`.chat-transcript-announcement`)?.setAttribute(`aria-live`,e?`polite`:`off`))}presentedChanged(e){if(e||(this.dashboardPresentationActivation=void 0,this.retainedProgressCard=void 0,this.syncSessionCompanionPresentation(!1),this.activeSessionResources.sync(null),this.state&&em(this.state),this.context&&_y(this.context,this)),!this.isConnected)return;if(e){this.minutePoll.start(),this.consumeSessionHandoff(this.sessionKey),this.activateComposerPresentation(),this.syncActiveBindings();let e=this.state;e&&(this.unreadPatchGuard.beginActivation(e.sessionKey),nw(e,{automatic:!0}),this.refreshTaskSuggestions({automatic:!0}));let t=this.resumeDeferredSessionHydration();e&&!t&&(this.markSessionRead(Z(e)),e.connected&&this.resolveChatReadTarget()&&(e.chatRunId||Z(e)?.hasActiveRun)&&Rd(e,{deferBranches:!0}),(!z(e.chatBranchesSessionKey,e.sessionKey)||e.chatBranchesConnectionEpoch!==e.connectionEpoch)&&eh(e)),this.refreshSwarmRoster(),this.refreshSessionPullRequests();return}this.minutePoll.stop(),this.state&&(Fd(this.state),fp(this.state)),this.swarmHydrator?.dispose(),this.swarmHydrator=null,this.clearHistoryObserver(),ch(this.context.gateway).unwatch(this),this.syncActiveBindings(),this.clearComposerPrefillAttention(),this.settleResetConfirmation(!1),this.cancelHeaderRename(),fv(this),W_(this.presentationId,this);let t=this.state;t&&(FS(t),QS(t),t.sidebarContent=null,Rg(t),t.requestUpdate?.()),this.querySelector(`.chat-transcript-announcement`)?.setAttribute(`aria-live`,`off`)}prepareForEviction(){let e=this.state;if(!e?.sessionKey)return;let t=this.chatState.composerPersistence.persistForRouteSwitchResult();if(t.status===`storage-failed`){let n=this.chatState.composerPersistence.scopeForRouteSwitch();n&&Bl(e,n,{message:e.chatMessage,mentions:e.chatMentions,goalMode:e.chatGoalDraftMode,replyTarget:e.chatReplyTarget,attachments:e.chatAttachments,draftRetry:t})}}takeSessionHandoff(e){return hf(this.context,this.paneId,e)}consumeSessionHandoff(e){if(!this.state||!e)return;let t=this.takeSessionHandoff(e);t&&this.applySessionHandoff(e,t)}applySessionHandoff(e,t){let n=this.state;if(n&&(t.composerFallbacks&&(n.chatComposerFallbackByScope=t.composerFallbacks),n.chatAttachments=[...t.attachments],n.chatGoalDraftMode=t.goalMode??null,n.chatReplyTarget=t.replyTarget??null,n.handleChatDraftChange(t.draft,t.mentions??[]),n.requestUpdate?.(),t.send)){let r=mg(this.presentationId),i=r.editRevision;queueMicrotask(()=>{if(this.state!==n||n.sessionKey!==e)return;let a=n.client,o=n.connectionEpoch,s=n.sessions,c=n.chatAttachments,l=n.chatMentions,u=n.chatGoalDraftMode,d=n.chatReplyTarget,f=this.headerOutcomeOwner,p=()=>this.state===n&&n.sessionKey===e&&n.connected&&n.client===a&&n.connectionEpoch===o&&n.sessions===s&&this.isConnected&&this.active&&this.ownsHeaderOutcome(f)&&r.editRevision===i&&n.chatMessage===t.draft&&n.chatAttachments===c&&n.chatMentions===l&&n.chatGoalDraftMode===u&&n.chatReplyTarget===d;if(!p())return;let m=ks(n);(m.phase===`in-flight`?m.promise:m.phase===`idle`&&Zp(n)?Rd(n,{startup:!0,deferBranches:!0}):Promise.resolve()).then(()=>{if(p()&&!Zp(n))return n.handleSendChat()}).catch(e=>{p()&&X(n,B(e),!0)})})}}}})))()}var Sw;function Cw(){return(Cw=e((()=>{F(),zt(),Ce(),te(),Ue(),R(),il(),lu(),af(),Fl(),xw(),pp(),Q(),V_(),Sw=class extends bw{constructor(...e){super(...e),this.recoveringSession=!1,this.creatingIncognitoSession=!1,this.recoverSession=async()=>{let e=this.state;if(!e||!e.client||!e.connected||this.recoveringSession)return!1;let t=this.context,n=t.sessions,r={context:t,state:e,client:e.client,generation:this.connectionGeneration},i=()=>this.isConnectionScopeCurrent(r)&&this.context.sessions===n,a=e.sessionKey,o=D(e,a).agentId??_(a),s={...o?{agentId:o}:{},key:a},c=b(t.gateway.snapshot,{method:`sessions.recover`,params:s});if(!c.allowed)return X(e,c.reason,!0),!1;this.recoveringSession=!0,this.requestUpdate(),X(e,null);try{let t=await n.recover(s);if(!i()||e.sessionKey!==a)return!1;if(!t)return X(e,e.sessionsError??`New Chat could not create a new thread. Try again in a moment.`,!0),!1;if(t.continuation.status===`rejected`)return X(e,B(t.continuation.error.message),!0),!1;let r=t.key;return this.onPaneSessionChange?.(this.paneId,r)!==!1&&(Af(this.context,this.paneId,r,{attachments:[],draft:``}),!0)}finally{this.recoveringSession=!1,this.requestUpdate()}},this.createSession=async()=>{let e=this.state;if(!e||!e.client||!e.connected||this.creatingIncognitoSession)return!1;let t=this.context,n=t.sessions,r=e.client,i=e.sessionKey,a=yp(e),o=!a&&this.resolveBoardView().hasBoard,s={...a?{incognito:!0}:{currentSessionKey:i},agentId:D(e,i).agentId??_(i)},c={...me(a?void 0:i,s.agentId),...a?{incognito:!0}:{}},l=()=>b(t.gateway.snapshot,{method:o?`sessions.reset`:`sessions.create`,...o?{requiredScope:`operator.admin`}:{params:c,sessionScope:!0}}),u={context:t,state:e,client:r,generation:this.connectionGeneration},d=()=>this.isConnectionScopeCurrent(u)&&this.context.sessions===n;if(!Kx(e))return X(e,Rf,!0),!1;if(e.sessionsLoading)return X(e,kp,!0),!1;let f=l();if(!f.allowed)return X(e,f.reason,!0),!1;if(!a&&!await this.confirmConversationReset()||!d()||!z(e.sessionKey,i))return!1;if(!Kx(e))return X(e,Rf,!0),!1;let p=l();if(!p.allowed)return X(e,p.reason,!0),!1;if(X(e,null),o)return await ml(e)!==`failed`;this.creatingIncognitoSession=a,a&&this.requestUpdate();try{let t=await n.create(s);return d()?!t||e.sessionKey!==i||!Kx(e)?(t||X(e,e.sessionsError??(e.sessionsLoading?`Session list is still refreshing. Try New Chat again in a moment.`:`New Chat could not create a new thread. Try again in a moment.`),!0),!1):this.onPaneSessionChange?.(this.paneId,t)!==!1&&(Af(this.context,this.paneId,t,{attachments:Mu(e.chatAttachments),draft:e.chatMessage,...e.chatMentions?.length?{mentions:e.chatMentions.map(e=>({...e}))}:{},...e.chatGoalDraftMode?{goalMode:e.chatGoalDraftMode}:{},...e.chatReplyTarget?{replyTarget:e.chatReplyTarget}:{}}),!0):!1}finally{this.creatingIncognitoSession=!1,a&&d()&&this.requestUpdate()}}}sessionDisabledBanner(e){if(e.selectedSession?.classification===`subagent`||ie(e.sessionKey)){let t=ke(e.selectedSession),n=w_(e.selectedSession,this.state?.sessionsResult?.sessions??[]);return{kind:`composer-replacement`,presentation:this.onBackToSubagents?`hidden`:`compact`,icon:`eye`,title:V(`chat.subagentViewOnly`),text:V(`chat.subagentSessionDisabled`,{parent:n?.title??V(`chat.parentSession`)}),tone:`neutral`,actionLabel:V(`chat.openParentSession`),disabledReason:t?void 0:V(`chat.parentSessionUnavailable`),onAction:()=>t&&this.onPaneSessionChange?.(this.paneId,t)}}if(!e.catalogDisabledReason){if(this.state&&yp(this.state)){let e=b(this.context.gateway.snapshot,{method:`sessions.create`,params:{incognito:!0,agentId:D(this.state,this.state.sessionKey).agentId??_(this.state.sessionKey)}});return{kind:`composer-replacement`,title:V(`chat.incognitoExpiredTitle`),text:V(`chat.incognitoExpiredBody`),tone:`neutral`,actionLabel:V(`chat.newIncognitoSession`),busy:this.creatingIncognitoSession,disabledReason:e.allowed?void 0:e.reason,onAction:()=>{this.createSession()}}}return e.restartRecoveryTombstoned?this.restartRecoveryComposerBanner():e.selectedSessionArchived?{kind:`composer-replacement`,text:V(`chat.archivedSessionDisabled`),icon:`archive`,actionLabel:V(`common.unarchive`),disabledReason:e.selectedSessionId?e.unarchiveAccess.allowed?void 0:e.unarchiveAccess.reason:`Session lifecycle action requires a durable session identity.`,onAction:()=>{e.selectedSessionId&&e.unarchiveAccess.allowed&&this.restoreArchivedSession(e.sessionKey,e.selectedSessionId)}}:e.modelSetupRequired?$s(()=>this.context.navigate(`model-providers`,{search:`?connect=1`})):void 0}}restartRecoveryComposerBanner(){let e=this.state;if(!e)return;let t=D(e,e.sessionKey).agentId??_(e.sessionKey),n={...t?{agentId:t}:{},key:e.sessionKey},r=b(this.context.gateway.snapshot,{method:`sessions.recover`,params:n});return{kind:`composer-replacement`,title:V(`chat.restartRecoveryTitle`),text:V(`chat.restartRecoveryDisabled`),tone:`neutral`,icon:`warning`,actionLabel:V(`chat.resumeInNewSession`),actionStyle:`primary`,busy:this.recoveringSession,busyLabel:V(`chat.resumingSession`),disabledReason:r.allowed||this.recoveringSession?void 0:r.reason,onAction:()=>{r.allowed&&!this.recoveringSession&&this.recoverSession()}}}}})))()}function ww(e,t){return e.chatQueue.some(e=>e.sendRunId===t&&e.sendState===`sending`)}function Tw(e){let t=J(e);return t?.role===`assistant`&&Array.isArray(t.content)?t:null}function Ew(e){let t=e.errorDetail;if(!t||t.providerRuntimeFailureKind!==`auth_refresh`)return null;let n=[t.provider?`Provider: ${t.provider}`:void 0,t.httpStatus?`HTTP status: ${t.httpStatus}`:void 0,t.failoverReason?`Reason: ${t.failoverReason}`:void 0,t.providerErrorType?`Type: ${t.providerErrorType}`:void 0].filter(e=>!!e);return n.length>0?n.join(`
`):null}function Dw(e,t){let n=e.errorMessage?.trim();if(n){if(e.state===`error`&&(e.errorKind===`state_contention`||e.stopReason===`aborted-partial-persistence-failed`))return n;let t=n.startsWith(`⚠️`)||n.startsWith(`Error:`)?n:`Error: ${n}`,r=Ew(e);return r?`${t}\n\n${r}`:t}return(t?ki(t)?.trim():null)||`chat error`}function Ow(e,t){if(!t)return null;let n=J(t.message),r=n&&t.state!==`delta`&&t.state!==`status`?ci(n):t.message,i=r===t.message?t:{...t,message:r},a=i.state===`aborted`&&i.stopReason===`auth-revoked`?{...i,errorMessage:V(`chat.providerAccessRemoved`)}:i,o=a.state===`error`&&a.errorKind===`state_contention`?`state_contention`:a.state===`error`&&a.stopReason===`aborted-partial-persistence-failed`?`stop`:a.errorDetail?.providerRuntimeFailureKind===`auth_refresh`?`auth_refresh`:void 0,s=a.state===`final`&&a.seq===0&&a.runId?.startsWith(`inject-`)?a.runId.slice(7):null,c=a.state===`final`?Qd(a.message):null,l=s&&c?{...c,__openclaw:{...J(c.__openclaw),id:s}}:c,u=(e,n)=>{if(r!==t.message)return null;let i=n?e.findLast(e=>Zr(e)?.role===`user`&&Am(e)===n):void 0;return i?Zr(i)?.sequence??null:void 0},d=e.chatRunId!==null,p=ze(e,a.sessionKey,a.agentId),h=e.chatRunId!==null&&typeof a.runId==`string`&&a.runId===e.chatRunId,g=!!(a.runId&&Ud(e,a.runId)&&p);if(!p){if(a.state===`final`){let t=l;if(t&&!qi(t)){let n=f(a.sessionKey)?a.agentId??m(e):a.agentId;if(e.chatMessagesBySession){let r=Ic(e.chatMessagesBySession,e,{sessionKey:a.sessionKey,agentId:n});if(s&&r.some(e=>Zr(e)?.id===s))return null;let i=u(r,a.runId);Wc(e.chatMessagesBySession,e,{sessionKey:a.sessionKey,agentId:n},t,s?{messageId:s}:i===void 0?a:{...a,afterSequence:i})}}}return null}if(s)return l&&!qi(l)&&!e.chatMessages.some(e=>Zr(e)?.id===s)&&js(e,{type:`messagePersisted`,message:l}),`injected`;let _=Zf(e),v=(t,n,r)=>{let i=a,o=u(e.chatMessages,r);Il(e,n,{scope:_,event:{type:`messagePersisted`,message:t,envelope:{...o===void 0?{}:{afterSequence:o},...r?{runId:r}:{},...i.messageId===void 0?{}:{messageId:i.messageId},...i.messageSeq===void 0?{}:{messageSeq:i.messageSeq}}}})},y=a.runId&&a.state!==`status`?ni(Lm(e,_),l?{...a,message:l}:a,_):null;y&&ec(e,y.projection);let b=a.runId??e.chatRunId,x=()=>{let t=y?.currentRun?.status;if(!a.runId||a.runId!==e.chatRunId||!t||t===`streaming`)return;cu(e);let n=[e.sessionKey,a.sessionKey];if(t===`yielded`){Fu(e,{yielded:!0,runId:b,sessionKey:e.sessionKey,sessionKeys:n,clearLocalRun:!0,clearChatStream:!0});return}Fu(e,{outcome:t===`completed`?`done`:`interrupted`,sessionStatus:t===`completed`?`done`:t===`aborted`?`killed`:t===`timeout`?`timeout`:`failed`,errorMessage:a.errorMessage?.trim()?Dw(a,null):void 0,runId:b,sessionKey:e.sessionKey,sessionKeys:n,clearLocalRun:!0,clearChatStream:!0,armLocalTerminalReconcile:d&&h})},S=y?.previousRun;if(S&&S.status!==`streaming`&&y.currentRun?.status!==`streaming`){if(a.state===`delta`)return null;if(a.state===`error`||a.state===`aborted`){let t=e.chatQueue.find(e=>e.sendState===`sending`&&e.sendRunId)?.sendRunId;if((e.chatRunId??t??e.lastLocalTerminalReconcile?.runId)===a.runId&&a.errorMessage?.trim()&&y.currentRun?.errorMessage!==S.errorMessage&&Ou(e,Dw(a,null),a.runId,o),a.state===`error`)return x(),`error`}let t=l;if(a.state===`aborted`||a.state===`final`&&(!t||qi(t)||Jr(S,t)))return x(),a.state}if(!e.chatRunId&&(!S||S.status===`streaming`||y?.currentRun?.status===`streaming`)&&typeof a.runId==`string`&&(a.state!==`status`||ww(e,a.runId))&&(a.state===`status`?Uf(e,a.runId,Date.now()):(e.chatRunId=a.runId,Ol(e,a.runId),e.chatRunError=null,e.chatStreamStartedAt??=Date.now())),e.chatRunId&&a.runId!==e.chatRunId){if(a.state===`final`){let t=l;return t&&!qi(t)?(v(t,[...e.chatMessages,t],a.runId),null):`final`}return null}h&&r!==t.message&&nh(e,ki(r)??null);let C=(t={})=>Ns(e.chatMessages,e,t),w=(e,t,n,r=!0)=>{let i=Sf(e,b,n);v(e,r?pl(t,i):[...t,i],b)},T=()=>{Il(e,C(),{scope:_}),Sf(e.chatMessages.findLast(e=>Lf(e)===b),b,a.state===`aborted`?`aborted`:y?.currentRun?.status===`timeout`?`timeout`:`error`)};if(a.state===`status`){if(!a.runId||a.runId!==e.chatRunId)return null;let t=a.retry?typeof a.seq==`number`&&{phase:`retrying`,seq:a.seq,message:V(`chat.startupStatus.retrying`,{attempt:String(a.retry.attempt),maxAttempts:String(a.retry.maxAttempts)})}:a.phase&&{phase:a.phase,...a.seq===void 0?{}:{seq:a.seq}};return t&&wc(e,{state:`status`,runId:a.runId,...t}),a.state}if(a.state===`delta`){a.runId&&a.runId===e.chatRunId&&wc(e,{state:`activity`,runId:a.runId});let t=a.message==null?null:ki(a.message)??``;if(typeof t==`string`){let n=Ki(t)||Wi(a.message);a.replace?nh(e,n?``:t):n||(e.chatStream=t)}}else if(a.state===`final`){let t=l;g||(t&&!qi(t)?w(t,C()):Il(e,C(),{scope:_})),x()}else if(a.state===`aborted`){let t=Tw(a.message);t&&!qi(t)?w(t,C({replacementMessages:[t],includeCurrent:!1}),`aborted`):T(),a.errorMessage?.trim()&&Ou(e,Dw(a,null),a.runId,o),x()}else if(a.state===`error`){let t=Qd(a.message),n=t&&!qi(t)?t:null,r=!!(n&&ai(n,a.errorMessage));if(d){if(n&&!r){let t=Ru(n,e,{isHiddenStreamText:Na});w(n,C({includeCurrent:!t}),y?.currentRun?.status===`timeout`?`timeout`:`error`,t)}else T()}x(),Ou(e,Dw(a,r?n:null),a.runId,o)}return a.state!==`delta`&&cu(e),a.state}function kw(){return(kw=e((()=>{Xr(),ri(),$r(),Qr(),li(),F(),Ni(),na(),ra(),y(),R(),$f(),Uu(),Ss(),Cu(),gc(),Gs(),Cd(),dh(),ap()})))()}function Aw(e,t,n){Rd(e,{deferBranches:!t,...n?{supersedeInFlight:n}:{}}).finally(()=>e.requestUpdate?.())}function jw(e,t){return t?yo(t):m(e)}function Mw(e,t){if(!f(t.key))return!0;let n=f(e.sessionKey)?E(e):A(e,e.sessionKey);return!n||jw(e,t.agentId)===n}function Nw(e,t,n,r,i){let a=r?Is(e,r,{publishRunStatus:!0}):sh(e,{publishRunStatus:!0}),o=r??Z(e),s=!(!e.chatRunId||o?.hasActiveRun!==!1||go(o));return!a&&!s?!1:(a&&Md(e,n??void 0),Rd(e,{deferBranches:!i(),supersedeInFlight:s}).finally(()=>{z(e.sessionKey,t)&&(Ju(e),e.requestUpdate?.())}).catch(()=>void 0),!0)}function Pw(e,t,n,r){let i=w(t);if(!i||!Mw(e,i))return!1;let a=ze(e,i.key,i.agentId??void 0),o=Zr(J(t)?.message)?.role===`user`;a&&(Om(e),ks(e).phase===`in-flight`&&Aw(e,n(),!0),gu(e,t,i.hasActiveRun??void 0,{kind:`live`,activeRunId:e.chatRunId})),a&&i.archived!==null&&(e.selectedChatSessionArchived=i.archived);let s=e.chatRunId;if(kf({event:i,host:e,matchesChat:a,payload:t,runIdBeforeApply:s}),r.applied&&iu(e),s&&a){let t=i.clientRunId??i.runId??s;return e.pendingSessionMessageReloadSessionKey=i.key,i.hasActiveRun===!0?(o&&Aw(e,n(),!0),!0):Nw(e,i.key,t,r.row,n)?(e.pendingSessionMessageReloadSessionKey=null,!0):(jp(e).then(()=>{e.pendingSessionMessageReloadSessionKey&&e.chatRunId===s&&Nw(e,e.pendingSessionMessageReloadSessionKey,t,void 0,n)&&(e.pendingSessionMessageReloadSessionKey=null)}),!0)}return a&&(e.pendingSessionMessageReloadSessionKey=null,Aw(e,n())),a}function Fw(e,t,n){let r=e.pendingSessionMessageReloadSessionKey,i=t?.sessionKey?.trim();return!r||!i||!z(r,i)||!z(i,e.sessionKey)||e.chatRunId?!1:(e.pendingSessionMessageReloadSessionKey=null,Aw(e,n()),!0)}function Iw(e,t){let n=Jw.get(e);n||(n=new Map,Jw.set(e,n));let r=[t.connectionEpoch,t.runLifecycleGeneration,t.agentId,t.sessionKey,t.runId].join(`\0`);return n.has(r)&&n.get(r)===t.client?!1:(n.delete(r),n.set(r,t.client),Wa(n,qw),!0)}function Lw(e,t){let n=tv(e,t.runId);return n.acceptedFinal||[...n.terminalReplySignatures].some(e=>!t.initialTerminalReplySignatures.has(e))}function Rw(e,t){return e.connected&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&z(e.sessionKey,t.sessionKey)&&Y(e)===t.agentId&&(e.chatRunId===null||e.chatRunId===t.runId)&&(e.chatRunLifecycleGeneration??0)===t.runLifecycleGeneration&&!Lw(e,t)}async function zw(e,t,n){for(let r=0;;r+=1){if(!Rw(e,t)||(await Rd(e,{deferBranches:!n(),supersedeInFlight:!0}),e.requestUpdate?.(),!Rw(e,t)))return;let i=Kw[r];if(i===void 0)return;await Va(i)}}function Bw(e,t,n,r){let i=n(),a=e.chatRunId,o=w(t),s=!!(o&&Mw(e,o)&&ze(e,o.key,o.agentId??void 0)),c=J(t),l=c?.reason===`reset`||c?.phase===`reset`;o&&(l||c?.reason===`new`)&&e.retireSessionCompanion?.(o.key,o.agentId);let u=s&&l;if(s&&(l||c?.reason===`new`)){let t=e.chatSubmissions?.readInitial(e.sessionKey,e.client??null);t&&Wf(e,new Set([t.pendingRunId]))}let d=s&&typeof c?.reason==`string`&&Ww.has(c.reason);if((u||d)&&fp(e),s&&c?.reason===`project`&&Vg(e),u){let t=Zf(e,{agentId:Y(e)});js(e,{type:`sessionReset`},{scope:t})}d&&(Om(e),e.chatBranches=[],e.chatBranchesSessionKey=null,e.chatBranchesConnectionEpoch=null,Vg(e),i&&eh(e)),o&&s&&o.archived!==null&&(e.selectedChatSessionArchived=o.archived),r.applied&&iu(e);let f=o?.clientRunId??o?.runId;return s&&c?.phase===`model`&&f&&r.admittedRow&&(e.chatSending?e.chatQueue.some(t=>t.sendState===`sending`&&(t.queueMode===`steer`&&e.chatRunId?e.chatRunId===f:t.sendRunId===f)):!e.chatRunId||e.chatRunId===f)&&uc(e,f,r.admittedRow),u||s&&c?.reason===`compact`?(Aw(e,i),!0):s&&c?.phase===`message`&&c.message===void 0&&c.messageId===void 0&&c.messageSeq===void 0?(Om(e),Aw(e,i,!0),!0):(s&&typeof c?.reason==`string`&&Gw.has(c.reason)&&Aw(e,i,!0),r.applied&&o&&a&&s&&Nw(e,o.key,o.clientRunId??o.runId??a,r.row,n),s)}function Vw(e,t){if(t?.state!==`final`||!ze(e,t.sessionKey,t.agentId))return!1;let n=ki(t.message),r=typeof t.runId==`string`&&t.runId===e.chatRunId?[e.chatStream,...(e.chatStreamSegments??[]).map(e=>e.text)]:[],i=e=>typeof e==`string`&&e.trim().length>0&&!Na(e);return(i(n)&&!qi(t.message)||r.some(i))&&[n,...r].some(e=>Zd(e).length>0)}function Hw(e,t){if(e.chatRunId)return t.runId===e.chatRunId;let n=Z(e);return!!(n?.hasActiveRun&&t.runId&&n.activeRunIds?.includes(t.runId))}function Uw(e,t,n=()=>!0,r={applied:!1}){if(t.event===`models.snapshot`){cw(e);return}if(t.event===`session.approval`){let n=J(t.payload);if(!n||typeof n.sessionKey!=`string`)return;let r=f_(e.chatSessionApprovalQueue??[],n,e.sessionKey,Y(e));r&&(e.chatSessionApprovalQueue=r,rC(e));return}if(t.event===`chat`){let r=t.payload,i=r&&(r.state===`final`||r.state===`aborted`||r.state===`error`)?r:void 0,a=()=>{let a=!!(r&&ze(e,r.sessionKey,r.agentId)),o=r?.state===`final`&&(r.message===void 0||r.message===null)&&a&&typeof r.runId==`string`&&(!e.chatRunId||e.chatRunId===r.runId)?r.runId:null,s=o?Zf(e):null;r?.state===`delta`&&typeof r.runId==`string`&&a&&(!e.chatRunId||e.chatRunId===r.runId)&&e.observerDigest&&e.observerDigest.runId!==r.runId&&(e.observerDigest=null),r?.state===`delta`&&typeof r.deltaText==`string`&&a&&Fp(e,r.runId,r.deltaText);let c=Vw(e,r);if(Ow(e,r)===`injected`){rC(e);return}i&&a&&Md(e,i.runId),c&&r&&pf(e,r.runId,r.message);let l=o&&s&&Lm(e,s).runs[o]?.status===`completed`&&r?.runId?{sessionKey:r.sessionKey,agentId:Y(e),runId:r.runId,client:e.client,connectionEpoch:e.connectionEpoch,runLifecycleGeneration:e.chatRunLifecycleGeneration??0,initialTerminalReplySignatures:tv(e,r.runId).terminalReplySignatures}:null;l&&Iw(e,l)?(e.pendingSessionMessageReloadSessionKey=null,zw(e,l,n).catch(()=>void 0)):Fw(e,r,n),i&&(qp(e,t),a&&(n()?L_(e,Ae(e.sidebarLayout,`workspace`)):Vg(e))),a&&rC(e,r?.state===`delta`?`animation-frame`:`immediate`)};if(!i){a();return}let o=I(e,i.sessionKey,f(i.sessionKey)?jw(e,i.agentId??null):i.agentId),s=e.connectionEpoch,c=Tm(e,i.runId,o),l=ih(e),u=Nl(e,i.runId,o,{retainUntilConsumed:!!(c&&El(c))}),d=t=>{t!==`stale`&&e.connectionEpoch===s&&l()&&a()};if(u instanceof Promise){u.then(d);return}d(u);return}if(t.event===`session.observer`){let n=t.payload;if(!n||!ze(e,n.sessionKey,n.agentId)||!Hw(e,n))return;let r=e.observerDigest;if(r?.runId===n.runId&&zu(r,n)===r)return;e.observerDigest=n,rC(e);return}if(t.event===`agent`||t.event===`session.tool`){Kf(e,t.payload)&&rC(e,`animation-frame`);return}if(t.event===`session.operation`){Al(e,t.payload),rC(e,`animation-frame`);return}if(t.event===`chat.send_timing`){zp(e,t.payload);return}if(t.event===`session.message`||t.event===`sessions.changed`){let i=(t.event===`session.message`?Pw:Bw)(e,t.payload,n,r);qp(e,t),i&&rC(e,`animation-frame`)}}var Ww,Gw,Kw,qw,Jw;function Yw(){return(Yw=e((()=>{$r(),Za(),na(),ra(),y(),l(),R(),kw(),xd(),af(),rh(),bm(),Jd(),Oc(),tp(),vf(),Vf(),pw(),Q(),ov(),Cu(),zd(),gc(),l_(),Ys(),vv(),ap(),yv(),Gl(),Sl(),Ww=new Set([`rewind`,`branch-switch`,`fork`,`reset`,`new`]),Gw=new Set([`send`,`agent.run.started`,`agent.input.settled`]),Kw=[100,400,1500,3e3],qw=64,Jw=new WeakMap})))()}function Xw(e,t,n=null){let r=Y(e);if(!t){let t=e.sessionsResult;if(!t||e.sessionsResultAgentId!==r)return!1;let i=t.sessions.filter(t=>!ze(e,t.key,t.agentId)||n!==null&&t.sessionId!==n);return i.length!==t.sessions.length&&(e.sessionsResult={...t,sessions:i,count:i.length},!0)}if(!ze(e,t.key,t.agentId??r))return!1;let i=e.sessionsResultAgentId===r?e.sessionsResult:null,a=t.sessionId?i?.sessions.find(n=>n.sessionId===t.sessionId&&ze(e,n.key,n.agentId)):void 0,s=a&&a.key!==t.key?e.sessions.inheritRow({...t,key:a.key},t):t,c=i&&a?o(i,i.sessions.map(e=>e===a?s:e)):ct(i,t,void 0,{resultAgentId:r,selectedGlobalAgentId:r,archivedFilter:t.archived?`all`:e.sessionsArchivedFilter},!1,{project:(n,r)=>e.sessions.inheritRow(n,t,r)});return t.providerReview&&(fd(e,t.key,t.agentId??r),(e.realtimeTalkSession||e.realtimeTalkActive||e.realtimeTalkUseSystemDefault)&&FS(e,{preserveConversation:!0})),c===e.sessionsResult&&e.sessionsResultAgentId===r?!1:(e.sessionsResult=c,e.sessionsResultAgentId=r,!0)}var Zw;function Qw(){return(Qw=e((()=>{_t(),y(),l(),R(),Cw(),rd(),RS(),Oc(),Yw(),Q(),Cu(),gc(),Zw=class extends Sw{constructor(...e){super(...e),this.sessionObservation=null,this.parentSessionObservation=null}observedParentSessionRow(){let e=this.parentSessionObservation;return e?.matchesPane()&&e.observation?.isCurrent()?e.observation.row:null}retireParentSessionObservation(){let e=this.parentSessionObservation;this.parentSessionObservation=null,e?.observation?.dispose()}synchronizeParentSessionObservation(){let e=this.state,t=this.resourceSessionObservation(),n=ke(t?.row);if(!e?.connected||!t||!n||z(n,e.sessionKey)){this.retireParentSessionObservation();return}let r=this.parentSessionObservation;if(r?.matchesPane()&&r.observation?.isCurrent()){r.retryFailedRead();return}this.retireParentSessionObservation();let i=this.context.sessions,a=e.client;if(!a)return;let o=Bt(n)?.agentId??Y(e),s=!1,c={retryFailedRead:()=>{s&&d()},matchesPane:()=>this.state===e&&e.connected&&e.client===a&&this.resourceSessionObservation()===t&&ke(t.row)===n,observation:null},l=()=>this.parentSessionObservation===c&&c.matchesPane(),u=null,d=()=>{!u&&l()&&(s=!1,u=(async()=>{let e=c.observation;for(;l()&&e?.isCurrent();){let t=e.captureReconcile(),{session:r}=await i.describe({key:n,agentId:o},{client:a});if(!l()||t(r??void 0).status!==`invalidated`)return}})().catch(()=>{s=!0}).finally(()=>{u=null}))};this.parentSessionObservation=c,c.observation=i.observeRow({key:n,agentId:o},(e,t)=>{l()&&(this.requestUpdate(),!t?.eventPending&&c.observation&&!c.observation.isCurrent()&&this.synchronizeParentSessionObservation())},{onInvalidate:d,onEvent:()=>{l()&&!c.observation?.isCurrent()&&this.synchronizeParentSessionObservation()}}),l()?d():c.observation.dispose()}resourceSessionObservation(){let e=this.sessionObservation;return e?.matchesPane()&&e.observation?.isCurrent()?e.observation:null}retireSessionObservation(){this.retireParentSessionObservation();let e=this.sessionObservation;this.sessionObservation=null,e?.observation?.dispose()}synchronizeSessionObservation(e={}){let n=this.state,r=this.context.sessions;if(!n?.connected||!n.sessionKey.trim()||L(n.sessionKey)){this.retireSessionObservation();return}let i=r.captureConnectionScope();if(!i){this.retireSessionObservation();return}let a=n.sessionKey,o=Y(n),s=this.sessionObservation;if(s?.matchesPane()&&s.observation?.isCurrent()){this.synchronizeParentSessionObservation();return}let c=s?.matchesPane()?s.observation?.sessionId:null,l=n.chatRunId||n.chatStream!=null||Lm(n).entries.some(e=>!e.pending)?s?.observation?.sessionId:null;this.retireSessionObservation();let u={matchesPane:()=>this.state===n&&n.sessionKey===a&&Y(n)===o&&r===this.context.sessions&&r.isConnectionScopeCurrent(i),observation:null},d=()=>n.connected&&u.matchesPane(),f=()=>this.sessionObservation===u&&d();if(this.sessionObservation=u,u.observation=r.observeRow({key:a,agentId:o},(e,r)=>{if(f()&&(e!==null||u.observation?.hasObserved)){let r=n.pendingAbort;!e&&r&&t(n,r.sessionKey,a,o,r.agentId)&&(n.pendingAbort=null),Xw(n,e,u.observation?.sessionId)&&this.requestUpdate(),this.synchronizeParentSessionObservation(),n.pendingAbort&&kc(n).finally(()=>n.requestUpdate?.())}!r?.eventPending&&f()&&u.observation&&!u.observation.isCurrent()&&this.synchronizeSessionObservation()},{onInvalidate:e=>{if(f()){if(e===`runner-availability`){this.activeSessionResources.invalidate(),this.requestUpdate();return}this.activeSessionResources.reconcileObservation({requestUpdate:()=>this.requestUpdate(),updated:()=>this.updateComplete})}},onEvent:(e,t)=>{if(!f())return;if(t.generationRejected){this.synchronizeSessionObservation(),d()&&qp(n,e);return}let r=t,i=l,a=w(e.payload);if(u.observation&&!u.observation.isCurrent()){let t=u.observation.sessionId;i=t,this.synchronizeSessionObservation({eventSessionId:a?.sessionId});let o=this.sessionObservation;if(!d()||!o?.matchesPane()||!o.observation?.isCurrent())return;if(!a?.sessionId||a.sessionId===t||a.sessionId!==o.observation.sessionId||a.sessionId!==o.observation.row?.sessionId||!ze(n,a.key,a.agentId??void 0)){qp(n,e);return}r={applied:!1}}let o=this.sessionObservation?.observation,s=n.currentSessionId??i;if(a?.sessionId&&o?.isCurrent()&&a.sessionId===o.sessionId&&a.sessionId===o.row?.sessionId&&ze(n,a.key,a.agentId??void 0)&&s&&s!==a.sessionId&&(n.currentSessionId||n.chatRunId||n.chatStream!=null||Lm(n).entries.some(e=>!e.pending))){this.refreshHistory(),qp(n,e);return}e.event===`session.message`&&this.clearTypingActorForSessionMessage(e.payload),Uw(n,e,()=>this.presented,r)}}),!f())u.observation.dispose();else{this.projectObservedSessionRow();let t=u.observation,r=n.currentSessionId??l;c&&t?.isCurrent()&&t.sessionId&&t.sessionId!==e.eventSessionId&&t.sessionId!==c&&t.row?.sessionId===t.sessionId&&r&&r!==t.sessionId&&this.refreshHistory()}}projectObservedSessionRow(){let e=this.state,t=this.sessionObservation;e&&t&&t.matchesPane()&&t.observation?.hasObserved&&t.observation?.isCurrent()&&(Xw(e,t.observation.row,t.observation.sessionId),this.synchronizeParentSessionObservation())}setPaneSessionKey(e){let t=super.setPaneSessionKey(e);return this.synchronizeSessionObservation(),t}}})))()}var $w,eT;function tT(){return(tT=e((()=>{Zn(),vr(),$n(),oy(),R(),Q(),vv(),$w=[[zn,`terminal`,`openclaw-terminal-panel`],[en,`browser`,`openclaw-browser-panel`],[Yn,`link-reader`,`openclaw-link-reader-panel`],[ar,`desktop`,`openclaw-desktop-panel`],[or,`portal`,`openclaw-portals-page`]],eT=class{constructor(e){this.options=e}subscribe(){let e=$w.map(([e,t,n])=>{let r=e=>{this.handle(t,n,e)};return window.addEventListener(e,r),()=>window.removeEventListener(e,r)}),t=e=>this.handlePluginPanel(e);window.addEventListener(Pn,t),e.push(()=>window.removeEventListener(Pn,t));let n=()=>{let e=this.options.current();e&&e.state.updateSidebarLayout(O_(e.state.sidebarLayout,`terminal`))};return window.addEventListener(hr,n),()=>{e.forEach(e=>e()),window.removeEventListener(hr,n),this.options.pending.clear()}}handlePluginPanel(e){let t=this.options.current();if(!t||!(e instanceof CustomEvent))return;let n=e.detail,r=`${n.pluginId}/${n.panelId}`;if(!t.pluginPanels.includes(r)||!z(n.sessionKey,t.state.sessionKey)||n.agentId&&n.agentId!==Y(t.state))return;let i=`plugin:${r}`;xn(i,e);let a=n.open?dv(t.state.sidebarLayout,i):O_(t.state.sidebarLayout,i);n.dock&&(a=S_(a,n.dock)),this.options.updateSidebarLayout(a)}handle(e,t,n){let r=this.options.current();if(!r)return!1;let i=tn(n);if(i&&!z(i,r.state.sessionKey))return!1;let a=n instanceof CustomEvent?n.detail:null;if(e===`link-reader`&&a?.open!==!1&&(!r.state.connected||!r.state.client||r.linkReaders.length===0||a?.url!==void 0&&!fn(a.url,r.linkReaders)))return xn(e,n),!1;if(xn(e,n),e===`link-reader`&&n.preventDefault(),a?.open===!1)return this.options.pending.delete(e),this.options.updateSidebarLayout(O_(r.state.sidebarLayout,e)),!0;let o=dv(r.state.sidebarLayout,e);(a?.dock===`right`||a?.dock===`bottom`)&&(o=S_(o,a.dock));let s=o.columns.flatMap(e=>e.panels).find(t=>t.slot===e);if(s&&e===`desktop`&&i&&typeof a?.environmentId==`string`&&(s.environmentId=a.environmentId),s&&e===`portal`&&typeof a?.portalId==`string`?(s.portalId=a.portalId,delete s.environmentId):s&&e===`portal`&&typeof a?.environmentId==`string`&&(s.environmentId=a.environmentId,delete s.portalId),e===`terminal`){let e=Lv(n,Y(r.state)),t=r.renderRoot.querySelector(`openclaw-terminal-panel[embedded]`),i=customElements.get(`openclaw-terminal-panel`),a=t!==null&&i!==void 0&&t instanceof i;return a&&t.activateTerminalHost(),e&&Jv.queue(e,{deferUntilHostChange:!a}),this.options.updateSidebarLayout(o),!0}let c=this.options.pending.get(e);if(e===`link-reader`&&c?.owner===r.state&&c.sessionKey===r.state.sessionKey)return c.events.push(n),this.options.updateSidebarLayout(o),!0;let l={events:[n],owner:r.state,sessionKey:r.state.sessionKey},u=r.state.sessionKey,d=()=>this.options.pending.get(e)===l&&this.options.current()?.state===r.state&&r.state.sessionKey===u;return this.options.pending.set(e,l),this.options.updateSidebarLayout(o),Promise.all([customElements.whenDefined(`openclaw-chat-sidebar-region`),customElements.whenDefined(t)]).then(async()=>{if(this.options.requestUpdate(),await this.options.current()?.updateComplete,!d())return;let t=r.renderRoot.querySelector(`openclaw-chat-sidebar-region`);if(await t?.updateComplete,d())for(let n of l.events){if(!d())return;let r=this.options.current(),i=n instanceof CustomEvent?n.detail:null;(e!==`link-reader`||r?.state.connected&&r.state.client&&r.linkReaders.length!==0&&(i?.url===void 0||fn(i.url,r.linkReaders)))&&t?.deliverPanelEvent(e,n)}}).finally(()=>{this.options.pending.get(e)===l&&(this.options.pending.delete(e),this.options.requestUpdate())}),!0}flush(){let e=this.options.current();if(e){for(let t of e.pluginPanels){let n;for(;n=yn(`plugin:${t}`,e.state.sessionKey,Y(e.state));)this.handlePluginPanel(n)}for(let[,t,n]of $w){let r;for(;r=yn(t,e.state.sessionKey);)this.handle(t,n,r)}}}}})))()}function nT(e,t){return e?W`<a
        class="rail-header__action"
        href=${e}
        target="_blank"
        rel="noopener"
        aria-label=${t}
        title=${t}
        >${H.externalLink}</a
      >`:void 0}function rT(e){let t=e?.state,r=t?.sidebarLayout.columns.flatMap(e=>e.panels)??[],i=e&&{...e,dashboardAvailable:()=>e.dashboard!==U},a=(e,n,r,a)=>{let o=e===`detail`?`review`:e===`workspace`?`files`:e;return{slot:e,label:V(`chat.sidePanel.${o}`),icon:n,available:!!(i&&(e===`portal`?t&&ui({hello:t.hello,client:t.client,phase:t.connected?`connected`:`stopped`},`portal.list`,`operator.read`):e===`subagents`||e===`processes`?i.subagentsAvailable:Ux[e]?.available(i))),content:r,loading:Xv(o===`conversation`||o===`companion`?`chat`:o===`subagents`||o===`processes`?`file-list`:o===`portal`?`browser`:o===`dashboard`?`board`:o,V(o===`desktop`?`desktop.connecting`:`common.loading`)),empty:{description:V(`chat.sidePanel.${o}Empty`)},headerAction:a,shortcut:Ux[e]?.combo}},o=(t,n)=>e?W`<button
          type="button"
          class="rail-header__action"
          aria-label=${V(`chat.${t}Panel.refresh`)}
          title=${V(`chat.${t}Panel.refresh`)}
          ?disabled=${!e.connected}
          @click=${n}
        >
          ${H.refresh}
        </button>`:void 0,s=t?.terminalAvailable?W`<openclaw-terminal-panel
        embedded
        .tabsInHeader=${e?.terminalTabsInHeader??!1}
        .onClose=${e?.onCloseTerminal}
        .client=${t.connected?t.client:null}
        .available=${t.terminalAvailable}
        .agentId=${e?.agentId??null}
        .sessionKey=${t.sessionKey}
        .themeMode=${e?.themeMode??`dark`}
        .basePath=${t.basePath}
      ></openclaw-terminal-panel>`:null,c=t?.browserPanelAvailable?W`<openclaw-browser-panel
        embedded
        data-chat-autotype-exempt
        .client=${t.connected?t.client:null}
        .available=${t.browserPanelAvailable}
        .remoteAvailable=${_r({phase:t.connected?`connected`:`offline`,hello:t.hello})}
        .presented=${Ge(e?.browserPresented??!1)}
        .tabsInHeader=${e?.browserTabsInHeader??!1}
        .refreshOnPresentation=${e?.browserRefreshOnPresentation??!0}
        .sessionKey=${t.sessionKey}
        .preferredTab=${e?.preferredBrowserTab}
        .sessionTabs=${e?.sessionBrowserTabs??[]}
        .resourceBasePath=${t.resourceBasePath}
        .authToken=${Un(t)}
      ></openclaw-browser-panel>`:null,l=e?W`<openclaw-chat-session-rail
        .presented=${Ge(e.companionPresented)}
        .focusRequest=${e.companionFocusRequest}
        .sessionKey=${t?.sessionKey}
        .digest=${e.digest}
        .running=${!!e.activeRunId}
        .activeRunId=${e.activeRunId}
        .pullRequests=${e.pullRequests}
        .companion=${e.companion}
        .connected=${t?.connected===!0}
        .sendShortcut=${t?.settings.chatSendShortcut??`enter`}
        .onSubmit=${e.onCompanionSubmit}
        .onDraftChange=${e.onCompanionDraftChange}
        .onAttachmentsChange=${e.onCompanionAttachmentsChange}
        .uploadConfig=${t?.uploadConfig}
        .attachmentLimits=${sf(t?.hello?.policy)}
      ></openclaw-chat-session-rail>`:null,u=t&&e?.desktopAvailable?W`<openclaw-desktop-panel
          embedded
          data-chat-autotype-exempt
          .client=${t.connected?t.client:null}
          .available=${e.desktopAvailable}
          .presented=${Ge(e?.desktopPresented??!1)}
          .refreshOnPresentation=${e?.desktopRefreshOnPresentation??!0}
          .requestedSource=${e?.desktopSource??null}
          .runtimeConfig=${e.desktopRuntimeConfig}
          .sessionKey=${t.sessionKey}
          .onFocusTargetChange=${e?.onDesktopFocusTargetChange}
        ></openclaw-desktop-panel>`:null,d=e?.discussion?W`<openclaw-session-discussion
        .sessionKey=${e.discussion.sessionKey}
        .canOpen=${e.discussion.canOpen}
        .sourceGeneration=${e.discussionSourceGeneration}
        .loadInfo=${e.discussion.loadInfo}
        .openDiscussion=${e.discussion.openDiscussion}
        .onStateChange=${e.discussion.onStateChange}
      ></openclaw-session-discussion>`:null,f=r.find(e=>e.slot===`portal`),p=t?W`<openclaw-portals-page
        embedded
        .presented=${Ge(e?.portalPresented??!1)}
        .requestedPortalId=${f?.portalId??null}
        .requestedEnvironmentId=${f?.environmentId??null}
      ></openclaw-portals-page>`:null,m=t?U_(t):null,h=t?.sidebarContent??(t?P_(t):null),g=r.some(e=>e.slot===`detail`),_=t&&e&&m?W`<openclaw-chat-files-panel
          .tabsInHeader=${n(t.sidebarLayout)?.slot!==`workspace`}
          .previews=${Pt(e.panePresentation??!0,m.previews,[])}
          .activeId=${Pt(e.panePresentation??!0,m.activePreviewId,null)}
          .browser=${e.workspace}
          .renderDetail=${e.renderDetail}
          .onSelect=${e=>pg(t,e)}
          .onClose=${e=>ng(t,e)}
        ></openclaw-chat-files-panel>`:e?.workspace??null,v=new Map((e?.pluginPanels??[]).map(e=>[`plugin:${e.key}`,e]));for(let{slot:e}of r)e.startsWith(`plugin:`)&&!v.has(e)&&v.set(e,void 0);return[a(`conversation`,H.messageSquare,U),a(`subagents`,H.bot,t&&e?W`<openclaw-chat-subagents-panel
            .sessionKey=${t.sessionKey}
            .agentId=${e.agentId??`main`}
            .paneId=${e.paneId}
            .presentationId=${e.panePresentationId}
            .inputRegion=${e.subagentsInputRegion}
            .presented=${Ge(e.subagentsPresented)}
            .showRequest=${e.subagentsShowRequest}
            .onSessionSelect=${e.onSubagentSessionSelect}
          ></openclaw-chat-subagents-panel>`:null,o(`subagents`,e?.onRefreshSubagents)),a(`processes`,H.terminal,t&&e?W`<openclaw-chat-processes-panel
            .sessionKey=${t.sessionKey}
            .agentId=${e.agentId??`main`}
            .presented=${Ge(e.processesPresented??!1)}
          ></openclaw-chat-processes-panel>`:null,o(`processes`,e?.onRefreshProcesses)),a(`detail`,H.diff,h?.kind===`loading`?Xv(`review`,V(`common.loading`)):h?.kind===`unavailable`?W`<div class="callout danger review-unavailable" role="alert">
              <strong>${V(`chat.detailPanel.unavailable`)}</strong>
              <span>${h.message}</span>
            </div>`:h&&e&&g?W`${ut(t?.sidebarContent?e.panePresentation??!0:!0,e.renderDetail(h))}`:null),a(`terminal`,H.terminal,s),a(`browser`,H.globe,c),{slot:`link-reader`,label:V(`linkReader.title`),icon:H.link,available:!!e?.linkReaders?.length,content:t?W`<openclaw-link-reader-panel
            embedded
            data-chat-autotype-exempt
            .client=${t.connected?t.client:null}
            .available=${t.connected}
            .readers=${e?.linkReaders??Sn}
            .agentId=${e?.agentId??void 0}
            .sessionKey=${t.sessionKey}
            .presented=${Ge(e?.linkReaderPresented??!1)}
            .tabsInHeader=${e?.linkReaderTabsInHeader??!0}
            .onClose=${e?.onCloseLinkReader}
          ></openclaw-link-reader-panel>`:null,loading:Xv(`files`,V(`linkReader.loadingPreview`)),empty:{description:V(`linkReader.urlPlaceholder`)}},a(`portal`,H.globe,p),a(`workspace`,H.fileText,_),a(`companion`,H.messageSquarePlus,l,e?W`<openclaw-tooltip .content=${V(`chat.rail.clear`)}>
            <button
              class="rail-header__action chat-session-rail__clear"
              type="button"
              aria-label=${V(`chat.rail.clear`)}
              ?disabled=${!e.connected||e.companion.turns.some(e=>e.status===`pending`)}
              @click=${e.onClearCompanion}
            >
              ${H.trash}
            </button>
          </openclaw-tooltip>`:void 0),a(`desktop`,H.monitor,u,nT(e?.desktopFocusHref,V(`desktop.openWindow`))),a(`discussion`,H.messageSquare,d,nT(e?.discussionOpenUrl,V(`chat.sessionDiscussion.openExternal`))),a(`dashboard`,H.layoutDashboard,e?.dashboard??null),...[...v].map(([n,r])=>({slot:n,label:r?.value.label??n.slice(7),icon:H.plug,available:r!==void 0,content:r?Et(`panels`,r.key,{sessionKey:t?.sessionKey??``,agentId:e?.agentId??void 0},e?.isPluginPanelPresented(n)):null,loading:Xv(`files`,V(`common.loading`)),empty:{description:r?.value.label??V(`pluginTabs.unavailableSubtitle`)}}))]}function iT(){return(iT=e((()=>{kr(),Mn(),Fn(),Rn(),Zn(),Bv(),F(),Qh(),di(),kt(),ht(),Wx(),Es(),Ng(),ov(),vv(),Bh()})))()}function aT(e,t){let n=fT[e];if(!n)return;let[r,i]=n;if(customElements.get(r)){pT.delete(e);return}let a=pT.get(e)??{listeners:new Set};return pT.set(e,a),a.error===void 0?(a.listeners.add(t),a.pending||=on(r,i).catch(e=>{a.error=Gn({error:e,stale:_n(e),onRetry:()=>void dr()})}).finally(()=>{delete a.pending,a.listeners.forEach(e=>e()),a.listeners.clear()}),null):a.error}function oT(e){let{layout:t,state:n}=e;return{activatePanel:r=>{let i=t.columns[0]?.panels.find(e=>e.id===r)?.slot;i===`dashboard`&&!Ae(t,`dashboard`)?e.openPanelSlot(i):n.updateSidebarLayout(eg(t,r)),n.updateSidebarActivePanel(r)},togglePanelExpanded:e=>{n.updateSidebarLayout(E_(t,e),{dashboardPresentation:`personal`}),n.updateSidebarActivePanel(e)},closeSlot:t=>{if(t===`conversation`){e.setPanelOpen(!1);return}t===`discussion`&&e.forgetDiscussionUrl(),e.closePanelSlot(t)},openSlot:e.openPanelSlot,reorderPanel:(e,r,i)=>n.updateSidebarLayout(nv(t,e,r,i)),resizePanel:e.resizePanel,setOpen:e.setPanelOpen}}function sT(e){let t=`chat-panel-${encodeURIComponent(e.presentationId)}`,r=e.panelDefinitions??rT(),i=e.layout.open===!0,a=e.layout.columns.length>0?aT(`region`,e.requestUpdate):void 0;for(let t of e.layout.columns[0]?.panels??[]){let n=aT(t.slot,e.requestUpdate);n!==void 0&&(r=r.map(e=>e.slot===t.slot?{...e,content:n??e.loading}:e))}let o=e.availableWidth>0?e.availableWidth:1/0,s=e.narrow||o<680,c=n(e.layout),l=!c||c.slot===`conversation`,u=e.layout.columns[0];return W`<div
    class="sidebar-region ${s?`sidebar-region--narrow`:``} ${e.layout.expanded?`sidebar-region--expanded`:``} ${e.layout.expanded&&e.layout.expandedSide?`sidebar-region--expanded-side`:``} sidebar-region--${de(e.layout)} ${i?`sidebar-region--open`:``}"
    style=${Or({"--side-panel-width":`${u?.width??480}px`,"--side-panel-height":`${u?.height??360}px`})}
  >
    <div class="sidebar-region__header">${e.header??U}</div>
    ${a===void 0?W`<openclaw-chat-sidebar-region
            .panelIdPrefix=${t}
            .conversationTab=${e.conversationTab}
            .layout=${e.layout}
            .fetchFavicon=${e.fetchFavicon}
            .panelDefinitions=${r}
            .callbacks=${e.callbacks}
            .narrow=${e.narrow}
            .sideFocusLocked=${e.sideFocusLocked===!0}
            .sideFocusOrigin=${e.sideFocusOrigin}
            .availableWidth=${e.availableWidth}
          ></openclaw-chat-sidebar-region>`:a===null?u?.panels.filter(t=>t.slot!==`conversation`&&Ae(e.layout,t.slot)).map(t=>W`<div
                  class="side-panel__panel"
                  data-region=${t.id===e.layout.mainPanelId?`main`:`side`}
                >
                  ${r.find(e=>e.slot===t.slot)?.loading}
                </div>`):null}
    <div
      id=${`${t}-conversation`}
      class="sidebar-region__primary"
      role="region"
      aria-label=${V(`chat.sidePanel.conversation`)}
      data-region=${l?`main`:`side`}
      ?hidden=${!Ae(e.layout,`conversation`)}
    >
      ${e.primary}
    </div>
    <div class="sidebar-region__right-runtime">${a??null}</div>
  </div>`}function cT(e){let t=e.layout;return e.board.available?e.board.face===`dashboard`&&t.columns.length===0&&(t=dv(t,`dashboard`)):t=O_(t,`dashboard`),Ct(t,e.paneWidth)??t}function lT(e,t){let n=t.snapshot.hello?.auth,r=Z(e);return{owner:yr(t),sessionKey:e.sessionKey,agentId:Y(e),sessionId:r?.sessionId,displayedSessionId:e.currentSessionId??void 0,lifecycleRevision:r?.lifecycleRevision,authorizationKey:JSON.stringify([e.mediaPolicyEpoch??0,n?.role,(n?.scopes??[]).toSorted()])}}function uT(e,n){if(L(e.sessionKey)||!e.client||!e.connected)return null;let r=()=>lT(e,n);return async n=>{if(!e.client||!e.connected)return null;let i=e.client,a=e.connectionEpoch,o={...r()},s=e=>o.owner===e.owner&&o.sessionKey===e.sessionKey&&o.agentId===e.agentId&&o.sessionId===e.sessionId&&o.displayedSessionId===e.displayedSessionId&&o.lifecycleRevision===e.lifecycleRevision&&o.authorizationKey===e.authorizationKey,c=mT.get(e);(!c||!s(c))&&(c={...o,messages:new Map},mT.set(e,c));let l=n.maxChars??dT,u=n.messageId.startsWith(Lr),d=t(e,o.sessionKey,n.sessionKey,n.agentId,o.agentId),f=n.sessionId??(d&&!u&&o.displayedSessionId!==o.sessionId?o.displayedSessionId:void 0),p=!u&&d&&o.sessionId!==void 0&&o.sessionId===o.displayedSessionId&&(f===void 0||f===o.sessionId)&&o.lifecycleRevision!==void 0,m=JSON.stringify([o.sessionKey,o.agentId,n.messageId,l]),h=p?c.messages.get(m):void 0;if(h)return h;let g=await i.request(`chat.message.get`,{sessionKey:n.sessionKey,...n.agentId?{agentId:n.agentId}:{},...f?{sessionId:f}:{},messageId:n.messageId,maxChars:l});if(!e.connected||e.client!==i||e.connectionEpoch!==a||!s(r()))return null;let _=xo(g?.message);return p&&g?.ok&&_&&!xo(_.__openclaw)?.importedFrom&&(_.role!==`assistant`||_.stopReason!==`error`)&&(c.messages.size>=16&&c.messages.delete(c.messages.keys().next().value),c.messages.set(m,g)),g}}var dT,fT,pT,mT;function hT(){return(hT=e((()=>{kr(),Dr(),Yr(),Hn(),On(),Dn(),Vn(),F(),_t(),R(),iT(),Q(),vv(),ho(),dT=5e5,fT={region:[`openclaw-chat-sidebar-region`,()=>_o(()=>import(`./chat-sidebar-region.runtime-B67R083E.js`),__vite__mapDeps([21,0,1,2,3,4,10,11,22,23,24,5,6,8,7,17,18,19,25,26,27,28]),import.meta.url)],"detail-panel":[`openclaw-chat-detail-panel`,()=>_o(()=>import(`./chat-detail-panel-DYod9DCg.js`),__vite__mapDeps([29,0,1,2,3,4,10,11,22,5,6,7,8,17,18,19,25,26,27]),import.meta.url)],terminal:[`openclaw-terminal-panel`,()=>_o(()=>import(`./terminal-panel-registration-DRAlY3On.js`).then(e=>(e.t(),e.n)),__vite__mapDeps([30,0,2,1,3,4,10,11,31,32,23,33,24,34,35,5,6,7,8,17,18,19]),import.meta.url)],"link-reader":[`openclaw-link-reader-panel`,()=>_o(()=>import(`./link-reader-panel-DAzjGGyQ.js`),__vite__mapDeps([36,0,2,1,3,4,32,23,37,5,6,7,8]),import.meta.url)],browser:[`openclaw-browser-panel`,()=>_o(()=>import(`./browser-panel-s0odPIu7.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([38,0,2,1,3,4,10,11,31,32,23,39,33,24,5,6,7,8,17,18,19]),import.meta.url)],desktop:[`openclaw-desktop-panel`,()=>_o(()=>import(`./desktop-panel-CuBSlrvl.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([40,0,1,2,3,4,10,11,31,32,39,41,42,5,6,8,7,17,18,19]),import.meta.url)],portal:[`openclaw-portals-page`,()=>_o(()=>import(`./portals-page-BKvqjvya.js`),__vite__mapDeps([43,0,1,2,3,4,5,6,8,7,44]),import.meta.url)],companion:[`openclaw-chat-session-rail`,()=>_o(()=>import(`./chat-session-rail-J1mIG8Ef.js`),__vite__mapDeps([45,0,1,2,3,4,10,11,22,24,5,6,7,8,17,18,19,25,26,27,46]),import.meta.url)],processes:[`openclaw-chat-processes-panel`,()=>_o(()=>import(`./chat-processes-panel-CKKlleIX.js`),__vite__mapDeps([47,0,1,2,3,4,48,5,6,7,8,49,50]),import.meta.url)],subagents:[`openclaw-chat-subagents-panel`,()=>_o(()=>import(`./chat-subagents-panel-krANCQ7F.js`),__vite__mapDeps([51,0,2,1,3,4,10,11,48,5,6,7,8,17,18,19,49,52]),import.meta.url)],discussion:[`openclaw-session-discussion`,()=>_o(()=>import(`./session-discussion-panel-Da6iwG46.js`),__vite__mapDeps([53,0,2,1,3,4,10,11,24,5,6,7,8,17,18,19]),import.meta.url)]},pT=new Map,mT=new WeakMap})))()}function gT(e,t){return e.placementStartup.subscribe(()=>{let e=t();e&&(Km(e,km(e)?.page.items),L(e.sessionKey)||qp(e),e.requestUpdate?.())})}function _T(e){return c(({sessionKey:t,scopePrefix:n,reason:r})=>{let i=e();r===`cache-eviction`||!i||n&&!qe(i,{sessionKey:i.sessionKey}).startsWith(n)||t&&qe(i,{sessionKey:i.sessionKey})!==t||(If(i),i.requestUpdate?.())})}function vT(){return(vT=e((()=>{_t(),af(),th(),Oc(),Cu(),Gs(),Rt()})))()}function yT(e,t){Pv(e),rg(e,t)}function bT(){return(bT=e((()=>{Cg(),lg()})))()}var xT;function ST(){return(ST=e((()=>{Vr(),bn(),Cn(),Fn(),Mo(),$v(),oe(),_t(),Ue(),R(),ym(),d(),af(),Dx(),Ix(),zx(),Vx(),Wx(),Zx(),Qw(),tT(),pp(),hT(),vT(),th(),Vf(),Yw(),tC(),pw(),bT(),xy(),Es(),B_(),ov(),pc(),lc(),Cu(),Yc(),Gs(),vv(),xT=class extends Zw{constructor(...e){super(...e),this.sessionPanelToggles=new eT({current:()=>{let e=this.state;return e&&this.active&&this.presented?{renderRoot:this.renderRoot,state:e,linkReaders:ln(this.context.gateway.snapshot),pluginPanels:this.context.plugins.registrations(`panels`).map(e=>e.key),updateComplete:this.updateComplete}:null},pending:this.pendingPanelToggleRequests,requestUpdate:()=>this.requestUpdate(),updateSidebarLayout:e=>this.commitSidebarLayout(e)}),this.mcpApps=new Bx({element:this,current:()=>{let e=this.state;return e?{context:this.context,state:e,presented:this.presented,agentId:this.agentId,launch:this.mcpAppLaunch,openFile:t=>Q_(e,{path:t})}:null}}),this.chatRouteReadyReported=!1,this.stagedAttachmentGatewayOwner=null,this.suppressStagedAttachmentHandoffOnDisconnect=!1,this.handlePaneInput=()=>{this.sessionCompanionFocusGeneration+=1},this.handlePaneFocus=()=>{this.sessionCompanionFocusGeneration+=1,Xn(this.context).claim(this.inputRegion),this.onFocusPane?.(this.paneId)},this.handleDocumentKeydown=e=>{let t=this.state;if(!t||!this.active||!this.presented||e.defaultPrevented||document.querySelector(`.shell-nav[aria-modal='true']`)||this.handleArchiveSessionShortcut(e))return;let n=Object.values(Ux).find(t=>t&&lt(t.combo,e)),r=this.sessionDiscussionStates.get(t.sessionKey.trim());if(n?.available({state:t,desktopAvailable:nr(this.context.gateway.snapshot),discussion:t.connected&&t.client?!0:null,discussionAvailable:r===`available`||r===`open`,dashboardAvailable:()=>!this.compact&&this.isBoardPanelAvailable()})){e.preventDefault();let{slot:r}=n,i=this.isSlotShown(t.sidebarLayout,r);i&&Yx(t,r),this.commitSidebarLayout(i?O_(t.sidebarLayout,r):Jx(t,t.sidebarLayout,r));return}Ip(this,e),!(e.defaultPrevented||e.isComposing||e.keyCode===229||e.key!==`Escape`)&&$d(this)&&e.preventDefault()},this.handleDocumentPointerdown=e=>{this.state&&$d(this,e.composedPath())&&this.state.requestUpdate()}}activateComposerPresentation(){this.selected&&this.presented&&this.composerPresentation?.claim()}discardStagedAttachments(){this.suppressStagedAttachmentHandoffOnDisconnect=!0,this.chatState.attachmentReads.abortReads(),jx(this.state)}resumeStagedAttachments(){this.suppressStagedAttachmentHandoffOnDisconnect=!1}replaceStagedAttachmentGatewayOwner(e){this.stagedAttachmentGatewayOwner=Mx(this.context,this.paneId,this.state,this.stagedAttachmentGatewayOwner,e)}syncActiveBindings(){if(this.nativeDraftCleanup?.(),this.nativeDraftCleanup=null,!this.state||!this.active||!this.presented){this.sessionCompanionFocusGeneration+=1,this.announceCommandPaletteTarget(null);return}this.announceCommandPaletteTarget(this.handleCommandPaletteSlashCommand),this.nativeDraftCleanup=this.context.nativeChatDrafts.subscribe(e=>{let t=this.state;t&&this.active&&this.presented&&(t.handleChatDraftChange(e,[]),t.requestUpdate?.())})}receiveBrowserAnnotation(e){Rx(this.state,this.active&&this.presented,e,this.chatState.attachmentReads.pendingBytes(sf(this.state?.hello?.policy)))&&(this.stagedAttachmentGatewayOwner??=this.context.gateway.snapshot.client,Lx(this))}connectedCallback(){this.boardProviderLifecycleConnected=!0,this.resumeStagedAttachments(),super.connectedCallback(),this.presented||this.minutePoll.stop();let e=this.context.gateway.snapshot.client;this.stagedAttachmentGatewayOwner=e,this.requestUpdate(),typeof ResizeObserver==`function`&&(this.paneResizeObserver=new ResizeObserver(e=>{let t=e.at(-1)?.contentRect.width;typeof t==`number`&&t>0&&t!==this.paneWidth&&(this.transcript.syncViewportGeometry(),this.paneWidth=t)}),this.paneResizeObserver.observe(this)),this.addEventListener(`pointerdown`,this.handlePaneFocus),this.addEventListener(`focusin`,this.handlePaneFocus),this.addEventListener(`input`,this.handlePaneInput),document.addEventListener(`keydown`,this.handleDocumentKeydown,!0),document.addEventListener(`pointerdown`,this.handleDocumentPointerdown,!0);let t=this.chatState;t.addCleanup(()=>_y(this.context,this)),t.addCleanup(()=>{document.removeEventListener(`keydown`,this.handleDocumentKeydown,!0),document.removeEventListener(`pointerdown`,this.handleDocumentPointerdown,!0),this.removeEventListener(`pointerdown`,this.handlePaneFocus),this.removeEventListener(`focusin`,this.handlePaneFocus),this.removeEventListener(`input`,this.handlePaneInput)});let n=eC(this.context,t.createRenderLifecycle(),this,this.chatMessagesBySession);n.chatMetadataIsPresented=()=>this.presented&&document.visibilityState!==`hidden`;let r=()=>{this.requestUpdate(),n.chatMetadataIsPresented?.()&&(nw(n,{automatic:!0}),this.resumeDeferredSessionHydration(),this.refreshTaskSuggestions({automatic:!0}))};document.addEventListener(`visibilitychange`,r),t.addCleanup(()=>document.removeEventListener(`visibilitychange`,r));let i=Bt(this.sessionKey)?.agentId??this.agentId;if(i&&(n.assistantAgentId=i,n.agentsSelectedId=i),n.sidebarLayout=this.restorePaneSidebarLayout(n.sidebarLayout),n.getWorkContext=()=>this.workContext,n.chatIsProgrammaticScroll=()=>this.transcript.isProgrammaticScroll,n.chatIsMaintenanceScroll=()=>this.transcript.isMaintenanceScroll,n.chatScrollElement=()=>this.transcript.scrollElement,n.chatScrollToEnd=e=>this.transcript.scrollToEnd(e),n.chatCancelScroll=()=>this.transcript.cancelScroll(),n.reviewQueuedMessageEdit=()=>this.reviewQueuedMessageEdit(n),n.createChatSession=()=>this.createSession(),n.confirmConversationReset=()=>this.confirmConversationReset(),n.exportCurrentChat=()=>Su(n.chatMessages,n.assistantName),n.refreshCurrentSessionTools=async()=>{n.requestUpdate?.()},n.refreshCurrentChat=async()=>{await dw(n),n.requestUpdate?.()},n.refreshSessionPullRequests=e=>this.refreshSessionPullRequests(e),n.openSessionCompanion=e=>this.openSessionCompanion(n,e),n.retireSessionCompanion=(e,t)=>this.sessionCompanionThreads.retire(e,t),this.state=n,this.sessionKey){let e=this.setPaneSessionKey(this.sessionKey);if(e&&!L(e)){n.client=this.context.gateway.snapshot.client??null;let t=Pu(n.chatMessagesBySession,n,{sessionKey:e});t?vl(n,t):this.hydrateStoredChatSnapshot(n,e),Wp(n,e)&&(n.lastError=Hm,n.chatError=Hm),Km(n,km(n)?.page.items)}}t.attach(n),t.addCleanup(()=>this.retireSessionObservation()),t.addCleanup(ld(()=>{Wp(n,n.sessionKey)&&(n.lastError=Hm,n.chatError=Hm),n.requestUpdate?.()})),t.addCleanup(this.context.agentIdentity.subscribe(()=>void n.loadAssistantIdentity())),t.composerPersistence.restore({preserveCurrent:!0});let a=this.takeSessionHandoff(n.sessionKey);kx(this.context,this.paneId,n,e),t.composerPersistence.start(),a&&this.applySessionHandoff(n.sessionKey,a),this.draft!==void 0&&this.state.handleChatDraftChange(this.draft,[]);let o=e=>this.receiveBrowserAnnotation(e);window.addEventListener(Hv,o),t.addCleanup(()=>window.removeEventListener(Hv,o)),t.addCleanup(this.sessionPanelToggles.subscribe()),t.addCleanup(this.mcpApps.subscribe()),t.addCleanup(this.context.gateway.subscribe(e=>{this.applyGatewaySnapshot(e),this.activateComposerPresentation(),this.synchronizeForegroundTranscript()})),t.addCleanup(this.context.theme.subscribe(()=>{n.settings={...this.context.theme.settings,token:this.context.gateway.connection.token},n.requestUpdate()})),t.addCleanup(this.context.agentSelection.subscribe(e=>{let t=this.state?.assistantAgentId;$C(this.state,this.agentId??e.selectedId),this.synchronizeSessionObservation();let n=this.state?.assistantAgentId!==t;n&&(this.swarmHydrator?.dispose(),this.swarmHydrator=null),this.synchronizeForegroundTranscript(),n&&this.refreshSwarmRoster(),this.state&&Cx(this.state),this.activateComposerPresentation()})),this.subscribeSessionRepositoryContext(),t.addCleanup(this.context.gateway.subscribeEvents(e=>{let t=this.state;if(t&&e.event===`sessions.changed`&&ao(e.payload).reason===`sharing`&&(t.mediaPolicyEpoch=(t.mediaPolicyEpoch??0)+1,t.requestUpdate?.()),e.event!==`sessions.changed`&&e.event!==`session.message`){if(e.event===`presence`){let t=this.hasMultipleIdentities(),n=an(e.payload);this.presencePayload=n?{presence:n}:void 0,this.pruneTypingActors(),this.hasMultipleIdentities()?t||this.refreshSessionSuggestions():(this.resetSessionSuggestions(),this.clearTypingActors())}t&&(e.event===`config.changed`&&(t.mediaPolicyEpoch=(t.mediaPolicyEpoch??0)+1,t.requestUpdate?.(),Xd(t),ff(t).finally(()=>t.requestUpdate?.())),Xo(this.questionPromptState,e)),t&&!L(t.sessionKey)&&(e.event===`task.suggestion`&&e.payload&&this.handleTaskSuggestionEvent(e.payload),e.event===`session.suggestion`&&e.payload&&this.handleSessionSuggestionEvent(e.payload),e.event===`session.reaction`&&Hr(e.payload)&&this.handleSessionReactionEvent(e.payload),e.event===`session.typing`&&e.payload&&this.handleSessionTypingEvent(e.payload),Uw(t,e,()=>this.presented),e.event===`node.runnerInventory.changed`&&(this.activeSessionResources.invalidate(),this.requestUpdate()))}})),this.applyApplicationConfig(this.context.config.current),t.addCleanup(this.context.config.subscribe(this.applyApplicationConfig.bind(this))),this.applySessionsState(this.context.sessions.state),t.addCleanup(this.context.sessions.subscribe(this.applySessionsState.bind(this))),t.addCleanup(gT(this.context,()=>this.state)),t.addCleanup(_T(()=>this.state)),this.applyGatewaySnapshot(this.context.gateway.snapshot),this.synchronizeForegroundTranscript();let s=new Fx(this.context,{state:()=>this.state,owner:()=>this.stagedAttachmentGatewayOwner,presentationOwner:()=>this.chatState.composerPersistence.presentationOwner,region:()=>this.inputRegion,presented:()=>this.selected&&this.presented,pause:()=>this.chatState.composerPersistence.stop(),takeAttachmentReads:()=>this.chatState.takeAttachmentReads(),adoptAttachmentReads:e=>this.chatState.adoptAttachmentReads(e,n),resume:e=>{e&&this.chatState.composerPersistence.restore(),this.chatState.composerPersistence.start()}});this.composerPresentation=s,n.captureComposerRecoveryOwner=()=>s.captureOwner(),this.activateComposerPresentation()}willUpdate(e){if(this.captureArchivePresentationFocus(),e.has(`sessionKey`)&&this.state){let e=L(this.sessionKey),t=e?this.sessionKey:be(this.sessionKey,this.context.gateway.snapshot.hello);if(t&&this.sessionDiscussionStates.delete(t),e&&this.catalogRequestedSessionKey!==this.sessionKey)this.catalogLoadGeneration+=1,this.openCatalogSession(e,this.state);else if(t){this.state.sessionKey=t;let e=Bt(t)?.agentId;e&&ew(this.state,e),this.synchronizeSessionObservation();let n=Wp(this.state,t),r=Km(this.state,km(this.state)?.page.items);n&&(this.state.lastError=Hm,this.state.chatError=Hm),(n||r)&&this.requestUpdate()}if(t){let e=this.takeSessionHandoff(t);e&&this.applySessionHandoff(t,e)}}(e.has(`sessionKey`)||e.has(`inputRegion`))&&(this.syncActiveBindings(),this.activateComposerPresentation()),e.has(`draft`)&&this.draft!==void 0&&this.state&&this.draft!==this.state.chatMessage&&this.state.handleChatDraftChange(this.draft,[]),this.syncSessionReactions(),this.syncRetainedBoardSession(this.resolveBoardView())}updated(e=new Map){if(this.mcpApps.syncLaunch(),Pp(this.state),!this.chatRouteReadyReported&&this.querySelector(`.agent-chat__composer-combobox > textarea`)&&(this.chatRouteReadyReported=!0,this.dispatchEvent(new Event(M,{bubbles:!0,composed:!0}))),e.has(`focusComposer`)&&this.focusComposer){let e=this.querySelector(pm),t=e?.closest(`.agent-chat__input`);e?.focus({preventScroll:!0}),t&&this.draft&&this.showComposerPrefillAttention(t)}if(this.retireArchivedPresentation(),this.cancelResetConfirmationForSessionChange(),this.syncHistoryObserver(),this.sessionPanelToggles.flush(),this.activeSessionResources.syncPane({state:()=>this.state,observation:()=>this.resourceSessionObservation(),gateway:this.context.gateway.snapshot,isConnected:()=>this.isConnected,isPresented:()=>this.presented&&this.visuallyPresented,commit:(e,t)=>this.commitSidebarLayout(e,{persist:!1,automaticResource:t}),requestUpdate:()=>this.requestUpdate()}),this.state){let e=this.initializeBrowserSidebarLayout(this.state.sidebarLayout);e!==this.state.sidebarLayout&&this.state.updateSidebarLayout(e,{geometryOnly:!0})}this.setConversationVisible(!!(this.state&&this.isSlotShown(cT({board:this.resolveBoardView(),layout:this.state.sidebarLayout,paneWidth:this.paneWidth}),`conversation`)))}disconnectedCallback(){this.activeSessionResources.sync(null),this.syncSessionCompanionPresentation(!1),this.composerPresentation?.dispose(),this.composerPresentation=void 0,this.state&&(em(this.state),Ad(this.state),Xd(this.state),XC(this.state),this.suppressStagedAttachmentHandoffOnDisconnect?jx(this.state):Ax(this.context,this.paneId,this.state,this.stagedAttachmentGatewayOwner,this.chatState.composerPersistence.draftRevision,this.chatState.composerPersistence.presentationOwner)),this.stagedAttachmentGatewayOwner=null,this.clearComposerPrefillAttention(),this.boardProviderLifecycleConnected=!1,this.releaseBoardProviderLease(),this.settleResetConfirmation(!1),this.paneResizeObserver?.disconnect(),this.paneResizeObserver=null,this.connectionGeneration+=1,this.retireReplyMessages(),this.retireHeaderSessionMutations(),this.retireDeferredSessionHydration(),this.sessionDiscussionPanels.clear(),this.taskSuggestionsRequestVersion+=1,this.setTaskSuggestions([]),this.taskSuggestionBusyIds.clear(),this.taskSuggestionOperations.clear(),this.resetSessionSuggestions(),this.resetSessionReactions(),this.clearTypingActors(),this.resetSessionPullRequests(),this.resetOlderMessagesViewport(),this.nativeDraftCleanup?.(),this.nativeDraftCleanup=null,this.headerCopiedTimer!==null&&(window.clearTimeout(this.headerCopiedTimer),this.headerCopiedTimer=null),this.swarmHydrator?.dispose(),this.swarmHydrator=null,this.headerWorktreePaths.clear(),this.headerBranches.clear(),this.presencePayload=void 0,this.announceCommandPaletteTarget(null),fv(this),yT(this.presentationId),this.state=void 0,this.connectedClient=null,_s(this.questionPromptState),super.disconnectedCallback()}}})))()}function CT(e,t,n,r){let i=e.sessionsResult,a=i?.sessions??[],o=new Set([...e.chatSessionApprovalQueue??[],...r??[]].map(e=>e.sourceSessionKey).filter(e=>typeof e==`string`));return JSON.stringify([e.sessionKey,Y(e),e.connectionEpoch,e.sessionsResultAgentId,e.sessionsLoading,e.sessionsError,n,w_(n,a),i?.defaults,i?.owners,t.modelOverrides[e.sessionKey],Object.hasOwn(t.modelOverrides,e.sessionKey),e.sessions.think(e.sessionKey,D(e,e.sessionKey).agentId),e.sessions.archiveVisibility(n?.key??e.sessionKey),mp(t.groups,t.result?.sessions??[]),t.groupSettings,[...o].map(e=>a.find(t=>z(t.key,e))),e.chatMessages.length===0?a:void 0])}function wT(){return(wT=e((()=>{Td(),y(),R(),Q(),V_()})))()}var TT;function ET(){return(ET=e((()=>{Mn(),Tr(),Fn(),Mo(),Jn(),g(),di(),ft(),_t(),Ue(),R(),j(),ym(),af(),Dx(),rh(),ST(),lS(),wT(),NS(),YC(),RS(),Oc(),Vf(),pw(),Q(),ol(),ov(),gc(),Hs(),Gs(),Eg(),vv(),dh(),Gl(),ho(),TT=class extends xT{constructor(){super(),this.outboxRecoveryReady=!1,this.gatewayReadsAvailable=!1,this.questionProjection={prompts:[],revisions:[]},new S(this).effect(()=>this.context?.gateway,e=>e.subscribeEvents(e=>{let t=this.state;t&&Je(e)&&(t.modelAuthStatusResult=null,t.modelAuthStatusError=null,this.requestUpdate(),iw(t).finally(()=>this.requestUpdate()))}))}placementComposerPresentation(e,t){return iS({gatewaySnapshot:this.context.gateway.snapshot,movingKey:this.headerPlacementMovingKey,reclaimingKey:this.headerPlacementReclaimingKey,restartingKey:this.headerPlacementRestartingKey,row:e,startupPending:t,workspaceResultReconciling:(e?.placement?.state===`active`||e?.placement?.state===`draining`)&&e.placement.workspaceResultReconciling===!0,onRecover:()=>e&&void this.changeHeaderPlacement(e,`recover`),onReclaim:()=>e&&void this.changeHeaderPlacement(e,`reclaim`)})}disconnectedCallback(){this.sessionPresentationKey=void 0,this.continueInTerminalDialog=null,this.gatewayConnectionLifecycle?.dispose(),this.gatewayConnectionLifecycle=void 0,this.outboxRecoveryReady=!1,super.disconnectedCallback()}async changeHeaderPlacement(e,t){let n=this.captureConnectionScope();if(!n)return;let r={move:`headerPlacementMovingKey`,recover:`headerPlacementRestartingKey`,reclaim:`headerPlacementReclaimingKey`}[t],i=this[r],a=n.context.placementStartup,o=n=>{t===`recover`&&n!==null&&this.state&&(OS(this.state),this.state.chatRunError=null),(n!==null||this[r]===e.key)&&(this[r]=n)},s={client:n.client,gatewaySnapshot:n.context.gateway.snapshot,row:e,isCurrent:()=>this.ownsHeaderOutcomeScope(n),publishError:e=>this.publishHeaderError(e,n.headerOutcomeOwner),reconcileMutation:e=>n.sessions.reconcileMutation(e),requestUpdate:()=>this.requestUpdate()},c=await _o(()=>import(`./chat-pane-placement.runtime-CoEpFcJk.js`),__vite__mapDeps([54,0,1,2,3,4,10,22,55,5,6,7,8,17,25,26]),import.meta.url);t===`reclaim`?await c.reclaimChatPanePlacement({...s,reclaimingKey:i,placementStartup:a,onReclaimingChange:o}):await c.changeChatPanePlacement({...s,mode:t,pendingKey:i,currentRow:()=>this.state?Z(this.state):void 0,onPendingChange:o})}applySessionsState(e){let t=this.state;if(!t)return;let n=this.context.sessions.canonicalListRevision,r=this.canonicalSessionList,i=r?.sessions===this.context.sessions&&n>r.revision,a=this.context.sessions.deletionState(t.sessionKey,Y(t));for(let{key:n,agentId:r}of e.deletedSessions)hh(t.chatMessagesBySession,t,{sessionKey:n,agentId:r});(!C(t,t.sessionKey)||e.agentId===Y(t))&&(t.sessionsResult=e.result,t.sessionsResultAgentId=e.agentId),this.projectObservedSessionRow(),t.sessionsLoading=e.loading,t.sessionsError=e.error,t.connected&&t.pendingAbort&&kc(t).finally(()=>t.requestUpdate?.()),this.refreshSwarmRoster();let o=Z(t),s=o?JSON.stringify([t.sessionKey,Y(t),o.sessionId,o.status,go(o),o.lastRunId,o.activeLeafEntryId]):void 0;if(this.canonicalSessionList={sessions:this.context.sessions,revision:n,outboxState:i?s:r?.sessions===this.context.sessions?r.outboxState:void 0},DS(t,o)&&this.presented&&this.markSessionRead(o),this.syncSessionSuggestionTarget(e.agentId??Y(t)??`main`,o),a){let e=Y(t);this.onSessionDeleted?.(this.paneId,t.sessionKey,vo({agentId:e,mainKey:ye({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello})}),a===`pending`);return}let c=iu(t);if(this.reconcileWaitingApprovalSnapshot(),c){qp(t);return}let l=CT(t,e,o,this.context.overlays?.snapshot?.approvalQueue),u=l!==this.sessionPresentationKey;this.sessionPresentationKey=l,this.presented&&u&&rC(t,`animation-frame`),i&&r?.outboxState!==s&&o&&!go(o)&&t.chatQueue.length>0&&Ju(t)}reconcileWaitingApprovalSnapshot(e){let t=this.state,n=e??this.context?.overlays?.snapshot.approvalQueue;return!t||!n?!1:yc(t,n)}projectConversationAttention(e,n,r){let i=r=>t(e,e.sessionKey,r.sessionKey,r.agentId,n),a=r?this.questionPrompts.filter(i):[];return(a.length!==this.questionProjection.prompts.length||a.some((e,t)=>e!==this.questionProjection.prompts[t]||e.revision!==this.questionProjection.revisions[t]))&&(this.questionProjection={prompts:a,revisions:a.map(e=>e.revision)}),{gatewayQuestionPrompts:this.questionProjection.prompts,inlineApproval:r?e.chatSessionApprovalQueue?.[0]??this.context.overlays?.snapshot?.approvalQueue?.find(e=>i(e.request))??null:null}}applyApplicationConfig(e){let t=this.state;if(!t)return;t.requestUpdate?.();let n=t.terminalAvailable;t.terminalAvailable=e.terminalEnabled&&t.connected&&Er(t.hello?.auth??null)&&K(this.context.gateway.snapshot,`terminal.open`)===!0,(t.terminalAvailable!==n||t.embedSandboxMode!==e.embedSandboxMode||t.allowExternalEmbedUrls!==e.allowExternalEmbedUrls||t.automaticallyFetchFavicons!==e.automaticallyFetchFavicons)&&(t.embedSandboxMode=e.embedSandboxMode,t.allowExternalEmbedUrls=e.allowExternalEmbedUrls,t.automaticallyFetchFavicons=e.automaticallyFetchFavicons,t.requestUpdate?.())}applyGatewaySnapshot(e){let t=this.state;if(!t)return;let n=Un(t),r=k(e),i=r&&!this.gatewayReadsAvailable;this.gatewayReadsAvailable=r;let o=t.connected,s=t.assistantAgentId,c=Bt(t.sessionKey)?.agentId??this.agentId??this.context.agentSelection.state.selectedId??e.assistantAgentId,l=a(t,t.sessionKey),u=(this.gatewayConnectionLifecycle??=Xe({client:t.client,phase:t.connected?`connected`:`stopped`})).transition(e),d=this.connectedClient!==e.client,f=this.sidebarLayoutSource?e.client!==null&&this.sidebarLayoutSource.client!==e.client:t.client!==e.client,p=!this.sidebarLayoutSource||f||e.phase===`connected`&&!this.sidebarLayoutSource.ready;if(d&&this.replaceStagedAttachmentGatewayOwner(e.client),e.phase!==`connected`)this.presencePayload=void 0;else if(d||!o){let t=an(e.hello?.snapshot);this.presencePayload=t?{presence:t}:void 0}u&&(this.resetSessionReadAcknowledgements(),this.continueInTerminalDialog=null,this.cancelHeaderRename(),bc(t),Zc(t.requestUpdate),o&&(e.phase===`connected`&&WC(t),t.chatSending=!1,t.chatSendingScopeKey=null),this.connectionGeneration+=1,this.retireReplyMessages(),this.retireHeaderSessionMutations(),Xd(t),t.assistantIdentityRequestVersion+=1,XC(t),this.taskSuggestionsRequestVersion+=1,this.resetSessionSuggestions(),this.resetSessionReactions(),this.clearTypingActors(),this.sessionDiscussionStates.clear(),this.sessionDiscussionOpenUrls.clear(),this.sessionDiscussionPanels.clear(),this.sessionParticipationTracker.reset(),t.client!==e.client&&(this.sessionCompanionThreads.retire(),Fu(t,{clearLocalRun:!0,clearChatStream:!0,clearToolStream:!0,clearRunStatus:!0,requestUpdate:!1}),t.pendingAbort=null),this.sessionSharingStates=new Map,this.sessionSharingHydrationTargets.clear(),t.guardianNotices=[],t.providerPolicyNotice=null,this.resetSessionPullRequests(),this.resetOlderMessagesViewport(),t.chatLoading=!1),(u||s!==c&&C(t,t.sessionKey))&&(om(t),this.swarmHydrator?.dispose(),this.swarmHydrator=null),t.client=e.client,t.connected=e.phase===`connected`,ip(t);let m=t.connected&&!!t.client?.recoveryScopeReady,h=m&&(d||!this.outboxRecoveryReady);this.outboxRecoveryReady=m,t.connectionEpoch=this.connectionGeneration,t.hello=e.hello,t.selfUser=e.selfUser??null,t.assistantAgentId=c;let g=this.sessionKey.trim(),_=L(g);t.connected&&!_&&(u||this.connectedClient!==e.client)&&Cx(t,{force:!0}),this.reconcileTaskSuggestionConnection(u),this.synchronizeSessionObservation(),i&&!u&&this.presented&&this.markSessionRead(Z(t)),o&&!t.connected&&(t.chatLoading=ks(t).phase===`pending-connection`);let v=!o&&t.connected?Jm(t):void 0;u&&Vg(t),!u&&n!==Un(t)&&Zc(t.requestUpdate),t.canvasPluginSurfaceUrl=e.canvasPluginSurfaceUrl,t.terminalAvailable=this.context.config.current.terminalEnabled&&e.phase===`connected`&&Er(e.hello?.auth??null)&&K(e,`terminal.open`)===!0,t.browserPanelAvailable=Bn(e);let y=nr(e),b=a(t,t.sessionKey),x=b!==l;if(b&&(p||x)){this.sidebarLayoutSource={client:e.client,ready:t.connected},this.dashboardPresentationActivation=void 0;let n=cv({settings:Nn(),sessionKey:b,browserAvailable:t.browserPanelAvailable,desktopAvailable:y}),r=n.sidebarSessionLayouts?.[b];r===void 0?f?t.sidebarLayout={columns:[]}:x&&t.sidebarLayout.columns.length>0&&t.updateSidebarLayout(t.sidebarLayout):t.sidebarLayout=this.restorePaneSidebarLayout(De(r)),t.sidebarFocusPanelId=n.sidebarSessionActivePanels?.[b]??``,t.sidebarFocusVersion+=1}t.connected&&t.pendingAbort&&kc(t).finally(()=>t.requestUpdate?.());let S=g&&!_?be(g,e.hello):null;if(!(g&&S&&S!==g&&this.presented&&(this.onPaneSessionChange?.(this.paneId,S,{replace:!0}),t.requestUpdate?.(),t.sessionKey!==S))){if(u&&(t.assistantName=this.context.config.current.assistantIdentity.name),e.phase!==`connected`){if(o){let e=typeof t.currentSessionId==`string`?t.currentSessionId.trim():``;e&&(t.reconnectResumeSessionId=e),WC(t)}this.connectedClient=null,us(this.questionPromptState,null),FS(t),Bs(t,{preserveStreamSegments:t.chatRunId!==null}),t.requestUpdate?.();return}if(this.refreshSwarmRoster(),(this.connectedClient!==e.client||u&&_)&&e.client){let n=e.client,r=this.connectionGeneration,i=t.sessionKey,a=()=>this.connectionGeneration===r&&this.connectedClient===n&&t.client===n&&t.connected,o=async()=>{if(!a())return;let e=await this.context.agents.ensureList();a()&&(e&&jm(t,e,n),t.requestUpdate?.())};if(this.connectedClient=n,us(this.questionPromptState,n),Go(this.questionPromptState,n,a),this.headerWorktreePaths.clear(),this.headerBranches.clear(),this.headerPlatform=null,_){this.loadHeaderPlatform(n,r),this.loadCatalogSession(_,!1),t.requestUpdate?.();return}let s=dw(t,{startup:!0,awaitHistory:!0,deferBranches:!0,historyLoad:v});this.deferSessionHydrationUntilTranscript(i,s.then(()=>ks(t).phase===`committed`)),s.finally(()=>{o()}),iw(t).finally(()=>t.requestUpdate?.()),t.loadAssistantIdentity(),this.refreshSessionSuggestions()}h&&!_&&qp(t),this.reconcileWaitingApprovalSnapshot(),t.requestUpdate?.()}}}})))()}var DT;function OT(){return(OT=e((()=>{DT=class{read(e,t){return(!this.inputs||e.length!==this.inputs.length||e.some((e,t)=>!Object.is(e,this.inputs[t])))&&(this.value=t(),this.inputs=e),this.value}}})))()}var kT;function AT(){return(AT=e((()=>{nn(),Ro(),cs(),rs(),F(),Fe(),zi(),zt(),oe(),gt(),Ce(),md(),Td(),R(),Ks(),dp(),Be(),nm(),ET(),OT(),Q(),hg(),ho(),kT=class extends TT{constructor(...e){super(...e),this.headerSessionDataMemo=new DT,this.handleArchiveSessionShortcut=e=>{if(!lt(_e.archiveSession,e))return!1;let t=this.state;if(e.repeat||e.defaultPrevented||!t?.connected||!this.active||!this.presented||this.onboarding||document.openClawModalLayers?.size||document.querySelector(`.shell-nav[aria-modal='true']`))return!0;let n=Z(t);return!n||!this.canArchiveHeaderSession(n)||(e.preventDefault(),this.handleHeaderSessionAction({kind:`toggle-archived`},n),!0)},this.headerSessionOperationsLoad=null}resolveHeaderSessionTitle(e){return this.presentationTitle??He(e?.key??this.state?.sessionKey??this.sessionKey,e)}canArchiveHeaderSession(e){return!e.archived&&!this.context.sessions.archiveVisibility(e.key)&&ge(e,ye({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}))&&!ts({snapshot:this.context.gateway.snapshot,session:e})[`toggle-archived`]}headerSessionMenuData(e,t){let n=I({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello},`main`,Bt(e.key)?.agentId??e.agentId).sessionKey,r=this.resolveHeaderSessionTitle(e),i=!!hs(e,new Set([n])),a=this.context.sessions.archiveVisibility(e.key)===`pending`;return this.headerSessionDataMemo.read([r,e.sessionId,i,e.pinned,t,e.snoozedUntil,e.unread,e.hiddenFromInvolvingMe,e.archived,a,e.category,e.icon,e.color],()=>({label:r,sessionId:e.sessionId??null,isChild:i,pinned:e.pinned===!0,pinnable:t,snoozedUntil:e.snoozedUntil??null,unread:e.unread===!0,hiddenFromInvolvingMe:e.hiddenFromInvolvingMe,archived:e.archived===!0,archiving:a,category:qa(e.category)??null,icon:qa(e.icon)??null,color:qa(e.color)??null,categoryClearReturnsToGroups:!1}))}async loadHeaderPlatform(e,t){let n=this.context.gateway,r=await Of(n).then(e=>e.value.platform).catch(()=>null);this.context.gateway===n&&this.connectedClient===e&&this.connectionGeneration===t&&(this.headerPlatform=r)}async handleHeaderSessionAction(e,t){if(e.kind===`stop-cloud-worker`)return this.changeHeaderPlacement(t,`reclaim`);if(e.kind===`toggle-archived`&&!t.archived&&!this.canArchiveHeaderSession(t))return;if(e.kind===`open-in`){Ui(e.editor,e.path);return}if(e.kind===`rename`){this.beginHeaderRename(t);return}if(e.kind===`copy-session-id`||e.kind===`copy-session-link`||e.kind===`copy-session-preview-link`||e.kind===`copy-markdown`||e.kind===`open-new-tab`||e.kind===`open-new-window`||e.kind===`split-right`||e.kind===`split-below`){let n=this.headerOutcomeOwner;await Im(e.kind,{context:this.context,session:t,agentId:this.state?Y(this.state):t.agentId,sourceSessionKey:t.key,isCurrent:()=>this.ownsHeaderOutcome(n)});return}if(e.kind===`continue-in-terminal`){this.openContinueInTerminalDialog(t);return}let n=this.captureHeaderSessionActionScope();if(!n){this.publishHeaderError(V(`sessionsView.actionRequiresConnection`));return}let r=this.headerOutcomeOwner;if(e.kind===`plugin`){let i=this.state?Z(this.state):void 0;try{await np({runtime:this.context.plugins,id:e.id,placement:`session`,sessionKey:t.key,agentId:t.agentId,session:i?.key===t.key&&i.sessionId===t.sessionId?i:void 0,signal:n.signal})}catch(e){this.publishHeaderError(e,r)}return}let i=e=>({key:e.key,sessionId:e.sessionId,sharingRole:e.sharingRole,label:this.resolveHeaderSessionTitle(e),pinned:e.pinned===!0,unread:e.unread===!0,archived:e.archived===!0,category:e.category,active:!0,hasActiveRun:e.hasActiveRun??e.status===`running`,gatewayHasActiveRun:e.hasActiveRun}),a=i(t),o=(e=!1)=>{let r=n.sessions.state.result?.sessions.find(e=>z(e.key,t.key)&&(!a.sessionId||e.sessionId===a.sessionId))??(a.sessionId?t:null);return!r&&e&&Lt({message:V(`common.refresh`)}),r?i(r):null};try{let i=await(this.headerSessionOperationsLoad??=_o(()=>import(`./session-organizer-operations.runtime-SirMtAXt.js`),__vite__mapDeps([56,0,1,2,3,4,57,10,22,58,55,5,6,7,8,17,25,26]),import.meta.url)),s={sessionData:{isSessionMutationScopeCurrent:e=>this.isHeaderSessionActionCurrent(e,r),publishSessionMutationError:(e,t)=>{this.isHeaderSessionActionCurrent(e,r)&&this.publishHeaderError(t,r)},refreshSidebarSessions:async e=>{let t=await n.sessions.reconcileMutation(e);t.status===`failed`&&this.isHeaderSessionActionCurrent(n,r)&&this.publishHeaderError(t.error,r)}},pruneSidebarSessionEntry:e=>{let t=vn({type:`session`,key:e}),r=n.context.navigation.snapshot.sidebarEntries.filter(e=>e!==t);n.context.navigation.update({sidebarEntries:r})},selectSession:e=>this.onPaneSessionChange?.(this.paneId,e),sidebarSessionStatusFilter:()=>`active`,knownSessionGroups:()=>mp(n.sessions.state.groups,n.sessions.state.result?.sessions??[])},c=e=>i.assignSessionCategory(s,a,e,n,{},{resolveSession:o});switch(e.kind){case`toggle-involving-me`:await i.setSessionInvolvement(s,a,!t.hiddenFromInvolvingMe,n);break;case`toggle-pin`:case`toggle-unread`:case`set-icon`:case`set-color`:case`reset-appearance`:{let t=o(!0);if(t){let r=e.kind===`toggle-pin`?{pinned:!t.pinned}:e.kind===`toggle-unread`?{unread:!t.unread}:e.kind===`set-icon`?{icon:e.icon}:e.kind===`set-color`?{color:e.color}:{icon:null,color:null};await i.patchSession(s,t,r,n,e.kind===`toggle-pin`?{sessionScope:!0}:void 0)}break}case`assign-owner`:await i.assignSessionOwner(s,a,e.owner,n);break;case`fork`:await i.forkSession(s,a,n);break;case`move-to-group`:await c(e.category);break;case`new-group`:{let{showInputDialog:e}=await _o(async()=>{let{showInputDialog:e}=await import(`./input-dialog-CnAqzRxY.js`).then(e=>(e.t(),e.n));return{showInputDialog:e}},__vite__mapDeps([58,0,5]),import.meta.url),t=await e({title:V(`sessionsView.newGroupTitle`),label:V(`sessionsView.newGroupPrompt`),submitLabel:V(`sessionsView.newGroupCreate`),requireValue:!0});t&&this.isHeaderSessionActionCurrent(n,r)&&await c(t);break}case`snooze`:await i.snoozeSessionWithUndo(s,a,e.snoozedUntil,n);break;case`wake`:await i.patchSession(s,a,{snoozedUntil:null},n,{sessionScope:!0});break;case`toggle-archived`:a.archived?await i.patchSession(s,a,{archived:!1},n,{sessionScope:!0}):await i.archiveSessionWithUndo(s,a,n);break;case`delete`:await i.deleteSession(s,a,n)}}catch(e){this.isHeaderSessionActionCurrent(n,r)&&this.publishHeaderError(e,r)}}resolveContinueInTerminalCommand(e,t){return r_({gatewayUrl:t.gatewayUrl,sessionKey:e.key,rowAgentId:e.agentId,selectedAgentId:this.context.agentSelection.state.selectedId??void 0})}continueInTerminalDisabledReason(e){let t=this.context.gateway,n=t.snapshot.client;if(t.snapshot.phase!==`connected`||!n)return V(`chat.sessionHeader.continueInTerminal.disconnected`);let r=this.resolveContinueInTerminalCommand(e,n);if(!r.ok)return V(r.reason===`query-routed`?`chat.sessionHeader.continueInTerminal.queryRouted`:`chat.sessionHeader.continueInTerminal.unavailable`)}openContinueInTerminalDialog(e){let t=this.captureConnectionScope();if(!t)return;let n=this.resolveContinueInTerminalCommand(e,t.client);n.ok&&(this.continueInTerminalDialog={qualifiedSessionKey:n.qualifiedSessionKey,selectedGatewayUrl:this.context.gateway.connection.gatewayUrl,clientGatewayUrl:t.client.gatewayUrl,scope:t},this.requestUpdate())}closeContinueInTerminalDialog(){this.continueInTerminalDialog&&(this.continueInTerminalDialog=null,this.requestUpdate())}currentContinueInTerminalCommand(e){let t=this.continueInTerminalDialog,n=this.context.gateway,r=n.snapshot.client;if(!t)return null;let i=e&&r?this.resolveContinueInTerminalCommand(e,r):null;return!this.isConnectionScopeCurrent(t.scope)||!i?.ok||i.qualifiedSessionKey!==t.qualifiedSessionKey||n.connection.gatewayUrl!==t.selectedGatewayUrl||r?.gatewayUrl!==t.clientGatewayUrl?(this.continueInTerminalDialog=null,null):i.command}captureHeaderSessionActionScope(){let e=this.context.gateway,t=e.snapshot.client;return e.snapshot.phase!==`connected`||!t?null:{epoch:this.connectionGeneration,context:this.context,gateway:e,sessions:this.context.sessions,client:t,selectedAgentId:this.context.agentSelection.state.selectedId??`main`,signal:this.headerSessionMutationAbortController.signal}}isHeaderSessionActionCurrent(e,t){return this.ownsHeaderOutcome(t)&&this.isConnected&&this.context===e.context&&this.context.gateway===e.gateway&&this.context.sessions===e.sessions&&e.gateway.snapshot.phase===`connected`&&e.gateway.snapshot.client===e.client}beginHeaderRename(e){let t=b(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,label:null},sessionScope:!0,session:e});if(!t.allowed){this.publishHeaderError(t.reason);return}this.headerRenameSession={key:e.key,sessionId:e.sessionId,label:e.label},this.headerRenameInitialValue=xs(e),this.headerRenameValue=this.headerRenameInitialValue,this.updateComplete.then(()=>{let e=this.querySelector(`.chat-pane__session-title-input`);e?.focus(),e?.select()})}cancelHeaderRename(){this.headerRenameSession=null}commitHeaderRename(){let e=this.headerRenameSession;if(!e)return;let t=Xl(this.headerRenameValue,this.headerRenameInitialValue,e.label);this.headerRenameSession=null;let n=this.state;if(!n||!t)return;let r=b(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,...t},sessionScope:!0,session:n.sessionsResult?.sessions.find(t=>z(t.key,e.key)&&t.sessionId===e.sessionId)});if(!r.allowed){this.publishHeaderError(r.reason);return}let i=this.headerOutcomeOwner;this.context.sessions.patch(e.key,t,{agentId:Y(n),expectedSessionId:e.sessionId}).catch(e=>this.publishHeaderError(e,i))}async loadHeaderMenuData(e,t,n){let r=this.connectedClient;if(!r)return;let i=[this.loadHeaderPlatform(r,this.connectionGeneration)],a=(e.execNode?e.execCwd?.trim():void 0)||e.spawnedWorkspaceDir?.trim()||e.spawnedCwd?.trim()||null,o=e.worktree?.id;if(o&&!a){let e=this.headerWorktreePaths.get(o)??{};this.headerWorktreePaths.set(o,e),e.path===void 0&&!e.loading&&(e.loading=!0,i.push(r.request(`worktrees.list`,{}).then(t=>{e.path=t.worktrees.find(e=>e.id===o&&e.removedAt===void 0)?.path??null}).catch(()=>{e.path=void 0}).finally(()=>{e.loading=!1})))}let s=e.worktree?void 0:t?.trim(),c=a||(o?this.headerWorktreePaths.get(o)?.path:void 0)||s,l=!!e.execNode||Br(e.placement?.state),u=c===s?n:!!c;if(!e.worktree&&!l&&c&&u){let e=this.headerBranches.get(c)??{};this.headerBranches.set(c,e),e.loading||(e.loading=!0,i.push(r.request(`worktrees.branches`,{repoRoot:c}).then(t=>{e.value=t.headBranch??null}).catch(()=>{e.value=null}).finally(()=>{e.loading=!1})))}await Promise.all(i),this.requestUpdate()}showHeaderCopied(e){this.headerCopiedAction=e,this.headerCopiedTimer!==null&&window.clearTimeout(this.headerCopiedTimer),this.headerCopiedTimer=window.setTimeout(()=>{this.headerCopiedAction=null,this.headerCopiedTimer=null},1500)}handleHeaderMenuAction(e,t,n,r,i=O){let a=e===`copy-path`?n:e===`copy-branch`?r:null;if(a){let t=this.headerOutcomeOwner;i(a).then(n=>{this.ownsHeaderOutcome(t)&&(n?this.showHeaderCopied(e):this.publishHeaderError(V(`common.copyFailed`),t))});return}e===`reveal`&&n&&this.revealHeaderWorkspace(t)}publishHeaderError(e,t=this.headerOutcomeOwner){this.state&&this.ownsHeaderOutcome(t)&&(this.state.chatError=this.state.lastError=B(e),this.state.requestUpdate?.())}async revealHeaderWorkspace(e){let t=this.connectedClient;if(!t)return;let n=this.headerOutcomeOwner,r=Bt(e.key)?.agentId;try{let i=await t.request(`sessions.files.reveal`,{key:e.key,...r?{agentId:r}:{}});if(!i.ok){let e=i.error??`Failed to reveal session workspace.`;this.publishHeaderError(e,n)}}catch(e){this.publishHeaderError(e,n)}}}})))()}var jT;function MT(){return(MT=e((()=>{F(),di(),AT(),Q(),vv(),jT=class extends kT{async probeSessionDiscussion(e){let t=this.state;if(!t?.connected||!t.client||this.sessionDiscussionStates.has(e)||this.sessionDiscussionProbes.has(e)||!ui(this.context.gateway.snapshot,`session.discussion.info`,`operator.read`))return;let n=this.connectionGeneration;this.sessionDiscussionProbes.add(e);try{let r=await t.client.request(`session.discussion.info`,{sessionKey:e,agentId:Y(t)});if(n!==this.connectionGeneration)return;this.sessionDiscussionStates.set(e,r.state),this.requestUpdate()}catch{}finally{this.sessionDiscussionProbes.delete(e),n!==this.connectionGeneration&&this.state?.sessionKey===e&&!this.sessionDiscussionStates.has(e)&&this.probeSessionDiscussion(e)}}buildSessionDiscussionPanel(e,t){if(!e.connected||!e.client||!ui(this.context.gateway.snapshot,`session.discussion.info`,`operator.read`))return null;let n=ui(this.context.gateway.snapshot,`session.discussion.open`,`operator.write`),r=this.connectionGeneration,i=this.sessionDiscussionPanels.get(t);if(i?.generation===r&&i.canOpen===n)return i.config.openUrl=this.sessionDiscussionOpenUrls.get(t)??null,i.config;let a=async(t,n)=>{if(r!==this.connectionGeneration||!e.connected||!e.client||e.client!==this.context.gateway.snapshot.client||!ui(this.context.gateway.snapshot,t,t===`session.discussion.info`?`operator.read`:`operator.write`))throw Error(V(`chat.sessionDiscussion.disconnected`));return e.client.request(t,{sessionKey:n,agentId:Y(e)})},o={sessionKey:t,canOpen:n,openUrl:this.sessionDiscussionOpenUrls.get(t)??null,loadInfo:e=>a(`session.discussion.info`,e),openDiscussion:e=>a(`session.discussion.open`,e),onStateChange:(t,n,i)=>{if(r!==this.connectionGeneration)return;this.sessionDiscussionStates.set(t,n);let a=e.sessionKey.trim()===t;if(a&&this.sessionDiscussionOpenUrls.set(t,i),n===`none`&&this.sessionDiscussionOpenUrls.delete(t),n===`none`&&a){e.updateSidebarLayout(O_(e.sidebarLayout,`discussion`));return}e.requestUpdate()}};return this.sessionDiscussionPanels.set(t,{generation:r,canOpen:n,config:o}),o}openSessionDiscussionSlot(){let e=this.state;if(!e)return;let t=dv(e.sidebarLayout,`discussion`),n=t.columns.flatMap(e=>e.panels).find(e=>e.slot===`discussion`);this.commitSidebarLayout(t),n&&e.updateSidebarActivePanel(n.id)}resolveSessionDiscussionAction(){let e=this.state,t=e?.sessionKey.trim()??``,n=t?this.sessionDiscussionStates.get(t):void 0;if(!e||!t||n===void 0||n===`none`||!this.buildSessionDiscussionPanel(e,t))return null;let r=e.sidebarLayout.columns.some(e=>e.panels.some(e=>e.slot===`discussion`));return{active:r,label:V(r?`chat.sessionDiscussion.hide`:`chat.sessionDiscussion.show`),onToggle:()=>r?this.commitSidebarLayout(O_(e.sidebarLayout,`discussion`)):this.openSessionDiscussionSlot()}}}})))()}var NT;function PT(){return(PT=e((()=>{Lo(),Rn(),F(),di(),nm(),OT(),NT=class{constructor(){this.memo=new DT}read(e,t,n,r){let i=e.nativeConversation?.supportsSessionActions,a=i&&t?Vd(e.plugins,t):[],o=!!(i&&$o(t?.placement)&&K(e.gateway.snapshot,`sessions.reclaim`));return this.memo.read([...a.flatMap(({id:e,label:t,disabled:n})=>[e,t,n]),o,n,ne.getLocale(),r],()=>[...a.map(e=>({label:e.label,disabled:e.disabled,id:`plugin/${e.id}`,icon:H.plug,onActivate:()=>r({kind:`plugin`,id:e.id})})),...o?[{id:`stop-cloud-worker`,label:V(`sessionsView.stopCloudWorker`),icon:H.stop,variant:`danger`,disabled:!!n,description:n,onActivate:()=>r({kind:`stop-cloud-worker`})}]:[]])}}})))()}var FT;function IT(){return(IT=e((()=>{kr(),fo(),ko(),Tr(),Fn(),mn(),Rn(),ys(),cs(),rs(),F(),di(),lm(),Ce(),Td(),R(),Ks(),xd(),MT(),iT(),OT(),PT(),lS(),bs(),Cg(),Zg(),V_(),e_(),h_(),Mv(),gc(),vv(),FT=class extends jT{constructor(...e){super(...e),this.headerWorkspaceGit=!1,this.headerPanelsMemo=new DT,this.headerLayoutMemo=new DT,this.headerSessionActions=new NT,this.headerReasonsMemo=new DT,this.headerSharingMemo=new DT,this.headerGroupsMemo=new DT,this.headerActivityMemo=new DT,this.headerViewersMemo=new DT,this.headerBoardMenuMemo=new DT,this.onHeaderMenuOpen=()=>{this.headerMenuRow&&this.loadHeaderMenuData(this.headerMenuRow,this.headerAgentWorkspace,this.headerWorkspaceGit)},this.onHeaderCommandPalette=()=>window.dispatchEvent(new Event(pn)),this.onHeaderSettingsChange=e=>this.state?.applySettings(e),this.onHeaderAction=e=>{this.headerMenuRow&&this.handleHeaderSessionAction(e,this.headerMenuRow)},this.headerPanelCallbacks={terminal:()=>this.headerWorkspace?.onToggleTerminal?.(),browser:()=>this.headerWorkspace?.onToggleBrowser?.(),desktop:()=>this.headerWorkspace?.onToggleDesktop?.(),discussion:()=>this.resolveSessionDiscussionAction()?.onToggle(),changes:()=>this.headerWorkspace?.onOpenDiff?.(),files:()=>this.headerWorkspace?.onToggleCollapsed(),companion:()=>this.requestSessionRail(`toggle`),subagents:()=>this.requestSubagentsPanel(`toggle`),processes:()=>this.requestBackgroundPanel(`processes`,`toggle`)},this.onHeaderDefault=()=>{this.headerDefaultAction?.kind!==`status`&&this.headerDefaultAction?.onActivate()},this.onHeaderSplitView=()=>this.onOpenSplitView?.(),this.onHeaderSplitDown=()=>this.onSplitDown?.(this.paneId),this.onHeaderSplitRight=()=>this.onSplitRight?.(this.paneId),this.onHeaderBoardSelect=e=>this.headerBoardMenu?.onSelect(e)}renderPaneHeader(e,t,n,r,i,a,o,c=rT(),l=U){this.headerMenuRow=t,this.headerWorkspace=e,this.headerAgentWorkspace=r,this.headerWorkspaceGit=i,this.syncSelectedSessionSharing(t);let u=xh({session:t,agentWorkspace:t?.worktree?void 0:r,worktreePath:t?.worktree?this.headerWorktreePaths.get(t.worktree.id)?.path:void 0}),d=!!t?.execNode||Br(t?.placement?.state),f=t?.repository?.branch||t?.worktree?.branch||(d||!u.root?null:this.headerBranches.get(u.root)?.value)||null,p=pv({session:t,workspaceRoot:u.root,methodAdvertised:K(this.context.gateway.snapshot,`sessions.files.reveal`)===!0,hasAdminAccess:Er(this.context.gateway.snapshot.hello?.auth??null)}),m=this.state?this.state.chatSending||Kg({runActive:Hl(this.state),queue:this.state.chatQueue,runStatus:this.state.chatRunStatus,sessionKey:this.state.sessionKey}):!1,h=lf(this.context.gateway.snapshot,!!this.state?.chatRunId).branchSwitch,g=this.state&&this.isCurrentSessionArchived(this.state)?V(`chat.archivedSessionDisabled`):h.allowed?m?V(`chat.sessionHeader.branchSwitchUnavailable`):null:h.reason,_=this.context.gateway.snapshot,v=K(_,`session.visibility.set`)===!0,y=b(_,{method:`session.members.listEvidence`,requiredScope:`operator.read`}),x=e=>{let t=b(_,{method:e,requiredScope:`operator.write`});return t.allowed?void 0:t.reason},S=x(`session.visibility.set`),C=x(`session.publicShare.set`),w=x(`session.members.add`),T=x(`session.members.remove`),E=y.allowed||S===void 0?void 0:y.reason,D=t?b(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:t.key,label:null},sessionScope:!0,session:t}):null,O=this.state?.connected!==!0||!D?V(`sessionsView.actionRequiresConnection`):D.allowed?void 0:D.reason,k=ye({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}),ee=!!(t&&this.canArchiveHeaderSession(t)),A=!!(t&&s([t],k)),j=t!=null&&N(t),te=t?ts({snapshot:this.context.gateway.snapshot,session:{...t,pinnable:j}}):{},M=t?b(this.context.gateway.snapshot,{method:`sessions.assignOwner`,params:{key:t.key,owner:{type:`human`,id:_.selfUser?.id??`profile`}},requiredScope:`operator.write`}):null,P=t?this.continueInTerminalDisabledReason(t):void 0,re=this.headerReasonsMemo.read([...Object.entries(te).flat(),M?.allowed,M&&!M.allowed?M.reason:void 0,P],()=>({...te,...M&&!M.allowed?{"assign-owner":M.reason}:{},...P?{"continue-in-terminal":P}:{}})),ie=sS(t)!==null&&nr(this.context.gateway.snapshot),ae=this.resolveSessionDiscussionAction(),oe=o??this.state?.sidebarLayout,se=oe?.open===!0&&!oe.expanded,ce=_v({label:V(se?`chat.sidePanel.minimize`:`chat.sidePanel.label`),icon:se?H.panelRightClose:H.panelRightOpen,className:`chat-side-panel-toggle`,expanded:se,onToggle:()=>this.setChatSidePanelOpen(!se,o)}),F=e.onToggleBrowser?_v({label:V(`browser.toggle`),icon:H.globe,className:`chat-browser-panel-toggle`,onToggle:e.onToggleBrowser}):U,le=this.state!==void 0&&Ae(this.state.sidebarLayout,`companion`),ue=this.state!==void 0&&Ae(this.state.sidebarLayout,`subagents`),de=this.state!==void 0&&Ae(this.state.sidebarLayout,`processes`),fe=e.list?.files.filter(e=>e.kind===`modified`).length??0,pe=this.headerPanelsMemo.read([!!e.onToggleTerminal,!!e.onToggleBrowser,ie&&!!e.onToggleDesktop,ae?.label,ae?.active,!!e.onOpenDiff,e.collapsed,fe,le,ue,de,n,ne.getLocale()],()=>{let t=this.headerPanelCallbacks,r=[];for(let[n,i,a,o]of[[`terminal`,V(`terminal.toggle`),H.terminal,e.onToggleTerminal&&t.terminal],[`browser`,V(`browser.toggle`),H.globe,e.onToggleBrowser&&t.browser],[`desktop`,V(`desktop.toggle`),H.monitor,ie&&e.onToggleDesktop&&t.desktop],[`discussion`,ae?.label??``,H.messageSquare,ae&&t.discussion],[`changes`,V(`chat.sessionDiff.show`),H.diff,e.onOpenDiff&&t.changes]])o&&r.push({id:n,label:i,icon:a,onActivate:o,...n===`discussion`?{active:ae?.active}:{}});if(r.push({id:`session-files`,label:V(e.collapsed?`chat.workspaceFiles.showFiles`:`chat.workspaceFiles.collapse`),icon:H.fileText,active:!e.collapsed,badge:fe,onActivate:t.files}),r.push({id:`session-companion`,label:V(le?`chat.rail.collapse`:`chat.rail.show`),icon:H.spark,active:le,onActivate:t.companion}),!n)for(let e of[`subagents`,`processes`]){let n=e===`subagents`;r.push({id:`session-${e}`,label:V(n?`chat.subagentsPanel.title`:`chat.processesPanel.title`),icon:n?H.bot:H.terminal,active:n?ue:de,onActivate:t[e]})}return r}),me=!n&&this.dashboardDefaultMenuAction(t,oe);this.headerDefaultAction=me?{id:`dashboard-default`,icon:H.check,...me}:void 0;let he=this.headerLayoutMemo.read([me&&me.kind,me&&me.label,me&&me.description,me&&me.disabled,!!this.onOpenSplitView,this.narrow,!!this.onSplitDown,!!this.onSplitRight,ne.getLocale()],()=>{let e=[];me&&e.push({id:`dashboard-default`,icon:H.check,...me,...me.kind===`status`?{}:{onActivate:this.onHeaderDefault}}),this.onOpenSplitView&&e.push({id:`open-split-view`,label:V(`chat.splitView.open`),icon:H.columns2,onActivate:this.onHeaderSplitView});for(let[t,n,r,i]of[[`split-down`,`chat.splitView.splitDown`,H.panelBottomOpen,`onSplitDown`],[`split-right`,`chat.splitView.splitRight`,H.panelRightOpen,`onSplitRight`]])!this.narrow&&this[i]&&e.push({id:t,label:V(n),icon:r,onActivate:i===`onSplitDown`?this.onHeaderSplitDown:this.onHeaderSplitRight});return e}),ge=cS({gatewaySnapshot:this.context.gateway.snapshot,movingKey:this.headerPlacementMovingKey,reclaimingKey:this.headerPlacementReclaimingKey,restartingKey:this.headerPlacementRestartingKey,row:t}),_e=this.state?.sessionKey??``,ve=this.state?.sessionsResult,be=this.context.sessions?.state?.groups,xe=this.context.sessions?.state?.result?.sessions,Se=this.headerGroupsMemo.read([be,xe],()=>mp(be??[],xe??[])),Ce=(ve?.owners?.length??0)>=2||(t?.participantCount??0)>0,we=this.headerActivityMemo.read([this.context,this.context.basePath],()=>Zo(this.context)),Te=Ce?t?.owner?.actor.identity:void 0,Ee=n?void 0:this.headerViewersMemo.read([this.presencePayload,_.selfUser,_.client?.instanceId,_e,Te,Ce?t?.participants:void 0],()=>Df(this.presencePayload,_.selfUser,_.client?.instanceId,_e,[...Te?[Te]:[],...Ce?(t?.participants??[]).map(({identity:e})=>e):[]])),I=Nf(this.presencePayload).users.some(e=>up(e,Te)&&e.watchedSessions.includes(_e)),De=t?this.sessionSharingStates.get(this.sessionSharingCacheKey(t.key)):void 0,Oe=_.hello?.policy?.allowedSessionVisibilities,ke=this.headerSharingMemo.read([v,...t?Object.entries(t).flat():[void 0],De,Oe,y.allowed,E,S,w,T,C,I,we,Ce,ne.getLocale()],()=>v&&t?{session:t,state:De,allowedVisibilities:Oe,membersAvailable:y.allowed,openDisabledReason:E,visibilityDisabledReason:S,memberAddDisabledReason:w,memberRemoveDisabledReason:T,publicShareDisabledReason:!t.sessionId||oo(t.key)?V(`chat.sessionSharing.publicUnavailable`):C,onPublicShareChange:e=>void this.setSessionPublicShare(t,e),onCopyPublicLink:()=>void this.copySessionPublicLink(t),ownerViewing:I,personActivity:we,showOwner:Ce,onOpen:()=>void this.loadSessionSharing(t),onVisibilityChange:e=>void this.setSessionVisibility(t,e),onMemberChange:(e,n)=>void this.setSessionMember(t,e,n)}:null);this.headerBoardMenu=this.pageBoardWidgetMenu(oe);let je=this.headerBoardMenuMemo.read([this.headerBoardMenu?.widget,this.headerBoardMenu?.tabs,this.headerBoardMenu?.canMutate],()=>this.headerBoardMenu&&{...this.headerBoardMenu,onSelect:this.onHeaderBoardSelect}),Me=this.observedParentSessionRow(),Ne=v_({paneId:this.paneId,narrow:this.narrow,mergedChrome:this.mergedChrome,navDrawerOpen:this.navDrawerOpen,title:(n?this.catalogSession?.name?.trim():void 0)||this.resolveHeaderSessionTitle(t),session:t,showOwnerChip:Ce,ownerViewing:I,personActivity:we,catalog:n,catalogColor:this.catalogSession?.color,editing:!!(this.headerRenameSession&&this.headerRenameSession.key===t?.key),renameValue:this.headerRenameValue,workspaceRoot:u.root,workspaceLabel:u.label,workspaceIcon:X_(this.context,u.root?t?.key:void 0),parentSession:w_(t,Me?[Me]:[]),branch:f,branches:this.state?yf(this.state):[],branchSwitchDisabledReason:g,platform:this.headerPlatform,canReveal:p,copiedAction:this.headerCopiedAction,renameDisabledReason:O,actionsDisabled:this.state?.connected!==!0,panelActions:F,runAction:l,panelLayoutActions:W`${iv(oe,c,this.narrow,(e,t)=>this.state?.updateSidebarLayout(e,t))}${ce}`,presence:Ee?.length?W`<openclaw-viewer-facepile
            class="chat-pane__presence"
            .staticUsers=${Ee}
            .maxVisible=${4}
            .personActivity=${we}
            variant="session"
          ></openclaw-viewer-facepile>`:U,sharingControl:ke&&(!F_(ke.session)||!ke.openDisabledReason)&&(!this.narrow||!F_(ke.session))?jv(ke):U,publicAccessIndicator:this.narrow&&ke?Tv(ke):U,placementControl:vg({session:t,placementStartupStatus:a,placementMoving:ge.moving,placementRestarting:ge.restarting,placementMoveDisabledReason:ge.moveDisabledReason,placementReclaimDisabledReason:ge.reclaimDisabledReason,placementRecoveryDisabledReason:ge.recoveryDisabledReason,onPlacementMove:()=>t&&void this.changeHeaderPlacement(t,`move`),onPlacementReclaim:()=>t&&void this.changeHeaderPlacement(t,`reclaim`),onPlacementRecover:()=>t&&void this.changeHeaderPlacement(t,`recover`)}),sessionMenuAction:t&&this.state?W`<openclaw-chat-header-session-menu
              .session=${this.headerSessionMenuData(t,j)}
              .worktreePath=${t.execNode||!ls()?null:u.root}
              .onboarding=${this.onboarding}
              .preferencesBrowserOnly=${this.context.runtimeConfig?.state.connected&&this.context.runtimeConfig.canPatch===!1}
              .compact=${this.narrow}
              .copyMarkdownAllowed=${Gm(this.context.gateway.snapshot)}
              .splitAllowed=${pu()}
              .settings=${this.state.settings}
              .panelActions=${pe}
              .layoutActions=${he}
              .boardWidgetMenu=${je}
              .sessionActions=${this.headerSessionActions.read(this.context,t,ge.reclaimDisabledReason,this.onHeaderAction)}
              .sharing=${ke}
              .groups=${Se}
              .currentOwner=${t.owner?.actor??null}
              .actionDisabledReasons=${re}
              .forkDisabled=${this.state.sessionsLoading||t.modelSelectionLocked===!0}
              .forkFromLastCompleted=${t.hasActiveRun===!0}
              .archiveAllowed=${ee}
              .archiveShortcut=${this.active&&this.presented&&!this.onboarding}
              .deleteAllowed=${A}
              .onOpen=${this.onHeaderMenuOpen}
              .onOpenCommandPalette=${this.onHeaderCommandPalette}
              .onSettingsChange=${this.onHeaderSettingsChange}
              .onAction=${this.onHeaderAction}
            ></openclaw-chat-header-session-menu>`:U,onBeginRename:()=>t&&this.beginHeaderRename(t),onRenameInput:e=>{this.headerRenameValue=e},onCommitRename:()=>this.commitHeaderRename(),onCancelRename:()=>this.cancelHeaderRename(),onMenuOpenChange:e=>{e&&t&&this.loadHeaderMenuData(t,r,i)},onMenuAction:e=>{t&&this.handleHeaderMenuAction(e,t,u.root,f)},onOpenParentSession:e=>{this.onPaneSessionChange?.(this.paneId,e)},onBranchSelect:e=>{let t=lf(this.context.gateway.snapshot,!!this.state?.chatRunId).branchSwitch;if(!t.allowed){this.publishHeaderError(t.reason);return}this.switchToBranch(e)},onOpenSplitView:this.onOpenSplitView,onSplitDown:this.onSplitDown,onSplitRight:this.onSplitRight,onClosePane:this.onClosePane}),Pe=this.currentContinueInTerminalCommand(t);return W`${Ne}${Pe?ig({command:Pe,onClose:()=>this.closeContinueInTerminalDialog()}):U}`}}})))()}var LT;function RT(){return(RT=e((()=>{F(),_x(),IT(),pp(),LT=class extends FT{constructor(...e){super(...e),this.removeBrowserAnnotation=e=>{let t=this.state;if(!t)return;let n=t.sessionKey,r=e=>{this.updateComplete.then(()=>{this.state===t&&this.state.sessionKey===n&&e()?.focus({preventScroll:!0})})};gx({getOwner:()=>this.stagedAttachmentGatewayOwner??void 0,getSessionKey:()=>this.state?.sessionKey??``,getAttachments:()=>this.state?.chatAttachments??[],setAttachments:e=>{this.state&&(this.state.chatAttachments=e)},requestUpdate:()=>this.state?.requestUpdate?.(),focusComposer:()=>r(()=>this.querySelector(pm)),focusRestoredAnnotation:e=>r(()=>[...this.querySelectorAll(`[data-attachment-id]`)].find(t=>t.dataset.attachmentId===e)?.querySelector(`button`))},e,{removed:V(`chat.composer.browserAnnotationRemoved`),undo:V(`common.undo`),undoUnavailable:V(`chat.composer.browserAnnotationUndoUnavailable`)})}}}})))()}var zT;function BT(){return(BT=e((()=>{_l(),ly(),zT=class{constructor(e,t,n){this.host=e,this.getContext=t,this.getSession=n,this.icons={get:e=>this.getIcon(e)},this.owner=null,this.toolIcons=new Map,this.activityIcons=new Map,this.requested=new Set,this.pending=new Set,this.urls={},e.addController(this),this.loader=new uy({getFetchContext:()=>{let{gateway:e,resourceBasePath:n}=t();return{resourceBasePath:n,gatewayUrl:e.connection.gatewayUrl,auth:{hello:e.snapshot.hello,settings:{token:e.connection.token},password:e.connection.password}}},isConnected:()=>this.isCurrent(),fetchIcon:(e,t,n)=>{let r=this.activityIcons.get(e);return r?Ml({...t,...r,signal:n}):Promise.resolve(null)},onUrlsChange:e=>this.publish(e)})}publish(e=this.urls){this.urls=e,this.icons={get:e=>this.getIcon(e)},this.host.requestUpdate()}getIcon(e){let t=this.owner;if(!t||!this.isCurrent())return;if(this.requested.add(e),!this.toolIcons.has(e)){let t=this.pending.size>0;this.pending.add(e),t||queueMicrotask(()=>this.refresh())}let n=this.toolIcons.get(e);if(!n)return;this.loader.load(n);let r=this.urls[n];return r?{url:r,onError:()=>{this.owner===t&&this.isCurrent()&&this.urls[n]===r&&this.loader.handleError(n)}}:void 0}isCurrent(){let{snapshot:e,connectionRevision:t}=this.getContext().gateway,n=this.getSession();return!!(this.owner&&e.phase===`connected`&&e.client===this.owner.client&&t===this.owner.revision&&n?.sessionKey===this.owner.session.sessionKey&&n?.agentId===this.owner.session.agentId)}hostUpdate(){if(this.isCurrent())return;let{snapshot:e,connectionRevision:t}=this.getContext().gateway,{client:n,phase:r}=e,i=this.getSession();this.hostDisconnected(),r===`connected`&&n&&i&&(this.owner={client:n,session:i,revision:t,controller:new AbortController},this.publish())}refresh(){let e=this.owner;if(!e||!this.isCurrent()||e.loading||this.pending.size===0)return;for(let e of this.pending)this.toolIcons.set(e,void 0);this.pending.clear(),e.loading=!0;let t={signal:e.controller.signal};Promise.all([e.client.request(`tools.effective`,e.session,t),e.plugins??=e.client.request(`plugins.list`,{},t).catch(t=>{throw e.plugins=void 0,t})]).then(([t,n])=>{if(this.owner!==e||!this.isCurrent())return;let r=new Map(n.plugins.map(e=>[e.id,{default:e.hasActivityIcon,tools:new Set(e.activityIconTools)}]));this.activityIcons.clear();for(let e of t.groups)for(let t of e.tools){let e=t.pluginId,n=e?r.get(e):void 0,i=n?.tools.has(t.id)?t.id:void 0,a=e&&(i||n?.default)?JSON.stringify([e,i??null]):void 0;a&&e&&this.activityIcons.set(a,{pluginId:e,tool:i}),this.toolIcons.set(t.id,a),this.pending.delete(t.id)}this.loader.reconcileKeys(new Set(this.activityIcons.keys()));for(let e of this.requested){let t=this.toolIcons.get(e);t&&this.loader.load(t)}this.publish()}).catch(()=>{}).finally(()=>{this.owner===e&&(e.loading=!1,this.refresh())})}hostDisconnected(){this.owner&&(this.owner.controller.abort(),this.owner=null,this.toolIcons.clear(),this.activityIcons.clear(),this.requested.clear(),this.pending.clear(),this.loader.reset())}}})))()}function VT(e,t,n,r,i=U){return W`
    <div
      class="chat-composer-neighbor-card chat-composer-neighbor-card--${t} ${e}"
      role=${t===`danger`?`alert`:`status`}
      title=${i}
    >
      <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
        >${t===`info`?H.info:H.alertTriangle}</span
      >
      <div class="chat-composer-neighbor-card__copy">
        <strong>${n}</strong>
        <span>${r}</span>
      </div>
    </div>
  `}function HT(e){if(!e||e.status===`ok`)return U;let t=e.totalBytes>0?Math.round((e.totalBytes-e.availableBytes)/e.totalBytes*100):0,n=e.status===`critical`;return VT(`chat-cloud-disk-space-notice`,n?`danger`:`warn`,V(n?`chat.diskSpace.criticalTitle`:`chat.diskSpace.warningTitle`),V(n?`chat.diskSpace.criticalBody`:`chat.diskSpace.warningBody`,{percent:String(t),free:Ke(e.availableBytes)}))}function UT(e){if(!e)return U;let t={transferred:Ke(e.transferredBytes),total:Ke(e.totalBytes),percent:String(Math.round(e.transferredBytes/e.totalBytes*100))},n=e.phase===`installing`,r=n?V(`chat.workerRuntimeInstall.installingBody`):V(`chat.workerRuntimeInstall.transferringBody`,t);return VT(`chat-worker-runtime-install-notice`,`info`,n?V(`chat.workerRuntimeInstall.installingTitle`):V(`chat.workerRuntimeInstall.transferringTitle`,t),r,r)}function WT(e,t=U,n=os(e),r=`danger`,i){let a=n.trim().split(/\r?\n/u).map(e=>e.replace(/\s+/gu,` `).trim()),o=i??st(a[0]??``),s=a.some(e=>e!==``&&e!==o);return W`
    <div
      class="chat-composer-neighbor-card chat-composer-neighbor-card--${r} chat-error"
      role=${r===`warn`?`status`:`alert`}
    >
      <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
        >${H.alertTriangle}</span
      >
      ${s?W`<details class="chat-error__content">
              <summary class="chat-error__summary">
                <strong>${o}</strong>
                <span>${V(`chat.details`)}</span>
                <span class="chat-error__chevron" aria-hidden="true">${H.chevronDown}</span>
                ${ns(e,V(`chat.copyError`))}
              </summary>
              <pre class="chat-error__diagnostic" tabindex="0" aria-label=${V(`chat.errorDetails`)}>
${n}</pre>
            </details>`:W`<span class="chat-error__content"
              ><strong>${o}</strong>${ns(e,V(`chat.copyError`))}</span
            >`}
      ${t}
    </div>
  `}function GT(e){let t=e.onDismissError?W`
        <openclaw-tooltip .content=${V(`chat.actions.dismissError`)}>
          <button
            class="chat-error__dismiss"
            type="button"
            @click=${e.onDismissError}
            aria-label=${V(`chat.actions.dismissError`)}
          >
            ${H.x}
          </button>
        </openclaw-tooltip>
      `:U;return W`
    <div class="chat-topbar-notices">
      ${HT(e.diskSpace)}
      ${UT(e.workerRuntimeInstall)}
      ${e.error?WT(e.error,t):U}
    </div>
  `}function KT(e){let t=e.runError?.kind===`state_contention`,n=e.onRefresh?W`<button
        class="btn btn--sm chat-error__refresh"
        type="button"
        ?disabled=${!e.connected}
        @click=${e.onRefresh}
      >
        ${V(t?`chat.checkStatus`:`common.refresh`)}
      </button>`:U;return W`
    ${e.subagentParentKey&&e.subagentSessionsRead?W`<openclaw-chat-child-attention
            .sessionKey=${e.subagentParentKey}
            .sessions=${e.subagentSessions??[]}
            .onOpenSubagent=${e.onOpenSubagent}
            .onOpenSession=${e.onSessionSelect}
          ></openclaw-chat-child-attention>`:U}
    ${e.providerReviewNotice??U}
    ${qT(e.providerPolicyNotice)}
    ${e.runError?WT(e.runError.summary,n,void 0,t?`warn`:`danger`,e.runError.kind===`stop`?void 0:V(t?`chat.errorBusySummary`:e.runError.kind===`auth_refresh`?`chat.errorSignInSummary`:`chat.errorReplySummary`)):U}
    ${rv({conflict:e.workspaceConflict??void 0,onDismiss:e.onDismissWorkspaceConflict})}
    ${JT(e.placementStartup,e.messages,e.onRetrySessionPlacementStartup)}
  `}function qT(e){if(!e)return U;let t=e.state===`blocked`||e.state===`unavailable`,n=e.fallbackModel??e.model,r=e.state!==`buffering`&&e.state!==`blocked`&&!n?V(`chat.providerPolicy.fallbackUnknownBody`):V(`chat.providerPolicy.${e.state}Body`,{model:n??``});return VT(`chat-provider-policy-notice`,t?`danger`:`warn`,V(`chat.providerPolicy.${e.state}Title`),r)}function JT(e,t,n){if(e?.phase!==`failed`)return U;let r=e.action===`check-delivery`,i=e.error??V(`newSession.createFailed`),a=r?[V(`chat.queue.checkDeliveryHelp`),e.error].filter(Boolean).join(`

`):V(`newSession.placementStartFailed`,{error:i}),o=os(i),s=r?[V(`chat.queue.checkDeliveryHelp`),e.error?o:void 0].filter(Boolean).join(`

`):V(`newSession.placementStartFailed`,{error:o}),c=e.initialTurn&&!xa(t,e.initialTurn.sendRunId,!0);return WT(a,e.discardAndReload?W`<button
        class="btn btn--sm danger chat-error__discard"
        type="button"
        @click=${e.discardAndReload}
      >
        ${V(`newSession.discardUnsavedAndReload`)}
      </button>`:e.retryable&&n&&!c?W`<button class="btn btn--sm" type="button" @click=${n}>
          ${V(r?`chat.queue.checkDelivery`:`common.retry`)}
        </button>`:U,s,`danger`,r?V(`chat.queue.checkDeliveryHelp`):e.discardAndReload?s:V(`chat.errorStartSummary`))}function YT(){return(YT=e((()=>{kr(),ms(),is(),Rn(),F(),fa(),dt(),Da(),we(),Wg(),__(),da()})))()}function XT(e,t){return t.subagentSessionsHydrated?(t.subagentSessions??[]).filter(t=>{let n=ke(t);return!t.archived&&(t.status===`queued`||kd(t))&&!z(t.key,e.key)&&(n?z(n,e.key):e.childSessions?.some(e=>z(e,t.key)))}):[]}function ZT(e,t){let n=e.selectedSession,r=n&&!n.archived&&n.hasActiveSubagentRun===!0,i=r&&!e.runActive&&!e.runWorking&&!go(n),a=i?Ay(e.messages):null,o=a?.timestamp??null,s=o!==null&&typeof n?.startedAt==`number`&&o>n.startedAt?o:null,c=r?XT(n,e):[],l=c.filter(e=>!it(e.key)),u=l.length,d=u===1?l[0]:void 0,f=t?[]:l.toSorted((e,t)=>(e.createdAt??e.startedAt??0)-(t.createdAt??t.startedAt??0)||e.key.localeCompare(t.key)).map(e=>{let t=e.status===`queued`?`queued`:go(e)?`running`:`waiting`,n=e.observerDigest;return{session:e,key:e.key,label:He(e.key,e),status:t,activity:t===`running`&&n?.runId&&e.activeRunIds?.includes(n.runId)&&n.headline.trim()||void 0,listed:Ff(e)}}),p=i&&(!e.subagentSessionsHydrated||c.length>0)?{startedAt:s!==null&&typeof n.endedAt==`number`&&n.endedAt>=s?n.endedAt:s,...s!==null&&a?.runId?{runId:a.runId}:{},runningCount:u,...c.length>u?{sessionCount:c.length-u}:{},...d?{child:{key:d.key,label:He(d.key,d)}}:{}}:null,m=(p!==null||u>0)&&c.every(e=>it(e.key)||Ff(e));return{wait:p,placedWait:!t&&p?.runId&&p.startedAt!==null?{startedAt:p.startedAt,runId:p.runId}:void 0,running:u,activity:f,listed:m,statusKey:JSON.stringify([p?[p.startedAt,p.runningCount,p.sessionCount,p.child?.key,p.child?.label,m]:[u,m],f.map(({session:e,...t})=>[t,e.sessionId,e.lifecycleRevision,e.agentId,e.activeRunIds,e.observerDigest])]),rowsKey:rp(e.subagentSessions)}}function QT(){return(QT=e((()=>{gt(),R(),My(),Xp()})))()}function $T(e){let t=e.inlineApproval?.sourceSessionKey,n=t?e.sessions?.sessions.find(e=>z(e.key,t)):void 0,r=e.historyState?km(e.historyState):void 0,i=r?[...r.page.items.filter(e=>!e.queued),...r.queuedInputs]:void 0,a=e.onRequestUpdate??(()=>{}),o=(t=`.agent-chat__composer-combobox > textarea`)=>e.transcript.scrollElement?.closest(`.chat`)?.querySelector(t)?.focus({preventScroll:!0}),s=(t,n,r,i,a=!1)=>{Hg({paneId:e.paneId,anchorRect:n,sourceRange:e.transcript.scrollElement?kg(e.transcript.scrollElement,t)?.range:void 0,comment:``,readSignal:e.readSignal,onCancel:i,onSave:n=>{if(e.readSignal?.aborted)return!0;if(!a&&!$e(e.uploadConfig))return Lt({message:tt()}),!1;let i=b_({...t,comment:n,sessionKey:e.sessionKey},{attachmentLimits:e.attachmentLimits,selectionContextOnly:a},Ws(e));return i?r(i)?!0:(At([i]),!1):!1}})},c=e.canSend,l=dg(e.paneId),u=gv(l,{...e,onReopen:(t,n)=>{let r=mg(e.paneId);r.activeQuestionKey=JSON.stringify([n,t]),r.questionCollapsed=!1}}),d=e.onOpenImage?(t,n)=>n===void 0?e.onOpenImage?.(t):e.onOpenImage?.(t,n):void 0,f=e.onOpenImage?t=>d?.(t,e.onRequestOpenImage?.()):void 0,p=xc({...e,canCompose:c}),m=e.placementStartup?.phase===`failed`?null:e.placementStartup,h=e.placementStartup?.initialTurn,g=e.queue;if(h){let t=eE.get(e.queue);t?.initialTurn!==h&&(t={initialTurn:h,queue:[...e.queue,h]},eE.set(e.queue,t)),g=t.queue}let _=!!m||Kg(e),v=nt(`transcript`,{sessionKey:e.sessionKey,agentId:e.currentAgentId,messages:e.messages,stream:e.stream,loading:e.loading},Ev({...e,asyncQuestions:u,loading:e.loading&&!m,streamStartedAt:m?.startedAt??e.streamStartedAt,queue:g,initialTurnId:e.placementStartup?.initialTurn?.id,pendingInputs:i,runActive:e.runActive===!0,runWorking:_,startupLabel:ku(e.startupStatus,m),questionPrompts:e.gatewayQuestionPrompts,agents:e.agentsList?.agents,onOpenImage:d,onRequestUpdate:a,queuedMessageAction:e.placementStartup?.initialTurn?{id:e.placementStartup.initialTurn.id,label:e.placementStartup.action===`check-delivery`?V(`chat.queue.checkDelivery`):void 0,onAction:e.connected?e.onRetrySessionPlacementStartup:void 0}:void 0,onRetryQueuedMessage:e.connected&&c?e.onQueueRetry:void 0,onDiscardQueuedMessage:e.onQueueRemove,onCompanionSelection:e.canSend&&!e.suggestionComposer&&e.onCompanionStageAttachment?(t,n)=>s(t,n,t=>e.onCompanionStageAttachment?.(t,e.sessionKey)??!1,void 0,!0):void 0,commentAttachments:e.suggestionComposer?void 0:e.attachments,commentsDisabled:!c||!!e.readSignal?.aborted,onAddToChat:e.canSend&&!e.suggestionComposer&&$e(e.uploadConfig)?(t,n)=>s(t,n,t=>e.onAttachmentsChange?(e.onAttachmentsChange([...e.getAttachments?.()??e.attachments??[],t]),a(),o(),!0):!1,o):void 0,onOpenSession:e.onSessionSelect,onFocusComposer:()=>o(`openclaw-plugin-view[data-plugin-composer], .agent-chat__composer-combobox > textarea`)},e.transcript),e.presented??!0),y=t=>W`<button
    class="btn btn--sm"
    type="button"
    ?disabled=${r?.loading}
    @click=${()=>e.historyState&&Id(e.historyState,t===`earlier`?r?.page.nextBefore:void 0)}
  >
    ${V(`chat.pendingInputs.${t}`)}
  </button>`,b=t=>W`<openclaw-plugin-contributions
    .kind=${t}
    .sessionKey=${e.sessionKey}
    .agentId=${e.currentAgentId}
    .presented=${Ge(e.presented??!0)}
  ></openclaw-plugin-contributions>`,x=W`${r&&(r.error||r.page.nextBefore!==void 0||r.before!==void 0)?W`<div class="chat-pending-inputs" role="status">
          ${r.error?W`<span>${r.error}</span>`:U}
          ${r.page.nextBefore===void 0?U:y(`earlier`)}
          ${r.before===void 0?U:y(`latest`)}
        </div>`:U}
  ${e.inlineApproval&&e.onApprovalDecision?W`<div class="chat-inline-approval">
          ${Jo({approval:e.inlineApproval,sourceSession:n,busy:e.approvalBusy===!0,canGrant:e.approvalCanGrant,error:e.approvalErrors?.get(e.inlineApproval.id)??null,variant:`inline`,onDecision:e.onApprovalDecision})}
        </div>`:U}
  ${R_({pullRequests:e.pullRequests??[],gateway:e.pullRequestsGateway,sessionId:e.pullRequestsSessionId,sessionKey:ue(e.sessionKey,e.currentAgentId??void 0),presented:e.presented??!0,branch:e.pullRequestsBranch,branchDismissed:e.pullRequestsBranchDismissed,status:e.pullRequestsStatus??`ready`,onDismiss:t=>e.onDismissPullRequest?.(t),onDismissBranch:e.onDismissPullRequestsBranch,onOpenSessionDiff:e.onOpenSessionDiff,publication:e.githubPublication})}
  ${Bg({suggestions:e.sessionSuggestions??[],role:e.sessionSuggestionRole,busyIds:e.sessionSuggestionBusyIds??new Set,archived:e.sessionSuggestionsArchived===!0,canResolve:e.canResolveSessionSuggestions===!0,onResolve:(t,n)=>e.onResolveSessionSuggestion?.(t,n)})}
  ${e.swarm?Mg(e.swarm):U} ${b(`composer`)}`,S=KT(e);l.transcriptRenderContext.onAsyncQuestionSubmit=e.onAsyncQuestionSubmit,l.transcriptRenderContext.onAsyncQuestionDiscard=u.discard;let C=bl(e.messages,e.queue,i??[]),w=[...Sd(C.queuedInputs),...C.queue],T={...e,displayQueue:w},E=c_({...e,asyncQuestions:u,displayQueue:w,footerContent:x,notices:S,onRequestUpdate:a,onToggleRealtimeTalk:e.suggestionComposer?void 0:e.onToggleRealtimeTalk,onOpenImage:f}),D=nt(`composer`,{sessionKey:e.sessionKey,agentId:e.currentAgentId,draft:e.draft,canSend:e.canSend&&!e.submitDisabledReason,sending:e.sending,disabledReason:e.submitDisabledReason??e.disabledReason,setDraft:e.onDraftChange,send:async()=>e.onSend(),abort:e.onAbort},E,e.presented??!0,W`<div class="chat-footer__context">
      ${x}
      <div class="agent-chat__composer-notices">${S}</div>
      ${$h(k_({...e,asyncQuestions:u},mg(e.paneId),a))}
      ${d_(T,!!(e.canAbort&&e.onAbort)&&!Sg(e.runStatus))}
      ${e.suggestionComposer?U:Nu({...e,disabled:!c})}
      ${e.composerRecovery??U}
    </div>`),O=tg(e),k=O===U?U:W`<div class="chat-gutter-stack">${O}</div>`,ee=e.onScrollToBottom?W`
        <div class="chat-scroll-to-bottom-wrap">
          <button
            class="chat-scroll-to-bottom"
            data-visible=${!!e.showNewMessages}
            type="button"
            ?inert=${!e.showNewMessages}
            aria-hidden=${!e.showNewMessages}
            @click=${()=>e.onScrollToBottom?.({smooth:!0})}
            aria-label=${V(`chat.actions.scrollToLatest`)}
          >
            ${H.arrowDown}
          </button>
        </div>
      `:U,A=e.historyState,j=A?ks(A):void 0,te=A!==void 0&&j?.phase===`failed`&&j.sessionKey===e.sessionKey,ne=!_&&e.messages.length===0&&C.pendingInputs.length===0&&C.queuedInputs.length===0&&e.toolMessages.length===0&&e.streamSegments.length===0&&!e.stream&&g.length===0,M=t=>W`<div
      class="chat-history-error${t?` chat-history-error--inline`:``}"
      role=${t?`status`:`alert`}
    >
      <span>${j?.phase===`failed`?j.message:``}</span>
      <button
        class="btn btn--sm"
        type="button"
        @click=${()=>{A&&ks(A).phase===`failed`&&(e.onRefresh(),A.requestUpdate?.())}}
      >
        ${V(`common.retry`)}
      </button>
    </div>`,N=te&&ne?M(!1):U,P=te&&!ne?M(!0):U;return W`
    <section
      class="chat"
      style=${Or(e.chatMessageMaxWidth?{"--chat-thread-max-width":e.chatMessageMaxWidth,"--chat-message-max-width":`100%`}:{})}
      @drop=${p.onDrop}
      @dragenter=${p.onDragenter}
      @dragleave=${p.onDragleave}
      @click=${e=>ru(e,f)}
      @dragover=${p.onDragover}
      @keydown=${t=>{if(!ll(t)&&(t.key!==`Enter`&&t.key!==` `||!ru(t,f))){if(t.key===`Escape`&&e.replyTarget&&!t.defaultPrevented&&!t.isComposing&&t.keyCode!==229&&!mg(e.paneId).composerComposing){t.preventDefault(),e.onClearReply?.();return}lt(_e.transcriptSearch,t)&&(t.preventDefault(),Pg(e.paneId,a,t))}}}
    >
      ${e.suggestionComposer?U:W`<openclaw-chat-comment-controller
              .paneId=${e.paneId}
              .props=${e}
              .disabled=${!c}
              .sessionKey=${e.sessionKey}
              .presented=${Ge(e.presented??!0)}
            ></openclaw-chat-comment-controller>`}
      <div class="chat-workbench" ${gr({workbench:!0})}>
        <div class="chat-workbench__main">
          <div class="chat-split-container">
            <div class="chat-main">
              <div class="chat-main__conversation-column">
                ${GT(e)} ${b(`header`)}
                ${q_(e.paneId,a)}
                <div class="chat-main__conversation-frame">
                  <!-- Chromium can crash when DevTools inspects a blocking Lit object listener. -->
                  <div
                    class="chat-main__conversation"
                    .onwheel=${t=>sC(t,e.transcript.scrollElement)}
                  >
                    ${P} ${N===U?v:N}
                    ${ee} ${k}
                    <div class="chat-footer">${D}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  `}var eE;function tE(){return(tE=e((()=>{kr(),Dr(),sr(),vs(),Rn(),F(),oe(),R(),Be(),pt(),kt(),ht(),il(),af(),th(),Uu(),uC(),YT(),fg(),C_(),gl(),Ug(),jg(),a_(),Cg(),Lc(),sv(),Fc(),Jg(),Lg(),Fg(),H_(),G_(),lg(),sg(),Cu(),Cr(),eE=new WeakMap})))()}var nE;function rE(){return(rE=e((()=>{za(),kr(),dx(),Cn(),Fn(),Rn(),Po(),F(),Vh(),pa(),Ue(),R(),kt(),RT(),iT(),lS(),hT(),BT(),tE(),xy(),jg(),Ov(),Lc(),ov(),cc(),Yg(),vv(),nE=class extends LT{constructor(...e){super(...e),this.refreshProcesses=()=>{this.querySelector(`openclaw-chat-processes-panel`)?.refresh()},this.refreshSubagents=()=>{this.querySelector(`openclaw-chat-subagents-panel`)?.refresh()},this.toolIcons=new zT(this,()=>this.context,()=>this.state&&!this.catalogHost?this.resolveChatReadTarget():void 0),this.desktopFocus=null}renderChatPaneLayout(e){let{state:t,selectedSession:r,currentAgentId:i,board:a,sidebarLayout:o,sessionWorkspace:s,chatProps:c,observerDigest:l,observerRunId:u,catalog:d,agentWorkspace:f,workspaceGit:p,openPanelSlot:m,closePanelSlot:h}=e,g=this.presentSidebarLayout(o);if(this.inputRegion===`page`){let e=t.sessionWorkspaceState?.previews.find(e=>e.id===t.sessionWorkspaceState?.activePreviewId)?.content,n=e?.kind===`file`&&Ae(g,`workspace`)?e:void 0,a=xh({session:r,agentWorkspace:f,worktreePath:r?.worktree?this.headerWorktreePaths.get(r.worktree.id)?.path:void 0});_y(this.context,this,this.presented&&this.selected?{sessionKey:t.sessionKey,sessionId:t.currentSessionId??void 0,agentId:i,workspace:n?.root??a.root??void 0,file:n?.path}:void 0)}let _=c.disabledBanner?.kind===`composer-replacement`?U:W`<openclaw-chat-outbox-recovery
            .host=${t}
            .messages=${t.chatMessages}
            .identity=${JSON.stringify([t.settings.gatewayUrl,t.connected&&t.client?.recoveryScopeReady?t.client.recoveryScope:null,mt(I(t,t.sessionKey)),t.currentSessionId])}
            @outbox-restored=${()=>{this.chatState.composerPersistence.restore(),t.requestUpdate?.()}}
          ></openclaw-chat-outbox-recovery>`,v=Hh(c.messages,c.toolMessages),y={owner:this,isPresented:()=>this.presented},b=(e,t=`visible`)=>({owner:this,isPresented:()=>this.presented&&(t===`active`?this.active:this.visuallyPresented)&&Ae(g,e)}),x=!d&&!this.compact,S=$T({...c,onOpenSubagent:x?e=>this.showSubagents(e):void 0,onOpenSubagents:x?()=>this.showSubagents(null):void 0,composerRecovery:_,pluginToolIcons:this.toolIcons.icons,presented:{owner:this,isPresented:()=>(this.active||!!this.onBackToSubagents)&&this.presented},progressCardVisibility:y,transcriptVisible:b(`conversation`),latestBrowserTabs:this.active&&this.presented?v:void 0,historyState:d?void 0:t}),C=c.disabledBanner?.presentation&&c.canAbort&&c.onAbort&&!Sg(c.runStatus)?W`<button
            class="chat-subagent-detail__stop"
            type="button"
            aria-label=${V(`chat.runControls.stopGenerating`)}
            @click=${c.onAbort}
          >
            ${H.stop}<span>${V(`chat.runControls.stop`)}</span>
          </button>`:U,w=this.onBackToSubagents?W`<header class="chat-subagent-detail__header">
          <button class="chat-subagent-detail__back" type="button" @click=${this.onBackToSubagents}>
            ${H.arrowLeft}${V(`chat.subagentsPanel.back`)}
          </button>
          <div class="chat-subagent-detail__heading">
            <strong class="chat-subagent-detail__title"
              >${this.resolveHeaderSessionTitle(r)}</strong
            >
            ${C}
          </div>
        </header>`:U,T=this.buildSessionDiscussionPanel(t,t.sessionKey.trim()),E=this.sessionDiscussionStates.get(t.sessionKey.trim()),O=E===`available`||E===`open`,k=nr(this.context.gateway.snapshot),ee=t.sessionKey,A=this.sessionCompanionThreads.view(ee,i),j=b(`companion`);this.syncSessionCompanionPresentation(j.isPresented());let te=b(`desktop`),ne=this.activeSessionResources.desktopSource(t.client,t.sessionKey,D(t,t.sessionKey).agentId,t.connectionEpoch,this.resourceSessionObservation()?.row??void 0),M=g.columns.flatMap(e=>e.panels).find(e=>e.slot===`desktop`)?.environmentId??(ne===void 0?sS(r):ne),N=JSON.stringify([t.sessionKey,this.connectionGeneration,k,te.isPresented(),t.basePath]);(this.desktopFocus?.key!==N||this.desktopFocus.client!==t.client)&&(this.desktopFocus={key:N,client:t.client,href:no({kind:`desktop`,session:t.sessionKey},t.basePath)});let P=this.desktopFocus,re=rT({paneId:this.paneId,panePresentationId:this.presentationId,subagentsInputRegion:this.inputRegion,subagentsPresented:b(`subagents`),processesPresented:b(`processes`),onRefreshProcesses:this.refreshProcesses,subagentsAvailable:!d,subagentsShowRequest:this.subagentsShowRequest,onRefreshSubagents:this.refreshSubagents,onSubagentSessionSelect:(e,t)=>this.onPaneSessionChange?.(this.paneId,e,t),panePresentation:y,state:t,themeMode:this.context.theme.resolvedMode,agentId:i,browserPresented:b(`browser`,`active`),browserTabsInHeader:n(g)?.slot!==`browser`,linkReaders:ln(this.context.gateway.snapshot),linkReaderPresented:b(`link-reader`),linkReaderTabsInHeader:n(g)?.slot!==`link-reader`,onCloseLinkReader:()=>h(`link-reader`),terminalTabsInHeader:n(g)?.slot!==`terminal`,onCloseTerminal:()=>h(`terminal`),browserRefreshOnPresentation:!this.pendingPanelToggleRequests.has(`browser`),preferredBrowserTab:[...v.values()].at(-1),sessionBrowserTabs:[...v.values()].map(e=>e.tab),desktopPresented:te,desktopRefreshOnPresentation:!this.pendingPanelToggleRequests.has(`desktop`),desktopAvailable:k,desktopSource:M,desktopRuntimeConfig:this.context.runtimeConfig,portalPresented:b(`portal`),desktopFocusHref:P.href,onDesktopFocusTargetChange:e=>{let n=no(e,t.basePath);this.desktopFocus===P&&P.href!==n&&(P.href=n,this.requestUpdate())},dashboard:this.compact?U:this.renderBoardPanel(a,g),workspace:wv(s),renderDetail:e=>qg({chat:c,content:e,host:t,requestUpdate:t.requestUpdate}),digest:l,activeRunId:u,pullRequests:this.sessionPullRequests,companion:A,companionFocusRequest:this.sessionCompanionFocusRequest,companionPresented:j,onCompanionSubmit:e=>void this.submitSessionCompanionQuestion(e),onCompanionDraftChange:e=>this.sessionCompanionThreads.setDraft(t.sessionKey,e,i),onCompanionAttachmentsChange:e=>this.sessionCompanionThreads.setAttachments(ee,e,i),connected:t.connected,onClearCompanion:()=>void this.clearSessionCompanion(),discussion:T,discussionAvailable:O,discussionOpenUrl:T?.openUrl??null,discussionSourceGeneration:this.connectionGeneration,pluginPanels:this.context.plugins.registrations(`panels`),isPluginPanelPresented:e=>b(e,`active`)}),ie=this.connectionGeneration,ae=w===U?this.compact?U:W`${this.renderPaneHeader(s,r,d,f,p,c.placementStartup,o,re,C)}
              <openclaw-plugin-contributions
                .kind=${`session-header`}
                .sessionKey=${t.sessionKey}
                .agentId=${i}
                .presented=${Ge({owner:this,isPresented:()=>this.visuallyPresented,preview:()=>!this.presented&&this.connectionGeneration===ie})}
              ></openclaw-plugin-contributions>`:w,oe=sT({presentationId:this.presentationId,conversationTab:{label:c.assistantName,icon:zo(Pl(c))},availableWidth:this.paneWidth,fetchFavicon:ug(t),callbacks:oT({state:t,layout:o,closePanelSlot:h,openPanelSlot:m,forgetDiscussionUrl:()=>this.sessionDiscussionOpenUrls.delete(t.sessionKey.trim()),resizePanel:(e,t)=>this.commitSidebarPanelResize(o,e,t),setPanelOpen:e=>this.setChatSidePanelOpen(e,o)}),layout:g,sideFocusLocked:g!==o,sideFocusOrigin:this.sideFocusOrigin,panelDefinitions:re,narrow:this.paneWidth<680,header:ae,primary:W`<div class="chat-pane-primary-column">${S}</div>`,requestUpdate:t.requestUpdate}),se=ut(y,W`${oh(t.imageLightbox,t.handleCloseImage)}${this.renderResetConfirmation()}`);return this.onBackToSubagents?W`<section class="chat-subagent-detail">${oe}${se}</section>`:W`${oe}${se}`}}})))()}function iE(e,t){let n=Nd(e);return{editingId:n?.id??null,editingText:n?.draftText,editingMentions:n?.mentions,source:n?.source,onEdit:t?void 0:e.editQueuedChatMessage,onEditChange:t?void 0:e.updateQueuedChatMessageEdit,onEditSubmit:t?void 0:e.submitQueuedChatMessageEdit,onCancel:e.cancelQueuedChatMessageEdit}}function aE(e,t,n){let r=e.hello?.auth??null;return sn(r)||!n&&xe(r,{method:`chat.send`,requiredScope:`operator.write`,sessionScope:!0,session:t}).allowed}function oE(e,t,n){let r=r=>b(e,{method:`sessions.patch`,params:{key:t,...r},sessionScope:!0,session:n});return{model:r({model:null}),effort:r({thinkingLevel:null}),contextWindow:b(e,{method:`sessions.patch`,params:{key:t,contextWindow:null}}),permission:r({permissionMode:`guarded`}),unarchive:r({archived:!1})}}function sE(e,t,n){let r=!t.archived&&!n;return{canPublishShared:r&&b(e,{method:`sessions.github.publish`,requiredScope:`operator.sessions.write`,session:t}).allowed,canPublishPersonal:r&&sn(e.hello?.auth??null)}}function cE(e){let{state:t,selectedSession:n,agentDefaultModel:r,agentDefaultPermissionMode:i,modelAccess:a,effortAccess:o,contextWindowAccess:s,permissionAccess:c,canSelectFull:l,onModelSetup:u,onProviderSettings:d,onModelAccounts:f}=e,p=t.sessionKey,m=t.client,h=t.chatAccountSelection,g=t.connectionEpoch,_=D(t,p),v=wt(t,p).agentId,y=n?.sessionId?.trim(),x=JSON.stringify([p,_.agentId]),S=uE.get(t)??new Map;uE.set(t,S);let C=()=>t.connected&&t.sessionKey===p&&t.client===m&&t.connectionEpoch===g&&D(t,p).agentId===_.agentId,w=()=>{let e=Z(t);return C()&&!!e==!!n&&e?.sessionId===y},T=(e,n=p)=>z(n,p)&&w()&&b({client:t.client,hello:t.hello,phase:t.connected?`connected`:`offline`},{method:`sessions.patch`,params:{key:p,...e},sessionScope:!0,session:Z(t)}).allowed,E=S.get(x);E&&E.expectedSessionId!==y&&(S.delete(x),E=void 0),E?.retainWhileCurrent&&!E.retainWhileCurrent()&&(S.delete(x),E=void 0);let O=E?.ownsSelection()?E:void 0,k=!!(O&&!O.retainWhileCurrent||n?.permissionModePending),ee=ic({models:t.chatModelCatalog,refreshFailed:t.chatModelCatalogRefreshFailed,pendingProviders:t.chatModelCatalogPendingProviders,modelSelectionPolicy:t.chatModelSelectionPolicy},{connected:t.connected,loading:t.chatModelsLoading,error:t.chatModelCatalogError,retired:t.chatModelCatalogRetired,initialized:t.chatModelCatalogInitialized}),A=t.sessions.think(p,_.agentId),j=t.sessions.settingsPreview(p,_.agentId),te=A||j?{...n,...A?{thinkingLevel:A}:{},...j}:n;return{composerControls:W`
      <div class="chat-composer-model-control">
        ${$m({modelAuthStatusResult:t.modelAuthStatusResult,accountSelection:h,renderAccountSection:e=>xu({owner:t,client:m,selection:h,modelAuthStatusResult:t.modelAuthStatusResult,model:e,disabled:!a.allowed||!t.connected||!e||n?.modelSelectionLocked===!0||t.chatLoading||t.chatSending||!!t.chatRunId||t.chatStream!==null||!!t.chatModelSwitchPromises[p],ownsSelection:()=>w()&&t.chatAccountSelection===h,onSelect:n=>a.allowed&&T({model:`${e}@${n.authProfileId}`})?qd(t,`${e}@${n.authProfileId}`,p):Promise.resolve(!1),onManage:f,onRequestUpdate:()=>t.requestUpdate?.()}),activeRunId:t.chatRunId,activeRunSessionKey:qs(t),modelObservedRunId:mu(t,n),agentDefaultModel:r,connected:t.connected,gatewayAvailable:!!t.client,loading:t.chatLoading,modelCatalog:t.chatModelCatalog,modelCatalogState:ee,modelOverrides:t.sessions.state.modelOverrides,thinkingSession:te,fastModeTarget:te,contextWindowTarget:j?{...n??t.sessionsResult?.defaults,...j}:void 0,modelSelectionLocked:n?.modelSelectionLocked===!0,modelSelectionTarget:t.sessionsResult?.defaults.modelSelectionTarget,modelPickerOpen:t.chatModelPickerOpenSessionKey===t.sessionKey,modelSwitching:!!t.chatModelSwitchPromises[t.sessionKey],modelMutationDisabledReason:a.allowed?void 0:a.reason,effortMutationDisabledReason:o.allowed?void 0:o.reason,contextWindowMutationDisabledReason:s.allowed?void 0:s.reason,sending:t.chatSending&&t.chatSendingScopeKey===mt({sessionKey:p,..._.agentId?{agentId:_.agentId}:{}}),sessionKey:t.sessionKey,selectedSession:n,sessionsResult:t.sessionsResult,stream:t.chatStream,onRequestUpdate:()=>t.requestUpdate?.(),onModelSetup:u,onProviderSettings:d,onFastModeSelect:(e,n)=>o.allowed&&T({fastMode:null},n)?cp(t,{kind:`fastMode`,value:e},n):Promise.resolve(!1),onContextWindowSelect:(e,n)=>s.allowed&&T({contextWindow:e},n)?cp(t,{kind:`contextWindow`,value:e},n):Promise.resolve(!1),onModelPickerOpen:()=>lw(t),onModelPickerOpenChange:e=>{t.chatModelPickerOpenSessionKey=e?t.sessionKey:null,t.requestUpdate?.()},onModelSelect:(e,n,r)=>a.allowed&&T({model:e,agentRuntime:r},n)?qd(t,e,n,r):Promise.resolve(!1),onThinkingSelect:(e,n)=>o.allowed&&T({thinkingLevel:e},n)?cp(t,{kind:`thinkingLevel`,value:e},n):Promise.resolve(!1)})}
      </div>
    `,permissionPicker:{canSelectFull:l,defaultMode:i,disabled:!c.allowed,disabledReason:c.allowed?void 0:c.reason,mode:O?O.nextMode:n?.permissionMode,pending:k,onSelect:async e=>{let r=S.get(x);if(!c.allowed||!T({permissionMode:e})||n?.permissionModePending||r&&!r.retainWhileCurrent&&r.ownsSelection())return;let i={expectedSessionId:y,nextMode:e??void 0,ownsSelection:w},a=Symbol(x),o=dE.get(t)??new Map;dE.set(t,o),o.set(x,a);let s=()=>o.get(x)===a;S.set(x,i),t.requestUpdate?.();try{t.chatError=t.lastError=null;let n=await _f(t,p,{permissionMode:e},{..._,expectedSessionId:y,canDispatch:()=>T({permissionMode:e})});if(!w())return;if(!n)throw Error(`Session capability is unavailable`);n.listRefreshError&&s()&&(t.chatError=t.lastError=V(`chat.permissionControls.refreshFailed`,{error:n.listRefreshError}))}catch(e){if(!C()||!s())return;let n=t.sessions.capturePermissionObservation(p,v),r=await t.sessions.reconcileMutation(v);if(!w()||!s())return;r.status!==`refreshed`&&(i.retainWhileCurrent=n),t.chatError=t.lastError=V(`chat.permissionControls.updateFailed`,{error:String(e)})}finally{s()&&o.delete(x),S.get(x)===i&&i.retainWhileCurrent===void 0&&S.delete(x),C()&&t.requestUpdate?.()}}}}}function lE(e){let{state:t}=e,n=t.client,r=e.getSnapshot().hello?.auth?.recoveryScope??n?.recoveryScope,i=t.sessionKey,a=Z(t),o=a?.sessionId,s=D(t,i).agentId,c=t.chatRunId??null,l=c?void 0:a?.activeRunIds?.slice(),u=t.chatRunSessionAbortable===!0,d=()=>{let a=Z(t),d=e.getSnapshot(),f=d.hello?.auth?.recoveryScope??(d.phase!==`connected`||n?.recoveryScopeReady?n?.recoveryScope:void 0);return t.client===n&&d.client===n&&r===f&&t.sessionKey===i&&D(t,i).agentId===s&&(t.chatRunId??null)===c&&t.chatRunSessionAbortable===!0===u&&(!o||!a?.sessionId||a.sessionId===o)&&(!l||a?.activeRunIds?.length===l.length&&l.every(e=>a?.activeRunIds?.includes(e)))},f=()=>{let n=e.getSnapshot(),i=!!t.chatRunId,a=lf(n,i,{session:Z(t),sessionAbortable:t.chatRunSessionAbortable===!0});return n.client&&i&&r&&!a.abort.allowed&&a.abort.cause===`disconnected`&&(a.abort={allowed:!0,requiredScope:`operator.write`}),a},p=f(),m=t=>{let n=f()[t];return n.allowed?!0:(e.onDenied(n.reason),!1)};return{onAbort:e.sessionParticipationBlocked||!p.abort.allowed?void 0:()=>{d()&&m(`abort`)&&e.onAbort()},onRewindMessage:p.rewind.allowed?t=>m(`rewind`)?e.onRewind(t):!1:void 0,onForkMessage:p.fork.allowed?t=>m(`fork`)?e.onFork(t):void 0:void 0}}var uE,dE;function fE(){return(fE=e((()=>{kr(),Tr(),F(),ka(),pa(),Ym(),Ce(),Ue(),R(),bs(),Vf(),ef(),pw(),Q(),Fm(),Dm(),Cu(),Yd(),ia(),uE=new WeakMap,dE=new WeakMap})))()}var pE;function mE(){return(mE=e((()=>{kr(),Rn(),F(),zt(),R(),Ua(),rd(),cf(),ho(),pE=class{constructor(e,t){this.host=e,this.readState=t,this.canWrite=!1,this.binding=null,e.addController(this)}hostDisconnected(){this.binding=null}isCurrent(e){let t=this.readState(),n=t&&$c(t),r=n?.providerReview;return this.binding===e&&t===e.state&&t.connected&&t.client===e.client&&t.connectionEpoch===e.connectionEpoch&&t.client?.connectionGeneration===e.connectionGeneration&&t.sessionKey===e.sessionKey&&Ne(t)===e.agentId&&n?.sessionId===e.sessionId&&(!t.currentSessionId||t.currentSessionId===e.sessionId)&&r?.id===e.review.id&&r.runId===e.review.runId&&r.explanation===e.review.explanation&&r.continuationMessage===e.review.continuationMessage&&r.canContinue===e.review.canContinue}sync(e){if(this.canWrite=e,this.binding&&this.isCurrent(this.binding)){this.reconcileTerminalAttempt(this.binding);return}this.binding=null;let t=this.readState(),n=t&&$c(t);t?.connected&&n?.sessionId&&n.providerReview&&(this.binding={state:t,sessionKey:t.sessionKey,sessionId:n.sessionId,agentId:Ne(t),client:t.client,connectionEpoch:t.connectionEpoch,connectionGeneration:t.client?.connectionGeneration,review:n.providerReview,open:!1,loading:!1,pending:!1,submitted:!1,refreshing:!1,error:null,idempotencyKey:mo(),attemptedRunId:null})}reconcileTerminalAttempt(e){if(e.pending||e.refreshing||!e.attemptedRunId)return;let t=$c(e.state);!t||t.lastRunId!==e.attemptedRunId||t.hasActiveRun!==!1||t.activeRunIds?.length||t.status!==`failed`&&t.status!==`timeout`&&t.status!==`killed`||this.recordFailedAttempt(e,t.lastRunError)}recordFailedAttempt(e,t){e.submitted=!1,e.attemptedRunId=null,e.idempotencyKey=mo(),e.error=[V(`chat.providerReview.continuationFailed`),t?B(t):null].filter(Boolean).join(` `)}clearCurrentFlag(e,t){this.isCurrent(e)&&(e[t]=!1,this.host.requestUpdate())}async open(e){if(this.isCurrent(e)&&!e.loading){e.loading=!0,this.host.requestUpdate();try{await _o(()=>import(`./control-ui-core-DtLivg_r.js`).then(e=>(e.qr(),e.Jr)),__vite__mapDeps([0,5]),import.meta.url),this.isCurrent(e)&&(e.open=!0)}catch(t){this.isCurrent(e)&&(e.error=B(t))}finally{this.clearCurrentFlag(e,`loading`)}}}async acknowledge(e){if(this.isCurrent(e)&&e.open&&this.canWrite&&!e.pending&&!e.submitted&&e.review.canContinue&&e.review.explanation?.trim()&&e.review.continuationMessage?.trim()){if(!fd(e.state,e.sessionKey,e.agentId)){e.error=V(`chat.providerReview.queueHoldFailed`),this.host.requestUpdate();return}e.pending=!0,e.attemptedRunId=e.idempotencyKey,e.error=null,this.host.requestUpdate();try{let t=await e.client.request(`sessions.providerReview.continue`,{sessionKey:e.sessionKey,...e.agentId?{agentId:e.agentId}:{},sessionId:e.sessionId,reviewId:e.review.id,idempotencyKey:e.idempotencyKey});if(!this.isCurrent(e))return;let n=Cp(t,e.idempotencyKey);if(mm(n)){this.recordFailedAttempt(e);return}e.attemptedRunId=n.runId,e.submitted=!0,await this.refresh(e)}catch(t){this.isCurrent(e)&&(e.error=B(t))}finally{this.clearCurrentFlag(e,`pending`)}}}async refresh(e){if(this.isCurrent(e)&&e.submitted&&!e.refreshing){e.refreshing=!0,e.error=null,this.host.requestUpdate();try{let t=await e.state.sessions.reconcileMutation(e.agentId);this.isCurrent(e)&&t.status===`failed`&&(e.error=V(`chat.providerReview.refreshFailed`))}catch{this.isCurrent(e)&&(e.error=V(`chat.providerReview.refreshFailed`))}finally{this.clearCurrentFlag(e,`refreshing`)}}}notice(){let e=this.readState(),t=e&&$c(e)?.providerReview;if(!t)return U;let n=this.binding,r=!!t.explanation?.trim();return W`
      <div
        class="chat-composer-neighbor-card chat-composer-neighbor-card--warn chat-provider-review"
        role="alert"
      >
        <span class="chat-composer-neighbor-card__icon" aria-hidden="true"
          >${H.alertTriangle}</span
        >
        <div class="chat-composer-neighbor-card__copy">
          <strong
            >${V(t.canContinue?`chat.providerReview.pausedTitle`:`chat.providerReview.stoppedTitle`)}</strong
          >
          <span
            >${V(r?t.canContinue?`chat.providerReview.pausedBody`:`chat.providerReview.stoppedWithFindingsBody`:`chat.providerReview.stoppedBody`)}</span
          >
          ${n?.error&&!n.open?W`<span>${n.error}</span>`:U}
        </div>
        ${r?W`<button class="btn btn--sm" type="button" ?disabled=${!n||n.loading} @click=${()=>n&&void this.open(n)}>${V(`chat.providerReview.review`)}</button>`:U}
      </div>
    `}dialog(){let e=this.binding;if(!e?.open||!this.isCurrent(e))return U;let{review:t}=e,n=t.canContinue&&!!(t.explanation?.trim()&&t.continuationMessage?.trim()),r=()=>this.clearCurrentFlag(e,`open`);return W`
      <openclaw-modal-dialog label=${V(`chat.providerReview.review`)} @modal-cancel=${r}>
        <section class="exec-approval-card chat-provider-review-dialog">
          <h2 class="exec-approval-title">
            ${V(n?`chat.providerReview.pausedTitle`:`chat.providerReview.stoppedTitle`)}
          </h2>
          <div class="chat-provider-review-dialog__content">
            ${n?W`
                    <h3>${V(`chat.providerReview.continuationTitle`)}</h3>
                    <p>${V(`chat.providerReview.continuationBody`)}</p>
                    <blockquote
                      class="chat-provider-review-dialog__text"
                      .textContent=${t.continuationMessage}
                    ></blockquote>
                  `:W`<p>${V(`chat.providerReview.noContinuation`)}</p>`}
            <h3>${V(`chat.providerReview.findings`)}</h3>
            <div class="chat-provider-review-dialog__text">${t.explanation}</div>
            <p>
              ${V(n?`chat.providerReview.queueHelp`:`chat.providerReview.queueStopped`)}
            </p>
            ${e.error?W`<p class="callout danger" role="alert">${e.error}</p>`:U}
            ${e.submitted&&!e.error?W`<p role="status">${V(e.refreshing?`chat.providerReview.checkingStatus`:`chat.providerReview.waiting`)}</p>`:U}
          </div>
          <div class="exec-approval-actions">
            <button type="button" class="btn" autofocus @click=${r}>
              ${V(`common.close`)}
            </button>
            ${e.submitted?W`<button type="button" class="btn" ?disabled=${e.refreshing} @click=${()=>void this.refresh(e)}>${V(e.refreshing?`chat.providerReview.checkingStatus`:`chat.providerReview.checkStatus`)}</button>`:U}
            ${n?W`<button type="button" class="btn primary" ?disabled=${!this.canWrite||e.pending||e.submitted} @click=${()=>void this.acknowledge(e)}>${V(e.pending&&!e.submitted?`chat.providerReview.continuing`:`chat.providerReview.acknowledge`)}</button>`:U}
          </div>
        </section>
      </openclaw-modal-dialog>
    `}}})))()}function hE({state:e,questionState:t,canSend:n,isCurrent:r}){let i=e.sessionKey,a=e.connectionEpoch,o=()=>e.sessionKey===i&&e.connectionEpoch===a&&r();return{onGatewayQuestionChange:t.onChange,onGatewayQuestionSubmit:(e,n)=>Oo(t,e,n),onGatewayQuestionSkip:e=>Yo(t,e),onAsyncQuestionSubmit:n?async(t,n,r)=>{if(!o())return!1;if(n&&e.chatQueue.some(e=>e.asyncQuestionItemId===n))return!0;let i=!1,a;try{a=await e.handleSendChat(t,{followUpMode:`steer`,asyncQuestionItemId:n,replyTargetOverride:r?{messageId:r,sourceMessageId:r,text:``}:null,onOutboxAdmitted:()=>{i=!0}})}catch(e){if(!i)throw e}if(!o())return!1;if(!i&&!a&&e.lastError)throw Error(e.lastError);return i||a===!0}:void 0}}function gE(){return(gE=e((()=>{Mo()})))()}var _E;function vE(){return(vE=e((()=>{kr(),Fv(),Mn(),Hn(),Tr(),Jn(),fs(),ys(),rs(),F(),pi(),di(),lm(),Ed(),_t(),Sh(),Ue(),R(),cx(),af(),Fl(),rE(),Zx(),fE(),hT(),NS(),mE(),gE(),RS(),Uu(),tp(),pw(),Q(),jg(),ov(),Yg(),gc(),Hs(),Gl(),y_(),_E=class extends nE{constructor(...e){super(...e),this.providerReview=new pE(this,()=>this.state??void 0),this.presentationUserId=null,this.emptyTranscriptItems=[],this.retrySessionPlacementStartup=()=>{let e=this.state?.sessionKey;e&&this.context.placementStartup.retry(e)}}render(){let e=this.state;if(!e)return W`<main class="app-shell app-shell--booting" aria-busy="true"></main>`;let t=this.connectionGeneration,n=Z(e),r=!!n?.providerReview,i=this.resolveChatReadTarget(),a=this.progressCardPresentation,o=this.isCurrentSessionArchived(e),s=oE(this.context.gateway.snapshot,e.sessionKey,n),c=zu(e.observerDigest,Nc(n?.key??e.sessionKey,n?.observerDigest)),l=Au({localRunId:e.chatRunId,session:n,digest:c}),u=kv(n?.placement),d=n?.placement,f=u&&this.dismissedWorkspaceConflictRefs.get(n?.key??e.sessionKey)!==u.stagedResultRef?u:void 0,p=this.resolveBoardView(),m=cT({board:p,layout:e.sidebarLayout,paneWidth:this.paneWidth});e.chatFollowUpMode=AS(e,n,this.context.runtimeConfig.state);let h=Y(e),g=L(e.sessionKey),_=g!==null,v=this.context?.overlays,y=this.context.agents.state.agentsList?.agents.find(e=>e.id===h),b=y?.model?.primary,{modelSetupRequired:x,modelUnavailableBanner:S,requiredReason:C}=As({activeSession:n,chatModelCatalog:e.chatModelCatalog,modelOverrides:e.sessions.state.modelOverrides,sessionKey:e.sessionKey,sessionsResult:e.sessionsResult,catalog:_,connected:e.connected,agentsLoaded:this.context.agents.state.agentsList!==null,selectedAgentFound:y!==void 0,agentModel:b,modelSelectionPolicy:e.chatModelSelectionPolicy,catalogRetired:e.chatModelCatalogRetired,catalogInitialized:e.chatModelCatalogInitialized,catalogError:e.chatModelCatalogError,onSetup:()=>this.context.navigate(`model-setup`)}),w=this.context.placementStartup.get(e.sessionKey),T=hc(e,e.sessionKey,w!==null),E=Hl(e),O=this.sessionParticipationTracker.resolve({catalog:_,listLoading:e.sessionsLoading,sessionKey:`${h??``}\0${e.sessionKey}`,session:n}),k=this.context.gateway.snapshot,ee=aE(k,n,_),A=sn(k.hello?.auth??null),j=this.placementComposerPresentation(n,w!==null),te=e.connected&&!O&&A;this.providerReview.sync(te&&!o);let ne=n?.restartRecoveryStatus===`tombstoned`,M=this.hasMultipleIdentities(),N=M&&!o&&A&&n?.visibility===`suggest`&&n.sharingRole===`viewer`&&K(k,`session.suggestions.add`)===!0&&K(k,`session.suggestions.list`)===!0,P=!g&&!N?n?.sendDisabledReason??(O?V(`chat.sessionSharing.readOnlyNotice`):null):null,re=g||N?void 0:C,ie=M&&A&&!g&&K(k,`session.typing`)===!0&&Np(this.presencePayload,k.selfUser,k.client?.instanceId,e.sessionKey),ae=g&&!this.catalogLoading&&this.catalogSession?.canContinue!==!0?this.catalogHost?.kind===`node`?V(`chat.catalog.remoteViewOnly`):V(`chat.catalog.unsupportedViewOnly`):null,{closePanelSlot:oe,openPanelSlot:se,sessionWorkspace:ce}=Xx({state:e,sidebarLayout:m,presentationId:this.presentationId,sessionTitle:this.resolveHeaderSessionTitle(n),paneLabel:this.paneLabel,presented:this.presented,gatewaySnapshot:k,setObserverVisibility:this.setSessionObserverVisibility,updateSidebarLayout:e=>this.commitSidebarLayout(e)}),F=Qn({snapshotUser:k.selfUser,presenceEntries:an(this.presencePayload),presenceInstanceId:k.client?.instanceId});F?.identity?.type===`profile`&&(this.presentationUserId=F.identity.id);let le=Vc({localRunId:e.chatRunId,activeRunIds:n?.activeRunIds,queue:e.chatQueue}),ue=g?!!this.catalogCursor:e.chatHistoryPagination.hasMore,de=lE({getSnapshot:()=>this.context.gateway.snapshot,state:e,sessionParticipationBlocked:O,onDenied:e=>this.publishHeaderError(e),onAbort:()=>void e.handleAbortChat({preserveDraft:!0}),onRewind:e=>this.rewindToMessage(e),onFork:e=>this.forkFromMessage(e)}),fe=t=>{e.chatReplyTarget=t,e.handleChatDraftChange(e.chatMessage),e.requestUpdate?.()},pe=this.currentReplyMessageAccess(e.sessionKey),me=g?void 0:cE({state:e,selectedSession:n,agentDefaultModel:b,agentDefaultPermissionMode:y?.defaultPermissionMode,modelAccess:s.model,effortAccess:s.effort,contextWindowAccess:s.contextWindow,permissionAccess:s.permission,canSelectFull:Er(k.hello?.auth??null),onModelSetup:()=>this.context.navigate(`model-setup`),onProviderSettings:e=>wf(this.context,h,e),onModelAccounts:()=>this.context.navigate(`profile`)}),he=mg(this.presentationId),ge=Mm(this.context.gateway).snapshot,_e=this.captureConnectionScope(),ve=()=>{let t=Z(e);return t&&{...t,agentId:t.agentId??Y(e)??void 0,archived:this.isCurrentSessionArchived(e)}},be=ve();if(!_e||!be||K(k,`sessions.github.publish`)!==!0||!ui(k,`sessions.github.options`,`operator.read`))this.githubPublication?.detach(),this.githubPublication=null;else{this.githubPublication?.matches(be)||(this.githubPublication?.detach(),this.githubPublication=this.context.sessions.githubPublication.attach(be,()=>this.requestUpdate(),bh));let t=this.githubPublication;t?.sync({...sE(k,be,O),personalReady:!Dl(e)&&(!Br(d?.state)||!!be.repositoryWorkspaceId&&d?.state===`active`)&&!u,isPresented:()=>this.presented,isCurrent:()=>{let e=ve();return this.isConnectionScopeCurrent(_e)&&e!==void 0&&t?.matches(e)}})}let xe=this.sessionDisabledBanner({catalogDisabledReason:ae,modelSetupRequired:x,restartRecoveryTombstoned:ne,selectedSessionArchived:o,selectedSessionId:n?.sessionId?.trim()||void 0,selectedSession:n,sessionKey:e.sessionKey,unarchiveAccess:s.unarchive}),Se=!g&&Zp(e),Ce=!r&&xe?.kind!==`composer-replacement`&&(g?this.catalogSession?.canContinue===!0:!P&&!(o||ne||j.blocksSend)&&(!T||Se)),we={canCompose:ee&&Ce,canSend:ee&&Ce,...kS(e,Se,!_&&!N),modelRequiredReason:re,disabledReason:ae??(ee?null:V(`chat.sessionSharing.scopeReadOnlyNotice`))??P??j.busyMessage??(j.state.kind===`failed`&&!j.state.recoveryAction?j.failedUnavailableMessage:null)??(e.connected&&(w||Se)?null:T),disabledReasonTone:!ee||P||j.busyMessage||O&&!N?`info`:`danger`,disabledReasonBusy:j.busyMessage!==null,disabledBanner:xe??j.disabledBanner??S},Te=te&&we.canSend&&!g&&!N&&a?this.captureProgressCardRefreshAction():void 0,Ee=F?.identity?.type===`profile`?F.identity.id:null,I=!!(g||N||n?.incognito||!Ee),{gatewayQuestionPrompts:De,inlineApproval:Oe}=this.projectConversationAttention(e,h,!g&&!O),ke={transcript:this.transcript,paneId:this.presentationId,sessionKey:e.sessionKey,announceTranscript:this.active&&this.presented,autoExpandToolCalls:e.chatVerboseLevel===`full`,showThinking:e.settings.chatShowThinking,showToolCalls:e.settings.chatShowToolCalls,persistCommentary:e.settings.chatPersistCommentary!==!1,loading:g?this.catalogLoading:e.chatLoading||!E&&T!==null&&w===null,routeLoadingSkeleton:this.routeLoadingSkeleton&&Se,sending:w!==null&&w.phase!==`failed`||e.chatSending||this.recoveringSession||this.sessionSuggestionAddOperation!==void 0,placementStartup:w??j.startup,onRetrySessionPlacementStartup:w?.retryable?this.retrySessionPlacementStartup:void 0,canAbort:!O&&Dl(e),runActive:E,runStatus:e.chatRunStatus,startupStatus:Mc(e.chatRunStartup),waitingApproval:e.waitingApprovalStatuses.size>0,compactionStatus:e.compactionStatus,fallbackStatus:e.fallbackStatus,providerPolicyNotice:g?null:e.providerPolicyNotice,providerReviewNotice:this.providerReview.notice(),progressCard:a?.card??null,progressCardIdentity:a?.identity,progressCardLifetime:a?.lifetime,gatewayScope:yr(this.context.gateway),progressCardInitialLoading:this.progressCardInitialLoading,progressCardRefresh:Te,collapseTaskProgress:e.settings.chatCollapseTaskProgress===!0,readingHistory:e.chatReadingHistory,onProgressManipulate:()=>{Bu(e),this.transcript.cancelScroll()},onDismissProgressCard:a?e=>this.hideProgressCard(e):void 0,onClearSavedProgressCard:te?this.clearSavedProgressCard:void 0,gatewayQuestionPrompts:De,asyncQuestionStorage:!g&&!N?this.chatState.composerPersistence.durableScope:null,...hE({state:e,questionState:this.questionPromptState,canSend:we.canSend&&!g&&!N&&e.connected,isCurrent:()=>this.state===e}),messages:g?this.catalogMessages:e.chatMessages,historyPagination:ue||this.loadingOlder?{hasMore:ue,loading:this.loadingOlder||(g?this.catalogLoading:e.chatLoading),onShowEarlier:()=>void this.loadOlderMessages()}:void 0,toolMessages:g?this.emptyTranscriptItems:e.chatToolMessages,guardianNotices:g?this.emptyTranscriptItems:e.guardianNotices,streamSegments:g?this.emptyTranscriptItems:e.chatStreamSegments,stream:g?null:e.chatStream,streamStartedAt:g?null:e.chatStreamStartedAt,runId:g?null:le,runUsageById:g?void 0:e.chatRunUsageById,assistantAvatarUrl:qx(e),sendShortcut:e.settings.chatSendShortcut,followUpMode:e.chatFollowUpMode,draft:e.chatMessage,mentions:e.chatMentions,getMentions:()=>e.chatMentions??[],mentionsUnsupported:I,mentionDirectory:e.connected&&e.client&&!I&&!O?{client:e.client,ownerKey:JSON.stringify([e.connectionEpoch,Ee]),params:{sessionKey:e.sessionKey,agentId:h}}:void 0,modelCatalog:e.chatModelCatalog,modelSwitching:!!e.chatModelSwitchPromises[e.sessionKey],queue:e.chatQueue,queuedOutboxCount:e.chatQueue.filter(e=>!e.pendingRunId).length,realtimeTalkActive:e.realtimeTalkActive,realtimeTalkStatus:e.realtimeTalkStatus,realtimeTalkDetail:e.realtimeTalkDetail,realtimeTalkInputNotice:e.realtimeTalkInputNotice,realtimeTalkInputLevel:e.realtimeTalkInputLevel,realtimeTalkConversation:e.realtimeTalkConversationState.entries,realtimeTalkVideoStream:e.realtimeTalkVideoStream,realtimeTalkCameraDevices:e.realtimeTalkCameraDevices,realtimeTalkVideoCapable:e.realtimeTalkVideoCapable,realtimeTalkVideoPending:e.realtimeTalkVideoPending,realtimeTalkCameraError:e.realtimeTalkCameraError,connected:e.connected,offline:k.offlineStable,gatewayClient:e.client,composerHoldToRecord:e.settings.composerHoldToRecord,realtimeTalkInputDeviceId:e.settings.realtimeTalkInputDeviceId,onComposerHoldToRecordChange:t=>{e.settings=wr({composerHoldToRecord:t})},onOpenTalkSettings:()=>this.context.navigate(`talk`),onOpenDictationSettings:()=>this.context.navigate(`model-setup`),suggestionComposer:N,typingActors:M?this.typingActorViews():[],typingOverflow:M?this.typingOverflow:void 0,onTypingChange:ie?(e,t)=>this.sendTypingState(e,t):void 0,...we,modelSetupRequired:x&&!o&&!ne,onModelSetup:()=>this.context.navigate(`model-setup`),error:r?null:e.lastError,diskSpace:j.diskSpace,workerRuntimeInstall:j.workerRuntimeInstall,runError:g||r?null:e.chatRunError??j.runError,inlineApproval:Oe,approvalBusy:v?.snapshot?.approvalBusy,approvalCanGrant:v?.snapshot?.approvalCanGrant??!1,approvalErrors:v?.snapshot?.approvalErrors,onApprovalDecision:v&&!O?(e,t)=>v.decideApproval(t,e,Oe??void 0):void 0,workspaceConflict:f,onDismissWorkspaceConflict:f&&n?()=>{this.dismissedWorkspaceConflictRefs.set(n.key,f.stagedResultRef),this.requestUpdate()}:void 0,sessions:e.sessionsResult,selectedSession:g?void 0:n,toolOverrides:n?.toolOverrides,capabilityMenu:g?void 0:this.composerCapabilities.props(this.context,e,n,h,he.capabilityMenuView.startsWith(`tools:`),he.capabilityMenuOpen&&(he.capabilityMenuView===`skills`||he.capabilityMenuView.startsWith(`library:`))),...this.projectChildRoster(i),sessionHost:{assistantAgentId:e.assistantAgentId,agentsList:e.agentsList,hello:e.hello},providerUsage:{basePath:e.basePath,modelAuthStatusResult:e.modelAuthStatusResult},composerControls:me?.composerControls??U,permissionPicker:me?.permissionPicker,...this.suggestionChatProps(e.connected,o,M),messageReactions:this.messageReactions,onReact:this.canReactToCurrentSession()?this.handleMessageReaction:void 0,pullRequests:this.visibleSessionPullRequests,pullRequestsGateway:this.context.gateway,pullRequestsSessionId:n?.sessionId,pullRequestsBranch:this.sessionPullRequestsBranch,pullRequestsBranchDismissed:this.sessionPullRequestsBranchDismissed,pullRequestsStatus:this.sessionPullRequestsStatus,onDismissPullRequest:this.dismissSessionPullRequest,onDismissPullRequestsBranch:this.dismissSessionPullRequestsBranch,githubRepo:ge.result?this.githubRepo:null,githubRepositories:ge.repositories,onOpenSessionDiff:ce.onOpenDiff,githubPublication:this.githubPublication?.view(),onOpenWorkspaceFile:t=>Q_(e,t),onOpenSessionLink:e=>Wo(this.context,e),onNavigate:(e,t)=>this.context.navigate(e,t),onRefresh:this.refreshHistory,onChatScroll:e=>this.handleTranscriptScroll(e),onHistoryIntent:e=>this.handleTranscriptHistoryIntent(e),onAssistantAttachmentLoaded:()=>Wu(e),getDraft:()=>e.chatMessage,onRequestUpdate:e.requestUpdate,onHistoryKeydown:e.handleChatInputHistoryKey,onSlashIntent:()=>QC(e),onSlashCommand:N||g?void 0:t=>void e.handleSendChat(t),showNewMessages:e.chatNewMessagesBelow,onScrollToBottom:e.scrollToBottom,...this.chatState.attachmentInputProps(e),cameraActive:this.conversationPresented,onRemoveAttachment:this.removeBrowserAnnotation,onSend:(t,n)=>!we.canSend||re&&(e.chatAttachments.length>0||!Aa(e.chatMessage))?void 0:g?this.continueCatalogSession(g):N?this.addCurrentSessionSuggestion():e.handleSendChat(void 0,t?{followUpMode:t}:void 0,n),onUseSystemDefaultMicrophone:e.realtimeTalkUseSystemDefault??void 0,onToggleRealtimeTalk:()=>r?void 0:void e.toggleRealtimeTalk(),onToggleRealtimeCamera:()=>void e.toggleRealtimeTalkCamera(),onSwitchRealtimeCamera:()=>void e.switchRealtimeTalkCamera(),onDismissError:()=>{OS(e),e.requestUpdate?.()},onDismissRealtimeTalkError:()=>{IS(e),e.requestUpdate?.()},onDismissRealtimeTalkInputNotice:()=>{e.realtimeTalkInputNotice=null,e.requestUpdate?.()},onAbort:de.onAbort,onQueueRemove:e.removeQueuedMessage,onQueueRetry:r?void 0:t=>void e.retryQueuedChatMessage(t),onQueueSteer:O||r?void 0:t=>void e.steerQueuedChatMessage(t),onQueueMove:O?void 0:e.moveQueuedChatMessage,queuedEdit:iE(e,O),goalRecovery:tx(e),onGoalAction:(t,n)=>void rx(e,{goalId:t,action:n}),goalDraftMode:e.chatGoalDraftMode??null,currentSessionId:e.currentSessionId,onGoalDraftModeChange:t=>{e.chatGoalDraftMode=t,e.handleChatDraftChange(e.chatMessage)},onGoalSubmit:N||g?void 0:(t,n)=>nx(e,t,n),onCompanionStageAttachment:(n,r)=>this.state===e&&this.connectionGeneration===t&&Y(e)===h&&this.stageSessionCompanionAttachment(n,r),replyTarget:e.chatReplyTarget??null,onClearReply:()=>fe(null),onSetReply:xe?void 0:fe,replyMessageAccess:g||o?void 0:pe,onRewindMessage:o?void 0:de.onRewindMessage,onForkMessage:de.onForkMessage,agentsList:e.agentsList,currentAgentId:h,fullMessageAgentId:D(e,e.sessionKey).agentId,loadFullAssistantMessage:uT(e,this.context.gateway),onSessionSelect:e=>this.onPaneSessionChange?.(this.paneId,e),canvasPluginSurfaceUrl:e.canvasPluginSurfaceUrl,boardProvider:p.provider,onOpenSidebar:e.handleOpenSidebar,onRequestOpenImage:e.beginImageOpen,onOpenImage:e.handleOpenImage,assistantName:e.assistantName,assistantAvatar:e.assistantAvatar,senderAgentAvatars:e.senderAgentAvatars,mainKey:ye({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}),userId:this.presentationUserId,userName:F?.name??e.userName,userAvatar:F?.avatarUrl??e.userAvatar,personActivity:Zo(this.context),mediaPolicyEpoch:e.mediaPolicyEpoch,connectionEpoch:e.connectionEpoch,embedSandboxMode:e.embedSandboxMode,allowExternalEmbedUrls:e.allowExternalEmbedUrls,fetchLinkFavicon:ug(e),chatMessageMaxWidth:e.settings.chatMessageMaxWidth,branding:this.context?.theme.branding,assistantAttachmentAuthToken:Un(e),resolveArtifactDownload:(t,n)=>iy(e,t,n),basePath:e.basePath,sessionPublicOrigin:Vo(this.context),resourceBasePath:e.resourceBasePath};return W`${this.renderChatPaneLayout({state:e,selectedSession:n,currentAgentId:h,board:p,sidebarLayout:m,sessionWorkspace:ce,chatProps:ke,observerDigest:c,observerRunId:l,catalog:_,agentWorkspace:y?.workspace,workspaceGit:y?.workspaceGit===!0,openPanelSlot:se,closePanelSlot:oe})}${this.providerReview.dialog()}`}}})))()}function yE(){return(yE=e((()=>{vE(),customElements.get(`openclaw-chat-pane`)||customElements.define(`openclaw-chat-pane`,_E)})))()}function bE(){return{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash}}function xE(e,t){return e.pathname===t.pathname&&e.search===t.search&&e.hash===t.hash}function SE(e,t){if(!e)return!1;let n=bE();if(xE(n,e))return!0;let r=new URLSearchParams(e.search).has(`draft`),i=new URLSearchParams(n.search).has(`draft`);return t&&r&&!i&&xE(m_(n),m_(e))}function CE(){return(CE=e((()=>{N_()})))()}var wE;function TE(){return(TE=e((()=>{R(),wE=class{constructor(e){this.host=e}clear(){this.pending?.abort.abort(),this.pending=void 0}capture(e){this.clear();let t=this.host.ownerDocument.activeElement;return t&&([...this.host.querySelectorAll(`openclaw-chat-pane`)].some(n=>n.paneId===e&&n.contains(t))||[...this.host.querySelectorAll(`[data-unbound-pane-id]`)].some(n=>n.dataset.unboundPaneId===e&&n.contains(t)))?t:null}schedule(e,t,n){let r=new AbortController;this.pending={source:e,paneId:t.id,sessionKey:t.sessionKey,layout:n,href:window.location.href,abort:r},this.host.ownerDocument.addEventListener(`focusin`,()=>this.clear(),{signal:r.signal})}restore(e,t){let n=this.pending;if(!n)return;let r=this.host.ownerDocument.activeElement;if(e!==n.layout||window.location.href!==n.href||r!==n.source&&r!==this.host.ownerDocument.body){this.clear();return}if(t)return;let i=[...this.host.querySelectorAll(`openclaw-chat-pane`)].find(e=>e.paneId===n.paneId&&z(e.sessionKey,n.sessionKey)),a=i?.active&&i.presented?i.querySelector(`.chat-pane__header`):[...this.host.querySelectorAll(`[data-unbound-pane-id]`)].find(e=>e.dataset.unboundPaneId===n.paneId);a&&(this.clear(),a.focus({preventScroll:!0}))}}})))()}function EE(e,t,n,r){let i=t.paneId??t.dataset.unboundPaneId,a=e.querySelector(`.chat-split-view__drop-container`);if(!i||!a)return null;let o=t.getBoundingClientRect(),s=Z_(o,n,r),c=I_(o,s),l=a.getBoundingClientRect();return{paneId:i,zone:s,rect:{left:c.left-l.left,top:c.top-l.top,width:c.width,height:c.height}}}var DE;function OE(){return(OE=e((()=>{Tc(),av(),DE=class{constructor(e,t){this.host=e,this.options=t,this.indicator=null,this.dragDepth=0,this.dragFrame=0,this.pendingDragOver=null,this.handleDragEnter=e=>{this.options.sessionSplitAvailable()&&cd(e.dataTransfer)&&(this.dragDepth+=1)},this.handleDragOver=e=>{if(!this.options.sessionSplitAvailable()||!cd(e.dataTransfer))return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`);let t=(e.target instanceof Element?e.target:null)?.closest(`openclaw-chat-pane, [data-unbound-pane-id]`);if(!t||!this.host.contains(t)){this.clear();return}this.pendingDragOver={pane:t,x:e.clientX,y:e.clientY},!this.dragFrame&&(this.dragFrame=window.requestAnimationFrame(()=>{this.dragFrame=0;let e=this.pendingDragOver;if(this.pendingDragOver=null,!e||this.options.narrow()||!this.host.isConnected)return;let t=EE(this.host,e.pane,e.x,e.y);if(!t){this.clear();return}let n=this.indicator;(n?.paneId!==t.paneId||n.zone.kind!==t.zone.kind||t.zone.kind!==`center`&&(n.zone.kind!==`edge`||n.zone.edge!==t.zone.edge))&&(this.indicator=t,this.host.requestUpdate())}))},this.handleDragLeave=e=>{this.options.sessionSplitAvailable()&&cd(e.dataTransfer)&&(this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&this.clear())},this.handleDrop=e=>{if(!this.options.sessionSplitAvailable()||!cd(e.dataTransfer))return;e.preventDefault();let t=rl(e.dataTransfer),n=(e.target instanceof Element?e.target:null)?.closest(`openclaw-chat-pane, [data-unbound-pane-id]`),r=n&&this.host.contains(n)?EE(this.host,n,e.clientX,e.clientY):null;this.clear(),t&&r&&this.options.applySessionDrop(t,r.paneId,r.zone)},this.clear=()=>{this.dragDepth=0,this.pendingDragOver=null,this.dragFrame&&=(window.cancelAnimationFrame(this.dragFrame),0),this.indicator&&(this.indicator=null,this.host.requestUpdate())}}connect(){this.host.addEventListener(`dragenter`,this.handleDragEnter),this.host.addEventListener(`dragover`,this.handleDragOver),this.host.addEventListener(`dragleave`,this.handleDragLeave),this.host.addEventListener(`drop`,this.handleDrop),window.addEventListener(`dragend`,this.clear)}disconnect(){this.host.removeEventListener(`dragenter`,this.handleDragEnter),this.host.removeEventListener(`dragover`,this.handleDragOver),this.host.removeEventListener(`dragleave`,this.handleDragLeave),this.host.removeEventListener(`drop`,this.handleDrop),window.removeEventListener(`dragend`,this.clear),this.clear()}}})))()}function kE(e,n,r){return!!(n&&r&&t({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello},n.sessionKey,r.sessionKey,r.agentId,n.agentId))}function AE(e,t){if(!f(t?.sessionKey)||!t.agentId?.trim())return t;let n=jE(e,t.sessionKey,t.agentId);if(n===t.sessionKey)return t;let r=NE.get(t);return r?.sessionKey!==n&&(r={sessionKey:n,value:{...t,sessionKey:n}},NE.set(t,r)),r.value}function jE(e,t,n){return f(t)&&n?.trim()&&ce({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})?vo({agentId:n,mainKey:ye({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})}):t}function ME(e,n,r,i=!1,a,o){let s=St(e,o??n?.agentId),c=n&&t({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello,assistantAgentId:s},n.sessionKey,r,f(r)?s:void 0,n.agentId),l=a??n?.face??`chat`;a===void 0&&!c&&(l=Me(e,r,o??n?.agentId));let u=Oe({context:e,face:l,preferenceDerivedFace:a===void 0&&!c,sessionKey:r,agentId:o??n?.agentId,shortIdLength:n?.sessionKey===r?n.shortId?.length:void 0}).options,d=i&&c&&(n.draft||n.focusComposer)?m_(bE(),u):u;e[i?`replace`:`navigate`](l,d)}var NE;function PE(){return(PE=e((()=>{Te(),R(),CE(),N_(),NE=new WeakMap})))()}function FE(e,t,n){let r=new Set;for(let i of t.columns)for(let t of i.panes){let a=JSON.stringify([i.id,t.id]);for(let i of n.get(t.id)??[])i!==void 0&&(!e||!cr(e,i))&&r.add(JSON.stringify([a,i]))}return r}function IE(e){let t=e.context?.sessions?.presentation.result?.sessions??[];return W`
    <div
      class="chat-split-view__cell ${e.splitMode&&e.active?`chat-split-view__cell--active`:``} ${e.narrow&&!e.active?`chat-split-view__cell--narrow-hidden`:``}"
      aria-current=${e.splitMode&&e.active?`true`:U}
      style="flex: ${e.narrow?1:e.weight} 1 0"
      @pointerdown=${()=>e.onFocusPane(e.pane.id)}
      @focusin=${()=>e.onFocusPane(e.pane.id)}
    >
      <div class="chat-pane-cache">
        ${e.unbound?W`
                <div
                  class="chat-split-view__unbound"
                  data-unbound-pane-id=${e.pane.id}
                  tabindex="0"
                  role="region"
                  aria-label=${V(`chat.splitView.chooseConversation`)}
                >
                  <strong>${V(`chat.splitView.chooseConversation`)}</strong>
                  <p>${V(`chat.splitView.missingOwner`)}</p>
                  ${e.onClosePane?W`<button class="btn" @click=${()=>e.onClosePane?.(e.pane.id)}>${V(`chat.splitView.closePane`)}</button>`:U}
                </div>
              `:U}
        ${e.sessionSlots.map(n=>{if(n===void 0||e.unbound)return U;let r=n===e.pane.sessionKey||z(n,e.pane.sessionKey),i=e.presented&&r&&(!e.narrow||e.active),a=e.active&&r,o=e.data&&z(n,e.data.sessionKey)?e.data:void 0,s=a?Cv(e.data,e.consumedDraftData,n):void 0,c=be(n,e.context?.gateway?.snapshot?.hello)||n,l=t.find(e=>z(e.key,c)),u=l?He(c,l):void 0;return e.context&&(o?.creation?.admitted===!1||cr(e.context,n))?Mr(n,W`<openclaw-pending-session-create
                class="chat-pane-cache__pane ${r?`chat-pane-cache__pane--visible`:``}
                ${a?`chat-pane-cache__pane--active`:``}
                ${e.splitMode?`chat-split-view__pane`:``}"
                aria-hidden=${String(!i)}
                ?inert=${!i}
                .context=${e.context}
                .sessionKey=${n}
                .narrow=${e.narrow}
                .mergedChrome=${e.mergedChrome&&a}
                .navDrawerOpen=${e.navDrawerOpen&&a}
              ></openclaw-pending-session-create>`):Mr(n,W`<openclaw-chat-pane
              class="chat-pane-cache__pane ${r?`chat-pane-cache__pane--visible`:``} ${a?`chat-pane-cache__pane--active`:``} ${e.splitMode?`chat-split-view__pane`:``}"
              data-mcp-app-owner-key=${JSON.stringify([e.ownerKey,n])}
              aria-hidden=${i?`false`:`true`}
              ?inert=${!i}
              .paneId=${e.pane.id}
              .paneLabel=${V(`chat.splitView.panePosition`,{column:String(e.panePosition.column),row:String(e.panePosition.row),pane:e.pane.id})}
              .presentationId=${JSON.stringify([e.pane.id,n])}
              .chatMessagesBySession=${e.chatMessagesBySession}
              .sessionSnapshotStore=${e.sessionSnapshotStore}
              .sessionKey=${n}
              .agentId=${e.splitMode?Bt(n)?.agentId:void 0}
              .routeLoadingSkeleton=${o?.routeLoadingSkeleton??Pr}
              .presented=${i}
              .visuallyPresented=${i}
              .active=${a}
              .draft=${s}
              .focusComposer=${e.draftFocus.shouldFocusPane(a,s,n,e.data)}
              .dashboardExpanded=${o?o.dashboardExpanded===!0:Pr}
              .routeFace=${o?o.face??`chat`:Pr}
              .presentationTitle=${u}
              .narrow=${e.narrow}
              .mergedChrome=${e.mergedChrome&&a}
              .navDrawerOpen=${e.navDrawerOpen&&a}
              .onboarding=${e.onboarding}
              .onOpenSplitView=${e.onOpenSplitView}
              .onSplitDown=${e.onSplitDown}
              .onSplitRight=${e.onSplitRight}
              .onClosePane=${e.onClosePane}
              .onFocusPane=${e.onFocusPane}
              .onPaneSessionChange=${(t,r,i)=>e.onPaneSessionChange(t,n,r,i)}
              .onSessionDeleted=${e.onSessionDeleted}
              .onFaceChange=${e.onFaceChange}
            ></openclaw-chat-pane>`)})}
      </div>
    </div>
  `}function LE(e,t){let n=t.activePaneId!==void 0&&Gg(e,t.activePaneId)!==null,r=(n,r)=>W`
    <resizable-divider
      orientation=${r?`horizontal`:U}
      .splitRatio=${lv(r?.paneWeights??e.columnWeights,n,r?`split pane weight`:`split column weight`)}
      .minRatio=${.15}
      .maxRatio=${.85}
      .label=${V(`nav.resize`)}
      @resize=${e=>r?t.onResizePanes(r.id,n,e.detail.splitRatio):t.onResizeColumns(n,e.detail.splitRatio)}
      @resize-end=${t.onResizeEnd}
    ></resizable-divider>
  `;return W`
    <div
      class="chat-split-view ${t.narrow?`chat-split-view--narrow`:``} ${n?`chat-split-view--active-cell`:``}"
    >
      ${Nr(e.columns,e=>e.id,(n,i)=>W`
          <div
            class="chat-split-view__column ${t.narrow&&!n.panes.some(t=>t.id===e.activePaneId)?`chat-split-view__column--narrow-hidden`:``}"
            style="flex: ${t.narrow?1:Ga(e.columnWeights[i],`rendered split column weight`)} 1 0"
          >
            ${Nr(n.panes,e=>e.id,(e,i)=>W`
                ${t.renderPane(n,e,Ga(n.paneWeights[i],`rendered split pane weight`))}
                ${!t.narrow&&i<n.panes.length-1?r(i,n):U}
              `)}
          </div>
          ${!t.narrow&&i<e.columns.length-1?r(i):U}
        `)}
    </div>
  `}function RE(e,t){return W`<div class="chat-split-view__drop-container">
    ${e}${t?W`<div
            class="chat-split-view__drop-indicator ${t.zone.kind===`center`?`chat-split-view__drop-indicator--center`:``}"
            style=${`left: ${t.rect.left}px; top: ${t.rect.top}px; width: ${t.rect.width}px; height: ${t.rect.height}px;`}
          >
            <span class="chat-split-view__drop-indicator-label"
              >${t.zone.kind===`center`?V(`chat.splitView.dropOpenHere`):V(`chat.splitView.dropSplit`)}</span
            >
          </div>`:U}
  </div>`}function zE(){return(zE=e((()=>{co(),kr(),jr(),Cr(),Ir(),F(),gt(),Ue(),R(),N_(),Nv()})))()}var BE;function VE(){return(VE=e((()=>{Dh(),Nv(),BE=class{constructor(e){this.owner=e,this.gateway=null}sync(e,t,n,r){let i=e&&typeof e.subscribe==`function`?e:null;this.gateway&&this.gateway!==i&&Eh(this.gateway).unwatch(this.owner),this.gateway=i,i&&Eh(i).watch(this.owner,wg(t,n).filter(e=>!r.has(e.id)).map(e=>e.sessionKey))}dispose(){this.gateway&&=(Eh(this.gateway).unwatch(this.owner),null)}}})))()}var HE;function UE(){return(UE=e((()=>{eo(),kr(),Ar(),rn(),Sr(),ur(),Jn(),mr(),vr(),R(),ae(),j(),CE(),TE(),OE(),PE(),zE(),nS(),Ix(),Q(),VE(),dy(),yE(),A_(),N_(),Gs(),bv(),x_(),Nv(),HE=class extends ot{get conversationPresented(){let e=this.context?.nativeConversation?.presentation;return this.presented&&(!e||e.visible)}get pendingCreate(){return this.data?.creation?.admitted===!1}get sessionSplitAvailable(){return this.presented&&!this.pendingCreate&&!this.narrow&&!this.nativeConversation&&!!this.data?.sessionKey?.trim()}get paneData(){return this.layout&&!this.pendingCreate?AE(this.context,this.data):this.data}get singleBoundPane(){let e=this.layout?t_(this.layout):[],t=e.length===1?e[0]:void 0;return t&&!this.retainedSessions.unboundPaneIds.has(t.id)?t:void 0}constructor(){super(),this.navDrawerOpen=!1,this.presented=!0,this.narrow=!1,this.mergedChrome=!1,this.wasConversationPresented=!1,this.nativeConversation=kn()?.surface===`conversation`,this.mediaQuery=null,this.mobileNavMediaQuery=null,this.consumedDraftData=null,this.draftFocus=new T_(this),this.messageCache=new Map,this.snapshotStore=new mv(this.messageCache),this.classicColumnId=`c1`,this.classicPaneId=`p1`,this.routeHref=``,this.closeFocus=new wE(this),this.sessionDrop=new DE(this,{sessionSplitAvailable:()=>this.sessionSplitAvailable,narrow:()=>this.narrow,applySessionDrop:(e,t,n)=>this.applySessionDrop(e,t,n)}),this.mcpAppUnmountGate=new ir(this),this.viewerPresence=new BE(this),this.retainedSessions=new tS(this,{context:()=>this.context,presented:()=>this.conversationPresented,routeHref:()=>this.routeHref,layout:()=>this.layout??this.classicLayout(),narrow:()=>this.narrow,selectReplacement:(e,t,n)=>this.handlePaneSessionChange(e,t,n),adoptNavigation:(e,t,n)=>this.adoptPaneNavigation(e,t,n)}),this.handleViewportChange=e=>{this.narrow=e.matches,e.matches&&this.sessionDrop.clear()},this.handleMobileNavViewportChange=e=>{this.mergedChrome=this.resolveMergedChrome(e.matches)},this.handleUiCommand=e=>{if(!this.presented||this.pendingCreate||!(e instanceof CustomEvent))return;let{command:t,sessionKey:n,agentId:r}=e.detail;if(t.kind!==`navigate`&&t.kind!==`split`&&t.kind!==`focus`&&t.kind!==`close-pane`)return;let i=jE(this.context,t.sessionKey,r);if(t.kind===`navigate`){e.preventDefault(),this.layout&&this.retainedSessions.unboundPaneIds.has(this.layout.activePaneId)&&this.adoptPaneNavigation(this.layout.activePaneId,i,r),this.updateRoute(i,!1,void 0,r);return}if(t.kind===`split`&&(this.narrow||this.nativeConversation))return;let a=AE(this.context,this.data)?.sessionKey?.trim(),o=this.layout??(t.kind===`split`&&a?this.classicLayout(a):void 0);if(!o)return;if(t.kind===`close-pane`){let t=t_(o).find(e=>e.sessionKey===i);if(!t)return;e.preventDefault(),this.closeSplitPane(o,t.id);return}let s=xg(o,{...t,sessionKey:i},n?jE(this.context,n,r):void 0);if(s===o)return;e.preventDefault(),this.persistLayout(s);let c=s&&Gg(s,s.activePaneId)?.pane;c&&this.updateRouteToPane(c)},this.handleFocusPane=(e,t)=>{let n=this.layout;if(this.pendingCreate||!this.presented&&t!==`review-edit`||!n||n.activePaneId===e)return;let r=Gg(n,e)?.pane;r&&(this.persistLayout(i_(n,e)),this.updateRouteToPane(r))},this.handlePaneSessionChange=(e,t,n,r)=>{let i=n.trim();if(!this.presented||!i||window.location.href!==this.routeHref)return!1;let a=this.layout??this.classicLayout(),o=Gg(a,e)?.pane;return!o||!z(o.sessionKey,t)?!1:(this.layout&&f(i)&&A({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello},o.sessionKey)&&(i=o.sessionKey),this.layout?o.sessionKey===i||(this.persistLayout(gg(a,e,i)),a.activePaneId===e&&this.updateRoute(i,r?.replace),!0):z(o.sessionKey,i)?(this.syncRouteBindings(),!0):(this.updateRoute(i,r?.replace),!0))},this.handlePaneFaceChange=(e,t,n)=>{if(!this.presented)return;let r=Gg(this.layout??this.classicLayout(),e)?.pane.sessionKey;if(r&&z(r,t)){if((!this.layout||this.layout.activePaneId===e)&&z(this.data.sessionKey,t)&&(this.data.face??`chat`)===n){this.syncRouteBindings();return}this.layout&&this.layout.activePaneId!==e&&this.persistLayout(i_(this.layout,e)),this.updateRoute(t,!1,n)}},this.openSplitView=()=>this.handleSplit(this.classicPaneId,`right`),this.handleSplitRight=e=>this.handleSplit(e,`right`),this.handleSplitDown=e=>this.handleSplit(e,`down`),this.handleClosePane=e=>{this.layout&&this.closeSplitPane(this.layout,e)},new S(this).watchStore(()=>this.context?.sessions,void 0,()=>this.performUpdate()).watch(()=>this.context?.chatSubmissions,(e,t)=>e.subscribeCreate(t)).watchStore(()=>this.context?.placementStartup).watchStore(()=>this.context?.gateway).watchStore(()=>this.context?.nativeConversation),this.addController(new J_(this,this.messageCache,this.snapshotStore,()=>this.context))}connectedCallback(){super.connectedCallback(),this.toggleAttribute(`data-native-conversation`,this.nativeConversation),this.snapshotStore.connect(),Vu(this.messageCache,this.snapshotStore),this.routeHref=window.location.href,this.layout=this.nativeConversation?void 0:Nn().chatSplitLayout,this.retainedSessions.restore(this.layout?t_(this.layout):[]),this.unboundRoute=this.layout&&this.retainedSessions.unboundPaneIds.has(this.layout.activePaneId)?this.paneData:void 0,this.mediaQuery=window.matchMedia(`(max-width: 1099px)`),this.narrow=this.mediaQuery.matches,this.mediaQuery.addEventListener(`change`,this.handleViewportChange),this.mobileNavMediaQuery=window.matchMedia(cn()),this.mergedChrome=this.resolveMergedChrome(this.mobileNavMediaQuery.matches),this.mobileNavMediaQuery.addEventListener(`change`,this.handleMobileNavViewportChange),this.sessionDrop.connect(),window.addEventListener(tr,this.handleUiCommand),this.retainedSessions.connect(),this.syncRouteToActivePane(),this.syncRouteBindings();let e=this.layout??this.classicLayout();this.conversationPresented&&!this.pendingCreate&&this.viewerPresence.sync(this.context?.gateway,e,this.narrow,this.retainedSessions.unboundPaneIds)}disconnectedCallback(){this.closeFocus.clear(),this.snapshotStore.disconnect(),this.retainedSessions.disconnect(),this.viewerPresence.dispose(),this.mediaQuery?.removeEventListener(`change`,this.handleViewportChange),this.mediaQuery=null,this.mobileNavMediaQuery?.removeEventListener(`change`,this.handleMobileNavViewportChange),this.mobileNavMediaQuery=null,this.sessionDrop.disconnect(),window.removeEventListener(tr,this.handleUiCommand),super.disconnectedCallback()}updated(e){if(this.wasConversationPresented&&!this.conversationPresented&&(this.retainedSessions.suspend(),this.sessionDrop.clear()),this.wasConversationPresented=this.conversationPresented,!this.conversationPresented||this.pendingCreate){this.closeFocus.clear(),this.viewerPresence.dispose();return}let t=this.layout??this.classicLayout();Nx(this,t,this.narrow),this.isConnected&&this.viewerPresence.sync(this.context?.gateway,t,this.narrow,this.retainedSessions.unboundPaneIds),this.closeFocus.restore(this.layout,this.mcpAppUnmountGate.retiring);let n=this.paneData,r=this.layout?Gg(this.layout,this.layout.activePaneId)?.pane:null,i=this.layout?r?.sessionKey??null:void 0,a=this.draftFocus.rendered(n,i,this.consumedDraftData),o=this.data!==this.processedRouteData;if(n&&(o||e.has(`presented`))){if(this.processedRouteData=this.data,this.routeHref=window.location.href,n?.canonicalLocation&&SE(n.canonicalLocationSource,this.consumedDraftData===n)){this.context.replace(n.face??`chat`,n.canonicalLocation);return}n?.canonicalLocationReady?.then(e=>{e&&this.isConnected&&this.presented&&this.paneData===n&&SE(n.canonicalLocationSource,this.consumedDraftData===n)&&this.context.replace(n.face??`chat`,this.consumedDraftData===n?m_(e):e)}),(o||!this.singleBoundPane)&&this.syncRouteToActivePane(),this.syncRouteBindings(),this.retainedSessions.settleRoute()}n&&a&&queueMicrotask(()=>{this.isConnected&&this.presented&&this.paneData===n&&this.consumedDraftData!==n&&(this.draftFocus.beforeDraftCleanup(n),this.consumedDraftData=n,this.updateRoute(n.sessionKey,!0,n.face??`chat`),this.requestUpdate())});let s=this.singleBoundPane,c=this.layout?.columns[0];s&&c&&!this.mcpAppUnmountGate.retiring&&z(s.sessionKey,n?.sessionKey??``)&&(this.classicColumnId=c.id,this.classicPaneId=s.id,this.persistLayout(void 0))}resolveMergedChrome(e){let t=e&&!this.nativeConversation;return un(t,this.closest(`.shell--onboarding`)!==null)}syncRouteToActivePane(){let e=this.layout,t=this.paneData?.sessionKey?.trim();if(!e||!t||this.pendingCreate)return;let n=Gg(e,e.activePaneId)?.pane;n&&n.sessionKey!==t&&(this.retainedSessions.unboundPaneIds.has(n.id)&&this.retainedSessions.wasPendingAtFocus()&&(this.unboundRoute=this.paneData),!(this.retainedSessions.unboundPaneIds.has(n.id)&&kE(this.context,this.unboundRoute,this.paneData))&&(this.retainedSessions.bindPane(n.id),this.persistLayout(gg(e,n.id,t))))}syncRouteBindings(e=this.data?.agentId){if(!this.presented||this.pendingCreate)return;let t=this.layout&&Gg(this.layout,this.layout.activePaneId)?.pane,n=(t?.sessionKey??this.data?.sessionKey)?.trim();this.context&&n&&(!t||!this.retainedSessions.unboundPaneIds.has(t.id))&&Gx(this.context,n,e)}adoptPaneNavigation(e,t,n){!this.layout||f(t)&&!n?.trim()||(this.retainedSessions.bindPane(e),this.unboundRoute=void 0,this.persistLayout(gg(this.layout,e,jE(this.context,t,n)),n))}persistLayout(e,t){this.layout=e,wr({chatSplitLayout:this.singleBoundPane?void 0:e}),this.syncRouteBindings(t)}updateRoute(e,t=!1,n,r){this.presented&&ME(this.context,this.data,e,t,n,r)}updateRouteToPane(e){if(this.retainedSessions.unboundPaneIds.has(e.id)){this.retainedSessions.capturePendingNavigation(),this.unboundRoute=this.paneData;return}this.unboundRoute=void 0;let t=this.retainedSessions.findPane(e.id,e.sessionKey);this.updateRoute(e.sessionKey,!0,t?.captureNavigationFace?.())}applySessionDrop(e,t,n){let r=e.trim();if(!r)return;if(!this.layout&&n.kind===`center`){this.updateRoute(r);return}let i=this.layout??this.classicLayout(AE(this.context,this.data)?.sessionKey),a=this.layout?t:this.classicPaneId,o=Gg(i,a)?.pane;o&&(this.layout||o.sessionKey)&&(n.kind!==`center`||o.sessionKey!==r)&&(this.persistLayout(n.kind===`center`?gg(i_(i,a),a,r):ag(i,a,r,n.edge)),this.updateRoute(r,!0))}handleSplit(e,t){let n=this.layout??this.classicLayout(AE(this.context,this.data)?.sessionKey?.trim()),r=Gg(n,e)?.pane;r?.sessionKey&&this.persistLayout(ag(n,e,r.sessionKey,t))}closeSplitPane(e,t){if(this.singleBoundPane)return;let n=this.closeFocus.capture(t),r=t_(e).find(e=>e.id!==t);this.retainedSessions.discardPane(t);let i=Ag(e,t,this.retainedSessions.unboundPaneIds);if(!i&&r){let t=Gg(e,r.id);t&&(this.classicColumnId=t.column.id,this.classicPaneId=r.id,z(r.sessionKey,this.paneData?.sessionKey??``)||(i=this.classicLayout(r.sessionKey)))}this.persistLayout(i);let a=i?Gg(i,i.activePaneId)?.pane:r;a&&(this.updateRouteToPane(a),n&&this.closeFocus.schedule(n,a,i))}classicLayout(e=this.data?.sessionKey?.trim()??``){return Dg(this.classicColumnId,this.classicPaneId,e)}renderSplitLayout(e,t,n){return LE(e,{narrow:this.narrow,activePaneId:t&&this.conversationPresented?e.activePaneId:void 0,renderPane:(r,i,a)=>IE({active:this.conversationPresented&&i.id===e.activePaneId,presented:this.conversationPresented,chatMessagesBySession:this.messageCache,sessionSnapshotStore:this.snapshotStore,consumedDraftData:this.consumedDraftData,context:this.context,data:this.paneData,draftFocus:this.draftFocus,mergedChrome:this.mergedChrome,narrow:this.narrow,navDrawerOpen:this.navDrawerOpen,onboarding:this.closest(`.shell--onboarding`)!==null,onClosePane:t?this.handleClosePane:void 0,onFaceChange:this.handlePaneFaceChange,onFocusPane:this.handleFocusPane,onOpenSplitView:t||this.narrow||this.nativeConversation?void 0:this.openSplitView,onPaneSessionChange:this.handlePaneSessionChange,onSessionDeleted:this.retainedSessions.removeSession,onSplitDown:t?this.handleSplitDown:void 0,onSplitRight:t?this.handleSplitRight:void 0,ownerKey:JSON.stringify([r.id,i.id]),pane:i,panePosition:{column:e.columns.indexOf(r)+1,row:r.panes.indexOf(i)+1},sessionSlots:n.get(i.id)??[],splitMode:t,unbound:!this.pendingCreate&&this.retainedSessions.unboundPaneIds.has(i.id),weight:a}),onResizePanes:(e,t,n)=>{this.layout=this.layout?Qg(this.layout,e,t,n):void 0},onResizeColumns:(e,t)=>{this.layout=this.layout?yg(this.layout,e,t):void 0},onResizeEnd:()=>this.persistLayout(this.layout)})}render(){if(this.pendingCreate)return this.mcpAppUnmountGate.render(`pending-create`,()=>{if(!this.conversationPresented)return U;let e=this.classicLayout();return RE(this.renderSplitLayout(e,!1,new Map([[e.activePaneId,[this.data.sessionKey]]])),null)},()=>[...this.querySelectorAll(`openclaw-chat-pane`)]);let e=this.layout??this.classicLayout(),t=this.retainedSessions.retain(t_(e)),n=FE(this.context,e,t),r=()=>RE(this.renderSplitLayout(e,!(!this.layout||this.singleBoundPane),t),this.sessionDrop.indicator);return this.mcpAppUnmountGate.render(JSON.stringify([...n]),r,()=>[...this.querySelectorAll(`openclaw-chat-pane`)].filter(e=>!n.has(e.dataset.mcpAppOwnerKey??``)))}},q([Qa({context:er,subscribe:!0})],HE.prototype,`context`,void 0),q([G({attribute:!1})],HE.prototype,`data`,void 0),q([G({attribute:!1})],HE.prototype,`navDrawerOpen`,void 0),q([G({type:Boolean})],HE.prototype,`presented`,void 0),q([Fr()],HE.prototype,`layout`,void 0),q([Fr()],HE.prototype,`narrow`,void 0),q([Fr()],HE.prototype,`mergedChrome`,void 0),customElements.get(`openclaw-chat-page`)||customElements.define(`openclaw-chat-page`,HE)})))()}export{mb as A,Cy as B,Lb as C,Rb as D,wb as E,Ky as F,xy as H,tb as I,cb as L,Cb as M,Qy as N,Gb as O,ob as P,Sy as R,Ub as S,Bb as T,vy as U,yy as V,Z as _,aT as a,Fb as b,rT as c,cC as d,lS as f,Q as g,oS as h,ZT as i,Sb as j,xb as k,sC as l,sS as m,yE as n,hT as o,aS as p,QT as r,iT as s,UE as t,uC as u,Ib as v,Qb as w,Hb as x,Pb as y,wy as z};