openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
713 lines • 429 kB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./session-snapshot-database-BurLa_ut.js","./control-ui-boot-shared-em9-jnbz.js","./plugin-contracts-runtime-CNCaYops.js","./config-runtime-BecGLziM.js","./markdown-runtime-ORQpioyT.js","./sidebar-update-runtime-DonYLwN5.js","./control-ui-core-yIvVj14Y.css","./control-ui-boot-shared-styles-DKyMAG_6.css","./control-ui-boot-shared-CXHNz0Bh.css","./sidebar-update-runtime-ah7rgQE7.css","./board-view-1zQa7RX5.js","./chat-transcript-styles-Dzr3t9kA.js","./control-ui-boot-chat-styles-BRrYkFSc.js","./control-ui-disabled-DfZ2EcL3.js","./near-viewport-observer-WgGck829.js","./widget-sandbox-host-BtiBzdny.js","./mcp-app-confirm-C5ZrOS-h.js","./chat-transcript-styles-B_dd5Ueo.css","./control-ui-boot-chat-styles-C_Ls1c0m.css","./control-ui-boot-chat-mLz7NUiY.css","./board-view-DsuslJec.css","./chat-sidebar-region.runtime-Cm79n6xu.js","./panel-tab-strip-DvSbDG3-.js","./panel-empty-state-DS_rQC2v.js","./control-ui-boot-chat-Dh5vtL-G.css","./chat-sidebar-region-BT887V4g.css","./chat-detail-panel-DL_gv0lj.js","./terminal-panel-registration-DwNbVu-U.js","./scrollbar-styles-BIL0YPCY.js","./dock-panel-styles-C_3Cdw6M.js","./dock-destination-controls-CzLuh1pj.js","./theme-color-DAo4KRoc.js","./catalog-terminal-start-BmIoZaYn.js","./link-reader-panel-DRh0JX44.js","./link-reader-response-DDChabPB.js","./browser-panel-CpBLyCyg.js","./gateway-websocket-url-cYJwVUmD.js","./desktop-panel-DON9OquX.js","./reasoned-disabled-control-U3kHzkKT.js","./desktop-focus-window-BNmA4flB.js","./portals-page-Ce3PZSf5.js","./portals-page-pG5r4WM8.css","./chat-session-rail-CCqxxauE.js","./chat-session-rail-BmiGPeTv.css","./session-discussion-panel-BuqxXJ-E.js","./chat-pane-placement.runtime-6ICY8ken.js","./control-ui-boot-new-CxgnwT6A.js","./control-ui-boot-new-styles-Bb6Ub5D3.js","./cloud-worker-stop.runtime-BR0jZ8bp.js","./control-ui-boot-new-styles-u1aN_ui5.css","./control-ui-boot-new-D-SpiTTi.css","./session-organizer-operations.runtime-RnGN66Ok.js","./session-workspace-recovery.runtime-sCzaBa0p.js","./input-dialog-OAeQnraY.js"])))=>i.map(i=>d[i]);
import{n as e}from"./rolldown-runtime-8BhlS34s.js";import{$i as t,$n as n,Ac as r,Al as i,Bc as a,Bl as o,Bo as s,Cc as c,Co as l,Ct as u,Cu as d,Dc as f,Dl as p,Dn as m,Dt as h,Ec as g,El as _,Eo as v,Eu as y,Fl as b,Gc as x,Gl as S,Gn as C,Go as ee,Hc as w,Hi as T,Hl as E,Hn as D,Hr as O,Hs as k,I as A,Il as j,Jn as M,Jt as te,Kl as ne,Ko as N,Lc as P,Ll as F,No as re,Oc as ie,Ol as ae,Oo as oe,Pl as se,Qn as ce,Qs as le,Rl as ue,Rr as de,Rs as fe,Sl as I,Tc as pe,Tl as me,Tn as he,Tu as ge,Uc as _e,Ui as ve,Un as ye,Uo as be,Ur as L,Vc as xe,Vl as Se,Vo as Ce,W as we,Wi as Te,Wl as Ee,Wr as De,Xc as Oe,Xn as ke,Xr as Ae,Xt as je,Yc as Me,Yo as Ne,Yr as Pe,Ys as Fe,Yt as Ie,Zc as R,Zn as Le,Zt as Re,_l as z,_r as ze,_u as Be,a as Ve,bl as He,bu as Ue,c as We,cn as Ge,cr as Ke,dn as qe,dt as Je,du as B,er as Ye,fu as Xe,g as Ze,h as Qe,i as $e,ir as et,jl as tt,ju as V,k as nt,kc as rt,ko as it,ku as at,l as ot,lr as st,lt as ct,lu as lt,m as ut,mn as dt,n as ft,nl as pt,nr as mt,nu as ht,oc as gt,p as _t,pu as vt,ql as yt,r as bt,ru as xt,s as St,sc as Ct,sn as wt,tl as Tt,tr as Et,u as Dt,uu as Ot,vl as kt,wc as At,wl as jt,wo as Mt,wt as Nt,xr as Pt,xu as Ft,yl as It,zn as Lt,zr as Rt}from"./control-ui-core-BncvAZjR.js";import{A as zt,J as Bt,L as Vt,N as Ht,R as Ut,X as Wt,Y as Gt,Z as Kt,c as qt,j as Jt,q as Yt,s as Xt}from"./control-ui-boot-shared-Dfs-gZII.js";import{$r as Zt,$t as Qt,At as $t,C as en,Cn as tn,D as nn,Di as rn,Dt as an,E as on,Ei as sn,Et as cn,Fi as ln,G as un,Ga as dn,Gi as fn,Hi as pn,Ii as mn,Ja as hn,Jr as gn,Ki as _n,Kt as vn,Ma as yn,Mr as bn,O as xn,Or as Sn,Ri as Cn,Sr as wn,T as Tn,Ti as En,Tr as Dn,Vi as On,W as kn,Wr as An,Xn as jn,Xt as Mn,Zn as Nn,Zr as Pn,_r as Fn,ai as In,bi as Ln,br as Rn,cr as zn,ct as Bn,ei as Vn,gn as Hn,go as Un,gr as Wn,hn as Gn,hr as Kn,ii as qn,ir as Jn,it as Yn,j as Xn,k as Zn,kt as Qn,mn as $n,mo as er,n as tr,na as H,ni as nr,oi as rr,ot as ir,p as ar,q as or,qt as sr,r as cr,ra as lr,ri as ur,rr as dr,si as fr,sr as pr,st as mr,ti as hr,wa as gr,wi as _r,xi as vr,xr as yr,yi as br,yn as xr,yr as Sr}from"./control-ui-core-9qYjK5B2.js";import{$ as U,Q as Cr,X as W,Y as wr,a as Tr,c as Er,ct as Dr,d as Or,i as kr,j as Ar,k as jr,nt as Mr,s as Nr,u as Pr,ut as G}from"./lit-runtime-B8uOr6OX.js";import{Et as Fr,Gt as Ir,Lt as Lr,Mt as Rr,Nt as zr,Tt as Br,Ut as Vr,Wt as Hr,_r as Ur,ar as Wr,br as Gr,cr as Kr,fr as qr,hr as Jr,in as Yr,lr as Xr,or as Zr,pr as Qr,sr as $r,ur as ei,yr as ti}from"./control-ui-boot-shared-umGE-sEP.js";import{I as ni,L as ri,T as ii,w as ai}from"./control-ui-boot-chat-VeeaXyJz.js";import{c as oi,d as K,l as si,u as ci}from"./gateway-runtime-Cr51Pi7N.js";import{$a as li,Ar as ui,At as di,B as fi,Do as pi,Ea as mi,Eo as hi,Fa as gi,Fn as _i,Fo as vi,Fr as yi,Ft as bi,G as xi,Gi as Si,Gt as Ci,H as wi,Hi as Ti,Ia as Ei,Io as Di,Ja as Oi,Jr as ki,Jt as Ai,K as ji,Ki as Mi,Lr as Ni,Mn as Pi,Mt as Fi,No as Ii,Nr as Li,Nt as Ri,Or as zi,Pr as Bi,Pt as Vi,R as Hi,Ri as Ui,Rr as Wi,So as Gi,Ta as Ki,Ti as qi,Tr as Ji,U as Yi,Ui as Xi,V as Zi,Vr as Qi,Wi as $i,Wt as ea,Y as ta,Yi as na,Yt as ra,Z as ia,Za as aa,an as oa,ao as sa,bo as ca,br as la,ca as ua,cn as da,ct as fa,da as pa,di as ma,dn as ha,dt as ga,ft as _a,gi as va,in as ya,jo as ba,jt as xa,ko as Sa,kr as Ca,la as wa,lt as Ta,ma as Ea,no as Da,nt as Oa,oo as ka,ot as Aa,pt as ja,q as Ma,qr as Na,qt as Pa,rn as Fa,rt as Ia,sn as La,st as Ra,to as za,un as Ba,uo as Va,ut as Ha,va as Ua,vi as Wa,wi as Ga,wr as Ka,xa as qa,xo as Ja,xr as Ya,yo as Xa,z as Za,zr as Qa}from"./control-ui-boot-shared-DJkUdZmL.js";import{$t as $a,B as eo,Bi as to,Di as no,Do as ro,Ei as io,Er as ao,Fi as oo,Ft as so,Ha as co,Ni as lo,Pt as uo,Qa as fo,Qi as po,Ra as mo,Rt as ho,To as go,Tr as _o,Xa as vo,Xr as yo,Yi as bo,Za as xo,Zr as So,_a as Co,_t as wo,en as To,fa as q,ha as Eo,hi as Do,ia as Oo,ii as J,oa as ko,ro as Ao,sa as jo,ta as Mo,ua as No,va as Po,wo as Fo,zt as Io}from"./ui-DuRgK6kL.js";import{b as Lo,h as Ro}from"./control-ui-boot-shared-Sj2zqjOr.js";import{Bi as zo,Ci as Bo,F as Vo,Gn as Ho,Hn as Uo,I as Wo,M as Go,Mr as Ko,Mt as qo,N as Jo,Nt as Yo,On as Xo,P as Zo,Pr as Qo,S as $o,Sr as es,Ti as ts,Un as ns,Wn as rs,X as is,_t as as,at as os,ca as ss,cr as cs,da as ls,fa as us,gt as ds,ht as fs,ii as ps,in as ms,it as hs,jn as gs,kn as _s,kt as vs,la as ys,lr as bs,ma as xs,oa as Ss,on as Cs,pa as ws,sa as Ts,ua as Es,x as Ds,xr as Os,zi as ks}from"./control-ui-boot-shared-xfDhIVun.js";import{$d as As,$i as js,$l as Y,$n as Ms,$r as Ns,$t as Ps,$u as Fs,Aa as Is,Ac as Ls,Ad as Rs,Ai as zs,Al as Bs,An as Vs,Ar as Hs,As as Us,Au as Ws,Ba as Gs,Bd as Ks,Bf as qs,Bl as Js,Bn as Ys,Br as Xs,Bt as Zs,Bu as Qs,Ca as $s,Cc as ec,Cd as tc,Ci as nc,Cl as rc,Cr as ic,Cu as ac,D as oc,Da as sc,Dd as cc,Df as lc,Di as uc,Dn as dc,Dr as fc,Ds as pc,Du as mc,E as hc,Ea as gc,Ed as _c,Ef as vc,Ei as yc,El as bc,Er as xc,Eu as Sc,Fa as Cc,Fd as wc,Ff as Tc,Fi as Ec,Fl as Dc,Fn as Oc,Fs as kc,Ft as Ac,Fu as jc,Ga as Mc,Gi as Nc,Gl as Pc,Gn as Fc,Gr as Ic,Gt as Lc,Gu as Rc,Ha as zc,Hd as Bc,Hl as Vc,Hn as Hc,Hr as Uc,Ht as Wc,Hu as Gc,Ia as Kc,Id as qc,If as Jc,Ii as Yc,Il as Xc,In as Zc,Ir as Qc,Is as $c,It as el,Ji as tl,Jl as nl,Jn as rl,Jr as il,Jt as al,Ju as ol,Kd as sl,Ki as cl,Kl as ll,Kn as ul,Kr as dl,Kt as fl,Ku as pl,La as ml,Ld as hl,Lf as gl,Li as _l,Ln as vl,Lr as yl,Ls as bl,Lt as xl,Lu as Sl,Ma as Cl,Mf as wl,Mi as Tl,Ml as El,Mn as Dl,Mr as Ol,Ms as kl,Mu as Al,Na as jl,Nc as Ml,Ni as Nl,Nl as Pl,Nn as Fl,Nr as Il,Ns as Ll,Nt as Rl,Nu as zl,O as Bl,Oa as Vl,Od as Hl,Of as Ul,Oi as Wl,On as Gl,Or as Kl,Os as ql,Ou as Jl,Pa as Yl,Pd as Xl,Pf as Zl,Pi as Ql,Pl as $l,Pn as eu,Pr as tu,Ps as nu,Pt as ru,Pu as iu,Qd as au,Qi as ou,Ql as su,Qn as cu,Qr as lu,Qt as uu,Ra as du,Rd as fu,Ri as pu,Rl as mu,Rn as hu,Rr as gu,Rs as _u,Rt as vu,Ru as yu,Sa as bu,Sc as xu,Sd as Su,Sf as Cu,Si as wu,Sl as Tu,Sr as Eu,Ss as Du,Su as Ou,T as ku,Ta as Au,Tf as ju,Ti as Mu,Tl as Nu,Tr as Pu,Ts as Fu,Tu as Iu,Ua as Lu,Ud as Ru,Ul as zu,Un as Bu,Ur as Vu,Ut as Hu,Uu,Va as Wu,Vd as Gu,Vf as Ku,Vl as qu,Vn as Ju,Vr as Yu,Vs as Xu,Vt as Zu,Vu as Qu,Wa as $u,Wi as ed,Wl as td,Wn as nd,Wr as rd,Wu as id,Xc as ad,Xd as od,Xi as sd,Xl as cd,Xn as ld,Xr as ud,Xu as dd,Yd as fd,Yi as pd,Yl as md,Yn as hd,Yr as gd,Yu as _d,Zc as vd,Zi as yd,Zl as bd,Zn as xd,Zr as Sd,_ as Cd,_a as wd,_d as Td,_f as Ed,_i as Dd,_l as Od,_n as kd,_o as Ad,_u as jd,ac as Md,ai as Nd,ao as Pd,ar as Fd,au as Id,ba as Ld,bc as Rd,bd as zd,bi as Bd,bl as Vd,bn as Hd,bo as Ud,br as Wd,bs as Gd,bu as Kd,ca as qd,cd as Jd,cf as Yd,ci as Xd,cs as Zd,d as Qd,da as $d,dd as ef,df as tf,di as nf,dn as rf,do as af,dr as of,dt as sf,du as cf,ea as lf,ed as uf,ei as df,el as ff,en as pf,er as mf,eu as hf,f as gf,fa as _f,fd as vf,ff as yf,fi as bf,fn as xf,fs as Sf,fu as Cf,ga as wf,gd as Tf,gf as Ef,gi as Df,gl as Of,gn as kf,go as Af,gr as jf,gs as Mf,gu as Nf,h as Pf,ha as Ff,hc as If,hd as Lf,hf as Rf,hi as zf,ho as Bf,hu as Vf,ia as Hf,ic as Uf,if as Wf,ii as Gf,in as Kf,ir as qf,iu as Jf,ja as Yf,jf as Xf,ji as Zf,jl as Qf,jn as $f,jr as ep,js as tp,ju as np,ka as rp,kd as ip,kl as ap,kn as op,kr as sp,ks as cp,ku as lp,la as up,ld as dp,lf as fp,li as pp,lo as mp,lu as hp,m as gp,ma as _p,mc as vp,md as yp,mf as bp,mi as xp,mo as Sp,mr as Cp,mu as wp,na as Tp,nc as Ep,nd as Dp,ni as Op,nn as kp,nr as Ap,nu as jp,oa as Mp,od as Np,of as Pp,oi as Fp,or as Ip,ou as Lp,p as Rp,pa as zp,pc as Bp,pd as Vp,pf as Hp,pi as Up,pn as Wp,po as Gp,pr as Kp,pu as qp,qa as Jp,qd as Yp,qi as Xp,ql as Zp,qn as Qp,qr as $p,qu as em,ra as tm,rc as nm,rd as rm,rf as im,ri as am,rn as om,rr as sm,ru as cm,sd as lm,sf as um,si as dm,so as fm,sr as pm,su as mm,ta as hm,td as gm,tf as _m,ti as X,tr as vm,tu as ym,ua as bm,ud as xm,uf as Sm,ui as Cm,uo as wm,ur as Tm,ut as Em,uu as Dm,va as Om,vc as km,vd as Am,vi as jm,vl as Mm,vn as Nm,vo as Pm,vs as Fm,vu as Im,wa as Lm,wc as Rm,wd as zm,wi as Bm,wl as Vm,wr as Hm,wu as Um,xd as Wm,xi as Gm,xl as Km,xr as qm,xu as Jm,ya as Ym,yd as Xm,yf as Zm,yi as Qm,yl as $m,yn as eh,yo as th,yr as nh,yu as rh,za as ih,zf as ah,zi as oh,zl as sh,zn as ch,zr as lh,zt as uh,zu as dh}from"./control-ui-boot-shared-D3oo_6Fq.js";import{G as fh,K as ph,W as mh,at as hh}from"./control-ui-boot-shared-D4XEBdOG.js";import"./control-ui-boot-shared-styles-BaQ2sAfZ.js";import{D as gh,G as _h,O as vh,b as yh,m as bh,n as xh,p as Sh,t as Ch,v as wh,w as Th,x as Eh,y as Dh}from"./control-ui-boot-chat-Ck7W_FPO.js";import{At as Oh,B as kh,C as Ah,Dn as jh,Dt as Mh,Et as Nh,Ft as Ph,G as Fh,H as Ih,Hn as Lh,In as Rh,J as zh,Jt as Bh,K as Vh,Kt as Hh,Nt as Uh,Ot as Wh,T as Gh,Tn as Kh,U as qh,V as Jh,W as Yh,X as Xh,Xt as Zh,Y as Qh,Yt as $h,Z as eg,_t as tg,bt as ng,dn as rg,dt as ig,ft as ag,gt as og,ht as sg,in as cg,jt as lg,kt as ug,lt as dg,mt as fg,nn as pg,on as mg,pt as hg,q as gg,rn as _g,rt as vg,ut as yg,vt as bg,w as xg,wn as Sg,wt as Cg,yt as wg}from"./control-ui-boot-chat-C8hdsB2M.js";import{$ as Tg,$n as Eg,$t as Dg,A as Og,An as kg,At as Ag,B as jg,Bn as Mg,Bt as Ng,C as Pg,Ct as Fg,Dn as Ig,Dt as Lg,E as Rg,En as zg,Et as Bg,F as Vg,Fn as Hg,Ft as Ug,G as Wg,Gn as Gg,Gt as Kg,H as qg,Hn as Jg,Ht as Yg,In as Xg,It as Zg,J as Qg,Jt as $g,K as e_,Kn as t_,Kt as n_,L as r_,Ln as i_,Lt as a_,M as o_,Mn as s_,Mt as c_,N as l_,Nn as u_,Nt as d_,On as f_,Ot as p_,P as m_,Pn as h_,Pt as g_,Q as __,Qt as v_,R as y_,Rn as b_,Rt as x_,S as S_,St as C_,T as w_,Tn as T_,Tt as E_,U as D_,Un as O_,Ut as k_,V as A_,Vn as j_,W as M_,Wn as N_,Wt as P_,X as F_,Xt as I_,Y as L_,Z as R_,Zt as z_,_ as B_,_r as V_,_t as H_,an as U_,at as W_,bt as G_,c as K_,cn as q_,ct as J_,d as Y_,dn as X_,dt as Z_,en as Q_,er as $_,et as ev,f as tv,fn as nv,ft as rv,g as iv,gr as av,gt as ov,h as sv,ht as cv,in as lv,ir as uv,it as dv,j as fv,jn as pv,jt as mv,k as hv,kn as gv,kt as _v,l as vv,ln as yv,lt as bv,m as xv,mn as Sv,mt as Cv,nn as wv,nr as Tv,nt as Ev,on as Dv,ot as Ov,p as kv,pt as Av,q as jv,qn as Mv,qt as Nv,rn as Pv,rr as Fv,rt as Iv,s as Lv,sn as Rv,st as zv,tn as Bv,tr as Vv,tt as Hv,u as Uv,un as Wv,ut as Gv,v as Kv,vt as qv,w as Jv,wn as Yv,wt as Xv,x as Zv,xt as Qv,yt as $v,z as ey,zn as ty,zt as ny}from"./control-ui-boot-chat-XcDaYmck.js";import{_ as ry,g as iy,n as ay,o as oy,r as sy}from"./control-ui-boot-chat-DxoNF0Ad.js";function cy(e){let t=fy.get(e);return t||(t={panes:new Map,listeners:new Set},fy.set(e,t)),t}function ly(e,t,n){let r=cy(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 uy(e,t){let{listeners:n}=cy(e);return n.add(t),()=>n.delete(t)}function dy(e,t,n,r){if(!Un(t)||!n)return{page:t};let i={hello:e.gateway.snapshot.hello,agentsList:e.agents.state.agentsList,assistantAgentId:r},a=j(i,n),o=e.sessions.state.result?.sessions.find(e=>S(i,n,e.key,e.agentId)),s=i.agentsList?.agents.find(e=>e.id===a.agentId),c=_h({session:o,agentWorkspace:s?.workspace}),l=[...cy(e).panes.values()].find(e=>e.sessionKey===a.sessionKey&&e.agentId===a.agentId);return{page:t,title:o?.label||o?.displayName||a.sessionKey,...a,sessionId:o?.sessionId,workspace:c.root??void 0,...l}}var fy;function py(){return(py=e((()=>{er(),I(),fy=new WeakMap})))()}function my(e){let t=q(e),n=typeof t?.stopReason==`string`?t.stopReason.toLowerCase():``;return rm(e)!==null||q(t?.openclawAbort)?.aborted===!0||[`aborted`,`cancelled`,`canceled`,`timeout`,`timed_out`].includes(n)}function hy(e){if(pl(e))return`commentary`;if(mh(e,{phase:`final_answer`}))return`final_answer`;let t=ph(e);if(t)return t;let n=q(e),r=q(n?.__openclaw);return r?.mirrorOrigin===`codex-app-server`&&r.runTerminal===!0&&n?.stopReason===`stop`&&!my(e)?`final_answer`:void 0}function gy(){return(gy=e((()=>{fh(),Rc(),uf()})))()}function _y(e){return e.name===`sessions_yield`&&Object.hasOwn(e,`args`)&&e.completed===!0&&e.isError!==!0&&(q(e.details)?.status===`yielded`||oo(e.outputText??``)?.status===`yielded`)}function vy(e){return ma(e).some(e=>e.name===`sessions_yield`)}function yy(e,t,n=!0){let r=[],i=!1,a=new Set;for(let o=e.length-1;o>=0;o--){let s=e[o],c=s.kind===`message`?q(s.message):null,l=(c?ma(c):[]).filter(e=>e.name===`sessions_yield`),u=l.filter(_y),d=[],f=c?tc(c):null;for(let e=u.length-1;e>=0;e--){let n=u[e],r=i||[...a].some(e=>n.runId!==void 0&&e!==n.runId)||t!==void 0&&(n.runId!==void 0&&t.runId!=null&&t.runId!==n.runId||f!==null&&t.startedAt!=null&&t.startedAt>f);d.unshift({kind:`notice`,key:`yield:${s.key}:${n.id}`,sessionsYield:r?`resumed`:`waiting`,label:V(r?`chat.yieldResumed`:`chat.yieldWaiting`),text:``,timestamp:f??0}),i=!0}let p=[s];if(c&&l.length>0&&!n&&$i(c))p=[];else if(c&&l.length>0&&Array.isArray(c.content)){let e=new Set(l.map(e=>e.callId)),t=new Set(u.map(e=>e.callId)),r=c.content.filter(r=>{let i=q(r);if(!i||!Jt(i.type)&&!Ht(i.type))return!0;let a=_c(i,c);return!n||Jt(i.type)&&(a?e.has(a):i.name===`sessions_yield`)?!1:a?!t.has(a):!(u.length>0&&i.name===`sessions_yield`)});p=r.length?[{...s,kind:`message`,message:{...c,content:r,activity:qi(c).filter(t=>n&&!e.has(t.toolCallId??t.itemId))}}]:[]}r.push([...p,...d]);let m=c?dd(c):s.kind===`stream`||s.kind===`reading-indicator`?s.runId:void 0;m&&a.add(m),i||=qc(s)||s.kind===`stream`||c!==null&&Mi(na(c))===`assistant`&&Lf(c)}return r.toReversed().flat()}function by(e){if(xy.has(e))return xy.get(e)??null;let t=yy(Ll(dp(Xt([...e])))).findLast(e=>e.kind===`notice`&&e.sessionsYield===`waiting`),n=t?.kind===`notice`&&t.timestamp>0?t.timestamp:null;return xy.set(e,n),n}var xy;function Sy(){return(Sy=e((()=>{lo(),zt(),qt(),y(),Xi(),Ga(),va(),Tf(),Rc(),nu(),fu(),xy=new WeakMap})))()}function Cy(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 wy(e,t){return e.replace(RegExp(`^${hh(t)}(?::|:|-|—)?[ \\t]+`),``)}function Ty(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:za(e.sender),senderSession:e.senderSession,clientSourcesKey:Ut(e.sourceClients??[]),text:n.join(`
`)}}function Ey(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||wy(n.text,n.senderLabel)===r.text}function Dy(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 Oy(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=Si(a.message),o={kind:`message`,item:a,normalized:e},s=Mi(e.role).toLowerCase(),c=Xm(a.message),l=c?null:Ty(e,s),u=zm(a.message),d=c?null:Cy(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`&&Ey(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=Dy(l);if(e&&e===Dy(n)){p.item.duplicateCount=(p.item.duplicateCount??1)+1;continue}}t.push(o),n=l,r=d,i=f}return t}function ky(){return(ky=e((()=>{Vt(),Xi(),li(),Tf()})))()}function Ay(e,t){return hy(e)??(t===`none`?`activity`:`reply`)}function jy(e,t,n){if(!e.id)return JSON.stringify([`sender-label`,e.username??e.name??``]);let r=Da({type:`profile`,id:e.id});return t.has(r)||r===n?r:JSON.stringify([`sender`,e.id])}function My(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=Rs(t.message);e&&o.set(e,o.has(e)?null:t)}e.sender?.identity?i.add(Da(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`&&hl(e)&&(c={})}for(let e of a)i.add(jy(e,i,r));let l=i.size>=2,u=[],d=c;for(let t=e.length-1;t>=0;--t){let n=e[t],r=n.kind===`group`?n.messages.map(e=>s.get(e.key)).find(Boolean):n.kind===`stream`?s.get(n.key):void 0;u[t]=r??d,r&&(d=r)}for(let[t,n]of e.entries()){let{sender:e,message:r,turnSource:i}=u[t];if(n.kind===`stream`){l&&(n.replyToSender=e,n.replyToMessage=r);continue}if(n.kind!==`group`||(l&&(n.replyShared=!0),n.role!==`assistant`||hl(n)))continue;let a=n.runId&&n.messages.some(e=>e.replyTarget?.kind===`current`)?o.get(n.runId):void 0;i&&(n.replyTurnSource=i),a&&(n.replyCurrentSource=a),l&&e&&(n.replyToSender=e,n.replyToMessage=r)}return e}function Ny(e,t={}){let n=Fy(e,t.items&&Py(e,t.items));return My(n,t.items?Fy(t.items):n,t)}function Py(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||=wc(e);return r}function Fy(e,t){let n=[],r=null,i=null,a=null;for(let o of Oy(e)){if(o.kind!==`message`){r&&=(n.push(r),null),n.push(o);continue}let{item:e,normalized:s}=o,c=Mi(s.role),l=La(e.message,s),u={message:e.message,key:e.key,duplicateCount:e.duplicateCount,...s.replyTarget?{replyTarget:s.replyTarget}:{},hasVisibleContent:l===`non-text`||!!ha(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`?dd(e.message):void 0,h=c===`user`?tp(e.message):null,g=c===`user`?h??Rs(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||q(q(e.message)?.__openclaw)?.turnBoundary===!0,b=c===`assistant`&&r?.role===`assistant`&&Ay(r.messages[0]?.message,r.visibleContent)!==Ay(e.message,l);!r||y||Ks(e.message)&&!s.senderSession?.sessionKey||r.role!==c||r.runId!==m||Ks(r.messages[0]?.message)!==Ks(e.message)||i!==g||c===`assistant`&&a!==_||b||Ut(r.sourceClients??[])!==Ut(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||za(r.sender)!==za(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 Iy(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 Ly(e){return e.kind===`group`&&(e.role===`assistant`||e.role===`tool`)&&!Xl(e)}function Ry(e){if(e.kind!==`group`||e.isStreaming||zy(e,!1))return!1;let t=e.role.toLowerCase();return t===`tool`||t===`assistant`&&!Xl(e)&&Ay(e.messages[0]?.message,e.visibleContent)!==`final_answer`}function zy(e,t=!0){return e.visibleContent===`non-text`||t&&e.visibleContent===`text`}function By(e){return e.role.toLowerCase()===`assistant`&&!Xl(e)&&zy(e)}function Vy(e){return e.kind===`group`&&!e.isStreaming&&By(e)&&Ay(e.messages[0]?.message,e.visibleContent)!==`commentary`}function Hy(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 Uy(e,t){let[n,r,i,a,...o]=Fo(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{continuationTurnIndexes:l,precedingContinuationTurnIndexes:u}=pc(s,Hy),d=s.map((e,t)=>l.has(t)?void 0:e.findLast(Vy)),f=s.map((e,t)=>{let n=d[t];return n?e.lastIndexOf(n):-1});for(let e=s.length-2;e>=0;--e){let t=l.get(e);!d[e]&&t!==void 0&&(d[e]=d[t])}let p=new Set;if(t.runWorking){let e=s.length-1;for(p.add(e);;){let t=u.get(e);if(t===void 0)break;e=t,p.add(e)}}let m=[];for(let[e,n]of s.entries()){if(p.has(e)||n.some(e=>e.kind===`stream-run`||e.kind===`group`&&e.isStreaming)){m.push(...n);continue}let r=f[e]??-1,i=d[e];if(!i){m.push(...n);continue}let a=r>=0?r:n.length-1,o=a;for(;a>0&&Ly(n[a-1]);)--a;let c=Wy(n);for(;o+1<n.length;){let e=n[o+1];if(!Ly(e)||e.runId&&!c.has(e.runId))break;o+=1}let u=[],h=[],g=new Map,_;for(let e=a;e<=o;e+=1){let t=n[e];e!==r&&Ry(t)&&(r<0||e<r||!t.messages.some(({message:e})=>ma(e).some(Wa)))?(u.push(t),_&&g.set(t.key,_)):(h.push(t),_=t.key)}if(u.length===0){m.push(...n);continue}let v=t.session,y=v?.runtimeMs,b=v?.key===t.sessionKey&&i.runId!==void 0&&v.lastRunId===i.runId&&(v.status===`done`||v.status===`failed`||v.status===`timeout`||v.status===`killed`)&&typeof y==`number`&&Number.isFinite(y)&&y>=0?y:null,x=s[l.get(e)??-1]?.[0],S=r>=0&&!hl(i)&&!u.some(hl)&&h.slice(0,h.indexOf(i)).every(e=>e.kind===`group`&&!hl(e)&&e.runId===i.runId)?i.runId:void 0;m.push(...n.slice(0,a)),m.push({kind:`work-group`,key:`work:${r>=0||!x?i.key:x.key}`,groups:u,...S?{replyRunId:S}:{},...g.size>0?{previewAfterGroup:g}:{},durationMs:b}),m.push(...h,...n.slice(o+1))}return m}function Wy(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 Gy(e,t={}){if(t.searchActive)return e;let n=e=>{if(e.isStreaming||e.visibleContent===`non-text`||hl(e)||e.messages.some(({message:e,hasVisibleContent:t})=>{let n=q(e);return n?.role===`assistant`&&(t||hy(e)===`final_answer`||my(e)||n.stopReason===`error`)}))return!1;let t=e.role.toLowerCase();return t===`tool`||t===`assistant`&&e.visibleContent===`none`&&e.messages.some(({message:e})=>ma(e).length>0)},r=[],i=[],a=()=>{let[e]=i;e&&(r.push(i.length===1?e:{kind:`activity-run`,key:`activity:${e.key}`,groups:i}),i=[])};for(let t of e){if(t.kind===`group`&&n(t)){i.push(t);continue}a(),r.push(t)}return a(),r}function Ky(){return(Ky=e((()=>{Vt(),Ba(),Xi(),Fa(),li(),va(),gy(),ky(),Tf(),Rc(),fu(),ql()})))()}function qy(e,t,n,r,i){let a=(n.queue??[]).toSorted(Ui),{queue:o,pendingInputs:s}=Iu(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()&&!zd(e,n.searchQuery,n.messageRecovery))for(let e of t)u.add(e.key)};for(let t of s){let r=hp([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}Td(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(!yu(e))continue;let t=Su(e);if(!t)continue;let i={items:[{kind:`message`,key:e.sendRunId?dp([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&&!zl(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=Ur(e.message);return gm(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`||Lf(e.message)).map(e=>e.key),{pendingKeys:l,historicalKeys:c,hiddenKeys:u,activeInputKey:f}}function Jy(){return(Jy=e((()=>{Jr(),Cf(),np(),Tf(),Im(),uf()})))()}function Yy(e,t,n){let r=xm(e,t);return r?`canvas:${r}`:`${n}:canvas`}function Xy(e,t={keys:[]}){let n=[],r=e.toolMessages.filter(e=>q(e)!==null),i=dp(r).map(e=>({projection:{item:e},runId:ro(e.message.runId),callId:ro(e.message.toolCallId),preview:vf(e.message)})),a=e.queue??[],o=e.streamSegments,s=null,c=()=>s??=Sl(e.sessionKey,e.runId??null,e.streamStartedAt,a,o,r),l=e.persistCommentary===!1&&(e.runWorking||e.runActive)?ro(c().runId):void 0,u=Xt(e.messages.filter(t=>!Ca(t)&&(e.persistCommentary!==!1||!pl(t)||l!==void 0&&dd(t)===l))),d=e.searchOpen===!0&&!!e.searchQuery?.trim(),f=new Set,p=new Set,m=u.map(Gu),h=dp(u),g={previews:[],lastMatchingAssistantIndex:-1},_=h.map((t,n)=>{let r=m[n],i=r&&Mi(r.role);return(i===`user`||i===`system`)&&(g={previews:[],lastMatchingAssistantIndex:-1}),i===`assistant`&&r&&(!d||zd(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=q(i)??{},s=q(o.__openclaw);if(s?.kind===`compaction`||Al(i)){let e=v!=null&&iu(i,v),r=mc(s??{},tc(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(lp(s,c.timestamp??Date.now(),t));continue}if(Mi(c.role)===`system`){let e=wa(i);e?.trim()&&n.push({kind:`notice`,key:a,text:e,timestamp:c.timestamp});continue}let l=c.role.toLowerCase()===`toolresult`,h=l?vf(i):null;if(h){let e=xm(i,h);e&&p.add(e)}let g=h&&_[t].previews.find(({preview:e})=>Ti(e,h.preview));h&&g&&(g.item.message=Jd(g.item.message,h.preview,h.text));let x=h!=null&&!g&&(!d||_[t].lastMatchingAssistantIndex>t);if(h&&x&&n.push({kind:`message`,key:Yy(i,h,a),message:ef(h,h.timestamp??ip(u,t))}),!e.showToolCalls&&l&&!vy(i))continue;let S=e.searchQuery??``;e.searchOpen&&S.trim()&&!zd(i,S,e.messageRecovery)&&f.add(a),(Lf(i,c)||c.role.toLowerCase()===`assistant`)&&n.push(...Qs(r,c))}let x=e.runId??(e.stream!==null||a.some(yu)?c().runId:null),S=id(n),{pendingKeys:C,historicalKeys:ee,hiddenKeys:w,activeInputKey:T}=qy(n,u,e,t,x),E=()=>n.filter(e=>!ee.has(e.key)),D=Gc(E()),O=(x?D(x):null)??(T?{afterKey:T}:S),k=e=>{let{minimum:t,maximum:r}=Am(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=xm(e.item.message,t);if(r&&p.has(r))continue;let i=k(_d(D,e.item.message.runId,x,O)??(!e.item.message.runId&&T?O:void 0)),{minimum:a,maximum:o}=Am(n,i??void 0),s=yp(n,t.timestamp,a,o);if(s){n[s.index]={...s.item,message:Jd(s.item.message,t.preview,t.text)};continue}if(d)continue;let c=Vp(n,t.timestamp,a,o),l=n[c],u=l?.kind===`message`?tc(l.message):null,f=t.timestamp!=null&&u!=null?Math.min(t.timestamp,u):t.timestamp;n.splice(c,0,{kind:`message`,key:Yy(e.item.message,t,e.item.key),message:ef(t,f)})}n=n.filter(e=>e.kind!==`message`||Lf(e.message));let A=[];if(v&&y&&!b){let e=v.startedAt??v.completedAt??Date.now();A.push({item:{...mc({},e,0,v.phase===`complete`?`complete`:`active`),key:y}})}let j=new Map,M;for(let e of o){let t=ro(e.afterBoundaryRunId)??M;t&&j.set(e,t),M=ro(e.boundaryRunId)??M}let te=o.filter(Pa),ne=o.filter(e=>!Pa(e)&&e.boundaryMarker!==!0),N=Uu();for(let e of i)N.add(e.runId,e.callId,e.projection);let P=Gc(E()),F=(e,t,n)=>{let r=_d(P,e,x,O)??(!e&&T?O:void 0),i=t?P(t)?.afterKey:void 0,a=n?P(n):void 0;return k(r||i||a?{...r,...a?.afterKey?{afterKey:a.afterKey}:{},...a?.beforeKey?{beforeKey:a.beforeKey}:{},...i?{beforeKey:i}:{}}:void 0)};if(!d){e.archiveNotice&&A.push({item:e.archiveNotice});for(let t of e.guardianNotices??[])A.push({item:Jl(t),bounds:F(t.runId)})}let re=Uu(),ie=Uu();for(let e of ne){let t=ro(e.toolCallId),n=ro(e.runId),r=ro(e.boundaryRunId),i=j.get(e);r&&re.add(n,t,r),i&&ie.add(n,t,i)}let ae=(e,t,n)=>{let r=j.get(e);A.push({item:{kind:`stream`,key:t,text:n,startedAt:e.ts,isStreaming:!1,...ol(e.runId),...em(r??e.runId)},bounds:F(e.runId,e.boundaryRunId,r)})},oe=null,se=Math.max(ne.length,i.length);for(let t=0;t<se;t++){let n=ne[t];if(n){let r=cc(n.text),i=Ai(n),a=i?ra(r,oe):r;if(i&&(oe=Ci(oe,r)),a.length>0&&n.persisted!==!0){let r=`stream-seg:${e.sessionKey}:${t}`;ae(n,r,a);let i=N.get(ro(n.runId),n.toolCallId?.trim());i&&(i.predecessorKey=r)}}let r=i[t];if(r&&(e.showToolCalls||vy(r.projection.item.message))){let e=re.get(r.runId,r.callId),t=ie.get(r.runId,r.callId);r.projection.bounds=F(r.runId,e,t),A.push(r.projection)}}for(let t of te){let n=cc(t.text);n.length>0&&ae(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};A.push({item:e,bounds:t.runId?F(t.runId):void 0})}Qu(n,i.map(e=>e.projection)),Td(n,A);let ce=e.stream===null&&e.loading===!0&&n.length===0,le=e.stream!==null&&e.stream.trim().length===0,ue=(!v||v.phase===`complete`)&&(e.runWorking===!0&&!ce||le||a.some(e=>(e.sendState===`submitting`||e.sendState===`sending`)&&yu(e)));e.runWorking!==!0&&e.stream===null&&!ue&&Ws(e.sessionKey);let de=x?cp(u,x):null,fe=de&&(!M||u.findIndex(e=>Rs(e)===M)<=de.index)?de.runId:M,I=fe??x,pe=k((I?Gc(E())(I):null)??(T?{afterKey:T}:null)),me=e=>{if(pe){let{maximum:t}=Am(n,pe);n.splice(t,0,e)}else n.push(e)};if(e.stream!==null){let t=cc(e.stream),r=ea(o,cc),i=ra(t,r);if(i.length>0&&!ui(i).shouldSkip){let t=c(),r=e.runId??t.runId;me({kind:`stream`,key:fe?`${t.key}:after:${fe}`:t.key,text:i,startedAt:Hl(n,e.streamStartedAt??Date.now()),isStreaming:!0,...ol(r),...em(fe??r)})}}if(ue){let t=c(),n=e.runId??t.runId;me({kind:`reading-indicator`,key:t.key,startedAt:t.startedAt,...ol(n),...em(fe??n)})}let he=f.size>0||w.size>0?new Set([...f,...w]):void 0,ge=t=>yy(t,e.runActive||e.runWorking?{runId:x,startedAt:e.streamStartedAt}:void 0,e.showToolCalls);return Ny(ge(Ll(n,he)),{items:he?ge(Ll(n)):void 0,people:e.replyPeople,localPerson:e.replyLocalPerson})}function Zy(){return(Zy=e((()=>{qt(),zi(),pa(),Xi(),np(),Sy(),dh(),Ky(),Jy(),Tf(),Rc(),nu(),fu(),ql()})))()}function Qy(e){return e.kind===`agent-run-frame`?e.parts.flatMap(Qy):e.kind===`group`?[e]:e.kind===`work-group`||e.kind===`activity-run`?e.groups:[]}function $y(e){if(e.kind===`work-group`){if(e.replyRunId)return e.replyRunId;if(e.groups.some(hl))return}if(e.kind===`stream-run`)return e.runId;let t=Qy(e),n=t[0]?.runId;return n&&t.every(e=>e.runId===n)?n:void 0}function eb(e){return e.kind===`work-group`&&e.replyRunId?!1:Qy(e).some(e=>e.messages.some(({message:e})=>my(e)||q(e)?.stopReason===`error`))}function tb(e){return e.kind===`stream-run`?e.parts.some(e=>e.kind===`reading-indicator`||e.kind===`stream`&&e.isStreaming):Qy(e).some(e=>e.isStreaming)}function nb(e){let t=e.messages[0]?.message,n=Ur(t),r=n?.runId;return r?`send:${r}`:n?.id?`entry:${n.id}`:void 0}function rb(e,t,n){return`agent-run:${JSON.stringify(n?[e,t,n]:[e,t])}`}function ib(e,t){return t??e.flatMap(e=>e.kind===`stream-run`?e.parts:[]).find(e=>e.kind===`stream`&&e.key.includes(`:after:`))?.key}function ab(e,t){let n=q(e),r=hy(e),i=n?.stopReason,a=q(n?.__openclaw);return!(wa(e)?.trim()||Mf(e))||my(e)||r===`commentary`||i===`toolUse`||i===`error`||a?.mirrorOrigin===`codex-app-server`&&a.runTerminal!==!0?!1:!t||r===`final_answer`||i===`stop`}function ob(e){let t=e.flatMap(Qy).flatMap(e=>e.role===`assistant`?e.messages:[]).findLast(({message:e})=>ab(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&&ab(r.message,!1)?r:null}function sb(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 cb(e){return e.kind===`group`||e.kind===`work-group`||e.kind===`activity-run`||e.kind===`stream-run`}function lb(e,t={}){if(t.searchActive)return e;let n=[],r,i,a=new Set,o,s,c=[],l=(e=!1)=>{if(!s||c.length===0)return;let t=c.some(tb),l=t||e?null:ob(c);if(!r&&!t&&!l){n.push(...c),c=[],s=void 0;return}let u=r??`send:${s}`,d=rb(s,u,ib(c,o)),f=a.has(d)?rb(s,u,JSON.stringify([i,c[0].key])):d;a.add(d),n.push({kind:`agent-run-frame`,key:f,runId:s,boundaryId:u,outcome:e?{kind:`failed`}:t?{kind:`active`}:{kind:`completed`,actionOwner:l},parts:c}),c=[],s=void 0};for(let t of e){if(!cb(t)){l(),n.push(t),r=t.kind===`notice`&&t.startsTurn?t.boundaryId:void 0,o=r?void 0:t.key;continue}let e=Qy(t)[0];if(e&&wc(e)){l(),i=e.key,o=void 0;let a=nb(e);if(e.role===`user`||hl(e)||!a){n.push(t),r=a;continue}r=a}let a=t.kind===`stream-run`?t.boundaryId:void 0;a&&(a!==(r??(s?`send:${s}`:void 0))&&l(),r=a);let u=$y(t);if(t.kind===`activity-run`&&!u){l(),n.push(t);let e=t.groups.findLast(qc);e?(r=nb(e),i=e.key,o=void 0):t.groups.some(e=>e.runId===void 0)&&(r=void 0,o=t.key);continue}if(!u){l(),n.push(t),r=void 0,o=t.key;continue}let d=eb(t);s&&s!==u&&l(),s=u,c.push(t),d&&(l(!0),r=void 0,o=t.key)}return l(),n}function ub(){return(ub=e((()=>{Jr(),pa(),gy(),fu(),Fm()})))()}function db(e){if(e){jb.delete(e);return}jb.clear(),jc(),Nb.clear(),Pb.clear()}function fb(e,t){return e?.key===t?.key&&e?.message===t?.message}function pb(e,t){return e.role===t.role&&e.senderLabel===t.senderLabel&&e.senderSession?.sessionKey===t.senderSession?.sessionKey&&e.senderSession?.agentId===t.senderSession?.agentId&&e.senderSession?.label===t.senderSession?.label&&Ut(e.sourceClients??[])===Ut(t.sourceClients??[])&&JSON.stringify(e.sender)===JSON.stringify(t.sender)&&JSON.stringify(e.replyToSender)===JSON.stringify(t.replyToSender)&&fb(e.replyToMessage,t.replyToMessage)&&e.replyShared===t.replyShared&&fb(e.replyTurnSource,t.replyTurnSource)&&fb(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 mb(e,t){if(e.kind!==t.kind||e.key!==t.key)return!1;switch(t.kind){case`group`:return e.kind===`group`&&pb(e,t);case`message`:return e.kind===`message`&&e.message===t.message&&e.duplicateCount===t.duplicateCount;case`notice`:return e.kind===`notice`&&e.text===t.text&&e.label===t.label&&e.sessionsYield===t.sessionsYield&&e.startsTurn===t.startsTurn&&e.boundaryId===t.boundaryId&&e.timestamp===t.timestamp;case`divider`:return e.kind===`divider`&&e.compaction===t.compaction&&e.compactionId===t.compactionId&&e.label===t.label&&e.metric===t.metric&&e.description===t.description&&e.timestamp===t.timestamp;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)&&fb(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.runId===t.runId&&e.boundaryId===t.boundaryId;case`question`:return e.kind===`question`&&e.questionId===t.questionId&&e.startedAt===t.startedAt}return!1}function hb(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||s.senderSession?.sessionKey!==e.senderSession?.sessionKey||s.senderSession?.agentId!==e.senderSession?.agentId||s.senderSession?.label!==e.senderSession?.label||Ut(s.sourceClients??[])!==Ut(e.sourceClients??[])||za(s.sender)!==za(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&&mb(t,e)?t:e});return gb(l,e)?e:l}function gb(e,t){return e===t||e!==void 0&&t!==void 0&&e.length===t.length&&e.every((e,n)=>e===t[n])}function _b(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&&gb(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.questionPrompts===t.questionPrompts&&e.loading===t.loading&&gb(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 vb(e){return JSON.stringify([e.sessionKey,e.runId??null,e.streamStartedAt])}function yb(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!==vb(t))return!1;let i=ra(cc(t.stream),n.prefix);return i.length===0||ui(i).shouldSkip?!1:(e.items[n.index]={...r,text:i},!0)}function bb(e){return e.findIndex(e=>e.kind===`stream`&&e.isStreaming)}function xb(e){return Mb.get(e)??0}function Sb(e,t=`visible`){let n=jb.get(e.paneId);n||(n=new Map,jb.set(e.paneId,n));let r=Xc(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&&_b(i.input,e)){if(i.input.stream===e.stream)return i.items;if(i.input.stream!==null&&yb(i,e))return i.input=e,i.items}let a=hb(i.items,Xy(e,r.inputOrder));Mb.set(a,++i.generation),i.input=e,i.items=a;let o=bb(a);return i.liveStream=o<0?null:{index:o,identity:vb(e),prefix:ea(e.streamSegments,cc)},a}function Cb(e){return Fb.get(e)??0}function wb(e,t,n){e.has(t)&&e.get(t)===n||(e.set(t,n),Fb.set(e,Cb(e)+1))}function Tb(e,t){e.delete(t)&&Fb.set(e,Cb(e)+1)}function Eb(e,t,n){let r=new Set(n.map(e=>zm(e)?.id).filter(e=>typeof e==`string`).map(e=>Ru(t,e)));for(let t of e.keys())r.has(t)||Tb(e,t)}function Db(e){return Xc(Nb,e,()=>({expanded:new Map,initialized:new Set}))}function Ob(e){return Db(e).expanded}function kb(e){for(let[t,n]of Pb)if(z(t,e))return t!==e&&(Pb.delete(t),sh(Pb,e,n)),n;return Xc(Pb,e,()=>new Map)}function Ab(e,t,n,r=!1){let i=Db(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=e=>{c.add(e),o.has(e)||(wb(a,e,n),o.add(e))};for(let e of t)if(e.kind===`group`)for(let t of e.messages){let e=ma(t.message);for(let n=0;n<e.length;n++)l(`${t.key}:toolcard:${n}`);$i(t.message)&&l(`toolmsg:${t.key}`)}if(n&&!s?.autoExpandToolCalls)for(let e of o)wb(a,e,!0);if(!r)for(let e of o)c.has(e)||(o.delete(e),Tb(a,e));i.lastSync={items:new WeakRef(t),isFilteredProjection:r,autoExpandToolCalls:n}}var jb,Mb,Nb,Pb,Fb;function Ib(){return(Ib=e((()=>{Vt(),zi(),Xi(),li(),va(),I(),Bc(),np(),Zy(),Tf(),mu(),Ky(),ub(),jb=new Map,Mb=new WeakMap,Nb=new Map,Pb=new Map,Fb=new WeakMap})))()}function Lb(e,t){return Y(e,t),e.requestUpdate?.(),!1}function Rb(e){if(!e.client?.recoveryScopeReady||!e.client.recoveryScope)return null;let t=e.settings?.gatewayUrl??``,n=e.sessionKey,r=be(e,n),i=e.currentSessionId??void 0,a=!!e.selectedChatSessionIncognito,o=`${Ie(t,e.client.recoveryScope)}${JSON.stringify([n,r,i,a])}`,s=`${je(t)}:${o}`,c=Ub.get(e)??new Map;Ub.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=Co(t)&&`action`in t?Hr:Vr;u=t===`expired`?{retired:`expired`,pending:!1}:Co(t)&&Lo(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&&te(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 zb(e){try{let t=Rb(e)?.operation;return t?{pending:t.pending,retired:t.retired,onCheck:()=>Hb(e,void 0,t)}:void 0}catch{return}}async function Bb(e,t,n){return t.objective.trim()?t.sessionId&&t.sessionId!==e.currentSessionId?Lb(e,V(`chat.goals.sessionChanged`)):t.action===`edit`?Vb(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 Vb(e,t){return Hb(e,t)}async function Hb(e,t,n){let r=e.client;if(!r||!e.connected||!r.recoveryScopeReady)return Lb(e,V(`chat.goals.offline`));if(!r.recoveryScope)return Lb(e,V(`chat.goals.recoveryUnavailable`));let i;try{i=Rb(e)}catch(t){return Lb(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=ee(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&&Ne(e,a,o);if(p?.pending)return Lb(e,V(`chat.goals.actionPending`));if(p?.retired){if(t)return!1;let n=e.sessions,i=n.captureConnectionScope(),f=j(e,a);if(!i||!f.agentId)return!1;let m=()=>g()&&e.sessions===n&&n.isConnectionScopeCurrent(i)&&Rb(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:Wb});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),Y(e,null),!0):(t.status===`failed`&&Y(e,t.error),!1)}catch(t){return g()&&Y(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 Lb(e,V(`chat.goals.outcomeUnknown`))}if(!p){if(!t)return!1;if(!s||cd(e))return Lb(e,V(`chat.thread.loading`));let n={sessionKey:a,...o?{agentId:o}:{},sessionId:s,goalId:t.goalId,operationId:uo(),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`?Vr:Hr;if(!Lo(r,p.params))return Lb(e,V(`chat.goals.invalidRequest`));try{u?.setItem(l,JSON.stringify(p.params))}catch(t){return Lb(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`);Co(t)&&t.operationId===_.operationId&&(e?u?.setItem(l,JSON.stringify(e)):u?.removeItem(l))};p.pending=!0,Y(e,null),e.requestUpdate?.();try{let t=await r.request(`action`in _?`sessions.goal.update`:`sessions.goal.clear`,_,{timeoutMs:Wb});d.delete(c);try{v()}catch{}if(g()){if(t.replayed)return Kc(e,{sessionKey:a,agentId:o}).catch(t=>{g()&&(Y(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&&qd(e,t.runId,Date.now()))}return!0}catch(t){let n=t instanceof jn&&Co(t.details)?t.details:null,r=n?.reason,i=typeof r==`string`&&(n?.code===`GOAL_OPERATION_REJECTED`&&Gb.has(r)||r.startsWith(`goal-`)&&Gb.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()&&Y(e,i?B(t):`${V(`chat.goals.outcomeUnknown`)} ${B(t)}`),!1}finally{p.pending=!1,e.requestUpdate?.()}}var Ub,Wb,Gb;function Kb(){return(Kb=e((()=>{Ro(),Ir(),Nn(),y(),Fi(),Re(),vt(),Pt(),I(),so(),Zp(),Cc(),_f(),Ri(),Ub=new WeakMap,Wb=3e4,Gb=new Set([`expired`,`operation-conflict`,`session-rebound`,`goal-rebound`,`capacity`,`invalid`])})))()}var qb,Jb;function Yb(){return(Yb=e((()=>{wr(),ks(),y(),gi(),Wh(),Ua(),we(),Fe(),I(),jo(),qb=ko(()=>import(`./control-ui-boot-shared-DJkUdZmL.js`).then(e=>(e.d(),e.u)),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]),import.meta.url),Jb=class extends Oo{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=mi(()=>{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||!Ei(e)?null:{gatewayOwner:Ki(e.settings.gatewayUrl).gatewayOwner,recoveryScope:Ei(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?ug(t):null,i=``;if(t&&r?.entries.length){let e=lg(t,r.entries);e!==`unchanged`&&(r=ug(t)),e===`storage-failed`&&(i=V(`chat.outboxRecoveryStorageFailed`))}if(this.entries=r?.entries??[],this.error=i||(r?.blocked?V(`chat.outboxRecoveryFull`):``),n){let t=await(await qb).prepareDurableComposerRecovery(n);if(e!==this.generation||!this.isConnected)return;if(t.status===`storage-failed`)throw Error(`storage-failed`);this.drafts=t.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=j(t,t.sessionKey),a=Nh(t,i),o={...n,scopeKey:`chat:v3:${Ct(i)}`},c=await qb,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 zo({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?Oh(t,e,a,l.revision??0):(await c.restoreDurableComposerRecovery(o,e,l.revision??0,l.writeId,()=>s()&&JSON.stringify(Nh(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 le(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 r=`id`in e?e.session.goalMode:e.goalMode,i=`id`in e?e.session.replyTarget:e.replyTarget;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,r=`id`in e?e.session.goalMode:e.goalMode,i=`id`in e?e.session.replyTarget:e.replyTarget,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 zo({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?Mh(t,e,o):(await(await qb).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=qa(`id`in e?e.sourceScopeKey:e.scopeKey),n=this.host?j(this.host,this.host.sessionKey):void 0,r=t&&![`global`,`main`].includes(t.sessionKey)&&(!n||Ct(t)!==Ct(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 U`<div
class="chat-outbox-recovery-row"
title=${i>0?V(`chat.outboxRecoveryUpdated`,{time:A(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)?U`<span
class="chat-outbox-recovery__warning"
title=${V(`chat.outboxRecoveryUnconfirmed`)}
>${V(`chat.outboxRecoveryUnconfirmedLabel`)}</span
>`:W}
${r?U`<span class="chat-outbox-recovery__source"
>${V(`chat.outboxRecoverySource`,{chat:le(r.key,r)})}</span
>`:W}
<div class="chat-outbox-recovery__actions">
<button
class="btn btn--sm"
?disabled=${this.busy||!this.owner()}
@click=${()=>void this.recover(e)}
>
${V(`chat.outboxRecoveryRestore`)}
</button>
<button
class="btn btn--sm"
?disabled=${this.busy||!this.owner()}
@click=${()=>void this.discard(e)}
>
${V(`chat.outboxRecoveryDelete`)}
</button>
</div>
</div>`}render(){let e=[...this.entries,...this.drafts];return!e.length&&!this.error?W:U`<div class="chat-outbox-recovery">
${this.error?U`<div class="chat-outbox-recovery__error" role="alert" title=${this.error}>${this.error}</div>`:W}
${e.map(e=>this.renderEntry(e))}
</div>`}},customElements.define(`openclaw-chat-outbox-recovery`,Jb)})))()}function Xb(e,t){let n=1,r=t.length;if(r>Qb)return!1;for(let t of e){let e=t.browserAnnotation;if(e&&(n+=1,r+=e.modelContext.length,n>Zb||r>Qb))return!1}return!0}var Zb,Qb;function $b(){return($b=e((()=>{Zb=4,Qb=8e3})))()}function ex(e,t,n,r={}){if(!t.browserAnnotation)return!1;let i=t.browserAnnotation.modelContext,a=e.getOwner(),o=e.getSessionKey(),s=e.getAttachments(),c=s.findIndex(e=>e.id===t.id);if(c<0)return!1;e.setAttachments(s.filter(e=>e.id!==t.id)),e.requestUpdate(),e.focusComposer();let l=r.releasePayload??wt,u=!1,d=()=>{u||(u=!0,l(t.id))},f=r.presentToast??Ot;return f({message:n.removed,actionLabel:n.undo,onAction:()=>{if(u)return;if(e.getOwner()!==a||e.getSessionKey()!==o){d();return}let r=e.getAttachments();if(r.some(e=>e.id===t.id)){u=!0;return}if(!Xb(r,i)){d(),f({message:n.undoUnavailable});return}u=!0;let s=Math.min(c,r.length);e.setAttachments([...r.slice(0,s),t,...r.slice(s)]),e.requestUpdate(),e.focusRestoredAnnotation(t.id)},onDismiss:e=>{e!==`action`&&d()}})||d(),!0}function tx(){return(tx=e((()=>{lt(),Zl(),$b()})))()}function nx(e,t){return p(t)?o(e):ue(e,t)}function rx(e,t){return zu(e).subscriptionGeneration===t.generation&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&e.connected&&e.sessionKey.trim()===t.requestedKey&&nx(e,t.requestedKey)===(t.requestedAgentId??null)}async function ix(e){let t=zu(e).pendingSubscriptionReleases;t.size!==0&&await Promise.all([...t].map(async n=>{try{await e.sessions.unsubscribeMessages(n),t.delete(n)}catch{}}))}async function ax(e,t,n){for(let r=0;r<ux;r+=1)try{await e(t);return}catch(e){if(n?.()||r+1===ux)throw e;await po(lx*2**r)}}function ox(e){let t=zu(e);t.subscriptionGeneration+=1,t.subscriptionRetry?.abort(),delete t.subscriptionRetry,ym(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)ax(i,e).catch(()=>void 0)}function sx(e,t){let n=zu(e),r=e.client,i=e.connectionEpoch,a=e.sessionKey.trim(),o=nx(e,a);n.subscriptionRetry?.abort();let s=new AbortController;n.subscriptionRetry=s;let c=cx(e,s.signal,t).finally(()=>{n.subscriptionRetry===s&&(delete n.subscriptionRetry,ym(e,`subscription`,!1))}),l=n.subscriptionGeneration,u=c.then(t=>t&&r!==null&&rx(e,{generation:l,client:r,connectionEpoch:i,requestedKey:a,requestedAgentId:o})&&e.chatSessionMessageSubscriptionRequestedKey===a&&e.chatSessionMessageSubscription!=null);return n.subscriptionReady=u,u}async function cx(e,t,n){if(!e.client||!e.connected)return!1;let r=e.client,i=e.sessions,a=Date.now()+Nl,o=e.connectionEpoch,s=e.sessionKey.trim();if(!s)return!1;let c=go(e.chatSessionMessageSubscriptionRequestedKey),l=e.chatSessionMessageSubscription??null,u=go(l?.key),d=c??u,f=nx(e,s),p=f!==null&&d===s&&(l?.agentId??null)!==f;p&&(e.chatSessionApprovalQueue=[],e.requestUpdate?.());let m=zu(e),h=++m.subscriptionGeneration;await ix(e);let g=d!==null&&d!==s,_=l!==null&&(n?.force===!0||g||p),v=n?.force===!0||g||p||u===null||c===null,y=()=>!t.aborted&&e.sessions===i&&rx(e,{generation:h,client:r,connectionEpoch:o,requestedKey:s,requestedAgentId:f}),b=()=>{let t=m.subscriptionError;!t||m.pendingSubscriptionReleases.size>0||(m.subscriptionError=void 0,m.historyLoad.phase===`failed`&&m.historyLoad.message===t&&hf(e,{phase:`idle`}),e.requestUpdate?.())},x=t=>{let n=Ql(t);m.subscriptionError=n;let r=m.historyLoad;hf(e,{phase:`failed`,sessionKey:s,requestAgentId:ae(e,s)?Se(e):void 0,startup:r.phase!==`idle`&&`startup`in r?r.startup:!m.acceptedHistory,message:n,retryable:Yc(t,`sessions.messages.subscribe`)}),e.requestUpdate?.()},S=async()=>{let n=0;for(;y();)try{return await i.subscribeMessages(s,{agentId:f??void 0,...Fn(e.hello?.auth??null)?{includeApprovals:!0}:{}})}catch(r){if(!y()||!Yc(r,`sessions.messages.subscribe`))throw r;let i=a-Date.now();if(i<=0)throw r;if(ym(e,`subscription`,!0),await po(Math.min(k(r,n++),i),t),!y())return null;if(Date.now()>=a)throw r}return null};if(!_&&!v)return y()&&l&&z(l.key,s)&&(l.agentId??null)===f&&b(),y()&&l!==null;try{let t=Promise.resolve();_&&l&&(t=i.unsubscribeMessages(l));let n=v&&y()?S():Promise.resolve(null),[r,a]=await Promise.allSettled([t,n]);if(r.status===`rejected`){if(a.status===`fulfilled`&&a.value)try{await ax(i.unsubscribeMessages.bind(i),a.value,y)}catch(t){return y()?(l&&m.pendingSubscriptionReleases.add(l),e.chatSessionMessageSubscriptionRequestedKey=s,e.chatSessionMessageSubscription=a.value,x(`${B(r.reason)}; replacement release failed: ${B(t)}`),!0):(m.pendingSubscriptionReleases.add(a.value),!1)}return y()&&x(r.reason),!1}let o=a.status===`fulfilled`?a.value:null;if(!o){if(y()&&_&&(e.chatSessionMessageSubscriptionRequestedKey=null,e.chatSessionMessageSubscription=null),a.status===`rejected`)throw a.reason;return!1}if(!y()){try{await ax(i.unsubscribeMessages.bind(i),o)}catch{m.pendingSubscriptionReleases.add(o)}return!1}return e.chatSessionMessageSubscriptionRequestedKey=s,e.chatSessionMessageSubscription=o,e.chatSessionApprovalQueue=o.includeApprovals?t_(o.approvalReplay,o.key,o.agentId??void 0):[],b(),!0}catch(e){return y()&&x(e),!1}}var lx,ux;function dx(){return(dx=e((()=>{bo(),yr(),vt(),fe(),I(),Ec(),Zp(),Gg(),lx=250,ux=3})))()}function fx(e,t,n){return{owner:n,paneId:e,scopeKey:Ct(j(t,t.sessionKey))}}function px(e,t,n,r){let i=e.chatAttachmentHandoff.consume(fx(t,n,r));if(!i)return;let a=i.draftRevision===void 0||i.draftRevision>=Rf(n,n.sessionKey);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[fx(t,n,r).scopeKey];a&&c?.storageFailed&&(n.lastError=yf,n.chatError=yf),Jc([...s,...a?[]:i.attachments],[n.chatAttachments,...Object.values(n.chatComposerFallbackByScope).map(e=>e.attachments)])}function mx(e,t,n,r,i,a){if(a&&!lc({...n,connected:!1},a))return;let o=[...n.chatAttachments];e.chatAttachmentHandoff.prepare({reviewPrivateDraft:$p,...fx(t,n,r),attachments:o,fallbacks:n.chatComposerFallbackByScope,message:n.chatMessage,mentions:n.chatMentions,goalMode:n.chatGoalDraftMode,replyTarget:n.chatReplyTarget,draftRevision:i,incognito:Ul(n,j(n,n.sessionKey))})}function hx(e){if(e){Ge(e.chatAttachments);for(let t of Object.values(e.chatComposerFallbackByScope))Ge(t.attachments),t.attachments=[];e.chatAttachments=[]}}function gx(e,t,n,r,i){if(!i||r===i)return r;if(n){let e=e=>(Ge(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 _x(e,t,n){let r=new Set(N_(t,n).map(e=>e.id));for(let t of e.querySelectorAll(`openclaw-chat-pane`))r.has(t.paneId)&&t.resumeStagedAttachments?.()}var vx,yx;function bx(){return(bx=e((()=>{Ua(),I(),Zl(),dl(),vc(),bp(),Hg(),vx=new WeakMap,yx=class{constructor(e,t){this.context=e,this.host=t,this.ownsComposer=!0,this.custody=Symbol(`chat-composer-custody`);let n=vx.get(e);n||(n=new Set,vx.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&&!lc({...e,connected:!1},t))return null;let n=this.host.owner(),r=n?.recoveryScope;return e&&n&&e.client===n&&r?{owner:n,gatewayOwner:Ki(e.settings.gatewayUrl).gatewayOwner,recoveryScope:r,scopeKey:Ct(j(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;Jc([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 xx(e){e.updateComplete.then(()=>{e.querySelector(ep)?.focus({preventScroll:!0})})}function Sx(e,t,n,r){if(!e||!t||n.defaultPrevented||!(n instanceof CustomEvent))return!1;if(!Ze(e.uploadConfig))return Ot({message:Qe()}),!1;let i=n.detail;if(!i||typeof i.modelContext!=`string`||typeof i.dataUrl!=`string`||!i.card)return!1;if(!Xb(e.chatAttachments,i.modelContext))return n.rejection=`limit`,!1;let a=Kp(i.dataUrl,i.fileName||`annotation`,Hs(e.hello?.policy),Kl(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 Cx(){return(Cx=e((()=>{lt(),ut(),$b(),rd(),sp(),jf()})))()}var wx;function Tx(){return(Tx=e((()=>{es(),wg(),rg(),y(),la(),Eh(),wh(),ut(),Zl(),sp(),ic(),Ya(),wx=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(bg,e=>this.receiveResourceMention(e)),t(cg,e=>this.receiveMessage(e)),t(_g,e=>this.receiveFile(e)),t(pg,e=>this.receiveContext(e)),t(Os,e=>this.receiveOpen(e)),t(mg,e=>this.receiveWidgetPrompt(e))];return()=>{for(let e of n)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,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`}`,label:t.entrypoint.title}}))}receiveWidgetPrompt(e){let t=e.detail,n=typeof t?.text==`string`?t.text.trim():``;n&&this.options.current()?.state.handleSendChat(n)}receiveResourceMention(e){if(!(e instanceof CustomEvent)||e.defaultPrevented)return;let t=e.detail,n=this.options.current();if(!n||!n.presented||t.sessionKey!==n.state.sessionKey||!Ze(n.state.uploadConfig))return;let r=n.state,{resource:i}=t,a=i.title||i.name,o=JSON.stringify({serverName:t.serverName,resource:i},null,2),s=new File([o],`${a.replace(/[\\/]/gu,`-`)}.txt`,{type:`text/plain`});if(!xc([s],Hs(r.hello?.policy),Kl(r.chatAttachments)).length)return;e.preventDefault();let c=Tc({attachment:{id:wl(),mimeType:s.type,fileName:s.name,sizeBytes:s.size,origin:`file`},dataUrl:Eu(o),file:s});r.chatAttachments=[...r.chatAttachments,c],r.requestUpdate()}receiveMessage(e){if(!(e instanceof CustomEvent)||e.defaultPrevented)return;let t=e.detail,n=this.options.current();if(!n||!n.presented||t.sessionKey!==n.state.sessionKey)return;let{state:r,context:i}=n;e.preventDefault(),(async()=>{if(t.target===`new`)return yh(i,r.assistantAgentId||n.agentId||``,t);let e=Dh(t.content,i),a=!1;try{return await r.handleSendChat(e.text,{attachmentsOverride:e.attachments,onOutboxAdmitted:()=>{a=!0}}),a}finally{a||Ge(e.attachments)}})().then(t.respond,()=>t.respond(!1))}receiveFile(e){if(!(e instanceof CustomEvent)||e.defaultPrevented)return;let t=e.detail,n=this.options.current();n&&n.presented&&t.sessionKey===n.state.sessionKey&&(e.preventDefault(),n.openFile(t.path),t.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&&Th(r,{...t,agentId:n.state.assistantAgentId??void 0,title:i.title||V(`mcpApp.title`)})}receiveOpen(e){if(!(e instanceof CustomEvent)||e.defaultPrevented)return;let t=e.detail,n=this.options.current();n&&n.presented&&t.sessionKey===n.state.sessionKey&&t.owner===n.context.gateway.snapshot.client&&(e.preventDefault(),n.state.handleOpenSidebar({kind:`mcp-app`,title:t.entrypoint.title,launch:t,fileTab:{id:`mcp-app:${t.serverName}/${t.entrypoint.toolName}:${t.settings?`settings`:`app`}:${t.filePath??``}`,label:t.entrypoint.title}}))}}})))()}function Ex(e,t,n=()=>!0){return{slot:e,combo:t,available:n}}var Dx;function Ox(){return(Ox=e((()=>{Ue(),Dx={terminal:Ex(`terminal`,Be.terminalPanel,e=>e.state?.terminalAvailable===!0),browser:Ex(`browser`,Be.browserPanel,e=>e.state?.browserPanelAvailable===!0),workspace:Ex(`workspace`,Be.workspaceFiles),companion:Ex(`companion`,Be.sideChat),desktop:Ex(`desktop`,Be.desktopPanel,e=>e.desktopAvailable===!0),discussion:Ex(`discussion`,Be.discussionPanel,e=>e.discussion!=null&&e.discussionAvailable===!0),dashboard:Ex(`dashboard`,Be.dashboardPanel,e=>e.dashboardAvailable()),detail:Ex(`detail`,Be.reviewPanel),conversation:void 0,"link-reader":void 0,portal:void 0}})))()}function kx(e,t,n){let r=tt(t)?.agentId??n?.trim();if(R(t)){r&&e.agentSelection.set(r,{background:!0});return}let i=Ce(t,e.gateway.snapshot.hello),a=Hn();(a.sessionKey!==i||a.lastActiveSessionKey!==i)&&tn({sessionKey:i,lastActiveSessionKey:i}),(e.gateway.snapshot.sessionKey!==i||r&&e.agentSelection.state.selectedId!==r)&&vr({selection:e.agentSelection,gateway:e.gateway,sessionKey:i,agentId:r,background:!0})}function Ax(e){return!e.chatLoading&&!e.chatSending&&!e.chatRunId&&e.chatStream===null&&(e.chatQueue.length===0||md(e))}function Z(e){let t=(e.sessionsResult?.sessions??[]).find(t=>yt(e,t.key,e.sessionKey,t.agentId));if(!t||!p(t.key))return t;let n=X(e);if(!(e.sessionsResultAgentId&&Ao(e.sessionsResultAgentId)!==n))return t.observerDigest?.agentId&&Ao(t.observerDigest.agentId)!==n?{...t,observerDigest:void 0}:t}function jx(e){let t=X(e);if(e.chatAvatarUrl)return e.chatAvatarUrl;let n=as({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&&xt(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`&&xt(o)?o:null}function Q(){return(Q=e((()=>{Ln(),ds(),$n(),ht(),Me(),Pt(),I(),df(),Zp()})))()}function Mx(e,t,n){if(n!==`dashboard`)return Q_(t,n);let r=Hn().sidebarSessionLayouts?.[He(e,e.sessionKey)],i=r?r.dashboardPresentationOverride:null,a={...t,dashboardPresentationOverride:i};return r&&i===void 0?Q_(a,n):Dg(a,i??Z(e)?.boardPresentation??`split`)}function Nx(e,t){t===`workspace`&&Yv(e)}function Px(e){let{state:t,sidebarLayout:n}=e,r=e=>Le(n,e),i=r=>{e.updateSidebarLayout(Mx(t,n,r)),r===`companion`&&e.setObserverVisibility(!0)},a=r=>{r===`companion`&&e.setObserverVisibility(!1),Nx(t,r),e.updateSidebarLayout(z_(n,r))},o=e=>r(e)?a(e):i(e);return{closePanelSlot:a,openPanelSlot:i,sessionWorkspace:{...q_(t,{draftScope:e.presentationId,draftContext:{sessionTitle:e.sessionTitle,paneLabel:e.paneLabel},expanded:Le(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:Bn(e.gatewaySnapshot)?()=>o(`desktop`):void 0}}}function Fx(){return(Fx=e((()=>{Yn(),$n(),I(),Q(),f_(),yv(),v_()})))()}var Ix,Lx,Rx,zx;function Bx(){return(Bx=e((()=>{Rd(),I(),rd(),Hg(),Ix=`openclaw:queued-edit-retention-change`,Lx=3,Rx=5e3,zx=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&&ar(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&&lh(i,e,t),this.preview?.paneId===e&&z(this.preview.sessionKey,t)&&this.cancelPreview();let c=h_(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=h_(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)&&(!p(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,Rx),e.preventDefault()},this.cancelPreview=()=>{let e=this.bindings.layout(),t=this.preview?.paneId??e.activePaneId;this.clearPreviewWork(),this.preview=null;let n=h_(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)p(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(Ix,this.refreshRetention),window.addEventListener(`popstate`,this.cancelPreview),window.addEventListener(km,this.handleNavigationIntent)}disconnect(){this.sessionsByPane.clear(),this.unbound.clear(),this.pendingAtFocus=new WeakSet,this.host.removeEventListener(Ix,this.refreshRetention),window.removeEventListener(`popstate`,this.cancelPreview),window.removeEventListener(km,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&&p(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:Lx},()=>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<=Lx)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>Lx&&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&&Xs(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=N_(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}}clearPreviewWork(){this.previewFrame!==void 0&&(cancelAnimationFrame(this.previewFrame),this.previewFrame=void 0),this.previewTimer!==void 0&&(window.clearTimeout(this.previewTimer),this.previewTimer=void 0)}}})))()}function Vx(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(Ux(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 Hx(e){let t=Kx(e),n=e.workspaceResultReconciling&&e.row?.placement?.state===`active`&&!t.moving&&!t.restarting&&e.reclaimingKey!==e.row.key,r=Vx({...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 Ux(e){return!(!e?.repositoryWorkspaceId||e.placement&&e.placement.state!==`local`)}function Wx(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 Gx(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=ro(t.runner.deviceId);return t.runner.status===`available`&&e?`node:${e}`:null}return ro(t.environmentId)??null}let n=ro(e.execNode);return n?`node:${n}`:`gateway`}function Kx(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=Ho(e.row?.placement),a=L(e.gatewaySnapshot,{method:`sessions.move`,requiredScope:`operator.write`}),o=L(e.gatewaySnapshot,{method:`sessions.reclaim`,requiredScope:`operator.write`}),s=L(e.gatewaySnapshot,{method:`sessions.dispatch`,requiredScope:`operator.write`}),c=e.row?.placement?.state,l=Ux(e.row),u=c===`failed`?e.row?.placement?.recoveryAction:void 0,d=c===`active`?e.row?.placement?.runner:void 0,f=d?.kind===`device`&&d.status===`offline`,p=t?V(`common.loading`):n||c!==`active`?V(`sessionsView.actionUnavailable`):a.allowed?void 0:a.reason,m=r?V(`common.loading`):t||n||!l&&u!==`restart`?V(`sessionsView.actionUnavailable`):e.row?.archived?V(`chat.archivedSessionDisabled`):s.allowed||!l&&o.allowed?void 0:s.reason;return{moving:t,restarting:r,moveDisabledReason:p,reclaimDisabledReason:n?V(`common.loading`):r?V(`sessionsView.actionUnavailable`):f?V(`sessionsView.offlineDeviceStopUnavailable`):i?.blocksActiveRun&&e.row?.hasActiveRun===!0?V(`sessionsView.activeRun`):i?o.allowed?void 0:o.reason:V(`sessionsView.actionUnavailable`),recoveryDisabledReason:m}}function qx(){return(qx=e((()=>{rs(),y(),vi(),dg(),O(),Di(),yg()})))()}function Jx(e){if(!e)return null;let t=e.state===`active`?e.runner:void 0;return[e.state,e.generation,`environmentId`in e?e.environmentId:void 0,`activeOwnerEpoch`in e?e.activeOwnerEpoch:void 0,`providerId`in e?e.providerId:void 0,`profileId`in e?e.profileId:void 0,t?.kind,t?.deviceId,t?.status]}function Yx(e){return JSON.stringify([e?.sessionId,e?.execNode,e?.archived===!0,Jx(e?.placement)])}var Xx;function Zx(){return(Zx=e((()=>{Yn(),Rh(),ag(),Sg(),Me(),Pt(),I(),qx(),v_(),Xx=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?N(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()&&!R(r)?{client:n,sessions:t.sessions,observation:o,sessionKey:r,agentId:a,connectionEpoch:t.connectionEpoch,desktopAvailable:Bn(e.gateway),browserAvailable:ir(e.gateway),placement:s?.placement,sessionId:s?.sessionId,execNode:s?.execNode,archived:s?.archived,browserTab:[...Kh(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&&N(t,t.sessionKey).agentId===a&&t.connectionEpoch===i&&t.connected&&e.observation()===o&&o.isCurrent()&&Yx(o.row??void 0)===Yx(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||!n.columns.some(e=>e.panels.some(e=>e.slot===`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===Yx(i)?this.desktop.source:null}sync(e){let t=this.owner;if(this.owner=e,!e){this.invalidate();return}let n=Yx(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=e.layout().columns.some(e=>e.panels.some(e=>e.slot===`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&&e.layout().columns.some(e=>e.panels.some(e=>e.slot===`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&&Et(e).some(e=>e.slot!==`conversation`)}publishDesktop(e,t){let n=e.layout().columns.some(e=>e.panels.some(e=>e.slot===`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:Yx(e),source:t},t!==null&&this.reveal(e,`desktop`),r&&e.requestUpdate()}reveal(e,t){let n=e.layout();if(this.dismissed(n)||n.columns.some(e=>e.panels.some(e=>e.slot===t)))return;let r=Q_(n,t);n.open&&ce(n)&&(r.columns[0].activePanelId=n.columns[0].activePanelId),Ye(n)?.slot!==void 0&&Ye(n)?.slot!==`conversation`&&(r.open=n.open),r.expanded=n.expanded,r.expandedSide=n.expandedSide,e.commit(r,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=Gx(n);if(!t||t===`gateway`||ig({id:t}).kind===`environment`&&!n.sessionId){this.publishDesktop(e,null);return}return t});if(!r)return;let i=await hg(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){this.publishDesktop(e,null);return}if(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,()=>Lh(jh(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 Qx(){return!customElements.get(`openclaw-board-view`)&&(eS??=ko(()=>import(`./board-view-1zQa7RX5.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([10,0,1,2,3,4,5,11,12,13,14,15,16,6,7,8,9,17,18,19,20]),import.meta.url),await eS,!0)}function $x(e){return U`
<div
class="board-session-surface"
?hidden=${We(e.active,!0)}
?inert=${We(e.active,!0)}
>
<div class="board-session-surface__board">
<openclaw-board-view
.active=${We(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>
</div>
</div>
`}var eS;function tS(){return(tS=e((()=>{wr(),St(),jo(),eS=null})))()}function nS(e){let t=q(e)?.messageId;return typeof t==`string`&&t?t:null}function rS(){return(rS=e((()=>{})))()}function iS(e){return(e?.appliedConfigHash??e?.configRevisionHash??e?.hash??null)||JSON.stringify(q(q(e?.runtimeConfig)?.mcp)?.servers??null)}var aS;function oS(){return(oS=e((()=>{wr(),yr(),Fh(),An(),Wo(),y(),Ha(),ve(),Aa(),vt(),si(),O(),Pt(),I(),sy(),Cc(),$u(),Wp(),$g(),ga(),aS=class e{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 rf(e),this.library=new Nv(e)}static async addMcpServer(e){let t=e.scope===`session`?{...e.config,enabled:!1}:e.config,n=`config`;try{let r=await e.patchGlobal(t);if(!r.ok)return{...r,stage:n};if(e.scope===`everywhere`)return{ok:!0};n=`session`;let i=await e.loadSessionOverrides();if(!i.ok)return{...i,stage:n};let a=kf(i.overrides,`mcpServers`,e.name,!0,!1),o=await e.patchSession(a);return o.ok?o:{...o,stage:n}}catch(e){return{ok:!1,error:B(e),stage:n}}}loadSkills(e,t,n){let r=e.runtimeConfig.state;!r.configSnapshot&&!r.configLoading&&e.runtimeConfig.ensureLoaded().catch(()=>void 0);let i=t.client,a=t.connectionEpoch;this.skillCatalog.load(i,a,n,()=>t.connected&&t.client===i&&t.connectionEpoch===a)}effectiveToolsKeys(e,t,n){let r=T({chatModelCatalog:t.chatModelCatalog,sessions:e.sessions,sessionsResult:t.sessionsResult},{agentId:n,sessionKey:t.sessionKey});return{cacheKey:`${r}\0config=${iS(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(),Te(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=L(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 Mc(t,i,{toolOverrides:n},N(t,i)))throw Error(V(`chat.composer.menu.offlineBlocked`));return{ok:!0}}catch(e){let n=B(e);if(s()){try{await ml(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=wn(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&&ee(e,t).agentId===n;if(!r())return{ok:!1,error:V(`mcpServers.sessionChanged`)};try{await ml(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(t,n,r,i){if(this.addBusy)return;let a=this.addServerBlockedReason(t,n,r,this.addScope);if(a){this.addError=a,this.notify();return}let o=i.name.trim();if(!Oa.test(o)){this.addError=V(`mcpServers.nameInvalid`),this.notify();return}let s=Ra(i.target,i.transport);if(!s){this.addError=V(`mcpServers.targetInvalid`),this.notify();return}this.addBusy=!0,this.addError=null,this.notify();let c=n.sessionKey,l=ee(n,c).agentId,u;try{u=await e.addMcpServer({scope:this.addScope,name:o,config:s,patchGlobal:e=>fa(t.runtimeConfig,{buildPatch:t=>Ia(t,o,e),note:`composer connectors: add MCP server ${o}`}),loadSessionOverrides:()=>this.loadCurrentSessionOverrides(n,c,l),patchSession:e=>this.patch(t,n,e)})}finally{this.addBusy=!1}if(!u.ok){let e=Xe(u.error);this.addError=u.stage===`session`?V(`mcpServers.sessionEnableFailed`,{error:e}):e,this.notify();return}this.addDialogOpen=!1,this.notify()}renderAddServerDialog(e,t,n){if(!this.addDialogOpen)return W;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 U`
<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>
${is({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>
${Vh({busy:this.addBusy,disabled:i!==null,blockedReason:i,autofocus:!0,onSubmit:r=>void this.submitAddServer(e,t,n,r),onCancel:()=>this.closeAddDialog()})}
${this.addError?U`<div class="mcp-server-message mcp-server-message--error" role="alert">
${this.addError}
</div>`:W}
</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=oi(e.gateway.snapshot,`skills.library.activate`,`operator.write`,{requireAdvertisement:!1}),d=e.runtimeConfig.state.configSnapshot?.runtimeConfig??null,f=wn(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,b=L(e.gateway.snapshot,{method:`sessions.patch`,params:{key:t.sessionKey,toolOverrides:null}}),x=p?y?b.allowed?this.patchTokens.has(t.sessionKey)?V(`chat.composer.menu.savingBlocked`):null:b.reason:V(`common.loading`):V(`chat.composer.menu.offlineBlocked`),S=x??(g?null:V(v?`chat.composer.menu.toolAccess.loadFailed`:`common.loading`)),C=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:Ta(d)??[],toolsEffectiveResult:g,toolsEffectiveLoading:_,toolsEffectiveError:v,toolAccessMutationBlockedReason:S,webSearchBaseEnabled:xf(d),mutationBlockedReason:x,canAdmin:f.canAdmin&&p,adminBlockedReason:C,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?oy({read:this.library.read,file:this.library.selectedFile,onFile:e=>{this.library.selectedFile=e,this.notify()},onClose:()=>{this.library.closeRead(),this.notify()}}):W,onLoadSkills:()=>{l()&&(this.loadSkills(e,t,r),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 sS(e){return e?[e.id,e.identity?.type,e.identity?.id,e.name,e.email,e.avatarUrl]:null}function cS(e,t){let{users:n}=Na(e),r=$t({snapshotUser:t.selfUser,presenceEntries:e?.presence,presenceInstanceId:t.selfInstanceId});return JSON.stringify([n.length>=2,sS(r),n.filter(e=>e.watchedSessions.includes(t.sessionKey)).map(sS)])}function lS(e,t,n){return e===t||cS(e,n)===cS(t,n)}function uS(){return(uS=e((()=>{Qa()})))()}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 fS(e){e.lastError=null,e.lastErrorCode=null,e.chatError=null}function pS(e,t,n){let r=ll(e),i=t&&r.phase===`failed`?r.message:null,a=n?$m(e,e.sessionKey):null,o=ca(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!==ca(e.chatMessage)&&e.requestUpdate?.()}}}function mS(e,t,n){return qh(e.settings.chatFollowUpMode,Yh(n.configSnapshot?.runtimeConfig,{configNeedsApply:n.configNeedsApply,effectiveMode:e.chatEffectiveQueueMode,sessionMetadataLoaded:t!==void 0||e.chatEffectiveQueueMode!==void 0,sessionMode:e.chatQueueModeOverride}))}var hS,gS;function _S(){return(_S=e((()=>{y(),Xa(),Ih(),Zp(),Tu(),hS=256,gS=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`;return this.remember(e.sessionKey,t),t}return e.listLoading?this.lastBlocked.get(e.sessionKey)===!0:!1}remember(e,t){if(this.lastBlocked.delete(e),this.lastBlocked.set(e,t),this.lastBlocked.size<=hS)return;let n=this.lastBlocked.keys().next().value;n&&this.lastBlocked.delete(n)}}})))()}function vS(){return{realtimeTalkActive:!1,realtimeTalkStatus:`idle`,realtimeTalkDetail:null,realtimeTalkInputNotice:null,realtimeTalkUseSystemDefault:null,realtimeTalkInputLevel:new Wc,realtimeTalkVideoStream:null,realtimeTalkCameraDevices:[],realtimeTalkVideoCapable:!1,realtimeTalkVideoPending:!1,realtimeTalkCameraError:!1,realtimeTalkSession:null,realtimeTalkVoiceController:null,realtimeTalkConversationState:k_()}}function yS(e){e.realtimeTalkConversationState=k_()}function bS(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,t.preserveConversation?e.realtimeTalkConversationState=Yg(e.realtimeTalkConversationState):yS(e),n?.stop()}function xS(e){e.realtimeTalkStatus===`error`&&bS(e)}function SS(e,t=()=>!0){let n=0,r=()=>e.realtimeTalkStatus===`error`,i=t=>{e.settings=tn({talkCameraAutoEnable:t})},a=t=>{e.realtimeTalkDetail=B(t),e.realtimeTalkCameraError=!0,e.requestUpdate()},o=async t=>{let n=await fl(()=>!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(Hn().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=()=>{yS(e)};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=Hn(),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=Yg(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 a_({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=>{bS(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 ny(p,m,{onStatus:S((t,n)=>{e.realtimeTalkStatus=t,e.realtimeTalkDetail=t===`error`&&n?Xe(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=Xe(t),e.requestUpdate()}),onVideoCapability:S(t=>{e.realtimeTalkVideoCapable=t,e.requestUpdate()}),onInputLevel:S(t=>{e.realtimeTalkInputLevel.set(t)}),onTranscript:S(t=>{e.realtimeTalkConversationState=n_(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=Kg(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(bS(e),e.realtimeTalkStatus=`error`,e.realtimeTalkDetail=n,t instanceof Lc){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){bS(e),e.requestUpdate();return}await c()},e.toggleRealtimeTalkCamera=async()=>{let t=e.realtimeTalkVideoStream===null;await s(t)},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()||Hn().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=tn({realtimeTalkVideoDeviceId:s.deviceId}))}catch(n){e.realtimeTalkSession===t&&!r()&&a(n)}finally{e.realtimeTalkSession===t&&(e.realtimeTalkVideoPending=!1,e.requestUpdate())}}}}function CS(){return(CS=e((()=>{$n(),y(),vt(),P_(),al(),Hu(),Ng(),x_()})))()}function wS(e,t){let n=t.flatMap(e=>{let t=e.browserAnnotation?.modelContext.trim();return t?[t]:[]});if(n.length===0)return e;let r=n.join(`
`);return e?`${r}\n\n${e}`:r}async function TS(e,t,n){let r=null;if(e.client&&e.connected&&(t.trim()||n.attachments?.length)){Fd(e,n.recovery)&&Y(e,null);try{r=await ld(e,{message:t.trim(),attachments:n.attachments,runId:uo(),expectedLeafEntryId:xd(e)})}catch(t){if(Fd(e,n.recovery)){let n=hd(t);Y(e,n?V(`chat.sendErrors.activeLeafChanged`):t instanceof $a&&t.requestSent?Od:Vl(t)),n&&Promise.all([ud(e),pd(e)])}}}let i=r?.status===`ok`||r?.status===`started`||r?.status===`in_flight`;sm(e,n.recovery,i,n.attachments),qs(r)&&Fd(e,n.recovery)&&Y(e,Km(r,`detached`))}function ES(){return(ES=e((()=>{To(),y(),so(),Xp(),Zp(),gd(),ah(),Ap(),rl(),Tu(),rp()})))()}function DS(){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 OS(e,t,n,r){let i=n.yieldToInput&&typeof MessageChannel<`u`,a=i&&n.isCurrent()&&e.connected&&e.client&&!e.chatLoading&&!cd(e)&&!n.pendingSettings&&t.sendState===`waiting-idle`&&(t.queueMode||n.allowActiveRunSend&&!t.intent||!zp(e)&&!$d(e)&&e.chatQueue.find(e=>e.sendState!==`failed`||e.localCommandName)?.id===t.id),o=i&&e.connected&&n.isCurrent()?Wf(e).beginSubmission(e,t.id,{inline:!!a,isCurrent:()=>e.connected&&n.isCurrent()}):void 0;try{let a=t;if(i){await DS();let r=n.isCurrent()&&Ne(e,t.sessionKey,t.agentId)?As(e,t.id):null;if(!r||!aa(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 kS(e,t,n,r){let i=t,{action:a,scope:o}=n;if(a){let e=AS.get(a)??uo();AS.set(a,e),i=`${t}\0${e}`}let s=e.chatSubmitGuards??=new Set;if(s.has(i))return;s.add(i);let c=Ct(o),l={signatures:new Set(n.attachments?.map(e=>Zm(``,[e]))),isCurrent:()=>n.isCurrent()&&Ct(j(e,e.sessionKey))===c},u=jS.get(e);l.signatures.size&&(u??=new Set,u.add(l),jS.set(e,u));let d=()=>{u?.delete(l)&&(u.size||jS.delete(e))};try{return await r({releaseAttachments:d,canRetireAttachment:t=>{let n=Zm(``,[t]);return l.isCurrent()&&l.signatures.has(n)&&![...jS.get(e)??[]].some(e=>e.isCurrent()&&e.signatures.has(n))}})}finally{d(),s.delete(i)}}var AS,jS;function MS(){return(MS=e((()=>{Oi(),gt(),Pt(),I(),so(),Zp(),Pp(),od(),Cu(),_f(),AS=new WeakMap,jS=new WeakMap})))()}async function NS(e,t){let n=Lu(e,t);return n&&!await Oc(e,t,n)?!1:e.sessionKey===t}async function PS(e,t,n,r){if(Js(e)?.providerReview&&!_p(t??e.chatMessage)){Y(e,V(`chat.providerReview.pausedBody`));return}if(cd(e)&&(n?.intent||n?.resumeQueuedMessageEditId||!Va(t??e.chatMessage)))return;if(n?.intent&&Js(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=Ii(l,u),f=c?l:d.text,p=Op(),m=e.sessionKey,h=e.client,g=e.connectionEpoch,_=um(e),v=xd(e),y=qf(t==null?e.chatAttachments:n?.attachmentsOverride??[]),b={attachments:t==null?y:[],scope:j(e,m),isCurrent:()=>_()&&e.client===h&&e.connectionEpoch===g&&e.sessionKey===m},x=(n=`none`)=>t==null?vm(e,i,y,a,o,n):{},S=y.length>0;if(S&&!Ze(e.uploadConfig)){Y(e,Qe());return}if(c){if(u?.length){Y(e,V(`chat.mentions.unsupported`));return}if(!e.connected||!e.client){Y(e,V(`chat.goals.offline`));return}if(zp(e)||$d(e)){Y(e,V(`chat.goals.busy`));return}if(y.some(e=>e.browserAnnotation)){Y(e,V(`chat.goals.annotationUnsupported`));return}if(!f.trim())return}let C=n?.resumeQueuedMessageEditId,ee=C?hu(e):null;if(C!=null&&ee?.id!==C)return;let w=C!=null&&ee?.id===C,T=w?ee.revision:null,E=c?null:Gi(f);if(d.mentions?.length&&(E||/^\/(?:btw|side)(?::|\s|$)/i.test(f))){Y(e,V(`chat.mentions.unsupported`));return}if(w&&(E||_p(f))){Y(e,`Queued-row edits cannot run commands or stop aliases. Cancel this edit and send the command from the composer.`);return}let D=E||c?f:wS(f,y),O=E?y.filter(e=>!e.browserAnnotation&&!e.selectionAnnotation):y,k=()=>{let t=fc(O,e.hello?.policy);return t!==void 0&&(Ot({message:t}),!0)};if(!D&&!S)return;if(!c){if(_p(f)&&(f.startsWith(`/`)||bm(e))){if(e.connected&&!om(e,`abort`))return;e.chatRunError=null,t??gc(e,f),await up(e,{scope:`session`});return}let r=E;if(/^\/(?:btw|side)(?::|\s|$)/i.test(f)){e.chatRunError=null;let n=Xh(f);await kS(e,mf(e,`local`,D,[]),b,async()=>{t??(gc(e,f),x(`all`)),await e.openSessionCompanion?.(n)});return}let s=r?.command.clientPresentation,c=e.dispatchClientPresentation;if(e.connected&&r?.args===``&&s?.when===`no-arguments`&&!S&&e.chatReplyTarget==null&&c&&await kS(e,mf(e,`local`,D,[]),b,async()=>{if(e.sessionKey!==m)return`not-handled`;let n=!1;try{n=await c(s.action)}catch{}return n?e.sessionKey===m?(e.chatRunError=null,t??(x(),gc(e,D)),`handled`):`handled`:`not-handled`})!==`not-handled`)return;let l=r?.command.key===`model`&&Fr(r.args);if((!r?.command.executeLocal||l)&&Js(e)?.sendDisabledReason){e.requestUpdate?.();return}if(e.chatRunError=null,r?.command.key===`approve`&&(zp(e)||cd(e))){await kS(e,mf(e,`detached`,D,y),b,async()=>{if(!await NS(e,m)||k())return;let n=x(`annotations`);t??gc(e,f);let r=j(e,m);th(e,!0,!1,{source:`manual`}),await TS(e,D,{attachments:O.length?O:void 0,recovery:Ms(e,r,n)})});return}if(r?.command.executeLocal&&!l){if(Kf(r.command.key)){if(Mm(e,m)){e.requestUpdate?.();return}await kS(e,mf(e,`local`,D,y),b,async()=>{let n=Ea(e,e.sessionKey);t??(gc(e,f),x(`all`));let s=fd(e,D,rc(D),{args:r.args,name:r.command.key},ja(e.hello,e.client?.instanceId,e.selfUser)??void 0);if(s){if(s.sendState=eu(e),!sl(e,n,s)){Wf(e).remove(e,s.id),t??(e.chatMessage=i,e.chatMentions=a??[],e.chatReplyTarget=o,e.chatAttachments=y),Y(e,Of);return}th(e,!0,!1,{source:`manual`}),await Zs(e,s,{routingSessionKey:e.sessionKey})}});return}let s=r.command.key===`redirect`,c=async()=>{if(s&&!await NS(e,m))return;let a=t==null?i:void 0,o,c=j(e,m);if(t==null&&(gc(e,f),r.command.key!==`export-session`)){let e=x();a=e.previousDraft,o=e}let l=Ms(e,c,o);(r.command.key===`steer`||r.command.key===`redirect`)&&th(e,!0,!1,{source:`manual`});let u=await Ps(e,r.command.key,r.args,{previousDraft:a,restoreDraft:!!(t&&n?.restoreDraft),sendResetMessage:(t,n)=>uh.sendResetSlashCommand(e,t,n)});r.command.key===`export-session`&&u===`completed`&&t==null&&Fd(e,l)&&x(`all`),u===`failed`&&(t!=null||Fd(e,l))&&n?.onLocalCommandSendRejected?.(),u===`failed`||u===`cancelled`?sm(e,l,!1,l.composer?.previousAttachments):u===`completed`&&sm(e,l,!0,l.composer?.previousAttachments)};s?await kS(e,mf(e,`local`,D,y),b,c):await c();return}}if(k())return;let{replyTargetOverride:A=o}=n??{},M=w?null:A,te=w?ee.replyToId:M?.sourceMessageId?.trim()||void 0,ne=M&&!te&&!c?Vm(D,M):D,N=!c&&!f.startsWith(`/`)&&!f.startsWith(`!`)&&!ii(ne)?w?ee.source.workContext:e.getWorkContext?.():void 0,P=N?Gt(N):void 0,F=ne.length-f.length,re=d.mentions?.map(e=>({profileId:e.profileId,start:e.start+F,end:e.end+F})),ie=mf(e,C?`queued-edit`:c?`goal`:`message`,P?`${ne}\n\n${Wt(P)}`:ne,y,re),ae=!1,oe=async i=>{if(e.chatLoading&&(c||E||w)){if(!await ud(e))return;v=xd(e)}if(e.sessionKey!==m)return;let a=be(e,m),o=()=>b.isCurrent()&&Ne(e,m,a);if(!Ne(e,m,a)){Y(e,V(`mcpServers.sessionUnavailable`));return}if(c&&(zp(e)||$d(e))){Y(e,V(`chat.goals.busy`));return}let l=hu(e);if(w&&(l!==ee||l.revision!==T))return;if(Mm(e,m,!1,a)){e.requestUpdate?.();return}let u=Lu(e,m),d=$d(e)||cd(e),h=C&&l?.id===C?l:null,g=h?h.source.queueMode??`queue`:n?.followUpMode??e.chatFollowUpMode??xr(e.settings?.chatFollowUpMode),_=!c&&d&&g!==`queue`?g:void 0,y=!!(c||d&&g!==`queue`),S=$f(e,ne,O.length?O:void 0,!!c||rc(D),p,u?`waiting-model`:eu(e),te,h?.orderKey,_,c,v,re,P);if(!S)return;let k=S.item;if(k.asyncQuestionItemId=h?.source.asyncQuestionItemId??n?.asyncQuestionItemId,k.attachments?.length){let t=await Sm(e,k),n=hu(e);if(!o()||w&&(n!==ee||n.revision!==T)){t.status===`ready`&&tf(t.update);return}if(t.status===`failed`){Y(e,fp(t.reason));return}k={...k,...t.update};let r=Mm(e,m,!1,a);if(r||c&&(zp(e)||$d(e))){tf(k),r?e.requestUpdate?.():Y(e,V(`chat.goals.busy`));return}u??=Lu(e,m),k.sendState=u?`waiting-model`:eu(e)}let A=x(E?`annotations`:`none`);t??gc(e,f),k=Fl(e,k);let j=Wf(e).admit(e,S.admission,k,h?{id:h.id,expected:h.source}:void 0),M=j===`admitted`;M&&(i.releaseAttachments(),t==null&&!E&&!c&&o()&&(e.chatAttachments=e.chatAttachments.filter(e=>!i.canRetireAttachment(e)))),h&&Bu(e,M,k.attachments,h);let N=!M&&!k.attachments?.length&&(!h||!h.sourceWasDurable)&&!hu(e)&&!u&&Vs(e,k,m);if(!M&&!N){tf(k),cu(e,k,{...A,previousGoalDraftMode:s}),Y(e,Vd(j,!!h));return}Y(e,null),n?.onOutboxAdmitted?.();let F=await OS(e,k,{yieldToInput:M&&!!r,isCurrent:o,allowActiveRunSend:y,pendingSettings:u},r=>Zs(e,r,{...A,previousGoalDraftMode:s,...y?{allowActiveRunSend:!0}:{},...v===void 0?{}:{expectedLeafEntryId:v},...u?{pendingSettings:u}:{},restoreAttachments:!!(t&&n?.restoreDraft),restoreDraft:!!(t&&n?.restoreDraft),restoreOnTerminalFailure:!!(E||c),routingSessionKey:m,storageMode:N?`memory`:`durable`})),ie=As(e,k.id);ae=F!==`failed`,F===`pending`&&ie?.sendState===`waiting-idle`&&e.sessionKey===m&&Ne(e,m,ie.agentId)&&(zp(e)||$d(e))&&Qp(e,ie,`queued-busy`,p)};return await kS(e,ie,{...b,action:r},oe),ae}function FS(){return(FS=e((()=>{Br(),ai(),Kt(),$n(),y(),Fi(),Ha(),Xa(),eg(),_a(),ba(),Ua(),Pt(),I(),lt(),ut(),pf(),Zp(),gd(),Pp(),Vc(),od(),Ap(),Zu(),ES(),Dl(),rl(),Tu(),Fc(),$u(),MS(),sp(),Au(),Yd(),am(),Ju(),_f(),Bf(),Ri(),ga()})))()}function IS(e,t){let n=cf(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=()=>cf(e)===n&&e.client===i&&e.connected&&e.connectionEpoch===a;return jl(i,{sessionKey:n.sessionKey,agentId:n.agentId,runId:r.runId,...Ul(e,n)?{}:{discardPendingInput:!0}}).then(async t=>{if(o()){if(!t.ok){e.chatError=B(t.error),e.requestUpdate?.();return}await ud(e,{supersedeInFlight:!0})}}),!0}function LS(e){e.imageLightboxRequestVersion+=1;let t=e.imageLightbox;return e.imageLightbox=null,t?.release?.(),e.imageLightboxRequestVersion}async function RS(e){if(!e.client||!e.connected)return;let t=e.client,n=e.sessionKey.trim(),r=Xu({sessionKey:n,assistantAgentId:e.assistantAgentId,agentsList:e.agentsList,hello:e.hello});if(!r)return;let i=++e.assistantIdentityRequestVersion;try{let a=await fs(t,r);if(e.client!==t||!e.connected||e.assistantIdentityRequestVersion!==i||e.sessionKey.trim()!==n||Xu(e)!==r||!a)return;e.assistantAgentId!==(a.agentId??null)&&ae(e,e.sessionKey)&&du(e),e.assistantName=a.name,e.assistantAvatar=a.avatar,e.assistantAvatarSource=a.avatarSource??null,e.assistantAvatarStatus=a.avatarStatus??null,e.assistantAvatarReason=a.avatarReason??null,e.assistantAgentId=a.agentId??null,e.requestUpdate?.()}catch{}}function zS(e,t,n,r=new Map){let i=Hn(),a=n.sessionKey?.trim()||i.sessionKey,o=He({agentsList:e.agents.state.agentsList,hello:e.gateway?.snapshot.hello},a),s=Gn(),l=e.config.current,d={uploadConfig:e.config,captureComposerRecoveryReload:()=>{let t=vn(e.gateway);return()=>pn({timeoutMs:0,...t})},sessions:e.sessions,hasPendingInitialTurn:t=>e.placementStartup.hasPendingTurn(t),chatSubmissions:e.chatSubmissions,settings:i,password:``,onboarding:!1,assistantName:l.assistantIdentity.name,assistantAvatar:null,assistantAvatarStatus:null,assistantAvatarReason:null,assistantAvatarSource:null,assistantIdentityRequestVersion:0,userName:s.name,userAvatar:s.avatar,embedSandboxMode:l.embedSandboxMode,allowExternalEmbedUrls:l.allowExternalEmbedUrls,automaticallyFetchFavicons:l.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:a,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,chatAvatarSource:null,chatAvatarStatus:null,chatAvatarReason:null,chatModelSwitchPromises:{},chatModelPickerOpenSessionKey:null,chatModelsLoading:!1,chatModelCatalog:[],chatModelCatalogInitialized:u(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:r,eventLogBuffer:[],dispatchClientPresentation:t=>kh(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:C(i.sidebarSessionLayouts?.[o]),sidebarContent:null,sidebarFocusPanelId:i.sidebarSessionActivePanels?.[o]??``,sidebarFocusVersion:0,imageLightbox:null,imageLightboxRequestVersion:0,toolStreamById:new Map,toolStreamOrder:[],activityEventSeqById:new Map,toolStreamSyncTimer:null,...vS(),renderLifecycle:t,requestUpdate:()=>t.invalidate(),transcriptLoadingChanged:()=>n.dispatchEvent(new CustomEvent(f,{bubbles:!0,composed:!0})),historyRecoveryChanged:()=>n.dispatchEvent(new Event(c,{bubbles:!0,composed:!0})),sessionWorkspaceState:void 0,querySelector:n.querySelector.bind(n)};d.resetToolStream=()=>bu(d),d.resetChatInputHistoryNavigation=()=>sc(d),d.resetChatScroll=()=>Ad(d),d.scrollToBottom=e=>{Ad(d),th(d,!0,!!e?.smooth,{source:`manual`})},d.handleChatScroll=e=>Gp(d,e),d.handleChatDraftChange=(e,t)=>$s(d,e,t),d.handleChatInputHistoryKey=e=>Lm(d,e),d.applySettings=e=>{let n={...d.settings,...e};d.settings=tn({chatShowThinking:n.chatShowThinking,chatShowToolCalls:n.chatShowToolCalls,chatPersistCommentary:n.chatPersistCommentary,chatSendShortcut:n.chatSendShortcut}),t.invalidate()},SS(d,()=>!Js(d)?.providerReview),d.loadAssistantIdentity=()=>RS(d),d.handleSendChat=(t,n,r)=>{let i=t??d.chatMessage,a=Gi(i)!==null||_p(i)&&bm(d);return Vo({connected:d.connected,directComposerSend:t===void 0&&n===void 0&&Jo(),message:i,hasAttachments:d.chatAttachments.length>0,isCommand:a})&&Go(e),PS(d,t,n,r)},d.handleAbortChat=async e=>{await up(d,e),t.invalidate()},d.removeQueuedMessage=e=>{if(IS(d,e))return;if(Hc(d,e)){Y(d,vl),t.invalidate();return}let n=_m(d,e,{discard:!0});n===`removed`?(Y(d,null),el(d)):n===`rejected`&&Y(d,Of),t.invalidate()},d.retryQueuedChatMessage=async e=>{await xl(d,e),t.invalidate()},d.steerQueuedChatMessage=async e=>{await vu(d,e),t.invalidate()},d.moveQueuedChatMessage=(e,n)=>{Ac(d,e,n),t.invalidate()},d.editQueuedChatMessage=e=>{if(ch(d,e)===`unavailable`)Y(d,Zc);else for(let e of[`lastError`,`chatError`])d[e]===`A queued message is being edited in another pane. Finish or cancel that edit before editing it here.`&&(d[e]=null);t.invalidate()},d.updateQueuedChatMessageEdit=(e,n)=>{nd(d,e,n),t.invalidate()},d.submitQueuedChatMessageEdit=()=>{let e=hu(d);e&&d.handleSendChat(e.draftText,{attachmentsOverride:[...e.attachments],mentionsOverride:e.mentions,resumeQueuedMessageEditId:e.id}).then(()=>t.invalidate(),()=>t.invalidate())},d.cancelQueuedChatMessageEdit=()=>{Ys(d)&&el(d),t.invalidate()};let p=new Set,m=``;return d.updateSidebarLayout=(e,n)=>{let r=He(d,d.sessionKey),i=JSON.stringify([d.settings.gatewayUrl,r]);i!==m&&(p.clear(),m=i);let a=C(e),o=d.sidebarLayout,s=(e,t)=>e.columns.some(e=>e.panels.some(e=>e.slot===t));n?.automaticResource&&!s(o,n.automaticResource)&&s(a,n.automaticResource)&&p.add(n.automaticResource);for(let e of p){let t=a.columns.flatMap(e=>e.panels).find(t=>t.slot===e);(!t||e===`desktop`&&t.environmentId!==void 0)&&p.delete(e)}(o.resourceAutoOpenDismissed||n?.persist!==!1&&(o.open&&!a.open||s(o,`desktop`)&&!s(a,`desktop`)||s(o,`browser`)&&!s(a,`browser`)))&&(a.resourceAutoOpenDismissed=!0);let c=n?.dashboardPresentation===`personal`?Dv(a):void 0;if(c){let e=Z(d);a.dashboardPresentationOverride=e&&c===(e.boardPresentation??`split`)?null:c}if((d.sidebarContent?.kind===`loading`||d.sidebarContent?.kind===`unavailable`)&&!a.columns.some(e=>e.panels.some(e=>e.slot===`detail`))&&(d.sidebarContent=null),d.sidebarLayout=a,n?.persist===!1){t.invalidate();return}let l=a;for(let e of p)l=z_(l,e);d.settings=tn({sidebarSessionLayouts:ye(Hn().sidebarSessionLayouts,r,l,{geometryOnly:n?.geometryOnly,dashboardPresentationOverride:c?a.dashboardPresentationOverride:void 0})}),a.dashboardPresentationOverride=d.settings.sidebarSessionLayouts?.[r]?.dashboardPresentationOverride,t.invalidate()},d.updateSidebarActivePanel=e=>{let n=e.trim();if(!n)return;d.sidebarFocusPanelId=n,d.sidebarFocusVersion+=1;let r=d.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.id===n)?.slot;if((r===`desktop`||r===`browser`)&&p.has(r)){t.invalidate();return}d.settings=tn({sidebarSessionActivePanels:D(Hn().sidebarSessionActivePanels,He(d,d.sessionKey),n)}),t.invalidate()},d.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=Q_(d.sidebarLayout,r),a=i.columns.flatMap(e=>e.panels).find(e=>e.slot===r);a&&(i=I_(i,a.id));let o=n.getBoundingClientRect?.().width??0,s=o>0&&o>=680?M(i,o)??i:i;if(t&&e){let n=gv(d,t.id,t.label,e);if(e.kind===`mcp-app`&&n.content.kind===`mcp-app`){n.content=e,n.label=t.label;let r=Ig(d);r.previews=[...r.previews]}}else d.sidebarContent=e;d.updateSidebarLayout(s),a&&d.updateSidebarActivePanel(a.id)},d.handleCloseSidebar=e=>{e===`workspace`&&Yv(d),d.updateSidebarLayout(z_(d.sidebarLayout,e))},d.beginImageOpen=()=>{let e=LS(d);return t.invalidate(),e},d.handleOpenImage=(e,n)=>{if((n??d.beginImageOpen())!==d.imageLightboxRequestVersion){e.release?.();return}let r=e.kind===`video`,i=e=>r?Fu(e,`video`):dt(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}d.imageLightbox={...e,src:a,...o?{originalSrc:o}:{}},t.invalidate()},d.handleCloseImage=()=>{LS(d),t.invalidate()},d}function BS(){return(BS=e((()=>{ds(),Jh(),sr(),Zo(),$n(),Cn(),Xa(),vt(),Nt(),qe(),I(),Cl(),kc(),ie(),Zp(),gd(),Cf(),Vc(),od(),CS(),ru(),FS(),Tu(),Cc(),Q(),Du(),f_(),vc(),Au(),Ju(),_f(),Bf(),Lt(),v_()})))()}function VS(e){let t=e.chatStreamRenderFrame;t!=null&&(e.chatStreamRenderFrame=null,typeof globalThis.cancelAnimationFrame==`function`&&globalThis.cancelAnimationFrame(t))}function HS(e,t=`immediate`){if(globalThis.document?.visibilityState===`hidden`||t===`immediate`||typeof globalThis.requestAnimationFrame!=`function`){VS(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}var US;function WS(){return(WS=e((()=>{fn(),y(),Ua(),I(),lt(),Zl(),dx(),Pp(),Cf(),CS(),BS(),sp(),Pu(),Fm(),f_(),dl(),vc(),bp(),Ju(),Bf(),US=class{constructor(e,t,n){this.host=e,this.onStateChange=t,this.onQueuedMessageDiscarded=n,this.previousChatLoading=!1,this.previousChatMessages=[],this.previousChatToolMessages=[],this.previousChatStreamSegments=[],this.previousGuardianNotices=[],this.previousChatStream=null,this.previousRealtimeConversation=[],this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1,this.cleanups=[],this.renderLifecycleConnected=!1,this.attachmentReadsValue=new Hm(()=>this.stateValue?.requestUpdate?.()),this.composerPersistence=new Hp(()=>this.stateValue),e.addController(this)}get attachmentReads(){return this.attachmentReadsValue}takeAttachmentReads(){let e=this.attachmentReadsValue;return this.attachmentReadsValue=new Hm(()=>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:Hs(e.hello?.policy),getAttachments:()=>e.chatAttachments,pendingAttachmentReads:t.pendingReads,getPendingAttachmentReads:()=>t.pendingReads,readSignal:n,onPendingReadsChange:r=>{r===1&&n===t.readSignal&&Ef(e),t.updatePending(n,r)},onAttachmentsChange:t=>{e.chatAttachments=t,e.requestUpdate?.()}}}createRenderLifecycle(){this.cancelRenderLifecycleScope();let e={cancellations: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(),ox(this.stateValue),Gd(this.stateValue.requestUpdate),this.attachmentReads.abortReads(),this.composerPersistence.stop(),VS(this.stateValue),wm(this.stateValue),bS(this.stateValue)),this.stateValue=e;let t=cf(e)?.page;this.previousPendingInputs=t,e.canRestoreComposer=()=>this.stateValue===e&&this.composerPersistence.active,this.previousChatLoading=e.chatLoading,this.previousChatMessages=e.chatMessages,this.previousChatToolMessages=e.chatToolMessages,this.previousChatStreamSegments=e.chatStreamSegments,this.previousGuardianNotices=e.guardianNotices,this.previousChatStream=e.chatStream,this.previousRealtimeConversation=e.realtimeTalkConversationState.entries;let n=e.renderLifecycle;e.requestUpdate=()=>n.invalidate(),this.cleanups.push(Wf(e).subscribe(e,t=>{this.stateValue===e&&this.onQueuedMessageDiscarded?.(t)})),this.cleanups.push(_n(()=>this.stateValue!==e||!e.chatQueuedEdit&&!this.hasPrivateDraft(e),()=>{if(!e.chatQueuedEdit&&this.hasPrivateDraft(e)){Ot({message:V(`chat.privateDraftReload.blocked`),actionLabel:V(`chat.privateDraftReload.review`),onAction:()=>void this.reviewPrivateDraft(e)});return}let t=e.chatQueuedEdit,n=e.client;Ot({message:V(`chat.queue.reloadBlocked`),actionLabel:e.reviewQueuedMessageEdit?V(`chat.queue.reviewEdit`):void 0,onAction:()=>{this.stateValue===e&&e.client===n&&t&&hu(e)===t&&e.reviewQueuedMessageEdit?.()}})}));let r=e.handleSendChat;e.handleSendChat=async(e,t,i)=>{let a=r(e,t,i);n.invalidate();try{return await a}finally{n.invalidate()}};let i=e.handleChatDraftChange;e.handleChatDraftChange=(e,t)=>{i(e,t),this.composerPersistence.schedule()};let a=e.handleChatInputHistoryKey;e.handleChatInputHistoryKey=t=>{let n=a(t);return n.handled&&(this.composerPersistence.schedule(),e.renderLifecycle.invalidate()),n}}hasPrivateComposerInput(e){return Ul(e,j(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=qa(t);return(n.incognito||r&&Ul(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=ju(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&&lc(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 $p({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);Jc(l.filter(e=>!t?.has(e.id)),[e.chatAttachments,...Object.values(e.chatComposerFallbackByScope).map(e=>e.attachments)]),e.requestUpdate?.(),await f?.()}catch{p.isCurrent()&&Ot({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)&&Ot({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.cancellations)t()}}afterCommit(e,t,n){if(!this.isRenderLifecycleScopeActive(e))return n?.(),()=>void 0;let r=!0,i=!1,a,o=()=>{r&&(r=!1,a=void 0,e.cancellations.delete(s))},s=()=>{if(r){r=!1,e.cancellations.delete(s);try{a?.()}finally{a=void 0,i||n?.()}}};return e.cancellations.add(s),this.requestUpdateForScope(e)?(this.host.updateComplete.then(()=>{if(r){if(!this.isRenderLifecycleScopeActive(e)){s();return}i=!0;try{let n=t(o);typeof n==`function`?r&&this.isRenderLifecycleScopeActive(e)?a=n:n():o()}catch(e){throw o(),e}}},s),s):(s(),s)}captureRenderLifecycleChanges(){let e=this.stateValue;if(!e)return;let t=cf(e)?.page,n=this.previousPendingInputs!==t||this.previousChatMessages!==e.chatMessages||this.previousChatToolMessages!==e.chatToolMessages||this.previousChatStreamSegments!==e.chatStreamSegments||this.previousGuardianNotices!==e.guardianNotices||this.previousRealtimeConversation!==e.realtimeTalkConversationState.entries,r=this.previousChatStream!==e.chatStream,i=this.previousChatLoading!==e.chatLoading,a=this.previousChatLoading&&!e.chatLoading,o=this.previousChatStream==null&&typeof e.chatStream==`string`;this.previousPendingInputs=t,this.previousChatLoading=e.chatLoading,this.previousChatMessages=e.chatMessages,this.previousChatToolMessages=e.chatToolMessages,this.previousChatStreamSegments=e.chatStreamSegments,this.previousGuardianNotices=e.guardianNotices,this.previousChatStream=e.chatStream,this.previousRealtimeConversation=e.realtimeTalkConversationState.entries,(n||r||i)&&(this.scrollAfterUpdate=!0,this.scrollContentChangedAfterUpdate||=n||r,this.forceScrollAfterUpdate||=a||o||!e.chatHasAutoScrolled)}handleTranscriptResize(){this.stateValue&&this.renderLifecycleConnected&&Ud(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&&Ud(e,t,e.chatHasAutoScrolled,{contentChanged:n})}stopChatEffects(){for(this.privateDraftReview?.controller.abort();this.cleanups.length>0;)this.cleanups.pop()?.();let e=this.stateValue;e&&(ox(e),Gd(e.requestUpdate),VS(e),wm(e),LS(e),(e.sidebarContent?.kind===`loading`||e.sidebarContent?.kind===`unavailable`)&&(e.sidebarContent=null),Yv(e),T_(e.sessionWorkspaceState),bS(e),e.resetToolStream?.())}hostDisconnected(){this.renderLifecycleConnected=!1,this.cancelRenderLifecycleScope(),this.attachmentReads.abortReads(),this.composerPersistence.stop(),this.stopChatEffects(),this.stateValue=void 0,this.previousPendingInputs=void 0,this.scrollAfterUpdate=!1,this.scrollContentChangedAfterUpdate=!1,this.forceScrollAfterUpdate=!1}}})))()}function GS(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 KS(e){if(e.defaultPrevented||!qS.has(e.key))return!1;let t=e.key!==` `&&e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&!e.shiftKey&&!e.altKey&&!e.metaKey,n=Mo(),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 qS;function JS(){return(JS=e((()=>{Ue(),qS=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `])})))()}var $;function YS(){return(YS=e((()=>{So(),Mr(),rn(),En(),Xo(),Es(),zh(),I(),bh(),ge(),Rm(),St(),r(),oS(),ie(),Zp(),uS(),_S(),WS(),Q(),g_(),Em(),Xv(),Qv(),_f(),Bf(),Ke(),$=class extends d{connectedCallback(){this.paneLifecycleRoot=this.closest(`openclaw-app-shell`)??this.parentElement,document.addEventListener(`visibilitychange`,this.handleVisibilityChange),super.connectedCallback(),this.addEventListener(f,this.synchronizeForegroundTranscript),this.paneLifecycleRoot?.dispatchEvent(new Event(At))}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(f,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(At))}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(At,{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?ll(this.state).phase:`idle`;return e===`pending-connection`||e===`in-flight`}get historyRecovering(){return!!(this.state&&this.state.client===this.context?.gateway.snapshot.client&&nl(this.state))}get transcriptReady(){if(!this.state?.connected||this.state.client!==this.context?.gateway.snapshot.client)return!1;let e=this.state?ll(this.state).phase:`idle`;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||sn(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:X(e),working:$d(e),completion:e.chatRunStatus}:null}resolveChatReadTarget(){let e=this.state;if(!e)return;let t=j(e,e.sessionKey);if(t.agentId)return t;let n=Pc(e);return n&&tt(n.key)?j(e,n.key):n?.agentId&&(n.key===`global`||n.key===`unknown`)?{sessionKey:n.key,agentId:n.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;lS(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=c_(this.presentationId).composerTextarea?.value,n=t!==void 0&&t!==e.chatMessage;n&&e.handleChatDraftChange(t),(n||e.chatStreamRenderFrame!=null)&&HS(e)},this.minutePoll=new ec(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:st(this.state,{sessionKey:this.state.sessionKey}),client:this.state.client,ready:this.transcriptReady||Pc(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 US(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(g,{bubbles:!0})))},e=>Fg(this.presentationId).transcriptRenderContext.onAsyncQuestionDiscard?.(e)),this.composerCapabilities=new aS(()=>this.requestUpdate()),this.transcript=new G_(this,()=>this.paneId,{visuallyPresented:()=>this.visuallyPresented,onViewportResize:()=>this.chatState.handleTranscriptResize(),canFollowEnd:()=>this.state!==void 0&&mp(this.state),onReaderScroll:e=>this.state&&Sp(this.state,e)}),this.progressCard=new gg(this,{gateway:()=>this.context?.gateway,target:()=>this.initialProgressCardTarget()}),this.questionPromptState=Ts(()=>{this.questionPrompts=ls(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.headerEditing=!1,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 gS,this.resetConfirmationOpen=!1,this.deferredSessionHydrationRequestVersion=0,this.observedBoardPresence=new Map,this.swarmHydrator=null,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 Sh,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.historyObserverRoot=null,this.historyObserverSentinel=null,this.historyObserverBootstrap=!1,this.historyObserverArmed=!1,this.historyAutoLoadBlocked=!1,this.historyIntentConsumed=!1,this.historyIntentTimer=null,this.historyTouchY=null,this.transcriptScrollTop=null,this.olderCursorsSeen=new Set,gs(this),new rt(this).effect(()=>this.ownerDocument,sf).watchStore(()=>this.context&&sn(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)))}},J([yo({context:_r,subscribe:!0})],$.prototype,`context`,void 0),J([G({attribute:!1})],$.prototype,`mcpAppLaunch`,void 0),J([G({attribute:!1})],$.prototype,`paneId`,void 0),J([G({attribute:!1})],$.prototype,`paneLabel`,void 0),J([G({attribute:!1})],$.prototype,`presentationId`,void 0),J([G({attribute:!1})],$.prototype,`chatMessagesBySession`,void 0),J([G({attribute:!1})],$.prototype,`sessionSnapshotStore`,void 0),J([G({attribute:!1})],$.prototype,`sessionKey`,void 0),J([G({attribute:!1})],$.prototype,`routeLoadingSkeleton`,void 0),J([G({attribute:!1})],$.prototype,`agentId`,void 0),J([G({attribute:!1})],$.prototype,`inputRegion`,void 0),J([G({attribute:!1})],$.prototype,`compact`,void 0),J([G({attribute:!1})],$.prototype,`workContext`,void 0),J([G({attribute:!1})],$.prototype,`draft`,void 0),J([G({attribute:!1})],$.prototype,`focusComposer`,void 0),J([G({attribute:!1})],$.prototype,`dashboardExpanded`,void 0),J([G({attribute:!1})],$.prototype,`routeFace`,void 0),J([G({attribute:!1})],$.prototype,`onFaceChange`,void 0),J([G({attribute:!1})],$.prototype,`onFocusPane`,void 0),J([G({attribute:!1})],$.prototype,`onSessionDeleted`,void 0),J([G({attribute:!1})],$.prototype,`presentationTitle`,void 0),J([G({attribute:!1})],$.prototype,`narrow`,void 0),J([G({attribute:!1})],$.prototype,`mergedChrome`,void 0),J([G({attribute:!1})],$.prototype,`navDrawerOpen`,void 0),J([G({attribute:!1})],$.prototype,`onboarding`,void 0),J([G({attribute:!1})],$.prototype,`onOpenSplitView`,void 0),J([G({attribute:!1})],$.prototype,`onSplitDown`,void 0),J([G({attribute:!1})],$.prototype,`onSplitRight`,void 0),J([G({attribute:!1})],$.prototype,`onClosePane`,void 0),J([G({attribute:!1})],$.prototype,`boardProvider`,void 0),J([Dr()],$.prototype,`paneWidth`,void 0),J([Dr()],$.prototype,`headerEditing`,void 0),J([Dr()],$.prototype,`headerRenameValue`,void 0),J([Dr()],$.prototype,`headerPlatform`,void 0),J([Dr()],$.prototype,`headerCopiedAction`,void 0),J([Dr()],$.prototype,`headerPlacementMovingKey`,void 0),J([Dr()],$.prototype,`headerPlacementReclaimingKey`,void 0),J([Dr()],$.prototype,`headerPlacementRestartingKey`,void 0),J([Dr()],$.prototype,`sessionSharingStates`,void 0),J([Dr()],$.prototype,`resetConfirmationOpen`,void 0),J([Dr()],$.prototype,`catalogMessages`,void 0),J([Dr()],$.prototype,`catalogLoading`,void 0),J([Dr()],$.prototype,`loadingOlder`,void 0)})))()}function XS(e){return JSON.stringify([e.question,e.answer,e.ts])}function ZS(e,t){let n=e.turns.flatMap(e=>e.attachments??[]),r=[...e.responses],i=t.map(e=>({exchange:e,key:XS(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),Jc(n,[e.turns.flatMap(e=>e.attachments??[])]),e.responses=new Map(a.slice(-24).map(({turn:e,key:t})=>[e,t]))}function QS(e,t){return`${t?.trim()??``}\0${e.trim()}`}function $S(e){let t=e.flatMap(e=>e.selectionAnnotation?[qv(e.selectionAnnotation)]:[]);return t.length?t.join(`
`):void 0}function eC(e,t,n,r,i,a){let o=$S(i??[]),s=i?.filter(e=>!e.selectionAnnotation);return s?.length&&_t(a),e.request(`sessions.companion.ask`,{sessionKey:t,...r?{agentId:r}:{},question:n,...o?{selectionContext:o}:{},...s?.length?{attachments:Tm(s)}:{}},{timeoutMs:iC})}function tC(e,t,n){return e.request(`sessions.companion.state`,{sessionKey:t,...n?{agentId:n}:{}})}function nC(e,t,n){return e.request(`sessions.companion.reset`,{sessionKey:t,...n?{agentId:n}:{}})}var rC,iC,aC;function oC(){return(oC=e((()=>{Yr(),ao(),y(),lt(),ut(),of(),Zl(),Pu(),$v(),rC=`SESSION_COMPANION_BUSY`,iC=7e4,aC=class{constructor(e=()=>{}){this.notify=e,this.threads=new Map,this.hydrationTokens=new Map,this.submissionTokens=new Map}view(e,t){return this.get(e,t)}setDraft(e,t,n){let r=this.get(e,n);r.draft!==t&&(r.draft=t,r.draftRevision+=1,this.notify())}setAttachments(e,t,n){if(($S(t)?.length??0)>16e3)return Ot({message:V(`chat.rail.selectionTooLong`)}),!1;let r=this.get(e,n);return r.attachments=t,this.notify(),!0}async hydrate(e,t,n){let r=e.trim();if(!r)return;let i=QS(r,n),a=this.get(r,n),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;ZS(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=QS(i,r),s=this.get(i,r);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))Ge(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=_o();this.submissionTokens.set(o,u),this.notify();try{let e=await n(i,a,l.attachments);if(this.submissionTokens.get(o)!==u)return;Ge(l.attachments??[]),delete l.attachments,Object.assign(l,{status:`answered`,answer:e.answer,ts:e.ts}),s.responses.set(l,XS({question:a,...e})),s.responses=new Map([...s.responses].slice(-24))}catch(e){if(this.submissionTokens.get(o)!==u)return;let t=Eo(Eo(e).details),n=Po(t,`reason`)??null,r=n===`image-input-unsupported`,i=t.code===rC?`busy`:n===`context-unavailable`?`history-unavailable`:n===`session-missing`?`missing`:n===`rate-limited`?`rate-limited`:r?`image-unsupported`:n===`utility-model-unavailable`?`model-unavailable`:`unavailable`;Object.assign(l,{status:`failed`,hint:i,retryable:r||!!Eo(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=QS(r,n),a=this.get(r,n),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=_o();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),Jc(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?QS(e,t):null;for(let[e,t]of this.threads)if(!(n&&n!==e)){t.attachmentReads?.abortReads(),Ge(t.attachments??[]);for(let e of t.turns)Ge(e.attachments??[])}for(let e of[this.threads,this.hydrationTokens,this.submissionTokens])n?e.delete(n):e.clear();this.notify()}get(e,t){let n=QS(e,t),r=this.threads.get(n);return r||(r={turns:[],loading:!1,draft:``,attachments:[],attachmentReads:new Hm(this.notify),revision:0,draftRevision:0,pendingResets:new Set,responses:new Map},this.threads.set(n,r)),r}}})))()}var sC;function cC(){return(cC=e((()=>{Yr(),y(),eg(),Me(),lt(),ut(),YS(),oC(),Q(),g_(),$v(),v_(),sC=class extends ${constructor(...e){super(...e),this.sessionCompanionHydrationKey=``,this.sessionCompanionFocusGeneration=0,this.sessionCompanionPresented=!1,this.sessionCompanionThreads=new aC(()=>{this.requestUpdate()}),this.setSessionObserverVisibility=e=>{let t=this.state;t?.connected&&t.client&&ze(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=X(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)&&!Ze(t.uploadConfig)){Ot({message:Qe()});return}await this.sessionCompanionThreads.submit(n,e,(e,n,i)=>eC(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=X(n),i=this.sessionCompanionThreads.view(t,r),a=[...i.attachments??[],e];if(qv({...e.selectionAnnotation,comment:``}).length>16e3)Ot({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,Qh(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?Bv(e,t.id):e,open:!1,expanded:!1}}setChatSidePanelOpen(e,t){let n=this.state;if(!n)return;let r=t??n.sidebarLayout,i=U_(r,e);r.columns[0]?.panels.some(e=>e.slot===`companion`)&&this.setSessionObserverVisibility(Le(i,`companion`)),this.commitSidebarLayout(i,Ye(r)?.slot===`dashboard`?{dashboardPresentation:`personal`}:void 0)}requestSessionRail(e){let t=this.state;if(t){if(e===`toggle`&&Le(t.sidebarLayout,`companion`)){this.commitSidebarLayout(z_(t.sidebarLayout,`companion`)),this.setSessionObserverVisibility(!1);return}this.commitSidebarLayout(Q_(t.sidebarLayout,`companion`)),this.setSessionObserverVisibility(!0)}}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=X(e),r=this.connectionGeneration,i=this.sessionCompanionFocusGeneration,a=c_(this.presentationId),o=a.editRevision,s=e.chatMessage,c=()=>this.state===e&&e.sessionKey===t&&X(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||R(e))return;let n=X(t),r=`${this.connectionGeneration}\0${n}\0${e}`;this.sessionCompanionHydrationKey!==r&&(this.sessionCompanionHydrationKey=r,this.sessionCompanionThreads.hydrate(e,e=>tC(t.client,e,n),n))}}})))()}var lC,uC;function dC(){return(dC=e((()=>{ri(),ks(),y(),Ae(),vt(),O(),I(),lt(),cC(),oC(),Q(),Cv(),lC=`session.members.listEvidence`,uC=class extends sC{constructor(...e){super(...e),this.clearSessionCompanion=async()=>{let e=this.captureConnectionScope(),t=e?.state.sessionKey;if(!e||!t)return;let n=X(e.state);await this.sessionCompanionThreads.reset(t,t=>nC(e.client,t,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?X(this.state):void 0:tt(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||!Av(t)||!Av(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||!L(n.context.gateway.snapshot,{method:lC,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,c=()=>{if(!s())return;let e=new Map(this.sessionSharingStates);e.delete(i),this.sessionSharingStates=e};this.setSessionSharingState(i,o);let l;try{l={loading:!1,result:await n.client.request(lC,{sessionKey:r.key,...this.sessionSharingAgentId(r.key)?{agentId:this.sessionSharingAgentId(r.key)}:{}})}}catch(e){l={loading:!1,error:B(e)}}if(!this.ownsSessionSharing(n,r)||!s()){this.isConnectionScopeCurrent(n)&&c();return}this.setSessionSharingState(i,l)}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=()=>L(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 zo({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}}:{}}),Ot({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,n=e.snapshot.hello?.controlUiUrl,i=n??t.client.gatewayUrl??e.connection.gatewayUrl,o=new URL(i||window.location.href);o.protocol=o.protocol.replace(/^ws/u,`http`);let s=ni({basePath:n?o.pathname:t.context.basePath,token:r.token}),c=await Pe(new URL(s,o.origin).href,a);a()&&Ot({message:V(c?`common.copied`:`common.copyFailed`)})}catch(e){a()&&this.publishHeaderError(e)}}async setSessionVisibility(e,t){let n=this.captureConnectionScope(),r=n?this.currentSessionSharingRow(n,e):null;if(!n||!r||t===r.visibility)return;let i=this.sessionSharingAgentId(r.key),a=this.sessionSharingCacheKey(r.key),o={sessionKey:r.key,visibility:t,...i?{agentId:i}:{}};if(L(n.context.gateway.snapshot,{method:`session.visibility.set`,requiredScope:`operator.write`}).allowed)try{if(await n.client.request(`session.visibility.set`,o),!this.ownsSessionSharing(n,r))return;let e=await n.sessions.reconcileMutation(i),t=this.currentSessionSharingRow(n,r);if(!this.ownsHeaderOutcomeScope(n)||!t)return;if(e.status===`failed`){this.failSharing(n,a,r.key,e.error);return}await this.loadSessionSharing(t,!0)}catch(e){if(!this.ownsSessionSharing(n,r))return;this.failSharing(n,a,r.key,e)}}async setSessionMember(e,t,n){let r=this.captureConnectionScope(),i=r?this.currentSessionSharingRow(r,e):null;if(!r||!i)return;let a=this.sessionSharingAgentId(i.key),o=this.sessionSharingCacheKey(i.key),s=n?`session.members.add`:`session.members.remove`,c={sessionKey:i.key,identityId:t,...a?{agentId:a}:{}};if(L(r.context.gateway.snapshot,{method:s,requiredScope:`operator.write`}).allowed)try{if(await r.client.request(s,c),!this.ownsSessionSharing(r,i)||(await this.loadSessionSharing(i,!0),!this.ownsSessionSharing(r,i)))return;let e=await r.sessions.reconcileMutation(a);e.status===`failed`&&this.ownsSessionSharing(r,i)&&this.failSharing(r,o,i.key,e.error)}catch(e){if(!this.ownsSessionSharing(r,i))return;this.failSharing(r,o,i.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 fC;function pC(){return(pC=e((()=>{yr(),vt(),si(),Me(),Pt(),I(),dC(),Q(),fC=class extends uC{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,...N(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&&Kn(this.context.gateway.snapshot,Z(e),{archived:this.isCurrentSessionArchived(e),catalog:!!R(e.sessionKey)}))}syncSessionReactions(){let e=this.captureConnectionScope(),t=e?.state,n=t&&(Z(t)?.sessionId??t.currentSessionId),r=e&&t&&n&&!R(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,...N(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&&ne({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 mC(e,t){let n=re(e);if(!n||!ne(t,n.key,n.agentId??void 0))return;let r=q(q(e)?.message);if(ro(r?.role)?.toLowerCase()!==`user`)return;let i=Bt(q(r?.__openclaw)?.senderIdentity);return i?.type===`profile`?i.id:void 0}function hC(){return(hC=e((()=>{Yt(),l(),I()})))()}var gC,_C,vC,yC,bC,xC;function SC(){return(SC=e((()=>{Nn(),y(),vt(),si(),Qa(),Pt(),I(),pC(),rd(),Q(),hC(),Cv(),gC=2500,_C=1e4,vC=3e4,yC=300,bC=250,xC=class extends fC{constructor(...e){super(...e),this.typingActiveIds=new Set,this.typingViews=[]}syncSelectedSessionSharing(e){let t=e?.sessionId?.trim();if(!e||!t||!this.presented||!Av(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&&ne({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello,sessionKey:t.sessionKey},e.sessionKey,e.agentId))}hasMultipleIdentities(){return Ni(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,...N(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,...N(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(ep)?.focus({preventScroll:!0}))),this.requestUpdate();try{let i=await n.client.request(`session.suggestions.resolve`,{sessionKey:r,id:e.id,resolution:t,...N(n.state,r)});if(!a())return;this.sessionSuggestions=i.suggestion.author.id===this.context.gateway.snapshot.selfUser?.id?[...this.sessionSuggestions.filter(t=>t.id!==e.id),i.suggestion].toSorted((e,t)=>e.createdAt-t.createdAt||e.id.localeCompare(t.id)):this.sessionSuggestions.filter(t=>t.id!==e.id)}catch(r){a()&&(t===`edit`&&r instanceof jn&&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=j(e,e.sessionKey),n=Ee(t.sessionKey,t.agentId),r=new Set(Na(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||!ne({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?_C:gC,o=Date.now(),s=o+vC,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-vC+_C<=Date.now()&&(t.paused=!0,this.typingActiveIds.delete(e))}let n=t-yC;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=mC(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}:{},...N(n.state,i)}).catch(()=>void 0)},l=e&&this.typingRequestSentAt!==void 0?bC-(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 CC;function wC(){return(wC=e((()=>{Io(),Nn(),zn(),yr(),y(),Ae(),vt(),si(),Me(),P(),SC(),Q(),CC=class extends xC{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 Pe(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`)){this.setTaskSuggestions([]),this.requestUpdate();return}let r=n.state.sessionKey;if(R(r)){this.setTaskSuggestions([]),this.requestUpdate();return}let i=X(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&&(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&&Rn(i),o=e&&Wn(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`&&Sr(i),onOpenTaskSuggestion:this.onPaneSessionChange?e=>{let t=this.taskSuggestionOperations.get(e.id),n=this.context.gateway.snapshot;n.phase===`connected`&&Sr(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`?Wn(s):Rn(s)))return;let c=i.state.sessionKey,l=ro(i.state.currentSessionId),u=!1,d=pr(i.context.gateway),f=o.hello?.auth?.recoveryScope??(i.client.recoveryScopeReady?i.client.recoveryScope:void 0),p=()=>{let e=ro(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&&pr(i.context.gateway)===d&&(!n||n===f)},m=()=>this.isConnectionScopeCurrent(i)&&p(),h=t===`accept`?{action:t,resolved:!1,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=ro(t.key);if(t.taskId!==e.id||!n)throw Error(V(`chat.taskSuggestions.startUnconfirmed`));h.outcome={phase:`started`,sessionKey:n,href:_e({face:`chat`,sessionKey:n,fallbackAgentId:e.agentId??X(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 jn?e.details:void 0,n=h.mode===`worktree`&&t&&typeof t==`object`&&`code`in t&&t.code===ho.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 TC;function EC(){return(EC=e((()=>{io(),y(),vt(),we(),si(),Vi(),O(),Ep(),Me(),Pt(),I(),Zl(),rS(),Xp(),Zp(),rd(),wC(),cm(),Q(),Gv(),am(),Bf(),TC=class extends CC{constructor(...e){super(...e),this.deferredSessionHydrationActive=!1,this.pendingDeferredSessionHydration=null,this.dismissSessionPullRequest=e=>{let t=this.state?.sessionKey;t&&(this.dismissedSessionPullRequestIds=bv(t,e),this.requestUpdate())}}secondarySessionReadsReady(e=!1){let t=this.state;return!!(t?.connected&&this.presented&&document.visibilityState!==`hidden`&&(e||!this.deferredSessionHydrationActive&&(R(t.sessionKey)||this.transcriptReady||Pc(t))))}subscribeSessionRepositoryContext(){this.chatState.addCleanup(bi(this.context.gateway).subscribe(()=>this.requestUpdate()));let e=Uf(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(J_(e)))}applyPullRequestPresentation(e,t=this.dismissedSessionPullRequestIds){let n=e?.pullRequests??[],r=nm(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 Uf(this.context.gateway).unwatch(this),!1;let t=this.captureConnectionScope();if(!t||!oi(t.context.gateway.snapshot,`controlUi.sessionPullRequests.subscribe`,`operator.read`))return t&&Uf(t.context.gateway).unwatch(this),this.applyPullRequestPresentation(),!1;let n=t.state.sessionKey;if(!n.trim()||R(n))return Uf(t.context.gateway).unwatch(this),this.applyPullRequestPresentation(),!1;let r=t.context.sessions.capturePullRequestEpoch(n),i=Uf(t.context.gateway),a=Ee(n,N(t.state,n).agentId??X(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=nm(s),l=this.githubRepo!=null&&c!==null&&(this.githubRepo.owner!==c.owner||this.githubRepo.repo!==c.repo);if(this.applyPullRequestPresentation(s,Z_(n)),!s.rateLimited||s.pullRequests.length>0||l){let e=t.context.sessions.pullRequestSummary(n);t.context.sessions.setPullRequestSummary(n,Md(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&&mm(this.state),Uf(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}deferSessionHydrationUntilTranscript(e,t){let n=this.state;if(!n)return;this.deferredSessionHydrationActive=!0,this.pendingDeferredSessionHydration=null;let r=++this.deferredSessionHydrationRequestVersion,i=this.connectionGeneration,a=n.client,o=()=>{this.deferredSessionHydrationRequestVersion===r&&(this.deferredSessionHydrationActive=!1,this.pendingDeferredSessionHydration=null)},s=()=>this.deferredSessionHydrationRequestVersion===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`){this.pendingDeferredSessionHydration=()=>c(t);return}this.pendingDeferredSessionHydration=null,Gf(n,()=>{s()&&this.presented&&document.visibilityState!==`hidden`?(this.deferredSessionHydrationActive=!1,n.requestUpdate?.(),this.refreshTaskSuggestions({automatic:!0}),t&&this.markSessionRead(Z(n)),a&&this.loadHeaderPlatform(a,i),pd(n),this.probeSessionDiscussion(e),this.hydrateSessionCompanion(e),this.refreshSessionPullRequests()):s()?this.pendingDeferredSessionHydration=()=>c(t):o()})};t.then(c,()=>c(!1))}resumeDeferredSessionHydration(){let e=this.pendingDeferredSessionHydration;return this.pendingDeferredSessionHydration=null,e?.(),this.deferredSessionHydrationActive}retireDeferredSessionHydration(){this.deferredSessionHydrationRequestVersion+=1,this.deferredSessionHydrationActive=!1,this.pendingDeferredSessionHydration=null}markSessionRead(e){let t=this.state;if(!t?.connected||!e)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());if(!(e.unread===!0||r||i)){this.unreadPatchGuard.shouldPatch(t.sessionKey,!1,e.markedUnreadAt);return}let a=tt(e.key)?.agentId??X(t);if(!L(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,unread:!1,agentId:a}}).allowed||e.sharingRole===`viewer`||this.sessionParticipationTracker.resolve({catalog:R(t.sessionKey)!==null,listLoading:t.sessionsLoading,sessionKey:`${X(t)??``}\0${t.sessionKey}`,session:e})||!this.unreadPatchGuard.shouldPatch(t.sessionKey,!0,e.markedUnreadAt))return;let o=t.sessionKey;this.context.sessions.patch(e.key,{unread:!1},{agentId:a,expectedMarkedUnreadAt:e.markedUnreadAt??null}).then(e=>{e===null&&this.unreadPatchGuard.patchFailed(o)},e=>{this.unreadPatchGuard.patchFailed(o,e)})}async restoreArchivedSession(e,t){let n=this.captureConnectionScope();if(!n||n.state.sessionKey!==e)return;let r=L(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=tt(e)?.agentId??X(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=R(e)?e:Ce(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,Ge(t.chatAttachments),t.chatAttachments=[],t.chatLoading=!0,t.requestUpdate(),this.loadCatalogSession(e,!1)}catalogItemMessage(e){let t=no(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??gu(e.raw,[`command`,`name`,`tool`,`title`,`query`]);r=t?`Tool call\n\n${t}`:`Tool call`}else if(e.type===`toolResult`){let t=n??gu(e.raw,[`aggregatedOutput`])??yl(e.raw),a=t?nt(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(nS).filter(Boolean));return[...e.filter(e=>{let n=nS(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=X(r),o=t?this.catalogLoadGeneration:++this.catalogLoadGeneration,s=this.sessionKey,c=()=>this.isConnectionScopeCurrent(n)&&o===this.catalogLoadGeneration&&this.sessionKey===s&&X(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 Oe({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,th(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 DC;function OC(){return(OC=e((()=>{y(),sa(),Me(),Pt(),I(),EC(),Ib(),ka(),DC=class extends TC{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.state;if(!t||R(t.sessionKey))return;let n=this.currentReplyMessage(e);return n?.message?void 0:n?.status??`pending`},this.requestReplyMessage=e=>{this.loadReplyMessage(e)},this.openReplyMessage=e=>{this.navigateToReplyMessage(e)}}currentReplyMessage(e){let t=this.state;if(!t)return;let n=this.replyMessages.get(this.replyMessageCacheKey(t.sessionKey,e));return n?.client===t.client&&n.generation===this.connectionGeneration?n:void 0}replyMessageCacheKey(e,t){let n=this.state;return`${e}\u0000${(n?N(n,e).agentId:void 0)??``}\u0000${t}`}async loadReplyMessage(e){let t=this.captureConnectionScope();if(!t||R(t.state.sessionKey))return;let n=t.state.sessionKey,r=N(t.state,n).agentId,i=this.replyMessageCacheKey(n,e),a=this.replyMessages.get(i);if(a?.client===t.client&&a.generation===t.generation)return;for(;this.replyMessages.size>=256;)this.replyMessages.delete(this.replyMessages.keys().next().value);let o={client:t.client,generation:t.generation};this.replyMessages.set(i,o);let s;try{s=await t.client.request(`chat.message.get`,{sessionKey:n,...r?{agentId:r}:{},messageId:e,maxChars:500})}catch{s=void 0}s&&this.isConnectionScopeCurrent(t)&&this.replyMessages.get(i)===o&&(this.replyMessages.set(i,s.ok&&s.message?{...o,message:s.message}:{...o,status:s.unavailableReason===`oversized`?`oversized`:`missing`}),this.replyMessageRevision+=1,z(t.state.sessionKey,n)&&this.requestUpdate())}replyNavigationIsCurrent(e,t,n,r){return this.activeReplyNavigation===e&&this.state===t&&z(t.sessionKey,n)&&(!r||t.currentSessionId===r)}currentReplyNavigationId(e){return this.replyNavigationSessionKey&&z(this.replyNavigationSessionKey,e)?this.replyNavigationId:null}currentReplyMessageAccess(e){return{revision:this.replyMessageRevision,navigationId:this.currentReplyNavigationId(e),read:this.readReplyMessage,status:this.replyMessageStatus,request:this.requestReplyMessage,open:this.openReplyMessage}}retireReplyMessages(){this.replyMessages.clear()}resetReplyNavigation(){this.activeReplyNavigation=null,this.replyNavigationSessionKey=null,this.replyNavigationId=null}async navigateToReplyMessage(e){let t=this.state;if(!t||R(t.sessionKey))return;let n=t.sessionKey,r=t.currentSessionId?.trim()??``,i=Symbol(`reply-navigation`);this.activeReplyNavigation=i,this.replyNavigationSessionKey=n,this.replyNavigationId=e,this.requestUpdate();try{for(;!t.chatMessages.some(t=>Wm(t)===e);){if(!this.replyNavigationIsCurrent(i,t,n,r))return;if(!t.chatHistoryPagination.hasMore){t.lastError=V(`chat.messages.originalUnavailable`),t.requestUpdate?.();return}let e=await this.loadOlderMessages();if(!this.replyNavigationIsCurrent(i,t,n,r))return;if(!e){!t.chatHistoryPagination.hasMore&&!t.lastError&&(t.lastError=V(`chat.messages.originalUnavailable`),t.requestUpdate?.());return}}if(!this.replyNavigationIsCurrent(i,t,n,r))return;this.requestUpdate(),await this.updateComplete,this.replyNavigationIsCurrent(i,t,n,r)&&this.transcript.revealMessage(e)}finally{this.activeReplyNavigation===i&&(this.resetReplyNavigation(),this.requestUpdate())}}}})))()}function kC(e){let t=Wf(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&&Hc(e,n.id))){if(Wf(e).hasVolatile(e,n.id)){Wf(e).change(e,n.id,e=>({...e,sendState:`unconfirmed`}));continue}im(e,n.id,e=>({...e,sendState:`waiting-reconnect`}))}}function AC(e,t){let n=e.sessions.find(e=>z(e.key,t));return!(!n||wo(n))}function jC(e,t,n){return z(t,n)?!0:!!(t&&p(t)&&ue(e,n))}function MC(e,t,n,r){let i=r&&p(r)?ue(e,n):void 0;return t?.sessions.find(t=>z(t.key,n)?!0:i!=null&&ue(e,t.key)===i)}function NC(e,t){if(!t||!wo(t)||wo(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 PC(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=MC(e,s,t,c?.key),u=!(!c||!jC(e,c.key,t)||wo(c)||NC(c,l)),d=s?AC(s,t):!1;o.status!==`fulfilled`||e.chatQueue.length===0||!z(e.sessionKey,t)||!s&&!u||s===i&&!u||e.sessionsError&&!u||!(u||d)||a()})}function FC(){return(FC=e((()=>{I(),Pp(),od(),Ju()})))()}function IC(e){QC.get(e)?.catalogRequest?.controller.abort(),QC.get(e)?.unsubscribe(),QC.delete(e),KC(e),e.chatModelsLoading=!1}function LC(e){let t=typeof globalThis.requestIdleCallback==`function`?globalThis.requestIdleCallback:null;if(t){t(e,{timeout:750});return}globalThis.setTimeout(e,50)}async function RC(e){await kp({client:e.client,agentId:X(e),sessionKey:e.sessionKey})}function zC(e,t){e&&ae(e,e.sessionKey)&&!tt(e.sessionKey)?.agentId&&(e.assistantAgentId??null)!==t&&(BC(e,t),ml(e))}function BC(e,t){(e.assistantAgentId??null)!==t&&(du(e),e.assistantIdentityRequestVersion+=1,e.assistantAgentId=t,e.assistantName=``,e.assistantAvatar=null,e.assistantAvatarSource=null,e.assistantAvatarStatus=null,e.assistantAvatarReason=null,e.chatAvatarUrl=null,e.chatAvatarSource=null,e.chatAvatarStatus=null,e.chatAvatarReason=null,e.modelAuthStatusResult=null,e.modelAuthStatusError=null,HC(e,{automatic:!0}),WC(e).finally(()=>e.requestUpdate?.()),e.loadAssistantIdentity(),e.requestUpdate?.())}function VC(e){let t=QC.get(e);if(t?.isCurrent())return t;t&&IC(e);let n=e.client;if(!n||!e.connected)return;let r={agentId:X(e)??void 0,sessionKey:e.sessionKey},i=e.connectionEpoch,a={client:n,sessions:e.sessions,scope:r,version:0,sessionFactsInvalidated:!1,isCurrent:()=>QC.get(e)===a&&e.connected&&e.client===n&&e.sessions===a.sessions&&e.connectionEpoch===i&&e.sessionKey===r.sessionKey&&(X(e)??void 0)===r.agentId,unsubscribe:xi(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`){t.scope===`full`&&(a.catalogRequest?.controller.abort(),a.catalogRequest=void 0,e.chatModelsLoading=!1,qC(e,a)),a.sessionFactsInvalidated||=t.refreshSessionFacts,HC(e,{automatic:!0});return}t.type!==`loading`&&(t.type===`result`&&(uu(t.result),t.catalogChanged&&(a.sessionFactsInvalidated=!0,HC(e,{automatic:!0}))),a.sessionFactsRetryPending&&(a.sessionFactsRetryPending=!1,JC(e))),e.requestUpdate?.()}},()=>a.isCurrent()&&e.chatMetadataIsPresented?.()!==!1)};QC.set(e,a),e.chatModelCatalogInitialized=u(n);let o=wi(n,r);return o&&uu(o),a}async function HC(e,t){let n=VC(e);if(!n){IC(e);return}if(t?.automatic){if(e.chatMetadataIsPresented?.()===!1)return;let r=Zi(n.client,n.scope,{kind:t.startup?`startup`:void 0}),i=JC(e);if(n.refreshPending?.refresh===r)return n.refreshPending.promise;n.catalogRequest=void 0,e.chatModelsLoading=!i&&e.chatModelCatalog.length===0,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&&ta(n.client,n.scope,{allowStale:!0})!==t||(o=!1,qC(e,n),a()&&(e.chatModelsLoading=!1,e.requestUpdate?.(),n.sessionFactsInvalidated&&e.chatMetadataIsPresented?.()!==!1&&await UC(e,n))))},t=>{o=!r.isCurrent(),a()&&!JC(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 HC(e,{automatic:!0})});return n.refreshPending={refresh:r,promise:c},c}n.refreshPending=void 0,Yi(n.client,n.scope);let r=fi(n.client,n.scope).catch(()=>void 0),i=n.version,a=GC(e,n).then(async t=>{n.sessionFactsInvalidated&&t&&n.isCurrent()&&n.version===i&&await UC(e,n)});await Promise.all([r,a])}function UC(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 WC(e,t){if(!e.client||!e.connected)return;let n=e.client,r=e.connectionEpoch,i=X(e),a=++e.modelAuthStatusRequestVersion,o=()=>e.client===n&&e.connected&&e.connectionEpoch===r&&e.modelAuthStatusRequestVersion===a&&X(e)===i;try{let r=await _i(n,{...t,agentId:i});if(!o())return;e.modelAuthStatusResult=r,e.modelAuthStatusError=r.unavailable?.message??null}catch(t){if(!o())return;e.modelAuthStatusResult={ts:0,providers:[]},e.modelAuthStatusError=B(t)}}async function GC(e,t){if(qC(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.chatModelCatalog.length===0,e.requestUpdate?.();let a=Ma(t.client,{...t.scope,signal:n.signal}).then(n=>{if(!t.isCurrent())return!1;let r=ta(t.client,t.scope);if(r||i()){qC(e,t);let a=!!r||ta(t.client,t.scope,{allowStale:!0})===n;return!a&&i()?(t.catalogRequest=void 0,GC(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 KC(e,t){e.chatModelCatalog=t?.models??[],e.chatModelCatalogInitialized=t!==void 0||u(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 qC(e,t){let n=ta(t.client,t.scope),r=n??ta(t.client,t.scope,{allowStale:!0});return!r&&t.isCurrent()&&h(t.client,t.scope)&&(KC(e),e.chatModelCatalogRetired=!0,e.requestUpdate?.()),!r||!t.isCurrent()?!1:(n&&(t.catalogRequest?.controller.abort(),t.catalogRequest=void 0),KC(e,r),e.chatModelsLoading=!1,e.requestUpdate?.(),!!n)}function JC(e){let t=QC.get(e),n=!!(t&&qC(e,t));return t&&n&&!t.sessionRefreshPending&&t.sessionFactsInvalidated&&e.chatMetadataIsPresented?.()!==!1&&UC(e,t),n}async function YC(e){let t=VC(e);t&&qC(e,t)||(t&&(t.refreshPending=void 0,Yi(t.client,t.scope)),t&&await GC(e,t)&&t.isCurrent()&&await UC(e,t))}async function XC(e,t){let n=e.client,r=e.sessions,i=e.connectionEpoch,a=e.sessionKey,o=Xu(e),s=()=>e.connected&&e.sessions===r&&e.client===n&&e.connectionEpoch===i&&e.sessionKey===a&&Xu(e)===o,c=()=>e.requestUpdate?.(),l=e.sessionsResult,u=t?.historyLoad??ud(e,{deferBranches:t?.deferBranches===!0,startup:t?.startup===!0}),d=u.finally(()=>{t?.scheduleScroll!==!1&&th(e),c()}),f=u.then(t=>{if(!t?.sessionInfo||!s()||t.observation.owner!==r)return;let n=t.observation.reconcile(t.sessionInfo,t.defaults,{resultAgentId:e.sessions.state.agentId??o,selectedGlobalAgentId:o,archivedFilter:t.sessionInfo.archived===!0?`all`:e.sessionsArchivedFilter});if(!n||!s())return;let i=e.sessions.state.agentId!==o&&(ae(e,a)||it(t.sessionInfo));if(e.sessionsResult=i?v(e.sessionsResultAgentId===o?e.sessionsResult:null,n===`defaults-only`?Z(e):t.sessionInfo,t.defaults,{resultAgentId:o,selectedGlobalAgentId:o,archivedFilter:`all`},n===`defaults-only`||e.sessionsResultAgentId===o&&e.sessionsResult!==l):e.sessions.state.result,e.sessionsResultAgentId=i?o:e.sessions.state.agentId,n===`defaults-only`)return;let c=Z(e),u=c??t.sessionInfo;c&&(e.selectedChatSessionArchived=u.archived===!0,e.selectedChatSessionIncognito=u.incognito===!0);let d=t.inFlightRun?.runId?.trim(),f=t.sessionInfo.activeRunIds;(!d||e.chatRunId!==d||!wo(t.sessionInfo)||Array.isArray(f)&&!f.includes(d))&&c&&!wd(e,c,{publishRunStatus:!0,historyRun:t.observation.run&&t.sessionInfo.hasActiveRun===!1&&!wo(t.sessionInfo)&&!t.inFlightRun&&t.sessionInfo.sessionId===t.observation.run.sessionId?t.observation.run:null})&&!e.chatRunId&&e.chatStream==null&&wf(e,{publishRunStatus:!0})}),p=t?.startup===!0&&t.onStartupMetadata?u.then(e=>t.onStartupMetadata?.(e?.metadata),()=>t.onStartupMetadata?.(void 0)):Promise.resolve();if(PC(e,a,d,f,l,()=>void Rl(e)),Promise.allSettled([f,p]).finally(c),t?.awaitHistory===!0){await d;return}await Promise.resolve()}function ZC(e,t){let n=t?.startup?VC(e):void 0,r=n?Hi(n.client,n.scope):void 0;n&&HC(e,{automatic:!0,startup:!0});let i=XC(e,{...t,onStartupMetadata:async e=>{n&&r?.isCurrent()&&(e?r.publish(e):await Zi(n.client,n.scope,{kind:`metadata`,revalidateMetadata:()=>r.isCurrent()}).completed)}}),a=e.sessionKey,o=e.client,s=e.connectionEpoch;return LC(()=>{e.connected&&e.client===o&&e.connectionEpoch===s&&e.sessionKey===a&&Promise.allSettled([bl(e),...t?.startup?[]:[HC(e,{automatic:!0})]]).finally(()=>e.requestUpdate?.())}),i}var QC;function $C(){return($C=e((()=>{Za(),vt(),Pi(),Nt(),ji(),l(),I(),oe(),kc(),pf(),gd(),FC(),ru(),Cc(),Q(),_f(),Bf(),QC=new WeakMap})))()}var ew;function tw(){return(tw=e((()=>{Jr(),Wr(),or(),pi(),vt(),Me(),Pt(),I(),Zl(),Nm(),yc(),Zf(),Zp(),dx(),gd(),OC(),rd(),JS(),$C(),Q(),Pd(),bp(),Im(),Bf(),Pl(),jm(),ew=class extends DC{constructor(...e){super(...e),this.activeCatalogContinuation=null,this.activeOlderLoad=null,this.stagedOlderPage=null,this.stagedOlderLoad=null,this.stagedOlderGeneration=0,this.refreshHistory=()=>{let e=this.state;if(!e)return;let t=R(e.sessionKey);if(t){this.loadCatalogSession(t,!1);return}Qm(e,{preserveStreamSegments:e.chatRunId!==null}),this.reconcileWaitingApprovalSnapshot(),zu(e).subscriptionError&&sx(e);let n=ll(e),r=n.phase===`failed`&&n.startup;ZC(e,{historyLoad:ud(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=st(e,{sessionKey:t}),i=zu(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)||st(e,{sessionKey:t})!==r)return c.complete?.();let a=e.chatMessagesBySession,o=Dc(a,e,{sessionKey:t})??n;if(!o)return c.complete?.();Bs(e,o);let s={...o,messages:e.chatMessages};Qf(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?R(e.sessionKey)?!(!this.catalogCursor||this.catalogLoading):e.chatHistoryPagination.hasMore&&!e.chatLoading:!1}resetOlderMessagesViewport(){this.olderLoadGeneration+=1,this.activeOlderLoad=null,this.stagedOlderGeneration+=1,this.stagedOlderPage=null,this.stagedOlderLoad=null,this.resetReplyNavigation(),this.loadingOlder=!1,this.historyObserverArmed=!1,this.historyAutoLoadBlocked=!1,this.historyIntentConsumed=!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.historyObserverRoot=null,this.historyObserverSentinel=null,this.historyObserverBootstrap=!1}syncHistoryObserver(){if((this.state&&R(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.historyObserverRoot===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:`${Ol}px 0px 0px`,threshold:0}),this.historyObserverRoot=e,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?fm(t):null;if(r){this.transcriptScrollTop=r.scrollTop;let e=this.transcript.renderedSessionKey,t=this.state?.sessionKey;e&&t&&z(e,t)&&Pm(this.paneId,e,af(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(){return this.historyIntentTimer!==null&&window.clearTimeout(this.historyIntentTimer),this.historyIntentTimer=window.setTimeout(()=>{this.historyIntentTimer=null,this.historyIntentConsumed=!1},200),!this.historyIntentConsumed&&(this.historyIntentConsumed=!0,!0)}handleTranscriptHistoryIntent(e){let t=e.currentTarget instanceof HTMLElement?e.currentTarget:null,n=e instanceof WheelEvent&&e.deltaY<0||e instanceof KeyboardEvent&&Il.has(e.key)&&KS(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?R(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.stagedOlderLoad){if(r(),await this.stagedOlderLoad,n!==this.olderLoadGeneration)return!1;s=this.takeStagedOlderPage(e)}if(s||=(r(),await Wl(e,a)??null),!s||n!==this.olderLoadGeneration)return!1;if(s.windowReset)return Bs(e,{messages:s.messages??[],pagination:Tl(s),sessionId:s.sessionInfo?.sessionId??s.sessionId??null,displayedLeafEntryId:s.sessionInfo?.activeLeafEntryId??null,deltaCursor:s.deltaCursor}),zs(e),e.lastError=null,i=!0,!0;let c=typeof s.sessionInfo?.sessionId==`string`&&s.sessionInfo.sessionId.trim()?s.sessionInfo.sessionId.trim():typeof s.sessionId==`string`?s.sessionId.trim():``;if(o&&c!==o)return await ud(e),i=!0,!0;let l=Tl(s),u=!l.hasMore||l.nextOffset<=a,d=Array.isArray(s.messages)?s.messages:[],f=jd(e),p=f.entries.flatMap(e=>e.pending&&e.identity?.role===`user`&&e.pendingRunId?[e.pendingRunId]:[]);if(p.length){let t=d.filter(e=>{let t=Ur(e);return t?.role===`user`&&!t.isImported&&(t.id!==null||t.sequence!==null)}),n=Zr(f,{type:`snapshotLoaded`,messages:t,scope:f.scope}),r=new Set(n.entries.filter(e=>e.pending&&e.identity?.role===`user`).map(e=>e.pendingRunId));Um(e,new Set(p.filter(e=>!r.has(e))))}let m=Sa(d,e.chatMessages),h=m.length>e.chatMessages.length;Jm(e,m),e.chatHistoryPagination=u?{hasMore:!1,...l.totalMessages===void 0?{}:{totalMessages:l.totalMessages}}:l,e.lastError=null,zs(e),th(e,!1),i=h||!u,u||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.stagedOlderPage||this.stagedOlderLoad)return;let t=e.chatHistoryPagination;if(!t.hasMore||R(e.sessionKey))return;let n=this.stagedOlderGeneration;this.stagedOlderLoad=(async()=>{try{let r=await Mu(e,t.nextOffset);r&&n===this.stagedOlderGeneration&&this.state===e&&(this.stagedOlderPage=r)}catch{}finally{n===this.stagedOlderGeneration&&(this.stagedOlderLoad=null)}})()}takeStagedOlderPage(e){let t=this.stagedOlderPage;return t?(this.stagedOlderPage=null,uc(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=Xf(n.chatAttachments);if(!i&&a.length===0)return;let o=n.sessionKey,s=X(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&&X(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(Ic(this.context,this.paneId,t.sessionKey,{attachments:a,draft:i,send:!0}),this.onPaneSessionChange?.(this.paneId,t.sessionKey)===!1){lh(this.context,this.paneId,t.sessionKey),d();return}x({...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 eh(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=N(n,r);try{let a=await n.sessions.forkAtMessage(r,e,i),o=a.editorText??``;if(!this.ownsHeaderOutcomeScope(t)||!Ne(n,r,i.agentId)||this.onPaneSessionChange?.(this.paneId,a.sessionKey)===!1)return;Ed(n,a.sessionKey,{agentId:tt(a.sessionKey)?.agentId,draft:o,mentions:[],replyTarget:null}),Ic(this.context,this.paneId,a.sessionKey,{attachments:gl([],a.editorAttachments),draft:o})}catch(e){if(!this.ownsHeaderOutcomeScope(t)||!Ne(n,r,i.agentId))return;n.lastError=B(e),n.chatError=n.lastError,n.requestUpdate?.()}}async switchToBranch(e){let t=this.state;t&&(await Hd(t,e),t.requestUpdate?.())}announceCommandPaletteTarget(e){this.dispatchEvent(new CustomEvent(un,{bubbles:!0,composed:!0,detail:{owner:this,onSlashCommand:e}}))}}})))()}var nw;function rw(){return(rw=e((()=>{wr(),Nr(),Gr(),yr(),$n(),fg(),y(),vg(),Zh(),mt(),vt(),si(),O(),Pt(),P(),I(),lt(),tS(),tw(),Q(),v_(),jo(),nw=class extends ew{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})&&L(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:e.key,boardFace:`dashboard`,boardPresentation:`split`}}).allowed)}isDashboardDefault(e,t){return xe(e)===`dashboard`&&t===(e.boardPresentation??`split`)}dashboardDefaultMenuAction(e,t){let n=t?Dv(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?Dv(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`));Ot({message:V(`chat.sidePanel.defaultSaved`),anchor:this})}catch(e){o()&&(this.publishHeaderError(e,n.headerOutcomeOwner),Ot({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),i=this.paneWidth>=680?M(r,this.paneWidth)??r:r;n.updateSidebarLayout(i,t)}initializeBrowserSidebarLayout(e){if(!e.columns[0]?.browserWidthPending||!Le(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 ke(e,this.querySelector(`.sidebar-region`)?.getBoundingClientRect().width??this.paneWidth,t.getBoundingClientRect().width+(Number.isFinite(n)?n:0))}commitSidebarPanelResize(e,t,r){let i=this.state;if(!i)return;let a=Pv(e,t,r),o=this.paneWidth>=680?M(a,this.paneWidth)??a:a,s=o.columns.find(e=>e.id===t),c=n(o)===`bottom`?s?.height:s?.width;if(c!==void 0&&i.sidebarLayout.columns.some(e=>e.id===t)){i.updateSidebarLayout(Pv(i.sidebarLayout,t,c),{geometryOnly:!0});return}this.commitSidebarLayout(o,{geometryOnly:!0})}resolveBoardConversation(){return j({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||Rn(t.hello?.auth??null),i=!t||Fn(t.hello?.auth??null),a=r&&(!t||ci(t,ti.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=Bh(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={...Hh(e,s,t.phase===`connected`,a,o,r,i),cacheKey:n}),this.boardProviderLease.provider}return this.releaseBoardProviderLease(),$h(e,n)}releaseBoardProviderLease(){this.boardProviderLease?.release(),this.boardProviderLease=void 0}readSavedDashboardLayout(){return this.state?Hn().sidebarSessionLayouts?.[He(this.state,this.state.sessionKey)]:void 0}captureNavigationFace(){let e=this.state;return e?Le(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:Bh(this.resolveBoardConversation()),expanded:this.dashboardExpanded,pendingRoute:e}}syncRetainedBoardSession(e){let t=this.resolveBoardSessionKey(e.snapshot.sessionKey),n=this.routeFace===`dashboard`||this.dashboardExpanded,r=Bh(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&&(Dv(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&&Le(this.state.sidebarLayout,`dashboard`)&&!customElements.get(`openclaw-board-view`)&&Qx().then(e=>{e&&this.requestUpdate()})}resolveBoardSessionKey(e=``){let t=Ce(e||this.state?.sessionKey||this.sessionKey,this.context?.gateway.snapshot.hello),n=i(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 ko(async()=>{let{isSwarmEnabledInConfig:e,SwarmRosterHydrator:t}=await import(`./control-ui-boot-chat-Ck7W_FPO.js`).then(e=>(e.r(),e.i));return{isSwarmEnabledInConfig:e,SwarmRosterHydrator:t}},__vite__mapDeps([0,1,3,2,4,5,6,7,8,9]),import.meta.url).then(({isSwarmEnabledInConfig:n,SwarmRosterHydrator:l})=>{if(!s()){c=!0;return}if(!(e.connected&&n(t.runtimeConfig?.state.configSnapshot?.config,i))){this.swarmHydrator&&(this.swarmHydrator.dispose(),this.swarmHydrator=null,HS(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,...tt(r)?{}:{agentId:i}},{client:a,refresh:e}).then(e=>e.session??null),currentRows:()=>s()?e.sessionsResult?.sessions??[]:[],onRows:()=>{s()&&HS(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=tn({boardSessionViews:et(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`)||!Le(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??=tt(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 W;if(!e.provider.hasLoadedSnapshot){let t=e.provider.loadError$.value;return t?U`<div
class="board-session-surface__state board-session-surface__state--error"
role="alert"
>
${V(`dashboardDocument.loadFailed`,{error:t})}
</div>`:sg(`board`,V(`common.loading`))}n.agentId??=tt(e.snapshot.sessionKey)?.agentId;let i=Le(t,`dashboard`)&&this.visuallyPresented,a=this.connectionGeneration,o=()=>$x({active:{owner:this,isPresented:()=>Le(t,`dashboard`)&&this.visuallyPresented,preview:()=>!this.presented&&this.connectionGeneration===a},session:n,snapshot:e.snapshot,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 U`${i?o():Er([r,n.agentId],o)}`}showDashboard(e){let t=this.state;if(!t)return;let n=Dg(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 iw,aw,ow;function sw(){return(sw=e((()=>{wr(),zn(),An(),y(),Zh(),vt(),Ep(),Me(),Rd(),P(),I(),lt(),Ip(),Xp(),Zp(),gd(),Bx(),Zx(),rw(),rd(),cm(),CS(),ru(),Cc(),BS(),$C(),Q(),py(),g_(),$_(),f_(),Xv(),Ju(),iw=600,aw=`agent-chat__input--prefill-attention`,ow=class extends nw{constructor(...e){super(...e),this.activeSessionResources=new Xx,this.archiveFocusOwned=!1,this.retainedQueuedEdit=!1,this.progressPresentationReady=!1,this.hiddenProgressCards=new Map,this.clearSavedProgressCard=e=>{this.progressCard.dismiss(e).catch(()=>Ot({message:V(`sessionProgressCard.clearFailed`)}))}}captureProgressCardRefreshAction(){let e=this.state,t=this.captureConnectionScope();if(!e||!t)return;let n=e.sessionKey,r=e.currentSessionId,i=X(e);return{state:this.progressCard.refreshState,onRefresh:e=>{let a=this.state;a&&this.isConnectionScopeCurrent(t)&&a.sessionKey===n&&a.currentSessionId===r&&X(a)===i&&this.progressCard.refresh(e)}}}captureArchivePresentationFocus(){this.archiveFocusOwned=!!(this.state&&this.isCurrentSessionArchived(this.state)&&this.currentSessionArchived===!1&&E_(this.presentationId,this))}retireArchivedPresentation(){let e=this.state?this.isCurrentSessionArchived(this.state):!1;e&&this.currentSessionArchived===!1&&(C_(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(Ix,{bubbles:!0})))}reviewQueuedMessageEdit(e){let t=hu(e);if(!t||this.state!==e||!this.isConnected)return;let n=e.client,r=_e({context:this.context,face:`chat`,sessionKey:t.sessionKey,agentId:t.agentId,exactKey:!0});xu(this,{agentId:t.agentId,face:`chat`,sessionKey:t.sessionKey,commit:()=>this.state!==e||e.client!==n||this.context.gateway.snapshot.client!==n||hu(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)||R(e.sessionKey))return this.retainedProgressCard=void 0,null;let t=pr(this.context.gateway);this.hiddenProgressCardScope!==t&&(this.hiddenProgressCardScope=t,this.hiddenProgressCards.clear());let n=Se(e),r=this.retainedProgressCard;r&&(!zu(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)&&!R(e.sessionKey)&&(this.transcriptReady||Pc(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)&&!R(e.sessionKey)&&ll(e).phase!==`failed`&&(t===`connecting`||t===`starting`||e.connected&&(!this.presented||document.visibilityState===`hidden`||!this.transcriptReady&&!Pc(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(aw),this.composerPrefillAttentionTarget=null}showComposerPrefillAttention(e){this.clearComposerPrefillAttention(),e.offsetWidth,e.classList.add(aw),this.composerPrefillAttentionTarget=e,this.composerPrefillAttentionTimer=window.setTimeout(()=>{this.composerPrefillAttentionTarget===e&&this.clearComposerPrefillAttention()},iw)}confirmConversationReset(){let e=this.resolveBoardView(),t=Bh(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 r,i=new Promise(e=>{r=e});return this.resetConfirmation={scopeKey:t,promise:i,resolve:r},this.resetConfirmationOpen=!0,i}cancelResetConfirmationForSessionChange(){let e=this.resetConfirmation;e&&e.scopeKey!==Bh(this.resolveBoardConversation())&&this.settleResetConfirmation(!1)}settleResetConfirmation(e){let t=this.resetConfirmation;t&&(this.resetConfirmation=void 0,this.resetConfirmationOpen=!1,t.resolve(e))}renderResetConfirmation(){if(!this.resetConfirmationOpen)return W;let e=V(`chat.board.resetTitle`),t=V(`chat.board.resetDescription`);return U`
<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&&(ml(this.state).catch(()=>void 0),el(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&&Yl(this.state),this.context&&ly(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),HC(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)&&ud(e,{deferBranches:!0})),e&&!t&&(!z(e.chatBranchesSessionKey,e.sessionKey)||e.chatBranchesConnectionEpoch!==e.connectionEpoch)&&pd(e),this.refreshSwarmRoster(),this.refreshSessionPullRequests();return}this.minutePoll.stop(),this.state&&(sd(this.state),mm(this.state)),this.swarmHydrator?.dispose(),this.swarmHydrator=null,this.clearHistoryObserver(),Uf(this.context.gateway).unwatch(this),this.syncActiveBindings(),this.clearComposerPrefillAttention(),this.settleResetConfirmation(!1),this.cancelHeaderRename(),Eg(this),p_(this.presentationId,this);let t=this.state;t&&(bS(t),LS(t),t.sidebarContent=null,Yv(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&&pm(e,n,{message:e.chatMessage,mentions:e.chatMentions,goalMode:e.chatGoalDraftMode,replyTarget:e.chatReplyTarget,attachments:e.chatAttachments,draftRetry:t})}}takeSessionHandoff(e){return Uc(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=c_(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=ll(n);(m.phase===`in-flight`?m.promise:m.phase===`idle`&&cd(n)?ud(n,{startup:!0,deferBranches:!0}):Promise.resolve()).then(()=>{if(p()&&!cd(n))return n.handleSendChat()}).catch(e=>{p()&&Y(n,B(e),!0)})})}}}})))()}var cw;function lw(){return(lw=e((()=>{y(),vt(),O(),de(),Pt(),I(),Zl(),Nm(),Zp(),Hf(),sw(),rd(),Q(),Iv(),cw=class extends ow{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=N(e,a).agentId??se(a),s={...o?{agentId:o}:{},key:a},c=L(t.gateway.snapshot,{method:`sessions.recover`,params:s});if(!c.allowed)return Y(e,c.reason,!0),!1;this.recoveringSession=!0,this.requestUpdate(),Y(e,null);try{let t=await n.recover(s);if(!i()||e.sessionKey!==a)return!1;if(!t)return Y(e,e.sessionsError??`New Chat could not create a new thread. Try again in a moment.`,!0),!1;if(t.continuation.status===`rejected`)return Y(e,B(t.continuation.error.message),!0),!1;let r=t.key;return this.onPaneSessionChange?.(this.paneId,r)!==!1&&(Ic(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=md(e),o=!a&&this.resolveBoardView().hasBoard,s={...a?{incognito:!0}:{currentSessionKey:i},agentId:N(e,i).agentId??se(i)},c={...Rt(a?void 0:i,s.agentId),...a?{incognito:!0}:{}},l=()=>L(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(!Ax(e))return Y(e,tu,!0),!1;if(e.sessionsLoading)return Y(e,Qc,!0),!1;let f=l();if(!f.allowed)return Y(e,f.reason,!0),!1;if(!a&&!await this.confirmConversationReset()||!d()||!z(e.sessionKey,i))return!1;if(!Ax(e))return Y(e,tu,!0),!1;let p=l();if(!p.allowed)return Y(e,p.reason,!0),!1;if(Y(e,null),o)return await kd(e)!==`failed`;this.creatingIncognitoSession=a,a&&this.requestUpdate();try{let t=await n.create(s);return d()?!t||e.sessionKey!==i||!Ax(e)?(t||Y(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&&(Ic(this.context,this.paneId,t,{attachments:Xf(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`||me(e.sessionKey)){let t=E(e.selectedSession),n=Ov(e.selectedSession,this.state?.sessionsResult?.sessions??[]);return{kind:`composer-replacement`,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&&md(this.state)){let e=L(this.context.gateway.snapshot,{method:`sessions.create`,params:{incognito:!0,agentId:N(this.state,this.state.sessionKey).agentId??se(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?tm(()=>this.context.navigate(`model-providers`,{search:`?connect=1`})):void 0}}restartRecoveryComposerBanner(){let e=this.state;if(!e)return;let t=N(e,e.sessionKey).agentId??se(e.sessionKey),n={...t?{agentId:t}:{},key:e.sessionKey},r=L(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 uw(e,t){return e.chatQueue.some(e=>e.sendRunId===t&&e.sendState===`sending`)}function dw(e){let t=q(e);return t?.role===`assistant`&&Array.isArray(t.content)?t:null}function fw(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 pw(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=fw(e);return r?`${t}\n\n${r}`:t}return(t?ua(t)?.trim():null)||`chat error`}function mw(e,t,n,r,i){e.chatMessagesBySession&&ap(e.chatMessagesBySession,e,{sessionKey:t,agentId:i},n,r)}function hw(e,t){if(!t)return null;let n=t.state===`aborted`&&t.stopReason===`auth-revoked`?{...t,errorMessage:V(`chat.providerAccessRemoved`)}:t,r=n.state===`error`&&n.errorKind===`state_contention`?`state_contention`:n.state===`error`&&n.stopReason===`aborted-partial-persistence-failed`?`stop`:n.errorDetail?.providerRuntimeFailureKind===`auth_refresh`?`auth_refresh`:void 0,i=n.state===`final`?Dp(n.message):null,a=e.chatRunId!==null,o=td(e,n.sessionKey,n.agentId),s=e.chatRunId!==null&&typeof n.runId==`string`&&n.runId===e.chatRunId,c=!!(n.runId&&Fs(e,n.runId)&&o);if(!o){if(n.state===`final`){let t=i;if(t&&!da(t)){let r=p(n.sessionKey)?n.agentId??F(e):n.agentId;mw(e,n.sessionKey,t,n,r)}}return null}let l=Ou(e),u=(t,r,i,a)=>{let o=n;Jm(e,r,{scope:l,event:{type:`messagePersisted`,message:t,envelope:{afterSequence:a,...i?{runId:i}:{},...o.messageId===void 0?{}:{messageId:o.messageId},...o.messageSeq===void 0?{}:{messageSeq:o.messageSeq}}}})},d=n.runId&&n.state!==`status`?Kr(jd(e,l),i?{...n,message:i}:n,l):null;d&&Kd(e,d.projection);let f=n.runId??e.chatRunId,m=()=>{let t=d?.currentRun?.status;if(!n.runId||n.runId!==e.chatRunId||!t||t===`streaming`)return;Dd(e);let r=[e.sessionKey,n.sessionKey];if(t===`yielded`){Om(e,{yielded:!0,runId:f,sessionKey:e.sessionKey,sessionKeys:r,clearLocalRun:!0,clearChatStream:!0});return}Om(e,{outcome:t===`completed`?`done`:`interrupted`,sessionStatus:t===`completed`?`done`:t===`aborted`?`killed`:t===`timeout`?`timeout`:`failed`,errorMessage:n.errorMessage?.trim()?pw(n,null):void 0,runId:f,sessionKey:e.sessionKey,sessionKeys:r,clearLocalRun:!0,clearChatStream:!0,armLocalTerminalReconcile:a&&s})},h=d?.previousRun;if(h&&h.status!==`streaming`&&d.currentRun?.status!==`streaming`){if(n.state===`delta`)return null;if(n.state===`error`||n.state===`aborted`){let t=e.chatQueue.find(e=>e.sendState===`sending`&&e.sendRunId)?.sendRunId;if((e.chatRunId??t??e.lastLocalTerminalReconcile?.runId)===n.runId&&n.errorMessage?.trim()&&d.currentRun?.errorMessage!==h.errorMessage&&Ld(e,pw(n,null),n.runId,r),n.state===`error`)return m(),`error`}let t=i;if(n.state===`aborted`||n.state===`final`&&(!t||da(t)||Xr(h,t)))return m(),n.state}if(!e.chatRunId&&(!h||h.status===`streaming`||d?.currentRun?.status===`streaming`)&&typeof n.runId==`string`&&(n.state!==`status`||uw(e,n.runId))&&(n.state===`status`?qd(e,n.runId,Date.now()):(e.chatRunId=n.runId,Sc(e,n.runId),e.chatRunError=null,e.chatStreamStartedAt??=Date.now())),e.chatRunId&&n.runId!==e.chatRunId){if(n.state===`final`){let t=i;return t&&!da(t)?(u(t,[...e.chatMessages,t],n.runId),null):`final`}return null}let g=Us(e),_=(t={})=>Fp(e.chatMessages,e,t),v=()=>{Jm(e,_(),{scope:l}),lm(e.chatMessages.findLast(e=>dd(e)===f),f,g,n.state===`aborted`?`aborted`:d?.currentRun?.status===`timeout`?`timeout`:`error`)};if(n.state===`status`){if(!n.runId||n.runId!==e.chatRunId)return null;let t=n.retry?typeof n.seq==`number`&&{phase:`retrying`,seq:n.seq,message:V(`chat.startupStatus.retrying`,{attempt:String(n.retry.attempt),maxAttempts:String(n.retry.maxAttempts)})}:n.phase&&{phase:n.phase,...n.seq===void 0?{}:{seq:n.seq}};return t&&Bm(e,{state:`status`,runId:n.runId,...t}),n.state}if(n.state===`delta`){n.runId&&n.runId===e.chatRunId&&Bm(e,{state:`activity`,runId:n.runId});let t=n.message==null?null:ua(n.message)??``;typeof t==`string`&&!oa(t)&&!Ca(n.message)&&(e.chatStream=t,zf(e))}else if(n.state===`final`){let t=i;if(!c){let n=t?kl(t,e):{kind:`none`};if(n.kind===`split`){Up(e,n.replacedSegmentIndexes);let t=_({includeCurrent:!1});if(n.tailMessage&&!da(n.tailMessage)){let e=lm(n.tailMessage,f,n.afterBoundaryRunId);t=Df(t,e,{preserveKeyedCommentary:n.preserveKeyedCommentary}),u(n.tailMessage,t,f,n.afterSequence)}else Jm(e,t,{scope:l})}else if(t&&!da(t)){let e=_(),n=lm(t,f,g);u(t,Df(e,n),f)}else Jm(e,_(),{scope:l})}m()}else if(n.state===`aborted`){let t=dw(n.message);if(t&&!da(t)){let e=_({replacementMessages:[t],includeCurrent:!1}),n=lm(t,f,g,`aborted`);u(t,Df(e,n),f)}else v();n.errorMessage?.trim()&&Ld(e,pw(n,null),n.runId,r),m()}else if(n.state===`error`){let t=Dp(n.message),i=t&&!da(t)?t:null,o=!!(i&&Qr(i,n.errorMessage));if(a){if(i&&!o){let t=Bd(i,e,{isHiddenStreamText:ya,persistCommentary:e.settings?.chatPersistCommentary!==!1}),n=_({includeCurrent:!t}),r=lm(i,f,g,d?.currentRun?.status===`timeout`?`timeout`:`error`);u(i,t?Df(n,r):[...n,r],f)}else v()}m(),Ld(e,pw(n,o?i:null),n.runId,r)}return n.state!==`delta`&&Dd(e),n.state}function gw(){return(gw=e((()=>{ei(),qr(),$r(),y(),zi(),pa(),Fa(),I(),Zp(),Nd(),nc(),Rc(),Im(),_f(),Pl(),ql(),jm(),xp(),uf()})))()}function _w(e,t){return td(e,t.key,t.agentId??void 0)}function vw(e,t){return t?Ao(t):F(e)}function yw(e,t){if(!p(t.key))return!0;let n=p(e.sessionKey)?o(e):ue(e,e.sessionKey);return!n||vw(e,t.agentId)===n}function bw(e,t,n,r,i){return(r?wd(e,r,{publishRunStatus:!0}):wf(e,{publishRunStatus:!0}))?(Yp(e,n??void 0),ud(e,{deferBranches:!i()}).finally(()=>{z(e.sessionKey,t)&&(Rl(e),e.requestUpdate?.())}).catch(()=>void 0),!0):!1}function xw(e,t,n,r){let i=re(t);if(!i||!yw(e,i))return!1;let a=_w(e,i),o=Ur(q(t)?.message)?.role===`user`;a&&(tl(e),ll(e).phase===`in-flight`&&ud(e,{deferBranches:!n(),supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),lu(e,t,i.hasActiveRun??void 0,{kind:`live`,activeRunId:e.chatRunId})),a&&i.archived!==null&&(e.selectedChatSessionArchived=i.archived);let s=e.chatRunId;if(Np({event:i,host:e,matchesChat:a,payload:t,runIdBeforeApply:s}),r.applied&&Ff(e),s&&a){let t=i.clientRunId??i.runId??s;return e.pendingSessionMessageReloadSessionKey=i.key,i.hasActiveRun===!0?(o&&ud(e,{deferBranches:!n(),supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),!0):bw(e,i.key,t,r.row,n)?(e.pendingSessionMessageReloadSessionKey=null,!0):(ml(e).then(()=>{e.pendingSessionMessageReloadSessionKey&&e.chatRunId===s&&bw(e,e.pendingSessionMessageReloadSessionKey,t,void 0,n)&&(e.pendingSessionMessageReloadSessionKey=null)}),!0)}return a&&(e.pendingSessionMessageReloadSessionKey=null,ud(e,{deferBranches:!n()}).finally(()=>e.requestUpdate?.())),a}function Sw(e,t,n,r=!1){let i=e.pendingSessionMessageReloadSessionKey,a=t?.sessionKey?.trim();return!i||!a||!z(i,a)||!z(a,e.sessionKey)||e.chatRunId?!1:(e.pendingSessionMessageReloadSessionKey=null,ud(e,{deferBranches:!n(),supersedeInFlight:r}).finally(()=>e.requestUpdate?.()),!0)}function Cw(e,t){let n=t.runId;return n?{sessionKey:t.sessionKey,agentId:X(e),runId:n,client:e.client,connectionEpoch:e.connectionEpoch,runLifecycleGeneration:e.chatRunLifecycleGeneration??0,initialTerminalReplySignatures:Hv(e,n).terminalReplySignatures}:null}function ww(e,t){let n=Iw.get(e);n||(n=new Map,Iw.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),eo(n,Fw),!0)}function Tw(e,t){let n=Hv(e,t.runId);return n.acceptedFinal||[...n.terminalReplySignatures].some(e=>!t.initialTerminalReplySignatures.has(e))}function Ew(e,t){return e.connected&&e.client===t.client&&e.connectionEpoch===t.connectionEpoch&&z(e.sessionKey,t.sessionKey)&&X(e)===t.agentId&&(e.chatRunId===null||e.chatRunId===t.runId)&&(e.chatRunLifecycleGeneration??0)===t.runLifecycleGeneration&&!Tw(e,t)}async function Dw(e,t,n){for(let r=0;;r+=1){if(!Ew(e,t)||(await ud(e,{deferBranches:!n(),supersedeInFlight:!0}),e.requestUpdate?.(),!Ew(e,t)))return;let i=Pw[r];if(i===void 0)return;await po(i)}}function Ow(e,t,n,r){let i=n(),a=e.chatRunId,o=re(t),s=!!(o&&yw(e,o)&&_w(e,o)),c=q(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&&Um(e,new Set([t.pendingRunId]))}let d=s&&typeof c?.reason==`string`&&Mw.has(c.reason);if((u||d)&&mm(e),s&&c?.reason===`project`&&kg(e),u){let t=Ou(e,{agentId:X(e)});ac(e,{type:`sessionReset`},{scope:t})}d&&(tl(e),e.chatBranches=[],e.chatBranchesSessionKey=null,e.chatBranchesConnectionEpoch=null,kg(e),i&&pd(e)),o&&s&&o.archived!==null&&(e.selectedChatSessionArchived=o.archived),r.applied&&Ff(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)&&rh(e,f,r.admittedRow),u||s&&c?.reason===`compact`?(ud(e,{deferBranches:!i}).finally(()=>e.requestUpdate?.()),!0):s&&c?.phase===`message`&&c.message===void 0&&c.messageId===void 0&&c.messageSeq===void 0?(tl(e),ud(e,{deferBranches:!i,supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),!0):(s&&typeof c?.reason==`string`&&Nw.has(c.reason)&&ud(e,{deferBranches:!i,supersedeInFlight:!0}).finally(()=>e.requestUpdate?.()),r.applied&&o&&a&&s&&bw(e,o.key,o.clientRunId??o.runId??a,r.row,n),s)}function kw(e,t){if(t?.state!==`final`||!td(e,t.sessionKey,t.agentId))return!1;let n=ua(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&&!ya(e);return(i(n)&&!da(t.message)||r.some(i))&&[n,...r].some(e=>Jf(e).length>0)}function Aw(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 jw(e,t,n=()=>!0,r={applied:!1}){if(t.event===`models.snapshot`){JC(e);return}if(t.event===`session.approval`){let n=q(t.payload);if(!n||typeof n.sessionKey!=`string`)return;let r=Mv(e.chatSessionApprovalQueue??[],n,e.sessionKey,X(e));r&&(e.chatSessionApprovalQueue=r,HS(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&&td(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?Ou(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&&Lp(e,r.runId,r.deltaText);let c=kw(e,r);hw(e,r),i&&a&&Yp(e,i.runId),c&&r&&Id(e,r.runId,r.message);let l=o&&s&&jd(e,s).runs[o]?.status===`completed`&&r?Cw(e,r):null,u=l?ww(e,l):!1;l&&u?(e.pendingSessionMessageReloadSessionKey=null,Dw(e,l,n).catch(()=>void 0)):Sw(e,r,n),i&&(el(e,t),a&&(n()?X_(e,Le(e.sidebarLayout,`workspace`)):kg(e))),a&&HS(e,r?.state===`delta`?`animation-frame`:`immediate`)};if(!i){a();return}let o=j(e,i.sessionKey,p(i.sessionKey)?vw(e,i.agentId??null):i.agentId),s=e.connectionEpoch,c=au(e,i.runId,o)?.item,l=um(e),u=bc(e,i.runId,o,{retainUntilConsumed:!!(c&&Nu(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||!td(e,n.sessionKey,n.agentId)||!Aw(e,n))return;let r=e.observerDigest;if(r?.runId===n.runId&&Li(r,n)===r)return;e.observerDigest=n,HS(e);return}if(t.event===`agent`||t.event===`session.tool`){dm(e,t.payload)&&HS(e,`animation-frame`);return}if(t.event===`session.operation`){pp(e,t.payload),HS(e,`animation-frame`);return}if(t.event===`chat.send_timing`){ul(e,t.payload);return}if(t.event===`session.message`||t.event===`sessions.changed`){let i=(t.event===`session.message`?xw:Ow)(e,t.payload,n,r);el(e,t),i&&HS(e,`animation-frame`)}}var Mw,Nw,Pw,Fw,Iw;function Lw(){return(Lw=e((()=>{Jr(),bo(),pa(),Fa(),l(),I(),gw(),Xp(),Zp(),gd(),cm(),od(),ru(),Tu(),Fc(),Cc(),$C(),Q(),yv(),Im(),Yd(),_f(),Gg(),Ns(),v_(),uf(),ev(),Cm(),Xd(),Mw=new Set([`rewind`,`branch-switch`,`fork`,`reset`,`new`]),Nw=new Set([`send`,`agent.run.started`,`agent.input.settled`]),Pw=[100,400,1500,3e3],Fw=64,Iw=new WeakMap})))()}function Rw(e,t,n=null){let r=X(e);if(!t){let t=e.sessionsResult;if(!t||e.sessionsResultAgentId!==r)return!1;let i=t.sessions.filter(t=>!td(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(!td(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&&td(e,n.key,n.agentId)):void 0,o=a&&a.key!==t.key?e.sessions.inheritRow({...t,key:a.key},t):t,s=i&&a?Mt(i,i.sessions.map(e=>e===a?o:e)):v(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&&(qu(e,t.key,t.agentId??r),(e.realtimeTalkSession||e.realtimeTalkActive||e.realtimeTalkUseSystemDefault)&&bS(e,{preserveConversation:!0})),s===e.sessionsResult&&e.sessionsResultAgentId===r?!1:(e.sessionsResult=s,e.sessionsResultAgentId=r,!0)}var zw;function Bw(){return(Bw=e((()=>{Me(),l(),I(),Zp(),lw(),Vc(),CS(),ru(),Lw(),Q(),Im(),_f(),zw=class extends cw{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=E(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=tt(n)?.agentId??X(e),s=!1,c={retryFailedRead:()=>{s&&d()},matchesPane:()=>this.state===e&&e.connected&&e.client===a&&this.resourceSessionObservation()===t&&E(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 t=this.state,n=this.context.sessions;if(!t?.connected||!t.sessionKey.trim()||R(t.sessionKey)){this.retireSessionObservation();return}let r=n.captureConnectionScope();if(!r){this.retireSessionObservation();return}let i=t.sessionKey,a=X(t),o=this.sessionObservation;if(o?.matchesPane()&&o.observation?.isCurrent()){this.synchronizeParentSessionObservation();return}let s=o?.matchesPane()?o.observation?.sessionId:null,c=t.chatRunId||t.chatStream!=null||jd(t).entries.some(e=>!e.pending)?o?.observation?.sessionId:null;this.retireSessionObservation();let l={matchesPane:()=>this.state===t&&t.sessionKey===i&&X(t)===a&&n===this.context.sessions&&n.isConnectionScopeCurrent(r),observation:null},u=()=>t.connected&&l.matchesPane(),d=()=>this.sessionObservation===l&&u();if(this.sessionObservation=l,l.observation=n.observeRow({key:i,agentId:a},(e,n)=>{if(d()&&(e!==null||l.observation?.hasObserved)){let n=t.pendingAbort;!e&&n&&S(t,n.sessionKey,i,a,n.agentId)&&(t.pendingAbort=null),Rw(t,e,l.observation?.sessionId)&&this.requestUpdate(),this.synchronizeParentSessionObservation(),t.pendingAbort&&Ym(t).finally(()=>t.requestUpdate?.())}!n?.eventPending&&d()&&l.observation&&!l.observation.isCurrent()&&this.synchronizeSessionObservation()},{onInvalidate:e=>{if(d()){if(e===`runner-availability`){this.activeSessionResources.invalidate(),this.requestUpdate();return}this.activeSessionResources.reconcileObservation({requestUpdate:()=>this.requestUpdate(),updated:()=>this.updateComplete})}},onEvent:(e,n)=>{if(!d())return;if(n.generationRejected){this.synchronizeSessionObservation(),u()&&el(t,e);return}let r=n,i=c,a=re(e.payload);if(l.observation&&!l.observation.isCurrent()){let n=l.observation.sessionId;i=n,this.synchronizeSessionObservation({eventSessionId:a?.sessionId});let o=this.sessionObservation;if(!u()||!o?.matchesPane()||!o.observation?.isCurrent())return;if(!a?.sessionId||a.sessionId===n||a.sessionId!==o.observation.sessionId||a.sessionId!==o.observation.row?.sessionId||!td(t,a.key,a.agentId??void 0)){el(t,e);return}r={applied:!1}}let o=this.sessionObservation?.observation,s=t.currentSessionId??i;if(a?.sessionId&&o?.isCurrent()&&a.sessionId===o.sessionId&&a.sessionId===o.row?.sessionId&&td(t,a.key,a.agentId??void 0)&&s&&s!==a.sessionId&&(t.currentSessionId||t.chatRunId||t.chatStream!=null||jd(t).entries.some(e=>!e.pending))){this.refreshHistory(),el(t,e);return}e.event===`session.message`&&this.clearTypingActorForSessionMessage(e.payload),jw(t,e,()=>this.presented,r)}}),!d())l.observation.dispose();else{this.projectObservedSessionRow();let n=l.observation,r=t.currentSessionId??c;s&&n?.isCurrent()&&n.sessionId&&n.sessionId!==e.eventSessionId&&n.sessionId!==s&&n.row?.sessionId===n.sessionId&&r&&r!==n.sessionId&&this.refreshHistory()}}projectObservedSessionRow(){let e=this.state,t=this.sessionObservation;e&&t&&t.matchesPane()&&t.observation?.hasObserved&&t.observation?.isCurrent()&&(Rw(e,t.observation.row,t.observation.sessionId),this.synchronizeParentSessionObservation())}setPaneSessionKey(e){let t=super.setPaneSessionKey(e);return this.synchronizeSessionObservation(),t}}})))()}var Vw,Hw;function Uw(){return(Uw=e((()=>{Sn(),In(),xn(),Ah(),I(),Q(),v_(),Vw=[[ur,`terminal`,`openclaw-terminal-panel`],[gn,`browser`,`openclaw-browser-panel`],[Zt,`link-reader`,`openclaw-link-reader-panel`],[Pn,`desktop`,`openclaw-desktop-panel`],[hr,`portal`,`openclaw-portals-page`]],Hw=class{constructor(e){this.options=e}subscribe(){let e=Vw.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(Vn,t),e.push(()=>window.removeEventListener(Vn,t));let n=()=>{let e=this.options.current();e&&e.state.updateSidebarLayout(z_(e.state.sidebarLayout,`terminal`))};return window.addEventListener(nr,n),()=>{e.forEach(e=>e()),window.removeEventListener(nr,n),this.options.pending.clear()}}handlePluginPanel(e){let t=this.options.current();if(!t||!(e instanceof CustomEvent))return!1;let n=e.detail,r=`${n.pluginId}/${n.panelId}`;if(!t.pluginPanels.includes(r)||!z(n.sessionKey,t.state.sessionKey)||n.agentId&&n.agentId!==X(t.state))return!1;let i=`plugin:${r}`;nn(i,e);let a=n.open?Q_(t.state.sidebarLayout,i):z_(t.state.sidebarLayout,i);return n.dock&&(a=lv(a,n.dock)),this.options.updateSidebarLayout(a),!0}handle(e,t,n){let r=this.options.current();if(!r)return!1;let i=Zn(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&&!bn(a.url,r.linkReaders)))return nn(e,n),!1;if(nn(e,n),e===`link-reader`&&n.preventDefault(),a?.open===!1)return this.options.pending.delete(e),this.options.updateSidebarLayout(z_(r.state.sidebarLayout,e)),!0;let o=Q_(r.state.sidebarLayout,e);(a?.dock===`right`||a?.dock===`bottom`)&&(o=lv(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=Gh(n,X(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 e&&xg.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||bn(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=Xn(`plugin:${t}`,e.state.sessionKey,X(e.state));)this.handlePluginPanel(n)}for(let[,t,n]of Vw){let r;for(;r=Xn(t,e.state.sessionKey);)this.handle(t,n,r)}}}}})))()}function Ww(e,t){return e?U`<a
class="rail-header__action"
href=${e}
target="_blank"
rel="noopener"
aria-label=${t}
title=${t}
>${H.externalLink}</a
>`:void 0}function Gw(e){let t=e?.state,n=e&&{...e,dashboardAvailable:()=>e.dashboard!==W},r=(e,r,i,a,o)=>({slot:e,label:V(`chat.sidePanel.${r}`),icon:i,available:!!(n&&(e===`portal`?t&&oi({hello:t.hello,client:t.client,phase:t.connected?`connected`:`stopped`},`portal.list`,`operator.read`):Dx[e]?.available(n))),content:a,loading:sg(r===`conversation`||r===`companion`?`chat`:r===`portal`?`browser`:r===`dashboard`?`board`:r,V(r===`desktop`?`desktop.connecting`:`common.loading`)),empty:{description:V(`chat.sidePanel.${r}Empty`)},headerAction:o,shortcut:Dx[e]?.combo}),i=t?.terminalAvailable?U`<openclaw-terminal-panel
embedded
.tabsInHeader=${e?.terminalTabsInHeader??!1}
.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,a=t?.browserPanelAvailable?U`<openclaw-browser-panel
embedded
data-chat-autotype-exempt
.client=${t.connected?t.client:null}
.available=${t.browserPanelAvailable}
.remoteAvailable=${ir({phase:t.connected?`connected`:`offline`,hello:t.hello})}
.presented=${We(e?.browserPresented??!1)}
.tabsInHeader=${e?.browserTabsInHeader??!1}
.refreshOnPresentation=${e?.browserRefreshOnPresentation??!0}
.sessionKey=${t.sessionKey}
.preferredTab=${e?.preferredBrowserTab}
.sessionTabs=${e?.sessionBrowserTabs??[]}
.resourceBasePath=${t.resourceBasePath}
.authToken=${Qt(t)}
></openclaw-browser-panel>`:null,o=e?U`<openclaw-chat-session-rail
.presented=${We(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=${Hs(t?.hello?.policy)}
></openclaw-chat-session-rail>`:null,s=t&&e?.desktopAvailable?U`<openclaw-desktop-panel
embedded
data-chat-autotype-exempt
.client=${t.connected?t.client:null}
.available=${e.desktopAvailable}
.presented=${We(e?.desktopPresented??!1)}
.refreshOnPresentation=${e?.desktopRefreshOnPresentation??!0}
.requestedSource=${e?.desktopSource??null}
.sessionKey=${t.sessionKey}
.onFocusTargetChange=${e?.onDesktopFocusTargetChange}
></openclaw-desktop-panel>`:null,c=e?.discussion?U`<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,l=t?U`<openclaw-portals-page
embedded
.presented=${We(e?.portalPresented??!1)}
.requestedPortalId=${t.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.slot===`portal`)?.portalId??null}
.requestedEnvironmentId=${t.sidebarLayout.columns.flatMap(e=>e.panels).find(e=>e.slot===`portal`)?.environmentId??null}
></openclaw-portals-page>`:null,u=t?Ig(t):null,d=t?.sidebarContent??(t?nv(t):null),f=t?.sidebarLayout.columns.some(e=>e.panels.some(e=>e.slot===`detail`))??!1,p=t&&e&&u?U`<openclaw-chat-files-panel
.tabsInHeader=${Ye(t.sidebarLayout)?.slot!==`workspace`}
.previews=${Dt(e.panePresentation??!0,u.previews,[])}
.activeId=${Dt(e.panePresentation??!0,u.activePreviewId,null)}
.browser=${e.workspace}
.renderDetail=${e.renderDetail}
.onSelect=${e=>pv(t,e)}
.onClose=${e=>zg(t,e)}
></openclaw-chat-files-panel>`:e?.workspace??null,m=new Map((e?.pluginPanels??[]).map(e=>[`plugin:${e.key}`,e]));for(let e of t?.sidebarLayout.columns??[])for(let{slot:t}of e.panels)t.startsWith(`plugin:`)&&!m.has(t)&&m.set(t,void 0);return[r(`conversation`,`conversation`,H.messageSquare,W),r(`detail`,`review`,H.diff,d?.kind===`loading`?sg(`review`,V(`common.loading`)):d?.kind===`unavailable`?U`<div class="callout danger review-unavailable" role="alert">
<strong>${V(`chat.detailPanel.unavailable`)}</strong>
<span>${d.message}</span>
</div>`:d&&e&&f?U`${ot(t?.sidebarContent?e.panePresentation??!0:!0,e.renderDetail(d))}`:null),r(`terminal`,`terminal`,H.terminal,i),r(`browser`,`browser`,H.globe,a),{slot:`link-reader`,label:V(`linkReader.title`),icon:H.link,available:!!e?.linkReaders?.length,content:t?U`<openclaw-link-reader-panel
embedded
data-chat-autotype-exempt
.client=${t.connected?t.client:null}
.available=${t.connected}
.readers=${e?.linkReaders??Dn}
.agentId=${e?.agentId??void 0}
.sessionKey=${t.sessionKey}
.presented=${We(e?.linkReaderPresented??!1)}
.tabsInHeader=${e?.linkReaderTabsInHeader??!0}
.onClose=${e?.onCloseLinkReader}
></openclaw-link-reader-panel>`:null,loading:sg(`files`,V(`linkReader.loadingPreview`)),empty:{description:V(`linkReader.urlPlaceholder`)}},r(`portal`,`portal`,H.globe,l),r(`workspace`,`files`,H.fileText,p),r(`companion`,`companion`,H.messageSquarePlus,o,e?U`<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),r(`desktop`,`desktop`,H.monitor,s,Ww(e?.desktopFocusHref,V(`desktop.openWindow`))),r(`discussion`,`discussion`,H.messageSquare,c,Ww(e?.discussionOpenUrl,V(`chat.sessionDiscussion.openExternal`))),r(`dashboard`,`dashboard`,H.layoutDashboard,e?.dashboard??null),...[...m].map(([n,r])=>({slot:n,label:r?.value.label??n.slice(7),icon:H.plug,available:r!==void 0,content:r?bt(`panels`,r.key,{sessionKey:t?.sessionKey??``,agentId:e?.agentId??void 0},W,e?.isPluginPanelPresented(n)):null,loading:sg(`files`,V(`common.loading`)),empty:{description:r?.value.label??V(`pluginTabs.unavailableSubtitle`)}}))]}function Kw(e){return e.filter(e=>e.available).map(e=>e.slot)}function qw(e,t=`content`){let n={};for(let r of e){let e=r[t];e!=null&&(n[r.slot]=e)}return n}function Jw(){return(Jw=e((()=>{wr(),Mn(),Yn(),lr(),Sn(),fg(),y(),og(),si(),St(),ft(),Ox(),sp(),f_(),yv(),v_(),tg()})))()}function Yw(e,t){let n=tT[e];if(!n)return;let[r,i]=n;if(customElements.get(r)){nT.delete(e);return}let a=nT.get(e)??{listeners:new Set};return nT.set(e,a),a.error===void 0?(a.listeners.add(t),a.pending||=ln(r,i).catch(e=>{a.error=fr({error:e,stale:On(e),onRetry:()=>void pn()})}).finally(()=>{delete a.pending,a.listeners.forEach(e=>e()),a.listeners.clear()}),null):a.error}function Xw(e){let{layout:t,state:n}=e;return{activatePanel:r=>{let i=t.columns[0]?.panels.find(e=>e.id===r)?.slot;i===`dashboard`&&!Le(t,`dashboard`)?e.openPanelSlot(i):n.updateSidebarLayout(I_(t,r)),n.updateSidebarActivePanel(r)},togglePanelExpanded:e=>{n.updateSidebarLayout(Rv(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(wv(t,e,r,i)),resizePanel:e.resizePanel,setOpen:e.setPanelOpen}}function Zw(e){let t=`chat-panel-${encodeURIComponent(e.presentationId)}`,r=e.panelDefinitions??Gw(),i=e.layout.open===!0,a=e.layout.columns.length>0?Yw(`region`,e.requestUpdate):void 0,o=null;for(let t of e.layout.columns[0]?.panels??[]){let n=Yw(t.slot,e.requestUpdate);n!==void 0&&(o??={...e.panelTemplates},o[t.slot]=n??r.find(e=>e.slot===t.slot)?.loading)}let s=e.availableWidth>0?e.availableWidth:1/0,c=e.narrow||s<680,l=Ye(e.layout),u=!l||l.slot===`conversation`,d=e.layout.columns[0],f=e.layout.columns[0]?.activePanelId,p=e.layout.columns[0]?.panels.find(e=>e.id===f)?.slot,m=r.find(e=>e.slot===p)?.loading;return U`<div
class="sidebar-region ${c?`sidebar-region--narrow`:``} ${e.layout.expanded?`sidebar-region--expanded`:``} ${e.layout.expanded&&e.layout.expandedSide?`sidebar-region--expanded-side`:``} sidebar-region--${n(e.layout)} ${i?`sidebar-region--open`:``}"
style=${Ar({"--side-panel-width":`${d?.width??480}px`,"--side-panel-height":`${d?.height??360}px`})}
>
<div class="sidebar-region__header">${e.header??W}</div>
${a===void 0?U`<openclaw-chat-sidebar-region
.panelIdPrefix=${t}
.conversationTab=${e.conversationTab}
.layout=${e.layout}
.fetchFavicon=${e.fetchFavicon}
.panelDefinitions=${r}
.panelTemplates=${o??e.panelTemplates}
.panelActions=${e.panelActions}
.availableSlots=${e.availableSlots}
.callbacks=${e.callbacks}
.narrow=${e.narrow}
.availableWidth=${e.availableWidth}
></openclaw-chat-sidebar-region>`:a===null?m??null:null}
<div
id=${`${t}-conversation`}
class="sidebar-region__primary"
role="region"
aria-label=${V(`chat.sidePanel.conversation`)}
data-region=${u?`main`:`side`}
?hidden=${!Le(e.layout,`conversation`)}
>
${e.primary}
</div>
<div class="sidebar-region__right-runtime">${a??null}</div>
</div>`}function Qw(e){let t=e.layout;return e.board.available?e.board.face===`dashboard`&&t.columns.length===0&&(t=Q_(t,`dashboard`)):t=z_(t,`dashboard`),M(t,e.paneWidth)??t}function $w(e,t){return t||!e.client||!e.connected?null:async t=>{if(!e.client||!e.connected)return null;let n=e.client,r=await n.request(`chat.message.get`,{sessionKey:t.sessionKey,...t.agentId?{agentId:t.agentId}:{},messageId:t.messageId,maxChars:t.maxChars??eT});return e.connected&&e.client===n?r:null}}var eT,tT,nT;function rT(){return(rT=e((()=>{wr(),jr(),mn(),Cn(),rr(),y(),Jw(),v_(),jo(),eT=5e5,tT={region:[`openclaw-chat-sidebar-region`,()=>ko(()=>import(`./chat-sidebar-region.runtime-Cm79n6xu.js`),__vite__mapDeps([21,0,1,2,3,4,5,11,12,22,23,6,7,9,8,17,18,19,24,25]),import.meta.url)],"detail-panel":[`openclaw-chat-detail-panel`,()=>ko(()=>import(`./chat-detail-panel-DL_gv0lj.js`),__vite__mapDeps([26,0,1,2,3,4,5,11,12,6,7,8,9,17,18,19,24]),import.meta.url)],terminal:[`openclaw-terminal-panel`,()=>ko(()=>import(`./terminal-panel-registration-DwNbVu-U.js`).then(e=>(e.t(),e.n)),__vite__mapDeps([27,0,1,2,3,4,5,11,12,28,29,22,30,23,31,32,6,7,8,9,17,18,19]),import.meta.url)],"link-reader":[`openclaw-link-reader-panel`,()=>ko(()=>import(`./link-reader-panel-DRh0JX44.js`),__vite__mapDeps([33,0,1,3,2,4,5,29,22,34,6,7,8,9]),import.meta.url)],browser:[`openclaw-browser-panel`,()=>ko(()=>import(`./browser-panel-CpBLyCyg.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([35,0,1,2,3,4,5,11,12,28,29,22,36,30,23,6,7,8,9,17,18,19]),import.meta.url)],desktop:[`openclaw-desktop-panel`,()=>ko(()=>import(`./desktop-panel-DON9OquX.js`).then(e=>(e.n(),e.t)),__vite__mapDeps([37,0,1,2,3,4,5,11,12,28,29,36,38,39,6,7,9,8,17,18,19]),import.meta.url)],portal:[`openclaw-portals-page`,()=>ko(()=>import(`./portals-page-Ce3PZSf5.js`),__vite__mapDeps([40,0,1,2,3,4,5,6,7,9,8,41]),import.meta.url)],companion:[`openclaw-chat-session-rail`,()=>ko(()=>import(`./chat-session-rail-CCqxxauE.js`),__vite__mapDeps([42,0,1,2,3,4,5,11,12,23,6,7,8,9,17,18,19,24,43]),import.meta.url)],discussion:[`openclaw-session-discussion`,()=>ko(()=>import(`./session-discussion-panel-BuqxXJ-E.js`),__vite__mapDeps([44,0,1,3,2,4,5,11,12,23,6,7,8,9,17,18,19]),import.meta.url)]},nT=new Map})))()}function iT(e,t){return e.placementStartup.subscribe(()=>{let e=t();e&&(wp(e,cf(e)?.page.items),R(e.sessionKey)||el(e),e.requestUpdate?.())})}function aT(e){return m(({sessionKey:t,scopePrefix:n,reason:r})=>{let i=e();r===`cache-eviction`||!i||n&&!st(i,{sessionKey:i.sessionKey}).startsWith(n)||t&&st(i,{sessionKey:i.sessionKey})!==t||(bd(i),i.requestUpdate?.())})}function oT(){return(oT=e((()=>{Me(),Zp(),Cf(),ru(),Im(),Pl(),he()})))()}function sT(e,t){Zg(e),Lg(e,t)}function cT(){return(cT=e((()=>{jv(),Xv()})))()}var lT;function uT(){return(uT=e((()=>{Rr(),rn(),an(),Yn(),Es(),Cg(),Ue(),Me(),Pt(),I(),kc(),ie(),Zp(),dx(),bx(),Cx(),Tx(),Ox(),Fx(),Bw(),Uw(),rd(),rT(),oT(),Cf(),Cc(),Lw(),BS(),$C(),cT(),py(),sp(),$_(),yv(),bp(),Tp(),Im(),Gl(),Pl(),v_(),lT=class extends zw{constructor(...e){super(...e),this.sessionPanelToggles=new Hw({current:()=>{let e=this.state;return e&&this.active&&this.presented?{renderRoot:this.renderRoot,state:e,linkReaders:cn(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 wx({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=>Wv(e,{path:t})}:null}}),this.chatRouteReadyReported=!1,this.stagedAttachmentGatewayOwner=null,this.suppressStagedAttachmentHandoffOnDisconnect=!1,this.handlePaneInput=()=>{this.sessionCompanionFocusGeneration+=1},this.handlePaneFocus=()=>{this.sessionCompanionFocusGeneration+=1,sn(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(Dx).find(t=>t&&Ft(t.combo,e)),r=this.sessionDiscussionStates.get(t.sessionKey.trim());if(n?.available({state:t,desktopAvailable:Bn(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=Le(t.sidebarLayout,r);i&&Nx(t,r),this.commitSidebarLayout(i?z_(t.sidebarLayout,r):Mx(t,t.sidebarLayout,r));return}Vu(this,e),!(e.defaultPrevented||e.isComposing||e.keyCode===229||e.key!==`Escape`)&&Yu(this)&&e.preventDefault()},this.handleDocumentPointerdown=e=>{this.state&&Yu(this,e.composedPath())&&this.state.requestUpdate()}}activateComposerPresentation(){this.selected&&this.presented&&this.composerPresentation?.claim()}discardStagedAttachments(){this.suppressStagedAttachmentHandoffOnDisconnect=!0,this.chatState.attachmentReads.abortReads(),hx(this.state)}resumeStagedAttachments(){this.suppressStagedAttachmentHandoffOnDisconnect=!1}replaceStagedAttachmentGatewayOwner(e){this.stagedAttachmentGatewayOwner=gx(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){Sx(this.state,this.active&&this.presented,e,this.chatState.attachmentReads.pendingBytes(Hs(this.state?.hello?.policy)))&&(this.stagedAttachmentGatewayOwner??=this.context.gateway.snapshot.client,xx(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(()=>ly(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=zS(this.context,t.createRenderLifecycle(),this,this.chatMessagesBySession);n.chatMetadataIsPresented=()=>this.presented&&document.visibilityState!==`hidden`;let r=()=>{this.requestUpdate(),n.chatMetadataIsPresented?.()&&(HC(n,{automatic:!0}),this.resumeDeferredSessionHydration(),this.refreshTaskSuggestions({automatic:!0}))};document.addEventListener(`visibilitychange`,r),t.addCleanup(()=>document.removeEventListener(`visibilitychange`,r));let i=tt(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=()=>hm(n.chatMessages,n.assistantName),n.refreshCurrentSessionTools=async()=>{n.requestUpdate?.()},n.refreshCurrentChat=async()=>{await ZC(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&&!R(e)){n.client=this.context.gateway.snapshot.client??null;let t=Dc(n.chatMessagesBySession,n,{sessionKey:e});t?Bs(n,t):this.hydrateStoredChatSnapshot(n,e),dc(n,e)&&(n.lastError=yf,n.chatError=yf),wp(n,cf(n)?.page.items)}}t.attach(n),t.addCleanup(()=>this.retireSessionObservation()),t.addCleanup(op(()=>{dc(n,n.sessionKey)&&(n.lastError=yf,n.chatError=yf),n.requestUpdate?.()})),t.addCleanup(this.context.agentIdentity.subscribe(()=>void n.loadAssistantIdentity())),t.composerPersistence.restore({preserveCurrent:!0});let a=this.takeSessionHandoff(n.sessionKey);px(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(ng,o),t.addCleanup(()=>window.removeEventListener(ng,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;zC(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&&sx(this.state),this.activateComposerPresentation()})),this.subscribeSessionRepositoryContext(),t.addCleanup(this.context.gateway.subscribeEvents(e=>{let t=this.state;if(t&&e.event===`sessions.changed`&&No(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=Qn(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?.(),$c(t),bl(t).finally(()=>t.requestUpdate?.())),ys(this.questionPromptState,e)),t&&!R(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`&&zr(e.payload)&&this.handleSessionReactionEvent(e.payload),e.event===`session.typing`&&e.payload&&this.handleSessionTypingEvent(e.payload),jw(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(iT(this.context,()=>this.state)),t.addCleanup(aT(()=>this.state)),this.applyGatewaySnapshot(this.context.gateway.snapshot),this.synchronizeForegroundTranscript();let s=new yx(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=R(this.sessionKey),t=e?this.sessionKey:Ce(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=tt(t)?.agentId;e&&BC(this.state,e),this.synchronizeSessionObservation();let n=dc(this.state,t),r=wp(this.state,cf(this.state)?.page.items);n&&(this.state.lastError=yf,this.state.chatError=yf),(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()}updated(e=new Map){if(this.mcpApps.syncLaunch(),_u(this.state),!this.chatRouteReadyReported&&this.querySelector(`.agent-chat__composer-combobox > textarea`)&&(this.chatRouteReadyReported=!0,this.dispatchEvent(new Event(pe,{bubbles:!0,composed:!0}))),e.has(`focusComposer`)&&this.focusComposer){let e=this.querySelector(ep),t=e?.closest(`.agent-chat__input`);e?.focus({preventScroll:!0}),t&&this.draft&&this.showComposerPrefillAttention(t)}this.retireArchivedPresentation(),this.cancelResetConfirmationForSessionChange(),this.syncHistoryObserver();let t=this.resolveBoardView();if(this.syncRetainedBoardSession(t),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&&Le(Qw({board:t,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&&(Yl(this.state),su(this.state),$c(this.state),IC(this.state),this.suppressStagedAttachmentHandoffOnDisconnect?hx(this.state):mx(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),Eg(this),sT(this.presentationId),this.state=void 0,this.connectedClient=null,ss(this.questionPromptState),super.disconnectedCallback()}}})))()}function dT(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,X(e),e.connectionEpoch,e.sessionsResultAgentId,e.sessionsLoading,e.sessionsError,n,Ov(n,a),i?.defaults,i?.owners,t.modelOverrides[e.sessionKey],Object.hasOwn(t.modelOverrides,e.sessionKey),e.sessions.think(e.sessionKey,N(e,e.sessionKey).agentId),e.sessions.archiveVisibility(n?.key??e.sessionKey),Ls(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 fT(){return(fT=e((()=>{Ml(),s(),I(),Q(),Iv()})))()}var pT;function mT(){return(mT=e((()=>{Mn(),yr(),Yn(),Es(),$n(),si(),ct(),Me(),Pt(),I(),r(),kc(),Zp(),dx(),gd(),uT(),qx(),fT(),_S(),FC(),CS(),ru(),Cc(),$C(),Q(),Fm(),yv(),_f(),Bf(),Pl(),Wg(),v_(),jm(),Cm(),jo(),pT=class extends lT{constructor(){super(),this.outboxRecoveryReady=!1,this.questionProjection={prompts:[],revisions:[]},new rt(this).effect(()=>this.context?.gateway,e=>e.subscribeEvents(e=>{let t=this.state;t&&Je(e)&&(t.modelAuthStatusResult=null,t.modelAuthStatusError=null,this.requestUpdate(),WC(t).finally(()=>this.requestUpdate()))}))}placementComposerPresentation(e,t){return Hx({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.reclaimHeaderPlacement(e)})}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=t===`move`?`headerPlacementMovingKey`:`headerPlacementRestartingKey`,i={client:n.client,gatewaySnapshot:n.context.gateway.snapshot,mode:t,pendingKey:this[r],row:e,isCurrent:()=>this.ownsHeaderOutcomeScope(n),currentRow:()=>this.state?Z(this.state):void 0,onPendingChange:n=>{t===`recover`&&n!==null&&this.state&&(fS(this.state),this.state.chatRunError=null),(n!==null||this[r]===e.key)&&(this[r]=n)},publishError:e=>this.publishHeaderError(e,n.headerOutcomeOwner),reconcileMutation:e=>n.sessions.reconcileMutation(e),requestUpdate:()=>this.requestUpdate()},{changeChatPanePlacement:a}=await ko(async()=>{let{changeChatPanePlacement:e}=await import(`./chat-pane-placement.runtime-6ICY8ken.js`);return{changeChatPanePlacement:e}},__vite__mapDeps([45,0,1,2,3,4,5,46,11,47,48,6,7,8,9,17,49,50]),import.meta.url);await a(i)}async reclaimHeaderPlacement(e){let t=this.captureConnectionScope();if(!t)return;let n={client:t.client,gatewaySnapshot:t.context.gateway.snapshot,reclaimingKey:this.headerPlacementReclaimingKey,placementStartup:t.context.placementStartup,row:e,isCurrent:()=>this.ownsHeaderOutcomeScope(t),onReclaimingChange:t=>{(t!==null||this.headerPlacementReclaimingKey===e.key)&&(this.headerPlacementReclaimingKey=t)},publishError:e=>this.publishHeaderError(e,t.headerOutcomeOwner),reconcileMutation:e=>t.sessions.reconcileMutation(e),requestUpdate:()=>this.requestUpdate()},{reclaimChatPanePlacement:r}=await ko(async()=>{let{reclaimChatPanePlacement:e}=await import(`./chat-pane-placement.runtime-6ICY8ken.js`);return{reclaimChatPanePlacement:e}},__vite__mapDeps([45,0,1,2,3,4,5,46,11,47,48,6,7,8,9,17,49,50]),import.meta.url);await r(n)}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,X(t));for(let{key:n,agentId:r}of e.deletedSessions)El(t.chatMessagesBySession,t,{sessionKey:n,agentId:r});(!ae(t,t.sessionKey)||e.agentId===X(t))&&(t.sessionsResult=e.result,t.sessionsResultAgentId=e.agentId),this.projectObservedSessionRow(),t.sessionsLoading=e.loading,t.sessionsError=e.error,t.connected&&t.pendingAbort&&Ym(t).finally(()=>t.requestUpdate?.()),this.refreshSwarmRoster();let o=Z(t),s=o?JSON.stringify([t.sessionKey,X(t),o.sessionId,o.status,wo(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??X(t)??`main`,o),a){let e=X(t);this.onSessionDeleted?.(this.paneId,t.sessionKey,vo({agentId:e,mainKey:b({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello})}),a===`pending`);return}let c=Ff(t);if(this.reconcileWaitingApprovalSnapshot(),c){el(t);return}let l=dT(t,e,o,this.context.overlays?.snapshot?.approvalQueue),u=l!==this.sessionPresentationKey;this.sessionPresentationKey=l,this.presented&&u&&HS(t,`animation-frame`),i&&r?.outboxState!==s&&o&&!wo(o)&&t.chatQueue.length>0&&Rl(t)}reconcileWaitingApprovalSnapshot(e){let t=this.state,n=e??this.context?.overlays?.snapshot.approvalQueue;return!t||!n?!1:nf(t,n)}projectConversationAttention(e,t,n){let r=n=>S(e,e.sessionKey,n.sessionKey,n.agentId,t),i=n?this.questionPrompts.filter(r):[];return(i.length!==this.questionProjection.prompts.length||i.some((e,t)=>e!==this.questionProjection.prompts[t]||e.revision!==this.questionProjection.revisions[t]))&&(this.questionProjection={prompts:i,revisions:i.map(e=>e.revision)}),{gatewayQuestionPrompts:this.questionProjection.prompts,inlineApproval:n?e.chatSessionApprovalQueue?.[0]??this.context.overlays?.snapshot?.approvalQueue?.find(e=>r(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&&Wn(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 n=this.state;if(!n)return;let r=Qt(n),i=n.connected,a=n.assistantAgentId,o=tt(n.sessionKey)?.agentId??this.agentId??this.context.agentSelection.state.selectedId??e.assistantAgentId,s=He(n,n.sessionKey),c=(this.gatewayConnectionLifecycle??=t({client:n.client,phase:n.connected?`connected`:`stopped`})).transition(e),l=this.connectedClient!==e.client,u=this.sidebarLayoutSource?e.client!==null&&this.sidebarLayoutSource.client!==e.client:n.client!==e.client,d=!this.sidebarLayoutSource||u||e.phase===`connected`&&!this.sidebarLayoutSource.ready;if(l&&this.replaceStagedAttachmentGatewayOwner(e.client),e.phase!==`connected`)this.presencePayload=void 0;else if(l||!i){let t=Qn(e.hello?.snapshot);this.presencePayload=t?{presence:t}:void 0}c&&(this.continueInTerminalDialog=null,this.cancelHeaderRename(),wm(n),Gd(n.requestUpdate),i&&(e.phase===`connected`&&kC(n),n.chatSending=!1,n.chatSendingScopeKey=null),this.connectionGeneration+=1,this.retireReplyMessages(),this.retireHeaderSessionMutations(),$c(n),n.assistantIdentityRequestVersion+=1,IC(n),this.taskSuggestionsRequestVersion+=1,this.resetSessionSuggestions(),this.resetSessionReactions(),this.clearTypingActors(),this.sessionDiscussionStates.clear(),this.sessionDiscussionOpenUrls.clear(),this.sessionDiscussionPanels.clear(),this.sessionParticipationTracker.reset(),n.client!==e.client&&(this.sessionCompanionThreads.retire(),Om(n,{clearLocalRun:!0,clearChatStream:!0,clearToolStream:!0,clearRunStatus:!0,requestUpdate:!1}),n.pendingAbort=null),this.sessionSharingStates=new Map,this.sessionSharingHydrationTargets.clear(),n.guardianNotices=[],n.providerPolicyNotice=null,this.resetSessionPullRequests(),this.resetOlderMessagesViewport(),n.chatLoading=!1),(c||a!==o&&ae(n,n.sessionKey))&&(du(n),this.swarmHydrator?.dispose(),this.swarmHydrator=null),n.client=e.client,n.connected=e.phase===`connected`,jp(n);let f=n.connected&&!!n.client?.recoveryScopeReady,p=f&&(l||!this.outboxRecoveryReady);this.outboxRecoveryReady=f,n.connectionEpoch=this.connectionGeneration,n.hello=e.hello,n.selfUser=e.selfUser??null,n.assistantAgentId=o;let m=this.sessionKey.trim(),h=R(m);n.connected&&!h&&(c||this.connectedClient!==e.client)&&sx(n,{force:!0}),this.reconcileTaskSuggestionConnection(c),this.synchronizeSessionObservation(),i&&!n.connected&&(n.chatLoading=ll(n).phase===`pending-connection`);let g=!i&&n.connected?Sd(n):void 0;c&&kg(n),!c&&r!==Qt(n)&&Gd(n.requestUpdate),n.canvasPluginSurfaceUrl=e.canvasPluginSurfaceUrl,n.terminalAvailable=this.context.config.current.terminalEnabled&&e.phase===`connected`&&Wn(e.hello?.auth??null)&&K(e,`terminal.open`)===!0,n.browserPanelAvailable=mr(e);let _=Bn(e),v=He(n,n.sessionKey),y=v!==s;if(v&&(d||y)){this.sidebarLayoutSource={client:e.client,ready:n.connected},this.dashboardPresentationActivation=void 0;let t=e_({settings:Hn(),sessionKey:v,browserAvailable:n.browserPanelAvailable,desktopAvailable:_}),r=t.sidebarSessionLayouts?.[v];r===void 0?u?n.sidebarLayout={columns:[]}:y&&n.sidebarLayout.columns.length>0&&n.updateSidebarLayout(n.sidebarLayout):n.sidebarLayout=this.restorePaneSidebarLayout(C(r)),n.sidebarFocusPanelId=t.sidebarSessionActivePanels?.[v]??``,n.sidebarFocusVersion+=1}n.connected&&n.pendingAbort&&Ym(n).finally(()=>n.requestUpdate?.());let b=m&&!h?Ce(m,e.hello):null;if(!(m&&b&&b!==m&&this.presented&&(this.onPaneSessionChange?.(this.paneId,b,{replace:!0}),n.requestUpdate?.(),n.sessionKey!==b))){if(c&&(n.assistantName=this.context.config.current.assistantIdentity.name),e.phase!==`connected`){if(i){let e=typeof n.currentSessionId==`string`?n.currentSessionId.trim():``;e&&(n.reconnectResumeSessionId=e),kC(n)}this.connectedClient=null,ws(this.questionPromptState,null),bS(n),Qm(n,{preserveStreamSegments:n.chatRunId!==null}),n.requestUpdate?.();return}if(this.refreshSwarmRoster(),(this.connectedClient!==e.client||c&&h)&&e.client){let t=e.client,r=this.connectionGeneration,i=n.sessionKey,a=()=>this.connectionGeneration===r&&this.connectedClient===t&&n.client===t&&n.connected,o=async()=>{if(!a())return;let e=await this.context.agents.ensureList();a()&&(e&&il(n,e,t),n.requestUpdate?.())};if(this.connectedClient=t,ws(this.questionPromptState,t),us(this.questionPromptState,t,a),this.headerWorktreePaths.clear(),this.headerBranches.clear(),this.headerPlatform=null,h){this.loadHeaderPlatform(t,r),this.loadCatalogSession(h,!1),n.requestUpdate?.();return}let s=ZC(n,{startup:!0,awaitHistory:!0,deferBranches:!0,historyLoad:g});this.deferSessionHydrationUntilTranscript(i,s.then(()=>ll(n).phase===`committed`)),s.finally(()=>{o()}),WC(n).finally(()=>n.requestUpdate?.()),n.loadAssistantIdentity(),this.refreshSessionSuggestions()}p&&!h&&el(n),this.reconcileWaitingApprovalSnapshot(),n.requestUpdate?.()}}}})))()}var hT;function gT(){return(gT=e((()=>{hT=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 _T;function vT(){return(vT=e((()=>{gr(),Uo(),hs(),ps(),y(),Ae(),Ka(),vt(),Ue(),Fe(),O(),Bp(),Ml(),I(),js(),ed(),lt(),_l(),mT(),gT(),Q(),M_(),jo(),_T=class extends pT{constructor(...e){super(...e),this.headerSessionDataMemo=new hT,this.handleArchiveSessionShortcut=e=>{if(!Ft(Be.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??le(e?.key??this.state?.sessionKey??this.sessionKey,e)}canArchiveHeaderSession(e){return!e.archived&&!this.context.sessions.archiveVisibility(e.key)&&kt(e,b({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}))&&!os({snapshot:this.context.gateway.snapshot,session:e})[`toggle-archived`]}headerSessionMenuData(e,t){let n=j({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello},`main`,tt(e.key)?.agentId??e.agentId).sessionKey,r=this.resolveHeaderSessionTitle(e),i=!!ns(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:ro(e.category)??null,icon:ro(e.icon)??null,color:ro(e.color)??null,categoryClearReturnsToGroups:!1}))}async loadHeaderPlatform(e,t){let n=this.context.gateway,r=await Nc(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.reclaimHeaderPlacement(t);if(e.kind===`toggle-archived`&&!t.archived&&!this.canArchiveHeaderSession(t))return;if(e.kind===`open-in`){Ji(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 lf(e.kind,{context:this.context,session:t,agentId:this.state?X(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 oh({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&&Ot({message:V(`common.refresh`)}),r?i(r):null};try{let i=await(this.headerSessionOperationsLoad??=ko(()=>import(`./session-organizer-operations.runtime-RnGN66Ok.js`),__vite__mapDeps([51,0,1,2,3,4,5,52,11,12,53,48,6,7,8,9,17,18,19]),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=yn({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:()=>Ls(n.sessions.state.groups,n.sessions.state.result?.sessions??[])};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 i.assignSessionCategory(s,a,e.category,n,{},{resolveSession:o});break;case`new-group`:{let{showInputDialog:e}=await ko(async()=>{let{showInputDialog:e}=await import(`./input-dialog-OAeQnraY.js`).then(e=>(e.t(),e.n));return{showInputDialog:e}},__vite__mapDeps([53,0,6]),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 i.assignSessionCategory(s,a,t,n,{},{resolveSession:o});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 D_({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=L(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=If(e),this.headerRenameValue=this.headerRenameInitialValue,this.headerEditing=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.chat-pane__session-title-input`);e?.focus(),e?.select()})}cancelHeaderRename(){this.headerEditing=!1,this.headerRenameSession=null}commitHeaderRename(){if(!this.headerEditing)return;let e=this.headerRenameSession,t=vp(this.headerRenameValue,this.headerRenameInitialValue,e?.label);this.headerEditing=!1,this.headerRenameSession=null;let n=this.state;if(!e||!n||!t)return;let r=L(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:X(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.loaded&&!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,e.loaded=!0}).catch(()=>{e.path=null,e.loaded=!1}).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||Lr(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=Pe){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=tt(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 yT;function bT(){return(bT=e((()=>{y(),si(),vT(),Q(),v_(),yT=class extends _T{async probeSessionDiscussion(e){let t=this.state;if(!t?.connected||!t.client||this.sessionDiscussionStates.has(e)||this.sessionDiscussionProbes.has(e)||!oi(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:X(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||!oi(this.context.gateway.snapshot,`session.discussion.info`,`operator.read`))return null;let n=oi(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||!oi(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:X(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(z_(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!1;let t=Q_(e.sidebarLayout,`discussion`),n=t.columns.flatMap(e=>e.panels).find(e=>e.slot===`discussion`);return this.commitSidebarLayout(t),n&&e.updateSidebarActivePanel(n.id),!0}resolveSessionDiscussionAction(){let e=this.state,t=e?.sessionKey.trim()??``,n=t?this.sessionDiscussionStates.get(t):void 0;if(!e?.connected||!e.client||!t||n===void 0||n===`none`||!oi(this.context.gateway.snapshot,`session.discussion.info`,`operator.read`)||!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(z_(e.sidebarLayout,`discussion`)):this.openSessionDiscussionSlot()}}}})))()}var xT;function ST(){return(ST=e((()=>{rs(),lr(),y(),si(),_l(),gT(),xT=class{constructor(){this.memo=new hT}read(e,t,n,r){let i=e.nativeConversation?.supportsSessionActions,a=i&&t?pu(e.plugins,t):[],o=!!(i&&Ho(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,at.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 CT;function wT(){return(wT=e((()=>{wr(),xo(),Xo(),yr(),Yn(),or(),lr(),Ko(),hs(),ps(),y(),si(),Qa(),O(),Ml(),I(),js(),Xp(),bT(),Jw(),gT(),ST(),qx(),Is(),jv(),qg(),Iv(),jg(),Cv(),y_(),_f(),v_(),CT=class extends yT{constructor(...e){super(...e),this.headerWorkspaceGit=!1,this.headerPanelsMemo=new hT,this.headerLayoutMemo=new hT,this.headerSessionActions=new xT,this.headerReasonsMemo=new hT,this.headerSharingMemo=new hT,this.headerGroupsMemo=new hT,this.headerActivityMemo=new hT,this.headerViewersMemo=new hT,this.headerBoardMenuMemo=new hT,this.onHeaderMenuOpen=()=>{this.headerMenuRow&&this.loadHeaderMenuData(this.headerMenuRow,this.headerAgentWorkspace,this.headerWorkspaceGit)},this.onHeaderCommandPalette=()=>window.dispatchEvent(new Event(kn)),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`)},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,s=Gw()){this.headerMenuRow=t,this.headerWorkspace=e,this.headerAgentWorkspace=r,this.headerWorkspaceGit=i,this.syncSelectedSessionSharing(t);let c=_h({session:t,agentWorkspace:t?.worktree?void 0:r,worktreePath:t?.worktree?this.headerWorktreePaths.get(t.worktree.id)?.path:void 0}),l=!!t?.execNode||Lr(t?.placement?.state),u=t?.repository?.branch||t?.worktree?.branch||(l||!c.root?null:this.headerBranches.get(c.root)?.value)||null,d=Ev({session:t,workspaceRoot:c.root,methodAdvertised:K(this.context.gateway.snapshot,`sessions.files.reveal`)===!0,hasAdminAccess:Wn(this.context.gateway.snapshot.hello?.auth??null)}),f=this.state?this.state.chatSending||Ug({runActive:$d(this.state),queue:this.state.chatQueue,runStatus:this.state.chatRunStatus,sessionKey:this.state.sessionKey}):!1,p=Yf(this.context.gateway.snapshot,!!this.state?.chatRunId).branchSwitch,m=this.state&&this.isCurrentSessionArchived(this.state)?V(`chat.archivedSessionDisabled`):p.allowed?f?V(`chat.sessionHeader.branchSwitchUnavailable`):null:p.reason,h=this.context.gateway.snapshot,g=K(h,`session.visibility.set`)===!0,_=L(h,{method:`session.members.listEvidence`,requiredScope:`operator.read`}),v=e=>L(h,{method:e,requiredScope:`operator.write`}),y=v(`session.visibility.set`),x=v(`session.publicShare.set`),S=v(`session.members.add`),C=v(`session.members.remove`),ee=_.allowed||y.allowed?void 0:_.reason,w=t?L(this.context.gateway.snapshot,{method:`sessions.patch`,params:{key:t.key,label:null},sessionScope:!0,session:t}):null,T=this.state?.connected!==!0||!w?V(`sessionsView.actionRequiresConnection`):w.allowed?void 0:w.reason,E=b({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}),D=!!(t&&this.canArchiveHeaderSession(t)),O=!!(t&&It([t],E)),k=t!=null&&jt(t),A=t?os({snapshot:this.context.gateway.snapshot,session:{...t,pinnable:k}}):{},j=t?L(this.context.gateway.snapshot,{method:`sessions.assignOwner`,params:{key:t.key,owner:{type:`human`,id:h.selfUser?.id??`profile`}},requiredScope:`operator.write`}):null,M=t?this.continueInTerminalDisabledReason(t):void 0,te=this.headerReasonsMemo.read([...Object.entries(A).flat(),j?.allowed,j&&!j.allowed?j.reason:void 0,M],()=>({...A,...j&&!j.allowed?{"assign-owner":j.reason}:{},...M?{"continue-in-terminal":M}:{}})),ne=Gx(t)!==null&&Bn(this.context.gateway.snapshot),N=this.resolveSessionDiscussionAction(),P=o??this.state?.sidebarLayout,F=P?.open===!0&&!P.expanded,re=U`<openclaw-tooltip
.content=${V(F?`chat.sidePanel.minimize`:`chat.sidePanel.label`)}
>
<button
class="btn btn--ghost btn--icon chat-icon-btn chat-side-panel-toggle"
type="button"
aria-label=${V(F?`chat.sidePanel.minimize`:`chat.sidePanel.label`)}
aria-expanded=${String(F)}
@click=${()=>this.setChatSidePanelOpen(!F,o)}
>
${F?H.panelRightClose:H.panelRightOpen}
</button>
</openclaw-tooltip>`,ie=e.onToggleBrowser?U`<openclaw-tooltip .content=${V(`browser.toggle`)}>
<button
class="btn btn--ghost btn--icon chat-icon-btn chat-browser-panel-toggle"
type="button"
aria-label=${V(`browser.toggle`)}
@click=${e.onToggleBrowser}
>
${H.globe}
</button>
</openclaw-tooltip>`:W,ae=this.state!==void 0&&Le(this.state.sidebarLayout,`companion`),oe=e.list?.files.filter(e=>e.kind===`modified`).length??0,se=this.headerPanelsMemo.read([!!e.onToggleTerminal,!!e.onToggleBrowser,ne&&!!e.onToggleDesktop,N?.label,N?.active,!!e.onOpenDiff,e.collapsed,oe,ae,at.getLocale()],()=>{let t=[[`terminal`,V(`terminal.toggle`),H.terminal,e.onToggleTerminal&&this.headerPanelCallbacks.terminal],[`browser`,V(`browser.toggle`),H.globe,e.onToggleBrowser&&this.headerPanelCallbacks.browser],[`desktop`,V(`desktop.toggle`),H.monitor,ne&&e.onToggleDesktop?this.headerPanelCallbacks.desktop:void 0],[`discussion`,N?.label??``,H.messageSquare,N&&this.headerPanelCallbacks.discussion],[`changes`,V(`chat.sessionDiff.show`),H.diff,e.onOpenDiff&&this.headerPanelCallbacks.changes]].flatMap(([e,t,n,r])=>r?[{id:e,label:t,icon:n,onActivate:r,...e===`discussion`?{active:N?.active}:{}}]:[]);return t.push({id:`session-files`,label:V(e.collapsed?`chat.workspaceFiles.showFiles`:`chat.workspaceFiles.collapse`),icon:H.fileText,active:!e.collapsed,badge:oe,onActivate:this.headerPanelCallbacks.files}),t.push({id:`session-companion`,label:V(ae?`chat.rail.collapse`:`chat.rail.show`),icon:H.spark,active:ae,onActivate:this.headerPanelCallbacks.companion}),t}),ce=!n&&this.dashboardDefaultMenuAction(t,P);this.headerDefaultAction=ce?{id:`dashboard-default`,icon:H.check,...ce}:void 0;let le=this.headerLayoutMemo.read([ce&&ce.kind,ce&&ce.label,ce&&ce.description,ce&&ce.disabled,!!this.onOpenSplitView,this.narrow,!!this.onSplitDown,!!this.onSplitRight,at.getLocale()],()=>{let e=[];ce&&e.push({id:`dashboard-default`,icon:H.check,...ce,...ce.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}),ue=Kx({gatewaySnapshot:this.context.gateway.snapshot,movingKey:this.headerPlacementMovingKey,reclaimingKey:this.headerPlacementReclaimingKey,restartingKey:this.headerPlacementRestartingKey,row:t}),de=this.state?.sessionKey??``,fe=this.state?.sessionsResult,I=this.context.sessions?.state?.groups,pe=this.context.sessions?.state?.result?.sessions,me=this.headerGroupsMemo.read([I,pe],()=>Ls(I??[],pe??[])),he=(fe?.owners?.length??0)>=2||(t?.participantCount??0)>0,ge=this.headerActivityMemo.read([this.context,this.context.basePath],()=>Qo(this.context)),_e=he?t?.owner?.actor.identity:void 0,ve=n?void 0:this.headerViewersMemo.read([this.presencePayload,h.selfUser,h.client?.instanceId,de,_e,he?t?.participants:void 0],()=>ki(this.presencePayload,h.selfUser,h.client?.instanceId,de,[..._e?[_e]:[],...he?(t?.participants??[]).map(({identity:e})=>e):[]])),ye=Na(this.presencePayload).users.some(e=>Qi(e,_e)&&e.watchedSessions.includes(de)),be=t?this.sessionSharingStates.get(this.sessionSharingCacheKey(t.key)):void 0,xe=h.hello?.policy?.allowedSessionVisibilities,Se=this.headerSharingMemo.read([g,...t?Object.entries(t).flat():[void 0],be,xe,_.allowed,ee,y.allowed,y.allowed?void 0:y.reason,S.allowed,S.allowed?void 0:S.reason,C.allowed,C.allowed?void 0:C.reason,x.allowed,x.allowed?void 0:x.reason,ye,ge,he,at.getLocale()],()=>g&&t?{session:t,state:be,allowedVisibilities:xe,membersAvailable:_.allowed,openDisabledReason:ee,visibilityDisabledReason:y.allowed?void 0:y.reason,memberAddDisabledReason:S.allowed?void 0:S.reason,memberRemoveDisabledReason:C.allowed?void 0:C.reason,publicShareDisabledReason:!t.sessionId||fo(t.key)?V(`chat.sessionSharing.publicUnavailable`):x.allowed?void 0:x.reason,onPublicShareChange:e=>void this.setSessionPublicShare(t,e),onCopyPublicLink:()=>void this.copySessionPublicLink(t),ownerViewing:ye,personActivity:ge,showOwner:he,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(P);let Ce=this.headerBoardMenuMemo.read([this.headerBoardMenu?.widget,this.headerBoardMenu?.tabs,this.headerBoardMenu?.canMutate],()=>this.headerBoardMenu&&{...this.headerBoardMenu,onSelect:this.onHeaderBoardSelect}),we=this.observedParentSessionRow(),Te=dv({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:he,ownerViewing:ye,personActivity:ge,catalog:n,catalogColor:this.catalogSession?.color,editing:this.headerEditing&&this.headerRenameSession?.key===t?.key,renameValue:this.headerRenameValue,workspaceRoot:c.root,workspaceLabel:c.label,workspaceIcon:zv(this.context,c.root?t?.key:void 0),parentSession:Ov(t,we?[we]:[]),branch:u,branches:this.state?cl(this.state):[],branchSwitchDisabledReason:m,platform:this.headerPlatform,canReveal:d,copiedAction:this.headerCopiedAction,renameDisabledReason:T,actionsDisabled:this.state?.connected!==!0,panelActions:ie,panelLayoutActions:U`${W_(P,s,this.narrow,(e,t)=>this.state?.updateSidebarLayout(e,t))}${re}`,presence:ve?.length?U`<openclaw-viewer-facepile
class="chat-pane__presence"
.staticUsers=${ve}
.maxVisible=${4}
.personActivity=${ge}
variant="session"
></openclaw-viewer-facepile>`:W,sharingControl:Se&&(!Av(Se.session)||!Se.openDisabledReason)&&(!this.narrow||!Av(Se.session))?ov(Se):W,publicAccessIndicator:this.narrow&&Se?cv(Se):W,placementControl:A_({session:t,placementStartupStatus:a,placementMoving:ue.moving,placementRestarting:ue.restarting,placementMoveDisabledReason:ue.moveDisabledReason,placementReclaimDisabledReason:ue.reclaimDisabledReason,placementRecoveryDisabledReason:ue.recoveryDisabledReason,onPlacementMove:()=>t&&void this.changeHeaderPlacement(t,`move`),onPlacementReclaim:()=>t&&void this.reclaimHeaderPlacement(t),onPlacementRecover:()=>t&&void this.changeHeaderPlacement(t,`recover`)}),sessionMenuAction:t&&this.state?U`<openclaw-chat-header-session-menu
.session=${this.headerSessionMenuData(t,k)}
.worktreePath=${t.execNode||!_s()?null:c.root}
.onboarding=${this.onboarding}
.preferencesBrowserOnly=${this.context.runtimeConfig?.state.connected&&this.context.runtimeConfig.canPatch===!1}
.compact=${this.narrow}
.navigationAllowed=${!0}
.copyMarkdownAllowed=${yd(this.context.gateway.snapshot)}
.splitAllowed=${ou()}
.settings=${this.state.settings}
.panelActions=${se}
.layoutActions=${le}
.boardWidgetMenu=${Ce}
.sessionActions=${this.headerSessionActions.read(this.context,t,ue.reclaimDisabledReason,this.onHeaderAction)}
.sharing=${Se}
.groups=${me}
.currentOwner=${t.owner?.actor??null}
.actionDisabledReasons=${te}
.forkDisabled=${this.state.sessionsLoading||t.modelSelectionLocked===!0}
.forkFromLastCompleted=${t.hasActiveRun===!0}
.archiveAllowed=${D}
.archiveShortcut=${this.active&&this.presented&&!this.onboarding}
.deleteAllowed=${O}
.onOpen=${this.onHeaderMenuOpen}
.onOpenCommandPalette=${this.onHeaderCommandPalette}
.onSettingsChange=${this.onHeaderSettingsChange}
.onAction=${this.onHeaderAction}
></openclaw-chat-header-session-menu>`:W,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,c.root,u)},onOpenParentSession:e=>{this.onPaneSessionChange?.(this.paneId,e)},onBranchSelect:e=>{let t=Yf(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}),Ee=this.currentContinueInTerminalCommand(t);return U`${Te}${Ee?ey({command:Ee,onClose:()=>this.closeContinueInTerminalDialog()}):W}`}}})))()}var TT;function ET(){return(ET=e((()=>{y(),tx(),wT(),rd(),TT=class extends CT{constructor(...e){super(...e),this.removeBrowserAnnotation=e=>{let t=this.state;if(!t)return;let n=t.sessionKey;ex({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:()=>{this.updateComplete.then(()=>{this.state===t&&this.state.sessionKey===n&&this.querySelector(ep)?.focus({preventScroll:!0})})},focusRestoredAnnotation:e=>{this.updateComplete.then(()=>{this.state===t&&this.state.sessionKey===n&&[...this.querySelectorAll(`[data-attachment-id]`)].find(t=>t.dataset.attachmentId===e)?.querySelector(`button`)?.focus({preventScroll:!0})})}},e,{removed:V(`chat.composer.browserAnnotationRemoved`),undo:V(`common.undo`),undoUnavailable:V(`chat.composer.browserAnnotationUndoUnavailable`)})}}}})))()}var DT;function OT(){return(OT=e((()=>{Sf(),ry(),DT=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 iy({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?Zd({...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 kT(e){if(!e||e.status===`ok`)return W;let t=e.totalBytes>0?Math.round((e.totalBytes-e.availableBytes)/e.totalBytes*100):0,n=e.status===`critical`;return U`
<div
class="chat-composer-neighbor-card chat-composer-neighbor-card--${n?`danger`:`warn`} chat-cloud-disk-space-notice"
role=${n?`alert`:`status`}
>
<span class="chat-composer-neighbor-card__icon" aria-hidden="true"
>${H.alertTriangle}</span
>
<div class="chat-composer-neighbor-card__copy">
<strong
>${V(n?`chat.diskSpace.criticalTitle`:`chat.diskSpace.warningTitle`)}</strong
>
<span>
${V(n?`chat.diskSpace.criticalBody`:`chat.diskSpace.warningBody`,{percent:String(t),free:Tt(e.availableBytes)})}
</span>
</div>
</div>
`}function AT(e){if(!e)return W;let t={transferred:Tt(e.transferredBytes),total:Tt(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 U`
<div
class="chat-composer-neighbor-card chat-composer-neighbor-card--info chat-worker-runtime-install-notice"
role="status"
title=${r}
>
<span class="chat-composer-neighbor-card__icon" aria-hidden="true">${H.info}</span>
<div class="chat-composer-neighbor-card__copy">
<strong
>${n?V(`chat.workerRuntimeInstall.installingTitle`):V(`chat.workerRuntimeInstall.transferringTitle`,t)}</strong
>
<span>${r}</span>
</div>
</div>
`}function jT(e,t=W,n=cs(e),r=`danger`,i){let a=n.trim().split(/\r?\n/u).map(e=>e.replace(/\s+/gu,` `).trim()),o=i??nt(a[0]??``),s=a.some(e=>e!==``&&e!==o);return U`
<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?U`<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>
${Cs(e,V(`chat.copyError`))}
</summary>
<pre class="chat-error__diagnostic" tabindex="0" aria-label=${V(`chat.errorDetails`)}>
${n}</pre>
</details>`:U`<span class="chat-error__content"
><strong>${o}</strong>${Cs(e,V(`chat.copyError`))}</span
>`}
${t}
</div>
`}function MT(e){let t=e.onDismissError?U`
<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>
`:W;return U`
<div class="chat-topbar-notices">
${kT(e.diskSpace)}
${AT(e.workerRuntimeInstall)}
${e.error?jT(e.error,t):W}
</div>
`}function NT(e){let t=e.runError?.kind===`state_contention`,n=e.onRefresh?U`<button
class="btn btn--sm chat-error__refresh"
type="button"
?disabled=${!e.connected}
@click=${e.onRefresh}
>
${V(t?`chat.checkStatus`:`common.refresh`)}
</button>`:W;return U`
${e.providerReviewNotice??W}
${PT(e.providerPolicyNotice)}
${e.runError?jT(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`)):W}
${Tv({conflict:e.workspaceConflict??void 0,onDismiss:e.onDismissWorkspaceConflict})}
${FT(e.placementStartup,e.messages,e.onRetrySessionPlacementStartup)}
`}function PT(e){if(!e)return W;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 U`
<div
class="chat-composer-neighbor-card chat-composer-neighbor-card--${t?`danger`:`warn`} chat-provider-policy-notice"
role=${t?`alert`:`status`}
>
<span class="chat-composer-neighbor-card__icon" aria-hidden="true"
>${H.alertTriangle}</span
>
<div class="chat-composer-neighbor-card__copy">
<strong>${V(`chat.providerPolicy.${e.state}Title`)}</strong>
<span>${r}</span>
</div>
</div>
`}function FT(e,t,n){if(e?.phase!==`failed`)return W;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=cs(i),s=r?[V(`chat.queue.checkDeliveryHelp`),e.error?o:void 0].filter(Boolean).join(`
`):V(`newSession.placementStartFailed`,{error:o}),c=e.initialTurn&&!hi(t,e.initialTurn.sendRunId,!0);return jT(a,e.discardAndReload?U`<button
class="btn btn--sm danger chat-error__discard"
type="button"
@click=${e.discardAndReload}
>
${V(`newSession.discardUnsavedAndReload`)}
</button>`:e.retryable&&n&&!c?U`<button class="btn btn--sm" type="button" @click=${n}>
${V(r?`chat.queue.checkDelivery`:`common.retry`)}
</button>`:W,s,`danger`,r?V(`chat.queue.checkDeliveryHelp`):e.discardAndReload?s:V(`chat.errorStartSummary`))}function IT(){return(IT=e((()=>{wr(),ms(),bs(),lr(),y(),vi(),pt(),pi(),we(),Vv(),Di()})))()}function LT(e){let t=e.selectedSession;if(!t||t.archived||t.hasActiveSubagentRun!==!0||e.runActive||e.runWorking||wo(t))return null;let n=by(e.messages),r=e.subagentSessions?.filter(e=>{let n=E(e);return!e.archived&&wo(e)&&!z(e.key,t.key)&&(n?z(n,t.key):t.childSessions?.some(t=>z(t,e.key)))}),i=r?.length===1?r[0]:void 0;return{startedAt:n!==null&&typeof t.startedAt==`number`&&n>t.startedAt?n:null,...i?{child:{key:i.key,label:le(i.key,i)}}:{}}}function RT(){return(RT=e((()=>{Fe(),I(),Sy()})))()}function zT(e){let t=e.inlineApproval?.sourceSessionKey,n=t?e.sessions?.sessions.find(e=>z(e.key,t)):void 0,r=e.historyState?cf(e.historyState):void 0,i=r?[...r.page.items.filter(e=>!e.queued),...r.queuedInputs]:void 0,a=e.onRequestUpdate??(()=>{}),o=()=>e.transcript.scrollElement?.closest(`.chat`)?.querySelector(`.agent-chat__composer-combobox > textarea`)?.focus({preventScroll:!0}),s=(t,n,r,i,a=!1)=>{mv({paneId:e.paneId,anchorRect:n,sourceRange:e.transcript.scrollElement?r_(e.transcript.scrollElement,t)?.range:void 0,comment:``,readSignal:e.readSignal,onCancel:i,onSave:n=>{if(e.readSignal?.aborted)return!0;if(!a&&!Ze(e.uploadConfig))return Ot({message:Qe()}),!1;let i=H_({...t,comment:n,sessionKey:e.sessionKey},{attachmentLimits:e.attachmentLimits,selectionContextOnly:a},nh(e));return i?r(i)?!0:(Ge([i]),!1):!1}})},c=e.canSend,l=Fg(e.paneId),u=Fv(l,{...e,onReopen:(t,n)=>{let r=c_(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=Cp({...e,canCompose:c}),m=e.placementStartup?.phase===`failed`?null:e.placementStartup,h=e.placementStartup?.initialTurn,g=e.queue;if(h){let t=BT.get(e.queue);t?.initialTurn!==h&&(t={initialTurn:h,queue:[...e.queue,h]},BT.set(e.queue,t)),g=t.queue}let _=!!m||Ug(e),v=$e(`transcript`,{sessionKey:e.sessionKey,agentId:e.currentAgentId,messages:e.messages,stream:e.stream,loading:e.loading},Jv({...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:_,subagentSessions:e.swarm?.sessions,startupLabel:wu(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&&Ze(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:()=>e.transcript.scrollElement?.closest(`.chat`)?.querySelector(`openclaw-plugin-view[data-plugin-composer], .agent-chat__composer-combobox > textarea`)?.focus({preventScroll:!0})},e.transcript),e.presented??!0),y=U`${r&&(r.error||r.page.nextBefore!==void 0||r.before!==void 0)?U`<div class="chat-pending-inputs" role="status">
${r.error?U`<span>${r.error}</span>`:W}
${r.page.nextBefore===void 0?W:U`<button
class="btn btn--sm"
type="button"
?disabled=${r.loading}
@click=${()=>e.historyState&&qp(e.historyState,r.page.nextBefore)}
>
${V(`chat.pendingInputs.earlier`)}
</button>`}
${r.before===void 0?W:U`<button
class="btn btn--sm"
type="button"
?disabled=${r.loading}
@click=${()=>e.historyState&&qp(e.historyState)}
>
${V(`chat.pendingInputs.latest`)}
</button>`}
</div>`:W}
${e.inlineApproval&&e.onApprovalDecision?U`<div class="chat-inline-approval">
${$o({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>`:W}
${rv({pullRequests:e.pullRequests??[],gateway:e.pullRequestsGateway,sessionId:e.pullRequestsSessionId,basePath:e.basePath,sessionKey:Ee(e.sessionKey,e.currentAgentId??void 0),presented:e.presented??!0,branch:e.pullRequestsBranch,status:e.pullRequestsStatus??`ready`,onDismiss:t=>e.onDismissPullRequest?.(t),onOpenSessionDiff:e.onOpenSessionDiff,publication:e.githubPublication})}
${m_({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?o_(e.swarm):W}
<openclaw-plugin-contributions
.kind=${`composer`}
.sessionKey=${e.sessionKey}
.agentId=${e.currentAgentId}
.presented=${We(e.presented??!0)}
></openclaw-plugin-contributions>`,b=NT(e);l.transcriptRenderContext.onAsyncQuestionSubmit=e.onAsyncQuestionSubmit,l.transcriptRenderContext.onAsyncQuestionDiscard=u.discard;let x=Iu(e.messages,e.queue,i??[]),S=[...Dm(x.queuedInputs),...x.queue],C={...e,displayQueue:S},ee=Qg({...e,asyncQuestions:u,displayQueue:S,footerContent:y,notices:b,onRequestUpdate:a,onToggleRealtimeTalk:e.suggestionComposer?void 0:e.onToggleRealtimeTalk,onOpenImage:f}),w=$e(`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},ee,e.presented??!0,U`<div class="chat-footer__context">
${y}
<div class="agent-chat__composer-notices">${b}</div>
${__(Tg({...e,asyncQuestions:u},c_(e.paneId),a))}
${F_(C,!!(e.canAbort&&e.onAbort)&&!d_(e.runStatus))}
${e.suggestionComposer?W:qm({...e,disabled:!c})}
${e.composerRecovery??W}
</div>`),T=Og(e),E=T===W?W:U`<div class="chat-gutter-stack">${T}</div>`,D=e.onScrollToBottom?U`
<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>
`:W,O=e.historyState,k=O?ll(O):void 0,A=O!==void 0&&k?.phase===`failed`&&k.sessionKey===e.sessionKey,j=!_&&e.messages.length===0&&x.pendingInputs.length===0&&x.queuedInputs.length===0&&e.toolMessages.length===0&&e.streamSegments.length===0&&!e.stream&&g.length===0,M=t=>U`<div
class="chat-history-error${t?` chat-history-error--inline`:``}"
role=${t?`status`:`alert`}
>
<span>${k?.phase===`failed`?k.message:``}</span>
<button
class="btn btn--sm"
type="button"
@click=${()=>{O&&ll(O).phase===`failed`&&(e.onRefresh(),O.requestUpdate?.())}}
>
${V(`common.retry`)}
</button>
</div>`,te=A&&j?M(!1):W,ne=A&&!j?M(!0):W;return U`
<section
class="chat"
style=${Ar(e.chatMessageMaxWidth?{"--chat-thread-max-width":e.chatMessageMaxWidth,"--chat-message-max-width":`100%`}:{})}
@drop=${p.onDrop}
@dragenter=${p.onDragenter}
@dragleave=${p.onDragleave}
@click=${e=>oc(e,f)}
@dragover=${p.onDragover}
@keydown=${t=>{if(!hc(t)&&(t.key!==`Enter`&&t.key!==` `||!oc(t,f))){if(t.key===`Escape`&&e.replyTarget&&!t.defaultPrevented&&!t.isComposing&&t.keyCode!==229&&!c_(e.paneId).composerComposing){t.preventDefault(),e.onClearReply?.();return}Ft(Be.transcriptSearch,t)&&(t.preventDefault(),_v(e.paneId,a,t))}}}
>
${e.suggestionComposer?W:U`<openclaw-chat-comment-controller
.paneId=${e.paneId}
.props=${e}
.disabled=${!c}
.sessionKey=${e.sessionKey}
.presented=${We(e.presented??!0)}
></openclaw-chat-comment-controller>`}
<div class="chat-workbench" ${Jn({workbench:!0})}>
<div class="chat-workbench__main">
<div class="chat-split-container">
<div class="chat-main">
<div class="chat-main__conversation-column">
${MT(e)}
<openclaw-plugin-contributions
.kind=${`header`}
.sessionKey=${e.sessionKey}
.agentId=${e.currentAgentId}
.presented=${We(e.presented??!0)}
></openclaw-plugin-contributions>
${Bg(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=>GS(t,e.transcript.scrollElement)}
>
${ne} ${te===W?v:te}
${D} ${E}
<div class="chat-footer">${w}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
`}var BT;function VT(){return(VT=e((()=>{wr(),jr(),dr(),Ds(),lr(),y(),Ue(),I(),lt(),ut(),St(),ft(),Zl(),Zp(),Cf(),nc(),JS(),IT(),Vg(),uv(),jf(),R_(),g_(),L_(),jv(),ku(),Gv(),Wd(),$v(),Ag(),l_(),fv(),hv(),Xv(),Pg(),Im(),br(),BT=new WeakMap})))()}var HT;function UT(){return(UT=e((()=>{mo(),wr(),Yb(),an(),Yn(),Bo(),Sg(),Ua(),Pt(),I(),St(),ET(),Jw(),qx(),rT(),OT(),VT(),py(),Zv(),ku(),yv(),Pf(),w_(),v_(),HT=class extends TT{constructor(...e){super(...e),this.toolIcons=new DT(this,()=>this.context,()=>this.state&&!this.catalogHost?this.resolveChatReadTarget():void 0),this.desktopFocus=null}renderChatPaneLayout(e){let{state:t,selectedSession:n,currentAgentId:r,board:i,sidebarLayout:a,sessionWorkspace:o,chatProps:s,observerDigest:c,observerRunId:l,catalog:u,agentWorkspace:d,workspaceGit:f,openPanelSlot:p,closePanelSlot:m}=e;if(this.inputRegion===`page`){let e=t.sessionWorkspaceState?.previews.find(e=>e.id===t.sessionWorkspaceState?.activePreviewId)?.content,i=e?.kind===`file`&&Le(a,`workspace`)?e:void 0,o=_h({session:n,agentWorkspace:d,worktreePath:n?.worktree?this.headerWorktreePaths.get(n.worktree.id)?.path:void 0});ly(this.context,this,this.presented&&this.selected?{sessionKey:t.sessionKey,sessionId:t.currentSessionId??void 0,agentId:r,workspace:i?.root??o.root??void 0,file:i?.path}:void 0)}let h=U`<openclaw-chat-outbox-recovery
.host=${t}
.messages=${t.chatMessages}
.identity=${JSON.stringify([t.settings.gatewayUrl,t.connected&&t.client?.recoveryScopeReady?t.client.recoveryScope:null,Ct(j(t,t.sessionKey)),t.currentSessionId])}
@outbox-restored=${()=>{this.chatState.composerPersistence.restore(),t.requestUpdate?.()}}
></openclaw-chat-outbox-recovery>`,g=Kh(s.messages,s.toolMessages),_={owner:this,isPresented:()=>this.presented},v=e=>({owner:this,isPresented:()=>this.presented&&this.visuallyPresented&&Le(a,e)}),y=zT({...s,composerRecovery:h,pluginToolIcons:this.toolIcons.icons,presented:{owner:this,isPresented:()=>this.active&&this.presented},progressCardVisibility:_,transcriptVisible:v(`conversation`),latestBrowserTabs:this.active&&this.presented?g:void 0,historyState:u?void 0:t}),b=U`<div class="chat-pane-primary-column">${y}</div>`,x=this.buildSessionDiscussionPanel(t,t.sessionKey.trim()),S=this.sessionDiscussionStates.get(t.sessionKey.trim()),C=S===`available`||S===`open`,ee=Bn(this.context.gateway.snapshot),w=t.sessionKey,T=this.sessionCompanionThreads.view(w,r),E=v(`companion`);this.syncSessionCompanionPresentation(E.isPresented());let D={owner:this,isPresented:()=>this.active&&this.presented&&Le(a,`browser`)},O=Ye(a)?.slot!==`browser`,k=Ye(a)?.slot!==`terminal`,A=v(`desktop`),M=!this.pendingPanelToggleRequests.has(`desktop`),te=this.activeSessionResources.desktopSource(t.client,t.sessionKey,N(t,t.sessionKey).agentId,t.connectionEpoch,this.resourceSessionObservation()?.row??void 0),ne=a.columns.flatMap(e=>e.panels).find(e=>e.slot===`desktop`)?.environmentId??(te===void 0?Gx(n):te),P=JSON.stringify([t.sessionKey,this.connectionGeneration,ee,A.isPresented(),t.basePath]);(this.desktopFocus?.key!==P||this.desktopFocus.client!==t.client)&&(this.desktopFocus={key:P,client:t.client,href:co({kind:`desktop`,session:t.sessionKey},t.basePath)});let F=this.desktopFocus,re=Gw({panePresentation:_,state:t,themeMode:this.context.theme.resolvedMode,agentId:r,browserPresented:D,browserTabsInHeader:O,linkReaders:cn(this.context.gateway.snapshot),linkReaderPresented:v(`link-reader`),linkReaderTabsInHeader:Ye(a)?.slot!==`link-reader`,onCloseLinkReader:()=>m(`link-reader`),terminalTabsInHeader:k,browserRefreshOnPresentation:!this.pendingPanelToggleRequests.has(`browser`),preferredBrowserTab:[...g.values()].at(-1),sessionBrowserTabs:[...g.values()].map(e=>e.tab),desktopPresented:A,desktopRefreshOnPresentation:M,desktopAvailable:ee,desktopSource:ne,portalPresented:v(`portal`),desktopFocusHref:F.href,onDesktopFocusTargetChange:e=>{let n=co(e,t.basePath);this.desktopFocus===F&&F.href!==n&&(F.href=n,this.requestUpdate())},dashboard:this.compact?W:this.renderBoardPanel(i,a),workspace:Sv(o),renderDetail:e=>S_({chat:s,content:e,host:t,requestUpdate:t.requestUpdate}),digest:c,activeRunId:l,pullRequests:this.sessionPullRequests,companion:T,companionFocusRequest:this.sessionCompanionFocusRequest,companionPresented:E,onCompanionSubmit:e=>void this.submitSessionCompanionQuestion(e),onCompanionDraftChange:e=>this.sessionCompanionThreads.setDraft(t.sessionKey,e,r),onCompanionAttachmentsChange:e=>this.sessionCompanionThreads.setAttachments(w,e,r),connected:t.connected,onClearCompanion:()=>void this.clearSessionCompanion(),discussion:x,discussionAvailable:C,discussionOpenUrl:x?.openUrl??null,discussionSourceGeneration:this.connectionGeneration,pluginPanels:this.context.plugins.registrations(`panels`),isPluginPanelPresented:e=>({owner:this,isPresented:()=>this.active&&this.presented&&Le(a,e)})}),ie=Kw(re),ae=qw(re),oe=qw(re,`headerAction`),se=this.connectionGeneration,ce=this.compact?W:U`${this.renderPaneHeader(o,n,u,d,f,s.placementStartup,a,re)}
<div class="chat-session-accessories">
<openclaw-plugin-contributions
.kind=${`session-header`}
.sessionKey=${t.sessionKey}
.agentId=${r}
.session=${n}
.presented=${We({owner:this,isPresented:()=>this.visuallyPresented,preview:()=>!this.presented&&this.connectionGeneration===se})}
></openclaw-plugin-contributions>
</div>`,le=Zw({presentationId:this.presentationId,conversationTab:{label:s.assistantName,icon:ts(Cd(s))},availableWidth:this.paneWidth,fetchFavicon:Rg(t),availableSlots:ie,callbacks:Xw({state:t,layout:a,closePanelSlot:m,openPanelSlot:p,forgetDiscussionUrl:()=>this.sessionDiscussionOpenUrls.delete(t.sessionKey.trim()),resizePanel:(e,t)=>this.commitSidebarPanelResize(a,e,t),setPanelOpen:e=>this.setChatSidePanelOpen(e,a)}),layout:a,panelDefinitions:re,panelActions:oe,narrow:this.paneWidth<680,panelTemplates:ae,header:ce,primary:b,requestUpdate:t.requestUpdate});return U`${le}
${ot(_,U`${Bl(t.imageLightbox,t.handleCloseImage)}${this.renderResetConfirmation()}`)}`}}})))()}function WT(e,t){let n=hu(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 GT(e,t,n){let r=e.hello?.auth??null,i=Rn(r)||!n&&De(r,{method:`chat.send`,requiredScope:`operator.write`,sessionScope:!0,session:t}).allowed;return{canCompose:i,canSend:i}}function KT(e,t,n){let r=r=>L(e,{method:`sessions.patch`,params:{key:t,...r},sessionScope:!0,session:n});return{model:r({model:null}),effort:r({thinkingLevel:null}),contextWindow:L(e,{method:`sessions.patch`,params:{key:t,contextWindow:null}}),permission:r({permissionMode:`guarded`}),unarchive:r({archived:!1})}}function qT(e,t,n){let r=!t.archived&&!n;return{canPublishShared:r&&L(e,{method:`sessions.github.publish`,requiredScope:`operator.sessions.write`,session:t}).allowed,canPublishPersonal:r&&Rn(e.hello?.auth??null)}}function JT(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,_=N(t,p),v=ee(t,p).agentId,y=n?.sessionId?.trim(),b=JSON.stringify([p,_.agentId]),x=XT.get(t)??new Map;XT.set(t,x);let S=()=>t.connected&&t.sessionKey===p&&t.client===m&&t.connectionEpoch===g&&N(t,p).agentId===_.agentId,C=()=>{let e=Z(t);return S()&&!!e==!!n&&e?.sessionId===y},w=(e,n=p)=>z(n,p)&&C()&&L({client:t.client,hello:t.hello,phase:t.connected?`connected`:`offline`},{method:`sessions.patch`,params:{key:p,...e},sessionScope:!0,session:Z(t)}).allowed,T=x.get(b);T&&T.expectedSessionId!==y&&(x.delete(b),T=void 0),T?.retainWhileCurrent&&!T.retainWhileCurrent()&&(x.delete(b),T=void 0);let E=T?.ownsSelection()?T:void 0,D=!!(E?.pending||n?.permissionModePending),O=ia({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}),k=t.sessions.think(p,_.agentId),A=t.sessions.settingsPreview(p,_.agentId),j=k||A?{...n,...k?{thinkingLevel:k}:{},...A}:n;return{composerControls:U`
<div class="chat-composer-model-control">
${gf({modelAuthStatusResult:t.modelAuthStatusResult,accountSelection:h,renderAccountSection:e=>gp({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:()=>C()&&t.chatAccountSelection===h,onSelect:n=>a.allowed&&w({model:`${e}@${n.authProfileId}`})?Wu(t,`${e}@${n.authProfileId}`,p):Promise.resolve(!1),onManage:f,onRequestUpdate:()=>t.requestUpdate?.()}),activeRunId:t.chatRunId,activeRunSessionKey:Nf(t),modelObservedRunId:Vf(t,n),agentDefaultModel:r,connected:t.connected,gatewayAvailable:!!t.client,loading:t.chatLoading,modelCatalog:t.chatModelCatalog,modelCatalogState:O,modelOverrides:t.sessions.state.modelOverrides,thinkingSession:j,fastModeTarget:j,contextWindowTarget:A?{...n??t.sessionsResult?.defaults,...A}:void 0,modelSelectionLocked:n?.modelSelectionLocked===!0,modelSelectionTarget:t.sessionsResult?.defaults.modelSelectionTarget,modelPickerOpen:t.chatModelPickerOpenSessionKey===t.sessionKey,modelSwitching:!!t.chatModelSwitchPromises[t.sessionKey],modelsLoading:t.chatModelsLoading,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===Ct({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&&w({fastMode:null},n)?Gs(t,e,n):Promise.resolve(!1),onContextWindowSelect:(e,n)=>s.allowed&&w({contextWindow:e},n)?ih(t,e,n):Promise.resolve(!1),onModelPickerOpen:()=>YC(t),onModelPickerOpenChange:e=>{t.chatModelPickerOpenSessionKey=e?t.sessionKey:null,t.requestUpdate?.()},onModelSelect:(e,n,r)=>a.allowed&&w({model:e,agentRuntime:r},n)?Wu(t,e,n,r):Promise.resolve(!1),onThinkingSelect:(e,n)=>o.allowed&&w({thinkingLevel:e},n)?zc(t,e,n):Promise.resolve(!1)})}
</div>
`,permissionPicker:{canSelectFull:l,defaultMode:i,disabled:!c.allowed,disabledReason:c.allowed?void 0:c.reason,mode:E?E.nextMode:n?.permissionMode,pending:D,onSelect:async e=>{let r=x.get(b);if(!c.allowed||!w({permissionMode:e})||n?.permissionModePending||r?.pending&&r.ownsSelection())return;let i={expectedSessionId:y,nextMode:e??void 0,ownsSelection:C,pending:!0},a=Symbol(b),o=ZT.get(t)??new Map;ZT.set(t,o),o.set(b,a);let s=()=>o.get(b)===a;x.set(b,i),t.requestUpdate?.();try{t.chatError=t.lastError=null;let n=await Mc(t,p,{permissionMode:e},{..._,expectedSessionId:y,canDispatch:()=>w({permissionMode:e})});if(!C())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(!S()||!s())return;let n=t.sessions.capturePermissionObservation(p,v),r=await t.sessions.reconcileMutation(v);if(!C()||!s())return;r.status!==`refreshed`&&(i.pending=!1,i.retainWhileCurrent=n),t.chatError=t.lastError=V(`chat.permissionControls.updateFailed`,{error:String(e)})}finally{s()&&o.delete(b),x.get(b)===i&&i.retainWhileCurrent===void 0&&x.delete(b),S()&&t.requestUpdate?.()}}}}}function YT(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=N(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&&N(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=Yf(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 XT,ZT;function QT(){return(QT=e((()=>{wr(),yr(),y(),di(),Ua(),ji(),O(),Pt(),I(),Is(),Cc(),$u(),$C(),Q(),Rp(),Qd(),Im(),Ju(),xa(),XT=new WeakMap,ZT=new WeakMap})))()}var $T;function eE(){return(eE=e((()=>{wr(),lr(),y(),vt(),I(),so(),Vc(),ah(),jo(),$T=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&&Js(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&&Se(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&&Js(t);t?.connected&&n?.sessionId&&n.providerReview&&(this.binding={state:t,sessionKey:t.sessionKey,sessionId:n.sessionId,agentId:Se(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:uo(),attemptedRunId:null})}reconcileTerminalAttempt(e){if(e.pending||e.refreshing||!e.attemptedRunId)return;let t=Js(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=uo(),e.error=[V(`chat.providerReview.continuationFailed`),t?B(t):null].filter(Boolean).join(` `)}async open(e){if(this.isCurrent(e)&&!e.loading){e.loading=!0,this.host.requestUpdate();try{await ko(()=>import(`./control-ui-core-9qYjK5B2.js`).then(e=>(e.Wr(),e.Gr)),__vite__mapDeps([0,6]),import.meta.url),this.isCurrent(e)&&(e.open=!0)}catch(t){this.isCurrent(e)&&(e.error=B(t))}finally{this.isCurrent(e)&&(e.loading=!1,this.host.requestUpdate())}}}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(!qu(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=Ku(t,e.idempotencyKey);if(qs(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.isCurrent(e)&&(e.pending=!1,this.host.requestUpdate())}}}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.isCurrent(e)&&(e.refreshing=!1,this.host.requestUpdate())}}}notice(){let e=this.readState(),t=e&&Js(e)?.providerReview;if(!t)return W;let n=this.binding,r=!!t.explanation?.trim();return U`
<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?U`<span>${n.error}</span>`:W}
</div>
${r?U`<button class="btn btn--sm" type="button" ?disabled=${!n||n.loading} @click=${()=>n&&void this.open(n)}>${V(`chat.providerReview.review`)}</button>`:W}
</div>
`}dialog(){let e=this.binding;if(!e?.open||!this.isCurrent(e))return W;let{review:t}=e,n=t.canContinue&&!!(t.explanation?.trim()&&t.continuationMessage?.trim()),r=()=>{this.isCurrent(e)&&(e.open=!1,this.host.requestUpdate())};return U`
<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?U`
<h3>${V(`chat.providerReview.continuationTitle`)}</h3>
<p>${V(`chat.providerReview.continuationBody`)}</p>
<blockquote
class="chat-provider-review-dialog__text"
.textContent=${t.continuationMessage}
></blockquote>
`:U`<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?U`<p class="callout danger" role="alert">${e.error}</p>`:W}
${e.submitted&&!e.error?U`<p role="status">${V(e.refreshing?`chat.providerReview.checkingStatus`:`chat.providerReview.waiting`)}</p>`:W}
</div>
<div class="exec-approval-actions">
<button type="button" class="btn" autofocus @click=${r}>
${V(`common.close`)}
</button>
${e.submitted?U`<button type="button" class="btn" ?disabled=${e.refreshing} @click=${()=>void this.refresh(e)}>${V(e.refreshing?`chat.providerReview.checkingStatus`:`chat.providerReview.checkStatus`)}</button>`:W}
${n?U`<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>`:W}
</div>
</section>
</openclaw-modal-dialog>
`}}})))()}function tE({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)=>xs(t,e,n),onGatewayQuestionSkip:e=>Ss(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 nE(){return(nE=e((()=>{Es()})))()}var rE;function iE(){return(iE=e((()=>{wr(),Uh(),Mn(),zn(),yr(),$n(),vs(),Ko(),ps(),y(),Xa(),si(),Qa(),Vi(),Me(),vh(),Pt(),I(),Kb(),Zp(),Hf(),UT(),Fx(),QT(),rT(),_S(),eE(),nE(),CS(),nc(),Tu(),$C(),Q(),g_(),yv(),w_(),_f(),Bf(),Cm(),av(),rE=class extends HT{constructor(...e){super(...e),this.providerReview=new $T(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 U`<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=KT(this.context.gateway.snapshot,e.sessionKey,n),c=Li(e.observerDigest,Bi(n?.key??e.sessionKey,n?.observerDigest)),l=yi({localRunId:e.chatRunId,session:n,digest:c}),u=V_(n?.placement),d=n?.placement,f=u&&this.dismissedWorkspaceConflictRefs.get(n?.key??e.sessionKey)!==u.stagedResultRef?u:void 0,p=this.resolveBoardView(),m=Qw({board:p,layout:e.sidebarLayout,paneWidth:this.paneWidth});e.chatFollowUpMode=mS(e,n,this.context.runtimeConfig.state);let h=X(e),g=R(e.sessionKey),_=g!==null,v=this.context?.overlays,y=this.context.agents.state.agentsList?.agents.find(e=>e.id===h),x=y?.model?.primary,{modelSetupRequired:S,modelUnavailableBanner:C,requiredReason:ee}=Mp({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:x,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=$m(e,e.sessionKey,w!==null),E=$d(e),D=this.sessionParticipationTracker.resolve({catalog:_,listLoading:e.sessionsLoading,sessionKey:`${h??``}\0${e.sessionKey}`,session:n}),O=this.context.gateway.snapshot,k=GT(O,n,_),A=Rn(O.hello?.auth??null),j=this.placementComposerPresentation(n,w!==null),M=e.connected&&!D&&A;this.providerReview.sync(M&&!o);let te=n?.restartRecoveryStatus===`tombstoned`,ne=this.hasMultipleIdentities(),P=ne&&!o&&A&&n?.visibility===`suggest`&&n.sharingRole===`viewer`&&K(O,`session.suggestions.add`)===!0&&K(O,`session.suggestions.list`)===!0,F=!g&&!P?n?.sendDisabledReason??(D?V(`chat.sessionSharing.readOnlyNotice`):null):null,re=g||P?void 0:ee,ie=ne&&A&&!g&&K(O,`session.typing`)===!0&&Wi(this.presencePayload,O.selfUser,O.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}=Px({state:e,sidebarLayout:m,presentationId:this.presentationId,sessionTitle:this.resolveHeaderSessionTitle(n),paneLabel:this.paneLabel,presented:this.presented,gatewaySnapshot:O,setObserverVisibility:this.setSessionObserverVisibility,updateSidebarLayout:e=>this.commitSidebarLayout(e)}),le=$t({snapshotUser:O.selfUser,presenceEntries:Qn(this.presencePayload),presenceInstanceId:O.client?.instanceId});le?.identity?.type===`profile`&&(this.presentationUserId=le.identity.id);let ue=bf({localRunId:e.chatRunId,activeRunIds:n?.activeRunIds,queue:e.chatQueue}),de=g?!!this.catalogCursor:e.chatHistoryPagination.hasMore,fe=YT({getSnapshot:()=>this.context.gateway.snapshot,state:e,sessionParticipationBlocked:D,onDenied:e=>this.publishHeaderError(e),onAbort:()=>void e.handleAbortChat({preserveDraft:!0}),onRewind:e=>this.rewindToMessage(e),onFork:e=>this.forkFromMessage(e)}),I=t=>{e.chatReplyTarget=t,e.handleChatDraftChange(e.chatMessage),e.requestUpdate?.()},pe=this.currentReplyMessageAccess(e.sessionKey),me=g?void 0:JT({state:e,selectedSession:n,agentDefaultModel:x,agentDefaultPermissionMode:y?.defaultPermissionMode,modelAccess:s.model,effortAccess:s.effort,contextWindowAccess:s.contextWindow,permissionAccess:s.permission,canSelectFull:Wn(O.hello?.auth??null),onModelSetup:()=>this.context.navigate(`model-setup`),onProviderSettings:e=>Jp(this.context,h,e),onModelAccounts:()=>this.context.navigate(`profile`)}),he=c_(this.presentationId),ge=bi(this.context.gateway).snapshot,_e=this.captureConnectionScope(),ve=()=>{let t=Z(e);return t&&{...t,agentId:t.agentId??X(e)??void 0,archived:this.isCurrentSessionArchived(e)}},ye=ve();if(!_e||!ye||K(O,`sessions.github.publish`)!==!0||!oi(O,`sessions.github.options`,`operator.read`))this.githubPublication?.detach(),this.githubPublication=null;else{this.githubPublication?.matches(ye)||(this.githubPublication?.detach(),this.githubPublication=this.context.sessions.githubPublication.attach(ye,()=>this.requestUpdate(),gh));let t=this.githubPublication;t?.sync({...qT(O,ye,D),personalReady:!bm(e)&&(!Lr(d?.state)||!!ye.repositoryWorkspaceId&&d?.state===`active`)&&!u,isPresented:()=>this.presented,isCurrent:()=>{let e=ve();return this.isConnectionScopeCurrent(_e)&&e!==void 0&&t?.matches(e)}})}let be=this.sessionDisabledBanner({catalogDisabledReason:ae,modelSetupRequired:S,restartRecoveryTombstoned:te,selectedSessionArchived:o,selectedSessionId:n?.sessionId?.trim()||void 0,selectedSession:n,sessionKey:e.sessionKey,unarchiveAccess:s.unarchive}),L=!g&&cd(e),xe=!r&&be?.kind!==`composer-replacement`&&(g?this.catalogSession?.canContinue===!0:!F&&!(o||te||j.blocksSend)&&(!T||L)),Se={canCompose:k.canCompose&&xe,canSend:k.canSend&&xe,...pS(e,L,!_&&!P),modelRequiredReason:re,disabledReason:ae??(k.canSend?null:V(`chat.sessionSharing.scopeReadOnlyNotice`))??F??j.busyMessage??(j.state.kind===`failed`&&!j.state.recoveryAction?j.failedUnavailableMessage:null)??(e.connected&&(w||L)?null:T),disabledReasonTone:!k.canSend||F||j.busyMessage||D&&!P?`info`:`danger`,disabledReasonBusy:j.busyMessage!==null,disabledBanner:be??j.disabledBanner??C},Ce=M&&Se.canSend&&!g&&!P&&a?this.captureProgressCardRefreshAction():void 0,we=le?.identity?.type===`profile`?le.identity.id:null,Te=!!(g||P||n?.incognito||!we),{gatewayQuestionPrompts:Ee,inlineApproval:De}=this.projectConversationAttention(e,h,!g&&!D),Oe={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&&L,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:!D&&bm(e),runActive:E,runStatus:e.chatRunStatus,startupStatus:Gm(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:pr(this.context.gateway),progressCardInitialLoading:this.progressCardInitialLoading,progressCardRefresh:Ce,collapseTaskProgress:e.settings.chatCollapseTaskProgress===!0,readingHistory:e.chatReadingHistory,onProgressManipulate:()=>{Af(e),this.transcript.cancelScroll()},onDismissProgressCard:a?e=>this.hideProgressCard(e):void 0,onClearSavedProgressCard:M?this.clearSavedProgressCard:void 0,gatewayQuestionPrompts:Ee,asyncQuestionStorage:!g&&!P?this.chatState.composerPersistence.durableScope:null,...tE({state:e,questionState:this.questionPromptState,canSend:Se.canSend&&!g&&!P&&e.connected,isCurrent:()=>this.state===e}),messages:g?this.catalogMessages:e.chatMessages,historyPagination:de||this.loadingOlder?{hasMore:de,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:ue,runUsageById:g?void 0:e.chatRunUsageById,assistantAvatarUrl:jx(e),sendShortcut:e.settings.chatSendShortcut,followUpMode:e.chatFollowUpMode,draft:e.chatMessage,mentions:e.chatMentions,getMentions:()=>e.chatMentions??[],mentionsUnsupported:Te,mentionDirectory:e.connected&&e.client&&!Te&&!D?{client:e.client,ownerKey:JSON.stringify([e.connectionEpoch,we]),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:O.offlineStable,gatewayClient:e.client,composerHoldToRecord:e.settings.composerHoldToRecord,realtimeTalkInputDeviceId:e.settings.realtimeTalkInputDeviceId,onComposerHoldToRecordChange:t=>{e.settings=tn({composerHoldToRecord:t})},onOpenTalkSettings:()=>this.context.navigate(`talk`),onOpenDictationSettings:()=>this.context.navigate(`model-setup`),suggestionComposer:P,typingActors:ne?this.typingActorViews():[],typingOverflow:ne?this.typingOverflow:void 0,onTypingChange:ie?(e,t)=>this.sendTypingState(e,t):void 0,...Se,modelSetupRequired:S&&!o&&!te,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:De,approvalBusy:v?.snapshot?.approvalBusy,approvalCanGrant:v?.snapshot?.approvalCanGrant??!1,approvalErrors:v?.snapshot?.approvalErrors,onApprovalDecision:v&&!D?(e,t)=>v.decideApproval(t,e,De??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:`))),swarm:i?{...i,sessions:this.swarmHydrator?.rows??[]}:void 0,sessionHost:{assistantAgentId:e.assistantAgentId,agentsList:e.agentsList,hello:e.hello},providerUsage:{basePath:e.basePath,modelAuthStatusResult:e.modelAuthStatusResult},composerControls:me?.composerControls??W,permissionPicker:me?.permissionPicker,...this.suggestionChatProps(e.connected,o,ne),messageReactions:this.messageReactions,onReact:this.canReactToCurrentSession()?this.handleMessageReaction:void 0,pullRequests:this.visibleSessionPullRequests,pullRequestsGateway:this.context.gateway,pullRequestsSessionId:n?.sessionId,pullRequestsBranch:this.sessionPullRequestsBranch,pullRequestsStatus:this.sessionPullRequestsStatus,onDismissPullRequest:this.dismissSessionPullRequest,githubRepo:ge.result?this.githubRepo:null,githubRepositories:ge.repositories,onOpenSessionDiff:ce.onOpenDiff,githubPublication:this.githubPublication?.view(),onOpenWorkspaceFile:t=>Wv(e,t),onOpenSessionLink:e=>Yo(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:()=>th(e),getDraft:()=>e.chatMessage,onRequestUpdate:e.requestUpdate,onHistoryKeydown:e.handleChatInputHistoryKey,onSlashIntent:()=>RC(e),onSlashCommand:P||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)=>!Se.canSend||re&&(e.chatAttachments.length>0||!Ja(e.chatMessage))?void 0:g?this.continueCatalogSession(g):P?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:()=>{fS(e),e.requestUpdate?.()},onDismissRealtimeTalkError:()=>{xS(e),e.requestUpdate?.()},onDismissRealtimeTalkInputNotice:()=>{e.realtimeTalkInputNotice=null,e.requestUpdate?.()},onAbort:fe.onAbort,onQueueRemove:e.removeQueuedMessage,onQueueRetry:r?void 0:t=>void e.retryQueuedChatMessage(t),onQueueSteer:D||r?void 0:t=>void e.steerQueuedChatMessage(t),onQueueMove:D?void 0:e.moveQueuedChatMessage,queuedEdit:WT(e,D),goalRecovery:zb(e),onGoalAction:(t,n)=>void Vb(e,{goalId:t,action:n}),goalDraftMode:e.chatGoalDraftMode??null,currentSessionId:e.currentSessionId,onGoalDraftModeChange:t=>{e.chatGoalDraftMode=t,e.handleChatDraftChange(e.chatMessage)},onGoalSubmit:P||g?void 0:(t,n)=>Bb(e,t,n),onCompanionStageAttachment:(n,r)=>this.state===e&&this.connectionGeneration===t&&X(e)===h&&this.stageSessionCompanionAttachment(n,r),replyTarget:e.chatReplyTarget??null,onClearReply:()=>I(null),onSetReply:be?void 0:I,replyMessageAccess:g||o?void 0:pe,onRewindMessage:o?void 0:fe.onRewindMessage,onForkMessage:fe.onForkMessage,agentsList:e.agentsList,currentAgentId:h,fullMessageAgentId:N(e,e.sessionKey).agentId,loadFullAssistantMessage:$w(e,_),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:b({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello}),userId:this.presentationUserId,userName:le?.name??e.userName,userAvatar:le?.avatarUrl??e.userAvatar,personActivity:Qo(this.context),mediaPolicyEpoch:e.mediaPolicyEpoch,connectionEpoch:e.connectionEpoch,embedSandboxMode:e.embedSandboxMode,allowExternalEmbedUrls:e.allowExternalEmbedUrls,fetchLinkFavicon:Rg(e),chatMessageMaxWidth:e.settings.chatMessageMaxWidth,branding:this.context?.theme.branding,assistantAttachmentAuthToken:Qt(e),resolveArtifactDownload:(t,n)=>Ph(e,t,n),basePath:e.basePath,sessionPublicOrigin:qo(this.context),resourceBasePath:e.resourceBasePath};return U`${this.renderChatPaneLayout({state:e,selectedSession:n,currentAgentId:h,board:p,sidebarLayout:m,sessionWorkspace:ce,chatProps:Oe,observerDigest:c,observerRunId:l,catalog:_,agentWorkspace:y?.workspace,workspaceGit:y?.workspaceGit===!0,openPanelSlot:se,closePanelSlot:oe})}${this.providerReview.dialog()}`}}})))()}function aE(){return(aE=e((()=>{iE(),customElements.get(`openclaw-chat-pane`)||customElements.define(`openclaw-chat-pane`,rE)})))()}function oE(){return{pathname:window.location.pathname,search:window.location.search,hash:window.location.hash}}function sE(e,t){return e.pathname===t.pathname&&e.search===t.search&&e.hash===t.hash}function cE(e,t){if(!e)return!1;let n=oE();if(sE(n,e))return!0;let r=new URLSearchParams(e.search).has(`draft`),i=new URLSearchParams(n.search).has(`draft`);return t&&r&&!i&&sE(B_(n),B_(e))}function lE(){return(lE=e((()=>{iv()})))()}var uE;function dE(){return(dE=e((()=>{I(),uE=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 fE(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=xv(o,n,r),c=sv(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 pE;function mE(){return(mE=e((()=>{ad(),kv(),pE=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()&&ff(e.dataTransfer)&&(this.dragDepth+=1)},this.handleDragOver=e=>{if(!this.options.sessionSplitAvailable()||!ff(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=fE(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()&&ff(e.dataTransfer)&&(this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&this.clear())},this.handleDrop=e=>{if(!this.options.sessionSplitAvailable()||!ff(e.dataTransfer))return;e.preventDefault();let t=vd(e.dataTransfer),n=(e.target instanceof Element?e.target:null)?.closest(`openclaw-chat-pane, [data-unbound-pane-id]`),r=n&&this.host.contains(n)?fE(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 hE(e,t,n){return!!(t&&n&&S({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello},t.sessionKey,n.sessionKey,n.agentId,t.agentId))}function gE(e,t){if(!p(t?.sessionKey)||!t.agentId?.trim())return t;let n=_E(e,t.sessionKey,t.agentId);if(n===t.sessionKey)return t;let r=yE.get(t);return r?.sessionKey!==n&&(r={sessionKey:n,value:{...t,sessionKey:n}},yE.set(t,r)),r.value}function _E(e,t,n){return p(t)&&n?.trim()&&_({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})?vo({agentId:n,mainKey:b({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello})}):t}function vE(e,t,n,r=!1,i,o){let s=a(e,o??t?.agentId),c=t&&S({agentsList:e.agents.state.agentsList,hello:e.gateway.snapshot.hello,assistantAgentId:s},t.sessionKey,n,p(n)?s:void 0,t.agentId),l=i??t?.face??`chat`;i===void 0&&!c&&(l=w(e,n,o??t?.agentId));let u=_e({context:e,face:l,preferenceDerivedFace:i===void 0&&!c,sessionKey:n,agentId:o??t?.agentId,shortIdLength:t?.sessionKey===n?t.shortId?.length:void 0}).options,d=r&&c&&(t.draft||t.focusComposer)?B_(oE(),u):u;e[r?`replace`:`navigate`](l,d)}var yE;function bE(){return(bE=e((()=>{P(),I(),lE(),iv(),yE=new WeakMap})))()}function xE(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||!ar(e,i))&&r.add(JSON.stringify([a,i]))}return r}function SE(e){let t=e.context?.sessions?.presentation.result?.sessions??[];return U`
<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`:W}
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?U`
<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?U`<button class="btn" @click=${()=>e.onClosePane?.(e.pane.id)}>${V(`chat.splitView.closePane`)}</button>`:W}
</div>
`:W}
${e.sessionSlots.map(n=>{if(n===void 0||e.unbound)return W;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?Kv(e.data,e.consumedDraftData,n):void 0,c=Ce(n,e.context?.gateway?.snapshot?.hello)||n,l=t.find(e=>z(e.key,c)),u=l?le(c,l):void 0;return e.context&&ar(e.context,n)?Or(n,U`<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}
></openclaw-pending-session-create>`):Or(n,U`<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?tt(n)?.agentId:void 0}
.routeLoadingSkeleton=${o?.routeLoadingSkeleton??Cr}
.presented=${i}
.visuallyPresented=${i}
.active=${a}
.draft=${s}
.focusComposer=${e.draftFocus.shouldFocusPane(a,s,n,e.data)}
.dashboardExpanded=${o?o.dashboardExpanded===!0:Cr}
.routeFace=${o?o.face??`chat`:Cr}
.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 CE(e,t){let n=t.activePaneId!==void 0&&h_(e,t.activePaneId)!==null;return U`
<div
class="chat-split-view ${t.narrow?`chat-split-view--narrow`:``} ${n?`chat-split-view--active-cell`:``}"
>
${Tr(e.columns,e=>e.id,(n,r)=>U`
<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:to(e.columnWeights[r],`rendered split column weight`)} 1 0"
>
${Tr(n.panes,e=>e.id,(e,r)=>U`
${t.renderPane(n,e,to(n.paneWeights[r],`rendered split pane weight`))}
${!t.narrow&&r<n.panes.length-1?U`
<resizable-divider
orientation="horizontal"
.splitRatio=${O_(n.paneWeights,r,`split pane weight`)}
.minRatio=${.15}
.maxRatio=${.85}
.label=${V(`nav.resize`)}
@resize=${e=>t.onResizePanes(n.id,r,e.detail.splitRatio)}
@resize-end=${t.onResizeEnd}
></resizable-divider>
`:W}
`)}
</div>
${!t.narrow&&r<e.columns.length-1?U`
<resizable-divider
.splitRatio=${O_(e.columnWeights,r,`split column weight`)}
.minRatio=${.15}
.maxRatio=${.85}
.label=${V(`nav.resize`)}
@resize=${e=>t.onResizeColumns(r,e.detail.splitRatio)}
@resize-end=${t.onResizeEnd}
></resizable-divider>
`:W}
`)}
</div>
`}function wE(e,t){return U`<div class="chat-split-view__drop-container">
${e}${t?U`<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>`:W}
</div>`}function TE(e,t,n){return n?U`<openclaw-pending-session-create
.context=${e}
.sessionKey=${t}
></openclaw-pending-session-create>`:W}function EE(){return(EE=e((()=>{Do(),wr(),Pr(),br(),kr(),y(),Fe(),Pt(),I(),iv(),Hg()})))()}var DE;function OE(){return(OE=e((()=>{Ch(),Hg(),DE=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&&xh(this.gateway).unwatch(this.owner),this.gateway=i,i&&xh(i).watch(this.owner,N_(t,n).filter(e=>!r.has(e.id)).map(e=>e.sessionKey))}dispose(){this.gateway&&=(xh(this.gateway).unwatch(this.owner),null)}}})))()}var kE;function AE(){return(AE=e((()=>{So(),Mr(),En(),en(),dn(),$n(),cr(),In(),I(),ge(),r(),lE(),dE(),mE(),bE(),EE(),Bx(),bx(),Q(),OE(),ay(),aE(),tv(),iv(),Pl(),Uv(),K_(),Hg(),kE=class extends d{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?gE(this.context,this.data):this.data}get singleBoundPane(){let e=this.layout?i_(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=hn()?.surface===`conversation`,this.mediaQuery=null,this.mobileNavMediaQuery=null,this.consumedDraftData=null,this.draftFocus=new Y_(this),this.messageCache=new Map,this.snapshotStore=new Lv(this.messageCache),this.classicColumnId=`c1`,this.classicPaneId=`p1`,this.routeHref=``,this.closeFocus=new uE(this),this.sessionDrop=new pE(this,{sessionSplitAvailable:()=>this.sessionSplitAvailable,narrow:()=>this.narrow,applySessionDrop:(e,t,n)=>this.applySessionDrop(e,t,n)}),this.mcpAppUnmountGate=new tr(this),this.viewerPresence=new DE(this),this.retainedSessions=new zx(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=_E(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=gE(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=i_(o).find(e=>e.sessionKey===i);if(!t)return;e.preventDefault(),this.closeSplitPane(o,t.id);return}let s=s_(o,{...t,sessionKey:i},n?_E(this.context,n,r):void 0);if(s===o)return;e.preventDefault(),this.persistLayout(s);let c=s&&h_(s,s.activePaneId)?.pane;c&&this.updateRouteToPane(c)},this.handleFocusPane=(e,t)=>{let n=this.layout;if(!(this.presented||t===`review-edit`)||!n||n.activePaneId===e)return;let r=h_(n,e)?.pane;r&&(this.persistLayout(Mg(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=h_(a,e)?.pane;return!o||!z(o.sessionKey,t)?!1:(this.layout&&p(i)&&ue({agentsList:this.context.agents.state.agentsList,hello:this.context.gateway.snapshot.hello},o.sessionKey)&&(i=o.sessionKey),this.layout?o.sessionKey===i||(this.persistLayout(j_(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=h_(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(Mg(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 rt(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 vv(this,this.messageCache,this.snapshotStore,()=>this.context))}connectedCallback(){super.connectedCallback(),this.toggleAttribute(`data-native-conversation`,this.nativeConversation),this.snapshotStore.connect(),$l(this.messageCache,this.snapshotStore),this.routeHref=window.location.href,this.layout=this.nativeConversation?void 0:Hn().chatSplitLayout,this.retainedSessions.restore(this.layout?i_(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(on()),this.mergedChrome=this.resolveMergedChrome(this.mobileNavMediaQuery.matches),this.mobileNavMediaQuery.addEventListener(`change`,this.handleMobileNavViewportChange),this.sessionDrop.connect(),window.addEventListener(qn,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(qn,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();_x(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?h_(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&&cE(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&&cE(n.canonicalLocationSource,this.consumedDraftData===n)&&this.context.replace(n.face??`chat`,this.consumedDraftData===n?B_(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 Tn(t,this.closest(`.shell--onboarding`)!==null)}syncRouteToActivePane(){let e=this.layout,t=this.paneData?.sessionKey?.trim();if(!e||!t||this.pendingCreate)return;let n=h_(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)&&hE(this.context,this.unboundRoute,this.paneData))&&(this.retainedSessions.bindPane(n.id),this.persistLayout(j_(e,n.id,t))))}syncRouteBindings(e=this.data?.agentId){if(!this.presented||this.pendingCreate)return;let t=this.layout&&h_(this.layout,this.layout.activePaneId)?.pane,n=(t?.sessionKey??this.data?.sessionKey)?.trim();this.context&&n&&(!t||!this.retainedSessions.unboundPaneIds.has(t.id))&&kx(this.context,n,e)}adoptPaneNavigation(e,t,n){!this.layout||p(t)&&!n?.trim()||(this.retainedSessions.bindPane(e),this.unboundRoute=void 0,this.persistLayout(j_(this.layout,e,_E(this.context,t,n)),n))}persistLayout(e,t){this.layout=e,tn({chatSplitLayout:this.singleBoundPane?void 0:e}),this.syncRouteBindings(t)}updateRoute(e,t=!1,n,r){this.presented&&vE(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(gE(this.context,this.data)?.sessionKey),a=this.layout?t:this.classicPaneId,o=h_(i,a)?.pane;if(o&&(this.layout||o.sessionKey)){if(n.kind===`center`){if(o.sessionKey===r)return;let e=Mg(i,a);this.persistLayout(j_(e,a,r)),this.updateRoute(r,!0);return}this.persistLayout(Xg(i,a,r,n.edge)),this.updateRoute(r,!0)}}handleSplit(e,t){let n=this.layout??this.classicLayout(gE(this.context,this.data)?.sessionKey?.trim()),r=h_(n,e)?.pane;r?.sessionKey&&this.persistLayout(Xg(n,e,r.sessionKey,t))}closeSplitPane(e,t){if(this.singleBoundPane)return;let n=this.closeFocus.capture(t),r=i_(e).find(e=>e.id!==t);this.retainedSessions.discardPane(t);let i=u_(e,t,this.retainedSessions.unboundPaneIds);if(!i&&r){let t=h_(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?h_(i,i.activePaneId)?.pane:r;a&&(this.updateRouteToPane(a),n&&this.closeFocus.schedule(n,a,i))}classicLayout(e=this.data?.sessionKey?.trim()??``){return Jg(this.classicColumnId,this.classicPaneId,e)}renderSplitLayout(e,t,n){return CE(e,{narrow:this.narrow,activePaneId:t&&this.conversationPresented?e.activePaneId:void 0,renderPane:(r,i,a)=>SE({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.retainedSessions.unboundPaneIds.has(i.id),weight:a}),onResizePanes:(e,t,n)=>{this.layout=this.layout?ty(this.layout,e,t,n):void 0},onResizeColumns:(e,t)=>{this.layout=this.layout?b_(this.layout,e,t):void 0},onResizeEnd:()=>this.persistLayout(this.layout)})}render(){if(this.pendingCreate)return this.mcpAppUnmountGate.render(`pending-create`,()=>TE(this.context,this.data.sessionKey,this.conversationPresented),()=>[...this.querySelectorAll(`openclaw-chat-pane`)]);let e=this.layout??this.classicLayout(),t=this.retainedSessions.retain(i_(e)),n=xE(this.context,e,t),r=()=>wE(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??``)))}},J([yo({context:_r,subscribe:!0})],kE.prototype,`context`,void 0),J([G({attribute:!1})],kE.prototype,`data`,void 0),J([G({attribute:!1})],kE.prototype,`navDrawerOpen`,void 0),J([G({type:Boolean})],kE.prototype,`presented`,void 0),J([Dr()],kE.prototype,`layout`,void 0),J([Dr()],kE.prototype,`narrow`,void 0),J([Dr()],kE.prototype,`mergedChrome`,void 0),customElements.get(`openclaw-chat-page`)||customElements.define(`openclaw-chat-page`,kE)})))()}export{Qy as A,hy as B,Cb as C,wb as D,db as E,Iy as F,py as H,Uy as I,Ky as L,ub as M,By as N,Ab as O,Gy as P,my as R,kb as S,Eb as T,uy as U,dy as V,Z as _,Yw as a,xb as b,Gw as c,KS as d,qx as f,Q as g,Wx as h,LT as i,lb as j,sb as k,GS as l,Gx as m,aE as n,rT as o,Ux as p,RT as r,Jw as s,AE as t,JS as u,Sb as v,Ib as w,Ob as x,bb as y,gy as z};