local-operator-ui 0.34.53 → 0.34.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/main/index.js +15 -9
- package/out/renderer/assets/{_basePickBy-CvpcKweF.js → _basePickBy-CjlcNifv.js} +1 -1
- package/out/renderer/assets/{_baseUniq-D1oOSrqB.js → _baseUniq-o0KeBMbn.js} +1 -1
- package/out/renderer/assets/{agent-details-page-Dbd7Qqbd.js → agent-details-page-B_mPfefi.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-hB4xULfK.js → agent-hub-page-BYHsrmlA.js} +1 -1
- package/out/renderer/assets/{agents-page-DfuX5-79.js → agents-page-DOt4Ktjv.js} +3 -3
- package/out/renderer/assets/{arc-BajJ7pje.js → arc-DFVKfWQu.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-IEHRJDOE-D1-CNSAD.js → architectureDiagram-IEHRJDOE-vpPdmlx-.js} +1 -1
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-CD5T8WZA.js → blockDiagram-JOT3LUYC-R2vBVEG1.js} +1 -1
- package/out/renderer/assets/{browser-page-DbFH9sog.js → browser-page-BpsxcPyu.js} +1 -1
- package/out/renderer/assets/{browser-webauthn-prompt-DW800ko_.js → browser-webauthn-prompt-DbKuqaik.js} +1 -1
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-COKPfAva.js → c4Diagram-VJAJSXHY-BdEM26t6.js} +1 -1
- package/out/renderer/assets/channel--0Jo_Ezu.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-iSOGNS5q.js → chunk-4BMEZGHF-BoFwJNuc.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-B7eDvfbn.js → chunk-A2AXSNBT-ho2uDxLt.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-CTtvvIx6.js → chunk-AEK57VVT-TPmT1lR6.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-D89NRhvc.js → chunk-D6G4REZN-DLDnsndg.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-D9-5Iwp7.js → chunk-RZ5BOZE2-CogvS2RR.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-Cdyx-enm.js → chunk-XZIHB7SX-BX6k9Ig_.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-BTAknOfl.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-BTAknOfl.js +1 -0
- package/out/renderer/assets/clone-AE7GdVaL.js +1 -0
- package/out/renderer/assets/{conversation-input-sync-Dlf10JWF.js → conversation-input-sync-_j7A_EDF.js} +251 -251
- package/out/renderer/assets/{dagre-OKDRZEBW-hOluomAX.js → dagre-OKDRZEBW-CnWKvNVv.js} +1 -1
- package/out/renderer/assets/{diagram-SSKATNLV-BWdY9OnP.js → diagram-SSKATNLV-CnaQJTb1.js} +1 -1
- package/out/renderer/assets/{diagram-VNBRO52H-CUZoZ2hJ.js → diagram-VNBRO52H-C0X5Htj5.js} +1 -1
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-BaXRnwVj.js → erDiagram-Q7BY3M3F-BlWSXVBt.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-D3gvS8EU.js → flowDiagram-4HSFHLVR-CSMU0Hc_.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-DRKxbsB1.js → ganttDiagram-APWFNJXF-OuBtu3nI.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-B-6CMRoo.js → gitGraphDiagram-7IBYFJ6S-z8O9AgtQ.js} +1 -1
- package/out/renderer/assets/{graph-Bvgoe8Zc.js → graph-DE2ohxxG.js} +1 -1
- package/out/renderer/assets/{index-DWZ82U8c.js → index-BcVwaP5j.js} +1 -1
- package/out/renderer/assets/{index-dNBOt_b9.js → index-EI_2-v5u.js} +4 -4
- package/out/renderer/assets/{index-Bg8G2adf.js → index-QCa7n3qU.js} +1 -1
- package/out/renderer/assets/{infoDiagram-PH2N3AL5-g5rZp0e7.js → infoDiagram-PH2N3AL5-a0rOJyNn.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-CyyN61cm.js → journeyDiagram-U35MCT3I-BaWlQxzG.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-BcYjcFGg.js → kanban-definition-NDS4AKOZ-ISbUCJsb.js} +1 -1
- package/out/renderer/assets/{layout-DIrLHdoU.js → layout-Cq5p0Yo5.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-C4087qcZ.js → legacy-agents-page-w-ygCimA.js} +1 -1
- package/out/renderer/assets/{mermaid.core-TBXZ6m8l.js → mermaid.core-BZ_OD6fR.js} +5 -5
- package/out/renderer/assets/{mesh-page-Z6_brJoS.js → mesh-page-GPZRPR4j.js} +1 -1
- package/out/renderer/assets/{mindmap-definition-ALO5MXBD-CDtMt6Do.js → mindmap-definition-ALO5MXBD-CAnWrx3w.js} +1 -1
- package/out/renderer/assets/{mini-DDoFzOhf.js → mini-CQ7ORVw7.js} +1 -1
- package/out/renderer/assets/{org-access-BVkMTwKq.js → org-access-CkXCfgnJ.js} +1 -1
- package/out/renderer/assets/{org-surface-gate-CV-1baVy.js → org-surface-gate-CnNhHebI.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-gmMGr-ui.js → pieDiagram-IB7DONF6-CrxsZY1R.js} +1 -1
- package/out/renderer/assets/{projects-page-B4mpUcqQ.js → projects-page-ygyrTO2Y.js} +1 -1
- package/out/renderer/assets/{publication-validation-cIO-Z0gj.js → publication-validation-CfKQMeAn.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-Ctwtym9P.js → quadrantDiagram-7GDLP6J5-FDR-PDld.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-CApF2ugX.js → radar-MK3ICKWK-BNPTl6F1.js} +1 -1
- package/out/renderer/assets/{radient-auth-buttons-B1WkSc0e.js → radient-auth-buttons-eShZasz1.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-DB3NXRpA.js → requirementDiagram-KVF5MWMF-DYSZWyII.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-lcLgzHR-.js → sankeyDiagram-QLVOVGJD-0ynlxxtV.js} +1 -1
- package/out/renderer/assets/{schedules-page-ByfZ04x2.js → schedules-page-5j5ANXIf.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-C92s7I-3.js → sequenceDiagram-X6HHIX6F-Dw4Xe-1g.js} +1 -1
- package/out/renderer/assets/{settings-page-DaWmx0G_.js → settings-page-rEYr23iA.js} +1 -1
- package/out/renderer/assets/{stateDiagram-DGXRK772-D1MupxMG.js → stateDiagram-DGXRK772-C4hZ7GES.js} +1 -1
- package/out/renderer/assets/{stateDiagram-v2-YXO3MK2T-BsNwRWuq.js → stateDiagram-v2-YXO3MK2T-77mQmjut.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-SK8QkNlF.js → timeline-definition-BDJGKUSR-BuKwQy9m.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-Bik5KhXj.js → use-download-agent-mutation-CHYPRtS_.js} +1 -1
- package/out/renderer/assets/{use-memberships-query-CXnke9-r.js → use-memberships-query-DG-_x04X.js} +1 -1
- package/out/renderer/assets/{use-session-snapshot-D20-nQEA.js → use-session-snapshot-CdDuQ-c-.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-_YTSS36c.js → xychartDiagram-VJFVF3MP-Da65s1FG.js} +1 -1
- package/out/renderer/index.html +2 -2
- package/out/renderer/mini.html +3 -3
- package/package.json +2 -2
- package/out/renderer/assets/channel-5khbBi1K.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-B_cQ6qiw.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-B_cQ6qiw.js +0 -1
- package/out/renderer/assets/clone-DUh4Smnq.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./agent-details-page-
|
|
2
|
-
import{r as g,j as c,c as T,b as $e,i as GA,p as U$,y as G$,o as V$,t as x,z as W1,L as Ro,A as W$,a as $$,R as z$}from"./index-C9huVbt8.js";import{ar as Ce,dV as q$,dW as $1,dX as Bw,c9 as _b,bE as qh,c7 as Va,bM as Hk,C as fs,ah as ba,ai as Ss,a4 as zt,aG as Kn,aH as Ls,u as nn,a3 as su,aN as k0,ca as K$,aO as T0,dY as w4,dZ as Y$,a as Bn,c as yt,e as R0,d_ as ym,d$ as X$,e0 as Q$,e1 as J$,e2 as Z$,aK as C4,aJ as Jr,e3 as Uk,e4 as cl,e5 as hy,e6 as fy,dj as xl,cb as Gk,cL as Gl,cu as Sb,ct as ez,cs as Ys,cv as ln,e7 as y4,e8 as tz,e9 as z1,d as xt,cB as Vk,cX as nz,Z as Hi,ay as Ba,D as Wk,ea as VA,eb as sz,ec as rz,ed as q1,ee as iz,ef as az,eg as oz,eh as lz,aC as Kh,ei as WA,ej as $A,ek as cz,el as uz,em as dz,en as _4,eo as hz,ep as fz,eq as S4,er as jw,es as Hw,et as pz,eu as gz,ev as mz,ew as zA,ex as vz,ey as Bh,ez as E4,eA as bz,eB as xz,eC as wz,eD as Cz,eE as yz,eF as _z,eG as Sz,eH as k4,eI as Ez,eJ as kz,a0 as bi,eK as T4,eL as Tz,eM as qA,eN as Rz,eO as Az,eP as Ui,eQ as Uw,eR as R4,eS as Fz,eT as Dz,eU as KA,eV as Pz,eW as Iz,aP as np,eX as Nz,eY as Mz,eZ as Oz,bm as A4,e_ as Lz,e$ as Bz,f0 as jz,dQ as F4,f1 as Hz,bD as Bo,f2 as Uz,f3 as Gz,bC as bd,f4 as zc,f5 as Vz,ad as $k,f6 as YA,f7 as Wz,f8 as $z,f9 as zz,fa as qz,fb as Kz,fc as Yz,fd as Rh,cP as Xz,fe as Qz,ff as Jz,cS as Zz,fg as Gw,fh as K1,fi as Vw,fj as eq,fk as tq,fl as nq,fm as sq,at as ed,fn as py,_ as D4,fo as P4,aR as I4,aT as pa,fp as zk,bq as N4,aL as qk,cM as Ww,fq as M4,bI as qc,cg as $w,fr as rq,ch as zw,bA as xd,fs as iq,ft as aq,fu as oq,fv as lq,fw as cq,fx as uq,fy as dq,fz as hq,fA as XA,fB as fq,fC as pq,fD as Kk,fE as QA,cU as gq,fF as mq,fG as O4,fH as vq,fI as bq,fJ as L4,fK as Y1,fL as xq,b as B4,fM as Yh,fN as sp,fO as wq,fP as Yk,br as Cq,fQ as yq,fR as _q,fS as Sq,fT as JA,fU as Eq,fV as qw,fW as kq,fX as Tq,fY as j4,fZ as H4,f_ as Rq,f$ as U4,g0 as tx,g1 as Aq,g2 as Fq,g3 as Dq,g4 as Pq,g5 as Iq,g6 as Nq,g7 as Mq,av as ls,g8 as Oq,au as Ac,g9 as G4,ga as V4,gb as Lq,gc as Bq,gd as jq,cj as Kw,ck as Yw,ge as Xw,gf as xa,gg as Hq,gh as kn,gi as en,gj as A0,gk as _m,gl as Qw,gm as Xk,gn as Jw,go as Uq,gp as Gq,gq as Vq,gr as fn,gs as Sm,gt as W4,gu as ra,gv as wd,gw as Wq,gx as $q,gy as zq,gz as qq,gA as ZA,gB as Kq,gC as Yq,gD as Xq,ci as Qq,gE as Jq,gF as Xh,gG as $4,gH as z4,gI as Qk,gJ as nx,gK as q4,V as Jk,gL as X1,gM as Zk,gN as gy,gO as Zq,gP as eK,gQ as tK,gR as jh,gS as Q1,gT as K4,gU as nK,gV as Y4,gW as sK,gX as rK,gY as iK,gZ as aK,g_ as oK,g$ as lK,h0 as cK,h1 as uK,h2 as dK,h3 as hK,h4 as sx,h5 as fK,h6 as pK,h7 as gK,h8 as mK,h9 as vK,ha as bK,hb as eT,hc as xK,hd as X4,I as nt,he as wK,hf as Zw,hg as rp,bL as Q4,bP as CK,hh as eF,bh as J4,hi as yK,hj as _K,hk as SK,hl as EK,hm as kK,hn as TK,aA as Er,ho as RK,hp as AK,hq as FK,hr as DK,hs as PK,ht as IK,hu as NK,hv as MK,hw as OK,hx as LK,hy as BK,hz as jK,hA as Z4,hB as eC,hC as eB,hD as tT,hE as Ef,hF as tC,hG as nT,hH as HK,hI as UK,hJ as GK,hK as tB,hL as VK,hM as tF,hN as WK,hO as sT,hP as $K,hQ as rT,hR as F0,hS as D0,hT as zK,hU as nB,hV as Em,hW as qK,hX as KK,hY as YK,hZ as XK,h_ as QK,h$ as JK,i0 as nF,i1 as sB,ce as rB,i2 as ZK,i3 as eY,i4 as tY,aS as nC,i5 as nY,i6 as sY,i7 as sF,i8 as rY,i9 as iY,ia as iB,ib as rF,ic as aY,id as oY,ie as lY,ig as aB,ih as my,ii as cY,ij as oB,bz as Og,ik as iT,dF as uY,il as dY,bO as aT,im as Lc,io as oT,ip as lB,iq as hY,bv as fY,bw as sC,bt as kf,ir as cB,is as pY,it as uB,iu as dB,cr as vy,aI as P0,iv as iF,iw as gY,ix as rx,iy as aF,iz as mY,iA as vY,iB as bY,iC as xY,iD as hB,iE as wY,iF as oF,c3 as Ah,iG as CY,iH as yY,iI as _Y,iJ as SY,iK as fB,c4 as EY,iL as kY,iM as TY,iN as RY,iO as AY,iP as FY,dc as DY,iQ as PY,iR as lT,iS as IY,iT as NY,iU as bv,iV as pB,iW as J1,a8 as lF,iX as MY,iY as OY,iZ as LY,i_ as td,de as gB,df as cT,i$ as BY,j0 as jY,j1 as HY,j2 as mB,cc as UY,j3 as cF,ae as uF,j4 as GY,j5 as vB,j6 as VY,j7 as Lg,j8 as WY,bH as bB,j9 as $Y,ja as dF,jb as zY,jc as qY,bj as hF,bk as fF,bl as pF,aB as KY,jd as YY,je as XY,jf as QY,jg as JY,jh as dh,ji as hh,jj as ZY,jk as eX,jl as tX,jm as nX,jn as xB,jo as sX,jp as wB,jq as Z1,jr as eS,js as by,jt as rX,ju as iX,jv as Fh,jw as aX,aq as ix,as as CB,aw as oX,aa as gF,jx as lX,jy as cX,jz as uX,jA as dX,jB as hX,jC as fX,jD as pX,jE as yB,jF as gX,jG as tS,jH as _B,jI as SB,jJ as mX,jK as vX,jL as bX,jM as xX,jN as EB,jO as ip,jP as wX,jQ as CX,jR as uT,bn as yX,jS as _X,jT as SX,jU as EX,jV as kX,jW as TX,jX as RX,jY as AX,jZ as FX,j_ as DX,j$ as PX,bi as IX,k0 as mF,k1 as NX,k2 as xy,k3 as vF,k4 as MX,k5 as OX,k6 as LX,k7 as BX,k8 as jX,k9 as HX,ka as UX,kb as GX,kc as VX,kd as WX,ke as $X,kf as zX,kg as qX,kh as KX,ki as bF,kj as YX,kk as XX,al as QX,am as JX,an as ZX,ao as eQ,ap as tQ,kl as nQ,km as sQ,kn as rQ,ko as iQ,kp as aQ,kq as oQ,kr as lQ,ax as cQ,ks as uQ,kt as dQ,ku as hQ,kv as xF,cT as kB,kw as dT,kx as fQ,aQ as TB,ky as RB,kz as pQ,kA as gQ,kB as AB,kC as mQ,kD as kr,kE as vQ,kF as bc,kG as FB,kH as DB,kI as PB,kJ as hT,kK as Ri,kL as bQ,kM as xQ,kN as wQ,kO as CQ,kP as yQ,kQ as _Q,kR as SQ,kS as EQ,kT as kQ,kU as TQ,kV as RQ,kW as IB,kX as AQ,kY as FQ,kZ as DQ,k_ as PQ,k$ as IQ,l0 as nS,l1 as NQ,l2 as MQ,l3 as wF,l4 as NB,l5 as OQ,l6 as LQ,l7 as BQ,l8 as CF,l9 as jQ,la as HQ,lb as UQ,lc as GQ,ld as VQ,le as WQ,lf as $Q,lg as zQ,lh as MB,li as qQ,lj as KQ,db as ax,lk as YQ,d6 as XQ,ll as yF,lm as QQ,ln as JQ,lo as ZQ,cH as eJ,cZ as tJ,lp as nJ,lq as sJ,lr as rJ,B as OB,cY as _F,ls as iJ,af as aJ,bB as Vl,lt as oJ,lu as lJ,lv as cJ,lw as ri,aU as SF,lx as ox,ly as uJ,lz as EF,lA as dJ,lB as wy,lC as Cy,lD as kF,lE as yy,lF as TF,lG as LB,lH as BB,lI as jB,lJ as hJ,aD as fJ,aE as pJ,lK as gJ,aF as mJ}from"./conversation-input-sync-Dlf10JWF.js";import{c as ft,af as vJ,ag as HB,ah as bJ,ai as xJ,aj as wJ,ak as CJ,al as yJ,am as _J,an as Up,ao as SJ,e as ru,S as pn,p as Qa,u as Et,B as ce,L as nr,I as ps,T as fT,g as Bs,X as Dn,ap as sS,aq as wl,D as Wl,a as $l,d as jo,y as ga,x as pi,o as I0,h as Tf,ae as rC,l as Je,a0 as ap,b as iC,A as Kr,f as aC,F as km,G as Tm,H as Rm,J as Am,K as Fm,q as Il,r as Ho,s as Nl,t as rS,v as Yr,w as Gt,ar as N0,as as EJ,at as kJ,z as Ml,ac as UB,au as iS,av as TJ,aw as RJ,ax as AJ,Y as GB,Z as VB,_ as aS,k as Eb,ad as FJ,a1 as Dm,a2 as WB,a3 as Rf,ay as Qh,az as DJ,M as RF,i as $B,aA as PJ,j as zB,aB as IJ,aC as AF,a4 as NJ,aa as oS,C as MJ,aD as Gp,aE as pT,N as gT,$ as OJ,a5 as LJ,a6 as BJ,a7 as jJ,a8 as HJ,a9 as UJ,aF as GJ,aG as VJ,aH as WJ,aI as $J,aJ as qB,m as FF,n as DF,E as zJ}from"./error-boundary-BCQ7FGQc.js";import{e as op,g as KB,s as qJ,t as KJ,v as lS,w as cS,x as YJ,u as qe,y as YB,z as XB,A as oC,S as XJ,B as QB,C as QJ,R as JJ,E as ZJ,F as Cl,G as PF,H as eZ,I as tZ,J as nZ,M as IF,L as lC,N as sZ,O as rZ,Q as mg,U as iZ,V as JB,W as aZ,X as NF,Y as MF,Z as oZ,_ as OF,$ as lZ,a0 as Eu,a1 as xv,a2 as cZ,a3 as uZ,a4 as dZ,a5 as LF,a6 as BF,a7 as hZ,a8 as fZ,a9 as pZ,aa as gZ,ab as jF,ac as HF,ad as UF,ae as mZ,af as vZ,ag as bZ,ah as xZ,ai as wZ,aj as GF,ak as CZ,al as yZ,am as VF,an as _Z,ao as SZ,ap as EZ,aq as kZ,ar as TZ,as as RZ,at as ZB,r as WF,au as AZ,T as FZ,av as DZ,aw as PZ,ax as IZ,ay as wv,az as Cv,aA as $F,aB as yv,aC as _v,aD as zF,aE as qF,aF as NZ,aG as kb,aH as MZ,aI as OZ,aJ as LZ,aK as BZ,aL as KF,aM as jZ,aN as HZ,aO as YF,aP as UZ}from"./ui-preferences-store-BSjv1eml.js";import{C as GZ}from"./console-mirror-D4VUczn2.js";const uS=8e3,e6=1e4;function VZ(e){return e?`“${e}”`:"Conversation"}const WZ="archived.";function $Z(e){return Ce.getState().archiveFacts[e]}function zZ(e){const t=Ce.getState(),n=t.archiveFacts[e];return n?n.archived:t.sessions.find(s=>s.session_id===e)?.archived}function qZ(){const e=Ce(t=>t.archiveUndo);g.useEffect(()=>{if(e===null)return;let t=!1;const n=()=>{t||(t=!0,r())},s=()=>{n();const i=Ce.getState().archiveUndo;i!==null&&i.sessionId===e.sessionId&&i.at===e.at&&Ce.getState().setArchiveUndo(null)},r=Ce.subscribe(()=>{const i=$Z(e.sessionId);i!==void 0&&!i.answered||q$(e.archived,zZ(e.sessionId))||s()});return n},[e])}function KZ(e){return e===1?"Draft":`${e} drafts`}const YZ="discarded.",XZ=e=>{const t=$1(e),n=t.length,s=t.filter(o=>!o.active).length,r=n===1?"chat":"chats",i=e.filter(o=>Bw(o)!==null&&$1([o]).length===0).length,a=[`Mark ${n} unread ${r} as read${s>0?`, including ${s} in Previous chats`:""}.`];return i>0&&a.push(`${i} unread ${i===1?"mark":"marks"} with no completion token cannot be cleared.`),{count:n,label:`Mark all ${n} read`,scope:a.join(" "),nameSuffix:s>0?`, including ${s} in Previous chats`:""}},t6=e=>e===1?"1 lives on another device and clears when that device updates.":`${e} live on other devices and clear when those devices update.`,QZ=e=>{if(e.attempted===0)return{tone:"success",message:"Nothing to clear."};const t=e.unknown-e.deferred,n=[e.superseded>0?`${e.superseded} ${e.superseded===1?"has a newer result and stays":"have newer results and stay"} unread.`:null,t>0?`${t} could not be cleared and ${t===1?"stays":"stay"} unread.`:null,e.deferred>0?t6(e.deferred):null].filter(s=>s!==null);return e.cleared===0?{tone:"warning",message:["Nothing was cleared.",...n].join(" ")}:{tone:"success",message:[`Marked ${e.cleared} ${e.cleared===1?"chat":"chats"} as read.`,...n].join(" ")}},_y="archive",XF="drafts-undo",QF="bulk-read-deferral",JZ=8e3;function ZZ(){const e=Ce(h=>h.archiveFailure),t=Ce(h=>h.archiveUndo),n=Ce(h=>h.draftsUndo),s=Ce(h=>h.bulkReadDeferral),r=Ce(h=>h.clearArchiveFailure),i=Ce(h=>h.setArchiveUndo),a=Ce(h=>h.setSessionArchived),o=Ce(h=>h.restoreDraftsUndo);qZ();const l=g.useRef(null);g.useEffect(()=>{if(e===null&&t===null){if(l.current===null)return;l.current=null,_b(_y);return}const h=e&&t?t.at>e.at?"offer":"failure":e?"failure":"offer",f=h==="offer"?t?.at??0:e?.at??0,p=l.current;l.current={kind:h,at:f},p!==null&&p.kind!==h&&f>p.at&&(h==="failure"?i(null):r());const m=(v,b)=>()=>{const w=Ce.getState();v==="offer"?w.archiveUndo?.at===b&&w.setArchiveUndo(null):w.archiveFailure?.at===b&&w.clearArchiveFailure();const C=l.current;C!==null&&C.kind===v&&C.at===b&&(l.current=null)};if(h==="failure"&&e){qh(`Could not ${e.archived?"archive":"unarchive"} “${e.title}”.${e.detail?` ${e.detail}`:""}`,{id:_y,duration:e6,onAutoClose:m("failure",e.at),onDismiss:m("failure",e.at),action:{label:"Retry",onClick:v=>{v.preventDefault(),a(e.sessionId,e.archived,e.title)}}});return}t&&Va(c.jsxs("span",{className:T("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:T("min-w-0 truncate"),children:VZ(t.title)}),c.jsx("span",{className:T("shrink-0"),children:WZ})]}),{id:_y,duration:uS,classNames:{content:"min-w-0"},onAutoClose:m("offer",t.at),onDismiss:m("offer",t.at),action:{label:"Undo",onClick:v=>{v.preventDefault(),a(t.sessionId,!t.archived,t.title)}}})},[e,t,i,r,a]);const u=g.useRef(!1);g.useEffect(()=>{if(n===null){if(!u.current)return;u.current=!1,_b(XF);return}u.current=!0;const h=()=>{const f=Ce.getState();f.draftsUndo?.at===n.at&&(f.setDraftsUndo(null),u.current=!1)};Va(c.jsxs("span",{className:T("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:T("min-w-0 truncate"),children:KZ(n.keys.length)}),c.jsx("span",{className:T("shrink-0"),children:YZ})]}),{id:XF,duration:uS,classNames:{content:"min-w-0"},onAutoClose:h,onDismiss:h,action:{label:"Undo",onClick:f=>{f.preventDefault(),o();const p=Ce.getState(),m=p.stagedByDiscard;p.setStagedByDiscard(null),n.keys.length===1&&m!==null&&Ce.getState().activeDraftKey===m&&Ce.getState().openDraft(n.keys[0])}}})},[n,o]);const d=g.useRef(!1);return g.useEffect(()=>{if(s===null){if(!d.current)return;d.current=!1,_b(QF);return}d.current=!0;const h=()=>{const f=Ce.getState();f.bulkReadDeferral?.at===s.at&&(f.clearBulkReadDeferral(),d.current=!1)};Va(t6(s.count),{id:QF,duration:JZ,onAutoClose:h,onDismiss:h})},[s]),null}const eee={"under-window":{dark:{canvas:.59,surface:.67,elevated:.87},light:{canvas:.61,surface:.5,elevated:.45}},menu:{dark:{canvas:.73,surface:.79,elevated:.94},light:{canvas:.79,surface:.7,elevated:.65}},popover:{dark:{canvas:.79,surface:.85,elevated:.97},light:{canvas:.86,surface:.79,elevated:.75}}},tee={"under-window":{dark:.15,light:.2},menu:{dark:.15,light:.2},popover:{dark:.15,light:.15}},nee={hover:.05,selected:.08,field:.05},Bg={alphaFloor:eee,controlMix:tee,stateAlpha:nee},JJe=["sidebars","full"],n6=(e,t)=>e!=="vibrancy"?"popover":t==="menu"?"menu":t==="popover"?"popover":"under-window",see=.96,s6=e=>Math.round(e*100)/100;function ree(e,t,n){const s=Bg.alphaFloor[n6(e,t)][n];return{canvas:s.canvas,surface:s.surface,elevated:s.elevated}}function iee(e){const t=Math.min(100,Math.max(0,e.intensity))/100,n=ree(e.mechanism,e.material,e.scheme),s=r=>{const i=Math.max(see,r);return s6(i-t*(i-r))};return{canvas:s(n.canvas),surface:s(n.surface),elevated:s(n.elevated)}}const aee={sidebars:["sidebar"],full:["sidebar","canvas","pane"]};function oee(e,t,n){return Bg.controlMix[n6(e,t)][n]}function lee(e){const t=iee(e),n=r=>s6(Math.min(1,Math.max(0,1-(1-r)/(1-t.canvas)))),s={"--lo-glass-a-canvas":String(t.canvas),"--lo-glass-a-surface":String(t.surface),"--lo-glass-a-elevated":String(t.elevated),"--lo-glass-a-row-hover":String(Bg.stateAlpha.hover),"--lo-glass-a-row-selected":String(Bg.stateAlpha.selected),"--lo-glass-a-field":String(Bg.stateAlpha.field),"--lo-glass-control-mix":String(oee(e.mechanism,e.material,e.scheme)),"--lo-glass-in-surface":String(n(t.surface)),"--lo-glass-in-elevated":String(n(t.elevated))};return{kinds:aee[e.coverage].join(" "),vars:s}}const r6=()=>document.documentElement,cee=["--lo-glass-a-canvas","--lo-glass-a-surface","--lo-glass-a-elevated","--lo-glass-a-row-hover","--lo-glass-a-row-selected","--lo-glass-a-field","--lo-glass-control-mix","--lo-glass-in-surface","--lo-glass-in-elevated"];let Tb=null;const lx=()=>r6().classList.contains("dark")?"dark":"light";function cx(e){Tb=e;const t=r6();if(!e||!e.active){delete t.dataset.glass;for(const r of cee)t.style.removeProperty(r);return}const{kinds:n,vars:s}=lee({coverage:e.settings.coverage,intensity:e.settings.intensity,mechanism:e.mechanism,material:e.settings.material,scheme:e.scheme});t.dataset.glass=n;for(const[r,i]of Object.entries(s))t.style.setProperty(r,i)}function uee(e){cx(e?{active:!0,scheme:e.scheme,mechanism:e.mechanism,settings:{coverage:e.coverage,intensity:e.intensity,material:e.material}}:null)}function i6(e){if(!e||!e.active||e.capability.mechanism==="none"){cx(null);return}e.restartRequired&&e.active||cx({active:!0,scheme:lx(),mechanism:e.capability.mechanism,settings:{coverage:e.settings.coverage,intensity:e.settings.intensity,material:e.settings.material}})}function dee(){!Tb||!Tb.active||(cx({...Tb,scheme:lx()}),window.api?.windowGlass?.reportScheme?.(lx()))}function hee(){const e=window.api?.windowGlass;return e?e.onState(t=>i6(t)):()=>{}}function ZJe(){const[e,t]=g.useState(null);return g.useEffect(()=>{const s=window.api?.windowGlass;if(!s)return;let r=!1;s.get().then(a=>{r||t(a)});const i=s.onState(a=>t(a));return()=>{r=!0,i()}},[]),{state:e,set:async s=>{const r=await window.api?.windowGlass?.set(s);r&&(t(r),i6(r),window.api?.windowGlass?.reportScheme?.(lx()))}}}var ja,Be=typeof window<"u"?window:void 0,ui=typeof globalThis<"u"?globalThis:Be,a6=Array.prototype,JF=a6.forEach,ZF=a6.indexOf,Ii=ui?.navigator,_t=ui?.document,li=ui?.location,dS=ui?.fetch,hS=ui!=null&&ui.XMLHttpRequest&&"withCredentials"in new ui.XMLHttpRequest?ui.XMLHttpRequest:void 0,eD=ui?.AbortController,Ns=Ii?.userAgent,Vt=Be??{},pl={DEBUG:!1,LIB_VERSION:"1.235.6"},Sy="$copy_autocapture",fee=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];(function(e){e.GZipJS="gzip-js",e.Base64="base64"})(ja||(ja={}));var pee=["fatal","error","warning","log","info","debug"];function Zt(e,t){return e.indexOf(t)!==-1}var cC=function(e){return e.trim()},mT=function(e){return e.replace(/^\$/,"")},gee=Array.isArray,o6=Object.prototype,l6=o6.hasOwnProperty,uC=o6.toString,cs=gee||function(e){return uC.call(e)==="[object Array]"},Wa=e=>typeof e=="function",us=e=>e===Object(e)&&!cs(e),Hh=e=>{if(us(e)){for(var t in e)if(l6.call(e,t))return!1;return!0}return!1},wt=e=>e===void 0,Os=e=>uC.call(e)=="[object String]",fS=e=>Os(e)&&e.trim().length===0,iu=e=>e===null,En=e=>wt(e)||iu(e),qr=e=>uC.call(e)=="[object Number]",ml=e=>uC.call(e)==="[object Boolean]",mee=e=>e instanceof FormData,vee=e=>Zt(fee,e),c6=e=>{var t={_log:function(n){if(Be&&(pl.DEBUG||Vt.POSTHOG_DEBUG)&&!wt(Be.console)&&Be.console){for(var s=("__rrweb_original__"in Be.console[n])?Be.console[n].__rrweb_original__:Be.console[n],r=arguments.length,i=new Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];s(e,...i)}},info:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];t._log("log",...s)},warn:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];t._log("warn",...s)},error:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];t._log("error",...s)},critical:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];console.error(e,...s)},uninitializedWarning:n=>{t.error("You must initialize PostHog before calling ".concat(n))},createLogger:n=>c6("".concat(e," ").concat(n))};return t},Rt=c6("[PostHog.js]"),Mr=Rt.createLogger,bee=Mr("[ExternalScriptsLoader]"),tD=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return bee.warn("".concat(t," was requested but loading of external scripts is disabled.")),n("Loading of external scripts is disabled");var s=_t?.querySelectorAll("script");if(s){for(var r=0;r<s.length;r++)if(s[r].src===t)return n()}var i=()=>{if(!_t)return n("document not found");var a=_t.createElement("script");if(a.type="text/javascript",a.crossOrigin="anonymous",a.src=t,a.onload=u=>n(void 0,u),a.onerror=u=>n(u),e.config.prepare_external_dependency_script&&(a=e.config.prepare_external_dependency_script(a)),!a)return n("prepare_external_dependency_script returned null");var o,l=_t.querySelectorAll("body > script");l.length>0?(o=l[0].parentNode)===null||o===void 0||o.insertBefore(a,l[0]):_t.body.appendChild(a)};_t!=null&&_t.body?i():_t?.addEventListener("DOMContentLoaded",i)};function nD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,s)}return n}function We(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?nD(Object(n),!0).forEach(function(s){dt(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):nD(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function dt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u6(e,t){if(e==null)return{};var n,s,r=function(a,o){if(a==null)return{};var l,u,d={},h=Object.keys(a);for(u=0;u<h.length;u++)l=h[u],o.indexOf(l)>=0||(d[l]=a[l]);return d}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}Vt.__PosthogExtensions__=Vt.__PosthogExtensions__||{},Vt.__PosthogExtensions__.loadExternalDependency=(e,t,n)=>{var s="/static/".concat(t,".js")+"?v=".concat(e.version);if(t==="remote-config"&&(s="/array/".concat(e.config.token,"/config.js")),t==="toolbar"){var r=3e5,i=Math.floor(Date.now()/r)*r;s="".concat(s,"&t=").concat(i)}var a=e.requestRouter.endpointFor("assets",s);tD(e,a,n)},Vt.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var s=e.requestRouter.endpointFor("api",t);tD(e,s,n)};var ux={};function Bc(e,t,n){if(cs(e)){if(JF&&e.forEach===JF)e.forEach(t,n);else if("length"in e&&e.length===+e.length){for(var s=0,r=e.length;s<r;s++)if(s in e&&t.call(n,e[s],s)===ux)return}}}function Nn(e,t,n){if(!En(e)){if(cs(e))return Bc(e,t,n);if(mee(e)){for(var s of e.entries())if(t.call(n,s[1],s[0])===ux)return}else for(var r in e)if(l6.call(e,r)&&t.call(n,e[r],r)===ux)return}}var xs=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return Bc(n,function(r){for(var i in r)r[i]!==void 0&&(e[i]=r[i])}),e},Rb=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return Bc(n,function(r){Bc(r,function(i){e.push(i)})}),e};function Ab(e){for(var t=Object.keys(e),n=t.length,s=new Array(n);n--;)s[n]=[t[n],e[t[n]]];return s}var sD=function(e){try{return e()}catch{return}},xee=function(e){return function(){try{for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return e.apply(this,n)}catch(r){Rt.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Rt.critical(r)}}},Pm=function(e){var t={};return Nn(e,function(n,s){Os(n)&&n.length>0&&(t[s]=n)}),t};function wee(e,t){return n=e,s=i=>Os(i)&&!iu(t)?i.slice(0,t):i,r=new Set,function i(a,o){return a!==Object(a)?s?s(a,o):a:r.has(a)?void 0:(r.add(a),cs(a)?(l=[],Bc(a,u=>{l.push(i(u))})):(l={},Nn(a,(u,d)=>{r.has(u)||(l[d]=i(u,d))})),l);var l}(n);var n,s,r}var Cee=["herokuapp.com","vercel.app","netlify.app"];function yee(e){var t=e?.hostname;if(!Os(t))return!1;var n=t.split(".").slice(-2).join(".");for(var s of Cee)if(n===s)return!1;return!0}function d6(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n]}function Cs(e,t,n,s){var{capture:r=!1,passive:i=!0}=s??{};e?.addEventListener(t,n,{capture:r,passive:i})}var h6="$people_distinct_id",vg="__alias",bg="__timers",rD="$autocapture_disabled_server_side",pS="$heatmaps_enabled_server_side",iD="$exception_capture_enabled_server_side",aD="$web_vitals_enabled_server_side",f6="$dead_clicks_enabled_server_side",oD="$web_vitals_allowed_metrics",gS="$session_recording_enabled_server_side",lD="$console_log_recording_enabled_server_side",cD="$session_recording_network_payload_capture",uD="$session_recording_masking",dD="$session_recording_canvas_recording",hD="$replay_sample_rate",fD="$replay_minimum_duration",pD="$replay_script_config",dx="$sesid",xg="$session_is_sampled",Ey="$session_recording_url_trigger_activated_session",ky="$session_recording_event_trigger_activated_session",Uh="$enabled_feature_flags",Fb="$early_access_features",mS="$feature_flag_details",wg="$stored_person_properties",Nu="$stored_group_properties",vS="$surveys",Sv="$surveys_activated",hx="$flag_call_reported",dl="$user_state",bS="$client_session_props",xS="$capture_rate_limit",wS="$initial_campaign_params",CS="$initial_referrer_info",yS="$initial_person_info",fx="$epp",p6="__POSTHOG_TOOLBAR__",gD="$posthog_cookieless",_ee=[h6,vg,"__cmpns",bg,gS,pS,dx,Uh,dl,Fb,mS,Nu,wg,vS,hx,bS,xS,wS,CS,fx];function mD(e){var t;return e instanceof Element&&(e.id===p6||!((t=e.closest)===null||t===void 0||!t.call(e,".toolbar-global-fade-container")))}function dC(e){return!!e&&e.nodeType===1}function jc(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function g6(e){return!!e&&e.nodeType===3}function m6(e){return!!e&&e.nodeType===11}function vT(e){return e?cC(e).split(/\s+/):[]}function vD(e){var t=Be?.location.href;return!!(t&&e&&e.some(n=>t.match(n)))}function px(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return vT(t)}function v6(e){return En(e)?null:cC(e).split(/(\s+)/).filter(t=>Af(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function hC(e){var t="";return SS(e)&&!w6(e)&&e.childNodes&&e.childNodes.length&&Nn(e.childNodes,function(n){var s;g6(n)&&n.textContent&&(t+=(s=v6(n.textContent))!==null&&s!==void 0?s:"")}),cC(t)}function b6(e){return wt(e.target)?e.srcElement||null:(t=e.target)!==null&&t!==void 0&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var _S=["a","button","form","input","select","textarea","label"];function x6(e){var t=e.parentNode;return!(!t||!dC(t))&&t}function See(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;if(!Be||!e||jc(e,"html")||!dC(e)||n!=null&&n.url_allowlist&&!vD(n.url_allowlist)||n!=null&&n.url_ignorelist&&vD(n.url_ignorelist))return!1;if(n!=null&&n.dom_event_allowlist){var i=n.dom_event_allowlist;if(i&&!i.some(p=>t.type===p))return!1}for(var a=!1,o=[e],l=!0,u=e;u.parentNode&&!jc(u,"body");)if(m6(u.parentNode))o.push(u.parentNode.host),u=u.parentNode.host;else{if(!(l=x6(u)))break;if(s||_S.indexOf(l.tagName.toLowerCase())>-1)a=!0;else{var d=Be.getComputedStyle(l);d&&d.getPropertyValue("cursor")==="pointer"&&(a=!0)}o.push(l),u=l}if(!function(p,m){var v=m?.element_allowlist;if(wt(v))return!0;var b=function(y){if(v.some(k=>y.tagName.toLowerCase()===k))return{v:!0}};for(var w of p){var C=b(w);if(typeof C=="object")return C.v}return!1}(o,n)||!function(p,m){var v=m?.css_selector_allowlist;if(wt(v))return!0;var b=function(y){if(v.some(k=>y.matches(k)))return{v:!0}};for(var w of p){var C=b(w);if(typeof C=="object")return C.v}return!1}(o,n))return!1;var h=Be.getComputedStyle(e);if(h&&h.getPropertyValue("cursor")==="pointer"&&t.type==="click")return!0;var f=e.tagName.toLowerCase();switch(f){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return a?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(_S.indexOf(f)>-1||e.getAttribute("contenteditable")==="true")}}function SS(e){for(var t=e;t.parentNode&&!jc(t,"body");t=t.parentNode){var n=px(t);if(Zt(n,"ph-sensitive")||Zt(n,"ph-no-capture"))return!1}if(Zt(px(e),"ph-include"))return!0;var s=e.type||"";if(Os(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var r=e.name||e.id||"";return!(Os(r)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(r.replace(/[^a-zA-Z0-9]/g,"")))}function w6(e){return!!(jc(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||jc(e,"select")||jc(e,"textarea")||e.getAttribute("contenteditable")==="true")}var C6="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",Eee=new RegExp("^(?:".concat(C6,")$")),kee=new RegExp(C6),y6="\\d{3}-?\\d{2}-?\\d{4}",Tee=new RegExp("^(".concat(y6,")$")),Ree=new RegExp("(".concat(y6,")"));function Af(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return!(En(e)||Os(e)&&(e=cC(e),(t?Eee:kee).test((e||"").replace(/[- ]/g,""))||(t?Tee:Ree).test(e)))}function _6(e){var t=hC(e);return Af(t="".concat(t," ").concat(S6(e)).trim())?t:""}function S6(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Nn(e.childNodes,function(n){var s;if(n&&((s=n.tagName)===null||s===void 0?void 0:s.toLowerCase())==="span")try{var r=hC(n);t="".concat(t," ").concat(r).trim(),n.childNodes&&n.childNodes.length&&(t="".concat(t," ").concat(S6(n)).trim())}catch(i){Rt.error("[AutoCapture]",i)}}),t}function Aee(e){return function(t){var n=t.map(s=>{var r,i,a="";if(s.tag_name&&(a+=s.tag_name),s.attr_class)for(var o of(s.attr_class.sort(),s.attr_class))a+=".".concat(o.replace(/"/g,""));var l=We(We(We(We({},s.text?{text:s.text}:{}),{},{"nth-child":(r=s.nth_child)!==null&&r!==void 0?r:0,"nth-of-type":(i=s.nth_of_type)!==null&&i!==void 0?i:0},s.href?{href:s.href}:{}),s.attr_id?{attr_id:s.attr_id}:{}),s.attributes),u={};return Ab(l).sort((d,h)=>{var[f]=d,[p]=h;return f.localeCompare(p)}).forEach(d=>{var[h,f]=d;return u[bD(h.toString())]=bD(f.toString())}),a+=":",a+=Ab(l).map(d=>{var[h,f]=d;return"".concat(h,'="').concat(f,'"')}).join("")});return n.join(";")}(function(t){return t.map(n=>{var s,r,i={text:(s=n.$el_text)===null||s===void 0?void 0:s.slice(0,400),tag_name:n.tag_name,href:(r=n.attr__href)===null||r===void 0?void 0:r.slice(0,2048),attr_class:Fee(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return Ab(n).filter(a=>{var[o]=a;return o.indexOf("attr__")===0}).forEach(a=>{var[o,l]=a;return i.attributes[o]=l}),i})}(e))}function bD(e){return e.replace(/"|\\"/g,'\\"')}function Fee(e){var t=e.attr__class;return t?cs(t)?t:vT(t):void 0}class E6{constructor(){this.clicks=[]}isRageClick(t,n,s){var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(t-r.x)+Math.abs(n-r.y)<30&&s-r.timestamp<1e3){if(this.clicks.push({x:t,y:n,timestamp:s}),this.clicks.length===3)return!0}else this.clicks=[{x:t,y:n,timestamp:s}];return!1}}var Dee=["localhost","127.0.0.1"],Jh=e=>{var t=_t?.createElement("a");return wt(t)?null:(t.href=e,t)},Pee=function(e){var t,n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",r=[];return Nn(e,function(i,a){wt(i)||wt(a)||a==="undefined"||(t=encodeURIComponent((o=>o instanceof File)(i)?i.name:i.toString()),n=encodeURIComponent(a),r[r.length]=n+"="+t)}),r.join(s)},gx=function(e,t){for(var n,s=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;r<s.length;r++){var i=s[r].split("=");if(i[0]===t){n=i;break}}if(!cs(n)||n.length<2)return"";var a=n[1];try{a=decodeURIComponent(a)}catch{Rt.error("Skipping decoding for malformed query param: "+a)}return a.replace(/\+/g," ")},Ty=function(e,t,n){if(!e||!t||!t.length)return e;for(var s=e.split("#"),r=s[0]||"",i=s[1],a=r.split("?"),o=a[1],l=a[0],u=(o||"").split("&"),d=[],h=0;h<u.length;h++){var f=u[h].split("=");cs(f)&&(t.includes(f[0])?d.push(f[0]+"="+n):d.push(u[h]))}var p=l;return o!=null&&(p+="?"+d.join("&")),i!=null&&(p+="#"+i),p},mx=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},xD=Mr("[AutoCapture]");function Ry(e,t){return t.length>e?t.slice(0,e)+"...":t}function Iee(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!dC(t));return t}function Nee(e,t,n,s){var r=e.tagName.toLowerCase(),i={tag_name:r};_S.indexOf(r)>-1&&!n&&(r.toLowerCase()==="a"||r.toLowerCase()==="button"?i.$el_text=Ry(1024,_6(e)):i.$el_text=Ry(1024,hC(e)));var a=px(e);a.length>0&&(i.classes=a.filter(function(d){return d!==""})),Nn(e.attributes,function(d){var h;if((!w6(e)||["name","id","class","aria-label"].indexOf(d.name)!==-1)&&(s==null||!s.includes(d.name))&&!t&&Af(d.value)&&(h=d.name,!Os(h)||h.substring(0,10)!=="_ngcontent"&&h.substring(0,7)!=="_nghost")){var f=d.value;d.name==="class"&&(f=vT(f).join(" ")),i["attr__"+d.name]=Ry(1024,f)}});for(var o=1,l=1,u=e;u=Iee(u);)o++,u.tagName===e.tagName&&l++;return i.nth_child=o,i.nth_of_type=l,i}function Mee(e,t){for(var n,s,{e:r,maskAllElementAttributes:i,maskAllText:a,elementAttributeIgnoreList:o,elementsChainAsString:l}=t,u=[e],d=e;d.parentNode&&!jc(d,"body");)m6(d.parentNode)?(u.push(d.parentNode.host),d=d.parentNode.host):(u.push(d.parentNode),d=d.parentNode);var h,f=[],p={},m=!1,v=!1;if(Nn(u,k=>{var _=SS(k);k.tagName.toLowerCase()==="a"&&(m=k.getAttribute("href"),m=_&&m&&Af(m)&&m),Zt(px(k),"ph-no-capture")&&(v=!0),f.push(Nee(k,i,a,o));var E=function(R){if(!SS(R))return{};var F={};return Nn(R.attributes,function(A){if(A.name&&A.name.indexOf("data-ph-capture-attribute")===0){var N=A.name.replace("data-ph-capture-attribute-",""),M=A.value;N&&M&&Af(M)&&(F[N]=M)}}),F}(k);xs(p,E)}),v)return{props:{},explicitNoCapture:v};if(a||(e.tagName.toLowerCase()==="a"||e.tagName.toLowerCase()==="button"?f[0].$el_text=_6(e):f[0].$el_text=hC(e)),m){var b,w;f[0].attr__href=m;var C=(b=Jh(m))===null||b===void 0?void 0:b.host,y=Be==null||(w=Be.location)===null||w===void 0?void 0:w.host;C&&y&&C!==y&&(h=m)}return{props:xs({$event_type:r.type,$ce_version:1},l?{}:{$elements:f},{$elements_chain:Aee(f)},(n=f[0])!==null&&n!==void 0&&n.$el_text?{$el_text:(s=f[0])===null||s===void 0?void 0:s.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},p)}}let Oee=class{constructor(t){dt(this,"_initialized",!1),dt(this,"_isDisabledServerSide",null),dt(this,"rageclicks",new E6),dt(this,"_elementsChainAsString",!1),this.instance=t,this._elementSelectors=null}get config(){var t,n,s=us(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)===null||t===void 0?void 0:t.map(r=>new RegExp(r)),s.url_ignorelist=(n=s.url_ignorelist)===null||n===void 0?void 0:n.map(r=>new RegExp(r)),s}_addDomEventHandlers(){if(this.isBrowserSupported()){if(Be&&_t){var t=s=>{s=s||Be?.event;try{this._captureEvent(s)}catch(r){xD.error("Failed to capture event",r)}};if(Cs(_t,"submit",t,{capture:!0}),Cs(_t,"change",t,{capture:!0}),Cs(_t,"click",t,{capture:!0}),this.config.capture_copied_text){var n=s=>{s=s||Be?.event,this._captureEvent(s,Sy)};Cs(_t,"copy",n,{capture:!0}),Cs(_t,"cut",n,{capture:!0})}}}else xD.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(t){t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[rD]:!!t.autocapture_opt_out}),this._isDisabledServerSide=!!t.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(t){this._elementSelectors=t}getElementSelectors(t){var n,s=[];return(n=this._elementSelectors)===null||n===void 0||n.forEach(r=>{var i=_t?.querySelectorAll(r);i?.forEach(a=>{t===a&&s.push(r)})}),s}get isEnabled(){var t,n,s=(t=this.instance.persistence)===null||t===void 0?void 0:t.props[rD],r=this._isDisabledServerSide;if(iu(r)&&!ml(s)&&!this.instance.config.advanced_disable_decide)return!1;var i=(n=this._isDisabledServerSide)!==null&&n!==void 0?n:!!s;return!!this.instance.config.autocapture&&!i}_captureEvent(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"$autocapture";if(this.isEnabled){var s,r=b6(t);g6(r)&&(r=r.parentNode||null),n==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!==null&&s!==void 0&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&this._captureEvent(t,"$rageclick");var i=n===Sy;if(r&&See(r,t,this.config,i,i?["copy","cut"]:void 0)){var{props:a,explicitNoCapture:o}=Mee(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.config.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString});if(o)return!1;var l=this.getElementSelectors(r);if(l&&l.length>0&&(a.$element_selectors=l),n===Sy){var u,d=v6(Be==null||(u=Be.getSelection())===null||u===void 0?void 0:u.toString()),h=t.type||"clipboard";if(!d)return!1;a.$selected_content=d,a.$copy_type=h}return this.instance.capture(n,a),!0}}}isBrowserSupported(){return Wa(_t?.querySelectorAll)}};Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return qr(e)&&isFinite(e)&&Math.floor(e)===e});var wD="0123456789abcdef";let Lee=class ES{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,n,s,r){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||!Number.isInteger(r)||t<0||n<0||s<0||r<0||t>0xffffffffffff||n>4095||s>1073741823||r>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=t/Math.pow(2,40),i[1]=t/Math.pow(2,32),i[2]=t/Math.pow(2,24),i[3]=t/Math.pow(2,16),i[4]=t/Math.pow(2,8),i[5]=t,i[6]=112|n>>>8,i[7]=n,i[8]=128|s>>>24,i[9]=s>>>16,i[10]=s>>>8,i[11]=s,i[12]=r>>>24,i[13]=r>>>16,i[14]=r>>>8,i[15]=r,new ES(i)}toString(){for(var t="",n=0;n<this.bytes.length;n++)t=t+wD.charAt(this.bytes[n]>>>4)+wD.charAt(15&this.bytes[n]),n!==3&&n!==5&&n!==7&&n!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new ES(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(var n=0;n<16;n++){var s=this.bytes[n]-t.bytes[n];if(s!==0)return Math.sign(s)}return 0}},Bee=class{constructor(){dt(this,"timestamp",0),dt(this,"counter",0),dt(this,"random",new jee)}generate(){var t=this.generateOrAbort();if(wt(t)){this.timestamp=0;var n=this.generateOrAbort();if(wt(n))throw new Error("Could not generate UUID after timestamp reset");return n}return t}generateOrAbort(){var t=Date.now();if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+1e4>this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Lee.fromFieldsV7(this.timestamp,Math.trunc(this.counter/Math.pow(2,30)),this.counter&Math.pow(2,30)-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}};var CD,k6=e=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;t<e.length;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};Be&&!wt(Be.crypto)&&crypto.getRandomValues&&(k6=e=>crypto.getRandomValues(e));let jee=class{constructor(){dt(this,"buffer",new Uint32Array(8)),dt(this,"cursor",1/0)}nextUint32(){return this.cursor>=this.buffer.length&&(k6(this.buffer),this.cursor=0),this.buffer[this.cursor++]}};var Fc=()=>Hee().toString(),Hee=()=>(CD||(CD=new Bee)).generate(),Uee="Thu, 01 Jan 1970 00:00:00 GMT",Vp="",Gee=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Vee(e,t){if(t){var n=function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_t;if(Vp)return Vp;if(!i||["localhost","127.0.0.1"].includes(r))return"";for(var a=r.split("."),o=Math.min(a.length,8),l="dmn_chk_"+Fc(),u=new RegExp("(^|;)\\s*"+l+"=1");!Vp&&o--;){var d=a.slice(o).join("."),h=l+"=1;domain=."+d;i.cookie=h,u.test(i.cookie)&&(i.cookie=h+";expires="+Uee,Vp=d)}return Vp}(e);if(!n){var s=(r=>{var i=r.match(Gee);return i?i[0]:""})(e);s!==n&&Rt.info("Warning: cookie subdomain discovery mismatch",s,n),n=s}return n?"; domain=."+n:""}return""}var _c,_l={is_supported:()=>!!_t,error:function(e){Rt.error("cookieStore error: "+e)},get:function(e){if(_t){try{for(var t=e+"=",n=_t.cookie.split(";").filter(i=>i.length),s=0;s<n.length;s++){for(var r=n[s];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length,r.length))}}catch{}return null}},parse:function(e){var t;try{t=JSON.parse(_l.get(e))||{}}catch{}return t},set:function(e,t,n,s,r){if(_t)try{var i="",a="",o=Vee(_t.location.hostname,s);if(n){var l=new Date;l.setTime(l.getTime()+24*n*60*60*1e3),i="; expires="+l.toUTCString()}r&&(a="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+i+"; SameSite=Lax; path=/"+o+a;return u.length>3686.4&&Rt.warn("cookieStore warning: large cookie, len="+u.length),_t.cookie=u,u}catch{return}},remove:function(e,t){try{_l.set(e,"",-1,t)}catch{return}}},Ay=null,Us={is_supported:function(){if(!iu(Ay))return Ay;var e=!0;if(wt(Be))e=!1;else try{var t="__mplssupport__";Us.set(t,"xyz"),Us.get(t)!=='"xyz"'&&(e=!1),Us.remove(t)}catch{e=!1}return e||Rt.error("localStorage unsupported; falling back to cookie store"),Ay=e,e},error:function(e){Rt.error("localStorage error: "+e)},get:function(e){try{return Be?.localStorage.getItem(e)}catch(t){Us.error(t)}return null},parse:function(e){try{return JSON.parse(Us.get(e))||{}}catch{}return null},set:function(e,t){try{Be?.localStorage.setItem(e,JSON.stringify(t))}catch(n){Us.error(n)}},remove:function(e){try{Be?.localStorage.removeItem(e)}catch(t){Us.error(t)}}},Wee=["distinct_id",dx,xg,fx,yS],Ev=We(We({},Us),{},{parse:function(e){try{var t={};try{t=_l.parse(e)||{}}catch{}var n=xs(t,JSON.parse(Us.get(e)||"{}"));return Us.set(e,n),n}catch{}return null},set:function(e,t,n,s,r,i){try{Us.set(e,t,void 0,void 0,i);var a={};Wee.forEach(o=>{t[o]&&(a[o]=t[o])}),Object.keys(a).length&&_l.set(e,a,n,s,r,i)}catch(o){Us.error(o)}},remove:function(e,t){try{Be?.localStorage.removeItem(e),_l.remove(e,t)}catch(n){Us.error(n)}}}),kv={},$ee={is_supported:function(){return!0},error:function(e){Rt.error("memoryStorage error: "+e)},get:function(e){return kv[e]||null},parse:function(e){return kv[e]||null},set:function(e,t){kv[e]=t},remove:function(e){delete kv[e]}},ku=null,hr={is_supported:function(){if(!iu(ku))return ku;if(ku=!0,wt(Be))ku=!1;else try{var e="__support__";hr.set(e,"xyz"),hr.get(e)!=='"xyz"'&&(ku=!1),hr.remove(e)}catch{ku=!1}return ku},error:function(e){Rt.error("sessionStorage error: ",e)},get:function(e){try{return Be?.sessionStorage.getItem(e)}catch(t){hr.error(t)}return null},parse:function(e){try{return JSON.parse(hr.get(e))||null}catch{}return null},set:function(e,t){try{Be?.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){hr.error(n)}},remove:function(e){try{Be?.sessionStorage.removeItem(e)}catch(t){hr.error(t)}}};(function(e){e[e.PENDING=-1]="PENDING",e[e.DENIED=0]="DENIED",e[e.GRANTED=1]="GRANTED"})(_c||(_c={}));let zee=class{constructor(t){this.instance=t}get config(){return this.instance.config}get consent(){return this.getDnt()?_c.DENIED:this.storedConsent}isOptedOut(){return this.consent===_c.DENIED||this.consent===_c.PENDING&&this.config.opt_out_capturing_by_default}isOptedIn(){return!this.isOptedOut()}optInOut(t){this.storage.set(this.storageKey,t?1:0,this.config.cookie_expiration,this.config.cross_subdomain_cookie,this.config.secure_cookie)}reset(){this.storage.remove(this.storageKey,this.config.cross_subdomain_cookie)}get storageKey(){var{token:t,opt_out_capturing_cookie_prefix:n}=this.instance.config;return(n||"__ph_opt_in_out_")+t}get storedConsent(){var t=this.storage.get(this.storageKey);return t==="1"?_c.GRANTED:t==="0"?_c.DENIED:_c.PENDING}get storage(){if(!this._storage){var t=this.config.opt_out_capturing_persistence_type;this._storage=t==="localStorage"?Us:_l;var n=t==="localStorage"?_l:Us;n.get(this.storageKey)&&(this._storage.get(this.storageKey)||this.optInOut(n.get(this.storageKey)==="1"),n.remove(this.storageKey,this.config.cross_subdomain_cookie))}return this._storage}getDnt(){return!!this.config.respect_dnt&&!!d6([Ii?.doNotTrack,Ii?.msDoNotTrack,Vt.doNotTrack],t=>Zt([!0,1,"1","yes"],t))}};var Tv=Mr("[Dead Clicks]"),qee=()=>!0,Kee=e=>{var t,n=!((t=e.instance.persistence)===null||t===void 0||!t.get_property(f6)),s=e.instance.config.capture_dead_clicks;return ml(s)?s:n};let T6=class{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(t,n,s){this.instance=t,this.isEnabled=n,this.onCapture=s,this.startIfEnabled()}onRemoteConfig(t){this.instance.persistence&&this.instance.persistence.register({[f6]:t?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.loadScript(()=>{this.start()})}loadScript(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.initDeadClicksAutocapture&&t(),(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"dead-clicks-autocapture",i=>{i?Tv.error("failed to load script",i):t()})}start(){var t;if(_t){if(!this._lazyLoadedDeadClicksAutocapture&&(t=Vt.__PosthogExtensions__)!==null&&t!==void 0&&t.initDeadClicksAutocapture){var n=us(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this._lazyLoadedDeadClicksAutocapture=Vt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this._lazyLoadedDeadClicksAutocapture.start(_t),Tv.info("starting...")}}else Tv.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,Tv.info("stopping..."))}};var Fy=Mr("[ExceptionAutocapture]");let Yee=class{constructor(t){var n;dt(this,"startCapturing",()=>{var s;if(Be&&this.isEnabled&&(s=Vt.__PosthogExtensions__)!==null&&s!==void 0&&s.errorWrappingFunctions){var r=Vt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=Vt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=Vt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.unwrapOnError&&this.config.capture_unhandled_errors&&(this.unwrapOnError=r(this.captureException.bind(this))),!this.unwrapUnhandledRejection&&this.config.capture_unhandled_rejections&&(this.unwrapUnhandledRejection=i(this.captureException.bind(this))),!this.unwrapConsoleError&&this.config.capture_console_errors&&(this.unwrapConsoleError=a(this.captureException.bind(this)))}catch(o){Fy.error("failed to start",o),this.stopCapturing()}}}),this.instance=t,this.remoteEnabled=!((n=this.instance.persistence)===null||n===void 0||!n.props[iD]),this.config=this.requiredConfig(),this.startIfEnabled()}requiredConfig(){var t=this.instance.config.capture_exceptions,n={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return us(t)?n=We(We({},n),t):(wt(t)?this.remoteEnabled:t)&&(n=We(We({},n),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),n}get isEnabled(){return this.config.capture_console_errors||this.config.capture_unhandled_errors||this.config.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(Fy.info("enabled"),this.loadScript(this.startCapturing))}loadScript(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.errorWrappingFunctions&&t(),(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"exception-autocapture",i=>{if(i)return Fy.error("failed to load script",i);t()})}stopCapturing(){var t,n,s;(t=this.unwrapOnError)===null||t===void 0||t.call(this),this.unwrapOnError=void 0,(n=this.unwrapUnhandledRejection)===null||n===void 0||n.call(this),this.unwrapUnhandledRejection=void 0,(s=this.unwrapConsoleError)===null||s===void 0||s.call(this),this.unwrapConsoleError=void 0}onRemoteConfig(t){var n=t.autocaptureExceptions;this.remoteEnabled=!!n||!1,this.config=this.requiredConfig(),this.instance.persistence&&this.instance.persistence.register({[iD]:this.remoteEnabled}),this.startIfEnabled()}captureException(t){var n=this.instance.requestRouter.endpointFor("ui");t.$exception_personURL="".concat(n,"/project/").concat(this.instance.config.token,"/person/").concat(this.instance.get_distinct_id()),this.instance.exceptions.sendExceptionEvent(t)}};function R6(e){return!wt(Event)&&A6(e,Event)}function A6(e,t){try{return e instanceof t}catch{return!1}}function Db(e,t){return Object.prototype.toString.call(e)==="[object ".concat(t,"]")}function Dy(e){return Db(e,"DOMError")}var yD=/\(error: (.*)\)/,_D=50,Gh="?";function Py(e,t,n,s){var r={platform:"web:javascript",filename:e,function:t==="<anonymous>"?Gh:t,in_app:!0};return wt(n)||(r.lineno=n),wt(s)||(r.colno=s),r}var Xee=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Qee=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Jee=/\((\S*)(?::(\d+))(?::(\d+))\)/,Zee=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ete=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,tte=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var s=t.sort((r,i)=>r[0]-i[0]).map(r=>r[1]);return function(r){for(var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=[],o=r.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./agent-details-page-B_mPfefi.js","./index-C9huVbt8.js","./index-DxyRyuQP.css","./publication-validation-CfKQMeAn.js","./conversation-input-sync-_j7A_EDF.js","./ui-preferences-store-BSjv1eml.js","./error-boundary-BCQ7FGQc.js","./conversation-input-sync-CAX4_ErH.css","./use-memberships-query-DG-_x04X.js","./use-download-agent-mutation-CHYPRtS_.js","./en-US-CHJkXXr4.js","./book-open-CfuxuX-l.js","./console-mirror-D4VUczn2.js","./console-mirror-DOrYoP_4.css","./agent-hub-page-BYHsrmlA.js","./page-header-Dl5IO6UP.js","./org-access-CkXCfgnJ.js","./radient-auth-buttons-eShZasz1.js","./format-esAOn2VS.js","./org-surface-gate-CnNhHebI.js","./agents-page-DOt4Ktjv.js","./schedules-page-5j5ANXIf.js","./parseISO-BHJWTxrA.js","./projects-page-ygyrTO2Y.js","./use-session-snapshot-CdDuQ-c-.js","./browser-page-BpsxcPyu.js","./mesh-page-GPZRPR4j.js","./settings-page-rEYr23iA.js","./notebook-pen-Dd0WXtBw.js","./browser-webauthn-prompt-DbKuqaik.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as g,j as c,c as T,b as $e,i as GA,p as U$,y as G$,o as V$,t as x,z as W1,L as Ro,A as W$,a as $$,R as z$}from"./index-C9huVbt8.js";import{ar as Ce,dV as q$,dW as $1,dX as Bw,c9 as _b,bE as qh,c7 as Va,bM as Hk,C as fs,ah as ba,ai as Ss,a4 as zt,aG as Kn,aH as Ls,u as nn,a3 as su,aN as k0,ca as K$,aO as T0,dY as w4,dZ as Y$,a as Bn,c as yt,e as R0,d_ as ym,d$ as X$,e0 as Q$,e1 as J$,e2 as Z$,aK as C4,aJ as Jr,e3 as Uk,e4 as cl,e5 as hy,e6 as fy,dj as xl,cb as Gk,cL as Gl,cu as Sb,ct as ez,cs as Ys,cv as ln,e7 as y4,e8 as tz,e9 as z1,d as xt,cB as Vk,cX as nz,Z as Hi,ay as Ba,D as Wk,ea as VA,eb as sz,ec as rz,ed as q1,ee as iz,ef as az,eg as oz,eh as lz,aC as Kh,ei as WA,ej as $A,ek as cz,el as uz,em as dz,en as _4,eo as hz,ep as fz,eq as S4,er as jw,es as Hw,et as pz,eu as gz,ev as mz,ew as zA,ex as vz,ey as Bh,ez as E4,eA as bz,eB as xz,eC as wz,eD as Cz,eE as yz,eF as _z,eG as Sz,eH as k4,eI as Ez,eJ as kz,a0 as bi,eK as T4,eL as Tz,eM as qA,eN as Rz,eO as Az,eP as Ui,eQ as Uw,eR as R4,eS as Fz,eT as Dz,eU as KA,eV as Pz,eW as Iz,aP as np,eX as Nz,eY as Mz,eZ as Oz,bm as A4,e_ as Lz,e$ as Bz,f0 as jz,dQ as F4,f1 as Hz,bD as Bo,f2 as Uz,f3 as Gz,bC as bd,f4 as zc,f5 as Vz,ad as $k,f6 as YA,f7 as Wz,f8 as $z,f9 as zz,fa as qz,fb as Kz,fc as Yz,fd as Rh,cP as Xz,fe as Qz,ff as Jz,cS as Zz,fg as Gw,fh as K1,fi as Vw,fj as eq,fk as tq,fl as nq,fm as sq,at as ed,fn as py,_ as D4,fo as P4,aR as I4,aT as pa,fp as zk,bq as N4,aL as qk,cM as Ww,fq as M4,bI as qc,cg as $w,fr as rq,ch as zw,bA as xd,fs as iq,ft as aq,fu as oq,fv as lq,fw as cq,fx as uq,fy as dq,fz as hq,fA as XA,fB as fq,fC as pq,fD as Kk,fE as QA,cU as gq,fF as mq,fG as O4,fH as vq,fI as bq,fJ as L4,fK as Y1,fL as xq,b as B4,fM as Yh,fN as sp,fO as wq,fP as Yk,br as Cq,fQ as yq,fR as _q,fS as Sq,fT as JA,fU as Eq,fV as qw,fW as kq,fX as Tq,fY as j4,fZ as H4,f_ as Rq,f$ as U4,g0 as tx,g1 as Aq,g2 as Fq,g3 as Dq,g4 as Pq,g5 as Iq,g6 as Nq,g7 as Mq,av as ls,g8 as Oq,au as Ac,g9 as G4,ga as V4,gb as Lq,gc as Bq,gd as jq,cj as Kw,ck as Yw,ge as Xw,gf as xa,gg as Hq,gh as kn,gi as en,gj as A0,gk as _m,gl as Qw,gm as Xk,gn as Jw,go as Uq,gp as Gq,gq as Vq,gr as fn,gs as Sm,gt as W4,gu as ra,gv as wd,gw as Wq,gx as $q,gy as zq,gz as qq,gA as ZA,gB as Kq,gC as Yq,gD as Xq,ci as Qq,gE as Jq,gF as Xh,gG as $4,gH as z4,gI as Qk,gJ as nx,gK as q4,V as Jk,gL as X1,gM as Zk,gN as gy,gO as Zq,gP as eK,gQ as tK,gR as jh,gS as Q1,gT as K4,gU as nK,gV as Y4,gW as sK,gX as rK,gY as iK,gZ as aK,g_ as oK,g$ as lK,h0 as cK,h1 as uK,h2 as dK,h3 as hK,h4 as sx,h5 as fK,h6 as pK,h7 as gK,h8 as mK,h9 as vK,ha as bK,hb as eT,hc as xK,hd as X4,I as nt,he as wK,hf as Zw,hg as rp,bL as Q4,bP as CK,hh as eF,bh as J4,hi as yK,hj as _K,hk as SK,hl as EK,hm as kK,hn as TK,aA as Er,ho as RK,hp as AK,hq as FK,hr as DK,hs as PK,ht as IK,hu as NK,hv as MK,hw as OK,hx as LK,hy as BK,hz as jK,hA as Z4,hB as eC,hC as eB,hD as tT,hE as Ef,hF as tC,hG as nT,hH as HK,hI as UK,hJ as GK,hK as tB,hL as VK,hM as tF,hN as WK,hO as sT,hP as $K,hQ as rT,hR as F0,hS as D0,hT as zK,hU as nB,hV as Em,hW as qK,hX as KK,hY as YK,hZ as XK,h_ as QK,h$ as JK,i0 as nF,i1 as sB,ce as rB,i2 as ZK,i3 as eY,i4 as tY,aS as nC,i5 as nY,i6 as sY,i7 as sF,i8 as rY,i9 as iY,ia as iB,ib as rF,ic as aY,id as oY,ie as lY,ig as aB,ih as my,ii as cY,ij as oB,bz as Og,ik as iT,dF as uY,il as dY,bO as aT,im as Lc,io as oT,ip as lB,iq as hY,bv as fY,bw as sC,bt as kf,ir as cB,is as pY,it as uB,iu as dB,cr as vy,aI as P0,iv as iF,iw as gY,ix as rx,iy as aF,iz as mY,iA as vY,iB as bY,iC as xY,iD as hB,iE as wY,iF as oF,c3 as Ah,iG as CY,iH as yY,iI as _Y,iJ as SY,iK as fB,c4 as EY,iL as kY,iM as TY,iN as RY,iO as AY,iP as FY,dc as DY,iQ as PY,iR as lT,iS as IY,iT as NY,iU as bv,iV as pB,iW as J1,a8 as lF,iX as MY,iY as OY,iZ as LY,i_ as td,de as gB,df as cT,i$ as BY,j0 as jY,j1 as HY,j2 as mB,cc as UY,j3 as cF,ae as uF,j4 as GY,j5 as vB,j6 as VY,j7 as Lg,j8 as WY,bH as bB,j9 as $Y,ja as dF,jb as zY,jc as qY,bj as hF,bk as fF,bl as pF,aB as KY,jd as YY,je as XY,jf as QY,jg as JY,jh as dh,ji as hh,jj as ZY,jk as eX,jl as tX,jm as nX,jn as xB,jo as sX,jp as wB,jq as Z1,jr as eS,js as by,jt as rX,ju as iX,jv as Fh,jw as aX,aq as ix,as as CB,aw as oX,aa as gF,jx as lX,jy as cX,jz as uX,jA as dX,jB as hX,jC as fX,jD as pX,jE as yB,jF as gX,jG as tS,jH as _B,jI as SB,jJ as mX,jK as vX,jL as bX,jM as xX,jN as EB,jO as ip,jP as wX,jQ as CX,jR as uT,bn as yX,jS as _X,jT as SX,jU as EX,jV as kX,jW as TX,jX as RX,jY as AX,jZ as FX,j_ as DX,j$ as PX,bi as IX,k0 as mF,k1 as NX,k2 as xy,k3 as vF,k4 as MX,k5 as OX,k6 as LX,k7 as BX,k8 as jX,k9 as HX,ka as UX,kb as GX,kc as VX,kd as WX,ke as $X,kf as zX,kg as qX,kh as KX,ki as bF,kj as YX,kk as XX,al as QX,am as JX,an as ZX,ao as eQ,ap as tQ,kl as nQ,km as sQ,kn as rQ,ko as iQ,kp as aQ,kq as oQ,kr as lQ,ax as cQ,ks as uQ,kt as dQ,ku as hQ,kv as xF,cT as kB,kw as dT,kx as fQ,aQ as TB,ky as RB,kz as pQ,kA as gQ,kB as AB,kC as mQ,kD as kr,kE as vQ,kF as bc,kG as FB,kH as DB,kI as PB,kJ as hT,kK as Ri,kL as bQ,kM as xQ,kN as wQ,kO as CQ,kP as yQ,kQ as _Q,kR as SQ,kS as EQ,kT as kQ,kU as TQ,kV as RQ,kW as IB,kX as AQ,kY as FQ,kZ as DQ,k_ as PQ,k$ as IQ,l0 as nS,l1 as NQ,l2 as MQ,l3 as wF,l4 as NB,l5 as OQ,l6 as LQ,l7 as BQ,l8 as CF,l9 as jQ,la as HQ,lb as UQ,lc as GQ,ld as VQ,le as WQ,lf as $Q,lg as zQ,lh as MB,li as qQ,lj as KQ,db as ax,lk as YQ,d6 as XQ,ll as yF,lm as QQ,ln as JQ,lo as ZQ,cH as eJ,cZ as tJ,lp as nJ,lq as sJ,lr as rJ,B as OB,cY as _F,ls as iJ,af as aJ,bB as Vl,lt as oJ,lu as lJ,lv as cJ,lw as ri,aU as SF,lx as ox,ly as uJ,lz as EF,lA as dJ,lB as wy,lC as Cy,lD as kF,lE as yy,lF as TF,lG as LB,lH as BB,lI as jB,lJ as hJ,aD as fJ,aE as pJ,lK as gJ,aF as mJ}from"./conversation-input-sync-_j7A_EDF.js";import{c as ft,af as vJ,ag as HB,ah as bJ,ai as xJ,aj as wJ,ak as CJ,al as yJ,am as _J,an as Up,ao as SJ,e as ru,S as pn,p as Qa,u as Et,B as ce,L as nr,I as ps,T as fT,g as Bs,X as Dn,ap as sS,aq as wl,D as Wl,a as $l,d as jo,y as ga,x as pi,o as I0,h as Tf,ae as rC,l as Je,a0 as ap,b as iC,A as Kr,f as aC,F as km,G as Tm,H as Rm,J as Am,K as Fm,q as Il,r as Ho,s as Nl,t as rS,v as Yr,w as Gt,ar as N0,as as EJ,at as kJ,z as Ml,ac as UB,au as iS,av as TJ,aw as RJ,ax as AJ,Y as GB,Z as VB,_ as aS,k as Eb,ad as FJ,a1 as Dm,a2 as WB,a3 as Rf,ay as Qh,az as DJ,M as RF,i as $B,aA as PJ,j as zB,aB as IJ,aC as AF,a4 as NJ,aa as oS,C as MJ,aD as Gp,aE as pT,N as gT,$ as OJ,a5 as LJ,a6 as BJ,a7 as jJ,a8 as HJ,a9 as UJ,aF as GJ,aG as VJ,aH as WJ,aI as $J,aJ as qB,m as FF,n as DF,E as zJ}from"./error-boundary-BCQ7FGQc.js";import{e as op,g as KB,s as qJ,t as KJ,v as lS,w as cS,x as YJ,u as qe,y as YB,z as XB,A as oC,S as XJ,B as QB,C as QJ,R as JJ,E as ZJ,F as Cl,G as PF,H as eZ,I as tZ,J as nZ,M as IF,L as lC,N as sZ,O as rZ,Q as mg,U as iZ,V as JB,W as aZ,X as NF,Y as MF,Z as oZ,_ as OF,$ as lZ,a0 as Eu,a1 as xv,a2 as cZ,a3 as uZ,a4 as dZ,a5 as LF,a6 as BF,a7 as hZ,a8 as fZ,a9 as pZ,aa as gZ,ab as jF,ac as HF,ad as UF,ae as mZ,af as vZ,ag as bZ,ah as xZ,ai as wZ,aj as GF,ak as CZ,al as yZ,am as VF,an as _Z,ao as SZ,ap as EZ,aq as kZ,ar as TZ,as as RZ,at as ZB,r as WF,au as AZ,T as FZ,av as DZ,aw as PZ,ax as IZ,ay as wv,az as Cv,aA as $F,aB as yv,aC as _v,aD as zF,aE as qF,aF as NZ,aG as kb,aH as MZ,aI as OZ,aJ as LZ,aK as BZ,aL as KF,aM as jZ,aN as HZ,aO as YF,aP as UZ}from"./ui-preferences-store-BSjv1eml.js";import{C as GZ}from"./console-mirror-D4VUczn2.js";const uS=8e3,e6=1e4;function VZ(e){return e?`“${e}”`:"Conversation"}const WZ="archived.";function $Z(e){return Ce.getState().archiveFacts[e]}function zZ(e){const t=Ce.getState(),n=t.archiveFacts[e];return n?n.archived:t.sessions.find(s=>s.session_id===e)?.archived}function qZ(){const e=Ce(t=>t.archiveUndo);g.useEffect(()=>{if(e===null)return;let t=!1;const n=()=>{t||(t=!0,r())},s=()=>{n();const i=Ce.getState().archiveUndo;i!==null&&i.sessionId===e.sessionId&&i.at===e.at&&Ce.getState().setArchiveUndo(null)},r=Ce.subscribe(()=>{const i=$Z(e.sessionId);i!==void 0&&!i.answered||q$(e.archived,zZ(e.sessionId))||s()});return n},[e])}function KZ(e){return e===1?"Draft":`${e} drafts`}const YZ="discarded.",XZ=e=>{const t=$1(e),n=t.length,s=t.filter(o=>!o.active).length,r=n===1?"chat":"chats",i=e.filter(o=>Bw(o)!==null&&$1([o]).length===0).length,a=[`Mark ${n} unread ${r} as read${s>0?`, including ${s} in Previous chats`:""}.`];return i>0&&a.push(`${i} unread ${i===1?"mark":"marks"} with no completion token cannot be cleared.`),{count:n,label:`Mark all ${n} read`,scope:a.join(" "),nameSuffix:s>0?`, including ${s} in Previous chats`:""}},t6=e=>e===1?"1 lives on another device and clears when that device updates.":`${e} live on other devices and clear when those devices update.`,QZ=e=>{if(e.attempted===0)return{tone:"success",message:"Nothing to clear."};const t=e.unknown-e.deferred,n=[e.superseded>0?`${e.superseded} ${e.superseded===1?"has a newer result and stays":"have newer results and stay"} unread.`:null,t>0?`${t} could not be cleared and ${t===1?"stays":"stay"} unread.`:null,e.deferred>0?t6(e.deferred):null].filter(s=>s!==null);return e.cleared===0?{tone:"warning",message:["Nothing was cleared.",...n].join(" ")}:{tone:"success",message:[`Marked ${e.cleared} ${e.cleared===1?"chat":"chats"} as read.`,...n].join(" ")}},_y="archive",XF="drafts-undo",QF="bulk-read-deferral",JZ=8e3;function ZZ(){const e=Ce(h=>h.archiveFailure),t=Ce(h=>h.archiveUndo),n=Ce(h=>h.draftsUndo),s=Ce(h=>h.bulkReadDeferral),r=Ce(h=>h.clearArchiveFailure),i=Ce(h=>h.setArchiveUndo),a=Ce(h=>h.setSessionArchived),o=Ce(h=>h.restoreDraftsUndo);qZ();const l=g.useRef(null);g.useEffect(()=>{if(e===null&&t===null){if(l.current===null)return;l.current=null,_b(_y);return}const h=e&&t?t.at>e.at?"offer":"failure":e?"failure":"offer",f=h==="offer"?t?.at??0:e?.at??0,p=l.current;l.current={kind:h,at:f},p!==null&&p.kind!==h&&f>p.at&&(h==="failure"?i(null):r());const m=(v,b)=>()=>{const w=Ce.getState();v==="offer"?w.archiveUndo?.at===b&&w.setArchiveUndo(null):w.archiveFailure?.at===b&&w.clearArchiveFailure();const C=l.current;C!==null&&C.kind===v&&C.at===b&&(l.current=null)};if(h==="failure"&&e){qh(`Could not ${e.archived?"archive":"unarchive"} “${e.title}”.${e.detail?` ${e.detail}`:""}`,{id:_y,duration:e6,onAutoClose:m("failure",e.at),onDismiss:m("failure",e.at),action:{label:"Retry",onClick:v=>{v.preventDefault(),a(e.sessionId,e.archived,e.title)}}});return}t&&Va(c.jsxs("span",{className:T("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:T("min-w-0 truncate"),children:VZ(t.title)}),c.jsx("span",{className:T("shrink-0"),children:WZ})]}),{id:_y,duration:uS,classNames:{content:"min-w-0"},onAutoClose:m("offer",t.at),onDismiss:m("offer",t.at),action:{label:"Undo",onClick:v=>{v.preventDefault(),a(t.sessionId,!t.archived,t.title)}}})},[e,t,i,r,a]);const u=g.useRef(!1);g.useEffect(()=>{if(n===null){if(!u.current)return;u.current=!1,_b(XF);return}u.current=!0;const h=()=>{const f=Ce.getState();f.draftsUndo?.at===n.at&&(f.setDraftsUndo(null),u.current=!1)};Va(c.jsxs("span",{className:T("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:T("min-w-0 truncate"),children:KZ(n.keys.length)}),c.jsx("span",{className:T("shrink-0"),children:YZ})]}),{id:XF,duration:uS,classNames:{content:"min-w-0"},onAutoClose:h,onDismiss:h,action:{label:"Undo",onClick:f=>{f.preventDefault(),o();const p=Ce.getState(),m=p.stagedByDiscard;p.setStagedByDiscard(null),n.keys.length===1&&m!==null&&Ce.getState().activeDraftKey===m&&Ce.getState().openDraft(n.keys[0])}}})},[n,o]);const d=g.useRef(!1);return g.useEffect(()=>{if(s===null){if(!d.current)return;d.current=!1,_b(QF);return}d.current=!0;const h=()=>{const f=Ce.getState();f.bulkReadDeferral?.at===s.at&&(f.clearBulkReadDeferral(),d.current=!1)};Va(t6(s.count),{id:QF,duration:JZ,onAutoClose:h,onDismiss:h})},[s]),null}const eee={"under-window":{dark:{canvas:.59,surface:.67,elevated:.87},light:{canvas:.61,surface:.5,elevated:.45}},menu:{dark:{canvas:.73,surface:.79,elevated:.94},light:{canvas:.79,surface:.7,elevated:.65}},popover:{dark:{canvas:.79,surface:.85,elevated:.97},light:{canvas:.86,surface:.79,elevated:.75}}},tee={"under-window":{dark:.15,light:.2},menu:{dark:.15,light:.2},popover:{dark:.15,light:.15}},nee={hover:.05,selected:.08,field:.05},Bg={alphaFloor:eee,controlMix:tee,stateAlpha:nee},JJe=["sidebars","full"],n6=(e,t)=>e!=="vibrancy"?"popover":t==="menu"?"menu":t==="popover"?"popover":"under-window",see=.96,s6=e=>Math.round(e*100)/100;function ree(e,t,n){const s=Bg.alphaFloor[n6(e,t)][n];return{canvas:s.canvas,surface:s.surface,elevated:s.elevated}}function iee(e){const t=Math.min(100,Math.max(0,e.intensity))/100,n=ree(e.mechanism,e.material,e.scheme),s=r=>{const i=Math.max(see,r);return s6(i-t*(i-r))};return{canvas:s(n.canvas),surface:s(n.surface),elevated:s(n.elevated)}}const aee={sidebars:["sidebar"],full:["sidebar","canvas","pane"]};function oee(e,t,n){return Bg.controlMix[n6(e,t)][n]}function lee(e){const t=iee(e),n=r=>s6(Math.min(1,Math.max(0,1-(1-r)/(1-t.canvas)))),s={"--lo-glass-a-canvas":String(t.canvas),"--lo-glass-a-surface":String(t.surface),"--lo-glass-a-elevated":String(t.elevated),"--lo-glass-a-row-hover":String(Bg.stateAlpha.hover),"--lo-glass-a-row-selected":String(Bg.stateAlpha.selected),"--lo-glass-a-field":String(Bg.stateAlpha.field),"--lo-glass-control-mix":String(oee(e.mechanism,e.material,e.scheme)),"--lo-glass-in-surface":String(n(t.surface)),"--lo-glass-in-elevated":String(n(t.elevated))};return{kinds:aee[e.coverage].join(" "),vars:s}}const r6=()=>document.documentElement,cee=["--lo-glass-a-canvas","--lo-glass-a-surface","--lo-glass-a-elevated","--lo-glass-a-row-hover","--lo-glass-a-row-selected","--lo-glass-a-field","--lo-glass-control-mix","--lo-glass-in-surface","--lo-glass-in-elevated"];let Tb=null;const lx=()=>r6().classList.contains("dark")?"dark":"light";function cx(e){Tb=e;const t=r6();if(!e||!e.active){delete t.dataset.glass;for(const r of cee)t.style.removeProperty(r);return}const{kinds:n,vars:s}=lee({coverage:e.settings.coverage,intensity:e.settings.intensity,mechanism:e.mechanism,material:e.settings.material,scheme:e.scheme});t.dataset.glass=n;for(const[r,i]of Object.entries(s))t.style.setProperty(r,i)}function uee(e){cx(e?{active:!0,scheme:e.scheme,mechanism:e.mechanism,settings:{coverage:e.coverage,intensity:e.intensity,material:e.material}}:null)}function i6(e){if(!e||!e.active||e.capability.mechanism==="none"){cx(null);return}e.restartRequired&&e.active||cx({active:!0,scheme:lx(),mechanism:e.capability.mechanism,settings:{coverage:e.settings.coverage,intensity:e.settings.intensity,material:e.settings.material}})}function dee(){!Tb||!Tb.active||(cx({...Tb,scheme:lx()}),window.api?.windowGlass?.reportScheme?.(lx()))}function hee(){const e=window.api?.windowGlass;return e?e.onState(t=>i6(t)):()=>{}}function ZJe(){const[e,t]=g.useState(null);return g.useEffect(()=>{const s=window.api?.windowGlass;if(!s)return;let r=!1;s.get().then(a=>{r||t(a)});const i=s.onState(a=>t(a));return()=>{r=!0,i()}},[]),{state:e,set:async s=>{const r=await window.api?.windowGlass?.set(s);r&&(t(r),i6(r),window.api?.windowGlass?.reportScheme?.(lx()))}}}var ja,Be=typeof window<"u"?window:void 0,ui=typeof globalThis<"u"?globalThis:Be,a6=Array.prototype,JF=a6.forEach,ZF=a6.indexOf,Ii=ui?.navigator,_t=ui?.document,li=ui?.location,dS=ui?.fetch,hS=ui!=null&&ui.XMLHttpRequest&&"withCredentials"in new ui.XMLHttpRequest?ui.XMLHttpRequest:void 0,eD=ui?.AbortController,Ns=Ii?.userAgent,Vt=Be??{},pl={DEBUG:!1,LIB_VERSION:"1.235.6"},Sy="$copy_autocapture",fee=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"];(function(e){e.GZipJS="gzip-js",e.Base64="base64"})(ja||(ja={}));var pee=["fatal","error","warning","log","info","debug"];function Zt(e,t){return e.indexOf(t)!==-1}var cC=function(e){return e.trim()},mT=function(e){return e.replace(/^\$/,"")},gee=Array.isArray,o6=Object.prototype,l6=o6.hasOwnProperty,uC=o6.toString,cs=gee||function(e){return uC.call(e)==="[object Array]"},Wa=e=>typeof e=="function",us=e=>e===Object(e)&&!cs(e),Hh=e=>{if(us(e)){for(var t in e)if(l6.call(e,t))return!1;return!0}return!1},wt=e=>e===void 0,Os=e=>uC.call(e)=="[object String]",fS=e=>Os(e)&&e.trim().length===0,iu=e=>e===null,En=e=>wt(e)||iu(e),qr=e=>uC.call(e)=="[object Number]",ml=e=>uC.call(e)==="[object Boolean]",mee=e=>e instanceof FormData,vee=e=>Zt(fee,e),c6=e=>{var t={_log:function(n){if(Be&&(pl.DEBUG||Vt.POSTHOG_DEBUG)&&!wt(Be.console)&&Be.console){for(var s=("__rrweb_original__"in Be.console[n])?Be.console[n].__rrweb_original__:Be.console[n],r=arguments.length,i=new Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];s(e,...i)}},info:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];t._log("log",...s)},warn:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];t._log("warn",...s)},error:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];t._log("error",...s)},critical:function(){for(var n=arguments.length,s=new Array(n),r=0;r<n;r++)s[r]=arguments[r];console.error(e,...s)},uninitializedWarning:n=>{t.error("You must initialize PostHog before calling ".concat(n))},createLogger:n=>c6("".concat(e," ").concat(n))};return t},Rt=c6("[PostHog.js]"),Mr=Rt.createLogger,bee=Mr("[ExternalScriptsLoader]"),tD=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return bee.warn("".concat(t," was requested but loading of external scripts is disabled.")),n("Loading of external scripts is disabled");var s=_t?.querySelectorAll("script");if(s){for(var r=0;r<s.length;r++)if(s[r].src===t)return n()}var i=()=>{if(!_t)return n("document not found");var a=_t.createElement("script");if(a.type="text/javascript",a.crossOrigin="anonymous",a.src=t,a.onload=u=>n(void 0,u),a.onerror=u=>n(u),e.config.prepare_external_dependency_script&&(a=e.config.prepare_external_dependency_script(a)),!a)return n("prepare_external_dependency_script returned null");var o,l=_t.querySelectorAll("body > script");l.length>0?(o=l[0].parentNode)===null||o===void 0||o.insertBefore(a,l[0]):_t.body.appendChild(a)};_t!=null&&_t.body?i():_t?.addEventListener("DOMContentLoaded",i)};function nD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,s)}return n}function We(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?nD(Object(n),!0).forEach(function(s){dt(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):nD(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function dt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u6(e,t){if(e==null)return{};var n,s,r=function(a,o){if(a==null)return{};var l,u,d={},h=Object.keys(a);for(u=0;u<h.length;u++)l=h[u],o.indexOf(l)>=0||(d[l]=a[l]);return d}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(s=0;s<i.length;s++)n=i[s],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}Vt.__PosthogExtensions__=Vt.__PosthogExtensions__||{},Vt.__PosthogExtensions__.loadExternalDependency=(e,t,n)=>{var s="/static/".concat(t,".js")+"?v=".concat(e.version);if(t==="remote-config"&&(s="/array/".concat(e.config.token,"/config.js")),t==="toolbar"){var r=3e5,i=Math.floor(Date.now()/r)*r;s="".concat(s,"&t=").concat(i)}var a=e.requestRouter.endpointFor("assets",s);tD(e,a,n)},Vt.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var s=e.requestRouter.endpointFor("api",t);tD(e,s,n)};var ux={};function Bc(e,t,n){if(cs(e)){if(JF&&e.forEach===JF)e.forEach(t,n);else if("length"in e&&e.length===+e.length){for(var s=0,r=e.length;s<r;s++)if(s in e&&t.call(n,e[s],s)===ux)return}}}function Nn(e,t,n){if(!En(e)){if(cs(e))return Bc(e,t,n);if(mee(e)){for(var s of e.entries())if(t.call(n,s[1],s[0])===ux)return}else for(var r in e)if(l6.call(e,r)&&t.call(n,e[r],r)===ux)return}}var xs=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return Bc(n,function(r){for(var i in r)r[i]!==void 0&&(e[i]=r[i])}),e},Rb=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return Bc(n,function(r){Bc(r,function(i){e.push(i)})}),e};function Ab(e){for(var t=Object.keys(e),n=t.length,s=new Array(n);n--;)s[n]=[t[n],e[t[n]]];return s}var sD=function(e){try{return e()}catch{return}},xee=function(e){return function(){try{for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];return e.apply(this,n)}catch(r){Rt.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Rt.critical(r)}}},Pm=function(e){var t={};return Nn(e,function(n,s){Os(n)&&n.length>0&&(t[s]=n)}),t};function wee(e,t){return n=e,s=i=>Os(i)&&!iu(t)?i.slice(0,t):i,r=new Set,function i(a,o){return a!==Object(a)?s?s(a,o):a:r.has(a)?void 0:(r.add(a),cs(a)?(l=[],Bc(a,u=>{l.push(i(u))})):(l={},Nn(a,(u,d)=>{r.has(u)||(l[d]=i(u,d))})),l);var l}(n);var n,s,r}var Cee=["herokuapp.com","vercel.app","netlify.app"];function yee(e){var t=e?.hostname;if(!Os(t))return!1;var n=t.split(".").slice(-2).join(".");for(var s of Cee)if(n===s)return!1;return!0}function d6(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n]}function Cs(e,t,n,s){var{capture:r=!1,passive:i=!0}=s??{};e?.addEventListener(t,n,{capture:r,passive:i})}var h6="$people_distinct_id",vg="__alias",bg="__timers",rD="$autocapture_disabled_server_side",pS="$heatmaps_enabled_server_side",iD="$exception_capture_enabled_server_side",aD="$web_vitals_enabled_server_side",f6="$dead_clicks_enabled_server_side",oD="$web_vitals_allowed_metrics",gS="$session_recording_enabled_server_side",lD="$console_log_recording_enabled_server_side",cD="$session_recording_network_payload_capture",uD="$session_recording_masking",dD="$session_recording_canvas_recording",hD="$replay_sample_rate",fD="$replay_minimum_duration",pD="$replay_script_config",dx="$sesid",xg="$session_is_sampled",Ey="$session_recording_url_trigger_activated_session",ky="$session_recording_event_trigger_activated_session",Uh="$enabled_feature_flags",Fb="$early_access_features",mS="$feature_flag_details",wg="$stored_person_properties",Nu="$stored_group_properties",vS="$surveys",Sv="$surveys_activated",hx="$flag_call_reported",dl="$user_state",bS="$client_session_props",xS="$capture_rate_limit",wS="$initial_campaign_params",CS="$initial_referrer_info",yS="$initial_person_info",fx="$epp",p6="__POSTHOG_TOOLBAR__",gD="$posthog_cookieless",_ee=[h6,vg,"__cmpns",bg,gS,pS,dx,Uh,dl,Fb,mS,Nu,wg,vS,hx,bS,xS,wS,CS,fx];function mD(e){var t;return e instanceof Element&&(e.id===p6||!((t=e.closest)===null||t===void 0||!t.call(e,".toolbar-global-fade-container")))}function dC(e){return!!e&&e.nodeType===1}function jc(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function g6(e){return!!e&&e.nodeType===3}function m6(e){return!!e&&e.nodeType===11}function vT(e){return e?cC(e).split(/\s+/):[]}function vD(e){var t=Be?.location.href;return!!(t&&e&&e.some(n=>t.match(n)))}function px(e){var t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return vT(t)}function v6(e){return En(e)?null:cC(e).split(/(\s+)/).filter(t=>Af(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function hC(e){var t="";return SS(e)&&!w6(e)&&e.childNodes&&e.childNodes.length&&Nn(e.childNodes,function(n){var s;g6(n)&&n.textContent&&(t+=(s=v6(n.textContent))!==null&&s!==void 0?s:"")}),cC(t)}function b6(e){return wt(e.target)?e.srcElement||null:(t=e.target)!==null&&t!==void 0&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var _S=["a","button","form","input","select","textarea","label"];function x6(e){var t=e.parentNode;return!(!t||!dC(t))&&t}function See(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;if(!Be||!e||jc(e,"html")||!dC(e)||n!=null&&n.url_allowlist&&!vD(n.url_allowlist)||n!=null&&n.url_ignorelist&&vD(n.url_ignorelist))return!1;if(n!=null&&n.dom_event_allowlist){var i=n.dom_event_allowlist;if(i&&!i.some(p=>t.type===p))return!1}for(var a=!1,o=[e],l=!0,u=e;u.parentNode&&!jc(u,"body");)if(m6(u.parentNode))o.push(u.parentNode.host),u=u.parentNode.host;else{if(!(l=x6(u)))break;if(s||_S.indexOf(l.tagName.toLowerCase())>-1)a=!0;else{var d=Be.getComputedStyle(l);d&&d.getPropertyValue("cursor")==="pointer"&&(a=!0)}o.push(l),u=l}if(!function(p,m){var v=m?.element_allowlist;if(wt(v))return!0;var b=function(y){if(v.some(k=>y.tagName.toLowerCase()===k))return{v:!0}};for(var w of p){var C=b(w);if(typeof C=="object")return C.v}return!1}(o,n)||!function(p,m){var v=m?.css_selector_allowlist;if(wt(v))return!0;var b=function(y){if(v.some(k=>y.matches(k)))return{v:!0}};for(var w of p){var C=b(w);if(typeof C=="object")return C.v}return!1}(o,n))return!1;var h=Be.getComputedStyle(e);if(h&&h.getPropertyValue("cursor")==="pointer"&&t.type==="click")return!0;var f=e.tagName.toLowerCase();switch(f){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return a?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(_S.indexOf(f)>-1||e.getAttribute("contenteditable")==="true")}}function SS(e){for(var t=e;t.parentNode&&!jc(t,"body");t=t.parentNode){var n=px(t);if(Zt(n,"ph-sensitive")||Zt(n,"ph-no-capture"))return!1}if(Zt(px(e),"ph-include"))return!0;var s=e.type||"";if(Os(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var r=e.name||e.id||"";return!(Os(r)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(r.replace(/[^a-zA-Z0-9]/g,"")))}function w6(e){return!!(jc(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||jc(e,"select")||jc(e,"textarea")||e.getAttribute("contenteditable")==="true")}var C6="(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11})",Eee=new RegExp("^(?:".concat(C6,")$")),kee=new RegExp(C6),y6="\\d{3}-?\\d{2}-?\\d{4}",Tee=new RegExp("^(".concat(y6,")$")),Ree=new RegExp("(".concat(y6,")"));function Af(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return!(En(e)||Os(e)&&(e=cC(e),(t?Eee:kee).test((e||"").replace(/[- ]/g,""))||(t?Tee:Ree).test(e)))}function _6(e){var t=hC(e);return Af(t="".concat(t," ").concat(S6(e)).trim())?t:""}function S6(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Nn(e.childNodes,function(n){var s;if(n&&((s=n.tagName)===null||s===void 0?void 0:s.toLowerCase())==="span")try{var r=hC(n);t="".concat(t," ").concat(r).trim(),n.childNodes&&n.childNodes.length&&(t="".concat(t," ").concat(S6(n)).trim())}catch(i){Rt.error("[AutoCapture]",i)}}),t}function Aee(e){return function(t){var n=t.map(s=>{var r,i,a="";if(s.tag_name&&(a+=s.tag_name),s.attr_class)for(var o of(s.attr_class.sort(),s.attr_class))a+=".".concat(o.replace(/"/g,""));var l=We(We(We(We({},s.text?{text:s.text}:{}),{},{"nth-child":(r=s.nth_child)!==null&&r!==void 0?r:0,"nth-of-type":(i=s.nth_of_type)!==null&&i!==void 0?i:0},s.href?{href:s.href}:{}),s.attr_id?{attr_id:s.attr_id}:{}),s.attributes),u={};return Ab(l).sort((d,h)=>{var[f]=d,[p]=h;return f.localeCompare(p)}).forEach(d=>{var[h,f]=d;return u[bD(h.toString())]=bD(f.toString())}),a+=":",a+=Ab(l).map(d=>{var[h,f]=d;return"".concat(h,'="').concat(f,'"')}).join("")});return n.join(";")}(function(t){return t.map(n=>{var s,r,i={text:(s=n.$el_text)===null||s===void 0?void 0:s.slice(0,400),tag_name:n.tag_name,href:(r=n.attr__href)===null||r===void 0?void 0:r.slice(0,2048),attr_class:Fee(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return Ab(n).filter(a=>{var[o]=a;return o.indexOf("attr__")===0}).forEach(a=>{var[o,l]=a;return i.attributes[o]=l}),i})}(e))}function bD(e){return e.replace(/"|\\"/g,'\\"')}function Fee(e){var t=e.attr__class;return t?cs(t)?t:vT(t):void 0}class E6{constructor(){this.clicks=[]}isRageClick(t,n,s){var r=this.clicks[this.clicks.length-1];if(r&&Math.abs(t-r.x)+Math.abs(n-r.y)<30&&s-r.timestamp<1e3){if(this.clicks.push({x:t,y:n,timestamp:s}),this.clicks.length===3)return!0}else this.clicks=[{x:t,y:n,timestamp:s}];return!1}}var Dee=["localhost","127.0.0.1"],Jh=e=>{var t=_t?.createElement("a");return wt(t)?null:(t.href=e,t)},Pee=function(e){var t,n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",r=[];return Nn(e,function(i,a){wt(i)||wt(a)||a==="undefined"||(t=encodeURIComponent((o=>o instanceof File)(i)?i.name:i.toString()),n=encodeURIComponent(a),r[r.length]=n+"="+t)}),r.join(s)},gx=function(e,t){for(var n,s=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;r<s.length;r++){var i=s[r].split("=");if(i[0]===t){n=i;break}}if(!cs(n)||n.length<2)return"";var a=n[1];try{a=decodeURIComponent(a)}catch{Rt.error("Skipping decoding for malformed query param: "+a)}return a.replace(/\+/g," ")},Ty=function(e,t,n){if(!e||!t||!t.length)return e;for(var s=e.split("#"),r=s[0]||"",i=s[1],a=r.split("?"),o=a[1],l=a[0],u=(o||"").split("&"),d=[],h=0;h<u.length;h++){var f=u[h].split("=");cs(f)&&(t.includes(f[0])?d.push(f[0]+"="+n):d.push(u[h]))}var p=l;return o!=null&&(p+="?"+d.join("&")),i!=null&&(p+="#"+i),p},mx=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},xD=Mr("[AutoCapture]");function Ry(e,t){return t.length>e?t.slice(0,e)+"...":t}function Iee(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!dC(t));return t}function Nee(e,t,n,s){var r=e.tagName.toLowerCase(),i={tag_name:r};_S.indexOf(r)>-1&&!n&&(r.toLowerCase()==="a"||r.toLowerCase()==="button"?i.$el_text=Ry(1024,_6(e)):i.$el_text=Ry(1024,hC(e)));var a=px(e);a.length>0&&(i.classes=a.filter(function(d){return d!==""})),Nn(e.attributes,function(d){var h;if((!w6(e)||["name","id","class","aria-label"].indexOf(d.name)!==-1)&&(s==null||!s.includes(d.name))&&!t&&Af(d.value)&&(h=d.name,!Os(h)||h.substring(0,10)!=="_ngcontent"&&h.substring(0,7)!=="_nghost")){var f=d.value;d.name==="class"&&(f=vT(f).join(" ")),i["attr__"+d.name]=Ry(1024,f)}});for(var o=1,l=1,u=e;u=Iee(u);)o++,u.tagName===e.tagName&&l++;return i.nth_child=o,i.nth_of_type=l,i}function Mee(e,t){for(var n,s,{e:r,maskAllElementAttributes:i,maskAllText:a,elementAttributeIgnoreList:o,elementsChainAsString:l}=t,u=[e],d=e;d.parentNode&&!jc(d,"body");)m6(d.parentNode)?(u.push(d.parentNode.host),d=d.parentNode.host):(u.push(d.parentNode),d=d.parentNode);var h,f=[],p={},m=!1,v=!1;if(Nn(u,k=>{var _=SS(k);k.tagName.toLowerCase()==="a"&&(m=k.getAttribute("href"),m=_&&m&&Af(m)&&m),Zt(px(k),"ph-no-capture")&&(v=!0),f.push(Nee(k,i,a,o));var E=function(R){if(!SS(R))return{};var F={};return Nn(R.attributes,function(A){if(A.name&&A.name.indexOf("data-ph-capture-attribute")===0){var N=A.name.replace("data-ph-capture-attribute-",""),M=A.value;N&&M&&Af(M)&&(F[N]=M)}}),F}(k);xs(p,E)}),v)return{props:{},explicitNoCapture:v};if(a||(e.tagName.toLowerCase()==="a"||e.tagName.toLowerCase()==="button"?f[0].$el_text=_6(e):f[0].$el_text=hC(e)),m){var b,w;f[0].attr__href=m;var C=(b=Jh(m))===null||b===void 0?void 0:b.host,y=Be==null||(w=Be.location)===null||w===void 0?void 0:w.host;C&&y&&C!==y&&(h=m)}return{props:xs({$event_type:r.type,$ce_version:1},l?{}:{$elements:f},{$elements_chain:Aee(f)},(n=f[0])!==null&&n!==void 0&&n.$el_text?{$el_text:(s=f[0])===null||s===void 0?void 0:s.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},p)}}let Oee=class{constructor(t){dt(this,"_initialized",!1),dt(this,"_isDisabledServerSide",null),dt(this,"rageclicks",new E6),dt(this,"_elementsChainAsString",!1),this.instance=t,this._elementSelectors=null}get config(){var t,n,s=us(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)===null||t===void 0?void 0:t.map(r=>new RegExp(r)),s.url_ignorelist=(n=s.url_ignorelist)===null||n===void 0?void 0:n.map(r=>new RegExp(r)),s}_addDomEventHandlers(){if(this.isBrowserSupported()){if(Be&&_t){var t=s=>{s=s||Be?.event;try{this._captureEvent(s)}catch(r){xD.error("Failed to capture event",r)}};if(Cs(_t,"submit",t,{capture:!0}),Cs(_t,"change",t,{capture:!0}),Cs(_t,"click",t,{capture:!0}),this.config.capture_copied_text){var n=s=>{s=s||Be?.event,this._captureEvent(s,Sy)};Cs(_t,"copy",n,{capture:!0}),Cs(_t,"cut",n,{capture:!0})}}}else xD.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(t){t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[rD]:!!t.autocapture_opt_out}),this._isDisabledServerSide=!!t.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(t){this._elementSelectors=t}getElementSelectors(t){var n,s=[];return(n=this._elementSelectors)===null||n===void 0||n.forEach(r=>{var i=_t?.querySelectorAll(r);i?.forEach(a=>{t===a&&s.push(r)})}),s}get isEnabled(){var t,n,s=(t=this.instance.persistence)===null||t===void 0?void 0:t.props[rD],r=this._isDisabledServerSide;if(iu(r)&&!ml(s)&&!this.instance.config.advanced_disable_decide)return!1;var i=(n=this._isDisabledServerSide)!==null&&n!==void 0?n:!!s;return!!this.instance.config.autocapture&&!i}_captureEvent(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"$autocapture";if(this.isEnabled){var s,r=b6(t);g6(r)&&(r=r.parentNode||null),n==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!==null&&s!==void 0&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&this._captureEvent(t,"$rageclick");var i=n===Sy;if(r&&See(r,t,this.config,i,i?["copy","cut"]:void 0)){var{props:a,explicitNoCapture:o}=Mee(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.config.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString});if(o)return!1;var l=this.getElementSelectors(r);if(l&&l.length>0&&(a.$element_selectors=l),n===Sy){var u,d=v6(Be==null||(u=Be.getSelection())===null||u===void 0?void 0:u.toString()),h=t.type||"clipboard";if(!d)return!1;a.$selected_content=d,a.$copy_type=h}return this.instance.capture(n,a),!0}}}isBrowserSupported(){return Wa(_t?.querySelectorAll)}};Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return qr(e)&&isFinite(e)&&Math.floor(e)===e});var wD="0123456789abcdef";let Lee=class ES{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,n,s,r){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(s)||!Number.isInteger(r)||t<0||n<0||s<0||r<0||t>0xffffffffffff||n>4095||s>1073741823||r>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=t/Math.pow(2,40),i[1]=t/Math.pow(2,32),i[2]=t/Math.pow(2,24),i[3]=t/Math.pow(2,16),i[4]=t/Math.pow(2,8),i[5]=t,i[6]=112|n>>>8,i[7]=n,i[8]=128|s>>>24,i[9]=s>>>16,i[10]=s>>>8,i[11]=s,i[12]=r>>>24,i[13]=r>>>16,i[14]=r>>>8,i[15]=r,new ES(i)}toString(){for(var t="",n=0;n<this.bytes.length;n++)t=t+wD.charAt(this.bytes[n]>>>4)+wD.charAt(15&this.bytes[n]),n!==3&&n!==5&&n!==7&&n!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new ES(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(var n=0;n<16;n++){var s=this.bytes[n]-t.bytes[n];if(s!==0)return Math.sign(s)}return 0}},Bee=class{constructor(){dt(this,"timestamp",0),dt(this,"counter",0),dt(this,"random",new jee)}generate(){var t=this.generateOrAbort();if(wt(t)){this.timestamp=0;var n=this.generateOrAbort();if(wt(n))throw new Error("Could not generate UUID after timestamp reset");return n}return t}generateOrAbort(){var t=Date.now();if(t>this.timestamp)this.timestamp=t,this.resetCounter();else{if(!(t+1e4>this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Lee.fromFieldsV7(this.timestamp,Math.trunc(this.counter/Math.pow(2,30)),this.counter&Math.pow(2,30)-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}};var CD,k6=e=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;t<e.length;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};Be&&!wt(Be.crypto)&&crypto.getRandomValues&&(k6=e=>crypto.getRandomValues(e));let jee=class{constructor(){dt(this,"buffer",new Uint32Array(8)),dt(this,"cursor",1/0)}nextUint32(){return this.cursor>=this.buffer.length&&(k6(this.buffer),this.cursor=0),this.buffer[this.cursor++]}};var Fc=()=>Hee().toString(),Hee=()=>(CD||(CD=new Bee)).generate(),Uee="Thu, 01 Jan 1970 00:00:00 GMT",Vp="",Gee=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Vee(e,t){if(t){var n=function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_t;if(Vp)return Vp;if(!i||["localhost","127.0.0.1"].includes(r))return"";for(var a=r.split("."),o=Math.min(a.length,8),l="dmn_chk_"+Fc(),u=new RegExp("(^|;)\\s*"+l+"=1");!Vp&&o--;){var d=a.slice(o).join("."),h=l+"=1;domain=."+d;i.cookie=h,u.test(i.cookie)&&(i.cookie=h+";expires="+Uee,Vp=d)}return Vp}(e);if(!n){var s=(r=>{var i=r.match(Gee);return i?i[0]:""})(e);s!==n&&Rt.info("Warning: cookie subdomain discovery mismatch",s,n),n=s}return n?"; domain=."+n:""}return""}var _c,_l={is_supported:()=>!!_t,error:function(e){Rt.error("cookieStore error: "+e)},get:function(e){if(_t){try{for(var t=e+"=",n=_t.cookie.split(";").filter(i=>i.length),s=0;s<n.length;s++){for(var r=n[s];r.charAt(0)==" ";)r=r.substring(1,r.length);if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length,r.length))}}catch{}return null}},parse:function(e){var t;try{t=JSON.parse(_l.get(e))||{}}catch{}return t},set:function(e,t,n,s,r){if(_t)try{var i="",a="",o=Vee(_t.location.hostname,s);if(n){var l=new Date;l.setTime(l.getTime()+24*n*60*60*1e3),i="; expires="+l.toUTCString()}r&&(a="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+i+"; SameSite=Lax; path=/"+o+a;return u.length>3686.4&&Rt.warn("cookieStore warning: large cookie, len="+u.length),_t.cookie=u,u}catch{return}},remove:function(e,t){try{_l.set(e,"",-1,t)}catch{return}}},Ay=null,Us={is_supported:function(){if(!iu(Ay))return Ay;var e=!0;if(wt(Be))e=!1;else try{var t="__mplssupport__";Us.set(t,"xyz"),Us.get(t)!=='"xyz"'&&(e=!1),Us.remove(t)}catch{e=!1}return e||Rt.error("localStorage unsupported; falling back to cookie store"),Ay=e,e},error:function(e){Rt.error("localStorage error: "+e)},get:function(e){try{return Be?.localStorage.getItem(e)}catch(t){Us.error(t)}return null},parse:function(e){try{return JSON.parse(Us.get(e))||{}}catch{}return null},set:function(e,t){try{Be?.localStorage.setItem(e,JSON.stringify(t))}catch(n){Us.error(n)}},remove:function(e){try{Be?.localStorage.removeItem(e)}catch(t){Us.error(t)}}},Wee=["distinct_id",dx,xg,fx,yS],Ev=We(We({},Us),{},{parse:function(e){try{var t={};try{t=_l.parse(e)||{}}catch{}var n=xs(t,JSON.parse(Us.get(e)||"{}"));return Us.set(e,n),n}catch{}return null},set:function(e,t,n,s,r,i){try{Us.set(e,t,void 0,void 0,i);var a={};Wee.forEach(o=>{t[o]&&(a[o]=t[o])}),Object.keys(a).length&&_l.set(e,a,n,s,r,i)}catch(o){Us.error(o)}},remove:function(e,t){try{Be?.localStorage.removeItem(e),_l.remove(e,t)}catch(n){Us.error(n)}}}),kv={},$ee={is_supported:function(){return!0},error:function(e){Rt.error("memoryStorage error: "+e)},get:function(e){return kv[e]||null},parse:function(e){return kv[e]||null},set:function(e,t){kv[e]=t},remove:function(e){delete kv[e]}},ku=null,hr={is_supported:function(){if(!iu(ku))return ku;if(ku=!0,wt(Be))ku=!1;else try{var e="__support__";hr.set(e,"xyz"),hr.get(e)!=='"xyz"'&&(ku=!1),hr.remove(e)}catch{ku=!1}return ku},error:function(e){Rt.error("sessionStorage error: ",e)},get:function(e){try{return Be?.sessionStorage.getItem(e)}catch(t){hr.error(t)}return null},parse:function(e){try{return JSON.parse(hr.get(e))||null}catch{}return null},set:function(e,t){try{Be?.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){hr.error(n)}},remove:function(e){try{Be?.sessionStorage.removeItem(e)}catch(t){hr.error(t)}}};(function(e){e[e.PENDING=-1]="PENDING",e[e.DENIED=0]="DENIED",e[e.GRANTED=1]="GRANTED"})(_c||(_c={}));let zee=class{constructor(t){this.instance=t}get config(){return this.instance.config}get consent(){return this.getDnt()?_c.DENIED:this.storedConsent}isOptedOut(){return this.consent===_c.DENIED||this.consent===_c.PENDING&&this.config.opt_out_capturing_by_default}isOptedIn(){return!this.isOptedOut()}optInOut(t){this.storage.set(this.storageKey,t?1:0,this.config.cookie_expiration,this.config.cross_subdomain_cookie,this.config.secure_cookie)}reset(){this.storage.remove(this.storageKey,this.config.cross_subdomain_cookie)}get storageKey(){var{token:t,opt_out_capturing_cookie_prefix:n}=this.instance.config;return(n||"__ph_opt_in_out_")+t}get storedConsent(){var t=this.storage.get(this.storageKey);return t==="1"?_c.GRANTED:t==="0"?_c.DENIED:_c.PENDING}get storage(){if(!this._storage){var t=this.config.opt_out_capturing_persistence_type;this._storage=t==="localStorage"?Us:_l;var n=t==="localStorage"?_l:Us;n.get(this.storageKey)&&(this._storage.get(this.storageKey)||this.optInOut(n.get(this.storageKey)==="1"),n.remove(this.storageKey,this.config.cross_subdomain_cookie))}return this._storage}getDnt(){return!!this.config.respect_dnt&&!!d6([Ii?.doNotTrack,Ii?.msDoNotTrack,Vt.doNotTrack],t=>Zt([!0,1,"1","yes"],t))}};var Tv=Mr("[Dead Clicks]"),qee=()=>!0,Kee=e=>{var t,n=!((t=e.instance.persistence)===null||t===void 0||!t.get_property(f6)),s=e.instance.config.capture_dead_clicks;return ml(s)?s:n};let T6=class{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(t,n,s){this.instance=t,this.isEnabled=n,this.onCapture=s,this.startIfEnabled()}onRemoteConfig(t){this.instance.persistence&&this.instance.persistence.register({[f6]:t?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.loadScript(()=>{this.start()})}loadScript(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.initDeadClicksAutocapture&&t(),(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"dead-clicks-autocapture",i=>{i?Tv.error("failed to load script",i):t()})}start(){var t;if(_t){if(!this._lazyLoadedDeadClicksAutocapture&&(t=Vt.__PosthogExtensions__)!==null&&t!==void 0&&t.initDeadClicksAutocapture){var n=us(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this._lazyLoadedDeadClicksAutocapture=Vt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this._lazyLoadedDeadClicksAutocapture.start(_t),Tv.info("starting...")}}else Tv.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,Tv.info("stopping..."))}};var Fy=Mr("[ExceptionAutocapture]");let Yee=class{constructor(t){var n;dt(this,"startCapturing",()=>{var s;if(Be&&this.isEnabled&&(s=Vt.__PosthogExtensions__)!==null&&s!==void 0&&s.errorWrappingFunctions){var r=Vt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=Vt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=Vt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.unwrapOnError&&this.config.capture_unhandled_errors&&(this.unwrapOnError=r(this.captureException.bind(this))),!this.unwrapUnhandledRejection&&this.config.capture_unhandled_rejections&&(this.unwrapUnhandledRejection=i(this.captureException.bind(this))),!this.unwrapConsoleError&&this.config.capture_console_errors&&(this.unwrapConsoleError=a(this.captureException.bind(this)))}catch(o){Fy.error("failed to start",o),this.stopCapturing()}}}),this.instance=t,this.remoteEnabled=!((n=this.instance.persistence)===null||n===void 0||!n.props[iD]),this.config=this.requiredConfig(),this.startIfEnabled()}requiredConfig(){var t=this.instance.config.capture_exceptions,n={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return us(t)?n=We(We({},n),t):(wt(t)?this.remoteEnabled:t)&&(n=We(We({},n),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),n}get isEnabled(){return this.config.capture_console_errors||this.config.capture_unhandled_errors||this.config.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(Fy.info("enabled"),this.loadScript(this.startCapturing))}loadScript(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.errorWrappingFunctions&&t(),(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"exception-autocapture",i=>{if(i)return Fy.error("failed to load script",i);t()})}stopCapturing(){var t,n,s;(t=this.unwrapOnError)===null||t===void 0||t.call(this),this.unwrapOnError=void 0,(n=this.unwrapUnhandledRejection)===null||n===void 0||n.call(this),this.unwrapUnhandledRejection=void 0,(s=this.unwrapConsoleError)===null||s===void 0||s.call(this),this.unwrapConsoleError=void 0}onRemoteConfig(t){var n=t.autocaptureExceptions;this.remoteEnabled=!!n||!1,this.config=this.requiredConfig(),this.instance.persistence&&this.instance.persistence.register({[iD]:this.remoteEnabled}),this.startIfEnabled()}captureException(t){var n=this.instance.requestRouter.endpointFor("ui");t.$exception_personURL="".concat(n,"/project/").concat(this.instance.config.token,"/person/").concat(this.instance.get_distinct_id()),this.instance.exceptions.sendExceptionEvent(t)}};function R6(e){return!wt(Event)&&A6(e,Event)}function A6(e,t){try{return e instanceof t}catch{return!1}}function Db(e,t){return Object.prototype.toString.call(e)==="[object ".concat(t,"]")}function Dy(e){return Db(e,"DOMError")}var yD=/\(error: (.*)\)/,_D=50,Gh="?";function Py(e,t,n,s){var r={platform:"web:javascript",filename:e,function:t==="<anonymous>"?Gh:t,in_app:!0};return wt(n)||(r.lineno=n),wt(s)||(r.colno=s),r}var Xee=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Qee=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Jee=/\((\S*)(?::(\d+))(?::(\d+))\)/,Zee=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ete=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,tte=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var s=t.sort((r,i)=>r[0]-i[0]).map(r=>r[1]);return function(r){for(var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=[],o=r.split(`
|
|
3
3
|
`),l=i;l<o.length;l++){var u=o[l];if(!(u.length>1024)){var d=yD.test(u)?u.replace(yD,"$1"):u;if(!d.match(/\S*Error: /)){for(var h of s){var f=h(d);if(f){a.push(f);break}}if(a.length>=_D)break}}}return function(p){if(!p.length)return[];var m=Array.from(p);return m.reverse(),m.slice(0,_D).map(v=>We(We({},v),{},{filename:v.filename||nte(m).filename,function:v.function||Gh}))}(a)}}([30,e=>{var t=Xee.exec(e);if(t){var[,n,s,r]=t;return Py(n,Gh,+s,+r)}var i=Qee.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){var a=Jee.exec(i[2]);a&&(i[2]=a[1],i[3]=a[2],i[4]=a[3])}var[o,l]=ED(i[1]||Gh,i[2]);return Py(l,o,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}}],[50,e=>{var t=Zee.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=ete.exec(t[3]);n&&(t[1]=t[1]||"eval",t[3]=n[1],t[4]=n[2],t[5]="")}var s=t[3],r=t[1]||Gh;return[r,s]=ED(r,s),Py(s,r,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]);function nte(e){return e[e.length-1]||{}}var Rv,SD,Iy,ED=(e,t)=>{var n=e.indexOf("safari-extension")!==-1,s=e.indexOf("safari-web-extension")!==-1;return n||s?[e.indexOf("@")!==-1?e.split("@")[0]:Gh,n?"safari-extension:".concat(t):"safari-web-extension:".concat(t)]:[e,t]},ste=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;function bT(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=e.stacktrace||e.stack||"",s=function(a){return a&&rte.test(a.message)?1:0}(e);try{var r=tte,i=function(a,o){var l=function(u){var d=globalThis._posthogChunkIds;if(!d)return{};var h=Object.keys(d);return Iy&&h.length===SD||(SD=h.length,Iy=h.reduce((f,p)=>{Rv||(Rv={});var m=Rv[p];if(m)f[m[0]]=m[1];else for(var v=u(p),b=v.length-1;b>=0;b--){var w=v[b],C=w?.filename,y=d[p];if(C&&y){f[C]=y,Rv[p]=[C,y];break}}return f},{})),Iy}(o);return a.forEach(u=>{u.filename&&(u.chunk_id=l[u.filename])}),a}(r(n,s),r);return i.slice(0,i.length-t)}catch{}return[]}var rte=/Minified React error #\d+;/i;function Ny(e,t){var n,s,r=bT(e),i=(n=t?.handled)===null||n===void 0||n,a=(s=t?.synthetic)!==null&&s!==void 0&&s;return{$exception_list:[{type:t!=null&&t.overrideExceptionType?t.overrideExceptionType:e.name,value:function(o){var l=o.message;return l.error&&typeof l.error.message=="string"?String(l.error.message):String(l)}(e),stacktrace:{frames:r,type:"raw"},mechanism:{handled:i,synthetic:a}}],$exception_level:"error"}}function My(e,t){var n,s,r,i=(n=t?.handled)===null||n===void 0||n,a=(s=t?.synthetic)===null||s===void 0||s,o={type:t!=null&&t.overrideExceptionType?t.overrideExceptionType:(r=t?.defaultExceptionType)!==null&&r!==void 0?r:"Error",value:e||t?.defaultExceptionMessage,mechanism:{handled:i,synthetic:a}};if(t!=null&&t.syntheticException){var l=bT(t.syntheticException,1);l.length&&(o.stacktrace={frames:l,type:"raw"})}return{$exception_list:[o],$exception_level:"error"}}function ite(e){return Os(e)&&!fS(e)&&pee.indexOf(e)>=0}function ate(e,t){var n,s,r=(n=t?.handled)===null||n===void 0||n,i=(s=t?.synthetic)===null||s===void 0||s,a=t!=null&&t.overrideExceptionType?t.overrideExceptionType:R6(e)?e.constructor.name:"Error",o="Non-Error 'exception' captured with keys: ".concat(function(d){var h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:40,f=Object.keys(d);if(f.sort(),!f.length)return"[object has no keys]";for(var p=f.length;p>0;p--){var m=f.slice(0,p).join(", ");if(!(m.length>h))return p===f.length||m.length<=h?m:"".concat(m.slice(0,h),"...")}return""}(e)),l={type:a,value:o,mechanism:{handled:r,synthetic:i}};if(t!=null&&t.syntheticException){var u=bT(t?.syntheticException,1);u.length&&(l.stacktrace={frames:u,type:"raw"})}return{$exception_list:[l],$exception_level:ite(e.level)?e.level:"error"}}function ote(e,t){var{error:n,event:s}=e,r={$exception_list:[]},i=n||s;if(Dy(i)||function(p){return Db(p,"DOMException")}(i)){var a=i;if(function(p){return"stack"in p}(i))r=Ny(i,t);else{var o=a.name||(Dy(a)?"DOMError":"DOMException"),l=a.message?"".concat(o,": ").concat(a.message):o,u=Dy(a)?"DOMError":"DOMException";r=My(l,We(We({},t),{},{overrideExceptionType:u,defaultExceptionMessage:l}))}return"code"in a&&(r.$exception_DOMException_code="".concat(a.code)),r}if(function(p){return Db(p,"ErrorEvent")}(i)&&i.error)return Ny(i.error,t);if(function(p){switch(Object.prototype.toString.call(p)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":return!0;default:return A6(p,Error)}}(i))return Ny(i,t);if(function(p){return Db(p,"Object")}(i)||R6(i))return ate(i,t);if(wt(n)&&Os(s)){var d="Error",h=s,f=s.match(ste);return f&&(d=f[1],h=f[2]),My(h,We(We({},t),{},{overrideExceptionType:d,defaultExceptionMessage:h}))}return My(i,t)}function vx(e){var t,n;return((t=JSON.stringify(e,(n=[],function(s,r){if(us(r)){for(;n.length>0&&n[n.length-1]!==this;)n.pop();return n.includes(r)?"[Circular]":(n.push(r),r)}return r})))===null||t===void 0?void 0:t.length)||0}function kS(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:66060288e-1;if(e.size>=t&&e.data.length>1){var n=Math.floor(e.data.length/2),s=e.data.slice(0,n),r=e.data.slice(n);return[kS({size:vx(s),data:s,sessionId:e.sessionId,windowId:e.windowId}),kS({size:vx(r),data:r,sessionId:e.sessionId,windowId:e.windowId})].flatMap(i=>i)}return[e]}var hl=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(hl||{}),Oa=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Oa||{}),TS="[SessionRecording]",RS="redacted",Av={initiatorTypes:["audio","beacon","body","css","early-hint","embed","fetch","frame","iframe","icon","image","img","input","link","navigation","object","ping","script","track","video","xmlhttprequest"],maskRequestFn:e=>e,recordHeaders:!1,recordBody:!1,recordInitialRequests:!1,recordPerformance:!1,performanceEntryTypeToObserve:["first-input","navigation","paint","resource"],payloadSizeLimitBytes:1e6,payloadHostDenyList:[".lr-ingest.io",".ingest.sentry.io",".clarity.ms","analytics.google.com"]},lte=["authorization","x-forwarded-for","authorization","cookie","set-cookie","x-api-key","x-real-ip","remote-addr","forwarded","proxy-authorization","x-csrf-token","x-csrftoken","x-xsrf-token"],cte=["password","secret","passwd","api_key","apikey","auth","credentials","mysql_pwd","privatekey","private_key","token"],ute=["/s/","/e/","/i/"];function kD(e,t,n,s){if(En(e))return e;var r=t?.["content-length"]||function(i){return new Blob([i]).size}(e);return Os(r)&&(r=parseInt(r)),r>n?TS+" ".concat(s," body too large to record (").concat(r," bytes)"):e}function TD(e,t){if(En(e))return e;var n=e;return Af(n,!1)||(n=TS+" "+t+" body "+RS),Nn(cte,s=>{var r,i;(r=n)!==null&&r!==void 0&&r.length&&((i=n)===null||i===void 0?void 0:i.indexOf(s))!==-1&&(n=TS+" "+t+" body "+RS+" as might contain: "+s)}),n}var dte=(e,t)=>{var n,s,r,i={payloadSizeLimitBytes:Av.payloadSizeLimitBytes,performanceEntryTypeToObserve:[...Av.performanceEntryTypeToObserve],payloadHostDenyList:[...t.payloadHostDenyList||[],...Av.payloadHostDenyList]},a=e.session_recording.recordHeaders!==!1&&t.recordHeaders,o=e.session_recording.recordBody!==!1&&t.recordBody,l=e.capture_performance!==!1&&t.recordPerformance,u=(n=i,r=Math.min(1e6,(s=n.payloadSizeLimitBytes)!==null&&s!==void 0?s:1e6),f=>(f!=null&&f.requestBody&&(f.requestBody=kD(f.requestBody,f.requestHeaders,r,"Request")),f!=null&&f.responseBody&&(f.responseBody=kD(f.responseBody,f.responseHeaders,r,"Response")),f)),d=f=>{return u(((v,b)=>{var w,C=Jh(v.name),y=b.indexOf("http")===0?(w=Jh(b))===null||w===void 0?void 0:w.pathname:b;y==="/"&&(y="");var k=C?.pathname.replace(y||"","");if(!(C&&k&&ute.some(_=>k.indexOf(_)===0)))return v})((m=(p=f).requestHeaders,En(m)||Nn(Object.keys(m??{}),v=>{lte.includes(v.toLowerCase())&&(m[v]=RS)}),p),e.api_host));var p,m},h=Wa(e.session_recording.maskNetworkRequestFn);return h&&Wa(e.session_recording.maskCapturedNetworkRequestFn)&&Rt.warn("Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored."),h&&(e.session_recording.maskCapturedNetworkRequestFn=f=>{var p=e.session_recording.maskNetworkRequestFn({url:f.name});return We(We({},f),{},{name:p?.url})}),i.maskRequestFn=Wa(e.session_recording.maskCapturedNetworkRequestFn)?f=>{var p,m,v,b=d(f);return b&&(p=(m=(v=e.session_recording).maskCapturedNetworkRequestFn)===null||m===void 0?void 0:m.call(v,b))!==null&&p!==void 0?p:void 0}:f=>function(p){if(!wt(p))return p.requestBody=TD(p.requestBody,"Request"),p.responseBody=TD(p.responseBody,"Response"),p}(d(f)),We(We(We({},Av),i),{},{recordHeaders:a,recordBody:o,recordPerformance:l,recordInitialRequests:l})};function ia(e,t,n,s,r){return t>n&&(Rt.warn("min cannot be greater than max."),t=n),qr(e)?e>n?(s&&Rt.warn(s+" cannot be greater than max: "+n+". Using max value instead."),n):e<t?(s&&Rt.warn(s+" cannot be less than min: "+t+". Using min value instead."),t):e:(s&&Rt.warn(s+" must be a number. using max or fallback. max: "+n+", fallback: "+r),ia(r||n,t,n,s))}let hte=class{constructor(t){var n,s,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};dt(this,"bucketSize",100),dt(this,"refillRate",10),dt(this,"mutationBuckets",{}),dt(this,"loggedTracker",{}),dt(this,"refillBuckets",()=>{Object.keys(this.mutationBuckets).forEach(i=>{this.mutationBuckets[i]=this.mutationBuckets[i]+this.refillRate,this.mutationBuckets[i]>=this.bucketSize&&delete this.mutationBuckets[i]})}),dt(this,"getNodeOrRelevantParent",i=>{var a=this.rrweb.mirror.getNode(i);if(a?.nodeName!=="svg"&&a instanceof Element){var o=a.closest("svg");if(o)return[this.rrweb.mirror.getId(o),o]}return[i,a]}),dt(this,"numberOfChanges",i=>{var a,o,l,u,d,h,f,p;return((a=(o=i.removes)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)+((l=(u=i.attributes)===null||u===void 0?void 0:u.length)!==null&&l!==void 0?l:0)+((d=(h=i.texts)===null||h===void 0?void 0:h.length)!==null&&d!==void 0?d:0)+((f=(p=i.adds)===null||p===void 0?void 0:p.length)!==null&&f!==void 0?f:0)}),dt(this,"throttleMutations",i=>{if(i.type!==3||i.data.source!==0)return i;var a=i.data,o=this.numberOfChanges(a);a.attributes&&(a.attributes=a.attributes.filter(u=>{var d,h,f,[p,m]=this.getNodeOrRelevantParent(u.id);return this.mutationBuckets[p]===0?!1:(this.mutationBuckets[p]=(d=this.mutationBuckets[p])!==null&&d!==void 0?d:this.bucketSize,this.mutationBuckets[p]=Math.max(this.mutationBuckets[p]-1,0),this.mutationBuckets[p]===0&&(this.loggedTracker[p]||(this.loggedTracker[p]=!0,(h=(f=this.options).onBlockedNode)===null||h===void 0||h.call(f,p,m))),u)}));var l=this.numberOfChanges(a);return l!==0||o===l?i:void 0}),this.rrweb=t,this.options=r,this.refillRate=ia((n=this.options.refillRate)!==null&&n!==void 0?n:this.refillRate,0,100,"mutation throttling refill rate"),this.bucketSize=ia((s=this.options.bucketSize)!==null&&s!==void 0?s:this.bucketSize,0,100,"mutation throttling bucket size"),setInterval(()=>{this.refillBuckets()},1e3)}};var ca=Uint8Array,di=Uint16Array,Ff=Uint32Array,xT=new ca([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),wT=new ca([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),RD=new ca([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),F6=function(e,t){for(var n=new di(31),s=0;s<31;++s)n[s]=t+=1<<e[s-1];var r=new Ff(n[30]);for(s=1;s<30;++s)for(var i=n[s];i<n[s+1];++i)r[i]=i-n[s]<<5|s;return[n,r]},D6=F6(xT,2),fte=D6[0],AS=D6[1];fte[28]=258,AS[258]=28;for(var AD=F6(wT,0)[1],P6=new di(32768),Gn=0;Gn<32768;++Gn){var Tu=(43690&Gn)>>>1|(21845&Gn)<<1;Tu=(61680&(Tu=(52428&Tu)>>>2|(13107&Tu)<<2))>>>4|(3855&Tu)<<4,P6[Gn]=((65280&Tu)>>>8|(255&Tu)<<8)>>>1}var jg=function(e,t,n){for(var s=e.length,r=0,i=new di(t);r<s;++r)++i[e[r]-1];var a,o=new di(t);for(r=0;r<t;++r)o[r]=o[r-1]+i[r-1]<<1;for(a=new di(s),r=0;r<s;++r)a[r]=P6[o[e[r]-1]++]>>>15-e[r];return a},Cd=new ca(288);for(Gn=0;Gn<144;++Gn)Cd[Gn]=8;for(Gn=144;Gn<256;++Gn)Cd[Gn]=9;for(Gn=256;Gn<280;++Gn)Cd[Gn]=7;for(Gn=280;Gn<288;++Gn)Cd[Gn]=8;var bx=new ca(32);for(Gn=0;Gn<32;++Gn)bx[Gn]=5;var pte=jg(Cd,9),gte=jg(bx,5),I6=function(e){return(e/8>>0)+(7&e&&1)},N6=function(e,t,n){(n==null||n>e.length)&&(n=e.length);var s=new(e instanceof di?di:e instanceof Ff?Ff:ca)(n-t);return s.set(e.subarray(t,n)),s},ll=function(e,t,n){n<<=7&t;var s=t/8>>0;e[s]|=n,e[s+1]|=n>>>8},Wp=function(e,t,n){n<<=7&t;var s=t/8>>0;e[s]|=n,e[s+1]|=n>>>8,e[s+2]|=n>>>16},Oy=function(e,t){for(var n=[],s=0;s<e.length;++s)e[s]&&n.push({s,f:e[s]});var r=n.length,i=n.slice();if(!r)return[new ca(0),0];if(r==1){var a=new ca(n[0].s+1);return a[n[0].s]=1,[a,1]}n.sort(function(_,E){return _.f-E.f}),n.push({s:-1,f:25001});var o=n[0],l=n[1],u=0,d=1,h=2;for(n[0]={s:-1,f:o.f+l.f,l:o,r:l};d!=r-1;)o=n[n[u].f<n[h].f?u++:h++],l=n[u!=d&&n[u].f<n[h].f?u++:h++],n[d++]={s:-1,f:o.f+l.f,l:o,r:l};var f=i[0].s;for(s=1;s<r;++s)i[s].s>f&&(f=i[s].s);var p=new di(f+1),m=FS(n[d-1],p,0);if(m>t){s=0;var v=0,b=m-t,w=1<<b;for(i.sort(function(_,E){return p[E.s]-p[_.s]||_.f-E.f});s<r;++s){var C=i[s].s;if(!(p[C]>t))break;v+=w-(1<<m-p[C]),p[C]=t}for(v>>>=b;v>0;){var y=i[s].s;p[y]<t?v-=1<<t-p[y]++-1:++s}for(;s>=0&&v;--s){var k=i[s].s;p[k]==t&&(--p[k],++v)}m=t}return[new ca(p),m]},FS=function(e,t,n){return e.s==-1?Math.max(FS(e.l,t,n+1),FS(e.r,t,n+1)):t[e.s]=n},FD=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new di(++t),s=0,r=e[0],i=1,a=function(l){n[s++]=l},o=1;o<=t;++o)if(e[o]==r&&o!=t)++i;else{if(!r&&i>2){for(;i>138;i-=138)a(32754);i>2&&(a(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(a(r),--i;i>6;i-=6)a(8304);i>2&&(a(i-3<<5|8208),i=0)}for(;i--;)a(r);i=1,r=e[o]}return[n.subarray(0,s),t]},$p=function(e,t){for(var n=0,s=0;s<t.length;++s)n+=e[s]*t[s];return n},DS=function(e,t,n){var s=n.length,r=I6(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var i=0;i<s;++i)e[r+i+4]=n[i];return 8*(r+4+s)},DD=function(e,t,n,s,r,i,a,o,l,u,d){ll(t,d++,n),++r[256];for(var h=Oy(r,15),f=h[0],p=h[1],m=Oy(i,15),v=m[0],b=m[1],w=FD(f),C=w[0],y=w[1],k=FD(v),_=k[0],E=k[1],R=new di(19),F=0;F<C.length;++F)R[31&C[F]]++;for(F=0;F<_.length;++F)R[31&_[F]]++;for(var A=Oy(R,7),N=A[0],M=A[1],D=19;D>4&&!N[RD[D-1]];--D);var L,V,j,te,X=u+5<<3,re=$p(r,Cd)+$p(i,bx)+a,G=$p(r,f)+$p(i,v)+a+14+3*D+$p(R,N)+(2*R[16]+3*R[17]+7*R[18]);if(X<=re&&X<=G)return DS(t,d,e.subarray(l,l+u));if(ll(t,d,1+(G<re)),d+=2,G<re){L=jg(f,p),V=f,j=jg(v,b),te=v;var J=jg(N,M);for(ll(t,d,y-257),ll(t,d+5,E-1),ll(t,d+10,D-4),d+=14,F=0;F<D;++F)ll(t,d+3*F,N[RD[F]]);d+=3*D;for(var ae=[C,_],O=0;O<2;++O){var U=ae[O];for(F=0;F<U.length;++F){var P=31&U[F];ll(t,d,J[P]),d+=N[P],P>15&&(ll(t,d,U[F]>>>5&127),d+=U[F]>>>12)}}}else L=pte,V=Cd,j=gte,te=bx;for(F=0;F<o;++F)if(s[F]>255){P=s[F]>>>18&31,Wp(t,d,L[P+257]),d+=V[P+257],P>7&&(ll(t,d,s[F]>>>23&31),d+=xT[P]);var z=31&s[F];Wp(t,d,j[z]),d+=te[z],z>3&&(Wp(t,d,s[F]>>>5&8191),d+=wT[z])}else Wp(t,d,L[s[F]]),d+=V[s[F]];return Wp(t,d,L[256]),d+V[256]},mte=new Ff([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vte=function(){for(var e=new Ff(256),t=0;t<256;++t){for(var n=t,s=9;--s;)n=(1&n&&3988292384)^n>>>1;e[t]=n}return e}(),bte=function(){var e=4294967295;return{p:function(t){for(var n=e,s=0;s<t.length;++s)n=vte[255&n^t[s]]^n>>>8;e=n},d:function(){return 4294967295^e}}},xte=function(e,t,n,s,r){return function(i,a,o,l,u,d){var h=i.length,f=new ca(l+h+5*(1+Math.floor(h/7e3))+u),p=f.subarray(l,f.length-u),m=0;if(!a||h<8)for(var v=0;v<=h;v+=65535){var b=v+65535;b<h?m=DS(p,m,i.subarray(v,b)):(p[v]=d,m=DS(p,m,i.subarray(v,h)))}else{for(var w=mte[a-1],C=w>>>13,y=8191&w,k=(1<<o)-1,_=new di(32768),E=new di(k+1),R=Math.ceil(o/3),F=2*R,A=function(de){return(i[de]^i[de+1]<<R^i[de+2]<<F)&k},N=new Ff(25e3),M=new di(288),D=new di(32),L=0,V=0,j=(v=0,0),te=0,X=0;v<h;++v){var re=A(v),G=32767&v,J=E[re];if(_[G]=J,E[re]=G,te<=v){var ae=h-v;if((L>7e3||j>24576)&&ae>423){m=DD(i,p,0,N,M,D,V,j,X,v-X,m),j=L=V=0,X=v;for(var O=0;O<286;++O)M[O]=0;for(O=0;O<30;++O)D[O]=0}var U=2,P=0,z=y,ne=G-J&32767;if(ae>2&&re==A(v-ne))for(var fe=Math.min(C,ae)-1,ue=Math.min(32767,v),le=Math.min(258,ae);ne<=ue&&--z&&G!=J;){if(i[v+U]==i[v+U-ne]){for(var q=0;q<le&&i[v+q]==i[v+q-ne];++q);if(q>U){if(U=q,P=ne,q>fe)break;var we=Math.min(ne,q-2),B=0;for(O=0;O<we;++O){var be=v-ne+O+32768&32767,ie=be-_[be]+32768&32767;ie>B&&(B=ie,J=be)}}}ne+=(G=J)-(J=_[G])+32768&32767}if(P){N[j++]=268435456|AS[U]<<18|AD[P];var Te=31&AS[U],ee=31&AD[P];V+=xT[Te]+wT[ee],++M[257+Te],++D[ee],te=v+U,++L}else N[j++]=i[v],++M[i[v]]}}m=DD(i,p,d,N,M,D,V,j,X,v-X,m)}return N6(f,0,l+I6(m)+u)}(e,t.level==null?6:t.level,t.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,s,!0)},PS=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},wte=function(e,t){var n=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=t.level<2?4:t.level==9?2:0,e[9]=3,t.mtime!=0&&PS(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),n){e[3]=8;for(var s=0;s<=n.length;++s)e[s+10]=n.charCodeAt(s)}},Cte=function(e){return 10+(e.filename&&e.filename.length+1||0)};function M6(e,t){t===void 0&&(t={});var n=bte(),s=e.length;n.p(e);var r=xte(e,t,Cte(t),8),i=r.length;return wte(r,t),PS(r,i-8,n.d()),PS(r,i-4,s),r}function O6(e,t){var n=e.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(e);for(var s=new ca(e.length+(e.length>>>1)),r=0,i=function(u){s[r++]=u},a=0;a<n;++a){if(r+5>s.length){var o=new ca(r+8+(n-a<<1));o.set(s),s=o}var l=e.charCodeAt(a);l<128||t?i(l):l<2048?(i(192|l>>>6),i(128|63&l)):l>55295&&l<57344?(i(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++a))>>>18),i(128|l>>>12&63),i(128|l>>>6&63),i(128|63&l)):(i(224|l>>>12),i(128|l>>>6&63),i(128|63&l))}return N6(s,0,r)}function yte(e,t){return function(n){for(var s=0,r=0;r<n.length;r++)s=(s<<5)-s+n.charCodeAt(r),s|=0;return Math.abs(s)}(e)%100<ia(100*t,0,100)}var Cg="[SessionRecording]",yr=Mr(Cg);function Fv(){var e,t;return Vt==null||(e=Vt.__PosthogExtensions__)===null||e===void 0||(t=e.rrweb)===null||t===void 0?void 0:t.record}var _te=3e5,Ste=[Oa.MouseMove,Oa.MouseInteraction,Oa.Scroll,Oa.ViewportResize,Oa.Input,Oa.TouchMove,Oa.MediaInteraction,Oa.Drag],PD=e=>({rrwebMethod:e,enqueuedAt:Date.now(),attempt:1});function Ru(e){return function(t,n){for(var s="",r=0;r<t.length;){var i=t[r++];s+=String.fromCharCode(i)}return s}(M6(O6(JSON.stringify(e))))}function ID(e){return e.type===hl.Custom&&e.data.tag==="sessionIdle"}function ND(e,t){return t.some(n=>n.matching==="regex"&&new RegExp(n.url).test(e))}let Ete=class{get sessionIdleThresholdMilliseconds(){return this.instance.config.session_recording.session_idle_threshold_ms||3e5}get started(){return this._captureStarted}get sessionManager(){if(!this.instance.sessionManager)throw new Error(Cg+" must be started with a valid sessionManager.");return this.instance.sessionManager}get fullSnapshotIntervalMillis(){var t,n;return this.triggerStatus==="trigger_pending"?6e4:(t=(n=this.instance.config.session_recording)===null||n===void 0?void 0:n.full_snapshot_interval_millis)!==null&&t!==void 0?t:_te}get isSampled(){var t=this.instance.get_property(xg);return ml(t)?t:null}get sessionDuration(){var t,n,s=(t=this.buffer)===null||t===void 0?void 0:t.data[((n=this.buffer)===null||n===void 0?void 0:n.data.length)-1],{sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0);return s?s.timestamp-r:null}get isRecordingEnabled(){var t=!!this.instance.get_property(gS),n=!this.instance.config.disable_session_recording;return Be&&t&&n}get isConsoleLogCaptureEnabled(){var t=!!this.instance.get_property(lD),n=this.instance.config.enable_recording_console_log;return n??t}get canvasRecording(){var t,n,s,r,i,a,o=this.instance.config.session_recording.captureCanvas,l=this.instance.get_property(dD),u=(t=(n=o?.recordCanvas)!==null&&n!==void 0?n:l?.enabled)!==null&&t!==void 0&&t,d=(s=(r=o?.canvasFps)!==null&&r!==void 0?r:l?.fps)!==null&&s!==void 0?s:4,h=(i=(a=o?.canvasQuality)!==null&&a!==void 0?a:l?.quality)!==null&&i!==void 0?i:.4;if(typeof h=="string"){var f=parseFloat(h);h=isNaN(f)?.4:f}return{enabled:u,fps:ia(d,0,12,"canvas recording fps",4),quality:ia(h,0,1,"canvas recording quality",.4)}}get networkPayloadCapture(){var t,n,s=this.instance.get_property(cD),r={recordHeaders:(t=this.instance.config.session_recording)===null||t===void 0?void 0:t.recordHeaders,recordBody:(n=this.instance.config.session_recording)===null||n===void 0?void 0:n.recordBody},i=r?.recordHeaders||s?.recordHeaders,a=r?.recordBody||s?.recordBody,o=us(this.instance.config.capture_performance)?this.instance.config.capture_performance.network_timing:this.instance.config.capture_performance,l=!!(ml(o)?o:s?.capturePerformance);return i||a||l?{recordHeaders:i,recordBody:a,recordPerformance:l}:void 0}get masking(){var t,n,s,r,i,a,o=this.instance.get_property(uD),l={maskAllInputs:(t=this.instance.config.session_recording)===null||t===void 0?void 0:t.maskAllInputs,maskTextSelector:(n=this.instance.config.session_recording)===null||n===void 0?void 0:n.maskTextSelector,blockSelector:(s=this.instance.config.session_recording)===null||s===void 0?void 0:s.blockSelector},u=(r=l?.maskAllInputs)!==null&&r!==void 0?r:o?.maskAllInputs,d=(i=l?.maskTextSelector)!==null&&i!==void 0?i:o?.maskTextSelector,h=(a=l?.blockSelector)!==null&&a!==void 0?a:o?.blockSelector;return wt(u)&&wt(d)&&wt(h)?void 0:{maskAllInputs:u==null||u,maskTextSelector:d,blockSelector:h}}get sampleRate(){var t=this.instance.get_property(hD);return qr(t)?t:null}get minimumDuration(){var t=this.instance.get_property(fD);return qr(t)?t:null}get status(){return this.receivedDecide?this.isRecordingEnabled?this.isSampled===!1?"disabled":this._urlBlocked?"paused":En(this._linkedFlag)||this._linkedFlagSeen?this.triggerStatus==="trigger_pending"?"buffering":ml(this.isSampled)?this.isSampled?"sampled":"disabled":"active":"buffering":"disabled":"buffering"}get urlTriggerStatus(){var t;return this._urlTriggers.length===0?"trigger_disabled":((t=this.instance)===null||t===void 0?void 0:t.get_property(Ey))===this.sessionId?"trigger_activated":"trigger_pending"}get eventTriggerStatus(){var t;return this._eventTriggers.length===0?"trigger_disabled":((t=this.instance)===null||t===void 0?void 0:t.get_property(ky))===this.sessionId?"trigger_activated":"trigger_pending"}get triggerStatus(){var t=this.eventTriggerStatus==="trigger_activated"||this.urlTriggerStatus==="trigger_activated",n=this.eventTriggerStatus==="trigger_pending"||this.urlTriggerStatus==="trigger_pending";return t?"trigger_activated":n?"trigger_pending":"trigger_disabled"}constructor(t){if(dt(this,"queuedRRWebEvents",[]),dt(this,"isIdle","unknown"),dt(this,"_linkedFlagSeen",!1),dt(this,"_lastActivityTimestamp",Date.now()),dt(this,"_linkedFlag",null),dt(this,"_removePageViewCaptureHook",void 0),dt(this,"_onSessionIdListener",void 0),dt(this,"_persistDecideOnSessionListener",void 0),dt(this,"_samplingSessionListener",void 0),dt(this,"_urlTriggers",[]),dt(this,"_urlBlocklist",[]),dt(this,"_urlBlocked",!1),dt(this,"_eventTriggers",[]),dt(this,"_removeEventTriggerCaptureHook",void 0),dt(this,"_forceAllowLocalhostNetworkCapture",!1),dt(this,"_onBeforeUnload",()=>{this._flushBuffer()}),dt(this,"_onOffline",()=>{this._tryAddCustomEvent("browser offline",{})}),dt(this,"_onOnline",()=>{this._tryAddCustomEvent("browser online",{})}),dt(this,"_onVisibilityChange",()=>{if(_t!=null&&_t.visibilityState){var r="window "+_t.visibilityState;this._tryAddCustomEvent(r,{})}}),this.instance=t,this._captureStarted=!1,this._endpoint="/s/",this.stopRrweb=void 0,this.receivedDecide=!1,!this.instance.sessionManager)throw yr.error("started without valid sessionManager"),new Error(Cg+" started without valid sessionManager. This is a bug.");if(this.instance.config.__preview_experimental_cookieless_mode)throw new Error(Cg+" cannot be used with __preview_experimental_cookieless_mode.");var{sessionId:n,windowId:s}=this.sessionManager.checkAndGetSessionAndWindowId();this.sessionId=n,this.windowId=s,this.buffer=this.clearBuffer(),this.sessionIdleThresholdMilliseconds>=this.sessionManager.sessionTimeoutMs&&yr.warn("session_idle_threshold_ms (".concat(this.sessionIdleThresholdMilliseconds,") is greater than the session timeout (").concat(this.sessionManager.sessionTimeoutMs,"). Session will never be detected as idle"))}startIfEnabledOrStop(t){this.isRecordingEnabled?(this._startCapture(t),Cs(Be,"beforeunload",this._onBeforeUnload),Cs(Be,"offline",this._onOffline),Cs(Be,"online",this._onOnline),Cs(Be,"visibilitychange",this._onVisibilityChange),this._setupSampling(),this._addEventTriggerListener(),En(this._removePageViewCaptureHook)&&(this._removePageViewCaptureHook=this.instance.on("eventCaptured",n=>{try{if(n.event==="$pageview"){var s=n!=null&&n.properties.$current_url?this._maskUrl(n?.properties.$current_url):"";if(!s)return;this._tryAddCustomEvent("$pageview",{href:s})}}catch(r){yr.error("Could not add $pageview to rrweb session",r)}})),this._onSessionIdListener||(this._onSessionIdListener=this.sessionManager.onSessionId((n,s,r)=>{var i,a,o,l;r&&(this._tryAddCustomEvent("$session_id_change",{sessionId:n,windowId:s,changeReason:r}),(i=this.instance)===null||i===void 0||(a=i.persistence)===null||a===void 0||a.unregister(ky),(o=this.instance)===null||o===void 0||(l=o.persistence)===null||l===void 0||l.unregister(Ey))}))):this.stopRecording()}stopRecording(){var t,n,s,r;this._captureStarted&&this.stopRrweb&&(this.stopRrweb(),this.stopRrweb=void 0,this._captureStarted=!1,Be?.removeEventListener("beforeunload",this._onBeforeUnload),Be?.removeEventListener("offline",this._onOffline),Be?.removeEventListener("online",this._onOnline),Be?.removeEventListener("visibilitychange",this._onVisibilityChange),this.clearBuffer(),clearInterval(this._fullSnapshotTimer),(t=this._removePageViewCaptureHook)===null||t===void 0||t.call(this),this._removePageViewCaptureHook=void 0,(n=this._removeEventTriggerCaptureHook)===null||n===void 0||n.call(this),this._removeEventTriggerCaptureHook=void 0,(s=this._onSessionIdListener)===null||s===void 0||s.call(this),this._onSessionIdListener=void 0,(r=this._samplingSessionListener)===null||r===void 0||r.call(this),this._samplingSessionListener=void 0,yr.info("stopped"))}_resetSampling(){var t;(t=this.instance.persistence)===null||t===void 0||t.unregister(xg)}makeSamplingDecision(t){var n,s=this.sessionId!==t,r=this.sampleRate;if(qr(r)){var i=this.isSampled,a=s||!ml(i),o=a?yte(t,r):i;a&&(o?this._reportStarted("sampled"):yr.warn("Sample rate (".concat(r,") has determined that this sessionId (").concat(t,") will not be sent to the server.")),this._tryAddCustomEvent("samplingDecisionMade",{sampleRate:r,isSampled:o})),(n=this.instance.persistence)===null||n===void 0||n.register({[xg]:o})}else this._resetSampling()}onRemoteConfig(t){var n,s,r,i,a,o;if(this._tryAddCustomEvent("$remote_config_received",t),this._persistRemoteConfig(t),this._linkedFlag=((n=t.sessionRecording)===null||n===void 0?void 0:n.linkedFlag)||null,(s=t.sessionRecording)!==null&&s!==void 0&&s.endpoint&&(this._endpoint=(o=t.sessionRecording)===null||o===void 0?void 0:o.endpoint),this._setupSampling(),!En(this._linkedFlag)&&!this._linkedFlagSeen){var l=Os(this._linkedFlag)?this._linkedFlag:this._linkedFlag.flag,u=Os(this._linkedFlag)?null:this._linkedFlag.variant;this.instance.onFeatureFlags((d,h)=>{var f=us(h)&&l in h,p=u?h[l]===u:f;p&&this._reportStarted("linked_flag_matched",{linkedFlag:l,linkedVariant:u}),this._linkedFlagSeen=p})}(r=t.sessionRecording)!==null&&r!==void 0&&r.urlTriggers&&(this._urlTriggers=t.sessionRecording.urlTriggers),(i=t.sessionRecording)!==null&&i!==void 0&&i.urlBlocklist&&(this._urlBlocklist=t.sessionRecording.urlBlocklist),(a=t.sessionRecording)!==null&&a!==void 0&&a.eventTriggers&&(this._eventTriggers=t.sessionRecording.eventTriggers),this.receivedDecide=!0,this.startIfEnabledOrStop()}_setupSampling(){qr(this.sampleRate)&&En(this._samplingSessionListener)&&(this._samplingSessionListener=this.sessionManager.onSessionId(t=>{this.makeSamplingDecision(t)}))}_persistRemoteConfig(t){if(this.instance.persistence){var n,s=this.instance.persistence,r=()=>{var i,a,o,l,u,d,h,f,p,m=(i=t.sessionRecording)===null||i===void 0?void 0:i.sampleRate,v=En(m)?null:parseFloat(m);En(v)&&this._resetSampling();var b=(a=t.sessionRecording)===null||a===void 0?void 0:a.minimumDurationMilliseconds;s.register({[gS]:!!t.sessionRecording,[lD]:(o=t.sessionRecording)===null||o===void 0?void 0:o.consoleLogRecordingEnabled,[cD]:We({capturePerformance:t.capturePerformance},(l=t.sessionRecording)===null||l===void 0?void 0:l.networkPayloadCapture),[uD]:(u=t.sessionRecording)===null||u===void 0?void 0:u.masking,[dD]:{enabled:(d=t.sessionRecording)===null||d===void 0?void 0:d.recordCanvas,fps:(h=t.sessionRecording)===null||h===void 0?void 0:h.canvasFps,quality:(f=t.sessionRecording)===null||f===void 0?void 0:f.canvasQuality},[hD]:v,[fD]:wt(b)?null:b,[pD]:(p=t.sessionRecording)===null||p===void 0?void 0:p.scriptConfig})};r(),(n=this._persistDecideOnSessionListener)===null||n===void 0||n.call(this),this._persistDecideOnSessionListener=this.sessionManager.onSessionId(r)}}log(t){var n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"log";(n=this.instance.sessionRecording)===null||n===void 0||n.onRRwebEmit({type:6,data:{plugin:"rrweb/console@1",payload:{level:s,trace:[],payload:[JSON.stringify(t)]}},timestamp:Date.now()})}_startCapture(t){if(!wt(Object.assign)&&!wt(Array.from)&&!(this._captureStarted||this.instance.config.disable_session_recording||this.instance.consent.isOptedOut())){var n,s;this._captureStarted=!0,this.sessionManager.checkAndGetSessionAndWindowId(),Fv()?this._onScriptLoaded():(n=Vt.__PosthogExtensions__)===null||n===void 0||(s=n.loadExternalDependency)===null||s===void 0||s.call(n,this.instance,this.scriptName,r=>{if(r)return yr.error("could not load recorder",r);this._onScriptLoaded()}),yr.info("starting"),this.status==="active"&&this._reportStarted(t||"recording_initialized")}}get scriptName(){var t,n,s;return((t=this.instance)===null||t===void 0||(n=t.persistence)===null||n===void 0||(s=n.get_property(pD))===null||s===void 0?void 0:s.script)||"recorder"}isInteractiveEvent(t){var n;return t.type===3&&Ste.indexOf((n=t.data)===null||n===void 0?void 0:n.source)!==-1}_updateWindowAndSessionIds(t){var n=this.isInteractiveEvent(t);n||this.isIdle||t.timestamp-this._lastActivityTimestamp>this.sessionIdleThresholdMilliseconds&&(this.isIdle=!0,clearInterval(this._fullSnapshotTimer),this._tryAddCustomEvent("sessionIdle",{eventTimestamp:t.timestamp,lastActivityTimestamp:this._lastActivityTimestamp,threshold:this.sessionIdleThresholdMilliseconds,bufferLength:this.buffer.data.length,bufferSize:this.buffer.size}),this._flushBuffer());var s=!1;if(n&&(this._lastActivityTimestamp=t.timestamp,this.isIdle)){var r=this.isIdle==="unknown";this.isIdle=!1,r||(this._tryAddCustomEvent("sessionNoLongerIdle",{reason:"user activity",type:t.type}),s=!0)}if(!this.isIdle){var{windowId:i,sessionId:a}=this.sessionManager.checkAndGetSessionAndWindowId(!n,t.timestamp),o=this.sessionId!==a,l=this.windowId!==i;this.windowId=i,this.sessionId=a,o||l?(this.stopRecording(),this.startIfEnabledOrStop("session_id_changed")):s&&this._scheduleFullSnapshot()}}_tryRRWebMethod(t){try{return t.rrwebMethod(),!0}catch(n){return this.queuedRRWebEvents.length<10?this.queuedRRWebEvents.push({enqueuedAt:t.enqueuedAt||Date.now(),attempt:t.attempt++,rrwebMethod:t.rrwebMethod}):yr.warn("could not emit queued rrweb event.",n,t),!1}}_tryAddCustomEvent(t,n){return this._tryRRWebMethod(PD(()=>Fv().addCustomEvent(t,n)))}_tryTakeFullSnapshot(){return this._tryRRWebMethod(PD(()=>Fv().takeFullSnapshot()))}_onScriptLoaded(){var t,n,s,r,i={blockClass:"ph-no-capture",blockSelector:void 0,ignoreClass:"ph-ignore-input",maskTextClass:"ph-mask",maskTextSelector:void 0,maskTextFn:void 0,maskAllInputs:!0,maskInputOptions:{password:!0},maskInputFn:void 0,slimDOMOptions:{},collectFonts:!1,inlineStylesheet:!0,recordCrossOriginIframes:!1},a=this.instance.config.session_recording;for(var[o,l]of Object.entries(a||{}))o in i&&(o==="maskInputOptions"?i.maskInputOptions=We({password:!0},l):i[o]=l);this.canvasRecording&&this.canvasRecording.enabled&&(i.recordCanvas=!0,i.sampling={canvas:this.canvasRecording.fps},i.dataURLOptions={type:"image/webp",quality:this.canvasRecording.quality}),this.masking&&(i.maskAllInputs=(n=this.masking.maskAllInputs)===null||n===void 0||n,i.maskTextSelector=(s=this.masking.maskTextSelector)!==null&&s!==void 0?s:void 0,i.blockSelector=(r=this.masking.blockSelector)!==null&&r!==void 0?r:void 0);var u=Fv();if(u){this.mutationRateLimiter=(t=this.mutationRateLimiter)!==null&&t!==void 0?t:new hte(u,{refillRate:this.instance.config.session_recording.__mutationRateLimiterRefillRate,bucketSize:this.instance.config.session_recording.__mutationRateLimiterBucketSize,onBlockedNode:(h,f)=>{var p="Too many mutations on node '".concat(h,"'. Rate limiting. This could be due to SVG animations or something similar");yr.info(p,{node:f}),this.log(Cg+" "+p,"warn")}});var d=this._gatherRRWebPlugins();this.stopRrweb=u(We({emit:h=>{this.onRRwebEmit(h)},plugins:d},i)),this._lastActivityTimestamp=Date.now(),this.isIdle=ml(this.isIdle)?this.isIdle:"unknown",this._tryAddCustomEvent("$session_options",{sessionRecordingOptions:i,activePlugins:d.map(h=>h?.name)}),this._tryAddCustomEvent("$posthog_config",{config:this.instance.config})}else yr.error("onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.")}_scheduleFullSnapshot(){if(this._fullSnapshotTimer&&clearInterval(this._fullSnapshotTimer),this.isIdle!==!0){var t=this.fullSnapshotIntervalMillis;t&&(this._fullSnapshotTimer=setInterval(()=>{this._tryTakeFullSnapshot()},t))}}_gatherRRWebPlugins(){var t,n,s,r,i=[],a=(t=Vt.__PosthogExtensions__)===null||t===void 0||(n=t.rrwebPlugins)===null||n===void 0?void 0:n.getRecordConsolePlugin;a&&this.isConsoleLogCaptureEnabled&&i.push(a());var o=(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.rrwebPlugins)===null||r===void 0?void 0:r.getRecordNetworkPlugin;return this.networkPayloadCapture&&Wa(o)&&(!Dee.includes(location.hostname)||this._forceAllowLocalhostNetworkCapture?i.push(o(dte(this.instance.config,this.networkPayloadCapture))):yr.info("NetworkCapture not started because we are on localhost.")),i}onRRwebEmit(t){var n;if(this._processQueuedEvents(),t&&us(t)){if(t.type===hl.Meta){var s=this._maskUrl(t.data.href);if(this._lastHref=s,!s)return;t.data.href=s}else this._pageViewFallBack();if(this._checkUrlTriggerConditions(),!this._urlBlocked||function(h){return h.type===hl.Custom&&h.data.tag==="recording paused"}(t)){t.type===hl.FullSnapshot&&this._scheduleFullSnapshot(),t.type===hl.FullSnapshot&&this.triggerStatus==="trigger_pending"&&this.clearBuffer();var r=this.mutationRateLimiter?this.mutationRateLimiter.throttleMutations(t):t;if(r){var i=function(h){var f=h;if(f&&us(f)&&f.type===6&&us(f.data)&&f.data.plugin==="rrweb/console@1"){f.data.payload.payload.length>10&&(f.data.payload.payload=f.data.payload.payload.slice(0,10),f.data.payload.payload.push("...[truncated]"));for(var p=[],m=0;m<f.data.payload.payload.length;m++)f.data.payload.payload[m]&&f.data.payload.payload[m].length>2e3?p.push(f.data.payload.payload[m].slice(0,2e3)+"...[truncated]"):p.push(f.data.payload.payload[m]);return f.data.payload.payload=p,h}return h}(r);if(this._updateWindowAndSessionIds(i),this.isIdle!==!0||ID(i)){if(ID(i)){var a=i.data.payload;if(a){var o=a.lastActivityTimestamp,l=a.threshold;i.timestamp=o+l}}var u=(n=this.instance.config.session_recording.compress_events)===null||n===void 0||n?function(h){if(vx(h)<1024)return h;try{if(h.type===hl.FullSnapshot)return We(We({},h),{},{data:Ru(h.data),cv:"2024-10"});if(h.type===hl.IncrementalSnapshot&&h.data.source===Oa.Mutation)return We(We({},h),{},{cv:"2024-10",data:We(We({},h.data),{},{texts:Ru(h.data.texts),attributes:Ru(h.data.attributes),removes:Ru(h.data.removes),adds:Ru(h.data.adds)})});if(h.type===hl.IncrementalSnapshot&&h.data.source===Oa.StyleSheetRule)return We(We({},h),{},{cv:"2024-10",data:We(We({},h.data),{},{adds:h.data.adds?Ru(h.data.adds):void 0,removes:h.data.removes?Ru(h.data.removes):void 0})})}catch(f){yr.error("could not compress event - will use uncompressed event",f)}return h}(i):i,d={$snapshot_bytes:vx(u),$snapshot_data:u,$session_id:this.sessionId,$window_id:this.windowId};this.status!=="disabled"?this._captureSnapshotBuffered(d):this.clearBuffer()}}}}}_pageViewFallBack(){if(!this.instance.config.capture_pageview&&Be){var t=this._maskUrl(Be.location.href);this._lastHref!==t&&(this._tryAddCustomEvent("$url_changed",{href:t}),this._lastHref=t)}}_processQueuedEvents(){if(this.queuedRRWebEvents.length){var t=[...this.queuedRRWebEvents];this.queuedRRWebEvents=[],t.forEach(n=>{Date.now()-n.enqueuedAt<=2e3&&this._tryRRWebMethod(n)})}}_maskUrl(t){var n=this.instance.config.session_recording;if(n.maskNetworkRequestFn){var s,r={url:t};return(s=r=n.maskNetworkRequestFn(r))===null||s===void 0?void 0:s.url}return t}clearBuffer(){return this.buffer={size:0,data:[],sessionId:this.sessionId,windowId:this.windowId},this.buffer}_flushBuffer(){this.flushBufferTimer&&(clearTimeout(this.flushBufferTimer),this.flushBufferTimer=void 0);var t=this.minimumDuration,n=this.sessionDuration,s=qr(n)&&n>=0,r=qr(t)&&s&&n<t;return this.status==="buffering"||this.status==="paused"||this.status==="disabled"||r?(this.flushBufferTimer=setTimeout(()=>{this._flushBuffer()},2e3),this.buffer):(this.buffer.data.length>0&&kS(this.buffer).forEach(i=>{this._captureSnapshot({$snapshot_bytes:i.size,$snapshot_data:i.data,$session_id:i.sessionId,$window_id:i.windowId,$lib:"web",$lib_version:pl.LIB_VERSION})}),this.clearBuffer())}_captureSnapshotBuffered(t){var n,s=2+(((n=this.buffer)===null||n===void 0?void 0:n.data.length)||0);!this.isIdle&&(this.buffer.size+t.$snapshot_bytes+s>943718.4||this.buffer.sessionId!==this.sessionId)&&(this.buffer=this._flushBuffer()),this.buffer.size+=t.$snapshot_bytes,this.buffer.data.push(t.$snapshot_data),this.flushBufferTimer||this.isIdle||(this.flushBufferTimer=setTimeout(()=>{this._flushBuffer()},2e3))}_captureSnapshot(t){this.instance.capture("$snapshot",t,{_url:this.instance.requestRouter.endpointFor("api",this._endpoint),_noTruncate:!0,_batchKey:"recordings",skip_client_rate_limiting:!0})}_checkUrlTriggerConditions(){if(Be!==void 0&&Be.location.href){var t=Be.location.href,n=this._urlBlocked,s=ND(t,this._urlBlocklist);s&&!n?this._pauseRecording():!s&&n&&this._resumeRecording(),ND(t,this._urlTriggers)&&this._activateTrigger("url")}}_activateTrigger(t){var n,s;this.triggerStatus==="trigger_pending"&&((n=this.instance)===null||n===void 0||(s=n.persistence)===null||s===void 0||s.register({[t==="url"?Ey:ky]:this.sessionId}),this._flushBuffer(),this._reportStarted(t+"_trigger_matched"))}_pauseRecording(){this._urlBlocked||(this._urlBlocked=!0,clearInterval(this._fullSnapshotTimer),yr.info("recording paused due to URL blocker"),this._tryAddCustomEvent("recording paused",{reason:"url blocker"}))}_resumeRecording(){this._urlBlocked&&(this._urlBlocked=!1,this._tryTakeFullSnapshot(),this._scheduleFullSnapshot(),this._tryAddCustomEvent("recording resumed",{reason:"left blocked url"}),yr.info("recording resumed"))}_addEventTriggerListener(){this._eventTriggers.length!==0&&En(this._removeEventTriggerCaptureHook)&&(this._removeEventTriggerCaptureHook=this.instance.on("eventCaptured",t=>{try{this._eventTriggers.includes(t.event)&&this._activateTrigger("event")}catch(n){yr.error("Could not activate event trigger",n)}}))}overrideLinkedFlag(){this._linkedFlagSeen=!0,this._tryTakeFullSnapshot(),this._reportStarted("linked_flag_overridden")}overrideSampling(){var t;(t=this.instance.persistence)===null||t===void 0||t.register({[xg]:!0}),this._tryTakeFullSnapshot(),this._reportStarted("sampling_overridden")}overrideTrigger(t){this._activateTrigger(t)}_reportStarted(t,n){this.instance.register_for_session({$session_recording_start_reason:t}),yr.info(t.replace("_"," "),n),Zt(["recording_initialized","session_id_changed"],t)||this._tryAddCustomEvent(t,n)}get sdkDebugProperties(){var{sessionStartTimestamp:t}=this.sessionManager.checkAndGetSessionAndWindowId(!0);return{$recording_status:this.status,$sdk_debug_replay_internal_buffer_length:this.buffer.data.length,$sdk_debug_replay_internal_buffer_size:this.buffer.size,$sdk_debug_current_session_duration:this.sessionDuration,$sdk_debug_session_start:t}}};var Ly=Mr("[SegmentIntegration]");function kte(e,t){var n=e.config.segment;if(!n)return t();(function(s,r){var i=s.config.segment;if(!i)return r();var a=l=>{var u=()=>l.anonymousId()||Fc();s.config.get_device_id=u,l.id()&&(s.register({distinct_id:l.id(),$device_id:u()}),s.persistence.set_property(dl,"identified")),r()},o=i.user();"then"in o&&Wa(o.then)?o.then(l=>a(l)):a(o)})(e,()=>{n.register((s=>{Promise&&Promise.resolve||Ly.warn("This browser does not have Promise support, and can not use the segment integration");var r=(i,a)=>{var o;if(!a)return i;i.event.userId||i.event.anonymousId===s.get_distinct_id()||(Ly.info("No userId set, resetting PostHog"),s.reset()),i.event.userId&&i.event.userId!==s.get_distinct_id()&&(Ly.info("UserId set, identifying with PostHog"),s.identify(i.event.userId));var l=s._calculate_event_properties(a,(o=i.event.properties)!==null&&o!==void 0?o:{},new Date);return i.event.properties=Object.assign({},l,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>r(i,i.event.event),page:i=>r(i,"$pageview"),identify:i=>r(i,"$identify"),screen:i=>r(i,"$screen")}})(e)).then(()=>{t()})})}var L6="posthog-js";function B6(e){var{organization:t,projectId:n,prefix:s,severityAllowList:r=["error"]}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return i=>{var a,o,l,u,d;if(!(r==="*"||r.includes(i.level))||!e.__loaded)return i;i.tags||(i.tags={});var h=e.requestRouter.endpointFor("ui","/project/".concat(e.config.token,"/person/").concat(e.get_distinct_id()));i.tags["PostHog Person URL"]=h,e.sessionRecordingStarted()&&(i.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var f=((a=i.exception)===null||a===void 0?void 0:a.values)||[],p=f.map(v=>We(We({},v),{},{stacktrace:v.stacktrace?We(We({},v.stacktrace),{},{type:"raw",frames:(v.stacktrace.frames||[]).map(b=>We(We({},b),{},{platform:"web:javascript"}))}):void 0})),m={$exception_message:((o=f[0])===null||o===void 0?void 0:o.value)||i.message,$exception_type:(l=f[0])===null||l===void 0?void 0:l.type,$exception_personURL:h,$exception_level:i.level,$exception_list:p,$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:((u=f[0])===null||u===void 0?void 0:u.value)||i.message,$sentry_exception_type:(d=f[0])===null||d===void 0?void 0:d.type,$sentry_tags:i.tags};return t&&n&&(m.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+i.event_id),e.exceptions.sendExceptionEvent(m),i}}let Tte=class{constructor(t,n,s,r,i){this.name=L6,this.setupOnce=function(a){a(B6(t,{organization:n,projectId:s,prefix:r,severityAllowList:i}))}}};var fl,Rte=Be!=null&&Be.location?mx(Be.location.hash,"__posthog")||mx(location.hash,"state"):null,MD="_postHogToolbarParams",OD=Mr("[Toolbar]");(function(e){e[e.UNINITIALIZED=0]="UNINITIALIZED",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"})(fl||(fl={}));class Ate{constructor(t){this.instance=t}setToolbarState(t){Vt.ph_toolbar_state=t}getToolbarState(){var t;return(t=Vt.ph_toolbar_state)!==null&&t!==void 0?t:fl.UNINITIALIZED}maybeLoadToolbar(){var t,n,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;if(!Be||!_t)return!1;s=(t=s)!==null&&t!==void 0?t:Be.location,i=(n=i)!==null&&n!==void 0?n:Be.history;try{if(!r){try{Be.localStorage.setItem("test","test"),Be.localStorage.removeItem("test")}catch{return!1}r=Be?.localStorage}var a,o=Rte||mx(s.hash,"__posthog")||mx(s.hash,"state"),l=o?sD(()=>JSON.parse(atob(decodeURIComponent(o))))||sD(()=>JSON.parse(decodeURIComponent(o))):null;return l&&l.action==="ph_authorize"?((a=l).source="url",a&&Object.keys(a).length>0&&(l.desiredHash?s.hash=l.desiredHash:i?i.replaceState(i.state,"",s.pathname+s.search):s.hash="")):((a=JSON.parse(r.getItem(MD)||"{}")).source="localstorage",delete a.userIntent),!(!a.token||this.instance.config.token!==a.token)&&(this.loadToolbar(a),!0)}catch{return!1}}_callLoadToolbar(t){var n=Vt.ph_load_toolbar||Vt.ph_load_editor;!En(n)&&Wa(n)?n(t,this.instance):OD.warn("No toolbar load function found")}loadToolbar(t){var n=!(_t==null||!_t.getElementById(p6));if(!Be||n)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=We(We({token:this.instance.config.token},t),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(Be.localStorage.setItem(MD,JSON.stringify(We(We({},r),{},{source:void 0}))),this.getToolbarState()===fl.LOADED)this._callLoadToolbar(r);else if(this.getToolbarState()===fl.UNINITIALIZED){var i,a;this.setToolbarState(fl.LOADING),(i=Vt.__PosthogExtensions__)===null||i===void 0||(a=i.loadExternalDependency)===null||a===void 0||a.call(i,this.instance,"toolbar",o=>{if(o)return OD.error("[Toolbar] Failed to load",o),void this.setToolbarState(fl.UNINITIALIZED);this.setToolbarState(fl.LOADED),this._callLoadToolbar(r)}),Cs(Be,"turbolinks:load",()=>{this.setToolbarState(fl.UNINITIALIZED),this.loadToolbar(r)})}return!0}_loadEditor(t){return this.loadToolbar(t)}maybeLoadEditor(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;return this.maybeLoadToolbar(t,n,s)}}var Fte=Mr("[TracingHeaders]");class Dte{constructor(t){dt(this,"_restoreXHRPatch",void 0),dt(this,"_restoreFetchPatch",void 0),dt(this,"_startCapturing",()=>{var n,s,r,i;wt(this._restoreXHRPatch)&&((n=Vt.__PosthogExtensions__)===null||n===void 0||(s=n.tracingHeadersPatchFns)===null||s===void 0||s._patchXHR(this.instance.sessionManager)),wt(this._restoreFetchPatch)&&((r=Vt.__PosthogExtensions__)===null||r===void 0||(i=r.tracingHeadersPatchFns)===null||i===void 0||i._patchFetch(this.instance.sessionManager))}),this.instance=t}_loadScript(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.tracingHeadersPatchFns&&t(),(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"tracing-headers",i=>{if(i)return Fte.error("failed to load script",i);t()})}startIfEnabledOrStop(){var t,n;this.instance.config.__add_tracing_headers?this._loadScript(this._startCapturing):((t=this._restoreXHRPatch)===null||t===void 0||t.call(this),(n=this._restoreFetchPatch)===null||n===void 0||n.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0)}}var hc=Mr("[Web Vitals]"),LD=9e5;class Pte{constructor(t){var n;dt(this,"_enabledServerSide",!1),dt(this,"_initialized",!1),dt(this,"buffer",{url:void 0,metrics:[],firstMetricTimestamp:void 0}),dt(this,"_flushToCapture",()=>{clearTimeout(this._delayedFlushTimer),this.buffer.metrics.length!==0&&(this.instance.capture("$web_vitals",this.buffer.metrics.reduce((s,r)=>We(We({},s),{},{["$web_vitals_".concat(r.name,"_event")]:We({},r),["$web_vitals_".concat(r.name,"_value")]:r.value}),{})),this.buffer={url:void 0,metrics:[],firstMetricTimestamp:void 0})}),dt(this,"_addToBuffer",s=>{var r,i=(r=this.instance.sessionManager)===null||r===void 0?void 0:r.checkAndGetSessionAndWindowId(!0);if(wt(i))hc.error("Could not read session ID. Dropping metrics!");else{this.buffer=this.buffer||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var a=this._currentURL();wt(a)||(En(s?.name)||En(s?.value)?hc.error("Invalid metric received",s):this._maxAllowedValue&&s.value>=this._maxAllowedValue?hc.error("Ignoring metric with value >= "+this._maxAllowedValue,s):(this.buffer.url!==a&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),wt(this.buffer.url)&&(this.buffer.url=a),this.buffer.firstMetricTimestamp=wt(this.buffer.firstMetricTimestamp)?Date.now():this.buffer.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0),this.buffer.metrics.push(We(We({},s),{},{$current_url:a,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()))}}),dt(this,"_startCapturing",()=>{var s,r,i,a,o=Vt.__PosthogExtensions__;wt(o)||wt(o.postHogWebVitalsCallbacks)||({onLCP:s,onCLS:r,onFCP:i,onINP:a}=o.postHogWebVitalsCallbacks),s&&r&&i&&a?(this.allowedMetrics.indexOf("LCP")>-1&&s(this._addToBuffer.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&r(this._addToBuffer.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this._addToBuffer.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&a(this._addToBuffer.bind(this)),this._initialized=!0):hc.error("web vitals callbacks not loaded - not starting")}),this.instance=t,this._enabledServerSide=!((n=this.instance.persistence)===null||n===void 0||!n.props[aD]),this.startIfEnabled()}get allowedMetrics(){var t,n,s=us(this.instance.config.capture_performance)?(t=this.instance.config.capture_performance)===null||t===void 0?void 0:t.web_vitals_allowed_metrics:void 0;return wt(s)?((n=this.instance.persistence)===null||n===void 0?void 0:n.props[oD])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(us(this.instance.config.capture_performance)?this.instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get _maxAllowedValue(){var t=us(this.instance.config.capture_performance)&&qr(this.instance.config.capture_performance.__web_vitals_max_value)?this.instance.config.capture_performance.__web_vitals_max_value:LD;return 0<t&&t<=6e4?LD:t}get isEnabled(){var t=li?.protocol;if(t!=="http:"&&t!=="https:")return hc.info("Web Vitals are disabled on non-http/https protocols"),!1;var n=us(this.instance.config.capture_performance)?this.instance.config.capture_performance.web_vitals:ml(this.instance.config.capture_performance)?this.instance.config.capture_performance:void 0;return ml(n)?n:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(hc.info("enabled, starting..."),this.loadScript(this._startCapturing))}onRemoteConfig(t){var n=us(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=us(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this.instance.persistence&&(this.instance.persistence.register({[aD]:n}),this.instance.persistence.register({[oD]:s})),this._enabledServerSide=n,this.startIfEnabled()}loadScript(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.postHogWebVitalsCallbacks&&t(),(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"web-vitals",i=>{i?hc.error("failed to load script",i):t()})}_currentURL(){var t=Be?Be.location.href:void 0;return t||hc.error("Could not determine current URL"),t}}var Ite=Mr("[Heatmaps]");function BD(e){return us(e)&&"clientX"in e&&"clientY"in e&&qr(e.clientX)&&qr(e.clientY)}class Nte{constructor(t){var n;dt(this,"rageclicks",new E6),dt(this,"_enabledServerSide",!1),dt(this,"_initialized",!1),dt(this,"_flushInterval",null),this.instance=t,this._enabledServerSide=!((n=this.instance.persistence)===null||n===void 0||!n.props[pS])}get flushIntervalMilliseconds(){var t=5e3;return us(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(t=this.instance.config.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return wt(this.instance.config.capture_heatmaps)?wt(this.instance.config.enable_heatmaps)?this._enabledServerSide:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;Ite.info("starting..."),this._setupListeners(),this._flushInterval=setInterval(this.flush.bind(this),this.flushIntervalMilliseconds)}else{var t,n;clearInterval((t=this._flushInterval)!==null&&t!==void 0?t:void 0),(n=this.deadClicksCapture)===null||n===void 0||n.stop(),this.getAndClearBuffer()}}onRemoteConfig(t){var n=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[pS]:n}),this._enabledServerSide=n,this.startIfEnabled()}getAndClearBuffer(){var t=this.buffer;return this.buffer=void 0,t}_onDeadClick(t){this._onClick(t.originalEvent,"deadclick")}_setupListeners(){Be&&_t&&(Cs(Be,"beforeunload",this.flush.bind(this)),Cs(_t,"click",t=>this._onClick(t||Be?.event),{capture:!0}),Cs(_t,"mousemove",t=>this._onMouseMove(t||Be?.event),{capture:!0}),this.deadClicksCapture=new T6(this.instance,qee,this._onDeadClick.bind(this)),this.deadClicksCapture.startIfEnabled(),this._initialized=!0)}_getProperties(t,n){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),a=function(o,l,u){for(var d=o;d&&dC(d)&&!jc(d,"body");){if(d===u)return!1;if(Zt(l,Be?.getComputedStyle(d).position))return!0;d=x6(d)}return!1}(b6(t),["fixed","sticky"],i);return{x:t.clientX+(a?0:r),y:t.clientY+(a?0:s),target_fixed:a,type:n}}_onClick(t){var n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"click";if(!mD(t.target)&&BD(t)){var r=this._getProperties(t,s);(n=this.rageclicks)!==null&&n!==void 0&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&this._capture(We(We({},r),{},{type:"rageclick"})),this._capture(r)}}_onMouseMove(t){!mD(t.target)&&BD(t)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout(()=>{this._capture(this._getProperties(t,"mousemove"))},500))}_capture(t){if(Be){var n=Be.location.href;this.buffer=this.buffer||{},this.buffer[n]||(this.buffer[n]=[]),this.buffer[n].push(t)}}flush(){this.buffer&&!Hh(this.buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class Mte{constructor(t){this._instance=t}doPageView(t,n){var s,r=this._previousPageViewProperties(t,n);return this._currentPageview={pathname:(s=Be?.location.pathname)!==null&&s!==void 0?s:"",pageViewId:n,timestamp:t},this._instance.scrollManager.resetContext(),r}doPageLeave(t){var n;return this._previousPageViewProperties(t,(n=this._currentPageview)===null||n===void 0?void 0:n.pageViewId)}doEvent(){var t;return{$pageview_id:(t=this._currentPageview)===null||t===void 0?void 0:t.pageViewId}}_previousPageViewProperties(t,n){var s=this._currentPageview;if(!s)return{$pageview_id:n};var r={$pageview_id:n,$prev_pageview_id:s.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:a,lastScrollY:o,maxScrollY:l,maxContentHeight:u,lastContentY:d,maxContentY:h}=i;if(!(wt(a)||wt(o)||wt(l)||wt(u)||wt(d)||wt(h))){a=Math.ceil(a),o=Math.ceil(o),l=Math.ceil(l),u=Math.ceil(u),d=Math.ceil(d),h=Math.ceil(h);var f=a<=1?1:ia(o/a,0,1),p=a<=1?1:ia(l/a,0,1),m=u<=1?1:ia(d/u,0,1),v=u<=1?1:ia(h/u,0,1);r=xs(r,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:d,$prev_pageview_last_content_percentage:m,$prev_pageview_max_content:h,$prev_pageview_max_content_percentage:v})}}return s.pathname&&(r.$prev_pageview_pathname=s.pathname),s.timestamp&&(r.$prev_pageview_duration=(t.getTime()-s.timestamp.getTime())/1e3),r}}let Ote=class{constructor(t){this.instance=t}sendExceptionEvent(t){this.instance.capture("$exception",t,{_noTruncate:!0,_batchKey:"exceptionEvent"})}};var ua="Mobile",xx="iOS",Ao="Android",Im="Tablet",j6=Ao+" "+Im,H6="iPad",U6="Apple",G6=U6+" Watch",Nm="Safari",Df="BlackBerry",V6="Samsung",W6=V6+"Browser",$6=V6+" Internet",yd="Chrome",Lte=yd+" OS",z6=yd+" "+xx,CT="Internet Explorer",q6=CT+" "+ua,yT="Opera",Bte=yT+" Mini",_T="Edge",K6="Microsoft "+_T,Zh="Firefox",Y6=Zh+" "+xx,Mm="Nintendo",Om="PlayStation",ef="Xbox",X6=Ao+" "+ua,Q6=ua+" "+Nm,yg="Windows",IS=yg+" Phone",jD="Nokia",NS="Ouya",J6="Generic",jte=J6+" "+ua.toLowerCase(),Z6=J6+" "+Im.toLowerCase(),MS="Konqueror",Vr="(\\d+(\\.\\d+)?)",By=new RegExp("Version/"+Vr),Hte=new RegExp(ef,"i"),Ute=new RegExp(Om+" \\w+","i"),Gte=new RegExp(Mm+" \\w+","i"),ST=new RegExp(Df+"|PlayBook|BB10","i"),Vte={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},OS,Wte=(e,t)=>t&&Zt(t,U6)||function(n){return Zt(n,Nm)&&!Zt(n,yd)&&!Zt(n,Ao)}(e),HD=function(e,t){return t=t||"",Zt(e," OPR/")&&Zt(e,"Mini")?Bte:Zt(e," OPR/")?yT:ST.test(e)?Df:Zt(e,"IE"+ua)||Zt(e,"WPDesktop")?q6:Zt(e,W6)?$6:Zt(e,_T)||Zt(e,"Edg/")?K6:Zt(e,"FBIOS")?"Facebook "+ua:Zt(e,"UCWEB")||Zt(e,"UCBrowser")?"UC Browser":Zt(e,"CriOS")?z6:Zt(e,"CrMo")||Zt(e,yd)?yd:Zt(e,Ao)&&Zt(e,Nm)?X6:Zt(e,"FxiOS")?Y6:Zt(e.toLowerCase(),MS.toLowerCase())?MS:Wte(e,t)?Zt(e,ua)?Q6:Nm:Zt(e,Zh)?Zh:Zt(e,"MSIE")||Zt(e,"Trident/")?CT:Zt(e,"Gecko")?Zh:""},$te={[q6]:[new RegExp("rv:"+Vr)],[K6]:[new RegExp(_T+"?\\/"+Vr)],[yd]:[new RegExp("("+yd+"|CrMo)\\/"+Vr)],[z6]:[new RegExp("CriOS\\/"+Vr)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Vr)],[Nm]:[By],[Q6]:[By],[yT]:[new RegExp("(Opera|OPR)\\/"+Vr)],[Zh]:[new RegExp(Zh+"\\/"+Vr)],[Y6]:[new RegExp("FxiOS\\/"+Vr)],[MS]:[new RegExp("Konqueror[:/]?"+Vr,"i")],[Df]:[new RegExp(Df+" "+Vr),By],[X6]:[new RegExp("android\\s"+Vr,"i")],[$6]:[new RegExp(W6+"\\/"+Vr)],[CT]:[new RegExp("(rv:|MSIE )"+Vr)],Mozilla:[new RegExp("rv:"+Vr)]},UD=[[new RegExp(ef+"; "+ef+" (.*?)[);]","i"),e=>[ef,e&&e[1]||""]],[new RegExp(Mm,"i"),[Mm,""]],[new RegExp(Om,"i"),[Om,""]],[ST,[Df,""]],[new RegExp(yg,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[IS,""];if(new RegExp(ua).test(t)&&!/IEMobile\b/.test(t))return[yg+" "+ua,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var s=n[1],r=Vte[s]||"";return/arm/i.test(t)&&(r="RT"),[yg,r]}return[yg,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){var t=[e[3],e[4],e[5]||"0"];return[xx,t.join(".")]}return[xx,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=wt(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Ao+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ao+")","i"),e=>{if(e&&e[2]){var t=[e[2],e[3],e[4]||"0"];return[Ao,t.join(".")]}return[Ao,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];if(e&&e[1]){var n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Lte,""]],[/Linux|debian/i,["Linux",""]]],GD=function(e){return Gte.test(e)?Mm:Ute.test(e)?Om:Hte.test(e)?ef:new RegExp(NS,"i").test(e)?NS:new RegExp("("+IS+"|WPDesktop)","i").test(e)?IS:/iPad/.test(e)?H6:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?G6:ST.test(e)?Df:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(jD,"i").test(e)?jD:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?!new RegExp(ua).test(e)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)?/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?Ao:j6:Ao:new RegExp("(pda|"+ua+")","i").test(e)?jte:new RegExp(Im,"i").test(e)&&!new RegExp(Im+" pc","i").test(e)?Z6:""},Dv="https?://(.*)",Pb=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","irclid","_kx"],zte=Rb(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Pb),jy="<masked>",Qn={campaignParams:function(){var{customTrackedParams:e,maskPersonalDataProperties:t,customPersonalDataProperties:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!_t)return{};var s=t?Rb([],Pb,n||[]):[];return this._campaignParamsFromUrl(Ty(_t.URL,s,jy),e)},_campaignParamsFromUrl:function(e,t){var n=zte.concat(t||[]),s={};return Nn(n,function(r){var i=gx(e,r);s[r]=i||null}),s},_searchEngine:function(e){return e?e.search(Dv+"google.([^/?]*)")===0?"google":e.search(Dv+"bing.com")===0?"bing":e.search(Dv+"yahoo.com")===0?"yahoo":e.search(Dv+"duckduckgo.com")===0?"duckduckgo":null:null},_searchInfoFromReferrer:function(e){var t=Qn._searchEngine(e),n=t!="yahoo"?"q":"p",s={};if(!iu(t)){s.$search_engine=t;var r=_t?gx(_t.referrer,n):"";r.length&&(s.ph_keyword=r)}return s},searchInfo:function(){var e=_t?.referrer;return e?this._searchInfoFromReferrer(e):{}},browser:HD,browserVersion:function(e,t){var n=HD(e,t),s=$te[n];if(wt(s))return null;for(var r=0;r<s.length;r++){var i=s[r],a=e.match(i);if(a)return parseFloat(a[a.length-2])}return null},browserLanguage:function(){return navigator.language||navigator.userLanguage},browserLanguagePrefix:function(){var e=this.browserLanguage();return typeof e=="string"?e.split("-")[0]:void 0},os:function(e){for(var t=0;t<UD.length;t++){var[n,s]=UD[t],r=n.exec(e),i=r&&(Wa(s)?s(r,e):s);if(i)return i}return["",""]},device:GD,deviceType:function(e){var t=GD(e);return t===H6||t===j6||t==="Kobo"||t==="Kindle Fire"||t===Z6?Im:t===Mm||t===ef||t===Om||t===NS?"Console":t===G6?"Wearable":t?ua:"Desktop"},referrer:function(){return _t?.referrer||"$direct"},referringDomain:function(){var e;return _t!=null&&_t.referrer&&((e=Jh(_t.referrer))===null||e===void 0?void 0:e.host)||"$direct"},referrerInfo:function(){return{$referrer:this.referrer(),$referring_domain:this.referringDomain()}},personInfo:function(){var{maskPersonalDataProperties:e,customPersonalDataProperties:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=e?Rb([],Pb,t||[]):[],s=li?.href.substring(0,1e3);return{r:this.referrer().substring(0,1e3),u:s?Ty(s,n,jy):void 0}},personPropsFromInfo:function(e){var t,{r:n,u:s}=e,r={$referrer:n,$referring_domain:n==null?void 0:n=="$direct"?"$direct":(t=Jh(n))===null||t===void 0?void 0:t.host};if(s){r.$current_url=s;var i=Jh(s);r.$host=i?.host,r.$pathname=i?.pathname;var a=this._campaignParamsFromUrl(s);xs(r,a)}if(n){var o=this._searchInfoFromReferrer(n);xs(r,o)}return r},initialPersonPropsFromInfo:function(e){var t=this.personPropsFromInfo(e),n={};return Nn(t,function(s,r){n["$initial_".concat(mT(r))]=s}),n},timezone:function(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}},timezoneOffset:function(){try{return new Date().getTimezoneOffset()}catch{return}},properties:function(){var{maskPersonalDataProperties:e,customPersonalDataProperties:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!Ns)return{};var n=e?Rb([],Pb,t||[]):[],[s,r]=Qn.os(Ns);return xs(Pm({$os:s,$os_version:r,$browser:Qn.browser(Ns,navigator.vendor),$device:Qn.device(Ns),$device_type:Qn.deviceType(Ns),$timezone:Qn.timezone(),$timezone_offset:Qn.timezoneOffset()}),{$current_url:Ty(li?.href,n,jy),$host:li?.host,$pathname:li?.pathname,$raw_user_agent:Ns.length>1e3?Ns.substring(0,997)+"...":Ns,$browser_version:Qn.browserVersion(Ns,navigator.vendor),$browser_language:Qn.browserLanguage(),$browser_language_prefix:Qn.browserLanguagePrefix(),$screen_height:Be?.screen.height,$screen_width:Be?.screen.width,$viewport_height:Be?.innerHeight,$viewport_width:Be?.innerWidth,$lib:"web",$lib_version:pl.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})},people_properties:function(){if(!Ns)return{};var[e,t]=Qn.os(Ns);return xs(Pm({$os:e,$os_version:t,$browser:Qn.browser(Ns,navigator.vendor)}),{$browser_version:Qn.browserVersion(Ns,navigator.vendor)})}},bo=Mr("[FeatureFlags]"),Hy="$active_feature_flags",fh="$override_feature_flags",VD="$feature_flag_payloads",zp="$override_feature_flag_payloads",WD="$feature_flag_request_id",$D=e=>{var t={};for(var[n,s]of Ab(e||{}))s&&(t[n]=s);return t},qte=e=>{var t=e.flags;return t?(e.featureFlags=Object.fromEntries(Object.keys(t).map(n=>{var s;return[n,(s=t[n].variant)!==null&&s!==void 0?s:t[n].enabled]})),e.featureFlagPayloads=Object.fromEntries(Object.keys(t).filter(n=>t[n].enabled).filter(n=>{var s;return(s=t[n].metadata)===null||s===void 0?void 0:s.payload}).map(n=>{var s;return[n,(s=t[n].metadata)===null||s===void 0?void 0:s.payload]}))):bo.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e};(function(e){e.FeatureFlags="feature_flags",e.Recordings="recordings"})(OS||(OS={}));class Kte{constructor(t){dt(this,"_override_warning",!1),dt(this,"_hasLoadedFlags",!1),dt(this,"_requestInFlight",!1),dt(this,"_reloadingDisabled",!1),dt(this,"_additionalReloadRequested",!1),dt(this,"_decideCalled",!1),dt(this,"_flagsLoadedFromRemote",!1),this.instance=t,this.featureFlagEventHandlers=[]}decide(){if(this.instance.config.__preview_remote_config)this._decideCalled=!0;else{var t=!this._reloadDebouncer&&(this.instance.config.advanced_disable_feature_flags||this.instance.config.advanced_disable_feature_flags_on_first_load);this._callDecideEndpoint({disableFlags:t})}}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.instance.get_property(mS),n=this.instance.get_property(fh),s=this.instance.get_property(zp);if(!s&&!n)return t||{};var r=xs({},t||{}),i=[...new Set([...Object.keys(s||{}),...Object.keys(n||{})])];for(var a of i){var o,l,u=r[a],d=n?.[a],h=wt(d)?(o=u?.enabled)!==null&&o!==void 0&&o:!!d,f=wt(d)?u.variant:typeof d=="string"?d:void 0,p=s?.[a],m=We(We({},u),{},{enabled:h,variant:h?f??u?.variant:void 0});h!==u?.enabled&&(m.original_enabled=u?.enabled),f!==u?.variant&&(m.original_variant=u?.variant),p&&(m.metadata=We(We({},u?.metadata),{},{payload:p,original_payload:u==null||(l=u.metadata)===null||l===void 0?void 0:l.payload})),r[a]=m}return this._override_warning||(bo.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this._override_warning=!0),r}getFlagVariants(){var t=this.instance.get_property(Uh),n=this.instance.get_property(fh);if(!n)return t||{};for(var s=xs({},t),r=Object.keys(n),i=0;i<r.length;i++)s[r[i]]=n[r[i]];return this._override_warning||(bo.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:n,finalFlags:s}),this._override_warning=!0),s}getFlagPayloads(){var t=this.instance.get_property(VD),n=this.instance.get_property(zp);if(!n)return t||{};for(var s=xs({},t||{}),r=Object.keys(n),i=0;i<r.length;i++)s[r[i]]=n[r[i]];return this._override_warning||(bo.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:n,finalPayloads:s}),this._override_warning=!0),s}reloadFeatureFlags(){this._reloadingDisabled||this.instance.config.advanced_disable_feature_flags||this._reloadDebouncer||(this._reloadDebouncer=setTimeout(()=>{this._callDecideEndpoint()},5))}clearDebouncer(){clearTimeout(this._reloadDebouncer),this._reloadDebouncer=void 0}ensureFlagsLoaded(){this._hasLoadedFlags||this._requestInFlight||this._reloadDebouncer||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._reloadingDisabled=t}_callDecideEndpoint(t){var n;if(this.clearDebouncer(),!this.instance.config.advanced_disable_decide)if(this._requestInFlight)this._additionalReloadRequested=!0;else{var s={token:this.instance.config.token,distinct_id:this.instance.get_distinct_id(),groups:this.instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:We(We({},((n=this.instance.persistence)===null||n===void 0?void 0:n.get_initial_props())||{}),this.instance.get_property(wg)||{}),group_properties:this.instance.get_property(Nu)};(t!=null&&t.disableFlags||this.instance.config.advanced_disable_feature_flags)&&(s.disable_flags=!0);var r=this.instance.config.__preview_flags_v2&&this.instance.config.__preview_remote_config;r&&(s.timezone=Qn.timezone()),this._requestInFlight=!0,this.instance._send_request({method:"POST",url:this.instance.requestRouter.endpointFor("api",r?"/flags/?v=2":"/decide/?v=4"),data:s,compression:this.instance.config.disable_compression?void 0:ja.Base64,timeout:this.instance.config.feature_flag_request_timeout_ms,callback:i=>{var a,o,l,u=!0;i.statusCode===200&&(this._additionalReloadRequested||(this.$anon_distinct_id=void 0),u=!1),this._requestInFlight=!1,this._decideCalled||(this._decideCalled=!0,this.instance._onRemoteConfig((l=i.json)!==null&&l!==void 0?l:{})),s.disable_flags&&!this._additionalReloadRequested||(this._flagsLoadedFromRemote=!u,i.json&&(a=i.json.quotaLimited)!==null&&a!==void 0&&a.includes(OS.FeatureFlags)?bo.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):(this.receivedFeatureFlags((o=i.json)!==null&&o!==void 0?o:{},u),this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callDecideEndpoint())))}})}}getFeatureFlag(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){var s=this.getFlagVariants()[t],r="".concat(s),i=this.instance.get_property(WD)||void 0,a=this.instance.get_property(hx)||{};if((n.send_event||!("send_event"in n))&&(!(t in a)||!a[t].includes(r))){var o,l,u,d,h,f,p,m,v,b,w;cs(a[t])?a[t].push(r):a[t]=[r],(o=this.instance.persistence)===null||o===void 0||o.register({[hx]:a});var C=this.getFeatureFlagDetails(t),y={$feature_flag:t,$feature_flag_response:s,$feature_flag_payload:this.getFeatureFlagPayload(t)||null,$feature_flag_request_id:i,$feature_flag_bootstrapped_response:((l=this.instance.config.bootstrap)===null||l===void 0||(u=l.featureFlags)===null||u===void 0?void 0:u[t])||null,$feature_flag_bootstrapped_payload:((d=this.instance.config.bootstrap)===null||d===void 0||(h=d.featureFlagPayloads)===null||h===void 0?void 0:h[t])||null,$used_bootstrap_value:!this._flagsLoadedFromRemote};wt(C==null||(f=C.metadata)===null||f===void 0?void 0:f.version)||(y.$feature_flag_version=C.metadata.version);var k,_=(p=C==null||(m=C.reason)===null||m===void 0?void 0:m.description)!==null&&p!==void 0?p:C==null||(v=C.reason)===null||v===void 0?void 0:v.code;_&&(y.$feature_flag_reason=_),C!=null&&(b=C.metadata)!==null&&b!==void 0&&b.id&&(y.$feature_flag_id=C.metadata.id),wt(C?.original_variant)&&wt(C?.original_enabled)||(y.$feature_flag_original_response=wt(C.original_variant)?C.original_enabled:C.original_variant),C!=null&&(w=C.metadata)!==null&&w!==void 0&&w.original_payload&&(y.$feature_flag_original_payload=C==null||(k=C.metadata)===null||k===void 0?void 0:k.original_payload),this.instance.capture("$feature_flag_called",y)}return s}bo.warn('getFeatureFlag for key "'+t+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){return this.getFlagPayloads()[t]}getRemoteConfigPayload(t,n){var s=this.instance.config.token;this.instance._send_request({method:"POST",url:this.instance.requestRouter.endpointFor("api","/decide/?v=4"),data:{distinct_id:this.instance.get_distinct_id(),token:s},compression:this.instance.config.disable_compression?void 0:ja.Base64,timeout:this.instance.config.feature_flag_request_timeout_ms,callback:r=>{var i,a=(i=r.json)===null||i===void 0?void 0:i.featureFlagPayloads;n(a?.[t]||void 0)}})}isFeatureEnabled(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0)return!!this.getFeatureFlag(t,n);bo.warn('isFeatureEnabled for key "'+t+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(n=>n!==t)}receivedFeatureFlags(t,n){if(this.instance.persistence){this._hasLoadedFlags=!0;var s=this.getFlagVariants(),r=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(a,o){var l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},u=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},h=qte(a),f=h.flags,p=h.featureFlags,m=h.featureFlagPayloads;if(p){var v=a.requestId;if(cs(p)){bo.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var b={};if(p)for(var w=0;w<p.length;w++)b[p[w]]=!0;o&&o.register({[Hy]:p,[Uh]:b})}else{var C=p,y=m,k=f;a.errorsWhileComputingFlags&&(C=We(We({},l),C),y=We(We({},u),y),k=We(We({},d),k)),o&&o.register(We({[Hy]:Object.keys($D(C)),[Uh]:C||{},[VD]:y||{},[mS]:k||{}},v?{[WD]:v}:{}))}}})(t,this.instance.persistence,s,r,i),this._fireFeatureFlagsCallbacks(n)}}override(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];bo.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:n})}overrideFeatureFlags(t){if(!this.instance.__loaded||!this.instance.persistence)return bo.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(t===!1)return this.instance.persistence.unregister(fh),this.instance.persistence.unregister(zp),void this._fireFeatureFlagsCallbacks();if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var n,s=t;if(this._override_warning=!!((n=s.suppressWarning)!==null&&n!==void 0&&n),"flags"in s){if(s.flags===!1)this.instance.persistence.unregister(fh);else if(s.flags)if(cs(s.flags)){for(var r={},i=0;i<s.flags.length;i++)r[s.flags[i]]=!0;this.instance.persistence.register({[fh]:r})}else this.instance.persistence.register({[fh]:s.flags})}return"payloads"in s&&(s.payloads===!1?this.instance.persistence.unregister(zp):s.payloads&&this.instance.persistence.register({[zp]:s.payloads})),void this._fireFeatureFlagsCallbacks()}this._fireFeatureFlagsCallbacks()}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this._hasLoadedFlags){var{flags:n,flagVariants:s}=this._prepareFeatureFlagsForCallbacks();t(n,s)}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,n){var s,r=(this.instance.get_property(Fb)||[]).find(l=>l.flagKey===t),i={["$feature_enrollment/".concat(t)]:n},a={$feature_flag:t,$feature_enrollment:n,$set:i};r&&(a.$early_access_feature_name=r.name),this.instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(i,!1);var o=We(We({},this.getFlagVariants()),{},{[t]:n});(s=this.instance.persistence)===null||s===void 0||s.register({[Hy]:Object.keys($D(o)),[Uh]:o}),this._fireFeatureFlagsCallbacks()}getEarlyAccessFeatures(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1],s=arguments.length>2?arguments[2]:void 0,r=this.instance.get_property(Fb),i=s?"&".concat(s.map(a=>"stage=".concat(a)).join("&")):"";if(r&&!n)return t(r);this.instance._send_request({url:this.instance.requestRouter.endpointFor("api","/api/early_access_features/?token=".concat(this.instance.config.token).concat(i)),method:"GET",callback:a=>{var o;if(a.json){var l=a.json.earlyAccessFeatures;return(o=this.instance.persistence)===null||o===void 0||o.register({[Fb]:l}),t(l)}}})}_prepareFeatureFlagsForCallbacks(){var t=this.getFlags(),n=this.getFlagVariants();return{flags:t.filter(s=>n[s]),flagVariants:Object.keys(n).filter(s=>n[s]).reduce((s,r)=>(s[r]=n[r],s),{})}}_fireFeatureFlagsCallbacks(t){var{flags:n,flagVariants:s}=this._prepareFeatureFlagsForCallbacks();this.featureFlagEventHandlers.forEach(r=>r(n,s,{errorsLoading:t}))}setPersonPropertiesForFlags(t){var n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],s=this.instance.get_property(wg)||{};this.instance.register({[wg]:We(We({},s),t)}),n&&this.instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this.instance.unregister(wg)}setGroupPropertiesForFlags(t){var n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],s=this.instance.get_property(Nu)||{};Object.keys(s).length!==0&&Object.keys(s).forEach(r=>{s[r]=We(We({},s[r]),t[r]),delete t[r]}),this.instance.register({[Nu]:We(We({},s),t)}),n&&this.instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var n=this.instance.get_property(Nu)||{};this.instance.register({[Nu]:We(We({},n),{},{[t]:{}})})}else this.instance.unregister(Nu)}}var Yte=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Uy{constructor(t){this.config=t,this.props={},this.campaign_params_saved=!1,this.name=(n=>{var s="";return n.token&&(s=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+s+"_posthog"})(t),this.storage=this.buildStorage(t),this.load(),t.debug&&Rt.info("Persistence loaded",t.persistence,We({},this.props)),this.update_config(t,t),this.save()}buildStorage(t){Yte.indexOf(t.persistence.toLowerCase())===-1&&(Rt.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");var n=t.persistence.toLowerCase();return n==="localstorage"&&Us.is_supported()?Us:n==="localstorage+cookie"&&Ev.is_supported()?Ev:n==="sessionstorage"&&hr.is_supported()?hr:n==="memory"?$ee:n==="cookie"?_l:Ev.is_supported()?Ev:_l}properties(){var t={};return Nn(this.props,function(n,s){if(s===Uh&&us(n))for(var r=Object.keys(n),i=0;i<r.length;i++)t["$feature/".concat(r[i])]=n[r[i]];else o=s,l=!1,(iu(a=_ee)?l:ZF&&a.indexOf===ZF?a.indexOf(o)!=-1:(Nn(a,function(u){if(l||(l=u===o))return ux}),l))||(t[s]=n);var a,o,l}),t}load(){if(!this.disabled){var t=this.storage.parse(this.name);t&&(this.props=xs({},t))}}save(){this.disabled||this.storage.set(this.name,this.props,this.expire_days,this.cross_subdomain,this.secure,this.config.debug)}remove(){this.storage.remove(this.name,!1),this.storage.remove(this.name,!0)}clear(){this.remove(),this.props={}}register_once(t,n,s){if(us(t)){wt(n)&&(n="None"),this.expire_days=wt(s)?this.default_expiry:s;var r=!1;if(Nn(t,(i,a)=>{this.props.hasOwnProperty(a)&&this.props[a]!==n||(this.props[a]=i,r=!0)}),r)return this.save(),!0}return!1}register(t,n){if(us(t)){this.expire_days=wt(n)?this.default_expiry:n;var s=!1;if(Nn(t,(r,i)=>{t.hasOwnProperty(i)&&this.props[i]!==r&&(this.props[i]=r,s=!0)}),s)return this.save(),!0}return!1}unregister(t){t in this.props&&(delete this.props[t],this.save())}update_campaign_params(){if(!this.campaign_params_saved){var t=Qn.campaignParams({customTrackedParams:this.config.custom_campaign_params,maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties});Hh(Pm(t))||this.register(t),this.campaign_params_saved=!0}}update_search_keyword(){this.register(Qn.searchInfo())}update_referrer_info(){this.register_once(Qn.referrerInfo(),void 0)}set_initial_person_info(){this.props[wS]||this.props[CS]||this.register_once({[yS]:Qn.personInfo({maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties})},void 0)}get_referrer_info(){return Pm({$referrer:this.props.$referrer,$referring_domain:this.props.$referring_domain})}get_initial_props(){var t={};Nn([CS,wS],r=>{var i=this.props[r];i&&Nn(i,function(a,o){t["$initial_"+mT(o)]=a})});var n=this.props[yS];if(n){var s=Qn.initialPersonPropsFromInfo(n);xs(t,s)}return t}safe_merge(t){return Nn(this.props,function(n,s){s in t||(t[s]=n)}),t}update_config(t,n){if(this.default_expiry=this.expire_days=t.cookie_expiration,this.set_disabled(t.disable_persistence),this.set_cross_subdomain(t.cross_subdomain_cookie),this.set_secure(t.secure_cookie),t.persistence!==n.persistence){var s=this.buildStorage(t),r=this.props;this.clear(),this.storage=s,this.props=r,this.save()}}set_disabled(t){this.disabled=t,this.disabled?this.remove():this.save()}set_cross_subdomain(t){t!==this.cross_subdomain&&(this.cross_subdomain=t,this.remove(),this.save())}get_cross_subdomain(){return!!this.cross_subdomain}set_secure(t){t!==this.secure&&(this.secure=t,this.remove(),this.save())}set_event_timer(t,n){var s=this.props[bg]||{};s[t]=n,this.props[bg]=s,this.save()}remove_event_timer(t){var n=(this.props[bg]||{})[t];return wt(n)||(delete this.props[bg][t],this.save()),n}get_property(t){return this.props[t]}set_property(t,n){this.props[t]=n,this.save()}}var ej,ds,tj,ju,zD,nj,LS,sj,qD,BS,KD,YD,XD,QD,jS={},rj=[],Xte=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,ET=Array.isArray;function Dc(e,t){for(var n in t)e[n]=t[n];return e}function ij(e){var t=e.parentNode;t&&t.removeChild(e)}function Gy(e,t,n,s,r){var i={type:e,props:t,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:r??++tj,__i:-1,__u:0};return r==null&&ds.vnode!=null&&ds.vnode(i),i}function kT(e){return e.children}function Ib(e,t){this.props=e,this.context=t}function Pf(e,t){if(t==null)return e.__?Pf(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?Pf(e):null}function aj(e){var t,n;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null){e.__e=e.__c.base=n.__e;break}return aj(e)}}function HS(e){(!e.__d&&(e.__d=!0)&&ju.push(e)&&!wx.__r++||zD!==ds.debounceRendering)&&((zD=ds.debounceRendering)||nj)(wx)}function wx(){var e,t,n,s,r,i,a,o,l;for(ju.sort(LS);e=ju.shift();)e.__d&&(t=ju.length,s=void 0,i=(r=(n=e).__v).__e,o=[],l=[],(a=n.__P)&&((s=Dc({},r)).__v=r.__v+1,ds.vnode&&ds.vnode(s),cj(a,s,r,n.__n,a.ownerSVGElement!==void 0,32&r.__u?[i]:null,o,i??Pf(r),!!(32&r.__u),l),s.__.__k[s.__i]=s,Zte(o,s,l),s.__e!=i&&aj(s)),ju.length>t&&ju.sort(LS));wx.__r=0}function oj(e,t,n,s,r,i,a,o,l,u,d){var h,f,p,m,v,b=s&&s.__k||rj,w=t.length;for(n.__d=l,Qte(n,t,b),l=n.__d,h=0;h<w;h++)(p=n.__k[h])!=null&&typeof p!="boolean"&&typeof p!="function"&&(f=p.__i===-1?jS:b[p.__i]||jS,p.__i=h,cj(e,p,f,r,i,a,o,l,u,d),m=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&TT(f.ref,null,p),d.push(p.ref,p.__c||m,p)),v==null&&m!=null&&(v=m),65536&p.__u||f.__k===p.__k?l=lj(p,l,e):typeof p.type=="function"&&p.__d!==void 0?l=p.__d:m&&(l=m.nextSibling),p.__d=void 0,p.__u&=-196609);n.__d=l,n.__e=v}function Qte(e,t,n){var s,r,i,a,o,l=t.length,u=n.length,d=u,h=0;for(e.__k=[],s=0;s<l;s++)(r=e.__k[s]=(r=t[s])==null||typeof r=="boolean"||typeof r=="function"?null:typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Gy(null,r,null,null,r):ET(r)?Gy(kT,{children:r},null,null,null):r.constructor===void 0&&r.__b>0?Gy(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r)!=null?(r.__=e,r.__b=e.__b+1,o=Jte(r,n,a=s+h,d),r.__i=o,i=null,o!==-1&&(d--,(i=n[o])&&(i.__u|=131072)),i==null||i.__v===null?(o==-1&&h--,typeof r.type!="function"&&(r.__u|=65536)):o!==a&&(o===a+1?h++:o>a?d>l-a?h+=o-a:h--:h=o<a&&o==a-1?o-a:0,o!==s+h&&(r.__u|=65536))):(i=n[s])&&i.key==null&&i.__e&&(i.__e==e.__d&&(e.__d=Pf(i)),US(i,i,!1),n[s]=null,d--);if(d)for(s=0;s<u;s++)(i=n[s])!=null&&(131072&i.__u)==0&&(i.__e==e.__d&&(e.__d=Pf(i)),US(i,i))}function lj(e,t,n){var s,r;if(typeof e.type=="function"){for(s=e.__k,r=0;s&&r<s.length;r++)s[r]&&(s[r].__=e,t=lj(s[r],t,n));return t}return e.__e!=t&&(n.insertBefore(e.__e,t||null),t=e.__e),t&&t.nextSibling}function Jte(e,t,n,s){var r=e.key,i=e.type,a=n-1,o=n+1,l=t[n];if(l===null||l&&r==l.key&&i===l.type)return n;if(s>(l!=null&&(131072&l.__u)==0?1:0))for(;a>=0||o<t.length;){if(a>=0){if((l=t[a])&&(131072&l.__u)==0&&r==l.key&&i===l.type)return a;a--}if(o<t.length){if((l=t[o])&&(131072&l.__u)==0&&r==l.key&&i===l.type)return o;o++}}return-1}function JD(e,t,n){t[0]==="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Xte.test(t)?n:n+"px"}function Pv(e,t,n,s,r){var i;e:if(t==="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof s=="string"&&(e.style.cssText=s=""),s)for(t in s)n&&t in n||JD(e.style,t,"");if(n)for(t in n)s&&n[t]===s[t]||JD(e.style,t,n[t])}else if(t[0]==="o"&&t[1]==="n")i=t!==(t=t.replace(/(PointerCapture)$|Capture$/,"$1")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?s?n.u=s.u:(n.u=Date.now(),e.addEventListener(t,i?eP:ZD,i)):e.removeEventListener(t,i?eP:ZD,i);else{if(r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!=="width"&&t!=="height"&&t!=="href"&&t!=="list"&&t!=="form"&&t!=="tabIndex"&&t!=="download"&&t!=="rowSpan"&&t!=="colSpan"&&t!=="role"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!=="-"?e.removeAttribute(t):e.setAttribute(t,n))}}function ZD(e){var t=this.l[e.type+!1];if(e.t){if(e.t<=t.u)return}else e.t=Date.now();return t(ds.event?ds.event(e):e)}function eP(e){return this.l[e.type+!0](ds.event?ds.event(e):e)}function cj(e,t,n,s,r,i,a,o,l,u){var d,h,f,p,m,v,b,w,C,y,k,_,E,R,F,A=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),i=[o=t.__e=n.__e]),(d=ds.__b)&&d(t);e:if(typeof A=="function")try{if(w=t.props,C=(d=A.contextType)&&s[d.__c],y=d?C?C.props.value:d.__:s,n.__c?b=(h=t.__c=n.__c).__=h.__E:("prototype"in A&&A.prototype.render?t.__c=h=new A(w,y):(t.__c=h=new Ib(w,y),h.constructor=A,h.render=tne),C&&C.sub(h),h.props=w,h.state||(h.state={}),h.context=y,h.__n=s,f=h.__d=!0,h.__h=[],h._sb=[]),h.__s==null&&(h.__s=h.state),A.getDerivedStateFromProps!=null&&(h.__s==h.state&&(h.__s=Dc({},h.__s)),Dc(h.__s,A.getDerivedStateFromProps(w,h.__s))),p=h.props,m=h.state,h.__v=t,f)A.getDerivedStateFromProps==null&&h.componentWillMount!=null&&h.componentWillMount(),h.componentDidMount!=null&&h.__h.push(h.componentDidMount);else{if(A.getDerivedStateFromProps==null&&w!==p&&h.componentWillReceiveProps!=null&&h.componentWillReceiveProps(w,y),!h.__e&&(h.shouldComponentUpdate!=null&&h.shouldComponentUpdate(w,h.__s,y)===!1||t.__v===n.__v)){for(t.__v!==n.__v&&(h.props=w,h.state=h.__s,h.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.forEach(function(N){N&&(N.__=t)}),k=0;k<h._sb.length;k++)h.__h.push(h._sb[k]);h._sb=[],h.__h.length&&a.push(h);break e}h.componentWillUpdate!=null&&h.componentWillUpdate(w,h.__s,y),h.componentDidUpdate!=null&&h.__h.push(function(){h.componentDidUpdate(p,m,v)})}if(h.context=y,h.props=w,h.__P=e,h.__e=!1,_=ds.__r,E=0,"prototype"in A&&A.prototype.render){for(h.state=h.__s,h.__d=!1,_&&_(t),d=h.render(h.props,h.state,h.context),R=0;R<h._sb.length;R++)h.__h.push(h._sb[R]);h._sb=[]}else do h.__d=!1,_&&_(t),d=h.render(h.props,h.state,h.context),h.state=h.__s;while(h.__d&&++E<25);h.state=h.__s,h.getChildContext!=null&&(s=Dc(Dc({},s),h.getChildContext())),f||h.getSnapshotBeforeUpdate==null||(v=h.getSnapshotBeforeUpdate(p,m)),oj(e,ET(F=d!=null&&d.type===kT&&d.key==null?d.props.children:d)?F:[F],t,n,s,r,i,a,o,l,u),h.base=t.__e,t.__u&=-161,h.__h.length&&a.push(h),b&&(h.__E=h.__=null)}catch(N){t.__v=null,l||i!=null?(t.__e=o,t.__u|=l?160:32,i[i.indexOf(o)]=null):(t.__e=n.__e,t.__k=n.__k),ds.__e(N,t,n)}else i==null&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=ene(n.__e,t,n,s,r,i,a,l,u);(d=ds.diffed)&&d(t)}function Zte(e,t,n){t.__d=void 0;for(var s=0;s<n.length;s++)TT(n[s],n[++s],n[++s]);ds.__c&&ds.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(i){i.call(r)})}catch(i){ds.__e(i,r.__v)}})}function ene(e,t,n,s,r,i,a,o,l){var u,d,h,f,p,m,v,b=n.props,w=t.props,C=t.type;if(C==="svg"&&(r=!0),i!=null){for(u=0;u<i.length;u++)if((p=i[u])&&"setAttribute"in p==!!C&&(C?p.localName===C:p.nodeType===3)){e=p,i[u]=null;break}}if(e==null){if(C===null)return document.createTextNode(w);e=r?document.createElementNS("http://www.w3.org/2000/svg",C):document.createElement(C,w.is&&w),i=null,o=!1}if(C===null)b===w||o&&e.data===w||(e.data=w);else{if(i=i&&ej.call(e.childNodes),b=n.props||jS,!o&&i!=null)for(b={},u=0;u<e.attributes.length;u++)b[(p=e.attributes[u]).name]=p.value;for(u in b)p=b[u],u=="children"||(u=="dangerouslySetInnerHTML"?h=p:u==="key"||u in w||Pv(e,u,null,p,r));for(u in w)p=w[u],u=="children"?f=p:u=="dangerouslySetInnerHTML"?d=p:u=="value"?m=p:u=="checked"?v=p:u==="key"||o&&typeof p!="function"||b[u]===p||Pv(e,u,p,b[u],r);if(d)o||h&&(d.__html===h.__html||d.__html===e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(h&&(e.innerHTML=""),oj(e,ET(f)?f:[f],t,n,s,r&&C!=="foreignObject",i,a,i?i[0]:n.__k&&Pf(n,0),o,l),i!=null)for(u=i.length;u--;)i[u]!=null&&ij(i[u]);o||(u="value",m!==void 0&&(m!==e[u]||C==="progress"&&!m||C==="option"&&m!==b[u])&&Pv(e,u,m,b[u],!1),u="checked",v!==void 0&&v!==e[u]&&Pv(e,u,v,b[u],!1))}return e}function TT(e,t,n){try{typeof e=="function"?e(t):e.current=t}catch(s){ds.__e(s,n)}}function US(e,t,n){var s,r;if(ds.unmount&&ds.unmount(e),(s=e.ref)&&(s.current&&s.current!==e.__e||TT(s,null,t)),(s=e.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(i){ds.__e(i,t)}s.base=s.__P=null,e.__c=void 0}if(s=e.__k)for(r=0;r<s.length;r++)s[r]&&US(s[r],t,n||typeof e.type!="function");n||e.__e==null||ij(e.__e),e.__=e.__e=e.__d=void 0}function tne(e,t,n){return this.constructor(e,n)}ej=rj.slice,ds={__e:function(e,t,n,s){for(var r,i,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((i=r.constructor)&&i.getDerivedStateFromError!=null&&(r.setState(i.getDerivedStateFromError(e)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(e,s||{}),a=r.__d),a)return r.__E=r}catch(o){e=o}throw e}},tj=0,Ib.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=Dc({},this.state),typeof e=="function"&&(e=e(Dc({},n),this.props)),e&&Dc(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),HS(this))},Ib.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),HS(this))},Ib.prototype.render=kT,ju=[],nj=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,LS=function(e,t){return e.__v.__b-t.__v.__b},wx.__r=0,sj=0,function(e){e.Button="button",e.Tab="tab",e.Selector="selector"}(qD||(qD={})),function(e){e.Left="left",e.Center="center",e.Right="right",e.NextToTrigger="next_to_trigger"}(BS||(BS={})),function(e){e.Popover="popover",e.API="api",e.Widget="widget"}(KD||(KD={})),function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"}(YD||(YD={})),function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"}(XD||(XD={})),function(e){e.Once="once",e.Recurring="recurring",e.Always="always"}(QD||(QD={}));var If=function(e,t){if(!function(n){try{new RegExp(n)}catch{return!1}return!0}(t))return!1;try{return new RegExp(t).test(e)}catch{return!1}},ur=Mr("[Surveys]"),tP={icontains:(e,t)=>e.some(n=>t.toLowerCase().includes(n.toLowerCase())),not_icontains:(e,t)=>e.every(n=>!t.toLowerCase().includes(n.toLowerCase())),regex:(e,t)=>e.some(n=>If(t,n)),not_regex:(e,t)=>e.every(n=>!If(t,n)),exact:(e,t)=>e.some(n=>t===n),is_not:(e,t)=>e.every(n=>t!==n)};function nP(e){return e??"icontains"}BS.Right;(function(e,t){var n={__c:t="__cC"+sj++,__:e,Consumer:function(s,r){return s.children(r)},Provider:function(s){var r,i;return this.getChildContext||(r=[],(i={})[t]=this,this.getChildContext=function(){return i},this.shouldComponentUpdate=function(a){this.props.value!==a.value&&r.some(function(o){o.__e=!0,HS(o)})},this.sub=function(a){r.push(a);var o=a.componentWillUnmount;a.componentWillUnmount=function(){r.splice(r.indexOf(a),1),o&&o.call(a)}}),s.children}};n.Provider.__=n.Consumer.contextType=n})({isPreviewMode:!1,previewPageIndex:0,onPopupSurveyDismissed:()=>{},isPopup:!0,onPreviewSubmit:()=>{}});let uj=class{constructor(){dt(this,"events",{}),this.events={}}on(t,n){return this.events[t]||(this.events[t]=[]),this.events[t].push(n),()=>{this.events[t]=this.events[t].filter(s=>s!==n)}}emit(t,n){for(var s of this.events[t]||[])s(n);for(var r of this.events["*"]||[])r(t,n)}},nne=class Dh{constructor(t){dt(this,"_debugEventEmitter",new uj),dt(this,"checkStep",(n,s)=>this.checkStepEvent(n,s)&&this.checkStepUrl(n,s)&&this.checkStepElement(n,s)),dt(this,"checkStepEvent",(n,s)=>s==null||!s.event||n?.event===s?.event),this.instance=t,this.actionEvents=new Set,this.actionRegistry=new Set}init(){var t;if(!wt((t=this.instance)===null||t===void 0?void 0:t._addCaptureHook)){var n;(n=this.instance)===null||n===void 0||n._addCaptureHook((s,r)=>{this.on(s,r)})}}register(t){var n,s;if(!wt((n=this.instance)===null||n===void 0?void 0:n._addCaptureHook)&&(t.forEach(a=>{var o,l;(o=this.actionRegistry)===null||o===void 0||o.add(a),(l=a.steps)===null||l===void 0||l.forEach(u=>{var d;(d=this.actionEvents)===null||d===void 0||d.add(u?.event||"")})}),(s=this.instance)!==null&&s!==void 0&&s.autocapture)){var r,i=new Set;t.forEach(a=>{var o;(o=a.steps)===null||o===void 0||o.forEach(l=>{l!=null&&l.selector&&i.add(l?.selector)})}),(r=this.instance)===null||r===void 0||r.autocapture.setElementSelectors(i)}}on(t,n){var s;n!=null&&t.length!=0&&(this.actionEvents.has(t)||this.actionEvents.has(n?.event))&&this.actionRegistry&&((s=this.actionRegistry)===null||s===void 0?void 0:s.size)>0&&this.actionRegistry.forEach(r=>{this.checkAction(n,r)&&this._debugEventEmitter.emit("actionCaptured",r.name)})}_addActionHook(t){this.onAction("actionCaptured",n=>t(n))}checkAction(t,n){if(n?.steps==null)return!1;for(var s of n.steps)if(this.checkStep(t,s))return!0;return!1}onAction(t,n){return this._debugEventEmitter.on(t,n)}checkStepUrl(t,n){if(n!=null&&n.url){var s,r=t==null||(s=t.properties)===null||s===void 0?void 0:s.$current_url;if(!r||typeof r!="string"||!Dh.matchString(r,n?.url,n?.url_matching||"contains"))return!1}return!0}static matchString(t,n,s){switch(s){case"regex":return!!Be&&If(t,n);case"exact":return n===t;case"contains":var r=Dh.escapeStringRegexp(n).replace(/_/g,".").replace(/%/g,".*");return If(t,r);default:return!1}}static escapeStringRegexp(t){return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}checkStepElement(t,n){if((n!=null&&n.href||n!=null&&n.tag_name||n!=null&&n.text)&&!this.getElementsList(t).some(i=>!(n!=null&&n.href&&!Dh.matchString(i.href||"",n?.href,n?.href_matching||"exact"))&&(n==null||!n.tag_name||i.tag_name===n?.tag_name)&&!(n!=null&&n.text&&!Dh.matchString(i.text||"",n?.text,n?.text_matching||"exact")&&!Dh.matchString(i.$el_text||"",n?.text,n?.text_matching||"exact"))))return!1;if(n!=null&&n.selector){var s,r=t==null||(s=t.properties)===null||s===void 0?void 0:s.$element_selectors;if(!r||!r.includes(n?.selector))return!1}return!0}getElementsList(t){return t?.properties.$elements==null?[]:t?.properties.$elements}},GS=class dj{constructor(t){this.instance=t,this.eventToSurveys=new Map,this.actionToSurveys=new Map}register(t){var n;wt((n=this.instance)===null||n===void 0?void 0:n._addCaptureHook)||(this.setupEventBasedSurveys(t),this.setupActionBasedSurveys(t))}setupActionBasedSurveys(t){var n=t.filter(s=>{var r,i,a,o;return((r=s.conditions)===null||r===void 0?void 0:r.actions)&&((i=s.conditions)===null||i===void 0||(a=i.actions)===null||a===void 0||(o=a.values)===null||o===void 0?void 0:o.length)>0});n.length!==0&&(this.actionMatcher==null&&(this.actionMatcher=new nne(this.instance),this.actionMatcher.init(),this.actionMatcher._addActionHook(s=>{this.onAction(s)})),n.forEach(s=>{var r,i,a,o,l,u,d,h,f,p;s.conditions&&(r=s.conditions)!==null&&r!==void 0&&r.actions&&(i=s.conditions)!==null&&i!==void 0&&(a=i.actions)!==null&&a!==void 0&&a.values&&((o=s.conditions)===null||o===void 0||(l=o.actions)===null||l===void 0||(u=l.values)===null||u===void 0?void 0:u.length)>0&&((d=this.actionMatcher)===null||d===void 0||d.register(s.conditions.actions.values),(h=s.conditions)===null||h===void 0||(f=h.actions)===null||f===void 0||(p=f.values)===null||p===void 0||p.forEach(m=>{if(m&&m.name){var v=this.actionToSurveys.get(m.name);v&&v.push(s.id),this.actionToSurveys.set(m.name,v||[s.id])}}))}))}setupEventBasedSurveys(t){var n;t.filter(s=>{var r,i,a,o;return((r=s.conditions)===null||r===void 0?void 0:r.events)&&((i=s.conditions)===null||i===void 0||(a=i.events)===null||a===void 0||(o=a.values)===null||o===void 0?void 0:o.length)>0}).length!==0&&((n=this.instance)===null||n===void 0||n._addCaptureHook((s,r)=>{this.onEvent(s,r)}),t.forEach(s=>{var r,i,a;(r=s.conditions)===null||r===void 0||(i=r.events)===null||i===void 0||(a=i.values)===null||a===void 0||a.forEach(o=>{if(o&&o.name){var l=this.eventToSurveys.get(o.name);l&&l.push(s.id),this.eventToSurveys.set(o.name,l||[s.id])}})}))}onEvent(t,n){var s,r,i=((s=this.instance)===null||s===void 0||(r=s.persistence)===null||r===void 0?void 0:r.props[Sv])||[];if(dj.SURVEY_SHOWN_EVENT_NAME==t&&n&&i.length>0){var a,o=n==null||(a=n.properties)===null||a===void 0?void 0:a.$survey_id;if(o){var l=i.indexOf(o);l>=0&&(i.splice(l,1),this._updateActivatedSurveys(i))}}else this.eventToSurveys.has(t)&&this._updateActivatedSurveys(i.concat(this.eventToSurveys.get(t)||[]))}onAction(t){var n,s,r=((n=this.instance)===null||n===void 0||(s=n.persistence)===null||s===void 0?void 0:s.props[Sv])||[];this.actionToSurveys.has(t)&&this._updateActivatedSurveys(r.concat(this.actionToSurveys.get(t)||[]))}_updateActivatedSurveys(t){var n,s;(n=this.instance)===null||n===void 0||(s=n.persistence)===null||s===void 0||s.register({[Sv]:[...new Set(t)]})}getSurveys(){var t,n,s=(t=this.instance)===null||t===void 0||(n=t.persistence)===null||n===void 0?void 0:n.props[Sv];return s||[]}getEventToSurveys(){return this.eventToSurveys}_getActionMatcher(){return this.actionMatcher}};dt(GS,"SURVEY_SHOWN_EVENT_NAME","survey shown");let sne=class{constructor(t){dt(this,"_isFetchingSurveys",!1),dt(this,"_isInitializingSurveys",!1),dt(this,"_surveyCallbacks",[]),this.instance=t,this._surveyEventReceiver=null}onRemoteConfig(t){var n=t.surveys;if(En(n))return ur.warn("Decide not loaded yet. Not loading surveys.");var s=cs(n);this._hasSurveys=s?n.length>0:n,ur.info("decide response received, hasSurveys: ".concat(this._hasSurveys)),this._hasSurveys&&this.loadIfEnabled()}reset(){localStorage.removeItem("lastSeenSurveyDate");var t=(()=>{for(var n=[],s=0;s<localStorage.length;s++){var r=localStorage.key(s);r!=null&&r.startsWith("seenSurvey_")&&n.push(r)}return n})();t.forEach(n=>localStorage.removeItem(n))}loadIfEnabled(){if(!this._surveyManager)if(this._isInitializingSurveys)ur.info("Already initializing surveys, skipping...");else if(this.instance.config.disable_surveys)ur.info("Disabled. Not loading surveys.");else{var t=Vt?.__PosthogExtensions__;if(t)if(this._hasSurveys){this._isInitializingSurveys=!0;try{var n=t.generateSurveys;if(n)this._surveyManager=n(this.instance),this._isInitializingSurveys=!1,this._surveyEventReceiver=new GS(this.instance),ur.info("Surveys loaded successfully"),this._notifySurveyCallbacks({isLoaded:!0});else{var s=t.loadExternalDependency;if(s)s(this.instance,"surveys",i=>{if(i||!t.generateSurveys)return ur.error("Could not load surveys script",i),void(this._isInitializingSurveys=!1);this._surveyManager=t.generateSurveys(this.instance),this._isInitializingSurveys=!1,this._surveyEventReceiver=new GS(this.instance),ur.info("Surveys loaded successfully"),this._notifySurveyCallbacks({isLoaded:!0})});else{var r="PostHog loadExternalDependency extension not found. Cannot load remote config.";ur.error(r),this._isInitializingSurveys=!1,this._notifySurveyCallbacks({isLoaded:!1,error:r})}}}catch(i){throw ur.error("Error initializing surveys",i),this._isInitializingSurveys=!1,this._notifySurveyCallbacks({isLoaded:!1,error:"Error initializing surveys"}),i}}else ur.info("No surveys to load.");else ur.error("PostHog Extensions not found.")}}onSurveysLoaded(t){return this._surveyCallbacks.push(t),this._surveyManager&&this._notifySurveyCallbacks({isLoaded:!0}),()=>{this._surveyCallbacks=this._surveyCallbacks.filter(n=>n!==t)}}getSurveys(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(this.instance.config.disable_surveys)return ur.info("Disabled. Not loading surveys."),t([]);var s=this.instance.get_property(vS);if(s&&!n)return t(s,{isLoaded:!0});if(this._isFetchingSurveys)return t([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this._isFetchingSurveys=!0,this.instance._send_request({url:this.instance.requestRouter.endpointFor("api","/api/surveys/?token=".concat(this.instance.config.token)),method:"GET",timeout:this.instance.config.surveys_request_timeout_ms,callback:r=>{var i;this._isFetchingSurveys=!1;var a=r.statusCode;if(a!==200||!r.json){var o="Surveys API could not be loaded, status: ".concat(a);return ur.error(o),t([],{isLoaded:!1,error:o})}var l,u=r.json.surveys||[],d=u.filter(h=>{var f,p,m,v,b,w,C,y,k,_,E,R;return((f=h.conditions)===null||f===void 0?void 0:f.events)&&((p=h.conditions)===null||p===void 0||(m=p.events)===null||m===void 0?void 0:m.values)&&((v=h.conditions)===null||v===void 0||(b=v.events)===null||b===void 0||(w=b.values)===null||w===void 0?void 0:w.length)>0||((C=h.conditions)===null||C===void 0?void 0:C.actions)&&((y=h.conditions)===null||y===void 0||(k=y.actions)===null||k===void 0?void 0:k.values)&&((_=h.conditions)===null||_===void 0||(E=_.actions)===null||E===void 0||(R=E.values)===null||R===void 0?void 0:R.length)>0});return d.length>0&&((l=this._surveyEventReceiver)===null||l===void 0||l.register(d)),(i=this.instance.persistence)===null||i===void 0||i.register({[vS]:u}),t(u,{isLoaded:!0})}})}catch(r){throw this._isFetchingSurveys=!1,r}}_notifySurveyCallbacks(t){for(var n of this._surveyCallbacks)try{t.isLoaded?this.getSurveys(n):n([],t)}catch(s){ur.error("Error in survey callback",s)}}isSurveyFeatureFlagEnabled(t){return!t||this.instance.featureFlags.isFeatureEnabled(t)}getActiveMatchingSurveys(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.getSurveys(s=>{var r,i=s.filter(l=>!(!l.start_date||l.end_date)).filter(l=>{var u;if(!l.conditions)return!0;var d=function(p){var m,v,b;if((m=p.conditions)===null||m===void 0||!m.url)return!0;var w=Be==null||(v=Be.location)===null||v===void 0?void 0:v.href;if(!w)return!1;var C=[p.conditions.url];return tP[nP((b=p.conditions)===null||b===void 0?void 0:b.urlMatchType)](C,w)}(l),h=(u=l.conditions)===null||u===void 0||!u.selector||_t?.querySelector(l.conditions.selector),f=function(p){var m,v,b;if((m=p.conditions)===null||m===void 0||!m.deviceTypes||((v=p.conditions)===null||v===void 0?void 0:v.deviceTypes.length)===0)return!0;if(!Ns)return!1;var w=Qn.deviceType(Ns);return tP[nP((b=p.conditions)===null||b===void 0?void 0:b.deviceTypesMatchType)](p.conditions.deviceTypes,w)}(l);return d&&h&&f}),a=(r=this._surveyEventReceiver)===null||r===void 0?void 0:r.getSurveys(),o=i.filter(l=>{var u,d,h,f,p,m,v,b,w;if(!(l.linked_flag_key||l.targeting_flag_key||l.internal_targeting_flag_key||(u=l.feature_flag_keys)!==null&&u!==void 0&&u.length))return!0;var C=this.isSurveyFeatureFlagEnabled(l.linked_flag_key),y=this.isSurveyFeatureFlagEnabled(l.targeting_flag_key),k=((d=(h=l.conditions)===null||h===void 0||(f=h.events)===null||f===void 0||(p=f.values)===null||p===void 0?void 0:p.length)!==null&&d!==void 0?d:0)>0,_=((m=(v=l.conditions)===null||v===void 0||(b=v.actions)===null||b===void 0||(w=b.values)===null||w===void 0?void 0:w.length)!==null&&m!==void 0?m:0)>0,E=!k&&!_||a?.includes(l.id),R=this._canActivateRepeatedly(l)||this.isSurveyFeatureFlagEnabled(l.internal_targeting_flag_key),F=this.checkFlags(l);return C&&y&&R&&E&&F});return t(o)},n)}checkFlags(t){var n;return(n=t.feature_flag_keys)===null||n===void 0||!n.length||t.feature_flag_keys.every(s=>{var{key:r,value:i}=s;return!r||!i||this.instance.featureFlags.isFeatureEnabled(i)})}_canActivateRepeatedly(t){var n;return En((n=Vt.__PosthogExtensions__)===null||n===void 0?void 0:n.canActivateRepeatedly)?(ur.warn("init was not called"),!1):Vt.__PosthogExtensions__.canActivateRepeatedly(t)}canRenderSurvey(t){if(En(this._surveyManager))return ur.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=null;return this.getSurveys(s=>{var r=s.filter(i=>i.id===t)[0];n=r?We({},this._surveyManager.canRenderSurvey(r)):{visible:!1,disabledReason:"Survey not found"}}),n}renderSurvey(t,n){En(this._surveyManager)?ur.warn("init was not called"):this.getSurveys(s=>{var r=s.filter(i=>i.id===t)[0];this._surveyManager.renderSurvey(r,_t?.querySelector(n))})}};var sP=Mr("[RateLimiter]");let rne=class{constructor(t){var n,s;dt(this,"serverLimits",{}),dt(this,"lastEventRateLimited",!1),dt(this,"checkForLimiting",r=>{var i=r.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach(a=>{sP.info("".concat(a||"events"," is quota limited.")),this.serverLimits[a]=new Date().getTime()+6e4})}catch(a){return void sP.warn('could not rate limit - continuing. Error: "'.concat(a?.message,'"'),{text:i})}}),this.instance=t,this.captureEventsPerSecond=((n=t.config.rate_limiting)===null||n===void 0?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((s=t.config.rate_limiting)===null||s===void 0?void 0:s.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(){var t,n,s,r=arguments.length>0&&arguments[0]!==void 0&&arguments[0],i=new Date().getTime(),a=(t=(n=this.instance.persistence)===null||n===void 0?void 0:n.get_property(xS))!==null&&t!==void 0?t:{tokens:this.captureEventsBurstLimit,last:i};a.tokens+=(i-a.last)/1e3*this.captureEventsPerSecond,a.last=i,a.tokens>this.captureEventsBurstLimit&&(a.tokens=this.captureEventsBurstLimit);var o=a.tokens<1;return o||r||(a.tokens=Math.max(0,a.tokens-1)),!o||this.lastEventRateLimited||r||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to ".concat(this.captureEventsPerSecond," events per second and ").concat(this.captureEventsBurstLimit," events burst limit.")},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=o,(s=this.instance.persistence)===null||s===void 0||s.set_property(xS,a),{isRateLimited:o,remainingTokens:a.tokens}}isServerRateLimited(t){var n=this.serverLimits[t||"events"]||!1;return n!==!1&&new Date().getTime()<n}};var Au=Mr("[RemoteConfig]");let ine=class{constructor(t){this.instance=t}get remoteConfig(){var t,n;return(t=Vt._POSTHOG_REMOTE_CONFIG)===null||t===void 0||(n=t[this.instance.config.token])===null||n===void 0?void 0:n.config}_loadRemoteConfigJs(t){var n,s,r;(n=Vt.__PosthogExtensions__)!==null&&n!==void 0&&n.loadExternalDependency?(s=Vt.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"remote-config",()=>t(this.remoteConfig)):(Au.error("PostHog Extensions not found. Cannot load remote config."),t())}_loadRemoteConfigJSON(t){this.instance._send_request({method:"GET",url:this.instance.requestRouter.endpointFor("assets","/array/".concat(this.instance.config.token,"/config")),callback:n=>{t(n.json)}})}load(){try{if(this.remoteConfig)return Au.info("Using preloaded remote config",this.remoteConfig),void this.onRemoteConfig(this.remoteConfig);if(this.instance.config.advanced_disable_decide)return void Au.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs(t=>{if(!t)return Au.info("No config found after loading remote JS config. Falling back to JSON."),void this._loadRemoteConfigJSON(n=>{this.onRemoteConfig(n)});this.onRemoteConfig(t)})}catch(t){Au.error("Error loading remote config",t)}}onRemoteConfig(t){t?this.instance.config.__preview_remote_config?(this.instance._onRemoteConfig(t),t.hasFeatureFlags!==!1&&this.instance.featureFlags.ensureFlagsLoaded()):Au.info("__preview_remote_config is disabled. Logging config instead",t):Au.error("Failed to fetch remote config from PostHog.")}};var ane=function(e){var t,n,s,r,i="";for(t=n=0,s=(e=(e+"").replace(/\r\n/g,`
|
|
4
4
|
`).replace(/\r/g,`
|
|
5
5
|
`)).length,r=0;r<s;r++){var a=e.charCodeAt(r),o=null;a<128?n++:o=a>127&&a<2048?String.fromCharCode(a>>6|192,63&a|128):String.fromCharCode(a>>12|224,a>>6&63|128,63&a|128),iu(o)||(n>t&&(i+=e.substring(t,n)),i+=o,t=n=r+1)}return n>t&&(i+=e.substring(t,e.length)),i},one=!!hS||!!dS,rP="text/plain",Cx=(e,t)=>{var[n,s]=e.split("?"),r=We({},t);s?.split("&").forEach(a=>{var[o]=a.split("=");delete r[o]});var i=Pee(r);return i=i?(s?s+"&":"")+i:s,"".concat(n,"?").concat(i)},_g=(e,t)=>JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString():s,t),Vy=e=>{var{data:t,compression:n}=e;if(t){if(n===ja.GZipJS){var s=M6(O6(_g(t)),{mtime:0}),r=new Blob([s],{type:rP});return{contentType:rP,body:r,estimatedSize:r.size}}if(n===ja.Base64){var i=function(l){var u,d,h,f,p,m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",v=0,b=0,w="",C=[];if(!l)return l;l=ane(l);do u=(p=l.charCodeAt(v++)<<16|l.charCodeAt(v++)<<8|l.charCodeAt(v++))>>18&63,d=p>>12&63,h=p>>6&63,f=63&p,C[b++]=m.charAt(u)+m.charAt(d)+m.charAt(h)+m.charAt(f);while(v<l.length);switch(w=C.join(""),l.length%3){case 1:w=w.slice(0,-2)+"==";break;case 2:w=w.slice(0,-1)+"="}return w}(_g(t)),a=(l=>"data="+encodeURIComponent(typeof l=="string"?l:_g(l)))(i);return{contentType:"application/x-www-form-urlencoded",body:a,estimatedSize:new Blob([a]).size}}var o=_g(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Hg=[];dS&&Hg.push({transport:"fetch",method:e=>{var t,n,{contentType:s,body:r,estimatedSize:i}=(t=Vy(e))!==null&&t!==void 0?t:{},a=new Headers;Nn(e.headers,function(d,h){a.append(h,d)}),s&&a.append("Content-Type",s);var o=e.url,l=null;if(eD){var u=new eD;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),e.timeout)}}dS(o,We({method:e?.method||"GET",headers:a,keepalive:e.method==="POST"&&(i||0)<52428.8,body:r,signal:(n=l)===null||n===void 0?void 0:n.signal},e.fetchOptions)).then(d=>d.text().then(h=>{var f,p={statusCode:d.status,text:h};if(d.status===200)try{p.json=JSON.parse(h)}catch(m){Rt.error(m)}(f=e.callback)===null||f===void 0||f.call(e,p)})).catch(d=>{var h;Rt.error(d),(h=e.callback)===null||h===void 0||h.call(e,{statusCode:0,text:d})}).finally(()=>l?clearTimeout(l.timeout):null)}}),hS&&Hg.push({transport:"XHR",method:e=>{var t,n=new hS;n.open(e.method||"GET",e.url,!0);var{contentType:s,body:r}=(t=Vy(e))!==null&&t!==void 0?t:{};Nn(e.headers,function(i,a){n.setRequestHeader(a,i)}),s&&n.setRequestHeader("Content-Type",s),e.timeout&&(n.timeout=e.timeout),n.withCredentials=!0,n.onreadystatechange=()=>{if(n.readyState===4){var i,a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}(i=e.callback)===null||i===void 0||i.call(e,a)}},n.send(r)}}),Ii!=null&&Ii.sendBeacon&&Hg.push({transport:"sendBeacon",method:e=>{var t=Cx(e.url,{beacon:"1"});try{var n,{contentType:s,body:r}=(n=Vy(e))!==null&&n!==void 0?n:{},i=typeof r=="string"?new Blob([r],{type:s}):r;Ii.sendBeacon(t,i)}catch{}}});var VS=3e3;let lne=class{constructor(t,n){dt(this,"isPaused",!0),dt(this,"queue",[]),this.flushTimeoutMs=ia(n?.flush_interval_ms||VS,250,5e3,"flush interval",VS),this.sendRequest=t}enqueue(t){this.queue.push(t),this.flushTimeout||this.setFlushTimeout()}unload(){this.clearFlushTimeout();var t=this.queue.length>0?this.formatQueue():{},n=Object.values(t),s=[...n.filter(r=>r.url.indexOf("/e")===0),...n.filter(r=>r.url.indexOf("/e")!==0)];s.map(r=>{this.sendRequest(We(We({},r),{},{transport:"sendBeacon"}))})}enable(){this.isPaused=!1,this.setFlushTimeout()}setFlushTimeout(){var t=this;this.isPaused||(this.flushTimeout=setTimeout(()=>{if(this.clearFlushTimeout(),this.queue.length>0){var n=this.formatQueue(),s=function(i){var a=n[i],o=new Date().getTime();a.data&&cs(a.data)&&Nn(a.data,l=>{l.offset=Math.abs(l.timestamp-o),delete l.timestamp}),t.sendRequest(a)};for(var r in n)s(r)}},this.flushTimeoutMs))}clearFlushTimeout(){clearTimeout(this.flushTimeout),this.flushTimeout=void 0}formatQueue(){var t={};return Nn(this.queue,n=>{var s,r=n,i=(r?r.batchKey:null)||r.url;wt(t[i])&&(t[i]=We(We({},r),{},{data:[]})),(s=t[i].data)===null||s===void 0||s.push(r.data)}),this.queue=[],t}};var cne=["retriesPerformedSoFar"];let une=class{constructor(t){dt(this,"isPolling",!1),dt(this,"pollIntervalMs",3e3),dt(this,"queue",[]),this.instance=t,this.queue=[],this.areWeOnline=!0,!wt(Be)&&"onLine"in Be.navigator&&(this.areWeOnline=Be.navigator.onLine,Cs(Be,"online",()=>{this.areWeOnline=!0,this.flush()}),Cs(Be,"offline",()=>{this.areWeOnline=!1}))}retriableRequest(t){var{retriesPerformedSoFar:n}=t,s=u6(t,cne);qr(n)&&n>0&&(s.url=Cx(s.url,{retry_count:n})),this.instance._send_request(We(We({},s),{},{callback:r=>{var i;r.statusCode!==200&&(r.statusCode<400||r.statusCode>=500)&&(n??0)<10?this.enqueue(We({retriesPerformedSoFar:n},s)):(i=s.callback)===null||i===void 0||i.call(s,r)}}))}enqueue(t){var n=t.retriesPerformedSoFar||0;t.retriesPerformedSoFar=n+1;var s=function(a){var o=3e3*Math.pow(2,a),l=o/2,u=Math.min(18e5,o),d=(Math.random()-.5)*(u-l);return Math.ceil(u+d)}(n),r=Date.now()+s;this.queue.push({retryAt:r,requestOptions:t});var i="Enqueued failed request for retry in ".concat(s);navigator.onLine||(i+=" (Browser is offline)"),Rt.warn(i),this.isPolling||(this.isPolling=!0,this.poll())}poll(){this.poller&&clearTimeout(this.poller),this.poller=setTimeout(()=>{this.areWeOnline&&this.queue.length>0&&this.flush(),this.poll()},this.pollIntervalMs)}flush(){var t=Date.now(),n=[],s=this.queue.filter(i=>i.retryAt<t||(n.push(i),!1));if(this.queue=n,s.length>0)for(var{requestOptions:r}of s)this.retriableRequest(r)}unload(){for(var{requestOptions:t}of(this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.queue))try{this.instance._send_request(We(We({},t),{},{transport:"sendBeacon"}))}catch(n){Rt.error(n)}this.queue=[]}},dne=class{constructor(t){dt(this,"_updateScrollData",()=>{var n,s,r,i;this.context||(this.context={});var a=this.scrollElement(),o=this.scrollY(),l=a?Math.max(0,a.scrollHeight-a.clientHeight):0,u=o+(a?.clientHeight||0),d=a?.scrollHeight||0;this.context.lastScrollY=Math.ceil(o),this.context.maxScrollY=Math.max(o,(n=this.context.maxScrollY)!==null&&n!==void 0?n:0),this.context.maxScrollHeight=Math.max(l,(s=this.context.maxScrollHeight)!==null&&s!==void 0?s:0),this.context.lastContentY=u,this.context.maxContentY=Math.max(u,(r=this.context.maxContentY)!==null&&r!==void 0?r:0),this.context.maxContentHeight=Math.max(d,(i=this.context.maxContentHeight)!==null&&i!==void 0?i:0)}),this.instance=t}getContext(){return this.context}resetContext(){var t=this.context;return setTimeout(this._updateScrollData,0),t}startMeasuringScrollPosition(){Cs(Be,"scroll",this._updateScrollData,{capture:!0}),Cs(Be,"scrollend",this._updateScrollData,{capture:!0}),Cs(Be,"resize",this._updateScrollData)}scrollElement(){if(!this.instance.config.scroll_root_selector)return Be?.document.documentElement;var t=cs(this.instance.config.scroll_root_selector)?this.instance.config.scroll_root_selector:[this.instance.config.scroll_root_selector];for(var n of t){var s=Be?.document.querySelector(n);if(s)return s}}scrollY(){if(this.instance.config.scroll_root_selector){var t=this.scrollElement();return t&&t.scrollTop||0}return Be&&(Be.scrollY||Be.pageYOffset||Be.document.documentElement.scrollTop)||0}scrollX(){if(this.instance.config.scroll_root_selector){var t=this.scrollElement();return t&&t.scrollLeft||0}return Be&&(Be.scrollX||Be.pageXOffset||Be.document.documentElement.scrollLeft)||0}};var hne=e=>Qn.personInfo({maskPersonalDataProperties:e?.config.mask_personal_data_properties,customPersonalDataProperties:e?.config.custom_personal_data_properties});let fne=class{constructor(t,n,s,r){dt(this,"_onSessionIdCallback",i=>{var a=this._getStored();if(!a||a.sessionId!==i){var o={sessionId:i,props:this._sessionSourceParamGenerator(this.instance)};this._persistence.register({[bS]:o})}}),this.instance=t,this._sessionIdManager=n,this._persistence=s,this._sessionSourceParamGenerator=r||hne,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[bS]}getSetOnceProps(){var t,n=(t=this._getStored())===null||t===void 0?void 0:t.props;return n?"r"in n?Qn.personPropsFromInfo(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var t={};return Nn(Pm(this.getSetOnceProps()),(n,s)=>{s==="$current_url"&&(s="url"),t["$session_entry_".concat(mT(s))]=n}),t}};var iP=Mr("[SessionId]");let pne=class{constructor(t,n,s){var r;if(dt(this,"_sessionIdChangedHandlers",[]),!t.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(t.config.__preview_experimental_cookieless_mode)throw new Error("SessionIdManager cannot be used with __preview_experimental_cookieless_mode");this.config=t.config,this.persistence=t.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this._sessionIdGenerator=n||Fc,this._windowIdGenerator=s||Fc;var i=this.config.persistence_name||this.config.token,a=this.config.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*ia(a,60,36e3,"session_idle_timeout_seconds",1800),t.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.resetIdleTimer(),this._window_id_storage_key="ph_"+i+"_window_id",this._primary_window_exists_storage_key="ph_"+i+"_primary_window_exists",this._canUseSessionStorage()){var o=hr.parse(this._window_id_storage_key),l=hr.parse(this._primary_window_exists_storage_key);o&&!l?this._windowId=o:hr.remove(this._window_id_storage_key),hr.set(this._primary_window_exists_storage_key,!0)}if((r=this.config.bootstrap)!==null&&r!==void 0&&r.sessionID)try{var u=(d=>{var h=d.replace(/-/g,"");if(h.length!==32)throw new Error("Not a valid UUID");if(h[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(h.substring(0,12),16)})(this.config.bootstrap.sessionID);this._setSessionId(this.config.bootstrap.sessionID,new Date().getTime(),u)}catch(d){iP.error("Invalid sessionID in bootstrap",d)}this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return wt(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(t),this._sessionId&&t(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter(n=>n!==t)}}_canUseSessionStorage(){return this.config.persistence!=="memory"&&!this.persistence.disabled&&hr.is_supported()}_setWindowId(t){t!==this._windowId&&(this._windowId=t,this._canUseSessionStorage()&&hr.set(this._window_id_storage_key,t))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?hr.parse(this._window_id_storage_key):null}_setSessionId(t,n,s){t===this._sessionId&&n===this._sessionActivityTimestamp&&s===this._sessionStartTimestamp||(this._sessionStartTimestamp=s,this._sessionActivityTimestamp=n,this._sessionId=t,this.persistence.register({[dx]:[n,t,s]}))}_getSessionId(){if(this._sessionId&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this._sessionId,this._sessionStartTimestamp];var t=this.persistence.props[dx];return cs(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this._setSessionId(null,null,null)}_listenToReloadWindow(){Cs(Be,"beforeunload",()=>{this._canUseSessionStorage()&&hr.remove(this._primary_window_exists_storage_key)},{capture:!1})}checkAndGetSessionAndWindowId(){var t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;if(this.config.__preview_experimental_cookieless_mode)throw new Error("checkAndGetSessionAndWindowId should not be called in __preview_experimental_cookieless_mode");var s=n||new Date().getTime(),[r,i,a]=this._getSessionId(),o=this._getWindowId(),l=qr(a)&&a>0&&Math.abs(s-a)>864e5,u=!1,d=!i,h=!t&&Math.abs(s-r)>this.sessionTimeoutMs;d||h||l?(i=this._sessionIdGenerator(),o=this._windowIdGenerator(),iP.info("new session ID generated",{sessionId:i,windowId:o,changeReason:{noSessionId:d,activityTimeout:h,sessionPastMaximumLength:l}}),a=s,u=!0):o||(o=this._windowIdGenerator(),u=!0);var f=r===0||!t||l?s:r,p=a===0?new Date().getTime():a;return this._setWindowId(o),this._setSessionId(i,f,p),t||this.resetIdleTimer(),u&&this._sessionIdChangedHandlers.forEach(m=>m(i,o,u?{noSessionId:d,activityTimeout:h,sessionPastMaximumLength:l}:void 0)),{sessionId:i,windowId:o,sessionStartTimestamp:p,changeReason:u?{noSessionId:d,activityTimeout:h,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:r}}resetIdleTimer(){clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout(()=>{this.resetSessionId()},1.1*this.sessionTimeoutMs)}};var gne=["$set_once","$set"],fc=Mr("[SiteApps]");let mne=class{constructor(t){this.instance=t,this.bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this.instance.config.opt_in_site_apps}eventCollector(t,n){if(n){var s=this.globalsForEvent(n);this.bufferedInvocations.push(s),this.bufferedInvocations.length>1e3&&(this.bufferedInvocations=this.bufferedInvocations.slice(10))}}get siteAppLoaders(){var t,n;return(t=Vt._POSTHOG_REMOTE_CONFIG)===null||t===void 0||(n=t[this.instance.config.token])===null||n===void 0?void 0:n.siteApps}init(){if(this.isEnabled){var t=this.instance._addCaptureHook(this.eventCollector.bind(this));this.stopBuffering=()=>{t(),this.bufferedInvocations=[],this.stopBuffering=void 0}}}globalsForEvent(t){var n,s,r,i,a,o,l;if(!t)throw new Error("Event payload is required");var u={},d=this.instance.get_property("$groups")||[],h=this.instance.get_property("$stored_group_properties")||{};for(var[f,p]of Object.entries(h))u[f]={id:d[f],type:f,properties:p};var{$set_once:m,$set:v}=t;return{event:We(We({},u6(t,gne)),{},{properties:We(We(We({},t.properties),v?{$set:We(We({},(n=(s=t.properties)===null||s===void 0?void 0:s.$set)!==null&&n!==void 0?n:{}),v)}:{}),m?{$set_once:We(We({},(r=(i=t.properties)===null||i===void 0?void 0:i.$set_once)!==null&&r!==void 0?r:{}),m)}:{}),elements_chain:(a=(o=t.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&a!==void 0?a:"",distinct_id:(l=t.properties)===null||l===void 0?void 0:l.distinct_id}),person:{properties:this.instance.get_property("$stored_person_properties")},groups:u}}setupSiteApp(t){var n=this.apps[t.id],s=()=>{var o;!n.errored&&this.bufferedInvocations.length&&(fc.info("Processing ".concat(this.bufferedInvocations.length," events for site app with id ").concat(t.id)),this.bufferedInvocations.forEach(l=>{var u;return(u=n.processEvent)===null||u===void 0?void 0:u.call(n,l)}),n.processedBuffer=!0),Object.values(this.apps).every(l=>l.processedBuffer||l.errored)&&((o=this.stopBuffering)===null||o===void 0||o.call(this))},r=!1,i=o=>{n.errored=!o,n.loaded=!0,fc.info("Site app with id ".concat(t.id," ").concat(o?"loaded":"errored")),r&&s()};try{var{processEvent:a}=t.init({posthog:this.instance,callback:o=>{i(o)}});a&&(n.processEvent=a),r=!0}catch(o){fc.error("Error while initializing PostHog app with config id ".concat(t.id),o),i(!1)}if(r&&n.loaded)try{s()}catch(o){fc.error("Error while processing buffered events PostHog app with config id ".concat(t.id),o),n.errored=!0}}setupSiteApps(){var t=this.siteAppLoaders||[];for(var n of t)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var s of t)this.setupSiteApp(s)}onCapturedEvent(t){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t);for(var s of Object.values(this.apps))try{var r;(r=s.processEvent)===null||r===void 0||r.call(s,n)}catch(i){fc.error("Error while processing event ".concat(t.event," for site app ").concat(s.id),i)}}}onRemoteConfig(t){var n,s,r,i=this;if((n=this.siteAppLoaders)!==null&&n!==void 0&&n.length)return this.isEnabled?(this.setupSiteApps(),void this.instance.on("eventCaptured",u=>this.onCapturedEvent(u))):void fc.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.stopBuffering)===null||s===void 0||s.call(this),(r=t.siteApps)!==null&&r!==void 0&&r.length)if(this.isEnabled){var a=function(u,d){var h,f;Vt["__$$ph_site_app_".concat(u)]=i.instance,(h=Vt.__PosthogExtensions__)===null||h===void 0||(f=h.loadSiteApp)===null||f===void 0||f.call(h,i.instance,d,p=>{if(p)return fc.error("Error while initializing PostHog app with config id ".concat(u),p)})};for(var{id:o,url:l}of t.siteApps)a(o,l)}else fc.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}};var Ku,vne=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google","bytespider"],aP=function(e,t){if(!e)return!1;var n=e.toLowerCase();return vne.concat(t||[]).some(s=>{var r=s.toLowerCase();return n.indexOf(r)!==-1})},hj=function(e,t){if(!e)return!1;var n=e.userAgent;if(n&&aP(n,t))return!0;try{var s=e?.userAgentData;if(s!=null&&s.brands&&s.brands.some(r=>aP(r?.brand,t)))return!0}catch{}return!!e.webdriver};function oP(e,t,n){return _g({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:n})}(function(e){e.US="us",e.EU="eu",e.CUSTOM="custom"})(Ku||(Ku={}));var lP="i.posthog.com";let bne=class{constructor(t){dt(this,"_regionCache",{}),this.instance=t}get apiHost(){var t=this.instance.config.api_host.trim().replace(/\/$/,"");return t==="https://app.posthog.com"?"https://us.i.posthog.com":t}get uiHost(){var t,n=(t=this.instance.config.ui_host)===null||t===void 0?void 0:t.replace(/\/$/,"");return n||(n=this.apiHost.replace(".".concat(lP),".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this._regionCache[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this._regionCache[this.apiHost]=Ku.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this._regionCache[this.apiHost]=Ku.EU:this._regionCache[this.apiHost]=Ku.CUSTOM),this._regionCache[this.apiHost]}endpointFor(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";if(n&&(n=n[0]==="/"?n:"/".concat(n)),t==="ui")return this.uiHost+n;if(this.region===Ku.CUSTOM)return this.apiHost+n;var s=lP+n;switch(t){case"assets":return"https://".concat(this.region,"-assets.").concat(s);case"api":return"https://".concat(this.region,".").concat(s)}}};var xne={icontains:(e,t)=>!!Be&&t.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>!!Be&&t.href.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>!!Be&&If(t.href,e),not_regex:(e,t)=>!!Be&&!If(t.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};let wne=class Wr{constructor(t){var n=this;dt(this,"getWebExperimentsAndEvaluateDisplayLogic",function(){var s=arguments.length>0&&arguments[0]!==void 0&&arguments[0];n.getWebExperiments(r=>{Wr.logInfo("retrieved web experiments from the server"),n._flagToExperiments=new Map,r.forEach(i=>{if(i.feature_flag_key){var a;n._flagToExperiments&&(Wr.logInfo("setting flag key ",i.feature_flag_key," to web experiment ",i),(a=n._flagToExperiments)===null||a===void 0||a.set(i.feature_flag_key,i));var o=n.instance.getFeatureFlag(i.feature_flag_key);Os(o)&&i.variants[o]&&n.applyTransforms(i.name,o,i.variants[o].transforms)}else if(i.variants)for(var l in i.variants){var u=i.variants[l];Wr.matchesTestVariant(u)&&n.applyTransforms(i.name,l,u.transforms)}})},s)}),this.instance=t,this.instance.onFeatureFlags(s=>{this.onFeatureFlags(s)})}onFeatureFlags(t){if(this._is_bot())Wr.logInfo("Refusing to render web experiment since the viewer is a likely bot");else if(!this.instance.config.disable_web_experiments){if(En(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Wr.logInfo("applying feature flags",t),t.forEach(n=>{var s;if(this._flagToExperiments&&(s=this._flagToExperiments)!==null&&s!==void 0&&s.has(n)){var r,i=this.instance.getFeatureFlag(n),a=(r=this._flagToExperiments)===null||r===void 0?void 0:r.get(n);i&&a!=null&&a.variants[i]&&this.applyTransforms(a.name,i,a.variants[i].transforms)}})}}previewWebExperiment(){var t=Wr.getWindowLocation();if(t!=null&&t.search){var n=gx(t?.search,"__experiment_id"),s=gx(t?.search,"__experiment_variant");n&&s&&(Wr.logInfo("previewing web experiments ".concat(n," && ").concat(s)),this.getWebExperiments(r=>{this.showPreviewWebExperiment(parseInt(n),s,r)},!1,!0))}}loadIfEnabled(){this.instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,n,s){if(this.instance.config.disable_web_experiments&&!s)return t([]);var r=this.instance.get_property("$web_experiments");if(r&&!n)return t(r);this.instance._send_request({url:this.instance.requestRouter.endpointFor("api","/api/web_experiments/?token=".concat(this.instance.config.token)),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return t([]);var a=i.json.experiments||[];return t(a)}})}showPreviewWebExperiment(t,n,s){var r=s.filter(i=>i.id===t);r&&r.length>0&&(Wr.logInfo("Previewing web experiment [".concat(r[0].name,"] with variant [").concat(n,"]")),this.applyTransforms(r[0].name,n,r[0].variants[n].transforms))}static matchesTestVariant(t){return!En(t.conditions)&&Wr.matchUrlConditions(t)&&Wr.matchUTMConditions(t)}static matchUrlConditions(t){var n;if(En(t.conditions)||En((n=t.conditions)===null||n===void 0?void 0:n.url))return!0;var s,r,i,a=Wr.getWindowLocation();return!!a&&((s=t.conditions)===null||s===void 0||!s.url||xne[(r=(i=t.conditions)===null||i===void 0?void 0:i.urlMatchType)!==null&&r!==void 0?r:"icontains"](t.conditions.url,a))}static getWindowLocation(){return Be?.location}static matchUTMConditions(t){var n;if(En(t.conditions)||En((n=t.conditions)===null||n===void 0?void 0:n.utm))return!0;var s=Qn.campaignParams();if(s.utm_source){var r,i,a,o,l,u,d,h,f,p,m,v,b,w,C,y,k=(r=t.conditions)===null||r===void 0||(i=r.utm)===null||i===void 0||!i.utm_campaign||((a=t.conditions)===null||a===void 0||(o=a.utm)===null||o===void 0?void 0:o.utm_campaign)==s.utm_campaign,_=(l=t.conditions)===null||l===void 0||(u=l.utm)===null||u===void 0||!u.utm_source||((d=t.conditions)===null||d===void 0||(h=d.utm)===null||h===void 0?void 0:h.utm_source)==s.utm_source,E=(f=t.conditions)===null||f===void 0||(p=f.utm)===null||p===void 0||!p.utm_medium||((m=t.conditions)===null||m===void 0||(v=m.utm)===null||v===void 0?void 0:v.utm_medium)==s.utm_medium,R=(b=t.conditions)===null||b===void 0||(w=b.utm)===null||w===void 0||!w.utm_term||((C=t.conditions)===null||C===void 0||(y=C.utm)===null||y===void 0?void 0:y.utm_term)==s.utm_term;return k&&E&&R&&_}return!1}static logInfo(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),r=1;r<n;r++)s[r-1]=arguments[r];Rt.info("[WebExperiments] ".concat(t),s)}applyTransforms(t,n,s){this._is_bot()?Wr.logInfo("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?s.forEach(r=>{if(r.selector){var i;Wr.logInfo("applying transform of variant ".concat(n," for experiment ").concat(t," "),r);var a=(i=document)===null||i===void 0?void 0:i.querySelectorAll(r.selector);a?.forEach(o=>{var l=o;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)})}}):Wr.logInfo("Control variants leave the page unmodified.")}_is_bot(){return Ii&&this.instance?hj(Ii,this.instance.config.custom_blocked_useragents):void 0}};var Ug={},WS=()=>{},Ph="posthog",fj=!one&&Ns?.indexOf("MSIE")===-1&&Ns?.indexOf("Mozilla")===-1,cP=()=>{var e;return{api_host:"https://us.i.posthog.com",ui_host:null,token:"",autocapture:!0,rageclick:!0,cross_subdomain_cookie:yee(_t?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:WS,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:!0,capture_pageleave:"if_capture_pageview",debug:li&&Os(li?.search)&&li.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(Be==null||(e=Be.location)===null||e===void 0?void 0:e.protocol)==="https:",ip:!0,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,session_recording:{},mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:t=>{var n="Bad HTTP status: "+t.statusCode+" "+t.text;Rt.error(n)},get_device_id:t=>t,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:VS},_onCapture:WS}},uP=e=>{var t={};wt(e.process_person)||(t.person_profiles=e.process_person),wt(e.xhr_headers)||(t.request_headers=e.xhr_headers),wt(e.cookie_name)||(t.persistence_name=e.cookie_name),wt(e.disable_cookie)||(t.disable_persistence=e.disable_cookie),wt(e.store_google)||(t.save_campaign_params=e.store_google),wt(e.verbose)||(t.debug=e.verbose);var n=xs({},t,e);return cs(e.property_blacklist)&&(wt(e.property_denylist)?n.property_denylist=e.property_blacklist:cs(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:Rt.error("Invalid value for property_denylist config: "+e.property_denylist)),n};class Cne{constructor(){dt(this,"__forceAllowLocalhost",!1)}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(t){Rt.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}}class fC{get decideEndpointWasHit(){var t,n;return(t=(n=this.featureFlags)===null||n===void 0?void 0:n.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){dt(this,"webPerformance",new Cne),dt(this,"_personProcessingSetOncePropertiesSent",!1),dt(this,"version",pl.LIB_VERSION),dt(this,"_internalEventEmitter",new uj),this.config=cP(),this.SentryIntegration=Tte,this.sentryIntegration=t=>function(n,s){var r=B6(n,s);return{name:L6,processEvent:i=>r(i)}}(this,t),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this._initialPageviewCaptured=!1,this._initialPersonProfilesConfig=null,this._cachedPersonProperties=null,this.featureFlags=new Kte(this),this.toolbar=new Ate(this),this.scrollManager=new dne(this),this.pageViewManager=new Mte(this),this.surveys=new sne(this),this.experiments=new wne(this),this.exceptions=new Ote(this),this.rateLimiter=new rne(this),this.requestRouter=new bne(this),this.consent=new zee(this),this.people={set:(t,n,s)=>{var r=Os(t)?{[t]:n}:t;this.setPersonProperties(r),s?.({})},set_once:(t,n,s)=>{var r=Os(t)?{[t]:n}:t;this.setPersonProperties(void 0,r),s?.({})}},this.on("eventCaptured",t=>Rt.info('send "'.concat(t?.event,'"'),t))}init(t,n,s){if(s&&s!==Ph){var r,i=(r=Ug[s])!==null&&r!==void 0?r:new fC;return i._init(t,n,s),Ug[s]=i,Ug[Ph][s]=i,i}return this._init(t,n,s)}_init(t){var n,s,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;if(wt(t)||fS(t))return Rt.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return Rt.warn("You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},this._triggered_notifs=[],r.person_profiles&&(this._initialPersonProfilesConfig=r.person_profiles),this.set_config(xs({},cP(),uP(r),{name:i,token:t})),this.config.on_xhr_error&&Rt.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=r.disable_compression?void 0:ja.GZipJS,this.persistence=new Uy(this.config),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Uy(We(We({},this.config),{},{persistence:"sessionStorage"}));var a=We({},this.persistence.props),o=We({},this.sessionPersistence.props);if(this._requestQueue=new lne(w=>this._send_retriable_request(w),this.config.request_queue_config),this._retryQueue=new une(this),this.__request_queue=[],this.config.__preview_experimental_cookieless_mode||(this.sessionManager=new pne(this),this.sessionPropsManager=new fne(this,this.sessionManager,this.persistence)),new Dte(this).startIfEnabledOrStop(),this.siteApps=new mne(this),(n=this.siteApps)===null||n===void 0||n.init(),this.config.__preview_experimental_cookieless_mode||(this.sessionRecording=new Ete(this),this.sessionRecording.startIfEnabledOrStop()),this.config.disable_scroll_properties||this.scrollManager.startMeasuringScrollPosition(),this.autocapture=new Oee(this),this.autocapture.startIfEnabled(),this.surveys.loadIfEnabled(),this.heatmaps=new Nte(this),this.heatmaps.startIfEnabled(),this.webVitalsAutocapture=new Pte(this),this.exceptionObserver=new Yee(this),this.exceptionObserver.startIfEnabled(),this.deadClicksAutocapture=new T6(this,Kee),this.deadClicksAutocapture.startIfEnabled(),pl.DEBUG=pl.DEBUG||this.config.debug,pl.DEBUG&&Rt.info("Starting in debug mode",{this:this,config:r,thisC:We({},this.config),p:a,s:o}),this._sync_opt_out_with_persistence(),((s=r.bootstrap)===null||s===void 0?void 0:s.distinctID)!==void 0){var l,u,d=this.config.get_device_id(Fc()),h=(l=r.bootstrap)!==null&&l!==void 0&&l.isIdentifiedID?d:r.bootstrap.distinctID;this.persistence.set_property(dl,(u=r.bootstrap)!==null&&u!==void 0&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:r.bootstrap.distinctID,$device_id:h})}if(this._hasBootstrappedFeatureFlags()){var f,p,m=Object.keys(((f=r.bootstrap)===null||f===void 0?void 0:f.featureFlags)||{}).filter(w=>{var C,y;return!((C=r.bootstrap)===null||C===void 0||(y=C.featureFlags)===null||y===void 0||!y[w])}).reduce((w,C)=>{var y,k;return w[C]=((y=r.bootstrap)===null||y===void 0||(k=y.featureFlags)===null||k===void 0?void 0:k[C])||!1,w},{}),v=Object.keys(((p=r.bootstrap)===null||p===void 0?void 0:p.featureFlagPayloads)||{}).filter(w=>m[w]).reduce((w,C)=>{var y,k,_,E;return(y=r.bootstrap)!==null&&y!==void 0&&(k=y.featureFlagPayloads)!==null&&k!==void 0&&k[C]&&(w[C]=(_=r.bootstrap)===null||_===void 0||(E=_.featureFlagPayloads)===null||E===void 0?void 0:E[C]),w},{});this.featureFlags.receivedFeatureFlags({featureFlags:m,featureFlagPayloads:v})}if(this.config.__preview_experimental_cookieless_mode)this.register_once({distinct_id:gD,$device_id:null},"");else if(!this.get_distinct_id()){var b=this.config.get_device_id(Fc());this.register_once({distinct_id:b,$device_id:b},""),this.persistence.set_property(dl,"anonymous")}return Cs(Be,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),r.segment?kte(this,()=>this._loaded()):this._loaded(),Wa(this.config._onCapture)&&this.config._onCapture!==WS&&(Rt.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",w=>this.config._onCapture(w.event,w))),this}_onRemoteConfig(t){var n,s,r,i,a,o,l,u;if(!_t||!_t.body)return Rt.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this._onRemoteConfig(t)},500);this.compression=void 0,t.supportedCompression&&!this.config.disable_compression&&(this.compression=Zt(t.supportedCompression,ja.GZipJS)?ja.GZipJS:Zt(t.supportedCompression,ja.Base64)?ja.Base64:void 0),(n=t.analytics)!==null&&n!==void 0&&n.endpoint&&(this.analyticsDefaultEndpoint=t.analytics.endpoint),this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:"identified_only"}),(s=this.siteApps)===null||s===void 0||s.onRemoteConfig(t),(r=this.sessionRecording)===null||r===void 0||r.onRemoteConfig(t),(i=this.autocapture)===null||i===void 0||i.onRemoteConfig(t),(a=this.heatmaps)===null||a===void 0||a.onRemoteConfig(t),this.surveys.onRemoteConfig(t),(o=this.webVitalsAutocapture)===null||o===void 0||o.onRemoteConfig(t),(l=this.exceptionObserver)===null||l===void 0||l.onRemoteConfig(t),(u=this.deadClicksAutocapture)===null||u===void 0||u.onRemoteConfig(t)}_loaded(){try{this.config.loaded(this)}catch(t){Rt.critical("`loaded` function failed",t)}this._start_queue_if_opted_in(),this.config.capture_pageview&&setTimeout(()=>{this.consent.isOptedIn()&&this._captureInitialPageview()},1),new ine(this).load(),this.featureFlags.decide()}_start_queue_if_opted_in(){var t;this.has_opted_out_capturing()||this.config.request_batching&&((t=this._requestQueue)===null||t===void 0||t.enable())}_dom_loaded(){this.has_opted_out_capturing()||Bc(this.__request_queue,t=>this._send_retriable_request(t)),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var t,n;this.config.request_batching?(this._shouldCapturePageleave()&&this.capture("$pageleave"),(t=this._requestQueue)===null||t===void 0||t.unload(),(n=this._retryQueue)===null||n===void 0||n.unload()):this._shouldCapturePageleave()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(t){this.__loaded&&(fj?this.__request_queue.push(t):this.rateLimiter.isServerRateLimited(t.batchKey)||(t.transport=t.transport||this.config.api_transport,t.url=Cx(t.url,{ip:this.config.ip?1:0}),t.headers=We({},this.config.request_headers),t.compression=t.compression==="best-available"?this.compression:t.compression,t.fetchOptions=t.fetchOptions||this.config.fetch_options,(n=>{var s,r,i,a=We({},n);a.timeout=a.timeout||6e4,a.url=Cx(a.url,{_:new Date().getTime().toString(),ver:pl.LIB_VERSION,compression:a.compression});var o=(s=a.transport)!==null&&s!==void 0?s:"fetch",l=(r=(i=d6(Hg,u=>u.transport===o))===null||i===void 0?void 0:i.method)!==null&&r!==void 0?r:Hg[0].method;if(!l)throw new Error("No available transport method");l(a)})(We(We({},t),{},{callback:n=>{var s,r,i;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((r=(i=this.config).on_request_error)===null||r===void 0||r.call(i,n)),(s=t.callback)===null||s===void 0||s.call(t,n)}}))))}_send_retriable_request(t){this._retryQueue?this._retryQueue.retriableRequest(t):this._send_request(t)}_execute_array(t){var n,s=[],r=[],i=[];Bc(t,o=>{o&&(n=o[0],cs(n)?i.push(o):Wa(o)?o.call(this):cs(o)&&n==="alias"?s.push(o):cs(o)&&n.indexOf("capture")!==-1&&Wa(this[n])?i.push(o):r.push(o))});var a=function(o,l){Bc(o,function(u){if(cs(u[0])){var d=l;Nn(u,function(h){d=d[h[0]].apply(d,h.slice(1))})}else this[u[0]].apply(this,u.slice(1))},l)};a(s,this),a(r,this),a(i,this)}_hasBootstrappedFeatureFlags(){var t,n;return((t=this.config.bootstrap)===null||t===void 0?void 0:t.featureFlags)&&Object.keys((n=this.config.bootstrap)===null||n===void 0?void 0:n.featureFlags).length>0||!1}push(t){this._execute_array([t])}capture(t,n,s){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue){if(!this.consent.isOptedOut())if(!wt(t)&&Os(t)){if(this.config.opt_out_useragent_filter||!this._is_bot()){var i=s!=null&&s.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){n!=null&&n.$current_url&&!Os(n?.$current_url)&&(Rt.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var a=new Date,o=s?.timestamp||a,l=Fc(),u={uuid:l,event:t,properties:this._calculate_event_properties(t,n||{},o,l)};i&&(u.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),s?.$set&&(u.$set=s?.$set);var d=this._calculate_set_once_properties(s?.$set_once);d&&(u.$set_once=d),(u=wee(u,s!=null&&s._noTruncate?null:this.config.properties_string_max_length)).timestamp=o,wt(s?.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=a);var h=We(We({},u.properties.$set),u.$set);if(Hh(h)||this.setPersonPropertiesForFlags(h),!En(this.config.before_send)){var f=this._runBeforeSend(u);if(!f)return;u=f}this._internalEventEmitter.emit("eventCaptured",u);var p={method:"POST",url:(r=s?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:s?._batchKey};return!this.config.request_batching||s&&(s==null||!s._batchKey)||s!=null&&s.send_instantly?this._send_retriable_request(p):this._requestQueue.enqueue(p),u}Rt.critical("This capture call is ignored due to client rate limiting.")}}else Rt.error("No event name provided to posthog.capture")}else Rt.uninitializedWarning("posthog.capture")}_addCaptureHook(t){return this.on("eventCaptured",n=>t(n.event,n))}_calculate_event_properties(t,n,s,r){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return n;var i=this.persistence.remove_event_timer(t),a=We({},n);if(a.token=this.config.token,this.config.__preview_experimental_cookieless_mode&&(a.$cookieless_mode=!0),t==="$snapshot"){var o=We(We({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=o.distinct_id,(!Os(a.distinct_id)&&!qr(a.distinct_id)||fS(a.distinct_id))&&Rt.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var l,u=Qn.properties({maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties});if(this.sessionManager){var{sessionId:d,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId();a.$session_id=d,a.$window_id=h}this.sessionPropsManager&&xs(a,this.sessionPropsManager.getSessionProps());try{var f,p;this.sessionRecording&&xs(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(f=this._retryQueue)===null||f===void 0||(p=f.queue)===null||p===void 0?void 0:p.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}if(this.requestRouter.region===Ku.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),l=t==="$pageview"?this.pageViewManager.doPageView(s,r):t==="$pageleave"?this.pageViewManager.doPageLeave(s):this.pageViewManager.doEvent(),a=xs(a,l),t==="$pageview"&&_t&&(a.title=_t.title),!wt(i)){var m=s.getTime()-i;a.$duration=parseFloat((m/1e3).toFixed(3))}Ns&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=xs({},u,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),cs(this.config.property_denylist)?Nn(this.config.property_denylist,function(w){delete a[w]}):Rt.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var v=this.config.sanitize_properties;v&&(Rt.error("sanitize_properties is deprecated. Use before_send instead"),a=v(a,t));var b=this._hasPersonProcessing();return a.$process_person_profile=b,b&&this._requirePersonProcessing("_calculate_event_properties"),a}_calculate_set_once_properties(t){var n;if(!this.persistence||!this._hasPersonProcessing()||this._personProcessingSetOncePropertiesSent)return t;var s=this.persistence.get_initial_props(),r=(n=this.sessionPropsManager)===null||n===void 0?void 0:n.getSetOnceProps(),i=xs({},s,r||{},t||{}),a=this.config.sanitize_properties;return a&&(Rt.error("sanitize_properties is deprecated. Use before_send instead"),i=a(i,"$set_once")),this._personProcessingSetOncePropertiesSent=!0,Hh(i)?void 0:i}register(t,n){var s;(s=this.persistence)===null||s===void 0||s.register(t,n)}register_once(t,n,s){var r;(r=this.persistence)===null||r===void 0||r.register_once(t,n,s)}register_for_session(t){var n;(n=this.sessionPersistence)===null||n===void 0||n.register(t)}unregister(t){var n;(n=this.persistence)===null||n===void 0||n.unregister(t)}unregister_for_session(t){var n;(n=this.sessionPersistence)===null||n===void 0||n.unregister(t)}_register_single(t,n){this.register({[t]:n})}getFeatureFlag(t,n){return this.featureFlags.getFeatureFlag(t,n)}getFeatureFlagPayload(t){var n=this.featureFlags.getFeatureFlagPayload(t);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(t,n){return this.featureFlags.isFeatureEnabled(t,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(t,n){this.featureFlags.updateEarlyAccessFeatureEnrollment(t,n)}getEarlyAccessFeatures(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1],s=arguments.length>2?arguments[2]:void 0;return this.featureFlags.getEarlyAccessFeatures(t,n,s)}on(t,n){return this._internalEventEmitter.on(t,n)}onFeatureFlags(t){return this.featureFlags.onFeatureFlags(t)}onSurveysLoaded(t){return this.surveys.onSurveysLoaded(t)}onSessionId(t){var n,s;return(n=(s=this.sessionManager)===null||s===void 0?void 0:s.onSessionId(t))!==null&&n!==void 0?n:()=>{}}getSurveys(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.surveys.getSurveys(t,n)}getActiveMatchingSurveys(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.surveys.getActiveMatchingSurveys(t,n)}renderSurvey(t,n){this.surveys.renderSurvey(t,n)}canRenderSurvey(t){return this.surveys.canRenderSurvey(t)}identify(t,n,s){if(!this.__loaded||!this.persistence)return Rt.uninitializedWarning("posthog.identify");if(qr(t)&&(t=t.toString(),Rt.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),t){if(["distinct_id","distinctid"].includes(t.toLowerCase()))Rt.critical('The string "'.concat(t,'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'));else if(this._requirePersonProcessing("posthog.identify")){var r=this.get_distinct_id();if(this.register({$user_id:t}),!this.get_property("$device_id")){var i=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}t!==r&&t!==this.get_property(vg)&&(this.unregister(vg),this.register({distinct_id:t}));var a=(this.persistence.get_property(dl)||"anonymous")==="anonymous";t!==r&&a?(this.persistence.set_property(dl,"identified"),this.setPersonPropertiesForFlags(We(We({},s||{}),n||{}),!1),this.capture("$identify",{distinct_id:t,$anon_distinct_id:r},{$set:n||{},$set_once:s||{}}),this._cachedPersonProperties=oP(t,n,s),this.featureFlags.setAnonymousDistinctId(r)):(n||s)&&this.setPersonProperties(n,s),t!==r&&(this.reloadFeatureFlags(),this.unregister(hx))}}else Rt.error("Unique user id has not been set in posthog.identify")}setPersonProperties(t,n){if((t||n)&&this._requirePersonProcessing("posthog.setPersonProperties")){var s=oP(this.get_distinct_id(),t,n);this._cachedPersonProperties!==s?(this.setPersonPropertiesForFlags(We(We({},n||{}),t||{})),this.capture("$set",{$set:t||{},$set_once:n||{}}),this._cachedPersonProperties=s):Rt.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(t,n,s){if(t&&n){if(this._requirePersonProcessing("posthog.group")){var r=this.getGroups();r[t]!==n&&this.resetGroupPropertiesForFlags(t),this.register({$groups:We(We({},r),{},{[t]:n})}),s&&(this.capture("$groupidentify",{$group_type:t,$group_key:n,$group_set:s}),this.setGroupPropertiesForFlags({[t]:s})),r[t]===n||s||this.reloadFeatureFlags()}}else Rt.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t){var n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];this.featureFlags.setPersonPropertiesForFlags(t,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(t){var n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(t,n)}resetGroupPropertiesForFlags(t){this.featureFlags.resetGroupPropertiesForFlags(t)}reset(t){var n,s,r,i;if(Rt.info("reset"),!this.__loaded)return Rt.uninitializedWarning("posthog.reset");var a=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)===null||n===void 0||n.clear(),(s=this.sessionPersistence)===null||s===void 0||s.clear(),this.surveys.reset(),(r=this.persistence)===null||r===void 0||r.set_property(dl,"anonymous"),(i=this.sessionManager)===null||i===void 0||i.resetSessionId(),this._cachedPersonProperties=null,this.config.__preview_experimental_cookieless_mode)this.register_once({distinct_id:gD,$device_id:null},"");else{var o=this.config.get_device_id(Fc());this.register_once({distinct_id:o,$device_id:t?o:a},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var t,n;return(t=(n=this.sessionManager)===null||n===void 0?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&t!==void 0?t:""}get_session_replay_url(t){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:s}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor("ui","/project/".concat(this.config.token,"/replay/").concat(n));if(t!=null&&t.withTimestamp&&s){var i,a=(i=t.timestampLookBack)!==null&&i!==void 0?i:10;if(!s)return r;var o=Math.max(Math.floor((new Date().getTime()-s)/1e3)-a,0);r+="?t=".concat(o)}return r}alias(t,n){return t===this.get_property(h6)?(Rt.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(wt(n)&&(n=this.get_distinct_id()),t!==n?(this._register_single(vg,t),this.capture("$create_alias",{alias:t,distinct_id:n})):(Rt.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){var n,s,r,i,a=We({},this.config);us(t)&&(xs(this.config,uP(t)),(n=this.persistence)===null||n===void 0||n.update_config(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Uy(We(We({},this.config),{},{persistence:"sessionStorage"})),Us.is_supported()&&Us.get("ph_debug")==="true"&&(this.config.debug=!0),this.config.debug&&(pl.DEBUG=!0,Rt.info("set_config",JSON.stringify({config:t,oldConfig:a,newConfig:We({},this.config)},null,2))),(s=this.sessionRecording)===null||s===void 0||s.startIfEnabledOrStop(),(r=this.autocapture)===null||r===void 0||r.startIfEnabled(),(i=this.heatmaps)===null||i===void 0||i.startIfEnabled(),this.surveys.loadIfEnabled(),this._sync_opt_out_with_persistence())}startSessionRecording(t){var n=t===!0,s={sampling:n||!(t==null||!t.sampling),linked_flag:n||!(t==null||!t.linked_flag),url_trigger:n||!(t==null||!t.url_trigger),event_trigger:n||!(t==null||!t.event_trigger)};if(Object.values(s).some(Boolean)){var r,i,a,o,l;(r=this.sessionManager)===null||r===void 0||r.checkAndGetSessionAndWindowId(),s.sampling&&((i=this.sessionRecording)===null||i===void 0||i.overrideSampling()),s.linked_flag&&((a=this.sessionRecording)===null||a===void 0||a.overrideLinkedFlag()),s.url_trigger&&((o=this.sessionRecording)===null||o===void 0||o.overrideTrigger("url")),s.event_trigger&&((l=this.sessionRecording)===null||l===void 0||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var t;return!((t=this.sessionRecording)===null||t===void 0||!t.started)}captureException(t,n){var s=new Error("PostHog syntheticException");this.exceptions.sendExceptionEvent(We(We({},ote((r=>r instanceof Error)(t)?{error:t,event:t.message}:{event:t},{syntheticException:s})),n))}loadToolbar(t){return this.toolbar.loadToolbar(t)}get_property(t){var n;return(n=this.persistence)===null||n===void 0?void 0:n.props[t]}getSessionProperty(t){var n;return(n=this.sessionPersistence)===null||n===void 0?void 0:n.props[t]}toString(){var t,n=(t=this.config.name)!==null&&t!==void 0?t:Ph;return n!==Ph&&(n=Ph+"."+n),n}_isIdentified(){var t,n;return((t=this.persistence)===null||t===void 0?void 0:t.get_property(dl))==="identified"||((n=this.sessionPersistence)===null||n===void 0?void 0:n.get_property(dl))==="identified"}_hasPersonProcessing(){var t,n,s,r;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Hh(this.getGroups())&&((t=this.persistence)===null||t===void 0||(n=t.props)===null||n===void 0||!n[vg])&&((s=this.persistence)===null||s===void 0||(r=s.props)===null||r===void 0||!r[fx]))}_shouldCapturePageleave(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing("posthog.createPersonProfile")&&this.setPersonProperties({},{})}_requirePersonProcessing(t){return this.config.person_profiles==="never"?(Rt.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._register_single(fx,!0),!0)}_sync_opt_out_with_persistence(){var t,n,s,r,i=this.consent.isOptedOut(),a=this.config.opt_out_persistence_by_default,o=this.config.disable_persistence||i&&!!a;((t=this.persistence)===null||t===void 0?void 0:t.disabled)!==o&&((s=this.persistence)===null||s===void 0||s.set_disabled(o)),((n=this.sessionPersistence)===null||n===void 0?void 0:n.disabled)!==o&&((r=this.sessionPersistence)===null||r===void 0||r.set_disabled(o))}opt_in_capturing(t){var n;this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),(wt(t?.captureEventName)||t!=null&&t.captureEventName)&&this.capture((n=t?.captureEventName)!==null&&n!==void 0?n:"$opt_in",t?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this._captureInitialPageview()}opt_out_capturing(){this.consent.optInOut(!1),this._sync_opt_out_with_persistence()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return Ii?hj(Ii,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){_t&&!this._initialPageviewCaptured&&(this._initialPageviewCaptured=!0,this.capture("$pageview",{title:_t.title},{send_instantly:!0}))}debug(t){t===!1?(Be?.console.log("You've disabled debug mode."),localStorage&&localStorage.removeItem("ph_debug"),this.set_config({debug:!1})):(Be?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),localStorage&&localStorage.setItem("ph_debug","true"),this.set_config({debug:!0}))}_runBeforeSend(t){if(En(this.config.before_send))return t;var n=cs(this.config.before_send)?this.config.before_send:[this.config.before_send],s=t;for(var r of n){if(s=r(s),En(s)){var i="Event '".concat(t.event,"' was rejected in beforeSend function");return vee(t.event)?Rt.warn("".concat(i,". This can cause unexpected behavior.")):Rt.info(i),null}s.properties&&!Hh(s.properties)||Rt.warn("Event '".concat(t.event,"' has no properties after beforeSend function, this is likely an error."))}return s}getPageViewId(){var t;return(t=this.pageViewManager._currentPageview)===null||t===void 0?void 0:t.pageViewId}captureTraceFeedback(t,n){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:n})}captureTraceMetric(t,n,s){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:n,$ai_metric_value:String(s)})}}(function(e,t){for(var n=0;n<t.length;n++)e.prototype[t[n]]=xee(e.prototype[t[n]])})(fC,["identify"]);var dP,Hu=(dP=Ug[Ph]=new fC,function(){function e(){e.done||(e.done=!0,fj=!1,Nn(Ug,function(t){t._dom_loaded()}))}_t!=null&&_t.addEventListener?_t.readyState==="complete"?e():Cs(_t,"DOMContentLoaded",e,{capture:!1}):Be&&Rt.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),dP),RT=g.createContext({client:Hu});function pj(e,t,n){if(n===void 0&&(n=new WeakMap),e===t)return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(n.has(e)&&n.get(e)===t)return!0;n.set(e,t);var s=Object.keys(e),r=Object.keys(t);if(s.length!==r.length)return!1;for(var i=0,a=s;i<a.length;i++){var o=a[i];if(!r.includes(o)||!pj(e[o],t[o],n))return!1}return!0}function yne(e){var t=e.children,n=e.client,s=e.apiKey,r=e.options,i=g.useRef(null),a=g.useMemo(function(){return n?(s&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),r&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),n):(s||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),Hu)},[n,s,JSON.stringify(r)]);return g.useEffect(function(){if(!n){var o=i.current;o?(s!==o.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),r&&!pj(r,o.options)&&Hu.set_config(r),i.current={apiKey:s,options:r??{}}):(Hu.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),Hu.init(s,r),i.current={apiKey:s,options:r??{}})}},[n,s,JSON.stringify(r)]),$e.createElement(RT.Provider,{value:{client:a}},t)}var _ne=function(){var e=g.useContext(RT).client;return e};function Wy(e){var t=_ne(),n=g.useState(function(){return t.isFeatureEnabled(e)}),s=n[0],r=n[1];return g.useEffect(function(){return t.onFeatureFlags(function(){r(t.isFeatureEnabled(e))})},[t,e]),s}var $S=function(e,t){return $S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(n[r]=s[r])},$S(e,t)};function Sne(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");$S(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var $y=function(e){return typeof e=="function"},Ene={componentStack:null,error:null},kne={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};(function(e){Sne(t,e);function t(n){var s=e.call(this,n)||this;return s.state=Ene,s}return t.prototype.componentDidCatch=function(n,s){var r=s.componentStack,i=this.props.additionalProperties;this.setState({error:n,componentStack:r});var a;$y(i)?a=i(n):typeof i=="object"&&(a=i);var o=this.context.client;o.captureException(n,a)},t.prototype.render=function(){var n=this.props,s=n.children,r=n.fallback,i=this.state;if(i.componentStack==null)return $y(s)?s():s;var a=$y(r)?$e.createElement(r,{error:i.error,componentStack:i.componentStack}):r;return $e.isValidElement(a)?a:(console.warn(kne.INVALID_FALLBACK),$e.createElement($e.Fragment,null))},t.contextType=RT,t})($e.Component);/**
|
|
@@ -671,7 +671,7 @@ ${QV(r)}`)}const JV=rY;function CL(e){return e.artifact&&iY(e.path)?e.artifact:n
|
|
|
671
671
|
`).find(r=>r.trim().length>0)??"").trim(),s=48;return n.length>s?`${n.slice(0,s).trimEnd()}…`:n},ML=e=>`Discard draft “${e.startsWith(Rk)?e.slice(Rk.length):e}”`;function wWe(e,t){const n=e.indexOf(t);return Math.max(n,0)}function CWe(e,t,n=bWe){const s=[];for(const[r,i]of Object.entries(e)){const a=i.sessionId??(r.startsWith("send:")?r.slice(5):void 0);if(a&&n.has(a)||i.target)continue;const o=t[r]?.currentInput??"",l=o.trim().length>0?o:i.submittedText??i.undelivered?.text??"";l.trim().length!==0&&s.push({key:r,label:`${Rk}${xWe(l)}`,text:l,pending:i.pending===!0})}return s.reverse()}const yWe="click the chat to try again",Ng="Click the chat to try again.",hW={pending:"marking read",offscreen:"scroll to the result to mark this chat read",unsettled:yWe,remote:"lives on another device, and it clears when that device updates"},q2={pending:"Marking this chat read.",offscreen:"Scroll to the result to mark this chat read.",unsettled:`Not marked read. ${Ng}`,remote:"The unread mark lives on another device. It clears when that device updates."},_We=e=>{const t=e?.trim();return t?{clause:`lives on ${t}, and it clears when that device updates`,description:`The unread mark lives on ${t}. It clears when that device updates.`}:{clause:hW.remote,description:q2.remote}},SWe=(e,t,n)=>!e||e.sessionId!==t?null:e.kind==="remote"?_We(n):{clause:hW[e.kind],description:q2[e.kind]},EWe=e=>e instanceof Hi?e.code===oY?"busy":lY(e.code)?"refused":aB(e)?"remote":"unreachable":"unreported",kWe="The app could not reach the backend.",TWe={busy:()=>`The read state is busy, so the unread mark was not cleared. ${Ng}`,refused:()=>`The read state could not be written, so the unread mark was not cleared. ${Ng}`,remote:()=>q2.remote,unreachable:e=>`${bi(e,kWe)} The unread mark was not cleared. ${Ng}`,unreported:()=>`The unread mark was not cleared. ${Ng}`},RWe=e=>TWe[EWe(e.reason)](e.reason);function AWe({state:e,cause:t=null,failed:n,answered:s,wasReady:r,rows:i,storeFailed:a,coveredByCompatibilityBanner:o}){const l=e==="enabled",u=s&&!n&&!l,h=(r||i>0)&&(n||u),f=h&&i>0;return{withdrawn:u,stale:h,showList:l||h,lastKnownRows:f,notice:u&&!a&&!o?B4(e,t)??`Update the backend to use canonical chats. Existing histories are unchanged.${f?" Showing the last chats and teams that loaded.":""}`:null}}const FWe=1,DWe="They may be archived. Search with Include archived.";function PWe(e){if(!e.pageable){const i=e.held===0;return{state:i?"empty":"rows",sentence:i?"No chats yet":null,retry:!1,more:!1,addCount:0,forbidden:!1}}const t=e.scope,n=e.total!==null&&e.total>0&&e.held===0;if(t===void 0)return{state:"loading",sentence:"Loading chats…",retry:!1,more:!1,addCount:0,forbidden:n};if(t.ids.length===0)return t.error!==null?{state:"error",sentence:t.error,retry:!0,more:!1,addCount:0,forbidden:!1}:t.loading?{state:"loading",sentence:"Loading chats…",retry:!1,more:!1,addCount:0,forbidden:n}:n?{state:"settled",sentence:DWe,retry:!1,more:!1,addCount:0,forbidden:!0}:{state:"empty",sentence:"No chats yet",retry:!1,more:!1,addCount:0,forbidden:!1};const s=e.total===null?my:e.total-e.held,r=s<=0?my:Math.min(my,s);return{state:"rows",sentence:t.error,retry:t.error!==null,more:t.nextCursor!==null,addCount:t.nextCursor===null?0:r,forbidden:!1}}function IWe(e){return!e.pageable||e.searching||e.total===null?e.held:e.total}function E1(e,t,n){if(e===null)return null;for(const s of e.scopes)if(s.kind===t&&s.name===n)return s.total;return null}function OL(e){return`${e} chats in this group`}function NWe(e){if(!e.pageable||e.total===null||e.shown>e.total)return null;if(e.searching===!0){const t=e.shown===1?"match":"matches",n=e.clipped===!0?"+":"";return`Showing ${e.shown}${n} ${t} of ${e.total} chats`}return`Showing ${e.shown} of ${e.total} chats`}function MWe(e){return e<=0?null:e===1?"1 more chat arrived.":`${e} more chats arrived.`}function OWe(e){return e.pageable?e.loading?{kind:"loading"}:e.error!==null?{kind:"error",sentence:e.error,retry:!0}:e.nextCursor===null?{kind:"none"}:{kind:"none"}:{kind:"none"}}function LWe(e){return!e.pageable||e.error!==null||e.loading||e.nextCursor===null?!1:e.scrollHeight-e.scrollTop-e.clientHeight<=e.clientHeight*FWe}const BWe=({unreachable:e})=>c.jsxs("svg",{"aria-hidden":"true","data-remote-mark":!0,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:"size-3.5 shrink-0 text-ink-dim",children:[c.jsx("path",{d:"M7 7h10v10"}),c.jsx("path",{d:"M7 17 17 7"}),e&&c.jsx("path",{"data-remote-mark-stroke":!0,d:"M9 9 15 15"})]}),LL="data-session-hover-intent";function jWe(){const e=g.useRef(null),t=g.useRef(null),n=g.useRef(null),s=g.useCallback(()=>{t.current!==null&&(window.clearTimeout(t.current),t.current=null),e.current?.removeAttribute(LL)},[]),r=g.useCallback(i=>{if(n.current?.(),n.current=null,!i)return;const a=i.closest("[data-session-row]")??i.closest("button[data-chat-row]");if(!a)return;e.current=a;const o=()=>{s(),t.current=window.setTimeout(()=>{t.current=null,a.setAttribute(LL,"")},cY)},l=()=>s();a.addEventListener("pointerenter",o),a.addEventListener("pointerleave",l),n.current=()=>{a.removeEventListener("pointerenter",o),a.removeEventListener("pointerleave",l),e.current=null,s()}},[s]);return g.useEffect(()=>()=>n.current?.(),[]),c.jsx("span",{ref:r,hidden:!0})}const HWe=32,UWe=8e3,BL=12,GWe="(prefers-reduced-motion: reduce)";function VWe({text:e}){const t=g.useRef(null),n=g.useRef(null),s=g.useRef(null),r=g.useRef(null),i=g.useRef(null),[a,o]=g.useState(!1),l=oB(GWe),u=g.useRef(l),d=g.useCallback(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null)},[]),h=g.useCallback(()=>{d();const b=n.current;b&&(b.style.transform="");const w=t.current;w&&(w.style.removeProperty("mask-image"),w.style.removeProperty("-webkit-mask-image")),o(!1)},[d]),f=g.useCallback((b,w,C)=>{const y=Math.max(HWe,C/(UWe/1e3)),k=performance.now(),_=E=>{const R=Math.min(C,(E-k)/1e3*y);w.style.transform=`translateX(${-R}px)`;const F=`linear-gradient(to right, transparent 0, black ${Math.min(BL,R)}px, black calc(100% - ${BL}px), transparent 100%)`;b.style.setProperty("mask-image",F),b.style.setProperty("-webkit-mask-image",F),i.current=R<C?window.requestAnimationFrame(_):null};i.current=window.requestAnimationFrame(_)},[]),p=g.useCallback(()=>{const b=t.current;b&&(b.scrollWidth-b.clientWidth<=.5||(o(!0),i.current=window.requestAnimationFrame(()=>{i.current=null;const w=n.current;if(!w)return;const C=w.getBoundingClientRect().width-b.clientWidth;if(C<=.5){o(!1);return}f(b,w,C)})))},[f]),m=g.useCallback(()=>{h(),!u.current&&(r.current=window.setTimeout(p,DJ))},[h,p]);g.useEffect(()=>{u.current=l,l&&h()},[l,h]),g.useEffect(()=>h,[h]);const v=g.useCallback(b=>{if(t.current=b,s.current?.(),s.current=null,!b)return;const w=b.closest("[data-session-row]")??b.closest("button[data-chat-row]");if(!w)return;const C=()=>m(),y=()=>h();w.addEventListener("pointerenter",C),w.addEventListener("pointerleave",y),s.current=()=>{w.removeEventListener("pointerenter",C),w.removeEventListener("pointerleave",y),h()}},[m,h]);return c.jsx("span",{ref:v,"data-session-title":!0,className:T("min-w-0 flex-1",a?"overflow-hidden whitespace-nowrap":"truncate"),children:a?c.jsx("span",{ref:n,"data-session-title-text":!0,className:"inline-block w-max whitespace-nowrap",children:e}):e})}const WWe={pinned:"ui.chat.sidebar_view.section.pinned",running:"ui.chat.sidebar_view.section.running",today:"ui.chat.sidebar_view.section.today",week:"ui.chat.sidebar_view.section.week",older:"ui.chat.sidebar_view.section.older",agents:"ui.chat.sidebar_view.section.agents",teams:"ui.chat.sidebar_view.section.teams"},k1=e=>x(WWe[e]),gb=(e,t=!1)=>c.jsx("div",{className:T("px-1 pt-3 pb-1 font-medium text-ink-dim text-meta uppercase tracking-wide",!t&&"mb-2 border-hairline border-b"),children:e}),T1=(e,t,n,s,r,i={"data-sidebar-view-choice":e})=>c.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":s,...i,onClick:r,className:T("flex h-7 w-full items-center gap-2 rounded-md px-1 text-left text-body-sm","transition-colors duration-fast ease-out-quart",s?"text-ink":"text-ink-muted hover:bg-row-hover hover:text-ink"),children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:t}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:n}),c.jsx(Bs,{"aria-hidden":"true",className:T("size-3.5 shrink-0",!s&&"opacity-0")})]},e);function $We({view:e,counts:t,onView:n}){Et();const s=t?o=>(t[o]??0)>0:void 0,r=[{key:"section",label:x("ui.chat.sidebar_view.time_section"),icon:c.jsx(wj,{"aria-hidden":"true",className:"size-3.5"})},{key:"agent",label:x("ui.chat.sidebar_view.agent_team"),icon:c.jsx(Uo,{"aria-hidden":"true",className:"size-3.5"})},{key:"flat",label:x("ui.chat.sidebar_view.one_list"),icon:c.jsx(qS,{"aria-hidden":"true",className:"size-3.5"})}],i=[{key:"active",label:x("ui.chat.sidebar_view.last_active"),icon:c.jsx(AT,{"aria-hidden":"true",className:"size-3.5"})},{key:"created",label:x("ui.chat.sidebar_view.created"),icon:c.jsx(Wne,{"aria-hidden":"true",className:"size-3.5"})}],a=[{key:"active-first",label:x("ui.chat.sidebar_view.active_first"),icon:c.jsx(gj,{"aria-hidden":"true",className:"size-3.5"})},{key:"recent",label:x("ui.chat.sidebar_view.most_recent"),icon:c.jsx(pi,{"aria-hidden":"true",className:"size-3.5"})}];return c.jsxs("div",{"data-sidebar-view-menu":!0,className:"w-full",children:[gb(x("ui.chat.sidebar_view.group_by")),c.jsxs("fieldset",{className:"min-w-0 space-y-0.5 border-0 p-0",children:[c.jsx("legend",{className:"sr-only",children:x("ui.chat.sidebar_view.group_by")}),r.map(o=>T1(o.key,o.icon,o.label,e.groupBy===o.key,()=>n({...e,groupBy:o.key})))]}),gb(x("ui.chat.sidebar_view.time_basis")),c.jsxs("fieldset",{className:"min-w-0 space-y-0.5 border-0 p-0",children:[c.jsx("legend",{className:"sr-only",children:x("ui.chat.sidebar_view.time_basis")}),i.map(o=>T1(o.key,o.icon,o.label,e.basis===o.key,()=>n({...e,basis:o.key}),{"data-sidebar-view-basis":o.key}))]}),c.jsx("p",{className:"px-1 pt-0.5 pb-1 text-meta text-ink-dim",children:x("ui.chat.sidebar_view.clock_hint")}),gb(x("ui.chat.sidebar_view.order_by")),c.jsxs("fieldset",{className:"min-w-0 space-y-0.5 border-0 p-0",children:[c.jsx("legend",{className:"sr-only",children:x("ui.chat.sidebar_view.order_by")}),a.map(o=>T1(o.key,o.icon,o.label,e.orderBy===o.key,()=>n({...e,orderBy:o.key})))]}),gb(x("ui.chat.sidebar_view.sections")),c.jsx("div",{className:"space-y-0.5",children:e.order.map(o=>{const l=mg(e,o);return c.jsxs("div",{className:"flex h-7 items-center gap-1 rounded-md pl-1 text-body-sm",children:[c.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":l,"data-sidebar-view-section":o,onClick:()=>n(aZ(e,o)),className:T("flex h-7 min-w-0 flex-1 items-center gap-2 text-left",l?"text-ink":"text-ink-muted"),children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:JB(o)?c.jsx(Og,{"aria-hidden":"true",className:"size-3.5"}):c.jsx(Nf,{"aria-hidden":"true",className:"size-3.5"})}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:k1(o)}),t?.[o]?c.jsx("span",{className:"shrink-0 font-mono text-ink-dim text-mono-sm",children:t[o]}):null,c.jsx(Bs,{"aria-hidden":"true",className:T("size-3.5 shrink-0",!l&&"opacity-0")})]}),iZ(o)&&c.jsxs(c.Fragment,{children:[c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-move":`${o}:up`,"aria-label":x("ui.chat.sidebar_view.move_up",{section:k1(o)}),disabled:!MF(e,o,-1,s),className:"size-6",onClick:()=>n(NF(e,o,-1)),children:c.jsx(N0,{"aria-hidden":"true",className:"size-3"})}),c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-move":`${o}:down`,"aria-label":x("ui.chat.sidebar_view.move_down",{section:k1(o)}),disabled:!MF(e,o,1,s),className:"size-6",onClick:()=>n(NF(e,o,1)),children:c.jsx(pi,{"aria-hidden":"true",className:"size-3"})})]})]},o)})}),e.hidden.length>0&&c.jsx("p",{className:"mt-2 px-1 text-meta text-ink-dim",children:x("ui.chat.sidebar_view.hidden",{count:e.hidden.length})})]})}function fW(e){switch(e?.split("/")[0]){case"unsupported-precondition":return x("ui.hub.status.unsupported");case"baseline-unknown":return x("ui.hub.status.baseline_unknown");case"mixed-lineage":case"origin-conflict":return x("ui.hub.status.mixed_lineage");case"no-credential":return x("ui.hub.status.no_credential");case"access-lost":case"unauthorized":case"forbidden":return x("ui.hub.status.access_lost");case"provider-error":return x("ui.hub.status.provider_error");case"model-unavailable":return x("ui.hub.status.model_unavailable");case"merge-refused":case"concurrent-edit":case"local-concurrent-edit":case"remote-revision-changed":return x("ui.hub.status.conflict");case"prompt-too-long":case"skill-too-large":return x("ui.hub.status.too_large");case"skill-validation":return x("ui.hub.status.skill_validation");case"unsafe-publication":return x("ui.hub.status.unsafe_publication");case"hub-error":case"transport":return x("ui.hub.status.transport_error");default:return x("ui.hub.status.other_error")}}function het(e){switch(e.state){case"idle":return x(e.last_checked_at?"ui.hub.status.idle":"ui.hub.status.not_checked");case"checking":return x("ui.hub.status.checking");case"available":return x("ui.hub.status.available");case"merging":return x("ui.hub.status.merging");case"applying":return x("ui.hub.status.applying");case"pushing":return x("ui.hub.status.pushing");case"retry-wait":return x("ui.hub.status.retry_wait");case"needs-review":return x("ui.hub.status.needs_review");case"failed":return x("ui.hub.status.failed");case"missing":return x("ui.hub.status.missing");default:return x("ui.hub.status.other_error")}}const pW=new Set(["needs-review","missing","blocked"]),gW=new Set(["checking","merging","applying","pushing"]),zWe=new Set(["idle","available","retry-wait","failed","applied","published",...pW,...gW]);function mW(e){const t=["pull","push"];for(const n of t){const s=e[n];if(!zWe.has(s.state)||pW.has(s.state)||s.state==="failed"&&!s.retryable||n==="push"&&!e.policy.autoPush&&(s.state==="failed"||s.state==="retry-wait")||n==="push"&&e.policy.autoPush&&!s.effective&&s.reason)return{kind:"review",direction:n,action:"detail"}}for(const n of t){const s=e[n];if((s.state==="failed"||s.state==="retry-wait")&&s.retryable)return{kind:"failed",direction:n,action:"retry"}}if(e.pull.state==="available")return e.pull.canApply?{kind:"available",direction:"pull",action:"apply"}:{kind:"review",direction:"pull",action:"detail"};for(const n of t)if(gW.has(e[n].state))return{kind:"busy",direction:n,action:"policy"};for(const n of t)if(e[n].state==="applied"||e[n].state==="published")return{kind:"applied",direction:n,action:"policy"};return{kind:"healthy",direction:"pull",action:"policy"}}function K2(e){const t=e.visibility==="public"&&e.eligibility.reason==="unsafe-publication",n=!e.eligibility.can_auto_push&&!t||!e.remote_revision||e.visibility==="org"&&!e.tenant_name;return{unavailable:n,requiresConsent:t&&!n}}function qWe(e){const{unavailable:t}=K2(e);return e.policy.auto_push?!e.eligibility.can_auto_push||t?"paused":"none":t?"unavailable":"none"}function Y2(e){return e.visibility==="public"?x("ui.hub.links.source_public"):e.tenant_name?x("ui.hub.links.source_private",{organization:e.tenant_name}):x("ui.hub.links.source_unavailable")}function vW({link:e,onConsentChange:t}){Et();const n=tVe(),s=g.useId(),r=g.useRef(null),i=Y2(e),[a,o]=g.useState("subscribe"),[l,u]=g.useState(null);g.useEffect(()=>{l&&(l.linkId!==e.link_id||l.revision!==e.policy.revision||l.source!==i)&&(t?.(!1),u(null))},[e.link_id,e.policy.revision,i,l,t]);const d=()=>{t?.(!1),u(null)},h=(b,w)=>{n.isPending||(o(w),n.mutate({link:e,patch:b},{onSuccess:d}))},{unavailable:f}=K2(e),p=qWe(e),m=e.eligibility.reason?fW(e.eligibility.reason):x("ui.hub.subscriptions.unsupported"),v=x(a==="subscribe"?"ui.hub.subscriptions.subscribe":"ui.hub.subscriptions.auto_push");return c.jsxs("div",{className:"flex min-w-0 flex-col gap-3","data-hub-link-policy":e.link_id,children:[n.upgradeMessage&&c.jsx("output",{className:"block text-meta text-warning","data-hub-core-upgrade":!0,children:n.upgradeMessage}),c.jsxs("div",{className:"flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("label",{htmlFor:`${s}-subscribe`,className:"text-body-sm text-ink",children:x("ui.hub.subscriptions.subscribe")}),c.jsx("p",{className:"text-meta text-ink-muted",children:x(n.canWrite?"ui.hub.subscriptions.subscribe_description":"ui.hub.subscriptions.subscribe_description_blocked",{source:i})})]}),c.jsx(RF,{id:`${s}-subscribe`,checked:e.policy.subscribe,disabled:n.isPending||!n.canWrite,"aria-label":`${x("ui.hub.subscriptions.subscribe")}: ${i}`,onCheckedChange:b=>h({subscribe:b},"subscribe")})]}),!e.policy.subscribe&&n.canWrite&&c.jsx("p",{className:"text-meta text-ink-muted",children:x("ui.hub.subscriptions.manual_available")}),c.jsxs("div",{className:"flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("label",{htmlFor:`${s}-push`,className:"text-body-sm text-ink",children:x("ui.hub.subscriptions.auto_push")}),c.jsx("p",{className:"text-meta text-ink-muted",children:x("ui.hub.subscriptions.auto_push_description",{source:i})})]}),c.jsx(RF,{id:`${s}-push`,"aria-describedby":p!=="none"?`${s}-push-line`:void 0,checked:e.policy.auto_push,disabled:n.isPending||!n.canWrite||!e.policy.auto_push&&f,"aria-label":`${x("ui.hub.subscriptions.auto_push")}: ${i}`,onCheckedChange:b=>{b?f||(t?.(!0),u({linkId:e.link_id,revision:e.policy.revision,source:i})):h({auto_push:!1},"auto_push")}})]}),p!=="none"&&c.jsx("p",{id:`${s}-push-line`,className:"text-meta text-warning",children:p==="paused"?x("ui.hub.subscriptions.effective_paused",{reason:m}):m}),n.isPending&&c.jsx("output",{className:"text-meta text-ink-muted",children:x("ui.hub.subscriptions.saving",{setting:v,source:i})}),n.error&&c.jsx("p",{role:"alert",className:"text-meta text-danger",children:n.error instanceof yf?n.error.message:n.error instanceof Hi&&n.error.code==="policy-revision-changed"?x("ui.hub.subscriptions.policy_changed"):x("ui.hub.subscriptions.save_failed",{setting:v,source:i})}),c.jsx(Wl,{open:l!==null,onOpenChange:b=>{!b&&!n.isPending&&d()},children:c.jsxs($l,{onOpenAutoFocus:b=>{b.preventDefault(),r.current?.focus()},closeDisabled:n.isPending,onEscapeKeyDown:b=>{n.isPending&&b.preventDefault()},children:[c.jsxs(iC,{children:[c.jsx(jo,{children:x("ui.hub.subscriptions.enable_title",{source:i})}),c.jsx(ru,{children:e.visibility==="public"?x("ui.hub.subscriptions.enable_public",{item:e.name}):x("ui.hub.subscriptions.enable_private",{item:e.name,organization:e.tenant_name??i})})]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.hub.subscriptions.enable_safety")}),n.upgradeMessage&&c.jsx("p",{role:"alert",className:"text-body-sm text-warning","data-hub-core-upgrade":!0,children:n.upgradeMessage}),n.error&&c.jsx("p",{role:"alert",className:"text-body-sm text-danger",children:x("ui.hub.subscriptions.save_failed",{setting:v,source:i})}),c.jsxs(aC,{children:[c.jsx(ce,{ref:r,variant:"outline",disabled:n.isPending,onClick:d,children:x("ui.hub.subscriptions.cancel")}),c.jsx(ce,{disabled:n.isPending||!n.canWrite||f||l?.linkId!==e.link_id||l?.revision!==e.policy.revision||l?.source!==i,onClick:()=>h({auto_push:!0,...e.visibility==="public"?{confirm_public_egress:!0}:{}},"auto_push"),children:x("ui.hub.subscriptions.enable")})]})]})})]})}const KWe=new Set(["provider-error","model-unavailable","prompt-too-long","concurrent-edit","local-concurrent-edit","remote-revision-changed","hub-error"]);function jL(e,t,n,s){return{state:e.state,effective:t,reason:n,retryable:e.error_class!==null&&KWe.has(e.error_class.split("/")[0]),canApply:s,lastSuccess:e.last_success_at,modelUsed:e.model_used,operationId:e.operation_id}}function bW(e){const t=e.visibility==="public"?{visibility:"public",address:e.hub_source}:e.tenant_name?{visibility:"org",address:e.hub_source,organization:e.tenant_name}:{visibility:"unavailable",address:e.hub_source};return{id:e.link_id,kind:e.kind,localId:e.local_id,name:e.name,source:t,policy:{subscribe:e.policy.subscribe,autoPush:e.policy.auto_push,revision:e.policy.revision},canEnableAutoPush:!K2(e).unavailable&&t.visibility!=="unavailable",autoPushUnavailableReason:e.eligibility.reason,canEditPolicy:!0,pull:jL(e.pull,e.auto_will_apply,null,nVe(e.baseline_state)&&e.pull.classification==="remote-only"),push:jL(e.push,e.auto_will_push,e.eligibility.reason,!1)}}function YWe(e){const t=nn(),n=JC(),s=`link:${e}`,r=Io(a=>a.pending.has(s)),i=Kn({onMutate:a=>{const o=Io.getState();if(a.linkId!==e||o.pending.has(s))throw new Error("hub-action-busy");return o.begin(s),s},mutationFn:a=>QC(async()=>{const o=crypto.randomUUID();switch(a.action){case"check":return xt({op:"hub.check",requestId:o,linkId:a.linkId});case"apply":return xt({op:"hub.apply",requestId:o,linkId:a.linkId,direction:"pull",...a.preview?{dryRun:!0}:{},...a.prefer?{prefer:a.prefer}:{},...a.acknowledgeUnknownBaseline?{acknowledgeUnknownBaseline:!0}:{},...a.previewReceipt?{previewReceipt:a.previewReceipt}:{},...a.confirmApply?{confirmApply:!0}:{}});case"retry":return xt({op:"hub.retry",requestId:o,linkId:a.linkId,direction:a.direction});case"preview":return xt({op:"hub.push",requestId:o,linkId:a.linkId,direction:"push",dryRun:!0});case"confirm":return xt({op:"hub.push",requestId:o,linkId:a.linkId,direction:"push",dryRun:!1,previewReceipt:a.previewReceipt,confirmPublish:!0})}},n.snapshot),onSuccess:a=>{if(t.setQueryData(Bd,a.links),t.setQueryData(["desktop","hub-updates"],a.status),a.reports.some(o=>o.applied))for(const o of["profiles","teams","skills"])t.invalidateQueries({queryKey:["desktop",o]})},onSettled:(a,o,l,u)=>{u&&Io.getState().end(u),t.invalidateQueries({queryKey:Bd})}});return{...i,...n,isPending:i.isPending||r}}function fet(){const e=nn(),t=JC();return{...Kn({onMutate:s=>{const r=`resolve:${s.kind}:${s.localId}`,i=Io.getState();if(i.pending.has(r))throw new Error("hub-action-busy");return i.begin(r),r},mutationFn:s=>QC(()=>xt({op:"hub.apply",requestId:crypto.randomUUID(),kind:s.kind,name:s.name,resolveSource:!0,hubSource:s.hubSource,visibility:s.visibility,tenantId:s.tenantId,acknowledgeUnknownBaseline:!0}),t.snapshot),onSuccess:s=>{e.setQueryData(Bd,s.links),e.setQueryData(["desktop","hub-updates"],s.status)},onSettled:(s,r,i,a)=>{a&&Io.getState().end(a),e.invalidateQueries({queryKey:Bd})}}),...t}}const xW={healthy:Cj,review:I0,available:iT,failed:Qa,busy:Ui,applied:Bs},wW={healthy:"text-ink-dim",review:"text-warning",available:"text-accent",failed:"text-danger",busy:"text-ink-dim",applied:"text-success"};function XWe({link:e,staged:t,onDetail:n}){Et();const s=YWe(e.link_id),[r,i]=g.useState(!1),[a,o]=g.useState(!1),l=g.useRef(null),u=g.useId(),d=g.useId(),h=Y2(e),f=mW(bW(e)),p=s.isPending?Ui:xW[f.kind],m=x(f.direction==="pull"?"ui.hub.links.direction_pull":"ui.hub.links.direction_push"),v=x("ui.hub.links.healthy",{item:e.name,source:h,subscribe:x(e.policy.subscribe?"ui.hub.subscriptions.configured_on":"ui.hub.subscriptions.configured_off"),autoPush:x(e.policy.auto_push?"ui.hub.subscriptions.configured_on":"ui.hub.subscriptions.configured_off")}),b=f.kind==="available"?x("ui.hub.links.available",{item:e.name,source:h}):f.kind==="failed"?x("ui.hub.links.failed",{direction:m,item:e.name,source:h}):f.kind==="busy"?x("ui.hub.links.busy",{direction:m,item:e.name,source:h}):f.kind==="applied"?x(f.direction==="pull"?"ui.hub.links.updated":"ui.hub.links.published",{item:e.name,source:h}):v,w=`${b} ${v}${e.policy.auto_push&&e.eligibility.reason?` ${x("ui.hub.subscriptions.effective_paused",{reason:fW(e.eligibility.reason)})}`:""}`;return c.jsxs(Dm,{open:r,onOpenChange:C=>{(C||!a)&&i(C)},children:[c.jsx(Je,{content:w,side:"right",disableHoverableContent:!0,children:c.jsx(WB,{asChild:!0,children:c.jsxs("button",{ref:l,type:"button","data-hub-mark":s.isPending?"busy":f.kind,"data-testid":`hub-mark-${e.kind}-${e.name}`,"aria-label":b,"aria-disabled":!s.canWrite&&(f.action==="apply"||f.action==="retry")||void 0,"aria-describedby":d,"aria-haspopup":"dialog","aria-expanded":r,className:T("flex size-6 shrink-0 items-center justify-center rounded-md",wW[f.kind],!t&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onContextMenu:C=>{C.preventDefault(),C.stopPropagation(),i(!0)},onKeyDown:C=>{(C.key==="ContextMenu"||C.shiftKey&&C.key==="F10")&&(C.preventDefault(),C.stopPropagation(),i(!0))},onClick:C=>{if(C.stopPropagation(),s.isPending||f.action==="policy"||!s.canWrite&&(f.action==="apply"||f.action==="retry")){i(!0);return}if(f.action==="detail"){n();return}s.mutate(f.action==="apply"?{action:"apply",linkId:e.link_id}:{action:"retry",linkId:e.link_id,direction:f.direction},{onError:()=>i(!0)})},children:[c.jsx("span",{id:d,className:"sr-only",children:w}),c.jsx(p,{"aria-hidden":"true",className:T("size-3.5",(s.isPending||f.kind==="busy")&&"motion-safe:animate-spin")})]})})}),c.jsxs(Rf,{side:"right",align:"start","aria-labelledby":u,className:"max-w-[calc(100vw-2rem)]",onInteractOutside:C=>{a&&C.preventDefault()},onCloseAutoFocus:C=>{C.preventDefault(),l.current?.focus()},children:[c.jsx("h4",{id:u,className:"mb-3 break-words text-body-sm text-ink",children:x("ui.hub.subscriptions.policy_menu",{item:e.name,source:h})}),c.jsx(vW,{link:e,onConsentChange:o},e.link_id),s.error&&c.jsx("p",{role:"alert",className:"mt-3 text-meta text-danger",children:s.error instanceof yf?s.error.message:x("ui.hub.links.action_failed",{direction:m,item:e.name,source:h})})]})]})}function QWe({item:e,staged:t,onResolve:n}){Et();const s=x("ui.hub.links.unresolved_mark",{item:e});return c.jsx(Je,{content:s,side:"right",disableHoverableContent:!0,children:c.jsx("button",{type:"button","data-hub-mark":"unresolved","data-testid":"hub-mark-unresolved","aria-label":s,className:T("flex size-6 shrink-0 items-center justify-center rounded-md text-warning",!t&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onClick:r=>{r.stopPropagation(),n()},children:c.jsx(Uw,{"aria-hidden":"true",className:"size-3.5"})})})}function JWe({link:e}){return Et(),c.jsxs("div",{className:"flex min-w-0 flex-col gap-2 px-3 py-2","data-hub-expanded-policy":e.link_id,children:[c.jsx("p",{className:"break-words text-meta text-ink-muted",children:Y2(e)}),c.jsx(vW,{link:e})]})}function ZWe({links:e,staged:t,onDetail:n}){Et();const s={healthy:0,applied:1,available:2,busy:3,failed:4,review:5},i=e.map(u=>mW(bW(u))).reduce((u,d)=>s[d.kind]>s[u]?d.kind:u,"healthy"),a=xW[i]??Cj,o={healthy:"ui.hub.links.mark_healthy",review:"ui.hub.links.mark_review",failed:"ui.hub.links.mark_failed",available:"ui.hub.links.mark_available",busy:"ui.hub.links.mark_busy",applied:"ui.hub.links.mark_applied"},l=x("ui.hub.links.aggregate_mark",{count:e.length,state:x(o[i]??"ui.hub.links.mark_healthy")});return c.jsx(Je,{content:l,side:"right",disableHoverableContent:!0,children:c.jsxs("button",{type:"button","data-hub-mark":"aggregate","data-testid":"hub-mark-aggregate","data-hub-mark-count":e.length,"data-hub-mark-state":i,"aria-label":l,className:T("relative flex size-6 shrink-0 items-center justify-center rounded-md",wW[i]??"text-ink-dim",!t&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onClick:u=>{u.stopPropagation(),n()},children:[c.jsx(a,{"aria-hidden":"true",className:"size-3.5"}),c.jsx("span",{"aria-hidden":"true",className:"absolute -right-0.5 -bottom-0.5 flex h-3 min-w-3 items-center justify-center rounded-full border border-control bg-surface px-0.5 text-meta-sm leading-none text-ink-muted",children:e.length})]})})}const e$e=2,CW={available:iT,review:I0,failed:Qa,updating:Ui,applied:Bs},yW={available:"text-accent",review:"text-warning",failed:"text-danger",updating:"text-ink-dim",applied:"text-success"};function pet({mark:e,className:t}){const n=CW[e.kind];return c.jsx(n,{"aria-hidden":"true",className:T("size-3.5 shrink-0",yW[e.kind],t)})}function t$e({item:e,mark:t,busy:n,blocked:s=!1,staged:r,onPress:i}){const a=g.useId(),o=n?{kind:"updating"}:t,l=o.kind,u=CW[l],d=W9e(e,o),h=G9e(o),f=s||l==="updating"||l==="applied";return c.jsx(Je,{content:h?`${d} ${h}`:d,side:"right",align:"center",disableHoverableContent:!0,children:c.jsxs("button",{type:"button","data-hub-mark":l,"data-testid":`hub-mark-${e.kind}-${e.name}`,className:T("flex size-6 shrink-0 items-center justify-center rounded-md",yW[l],!r&&!f&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),"aria-label":U9e(e.name,o),"aria-describedby":a,"aria-disabled":f||void 0,onClick:()=>{f||i()},children:[c.jsx(u,{className:T("size-3.5",l==="updating"&&"motion-safe:animate-spin"),"aria-hidden":"true"}),c.jsx("span",{id:a,className:"sr-only",children:h?`${d} ${h}`:d})]})})}function n$e({note:e}){return c.jsx("p",{role:e.tone==="error"?"alert":"status",className:T("pb-1 pl-13 pr-2 text-meta",e.tone==="error"?"text-danger":"text-ink-muted"),children:e.message})}function s$e({kind:e,available:t,busy:n,blocked:s=!1,onUpdateAll:r,onCheck:i,checking:a}){const o=t>=e$e;if(!o&&!i)return null;const l=e==="agent"?"agent":"team";return c.jsxs(c.Fragment,{children:[o&&c.jsx("button",{type:"button","data-testid":`hub-update-all-${e}`,"aria-label":`Update all ${t} ${l} updates from the hub`,"aria-disabled":n||s||void 0,className:T("h-6 shrink-0 rounded-md px-1.5 text-meta text-accent","hover:bg-row-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onClick:()=>{!n&&!s&&r()},children:n?"Updating…":`Update all (${t})`}),i&&c.jsx(Je,{content:"Check the hub for updates now",side:"right",children:c.jsx("button",{type:"button","data-testid":"hub-check-now","aria-label":"Check the hub for updates now","aria-disabled":a||s||void 0,className:T("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim","hover:bg-row-hover hover:text-ink-muted focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onClick:()=>{!a&&!s&&i()},children:c.jsx(pC,{className:T("size-3.5",a&&"motion-safe:animate-spin"),"aria-hidden":"true"})})})]})}function r$e({kind:e,reserve:t,signIn:n,signInHref:s,rollup:r,note:i,onDismissRollup:a}){return!t&&!n&&!r&&!i?null:c.jsxs("div",{"data-hub-strip":e,className:"flex flex-col gap-0.5 px-1 pb-1 text-meta text-ink-dim",children:[t&&!n&&!r&&!i&&c.jsx("p",{"aria-hidden":"true",children:" "}),n&&c.jsx("p",{children:c.jsx(R4,{to:s,className:"rounded-sm text-accent underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1",children:n})}),i&&c.jsx("p",{role:i.tone==="error"?"alert":"status",className:i.tone==="error"?"text-danger":void 0,children:i.message}),r&&c.jsxs("output",{className:"flex items-start justify-between gap-2",children:[c.jsx("span",{className:"min-w-0",children:r}),c.jsx("button",{type:"button","aria-label":"Dismiss update summary",className:"shrink-0 rounded-sm px-1 hover:text-ink",onClick:a,children:"Dismiss"})]})]})}const i$e=/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;function a$e(e){const t=e.split(i$e).filter(r=>r.length>0);if(t.length===0)return"?";const n=t[0],s=t[t.length-1];return t.length===1?n.slice(0,2).toUpperCase():`${n[0]}${s[0]}`.toUpperCase()}const _W=({name:e,imageUrl:t,slug:n,showTooltip:s=!0,onActivate:r,className:i})=>{const a=a$e(e),o=c.jsx("span",{"data-team-bubble":!0,"data-team-slug":n,tabIndex:s?0:void 0,role:"img","aria-label":e,onKeyDown:l=>{r&&(l.key!=="Enter"&&l.key!==" "&&l.key!=="Spacebar"||(l.preventDefault(),r()))},className:T(IJ({variant:"attentionQuiet",shape:"pill",size:"count"}),i),children:c.jsxs($B,{className:"h-4 w-fit",children:[t?c.jsx(PJ,{src:t,alt:"",className:"size-4"}):null,c.jsx(zB,{className:"h-full w-auto bg-transparent font-normal text-inherit text-meta-sm",children:a})]})});return s?c.jsx(Je,{content:c.jsx("span",{"aria-hidden":"true",children:e}),children:o}):o},SW=e=>{const n=e.getBoundingClientRect().top+e.clientTop;return{top:n,bottom:n+e.clientHeight}},Ak=(e,t)=>{const n=SW(t),s=e.getBoundingClientRect();return s.bottom<=n.top||s.top>=n.bottom?"outside":s.top>=n.top&&s.bottom<=n.bottom?"inside":"partly"},o$e=e=>{const t=getComputedStyle(e);if(t.outlineStyle==="none")return 0;const n=Number.parseFloat(t.outlineWidth),s=Number.parseFloat(t.outlineOffset);return(Number.isFinite(n)?n:0)+(Number.isFinite(s)?s:0)},HL=(e,t)=>{if(!e){t.current={node:null,index:-1,visibility:"outside",clipHeight:0};return}const n=[...e.querySelectorAll("[data-chat-row]")],s=document.activeElement instanceof HTMLElement?document.activeElement:null,r=s?n.indexOf(s):-1,i=t.current,a=e.clientHeight;if(!s||r<0){t.current={node:null,index:-1,visibility:"outside",clipHeight:a};return}const o=Ak(s,e);if(i.clipHeight!==a||i.node!==s||i.index<0||i.index===r||i.visibility==="outside"||o!=="outside"){t.current={node:s,index:r,visibility:o,clipHeight:a};return}const l=SW(e),u=s.getBoundingClientRect(),d=u.top-l.top,h=l.bottom-u.bottom,f=o$e(s);e.scrollTop=Math.min(Math.max(e.scrollTop+(d<0?d-f:-h+f),0),e.scrollHeight-e.clientHeight),t.current={node:s,index:r,visibility:Ak(s,e),clipHeight:e.clientHeight}},UL=(e,t)=>{const n=t.current.node;!e||!n||!n.isConnected||!e.contains(n)||n===document.activeElement&&(t.current={...t.current,visibility:Ak(n,e),clipHeight:e.clientHeight})},l$e=new Set(["idle","recent"]);function c$e({row:e,open:t}){const n=typeof t=="number"?t:e.asks_open;return typeof n!="number"||!Number.isFinite(n)||n<=0?null:c.jsxs("span",{role:"img","aria-label":`${dY(n)} outstanding. The agent is not blocked on you.`,className:T("inline-flex shrink-0 items-center gap-0.5"),children:[c.jsx(_x,{"aria-hidden":"true",size:14,className:T("text-accent")}),c.jsx("span",{className:T("tabular-nums text-ink-muted text-xs"),children:n})]})}function EW({className:e,mark:t}){return c.jsx("span",{"aria-hidden":"true","data-subagent-mark":t,className:T("flex shrink-0 items-center justify-center",e),children:c.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",className:"size-full",children:[c.jsx("circle",{cx:"12",cy:"6.8",r:"3.9",fill:"currentColor"}),c.jsx("circle",{cx:"7",cy:"17.4",r:"3.9",fill:"currentColor"}),c.jsx("circle",{cx:"17",cy:"17.4",r:"3.9",fill:"currentColor"})]})})}function u$e({row:e}){const t=e.status?.code,n=t==="delegating",s=Bw(e),r=s==="complete",i=t==="busy"?Ui:t==="approval"||t==="answer"||t==="error"?I0:t==="wedged"?sse:t==="interrupted"||t==="dormant"?Xse:t==="complete"?r?Bs:AF:t==="scheduled"?uY:t==="attached"?FT:l$e.has(t??"recent")?AF:Uw,a=t==="busy"?"text-accent motion-safe:animate-spin":t==="wedged"?"text-warning":t==="error"?"text-danger":t==="approval"||t==="answer"||t==="interrupted"?"text-warning":r?"text-success":t==="delegating"?"text-accent":"text-ink-dim";return c.jsxs("span",{className:"flex size-4 shrink-0",children:[n?c.jsx(EW,{className:T("size-4",a)}):c.jsx(i,{className:T("size-4",a),"aria-hidden":"true"}),c.jsxs("span",{className:"sr-only",children:[e.status?.label??"Recent",s!==null?", unread":""]})]})}const d$e="chat-sidebar-entities",h$e="chat-sidebar-chats",dg="flex h-8 min-w-0 items-center gap-1 rounded-md px-1 text-body-sm leading-5 hover:bg-row-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2",R1="flex h-8 items-center gap-1 rounded-md",f$e="@max-[253px]/chatheading:sr-only",GL="read-ack",VL="Sending - this draft can be discarded when the send settles",WL=e=>`draft-discard-why-${e}`,$L="Drafts are sending - they can be cleared when the sends settle",zL="drafts-clear-all-why",yo="bg-row-selected font-medium text-ink hover:bg-row-selected",p$e="bg-row-selected text-ink hover:bg-row-selected hover:text-ink",g$e="outline outline-1 outline-offset-[-1px] outline-ink-dim",m$e=5e3,v$e=3e4,qL="chat-search-include-archived",KL="/stop if it stays silent.",YL=e=>`chat-row-remedy-${e}`,XL=e=>`chat-row-read-ack-${e}`,b$e=()=>navigator.platform.toUpperCase().indexOf("MAC")>=0,x$e=({id:e,openMenuRowIdRef:t,setOpenMenuRowId:n,openedByKeyboard:s})=>(g.useEffect(()=>()=>{t.current===e&&(n(null),s.current=!1)},[e,t,n,s]),null),w$e=e=>e?"Right-click or press Shift+F10 (with Fn on most Mac keyboards) for its actions.":"Right-click or press Shift+F10 for its actions.",QL=e=>`chat-row-menu-${e}`,JL=(e,t)=>{document.querySelector(`[data-session-row="${CSS.escape(e)}"]`)?.querySelector(`[${xY[t]}]`)?.click()},C$e=["No","One","Two","Three","Four","Five","Six"],y$e=e=>{const t=e.map(a=>a.name),n=C$e[t.length]??String(t.length),s=t.length===1?"agent":"agents",r=t.length===1?"is":"are",i=t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`;return`${n} built-in ${s} ${r} ready to install — ${i}. You can edit ${t.length===1?"it":"them"} once installed.`},_$e=8;function S$e({selectedConversation:e,onSelectConversation:t,onStageDraft:n}){const s=Jr(),r=aT(),i=Lc(I=>I.requestPanel),a=Bn(),o=oT(),l=lB(),u=g.useMemo(()=>l.rows===null?null:hY(l.rows),[l.rows]),d=Ce(I=>I.sessions),h=Ce(I=>I.error),f=pa(a.data,"session_catalogue",2),p=f==="enabled",m=pa(a.data,"peers")==="enabled",v=wC(m,{poll:!1}),b=g.useMemo(()=>oWe(v.data),[v.data]),{data:w}=sp(),C=XT(w?.online===!1),y=w?.snapshot&&!w.snapshot.pairing.available?w.snapshot.pairing.cause??"unpaired":null,k=Yk(a.data,y),_=g.useRef(null),E=yt(a.data,"session_pins"),R=yt(a.data,"session_catalogue_page"),F=Ce(I=>I.setCataloguePageable);g.useEffect(()=>{F(R)},[R,F]);const A=yt(a.data,"session_catalogue_sort"),N=Ce(I=>I.setCatalogueActivityHead);g.useEffect(()=>{N(A)},[A,N]);const M=Ce(I=>I.scopes),D=Ce(I=>I.head),L=Ce(I=>I.counts),V=Ce(I=>I.fetchScopePage),j=Ce(I=>I.clearScope),te=Ce(I=>I.fetchCatalogueTail),X=g.useRef(null),re=g.useRef(null),G=Ce(I=>I.pinFailure),J=Ce(I=>I.pinFacts),ae=g.useMemo(()=>{const I={};for(const[pe,Ve]of Object.entries(J))I[pe]=Ve.pinned;return I},[J]),O=Ce(I=>I.setSessionPin),U=g.useRef(!1);p&&(U.current=!0);const{stale:P,showList:z,notice:ne}=AWe({state:f,cause:y,failed:!!a.error,answered:!!a.data,wasReady:U.current,rows:d.length,storeFailed:!!h,coveredByCompatibilityBanner:k}),fe=fY(p&&yt(a.data,"profile_catalogue")),ue=(fe.data??[]).filter(I=>I.source!=="builtin"),le=(fe.data??[]).filter(I=>I.source==="builtin"),q=!fe.isLoading&&ue.length===0,we=qe(I=>I.dismissedBuiltinOfferSignature),B=qe(I=>I.dismissBuiltinOffer),be=E9e(le),ie=k9e(we,be),Te=q&&le.length>0&&!ie,ee=q&&le.length>0&&ie,[de,De]=g.useState(!1),Ue=g.useRef(!1),Se=g.useRef(null);g.useEffect(()=>{!Ue.current||Te||(Ue.current=!1,Se.current?.focus())},[Te]);const ge=sC(p&&yt(a.data,"team_catalogue")),Ae=g.useMemo(()=>new Map((ge.data??[]).map(I=>[I.name,kf(I)])),[ge.data]),st=g.useMemo(()=>I=>Ae.get(I)??I,[Ae]),vt=Q9e(p&&yt(a.data,"hub_updates")),me=L9e(vt.data),it=yt(a.data,"hub_links"),ct=eVe(p&&it),Qe=Z9e(),Nt=(vt.data?.items.length??0)>0||Object.values(vt.data?.counts??{}).some(I=>I>0),Tt=Ce(I=>I.fetchSessions),At=Ce(I=>I.loading),sn=Ce(I=>I.truncated),rt=Ce(I=>I.statusUnavailable).includes("liveness"),An=Ce(I=>I.activeDraftKey),On=Ce(I=>I.drafts),ks=Ce(I=>I.openDraft),js=Ce(I=>I.discardDraft),sr=Ce(I=>I.discardDrafts),rs=Ba(I=>I.inputByConversation),Hr=Ce(I=>I.markAllRead),Ts=Ce(I=>I.readAckNotice),rr=g.useRef(Ts?`${Ts.sessionId}:${Ts.revision}`:null);g.useEffect(()=>{const I=Ts?`${Ts.sessionId}:${Ts.revision}`:null,pe=rr.current!==I;if(rr.current=I,Ts?.kind!=="unsettled"){_b(GL);return}pe&&qh(RWe(Ts),{id:GL,duration:e6})},[Ts]);const[Ot,br]=g.useState(""),[an,ms]=g.useState(!1),ir=an||Ot.length>0,Rs=g.useRef(null),[is,Ie]=g.useState(""),[Ne,Le]=g.useState(()=>Date.now());g.useEffect(()=>{const I=window.setInterval(()=>Le(Date.now()),6e4);return()=>window.clearInterval(I)},[]);const Ee=qe(I=>I.chatSidebarView),Ze=qe(I=>I.setChatSidebarView),H=qe(I=>I.openCommandPalette),K=qe(I=>I.setCommandPaletteQuery),[W,Y]=g.useState(!1),[Q,Z]=g.useState(!1),[ve,Pe]=g.useState(()=>{try{return JSON.parse(localStorage.getItem("chat-sidebar-disclosures")??"{}")}catch{return{}}}),xe=g.useRef(null),ye=g.useRef(null),Re=(I,pe,Ve,ot="pin",mt=!0)=>{const Ct=Array.from(xe.current?.querySelectorAll("[data-session-row]")??[]),on=Ct.findIndex(xn=>xn.getAttribute("data-session-row")===I);if(on<0){ye.current=null;return}const Hn=Ct[on+1]??Ct[on-1]??null;ye.current={id:I,top:Ct[on].getBoundingClientRect().top,follow:pe,pointer:Ve,caret:ot,scroll:mt,anchorId:Hn?.getAttribute("data-session-row")??null,anchorTop:Hn?Hn.getBoundingClientRect().top:0}};g.useEffect(()=>{const I=ye.current,pe=xe.current;if(!I||!pe)return;const Ve=pe.querySelector(`[data-session-row="${I.id}"]`);if(!Ve){ye.current=null;return}if(I.follow){if(I.scroll){const xn=Ve.getBoundingClientRect().top-I.top;xn!==0&&(pe.scrollTop+=xn)}const ot=pe.getBoundingClientRect(),mt=Ve.getBoundingClientRect();mt.top<ot.top?pe.scrollTop-=ot.top-mt.top:mt.bottom>ot.bottom&&(pe.scrollTop+=mt.bottom-ot.bottom);const Ct=Ve.querySelector("[data-session-pin]"),on=Ve.querySelector("[data-chat-row]");(I.caret==="row"?on:Ct!==null&&Ct.getBoundingClientRect().width>0?Ct:on)?.focus({preventScroll:!0})}else if(I.anchorId!==null&&I.scroll){const ot=pe.querySelector(`[data-session-row="${I.anchorId}"]`);if(ot){const mt=ot.getBoundingClientRect().top-I.anchorTop;mt!==0&&(pe.scrollTop+=mt)}}ye.current=null});const ze=g.useRef(null),at=6,pt=(I,pe)=>{const Ve=ze.current;return I===null?!1:Ve!==null&&Math.hypot(I.x-Ve.x,I.y-Ve.y)<=at&&Ve.sessionId!==pe?!0:(ze.current={...I,sessionId:pe},!1)},_e=(I,pe=!1)=>ve[I]??pe,Ye=R&&Ot.trim().length===0,St=g.useCallback(I=>{for(const[pe,Ve]of Object.entries(M)){if(!Ve.ids.includes(I))continue;const[ot,...mt]=pe.split(":"),Ct=mt.join(":");return ot==="agent"?{agent:Ct,team:null}:{agent:null,team:Ct}}},[M]),rn=(I,pe=!1)=>{const Ve=_Z(ve,Ip,I,pe,!!Ot);Pe(Ve.expanded),PA(Ve.caps)},Jt=XZ(d),bn=Ce(I=>I.raiseBulkReadDeferral),[xr,Zr]=g.useState(!1),ar=Jt.count>0&&!Ot.trim()&&yt(a.data,"completion_ack_bulk"),ei=async()=>{Zr(!0);try{const{tone:I,message:pe}=QZ(await Hr());I==="success"?Ls(pe):qh(pe)}catch(I){aB(I)?bn(Jt.count):qh(`${bi(I,"The backend did not answer.")} The unread marks were not cleared.`)}finally{Zr(!1)}},_a=g.useRef(ar);g.useEffect(()=>{if(_a.current&&!ar){const I=document.activeElement;(I===null||I===document.body)&&xe.current?.querySelector('[data-sidebar-region="chats"] [data-chat-row]')?.focus()}_a.current=ar},[ar]);const or=ar?c.jsxs(ce,{size:"sm",variant:"ghost","data-chat-row":!0,"data-tour-tag":"mark-all-read","aria-disabled":xr||void 0,title:Jt.scope,onClick:()=>{xr||ei()},className:"shrink-0 text-ink-dim hover:bg-row-hover",children:[xr?c.jsx(Ui,{className:"text-ink-disabled motion-safe:animate-spin","aria-hidden":"true"}):c.jsx(Kne,{"aria-hidden":"true"}),c.jsx("span",{className:T("truncate",f$e),children:Jt.label}),Jt.nameSuffix?c.jsx("span",{className:"sr-only",children:Jt.nameSuffix}):null]}):null;g.useEffect(()=>{localStorage.setItem("chat-sidebar-disclosures",JSON.stringify(ve))},[ve]);const Sa=g.useCallback(()=>Tt(R?cB:Ww,R),[Tt,R]);g.useEffect(()=>{if(!p)return;if(Sa(),!o.available){const Ve=window.setInterval(()=>{document.visibilityState==="visible"&&Sa()},m$e);return()=>window.clearInterval(Ve)}const I=window.setInterval(()=>{Sa()},v$e),pe=()=>void Sa();return window.addEventListener("focus",pe),()=>{window.clearInterval(I),window.removeEventListener("focus",pe)}},[p,Sa,o.available,o.catalogueRevision,o.activityRevision]),g.useEffect(()=>{if(!(!p||!Ye))for(const[I,pe]of Object.entries(ve)){const Ve=I.startsWith("team:")?"team":I.startsWith("agent:")?"agent":null;if(Ve===null)continue;const ot=I.slice(Ve.length+1);if(ot.length!==0){if(pe){M[I]===void 0&&V(Ve,ot,null);continue}M[I]!==void 0&&j(Ve,ot)}}},[ve,p,Ye,M,V,j]);const tc=yt(a.data,"session_search"),As=yt(a.data,"session_archive"),[gu,Ep]=g.useState(!1),Gi=pY(gu,Ot,As),Qo=Ce(I=>I.archiveFacts),nh=Ce(I=>I.forgotten),so=Ce(I=>I.setStagedByDiscard),kp=Ce(I=>I.setSessionArchived),Tp=Ce(I=>I.requestArchiveConfirm),ro=g.useMemo(()=>{const I={};for(const[pe,Ve]of Object.entries(Qo))Ve.answered&&(I[pe]=Ve.archived);return I},[Qo]),Ci=g.useMemo(()=>({include:Gi,facts:ro,forgotten:new Set(Object.keys(nh))}),[Gi,ro,nh]),Jo=g.useRef(null),lr=aW(Ot,p&&tc,Gi),Vi=lr.refused,Ea=g.useMemo(()=>uB(d,Qo),[d,Qo]),ti=g.useMemo(()=>dB(Ea,As&&!Gi),[Ea,As,Gi]),Zo=TL(lr.data,Ot)?lr.data.sessions:null,Wi=g.useMemo(()=>{const I=new Set(d.map(Ve=>Ve.session_id)),pe=[];for(const[Ve,ot]of Object.entries(J))!ot.pinned||I.has(Ve)||pe.push({session_id:Ve,title:ot.title||"Untitled chat",updated_at:ot.updated_at,pinned:!0});return pe},[J,d]),{rows:Hs,conversationMatches:el,synthesized:mu}=g.useMemo(()=>Ek([...ti,...Wi],Ot,Zo,ae,Ci,St,st),[ti,Wi,Ot,Zo,ae,Ci,St,st]),vu=Zo!==null&&dVe(Zo.length,lr.data?.limit),bu=NWe({pageable:R,shown:Hs.length,total:L?.total??null,searching:Ot.trim().length>0,clipped:vu}),tl=(I,pe)=>Hs.filter(Ve=>I==="team"?Ve.binding?.team===pe:!Ve.binding?.team&&Ve.binding?.agent===pe),xu=(I,pe)=>{if(!Ye)return tl(I,pe);const Ve=M[iF(I,pe)]?.ids;if(Ve===void 0)return[];const ot=new Map(Hs.map(Ct=>[Ct.session_id,Ct])),mt=[];for(const Ct of Ve){const on=ot.get(Ct);on!==void 0&&mt.push(on)}return mt},$i=Ye,wu=g.useRef(null),nc=g.useRef(!1),[nl,io]=g.useState(null),ao=g.useCallback(()=>{if(!$i||nc.current||D.tailCursor!==null&&D.tailCursor===wu.current)return;const I=xe.current;I!==null&&LWe({pageable:$i,nextCursor:D.tailCursor,loading:D.loading,error:D.error,scrollTop:I.scrollTop,clientHeight:I.clientHeight,scrollHeight:I.scrollHeight})&&(sc.current=!0,te())},[$i,D,te]);g.useEffect(()=>{D.error!==null&&D.tailCursor!==null&&(wu.current=D.tailCursor,io({cursor:D.tailCursor,sentence:D.error}))},[D.error,D.tailCursor]),g.useLayoutEffect(()=>{ao()},[ao,d.length]);const sc=g.useRef(!1),[Cu,oo]=g.useState(null),sh=g.useRef(d.length);g.useEffect(()=>{const I=sh.current;if(sh.current=d.length,!sc.current||d.length<=I)return;sc.current=!1,oo(MWe(d.length-I));const pe=window.setTimeout(()=>oo(null),4e3);return()=>window.clearTimeout(pe)},[d.length]);const[ni,sl]=g.useState(""),ka=g.useRef(null),wr=g.useRef(""),yi=g.useRef(null),si=I=>{yi.current!==null&&(window.cancelAnimationFrame(yi.current),yi.current=null),I!==""&&I===wr.current?(sl(""),yi.current=window.requestAnimationFrame(()=>{yi.current=null,sl(I)})):sl(I),wr.current=I,ka.current!==null&&window.clearTimeout(ka.current),ka.current=window.setTimeout(()=>{ka.current=null,wr.current="",sl("")},4e3)},rc=g.useRef(null),ic=g.useCallback((I,pe,Ve,ot,mt)=>{rc.current={key:Ve,name:pe,at:ot},sc.current=!1,V(I,pe,M[Ve]?.nextCursor??null,mt)},[M,V]);g.useEffect(()=>{const I=rc.current;if(I===null)return;const pe=M[I.key]?.ids;if(pe===void 0||pe.length<=I.at)return;rc.current=null;const Ve=pe[I.at],ot=[ch.current,xe.current],mt=Ve===void 0?null:ot.map(xn=>xn?.querySelector(`[data-session-row="${CSS.escape(Ve)}"]`)??null).find(xn=>xn!==null)??null,Ct=ch.current,on=Ct===null?null:[...Ct.querySelectorAll("[data-entity]")].find(xn=>xn.querySelector(`[data-disclosure][aria-label="Expand ${I.name} chats"], [data-disclosure][aria-label="Collapse ${I.name} chats"]`)!==null)??null;(mt?.querySelector("[data-chat-row]")??mt??on?.querySelector("[data-disclosure]")??null)?.focus()},[M]);const Ln=OWe({pageable:$i,nextCursor:$i?D.tailCursor:null,loading:D.loading,error:D.error??(nl!==null&&D.tailCursor===nl.cursor?nl.sentence:null)});g.useEffect(()=>{const I=re.current;if(I!==null){if(Ln.kind==="error"){re.current=null,X.current?.focus();return}if(D.tailCursor!==I.cursor){re.current=null;const Ve=xe.current?.querySelectorAll("[data-session-row]"),ot=Ve===void 0||Ve.length===0?null:Ve[Ve.length-1];(ot?.querySelector("[data-chat-row]")??ot)?.focus();return}Date.now()>I.deadline&&(re.current=null)}},[Ln.kind,D.tailCursor]);const ac=Ln.kind==="none"?null:c.jsxs("div",{className:"py-1","aria-live":"polite",children:[c.jsx("p",{className:"line-clamp-2 text-meta text-ink-dim",children:Ln.kind==="loading"?"Loading more chats…":Ln.sentence}),Ln.kind==="error"&&c.jsx("p",{className:"pt-1",children:c.jsx("button",{ref:X,type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>{re.current={deadline:Date.now()+2e4,cursor:D.tailCursor},wu.current=null,io(null),te()},children:"Retry"})})]}),lo=_1(Hs,E),oc=uWe(Hs,E),Dt=oZ(Ee),co=lo.map(I=>I.session_id),Ta=I=>Hs.find(pe=>pe.session_id===I)?.title||"Untitled chat",uo=XVe(lo,Dt.pins),Cr=uo.map(I=>I.session_id),ho=new Map(Cr.map((I,pe)=>[I,pe])),yu=I=>tWe(Ta(I),ho.get(I)??0,Cr.length),_u=(I,pe,Ve)=>{if(ho.get(I)===void 0)return;const mt=Ta(I);if(!y1(Cr,I,pe)){si(yu(I));return}const Ct=QVe(_1([...ti,...Wi],E).map(Hn=>Hn.session_id),Dt.pins,Cr,I,pe);if(Ct===null)return;Ze({...Dt,pins:Ct}),Re(I,Ve,null,"row",!1);const on=C0(co,Ct);si(FL(mt,on.indexOf(I),on.length))},Fe=(I,pe=!1)=>E&&Dt.groupBy==="section"&&!pe&&ho.has(I),bt=g.useRef(null),Kt=g.useRef(null),Ht=g.useRef(null),[Fn,Ge]=g.useState(null),[jn,Zn]=g.useState(null),[Ra,lc]=g.useState(null),as=g.useRef(null),Aa=g.useRef(0),cc=()=>{const I=bt.current;return I===null?[]:Array.from(I.querySelectorAll("[data-session-row]")).map(pe=>{const Ve=pe.getBoundingClientRect();return{id:pe.getAttribute("data-session-row")??"",top:Ve.top,bottom:Ve.bottom}})},fo=I=>{const pe=Ht.current;if(pe===null||!pe.armed)return;const Ve=ZVe(cc(),pe.id,I);pe.slot!==Ve&&(pe.slot=Ve,Ge({id:pe.id,slot:Ve}))},ov=(I,pe)=>{const Ve=bt.current,ot=Kt.current;if(Ve===null||ot===null)return;const mt=cc().filter(Hn=>Hn.id!==I),Ct=Ve.getBoundingClientRect().top,on=pe<=0?mt[0]?.top??Ct+Ve.offsetHeight:mt[pe-1]?.bottom??Ct;ot.style.top=`${Math.round(on-Ct)}px`},Rp=32,lv=12,cv=()=>{as.current=null;const I=Ht.current,pe=xe.current;if(I===null||!I.armed||pe===null)return;const Ve=pe.getBoundingClientRect(),ot=Aa.current,mt=pe.scrollHeight-pe.clientHeight;let Ct=0;ot-Ve.top<Rp&&pe.scrollTop>0?Ct=-1:Ve.bottom-ot<Rp&&pe.scrollTop<mt&&(Ct=1),Ct!==0&&(pe.scrollTop+=Ct*lv),fo(ot),as.current=requestAnimationFrame(cv)},rh=()=>{as.current!==null&&(cancelAnimationFrame(as.current),as.current=null)},Ap=(I,pe,Ve)=>{if(Ve.button===0){Ve.preventDefault(),Ve.stopPropagation();try{Ve.currentTarget.setPointerCapture(Ve.pointerId)}catch{}Ht.current={pointerId:Ve.pointerId,id:I,label:pe,armed:!1,slot:-1},Aa.current=Ve.clientY}},$s=I=>{const pe=Ht.current;pe===null||I.pointerId!==pe.pointerId||(Aa.current=I.clientY,pe.armed||(pe.armed=!0,Ge({id:pe.id,slot:pe.slot}),si(`Moving “${pe.label}”.`),as.current===null&&(as.current=requestAnimationFrame(cv))),fo(I.clientY))},uv=(I,pe)=>{const Ve=Ta(I),ot=JVe(_1([...ti,...Wi],E).map(Ct=>Ct.session_id),Dt.pins,Cr,I,pe);if(ot===null){si("");return}Ze({...Dt,pins:ot}),Re(I,!1,null,"row",!1);const mt=C0(co,ot);si(FL(Ve,mt.indexOf(I),mt.length))},ih=I=>{const pe=Ht.current;if(Ht.current=null,rh(),Ge(null),!(pe===null||!pe.armed)){if(!I){si("Move cancelled.");return}uv(pe.id,pe.slot)}},dv=g.useRef(ih);dv.current=ih,g.useEffect(()=>{if(Fn===null)return;const I=pe=>{pe.key==="Escape"&&(dv.current(!1),pe.preventDefault())};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[Fn!==null]),g.useEffect(()=>{if(Fn===null)return;const I=()=>dv.current(!0),pe=()=>dv.current(!1);return window.addEventListener("pointerup",I),window.addEventListener("pointercancel",pe),()=>{window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",pe)}},[Fn!==null]),g.useEffect(()=>()=>{as.current!==null&&cancelAnimationFrame(as.current)},[]),g.useLayoutEffect(()=>{Fn!==null&&ov(Fn.id,Fn.slot)},[Fn]);const mA=g.useMemo(()=>new Set(Hs.map(I=>I.session_id)),[Hs]),ry=g.useMemo(()=>CWe(On,rs,mA),[On,rs,mA]),ah=ry.filter(I=>!I.pending),hv=Ot.trim().length>0,vA=hv?oc:OF(oc,Dt.orderBy,Dt.basis),rl=lZ(vA,{limit:Eu(Dt.loads),currentId:e,searching:hv}),bA=rl.lifted?rl.rows[0]:null,xA=rl.lifted?rl.rows.slice(1):rl.rows;nc.current=rl.remaining>0||Dt.hidden.length>0;const m$=Eu(Dt.loads+1)-Eu(Dt.loads),v$=Ye&&D.tailCursor!==null,b$=()=>{const I=Dt.loads+1;Ze({...Dt,loads:I}),Ye&&Eu(I)>oc.length&&te()},x$=Dt.groupBy!==xv.groupBy||Dt.basis!==xv.basis||Dt.orderBy!==xv.orderBy||Dt.hidden.length>0||Dt.loads>0||Dt.pins.length>0||Dt.pinnedAgents.length>0||Dt.order.some((I,pe)=>I!==xv.order[pe]),oh=cZ(xA,Ne,Dt.basis),wA=uZ(Dt).filter(I=>I!=="pinned"&&!JB(I)),w$=mg(Dt,"pinned"),C$=wA.find(I=>oh[I].length>0)??null,y$={pinned:lo.length,running:oh.running.length,today:oh.today.length,week:oh.week.length,older:oh.older.length,agents:ue.length,teams:ge.data?.length??0},iy=g.useMemo(()=>gWe(ue.map(I=>({id:I.name,name:I.name})),{pinned:Dt.pinnedAgents,recency:I=>pWe(d,I.name)}),[ue,Dt.pinnedAgents,d]),ay=dZ(_e("agents",!0),Ot,is,ue.length),_$=g.useMemo(()=>fWe(iy,is),[iy,is]),CA=ay&&is.trim()?_$.filter(I=>LF(I.name,xu("agent",I.name).length,Ot)):[],fv=Dt,yA=An?On[An]:void 0,_A=I=>I.binding?.team||I.binding?.agent||"",oy=I=>I.binding?.team??"",SA=I=>{const pe=I.binding?.team;return pe?st(pe):I.binding?.agent??""},EA=I=>I.opened_by!=null,kA=I=>`opened by ${I.opened_by?.agent?.trim()||"an agent"}`,S$=I=>{if(!I.opened_by)return"";const pe=I.opened_by.label?.trim();return`, ${kA(I)}${pe?` in “${pe}”`:""}`},E$=I=>{const pe=_A(I);return!pe||I.opened_by?.agent?.trim()===pe?"":` (${SA(I)})`},Fp=TL(lr.data,Ot),TA=g.useMemo(()=>Fp||!lr.data||!Ot.trim()?null:Ek([...ti,...Wi],lr.data.query,lr.data.sessions,ae,Ci,St,st),[Fp,lr.data,ti,Wi,ae,Ci,St,st,Ot]),RA=!!Ot.trim()&&p&&tc&&!Vi&&!lr.isError&&!Fp,ly=g.useMemo(()=>new Set(Object.values(On).filter(I=>I.sessionId).map(I=>I.sessionId)),[On]),Dp=(I,pe=!1)=>{const Ve=cVe({marked:el.has(I.session_id),unstarted:ly.has(I.session_id),nested:pe,binding:_A(I),team:oy(I),agentOpened:EA(I)}),ot=I.pinned===!0,mt=I.locality==="remote",Ct=mt?lWe(I,b.get(typeof I.owner_device=="string"?I.owner_device:"")):"",on=mt?cWe(I):"",Hn=uW(I),xn=tn=>{pt(tn,I.session_id)||t(I.session_id)},Cn=(tn,Ur)=>c.jsx("span",{className:"ml-1 inline-flex shrink-0",onPointerEnter:()=>Zn(I.session_id),onPointerLeave:()=>Zn(null),onFocus:()=>lc(I.session_id),onBlur:()=>lc(null),children:c.jsx(_W,{name:tn,slug:Ur,onActivate:()=>xn(null)})}),vs=hWe(I),Yn=I.title||"Untitled chat",Fa=ro[I.session_id]??I.archived===!0,_i=e===I.session_id&&!An,Lp=E||As,uh=!ly.has(I.session_id),Su=b$e(),uc=pv===I.session_id,Si=Fn?.id===I.session_id,po=I.status?.code==="wedged",Da=SWe(Ts,I.session_id,typeof I.owner_device_name=="string"?I.owner_device_name:null),Bp=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"block",children:[I.title||"Untitled chat",E$(I)]}),c.jsxs("span",{className:"block",children:[I.status?.label??(mu.has(I.session_id)?"found by search, beyond the chats listed here":"Recent"),po?` · ${KL}`:"",S$(I),ly.has(I.session_id)?", not sent yet":"",Bw(I)!==null?", unread":"",Fa?", archived":"",vs,Da?` · ${Da.clause}`:""]}),mt&&c.jsx("span",{className:"block",children:Ct}),on&&c.jsx("span",{className:"block",children:on})]}),al=c.jsxs("button",{type:"button","data-chat-row":!0,"data-tour-tag":"chat-session-row","data-child":pe||void 0,"data-session-archived":Fa?"true":void 0,className:T(dg,"min-w-0 grow text-left",pe&&"pl-7",_i&&yo),"aria-current":_i?"page":void 0,...po||Da||Lp?{"aria-describedby":[po?YL(I.session_id):null,Da?XL(I.session_id):null,Lp?QL(I.session_id):null].filter(Boolean).join(" ")}:{},onClick:tn=>{xn(tn.detail===0?null:{x:tn.clientX,y:tn.clientY})},children:[c.jsx("span",{"aria-hidden":"true",className:"flex size-3.5 shrink-0 items-center justify-center",children:I.locality==="remote"&&c.jsx(BWe,{unreachable:I.reachable===!1})}),c.jsx(u$e,{row:I}),c.jsx(c$e,{row:I,open:u?.get(I.session_id)}),As&&Fa&&c.jsxs(c.Fragment,{children:[c.jsx(Yh,{"aria-hidden":"true",className:"ml-1 size-3.5 shrink-0 text-ink-dim"}),c.jsx("span",{className:"sr-only",children:", archived"})]}),c.jsx(VWe,{text:I.title||"Untitled chat"}),Hn.running&&c.jsx(EW,{mark:"running",className:"ml-1 size-3.5 text-accent"}),Hn.queued&&c.jsx(kse,{"aria-hidden":"true","data-subagent-mark":"queued",className:"ml-1 size-3.5 shrink-0 text-ink-muted"}),Ve==="team"&&Cn(st(oy(I)),oy(I)),Ve==="binding"&&(I.binding?.team?Cn(st(I.binding.team),I.binding.team):c.jsxs("span",{className:"ml-1 max-w-[45%] shrink-0 truncate text-meta text-ink-muted",children:["· ",SA(I)]})),Ve==="not_sent"&&c.jsx("span",{className:"ml-1 shrink-0 text-meta text-ink-muted",children:"· Not sent yet"}),Ve==="conversation"&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",className:"ml-1 shrink-0 whitespace-nowrap text-meta text-ink-muted",children:"· in conversation"}),c.jsx("span",{className:"sr-only",children:", matched in conversation"})]}),mt&&c.jsxs("span",{className:"sr-only",children:[", ",Ct]}),on&&c.jsxs("span",{className:"sr-only",children:[", ",on]}),EA(I)&&(Ve==="team"||Ve==="none")&&c.jsxs("span",{className:"sr-only",children:[", ",kA(I)]}),vs!==""&&c.jsx("span",{className:"sr-only",children:vs}),!CZ(I)&&GF(I,Ne,Dt.basis)&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true","data-session-time":!0,className:"ml-auto shrink-0 pl-2 font-mono text-ink-dim text-mono-sm tabular-nums group-has-[:focus-visible]:hidden group-data-[session-hover-intent]:hidden",children:GF(I,Ne,Dt.basis)}),c.jsxs("span",{className:"sr-only",children:[", ",yZ(I,Ne,Dt.basis)]})]})]}),jp=po?c.jsx("span",{id:YL(I.session_id),className:"sr-only",children:KL}):null,ol=Da?c.jsx("span",{id:XL(I.session_id),className:"sr-only",children:Da.description}):null,gv=Lp?c.jsx("span",{id:QL(I.session_id),className:"sr-only",children:w$e(Su)}):null,Hp=tn=>{const Ur=tn.relatedTarget;Ur&&tn.currentTarget.contains(Ur)&&tn.preventDefault()},mv=(tn,Ur)=>c.jsx(Je,{content:Bp,side:"right",align:"start",disableHoverableContent:!0,collisionPadding:_$e,overlayName:"sidebar-row-flyout",disabled:Fn!==null,suppressed:jn===I.session_id||Ra===I.session_id,children:tn},Ur);if(!E&&!As)return mv(c.jsxs("div",{onBlur:Hp,className:T(R1,_i&&yo),children:[al,jp,ol]}),I.session_id);const cr=E&&As,dc=y1(Cr,I.session_id,-1),vv=y1(Cr,I.session_id,1),HA=Fe(I.session_id,pe),UA=c.jsxs(c.Fragment,{children:[HA&&c.jsx(c.Fragment,{children:Cr.length>=2&&c.jsx("button",{type:"button","data-session-pin-grip":!0,tabIndex:-1,"aria-hidden":"true",title:"Drag to reorder · Esc cancels",onPointerDown:tn=>Ap(I.session_id,Yn,tn),onPointerMove:$s,onPointerUp:()=>ih(!0),onPointerCancel:()=>ih(!1),className:T("hidden size-6 shrink-0 cursor-grab items-center justify-center rounded-md active:cursor-grabbing","text-ink-dim","group-data-[session-hover-intent]:flex group-data-[session-hover-intent]:text-ink-muted",uc&&"flex text-ink-muted","hover:text-ink!",!_i&&"hover:bg-row-hover"),children:c.jsx(Cse,{"aria-hidden":"true",className:"size-4"})})}),I.pinned!==void 0&&c.jsx("button",{type:"button","data-session-pin":!0,tabIndex:-1,"aria-pressed":ot,"aria-label":`${ot?"Unpin":"Pin"} “${Yn}”`,title:`${ot?"Unpin":"Pin"} “${Yn}”`,onClick:tn=>{pt(tn.detail===0?null:{x:tn.clientX,y:tn.clientY},I.session_id)||(Re(I.session_id,tn.detail===0,{x:tn.clientX,y:tn.clientY}),O(I.session_id,!ot,{title:I.title??void 0,updated_at:I.updated_at??void 0}),ot&&Dt.pins.includes(I.session_id)&&Ze({...Dt,pins:eWe(Dt.pins,I.session_id)}))},className:T("size-6 shrink-0 items-center justify-center rounded-md",ot?"flex text-ink":T("hidden text-ink-dim","group-data-[session-hover-intent]:flex group-data-[session-hover-intent]:text-ink-muted group-has-[:focus-visible]:flex group-has-[:focus-visible]:text-ink-muted",uc&&"flex text-ink-muted","hover:text-ink!"),!_i&&"hover:bg-row-hover"),children:c.jsx(zy,{"aria-hidden":"true",className:"size-4",fill:ot?"currentColor":"none"})}),As&&c.jsx("button",{type:"button","data-session-archive":!0,tabIndex:-1,"aria-label":rx(Yn,Fa),title:rx(Yn,Fa),onClick:tn=>{const Ur=KVe(Jo.current,tn.detail===0?null:{x:tn.clientX,y:tn.clientY},I.session_id);if(Jo.current=Ur.record,Ur.drop)return;if(!Fa){Tp({sessionId:I.session_id,fromRow:!0});return}const j$=v5(tn.currentTarget);kp(I.session_id,!1,I.title??void 0).then(H$=>{H$&&j$()})},className:T(T("hidden size-6 shrink-0 items-center justify-center rounded-md","order-first","text-ink-dim","group-data-[session-hover-intent]:flex group-data-[session-hover-intent]:text-ink-muted","group-has-[:focus-visible]:flex group-has-[:focus-visible]:text-ink-muted",uc&&"flex text-ink-muted"),"hover:text-ink!",!_i&&"hover:bg-row-hover"),children:Fa?c.jsx(yx,{"aria-hidden":"true",className:"size-4"}):c.jsx(Yh,{"aria-hidden":"true",className:"size-4"})})]}),B$=c.jsxs("div",{"data-session-row":I.session_id,"data-session-menu-trigger":!0,onKeyDown:A$,onPointerDownCapture:F$,"data-dragging":Si?"":void 0,onBlur:Hp,className:T((E||As)&&"group",(E||As)&&!_i&&"hover:bg-row-hover",uc&&!_i&&"bg-row-hover",R1,_i&&yo,Si&&p$e,Si&&g$e),children:[(E||As)&&c.jsx(jWe,{}),al,jp,ol,gv,cr?c.jsx("div",{"data-session-control-pair":!0,className:T("items-center gap-1",ot||uc?"flex":"hidden group-data-[session-hover-intent]:flex group-has-[:focus-visible]:flex"),children:UA}):UA]});return c.jsxs(fVe,{open:uc,onOpenChange:tn=>{tn&&Op.current===null&&(Op.current=document.activeElement instanceof HTMLElement?document.activeElement:null),LA(Ur=>tn?I.session_id:Ur===I.session_id?null:Ur)},children:[c.jsx(x$e,{id:I.session_id,openMenuRowIdRef:dy,setOpenMenuRowId:LA,openedByKeyboard:Mp}),mv(c.jsx(pVe,{asChild:!0,children:B$}),I.session_id),c.jsxs(oW,{onFocus:tn=>{Mp.current&&tn.target===tn.currentTarget&&tn.currentTarget.querySelector('[role="menuitem"]')?.focus()},onCloseAutoFocus:tn=>{tn.preventDefault();const Ur=Op.current;if(Op.current=null,!Mp.current){Ur?.isConnected?Ur.focus():document.querySelector(`[data-session-row="${CSS.escape(I.session_id)}"] [data-chat-row]`)?.focus();return}Mp.current=!1,document.querySelector(`[data-session-row="${CSS.escape(I.session_id)}"] [data-chat-row]`)?.focus()},children:[As&&c.jsxs(yc,{onSelect:()=>JL(I.session_id,"archive"),children:[Fa?c.jsx(yx,{"aria-hidden":"true"}):c.jsx(Yh,{"aria-hidden":"true"}),c.jsx("span",{children:Fa?"Unarchive conversation":"Archive conversation"}),c.jsx("span",{className:"ml-auto pl-6",children:c.jsx(Er,{shortcut:aF("archive",Su),joined:!0})})]}),I.pinned!==void 0&&c.jsxs(yc,{onSelect:()=>JL(I.session_id,"pin"),children:[ot?c.jsx(Zse,{"aria-hidden":"true"}):c.jsx(zy,{"aria-hidden":"true"}),c.jsx("span",{children:ot?"Unpin conversation":"Pin conversation"}),c.jsx("span",{className:"ml-auto pl-6",children:c.jsx(Er,{shortcut:aF("pin",Su),joined:!0})})]}),uh&&c.jsxs(yc,{onSelect:()=>{i("session.fork",document.querySelector(`[data-session-row="${CSS.escape(I.session_id)}"] [data-chat-row]`),I.session_id),r.pathname.startsWith("/chat")||s("/chat")},children:[c.jsx(mY,{"aria-hidden":"true"}),c.jsx("span",{children:"Fork conversation"})]}),c.jsxs(yc,{onSelect:()=>void dW(I.session_id),children:[c.jsx(Gl,{"aria-hidden":"true"}),c.jsx("span",{children:"Copy session ID"})]}),c.jsxs(yc,{onSelect:()=>{i("session.rename",document.querySelector(`[data-session-row="${CSS.escape(I.session_id)}"] [data-chat-row]`),I.session_id,{subjectName:I.title||"Untitled chat"}),r.pathname.startsWith("/chat")||s("/chat")},children:[c.jsx(Gk,{"aria-hidden":"true"}),c.jsx("span",{children:"Rename conversation"})]}),HA&&c.jsxs(c.Fragment,{children:[c.jsxs(yc,{"aria-disabled":!dc,title:dc?void 0:yu(I.session_id),onSelect:()=>_u(I.session_id,-1,!0),className:T("aria-disabled:cursor-default aria-disabled:text-ink-disabled!","aria-disabled:hover:bg-transparent! aria-disabled:hover:text-ink-disabled!","aria-disabled:[&_kbd]:text-ink-disabled!"),children:[c.jsx(N0,{"aria-hidden":"true"}),c.jsx("span",{children:"Move conversation up"}),c.jsx("span",{className:"ml-auto pl-6",children:c.jsx(Er,{shortcut:DL(-1,Su),joined:!0})})]}),c.jsxs(yc,{"aria-disabled":!vv,title:vv?void 0:yu(I.session_id),onSelect:()=>_u(I.session_id,1,!0),className:T("aria-disabled:cursor-default aria-disabled:text-ink-disabled!","aria-disabled:hover:bg-transparent! aria-disabled:hover:text-ink-disabled!","aria-disabled:[&_kbd]:text-ink-disabled!"),children:[c.jsx(pi,{"aria-hidden":"true"}),c.jsx("span",{children:"Move conversation down"}),c.jsx("span",{className:"ml-auto pl-6",children:c.jsx(Er,{shortcut:DL(1,Su),joined:!0})})]})]})]})]},I.session_id)},Pp=(I,pe)=>s(`/agents?kind=${I}&name=${encodeURIComponent(pe)}`),k$=async(I,pe,Ve)=>{if(Ve.kind==="review"||Ve.kind==="failed"&&!Ve.retryable)return Pp(I,pe);(Ve.kind==="failed"?await Qe.retryItem(I,pe):await Qe.applyItem(I,pe))?.some(mt=>mt.outcome==="needs-review")&&Pp(I,pe)},T$=async I=>{await Qe.applyAll(I),requestAnimationFrame(()=>{const pe=document.activeElement;pe&&pe!==document.body||document.querySelector(`[data-chat-section="${I==="agent"?"agents":"teams"}"]`)?.focus()})},AA=I=>c.jsx(s$e,{kind:I,available:$9e(vt.data,I),busy:Qe.pending.has(`all:${I}`),blocked:!Qe.canWrite,onUpdateAll:()=>void T$(I),onCheck:I==="agent"&&Nt?()=>void Qe.checkNow():void 0,checking:Qe.pending.has("check")}),FA=I=>c.jsx(r$e,{kind:I,reserve:I==="agent"&&(Nt||vt.data?.credential==="none"),signIn:I==="agent"?z9e(vt.data):null,signInHref:"/settings?section=radient",rollup:Qe.rollups[I],note:Qe.notes[`all:${I}`]??(I==="agent"?Qe.notes.check:void 0)??(I==="agent"&&Nt&&Qe.upgradeMessage?{message:Qe.upgradeMessage,tone:"info"}:void 0),onDismissRollup:()=>Qe.clearRollup(I)}),cy=(I,pe,Ve=pe)=>{const ot=xu(I,pe),mt=iF(I,pe),Ct=I==="team"?st(pe):pe,on=Ct!==pe?`${Ct} (${pe})`:Ct,Hn=!!Ot||_e(mt),xn=xZ(hv?ot:OF(ot,fv.orderBy,fv.basis),{loads:IA[mt]??0,currentId:e,searching:hv}),Cn=xn.rows,vs=IWe({pageable:Ye,total:Ye?E1(L,I,pe):null,held:ot.length,searching:!!Ot.trim()}),Yn=PWe({pageable:Ye,scope:M[mt],held:M[mt]?.ids.length??ot.length,total:Ye?E1(L,I,pe):null}),Fa=Ye?E1(L,I,pe)??ot.length:ot.length,_i=IA[mt]??0,Lp=Eu(_i+1)-Eu(_i),uh=wZ({add:xn.hidden>0?Math.min(Lp,xn.hidden):Ye&&Yn.more?Yn.addCount:0,drawn:Cn.length,total:Fa}),Su=()=>{const cr=_i+1;if(NA(vv=>({...vv,[mt]:cr})),!Ye)return;const dc=M[mt]?.ids.length??0;M[mt]?.nextCursor!==null&&Eu(cr)>=dc&&ic(I,pe,mt,dc,Yn.addCount)};if(!LF(pe,ot.length,Ot,Ct))return null;const uc=I==="team"?Og:Uo,Si=yA?.target?.kind===I&&yA.target.name===pe,po=I==="agent"&&fv.pinnedAgents.includes(Ve),Da=x0(I,pe),Bp=me.get(Da),al=nW(Bp),jp=I==="team"?ge.data?.find(cr=>cr.name===pe)?.id:fe.data?.find(cr=>cr.name===pe)?.agent_id??void 0,ol=it?sVe(ct.data,I,jp,pe):[],gv=ol.length===1?ol[0]:void 0,Hp=ol.length>1?ol:null,mv=it&&ol.length===0?rVe(ct.data,I,jp,pe):[];return c.jsxs("div",{"data-entity":!0,children:[c.jsxs("div",{className:T("group flex h-8 items-center gap-1 rounded-md",Si&&yo),children:[c.jsx("button",{type:"button","data-disclosure":!0,"aria-label":`${Hn?"Collapse":"Expand"} ${Ct} chats`,"aria-expanded":Hn,className:T("flex size-6 shrink-0 items-center justify-center rounded-md",!Si&&"hover:bg-row-hover"),onClick:()=>{Hn&&NA(cr=>{if(cr[mt]===void 0)return cr;const dc={...cr};return delete dc[mt],dc}),rn(mt)},children:Hn?c.jsx(pi,{className:"size-3.5"}):c.jsx(ga,{className:"size-3.5"})}),c.jsxs("button",{type:"button","data-chat-row":!0,"data-entity-name":!0,className:T(dg,"flex-1 text-left",Si&&yo),onClick:()=>n({kind:I,name:pe}),"aria-label":`New chat with ${Ct}`,title:`New chat with ${Ct}`,children:[c.jsx(uc,{className:"size-4 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",title:on,children:Ct}),c.jsx(KS,{className:T("size-4 shrink-0 text-ink opacity-0","transition-opacity duration-base ease-out-quart","group-hover:opacity-100 group-hover:duration-fast","group-focus-within:opacity-100 group-focus-within:duration-fast"),"aria-hidden":"true"}),c.jsx("span",{title:vs>0?OL(vs):void 0,className:"min-w-4 shrink-0 text-right text-meta tabular-nums text-ink-dim",children:vs||""})]}),vs>0&&c.jsx("span",{className:"sr-only",children:OL(vs)}),I==="agent"&&c.jsx(Je,{content:po?`Unpin “${pe}”`:`Pin “${pe}”`,children:c.jsx("button",{type:"button","data-agent-pin":Ve,className:T("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim hover:text-ink-muted",!Si&&"hover:bg-row-hover",po?"opacity-100":"opacity-0","transition-opacity duration-base ease-out-quart","group-hover:opacity-100 group-hover:duration-fast","group-focus-within:opacity-100 group-focus-within:duration-fast"),"aria-pressed":po,"aria-label":`Pin “${pe}”`,onClick:()=>Ze(mWe(fv,Ve)),children:c.jsx(zy,{"aria-hidden":"true",className:T("size-4",po&&"text-ink"),fill:po?"currentColor":"none"})})}),gv&&c.jsx(XWe,{link:gv,staged:Si,onDetail:()=>Pp(I,pe)}),Hp&&c.jsx(ZWe,{links:Hp,staged:Si,onDetail:()=>Pp(I,pe)}),mv.length>0&&c.jsx(QWe,{item:pe,staged:Si,onResolve:()=>s(`/agents?kind=${I}&name=${encodeURIComponent(pe)}&resolve=${Date.now()}`)}),!it&&al&&Bp&&c.jsx(t$e,{item:Bp,mark:al,busy:Qe.pending.has(Da),blocked:!Qe.canWrite&&(al.kind==="available"||al.kind==="failed"&&al.retryable),staged:Si,onPress:()=>k$(I,pe,al)}),c.jsx("button",{type:"button",className:T("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim hover:text-ink-muted",!Si&&"hover:bg-row-hover"),"aria-label":`Manage ${Ct}`,onClick:()=>s(`/agents?kind=${I}&name=${encodeURIComponent(pe)}`),children:c.jsx(nC,{className:"size-4"})})]}),Qe.notes[Da]&&c.jsx(n$e,{note:Qe.notes[Da]}),Hn&&c.jsxs("div",{children:[ol.map(cr=>c.jsx(JWe,{link:cr},cr.link_id)),xn.lifted&&lh("Current chat"),Cn.map(cr=>Dp(cr,!0))," ",c.jsxs("div",{"aria-live":"polite",className:Yn.state!=="rows"&&Yn.sentence!==null?"py-1 pl-7":"sr-only",children:[Yn.state!=="rows"&&Yn.sentence!==null&&c.jsx("p",{className:"line-clamp-2 text-meta text-ink-dim",title:Yn.sentence,children:Yn.sentence}),Yn.state!=="rows"&&Yn.retry&&c.jsx("p",{className:"pt-1",children:c.jsx("button",{type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>void V(I,pe,null),children:"Retry"})})]}),Yn.state==="rows"&&(M[mt]?.loading?c.jsx("p",{className:"py-1 pl-7 text-meta text-ink-dim","aria-live":"polite",children:"Loading more…"}):Yn.retry?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"line-clamp-2 py-1 pl-7 text-meta text-ink-dim","aria-live":"polite",children:Yn.sentence}),c.jsx("p",{className:"py-1 pl-7",children:c.jsx("button",{type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>ic(I,pe,mt,M[mt]?.ids.length??ot.length,Yn.addCount),children:"Retry"})})]}):uh?c.jsx("button",{type:"button","data-scope-more":mt,"data-chat-row":!0,"data-entity-more":mt,"aria-label":`${uh.aria} in ${Ct}`,title:`${uh.aria} in ${Ct}`,className:"block w-full py-1 pl-7 text-left text-meta text-ink-dim underline hover:text-ink",onClick:Su,children:uh.label}):null)]})]},mt)},DA=(I,pe,Ve,ot,mt,Ct,on,Hn)=>{const xn=jF(Ip[I])?HF:null;return c.jsxs("div",{className:T("@container/chatheading flex h-7 items-center gap-1",Ct),children:[c.jsxs("button",{ref:on,type:"button","data-chat-row":!0,"data-chat-section":I,className:"flex h-7 min-w-0 flex-1 items-center gap-1 rounded-md px-1 text-body-sm font-medium text-ink-muted hover:bg-row-hover","aria-expanded":Ot?!0:_e(I,Ve),title:xn??void 0,"aria-describedby":xn?UF(I):void 0,onClick:()=>rn(I,Ve),children:[Ot||_e(I,Ve)?c.jsx(pi,{className:"size-3.5"}):c.jsx(ga,{className:"size-3.5"}),mt?g.createElement(mt,{"aria-hidden":!0,className:"size-3.5 shrink-0 text-ink-dim"}):null,c.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:pe}),ot!==void 0]}),xn&&c.jsx("span",{id:UF(I),className:"sr-only",children:xn}),Ct,Hn]})},[Ip,PA]=g.useState({}),[IA,NA]=g.useState({}),uy=g.useRef(null),MA=(I,pe)=>{const Ve=Ip[I]??BF,ot=pe.length-Ve,mt=vZ(ot,I);return c.jsxs(c.Fragment,{children:[pe.slice(0,Ve),ot>0&&c.jsx("button",{type:"button","data-sidebar-section-more":I,"data-chat-row":!0,"aria-label":mt,title:jF(Ve)?`${mt} - ${HF}`:mt,onClick:()=>{uy.current={key:I,at:Ve},PA(Ct=>bZ(Ct,I))},className:"flex h-7 w-full items-center rounded-md px-2 text-left text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:mZ(ot)})]})},lh=(I,pe)=>c.jsxs("div",{className:"flex h-6 items-center gap-1 px-2",children:[c.jsx("h3",{className:"min-w-0 flex-1 truncate font-medium text-ink-dim text-meta uppercase tracking-wide",children:I}),pe]}),OA=g.useRef(null),Np=I=>{const pe=il.current;if(pe===null)return;const Ve=[...pe.querySelectorAll("[data-chat-row]")],ot=Ve.filter(Ct=>!Ct.disabled);if(ot.length===0)return;const mt=I!==null&&ot.includes(I)?I:ot[0];OA.current=mt;for(const Ct of Ve)Ct.tabIndex=ot.includes(Ct)&&Ct===mt?0:-1,Ct.toggleAttribute(gY,ot.includes(Ct)&&Ct===mt)};g.useLayoutEffect(()=>{Np(OA.current)});const R$=I=>{const pe=I.target.closest?.("[data-chat-row]");pe!=null&&il.current?.contains(pe)&&Np(pe)},[pv,LA]=g.useState(null),Mp=g.useRef(!1),Op=g.useRef(null),dy=g.useRef(null);g.useEffect(()=>{dy.current=pv},[pv]);const A$=I=>{if(I.key!=="ContextMenu"&&!(I.shiftKey&&I.key==="F10"))return;const pe=I.currentTarget;I.preventDefault(),Mp.current=!0;const Ve=pe.getBoundingClientRect();pe.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:Ve.left,clientY:Ve.bottom-1}))},F$=()=>{dy.current===null&&(Op.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},D$=I=>{if(pv!==null)return;const pe=I.target,Ve=vY(I);if(Ve!==null){const Cn=bY(pe,Ve);Cn!==null&&(I.preventDefault(),Cn.click());return}const ot=sWe(I);if(ot!==null){const Cn=iWe(pe);if(Cn===null)return;Fe(Cn)?(I.preventDefault(),_u(Cn,ot,!0)):co.includes(Cn)||si(nWe(Ta(Cn)));return}if(pe===_.current){const Cn=()=>I.currentTarget.querySelector('[data-sidebar-region="chats"] [data-chat-row]');if(I.key==="ArrowDown"){const vs=Cn();vs&&(I.preventDefault(),vs.focus(),Np(vs));return}if(I.key==="Escape"){br(""),ms(!1);const vs=Cn();vs?(vs.focus(),Np(vs)):pe.blur()}return}if(I.key.length===1&&I.key!==" "&&!I.metaKey&&!I.ctrlKey&&!I.altKey&&pe.hasAttribute("data-chat-row")){I.preventDefault(),ms(!0),br(Cn=>Cn+I.key),window.requestAnimationFrame(()=>_.current?.focus());return}if(I.key==="Escape"){I.preventDefault(),ir&&_.current?.focus();return}if(I.key==="ArrowUp"&&pe.hasAttribute("data-entity-name")){const Cn=pe.closest("[data-entity]"),vs=Cn?.closest("section");if(Cn&&vs&&vs.querySelector("[data-entity]")===Cn){const Yn=vs.querySelector("[data-roster-filter]");if(Yn){I.preventDefault(),Yn.focus();return}}}const mt=[...I.currentTarget.querySelectorAll("[data-chat-row]")].filter(Cn=>!Cn.disabled),Ct=mt.indexOf(pe),on=I.key==="ArrowDown"?Math.min(mt.length-1,Ct+1):I.key==="ArrowUp"?Math.max(0,Ct-1):I.key==="Home"?0:I.key==="End"?mt.length-1:-1;if(on>=0){I.preventDefault();const Cn=mt[on];Cn?.focus(),Cn!==void 0&&Np(Cn);return}const Hn=pe.closest("[data-entity]"),xn=Hn?.querySelector("[data-disclosure]");I.key==="ArrowRight"&&xn&&(I.preventDefault(),xn.getAttribute("aria-expanded")==="false"?xn.click():Hn?.querySelector("[data-child]")?.focus()),I.key==="ArrowLeft"&&xn&&(I.preventDefault(),pe.hasAttribute("data-child")?Hn?.querySelector("[data-entity-name]")?.focus():xn.getAttribute("aria-expanded")==="true"&&xn.click())},ch=g.useRef(null),BA=g.useRef({node:null,index:-1,visibility:"outside",clipHeight:0}),jA=g.useRef({node:null,index:-1,visibility:"outside",clipHeight:0}),P$=g.useCallback(I=>{ch.current=I,xe.current=I},[]);g.useLayoutEffect(()=>{HL(ch.current,BA),HL(xe.current,jA)}),g.useEffect(()=>{const I=uy.current;if(I===null)return;uy.current=null;const pe=ch.current;if(pe===null)return;const Ve=pe.querySelector(`[data-chat-section="${CSS.escape(I.key)}"]`),ot=Ve?.closest("section")??null,mt=ot===null?[]:[...ot.querySelectorAll("[data-entity]")],on=(Ip[I.key]??BF)>I.at?mt[I.at]??null:null;(on?.querySelector("[data-chat-row]")??on??Ve??null)?.focus()},[Ip]);const il=g.useRef(null),I$=g.useRef(null),N$=z,M$=c.jsxs("div",{id:d$e,"data-sidebar-region":"entities",className:T("relative space-y-4"),children:[a.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:"Connecting to chats…"}),a.error&&!C&&!k&&c.jsxs("div",{className:"space-y-1 text-meta text-ink-muted",children:[c.jsxs("p",{children:[a.error.message,P?" Showing the last chats loaded.":""]}),c.jsx("button",{type:"button",className:"underline",onClick:()=>void a.refetch(),children:"Retry refresh"})]}),ne&&!C&&c.jsxs("div",{className:"space-y-1 text-meta text-ink-muted",children:[c.jsx("p",{children:ne}),c.jsx("button",{type:"button",className:"underline",onClick:()=>void a.refetch(),children:"Retry refresh"})]}),z&&c.jsxs("div",{className:"pb-2",children:[mg(Dt,"agents")&&c.jsxs("section",{children:[DA("agents","Agents",!0,void 0,Uo,void 0,void 0,AA("agent")),(Ot||_e("agents",!0))&&c.jsxs(c.Fragment,{children:[fe.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:"Loading agents…"}),FA("agent"),ay&&c.jsxs("div",{className:"relative mt-1 mb-2",children:[c.jsx("input",{ref:Rs,"data-roster-filter":!0,"aria-label":"Filter agents",placeholder:"Filter agents",className:"h-8 w-full rounded-md bg-row-hover pr-9 pl-2 text-body-sm",value:is,onChange:I=>Ie(I.target.value),onKeyDown:I=>{if(I.key==="Escape"){I.preventDefault(),I.stopPropagation(),is&&vy(Rs.current,Ie);return}if(I.key==="ArrowDown"){I.preventDefault(),I.stopPropagation(),il.current?.querySelector("[data-agent-pin]")?.closest("[data-entity]")?.querySelector("[data-entity-name]")?.focus();return}(I.key==="ArrowUp"||I.key==="Home"||I.key==="End")&&I.stopPropagation()}}),is&&c.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 right-1 -translate-y-1/2 focus-visible:outline-offset-[-2px]!",onClick:()=>vy(Rs.current,Ie),"aria-label":"Clear agent filter",children:c.jsx(Dn,{"aria-hidden":"true"})})]}),!ee&&c.jsxs("div",{className:T(q?"flex flex-col gap-2 px-3 py-2":"contents"),"data-testid":q?"agents-sidebar-empty":void 0,children:[c.jsx("div",{className:"contents",children:q?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("p",{className:"text-body-sm text-ink",children:"No agents yet"}),Te&&!de&&c.jsx(ce,{variant:"ghost",size:"icon-sm","data-testid":"agents-offer-dismiss","aria-label":"Dismiss built-in agents suggestion",onClick:()=>{Ue.current=!0,B(be)},children:c.jsx(Dn,{"aria-hidden":"true"})})]}),le.length>0&&c.jsx("p",{className:"text-meta text-ink-muted",children:y$e(le)})]}):ay&&is.trim()?CA.length>0?CA.map(I=>cy("agent",I.name,I.id)):c.jsx("p",{className:"text-meta text-ink-muted",children:"No agents match"}):MA("agents",iy.map(I=>cy("agent",I.name,I.id)))}),c.jsx(P9e,{builtins:le,presentation:q?"primary":"row",onBusyChange:De})]}),c.jsxs("button",{ref:Se,type:"button",className:T(dg,"w-full text-ink-muted"),onClick:()=>s("/agents?create=agent"),children:[c.jsx(Kc,{className:"size-4"}),"Create agent"]})]})]}),mg(Dt,"teams")&&c.jsxs("section",{className:hZ(mg(Dt,"agents")&&(!!Ot||_e("agents",!0))),children:[DA("teams","Teams",!0,void 0,Og,void 0,void 0,AA("team")),(Ot||_e("teams",!0))&&c.jsxs(c.Fragment,{children:[ge.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:"Loading teams…"}),FA("team"),ge.data&&MA("teams",ge.data.map(I=>cy("team",I.name))),c.jsxs("button",{type:"button",className:T(dg,"w-full text-ink-muted"),onClick:()=>s("/agents?create=team"),children:[c.jsx(Kc,{className:"size-4"}),"Create team"]})]})]})]})]},"entities"),O$=G?c.jsxs("p",{ref:I$,className:"pb-2 text-meta text-warning",children:["Could not ",G.pinned?"pin":"unpin"," “",G.title,"”.",G.detail?` ${G.detail}`:""," ",c.jsx("button",{type:"button",className:"underline",onClick:()=>void O(G.sessionId,G.pinned),children:"Retry"})]}):null,L$=c.jsxs("div",{"data-sidebar-region":"chats",onPointerMove:I=>{const pe=ze.current;pe!==null&&Math.hypot(I.clientX-pe.x,I.clientY-pe.y)>at&&(ze.current=null),YVe(Jo.current,{x:I.clientX,y:I.clientY})&&(Jo.current=null)},onPointerLeave:()=>{ze.current=null,Jo.current=null},className:T("relative space-y-4"),children:[bA&&c.jsxs("section",{"data-chat-section":"current",children:[lh("Current chat"),Dp(bA)]}),ry.length>0&&!Ot.trim()&&c.jsxs("section",{"data-chat-section":"drafts",children:[ry.map(I=>{const pe=I.key===An;return c.jsxs("div",{className:T(R1,"group",!pe&&"hover:bg-row-hover",pe&&yo),children:[c.jsxs("button",{type:"button","data-chat-row":!0,"data-draft-row":I.key,"aria-label":`Open ${I.label}`,title:I.label,onClick:()=>{ks(I.key),s("/chat")},className:T(dg,"min-w-0 flex-1 text-left",pe&&yo),children:[c.jsx(qw,{className:"size-4 shrink-0 text-ink-dim","aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:I.label})]}),I.pending&&c.jsx("span",{id:WL(I.key),className:"sr-only",children:VL}),c.jsx("button",{type:"button","data-draft-discard":I.key,"aria-disabled":I.pending,"aria-describedby":I.pending?WL(I.key):void 0,"aria-label":ML(I.label),title:I.pending?VL:ML(I.label),onClick:Ve=>{if(I.pending){Ve.preventDefault();return}if(pt(Ve.detail===0?null:{x:Ve.clientX,y:Ve.clientY},I.key))return;const ot=[...il.current?.querySelectorAll("[data-draft-row]")??[]].map(Ct=>Ct.getAttribute("data-draft-row")??""),mt=wWe(ot,I.key);js(I.key),An===I.key?(n(void 0,!0),so(Ce.getState().activeDraftKey)):so(null),requestAnimationFrame(()=>{const Ct=[...il.current?.querySelectorAll("[data-draft-row]")??[]];(Ct[Math.min(Math.max(mt,0),Ct.length-1)]??il.current?.querySelector("[data-chat-row]"))?.focus()})},className:T("size-6 shrink-0 items-center justify-center rounded-md","hidden text-ink-dim group-hover:flex group-hover:text-ink-muted","group-focus-within:flex group-focus-within:text-ink-muted hover:text-ink!","aria-disabled:cursor-default aria-disabled:text-ink-disabled!","aria-disabled:hover:text-ink-disabled!"),children:c.jsx(P0,{className:"size-4","aria-hidden":"true"})})]},I.key)}),c.jsxs("div",{className:"flex justify-end pt-1",children:[c.jsx("button",{type:"button","data-chat-row":!0,"data-drafts-clear-all":!0,"aria-disabled":ah.length===0,"aria-describedby":ah.length===0?zL:void 0,"aria-label":"Clear all drafts",title:ah.length===0?$L:"Clear all drafts",onClick:I=>{if(ah.length===0){I.preventDefault();return}const pe=I.currentTarget;if(pt(I.detail===0?null:{x:I.clientX,y:I.clientY},"drafts:clear-all"))return;const Ve=[...il.current?.querySelectorAll("[data-chat-row]")??[]].indexOf(pe),ot=ah.map(mt=>mt.key);sr(ot),An!==null&&ot.includes(An)?(n(void 0,!0),so(Ce.getState().activeDraftKey)):so(null),requestAnimationFrame(()=>{const mt=[...il.current?.querySelectorAll("[data-chat-row]")??[]];mt[Math.min(Math.max(Ve,0),mt.length-1)]?.focus()})},className:T("flex h-7 items-center rounded-md px-2 text-body-sm","text-ink-dim transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2","aria-disabled:cursor-default aria-disabled:text-ink-disabled!","aria-disabled:hover:bg-transparent! aria-disabled:hover:text-ink-disabled!"),children:"Clear all"}),ah.length===0&&c.jsx("span",{id:zL,className:"sr-only",children:$L})]})]}),Dt.groupBy!=="section"&&(fZ([...lo,...xA],Dt.groupBy)??[]).map(I=>c.jsxs("section",{"data-chat-section":I.key,children:[I.label?lh(I.label):null,I.rows.map(pe=>Dp(pe))]},I.key)),E&&c.jsx("span",{className:"sr-only","aria-live":"polite","data-sidebar-pin-order-announcement":!0,children:ni}),w$&&Dt.groupBy==="section"&&lo.length>0&&c.jsxs("section",{ref:bt,"data-chat-section":"pinned",className:"relative",children:[lh("Pinned"),uo.map(I=>Dp(I)),Fn!==null&&c.jsx("div",{ref:Kt,"aria-hidden":"true","data-session-pin-indicator":"",className:"pointer-events-none absolute right-1 left-1 h-0.5 rounded-full bg-accent"})]}),Dt.groupBy==="section"&&wA.map(I=>{const pe=oh[I];return I==="running"&&pe.length===0&&rt?c.jsxs("section",{children:[lh(VF[I]),c.jsx("p",{className:"px-2 text-meta text-ink-dim",children:rt?"The daemon could not read which chats are running, so this list may be incomplete.":"Nothing running right now."})]},I):pe.length===0?null:c.jsxs("section",{"data-chat-section":I,children:[lh(VF[I],I===C$?or:void 0),pe.map(Ve=>Dp(Ve))]},I)}),!Ot.trim()&&(rl.remaining>0||v$)&&c.jsx("button",{type:"button","data-sidebar-page-more":!0,onClick:b$,className:"flex h-7 w-full items-center rounded-md px-2 text-left text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:pZ(Dt.loads,rl.remaining>0?gZ(vA,Dt.loads,rl.remaining):m$)}),ac,Cu!==null&&c.jsx("span",{className:"sr-only","aria-live":"polite",children:Cu}),!d.length&&!Hs.length&&!At&&!Ot.trim()&&(L===null||L.total===0)&&c.jsx("p",{className:"text-meta text-ink-muted",children:"No chats yet. Choose an agent, team or New chat."}),bu!==null&&c.jsx("p",{className:"text-meta text-ink-muted",children:bu}),sn&&!R&&c.jsx("p",{className:"text-meta text-ink-muted",children:"Showing up to 500 chats. Older chats remain available in the terminal."}),o.available&&o.reported&&!o.connected&&!h&&!C&&c.jsx("p",{className:T("text-meta",d.some(I=>I.active)?"text-ink-dim":"text-warning"),children:"Not connected to the backend — showing the last known state."})]},"chats");return c.jsx("nav",{ref:il,"aria-label":"Chats","data-chat-region":"sidebar",tabIndex:-1,onFocus:R$,"data-glass-region":"sidebar",className:"relative flex h-full min-h-0 flex-col bg-surface p-2 text-ink",onKeyDown:D$,children:c.jsxs(NJ,{children:[z&&c.jsxs("div",{"data-sidebar-band":!0,className:"mb-2 flex h-7 shrink-0 items-center justify-end gap-0.5",children:[c.jsx(Je,{content:"Search chats and agents",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-search":!0,"aria-label":"Search chats and agents",onClick:()=>{ms(!0),window.requestAnimationFrame(()=>_.current?.focus())},children:c.jsx(xd,{"aria-hidden":"true"})})}),c.jsxs(Dm,{open:W,onOpenChange:Y,children:[c.jsx(Je,{content:"View options",children:c.jsx(oS,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-options":!0,"aria-label":"View options","aria-expanded":W,className:T(x$&&"bg-row-selected text-ink hover:bg-row-selected"),children:c.jsx(Nf,{"aria-hidden":"true"})})})}),c.jsx(Rf,{align:"end",className:"max-h-[calc(var(--radix-popover-content-available-height)_-_16px)] w-60 overflow-y-auto p-2","data-sidebar-view-panel":!0,children:c.jsx($We,{view:Dt,counts:y$,onView:Ze})})]}),c.jsxs(Dm,{open:Q,onOpenChange:Z,children:[c.jsx(Je,{content:"New agent or team",children:c.jsx(oS,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-create":!0,"aria-label":"New agent or team","aria-expanded":Q,children:c.jsx(gse,{"aria-hidden":"true"})})})}),c.jsxs(Rf,{align:"end",className:"w-44 p-1","data-sidebar-create-panel":!0,children:[c.jsxs("button",{type:"button","data-sidebar-create-agent":!0,onClick:()=>{Z(!1),s("/agents?create=agent")},className:"flex h-7 w-full items-center gap-2 rounded-md px-1 text-left text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:[c.jsx(Yre,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:"New agent"})]}),c.jsxs("button",{type:"button","data-sidebar-create-team":!0,onClick:()=>{Z(!1),s("/agents?create=team")},className:"flex h-7 w-full items-center gap-2 rounded-md px-1 text-left text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:[c.jsx(Og,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:"New team"})]})]})]}),c.jsx(Je,{content:"Open agent…",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-open-agent":!0,"aria-label":"Open agent…",onClick:()=>{H(),K(CVe)},children:c.jsx(One,{"aria-hidden":"true"})})})]}),c.jsxs("div",{className:T("relative mb-2",!ir&&"hidden"),children:[c.jsx("input",{ref:_,"aria-label":"Search chats and agents",placeholder:"Filter chats and agents",className:"h-8 w-full rounded-md bg-row-hover pr-9 pl-2 text-body-sm",value:Ot,onChange:I=>br(I.target.value),onBlur:()=>{Ot||ms(!1)}}),Ot&&c.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 right-1 -translate-y-1/2 focus-visible:outline-offset-[-2px]!",onClick:()=>vy(_.current,br),"aria-label":"Clear search",children:c.jsx(Dn,{"aria-hidden":"true"})})]}),As&&Ot.trim()&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(MJ,{id:qL,checked:gu,onCheckedChange:I=>Ep(I===!0)}),c.jsx(nr,{htmlFor:qL,className:"text-meta text-ink-muted",children:"Include archived"})]}),Vi&&p&&c.jsxs("p",{className:"pb-2 text-meta text-ink-muted",children:["Search terms are limited to ",lC," characters. This one is longer, so only chat names are being searched."]}),Ot&&p&&!tc&&!Vi&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:"Searching chat names only. Update Local Operator to search inside conversations."}),Ot&&tc&&lr.isError&&c.jsxs("p",{className:"pb-2 text-meta text-ink-muted",children:["Conversation search is unavailable, so these are name matches."," ",c.jsx(ce,{variant:"link",size:"sm",type:"button",onClick:()=>void lr.refetch(),children:"Retry"})]}),Ot.trim()&&z&&!Hs.length&&Fp&&c.jsxs("p",{className:"pb-2 text-meta text-ink-muted",children:["Nothing in your chats matches “",Ot.trim(),"”."]}),RA&&kL(TA?.rows.length??0,Hs.length)&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:"Searching conversations…"}),c.jsx("p",{"aria-live":"polite",className:"sr-only",children:RA&&kL(TA?.rows.length??0,Hs.length)?"Searching conversations.":Ot.trim()&&z&&!Hs.length&&Fp?`Nothing in your chats matches ${Ot.trim()}.`:""}),c.jsxs("div",{ref:P$,id:h$e,tabIndex:-1,"data-sidebar-region":"scroller","data-lo-sidebar-edge-cues":!0,onScroll:()=>{UL(ch.current,BA),UL(xe.current,jA),ao()},className:"relative min-h-0 flex-1 space-y-4 overflow-y-auto p-1 [overflow-anchor:none] [scrollbar-gutter:stable]",children:[M$,O$,N$&&L$]}),(h||fe.error||ge.error)&&!C&&!k&&c.jsxs("div",{className:"pt-2 text-meta text-ink-muted",children:[c.jsx("p",{children:h||fe.error?.message||ge.error?.message}),c.jsx("button",{type:"button",className:"mt-1 underline",onClick:()=>{Sa(),fe.refetch(),ge.refetch()},children:"Retry refresh"})]})]})})}const mb={recent:()=>x("ui.canvas.files.recent"),name:()=>x("ui.canvas.files.name"),kind:()=>x("ui.canvas.files.kind"),modified:()=>x("ui.canvas.files.modified"),created:()=>x("ui.canvas.files.created"),size:()=>x("ui.canvas.files.size")},E$e={Highlights:()=>x("ui.canvas.files.highlights"),"Working files":()=>x("ui.canvas.files.working"),Images:()=>x("ui.canvas.files.images"),Videos:()=>x("ui.canvas.files.videos"),Documents:()=>x("ui.canvas.files.documents"),Spreadsheets:()=>x("ui.canvas.files.spreadsheets"),Other:()=>x("ui.canvas.files.other"),Files:()=>x("ui.canvas.files.files")},A1=e=>{switch(e){case"images":return x("ui.canvas.files.images");case"video":return x("ui.canvas.files.videos");case"documents":return x("ui.canvas.files.documents");case"spreadsheets":return x("ui.canvas.files.spreadsheets");case"audio":return x("ui.canvas.files.audio");case"code":return x("ui.canvas.files.code");case"presentations":return x("ui.canvas.files.presentations");case"archives":return x("ui.canvas.files.archives");default:return x("ui.canvas.files.other")}},k$e="pointer-events-none absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity duration-fast ease-out-quart group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 has-[[aria-expanded=true]]:pointer-events-auto has-[[aria-expanded=true]]:opacity-100";function T$e({conversationId:e,items:t,index:n,cwd:s,onOpen:r,materialise:i,legacyScan:a}){const o=ls(ie=>ie.conversations[e]?.selectedTabId),[l,u]=g.useState(t),[d,h]=g.useState(!1),f=qe(ie=>ie.finderFiles),p=qe(ie=>ie.setFinderFiles),[m,v]=g.useState(""),b=g.useMemo(()=>new Set(f.closedSections),[f.closedSections]),[w,C]=g.useState(null),y=g.useRef(!1),[k,_]=g.useState({width:400,height:700,top:0}),E=g.useRef(null),R=g.useRef(null),F=g.useRef(new Map),A=g.useRef(new Map),[N,M]=g.useState(null),D=g.useRef(null);g.useEffect(()=>{n.localReadAllowed===!1?(u([]),M(null)):(!d||l.length===0)&&N===null&&u(t)},[t,d,N,n.localReadAllowed,l.length]);const[L,V]=g.useState(),[j,te]=g.useState(!1),X=g.useRef({text:"",at:0}),re=n.localReadAllowed===!1?[]:l,G=!!(m.trim()||f.kinds.length),J=g.useMemo(()=>{const ie=new Set(S9e(re.map(Te=>Te.row),{query:m,kinds:f.kinds}).map(Te=>Te.document.id));return SZ(re.filter(Te=>ie.has(Te.row.document.id)),f)},[re,m,f]),ae=g.useMemo(()=>EZ(J,f,G,b),[J,f,G,b]),O=g.useMemo(()=>kZ(ae,k.width,f.group),[ae,k.width,f.group]);g.useEffect(()=>{y.current&&w&&O.positions.has(w)&&document.activeElement===document.body&&F.current.get(w)?.focus({preventScroll:!0})},[O,w]);const U=O.bands.find(ie=>ie.items.length)?.items[0]?.row.document.id??null,P=w?.startsWith("header:")||w&&O.positions.has(w)?w:O.bands.find(ie=>ie.items.length)?.items[0]?.row.document.id??(ae[0]?`header:${ae[0].id}`:null),z=g.useMemo(()=>new Set(TZ(O,k.top,k.height,P)),[O,k.top,k.height,P]),ne=g.useMemo(()=>J.filter(ie=>ie.row.media==="image"&&O.positions.has(ie.row.document.id)),[J,O]),fe=ne.find(ie=>ie.row.document.id===N);g.useEffect(()=>{if(!fe){V(void 0),te(!1);return}let ie=!0,Te;return V(void 0),hB(fe.row.document).then(async ee=>{ie&&(Te=wY(await ee.arrayBuffer(),ee.type),ie?V(Te):oF(Te))}).catch(()=>{ie&&(V(void 0),te(!0))}),()=>{ie=!1,Te&&oF(Te)}},[fe]),g.useEffect(()=>{const ie=E.current;if(!ie)return;const Te=()=>_(de=>({...de,width:ie.clientWidth,height:ie.clientHeight}));Te();const ee=new ResizeObserver(Te);return ee.observe(ie),()=>ee.disconnect()},[]);const ue=g.useCallback(ie=>{const Te=O.positions.get(ie),ee=E.current;if(!Te||!ee)return;const de=O.bands[Te.band];de.top<ee.scrollTop?ee.scrollTop=de.top:de.top+de.height>ee.scrollTop+ee.clientHeight&&(ee.scrollTop=de.top+de.height-ee.clientHeight),C(ie),_(De=>({...De,top:ee.scrollTop})),requestAnimationFrame(()=>F.current.get(ie)?.focus())},[O]),le=(ie,Te)=>{if(ie.target===ie.currentTarget){if(ie.key==="Escape"&&(m||f.kinds.length)){ie.preventDefault(),ie.stopPropagation(),v(""),p({kinds:[]});return}if(ie.key==="/"){ie.preventDefault(),R.current?.focus();return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(ie.key)){ie.preventDefault();const ee=O.positions.get(Te.row.document.id);if(ee&&["ArrowUp","ArrowDown"].includes(ie.key)){const De=O.bands[ee.band+(ie.key==="ArrowUp"?-1:1)];if(De?.kind==="header"){ie.preventDefault(),C(`header:${De.section.id}`),A.current.get(De.section.id)?.focus();return}}const de=RZ(O,Te.row.document.id,ie.key,k.height);de&&ue(de);return}if(ie.key.length===1&&!ie.ctrlKey&&!ie.metaKey&&ie.key!==" "){const ee=Date.now(),de=(ee-X.current.at<500?X.current.text:"")+ie.key.toLocaleLowerCase();X.current={text:de,at:ee};const De=J.findIndex(Ue=>Ue.row.document.id===Te.row.document.id);for(let Ue=1;Ue<=J.length;Ue++){const Se=J[(De+Ue)%J.length];if(O.positions.has(Se.row.document.id)&&Qh(Se.row.name).startsWith(Qh(de))){ie.preventDefault(),ue(Se.row.document.id);break}}}}},q=ie=>{if(ie==="Working files"){G||p({workingOpen:!f.workingOpen});return}if(G)return;const Te=new Set(b);Te.has(ie)?Te.delete(ie):Te.add(ie),p({closedSections:[...Te]})},we=()=>{v(""),p({kinds:[]}),R.current?.focus()},B=g.useRef(null);g.useEffect(()=>()=>{B.current!==null&&cancelAnimationFrame(B.current)},[]);const be=()=>{B.current===null&&(B.current=requestAnimationFrame(()=>{B.current=null;const ie=E.current;ie&&_(Te=>({...Te,top:ie.scrollTop}))}))};return c.jsxs("div",{onKeyDownCapture:ie=>{const Te=ie.target;ie.key==="/"&&!ie.ctrlKey&&!ie.metaKey&&Te instanceof HTMLElement&&!Te.closest("input,textarea,[contenteditable=true]")&&(ie.preventDefault(),ie.stopPropagation(),R.current?.focus())},className:T("@container/fileslist flex min-h-0 flex-1 flex-col"),children:[c.jsxs("div",{className:T("shrink-0 space-y-1 px-2 py-2"),"data-tour-tag":"files-scanner-head",children:[c.jsxs("div",{className:T("flex items-center gap-2"),children:[c.jsx(ps,{ref:R,value:m,placeholder:x("ui.canvas.files.searchPlaceholder"),"aria-label":x("ui.canvas.files.search"),className:T("min-w-0 flex-1"),onChange:ie=>v(ie.target.value),onKeyDown:ie=>{ie.key==="ArrowDown"||ie.key==="Escape"&&!m&&!f.kinds.length?(ie.preventDefault(),ie.stopPropagation(),U&&ue(U)):ie.key==="Escape"&&(ie.preventDefault(),ie.stopPropagation(),v(""),p({kinds:[]}))}}),c.jsxs(Il,{children:[c.jsx(Ho,{asChild:!0,children:c.jsxs(ce,{variant:"outline",size:"md","aria-label":`${x("ui.canvas.files.sort")}: ${mb[f.sort]()}, ${f.order==="asc"?x("ui.canvas.files.asc"):x("ui.canvas.files.desc")}`,children:[c.jsx(Pne,{"aria-hidden":"true"}),c.jsx("span",{className:"hidden @min-[440px]/fileslist:inline",children:mb[f.sort]()}),c.jsx("span",{"aria-hidden":"true",children:f.order==="asc"?"↑":"↓"})]})}),c.jsxs(Nl,{align:"end",children:[Object.keys(mb).map(ie=>c.jsx(Gp,{checked:f.sort===ie,onCheckedChange:()=>p({sort:ie,order:["modified","created","size"].includes(ie)?"desc":"asc"}),children:mb[ie]()},ie)),c.jsx(Yr,{}),c.jsx(Gp,{checked:f.order==="asc",onCheckedChange:()=>p({order:"asc"}),children:x("ui.canvas.files.asc")}),c.jsx(Gp,{checked:f.order==="desc",onCheckedChange:()=>p({order:"desc"}),children:x("ui.canvas.files.desc")}),c.jsx(Yr,{}),c.jsx(Gp,{checked:f.group,onCheckedChange:ie=>p({group:ie}),children:x("ui.canvas.files.group")})]})]}),c.jsxs(Il,{children:[c.jsx(Ho,{asChild:!0,children:c.jsxs(ce,{variant:"outline",size:"md",className:T(f.kinds.length>0&&"bg-accent-wash"),"aria-label":`${x("ui.canvas.files.filter")}: ${f.kinds.map(A1).join(", ")||x("ui.canvas.files.files")}`,children:[c.jsx(vse,{"aria-hidden":"true"}),f.kinds.length?`${f.kinds.length}`:x("ui.canvas.files.filter")]})}),c.jsxs(Nl,{align:"end",children:[b9e.map(ie=>c.jsx(Gp,{checked:f.kinds.includes(ie.id),onCheckedChange:Te=>p({kinds:Te?[...f.kinds,ie.id]:f.kinds.filter(ee=>ee!==ie.id)}),children:A1(ie.id)},ie.id)),c.jsx(Yr,{}),c.jsx(Gt,{onSelect:()=>p({kinds:[]}),children:x("ui.canvas.files.reset")})]})]})]}),c.jsxs("div",{className:T("flex min-h-7 items-center justify-between gap-2 text-meta text-ink-dim"),children:[c.jsxs("span",{children:[n.mode==="index"&&n.state!=="ready"&&!t.length?"":G?x("ui.canvas.files.narrowCount",{shown:Ah(J.length),total:Ah(t.length)}):x("ui.canvas.files.count",{count:n.mode==="index"?n.total:t.length}),n.mode==="index"&&(n.state==="loading"||n.state==="building")&&n.pendingTotal>0?`${t.length?" · ":""}${x("ui.canvas.files.progress",{loaded:Ah(n.loadedRows),total:Ah(n.pendingTotal)})}`:"",n.state==="loading"&&t.length>0?` · ${x("ui.canvas.files.loading")}`:n.state==="building"?` · ${x("ui.canvas.files.building")}`:n.statComplete?"":` · ${x("ui.canvas.files.readingStats")}`]}),s&&c.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>void CY(s),children:[c.jsx(zw,{"aria-hidden":"true"}),x("ui.canvas.files.folder")]})]}),f.kinds.length>0&&c.jsxs("div",{className:T("flex items-center gap-2 text-meta text-ink-muted"),children:[c.jsx("span",{children:f.kinds.map(A1).join(", ")}),c.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>p({kinds:[]}),children:[c.jsx(Dn,{"aria-hidden":"true"}),x("ui.canvas.files.reset")]})]}),n.error&&J.length>0&&c.jsxs("output",{className:T("text-body-sm text-ink-muted"),children:[n.error,c.jsx(ce,{variant:"ghost",size:"sm",onClick:n.refresh,children:n.state==="building"?x("ui.canvas.files.continue"):x("ui.canvas.files.retry")})]})]}),c.jsx("section",{ref:E,"aria-label":x("ui.canvas.files.region"),"data-tour-tag":"files-scroller",className:T("min-h-0 flex-1 overflow-auto bg-surface px-2 pb-2"),onScroll:be,onKeyDown:ie=>{!ie.defaultPrevented&&ie.key==="Escape"&&(m||f.kinds.length)&&(ie.preventDefault(),ie.stopPropagation(),v(""),p({kinds:[]}))},onPointerEnter:()=>h(!0),onPointerLeave:()=>{E.current?.contains(document.activeElement)||h(!1)},onFocusCapture:()=>{y.current=!0,h(!0)},onBlurCapture:ie=>{ie.relatedTarget&&!ie.currentTarget.contains(ie.relatedTarget)&&(y.current=!1,h(!1))},children:J.length?ae.map(ie=>{const Te=O.bands.map((Ue,Se)=>Ue.section.id===ie.id?Se:-1).filter(Ue=>Ue>=0),ee=O.bands[Te[0]],de=O.bands[Te.at(-1)??0],De=de.top+de.height-ee.top-32;return c.jsxs("section",{style:{height:De+32},children:[c.jsx("h3",{className:T("sticky top-0 z-10 h-8 bg-surface"),children:c.jsxs("button",{type:"button",ref:Ue=>{Ue?A.current.set(ie.id,Ue):A.current.delete(ie.id)},tabIndex:P===`header:${ie.id}`?0:-1,onFocus:()=>C(`header:${ie.id}`),onKeyDown:Ue=>{if(Ue.key==="ArrowRight"&&!ie.open||Ue.key==="ArrowLeft"&&ie.open)Ue.preventDefault(),q(ie.id);else if(Ue.key==="ArrowDown"||Ue.key==="ArrowUp")if(Ue.preventDefault(),Ue.key==="ArrowDown"&&ie.open&&ie.items.length)ue(ie.items[0].row.document.id);else{const Se=ae[ae.indexOf(ie)+(Ue.key==="ArrowDown"?1:-1)];Se&&(C(`header:${Se.id}`),A.current.get(Se.id)?.focus())}},"aria-expanded":ie.open,"aria-disabled":G,onClick:()=>q(ie.id),className:T("flex h-8 w-full items-center gap-2 rounded-sm px-2 text-left font-medium text-body-sm text-ink hover:bg-row-hover",G&&"cursor-default hover:bg-surface",ie.id!=="Working files"&&!ie.highlights&&ae.some(Ue=>Ue.id==="Working files")&&"pl-4"),children:[ie.open?c.jsx(pi,{size:14,"aria-hidden":"true"}):c.jsx(ga,{size:14,"aria-hidden":"true"}),E$e[ie.id]?.()??ie.label,c.jsx("span",{className:T("text-meta text-ink-dim"),children:Ah(ie.items.length||(ie.id==="Working files"?J.filter(Ue=>!Ue.highlighted).length:0))})]})}),c.jsx("ul",{"data-tour-tag":"files-grid",className:T("relative"),style:{height:De},children:Te.filter(Ue=>O.bands[Ue].kind!=="header"&&z.has(Ue)).map(Ue=>{const Se=O.bands[Ue];return c.jsx("li",{style:{position:"absolute",top:Se.top-ee.top-32,height:Se.height,left:0,right:0},children:c.jsx("div",{className:T("grid gap-1"),style:{gridTemplateColumns:`repeat(${Se.cols},minmax(0,1fr))`},children:Se.items.map(ge=>c.jsx(R$e,{item:ge,current:o===ge.row.document.id||o===ge.row.document.path,band:Se,tabIndex:ge.row.document.id===P?0:-1,onFocus:()=>C(ge.row.document.id),buttonRef:Ae=>{Ae?F.current.set(ge.row.document.id,Ae):F.current.delete(ge.row.document.id)},onKeyDown:Ae=>le(Ae,ge),onOpen:()=>r(ge.row.document),onExpand:()=>{D.current=F.current.get(ge.row.document.id)??null,M(ge.row.document.id)},materialise:()=>i(ge.row.document)},ge.row.document.id))})},Se.items[0].row.document.id)})})]},ie.id)}):c.jsxs("div",{className:T("flex min-h-40 flex-col items-center justify-center gap-2 p-4 text-center"),children:[c.jsx("p",{className:T("text-heading text-ink"),children:n.state==="error"?n.error??x("ui.canvas.files.error"):n.state==="unsupported"?n.error??x("ui.canvas.files.remote"):n.state==="loading"?x("ui.canvas.files.loading"):n.state==="building"?x("ui.canvas.files.building"):G?x("ui.canvas.files.noMatch"):x("ui.canvas.files.empty")}),n.state==="ready"&&!G&&c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:x("ui.canvas.files.emptyDetail")}),n.error&&c.jsx(ce,{variant:"outline",size:"sm",onClick:n.refresh,children:n.state==="building"?x("ui.canvas.files.continue"):x("ui.canvas.files.retry")}),G&&c.jsx(ce,{variant:"outline",size:"sm",onClick:we,children:x("ui.canvas.files.clear")})]})}),n.mode==="fallback"&&a?.stopped&&c.jsx(ce,{variant:"ghost",size:"sm",onClick:a.resume,children:x("ui.canvas.files.earlier")}),fe&&c.jsx(yY,{open:!0,src:L,pending:!L&&!j,fallback:c.jsx("span",{className:T("text-body-sm text-ink-muted"),children:x("ui.canvas.files.unreadable")}),label:fe.row.name,onOpenChange:ie=>{ie||M(null)},restoreFocusTo:D,group:{index:ne.indexOf(fe),count:ne.length,onPrev:()=>M(ne[(ne.indexOf(fe)+ne.length-1)%ne.length].row.document.id),onNext:()=>M(ne[(ne.indexOf(fe)+1)%ne.length].row.document.id)}})]})}function R$e({item:e,current:t,band:n,tabIndex:s,onFocus:r,buttonRef:i,onKeyDown:a,onOpen:o,onExpand:l,materialise:u}){const d=e.row.document,[h,f]=_Y("200px"),p=SY(d,f&&e.row.media==="image"&&!e.row.missing),[m,v]=g.useState(!1),b=g.useRef(null),w=n.kind==="tiles"||n.kind==="video",C=w?n.height-32:n.kind==="highlight"?40:28,y=d.artifact?fB({...d.artifact,title:d.title}):d.path,k=qe(F=>F.finderFiles.sort),_=k==="created"?e.created:e.modified,E=_===null?"":EY(_*1e3,{month:"short",day:"numeric"}),R=e.row.missing?d.artifact?x("ui.canvas.files.gone"):x("ui.canvas.files.missing"):k==="modified"||k==="created"?E:k==="size"?e.row.size??"":d.artifact?x("ui.canvas.files.sessionOnly"):e.row.size??"";return c.jsxs("div",{ref:h,className:T("group relative min-w-0 rounded-sm",t?yo:"hover:bg-row-hover"),"data-tour-tag":"file-row","data-file-id":d.id,onContextMenu:F=>{F.preventDefault(),v(!0)},children:[c.jsxs("button",{type:"button",ref:F=>{b.current=F,i(F)},tabIndex:s,onFocus:r,title:y,onClick:o,onKeyDown:F=>{F.shiftKey&&F.key==="F10"||F.key==="ContextMenu"?(F.preventDefault(),v(!0)):a(F)},className:T("w-full min-w-0 rounded-sm p-1 text-left",!w&&"flex items-center gap-2 pr-8",e.row.missing&&"text-ink-muted"),style:{height:n.height-(w?4:0)},children:[c.jsx("span",{style:{height:C,width:w?"100%":C},className:T("flex shrink-0 items-center justify-center overflow-hidden rounded-sm bg-media-surface",w&&"mb-1"),children:p.state==="ready"&&e.row.media==="image"?c.jsx("img",{src:p.url,alt:"",className:T("h-full w-full object-contain outline-1 -outline-offset-1 outline-hairline")}):d.type==="video"?c.jsxs("span",{className:T("flex flex-col items-center gap-1 text-ink-muted"),children:[c.jsx(hse,{"aria-hidden":"true"}),w&&c.jsx("span",{className:T("text-meta"),children:x("ui.canvas.files.play")})]}):p.state==="loading"&&e.row.media==="image"&&!e.row.missing?null:c.jsx($w,{size:16,"aria-hidden":"true"})}),c.jsxs("span",{className:T("flex min-w-0 flex-1 flex-col",w?"text-meta":"text-body-sm"),children:[c.jsxs("span",{className:T("flex min-w-0 items-center justify-between gap-2"),children:[c.jsx("span",{className:T("min-w-0 flex-1 truncate",e.row.missing?"text-ink-muted":"text-ink"),children:e.row.name}),!w&&e.row.showParent&&e.row.parent&&c.jsx("span",{className:T("min-w-0 shrink truncate text-mono-sm text-ink-dim"),children:e.row.parent}),c.jsx("span",{title:_===null?void 0:N4(_*1e3),className:T("shrink-0 text-meta text-ink-dim"),children:w&&d.artifact?x("ui.canvas.files.inSession"):R})]}),n.kind==="highlight"&&e.why&&c.jsx("span",{className:T("line-clamp-2 text-meta text-ink-muted"),children:e.why})]})]}),c.jsxs("div",{className:k$e,onKeyDown:F=>F.stopPropagation(),children:[w&&e.row.media==="image"&&c.jsx(Je,{content:`${x("ui.canvas.files.expand")}: ${d.title}`,children:c.jsx(ce,{variant:"ghost",size:"icon-sm",tabIndex:-1,className:T("bg-accent-wash"),"aria-label":`${x("ui.canvas.files.expand")}: ${d.title}`,onClick:l,children:c.jsx(kY,{"aria-hidden":"true"})})}),c.jsx(eC,{file:d.path,tooltip:e.row.media==="image"?x("ui.canvas.files.imageActions"):x("ui.canvas.files.fileActions"),label:d.title,open:m,onOpenChange:v,onCloseAutoFocus:F=>{F.preventDefault(),b.current?.focus({preventScroll:!0})},triggerTabIndex:-1,mediaKind:e.row.media==="image"?"image":"video",onShowInCanvas:rp(d.path,d.type)===null?void 0:o,onExpand:e.row.media==="image"?l:void 0,resolveBytes:()=>hB(d),saveName:d.artifact?tT(d.artifact):void 0,resolvePath:d.artifact&&!e.row.missing?u:void 0,missing:e.row.missing&&!d.artifact})]})]})}const ZL=[],A$e=({conversationId:e,sessionId:t,cwd:n,index:s,onSwitchToDocumentView:r,scan:i=null})=>{const a=ls(b=>b.conversations[e]?.mentionedFiles??ZL),o=g.useMemo(()=>s.mode==="index"?s.rows.map(b=>Lpe(b,t??"")):s.mode==="fallback"?a:ZL,[s.mode,s.rows,a,t]),l=ls(b=>b.setFiles),u=ls(b=>b.setOpenTabs),d=ls(b=>b.setSelectedTab),h=ls(b=>b.setViewMode),f=g.useMemo(()=>_9e(o),[o]),p=g.useCallback(async b=>{const w=b.title,C=N=>{const D=ls.getState().conversations?.[e],L=D?.files??[],V=D?.openTabs??[],j=L.findIndex(G=>G.id===N.id),te=j!==-1?[...L.slice(0,j),N,...L.slice(j+1)]:[...L,N];l(e,te);const re=V.some(G=>G.id===N.id)?V:[...V,{id:N.id,title:N.title}];u(e,re),d(e,N.id),h(e,"documents"),r(N.id)},y=N=>{N&&console.error("Error processing file:",N);try{b.path.startsWith("data:")?console.warn("Opening data URI with OS default is not directly supported here.",`${b.path.substring(0,50)}...`):window.api.openFile(b.path)}catch(M){console.error("Error opening file natively:",M)}},k=rp(b.path,b.type);if(b.artifact){C({...b,content:""});return}if(b.path.startsWith("data:")){if(k===null)return y();C(Ac(b.path,{title:w,content:b.path,type:Ef(w)}));return}const _=iB(b.path),E=typeof window.api?.probeFiles=="function"?(await window.api.probeFiles([_]))[0]??null:null,R=!!(E?.exists&&E.isFile);if(b.availability==="missing"&&!R&&E?.error===void 0){zt(`File no longer exists at ${E?.resolved??_}`,{description:"Copy its path from the row's ⋯ menu to look for it, or check whether the agent wrote it somewhere else."});return}if(k===null)return y();const F={title:w,type:Ef(_),lastAgentModified:E?.mtimeMs??b.lastAgentModified,readMtimeMs:E?.mtimeMs??void 0,availability:R?"present":void 0,sizeBytes:E?.sizeBytes??b.sizeBytes},A=Zw[k];if(A==="bytes"||A==="range"){C(Ac(_,F));return}try{const N=await window.api.readFile(_,A);if(!N.success){const M=N.error?N.error instanceof Error?N.error.message:String(N.error):"Unknown error reading file";return y(M)}C(Ac(_,{...F,content:N.data}))}catch(N){const M=N instanceof Error?N.message:String(N??"Unknown error reading file");return y(M)}},[e,l,u,d,h,r]),m=f.map((b,w)=>{const C=s.mode==="index"?s.rows[w]:void 0;return{row:b,highlighted:C?.highlighted??!1,why:C?.highlight_why??"",created:C?.created_at??null,modified:C?.modified_at??(b.document.lastAgentModified===void 0?null:b.document.lastAgentModified/1e3),mentioned:C?.first_ts??C?.first_seq??w}}),v=async b=>{if(!t||s.mode!=="index")throw new Error("No indexed artifact owner");const w=await V4({op:"sessions.files.materialise",sessionId:t,fileId:b.indexedFileId??b.id}),C=w.body.result;if(w.status!==200||!C?.path)throw new Error(x("ui.canvas.files.saveError"));return C.path};return c.jsx(T$e,{items:m,conversationId:e,index:s.mode==="fallback"?{...s,state:"ready"}:s,legacyScan:i,cwd:s.state==="unsupported"?void 0:n,materialise:v,onOpen:b=>{b.artifact&&b.type!=="image"&&b.type!=="video"?v(b).then(w=>p(Ac(w,{title:b.title,type:b.type}))).catch(()=>zt(x("ui.canvas.files.saveError"))):p(b)}})},F$e=g.memo(A$e),D$e=({entries:e,truncated:t,goalPresent:n})=>e.length===0&&!t?c.jsx(_k,{title:"No goals completed yet",description:n?"Goals appear here once they are finished.":"No goal set — /goal <text> to set one. Finished goals are kept here."}):c.jsxs("section",{className:T("flex min-h-0 flex-1 flex-col overflow-y-auto"),children:[c.jsxs("div",{className:T("flex items-baseline justify-between gap-2 px-3 pt-2 pb-1"),children:[c.jsx("span",{className:T("shrink-0 text-meta text-ink-muted"),children:"Goals"}),c.jsx("span",{className:T("min-w-0 flex-1 truncate text-right text-meta text-ink-dim"),children:t?`${e.length===1?"1 goal":`${e.length} goals`} shown`:e.length===1?"1 goal":`${e.length} goals`})]}),t&&c.jsx("p",{className:T("max-w-80 px-3 pb-1 text-meta text-ink-dim"),children:"Older settled goals are not carried here — this list is capped."}),c.jsx("ul",{className:T("flex flex-col pb-1.5"),children:e.map(s=>c.jsx(P$e,{entry:s},s.id))})]}),P$e=({entry:e})=>{const t=e.status==="done",n=t?pT:AT,s=I$e(e),r=!!(e.reason?.trim()||e.settled_at);return c.jsx("li",{className:T("flex flex-col"),children:c.jsx(np,{disabled:!r,rowClassName:T("h-6 rounded-sm px-3 py-0"),summaryAlign:"center",triggerLabel:`${e.text} — ${s}`,triggerTooltip:e.text,summary:c.jsxs("span",{className:T("flex min-w-0 flex-1 items-center gap-2"),children:[c.jsx("span",{"aria-hidden":!0,className:T("flex size-4 shrink-0 items-center justify-center text-ink-dim"),children:c.jsx(n,{className:T("size-4")})}),c.jsx("span",{className:T("min-w-0 flex-1 truncate text-body-sm leading-5",t&&"line-through text-ink-dim"),title:e.text,children:e.text}),c.jsx("span",{className:T("shrink-0 text-meta text-ink-dim"),title:s,children:s})]}),children:c.jsxs("div",{className:T("flex flex-col gap-1 px-3 pb-1.5"),children:[e.reason?.trim()&&c.jsx("span",{"aria-hidden":!0,className:T("line-clamp-2 text-ink-muted text-meta leading-4"),title:e.reason,children:e.reason}),e.reason?.trim()&&c.jsx("span",{className:T("sr-only"),children:e.reason}),e.settled_at&&c.jsx("span",{className:T("text-mono text-2xs text-ink-dim"),children:e.settled_at})]})})})},I$e=(e,t=new Date)=>{const n=TY(e.settled_at,t);return n?`${e.status} · ${n}`:e.status};function X2(e,t){const n=e.findIndex(s=>s.id===t);return n===-1?null:e[n+1]??e[n-1]??null}const kW="canvas-selected-tab",TW="canvas-document-panel",N$e=({documents:e,activeDocumentId:t,onChangeActiveDocument:n,onCloseDocument:s})=>{const r=g.useRef(new Map),i=g.useRef(null),[a,o]=g.useState(!1);g.useEffect(()=>{const f=i.current;if(!f)return;const p=()=>{o(f.scrollWidth-f.clientWidth-f.scrollLeft>1)};p(),f.addEventListener("scroll",p,{passive:!0});const m=new ResizeObserver(p);return m.observe(f),()=>{f.removeEventListener("scroll",p),m.disconnect()}},[e]);const l=g.useMemo(()=>RY(e),[e]),u=t&&e.some(f=>f.id===t)?t:e[0]?.id??null;g.useEffect(()=>{if(!u)return;const f=r.current.get(u);(f?.parentElement??f)?.scrollIntoView({block:"nearest",inline:"nearest"})},[u]);const d=g.useCallback((f,p)=>{f.stopPropagation(),s(p);const m=X2(e,p);m&&r.current.get(m.id)?.focus()},[e,s]),h=g.useCallback((f,p)=>{const m=e.length-1;let v;switch(f.key){case"ArrowRight":v=p===m?0:p+1;break;case"ArrowLeft":v=p===0?m:p-1;break;case"Home":v=0;break;case"End":v=m;break;default:return}f.preventDefault();const b=e[v];b&&(r.current.get(b.id)?.focus(),n(b.id))},[e,n]);return e.length===0?null:c.jsxs("div",{className:T("flex shrink-0 items-stretch border-hairline border-b"),children:[c.jsx("div",{ref:i,role:"tablist","aria-label":"Open documents","aria-orientation":"horizontal",className:T("flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto bg-sunken px-1 py-1","[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",a&&"[mask-image:linear-gradient(to_right,black_calc(100%-24px),transparent)]"),children:e.map((f,p)=>{const m=f.id===u;return c.jsxs("div",{role:"presentation",className:T("group flex h-6 shrink-0 items-center rounded-sm pr-0.5","transition-colors duration-fast ease-out-quart",m?"bg-surface":"hover:bg-row-hover"),children:[c.jsx("button",{type:"button",role:"tab","aria-selected":m,id:m?kW:void 0,"aria-controls":m?TW:void 0,tabIndex:m?0:-1,title:f.artifact?fB({...f.artifact,title:f.title}):f.path??f.title,ref:v=>{v?r.current.set(f.id,v):r.current.delete(f.id)},onClick:()=>n(f.id),onKeyDown:v=>h(v,p),className:T("max-w-45 truncate rounded-sm py-1 pr-1 pl-2","text-left font-medium text-body-sm","transition-colors duration-fast ease-out-quart",m?"text-ink":"text-ink-muted"),children:l.get(f.id)??f.title}),c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":`Close ${l.get(f.id)??f.title}`,onClick:v=>d(v,f.id),className:T("size-5 [&_svg]:size-3","hover:bg-danger-wash hover:text-danger",!m&&["pointer-events-none opacity-0","group-hover:pointer-events-auto group-hover:opacity-100","group-focus-within:pointer-events-auto group-focus-within:opacity-100"]),children:c.jsx(Dn,{"aria-hidden":"true"})})]},f.id)})}),e.length>1&&c.jsxs(Il,{children:[c.jsx(Je,{content:"All open files",children:c.jsx(Ho,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"All open files",className:T("mr-1 shrink-0 self-center"),children:c.jsx(pi,{"aria-hidden":"true"})})})}),c.jsx(Nl,{align:"end",className:T("max-w-80"),children:e.map(f=>c.jsxs(Gt,{onSelect:()=>n(f.id),children:[c.jsx(Bs,{"aria-hidden":"true",className:T(f.id!==u&&"invisible")}),c.jsx("span",{className:T("truncate"),children:l.get(f.id)??f.title})]},f.id))})]})]})},M$e=g.memo(N$e),RW=["str","int","float","bool","list","dict"],Q2=e=>["desktop","sessions",e??"","variables"];async function O$e(e){return(await xt({op:"sessions.variables.list",sessionId:e})).data}async function L$e(e,t){return(await xt({op:"sessions.variables.create",sessionId:e,key:t.key,value:t.value,type:t.type})).data.variable}async function B$e(e,t){return(await xt({op:"sessions.variables.update",sessionId:e,key:t.key,value:t.value,type:t.type})).data.variable}async function j$e(e,t){await xt({op:"sessions.variables.delete",sessionId:e,key:t})}function AW(e){return e instanceof Hi&&e.status===404&&/^not found$/i.test(e.message.trim())}function H$e(e){return e instanceof Hi&&e.status===404&&!AW(e)}const U$e=(e,t)=>fs({queryKey:Q2(e),queryFn:async()=>{if(!e)throw new Error("A session id is required to read code memory.");return O$e(e)},enabled:t&&!!e,refetchInterval:n=>n.state.data?.state==="busy"?1500:!1,refetchOnMount:"always",retry:!1}),J2=e=>async(t,n,s)=>{await e.invalidateQueries({queryKey:Q2(s.sessionId)})},G$e=()=>{const e=nn();return Kn({mutationFn:({sessionId:t,...n})=>L$e(t,n),onSuccess:async()=>{Ls("Variable created")},onError:t=>{zt(bi(t,"The variable could not be created."))},onSettled:J2(e)})},V$e=()=>{const e=nn();return Kn({mutationFn:({sessionId:t,...n})=>B$e(t,n),onSuccess:async()=>{Ls("Variable updated")},onError:t=>{zt(bi(t,"The variable could not be updated."))},onSettled:J2(e)})},W$e=()=>{const e=nn();return Kn({mutationFn:({sessionId:t,key:n})=>j$e(t,n),onSuccess:async()=>{Ls("Variable deleted")},onError:t=>{zt(bi(t,"The variable could not be deleted."))},onSettled:J2(e)})},FW=e=>RW.includes(e),$$e={already_exists:"key",reserved_name:"key",invalid_value:"value",too_large:"value"},z$e=e=>({code:e instanceof Hi?e.code:void 0,message:bi(e,"The variable could not be saved. Try again.")}),e3=e=>{if(e){const t=FW(e.type)?e.type:"str",n=t==="list"||t==="dict";return{key:e.key,type:t,value:n?"":String(e.value)}}return{key:"",type:"str",value:""}},F1=()=>c.jsx("span",{className:T("text-danger"),"aria-hidden":"true",children:"*"}),q$e=({open:e,onClose:t,onSubmit:n,initialData:s})=>{const[r,i]=g.useState(e3(s)),[a,o]=g.useState(!1),[l,u]=g.useState(null),d=!!s;g.useEffect(()=>{e&&(i(e3(s)),u(null))},[e,s]);const h=async()=>{if(u(null),!ZB(r.key)){u({field:"key",message:"This name cannot be sent. Use up to 128 characters, without control characters, and not only dots."});return}o(!0);try{const w={key:r.key,type:r.type,value:r.value};await n(w),t()}catch(w){console.error("Failed to submit variable:",w),u(z$e(w))}finally{o(!1)}},f=l?.field??(l?.code?$$e[l.code]:void 0),p=d?"Edit variable":"New variable",m=c.jsxs(c.Fragment,{children:[c.jsx(k0,{onClick:t,disabled:a,startIcon:c.jsx(Nre,{size:18,"aria-hidden":"true"}),children:"Cancel"}),c.jsx(T0,{onClick:()=>void h(),disabled:a||!r.key.trim(),startIcon:a?c.jsx(pn,{}):c.jsx(fre,{size:18,"aria-hidden":"true"}),children:a?"Saving…":d?"Save":"Create"})]}),v=g.useMemo(()=>{switch(r.type){case"dict":return"Value (JSON object)";case"list":return"Value (JSON array)";case"bool":return"Value (true/false)";default:return"Value"}},[r.type]),b=r.type==="dict"||r.type==="list";return c.jsx(su,{open:e,onClose:t,title:p,actions:m,maxWidth:"sm",fullWidth:!0,children:c.jsxs("div",{className:T("flex flex-col gap-5 pt-2"),children:[c.jsxs("div",{className:T("flex flex-col gap-1.5"),children:[c.jsxs("div",{className:T("flex items-center gap-1"),children:[c.jsxs(nr,{htmlFor:"variable-key",children:["Name (key)",c.jsx(F1,{})]}),c.jsx(Je,{content:"The unique identifier for the variable (e.g., 'api_key', 'user_preference'). Cannot be changed after creation.",children:c.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",className:T("text-info"),"aria-label":"About the variable name",children:c.jsx(ap,{"aria-hidden":"true"})})})]}),c.jsx(ps,{id:"variable-key",value:r.key,onChange:w=>i(C=>({...C,key:w.target.value})),required:!0,disabled:a||d,placeholder:"e.g., my_variable_name","aria-invalid":f==="key","aria-describedby":f==="key"?"variable-key-refusal":void 0,className:T(f==="key"&&"border-danger")}),f==="key"&&c.jsx("p",{id:"variable-key-refusal",role:"alert",className:T("text-body-sm text-ink"),children:l?.message})]}),c.jsxs("div",{className:T("flex flex-col gap-1.5"),children:[c.jsxs(nr,{htmlFor:"variable-type-select",children:["Type",c.jsx(F1,{})]}),c.jsxs(km,{value:r.type,onValueChange:w=>{FW(w)&&i(C=>({...C,type:w}))},disabled:a,children:[c.jsx(Tm,{id:"variable-type-select",children:c.jsx(Rm,{})}),c.jsx(Am,{children:RW.map(w=>c.jsx(Fm,{value:w,children:w},w))})]})]}),c.jsxs("div",{className:T("flex flex-col gap-1.5"),children:[c.jsxs(nr,{htmlFor:"variable-value",children:[v,c.jsx(F1,{})]}),c.jsx(fT,{id:"variable-value",value:r.value,onChange:w=>i(C=>({...C,value:w.target.value})),required:!0,disabled:a,rows:b?5:2,"aria-describedby":[b&&"variable-value-hint",f==="value"&&"variable-value-refusal"].filter(Boolean).join(" ")||void 0,"aria-invalid":f==="value",className:T(f==="value"&&"border-danger"),placeholder:r.type==="dict"?'{ "example_key": "example_value" }':r.type==="list"?'[ "item1", "item2" ]':r.type==="bool"?"true or false":"Enter variable value"}),b&&c.jsx("p",{id:"variable-value-hint",className:T("text-ink-muted text-meta"),children:"Enter a valid JSON structure."}),f==="value"&&c.jsx("p",{id:"variable-value-refusal",role:"alert",className:T("text-body-sm text-ink"),children:l?.message})]}),l&&!f&&c.jsx("p",{role:"alert",className:T("text-body-sm text-ink"),children:l.message})]})})},t3="The backend did not answer, so this chat's code memory could not be read. Nothing was changed. Try again in a moment.",qi=({children:e})=>c.jsx("div",{className:T("flex h-full flex-col items-center justify-center gap-2 p-6 text-center"),children:e}),n3=(e,t)=>e.length<=t?e:`${e.substring(0,t)}…`,DW=g.memo(({variable:e,onEdit:t,onDelete:n})=>{const[s,r]=g.useState(!1),[i,a]=g.useState(!1),o=g.useId(),l=ZB(e.key),u=e.editable&&l,d=l,h=g.useMemo(()=>String(e.value),[e.value]),f=g.useMemo(()=>n3(h,200),[h]),p=g.useMemo(()=>n3(h,1e3),[h]),m=e.type,v=g.useCallback(()=>{r(y=>!y)},[]),b=g.useCallback(y=>{y.stopPropagation(),t(e)},[t,e]),w=g.useCallback(y=>{y.stopPropagation(),n(e.key)},[n,e.key]),C=g.useCallback(async y=>{y.stopPropagation();try{await navigator.clipboard.writeText(h),a(!0),setTimeout(()=>a(!1),2e3)}catch(k){console.error("Failed to copy to clipboard:",k)}},[h]);return c.jsxs("div",{className:T("group border-hairline border-b last:border-b-0"),children:[c.jsxs("div",{className:T("flex min-h-8 items-center gap-1 pr-1","transition-colors duration-fast ease-out-quart hover:bg-surface"),children:[c.jsxs("button",{type:"button",onClick:v,"aria-expanded":s,"aria-controls":o,className:T("flex min-w-0 flex-1 cursor-pointer select-none items-center gap-2 px-2 py-1 text-left font-mono text-mono-sm"),children:[s?c.jsx(pi,{"aria-hidden":"true",className:"size-3 shrink-0 text-ink-dim"}):c.jsx(ga,{"aria-hidden":"true",className:"size-3 shrink-0 text-ink-dim"}),c.jsx("span",{className:T("shrink-0 font-medium text-ink"),children:e.key}),c.jsx("span",{className:T("shrink-0 text-ink-dim"),children:m}),c.jsx(Je,{content:p,align:"start",children:c.jsx("span",{className:T("min-w-0 flex-1 truncate text-ink-muted"),children:f})})]}),c.jsxs("div",{className:T("flex shrink-0 items-center gap-0.5","pointer-events-none opacity-0","group-hover:pointer-events-auto group-hover:opacity-100","group-focus-within:pointer-events-auto group-focus-within:opacity-100"),children:[c.jsx(Je,{content:i?"Copied":"Copy value",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:C,"aria-label":"Copy value",children:c.jsx(Gl,{})})}),u?c.jsx(Je,{content:"Edit variable",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:b,"aria-label":"Edit variable",children:c.jsx(gP,{})})}):c.jsx(Je,{content:l?"This variable can't be edited because its type is not yet supported for editing.":"This variable's name can't be edited from here. Copy it to the session under a new name if you need to change it.",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-disabled":"true","aria-label":"Edit variable",className:T("cursor-default text-ink-disabled hover:bg-transparent hover:text-ink-disabled"),children:c.jsx(gP,{})})}),d&&c.jsx(Je,{content:"Delete variable",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:w,"aria-label":"Delete variable",className:T("hover:bg-danger-wash hover:text-danger"),children:c.jsx(P0,{})})})]})]}),s?c.jsx("div",{id:o,className:T("max-h-75 overflow-auto whitespace-pre-wrap break-words bg-sunken px-7 py-2 font-mono text-ink-muted text-mono-sm"),children:h}):null]})});DW.displayName="VariableRow";const PW=g.memo(({sessionId:e,turnTerminal:t})=>{const[n,s]=g.useState(!1),[r,i]=g.useState(null),[a,o]=g.useState(!1),[l,u]=g.useState(null),d=Bn(),h=yt(d.data,"session_variables"),{data:f,isLoading:p,error:m,isError:v}=U$e(e,h),b=nn(),w=g.useRef(t);g.useEffect(()=>{const j=w.current;w.current=t,!(j===void 0||t===void 0)&&(t<=j||!e||!h||b.invalidateQueries({queryKey:Q2(e)}))},[t,e,h,b]);const C=G$e(),y=V$e(),k=W$e(),_=g.useRef(null);g.useEffect(()=>{f?.state==="observed"&&(_.current=f)},[f]);const E=f?.state==="observed"?f:_.current,R=f?.state==="busy",F=g.useMemo(()=>E?.variables??[],[E]),A=g.useCallback(()=>{i(null),s(!0)},[]),N=g.useCallback(j=>{i(j),s(!0)},[]),M=g.useCallback(()=>{s(!1),i(null)},[]),D=g.useCallback(async j=>{if(e)try{r?await y.mutateAsync({sessionId:e,...j,key:r.key}):await C.mutateAsync({sessionId:e,...j})}catch(te){throw console.error("Submission failed in component:",te),te}},[e,r,C,y]),L=g.useCallback(j=>{u(j),o(!0)},[]),V=g.useCallback(async()=>{if(!e||!l){o(!1),u(null);return}try{await k.mutateAsync({sessionId:e,key:l})}catch(j){console.error("Deletion failed during confirmation:",j)}finally{o(!1),u(null)}},[e,l,k]);if(d.isLoading)return c.jsxs(qi,{children:[c.jsx(pn,{size:"sm"}),c.jsx("p",{className:T("text-body-sm text-ink-muted"),children:"Loading variables"})]});if(d.isError)return c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:"Could not reach the backend"}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:bi(d.error,t3)})]});if(!h)return c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:"Update the backend to read code memory."}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:"This app can read code memory; the backend it is running against is older than that. Settings, then Application updates and info, installs the newer one."})]});if(!e)return c.jsx(qi,{children:c.jsx("p",{className:T("text-heading text-ink"),children:"Code memory starts when you send your first message."})});if(p)return c.jsxs(qi,{children:[c.jsx(pn,{size:"sm"}),c.jsx("p",{className:T("text-body-sm text-ink-muted"),children:"Loading variables"})]});if(v)return AW(m)?c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:"Update the backend to read code memory."}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:"Settings, then Application updates and info, installs the newer backend."})]}):H$e(m)?c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:"Could not load variables"}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:bi(m,"The backend does not have a chat with this session id.")})]}):c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:"Could not load variables"}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:t3})]});if(f?.state==="unsupported")return c.jsx(qi,{children:c.jsx("p",{className:T("text-heading text-ink"),children:"This chat cannot read code memory."})});if(F.length===0){if(R)return c.jsxs(qi,{children:[c.jsx(pn,{size:"sm"}),c.jsx("p",{className:T("text-body-sm text-ink-muted"),children:"Reading…"})]});if(E?.truncated&&F.length===0&&!R)return c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:"Too large to show here"}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:"This chat keeps a value bigger than this panel can list, so nothing is shown here. It is still there for the next step."})]});const j=E?.kernel==="absent"||E?.runtime==="absent";return c.jsxs(qi,{children:[c.jsx("p",{className:T("text-heading text-ink"),children:j?"No code memory yet":"Nothing stored yet"}),c.jsx("p",{className:T("max-w-80 text-body-sm text-ink-muted"),children:j?"It fills in when code runs in this chat.":"When the agent runs code for you, the values it keeps around between steps show up here. You can add one yourself too."}),j?null:c.jsxs(ce,{variant:"secondary",size:"sm",onClick:A,children:[c.jsx(Kc,{"aria-hidden":"true"}),"New variable"]})]})}return c.jsxs("div",{className:T("flex h-full min-h-0 flex-col"),children:[c.jsxs("div",{className:T("flex h-10 shrink-0 items-center justify-between gap-3 border-hairline border-b px-3"),children:[c.jsxs("p",{className:T("flex min-w-0 items-center truncate text-body-sm text-ink-muted"),children:[c.jsx("span",{className:T("font-medium text-ink"),children:"Code memory"}),c.jsx("span",{className:T("mx-1.5 text-ink-dim"),children:"·"}),F.length," ",F.length===1?"variable":"variables",R?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:T("mx-1.5 text-ink-dim"),children:"·"}),c.jsx(pn,{size:"xs"}),c.jsx("span",{className:T("ml-1.5"),children:"Reading…"})]}):null]}),c.jsxs(ce,{variant:"ghost",size:"sm",onClick:A,children:[c.jsx(Kc,{"aria-hidden":"true"}),"New variable"]})]}),c.jsx("div",{className:T("min-h-0 flex-1 overflow-auto"),children:F.map(j=>c.jsx(DW,{variable:j,onEdit:N,onDelete:L},j.key))}),c.jsx(q$e,{open:n,onClose:M,onSubmit:D,initialData:r}),l&&c.jsx(au,{open:a,title:"Delete variable",message:c.jsxs(c.Fragment,{children:["Are you sure you want to delete the variable"," ",c.jsx("strong",{className:T("font-mono text-ink"),children:l}),"? This action cannot be undone."]}),confirmText:"Delete",cancelText:"Cancel",isDangerous:!0,onConfirm:V,onCancel:()=>{o(!1),u(null)}})]})});PW.displayName="CanvasVariablesViewer";const K$e=(e,t,n,s=!1)=>{const r=`${n} ${n===1?t:`${t}s`}`;return s?`${e} view, ${r} shown — this list is capped`:n>0?`${e} view, ${r}`:`${e} view`},s3="mb-1.5 flex w-fit items-center gap-2 font-normal text-ink-muted",r3=[{id:"md",name:"Markdown (.md)",group:"General"},{id:"txt",name:"Plain text (.txt)",group:"General"},{id:"html",name:"HTML (.html)",group:"Web development"},{id:"css",name:"CSS (.css)",group:"Web development"},{id:"js",name:"JavaScript (.js)",group:"Web development"},{id:"jsx",name:"JSX (.jsx)",group:"Web development"},{id:"ts",name:"TypeScript (.ts)",group:"Web development"},{id:"tsx",name:"TSX (.tsx)",group:"Web development"},{id:"py",name:"Python (.py)",group:"Backend and scripting"},{id:"go",name:"Go (.go)",group:"Backend and scripting"},{id:"java",name:"Java (.java)",group:"Backend and scripting"},{id:"cs",name:"C# (.cs)",group:"Backend and scripting"},{id:"php",name:"PHP (.php)",group:"Backend and scripting"},{id:"rb",name:"Ruby (.rb)",group:"Backend and scripting"},{id:"rs",name:"Rust (.rs)",group:"Backend and scripting"},{id:"sh",name:"Shell script (.sh)",group:"Backend and scripting"},{id:"json",name:"JSON (.json)",group:"Configuration"},{id:"yaml",name:"YAML (.yaml)",group:"Configuration"},{id:"yml",name:"YAML (.yml)",group:"Configuration"},{id:"xml",name:"XML (.xml)",group:"Configuration"},{id:"toml",name:"TOML (.toml)",group:"Configuration"},{id:"ini",name:"INI (.ini)",group:"Configuration"},{id:"env",name:".env",group:"Configuration"},{id:"dockerfile",name:"Dockerfile",group:"Configuration"},{id:"c",name:"C (.c)",group:"Other languages"},{id:"cpp",name:"C++ (.cpp)",group:"Other languages"},{id:"swift",name:"Swift (.swift)",group:"Other languages"},{id:"kt",name:"Kotlin (.kt)",group:"Other languages"},{id:"scala",name:"Scala (.scala)",group:"Other languages"}],Y$e=({open:e,onClose:t,onSave:n,isSaving:s,currentWorkingDirectory:r="~"})=>{const[i,a]=g.useState(""),[o,l]=g.useState("md"),[u,d]=g.useState(!1);g.useEffect(()=>{e&&(a(""),l("md"))},[e]);const h=g.useMemo(()=>r3.find(v=>v.id===o)??(o?{id:o,name:o}:null),[o]),f=i.trim()!==""&&!s,p=async(v=!1)=>{if(!f)return;const b=`${r}/${i}.${o}`;if(await window.api.fileExists(b)&&!v){d(!0);return}n({name:i,type:o,location:r},v)},m=c.jsxs(c.Fragment,{children:[c.jsx(k0,{onClick:t,disabled:s,children:"Cancel"}),c.jsx(T0,{onClick:()=>void p(),disabled:!f,startIcon:s?c.jsx(pn,{}):null,children:s?"Creating...":"Create file"})]});return c.jsxs(c.Fragment,{children:[c.jsx(su,{open:e&&!u,onClose:t,title:"Create new file",actions:m,maxWidth:"sm",fullWidth:!0,children:c.jsxs("div",{className:T("flex flex-col gap-4 pt-2"),children:[c.jsxs("div",{children:[c.jsxs(nr,{htmlFor:"create-file-name",className:T(s3),children:[c.jsx($w,{size:16,"aria-hidden":"true"}),"File name"]}),c.jsx(ps,{id:"create-file-name",value:i,onChange:v=>a(v.target.value),required:!0,autoFocus:!0,disabled:s,placeholder:"Enter file name (e.g., my-new-script)",onKeyDown:v=>{v.key==="Enter"&&f&&p()}})]}),c.jsx(gT,{label:"File type",icon:c.jsx(vj,{size:16,"aria-hidden":"true"}),labelTooltip:"Pick an extension, or type one that is not listed.",placeholder:"Select or type an extension",options:r3,selected:h,onSelect:v=>l(v.id),onCustomSubmit:v=>l(v),busyLabel:"Loading file types",disabled:s}),c.jsxs("div",{children:[c.jsxs("p",{className:T(s3,"text-body-sm"),children:[c.jsx(AY,{size:16,"aria-hidden":"true"}),"Location"]}),c.jsx(FY,{currentWorkingDirectory:r,readOnlyReason:"Change the working directory from the composer to create the file elsewhere."}),c.jsx("p",{className:T("mt-2 text-ink-muted text-meta"),children:"The file will be created in this working directory."})]})]})}),c.jsx(au,{open:u,title:"File already exists",message:`A file named "${i}.${o}" already exists. Do you want to overwrite it?`,confirmText:"Overwrite",onConfirm:()=>{d(!1),p(!0)},onCancel:()=>d(!1),isDangerous:!0})]})},X$e=2e3,Q$e={missing:"No longer on disk — showing the version we last read.",unreadable:"Could not be read — showing the version we last read.",failed:"Could not be re-read — showing the version we last read.","disk-changed":"Changed on disk — load it, or save to replace it.","save-replaced":"Your save replaced the change on disk."},J$e={missing:"This file is no longer on disk. The last version we read is still shown, and your unsaved edits are kept - saving writes them back.",unreadable:"This file could not be read. The last version we read is still shown, and your unsaved edits are kept - saving writes them back.",failed:"This file could not be re-read, so the version we last read is still shown.","disk-changed":"Your unsaved edits are kept until the app quits, and saving is paused while the file has changed on disk. Load its version to see the change (your unsaved edits are discarded), or save to replace the file with your version.","save-replaced":"Your save replaced the version that had changed on disk. Re-read the file to see what is there now."},Z$e=8e3;function i3(e,t){switch(e.status){case"applied":return"Re-read";case"identical":return"Up to date";case"unchanged":return t?"Up to date":void 0;case"unavailable":return t?"No local file access":void 0;default:return}}function a3(e,t){switch(e.status){case"applied":return"The file's version was re-read from disk and is now on screen.";case"identical":case"unchanged":return t?"Already up to date — the file is unchanged.":void 0;case"unavailable":return t?"Local file access is unavailable, so there is nothing to re-read from.":void 0;default:return}}function o3(e,t){switch(e.status){case"missing":return"missing";case"unreadable":return"unreadable";case"failed":return"failed";case"skipped-dirty":return e.unreadable?"unreadable":e.missing?"missing":e.diskChanged?"disk-changed":t==="disk-changed"||t==="missing"||t==="unreadable"?null:void 0;case"applied":case"identical":return null;case"unchanged":case"adopted":return t==="missing"||t==="unreadable"?null:void 0;default:return}}function eze({document:e,conversationId:t}){const n=ls(b=>b.updateOneFile),s=g.useSyncExternalStore(_0e,()=>EC(e.id),()=>!1),[r,i]=g.useState(!1),a=g.useSyncExternalStore(k0e,()=>E0e(e.id),()=>null),o=g.useRef(null);o.current=a;const[l,u]=g.useState(null);g.useEffect(()=>{u(null)},[e.id]),g.useEffect(()=>{if(!l)return;const b=Z$e-(Date.now()-l.at),w=window.setTimeout(()=>{u(C=>C?.at===l.at?null:C)},Math.max(0,b));return()=>window.clearTimeout(w)},[l]);const d=g.useRef(e);g.useEffect(()=>{d.current=e});const h=g.useMemo(()=>T0e({probe:b=>Z8(b),read:async(b,w)=>{if(typeof window.api?.readFile!="function")return{ok:!1,error:"Local file access is unavailable outside the desktop app."};try{const C=await window.api.readFile(b,w);return C.success?{ok:!0,content:C.data}:{ok:!1,error:C.error instanceof Error?C.error.message:String(C.error)}}catch(C){return{ok:!1,error:C instanceof Error?C.message:String(C)}}}}),[]),f=g.useCallback(b=>{if(!t)return;const w=d.current;w.id===b.id&&w.content===b.content&&w.readMtimeMs===b.readMtimeMs&&w.lastAgentModified===b.lastAgentModified&&w.sizeBytes===b.sizeBytes&&w.availability===b.availability||n(t,b)},[t,n]),p=g.useCallback(async b=>{b&&i(!0);const w=of(e.id);try{const C=await h.check(d.current,b);if(of(e.id)!==w)return;"document"in C&&f(C.document);const y=o3(C,o.current);y!==void 0&&La(e.id,y);const k=i3(C,b);k!==void 0&&u(k?{text:k,detail:a3(C,b)??null,at:Date.now()}:null)}finally{b&&i(!1)}},[f,e.id,h]),m=g.useCallback(async()=>{i(!0);try{F0e(e.id);const b=await h.load(d.current);"document"in b&&(A0e(b.document.id,b.document.content,b.document.readMtimeMs??null),f(b.document));const w=o3(b,o.current);w!==void 0&&La(e.id,w);const C=i3(b,!0);C!==void 0&&u(C?{text:C,detail:a3(b,!0)??null,at:Date.now()}:null)}finally{i(!1)}},[f,e.id,h]);g.useEffect(()=>{p(!1)},[p,e.id,e.path,t]),g.useEffect(()=>{const b=()=>{window.document.visibilityState==="visible"&&p(!1)};return window.addEventListener("focus",b),window.document.addEventListener("visibilitychange",b),()=>{window.removeEventListener("focus",b),window.document.removeEventListener("visibilitychange",b)}},[p]),g.useEffect(()=>{const b=window.setInterval(()=>{window.document.visibilityState==="visible"&&p(!1)},X$e);return()=>window.clearInterval(b)},[p]);const v=g.useCallback(()=>{if(o.current==="disk-changed"){m();return}o.current==="save-replaced"&&La(e.id,null),p(!0)},[p,e.id,m]);return{lastModifiedMs:e.readMtimeMs??null,refreshing:r,note:a?Q$e[a]:l?.text??null,detail:a?J$e[a]:l?.detail??l?.text??null,dirty:s,diskChanged:a==="disk-changed",refresh:v}}const tze=({document:e,conversationId:t})=>{const{lastModifiedMs:n,refreshing:s,note:r,detail:i,dirty:a,diskChanged:o,refresh:l}=eze({document:e,conversationId:t}),u=g.useId(),d=n===null?"Not read from disk yet":`Modified ${DY(new Date(n))}`,h=o?"Load the file's version (your unsaved edits are discarded)":a?"Check the file (your edits are kept)":"Re-read from disk";return c.jsxs("div",{className:T("flex h-8 shrink-0 items-center gap-2 border-hairline border-b bg-sunken px-2"),"data-tour-tag":"canvas-document-freshness",children:[c.jsx(Je,{content:[i,d].filter(Boolean).join(" · "),side:"bottom",delayDuration:1200,children:c.jsxs("div",{tabIndex:0,className:T("flex min-w-0 flex-1 items-center gap-2 overflow-hidden p-0.5"),"data-tour-tag":"canvas-document-freshness-region",children:[c.jsx("span",{className:T("min-w-0 truncate whitespace-nowrap text-meta text-ink-muted tabular-nums"),"data-tour-tag":"canvas-document-modified",children:d}),c.jsx("output",{id:u,className:"sr-only","aria-live":"polite","data-tour-tag":"canvas-document-freshness-announcement",children:r??""}),r?c.jsx("span",{className:T("min-w-[8ch] truncate whitespace-nowrap text-meta text-ink-muted"),"data-tour-tag":"canvas-document-freshness-note",children:r}):null]})}),c.jsx("div",{className:T("shrink-0"),children:c.jsx(Je,{content:h,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h,"aria-describedby":r?u:void 0,disabled:s,onClick:l,"data-tour-tag":"canvas-refresh-file-button",children:c.jsx(pC,{"aria-hidden":"true"})})})})]})},nze=[],l3=[{value:"documents",label:"Documents",tourTag:"canvas-documents-view-button",Icon:qw},{value:"files",label:"Files",tourTag:"canvas-files-view-button",Icon:zw},{value:"variables",label:"Variables",tourTag:"canvas-variables-view-button",Icon:Ose},{value:"goals",label:"Goals",tourTag:"canvas-goals-view-button",Icon:Vre}],sze=e=>e?l3:l3.filter(t=>t.value!=="goals"),rze=({current:e,onChange:t,views:n,fileCount:s,goalCount:r,goalTruncated:i})=>c.jsxs("fieldset",{className:T("inline-flex h-7 shrink-0 items-center gap-0.5 border-0 p-0"),children:[c.jsx("legend",{className:T("sr-only"),children:"Canvas view"}),n.map(({value:a,label:o,tourTag:l,Icon:u})=>{const d=e===a,h=a==="files"?s:a==="goals"?r:0,p=h===null?o:K$e(o,a==="files"?"file":"goal",h,a==="goals"&&i);return c.jsx(Je,{content:p,children:c.jsxs("button",{type:"button","aria-pressed":d,"aria-label":p,"data-tour-tag":l,onClick:()=>t(a),className:T("inline-flex h-6 items-center justify-center rounded-sm px-2","transition-colors duration-fast ease-out-quart","[&_svg]:size-3.5",d?"bg-surface text-ink":"text-ink-muted hover:text-ink"),children:[c.jsx(u,{"aria-hidden":"true"}),a==="files"&&c.jsxs("span",{className:T("ml-1 text-meta"),children:[o,h===null?"":` ${Ah(h)}`]})]})},a)})]}),ize=({activeDocumentId:e,initialDocuments:t=[],onChangeActiveDocument:n,onClose:s,onCloseDocument:r,conversationId:i,sessionId:a,filesSourceReady:o=!0,turnTerminal:l,agentId:u,currentWorkingDirectory:d,fileCount:h=0,fileIndex:f,scan:p=null,goalHistory:m=nze,goalHistoryTruncated:v=!1,goalCapable:b=!1,goalPresent:w=!1})=>{const C=e8(a,!f,l),y=f??C,k=y.mode==="negotiating"?null:y.mode==="index"?y.state==="ready"||y.total>0?y.total:null:h,[_,E]=g.useState(!1),[R,F]=g.useState(!1),[A,N]=g.useState("Ctrl");g.useEffect(()=>{(async()=>{const be=await window.api.systemInfo.getPlatformInfo();N(be.platform==="darwin"?"⌘":"Ctrl")})()},[]);const{addFileAndSelect:M,setViewMode:D,addMentionedFile:L}=ls(),{removeManager:V}=t8(),j=g.useCallback(async()=>{if(i){const B=await window.api.selectFile();if(B){const be={id:B.path,title:B.path.split("/").pop()||B.path,content:B.content,path:B.path,type:Ef(B.path)};M(i,be),L(i,be),D(i,"documents")}}},[M,L,i,D]);g.useEffect(()=>{const B=be=>{const ie=PY(be);if(ie==="open-file"?(be.preventDefault(),j()):ie==="new-file"&&(be.preventDefault(),E(!0)),be.key==="Escape"&&i){if(be.defaultPrevented||lT(be.target))return;be.preventDefault(),s()}};return window.addEventListener("keydown",B),()=>{window.removeEventListener("keydown",B)}},[j,i,s]);const te=async(B,be=!1)=>{F(!0);try{if(await Xpe(B.name,B.type,B.location,be),i){const ie={id:`${B.location}/${B.name}.${B.type}`,title:`${B.name}.${B.type}`,content:"",path:`${B.location}/${B.name}.${B.type}`};M(i,ie),L(i,ie)}E(!1)}catch{}finally{F(!1)}},X=ls(B=>i?B.conversations[i]:void 0),re=sze(b),G=X?.viewMode,J=G&&re.some(B=>B.value===G)?G:"documents",ae=k??0,O=ae>0,U=g.useCallback(B=>{i&&D(i,B)},[i,D]),P=t,[z,ne]=g.useState(P.length>0?P[0].id:null),fe=e??z,ue=g.useMemo(()=>P.find(B=>B.id===fe)||null,[P,fe]),le=g.useCallback(B=>{n?n(B):ne(B)},[n]),q=g.useCallback(B=>{U("documents"),le(B)},[le,U]),we=g.useCallback(B=>{if(r(B),V(B),fe===B){const be=X2(P,B)?.id??null;n?n(be):ne(be)}},[P,fe,n,r,V]);return c.jsxs("section",{"aria-label":"Canvas","data-tour-tag":"canvas-container","data-canvas-shortcuts":!0,"data-glass-region":"pane",className:T("flex h-full flex-col bg-elevated"),children:[c.jsxs("div",{className:T("flex h-10 shrink-0 items-center justify-between gap-2 px-2","[padding-inline-end:max(0.5rem,var(--chrome-inset-end-pane,var(--chrome-inset-end)))]"),children:[c.jsx(rze,{current:J,onChange:U,views:re,fileCount:k,goalCount:m.length,goalTruncated:v}),c.jsxs("div",{className:T("flex shrink-0 items-center gap-0.5"),children:[c.jsx(Je,{content:`New file (${A} + N)`,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":`New file (${A} + N)`,onClick:()=>E(!0),"data-tour-tag":"canvas-create-file-button",children:c.jsx(fP,{"aria-hidden":"true"})})}),c.jsx(Je,{content:`Open file from disk (${A} + O)`,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":`Open file from disk (${A} + O)`,onClick:j,children:c.jsx(zS,{"aria-hidden":"true"})})}),c.jsx(Je,{content:"Close canvas",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":"Close canvas",onClick:s,"data-tour-tag":"close-canvas-button",children:c.jsx(zc,{"aria-hidden":"true"})})})]})]}),J==="documents"&&c.jsxs(c.Fragment,{children:[c.jsx(M$e,{documents:P,activeDocumentId:fe,onChangeActiveDocument:le,onCloseDocument:we}),ue&&c.jsxs(OJ,{id:TW,labelledBy:kW,children:[!ue.artifact&&c.jsx(tze,{document:ue,conversationId:i}),c.jsx(h9e,{document:ue,conversationId:i,agentId:u},ue.id)]}),!ue&&P.length===0&&c.jsxs(_k,{title:"Nothing open yet",description:"Open a file to read or edit it here. Files the agent mentions in the conversation open here too.",children:[c.jsxs(ce,{variant:O?"primary":"secondary",size:"sm",onClick:()=>U("files"),children:[c.jsx(zw,{"aria-hidden":"true"}),O?`Browse files (${ae})`:"Browse files"]}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:j,children:[c.jsx(zS,{"aria-hidden":"true"}),"Open file from disk"]}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>E(!0),children:[c.jsx(fP,{"aria-hidden":"true"}),"New file"]})]})]}),J==="files"&&i&&c.jsx(F$e,{conversationId:i,sessionId:a,cwd:o?d:void 0,index:y.mode==="fallback"&&!o?{...y,mode:"negotiating",state:"loading",localReadAllowed:!1}:y,onSwitchToDocumentView:q,scan:p},i),J==="variables"&&i&&c.jsx(PW,{sessionId:a,turnTerminal:l}),J==="goals"&&c.jsx(D$e,{entries:m,truncated:v,goalPresent:w}),(J==="files"||J==="variables")&&!i&&c.jsx(_k,{title:"No conversation open",description:"Start a conversation with an agent to see the files and variables it is working with."}),u&&c.jsx(Y$e,{open:_,onClose:()=>E(!1),onSave:te,isSaving:R,currentWorkingDirectory:d})]})},aze=g.memo(ize),oze="max-h-[min(22rem,var(--radix-popover-content-available-height))]";function lze(e){return e==="team"?{recents:"Recent teams",all:"All teams"}:{recents:"Recent agents",all:"All agents"}}function IW(e){return!e.loading&&e.loadError===null&&e.rowCount>0}function cze(e){const{rows:t,matches:n,recents:s,kind:r,query:i}=e,a=lze(r),o=t.length,l=i.trim()!==""&&n.length===0;if(i.trim()!=="")return{bands:[{heading:null,rows:n}],matches:n.length,total:o,noMatches:l};const u=s.map(d=>t.find(h=>h.value===d)).filter(d=>d!==void 0).filter(d=>!d.disabled);return u.length===0||u.length===t.length?{bands:[{heading:null,rows:t}],matches:n.length,total:o,noMatches:l}:{bands:[{heading:a.recents,rows:u},{heading:a.all,rows:t}],matches:n.length,total:o,noMatches:l}}function D1(e){const t=e.findIndex(s=>s.current&&!s.disabled);if(t!==-1)return t;const n=e.findIndex(s=>!s.disabled);return n===-1?0:n}function uze(e){return`${e} cannot take the seat.`}const dze="No profile here can take the seat — clear the search, or switch the team.",hze="No profile can take the seat — switch the team.";function fze(e){const{view:t,kind:n,query:s,overflowing:r,hasSettable:i}=e,a=n==="team"?"teams":"agents";return s.trim()!==""?t.matches===0?null:i?t.matches===t.total?`${t.total} ${a} match`:`${t.matches} of ${t.total} ${a} match`:dze:r?i?`${t.total} ${a} in all — scroll, or type to filter`:hze:null}function NW(e){return e.teamOwnsSeat===!0?!1:e.name===e.manager||e.delegate===!0}function pze(e){return`${e} is led by its manager; only the manager and profiles that can delegate may take this seat.`}function gze(e,t){return`team ${e} owns this session: ${t??"its manager"} is the speaker, so /agent is closed. Run /team clear to detach the team first.`}function mze(e){return`Agent seat closed by ${e}`}const vze="Needs a delegating profile here.";function bze(e){return e.closure?{manager:e.closure.speaker,caption:e.closure.sentence,closed:e.closure.sentence,closedTitle:e.closure.title}:e.manager===null?null:{manager:e.manager,caption:pze(e.teamLabel)}}const c3=T("px-2 py-3 text-body-sm"),xze=({kind:e,open:t,listId:n,options:s,recents:r,loading:i,loadError:a,emptyText:o,caption:l,closedReason:u=null,closedNoteId:d,closedTitle:h,onPick:f,onClose:p,onCloseAutoFocus:m})=>{const[v,b]=g.useState(""),[w,C]=g.useState(0),[y,k]=g.useState(null),[_,E]=g.useState(!1),[R,F]=g.useState(null),A=g.useRef(null),[N,M]=g.useState(null),D=IW({loading:i,loadError:a,rowCount:s.length}),L=g.useMemo(()=>IY(s,v),[s,v]),V=g.useMemo(()=>cze({rows:s,matches:L,recents:r,kind:e,query:v}),[s,L,r,e,v]),j=g.useMemo(()=>V.bands.flatMap(ne=>ne.rows),[V]);g.useEffect(()=>{C(D1(j)),k(null),F(null)},[v]),g.useEffect(()=>{C(D1(j))},[j.length]),g.useEffect(()=>{F(null)},[w]),g.useEffect(()=>{document.getElementById(`${n}-${w}`)?.scrollIntoView({block:"nearest"})},[w,n]),g.useEffect(()=>{const ne=N;if(!ne){E(!1);return}const fe=()=>E(ne.scrollHeight>ne.clientHeight+1);fe();let ue;if(typeof ResizeObserver<"u"){ue=new ResizeObserver(fe),ue.observe(ne);for(const le of ne.children)ue.observe(le)}return()=>ue?.disconnect()},[V,N]),g.useEffect(()=>{if(!t)return;const ne=A.current;!ne||document.activeElement===ne||ne.focus()},[t,D]),g.useEffect(()=>{t&&(b(""),C(D1(j)),k(null),F(null))},[t]);const te=g.useCallback(ne=>{j.length!==0&&C(fe=>(fe+ne+j.length)%j.length)},[j.length]),X=g.useCallback(ne=>{if(!ne.nativeEvent.isComposing){if(ne.key==="Tab"){ne.stopPropagation(),p();return}if(ne.key==="ArrowDown"){ne.preventDefault(),te(1);return}if(ne.key==="ArrowUp"){ne.preventDefault(),te(-1);return}if(ne.key==="Home"&&j.length>0){ne.preventDefault(),C(0);return}if(ne.key==="End"&&j.length>0){ne.preventDefault(),C(j.length-1);return}if(ne.key==="Enter"){ne.preventDefault();const fe=j[w];fe&&!fe.disabled?f(fe.value):fe?.blocked&&F(uze(fe.label));return}}},[w,j,te,p,f]),re=e==="team"?"teams":"agents",G=j.length>0?`${n}-${w}`:void 0,J=j.some(ne=>!ne.blocked),ae=V.matches>0&&!J,O=fze({view:V,kind:e,query:v,overflowing:_,hasSettable:J}),U=g.useId();let P=-1;const z=c.jsxs("div",{className:"relative px-1 pt-1 pb-1",children:[c.jsx(xd,{className:"-translate-y-1/2 pointer-events-none absolute top-1/2 left-2.5 size-4 text-ink-dim","aria-hidden":"true"}),c.jsx(ps,{ref:A,role:"combobox","aria-expanded":!0,"aria-controls":D?n:void 0,"aria-activedescendant":G,"aria-autocomplete":"list","aria-label":`Search ${re}`,value:v,onChange:ne=>b(ne.target.value),onKeyDown:X,placeholder:`Search ${re}`,className:"pl-8",autoComplete:"off",spellCheck:!1})]});if(u!==null){const ne=`${d}-title`;return c.jsxs(Rf,{align:"start",sideOffset:6,collisionPadding:8,className:T("flex w-80 flex-col gap-0.5 p-1"),"data-header-identity-menu":e,"data-header-identity-closed":"",id:d,"aria-labelledby":ne,onOpenAutoFocus:fe=>fe.preventDefault(),onCloseAutoFocus:m,children:[c.jsx("p",{id:ne,className:"px-2 pt-1 text-body-sm text-ink-muted",children:h}),c.jsx("p",{"data-header-identity-constraint":"",className:"px-2 pb-1.5 text-ink-dim text-meta",children:u})]})}return c.jsx(Rf,{align:"start",sideOffset:6,collisionPadding:8,className:T("flex w-80 flex-col p-1",oze,"overflow-hidden"),"data-header-identity-menu":e,role:"presentation",onMouseDown:ne=>ne.preventDefault(),onCloseAutoFocus:m,children:D?c.jsxs(c.Fragment,{children:[z,l!==null&&c.jsx("p",{id:U,"data-header-identity-constraint":"",title:l,className:"px-2 pt-0.5 pb-1 text-ink-dim text-meta",children:l}),c.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[_&&c.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-6 bg-gradient-to-t from-elevated to-transparent"}),c.jsx("div",{ref:M,id:n,role:"listbox","aria-label":e==="team"?"Teams":"Agents","aria-describedby":l!==null?U:void 0,tabIndex:-1,onMouseLeave:()=>k(null),className:"min-h-0 flex-1 overflow-y-auto",children:V.noMatches?c.jsxs("p",{className:T(c3,"text-ink-dim"),"data-header-identity-no-matches":"",children:["Nothing matches “",v.trim(),"”."]}):V.bands.map(ne=>c.jsxs(g.Fragment,{children:[ne.heading&&c.jsxs("div",{role:"presentation","data-header-identity-band":ne.heading??void 0,className:"flex items-center gap-3 px-2 pt-2 pb-1",children:[c.jsx("span",{className:"shrink-0 text-ink-dim text-meta",children:ne.heading}),c.jsx("div",{className:"h-px flex-1 bg-hairline"})]}),ne.rows.map(fe=>{P+=1;const ue=P;return c.jsx(NY,{id:`${n}-${ue}`,option:fe,index:ue,isActive:ue===w,isHovered:ue===y,isPicked:!1,onHover:le=>k(le),onPick:(le,q)=>{C(q),le.disabled||f(le.value)}},`${fe.value}-${ue}`)})]},ne.heading??"all"))})]}),(O!==null||R!==null)&&c.jsxs("div",{"aria-live":"polite","data-header-identity-footer":"","data-header-identity-resolution":ae?"":void 0,className:"border-hairline border-t px-2 py-1.5 text-ink-dim text-meta",children:[R!==null&&c.jsx("span",{className:"block",children:R}),O!==null&&c.jsx("span",{className:"block",children:O})]})]}):c.jsxs(c.Fragment,{children:[z,c.jsx("div",{className:T(c3,"text-ink-dim"),children:i?c.jsxs("span",{"data-header-identity-loading":"",children:["Loading ",re,"…"]}):a?c.jsx("span",{className:"text-danger","data-header-identity-error":"",children:a}):c.jsx("span",{children:o})})]})})};function wze(e){return e?e.locality==="remote"?e.owner_device?`peer:${e.owner_device}`:null:"":null}function Cze(e){return typeof e=="string"&&e.startsWith("cold-")}function MW(e){if(!e||typeof e!="object")return null;const{speaker:t,team:n,role_of_speaker:s}=e;return typeof t!="string"&&typeof n!="string"&&typeof s!="string"?null:{speaker:typeof t=="string"?t:"",team:typeof n=="string"?n:"",role_of_speaker:typeof s=="string"?s:""}}const yze="No team",_ze="No agent",P1="manager",Sze="its manager";function Eze(e){const t=MW(e.effectiveIdentity),s=t!==null&&t.team===""&&e.coldFrame!==!0?e.activeTeam||null:e.activeTeam||e.boundTeam||t?.team||null,r=t?.team||s||"",i=s?e.teams?.find(d=>d.name===s):void 0,a=s?kf(i??{name:s}):yze,o=t===null&&e.hostPublishes===!0;let l=null;if((t!==null||o)&&r&&s){const d=i?i.manager||P1:null,h=t?.speaker??"",p=h!==""&&!(h===r&&d!==r)?h:d;l={speaker:p??Sze,speakerKnown:p!==null,team:r,sentence:gze(r,p),title:mze(a)}}let u=l?l.speaker:e.activeAgent||e.boundAgent||null;return!u&&s&&(u=i?.manager||P1),{teamValue:s,teamLabel:a,agentValue:u,agentLabel:u??_ze,teamManager:s&&i?i.manager||P1:null,seat:l}}function kze(e){return!e.hasSession||e.pending||!e.teamCatalogue?!1:e.identityKnown||e.streamLive}function Tze(e){return e.teamOwnsSeat===!0||e.explicitAgent===null||e.manager===null||e.delegate===null?!1:!NW({name:e.explicitAgent,manager:e.manager,delegate:e.delegate})}const Rze=T("inline-flex h-5 min-w-0 shrink-0 cursor-pointer items-center gap-1 rounded-xs px-1","font-mono whitespace-nowrap text-mono-sm","transition-colors duration-fast ease-out-quart","text-ink-muted hover:bg-elevated hover:text-ink","data-[state=open]:bg-elevated data-[state=open]:text-ink"),Aze=T("inline-flex size-3.5 shrink-0 items-center justify-center");function Fze(e){return e??""}const u3=({kind:e,label:t,current:n,busy:s,open:r,onOpenChange:i,onPick:a,sessionId:o,enabled:l,triggerLabel:u,constraint:d,flagged:h,recents:f,swapRef:p,markSwap:m})=>{const v=d?.closed??null,b=pB(o,e,void 0,l&&v===null),w=b.data?.entities??[],C=n!==null,y=C&&t!==n,k=`header-identity-${e}-list`,_=`header-identity-${e}-closed`,E=g.useRef(null),R=g.useRef(v!==null);g.useEffect(()=>{const D=v!==null;if(D&&!R.current&&r){const L=document.activeElement;(L===null||L===document.body||L.closest("[data-header-identity-menu]")!==null)&&E.current?.focus()}R.current=D},[v,r]);const F=g.useRef(!1),A=r&&IW({loading:b.isLoading,loadError:b.isError?lF(b.error):null,rowCount:w.length}),N=g.useMemo(()=>w.map(D=>{const L=kf({name:D.name??D.value,label:D.label}),V=d!==null&&!NW({name:D.value,manager:d.manager,delegate:D.delegate,teamOwnsSeat:d.closed!==void 0});return{value:D.value,label:L,description:V?vze:L!==D.value?D.description?`${D.value} · ${D.description}`:D.value:D.description,meta:D.kind,current:D.value===Fze(n),disabled:s||V,blocked:V}}),[w,n,s,d]),M=d?.caption??null;return c.jsxs(Dm,{open:r,onOpenChange:i,modal:!1,children:[c.jsx(oS,{asChild:!0,children:c.jsxs("button",{ref:E,type:"button","data-header-identity":e,"data-header-identity-closed":v!==null?"":void 0,className:T(Rze,!C&&"text-ink-dim"),"aria-busy":s||void 0,"aria-haspopup":v===null?"listbox":"dialog","aria-controls":v!==null?r?_:void 0:A?k:void 0,onPointerDown:m,"aria-label":v!==null?`${u}: ${t}. ${v}`:`${u}: ${t}. ${C?`Switch ${e==="team"?"team":"agent"}`:e==="team"?"Assign a team":"Assign an agent"}${h&&M?`. ${M}`:""}`,title:v!==null?`${t} — ${v}`:h&&M?`${t} — ${M}`:C?`${t}${y?` (${n})`:""}`:e==="team"?"Assign a team":"Assign an agent",children:[e==="team"&&C&&c.jsx(_W,{name:t,slug:n??void 0,showTooltip:!1}),h&&c.jsx(Qa,{"data-header-identity-cue":"","aria-hidden":"true",className:"size-3 shrink-0 text-warning"}),c.jsx("span",{className:T("min-w-0 max-w-[24ch] truncate",y&&"font-sans"),children:t}),c.jsx("span",{className:T(Aze),children:s?c.jsx(pn,{size:"xs"}):v!==null?c.jsx(Lm,{className:T("size-3 text-ink-dim"),"aria-hidden":"true"}):c.jsx(pi,{className:T("size-3 text-ink-dim"),"aria-hidden":"true"})})]})}),c.jsx(xze,{kind:e,open:r,listId:k,options:N,recents:f,loading:b.isLoading,loadError:b.isError?lF(b.error):null,emptyText:e==="team"?"No teams are registered.":"No agents are registered.",caption:d?.caption??null,closedReason:v,closedNoteId:_,closedTitle:d?.closedTitle,onPick:D=>{i(!1),a(D)},onClose:()=>{E.current?.focus(),F.current=!0,i(!1)},onCloseAutoFocus:D=>{(p.current||F.current)&&(p.current=!1,F.current=!1,D.preventDefault())}})]})},Dze=({sessionId:e,activeAgent:t,activeTeam:n,boundAgent:s,boundTeam:r,effectiveIdentity:i,hostKey:a=null,frameEpoch:o})=>{const l=n||r||null,u=MW(i)!==null;g.useSyncExternalStore(bv.subscribe,bv.version),g.useEffect(()=>{u&&i&&bv.noteFrame(a,i)},[u,a,i]);const d=u||a!==null&&bv.has(a),h=sC(!!l),f=Eze({activeAgent:t,activeTeam:n,boundAgent:s,boundTeam:r,teams:h.data,effectiveIdentity:i,hostPublishes:d,coldFrame:Cze(o)}),p=f.seat!==null,m=t||s||null,v=pB(e,"agent",void 0,!!(l&&m)&&!p),b=g.useMemo(()=>m?v.data?.entities.find(L=>L.value===m)?.delegate??null:null,[m,v.data]),w=Tze({explicitAgent:m,manager:f.teamManager,delegate:b,teamOwnsSeat:p}),C=g.useMemo(()=>bze({teamLabel:f.teamLabel,manager:f.teamManager,closure:f.seat}),[f.teamLabel,f.teamManager,f.seat]),[y,k]=g.useState(null),_=g.useRef(!1),E=g.useCallback(()=>{_.current=!0,window.setTimeout(()=>{_.current=!1},300)},[]),R=J1(e),F=J1(e),A=qe(D=>D.profileRecents),N=qe(D=>D.rememberProfile),M=g.useCallback(async(D,L,V)=>{if(V.busy)return;const{result:j}=await V.run(D,L,D==="team"?"Could not switch the team":"Could not switch the agent");j.tone==="error"?zt(j.text):j.tone==="warning"?qh(j.text):j.tone==="success"&&N(D,L)},[N]);return c.jsxs("span",{"data-header-identity-controls":"",className:T("flex shrink-0 items-center gap-1"),children:[c.jsx(u3,{kind:"agent",triggerLabel:"Agent",label:f.agentLabel,current:f.agentValue,busy:F.busy,constraint:C,flagged:w,swapRef:_,markSwap:E,open:y==="agent",onOpenChange:D=>k(D?"agent":null),onPick:D=>void M("agent",D,F),sessionId:e,enabled:y==="agent",recents:A.agent}),c.jsx(u3,{kind:"team",triggerLabel:"Team",label:f.teamLabel,current:f.teamValue,busy:R.busy,constraint:null,flagged:!1,swapRef:_,markSwap:E,open:y==="team",onOpenChange:D=>k(D?"team":null),onPick:D=>void M("team",D,R),sessionId:e,enabled:y==="team",recents:A.team})]})},Pze=40,Ize=({agentName:e="Local Operator",description:t="Your on-device AI assistant",descriptionPending:n=!1,identity:s,deviceSlot:r,renameSessionId:i,sessionId:a,onOpenOptions:o,reserveTrailingChrome:l=!1,onToggleBrowser:u,archived:d=!1,archiveEnabled:h=!1,onSetArchived:f,deleteEnabled:p=!1,onRequestDelete:m,onOpenConsole:v,onOpenCodeReview:b,onToggleAsks:w,asksScope:C="session",asksOpen:y=!1})=>{Et();const k=Bn(),_=pa(k.data,"peers"),E=pa(k.data,"session_transfer"),R=a_(_)??a_(E)??void 0,F=vde(a_(_)!==null?_:E),A=sa(ge=>ge.requestPicker),[N,M]=g.useState(!1),D=g.useRef(!1),L=qe(ge=>ge.setCanvasOpen),V=qe(ge=>ge.isCanvasOpen),j=qe(ge=>ge.isCodeReviewPaneOpen),te=qe(ge=>ge.transcriptDisplayMode),X=WF(te),re=qe(ge=>ge.setTranscriptDisplayMode),G=qe(ge=>ge.setRunPanelOpen),J=MY(),ae=OY(t,J),O=ae!=="~"&&ae!=="",U=qe(ge=>ge.isBrowserPaneOpen),P=qe(ge=>ge.isConsolePaneOpen),z=qe(ge=>ge.isRunPanelOpen),ne=J1(i??""),fe=ne.busy,[ue,le]=g.useState(!1),[q,we]=g.useState(""),[B,be]=g.useState(null),ie=g.useRef("closed"),Te=g.useRef(null),ee=g.useRef(null),de=g.useRef(null),De=()=>{if(!i||ue)return;const ge=ee.current?.getBoundingClientRect();be(ge?Math.ceil(ge.width):null),we(e),ie.current="edit",le(!0)},Ue=ge=>{ie.current="closed",ge&&de.current?.focus(),le(!1)},Se=async ge=>{if(ie.current!=="edit")return;const Ae=q.trim();if(!Ae||Ae===e){Ue(ge);return}ie.current="saving";const{result:st}=await ne.run("rename",Ae,"Could not rename the conversation");if(st.tone==="error"){zt(st.text),ie.current==="saving"&&(ie.current="edit",Te.current?.focus());return}st.tone==="warning"&&qh(st.text),ie.current==="saving"&&Ue(ge)};return g.useEffect(()=>{if(!ue)return;const ge=Te.current;ge&&(ge.focus(),ge.select())},[ue]),c.jsxs("header",{"data-chat-region":"header","data-region-entry":!0,tabIndex:-1,className:T("@container/chathdr flex h-10 shrink-0 items-center gap-3 px-4"),"data-tour-tag":"chat-header","data-titlebar-drag":"",children:[c.jsxs("div",{className:T("flex h-5 min-w-0 flex-1 items-baseline gap-x-2 overflow-clip @[13.5rem]/chathdr:min-w-10",!s&&"flex-wrap","has-[[data-device-chip]]:[overflow-clip-margin:4px]"),children:[c.jsxs("span",{className:T("group/title inline-flex min-w-0 max-w-full items-center gap-1"),"data-titlebar-no-drag":"",children:[ue?c.jsx("input",{ref:Te,"data-header-rename-input":"",className:T("min-w-0 max-w-full border-0 bg-transparent p-0 outline-none","font-medium text-body text-ink"),style:B===null?void 0:{width:B},value:q,readOnly:fe,"aria-label":x("ui.chat.header.conversation_name"),onChange:ge=>we(ge.target.value),onKeyDown:ge=>{if(ge.key==="Enter")ge.preventDefault(),Se(!0);else if(ge.key==="Escape"){if(ge.preventDefault(),ie.current==="saving")return;Ue(!0)}},onBlur:()=>void Se(!1),spellCheck:!1}):c.jsx("h2",{ref:ee,"data-header-title":"",onDoubleClick:i?De:void 0,className:T("min-w-0 max-w-full truncate font-medium text-body text-ink","cursor-default select-none"),children:e}),i&&c.jsx("button",{ref:de,type:"button","data-header-rename":"","aria-label":fe?"Saving the conversation name":ue?"Cancel rename":"Rename conversation",title:fe?"Saving the conversation name":ue?"Cancel rename":"Rename conversation","aria-busy":fe||void 0,"aria-disabled":fe||void 0,onMouseDown:ge=>{ue&&ge.preventDefault()},onClick:ge=>{if(!(ge.detail>1)&&ie.current!=="saving"){if(!ue){De();return}Ue(!0)}},className:T("inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-xs","text-ink-dim","transition-opacity duration-base ease-out-quart",!ue&&"opacity-0 group-hover/title:opacity-100 group-hover/title:duration-fast",!ue&&"group-focus-within/title:opacity-100 group-focus-within/title:duration-fast","hover:text-ink-muted"),children:fe?c.jsx(pn,{size:"xs"}):ue?c.jsx(Dn,{className:T("size-3"),"aria-hidden":"true"}):c.jsx(Gk,{className:T("size-3"),"aria-hidden":"true"})})]}),n?c.jsx(Eb,{className:T("h-3 w-24 shrink-0 bg-elevated")}):s?c.jsx(Dze,{...s}):O?c.jsx("span",{"data-header-path":"",className:T("shrink-0 whitespace-nowrap font-mono text-ink-dim text-mono-sm"),title:t,children:LY(ae,Pze)}):null,r]}),c.jsxs("div",{"data-titlebar-no-drag":"",className:"ml-auto flex items-center gap-2",children:[h&&d&&c.jsxs(c.Fragment,{children:[c.jsxs(Ml,{shape:"pill","data-session-archived-pill":!0,title:x("ui.chat.header.archived_hint"),children:[c.jsx(Yh,{"aria-hidden":"true"}),x("ui.chat.header.archived")]}),f&&c.jsx(ce,{variant:"ghost",size:"icon",onClick:()=>f(!1),"aria-label":rx(e,!0),title:rx(e,!0),children:c.jsx(yx,{"aria-hidden":"true"})})]}),(h||p||w||u||v||o)&&c.jsxs(Il,{open:N,onOpenChange:M,children:[c.jsx(Ho,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon","data-conversation-actions":!0,"aria-label":x("ui.chat.header.actions"),children:c.jsx(nC,{"aria-hidden":"true"})})}),c.jsxs(Nl,{align:"end",className:"min-w-45",onCloseAutoFocus:ge=>{D.current&&(D.current=!1,a&&A(a),ge.preventDefault())},children:[a&&c.jsxs(Gt,{onSelect:()=>void dW(a),children:[c.jsx(Gl,{"aria-hidden":"true"}),c.jsx("span",{children:x("ui.chat.header.copy_id")})]}),a&&c.jsxs(Gt,{"data-session-move-action":!0,title:R,"data-move-reason":R,"aria-disabled":R?!0:void 0,onSelect:()=>{R||(D.current=!0)},className:T(R&&"cursor-not-allowed data-[highlighted]:bg-transparent data-[highlighted]:text-ink-muted"),children:[c.jsx(qse,{"aria-hidden":"true"}),c.jsxs("span",{className:"flex min-w-0 flex-col items-start gap-0.5",children:[c.jsx("span",{children:x("ui.chat.header.move_device")}),R?c.jsx("span",{className:T("max-w-[11rem] whitespace-normal text-meta",F==="dim"?"text-ink-dim":"text-warning"),children:R}):null]})]}),c.jsxs(LJ,{children:[c.jsxs(BJ,{children:[c.jsx(dre,{"aria-hidden":"true"}),c.jsx("span",{children:x("ui.chat.header.transcript_display")}),c.jsx("span",{className:"text-body-sm text-ink-dim",children:AZ(X)})]}),c.jsx(jJ,{children:c.jsx(HJ,{value:X,onValueChange:ge=>re(WF(ge)),children:FZ.map(ge=>c.jsxs(UJ,{value:ge.value,children:[c.jsx("span",{children:ge.label}),X===ge.value&&c.jsx(Bs,{"aria-hidden":"true",className:"ml-auto text-accent"})]},ge.value))})})]}),c.jsx(Yr,{}),h&&c.jsxs(Gt,{"data-session-archive-action":!0,onSelect:()=>f?.(!d),disabled:!f,children:[d?c.jsx(yx,{"aria-hidden":"true"}):c.jsx(Yh,{"aria-hidden":"true"}),c.jsx("span",{children:d?"Restore conversation":"Archive conversation"})]}),h&&p&&c.jsx(Yr,{}),p&&c.jsxs(Gt,{"data-session-delete":!0,className:"text-danger",onSelect:()=>m?.(),disabled:!m,children:[c.jsx(P0,{"aria-hidden":"true"}),c.jsx("span",{children:x("ui.chat.header.delete")})]}),(w||u||v||b||o)&&c.jsx(Yr,{}),(w||u||v||b||o)&&c.jsxs(Gt,{onSelect:()=>G(!z),children:[c.jsx(ap,{"aria-hidden":"true"}),c.jsx("span",{children:z?x("ui.chat.header.close_run_details"):x("ui.chat.header.open_run_details")})]}),w&&c.jsxs(Gt,{onSelect:()=>w(),children:[c.jsx(X5,{scope:C,"aria-hidden":!0}),c.jsx("span",{children:y?"Close asks":"Open asks"})]}),u&&c.jsxs(Gt,{onSelect:()=>u(),children:[c.jsx(qc,{"aria-hidden":"true"}),c.jsx("span",{children:U?"Close browser":"Open browser"})]}),v&&c.jsxs(Gt,{onSelect:()=>v(),children:[c.jsx(DT,{"aria-hidden":"true"}),c.jsx("span",{children:P?"Close console":"Open console"})]}),o&&c.jsxs(Gt,{onSelect:()=>L(!V),children:[c.jsx(qw,{"aria-hidden":"true"}),c.jsx("span",{children:V?"Close canvas":"Open canvas"})]}),b&&c.jsxs(Gt,{onSelect:()=>b(),children:[c.jsx(Kk,{"aria-hidden":"true"}),c.jsx("span",{children:j?"Close code review":"Open code review"})]})]})]})]}),l?c.jsx("div",{className:"chrome-reserve-trailing"}):null]})},qs=async(e,t,n,s,r,i,a)=>{a(e);try{const o={[e]:t};await s.mutateAsync({agentId:n,update:o}),r(l=>l?{...l,[e]:t}:null),i&&await i()}catch{}finally{a(null)}},_h=({label:e,description:t,defaultValue:n,onSetValue:s,icon:r})=>c.jsxs("div",{className:"flex flex-col rounded-md border border-control bg-surface p-4",children:[c.jsxs("div",{className:"mb-2",children:[c.jsxs("span",{className:"mb-1 flex items-center font-medium text-body-sm text-ink",children:[r,e]}),c.jsx("span",{className:"mb-3 text-body-sm text-ink-muted",children:t})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-meta text-ink-dim",children:"Not set yet"}),c.jsxs(ce,{variant:"outline",size:"sm",onClick:async()=>{await s(n)},children:["Set to default (",n,")"]})]})]}),d3=({label:e,description:t,defaultDisplayText:n,onSetValue:s,icon:r})=>c.jsxs("div",{className:"mb-4 flex flex-col rounded-md border border-control bg-surface p-4",children:[c.jsxs("div",{className:"mb-2",children:[c.jsxs("span",{className:"mb-1 flex items-center font-medium text-body-sm text-ink",children:[r,e]}),c.jsx("span",{className:"mb-3 text-body-sm text-ink-muted",children:t})]}),c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-meta text-ink-dim",children:"Not set yet"}),c.jsxs(ce,{variant:"outline",size:"sm",onClick:async()=>{await s()},children:["Set to default (",n,")"]})]})]}),Nze=({agent:e,savingField:t,setSavingField:n,setLocalAgent:s,refetchAgent:r,updateAgentMutation:i})=>c.jsxs("div",{className:"flex flex-col gap-4 pt-6",children:[c.jsxs("div",{children:[c.jsxs("h3",{className:"flex items-center font-semibold text-heading text-ink",children:[c.jsx("span",{className:"mr-2 flex items-center rounded-sm bg-accent-wash p-1 text-accent",children:c.jsx(Nf,{size:16,"aria-hidden":"true"})}),"Generation settings",c.jsx(Je,{content:"Settings that control how the agent generates responses",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",type:"button",className:"ml-1 text-accent","aria-label":"More info",children:c.jsx(ap,{"aria-hidden":"true"})})})]}),c.jsx("p",{className:"mt-1 text-body-sm text-ink-muted",children:"You can set custom values for these settings by updating the options below. If not set, default values will be used that are optimized based on user testing."})]}),e.temperature===null?c.jsx(_h,{label:"Temperature",description:"Controls randomness in responses (0.0-1.0). Higher values make output more random.",defaultValue:.2,onSetValue:async a=>{await qs("temperature",a,e.id,i,s,r,n)}}):c.jsx(ph,{value:e.temperature??.2,label:"Temperature",description:"Controls randomness in responses (0.0-1.0). Higher values make output more random.",min:0,max:1,step:.01,isSaving:t==="temperature",onChange:async a=>{await qs("temperature",a,e.id,i,s,r,n)}}),e.top_p===null?c.jsx(_h,{label:"Top P",description:"Controls cumulative probability of tokens to sample from (0.0-1.0).",defaultValue:.9,onSetValue:async a=>{await qs("top_p",a,e.id,i,s,r,n)}}):c.jsx(ph,{value:e.top_p??.9,label:"Top P",description:"Controls cumulative probability of tokens to sample from (0.0-1.0).",min:0,max:1,step:.01,isSaving:t==="top_p",onChange:async a=>{await qs("top_p",a,e.id,i,s,r,n)}}),e.top_k===null?c.jsx(_h,{label:"Top K",description:"Limits tokens to sample from at each step.",defaultValue:40,onSetValue:async a=>{await qs("top_k",a,e.id,i,s,r,n)}}):c.jsx(ph,{value:e.top_k??40,label:"Top K",description:"Limits tokens to sample from at each step.",min:1,max:100,step:1,isSaving:t==="top_k",onChange:async a=>{await qs("top_k",a,e.id,i,s,r,n)}}),e.max_tokens===null?c.jsx(_h,{label:"Max tokens",description:"Maximum tokens to generate in response.",defaultValue:4096,onSetValue:async a=>{await qs("max_tokens",a,e.id,i,s,r,n)}}):c.jsx(ph,{value:e.max_tokens??4096,label:"Max tokens",description:"Maximum tokens to generate in response.",min:1,max:8192,step:1,isSaving:t==="max_tokens",onChange:async a=>{await qs("max_tokens",a,e.id,i,s,r,n)}}),e.stop===null?c.jsx(d3,{label:"Stop sequences",description:"Sequences that will cause the model to stop generating text.",defaultValue:[],defaultDisplayText:"empty",icon:c.jsx(Pc,{size:16,className:"mr-2.5","aria-hidden":"true"}),onSetValue:async()=>{await qs("stop",[],e.id,i,s,r,n)}}):c.jsx(OP,{value:e.stop?.join(`
|
|
672
672
|
`)||"",label:"Stop sequences",placeholder:"Enter stop sequences (one per line)...",icon:c.jsx(Pc,{size:16}),multiline:!0,rows:3,isSaving:t==="stop",onSave:async a=>{const o=a.split(`
|
|
673
673
|
`).map(l=>l.trim()).filter(l=>l.length>0);await qs("stop",o.length>0?o:void 0,e.id,i,s,r,n)}}),e.frequency_penalty===null?c.jsx(_h,{label:"Frequency penalty",description:"Reduces repetition by lowering likelihood of repeated tokens (-2.0 to 2.0).",defaultValue:0,onSetValue:async a=>{await qs("frequency_penalty",a,e.id,i,s,r,n)}}):c.jsx(ph,{value:e.frequency_penalty??0,label:"Frequency penalty",description:"Reduces repetition by lowering likelihood of repeated tokens (-2.0 to 2.0).",min:-2,max:2,step:.01,isSaving:t==="frequency_penalty",onChange:async a=>{await qs("frequency_penalty",a,e.id,i,s,r,n)}}),e.presence_penalty===null?c.jsx(_h,{label:"Presence penalty",description:"Increases diversity by lowering likelihood of prompt tokens (-2.0 to 2.0).",defaultValue:0,onSetValue:async a=>{await qs("presence_penalty",a,e.id,i,s,r,n)}}):c.jsx(ph,{value:e.presence_penalty??0,label:"Presence penalty",description:"Increases diversity by lowering likelihood of prompt tokens (-2.0 to 2.0).",min:-2,max:2,step:.01,isSaving:t==="presence_penalty",onChange:async a=>{await qs("presence_penalty",a,e.id,i,s,r,n)}}),e.seed===null?c.jsx(d3,{label:"Seed",description:"Random number seed for deterministic generation.",defaultValue:42,defaultDisplayText:"42",icon:c.jsx(Pc,{size:16,className:"mr-2.5","aria-hidden":"true"}),onSetValue:async()=>{await qs("seed",42,e.id,i,s,r,n)}}):c.jsx(OP,{value:e.seed?.toString()||"",label:"Seed",placeholder:"Random number seed for deterministic generation",icon:c.jsx(Pc,{size:16}),isSaving:t==="seed",onSave:async a=>{const o=a.trim()?Number.parseInt(a,10):void 0;if(a.trim()&&Number.isNaN(o)){zt("Seed must be a valid number");return}await qs("seed",o,e.id,i,s,r,n)}})]}),Mze=e=>({id:e.id,name:e.name||e.info.name||e.id,description:e.info.description,contextWindow:e.info.context_window||void 0,maxOutputTokens:e.info.max_tokens||void 0,supportsImages:e.info.supports_images||void 0,inputPrice:e.info.input_price,outputPrice:e.info.output_price,recommended:e.info.recommended||!1}),Oze=(e,t)=>({id:e.id,name:e.name,description:e.description,url:e.url,requiredCredentials:e.requiredCredentials,supportedModels:t.map(Mze)});let I1=null,h3=null,f3=null,p3=null;const Z2=()=>{const e=td.getState(),{providers:t,models:n,isInitialized:s}=e;if(I1&&h3===n&&f3===t&&p3===s)return I1;if(!s||t.length===0)return[];const r=t.map(i=>{const a=n.filter(o=>o.provider===i.id);return Oze(i,a)});return I1=r,h3=n,f3=t,p3=s,r},Yf=e=>Z2().find(n=>n.id===e),Fk=e=>Yf(e)?.supportedModels||[],Lze=e=>Z2().filter(n=>n.requiredCredentials.every(s=>e.includes(s))),OW=({value:e,onSave:t,isSaving:n=!1,filterByCredentials:s=!0,emptyHelperText:r=x("ui.common.models.hosting_select.no_hosting_providers_available_sign_in_to_a_provider_or_add_a_pro"),allowCustom:i=!0,allowDefault:a=!0})=>{Et();const o=Bn(),l=yt(o.data,"auth"),u=R0(l),{data:d}=gB(),h=g.useMemo(()=>d?.keys||[],[d]),{refreshModels:f,isInitialized:p,providers:m}=cT(),[v,b]=g.useState(!1),w=g.useMemo(()=>BY({data:u.data,isError:u.isError}),[u.data,u.isError]),C=l&&w.status==="failed",y=g.useMemo(()=>{const A=Z2();return s?l?jY(A,w):Lze(h):A},[s,l,w,h,p,m]),k=(()=>{const A=[];a&&A.push({id:"",name:x("ui.common.models.default"),description:x("ui.common.models.hosting_select.clear_hosting_provider_selection"),provider:void 0});for(const N of y)A.push({id:N.id,name:N.name,description:N.description,provider:N});if(e&&!y.some(N=>N.id===e)){const N=Yf(e);N?A.push({id:N.id,name:N.name,description:C?N.description:x("ui.common.models.hosting_select.detail",{description:String(N.description)}),provider:N}):i&&A.push({id:e,name:e,description:x("ui.common.models.hosting_select.custom_hosting_provider"),provider:{id:e,name:e,description:x("ui.common.models.hosting_select.custom_hosting_provider"),url:"",requiredCredentials:[],supportedModels:[]}})}return A})(),_=(()=>{if(s&&C)return HY(u.error);if(s&&y.length===0&&!e)return r})(),E=!e&&!a||!a&&y.length===0&&!k.some(A=>A.id===e&&e!=="")?null:!e&&a?k.find(A=>A.id==="")||null:e?k.find(A=>A.id===e)||{id:e,name:e,description:x("ui.common.models.hosting_select.custom_hosting_provider"),provider:void 0}:null,R=async A=>{try{if(b(!0),await t(A),A!==e)try{await f()}catch(N){console.error("Error refreshing models after hosting provider change:",N)}}catch(N){console.error("Error saving hosting provider:",N)}finally{b(!1)}},F=!a&&s&&!C&&y.length===0&&!k.some(A=>A.id===e&&e!=="");return c.jsx(gT,{label:x("ui.common.models.hosting_select.hosting_provider"),icon:c.jsx(mB,{size:16,"aria-hidden":"true"}),labelTooltip:x("ui.common.models.hosting_select.select_the_ai_provider_that_you_want_to_use_each_provider_has_dif"),placeholder:x("ui.common.models.hosting_select.select_a_hosting_provider"),options:k,selected:E,onSelect:A=>{R(A.id)},onCustomSubmit:i?A=>{R(A)}:void 0,helperText:_,busy:n||v,busyLabel:x("ui.common.models.hosting_select.saving_hosting_provider"),disabled:F})},g3=(e,t,n)=>{const s=e.find(i=>i.id===t);if(s)return s;if(!n||!Yf(n))return;const r=`${n}/`;if(t.startsWith(r)){const i=t.slice(r.length);return i?e.find(a=>a.id===i):void 0}return e.find(i=>i.id===`${r}${t}`)},Bze=e=>{if(!e||typeof e!="string")return"";const t=e.indexOf("/");return t>0?e.substring(0,t):""},N1=(e,t)=>{if(t==="radient"&&e==="auto")return x("ui.common.models.model_select.auto_recommended");if(e==="")return x("ui.common.models.model_select.general");const n=Bze(e);if(t==="radient"&&n==="radient")return"Radient";const s=Yf(n);return s?s.name:n||x("ui.common.models.model_select.other_models")},jze=({markdown:e})=>c.jsx("div",{className:"[&_p]:m-0",children:c.jsx(UY,{components:{a:({href:t,children:n})=>c.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:underline",children:n})},children:e})}),Hze=()=>(Et(),c.jsx(Je,{content:x("ui.common.models.model_select.recommended_based_on_community_usage_and_feedback"),children:c.jsxs("span",{className:"flex items-center text-warning",children:[c.jsx(Ore,{size:12,"aria-hidden":"true"}),c.jsx("span",{className:"sr-only",children:x("ui.common.models.model_select.recommended")})]})})),LW=({value:e,hostingId:t,onSave:n,isSaving:s=!1,allowCustom:r=!0,allowDefault:i=!0})=>{Et();const[a,o]=g.useState(!1),l=td(_=>_.models),u=td(_=>_.isInitialized),d=g.useMemo(()=>t?Fk(t):[],[t,l,u]),{refreshModels:h,isLoading:f}=cT(),p=g.useRef(null),m=g.useRef(null),v=g.useRef(!0);g.useEffect(()=>{if(v.current){v.current=!1,p.current=t;return}if(t&&p.current!==t)return p.current=t,m.current&&(clearTimeout(m.current),m.current=null),m.current=setTimeout(()=>{f||h().catch(_=>{console.error("Error refreshing models:",_)}),m.current=null},300),()=>{m.current&&(clearTimeout(m.current),m.current=null)}},[t,h,f]);const b=(()=>{const _=[],E=new Set,R=new Set(d.map(N=>N.id)),F=!!Yf(t),A=N=>({id:N.id,name:N.name,keywords:[N.id,...F&&!R.has(`${t}/${N.id}`)?[`${t}/${N.id}`]:[]],description:N.description?c.jsx(jze,{markdown:N.description}):void 0,adornment:N.recommended?c.jsx(Hze,{}):void 0,group:N1(N.id,t),model:N,recommended:N.recommended});if(t==="radient"){const N=d.find(M=>M.id==="auto");N&&(_.push(A(N)),E.add(N.id))}i&&!E.has("")&&(_.push({id:"",name:x("ui.common.models.default"),description:x("ui.common.models.model_select.clear_model_selection"),group:N1("",t),model:void 0}),E.add(""));for(const N of d)E.has(N.id)||(_.push(A(N)),E.add(N.id));return e&&e.trim()!==""&&!g3(_,e,t)&&_.push({id:e,name:e,description:x("ui.common.models.model_select.custom_model"),group:N1(e,t),model:void 0}),_})(),w=(()=>{if(!t&&!i)return x("ui.common.models.model_select.select_a_hosting_provider_first");if(t&&d.length===0&&!i&&!b.some(_=>_.id===e&&e!==""))return x("ui.common.models.model_select.no_models_available_for_selected_provider");if(d.length===0&&t&&!b.some(_=>_.id===e&&e!=="")){const _=Yf(t);return _?x("ui.common.models.model_select.no_models_for",{name:String(_.name)}):x("ui.common.models.model_select.no_models_available")}})(),C=(()=>{if((!e||e.trim()==="")&&!i&&d.length===0)return null;if((!e||e.trim()==="")&&i)return b.find(E=>E.id==="")||null;if(!e||e.trim()==="")return null;const _=g3(b,e,t);return _||{id:e,name:e,description:x("ui.common.models.model_select.custom_model"),model:void 0}})(),y=async _=>{try{o(!0),await n(_)}catch(E){console.error("Error saving model:",E)}finally{o(!1)}},k=!!(!t&&!i||t&&d.length===0&&!i&&!b.some(_=>_.id===e&&e!==""));return c.jsx(gT,{label:x("ui.common.models.model_select.model"),icon:c.jsx(tse,{size:16,"aria-hidden":"true"}),labelTooltip:x("ui.common.models.model_select.select_the_ai_model_that_you_want_to_use_each_model_has_different"),placeholder:x("ui.common.models.model_select.select_a_model"),options:b,selected:C,onSelect:_=>{y(_.id)},onCustomSubmit:r?_=>{y(_)}:void 0,helperText:w,busy:s||a||f,busyLabel:x("ui.common.models.model_select.loading_models"),disabled:k})},Uze=({agent:e,savingField:t,setSavingField:n,setLocalAgent:s,refetchAgent:r,updateAgentMutation:i})=>c.jsxs(c.Fragment,{children:[c.jsxs("h3",{className:"mt-6 mb-4 flex items-center font-semibold text-heading text-ink",children:[c.jsx("span",{className:"mr-2 flex items-center rounded-sm bg-accent-wash p-1 text-accent",children:c.jsx(mB,{size:16,"aria-hidden":"true"})}),"Model and hosting",c.jsx(Je,{content:"Configure which model and hosting provider to use",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",type:"button",className:"ml-1 text-accent","aria-label":"More info",children:c.jsx(ap,{"aria-hidden":"true"})})})]}),c.jsxs("div",{className:"mb-4 flex flex-col gap-4 rounded-md border border-hairline bg-sunken p-4",children:[c.jsx(OW,{value:e.hosting||"",isSaving:t==="hosting",onSave:async a=>{await qs("hosting",a,e.id,i,s,r,n)}}),c.jsx(LW,{value:e.model||"",hostingId:e.hosting||"",isSaving:t==="model",onSave:async a=>{await qs("model",a,e.id,i,s,r,n)}})]})]}),Gze=({agentId:e})=>{const[t,n]=g.useState(!1),s=Xj(),r=()=>{s.mutate({agentId:e}),n(!1)};return c.jsxs("div",{children:[c.jsxs(ce,{variant:"danger",className:"mb-4 mt-6 w-full",onClick:()=>n(!0),children:[c.jsx(P0,{"aria-hidden":"true"}),"Clear conversation"]}),c.jsx(au,{open:t,title:"Clear this conversation?",message:"Every message in it is deleted from this computer, and there is no undo. The agent itself is not affected.",confirmText:"Clear",cancelText:"Cancel",isDangerous:!0,onConfirm:r,onCancel:()=>n(!1)})]})},Vze=({open:e,onClose:t,agentId:n})=>{const[s,r]=g.useState(null),i=Qae(),{data:a,refetch:o,isLoading:l}=fie(n),[u,d]=g.useState(null);return g.useEffect(()=>{a&&d(a)},[a]),!u||l?null:c.jsx(GJ,{open:e,onOpenChange:h=>!h&&t(),children:c.jsxs(VJ,{side:"right",showClose:!1,className:"w-[380px] max-w-[380px] gap-0 bg-surface p-0",children:[c.jsxs("div",{className:"flex items-center justify-between border-hairline border-b px-6 py-4",children:[c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx(WJ,{className:"font-semibold text-heading text-ink",children:"Chat options"}),c.jsx($J,{className:"text-body-sm text-ink-muted",children:"Customize settings for this agent"})]}),c.jsx(ce,{variant:"ghost",size:"icon",onClick:t,"aria-label":"Close",children:c.jsx(Dn,{"aria-hidden":"true"})})]}),c.jsxs("div",{className:"grow overflow-y-auto px-6 py-4",children:[c.jsx(Uze,{agent:u,savingField:s,setSavingField:r,setLocalAgent:d,refetchAgent:o,updateAgentMutation:i}),c.jsx(Nze,{agent:u,savingField:s,setSavingField:r,setLocalAgent:d,refetchAgent:o,updateAgentMutation:i}),n&&c.jsx(Gze,{agentId:n})]})]})})},vb={unreachable:"Can't reach the Local Operator server. Sending will wait.","credential-refused":"The running server refused this app's credential, so sign-in, settings and slash commands are unavailable.",degraded:"The server is answering slowly. Your messages are queued.","internet-offline":"This machine is offline. Sending will wait."};function m3(e){return{state:e.state,reconnecting:e.reconnecting??!1,detail:e.detail??null,pairing:e.pairing??null,addressSubstitution:null}}function Wze(e){const{server:t,connectivityIssue:n}=e;if(t&&t.pairing?.cause==="credential-refused"&&t.state!=="detached")return{kind:"credential-refused",cause:"credential-refused",role:"alert",wash:"danger-wash",title:vb["credential-refused"],detail:cF(m3(t))?.detail??null,action:"retry",actionLabel:"Retry",dot:"danger"};if(n==="internet_offline"&&e.internetOffline)return{kind:"internet-offline",role:"status",wash:"warning-wash",title:vb["internet-offline"],detail:null,action:"retry",actionLabel:"Retry",dot:"warning"};if(t!==null&&uF(t.state)&&(t.reconnecting===!0||t.state==="degraded"))return{kind:"degraded",role:"status",wash:"warning-wash",title:vb.degraded,detail:null,action:"retry",actionLabel:"Retry",dot:"warning"};const s=t?.pairing??null;return!(s?.available===!1&&s.cause!=="credential-refused")&&(n==="server_offline"||t!==null&&!uF(t.state))?{kind:"unreachable",role:"alert",wash:"danger-wash",title:vb.unreachable,detail:t?cF(m3(t))?.detail??null:null,action:"retry",actionLabel:"Retry",dot:"danger"}:null}function BW(e){return e?`${e.kind}:${e.cause??""}`:null}const $ze=({display:e,dismissedKey:t,onDismiss:n,onShow:s,retrying:r=!1,outcome:i=null,onRetry:a})=>{const o=BW(e),l=o!==null&&t===o,u=g.useCallback(d=>{d.key!=="Escape"||!o||(d.stopPropagation(),n(o))},[o,n]);return e?l?c.jsx("div",{className:T("flex items-center px-6 py-1"),"data-lo-status-pill":"",children:c.jsxs("button",{type:"button",onClick:s,className:T("flex h-6 items-center gap-1.5 rounded-sm px-2","text-meta text-ink-muted hover:text-ink","focus-visible:outline-2 focus-visible:outline-accent"),"aria-label":`Connection status: ${e.title}${i?` ${i}`:""} Show details`,children:[c.jsx("span",{"aria-hidden":"true",className:T("size-1.5 rounded-full",e.dot==="danger"?"bg-danger":"bg-warning")}),e.kind==="internet-offline"?"Offline":"Connection"]})}):c.jsx("div",{className:T("shrink-0 px-6 py-1"),"data-lo-status-strip":"",onKeyDown:u,children:c.jsx(Kr,{variant:e.wash==="danger-wash"?"danger":"warning",className:nR,role:e.role,children:c.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2",children:[c.jsxs("span",{className:"min-w-0 flex-1 text-body-sm text-ink",children:[e.title,e.detail?c.jsx("span",{className:"block text-meta text-ink-muted",children:e.detail}):null,i&&!r?c.jsx("span",{className:"block text-meta text-ink-muted",children:i}):null]}),e.action==="retry"&&c.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[c.jsxs(ce,{variant:"primary",size:"sm",type:"button",onClick:a,disabled:r,children:[r?c.jsx(Ui,{"aria-hidden":"true",className:"animate-spin"}):null,r?"Retrying…":e.actionLabel??"Retry"]}),c.jsx("button",{type:"button",onClick:()=>o&&n(o),className:T("flex size-6 items-center justify-center rounded-sm","text-ink-muted hover:text-ink","focus-visible:outline-2 focus-visible:outline-accent"),"aria-label":"Dismiss",children:c.jsx(Dn,{"aria-hidden":"true",className:"size-3.5"})})]})]})})}):null},zze=()=>{const{connectivityIssue:e,serverSnapshot:t,refetchServerStatus:n}=GY(),[s,r]=g.useState(!1),i=g.useRef(Yj());g.useEffect(()=>{const C=()=>r(qae(i.current,{isOnline:navigator.onLine,at:Date.now()}).report);return C(),window.addEventListener("offline",C),window.addEventListener("online",C),()=>{window.removeEventListener("offline",C),window.removeEventListener("online",C)}},[]);const a=e==="server_offline"||e==="internet_offline"?e:null,o=g.useMemo(()=>Wze({connectivityIssue:a,server:t,internetOffline:s}),[a,t,s]),l=o!==null;g.useEffect(()=>(cI(l),()=>cI(!1)),[l]);const[u,d]=g.useState(null),[h,f]=g.useState(!1),[p,m]=g.useState(null),v=g.useRef(null),b=BW(o);g.useEffect(()=>{p!==null&&v.current!==b&&(v.current=null,m(null))},[b,p]);const w=g.useCallback(async()=>{f(!0),m(null),v.current=b;try{await window.api?.backend?.reconnect?.()}finally{f(!1),m(b?.startsWith("credential-refused")?"The server is running, but this app's credential is still refused.":"Still unreachable."),n()}},[b,n]);return c.jsx($ze,{display:o,dismissedKey:u,onDismiss:d,onShow:()=>d(null),retrying:h,outcome:p,onRetry:()=>void w()})},qze="This backend cannot delete conversations. Update the backend and try again.";function Kze(e,t){const s=`Every message in ${`“${e}”`} is permanently removed from this machine. This cannot be undone.`;return t?`${s} The subagent runs it started are kept.`:s}const Yze="The guard above is the daemon's own, and nothing in this window can clear it: clear it where the session runs - stop it there, or cancel the wake it names - and ask again.",Xze=({title:e,hasSubagentRuns:t})=>{Et();const n=Ce(p=>p.deleteCandidate),s=Ce(p=>p.sessions),r=Ce(p=>p.requestSessionDelete),i=Ce(p=>p.deleteSession),[a,o]=g.useState(null),l=a&&a.candidate===n?a:null,[u,d]=g.useState(0),h=g.useRef(null);g.useEffect(()=>{if(n!==null){h.current=document.activeElement instanceof HTMLElement?document.activeElement:null;return}const p=h.current;if(h.current=null,!!p){if(p.isConnected){p.focus();return}document.querySelector("[data-conversation-actions]")?.focus()}},[n]);const f=s.find(p=>p.session_id===n)?.title||e;return c.jsx(au,{open:n!==null,title:x("ui.chat.dialogs.delete_title"),message:c.jsxs(c.Fragment,{children:[c.jsx("p",{children:Kze(f,t)}),l&&c.jsx("p",{className:"pt-2 text-danger",children:l.detail}),l?.guarded&&c.jsx("p",{className:"pt-2 text-ink-muted",children:Yze})]}),confirmText:x("ui.chat.dialogs.delete_action"),cancelText:x("ui.chat.dialogs.cancel"),isDangerous:!0,focusCancelSignal:u,onConfirm:()=>{n&&(async()=>{const p=await i(n);p.ok||(o({candidate:n,detail:p.detail,guarded:p.guarded}),d(m=>m+1))})()},onCancel:()=>r(null)})},Qze=[],Jze=[{id:"canonical",role:"system",timestamp:new Date(0)}],Zze={},eqe=(e,t=!1)=>!!(e&&sX({status:e.view.status,failure:e.view.failure,stale:e.view.stale,missing:e.view.missing||t})),v3=(e,t=!1)=>!!(e&&xB({status:e.view.status,failure:e.view.failure,stale:e.view.stale,missing:e.view.missing||t})),bb={openTabs:[],selectedTabId:null,files:[],mentionedFiles:[]},b3=640,tqe=1200,nqe=1200,sqe=kb,rqe=$e.memo(({activeTab:e,onTabChange:t,agentName:n,description:s,descriptionPending:r,identity:i,deviceSlot:a,deviceNotice:o,deviceHold:l,renameSessionId:u,onOpenOptions:d,isOptionsSidebarOpen:h,onCloseOptions:f,agentId:p,messages:m,isLoading:v,isLoadingMessages:b,isFarFromBottom:w,hasNewActivity:C=!1,messagesContainerRef:y,scrollToBottom:k,rawInfoContent:_,onSendMessage:E,currentJobId:R,onCancelJob:F,onComposerInput:A,agentData:N,messageInputRef:M,cwd:D,sessionId:L,turnTerminal:V,cwdWritePath:j,cwdPending:te,cwdPendingAccepted:X,cwdReadOnlyReason:re,sendError:G,sessionStatus:J,onSlashCommand:ae,onSlashNote:O,paneHasSession:U,canonical:P,undelivered:z=null,runDetails:ne,mcpServers:fe=[],mcpGrantRunning:ue=!1,mcpRemedy:le,monitorControls:q,wakeControls:we,jobControls:B,wakeAida:be,childrenOpenable:ie=!1,mentionsEnabled:Te=!1,mentionsUnsupported:ee=!1,pulses:de})=>{const[De,Ue]=g.useState(!1),Se=J4(),ge=nn(),Ae=g.useCallback(Ge=>ge.invalidateQueries({queryKey:Bo.credentials(Ge)}),[ge]),st=g.useRef(null),vt=g.useRef(null),me=vB(P?.view.frontend),it=z!==null&&P.view.transcript.records.some(Ge=>Ge.kind==="user"&&Ge.id===z.recordId)?z:null,ct=Bn(),{needsProvider:Qe,needsModel:Nt}=VY(),Tt=yt(ct.data,"session_archive"),At=yt(ct.data,"session_delete"),sn=yt(ct.data,"aside_adopt_queue"),Ut=Lg(Ge=>L?Ge.attached[L]?.queued?.messageIds.length??-1:-1),rt=P.view.transcript.index;g.useEffect(()=>{Ut<0||!L||WY(L,Ge=>rt.has(Ge),P.turnAlive)},[Ut,L,rt,P.turnAlive]);const An=pa(ct.data,"code_requests"),On=bB(),ks=Hfe({sessionId:L,state:An,cause:On??null,loadError:ct.data?null:ct.error}),js=Ce(Ge=>L?(Ge.archiveFacts[L]?.archived??Ge.sessions.find(jn=>jn.session_id===L)?.archived)===!0:!1),sr=Ce(Ge=>L?Ge.forgotten[L]!==void 0:!1),rs=Ce(Ge=>L?Ge.sessions.some(jn=>jn.session_id===L):!1),Hr=sr||P?.view.missing===!0&&!rs,Ts=sr||P?.view.missing===!0,rr=P?.stopOutcome==="pending"||P?.stopOutcome==="awaiting-end",Ot=rr&&P?.turnAlive===!0,br=v3(P,Hr),an=g.useMemo(()=>$Y(P?.view.history),[P?.view.history]),ms=g.useMemo(()=>P?.stopAvailable&&!br?{active:P.turnAlive,stopping:Ot,onStop:P.onStop}:void 0,[P?.stopAvailable,br,P?.turnAlive,Ot,P?.onStop]),ir=Ce(Ge=>Ge.setSessionArchived),Rs=Ce(Ge=>Ge.requestArchiveConfirm),is=g.useCallback(Ge=>{if(L){if(!Ge){ir(L,!1,n);return}Rs({sessionId:L,fromRow:!1,fromHeader:!0,title:n})}},[L,n,ir,Rs]),Ie=Ce(Ge=>Ge.requestSessionDelete);g.useEffect(()=>{if(!st.current)return;const Ge=new ResizeObserver(jn=>{for(const Zn of jn)Zn.contentRect.width<550?Ue(!0):Ue(!1)});return Ge.observe(st.current),()=>{Ge.disconnect()}},[]);const Ne=qe(Ge=>Ge.rightSlotWidth),Le=qe(Ge=>Ge.setRightSlotWidth),Ee=qe(Ge=>Ge.restoreDefaultRightSlotWidth),Ze=p,H=Ce(Ge=>Ze?Ge.stoppedTurns[Ze]??null:null),K=g.useMemo(()=>{if(H===null||!P)return null;const Ge=P.view.transcript.records;for(let jn=Ge.length-1;jn>=0;jn-=1){const Zn=Ge[jn];if(Zn.kind==="user")return Zn.text}return null},[H,P]),W=ls(Ge=>Ge.conversations[Ze]),Y=qe(Ge=>Ge.isCanvasOpen),Q=Y&&(W?.viewMode??"documents")==="files",Z=g.useMemo(()=>Q&&P?{active:!0,hasMore:P.view.transcript.hasMore,oldestId:P.view.transcript.oldestId,loadOlder:P.view.loadOlder,blocked:P.view.loadingOlder}:null,[Q,P]),ve=Ce(Ge=>L?G4(Ge.sessions,Ge.placementFacts,L):!1),Pe=ct.data!==void 0&&!yt(ct.data,"session_files")&&!ve,xe=Mpe({conversationId:Ze,records:P?.view.transcript.records??null,cwd:P?.view.frontend?.cwd,sessionId:L,enabled:!!(P?.view.frontend&&!P.view.awaitingHydration&&p&&Pe),scan:Z}),ye=ls(Ge=>Ge.setOpenTabs),Re=ls(Ge=>Ge.setSelectedTab),ze=ls(Ge=>Ge.setFiles),at=qe(Ge=>Ge.isRunPanelOpen),pt=qe(Ge=>Ge.setRunPanelOpen),[_e,Ye]=g.useState(null),St=at&&_e===null;g.useEffect(()=>{at||Ye(null)},[at]);const rn=(W??bb).openTabs,Jt=(W??bb).selectedTabId,bn=(W??bb).files,xr=e8(L,!0,V),Zr=xr.mode==="index"?xr.total:(W??bb).mentionedFiles.length,ar=Math.max(yv,Ne===0?_v:Ne),ei=qe(Ge=>Ge.isBrowserPaneOpen),_a=qe(Ge=>Ge.setBrowserPaneOpen),or=Math.max(zF,Ne===0?_v:Ne),Sa=qe(Ge=>Ge.isConsolePaneOpen),tc=qe(Ge=>Ge.isCodeReviewPaneOpen),As=qe(Ge=>Ge.isAskDrawerOpen),gu=qe(Ge=>Ge.askDrawerScope),Ep=As&&gu==="session"&&!!L,Gi=qe(Ge=>Ge.setAskDrawerOpen),Qo=qe(Ge=>Ge.requestAskOpen),nh=qe(DZ),so=g.useMemo(()=>dF(P?.view.frontend??null),[P?.view.frontend]),kp=qpe({sessionId:L,composerId:Ze,view:so}),Tp=lB(),ro=!!L,Ci=ro?"session":"fleet",Jo=ro?zY(so):Tp.outstanding,lr=As&&gu===Ci,Vi=qe(Ge=>Ge.setRightSlotRoute),Ea=!!L;g.useLayoutEffect(()=>{Vi({mounted:!0,session:Ea})},[Vi,Ea]),g.useLayoutEffect(()=>()=>Vi(PZ),[Vi]);const ti=qe(Ge=>Ge.setConsolePaneOpen),Zo=qe(Ge=>Ge.requestConsoleOpen),Wi=Math.max(qF,Ne===0?_v:Ne),Hs=qe(Ge=>Ge.setCodeReviewPaneOpen),el=Math.max(yv,Ne===0?_v:Ne),mu=qe(Ge=>Ge.consoleUnseen),vu=g.useMemo(()=>L===null?[]:mu.filter(Ge=>Ge.sessionId===L),[mu,L]),bu=Y5(vu),xu=O4(L??null,{visible:!1,sessionLive:!1}).data?.rows??[],$i=L4(xu),wu=qY(xu),nc=Cfe(L??null),nl=g.useRef(null),io=g.useRef(null),ao=g.useRef(null),[sc,Cu]=g.useState(ar),[oo,sh]=g.useState(ar);g.useLayoutEffect(()=>{if(!at)return;const Ge=nl.current;if(!Ge)return;const jn=()=>{const Ra=Ge.getBoundingClientRect().width;if(Ra<=0)return;Cu(fo=>Math.abs(fo-Ra)<1?fo:Ra);const lc=io.current,as=ao.current;if(!lc||!as)return;const Aa=Number.parseFloat(getComputedStyle(as).minWidth)||sqe,cc=lc.getBoundingClientRect().width-Aa;sh(fo=>Math.abs(fo-cc)<1?fo:cc)};jn();const Zn=new ResizeObserver(jn);return Zn.observe(Ge),io.current&&Zn.observe(io.current),ao.current&&Zn.observe(ao.current),()=>Zn.disconnect()},[at]);const[ni,sl]=g.useState(0);g.useLayoutEffect(()=>{const Ge=io.current;if(!Ge)return;const jn=()=>sl(Ge.getBoundingClientRect().width);jn();const Zn=new ResizeObserver(jn);return Zn.observe(Ge),()=>Zn.disconnect()},[]);const ka=NZ(ni||Number.MAX_SAFE_INTEGER)==="docked",wr=qe(Ge=>IZ(ni,Ge)),yi=wv({capacity:oo,min:yv,max:b3,drawn:sc}),si=g.useCallback(Ge=>{yi.resizable&&Le(Ge)},[yi.resizable,Le]),rc=g.useCallback(()=>{si(0)},[si]),ic=ni>0?Math.max(0,ni-kb):or,Ln=wv({capacity:ic,min:zF,max:tqe,drawn:Math.min(or,ic)}),ac=g.useCallback(Ge=>{Ln.resizable&&Le(Ge)},[Ln.resizable,Le]),lo=g.useCallback(()=>{ac(0)},[ac]),oc=ni>0?Math.max(0,ni-kb):Wi,Dt=wv({capacity:oc,min:qF,max:nqe,drawn:Math.min(Wi,oc)}),co=g.useCallback(Ge=>{Dt.resizable&&Le(Ge)},[Dt.resizable,Le]),Ta=g.useCallback(()=>{co(0)},[co]),uo=ni>0?Math.max(0,ni-kb):el,Cr=wv({capacity:uo,min:yv,max:b3,drawn:Math.min(el,uo)}),ho=g.useCallback(Ge=>{Cr.resizable&&Le(Ge)},[Cr.resizable,Le]),yu=g.useCallback(()=>{ho(0)},[ho]),_u=g.useCallback(Ge=>Re(Ze,Ge),[Ze,Re]),Fe=g.useCallback(()=>{qe.getState().setCanvasOpen(!1)},[]),bt=g.useCallback(Ge=>{Gi(!1,"session",Ge)},[Gi]),Kt=g.useCallback(Ge=>{const jn=rn.filter(Ra=>Ra.id!==Ge),Zn=bn.filter(Ra=>Ra.id!==Ge);ye(Ze,jn),ze(Ze,Zn),Jt===Ge&&Re(Ze,X2(bn,Ge)?.id??null)},[Ze,bn,rn,Jt,ze,ye,Re]),Ht=qB(),Fn=(Ge,jn)=>jn;return c.jsxs("div",{ref:io,"data-tour-tag":"pane-row",className:"relative flex h-full w-full flex-row overflow-hidden",children:[c.jsx("output",{"data-ask-open-announcer":"",className:"sr-only","aria-live":"polite",children:kp}),c.jsx("div",{ref:ao,"data-tour-tag":"chat-column",className:"relative h-full w-0 min-w-[480px] flex-1",children:c.jsxs("div",{ref:st,"data-glass-region":"canvas",className:"flex h-full min-h-0 grow flex-col overflow-hidden rounded-none bg-canvas",children:[c.jsx(Ize,{agentName:n,description:s,descriptionPending:r,identity:i,deviceSlot:a,renameSessionId:u,sessionId:L,onOpenOptions:d,reserveTrailingChrome:!nh,onToggleBrowser:()=>_a(!ei),onToggleAsks:()=>{if(lr){Gi(!1,Ci,{dismissSlot:!0});return}Gi(!0,Ci),Qo(Ci)},asksScope:Ci,asksOpen:lr,archiveEnabled:Tt,archived:js,onSetArchived:L?Ge=>is(Ge):void 0,deleteEnabled:At,onRequestDelete:L?()=>Ie(L):void 0,onOpenConsole:L?()=>{ti(!0),Zo(L)}:()=>ti(!Sa),onOpenCodeReview:()=>Hs(!qe.getState().isCodeReviewPaneOpen)}),o,c.jsx(zze,{}),c.jsx(ope,{}),c.jsx(bpe,{}),At&&c.jsx(Xze,{title:n,hasSubagentRuns:(ne?.lineage.length??0)>0}),!P&&c.jsx(Vze,{open:h,onClose:f,agentId:p}),Ht,Fn("chat",c.jsx(k4,{frontend:P.view.frontend,transcript:P.view.transcript,openFrame:an,undelivered:it,gate:me,waiting:P.turnAlive,starting:P.starting===!0,startingAfterId:P.startingAfterId??null,startingSession:P.startingSession===!0,startingSince:P.startingSince??null,stopping:rr,onInterruptTurn:ms?.onStop,idleDisputed:P.idleDisputed===!0,loadingOlder:P.view.loadingOlder,onLoadOlder:P.view.loadOlder,onLoadOlderOutcome:P.view.loadOlderDetailed,olderFailed:P.view.olderFailed,containerRef:y,isSmallView:De,status:P.view.status,failure:P.view.failure,awaitingHydration:P.view.awaitingHydration,hydrationProven:P.view.hydrated,historyReadPending:P.view.historyReadPending,onRetryHydration:P.view.rehydrate,conversationId:Ze,labelPending:P.view.labelPending,labelHoldLate:P.view.labelHoldLate,labelMarked:P.view.labelMarked,onReconnect:P.view.retry,stale:P.view.stale,missing:Hr})),me!==null&&c.jsx("div",{className:T(pF,fF,"w-full shrink-0 pt-2"),children:c.jsx(Kle,{className:hF,gate:me,onAnswer:P.onAnswer,onAnswerSecret:P.onAnswerSecret,answering:!!P.admitting,answer:P.answer??null},me.request_id)}),H!==null&&!P.turnAlive&&P.stopOutcome!=="unconfirmed"&&c.jsx("div",{className:T(pF,fF,"w-full shrink-0 pt-2"),children:c.jsxs("p",{"data-stopped-turn":!0,className:T("flex items-center gap-2 text-ink-dim text-meta",hF),children:[c.jsx("span",{children:"Stopped"}),K!==null&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",children:"·"}),c.jsx("button",{type:"button","data-stopped-retry":!0,onClick:()=>void E(K,[]),className:"rounded-sm text-ink-muted underline-offset-2 transition-colors duration-fast ease-out-quart hover:text-ink hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2",children:"Retry"})]})]})}),(P||!(b&&m.length===0))&&c.jsx(KY,{ref:M,onSendMessage:E,onComposerInput:A,initialSuggestions:XY,noProvider:Qe,noModel:Nt,deviceHold:l,deliveryRemediesReachable:it!==null,onCredentialsStored:Ae,recordingProbe:Se,askExpanded:P?.askExpanded,onAskToggle:P?.onAskToggle,askOutcomes:P?.askOutcomes,isLoading:P?!!(P.admitting||P.starting):v,awaitingReply:!!(P&&QY(JY({waiting:P.turnAlive,compacting:P.view.transcript.compacting===!0,compactingSince:P.view.transcript.compactingSince,starting:P.starting===!0,startingAfterId:P.startingAfterId??null,startingSession:P.startingSession===!0,startingSince:P.startingSince??null,stopping:rr,gate:me,unavailable:v3(P,Hr),records:P.view.transcript.records}))),conversationId:Ze,messages:P?P.view.transcript.records.length>0||eqe(P,Hr)||P.starting?Jze:m.length>0?m:Qze:m,isHydrating:P?P.view.awaitingHydration:!1,awaitingAnswer:me!==null,secretAnswer:Kh(me)||YY(dF(P?.view.frontend)),unavailable:Ts,currentJobId:P?null:R,onCancelJob:F,canonicalStop:ms,asideSessionId:L,asideStreaming:P.turnAlive,asideAdoptQueue:sn,canonicalStopAvailable:P?.stopAvailable??!1,interruptNotice:P?.stopNotice??null,isFarFromBottom:w,hasNewActivity:C,scrollToBottom:k,agentData:N,cwd:D,mentionsEnabled:Te,mentionsUnsupported:ee,cwdWritePath:j,cwdPending:te,cwdPendingAccepted:X,cwdReadOnlyReason:re,sendError:G,sessionStatus:J,onSlashCommand:ae,onSlashNote:O,paneHasSession:U,runDetails:ne,isSmallView:De})]})}),Y&&c.jsxs(c.Fragment,{children:[ka&&c.jsx(dh,{sidebarWidth:wr,onSidebarWidthChange:Le,minWidth:Cv,maxWidth:Math.max(Cv,$F(ni)),side:"left",onDoubleClick:Ee,label:"Resize canvas. Double-click resets the shared pane width."}),c.jsx(hh,{ref:vt,width:wr,tourTag:"canvas-dock","data-canvas-mode":ka?"docked":"overlay",children:c.jsx(aze,{activeDocumentId:Jt,initialDocuments:D0e(bn),conversationId:Ze,agentId:p,sessionId:L,filesSourceReady:!!(!L||P?.view.frontend)&&!P?.view.awaitingHydration,turnTerminal:V,currentWorkingDirectory:D,fileCount:Zr,fileIndex:xr,scan:xe,goalCapable:eX(P?.view.frontend),goalPresent:ZY(P?.view.frontend),goalHistory:P?.view.frontend?.goal_history,goalHistoryTruncated:P?.view.frontend?.goal_history_truncated===!0,onChangeActiveDocument:_u,onClose:Fe,onCloseDocument:Kt})})]}),Ep&&c.jsxs(c.Fragment,{children:[ka&&c.jsx(dh,{sidebarWidth:wr,onSidebarWidthChange:Le,minWidth:Cv,maxWidth:Math.max(Cv,$F(ni)),side:"left",onDoubleClick:Ee,label:"Resize asks. Double-click resets the shared pane width."}),c.jsx(hh,{width:wr,tourTag:"ask-drawer-slot","data-ask-mode":ka?"docked":"overlay",children:c.jsx(tX,{frontend:P?.view.frontend??null,scope:"session",onClose:bt,onAnswer:P?.onAnswerAsk,onDecline:P?.onDeclineAsk,onRevise:P?.onReviseAsk,answering:!!P?.admitting,outcomes:P?.askOutcomes,drafts:P?.askDrafts,onDraftChange:P?.onAskDraftChange})})]}),at&&c.jsxs(c.Fragment,{children:[c.jsx(dh,{sidebarWidth:yi.value,onSidebarWidthChange:si,minWidth:yi.minWidth,maxWidth:yi.maxWidth,side:"left",onDoubleClick:rc,label:"Resize run details. Double-click resets the shared pane width."}),c.jsx(hh,{ref:nl,width:ar,tourTag:"run-panel-dock",children:ne?c.jsx(_ue,{details:ne,mcpServers:fe,mcpGrantRunning:ue,mcpRemedy:le,monitorControls:q,wakeControls:we,jobControls:B,wakeAida:be,sessionId:L??null,pulses:de??Zze,childrenOpenable:ie,olderTransportDown:(P?.view.status??"live")!=="live",paneWidth:sc,readerChildId:_e,onReaderChildChange:Ye,onClose:()=>pt(!1)}):c.jsx(OI,{label:"Run details",closeLabel:"Close run details",onClose:()=>pt(!1),labelInk:"dim",labelInset:!0,...Mfe({sessionId:L,status:P.view.status,missing:P.view.missing,failure:P.view.failure})})})]}),ei&&c.jsxs(c.Fragment,{children:[c.jsx(dh,{sidebarWidth:Ln.value,onSidebarWidthChange:ac,minWidth:Ln.minWidth,maxWidth:Ln.maxWidth,side:"left",onDoubleClick:lo,label:"Resize browser. Double-click resets the shared pane width."}),c.jsx(hh,{width:or,tourTag:"browser-pane-slot",children:c.jsx(bfe,{sessionId:L??null,onClose:()=>_a(!1)})})]}),Sa&&c.jsxs(c.Fragment,{children:[c.jsx(dh,{sidebarWidth:Dt.value,onSidebarWidthChange:co,minWidth:Dt.minWidth,maxWidth:Dt.maxWidth,side:"left",onDoubleClick:Ta,label:"Resize console. Double-click resets the shared pane width."}),c.jsx(hh,{width:Wi,tourTag:"console-pane-slot",children:c.jsx(rpe,{sessionId:L??null,onClose:()=>ti(!1)})})]}),tc&&c.jsxs(c.Fragment,{children:[c.jsx(dh,{sidebarWidth:Cr.value,onSidebarWidthChange:ho,minWidth:Cr.minWidth,maxWidth:Cr.maxWidth,side:"left",onDoubleClick:yu,label:"Resize code review. Double-click resets the shared pane width."}),c.jsx(hh,{width:el,tourTag:"code-review-pane-slot",children:ks.notice!==null?c.jsx(OI,{label:"Code review",closeLabel:"Close code review",onClose:()=>Hs(!1),labelInk:"muted",...ks.notice}):c.jsx(Dfe,{sessionId:ks.sessionId,sessionLive:P?.turnAlive===!0,onClose:()=>Hs(!1)})})]}),c.jsx(nX,{children:c.jsx(gpe,{sessionId:L??null,runDetails:ne??null,mcpServers:fe,listOnScreen:St,readerChildId:_e,browserAttentionCount:nc,askCount:Jo,askScope:Ci,consoleUnseenCount:vu.length,consoleUnseenPulsing:bu,fileCount:Zr,codeOpened:$i.opened.length,codeMentioned:$i.mentioned.length,codeAttention:wu})})]})});function M1(e,t){const n=t?.find(s=>s.destination===e);return n||{name:iqe[e]??e,description:"",aliases:[],arguments:"optional",echo:!0,consumes_prompt:!1,destination:e,execution:"native"}}const iqe={"session.model":"model","session.effort":"effort",info:"info",usage:"usage",analytics:"analytics","session.diagnostics":"session"};function aqe(e,t){return{id:Xh(),role:"system",message:e,timestamp:new Date,status:t}}function oqe(e,t){const n=(s,r)=>{const i=Array.from({length:r.length+1},(a,o)=>o);for(let a=1;a<=s.length;a++){let o=i[0];i[0]=a;for(let l=1;l<=r.length;l++){const u=i[l];i[l]=Math.min(i[l]+1,i[l-1]+1,o+(s[a-1]===r[l-1]?0:1)),o=u}}return i[r.length]};return t.map(s=>({name:s.name,score:n(e,s.name)})).sort((s,r)=>s.score-r.score).slice(0,3).map(s=>`/${s.name}`)}const lqe=new Set(["session.goal","session.context"]);function x3(e,t,n){const s=Ba.getState(),r=EB(e,t);return s.inputByConversation[r]?.inFlight!==void 0?!1:(s.returnPayload(r,{text:n,attachments:[],replies:[]}),!0)}function cqe({sessionId:e,addMessage:t,canonical:n,rebind:s,focusComposer:r,draftPicker:i,focusCwdChip:a,moveSession:o,moveReady:l,clearAsideRefusal:u,noteAsideRefusal:d}){const h=Jr(),f=Bn(),p=yt(f.data,"commands"),m=wB(f.data),v=l??!0,b=yt(f.data,"session_archive"),w=yt(f.data,"session_delete"),C=yt(f.data,"aida",1),y=B0(C),k=$T(),_=x5(),E=fs({queryKey:Bo.commands,queryFn:()=>xt({op:"commands.list"}).then(G=>G.commands),enabled:p,staleTime:3e5}),[R,F]=g.useState(null),A=Lc(G=>G.claimPresenter);g.useEffect(()=>A(),[A]);const N=g.useRef(null),M=g.useCallback(()=>{F(null);const G=N.current;N.current=null,G&&requestAnimationFrame(()=>{G.isConnected?G.focus():r?.()})},[r]),D=g.useCallback((G,J=!1)=>{if(e&&n.status!=="unavailable"){n.addNote(G,J?"error":"info");return}t(aqe(G,J?"error":void 0))},[t,n.addNote,n.status,e]),L=g.useCallback(G=>{if(!e){D(`/${G} needs an open conversation. Start one first.`,!0);return}if(!m){D(Z1,!0);return}if(!v){D(eS,!0);return}D("Choose the folder in the working directory chip above, or type /move <path> to move straight there."),a?.()},[m,a,v,D,e]),V=g.useCallback(async G=>{const{name:J,args:ae}=G;if(!p)return"not-a-command";const O=E.data??[],U=O.find(le=>le.name===J)??O.find(le=>le.aliases.includes(J));if(!U){const le=oqe(J,O);return D(le.length>0?`Unknown command /${J}. Did you mean ${le.join(", ")}? Type / for the full list.`:`Unknown command /${J}. Type / for the full list.`,!0),"consumed"}const P=by[U.destination];if(P?.kind==="aida"){if(!C)return D(`/${U.name} needs a newer backend. Update the backend and try again.`,!0),"consumed";const le=ae.trim(),q=rX(le);if(q)return k(q).then(B=>{const be=iX(q,B);be.kind==="success"?Ls(be.text):Va(be.text)}).catch(B=>zt(Fh(B))),"consumed";const we=aX(le);return _(y.data).then(B=>{if(we){const be=ix(null,B,Ce.getState().drafts);be&&CB(be,{text:we,attachments:[],images:[],mode:"prompt",cwd:""},B).then(ie=>{ie===null&&(x3(be,B,we),Va(ed.sendLock))}).catch(ie=>{if(oX(ie)){const Te=x3(be,B,we);zt(Te?Fh(ie):`${ed.sendLock} ${Fh(ie)}`);return}zt(Fh(ie))})}cp(h,B)}).catch(B=>zt(Fh(B))),"consumed"}if(P&&P.argsBehavior==="execute"&&ae)return e?m?v?(P.runArgs?await P.runArgs({sessionId:e,cwd:ae,canonical:n,note:D,moveTo:o}):D(`/${U.name} is not available in the desktop app yet. Run it in the terminal with local-operator.`,!0),"consumed"):(D(eS,!0),"consumed"):(D(Z1,!0),"consumed"):(D(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed");if(P?.kind==="direct"){if(P.action==="focus-cwd-chip")return L(U.name),"consumed";if(P.action==="compact"){if(!e)return D(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed";try{const q=(await xt({op:"sessions.command",sessionId:e,requestId:Xh(),command:U.name,args:ae})).result;if(gF(q))return D(`/${U.name} asked for a dialog this build does not have, so nothing ran. Run it in the terminal with local-operator.`,!0),"consumed";if(lX(q.text)){const we=Date.now(),B=n.transcript.viewEpoch;cX(()=>n.refreshTail(we,B))}else q.text&&D(q.text,q.kind==="error"||q.style==="error")}catch(le){D(`/${U.name} could not run: ${le instanceof Error?le.message:"the backend refused it"}`,!0)}return"consumed"}if(P.action==="clear")return n.clearView(),"consumed";if(P.action==="archive"||P.action==="unarchive"){const le=P.action==="archive";if(!e)return D(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed";const q=Ce.getState(),we=q.sessions.find(Te=>Te.session_id===e),B=q.archiveFacts[e]?.archived??we?.archived;if(!b)return D(uX,!0),"consumed";if(!dX(U.destination,B,b))return D(le?hX:B===void 0?fX:pX,!0),"consumed";if(le)return q.requestArchiveConfirm({sessionId:e,fromRow:!1,title:we?.title||void 0}),"consumed";const be=we?.title??void 0;return await q.setSessionArchived(e,!1,be),"consumed"}return P.action==="request-delete"?e?w?(Ce.getState().requestSessionDelete(e),"consumed"):(D(qze,!0),"consumed"):(D(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed"):(window.api?.desktop?.closeWindow?await window.api.desktop.closeWindow():D("Close this window to quit. Conversations keep running in the background."),"consumed")}if(P?.kind==="navigate")return h(P.route(ae,e??"")),"consumed";const z=(le,q,we)=>{N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,F({action:{kind:"native_action",destination:le.destination,session_id:we,args:q,fields:[],data:{}},spec:le,sessionId:we,canonical:n,commands:O,onClose:M,note:D,dispatch:B=>void V(B),rebind:s})},ne=(le,q)=>{N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,F({action:{kind:"native_action",destination:le.destination,session_id:"",args:q,fields:[],data:{}},spec:M1(le.destination,E.data),sessionId:"",canonical:n,commands:O,onClose:M,note:D,dispatch:we=>void V(we),rebind:s})};if(!e){const le=P?.kind==="picker"?P.draftIdentity:void 0,q=le==="team"&&(ae==="chart"||ae.startsWith("chart "));if(yB(U.destination)&&!(le&&!q))return D(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed";if(le&&!q){const we=ae.trim(),B=we.split(gX)[0]??"";if(B)return Ce.getState().restageDraft({kind:le,name:B},we.slice(B.length).trim()),"consumed"}return P?.kind==="picker"?(ne(U,ae),"consumed"):(z(U,ae,""),"consumed")}if(P?.kind==="machine-panel")return z(U,ae,e),"consumed";if(P?.kind==="aside"){if(u?.(),ae){const le=tS(Lg.getState(),e);if(le)return d?d(le):D(le,!0),"retained";const q=_B(e,ae,n.subscriptionId??void 0);SB(q,e,we=>D(we,!0))}else mX(e);return"consumed"}if(!ae&&lqe.has(U.destination))return F({action:{kind:"native_action",destination:U.destination,session_id:e,args:"",fields:[],data:{}},spec:U,sessionId:e,canonical:n,commands:O,onClose:M,note:D,dispatch:le=>void V(le),rebind:s}),"consumed";const fe=U.name==="credential"?"":ae,ue=vX(U.name,fe);if(ue)return D(ue,!0),"retained";U.name==="rename"&&bX("title-refresh",fe)&&D("refreshing the title…");try{const q=(await xt({op:"sessions.command",sessionId:e,requestId:Xh(),command:U.name,args:fe})).result;if(gF(q)){const we=q,B=by[we.destination];return B?.kind==="navigate"?(h(B.route(we.args,e)),"consumed"):B?.kind==="direct"&&B.action==="focus-cwd-chip"?(L(U.name),"consumed"):B?(N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,F({action:we,spec:U,sessionId:e,canonical:n,commands:O,onClose:M,note:D,dispatch:be=>void V(be),rebind:s}),"consumed"):(D(`/${U.name} is not available in the desktop app yet. Run it in the terminal with local-operator.`,!0),"consumed")}if(q.text)D(q.text,q.kind==="error"||q.style==="error");else if(q.kind==="block"){const we=q.data;Array.isArray(we.items)&&D([we.title,...we.items.map(([B,be])=>`${B}: ${be}`)].filter(Boolean).join(`
|
|
674
|
-
`))}return"consumed"}catch(le){return D(`/${U.name} could not run: ${le instanceof Error?le.message:"the backend refused it"}`,!0),"retained"}},[p,b,w,C,y.data,k,_,E.data,e,D,h,n,s,M,m,v,o,L,u,d]),j=g.useCallback(async G=>{const J=await V(G);return J==="not-a-command"&&D("The backend could not complete this request. Check its connection and try again.",!0),J},[V,D]),te=g.useCallback(G=>{i&&(N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,F({action:{kind:"native_action",destination:G,session_id:"",args:"",fields:[],data:{}},spec:M1(G,E.data),sessionId:"",canonical:n,commands:E.data??[],onClose:M,note:D,dispatch:J=>void V(J),rebind:s,draft:i}))},[n,M,E.data,V,i,D,s]),X=Lc(G=>G.request),re=Lc(G=>G.consumePanel);return g.useEffect(()=>{if(!X||(re(X.nonce),Date.now()-X.requestedAt>xX))return;const G=by[X.destination];if(G?.kind!=="picker"&&G?.kind!=="machine-panel")return;N.current=X.sessionId?X.invoker:null;const J=X.sessionId??e??"";F({action:{kind:"native_action",destination:X.destination,session_id:J,args:"",fields:[],data:{...X.entryId?{entryId:X.entryId}:{},...X.entryId&&X.entryExcerpt?{entryExcerpt:X.entryExcerpt}:{},...X.subjectName?{subjectName:X.subjectName}:{}}},spec:M1(X.destination,E.data),sessionId:J,canonical:n,commands:E.data??[],onClose:M,note:D,dispatch:ae=>void V(ae),rebind:s})},[X,re,e,n,E.data,M,D,V,s]),{dispatch:V,dispatchFromControl:j,picker:R,closePicker:M,openDraftPicker:te,note:D}}const uqe=/^[a-f0-9]{12}$/,O1=e=>`${e.request_id}:${e.question_index}`,dqe=" ";function L1(e,t){const n=e.activeDraftKey?e.drafts[e.activeDraftKey]:void 0;return!!t&&ip(e.activeDraftKey,n?.sessionId,e.activeSessionId)===t}function hqe({identity:e,draftKey:t,sessionId:n}){const s=Ce(Fe=>ix(t,n,Fe.drafts)),r=Ce(Fe=>s?Fe.drafts[s]:void 0),i=n??r?.warmId,a=Bn(),o=yX(i,!!i,!!n,e,{openFrame:yt(a.data,"open_frame"),journalOrder:yt(a.data,"journal_order"),peerJournalSource:yt(a.data,"peer_journal_source")});Vue(i,o.subscriptionId);const l=$ue(n,a.data),u=yt(a.data,"settings");que(n,u),g.useEffect(()=>{Ce.getState().setDraftWarmable(yt(a.data,"session_draft_warm"))},[a.data]),zue(r?.warmId,o.subscriptionId,a.data);const d=g.useCallback(()=>{if(n){l();return}t&&Ce.getState().ensureDraftWarm(t)},[n,l,t]),h=g.useRef(null),f=g.useRef(null),p=Ce(Fe=>Fe.cwd),{data:m}=sp(),v=XT(m?.online===!1),b=m?.online===!0,w=g.useRef(b);g.useEffect(()=>{const Fe=b&&!w.current;w.current=b,Fe&&o.status==="unavailable"&&o.retry()},[b,o]);const C=Ce(Fe=>Fe.setCwd),y=Ce(Fe=>Fe.markTurnStopped),k=Ce(Fe=>Fe.clearTurnStopped),[_,E]=g.useState(!1),R=g.useRef(null);R.current??=_X();const F=R.current,A=g.useRef(!1),N=g.useRef(o);N.current=o;const M=g.useRef([]),D=g.useRef(!1),[L,V]=g.useState(null),[j,te]=g.useState({}),X=qe(Fe=>Fe.isAskDrawerOpen),re=qe(Fe=>Fe.askDrawerScope),G=X&&re==="session",J=qe(Fe=>Fe.setAskDrawerOpen),[ae,O]=g.useState({}),U=o.frontend?.pending_gate??null,P=U?O1(U):null,z=g.useRef(null),ne=g.useRef(null);g.useLayoutEffect(()=>{z.current=P,ne.current=o.ownerEpoch});const fe=U&&L?.key===P?{sending:L.sending,refused:L.refused,retryable:L.retryable,muted:L.muted}:null,ue=g.useRef(""),[le,q]=g.useState(null),[we,B]=g.useState(),[be,ie]=g.useState(!1),[Te,ee]=g.useState(!1),[de,De]=g.useState(null),[Ue,Se]=g.useState(null),ge=g.useRef(Ue);ge.current=Ue;const Ae=g.useRef(0),st=g.useRef(null),vt=yhe(a.data),[me,it]=g.useState(!1),[ct,Qe]=g.useState("chat"),{isFarFromBottom:Nt,scrollToBottom:Tt}=Qj(50,f,o.transcript.records.length),At=(o.frontend??o.heldFrontend)?.streaming===!0,sn=g.useRef(At);sn.current=At;const Ut=SX(e),rt=g.useRef(null),An=g.useRef(null);Ut&&(An.current?.requestId!==Ut.id&&(An.current={requestId:Ut.id,anchor:o.frontend?.attention?.anchor_id??null}),rt.current?.requestId!==Ut.id&&(rt.current={requestId:Ut.id,submittedAt:Ut.submittedAt??r?.submittedAt}));const On=EX(o.transcript.records,rt.current?.requestId),ks=kX(o.transcript.records,rt.current?.requestId)||TX(o.frontend?.attention,An.current?.anchor??null);rt.current&&(On||ks||r?.error||r?.undelivered!==void 0&&r.undelivered.recordId===rt.current.requestId)&&(rt.current=null);const js=rt.current!==null,sr=js&&!(r?.sessionId??n),rs=o.frontend??o.heldFrontend,Hr=g.useMemo(()=>n&&rs?RX({jobs:rs.jobs,todos:rs.todos,wakes:rs.wakes,monitors:rs.monitors}):null,[n,rs]),{servers:Ts,grantRunning:rr}=Fue({sessionId:n,accelerator:o.frontend?JSON.stringify(o.frontend.mcp_servers??null):null,errors:AX(o.frontend?.mcp_servers)}),Ot=FX({sessionId:n}),br=Mue({sessionId:n}),an=Bn(),ms=Uue({sessionId:n}),ir=Lue({sessionId:n}),Rs=yt(an.data,"aida",1),is=B0(Rs),Ie=xle(),Ne={capability:Rs,statusResolved:is.isSuccess,sessionId:is.data?.session_id??null,name:Ie},Le=yt(an.data,"subagent_transcript"),Ee=yt(an.data,"references")&&!At,Ze=yt(an.data,"input_mode"),H=an.isSuccess&&!!an.data?.desktop_available&&!yt(an.data,"references"),K=!!n&&!t&&wB(an.data),W=DX({sessionId:n,canonical:o,capabilities:an.data}),Y=g.useMemo(()=>t&&!r?.sessionId&&!_?{kind:"stage",commit:C}:K?{kind:"move",commit:W.moveTo}:void 0,[t,r?.sessionId,_,K,C,W.moveTo]),Q=t&&(r?.sessionId||_)?eS:K?void 0:Z1,Z=Jr(),ve=Fe=>{cp(Z,Fe)},Pe=fs({queryKey:["desktop","entities",n,"effort",""],queryFn:()=>xt({op:"commands.entities",sessionId:n,command:"effort"}),enabled:!!n,staleTime:15e3}),xe=nn(),ye=PX(o.frontend,o.heldFrontend),Re=g.useRef(void 0);g.useEffect(()=>{const Fe=Re.current;Re.current={session:n??null,model:ye},!(!n||!ye||!(Fe?.session===n)||Fe?.model===ye)&&xe.invalidateQueries({queryKey:["desktop","entities",n,"effort",""]})},[n,ye,xe]);const ze=g.useRef(null),[at,pt]=g.useState(null);g.useEffect(()=>{if(!n){pt(null);return}if(o.frontend||o.heldFrontend){ze.current=n,pt(null);return}pt(ze.current===n&&o.status==="unavailable"&&!o.missing?n:null)},[n,o.frontend,o.heldFrontend,o.status,o.missing]);const _e={cwd:p,...r?.target?{target:r.target}:{},model:r?.model??null},Ye=!n&&p.length>0&&yt(an.data,"draft_preview"),St=fs({...IX(_e),enabled:Ye}),rn=Ye?St.data?void 0:St.isError?{status:"failed",retry:()=>void St.refetch()}:{status:"pending"}:void 0,Jt=!n&&yt(an.data,"draft_selection")&&yt(an.data,"commands")&&yt(an.data,"catalogues"),bn=g.useCallback(()=>{q(null),B(void 0)},[]),xr=Lg(Fe=>n?tS(Fe,n)!==null:!1),Zr=g.useCallback(Fe=>{q(Fe),B(mF)},[]);g.useEffect(()=>{we===mF&&(xr||bn())},[xr,bn,we]);const ar=g.useCallback(Fe=>o.addNote(Fe.message??""),[o.addNote]),{dispatch:ei,dispatchFromControl:_a,picker:or,openDraftPicker:Sa,note:tc}=cqe({sessionId:n,canonical:o,rebind:ve,addMessage:ar,focusComposer:()=>h.current?.focusInput(),focusCwdChip:()=>h.current?.openWorkingDirectoryMenu(),moveSession:W.moveTo,moveReady:!t,clearAsideRefusal:bn,noteAsideRefusal:Zr,draftPicker:Jt&&s&&St.data?{target:_e,select:Fe=>Ce.getState().setDraftModel(s,Fe)}:void 0}),As=MP(_a),gu=!!n;g.useEffect(()=>{t&&h.current?.focusInput()},[t]),g.useEffect(()=>{if(!n||!o.frontend)return;const Fe=Ce.getState();Fe.sessions.some(bt=>bt.session_id===n)&&Fe.upsertSession({session_id:n,...Que({liveTitle:o.frontend.conversation_title}),attention:o.frontend.attention})},[n,o.frontend]),g.useEffect(()=>{const Fe=JSON.stringify([n,o.frontend?.streaming,o.frontend?.attention?.unseen,o.frontend?.active_agent,o.frontend?.active_team]);!n||Fe===ue.current||(ue.current=Fe,Ce.getState().fetchSessions())},[n,o.frontend?.streaming,o.frontend?.attention?.unseen,o.frontend?.active_agent,o.frontend?.active_team]);const Ep=Fe=>cQ(Fe,void 0,!1),Gi=(Fe,bt)=>{const Kt=Ce.getState().drafts[Fe],Ht=Zue({rowError:Kt?.error,rowCode:Kt?.errorCode,rowRetry:Kt?.errorRetry,fallback:()=>Ep(bt)});q(Ht?.message??null),B(Ht?.code),ie(Ht?.retry===!0),ee(Ht?.muted===!0)},Qo=async(Fe,bt,Kt,Ht,Fn,Ge)=>{const jn=Ce.getState(),Zn=ix(t,n,jn.drafts);if(!Zn)return!1;const Ra=jn.drafts[Zn],lc=()=>(q(A.current?ed.queuedSend:lQ(o.frontend?.pending_gate)),B(void 0),ie(!1),ee(!0),!1);if(Ra?.pending||!F.tryAcquire())return lc();E(!0),q(null),B(void 0),ie(!1),ee(!1);try{if(!t&&!n)return!1;const as=vB(o.frontend);if(as&&o.ownerEpoch&&n){if(Kh(as))throw new K1(KX,bF);if(as.kind==="approval"){const $s=YX(Ht??Fe);if($s===null)throw new K1("Reply yes or no to answer the approval request.",bF);await xt({op:"sessions.answer",sessionId:n,epoch:o.ownerEpoch,requestId:as.request_id,approved:$s})}else await xt({op:"sessions.answer",sessionId:n,epoch:o.ownerEpoch,requestId:as.request_id,value:XX(as,Ht,Fe),questionIndex:as.question_index});return!0}const{images:Aa,unreadable:cc,overflow:fo}=await QX(bt,Fe),ov=JX(cc);if(ov)return q(ov),B(ZX),ie(!1),ee(!1),!1;const Rp=eQ(fo);if(Rp)return q(Rp),B(void 0),ie(!1),ee(!1),!1;const lv=tQ(Fe,Aa);if(lv)return q(lv),B(void 0),ie(!1),ee(!1),!1;const cv=n?Lg.getState().attached[n]:void 0;if(n&&cv){if(bt.length>0)return q("An aside answers text only. Remove the attached files to ask it."),!1;const $s=tS(Lg.getState(),n);if($s)return Zr($s),!1;q(null),B(void 0);const uv=_B(n,Fe,o.subscriptionId??void 0);return SB(uv,n,ih=>{q(ih),B(nQ)}),{offRecord:uv}}if(n&&!L1(Ce.getState(),n))return!1;if(n&&xy(Ce.getState().validatingSessionId,n)){A.current=!0,q(ed.queuedSend),B(void 0),ie(!1),ee(!0);let $s;try{$s=await ka()}finally{A.current=!1}if($s!=="ready")return $s==="failed"&&(q(N.current.failure?.statement??sQ),B(vF),ee(!1)),!1}const rh=await CB(Zn,{text:Fe,attachments:bt,images:Aa,mode:At?"steer":"prompt",cwd:p,inputMode:Ze?Ge:void 0},n,Kt,Fn);if(!rh)return!1;const Ap=bt.filter($s=>!$s.startsWith("data:")).map($s=>Ac($s));if(Ap.length>0){const $s=ls.getState();$s.addMentionedFilesBatch(e,Ap),$s.addMentionedFilesBatch(rh,Ap)}return t&&Ce.getState().activeSessionId===rh&&Z(`/chat/${rh}`,{replace:!0}),jn.fetchSessions(),!0}catch(as){const Aa=Ce.getState().drafts[Zn];return rQ(uT(t,Aa?.sessionId??n),Aa?.admissionRequestId??"")?(q(null),B(void 0),ie(!1),ee(!1)):Gi(Zn,as),!1}finally{F.release(),E(!1)}},nh=MP(Qo),so=(Fe,bt,Kt)=>{const Ht=oQ(Fe,{liveGateKey:z.current,pressedGateKey:bt,sentEpoch:o.ownerEpoch,liveEpoch:ne.current,cardOnScreen:document.querySelector('[aria-label="Answer options"], [data-ask-secret]')!==null});switch(Ht.to){case"refused":V(null);return;case"sent":V({key:bt,sending:!1,refused:null,retryable:!1,muted:!1}),Kt?.();return;case"card":V({key:bt,sending:!1,refused:Ht.refused,retryable:Ht.retryable,muted:Ht.muted});return;case"composer":V(null),q(Ht.message),B(Ht.code),ee(Ht.muted),ie(Ht.retry);return}},kp=async Fe=>{const bt=o.frontend?.pending_gate;if(!bt||!o.ownerEpoch||!n||F.held)return;const Kt=O1(bt);document.activeElement instanceof HTMLElement&&document.activeElement.closest('[aria-label="Answer options"]')!==null&&(D.current=!0,h.current?.focusInput()),E(!0),V({key:Kt,sending:!0,refused:null,retryable:!1,muted:!1}),q(null),B(void 0);let Fn;try{Fn=await qX({gate:bt,sessionId:n,epoch:o.ownerEpoch,label:Fe,lock:F},Ge=>xt(Ge))}finally{E(!1)}so(Fn,Kt,()=>{bt.kind==="approval"&&h.current?.consumeApprovalAnswerDraft()})},Tp=async Fe=>{const bt=o.frontend?.pending_gate;if(!bt||!o.ownerEpoch||!n||F.held)return;const Kt=O1(bt);document.activeElement instanceof HTMLElement&&document.activeElement.closest("[data-ask-secret]")!==null&&(D.current=!0,h.current?.focusInput()),E(!0),V({key:Kt,sending:!0,refused:null,retryable:!1,muted:!1}),q(null),B(void 0);let Fn;try{Fn=await zX({gate:bt,sessionId:n,epoch:o.ownerEpoch,value:Fe,lock:F},Ge=>xt(Ge))}finally{E(!1)}so(Fn,Kt)},ro=(Fe,bt,Kt=!1)=>{if(bt.status==="failed"){te(Ht=>({...Ht,[Fe]:{sending:!1,refused:aQ(bt.error),refusedByOwner:iQ(bt.error)}}));return}te(Ht=>({...Ht,[Fe]:{sending:!1,refused:null,...Kt?{changed:!0}:{}}}))},Ci=async(Fe,bt)=>{if(!n||F.held)return;E(!0),te(Ht=>({...Ht,[Fe]:{sending:!0,refused:null}}));let Kt;try{Kt=await $X({taskId:Fe,answers:bt,sessionId:n,lock:F},Ht=>xt(Ht))}finally{E(!1)}ro(Fe,Kt)},Jo=async(Fe,bt)=>{if(!n||F.held)return;E(!0),te(Ht=>({...Ht,[Fe]:{sending:!0,refused:null}}));let Kt;try{Kt=await VX({taskId:Fe,answers:bt,sessionId:n,lock:F},Ht=>xt(Ht))}finally{E(!1)}ro(Fe,Kt,Kt.status==="sent"),Kt.status==="sent"&&Ls("Answer changed")},lr=async Fe=>{if(!n||F.held)return;E(!0),te(Kt=>({...Kt,[Fe]:{sending:!0,refused:null}}));let bt;try{bt=await WX({taskId:Fe,sessionId:n,lock:F},Kt=>xt(Kt))}finally{E(!1)}ro(Fe,bt)},Vi=g.useCallback((Fe,bt)=>{Fe!==G&&J(Fe,"session",bt)},[G,J]);g.useLayoutEffect(()=>{if(!D.current||(D.current=!1,document.activeElement!==document.body&&!NX()))return;const Fe=document.querySelector('[aria-label="Answer options"] button:not([disabled]), [data-ask-secret] input:not([disabled])');Fe?Fe.focus():h.current?.focusInput()},[P]);const Ea=g.useCallback(()=>{const Fe=st.current;Fe!==null&&(st.current=null,q(bt=>bt===Fe?null:bt))},[]),ti=g.useCallback(()=>{if(!n||!vt)return;const Fe=ge.current;if(Fe==="pending"||Fe==="awaiting-end")return;const bt=++Ae.current;De(null),Se("pending");const Kt=Date.now();y(n,Kt),_he(n,crypto.randomUUID()).then(Ht=>{if(bt!==Ae.current)return;Ht.status!=="interrupted"&&k(n);const Fn=sn.current,Ge=Ehe(Ht,{turnClaimed:Fn});De(Ge===null?null:{text:Ge,kind:Ht.status!=="idle"?"outcome":Fn?"idle-disputed":"idle"}),Se(Ht.status==="interrupted"&&sn.current?"awaiting-end":null),Ea(),Ht.status==="idle"&&Fn&&o.retry()}).catch(Ht=>{if(bt!==Ae.current)return;if(!sn.current){Se(null);return}Se("unconfirmed");const Fn=bi(Ht,"Stop could not be confirmed. The turn may still be running.");st.current=Fn,q(Fn),B(void 0),ie(!1),ee(!1)})},[n,vt,y,k,Ea,o.retry]),Zo=g.useRef(null);g.useEffect(()=>{const Fe=Zo.current;Zo.current=At,!Fe&&At?(Ae.current+=1,De(null),Se(null),Ea(),n&&k(n)):Fe&&!At&&(De(bt=>bt?.kind==="idle"||bt?.kind==="idle-disputed"?null:bt),Se(bt=>bt==="awaiting-end"||bt==="unconfirmed"?null:bt),Ea())},[At,n,k,Ea]),g.useEffect(()=>{Ae.current+=1,Se(null)},[n]),g.useEffect(()=>{if(!G)return;const Fe=bt=>{UX(bt)&&(bt.preventDefault(),Vi(!1))};return window.addEventListener("keydown",Fe),()=>window.removeEventListener("keydown",Fe)},[G,Vi]);const Wi=xB({status:o.status,failure:o.failure,missing:o.missing,stale:o.stale});xhe({sessionId:n,turnAlive:At,available:vt&&!Wi,recording:uQ,onInterrupt:ti});const Hs=r?.target?.kind==="team"?r.target.name:null,el=o.frontend?.active_team||null,mu=sC(!!(Hs||el)&&yt(an.data,"team_catalogue")),vu=g.useMemo(()=>{const Fe=new Map((mu.data??[]).map(bt=>[bt.name,kf(bt)]));return bt=>Fe.get(bt)??bt},[mu.data]),bu=(el?vu(el):"")||o.frontend?.active_agent||(r?.target?r.target.kind==="team"?vu(r.target.name):r.target.name:void 0),tl=Ce(Fe=>n?Fe.sessions.find(bt=>bt.session_id===n):void 0),xu=Ce(Fe=>n?Fe.forgotten[n]?.title:void 0),$i=[o.frontend?.active_agent,o.frontend?.active_team].filter(Boolean).join(" · ")||[tl?.binding?.agent,tl?.binding?.team].filter(Boolean).join(" · "),wu=Xue({draftKey:t,draftTarget:bu,liveTitle:o.frontend?.conversation_title,catalogueTitle:tl?.title??xu}),nc=n?o:{...o,status:"live",error:null},nl=!$i&&!t&&nc.status==="connecting",io=n&&kze({hasSession:!!n,pending:nl,teamCatalogue:yt(an.data,"team_catalogue"),identityKnown:!!$i,streamLive:nc.status==="live"})?{sessionId:n,activeAgent:o.frontend?.active_agent??null,activeTeam:o.frontend?.active_team??null,boundAgent:tl?.binding?.agent??null,boundTeam:tl?.binding?.team??null,effectiveIdentity:o.frontend?.effective_identity??null,hostKey:wze(tl),frameEpoch:o.frontend?.epoch??null}:void 0,ao=o.frontend?.active_team||o.frontend?.active_agent,Cu=(we??r?.errorCode)==="unresolved_attachment"&&!!ao;g.useEffect(()=>{Cu&&(q(null),B(void 0),s&&Ce.getState().updateDraft(s,{error:void 0,errorCode:void 0}))},[Cu,s]);const oo=Ce(Fe=>xy(Fe.validatingSessionId,n)),sh=Ce(Fe=>L1(Fe,n));g.useEffect(()=>{if(!n||!oo)return;const Fe=Ce.getState();o.status==="live"?Fe.confirmSessionLive(n):o.missing&&Fe.confirmSessionMissing(n)},[n,oo,o.status,o.missing]);const ni=Fe=>{const bt=M.current.splice(0);for(const Kt of bt)Kt(Fe)},sl=()=>{if(N.current.missing)return"gone";if(!L1(Ce.getState(),n))return"abandoned";const Fe=N.current.status;return Fe==="unavailable"?"failed":xy(Ce.getState().validatingSessionId,n)?null:Fe==="live"?"ready":null},ka=()=>{const Fe=sl();return Fe?Promise.resolve(Fe):new Promise(bt=>{M.current.push(bt)})};g.useEffect(()=>{if(M.current.length===0)return;const Fe=sl();Fe&&ni(Fe)},[oo,sh,o.status,o.missing]),g.useEffect(()=>{const Fe=M.current;return()=>{for(const bt of Fe.splice(0))bt("abandoned")}},[]),g.useEffect(()=>{oo||we!==vF||(q(null),B(void 0))},[oo,we]),g.useEffect(()=>{s&&(MX(s,r),OX(s,r))},[s,r]);const wr=r?.admissionAttempted&&!r.pending?r.admissionRequestId:void 0,yi=Ce(()=>wr?o.transcript.index.get(wr):void 0),si=Ce(()=>{if(!wr)return!1;const Fe=o.transcript.records[yi??-1];return Fe?.kind==="user"&&!Fe.local});g.useEffect(()=>{!wr||!si||!s||(Ba.getState().reconcileDelivered(e),q(null),B(void 0),ie(!1),ee(!1),Ce.getState().finishDraft(s,r?.sessionId??n??""))},[wr,si,s,r?.sessionId,n,e]);const rc=Ba(Fe=>Fe.inputByConversation[e]?.lateDelivered),ic=Ba(Fe=>Fe.inputByConversation[e]?.currentInput??""),Ln=r?r.submittedText!==void 0&&(r.error!==void 0||wr!==void 0)?{recordId:wr??r.admissionRequestId,text:r.submittedText,attachments:r.submittedAttachments??[],message:r.error,retry:r.errorRetry??Nx(r.errorCode)}:r.undelivered??null:null,ac=Ln?LX(Ln.text):null,lo=Ln?ac?.text??Ln.text:null,oc=Ln?{recordId:Ln.recordId,message:Ln.message,retry:Ln.retry,retryDisabled:ic.trim().length>0&&ic===lo,onSendAgain:()=>{Qo(Ln.text,[...Ln.attachments])},onEdit:()=>{Ba.getState().returnPayload(e,{text:lo??Ln.text,attachments:[...Ln.attachments],replies:ac?.replies??[]}),r?.admissionAttempted!==!0&&(GX(e,Ln.recordId),s&&Ce.getState().updateDraft(s,{error:void 0,errorCode:void 0,errorRetry:void 0,undelivered:void 0})),h.current?.focusInput()}}:null,Dt=r?.admissionAttempted===!0&&r.pending!==!0,co=g.useRef(Dt);g.useEffect(()=>{co.current&&!Dt&&(q(null),B(void 0),ie(!1),ee(!1)),co.current=Dt},[Dt]),g.useEffect(()=>{ede({rowPending:r?.pending===!0,admitting:_,gatePending:o.frontend?.pending_gate!=null,muted:Te})&&(q(null),B(void 0),ie(!1),ee(!1))},[r?.pending,_,o.frontend?.pending_gate,Te]);const Ta=BX(e),uo=g.useMemo(()=>Jue({error:le,code:we,retry:be,muted:Te,rowError:Ta?void 0:r?.error,rowCode:Ta?void 0:r?.errorCode,rowRetry:Ta?void 0:r?.errorRetry,lateDelivered:rc}),[le,we,be,Te,Ta,r?.error,r?.errorCode,r?.errorRetry,rc]),Cr=g.useMemo(()=>uo&&!(v&&uo.code===oC.transportFailed)?{...uo,actions:void 0,onRetry:()=>{h.current?.submitNow(),h.current?.focusInput()},onClear:()=>{e&&Ba.getState().clearComposer(e),bn(),s&&Ce.getState().discardDraft(s),h.current?.focusInput()},onDismiss:()=>{bn(),s&&r&&Ce.getState().updateDraft(s,{error:void 0,errorCode:void 0})}}:void 0,[uo,v,e,s,r,bn]),ho=Ce(Fe=>jX(Fe.sessions,n)),yu=g.useMemo(()=>n?{frontend:o.frontend??o.heldFrontend,servingLocality:ho,held:o.frontend===null&&o.heldFrontend!==null,readingsDropped:at===n,pendingModel:o.pendingModel,onCommand:Fe=>void As(Fe),effortEntities:Pe.data?.entities,costChannels:yt(an.data,"cost_channels")}:void 0,[n,o.frontend,o.heldFrontend,ho,at,o.pendingModel,As,Pe.data,an.data]),_u=g.useMemo(()=>c.jsx(Rde,{sessionId:n??void 0}),[n]);return c.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[me&&c.jsx("div",{className:T("flex flex-wrap gap-2 border-b border-hairline px-4 py-2 text-body-sm"),children:["model","agent","team","rename","resume","fork","new","settings"].map(Fe=>c.jsx("button",{type:"button",className:T("rounded-md px-2 py-1 hover:bg-elevated"),onClick:()=>{it(!1),ei({name:Fe,args:""})},children:Fe==="agent"?"Choose agent":Fe==="team"?"Choose team":Fe.charAt(0).toUpperCase()+Fe.slice(1)},Fe))}),c.jsx("div",{className:T("min-h-0 flex-1"),children:c.jsx(rqe,{activeTab:ct,onTabChange:Qe,deviceSlot:c.jsx(ghe,{sessionId:n??void 0,draftKey:t??void 0}),deviceNotice:c.jsx(ahe,{sessionId:n??void 0}),deviceHold:_u,agentName:wu,description:$i||(t?js?bu??"Starting the session":r?.sessionId?o.frontend?.cwd||p||"Canonical chat":o.frontend?.cwd||p||"":W.cwd||dqe),descriptionPending:nl,identity:io,renameSessionId:n&&yt(an.data,"commands")?n:void 0,onOpenOptions:()=>it(Fe=>!Fe),isOptionsSidebarOpen:!1,onCloseOptions:()=>it(!1),agentId:e,turnTerminal:o.turnsCompleted,cwd:t?p:W.cwd,cwdWritePath:Y,cwdReadOnlyReason:Q,sessionId:n,cwdPending:K&&W.busy,cwdPendingAccepted:K&&W.accepted,messages:[],isLoading:!1,isLoadingMessages:!1,isFarFromBottom:Nt,messagesContainerRef:f,scrollToBottom:Tt,rawInfoContent:JSON.stringify(o.frontend,null,2),onSendMessage:nh,onSlashCommand:As,onSlashNote:tc,paneHasSession:gu,sendError:Cr,undelivered:oc,sessionStatus:n?yu:St.data?{frontend:St.data.snapshot,draft:!0,draftResolved:!0,onOpenDraftPicker:Jt?Sa:void 0,costChannels:yt(an.data,"cost_channels")}:rn?{frontend:null,draft:!0,draftResolved:!1,draftResolution:rn,costChannels:yt(an.data,"cost_channels")}:void 0,currentJobId:null,onCancelJob:ti,messageInputRef:h,runDetails:Hr,onComposerInput:d,mcpServers:Ts,mcpGrantRunning:rr,mcpRemedy:Ot,monitorControls:br,wakeControls:ms,jobControls:ir,wakeAida:Ne,childrenOpenable:Le,mentionsEnabled:Ee,mentionsUnsupported:H,pulses:o.subagentPulses,canonical:{view:nc,turnAlive:At,stopOutcome:Ue,idleDisputed:de?.kind==="idle-disputed",admitting:_,starting:js,startingAfterId:rt.current?.requestId??null,startingSession:sr,startingSince:r?.submittedAt??Ut?.submittedAt??rt.current?.submittedAt??null,onStop:ti,stopAvailable:vt,stopNotice:de?.text??khe(At,vt),onAnswer:Fe=>void kp(Fe),onAnswerSecret:Fe=>void Tp(Fe),answer:fe,onAnswerAsk:(Fe,bt)=>void Ci(Fe,bt),onDeclineAsk:Fe=>void lr(Fe),onReviseAsk:(Fe,bt)=>void Jo(Fe,bt),askOutcomes:j,askExpanded:G,onAskToggle:Vi,askDrafts:ae,onAskDraftChange:(Fe,bt)=>O(Kt=>({...Kt,[Fe]:bt}))}})}),c.jsx(HX,{context:or})]})}function w3(){const{agentId:e}=C4(),t=Jr(),n=Bn(),s=pa(n.data,"session_catalogue",2),r=s==="enabled",{data:i}=sp(),a=XT(i?.online===!1),o=i?.snapshot&&!i.snapshot.pairing.available?i.snapshot.pairing.cause??"unpaired":null,l=CX(s,o),u=Yk(n.data,o),d=wX(o),h=g.useCallback(async()=>{s==="unpaired"&&await window.api?.backend?.reconnect?.(),await n.refetch()},[s,n]),f=Ce(R=>R.activeSessionId),p=Ce(R=>R.activeDraftKey),m=Ce(R=>ix(p,R.activeSessionId,R.drafts)),v=Ce(R=>m?R.drafts[m]:void 0),b=Ce(R=>R.error),[w,C]=g.useState(null);g.useEffect(()=>{if(!r||!e)return;const R=Ce.getState();if(!uqe.test(e)){C("This legacy link has no canonical chat. Its saved history is unchanged.");return}const F=e;C(null),(R.activeSessionId!==F||R.activeDraftKey)&&R.openSession(F)},[r,e]);const y=g.useRef(p);g.useEffect(()=>{y.current!==p&&(y.current=p,p&&C(null))},[p]);const k=(R,F)=>{Ce.getState().stageDraft(R,F),C(null),t("/chat")},_=ip(p,v?.sessionId,f),E=uT(p,_);return c.jsxs("div",{className:T("flex h-full min-h-0 flex-col"),children:[(w||b&&!a&&!u)&&c.jsx("p",{role:"alert",className:T("px-4 py-2 text-body-sm text-danger"),children:w||b}),r?E?c.jsx("div",{className:T("min-h-0 flex-1"),children:c.jsx(hqe,{identity:E,draftKey:p,sessionId:_},E)}):c.jsx("div",{className:T("p-6"),children:c.jsx("button",{type:"button",className:T("rounded-md border border-control px-3 py-2"),onClick:()=>k(void 0,!0),children:"New chat"})}):c.jsxs("div",{className:T("flex h-full min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6","text-body text-ink-muted"),children:[c.jsx("p",{className:T("text-center"),children:n.isLoading?"Connecting to the backend… Your conversation is safe.":n.error?bi(n.error,"The Local Operator server did not answer as expected."):l??"Update the backend to use canonical chats. Your existing histories are unchanged."}),d&&c.jsx("button",{type:"button",className:T("underline"),onClick:()=>void h(),children:"Retry"})]})]})}const jW=100,fqe=4,pqe=16,gqe=3;function HW(e,t){return t.sessionId??(e.startsWith("send:")?e.slice(5):void 0)}function mqe(e){const t=[];for(const[n,s]of Object.entries(e)){if(s.admissionAttempted!==!0||s.pending===!0||s.submittedText===void 0)continue;const r=HW(n,s);r&&t.push({key:n,sessionId:r,submittedAt:s.submittedAt??0})}return t}function UW(e){const t=new Map;for(const[n,s]of Object.entries(e)){const r=s.undelivered?.recordId;if(r===void 0)continue;const i=HW(n,s);if(!i)continue;const a=t.get(i);a?a.push(r):t.set(i,[r])}return t}function vqe(e){const t=new Map,n=mqe(e).sort((s,r)=>s.submittedAt-r.submittedAt);for(const s of n){const r=t.get(s.sessionId);r?r.push(s.key):t.set(s.sessionId,[s.key])}return t}let hg=null;function bqe(){return hg||(hg=xqe().catch(()=>({visited:0,resolved:0,healed:0})).finally(()=>{hg=null}),hg)}async function xqe(){const e=Ce.getState().drafts,t=vqe(e),n=UW(e),s=[...new Set([...t.keys(),...n.keys()])].slice(0,pqe);let r=0,i=0,a=0;const o=async()=>{for(;;){const l=s.shift();if(l===void 0)return;r+=1;const u=await wqe(l,t.get(l)??[],n.get(l)??[]);i+=u.resolved,a+=u.healed}};return await Promise.all(Array.from({length:Math.min(gqe,s.length)},o)),{visited:r,resolved:i,healed:a}}async function wqe(e,t,n){let s;try{s=await xt({op:"sessions.history",sessionId:e,limit:jW})}catch{return{resolved:0,healed:0}}Ce.getState().resolveHeldFromServer(e,s.entries,!1);const r=new Set(UW(Ce.getState().drafts).get(e)??[]),i=n.filter(u=>r.has(u)),a=n.length-i.length,o=i.length>0?await Cqe(e,s,i):0;let l=0;for(const u of t){const d=Ce.getState().drafts[u];if(!(d!==void 0&&d.admissionAttempted===!0&&d.submittedText!==void 0)){l+=1;for(const f of[u,EB(u,e)])Ba.getState().reconcileDelivered(f)}}return{resolved:l,healed:a+o}}async function Cqe(e,t,n){const s=new Set(n);let r=t.entries[0]?.id;for(let i=0;i<fqe;i++){if(s.size===0||!r)return n.length-s.size;let a;try{a=await xt({op:"sessions.history",sessionId:e,limit:jW,beforeId:r})}catch{return n.length-s.size}for(const o of a.entries)s.delete(o.id);if(Ce.getState().resolveHeldFromServer(e,a.entries,!1),a.cursor_missing||!a.has_more||a.entries.length===0)return n.length-s.size;r=a.entries[0]?.id}return n.length-s.size}let C3=!1;function yqe(){g.useEffect(()=>{C3||(C3=!0,bqe())},[])}const _qe="n",Sqe=e=>e.defaultPrevented||e.repeat||e.isComposing||e.shiftKey||e.altKey||e.key.toLowerCase()!==_qe||!(e.metaKey||e.ctrlKey)||dQ(e.target)?!1:!lT(e.target),y3=e=>e?"⌘+N":"Ctrl+N",Eqe=()=>{const e=Lc(o=>o.request),t=Lc(o=>o.consumePanel),[n,s]=g.useState(null),r=g.useRef(null),i=g.useCallback(()=>{s(null);const o=r.current;r.current=null,o&&requestAnimationFrame(()=>{o.isConnected&&o.focus()})},[]);g.useEffect(()=>{if(!e)return;const o=hQ({request:e,presentable:!!xF(e.destination),claimed:Lc.getState().presenterClaimed,now:Date.now()});if(o==="retire"){t(e.nonce);return}if(o==="yield"){s(null);return}o==="present"&&(r.current=e.invoker??(document.activeElement instanceof HTMLElement?document.activeElement:null),t(e.nonce),s({destination:e.destination,action:{kind:"native_action",destination:e.destination,session_id:"",args:"",fields:[],data:{}}}))},[e,t]);const a=n?xF(n.destination):void 0;return!n||!a?null:c.jsx(a,{action:n.action,sessionId:"",frontend:null,onClose:i},n.destination)},Dk=op()(e=>({open:!1,openLanguage:()=>e({open:!0}),closeLanguage:()=>e({open:!1})}));function kqe(e){return!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.repeat||e.defaultPrevented?null:e.key.toLowerCase()==="k"?"chats":null}const Tqe={chats:wVe,everything:"",commands:yVe};function Rqe(e,t){const n=Tqe[e],s=Dw(n).scope;return t.open?Dw(t.query).scope===s?{action:"close"}:{action:"switch",query:n}:{action:"open",query:n}}function ko(e,t){switch(e){case"chats":return t?"⌘K":"Ctrl+K";case"commands":return t?"⌘⇧P":"Ctrl+Shift+P";default:return t?"⌘P":"Ctrl+P"}}function Aqe(e,t){switch(e){case"chats":return t?"⌘+K":"Ctrl+K";case"commands":return t?"⌘+⇧+P":"Ctrl+Shift+P";default:return t?"⌘+P":"Ctrl+P"}}function Fqe(e){if(e.key==="ArrowDown")return e.shiftKey||e.altKey||e.ctrlKey?null:"next";if(e.key==="ArrowUp")return e.shiftKey||e.altKey||e.ctrlKey?null:"previous";const t=e.key.toLowerCase();return t!=="n"&&t!=="p"||!e.ctrlKey||e.metaKey||e.shiftKey||e.altKey?null:t==="n"?"next":"previous"}function Dqe(e,t,n){return t<=0?null:n==="next"?(e+1)%t:(e-1+t)%t}function Pqe(e){return e?["Ctrl+N","Ctrl+P"]:["Ctrl+N"]}const Iqe={general:"settings-sidebar-general",radient:"settings-sidebar-radient-account",integrations:"settings-sidebar-integrations",appearance:"settings-sidebar-appearance",updates:"settings-sidebar-application-updates"},Nqe=[{get label(){return x("ui.settings.navigation.settings_sidebar.general")},ids:["general","appearance","speech","keyboard"]},{get label(){return x("ui.settings.navigation.settings_sidebar.account")},ids:["providers","integrations","radient"]},{get label(){return x("ui.settings.navigation.settings_sidebar.backend")},ids:["backend"]},{get label(){return x("ui.settings.navigation.settings_sidebar.system")},ids:["updates"]}],get=({activeSection:e,onSelectSection:t,sections:n})=>{Et();const s=oB("(min-width: 1040px)"),r=i=>{const a=e===i.id,o=c.jsxs("button",{type:"button",onClick:()=>t(i.id),"aria-current":a?"page":void 0,"aria-label":s?void 0:i.label,"data-tour-tag":Iqe[i.id],className:T("relative flex h-8 w-full items-center rounded-sm bg-transparent text-left text-body-sm hover:bg-row-hover hover:text-ink","transition-colors duration-fast ease-out-quart",s?"justify-start gap-2 px-3":"justify-center",a?"font-semibold text-ink":"text-ink-muted"),children:[a&&c.jsx("span",{"aria-hidden":"true",className:"absolute left-1 top-1/2 size-1 -translate-y-1/2 rounded-full bg-accent"}),c.jsx("span",{"aria-hidden":"true",className:T("flex size-4 shrink-0 items-center justify-center",a?"text-accent":"text-ink-dim"),children:c.jsx(i.icon,{size:16})}),s&&c.jsx("span",{className:"truncate",children:i.label})]});return s?c.jsx("li",{children:o},i.id):c.jsx("li",{children:c.jsx(Je,{content:i.label,side:"right",children:o})},i.id)};return c.jsx("nav",{"aria-label":x("ui.settings.navigation.settings_sidebar.settings_sections"),"data-glass-region":"page-sidebar",className:"flex h-full w-full flex-col overflow-hidden bg-surface",children:c.jsx("div",{className:"flex flex-1 flex-col gap-6 overflow-y-auto px-2 py-4",children:Nqe.map(i=>{const a=n.filter(o=>i.ids.includes(o.id));return a.length===0?null:c.jsxs("div",{children:[s&&c.jsx("div",{className:"px-3 pb-1 text-meta text-ink-dim",children:i.label}),c.jsx("ul",{className:"flex flex-col gap-0.5",children:a.map(r)})]},i.label)})})})},Mqe=[{id:"general",get label(){return x("ui.settings.navigation.settings_sidebar.general_settings")},icon:Pc},{id:"radient",get label(){return x("ui.settings.navigation.settings_sidebar.radient_account")},icon:Zj},{id:"integrations",get label(){return x("ui.settings.navigation.settings_sidebar.integrations")},icon:Sj},{id:"appearance",get label(){return x("ui.settings.navigation.settings_sidebar.appearance")},icon:_j},{id:"speech",get label(){return x("ui.settings.navigation.settings_sidebar.speech_voicing")},icon:Bne},{id:"keyboard",get label(){return x("ui.settings.navigation.settings_sidebar.keyboard_shortcuts")},icon:Fse},{id:"providers",get label(){return x("ui.settings.navigation.settings_sidebar.model_providers")},icon:kB},{id:"backend",get label(){return x("ui.settings.navigation.settings_sidebar.backend_settings")},icon:Nf},{id:"updates",get label(){return x("ui.settings.navigation.settings_sidebar.application_updates")},icon:qk}];function Oqe(){const e=Ce(n=>Lqe(n.activeDraftKey,n.activeDraftKey?n.drafts[n.activeDraftKey]?.sessionId:void 0,n.activeSessionId)),t=qe(n=>n.rememberConversation);g.useEffect(()=>{e!==null&&t(e)},[e,t])}function Lqe(e,t,n){const s=ip(e,t,n);return s||null}function Bqe(e,t,n,s,r){const i=t.indexOf(e.session_id);return{recentRank:i===-1?void 0:i,current:e.session_id===n,archived:dB(uB([e],r),s).length===0}}const _3=100,jqe=["desktop","settings"],Hqe=[{id:"chat",get name(){return x("ui.command_palette.use_palette_sources.chat")},path:"/chat",icon:"chat",keywords:["conversations","messages","history","sessions"]},{id:"agents",get name(){return x("ui.command_palette.use_palette_sources.my_agents")},path:"/agents",icon:"agents",keywords:["bots","assistants","roster","agent list"]},{id:"projects",get name(){return x("ui.command_palette.use_palette_sources.projects")},path:"/projects",icon:"projects",keywords:["workstreams","milestones","tracking","planning"]},{id:"agent-hub",get name(){return x("ui.command_palette.use_palette_sources.agent_hub")},path:"/agent-hub",icon:"hub",keywords:["store","marketplace","catalog","discover","browse agents"]},{id:"schedules",get name(){return x("ui.command_palette.use_palette_sources.schedules")},path:"/schedules",icon:"schedules",keywords:["cron","recurring","automation","jobs","timer","daily"]},{id:"browser",get name(){return x("ui.command_palette.use_palette_sources.browser")},path:"/browser",icon:"browser",keywords:["web","sites","url","internet"]},{id:"settings",get name(){return x("ui.command_palette.use_palette_sources.settings")},path:"/settings",icon:"settings",keywords:["preferences","config","options","configuration"]}],Uqe={id:"mesh",get name(){return x("ui.command_palette.use_palette_sources.mesh")},path:"/mesh",icon:"network",keywords:["networks","peers","devices","relay","mesh"]};function Gqe({open:e,query:t,isOnChatPage:n,hasConversation:s,isCanvasOpen:r}){Et();const{scope:i,terms:a}=Dw(t),o=i===null||i==="chat",l=i===null||i==="agent",u=i===null||i==="agent",d=i===null||i==="setting",h=Bn(),f=yt(h.data,"session_search"),p=yt(h.data,"settings"),m=yt(h.data,"session_catalogue",2),v=yt(h.data,"session_archive"),b=sC((o||u)&&yt(h.data,"team_catalogue")),w=g.useMemo(()=>new Map((b.data??[]).map(be=>[be.name,kf(be)])),[b.data]),C=ZT(yt(h.data,"peers")),y=yt(h.data,"projects",1),k=g.useMemo(()=>[...Hqe.filter(be=>be.id!=="projects"||y),...C==="member"?[Uqe]:[]],[C,y]),{data:_}=sp(),E=_?.snapshot?.pairing.available===!1,R=Ce(be=>be.sessions),F=Ce(be=>be.forgotten),A=Ce(be=>be.loading),N=Ce(be=>be.fetchSessions),M=g.useRef(!1);g.useEffect(()=>{if(!e){M.current=!1;return}M.current||R.length>0||A||(M.current=!0,N(Ww))},[e,R.length,A,N]);const D=aW(a,e&&o&&a.length>0&&f),L=D.data&&D.data.query===a?D.data.sessions:null,V=g.useMemo(()=>({include:!1,facts:{},forgotten:new Set(Object.keys(F))}),[F]),j=MZ(qe(be=>be.conversationRecents)),te=Ce(be=>{const ie=be.activeDraftKey?be.drafts[be.activeDraftKey]:void 0;return ip(be.activeDraftKey,ie?.sessionId,be.activeSessionId)}),X=Ce(be=>be.archiveFacts),re=(()=>{if(!o)return[];const{rows:be}=Ek(R,a,L,{},V),ie=new Map((L??[]).map(Te=>[Te.id,Te]));return be.map((Te,ee)=>{const de=ie.get(Te.session_id),De=rW(Te,a),Ue=qVe(Te,w),Se=Bqe(Te,j,te,v,X),ge=!!de?.body_match&&!De;return{...Ue,hint:ge?x("ui.command_palette.use_palette_sources.in_conversation"):Ue.hint,tier:De||de?Math.min(de?.rank??Fw,De?Fw:Number.POSITIVE_INFINITY):void 0,soft:Te.preview??void 0,order:ee,featured:a.length===0,unread:Bw(Te)!==null,recentRank:Se.recentRank,current:Se.current,archived:Se.archived}})})(),G=YS(1,_3),J=_p(a,iW),ae=(G.data?.total??0)>(G.data?.agents?.length??0),O=YS(1,_3,0,ae&&l&&J?J:void 0),U=(()=>{if(!l)return[];const be=new Set,ie=[];for(const ee of[G.data?.agents,O.data?.agents])for(const de of ee??[])be.has(de.id)||(be.add(de.id),ie.push(de));const Te=[];for(const ee of ie)m&&Te.push({id:`agent-chat-${ee.id}`,kind:"agent",group:"agents",name:ee.name,hint:x("ui.command_palette.use_palette_sources.agent_chat"),icon:"agents",keywords:ee.tags,target:{type:"draft",kind:"agent",name:ee.name},featured:a.length===0}),Te.push({id:`agent-settings-${ee.id}`,kind:"agent",group:"agents",name:ee.name,hint:x("ui.command_palette.use_palette_sources.agent_settings"),icon:"settings",keywords:ee.tags,target:{type:"path",path:`/agents/${ee.id}`}});return Te.map((ee,de)=>({...ee,order:de}))})(),P=u?m?(b.data??[]).map((be,ie)=>({id:`team-chat-${be.name}`,kind:"team",group:"teams",name:kf(be),hint:x("ui.command_palette.use_palette_sources.team_chat"),icon:"team",keywords:[be.name,...be.aliases??[]],target:{type:"draft",kind:"team",name:be.name},featured:a.length===0,order:ie})):[]:[],z=fs({queryKey:jqe,queryFn:()=>xt({op:"settings.list"}),enabled:e&&d&&p,staleTime:1e4}),ne=d?[...VVe(Mqe),...WVe((z.data?.settings??[]).map(dT))]:[],fe=Ce(be=>be.activeSessionId),ue=Ce(be=>be.activeDraftKey),le=m&&!!(fe??ue),q=!!fe,we=!m||E?[]:zVe([{id:"info",destination:"info",name:x("ui.command_palette.use_palette_sources.info"),hint:x("ui.command_palette.use_palette_sources.app_backend_and_environment"),icon:"info",keywords:["about","version","environment","diagnostics","host","runtime"]},{id:"usage",destination:"usage",name:x("ui.command_palette.use_palette_sources.provider_usage"),hint:x("ui.command_palette.use_palette_sources.credits_limits_and_spend"),icon:"usage",keywords:["usage","credits","billing","limits","cost","spend","tokens","quota"]},...le&&q?[{id:"session",destination:"session.diagnostics",name:x("ui.command_palette.use_palette_sources.session"),hint:x("ui.command_palette.use_palette_sources.diagnostics_for_this_conversation"),icon:"session",keywords:["diagnostics","report","tokens","context","timings","tool calls"]}]:[],{id:"analytics",destination:"analytics",name:x("ui.command_palette.use_palette_sources.analytics"),hint:x("ui.command_palette.use_palette_sources.usage_over_time"),icon:"analytics",keywords:["usage","charts","trends","cost","spend","tokens","reports"]}]);return{items:[...GVe(k),...$Ve(Vqe({isOnChatPage:n,hasConversation:s,isCanvasOpen:r,canStageDraft:m})),...we,...ne,...U,...P,...re],chats:{awaiting:e&&o&&a.length>0&&f&&!D.refused&&!D.isError&&D.data?.query!==a,unavailable:o&&a.length>0&&!f,unreachable:h.isError,pending:h.isLoading||h.isPending,overLong:D.refused,catalogue:R.length>0?"loaded":A||!M.current?"loading":"empty"}}}function Vqe({isOnChatPage:e,hasConversation:t,isCanvasOpen:n,canStageDraft:s}){return[...s?[{id:"new-chat",name:x("ui.command_palette.use_palette_sources.new_chat"),icon:"new-chat",keywords:["start chat","compose","draft","new conversation"],verb:x("ui.command_palette.use_palette_sources.start"),command:"new-chat",featured:!0}]:[],{id:"connect-provider",name:x("ui.command_palette.use_palette_sources.connect_a_model_provider"),icon:"providers",keywords:["sign in","login","api key","add provider","claude","chatgpt","radient","model"],verb:x("ui.command_palette.use_palette_sources.connect"),command:"connect-provider",featured:!0},{id:"change-interface-language",name:x("ui.settings.language.palette_action"),icon:"language",keywords:["language","locale","interface language","translation","i18n"],verb:x("ui.command_palette.use_palette_sources.change"),command:"change-interface-language"},{id:"create-agent",name:x("ui.command_palette.use_palette_sources.create_agent"),icon:"plus",keywords:["new agent","add agent","make agent"],verb:x("ui.command_palette.use_palette_sources.create"),command:"create-agent",featured:!0},...e?[{id:"toggle-canvas",name:n?x("ui.command_palette.use_palette_sources.close_canvas"):x("ui.command_palette.use_palette_sources.open_canvas"),icon:n?"canvas-close":"canvas-open",keywords:["files","workspace","panel","editor","artifacts"],verb:n?x("ui.command_palette.use_palette_sources.close"):x("ui.command_palette.use_palette_sources.open"),command:"toggle-canvas",featured:!0}]:[],...e&&t?[{id:"clear-conversation",name:x("ui.command_palette.use_palette_sources.clear_conversation"),icon:"trash",keywords:["delete chat","reset","wipe","erase","clear history"],verb:x("ui.command_palette.use_palette_sources.clear"),command:"clear-conversation",destructive:!0,featured:!0}]:[]]}const Wqe={chat:FT,conversation:Sx,agents:Uo,team:Og,projects:bj,hub:kj,network:TB,schedules:mj,browser:qc,settings:Pc,theme:_j,integrations:Sj,providers:kB,backend:Nf,updates:qk,plus:Kc,"new-chat":Are,trash:P0,"canvas-open":fQ,"canvas-close":zc,slider:Nf,info:ap,language:xj,usage:xse,session:gj,analytics:zne},$qe=({name:e})=>{if(e==="account")return c.jsx(Zj,{size:16});const t=Wqe[e];return c.jsx(t,{size:16,"aria-hidden":"true"})},fg="command-palette-input",S3="command-palette-results",zqe={get page(){return x("ui.command_palette.command_palette.go")},get action(){return x("ui.command_palette.command_palette.run")},get panel(){return x("ui.command_palette.command_palette.open")},get chat(){return x("ui.command_palette.command_palette.open")},get agent(){return x("ui.command_palette.command_palette.open")},get team(){return x("ui.command_palette.command_palette.open")},get"settings-section"(){return x("ui.command_palette.command_palette.open")},get setting(){return x("ui.command_palette.command_palette.open")}},qqe=200,E3=()=>{const e=Ce.getState(),t=e.activeDraftKey;return AB(t,t?e.drafts[t]?.sessionId:void 0,e.activeSessionId)},Kqe=()=>{Et();const e=Jr(),t=aT(),n=qe(ee=>ee.isCommandPaletteOpen),s=qe(ee=>ee.closeCommandPalette),r=qe(ee=>ee.commandPaletteQuery),i=qe(ee=>ee.setCommandPaletteQuery),a=qe(ee=>ee.isCanvasOpen),o=qe(ee=>ee.setCanvasOpen),l=qe(ee=>ee.isCreateAgentDialogOpen),u=Lc(ee=>ee.requestPanel),{agentId:d}=Yae(),h=Q4(ee=>ee.getLastAgentId),f=Xj(),[p,m]=g.useState(r),[v,b]=g.useState(0),w=g.useRef(null),[C,y]=g.useState(!1),[k,_]=g.useState(!1),E=g.useDeferredValue(p),R=_p(p,qqe);g.useEffect(()=>{i(R)},[R,i]),g.useEffect(()=>{n&&m(r)},[n,r]);const F=t.pathname.startsWith("/chat"),A=d||h("chat"),{items:N,chats:M}=Gqe({open:n,query:E,isOnChatPage:F,hasConversation:!!A,isCanvasOpen:a}),D=g.useMemo(()=>HVe({items:N,raw:E}),[N,E]),L=g.useMemo(()=>D.sections.flatMap(ee=>ee.items),[D]),V=L.length,j=L[v],te=D.terms.length>0,X=V>0,re=D.scope===null?null:Tk.find(ee=>ee.scope===D.scope)??null,G=vVe({scope:D.scope,hasTerms:te,terms:D.terms,awaiting:M.awaiting,catalogue:M.catalogue}),J=g.useCallback(()=>{s(),e("/agents?create=agent")},[s,e]),ae=g.useCallback(()=>{s(),RB.getState().openConnect()},[s]),O=g.useCallback(()=>{s(),Dk.getState().openLanguage()},[s]),U=g.useCallback(()=>{Ce.getState().stageDraft(void 0,!0),s(),e("/chat")},[s,e]),P=g.useCallback(()=>{o(!a),s()},[a,o,s]),z=g.useCallback(()=>{A&&_(!0)},[A]),ne=g.useCallback(()=>{A&&f.mutate({agentId:A}),_(!1),s()},[A,f,s]),fe=g.useCallback(ee=>{switch(ee){case"create-agent":J();return;case"connect-provider":ae();return;case"change-interface-language":O();return;case"new-chat":U();return;case"toggle-canvas":P();return;case"clear-conversation":z()}},[J,ae,O,U,P,z]),ue=g.useRef(null),le=g.useRef(void 0),q=g.useCallback(ee=>{switch(ee.target.type){case"path":s(),e(ee.target.path);return;case"session":{const{sessionId:de}=ee.target;s(),cp(e,de);return}case"command":fe(ee.target.command);return;case"draft":{const{kind:de,name:De}=ee.target;Ce.getState().stageDraft({kind:de,name:De}),s(),e("/chat");return}case"panel":{const{destination:de}=ee.target;u(de,ue.current),s(),yB(de)&&!t.pathname.startsWith("/chat")&&e("/chat");return}}},[s,e,t.pathname,u,fe]);g.useEffect(()=>{if(!n)return;const ee=document.activeElement;ue.current=ee instanceof HTMLElement?ee:null,le.current=E3()},[n]);const we=g.useCallback(()=>{const ee=ue.current,de=pQ({viewMoved:le.current!==E3(),capturedUsable:!!(ee?.isConnected&&ee!==document.body),caretUntouched:mQ(ee,document.activeElement,document.body)});if(!(de==="composer"&&gQ())&&de!=="leave"){if(de==="captured"&&ee){ee.focus();return}document.querySelector("[data-command-palette-trigger]")?.focus()}},[]);g.useEffect(()=>{n&&document.getElementById(fg)?.focus()},[n]),g.useEffect(()=>{b(0)},[E,n]);const B=g.useCallback(ee=>{if(w.current?.disconnect(),!ee?.parentElement)return;const de=ee.parentElement,De=()=>{const Se=getComputedStyle(de),ge=Number.parseFloat(Se.paddingTop)+Number.parseFloat(Se.paddingBottom);y(ee.offsetHeight+ge>de.clientHeight+1)};De();const Ue=new ResizeObserver(De);Ue.observe(de),Ue.observe(ee),w.current=Ue},[]);if(g.useEffect(()=>{b(ee=>ee>=V?Math.max(V-1,0):ee)},[V]),g.useEffect(()=>{if(!n)return;const ee=de=>{if(k||l||de.target?.id!==fg)return;const De=L.length,Ue=Fqe(de);if(Ue!==null)de.preventDefault(),b(Se=>Dqe(Se,De,Ue)??Se);else if(de.key==="Enter"){de.preventDefault();const Se=L[v];Se&&q(Se.item)}else de.key==="Escape"&&(de.preventDefault(),s())};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[n,k,l,L,v,q,s]),g.useEffect(()=>{if(!n)return;const ee=L[v]?.item.id;ee&&document.getElementById(ee)?.scrollIntoView({block:"nearest",behavior:"auto"})},[n,L,v]),!n)return null;const be=j?.item,ie=!te||!X,Te=Pqe(navigator.platform.toUpperCase().indexOf("MAC")>=0);return c.jsxs(c.Fragment,{children:[c.jsx(Wl,{open:n,onOpenChange:ee=>{ee||s()},children:c.jsxs($l,{"data-tour-tag":"command-palette-dialog",showClose:!1,className:"z-[2300] w-160 max-w-[90vw] gap-0 overflow-hidden p-0",overlayClassName:"z-[2300]",onOpenAutoFocus:ee=>{ee.preventDefault();const de=document.getElementById(fg);de instanceof HTMLInputElement&&(de.focus(),de.setSelectionRange(de.value.length,de.value.length))},onCloseAutoFocus:ee=>{ee.preventDefault(),we()},children:[c.jsx(jo,{className:"sr-only",children:x("ui.command_palette.command_palette.command_palette")}),c.jsxs("div",{className:"flex h-13 shrink-0 items-center gap-3 border-hairline border-b px-4",children:[c.jsx(xd,{size:16,"aria-hidden":"true",className:"shrink-0 text-ink-dim"}),c.jsx("input",{id:fg,type:"text",role:"combobox","aria-expanded":X,"aria-controls":X?S3:void 0,"aria-activedescendant":be?.id,"aria-autocomplete":"list",autoComplete:"off",placeholder:x("ui.command_palette.command_palette.search_chats_settings_pages_and_actions"),value:p,onChange:ee=>m(ee.target.value),className:"min-w-0 flex-1 bg-transparent text-body text-ink outline-none! placeholder:text-ink-dim"}),re&&c.jsxs("span",{className:"flex shrink-0 items-center gap-0 text-ink-dim text-meta",children:[c.jsx(Er,{shortcut:re.glyph}),re.label]}),p&&c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":x("ui.command_palette.command_palette.clear_search"),onClick:()=>{m(""),document.getElementById(fg)?.focus()},children:c.jsx(Dn,{"aria-hidden":"true"})})]}),X?c.jsxs("div",{className:"relative",children:[C&&c.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-6 bg-gradient-to-t from-elevated to-transparent"}),c.jsxs("div",{role:"listbox",id:S3,"aria-label":x("ui.command_palette.command_palette.results"),tabIndex:-1,className:"max-h-96 overflow-y-auto p-2",children:[c.jsx("div",{ref:B,children:D.sections.map((ee,de)=>c.jsxs(g.Fragment,{children:[c.jsx("div",{role:"presentation",className:T("px-2 pb-1 text-ink-dim text-meta",de===0?"pt-1":"pt-3"),children:NVe[ee.group]}),ee.items.map(De=>c.jsx(Yqe,{match:De,isActive:De.item.id===be?.id,onHover:()=>b(L.indexOf(De)),onRun:()=>q(De.item)},De.item.id))]},ee.group))}),C&&c.jsx("div",{"aria-hidden":"true",className:"h-6"})]})]}):c.jsxs("div",{className:"flex flex-col items-center gap-1 px-6 py-10 text-center",children:[c.jsx("p",{className:"text-body-sm text-ink",children:G.line}),G.hint!==null&&c.jsx("p",{className:"text-ink-dim text-meta",children:G.hint})]}),X&&te&&M.awaiting&&c.jsx("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:x("ui.command_palette.command_palette.searching_conversations")}),te&&M.overLong&&c.jsxs("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:[x("ui.command_palette.command_palette.search_terms_are_limited_to"),lC,x("ui.command_palette.command_palette.characters_so_chats_are_matched_by_name")]}),te&&!M.overLong&&M.unavailable&&!M.pending&&c.jsx("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:M.unreachable?x("ui.command_palette.command_palette.conversation_search_is_unavailable_while_the_backend_is_unreachab"):x("ui.command_palette.command_palette.chats_are_matched_by_name_update_local_operator_to_search_inside_")}),c.jsx("div",{className:"flex shrink-0 items-center gap-4 border-hairline border-t px-4 py-2 text-ink-dim text-meta",children:ie?c.jsxs(c.Fragment,{children:[Tk.map(ee=>c.jsxs("span",{className:"flex items-center gap-0",children:[c.jsx(Er,{shortcut:ee.glyph}),ee.label]},ee.scope)),c.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"esc"}),x("ui.command_palette.command_palette.to_close")]})]}):c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"↑"}),c.jsx(Er,{shortcut:"↓"}),Te.map(ee=>c.jsx(Er,{shortcut:ee,joined:!0},ee)),x("ui.command_palette.command_palette.to_move")]}),c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"↵"}),x("ui.command_palette.command_palette.to_run")]}),c.jsx("span",{className:"flex items-center gap-1.5",children:D.clipped&&c.jsx("span",{children:te?x("ui.command_palette.matches.best",{countText:String(V),total:D.total,totalText:String(D.total)}):x("ui.command_palette.matches.showing",{count:String(V),total:String(D.total)})})}),c.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"esc"}),x("ui.command_palette.command_palette.to_close")]})]})})]})}),c.jsx(au,{open:k,title:x("ui.command_palette.command_palette.clear_this_conversation"),message:x("ui.command_palette.command_palette.every_message_in_it_is_deleted_from_this_computer_and_there_is_no"),confirmText:x("ui.command_palette.command_palette.clear"),cancelText:x("ui.common.actions.cancel"),isDangerous:!0,onConfirm:ne,onCancel:()=>_(!1)})]})},Yqe=({match:e,isActive:t,onHover:n,onRun:s})=>{const{item:r,soft:i}=e,a=r.verb??zqe[r.kind];return c.jsxs("button",{id:r.id,type:"button",role:"option","aria-selected":t,tabIndex:-1,onClick:s,onMouseMove:n,className:T("flex h-9 w-full items-center gap-3 rounded-sm px-2 text-left","transition-colors duration-fast ease-out-quart",t?"bg-sunken outline-solid outline-1 -outline-offset-1 outline-control":"bg-transparent"),children:[c.jsx("span",{className:T("flex size-4 shrink-0 items-center justify-center",r.destructive?"text-danger":"text-ink-dim"),children:c.jsx($qe,{name:r.icon})}),c.jsx("span",{className:T("shrink-0 truncate text-body-sm",r.destructive?"text-danger":i&&!t?"text-ink-muted":"text-ink"),children:r.name}),r.hint&&c.jsx("span",{className:"min-w-0 flex-1 truncate text-ink-dim text-meta",children:r.hint}),!r.hint&&c.jsx("span",{className:"flex-1"}),t&&c.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-ink-dim text-meta",children:[a,c.jsx(Er,{shortcut:"↵"})]})]})},Xqe="toggle-command-palette",Qqe="toggle-command-palette-commands";function B1(e){const t=qe.getState(),n=Rqe(e,{open:t.isCommandPaletteOpen,query:t.commandPaletteQuery});n.action==="open"?t.toggleCommandPalette(n.query):n.action==="close"?t.closeCommandPalette():t.setCommandPaletteQuery(n.query)}function Jqe(){g.useEffect(()=>{const e=t=>{const n=kqe(t);n&&(t.preventDefault(),B1(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),g.useEffect(()=>{const e=window.electron.ipcRenderer.on(Xqe,()=>B1("everything")),t=window.electron.ipcRenderer.on(Qqe,()=>B1("commands"));return()=>{e?.(),t?.()}},[])}const Zqe=({enabled:e})=>{const t=ZT(e),n=ehe(e&&t==="member",{poll:!0,stamp:()=>Ce.getState().beginAnswer()}),s=Ce(r=>r.settlePeerCatalogue);return g.useEffect(()=>{n.data&&s(n.data.rows.map(ode),n.data.requestedAt)},[n.data,s]),null},eKe={single:"max-w-[min(40rem,calc(100vw-4rem))]"},tKe=({open:e,title:t,stepIndicators:n,children:s,actions:r,width:i="single",className:a,onDismiss:o})=>{const l=g.useRef(null);return c.jsx(Wl,{open:e,onOpenChange:u=>{u||o?.()},children:c.jsxs($l,{"data-onboarding-modal":"",showClose:o!==void 0,onEscapeKeyDown:u=>{o||u.preventDefault()},onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),onOpenAutoFocus:u=>{u.preventDefault(),l.current?.focus()},className:T("max-h-[calc(100vh-4rem)] gap-0 overflow-hidden p-0",eKe[i],a),children:[(t||n)&&c.jsxs("div",{className:T("flex shrink-0 items-center justify-between gap-4 border-hairline border-b px-6 py-4",o&&"pr-14"),children:[t?c.jsx(jo,{className:"text-title",children:t}):c.jsx(jo,{className:"sr-only",children:x("ui.onboarding.dialog.setup")}),n]}),c.jsx("div",{ref:l,tabIndex:-1,className:"min-h-0 flex-1 overflow-y-auto px-6 py-6 outline-none!",children:s}),r&&c.jsx("div",{className:"shrink-0 border-hairline border-t px-6 py-4",children:r})]})})};function nKe(e,t,n=!1){const s=e===kr.DEFAULT_MODEL&&t!==null;return{blocked:s,reason:s?t:null,primaryDisabled:n||s}}const Zb=({value:e,label:t,variant:n="ghost",onCopied:s})=>{Et();const[r,i]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const a=setTimeout(()=>i(!1),2e3);return()=>clearTimeout(a)},[r]),c.jsxs(ce,{variant:n,size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),i(!0),s?.()}catch{zt(x("ui.common.actions.copy_failed"))}},children:[r?c.jsx(Bs,{"aria-hidden":"true"}):c.jsx(Gl,{"aria-hidden":"true"}),r?x("ui.common.actions.copied"):t]})},sKe=3e3,Sh={all:["desktop","tunnel","setup"],local:e=>["desktop","tunnel","setup","local",e],fresh:e=>["desktop","tunnel","setup","fresh",e]};function xb(e,t){if(e instanceof Hi){const n=e.code;if(n==="setup_in_progress")return"in-progress";if(n!==void 0&&n!=="setup_intent_corrupt"&&LZ.has(n))return{kind:"backend",message:e.message,code:n};if(t==="run"&&(e.status===null||n===oC.transportFailed||n===QB))return"unconfirmed"}return{kind:"generic",during:t}}function rKe(e){if(!e.enabled)return{kind:"hidden"};if(e.runPending||e.local?.in_progress){const t=e.local?.progress??[];return{kind:"applying",progress:t,setup:e.runPending||t.length>1,account:e.fresh&&(e.runPending||e.local?.active_credential_id===e.fresh.credential_id)?e.fresh:void 0}}return e.failure?{kind:"failure",failure:e.failure}:e.fresh?{kind:"result",result:e.fresh}:e.freshErrored?{kind:"failure",failure:{kind:"generic",during:"check"}}:{kind:"checking"}}const j1=e=>OZ.parse(e);function iKe(){const e=nn(),t=Bn(),n=yt(t.data,"tunnel_setup"),[s,r]=g.useState(null),[i,a]=g.useState(null),[o,l]=g.useState(!1),u=g.useRef(0),d=g.useRef(!1),h=g.useRef(!1),f=g.useRef(!1),p=Kn({retry:!1,mutationFn:async N=>j1(await xt({op:"tunnel.setup.run",credentialId:N.credentialId,acceptMonthlyPrice:N.price})),onSuccess:N=>{f.current=h.current,a(null),e.setQueryData(Sh.fresh(s),N)},onError:N=>{const M=xb(N,"run");M==="unconfirmed"?(u.current=Date.now(),l(!0)):M!=="in-progress"&&a(M)},onSettled:(N,M)=>{d.current=M!==null&&xb(M,"run")==="unconfirmed",e.invalidateQueries({queryKey:Sh.local(s)})}}),m=p.isPending||o,v=fs({queryKey:Sh.local(s),queryFn:async()=>j1(await xt({op:"tunnel.setup.read",credentialId:s??void 0})),enabled:n,retry:!1,staleTime:0,refetchOnWindowFocus:!1,refetchInterval:N=>m||N.state.data?.in_progress?sKe:!1}),b=v.data,w=b?.in_progress===!0||m,C=fs({queryKey:Sh.fresh(s),queryFn:async()=>{try{return j1(await xt({op:"tunnel.setup.plan",credentialId:s??void 0}))}catch(N){throw xb(N,"check")==="in-progress"&&e.invalidateQueries({queryKey:Sh.local(s)}),N}},enabled:n&&v.isSuccess&&!w,retry:!1,staleTime:Number.POSITIVE_INFINITY,gcTime:0,refetchOnWindowFocus:!1,refetchOnMount:"always"}),y=g.useRef(Date.now()),k=C.data&&C.dataUpdatedAt>=y.current?C.data:void 0,_=b?.in_progress===!0;g.useEffect(()=>{h.current&&!_&&(f.current?f.current=!1:d.current||C.refetch()),h.current=_},[_,C.refetch]),g.useEffect(()=>{o&&b&&!b.in_progress&&v.dataUpdatedAt>u.current&&(l(!1),d.current=!1,e.resetQueries({queryKey:Sh.fresh(s)}))},[o,b,v.dataUpdatedAt,e,s]),g.useEffect(()=>{const N=v.error??C.error;if(!N)return;const M=xb(N,"check");M!=="in-progress"&&M!=="unconfirmed"&&a(M)},[v.error,C.error]);const E=rKe({enabled:n,local:b,fresh:k,failure:i,runPending:m,freshErrored:C.isError&&!k}),R=g.useCallback(N=>{a(null),r(N)},[]),F=g.useCallback(()=>{a(null),v.refetch(),C.refetch()},[v.refetch,C.refetch]),A=g.useCallback((N,M)=>{d.current||(d.current=!0,f.current=!1,a(null),p.mutate({credentialId:N,price:M}))},[p.mutate]);return{view:E,selectedId:s,choose:R,check:F,run:A}}const vm=({status:e})=>c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e==="connected"?c.jsx(pT,{size:20,className:"shrink-0 text-success","aria-hidden":"true"}):null,c.jsx("h4",{className:"text-heading text-ink",children:x("ui.providers.phone.heading")}),e==="checking"?c.jsxs("span",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{children:x("ui.providers.phone.status.checking")})]}):null,e==="applying"?c.jsxs("span",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{children:x("ui.providers.phone.status.applying")})]}):null,e==="connected"?c.jsx("output",{className:"text-body-sm text-success",children:x("ui.providers.phone.status.connected")}):null]}),eA=({result:e})=>{if(e.credential_id===null)return null;const t=String(e.credential_id);return c.jsx("p",{className:"break-words text-body-sm text-ink-muted",children:e.identity_label?x("ui.providers.phone.account",{identity:e.identity_label,id:t}):x("ui.providers.phone.account_unlabeled",{id:t})})},Pw=({heading:e,lines:t})=>t.length===0?null:c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("p",{className:"text-meta text-ink-dim",children:e}),c.jsx("ul",{className:"flex list-none flex-col gap-1 p-0",children:t.map((n,s)=>c.jsx("li",{className:"break-words text-body-sm text-ink",children:n},s))})]}),aKe=e=>{const t={not_activated:"ui.providers.phone.outcome.billing_not_activated",already_active:"ui.providers.phone.outcome.billing_already_active",activated:"ui.providers.phone.outcome.billing_activated_status",unconfirmed:"ui.providers.phone.outcome.billing_unconfirmed"},n={saved:"ui.providers.phone.outcome.reservation_saved",existing:"ui.providers.phone.outcome.reservation_existing",unconfirmed:"ui.providers.phone.outcome.reservation_unconfirmed"},s={billing:"ui.providers.phone.outcome.stage_billing",reservation:"ui.providers.phone.outcome.stage_reservation",configuration:"ui.providers.phone.outcome.stage_configuration",installation:"ui.providers.phone.outcome.stage_installation",verification:"ui.providers.phone.outcome.stage_verification",prerequisites:"ui.providers.phone.outcome.stage_prerequisites"},r=[],i=t[e.billing_outcome],a=n[e.reservation_outcome],o=s[e.failure_stage];return i&&r.push(x(i)),a&&r.push(x(a)),o&&r.push(x("ui.providers.phone.outcome.failure_stage",{stage:x(o)})),r},oKe=({failure:e,onCheck:t})=>c.jsxs("div",{className:"flex flex-col items-start gap-3",children:[c.jsx("p",{role:"alert",className:"break-words text-body-sm text-ink",children:e.kind==="backend"?e.message:e.during==="run"?x("ui.providers.phone.failure.run"):x("ui.providers.phone.failure.check")}),c.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:x("ui.providers.phone.action.check_again")})]}),lKe=({result:e})=>c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"verified","data-phone-verified":"true",children:[c.jsx(vm,{status:"connected"}),c.jsx(eA,{result:e}),e.url?c.jsxs("div",{className:"flex flex-col items-start gap-2",children:[c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.providers.phone.address_label")}),c.jsx("code",{className:"break-all text-ink text-mono-sm",children:e.url}),c.jsx(Zb,{value:e.url,label:x("ui.providers.phone.action.copy_address"),variant:"secondary"})]}):null,c.jsx("p",{className:"break-words text-body-sm text-ink-muted",children:x("ui.providers.phone.use_address")}),c.jsx(Pw,{heading:x("ui.providers.phone.receipts_heading"),lines:e.receipts.map(t=>t.text)})]}),cKe=({onDone:e})=>{const{issue:t,start:n,cancel:s}=vQ(),r=t.kind==="signing-in"||t.kind==="input-required",i=g.useRef(!1);return g.useEffect(()=>{i.current&&!r&&e(),i.current=r},[r,e]),r?c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{className:"text-body-sm text-ink-muted",children:x("ui.providers.phone.signing_in")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:x("ui.providers.phone.action.cancel")})]}):c.jsxs(ce,{variant:"primary",size:"sm",onClick:n,children:[x("ui.providers.phone.action.sign_in"),c.jsx(xl,{"aria-hidden":"true"})]})},uKe=({result:e,setup:t,offerSignIn:n})=>{const s=e.remedy?.kind??null,r=e.credential_id,i=e.quote?.monthly_price_usd??null,a=c.jsx(ce,{variant:"secondary",size:"sm",onClick:t.check,children:x("ui.providers.phone.action.check_again")}),o=s==="accept_quote"&&e.ready&&r!==null&&i!==null,l=s==="run"&&e.ready&&r!==null;let u=a,d=null;return o&&r!==null&&i!==null?(u=c.jsx(ce,{variant:"primary",size:"sm",onClick:()=>t.run(r,i),children:x("ui.providers.phone.action.activate",{amount:i})}),d=a):l&&r!==null?(u=c.jsx(ce,{variant:"primary",size:"sm",onClick:()=>t.run(r),children:x("ui.providers.phone.action.set_up")}),d=a):s==="sign_in"&&n&&(u=c.jsx(cKe,{onDone:t.check}),d=a),c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":e.blocked_on,"data-remedy-kind":s??"none",children:[c.jsx(vm,{}),c.jsx(eA,{result:e}),s==="choose_account"?c.jsxs("div",{className:"flex flex-col items-start gap-2",children:[c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.providers.phone.choose_heading")}),e.credential_choices.map(h=>c.jsx(ce,{variant:"secondary",size:"sm",onClick:()=>t.choose(h.id),children:h.identity_label?x("ui.providers.phone.action.choose",{identity:h.identity_label,id:String(h.id)}):x("ui.providers.phone.action.choose_unlabeled",{id:String(h.id)})},h.id))]}):null,e.remedy?c.jsx("p",{className:"break-words text-body-sm text-ink",children:e.remedy.text}):null,o&&i!==null?c.jsx("p",{className:"break-words text-body-sm text-ink",children:x("ui.providers.phone.consent",{amount:i})}):null,c.jsx(Pw,{heading:x("ui.providers.phone.progress_heading"),lines:aKe(e)}),c.jsx(Pw,{heading:x("ui.providers.phone.receipts_heading"),lines:e.receipts.map(h=>h.text)}),s==="choose_account"?null:c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[u,d]})]})},dKe=({offerSignIn:e})=>{const t=iKe(),{view:n}=t;return n.kind==="hidden"?null:c.jsxs("section",{className:"flex flex-col gap-3 border-hairline border-t pt-4","aria-label":x("ui.providers.phone.heading"),"data-phone-block":n.kind,children:[n.kind==="checking"?c.jsx("div",{className:"flex flex-col gap-3","data-phone-state":"checking",children:c.jsx(vm,{status:"checking"})}):null,n.kind==="applying"?c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"applying",children:[c.jsx(vm,{status:n.setup?"applying":"checking"}),n.account?c.jsx(eA,{result:n.account}):null,c.jsx(Pw,{heading:x("ui.providers.phone.progress_heading"),lines:n.progress})]}):null,n.kind==="failure"?c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"failure",children:[c.jsx(vm,{}),c.jsx(oKe,{failure:n.failure,onCheck:t.check})]}):null,n.kind==="result"&&n.result.verified?c.jsx(lKe,{result:n.result}):null,n.kind==="result"&&!n.result.verified?c.jsx(uKe,{result:n.result,setup:t,offerSignIn:e}):null]})},hKe=({offerSignIn:e=!1})=>{const t=Bn();return yt(t.data,"tunnel_setup")?c.jsx(dKe,{offerSignIn:e}):null},bm={phase:"idle",operation:null,opened:!1,openFailed:!1,error:null};let vo=null;const fKe=[[/^Sign-in complete\.?$/,"succeeded"],[/^Sign-in cancelled\.?$/,"cancelled"],[/^Replaced by a new sign-in\.?$/,"cancelled"],[/^Sign-in expired\b/,"expired"],[/^Sign-in failed\b/,"failed"]];function H1(e){if(bc(e.state))return e;for(const[t,n]of fKe)if(t.test(e.message))return{...e,state:n};return e.state!=="starting"&&e.expires_in<=0?{...e,state:"expired"}:e}function pKe(e,t){return{id:e,provider:t,state:"expired",message:"This sign-in is no longer available. Start again.",auth_url:null,instructions:null,input_required:!1,prompt_id:null,expires_in:0}}function k3(e,t){return e instanceof Error&&e.message?e.message:t}function gKe(e){let t=bm,n=null,s=null,r=0,i=!1;const a=f=>{t={...t,...f},i||e.onChange(t)},o=()=>{n?.(),n=null},l=async(f,p)=>{const m=f.auth_url;if(!m||FB(f))return;const v=`${f.id}|${m}`;if(s!==v){s=v;try{await e.open(f.id,!1),p===r&&a({opened:!0,openFailed:!1})}catch{p===r&&a({opened:!1,openFailed:!0})}}},u=(f,p)=>{if(p!==r)return;const m=H1(f),v=s!==null&&s===`${m.id}|${m.auth_url}`;if(bc(m.state)){o(),vo?.id===m.id&&(vo=null),a({phase:"settled",operation:m,opened:v&&t.opened}),m.state==="succeeded"&&e.onSucceeded?.(m);return}a({phase:"active",operation:m,opened:v?t.opened:!1}),l(m,p)},d=(f,p)=>{u(f,p),!(bc(H1(f).state)||p!==r)&&(o(),n=e.poll(f.id,m=>u(m,p),{onGone:()=>{p===r&&(n=null,vo?.id===f.id&&(vo=null),a({phase:"settled",operation:pKe(f.id,f.provider)}))}}))},h=async(f,p)=>{const m=vo;if(!m)return!1;let v=null;try{v=await e.read(m.id)}catch{v=null}if(p!==r)return!0;if(v&&!bc(v.state)&&m.provider===f)return d(v,p),!0;if(v&&!bc(v.state))try{await e.cancel(m.id)}catch{}if(vo=null,p!==r)return!0;const b=await e.start(f);return vo={id:b.id,provider:f},d(b,p),!0};return{async start(f){r+=1;const p=r;o();const m=t.operation;if(s=null,a({phase:"starting",operation:null,opened:!1,openFailed:!1,error:null}),m&&!bc(m.state)){try{await e.cancel(m.id)}catch{}if(p!==r)return}try{const v=await e.start(f);vo={id:v.id,provider:f},d(v,p)}catch(v){if(p!==r)return;if(v instanceof Hi&&v.status===409)try{if(await h(f,p))return}catch(b){if(p!==r)return;a({phase:"settled",error:k3(b,x("ui.providers.sign_in_flow.sign_in_could_not_start"))});return}a({phase:"settled",error:k3(v,x("ui.providers.sign_in_flow.sign_in_could_not_start"))})}},async cancel(){const f=t.operation;if(r+=1,o(),s=null,a({...bm}),!(!f||bc(f.state))){vo?.id===f.id&&(vo=null);try{await e.cancel(f.id)}catch{}}},async reopen(){const f=t.operation;if(!f?.auth_url)return;const p=r;try{await e.open(f.id,!0),s=`${f.id}|${f.auth_url}`,p===r&&a({opened:!0,openFailed:!1})}catch{p===r&&a({openFailed:!0})}},pause(){r+=1,o()},resume(){const f=t.operation;f&&(bc(H1(f).state)||(r+=1,d(f,r)))},reset(){r+=1,o(),s=null,a({...bm})},dispose(){i=!0,r+=1,o()},getState:()=>t}}const Pk=new Map,tA=new Map;function Mg(e){return tA.get(e)??{saved:null,error:null}}function mKe(e,t){tA.set(e,{...Mg(e),...t})}function vKe(e){tA.delete(e)}function bKe(e){return Pk.get(e)?.state??bm}function T3(e,t,n,s){const i=Pk.get(e)??(()=>{const a={flow:null,state:bm,listeners:new Set,deps:t};return a.flow=gKe({start:o=>a.deps.start(o),read:o=>a.deps.read(o),cancel:o=>a.deps.cancel(o),open:(o,l)=>a.deps.open(o,l),poll:(o,l,u)=>a.deps.poll(o,l,u),onChange:o=>{a.state=o;for(const l of a.listeners)l(o)},onSucceeded:o=>a.deps.onSucceeded?.(o)}),Pk.set(e,a),a})();return i.deps={...t,onSucceeded:t.onSucceeded},i.listeners.add(n),{flow:i.flow,getState:()=>i.state,setDeps:a=>{i.deps={...a,onSucceeded:a.onSucceeded}},resume:()=>i.flow.resume(),detach:()=>{i.listeners.delete(n),i.flow.pause()}}}function xKe(e,t){const n=g.useRef(t);n.current=t;const[s,r]=g.useState(()=>bKe(e)),[i,a]=g.useState(()=>T3(e,n.current(),r)),o=g.useRef(e);return g.useEffect(()=>{if(o.current===e)return;i.detach();const l=T3(e,n.current(),r);o.current=e,a(l),r(l.getState()),l.resume()},[e,i]),g.useEffect(()=>(i.setDeps(n.current()),r(i.getState()),i.resume(),()=>i.detach()),[i]),{flow:i.flow,state:s}}const wKe=({provider:e})=>{Et();const[t,n]=g.useState(!1),[s,r]=g.useState(null),i=g.useCallback(async()=>{n(!0);try{r(await xt({op:"auth.probe",provider:e.id}))}catch(o){r({reachable:!1,detail:o instanceof Error?o.message:x("ui.providers.provider_detail.the_connection_could_not_be_tested")})}finally{n(!1)}},[e.id]);g.useEffect(()=>{r(null),i()},[i]);const a=Ri(e);return c.jsxs("div",{className:"flex flex-col items-start gap-2",children:[s===null?c.jsxs("p",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{size:"sm"}),x("ui.providers.provider_detail.checking_whether"),a," ",x("ui.providers.provider_detail.is_running")]}):s.reachable?c.jsxs("p",{className:"text-body-sm text-success",children:[a," ",x("ui.providers.provider_detail.is_running")]}):c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[a," ",x("ui.providers.provider_detail.isn_t_answering"),e.base_url?c.jsxs(c.Fragment,{children:[x("ui.providers.provider_detail.at"),c.jsx("span",{className:"font-mono",children:e.base_url})]}):null]}),c.jsx(ce,{variant:"secondary",size:"sm",onClick:()=>void i(),disabled:t,children:t?x("ui.providers.provider_detail.checking"):x("ui.providers.provider_detail.check_again")})]})},R3=({id:e,value:t,onChange:n,label:s,invalid:r,describedBy:i})=>{Et();const[a,o]=g.useState(!1);return c.jsxs("div",{className:"relative",children:[c.jsx(ps,{id:e,type:a?"text":"password",value:t,onChange:l=>n(l.target.value),autoComplete:"off",spellCheck:!1,"aria-label":s,"aria-invalid":r||void 0,"aria-describedby":i,className:"pr-10 font-mono"}),c.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",className:"absolute top-1/2 right-1 -translate-y-1/2",onClick:()=>o(l=>!l),"aria-label":a?x("ui.providers.provider_detail.hide_key"):x("ui.providers.provider_detail.show_key"),children:a?c.jsx(ase,{"aria-hidden":"true"}):c.jsx(lse,{"aria-hidden":"true"})})]})},CKe=/[.!?]$/,yKe=e=>CKe.test(e.trim())?e:`${e}.`,A3=({brand:e,verb:t,defaults:n,unverified:s,onChangeModel:r,actionLabel:i,onAction:a,primaryAction:o,headline:l,tone:u="success",verdict:d})=>{Et();const h=d?.group==="Needs sign-in",f=g.useRef(null);return g.useEffect(()=>{f.current?.focus()},[]),c.jsxs("div",{className:"flex flex-col gap-3","data-sign-in-state":"succeeded","data-verdict":h?d.tone:void 0,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[h&&d?c.jsx(Qa,{size:20,className:d.tone==="attention"?"text-warning":"text-ink-muted","aria-hidden":"true"}):c.jsx(pT,{size:20,className:u==="unchecked"?"text-ink-muted":"text-success","aria-hidden":"true"}),c.jsx("output",{className:"text-heading text-ink",children:h&&d?d.label:l??(t==="Connected"?x("ui.providers.provider_detail.connected_variant_163",{brand:e}):x("ui.providers.provider_detail.signed_in_to_variant_164",{brand:e}))})]}),h&&d?c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[yKe(d.detail??(d.tone==="attention"?x("ui.providers.provider_detail.is_no_longer_accepting_the_sign_in",{brand:e}):x("ui.providers.provider_detail.this_app_could_not_confirm_the_sign",{brand:e})))," ",x("ui.providers.provider_detail.the_sign_in_itself_finished_what_follows")]}):null,n?.receipt||n?.model_name?c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[n.receipt,!n.receipt&&n.model_name?c.jsxs(c.Fragment,{children:[x("ui.providers.provider_detail.default_model")," ",c.jsx("span",{className:"text-ink",children:n.model_name}),"."]}):null,r?c.jsxs(c.Fragment,{children:[" ",c.jsx(ce,{variant:"link",size:"sm",onClick:r,children:x("ui.providers.provider_detail.change")})]}):null]}):null,n&&!n.hosting&&n.receipt?c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.providers.provider_detail.your_default_model_is_unchanged")}):null,s?c.jsxs("p",{className:u==="unchecked"?"text-body-sm text-ink-muted":"text-ink-dim text-meta",children:[x("ui.providers.provider_detail.saved_but_not_checked_yet"),s]}):null,c.jsx("div",{children:c.jsx(ce,{ref:f,variant:o?"primary":"secondary",size:"sm",onClick:a,children:i})})]})},_Ke=({provider:e,onConnected:t,onDone:n,onChangeModel:s,context:r="settings",readiness:i})=>{Et();const a=nn(),o=DB({retryOnMount:!1}),{accountRead:l,unavailable:u}=Vk({retryOnMount:!1}),d=PB(e.id,o,{accountRead:l,unavailable:u}),h=i!==void 0?i:d===null?null:hT(e,d),[f,p]=g.useState(null),[m,v]=g.useState(""),[b,w]=g.useState(!1),[C,y]=g.useState(()=>Mg(e.id).error),[k,_]=g.useState(()=>Mg(e.id).saved),E=g.useCallback(ee=>{"saved"in ee&&_(ee.saved??null),"error"in ee&&y(ee.error??null),mKe(e.id,ee)},[e.id]),[R,F]=g.useState(""),[A,N]=g.useState(null),M=Ri(e),D=e.auth_methods.find(ee=>ee.method_id===f)??bQ(e.auth_methods),L=g.useCallback(()=>{a.invalidateQueries({queryKey:Bo.providers}),a.invalidateQueries({queryKey:Bo.catalogue}),e.id==="radient"&&xQ(a),a.invalidateQueries({queryKey:["config"]}),a.invalidateQueries({queryKey:wQ}),t?.()},[a,t,e.id]),V=Jj(),j=g.useCallback(async(ee,de,De)=>{const Ue=async()=>{await a.invalidateQueries({queryKey:["config"]}),await a.invalidateQueries({queryKey:["desktop","session-preview"]})};try{if(de!==void 0){await Ue();return}const Se=await xt({op:"config.get"});if(await Ue(),Se?.values?.hosting)return;let ge=Fk(ee);if(ge.length===0&&(await td.getState().fetchModels(Ss.baseUrl,!0),ge=Fk(ee)),ge.length===0)return;const Ae=(De||"").trim()||ge.find(st=>st.recommended)?.id||ge[0].id;await V.mutateAsync({hosting:ee,model_name:Ae}),await Ue()}catch{}},[a,V]),te=g.useRef(j);te.current=j;const X=g.useRef(L);X.current=L;const{flow:re,state:G}=xKe(e.id,()=>({start:ee=>xt({op:"auth.start",provider:ee}),read:ee=>xt({op:"auth.status",id:ee}),cancel:ee=>xt({op:"auth.cancel",id:ee}),open:(ee,de)=>RQ(ee,de),poll:TQ,onSucceeded:ee=>{X.current(),te.current(e.id,ee.defaults_applied,e.suggested_model?.id)}})),J=g.useRef(null);g.useEffect(()=>{const ee=J.current!==null,de=J.current!==e.id;J.current=e.id,ee&&de&&(p(null),v(""),y(Mg(e.id).error),_(Mg(e.id).saved))},[e.id]);const ae=ee=>{p(ee),E({error:null}),_(null),re.reset()},O=g.useCallback(async()=>{const ee=G.operation;if(!(!ee?.prompt_id||!R)){N(null);try{await xt({op:"auth.input",id:ee.id,promptId:ee.prompt_id,value:R}),F("")}catch(de){N(de instanceof Error?de.message:x("ui.providers.provider_detail.the_code_was_not_accepted"))}}},[G.operation,R]),U=g.useCallback(async()=>{if(!(!D||!m.trim())){w(!0),E({error:null});try{const ee=await xt({op:"auth.key",provider:D.id,value:m.trim()})??{};v(""),E({saved:ee}),L(),te.current(e.id,ee?.defaults_applied,e.suggested_model?.id)}catch(ee){E({error:ee instanceof Hi||ee instanceof Error?ee.message:x("ui.providers.provider_detail.the_key_could_not_be_saved")})}finally{w(!1)}}},[D,m,L,E,e.id,e.suggested_model?.id]),P=r==="dialog"?x("ui.providers.provider_detail.continue"):x("ui.providers.provider_detail.done"),z=()=>{vKe(e.id),_(null),re.reset(),n?.()};if(e.local)return c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[x("ui.providers.provider_detail.runs_on_this_computer_and_needs_no"),M,x("ui.providers.provider_detail.then_check_the_connection")]}),c.jsx(wKe,{provider:e})]});if(!D)return c.jsx(Kr,{variant:"warning",children:x("ui.providers.provider_detail.this_provider_has_no_supported_sign_in")});const ne=e.auth_methods.find(ee=>ee.kind==="api_key"),fe=G.operation,ue=`key-help-${e.id}`,le=e.auth_methods.length>1&&G.phase!=="settled"?c.jsx(GB,{value:D.method_id,onValueChange:ae,children:c.jsx(VB,{"aria-label":x("ui.providers.provider_detail.how_to_connect"),children:e.auth_methods.map(ee=>c.jsx(aS,{value:ee.method_id,children:CQ(ee)},ee.method_id))})}):null;if(D.kind==="api_key")return k?c.jsxs("div",{className:"flex flex-col gap-4",children:[le,c.jsx(A3,{brand:M,verb:"Connected",defaults:k.defaults_applied,unverified:k.valid===!0?null:k.reason??x("ui.providers.provider_detail.this_local_operator_does_not_check_keys"),tone:k.valid===!0?"success":"unchecked",headline:k.valid===!0?void 0:x("ui.providers.provider_detail.key_saved",{brand:M}),onChangeModel:s,actionLabel:P,onAction:z,primaryAction:r==="dialog",verdict:h})]}):c.jsxs("div",{className:"flex flex-col gap-4",children:[le,c.jsxs("div",{className:"flex flex-col gap-2","data-sign-in-state":"api-key",children:[c.jsx(nr,{htmlFor:`key-${e.id}`,children:x("ui.providers.provider_catalog.api_key")}),c.jsx(R3,{id:`key-${e.id}`,value:m,onChange:ee=>{v(ee),E({error:null})},label:x("ui.providers.provider_detail.api_key_variant_215",{brand:M}),invalid:C!==null,describedBy:ue}),c.jsx("p",{id:ue,className:C?"text-danger text-meta":"text-ink-dim text-meta",role:C?"alert":void 0,children:C??(e.has_credential?x("ui.providers.provider_detail.a_key_is_saved_paste_a_new",{brand:M}):x("ui.providers.provider_detail.stored_encrypted_on_this_computer_billed_per",{brand:M}))}),c.jsx("div",{children:c.jsxs(ce,{variant:"primary",size:"sm",disabled:!m.trim()||b,onClick:()=>void U(),children:[b?c.jsx(pn,{size:"sm"}):null,b?x("ui.providers.provider_detail.checking_key"):x("ui.providers.provider_detail.save_key")]})})]})]});const q=()=>void re.start(D.id),we=yQ(fe?.auth_url),B=fe?FB(fe):null,be=fe?_Q(fe.expires_in):null,ie=fe?.input_optional??(D.paste_fallback&&!D.requires_secret_input);let Te;if(G.phase==="idle")Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"idle",children:[e.configured&&h?.group==="Needs sign-in"?c.jsxs(Kr,{variant:h.tone==="attention"?"warning":"neutral",children:[c.jsx(FF,{children:h.label}),c.jsx(DF,{children:h.detail??x("ui.providers.provider_detail.is_no_longer_accepting_the_sign_in",{brand:M})})]}):null,c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[SQ(D,e)," ",D.kind==="device"?x("ui.providers.provider_detail.you_ll_get_a_code_to_enter"):x("ui.providers.provider_detail.it_opens_in_your_browser")]}),c.jsx("div",{className:"flex items-center gap-2",children:c.jsxs(ce,{variant:"primary",size:"sm",onClick:q,children:[D.kind==="device"?x("ui.providers.provider_detail.get_a_sign_in_code"):x("ui.providers.provider_detail.continue_in_browser"),D.kind==="device"?null:c.jsx(xl,{"aria-hidden":"true"})]})})]});else if(G.phase==="starting"||G.phase==="active"&&fe&&!fe.auth_url&&!B&&!(fe.input_required&&!ie))Te=c.jsxs("div",{className:"flex items-center gap-3","data-sign-in-state":"starting",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{className:"text-body-sm text-ink-muted",children:D.kind==="device"?x("ui.providers.provider_detail.getting_a_code"):x("ui.providers.provider_detail.opening_your_browser")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]});else if(G.phase==="active"&&fe&&B){const ee=fe.auth_url;Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"device-code",children:[c.jsx("p",{className:"whitespace-pre-line text-body-sm text-ink-muted",children:fe.instructions?.trim()||c.jsxs(c.Fragment,{children:[x("ui.providers.provider_detail.enter_this_code"),we?x("ui.providers.provider_detail.at_variant_248",{host:we}):x("ui.providers.provider_detail.on_the_sign_in_page"),x("ui.providers.provider_detail.this_page_updates_on_its_own_once")]})}),c.jsx("div",{className:"flex items-center gap-3 rounded-md bg-sunken p-3",children:c.jsx("code",{className:"font-mono text-ink text-title tracking-wider",children:B})}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx(Zb,{value:B,label:ee?x("ui.providers.provider_detail.copy_code_and_open_page"):x("ui.providers.provider_detail.copy_code"),variant:"primary",onCopied:()=>{ee&&re.reopen()}}),ee?c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void re.reopen(),children:[c.jsx(xl,{"aria-hidden":"true"}),G.opened?x("ui.providers.provider_detail.open_browser_again"):x("ui.providers.provider_detail.open_sign_in_page")]}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]}),be?c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.providers.provider_detail.code_expiry",{minutes:be})}):null]})}else if(G.phase==="active"&&fe){const ee=de=>fe.input_required?c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx(nr,{htmlFor:`prompt-${fe.id}`,children:we?x("ui.providers.provider_detail.code_from",{host:we}):x("ui.providers.provider_detail.code_from_the_sign_in_page")}),c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex-1",children:c.jsx(R3,{id:`prompt-${fe.id}`,value:R,onChange:De=>{F(De),N(null)},label:x("ui.providers.provider_detail.sign_in_code"),invalid:A!==null})}),c.jsx(ce,{variant:de?"primary":"secondary",size:"md",disabled:!R,onClick:()=>void O(),children:x("ui.providers.provider_detail.continue")})]}),A?c.jsx("p",{className:"text-danger text-meta",role:"alert",children:A}):null]}):null;fe.input_required&&!ie?Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"paste-required",children:[c.jsxs("p",{className:"text-body text-ink",children:[x("ui.providers.provider_detail.paste_the_code"),we??x("ui.providers.provider_detail.the_provider")," ",x("ui.providers.provider_detail.shows_after_you_approve")]}),c.jsx("div",{className:"w-full",children:ee(!0)}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void re.reopen(),children:[c.jsx(xl,{"aria-hidden":"true"}),G.opened?x("ui.providers.provider_detail.open_browser_again"):x("ui.providers.provider_detail.open_sign_in_page")]}),fe.auth_url?c.jsx(Zb,{value:fe.auth_url,label:x("ui.providers.provider_detail.copy_link")}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]})]}):Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"waiting",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{className:"text-body text-ink",children:x("ui.providers.provider_detail.finish_signing_in_with_your_browser")})]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:G.opened?x("ui.providers.provider_detail.we_opened_approve_access_there_and_this",{host:we??x("ui.providers.provider_detail.the_sign_in_page")}):G.openFailed?x("ui.providers.provider_detail.your_browser_didn_t_open_open_the"):x("ui.providers.provider_detail.opening_approve_access_there_and_this_page",{host:we??x("ui.providers.provider_detail.the_sign_in_page")})}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void re.reopen(),children:[c.jsx(xl,{"aria-hidden":"true"}),G.opened?x("ui.providers.provider_detail.open_browser_again"):x("ui.providers.provider_detail.open_sign_in_page")]}),fe.auth_url?c.jsx(Zb,{value:fe.auth_url,label:x("ui.providers.provider_detail.copy_link")}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]}),be?c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.providers.provider_detail.link_expiry",{minutes:be})}):null,fe.input_required?c.jsx(np,{summary:x("ui.providers.provider_detail.browser_showed_a_code_paste_it_here"),className:"w-full",children:c.jsx("div",{className:"pt-2",children:ee(!1)})}):null]})}else if(G.phase==="settled"&&fe?.state==="succeeded")Te=c.jsx(A3,{brand:M,verb:"Signed in to",defaults:fe.defaults_applied,onChangeModel:s,actionLabel:e.id==="radient"&&h?.group==="Needs sign-in"?"Sign in again":P,onAction:e.id==="radient"&&h?.group==="Needs sign-in"?q:z,primaryAction:r==="dialog",verdict:h});else{const ee=fe?EQ(fe,M):G.error??x("ui.providers.provider_detail.didn_t_confirm_the_sign_in",{brand:M});Te=c.jsxs("div",{className:"flex flex-col gap-3","data-sign-in-state":"unfinished",children:[c.jsxs(Kr,{variant:fe?.state==="cancelled"?"neutral":"warning",children:[c.jsx(FF,{children:x("ui.providers.provider_detail.sign_in_didn_t_finish")}),c.jsx(DF,{children:ee})]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:q,children:[c.jsx(kQ,{"aria-hidden":"true"}),x("ui.providers.provider_detail.try_again")]}),ne?c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>ae(ne.method_id),children:x("ui.providers.provider_detail.use_an_api_key_instead")}):null]})]})}return c.jsxs("div",{className:"flex flex-col gap-4",children:[le,Te,e.id==="radient"&&e.has_credential?c.jsx(hKe,{offerSignIn:!1}):null]})},SKe=()=>x("ui.providers.provider_catalog.one_browser_sign_in_nothing_to_paste");function EKe(e){const t=e.find(n=>n.id===MQ);return t===void 0?null:hT(t).group==="Needs sign-in"?t:null}function kKe(e,t){return t!==null&&e===t}function TKe(e,t,n){const s=t.trim().toLowerCase();return s?e.filter(r=>[r.name,r.id,...r.search_aliases].join(" ").toLowerCase().includes(s)):e}const F3=({provider:e})=>c.jsx("span",{"aria-hidden":"true",className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-elevated font-medium text-body-sm text-ink",children:jQ(Ri(e))}),wb=({children:e,label:t})=>(Et(),c.jsx("ul",{"aria-label":t,className:"flex flex-col divide-y divide-hairline overflow-hidden rounded-[14px] bg-surface",children:e})),GW=({onConnected:e,initialProviderId:t=null,context:n="settings",featuredOnly:s=!1,focusGroup:r=null,onDone:i,onChangeModel:a})=>{Et();const o=R0(!0),{hosting:l,model:u}=IB(),d=nn(),h=DB(),{accountRead:f,unavailable:p}=Vk(),[m,v]=g.useState(t),b=g.useCallback(()=>{a?.(),requestAnimationFrame(()=>{document.getElementById("model-settings")?.focus?.({preventScroll:!0})})},[a]);g.useEffect(()=>{t&&v(t)},[t]);const[w,C]=g.useState(""),[y,k]=g.useState(null),_=g.useRef(null),E=g.useRef(null),R=g.useRef(new Map),F=g.useMemo(()=>o.data??[],[o.data]),A=g.useMemo(()=>AQ(F,l),[F,l]),N=g.useMemo(()=>FQ(F,l,w),[F,l,w]),M=EKe(F)?.id??null,[D,L]=g.useState(null);g.useEffect(()=>{if(D===null)return;const q=B=>B?.isConnected?B:null,we=q(R.current.get(D))??q(_.current)??q(E.current);L(null),we?.focus()},[D]),g.useEffect(()=>{m!==null&&R.current.get(m)?.closest("li")?.scrollIntoView({block:"nearest"})},[m,A.length]);const V=q=>{m===q?(v(null),L(q)):v(q)},j=()=>{const q=m;v(null),q&&L(q),i?.()};g.useEffect(()=>{if(m===null)return;const q=we=>{we.key!=="Escape"||we.defaultPrevented||we.target?.closest('[role="menu"], [role="dialog"], [role="listbox"]')||j()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)});const te=()=>{d.invalidateQueries({queryKey:Bo.providers}),d.invalidateQueries({queryKey:UQ})},X=async q=>{const we=q.suggested_model;try{await HQ.updateConfig("",{hosting:q.id,model_name:we?.id??""}),te()}catch(B){zt(B instanceof Error?B.message:x("ui.providers.provider_grid.the_default_was_not_changed"))}},re=async q=>{k(null);try{await xt({op:"auth.logout",provider:q.id}),await d.invalidateQueries({queryKey:Bo.providers}),e?.()}catch(we){zt(we instanceof Error?we.message:x("ui.providers.provider_grid.sign_out_did_not_complete"))}finally{L(q.id)}};if(o.isLoading)return c.jsx("div",{className:"flex h-40 items-center justify-center",children:c.jsx(pn,{size:"lg",label:x("ui.providers.provider_grid.loading_providers")})});if(o.isError)return c.jsx(Kr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:DQ(o.error)}),c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0",onClick:()=>void o.refetch(),disabled:o.isFetching,children:o.isFetching?x("ui.providers.provider_grid.retrying"):x("ui.providers.provider_grid.retry")})]})});const G=(q,we)=>m===q.id?c.jsx("div",{className:"border-hairline border-t bg-surface px-4 py-4",children:c.jsx(_Ke,{provider:q,onConnected:e,onDone:j,onChangeModel:a,context:n,readiness:we})}):null,J=q=>{const we=kKe(q.id,M),B=q.suggested_model?.name,be=m===q.id;return c.jsxs("li",{"data-provider-id":q.id,children:[c.jsxs("div",{className:"flex min-h-14 items-center gap-3 px-4 py-2",children:[c.jsx(F3,{provider:q}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("span",{className:"flex flex-wrap items-baseline gap-x-2 text-body text-ink",children:[Ri(q),we?c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-ink-dim text-meta",children:"·"}),c.jsx("span",{className:"shrink-0 font-medium text-ink text-meta",children:x("ui.providers.provider_grid.recommended")})]}):null]}),c.jsxs("span",{className:"text-ink-muted text-meta",children:[we?SKe():BQ(q),B?c.jsxs("span",{className:"text-ink-dim",children:[" ",x("ui.providers.provider_grid.suggests"),B]}):null]})]}),c.jsx(ce,{ref:ie=>{R.current.set(q.id,ie)},variant:we&&!be&&m===null&&A.length===0?"primary":"secondary",size:"sm","aria-expanded":be,"aria-label":x("ui.providers.provider_grid.row_action",{action:be?x("ui.providers.provider_grid.close"):CF(q),brand:Ri(q)}),onClick:()=>V(q.id),children:be?x("ui.providers.provider_grid.close"):CF(q)})]}),G(q)]},q.id)},ae=q=>{const we=q.id===l,B=we?NB(q,u):q.suggested_model?.name??null,be=m===q.id,ie=PB(q.id,h,{accountRead:f,unavailable:p}),Te=ie===null?null:hT(q,ie),ee=OQ(q,B,Te?.label??null);return c.jsxs("li",{"data-provider-id":q.id,children:[c.jsxs("div",{className:"flex min-h-14 items-center gap-3 px-4 py-2",children:[c.jsx(F3,{provider:q}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsx("span",{className:"text-body text-ink",children:Ri(q)}),c.jsx("span",{className:`truncate text-meta ${Te?.tone==="attention"?"text-warning":"text-ink-muted"}`,title:Te?.detail,"data-claim":ie===null?"withheld":void 0,"data-claim-tone":Te?.tone,children:ee??" "})]}),we?c.jsx("span",{className:"text-ink-muted text-meta",children:x("ui.providers.provider_grid.default")}):null,y===q.id?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("span",{className:"text-body-sm text-ink",children:[x("ui.providers.provider_grid.sign_out_of"),Ri(q),"?"]}),c.jsx(ce,{variant:"danger",size:"sm",onClick:()=>void re(q),children:x("ui.providers.provider_grid.sign_out")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>{k(null),L(q.id)},children:x("ui.providers.provider_grid.keep")})]}):c.jsxs(Il,{children:[c.jsx(Ho,{asChild:!0,children:c.jsx(ce,{ref:de=>{R.current.set(q.id,de)},variant:"ghost",size:"icon-sm",className:be?"bg-control text-on-accent":void 0,"aria-expanded":be,"aria-label":x("ui.providers.provider_grid.manage",{brand:Ri(q)}),children:c.jsx(nC,{"aria-hidden":"true"})})}),c.jsxs(Nl,{align:"end",onCloseAutoFocus:de=>de.preventDefault(),children:[we?null:c.jsx(Gt,{onSelect:()=>void X(q),children:x("ui.providers.provider_grid.make_default")}),we&&a?c.jsx(Gt,{onClick:()=>b(),onSelect:()=>b(),children:x("ui.providers.provider_grid.change_model")}):null,c.jsx(Gt,{onSelect:()=>V(q.id),"data-panel-toggle":q.id,children:be?x("ui.providers.provider_grid.close"):q.local?x("ui.providers.provider_grid.check_connection"):LQ(q)==="key"?x("ui.providers.provider_grid.replace_key"):x("ui.providers.provider_grid.sign_in_again")}),!q.local&&q.stored_credentials>0?c.jsxs(c.Fragment,{children:[c.jsx(Yr,{}),c.jsx(Gt,{destructive:!0,onSelect:()=>k(q.id),children:x("ui.providers.provider_grid.sign_out_variant_351")})]}):null]})]})]}),be?G(q,Te):null]},q.id)},O=s?PQ:IQ,U=O.every(q=>N[q].length===0),P=c.jsxs("div",{className:"relative w-full sm:w-64",children:[c.jsx(xd,{size:16,className:"pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-ink-dim","aria-hidden":"true"}),c.jsx(ps,{ref:_,value:w,onChange:q=>C(q.target.value),placeholder:x("ui.providers.provider_grid.search_providers"),"aria-label":x("ui.providers.provider_grid.search_providers"),className:"pl-9"})]}),z=x("ui.providers.provider_grid.no_providers_match_this_search"),ne=x("ui.providers.provider_grid.the_matching_providers_are_in_the_suggested"),fe=x("ui.providers.provider_grid.the_matching_providers_are_in_the_connected"),ue=(q,we)=>we?c.jsxs("div",{className:"flex flex-col items-center gap-2 py-6 text-center",children:[c.jsx("p",{className:"text-body-sm text-ink-muted",children:we}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>{C(""),_.current?.focus()},children:[c.jsx(Dn,{"aria-hidden":"true"}),x("ui.providers.provider_grid.clear_search")]})]}):O.map(B=>q[B].length>0?c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("h4",{className:"text-ink-dim text-meta",children:wF[B]}),c.jsx(wb,{label:wF[B],children:q[B].map(J)})]},B):null),le=ue(N,U?z:null);if(s){const q=new Set(TKe(F,w).map(de=>de.id)),we=nS.map(de=>F.find(De=>De.id===de)).filter(de=>de!==void 0&&!A.some(De=>De.id===de.id)&&q.has(de.id)),B=new Set(nS.filter(de=>F.some(De=>De.id===de))),be={subscription:N.subscription.filter(de=>!B.has(de.id)),key:N.key.filter(de=>!B.has(de.id)),local:N.local.filter(de=>!B.has(de.id))},ie=O.reduce((de,De)=>de+be[De].length,0),Te=w.trim().length>0,ee=Te?q.size===0?z:ie===0?we.length>0?ne:fe:null:null;return c.jsxs("div",{ref:E,tabIndex:-1,className:"flex flex-col gap-4","data-provider-grid":"",children:[A.length>0?c.jsx(wb,{label:x("ui.providers.provider_grid.connected"),children:A.map(ae)}):null,we.length>0?c.jsx(wb,{label:x("ui.providers.provider_grid.suggested_providers"),children:we.map(J)}):null,Te||ie>0?c.jsx(np,{summary:NQ(be,O),defaultOpen:r!==null||t!==null,chevron:"trailing",children:c.jsxs("div",{className:"flex flex-col gap-4 pt-3",children:[P,ue(be,ee)]})}):null]})}return c.jsxs("div",{ref:E,tabIndex:-1,className:"flex flex-col gap-6","data-provider-grid":"",children:[A.length>0?c.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"providers-connected",children:[c.jsx("h3",{id:"providers-connected",className:"text-heading text-ink",children:x("ui.providers.provider_grid.connected")}),c.jsx(wb,{children:A.map(ae)})]}):null,c.jsxs("section",{className:"flex flex-col gap-3","aria-labelledby":"providers-add",children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[c.jsx("h3",{id:"providers-add",className:"text-heading text-ink",children:A.length>0?x("ui.providers.provider_grid.add_a_provider"):x("ui.providers.provider_grid.connect_a_provider")}),P]}),le]})]})},RKe=({onContinue:e})=>c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:x("ui.onboarding.connect.intro")}),c.jsx(GW,{context:"dialog",featuredOnly:!0,onDone:e,onChangeModel:e})]});function D3(e){for(const t of nS){const n=e.find(s=>s.id===t);if(n)return n}return e[0]??null}function AKe(e,t){if(t.hosting)return{kind:"applied",hosting:t.hosting,model:t.model,provider:e.find(a=>a.id===t.hosting)??null};const n=e.filter(a=>!a.local&&GQ(a,null)),s=n.filter(a=>a.suggested_model),r=D3(s);if(r?.suggested_model)return{kind:"proposed",provider:r,model:r.suggested_model};const i=D3(n);return i?{kind:"choose",provider:i}:{kind:"none"}}const FKe="ui.onboarding.default_model.block.pick_a_model",DKe="ui.onboarding.default_model.block.loading_models";function PKe(e){const{choice:t,hosting:n,model:s,catalogue:r}=e,i=n??(t&&(t.kind==="choose"||t.kind==="proposed")?t.provider.id:""),a=s??"",o=t?.kind==="proposed"?t.model.id:"",l=a||o,u=r.ready&&r.providers.includes(i),d=!l&&(t?.kind==="choose"||t?.kind==="applied"&&!t.model);return{shownProvider:i,write:i&&!d&&l?{hosting:i,model_name:l}:null,block:d?u?x(FKe):r.ready?null:x(DKe):null,noCatalogue:d&&r.ready&&!u,modelToWrite:l}}const IKe=({choice:e,onChange:t})=>{if(e.kind==="none")return c.jsx(Kr,{variant:"neutral",children:x("ui.onboarding.default_model.none_connected")});if(e.kind==="choose")return c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.onboarding.default_model.connected_pick",{brand:Ri(e.provider)})});const n=e.kind==="applied"?NB(e.provider,e.model)??x("ui.onboarding.default_model.fallback_name",{brand:e.provider?Ri(e.provider):e.hosting}):e.model.name,s=e.kind==="applied"?e.provider?Ri(e.provider):e.hosting:Ri(e.provider);return c.jsxs("div",{className:"flex flex-col gap-1","data-default-model":e.kind,children:[c.jsx("p",{className:"text-heading text-ink",children:n}),c.jsxs("p",{className:"text-ink-dim text-meta",children:[s," ·"," ",e.kind==="applied"?x("ui.onboarding.default_model.tag.applied"):x("ui.onboarding.default_model.tag.suggested")]}),c.jsx("div",{className:"pt-2",children:c.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:x("ui.onboarding.default_model.change")})})]})},NKe=({onBeforeContinue:e,onBlockReason:t})=>{const n=R0(!0),s=IB(),r=Jj(),[i,a]=g.useState(!1),o=n.isLoading||s.isLoading?null:AKe(n.data??[],s),{refreshModels:l}=cT();g.useEffect(()=>{l()},[]);const u=td(_=>_.isInitialized),d=td(_=>_.models),h=g.useMemo(()=>{const _=new Set;for(const E of d)_.add(E.provider);return[..._]},[d]),f=g.useMemo(()=>PKe({choice:o,hosting:s.hosting,model:s.model,catalogue:{ready:u,providers:h}}),[o,s.hosting,s.model,u,h]),{shownProvider:p,write:m,block:v,noCatalogue:b,modelToWrite:w}=f,C=g.useCallback(_=>{const E=td.getState().models.filter(R=>R.provider===_);return E.find(R=>R.info?.recommended)?.id??E[0]?.id},[]),y=(n.data??[]).find(_=>_.id===p)??null;if(g.useEffect(()=>(e?.(m?async()=>{await r.mutateAsync(m)}:null),()=>e?.(null)),[e,m,r.mutateAsync]),g.useEffect(()=>{if(t)return t(v),()=>t(null)},[t,v]),o===null)return c.jsxs("div",{className:"flex items-center justify-center gap-3 py-8",children:[c.jsx(pn,{size:"sm"}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.onboarding.default_model.loading")})]});const k=c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsx(OW,{value:p,onSave:async _=>{const E=C(_);E&&await r.mutateAsync({hosting:_,model_name:E})},filterByCredentials:!0,allowCustom:!1,allowDefault:!1,emptyHelperText:x("ui.onboarding.default_model.empty_helper")}),c.jsx(LW,{value:w,hostingId:p,onSave:async _=>{await r.mutateAsync({model_name:_})},allowCustom:!0,allowDefault:!1})]});return c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:x("ui.onboarding.default_model.intro")}),b?c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.onboarding.default_model.nothing_saved",{brand:y?Ri(y):x("ui.onboarding.default_model.provider_fallback")})}):null,i||o.kind==="choose"?k:c.jsx(IKe,{choice:o,onChange:()=>a(!0)})]})};var VW=(e=>(e.Hosting="hosting",e.Search="search",e.Oauth="oauth",e))(VW||{});const MKe=[{key:"RADIENT_API_KEY",name:"Radient Pass",get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_your_radient_pass_radient_pass_provides_you_unified_a")},url:"https://radienthq.com",type:"hosting"},{key:"OPENAI_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_openai_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_accessing_openai_models_like_gpt_4o_o3_mini_and_gpt_4")},url:"https://platform.openai.com/api-keys",type:"hosting"},{key:"OPENROUTER_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_openrouter_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_openrouter_which_provides_access_to_various_ai_models")},url:"https://openrouter.ai/keys",type:"hosting"},{key:"DEEPSEEK_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_deepseek_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_deepseek_ai_models_specialized_in_code_generation_and")},url:"https://platform.deepseek.com/",type:"hosting"},{key:"MISTRAL_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_mistral_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_mistral_ai_models_known_for_efficient_and_powerful_la")},url:"https://console.mistral.ai/api-keys/",type:"hosting"},{key:"KIMI_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_kimi_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_kimi_ai_providing_advanced_language_models_with_stron")},url:"https://kimi.moonshot.cn/",type:"hosting"},{key:"ALIBABA_CLOUD_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_alibaba_cloud_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_alibaba_cloud_ai_models_offering_a_range_of_language_")},url:"https://www.alibabacloud.com/product/ai",type:"hosting"},{key:"GOOGLE_AI_STUDIO_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_google_ai_studio_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_google_ai_studio_providing_access_to_gemini_and_other")},url:"https://aistudio.google.com/",type:"hosting"},{key:"GOOGLE_ACCESS_TOKEN",get name(){return x("ui.settings.integrations.credential_manifest.name_google_access_token")},get description(){return x("ui.settings.integrations.credential_manifest.oauth_2_0_access_token_for_google_apis_used_by_local_operator_for")},url:"https://console.cloud.google.com/apis/credentials",internal:!0,type:"oauth"},{key:"GOOGLE_TOKEN_EXPIRY_TIMESTAMP",get name(){return x("ui.settings.integrations.credential_manifest.name_google_token_expiry_timestamp")},get description(){return x("ui.settings.integrations.credential_manifest.timestamp_in_milliseconds_since_epoch_indicating_when_the_current")},url:"",internal:!0,type:"oauth"},{key:"GOOGLE_REFRESH_TOKEN",get name(){return x("ui.settings.integrations.credential_manifest.name_google_refresh_token")},get description(){return x("ui.settings.integrations.credential_manifest.oauth_2_0_refresh_token_for_google_apis_used_to_obtain_new_access")},url:"https://console.cloud.google.com/apis/credentials",internal:!0,type:"oauth"},{key:"ANTHROPIC_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_anthropic_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_anthropic_s_claude_models_known_for_agentic_code_gene")},url:"https://console.anthropic.com/settings/keys",type:"hosting"},{key:"SERP_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_serp_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_search_engine_results_page_api_allowing_access_to_sea")},url:"https://serpapi.com/dashboard",type:"search"},{key:"TAVILY_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_tavily_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_tavily_a_search_api_designed_specifically_for_ai_appl")},url:"https://tavily.com/#api",type:"search"},{key:"BRAVE_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_brave_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_brave_search_an_independent_web_index_with_its_own_cr")},url:"https://api-dashboard.search.brave.com/app/keys",type:"search"},{key:"EXA_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_exa_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_exa_a_search_api_built_for_ai_applications_agents_can")},url:"https://dashboard.exa.ai/api-keys",type:"search"},{key:"PARALLEL_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_parallel_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_parallel_a_web_search_api_for_ai_agents_agents_can_al")},url:"https://platform.parallel.ai/",type:"search"},{key:"PERPLEXITY_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_perplexity_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_perplexity_s_sonar_search_perplexity_is_best_effort_a")},url:"https://console.perplexity.ai/",type:"search"},{key:"FAL_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_fal_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_fal_used_by_agents_for_generating_interpreting_and_un")},url:"https://docs.fal.ai/quick-start",type:"hosting"},{key:"XAI_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_xai_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_xai_providing_access_to_grok_and_other_advanced_xai_m")},url:"https://docs.x.ai/docs/overview",type:"hosting"}],OKe=MKe.filter(e=>e.type===VW.Search),LKe="onboarding-search-mode",BKe="onboarding-search-mode-free",jKe="onboarding-search-mode-keys",P3="onboarding-search-mode-label",HKe=e=>`onboarding-search-key-${e.toLowerCase()}`,I3=({id:e,title:t,recommended:n=!1,checked:s,onSelect:r,children:i})=>c.jsxs("label",{htmlFor:e,className:T("flex cursor-pointer items-start gap-3 rounded-sm p-3","transition-colors duration-fast ease-out-quart","hover:bg-sunken","has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2","has-[:focus-visible]:outline-accent has-[:focus-visible]:outline-offset-2",s&&"bg-sunken"),children:[c.jsx("input",{type:"radio",id:e,name:LKe,className:"sr-only outline-none",checked:s,onChange:r}),c.jsx("span",{"aria-hidden":"true",className:T("mt-1 grid size-4 shrink-0 place-items-center rounded-full","border border-control bg-surface",s&&"border-accent bg-accent"),children:c.jsx("span",{className:T("size-2 rounded-full",s&&"bg-on-accent")})}),c.jsxs("span",{className:"flex min-w-0 flex-col gap-1",children:[c.jsxs("span",{className:T("flex flex-wrap items-baseline gap-x-2 text-body text-ink",s&&"font-medium"),children:[t,n?c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-ink-dim text-meta",children:"·"}),c.jsx("span",{className:"shrink-0 font-medium text-ink text-meta",children:x("ui.onboarding.search.recommended")})]}):null]}),c.jsx("span",{className:"text-body-sm text-ink-muted",children:i})]})]}),UKe=({credential:e,showDescription:t,isStored:n,save:s})=>{const[r,i]=g.useState(""),[a,o]=g.useState(!1),[l,u]=g.useState(!1),[d,h]=g.useState(null),[f,p]=g.useState(null),m=HKe(e.key),v=n||l,b=async()=>{const w=r.trim();if(!(!w||a||w===d))try{o(!0),p(null),await s(e.key,w),h(w),u(!0)}catch(C){const y=C instanceof Error&&C.message?C.message:x("ui.onboarding.search.row.save_failed");p(x("ui.onboarding.search.row.not_saved",{message:y}))}finally{o(!1)}};return c.jsxs("div",{className:"flex flex-col gap-2","data-search-key":e.key,children:[c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx(nr,{htmlFor:m,children:e.name}),c.jsxs("span",{className:"flex items-center gap-2",children:[a?c.jsx(pn,{size:"sm",label:x("ui.onboarding.search.row.saving",{name:e.name})}):null,v?c.jsx(Ml,{variant:"success",children:x("ui.onboarding.search.row.saved")}):null]})]}),c.jsx(ps,{id:m,inputSize:"lg",type:"password",value:r,onChange:w=>{i(w.target.value),u(!1),p(null)},onBlur:b,onKeyDown:w=>{w.key==="Enter"&&r.trim()&&!a&&b()},placeholder:x("ui.onboarding.search.row.placeholder"),disabled:a}),f?c.jsx("p",{className:"text-danger text-meta",role:"alert",children:f}):t?c.jsx("p",{className:"text-ink-dim text-meta",children:e.description}):null,c.jsxs("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex w-fit items-center gap-1 text-accent text-meta underline-offset-4 hover:text-accent-hover hover:underline",children:[x("ui.onboarding.search.row.get_your",{name:e.name}),c.jsx(xl,{size:12,"aria-hidden":"true"})]})]})},GKe=({showCredentialDescription:e=!0})=>{const[t,n]=g.useState("free"),{data:s}=gB(),r=Jae(),i=s?.keys??[],a=async(o,l)=>{await r.mutateAsync({key:o,value:l})};return c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:x("ui.onboarding.search.intro")}),c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{id:P3,className:"sr-only",children:x("ui.onboarding.search.mode.label")}),c.jsxs("div",{role:"radiogroup","aria-labelledby":P3,className:"flex flex-col gap-2",children:[c.jsx(I3,{id:BKe,title:x("ui.onboarding.search.mode.free"),recommended:!0,checked:t==="free",onSelect:()=>n("free"),children:x("ui.onboarding.search.mode.free_detail")}),c.jsx(I3,{id:jKe,title:x("ui.onboarding.search.mode.keys"),checked:t==="keys",onSelect:()=>n("keys"),children:x("ui.onboarding.search.mode.keys_detail")})]})]}),t==="keys"?c.jsxs("div",{className:"flex flex-col gap-5 pl-10",children:[c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.onboarding.search.each_key_saved")}),OKe.map(o=>c.jsx(UKe,{credential:o,showDescription:e,isStored:i.includes(o.key),save:a},o.key))]}):null]})},VKe=({aidaName:e=null,oweGreeting:t=!0})=>c.jsxs("div",{className:"flex flex-col gap-8",children:[c.jsx(GKe,{showCredentialDescription:!1}),e?c.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"onboarding-extras-next",children:[c.jsx("h3",{id:"onboarding-extras-next",className:"text-heading text-ink",children:x("ui.onboarding.extras.next_meet",{name:e})}),c.jsx("p",{className:"text-body text-ink-muted",children:t?x("ui.onboarding.extras.greeting_owed",{name:e}):x("ui.onboarding.extras.greeting_done",{name:e})})]}):null]}),WKe={[kr.CONNECT_PROVIDER]:"ui.onboarding.modal.title.connect_provider",[kr.DEFAULT_MODEL]:"ui.onboarding.modal.title.default_model",[kr.EXTRAS]:"ui.onboarding.modal.title.extras"};function $Ke(e,t){return e===kr.EXTRAS&&t?x("ui.onboarding.modal.title.extras_with_name",{name:t}):x(WKe[e])}const Ma=[kr.CONNECT_PROVIDER,kr.DEFAULT_MODEL,kr.EXTRAS],zKe={},qKe=({open:e})=>{const{currentStep:t,setCurrentStep:n,completeModalOnboarding:s}=ym(),r=Jr(),i=R0(e),a=VQ(i.data??[]),o=Bn(),l=yt(o.data,"aida",1),u=B0(e&&l),d=l&&u.data?.enabled===!0,h=u.data?.name?.trim()||"Aida",f=WQ(u.data),p=$T(),m=g.useMemo(()=>{const O=d?h:null;return Object.fromEntries(Ma.map(U=>[U,$Ke(U,O)]))},[d,h]),[v,b]=g.useState(!1),w=g.useRef(null),[C,y]=g.useState(null),k=g.useCallback(O=>{y(O)},[]),[_,E]=g.useState(!1),R=_||v,F=g.useCallback(O=>{w.current=O},[]);g.useEffect(()=>{Ma.includes(t)||n(kr.CONNECT_PROVIDER)},[t,n]);const[A,N]=g.useState(new Set);g.useEffect(()=>{N(O=>{if(O.has(t))return O;const U=new Set(O);return U.add(t),U})},[t]);const M=m[t]??x("ui.onboarding.modal.title.fallback"),D=g.useCallback(()=>{s(),r("/chat")},[s,r]),L=g.useCallback(async()=>{b(!0);try{const O=await p("greet");if(s(),!O.session_id){r("/chat"),zt(x("ui.onboarding.modal.error.aida_open_failed",{name:h}));return}cp(r,O.session_id);const U=$Q(O,h);U&&Va(U)}catch(O){s(),r("/chat");const U=zQ(O,h);U?.kind==="info"?Va(U.text):U&&zt(U.text)}finally{b(!1)}},[p,h,s,r]),V=g.useCallback(async()=>{const O=Ma.indexOf(t);if(t===kr.DEFAULT_MODEL&&w.current){E(!0);try{await w.current()}catch{E(!1);return}E(!1)}O>=0&&O<Ma.length-1?n(Ma[O+1]):d?await L():D()},[t,n,D,d,L]),j=g.useCallback(()=>{const O=Ma.indexOf(t);O>0&&n(Ma[O-1])},[t,n]),te=g.useMemo(()=>{switch(t){case kr.CONNECT_PROVIDER:return c.jsx(RKe,{onContinue:()=>n(kr.DEFAULT_MODEL)});case kr.DEFAULT_MODEL:return c.jsx(NKe,{onBeforeContinue:F,onBlockReason:k});case kr.EXTRAS:return c.jsx(VKe,{aidaName:d?h:null,oweGreeting:f});default:return null}},[t,n,F,k,d,h,f]),X=t===kr.CONNECT_PROVIDER,re=t===kr.EXTRAS,G=nKe(t,C,R),J=c.jsxs("div",{className:"flex w-full flex-col gap-2",children:[G.reason?c.jsx("p",{className:"text-ink-dim text-meta",children:G.reason}):null,c.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[c.jsx("div",{children:X?c.jsx(ce,{variant:"ghost",size:"lg",onClick:D,children:x("ui.onboarding.modal.action.skip_for_now")}):c.jsx(ce,{variant:"secondary",size:"lg",onClick:j,children:x("ui.onboarding.modal.action.back")})}),c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[re?c.jsx(ce,{variant:"ghost",size:"lg",onClick:D,disabled:v,children:d?x("ui.onboarding.modal.action.skip_to_chat"):x("ui.onboarding.modal.action.skip")}):null,!X||a?c.jsx(ce,{variant:"primary",size:"lg",onClick:()=>void V(),disabled:G.primaryDisabled,children:re?d?x("ui.onboarding.modal.action.meet",{name:h}):x("ui.onboarding.modal.action.finish"):x("ui.onboarding.modal.action.continue")}):null]})]})]}),ae=g.useMemo(()=>{if(!t)return null;const O=Ma.indexOf(t);return c.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[c.jsx("span",{className:"whitespace-nowrap text-ink-dim text-meta",children:O>=0?x("ui.onboarding.modal.step_of",{current:O+1,total:Ma.length}):x("ui.onboarding.modal.steps_total",{total:Ma.length})}),c.jsx("ol",{className:"flex items-center gap-1",children:Ma.map((U,P)=>{const z=t===U,fe=A.has(U)&&!z,ue=P<=O;return c.jsx("li",{className:"flex",children:c.jsx(Je,{content:m[U],children:c.jsx("button",{type:"button","aria-label":m[U],"aria-current":z?"step":void 0,"aria-disabled":!fe,onClick:()=>{fe&&n(U)},className:"flex h-4 w-4 items-center",children:c.jsx("span",{className:T("h-1 w-full rounded-xs transition-colors duration-base ease-out-quart",ue?"bg-accent":"bg-control")})})})},U)})})]})},[t,A,n,m]);return c.jsx(tKe,{open:e,onDismiss:D,title:M,stepIndicators:ae,actions:J,width:zKe[t]??"single",children:te})};var N3={exports:{}},pg={};/**
|
|
674
|
+
`))}return"consumed"}catch(le){return D(`/${U.name} could not run: ${le instanceof Error?le.message:"the backend refused it"}`,!0),"retained"}},[p,b,w,C,y.data,k,_,E.data,e,D,h,n,s,M,m,v,o,L,u,d]),j=g.useCallback(async G=>{const J=await V(G);return J==="not-a-command"&&D("The backend could not complete this request. Check its connection and try again.",!0),J},[V,D]),te=g.useCallback(G=>{i&&(N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,F({action:{kind:"native_action",destination:G,session_id:"",args:"",fields:[],data:{}},spec:M1(G,E.data),sessionId:"",canonical:n,commands:E.data??[],onClose:M,note:D,dispatch:J=>void V(J),rebind:s,draft:i}))},[n,M,E.data,V,i,D,s]),X=Lc(G=>G.request),re=Lc(G=>G.consumePanel);return g.useEffect(()=>{if(!X||(re(X.nonce),Date.now()-X.requestedAt>xX))return;const G=by[X.destination];if(G?.kind!=="picker"&&G?.kind!=="machine-panel")return;N.current=X.sessionId?X.invoker:null;const J=X.sessionId??e??"";F({action:{kind:"native_action",destination:X.destination,session_id:J,args:"",fields:[],data:{...X.entryId?{entryId:X.entryId}:{},...X.entryId&&X.entryExcerpt?{entryExcerpt:X.entryExcerpt}:{},...X.subjectName?{subjectName:X.subjectName}:{}}},spec:M1(X.destination,E.data),sessionId:J,canonical:n,commands:E.data??[],onClose:M,note:D,dispatch:ae=>void V(ae),rebind:s})},[X,re,e,n,E.data,M,D,V,s]),{dispatch:V,dispatchFromControl:j,picker:R,closePicker:M,openDraftPicker:te,note:D}}const uqe=/^[a-f0-9]{12}$/,O1=e=>`${e.request_id}:${e.question_index}`,dqe=" ";function L1(e,t){const n=e.activeDraftKey?e.drafts[e.activeDraftKey]:void 0;return!!t&&ip(e.activeDraftKey,n?.sessionId,e.activeSessionId)===t}function hqe({identity:e,draftKey:t,sessionId:n}){const s=Ce(Fe=>ix(t,n,Fe.drafts)),r=Ce(Fe=>s?Fe.drafts[s]:void 0),i=n??r?.warmId,a=Bn(),o=yX(i,!!i,!!n,e,{openFrame:yt(a.data,"open_frame"),journalOrder:yt(a.data,"journal_order"),peerJournalSource:yt(a.data,"peer_journal_source")});Vue(i,o.subscriptionId);const l=$ue(n,a.data),u=yt(a.data,"settings");que(n,u),g.useEffect(()=>{Ce.getState().setDraftWarmable(yt(a.data,"session_draft_warm"))},[a.data]),zue(r?.warmId,o.subscriptionId,a.data);const d=g.useCallback(()=>{if(n){l();return}t&&Ce.getState().ensureDraftWarm(t)},[n,l,t]),h=g.useRef(null),f=g.useRef(null),p=Ce(Fe=>Fe.cwd),{data:m}=sp(),v=XT(m?.online===!1),b=m?.online===!0,w=g.useRef(b);g.useEffect(()=>{const Fe=b&&!w.current;w.current=b,Fe&&o.status==="unavailable"&&o.retry()},[b,o]);const C=Ce(Fe=>Fe.setCwd),y=Ce(Fe=>Fe.markTurnStopped),k=Ce(Fe=>Fe.clearTurnStopped),[_,E]=g.useState(!1),R=g.useRef(null);R.current??=_X();const F=R.current,A=g.useRef(!1),N=g.useRef(o);N.current=o;const M=g.useRef([]),D=g.useRef(!1),[L,V]=g.useState(null),[j,te]=g.useState({}),X=qe(Fe=>Fe.isAskDrawerOpen),re=qe(Fe=>Fe.askDrawerScope),G=X&&re==="session",J=qe(Fe=>Fe.setAskDrawerOpen),[ae,O]=g.useState({}),U=o.frontend?.pending_gate??null,P=U?O1(U):null,z=g.useRef(null),ne=g.useRef(null);g.useLayoutEffect(()=>{z.current=P,ne.current=o.ownerEpoch});const fe=U&&L?.key===P?{sending:L.sending,refused:L.refused,retryable:L.retryable,muted:L.muted}:null,ue=g.useRef(""),[le,q]=g.useState(null),[we,B]=g.useState(),[be,ie]=g.useState(!1),[Te,ee]=g.useState(!1),[de,De]=g.useState(null),[Ue,Se]=g.useState(null),ge=g.useRef(Ue);ge.current=Ue;const Ae=g.useRef(0),st=g.useRef(null),vt=yhe(a.data),[me,it]=g.useState(!1),[ct,Qe]=g.useState("chat"),{isFarFromBottom:Nt,scrollToBottom:Tt}=Qj(50,f,o.transcript.records.length),At=(o.frontend??o.heldFrontend)?.streaming===!0,sn=g.useRef(At);sn.current=At;const Ut=SX(e),rt=g.useRef(null),An=g.useRef(null);Ut&&(An.current?.requestId!==Ut.id&&(An.current={requestId:Ut.id,anchor:o.frontend?.attention?.anchor_id??null}),rt.current?.requestId!==Ut.id&&(rt.current={requestId:Ut.id,submittedAt:Ut.submittedAt??r?.submittedAt}));const On=EX(o.transcript.records,rt.current?.requestId),ks=kX(o.transcript.records,rt.current?.requestId)||TX(o.frontend?.attention,An.current?.anchor??null);rt.current&&(On||ks||r?.error||r?.undelivered!==void 0&&r.undelivered.recordId===rt.current.requestId)&&(rt.current=null);const js=rt.current!==null,sr=js&&!(r?.sessionId??n),rs=o.frontend??o.heldFrontend,Hr=g.useMemo(()=>n&&rs?RX({jobs:rs.jobs,todos:rs.todos,wakes:rs.wakes,monitors:rs.monitors}):null,[n,rs]),{servers:Ts,grantRunning:rr}=Fue({sessionId:n,accelerator:o.frontend?JSON.stringify(o.frontend.mcp_servers??null):null,errors:AX(o.frontend?.mcp_servers)}),Ot=FX({sessionId:n}),br=Mue({sessionId:n}),an=Bn(),ms=Uue({sessionId:n}),ir=Lue({sessionId:n}),Rs=yt(an.data,"aida",1),is=B0(Rs),Ie=xle(),Ne={capability:Rs,statusResolved:is.isSuccess,sessionId:is.data?.session_id??null,name:Ie},Le=yt(an.data,"subagent_transcript"),Ee=yt(an.data,"references")&&!At,Ze=yt(an.data,"input_mode"),H=an.isSuccess&&!!an.data?.desktop_available&&!yt(an.data,"references"),K=!!n&&!t&&wB(an.data),W=DX({sessionId:n,canonical:o,capabilities:an.data}),Y=g.useMemo(()=>t&&!r?.sessionId&&!_?{kind:"stage",commit:C}:K?{kind:"move",commit:W.moveTo}:void 0,[t,r?.sessionId,_,K,C,W.moveTo]),Q=t&&(r?.sessionId||_)?eS:K?void 0:Z1,Z=Jr(),ve=Fe=>{cp(Z,Fe)},Pe=fs({queryKey:["desktop","entities",n,"effort",""],queryFn:()=>xt({op:"commands.entities",sessionId:n,command:"effort"}),enabled:!!n,staleTime:15e3}),xe=nn(),ye=PX(o.frontend,o.heldFrontend),Re=g.useRef(void 0);g.useEffect(()=>{const Fe=Re.current;Re.current={session:n??null,model:ye},!(!n||!ye||!(Fe?.session===n)||Fe?.model===ye)&&xe.invalidateQueries({queryKey:["desktop","entities",n,"effort",""]})},[n,ye,xe]);const ze=g.useRef(null),[at,pt]=g.useState(null);g.useEffect(()=>{if(!n){pt(null);return}if(o.frontend||o.heldFrontend){ze.current=n,pt(null);return}pt(ze.current===n&&o.status==="unavailable"&&!o.missing?n:null)},[n,o.frontend,o.heldFrontend,o.status,o.missing]);const _e={cwd:p,...r?.target?{target:r.target}:{},model:r?.model??null},Ye=!n&&p.length>0&&yt(an.data,"draft_preview"),St=fs({...IX(_e),enabled:Ye}),rn=Ye?St.data?void 0:St.isError?{status:"failed",retry:()=>void St.refetch()}:{status:"pending"}:void 0,Jt=!n&&yt(an.data,"draft_selection")&&yt(an.data,"commands")&&yt(an.data,"catalogues"),bn=g.useCallback(()=>{q(null),B(void 0)},[]),xr=Lg(Fe=>n?tS(Fe,n)!==null:!1),Zr=g.useCallback(Fe=>{q(Fe),B(mF)},[]);g.useEffect(()=>{we===mF&&(xr||bn())},[xr,bn,we]);const ar=g.useCallback(Fe=>o.addNote(Fe.message??""),[o.addNote]),{dispatch:ei,dispatchFromControl:_a,picker:or,openDraftPicker:Sa,note:tc}=cqe({sessionId:n,canonical:o,rebind:ve,addMessage:ar,focusComposer:()=>h.current?.focusInput(),focusCwdChip:()=>h.current?.openWorkingDirectoryMenu(),moveSession:W.moveTo,moveReady:!t,clearAsideRefusal:bn,noteAsideRefusal:Zr,draftPicker:Jt&&s&&St.data?{target:_e,select:Fe=>Ce.getState().setDraftModel(s,Fe)}:void 0}),As=MP(_a),gu=!!n;g.useEffect(()=>{t&&h.current?.focusInput()},[t]),g.useEffect(()=>{if(!n||!o.frontend)return;const Fe=Ce.getState();Fe.sessions.some(bt=>bt.session_id===n)&&Fe.upsertSession({session_id:n,...Que({liveTitle:o.frontend.conversation_title}),attention:o.frontend.attention})},[n,o.frontend]),g.useEffect(()=>{const Fe=JSON.stringify([n,o.frontend?.streaming,o.frontend?.attention?.unseen,o.frontend?.active_agent,o.frontend?.active_team]);!n||Fe===ue.current||(ue.current=Fe,Ce.getState().fetchSessions())},[n,o.frontend?.streaming,o.frontend?.attention?.unseen,o.frontend?.active_agent,o.frontend?.active_team]);const Ep=Fe=>cQ(Fe,void 0,!1),Gi=(Fe,bt)=>{const Kt=Ce.getState().drafts[Fe],Ht=Zue({rowError:Kt?.error,rowCode:Kt?.errorCode,rowRetry:Kt?.errorRetry,fallback:()=>Ep(bt)});q(Ht?.message??null),B(Ht?.code),ie(Ht?.retry===!0),ee(Ht?.muted===!0)},Qo=async(Fe,bt,Kt,Ht,Fn,Ge)=>{const jn=Ce.getState(),Zn=ix(t,n,jn.drafts);if(!Zn)return!1;const Ra=jn.drafts[Zn],lc=()=>(q(A.current?ed.queuedSend:lQ(o.frontend?.pending_gate)),B(void 0),ie(!1),ee(!0),!1);if(Ra?.pending||!F.tryAcquire())return lc();E(!0),q(null),B(void 0),ie(!1),ee(!1);try{if(!t&&!n)return!1;const as=vB(o.frontend);if(as&&o.ownerEpoch&&n){if(Kh(as))throw new K1(KX,bF);if(as.kind==="approval"){const $s=YX(Ht??Fe);if($s===null)throw new K1("Reply yes or no to answer the approval request.",bF);await xt({op:"sessions.answer",sessionId:n,epoch:o.ownerEpoch,requestId:as.request_id,approved:$s})}else await xt({op:"sessions.answer",sessionId:n,epoch:o.ownerEpoch,requestId:as.request_id,value:XX(as,Ht,Fe),questionIndex:as.question_index});return!0}const{images:Aa,unreadable:cc,overflow:fo}=await QX(bt,Fe),ov=JX(cc);if(ov)return q(ov),B(ZX),ie(!1),ee(!1),!1;const Rp=eQ(fo);if(Rp)return q(Rp),B(void 0),ie(!1),ee(!1),!1;const lv=tQ(Fe,Aa);if(lv)return q(lv),B(void 0),ie(!1),ee(!1),!1;const cv=n?Lg.getState().attached[n]:void 0;if(n&&cv){if(bt.length>0)return q("An aside answers text only. Remove the attached files to ask it."),!1;const $s=tS(Lg.getState(),n);if($s)return Zr($s),!1;q(null),B(void 0);const uv=_B(n,Fe,o.subscriptionId??void 0);return SB(uv,n,ih=>{q(ih),B(nQ)}),{offRecord:uv}}if(n&&!L1(Ce.getState(),n))return!1;if(n&&xy(Ce.getState().validatingSessionId,n)){A.current=!0,q(ed.queuedSend),B(void 0),ie(!1),ee(!0);let $s;try{$s=await ka()}finally{A.current=!1}if($s!=="ready")return $s==="failed"&&(q(N.current.failure?.statement??sQ),B(vF),ee(!1)),!1}const rh=await CB(Zn,{text:Fe,attachments:bt,images:Aa,mode:At?"steer":"prompt",cwd:p,inputMode:Ze?Ge:void 0},n,Kt,Fn);if(!rh)return!1;const Ap=bt.filter($s=>!$s.startsWith("data:")).map($s=>Ac($s));if(Ap.length>0){const $s=ls.getState();$s.addMentionedFilesBatch(e,Ap),$s.addMentionedFilesBatch(rh,Ap)}return t&&Ce.getState().activeSessionId===rh&&Z(`/chat/${rh}`,{replace:!0}),jn.fetchSessions(),!0}catch(as){const Aa=Ce.getState().drafts[Zn];return rQ(uT(t,Aa?.sessionId??n),Aa?.admissionRequestId??"")?(q(null),B(void 0),ie(!1),ee(!1)):Gi(Zn,as),!1}finally{F.release(),E(!1)}},nh=MP(Qo),so=(Fe,bt,Kt)=>{const Ht=oQ(Fe,{liveGateKey:z.current,pressedGateKey:bt,sentEpoch:o.ownerEpoch,liveEpoch:ne.current,cardOnScreen:document.querySelector('[aria-label="Answer options"], [data-ask-secret]')!==null});switch(Ht.to){case"refused":V(null);return;case"sent":V({key:bt,sending:!1,refused:null,retryable:!1,muted:!1}),Kt?.();return;case"card":V({key:bt,sending:!1,refused:Ht.refused,retryable:Ht.retryable,muted:Ht.muted});return;case"composer":V(null),q(Ht.message),B(Ht.code),ee(Ht.muted),ie(Ht.retry);return}},kp=async Fe=>{const bt=o.frontend?.pending_gate;if(!bt||!o.ownerEpoch||!n||F.held)return;const Kt=O1(bt);document.activeElement instanceof HTMLElement&&document.activeElement.closest('[aria-label="Answer options"]')!==null&&(D.current=!0,h.current?.focusInput()),E(!0),V({key:Kt,sending:!0,refused:null,retryable:!1,muted:!1}),q(null),B(void 0);let Fn;try{Fn=await qX({gate:bt,sessionId:n,epoch:o.ownerEpoch,label:Fe,lock:F},Ge=>xt(Ge))}finally{E(!1)}so(Fn,Kt,()=>{bt.kind==="approval"&&h.current?.consumeApprovalAnswerDraft()})},Tp=async Fe=>{const bt=o.frontend?.pending_gate;if(!bt||!o.ownerEpoch||!n||F.held)return;const Kt=O1(bt);document.activeElement instanceof HTMLElement&&document.activeElement.closest("[data-ask-secret]")!==null&&(D.current=!0,h.current?.focusInput()),E(!0),V({key:Kt,sending:!0,refused:null,retryable:!1,muted:!1}),q(null),B(void 0);let Fn;try{Fn=await zX({gate:bt,sessionId:n,epoch:o.ownerEpoch,value:Fe,lock:F},Ge=>xt(Ge))}finally{E(!1)}so(Fn,Kt)},ro=(Fe,bt,Kt=!1)=>{if(bt.status==="failed"){te(Ht=>({...Ht,[Fe]:{sending:!1,refused:aQ(bt.error),refusedByOwner:iQ(bt.error)}}));return}te(Ht=>({...Ht,[Fe]:{sending:!1,refused:null,...Kt?{changed:!0}:{}}}))},Ci=async(Fe,bt)=>{if(!n||F.held)return;E(!0),te(Ht=>({...Ht,[Fe]:{sending:!0,refused:null}}));let Kt;try{Kt=await $X({taskId:Fe,answers:bt,sessionId:n,lock:F},Ht=>xt(Ht))}finally{E(!1)}ro(Fe,Kt)},Jo=async(Fe,bt)=>{if(!n||F.held)return;E(!0),te(Ht=>({...Ht,[Fe]:{sending:!0,refused:null}}));let Kt;try{Kt=await VX({taskId:Fe,answers:bt,sessionId:n,lock:F},Ht=>xt(Ht))}finally{E(!1)}ro(Fe,Kt,Kt.status==="sent"),Kt.status==="sent"&&Ls("Answer changed")},lr=async Fe=>{if(!n||F.held)return;E(!0),te(Kt=>({...Kt,[Fe]:{sending:!0,refused:null}}));let bt;try{bt=await WX({taskId:Fe,sessionId:n,lock:F},Kt=>xt(Kt))}finally{E(!1)}ro(Fe,bt)},Vi=g.useCallback((Fe,bt)=>{Fe!==G&&J(Fe,"session",bt)},[G,J]);g.useLayoutEffect(()=>{if(!D.current||(D.current=!1,document.activeElement!==document.body&&!NX()))return;const Fe=document.querySelector('[aria-label="Answer options"] button:not([disabled]), [data-ask-secret] input:not([disabled])');Fe?Fe.focus():h.current?.focusInput()},[P]);const Ea=g.useCallback(()=>{const Fe=st.current;Fe!==null&&(st.current=null,q(bt=>bt===Fe?null:bt))},[]),ti=g.useCallback(()=>{if(!n||!vt)return;const Fe=ge.current;if(Fe==="pending"||Fe==="awaiting-end")return;const bt=++Ae.current;De(null),Se("pending");const Kt=Date.now();y(n,Kt),_he(n,crypto.randomUUID()).then(Ht=>{if(bt!==Ae.current)return;Ht.status!=="interrupted"&&k(n);const Fn=sn.current,Ge=Ehe(Ht,{turnClaimed:Fn});De(Ge===null?null:{text:Ge,kind:Ht.status!=="idle"?"outcome":Fn?"idle-disputed":"idle"}),Se(Ht.status==="interrupted"&&sn.current?"awaiting-end":null),Ea(),Ht.status==="idle"&&Fn&&o.retry()}).catch(Ht=>{if(bt!==Ae.current)return;if(!sn.current){Se(null);return}Se("unconfirmed");const Fn=bi(Ht,"Stop could not be confirmed. The turn may still be running.");st.current=Fn,q(Fn),B(void 0),ie(!1),ee(!1)})},[n,vt,y,k,Ea,o.retry]),Zo=g.useRef(null);g.useEffect(()=>{const Fe=Zo.current;Zo.current=At,!Fe&&At?(Ae.current+=1,De(null),Se(null),Ea(),n&&k(n)):Fe&&!At&&(De(bt=>bt?.kind==="idle"||bt?.kind==="idle-disputed"?null:bt),Se(bt=>bt==="awaiting-end"||bt==="unconfirmed"?null:bt),Ea())},[At,n,k,Ea]),g.useEffect(()=>{Ae.current+=1,Se(null)},[n]),g.useEffect(()=>{if(!G)return;const Fe=bt=>{UX(bt)&&(bt.preventDefault(),Vi(!1))};return window.addEventListener("keydown",Fe),()=>window.removeEventListener("keydown",Fe)},[G,Vi]);const Wi=xB({status:o.status,failure:o.failure,missing:o.missing,stale:o.stale});xhe({sessionId:n,turnAlive:At,available:vt&&!Wi,recording:uQ,onInterrupt:ti});const Hs=r?.target?.kind==="team"?r.target.name:null,el=o.frontend?.active_team||null,mu=sC(!!(Hs||el)&&yt(an.data,"team_catalogue")),vu=g.useMemo(()=>{const Fe=new Map((mu.data??[]).map(bt=>[bt.name,kf(bt)]));return bt=>Fe.get(bt)??bt},[mu.data]),bu=(el?vu(el):"")||o.frontend?.active_agent||(r?.target?r.target.kind==="team"?vu(r.target.name):r.target.name:void 0),tl=Ce(Fe=>n?Fe.sessions.find(bt=>bt.session_id===n):void 0),xu=Ce(Fe=>n?Fe.forgotten[n]?.title:void 0),$i=[o.frontend?.active_agent,o.frontend?.active_team].filter(Boolean).join(" · ")||[tl?.binding?.agent,tl?.binding?.team].filter(Boolean).join(" · "),wu=Xue({draftKey:t,draftTarget:bu,liveTitle:o.frontend?.conversation_title,catalogueTitle:tl?.title??xu}),nc=n?o:{...o,status:"live",error:null},nl=!$i&&!t&&nc.status==="connecting",io=n&&kze({hasSession:!!n,pending:nl,teamCatalogue:yt(an.data,"team_catalogue"),identityKnown:!!$i,streamLive:nc.status==="live"})?{sessionId:n,activeAgent:o.frontend?.active_agent??null,activeTeam:o.frontend?.active_team??null,boundAgent:tl?.binding?.agent??null,boundTeam:tl?.binding?.team??null,effectiveIdentity:o.frontend?.effective_identity??null,hostKey:wze(tl),frameEpoch:o.frontend?.epoch??null}:void 0,ao=o.frontend?.active_team||o.frontend?.active_agent,Cu=(we??r?.errorCode)==="unresolved_attachment"&&!!ao;g.useEffect(()=>{Cu&&(q(null),B(void 0),s&&Ce.getState().updateDraft(s,{error:void 0,errorCode:void 0}))},[Cu,s]);const oo=Ce(Fe=>xy(Fe.validatingSessionId,n)),sh=Ce(Fe=>L1(Fe,n));g.useEffect(()=>{if(!n||!oo)return;const Fe=Ce.getState();o.status==="live"?Fe.confirmSessionLive(n):o.missing&&Fe.confirmSessionMissing(n)},[n,oo,o.status,o.missing]);const ni=Fe=>{const bt=M.current.splice(0);for(const Kt of bt)Kt(Fe)},sl=()=>{if(N.current.missing)return"gone";if(!L1(Ce.getState(),n))return"abandoned";const Fe=N.current.status;return Fe==="unavailable"?"failed":xy(Ce.getState().validatingSessionId,n)?null:Fe==="live"?"ready":null},ka=()=>{const Fe=sl();return Fe?Promise.resolve(Fe):new Promise(bt=>{M.current.push(bt)})};g.useEffect(()=>{if(M.current.length===0)return;const Fe=sl();Fe&&ni(Fe)},[oo,sh,o.status,o.missing]),g.useEffect(()=>{const Fe=M.current;return()=>{for(const bt of Fe.splice(0))bt("abandoned")}},[]),g.useEffect(()=>{oo||we!==vF||(q(null),B(void 0))},[oo,we]),g.useEffect(()=>{s&&(MX(s,r),OX(s,r))},[s,r]);const wr=r?.admissionAttempted&&!r.pending?r.admissionRequestId:void 0,yi=Ce(()=>wr?o.transcript.index.get(wr):void 0),si=Ce(()=>{if(!wr)return!1;const Fe=o.transcript.records[yi??-1];return Fe?.kind==="user"&&!Fe.local});g.useEffect(()=>{!wr||!si||!s||(Ba.getState().reconcileDelivered(e),q(null),B(void 0),ie(!1),ee(!1),Ce.getState().finishDraft(s,r?.sessionId??n??""))},[wr,si,s,r?.sessionId,n,e]);const rc=Ba(Fe=>Fe.inputByConversation[e]?.lateDelivered),ic=Ba(Fe=>Fe.inputByConversation[e]?.currentInput??""),Ln=r?r.submittedText!==void 0&&(r.error!==void 0||wr!==void 0)?{recordId:wr??r.admissionRequestId,text:r.submittedText,attachments:r.submittedAttachments??[],message:r.error,retry:r.errorRetry??Nx(r.errorCode)}:r.undelivered??null:null,ac=Ln?LX(Ln.text):null,lo=Ln?ac?.text??Ln.text:null,oc=Ln?{recordId:Ln.recordId,message:Ln.message,retry:Ln.retry,retryDisabled:ic.trim().length>0&&ic===lo,onSendAgain:()=>{Qo(Ln.text,[...Ln.attachments])},onEdit:()=>{Ba.getState().returnPayload(e,{text:lo??Ln.text,attachments:[...Ln.attachments],replies:ac?.replies??[]}),r?.admissionAttempted!==!0&&(GX(e,Ln.recordId),s&&Ce.getState().updateDraft(s,{error:void 0,errorCode:void 0,errorRetry:void 0,undelivered:void 0})),h.current?.focusInput()}}:null,Dt=r?.admissionAttempted===!0&&r.pending!==!0,co=g.useRef(Dt);g.useEffect(()=>{co.current&&!Dt&&(q(null),B(void 0),ie(!1),ee(!1)),co.current=Dt},[Dt]),g.useEffect(()=>{ede({rowPending:r?.pending===!0,admitting:_,gatePending:o.frontend?.pending_gate!=null,muted:Te})&&(q(null),B(void 0),ie(!1),ee(!1))},[r?.pending,_,o.frontend?.pending_gate,Te]);const Ta=BX(e),uo=g.useMemo(()=>Jue({error:le,code:we,retry:be,muted:Te,rowError:Ta?void 0:r?.error,rowCode:Ta?void 0:r?.errorCode,rowRetry:Ta?void 0:r?.errorRetry,lateDelivered:rc}),[le,we,be,Te,Ta,r?.error,r?.errorCode,r?.errorRetry,rc]),Cr=g.useMemo(()=>uo&&!(v&&uo.code===oC.transportFailed)?{...uo,actions:void 0,onRetry:()=>{h.current?.submitNow(),h.current?.focusInput()},onClear:()=>{e&&Ba.getState().clearComposer(e),bn(),s&&Ce.getState().discardDraft(s),h.current?.focusInput()},onDismiss:()=>{bn(),s&&r&&Ce.getState().updateDraft(s,{error:void 0,errorCode:void 0})}}:void 0,[uo,v,e,s,r,bn]),ho=Ce(Fe=>jX(Fe.sessions,n)),yu=g.useMemo(()=>n?{frontend:o.frontend??o.heldFrontend,servingLocality:ho,held:o.frontend===null&&o.heldFrontend!==null,contextHeld:o.contextCarried,readingsDropped:at===n,pendingModel:o.pendingModel,onCommand:Fe=>void As(Fe),effortEntities:Pe.data?.entities,costChannels:yt(an.data,"cost_channels")}:void 0,[n,o.frontend,o.heldFrontend,o.contextCarried,ho,at,o.pendingModel,As,Pe.data,an.data]),_u=g.useMemo(()=>c.jsx(Rde,{sessionId:n??void 0}),[n]);return c.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[me&&c.jsx("div",{className:T("flex flex-wrap gap-2 border-b border-hairline px-4 py-2 text-body-sm"),children:["model","agent","team","rename","resume","fork","new","settings"].map(Fe=>c.jsx("button",{type:"button",className:T("rounded-md px-2 py-1 hover:bg-elevated"),onClick:()=>{it(!1),ei({name:Fe,args:""})},children:Fe==="agent"?"Choose agent":Fe==="team"?"Choose team":Fe.charAt(0).toUpperCase()+Fe.slice(1)},Fe))}),c.jsx("div",{className:T("min-h-0 flex-1"),children:c.jsx(rqe,{activeTab:ct,onTabChange:Qe,deviceSlot:c.jsx(ghe,{sessionId:n??void 0,draftKey:t??void 0}),deviceNotice:c.jsx(ahe,{sessionId:n??void 0}),deviceHold:_u,agentName:wu,description:$i||(t?js?bu??"Starting the session":r?.sessionId?o.frontend?.cwd||p||"Canonical chat":o.frontend?.cwd||p||"":W.cwd||dqe),descriptionPending:nl,identity:io,renameSessionId:n&&yt(an.data,"commands")?n:void 0,onOpenOptions:()=>it(Fe=>!Fe),isOptionsSidebarOpen:!1,onCloseOptions:()=>it(!1),agentId:e,turnTerminal:o.turnsCompleted,cwd:t?p:W.cwd,cwdWritePath:Y,cwdReadOnlyReason:Q,sessionId:n,cwdPending:K&&W.busy,cwdPendingAccepted:K&&W.accepted,messages:[],isLoading:!1,isLoadingMessages:!1,isFarFromBottom:Nt,messagesContainerRef:f,scrollToBottom:Tt,rawInfoContent:JSON.stringify(o.frontend,null,2),onSendMessage:nh,onSlashCommand:As,onSlashNote:tc,paneHasSession:gu,sendError:Cr,undelivered:oc,sessionStatus:n?yu:St.data?{frontend:St.data.snapshot,draft:!0,draftResolved:!0,onOpenDraftPicker:Jt?Sa:void 0,costChannels:yt(an.data,"cost_channels")}:rn?{frontend:null,draft:!0,draftResolved:!1,draftResolution:rn,costChannels:yt(an.data,"cost_channels")}:void 0,currentJobId:null,onCancelJob:ti,messageInputRef:h,runDetails:Hr,onComposerInput:d,mcpServers:Ts,mcpGrantRunning:rr,mcpRemedy:Ot,monitorControls:br,wakeControls:ms,jobControls:ir,wakeAida:Ne,childrenOpenable:Le,mentionsEnabled:Ee,mentionsUnsupported:H,pulses:o.subagentPulses,canonical:{view:nc,turnAlive:At,stopOutcome:Ue,idleDisputed:de?.kind==="idle-disputed",admitting:_,starting:js,startingAfterId:rt.current?.requestId??null,startingSession:sr,startingSince:r?.submittedAt??Ut?.submittedAt??rt.current?.submittedAt??null,onStop:ti,stopAvailable:vt,stopNotice:de?.text??khe(At,vt),onAnswer:Fe=>void kp(Fe),onAnswerSecret:Fe=>void Tp(Fe),answer:fe,onAnswerAsk:(Fe,bt)=>void Ci(Fe,bt),onDeclineAsk:Fe=>void lr(Fe),onReviseAsk:(Fe,bt)=>void Jo(Fe,bt),askOutcomes:j,askExpanded:G,onAskToggle:Vi,askDrafts:ae,onAskDraftChange:(Fe,bt)=>O(Kt=>({...Kt,[Fe]:bt}))}})}),c.jsx(HX,{context:or})]})}function w3(){const{agentId:e}=C4(),t=Jr(),n=Bn(),s=pa(n.data,"session_catalogue",2),r=s==="enabled",{data:i}=sp(),a=XT(i?.online===!1),o=i?.snapshot&&!i.snapshot.pairing.available?i.snapshot.pairing.cause??"unpaired":null,l=CX(s,o),u=Yk(n.data,o),d=wX(o),h=g.useCallback(async()=>{s==="unpaired"&&await window.api?.backend?.reconnect?.(),await n.refetch()},[s,n]),f=Ce(R=>R.activeSessionId),p=Ce(R=>R.activeDraftKey),m=Ce(R=>ix(p,R.activeSessionId,R.drafts)),v=Ce(R=>m?R.drafts[m]:void 0),b=Ce(R=>R.error),[w,C]=g.useState(null);g.useEffect(()=>{if(!r||!e)return;const R=Ce.getState();if(!uqe.test(e)){C("This legacy link has no canonical chat. Its saved history is unchanged.");return}const F=e;C(null),(R.activeSessionId!==F||R.activeDraftKey)&&R.openSession(F)},[r,e]);const y=g.useRef(p);g.useEffect(()=>{y.current!==p&&(y.current=p,p&&C(null))},[p]);const k=(R,F)=>{Ce.getState().stageDraft(R,F),C(null),t("/chat")},_=ip(p,v?.sessionId,f),E=uT(p,_);return c.jsxs("div",{className:T("flex h-full min-h-0 flex-col"),children:[(w||b&&!a&&!u)&&c.jsx("p",{role:"alert",className:T("px-4 py-2 text-body-sm text-danger"),children:w||b}),r?E?c.jsx("div",{className:T("min-h-0 flex-1"),children:c.jsx(hqe,{identity:E,draftKey:p,sessionId:_},E)}):c.jsx("div",{className:T("p-6"),children:c.jsx("button",{type:"button",className:T("rounded-md border border-control px-3 py-2"),onClick:()=>k(void 0,!0),children:"New chat"})}):c.jsxs("div",{className:T("flex h-full min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6","text-body text-ink-muted"),children:[c.jsx("p",{className:T("text-center"),children:n.isLoading?"Connecting to the backend… Your conversation is safe.":n.error?bi(n.error,"The Local Operator server did not answer as expected."):l??"Update the backend to use canonical chats. Your existing histories are unchanged."}),d&&c.jsx("button",{type:"button",className:T("underline"),onClick:()=>void h(),children:"Retry"})]})]})}const jW=100,fqe=4,pqe=16,gqe=3;function HW(e,t){return t.sessionId??(e.startsWith("send:")?e.slice(5):void 0)}function mqe(e){const t=[];for(const[n,s]of Object.entries(e)){if(s.admissionAttempted!==!0||s.pending===!0||s.submittedText===void 0)continue;const r=HW(n,s);r&&t.push({key:n,sessionId:r,submittedAt:s.submittedAt??0})}return t}function UW(e){const t=new Map;for(const[n,s]of Object.entries(e)){const r=s.undelivered?.recordId;if(r===void 0)continue;const i=HW(n,s);if(!i)continue;const a=t.get(i);a?a.push(r):t.set(i,[r])}return t}function vqe(e){const t=new Map,n=mqe(e).sort((s,r)=>s.submittedAt-r.submittedAt);for(const s of n){const r=t.get(s.sessionId);r?r.push(s.key):t.set(s.sessionId,[s.key])}return t}let hg=null;function bqe(){return hg||(hg=xqe().catch(()=>({visited:0,resolved:0,healed:0})).finally(()=>{hg=null}),hg)}async function xqe(){const e=Ce.getState().drafts,t=vqe(e),n=UW(e),s=[...new Set([...t.keys(),...n.keys()])].slice(0,pqe);let r=0,i=0,a=0;const o=async()=>{for(;;){const l=s.shift();if(l===void 0)return;r+=1;const u=await wqe(l,t.get(l)??[],n.get(l)??[]);i+=u.resolved,a+=u.healed}};return await Promise.all(Array.from({length:Math.min(gqe,s.length)},o)),{visited:r,resolved:i,healed:a}}async function wqe(e,t,n){let s;try{s=await xt({op:"sessions.history",sessionId:e,limit:jW})}catch{return{resolved:0,healed:0}}Ce.getState().resolveHeldFromServer(e,s.entries,!1);const r=new Set(UW(Ce.getState().drafts).get(e)??[]),i=n.filter(u=>r.has(u)),a=n.length-i.length,o=i.length>0?await Cqe(e,s,i):0;let l=0;for(const u of t){const d=Ce.getState().drafts[u];if(!(d!==void 0&&d.admissionAttempted===!0&&d.submittedText!==void 0)){l+=1;for(const f of[u,EB(u,e)])Ba.getState().reconcileDelivered(f)}}return{resolved:l,healed:a+o}}async function Cqe(e,t,n){const s=new Set(n);let r=t.entries[0]?.id;for(let i=0;i<fqe;i++){if(s.size===0||!r)return n.length-s.size;let a;try{a=await xt({op:"sessions.history",sessionId:e,limit:jW,beforeId:r})}catch{return n.length-s.size}for(const o of a.entries)s.delete(o.id);if(Ce.getState().resolveHeldFromServer(e,a.entries,!1),a.cursor_missing||!a.has_more||a.entries.length===0)return n.length-s.size;r=a.entries[0]?.id}return n.length-s.size}let C3=!1;function yqe(){g.useEffect(()=>{C3||(C3=!0,bqe())},[])}const _qe="n",Sqe=e=>e.defaultPrevented||e.repeat||e.isComposing||e.shiftKey||e.altKey||e.key.toLowerCase()!==_qe||!(e.metaKey||e.ctrlKey)||dQ(e.target)?!1:!lT(e.target),y3=e=>e?"⌘+N":"Ctrl+N",Eqe=()=>{const e=Lc(o=>o.request),t=Lc(o=>o.consumePanel),[n,s]=g.useState(null),r=g.useRef(null),i=g.useCallback(()=>{s(null);const o=r.current;r.current=null,o&&requestAnimationFrame(()=>{o.isConnected&&o.focus()})},[]);g.useEffect(()=>{if(!e)return;const o=hQ({request:e,presentable:!!xF(e.destination),claimed:Lc.getState().presenterClaimed,now:Date.now()});if(o==="retire"){t(e.nonce);return}if(o==="yield"){s(null);return}o==="present"&&(r.current=e.invoker??(document.activeElement instanceof HTMLElement?document.activeElement:null),t(e.nonce),s({destination:e.destination,action:{kind:"native_action",destination:e.destination,session_id:"",args:"",fields:[],data:{}}}))},[e,t]);const a=n?xF(n.destination):void 0;return!n||!a?null:c.jsx(a,{action:n.action,sessionId:"",frontend:null,onClose:i},n.destination)},Dk=op()(e=>({open:!1,openLanguage:()=>e({open:!0}),closeLanguage:()=>e({open:!1})}));function kqe(e){return!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.repeat||e.defaultPrevented?null:e.key.toLowerCase()==="k"?"chats":null}const Tqe={chats:wVe,everything:"",commands:yVe};function Rqe(e,t){const n=Tqe[e],s=Dw(n).scope;return t.open?Dw(t.query).scope===s?{action:"close"}:{action:"switch",query:n}:{action:"open",query:n}}function ko(e,t){switch(e){case"chats":return t?"⌘K":"Ctrl+K";case"commands":return t?"⌘⇧P":"Ctrl+Shift+P";default:return t?"⌘P":"Ctrl+P"}}function Aqe(e,t){switch(e){case"chats":return t?"⌘+K":"Ctrl+K";case"commands":return t?"⌘+⇧+P":"Ctrl+Shift+P";default:return t?"⌘+P":"Ctrl+P"}}function Fqe(e){if(e.key==="ArrowDown")return e.shiftKey||e.altKey||e.ctrlKey?null:"next";if(e.key==="ArrowUp")return e.shiftKey||e.altKey||e.ctrlKey?null:"previous";const t=e.key.toLowerCase();return t!=="n"&&t!=="p"||!e.ctrlKey||e.metaKey||e.shiftKey||e.altKey?null:t==="n"?"next":"previous"}function Dqe(e,t,n){return t<=0?null:n==="next"?(e+1)%t:(e-1+t)%t}function Pqe(e){return e?["Ctrl+N","Ctrl+P"]:["Ctrl+N"]}const Iqe={general:"settings-sidebar-general",radient:"settings-sidebar-radient-account",integrations:"settings-sidebar-integrations",appearance:"settings-sidebar-appearance",updates:"settings-sidebar-application-updates"},Nqe=[{get label(){return x("ui.settings.navigation.settings_sidebar.general")},ids:["general","appearance","speech","keyboard"]},{get label(){return x("ui.settings.navigation.settings_sidebar.account")},ids:["providers","integrations","radient"]},{get label(){return x("ui.settings.navigation.settings_sidebar.backend")},ids:["backend"]},{get label(){return x("ui.settings.navigation.settings_sidebar.system")},ids:["updates"]}],get=({activeSection:e,onSelectSection:t,sections:n})=>{Et();const s=oB("(min-width: 1040px)"),r=i=>{const a=e===i.id,o=c.jsxs("button",{type:"button",onClick:()=>t(i.id),"aria-current":a?"page":void 0,"aria-label":s?void 0:i.label,"data-tour-tag":Iqe[i.id],className:T("relative flex h-8 w-full items-center rounded-sm bg-transparent text-left text-body-sm hover:bg-row-hover hover:text-ink","transition-colors duration-fast ease-out-quart",s?"justify-start gap-2 px-3":"justify-center",a?"font-semibold text-ink":"text-ink-muted"),children:[a&&c.jsx("span",{"aria-hidden":"true",className:"absolute left-1 top-1/2 size-1 -translate-y-1/2 rounded-full bg-accent"}),c.jsx("span",{"aria-hidden":"true",className:T("flex size-4 shrink-0 items-center justify-center",a?"text-accent":"text-ink-dim"),children:c.jsx(i.icon,{size:16})}),s&&c.jsx("span",{className:"truncate",children:i.label})]});return s?c.jsx("li",{children:o},i.id):c.jsx("li",{children:c.jsx(Je,{content:i.label,side:"right",children:o})},i.id)};return c.jsx("nav",{"aria-label":x("ui.settings.navigation.settings_sidebar.settings_sections"),"data-glass-region":"page-sidebar",className:"flex h-full w-full flex-col overflow-hidden bg-surface",children:c.jsx("div",{className:"flex flex-1 flex-col gap-6 overflow-y-auto px-2 py-4",children:Nqe.map(i=>{const a=n.filter(o=>i.ids.includes(o.id));return a.length===0?null:c.jsxs("div",{children:[s&&c.jsx("div",{className:"px-3 pb-1 text-meta text-ink-dim",children:i.label}),c.jsx("ul",{className:"flex flex-col gap-0.5",children:a.map(r)})]},i.label)})})})},Mqe=[{id:"general",get label(){return x("ui.settings.navigation.settings_sidebar.general_settings")},icon:Pc},{id:"radient",get label(){return x("ui.settings.navigation.settings_sidebar.radient_account")},icon:Zj},{id:"integrations",get label(){return x("ui.settings.navigation.settings_sidebar.integrations")},icon:Sj},{id:"appearance",get label(){return x("ui.settings.navigation.settings_sidebar.appearance")},icon:_j},{id:"speech",get label(){return x("ui.settings.navigation.settings_sidebar.speech_voicing")},icon:Bne},{id:"keyboard",get label(){return x("ui.settings.navigation.settings_sidebar.keyboard_shortcuts")},icon:Fse},{id:"providers",get label(){return x("ui.settings.navigation.settings_sidebar.model_providers")},icon:kB},{id:"backend",get label(){return x("ui.settings.navigation.settings_sidebar.backend_settings")},icon:Nf},{id:"updates",get label(){return x("ui.settings.navigation.settings_sidebar.application_updates")},icon:qk}];function Oqe(){const e=Ce(n=>Lqe(n.activeDraftKey,n.activeDraftKey?n.drafts[n.activeDraftKey]?.sessionId:void 0,n.activeSessionId)),t=qe(n=>n.rememberConversation);g.useEffect(()=>{e!==null&&t(e)},[e,t])}function Lqe(e,t,n){const s=ip(e,t,n);return s||null}function Bqe(e,t,n,s,r){const i=t.indexOf(e.session_id);return{recentRank:i===-1?void 0:i,current:e.session_id===n,archived:dB(uB([e],r),s).length===0}}const _3=100,jqe=["desktop","settings"],Hqe=[{id:"chat",get name(){return x("ui.command_palette.use_palette_sources.chat")},path:"/chat",icon:"chat",keywords:["conversations","messages","history","sessions"]},{id:"agents",get name(){return x("ui.command_palette.use_palette_sources.my_agents")},path:"/agents",icon:"agents",keywords:["bots","assistants","roster","agent list"]},{id:"projects",get name(){return x("ui.command_palette.use_palette_sources.projects")},path:"/projects",icon:"projects",keywords:["workstreams","milestones","tracking","planning"]},{id:"agent-hub",get name(){return x("ui.command_palette.use_palette_sources.agent_hub")},path:"/agent-hub",icon:"hub",keywords:["store","marketplace","catalog","discover","browse agents"]},{id:"schedules",get name(){return x("ui.command_palette.use_palette_sources.schedules")},path:"/schedules",icon:"schedules",keywords:["cron","recurring","automation","jobs","timer","daily"]},{id:"browser",get name(){return x("ui.command_palette.use_palette_sources.browser")},path:"/browser",icon:"browser",keywords:["web","sites","url","internet"]},{id:"settings",get name(){return x("ui.command_palette.use_palette_sources.settings")},path:"/settings",icon:"settings",keywords:["preferences","config","options","configuration"]}],Uqe={id:"mesh",get name(){return x("ui.command_palette.use_palette_sources.mesh")},path:"/mesh",icon:"network",keywords:["networks","peers","devices","relay","mesh"]};function Gqe({open:e,query:t,isOnChatPage:n,hasConversation:s,isCanvasOpen:r}){Et();const{scope:i,terms:a}=Dw(t),o=i===null||i==="chat",l=i===null||i==="agent",u=i===null||i==="agent",d=i===null||i==="setting",h=Bn(),f=yt(h.data,"session_search"),p=yt(h.data,"settings"),m=yt(h.data,"session_catalogue",2),v=yt(h.data,"session_archive"),b=sC((o||u)&&yt(h.data,"team_catalogue")),w=g.useMemo(()=>new Map((b.data??[]).map(be=>[be.name,kf(be)])),[b.data]),C=ZT(yt(h.data,"peers")),y=yt(h.data,"projects",1),k=g.useMemo(()=>[...Hqe.filter(be=>be.id!=="projects"||y),...C==="member"?[Uqe]:[]],[C,y]),{data:_}=sp(),E=_?.snapshot?.pairing.available===!1,R=Ce(be=>be.sessions),F=Ce(be=>be.forgotten),A=Ce(be=>be.loading),N=Ce(be=>be.fetchSessions),M=g.useRef(!1);g.useEffect(()=>{if(!e){M.current=!1;return}M.current||R.length>0||A||(M.current=!0,N(Ww))},[e,R.length,A,N]);const D=aW(a,e&&o&&a.length>0&&f),L=D.data&&D.data.query===a?D.data.sessions:null,V=g.useMemo(()=>({include:!1,facts:{},forgotten:new Set(Object.keys(F))}),[F]),j=MZ(qe(be=>be.conversationRecents)),te=Ce(be=>{const ie=be.activeDraftKey?be.drafts[be.activeDraftKey]:void 0;return ip(be.activeDraftKey,ie?.sessionId,be.activeSessionId)}),X=Ce(be=>be.archiveFacts),re=(()=>{if(!o)return[];const{rows:be}=Ek(R,a,L,{},V),ie=new Map((L??[]).map(Te=>[Te.id,Te]));return be.map((Te,ee)=>{const de=ie.get(Te.session_id),De=rW(Te,a),Ue=qVe(Te,w),Se=Bqe(Te,j,te,v,X),ge=!!de?.body_match&&!De;return{...Ue,hint:ge?x("ui.command_palette.use_palette_sources.in_conversation"):Ue.hint,tier:De||de?Math.min(de?.rank??Fw,De?Fw:Number.POSITIVE_INFINITY):void 0,soft:Te.preview??void 0,order:ee,featured:a.length===0,unread:Bw(Te)!==null,recentRank:Se.recentRank,current:Se.current,archived:Se.archived}})})(),G=YS(1,_3),J=_p(a,iW),ae=(G.data?.total??0)>(G.data?.agents?.length??0),O=YS(1,_3,0,ae&&l&&J?J:void 0),U=(()=>{if(!l)return[];const be=new Set,ie=[];for(const ee of[G.data?.agents,O.data?.agents])for(const de of ee??[])be.has(de.id)||(be.add(de.id),ie.push(de));const Te=[];for(const ee of ie)m&&Te.push({id:`agent-chat-${ee.id}`,kind:"agent",group:"agents",name:ee.name,hint:x("ui.command_palette.use_palette_sources.agent_chat"),icon:"agents",keywords:ee.tags,target:{type:"draft",kind:"agent",name:ee.name},featured:a.length===0}),Te.push({id:`agent-settings-${ee.id}`,kind:"agent",group:"agents",name:ee.name,hint:x("ui.command_palette.use_palette_sources.agent_settings"),icon:"settings",keywords:ee.tags,target:{type:"path",path:`/agents/${ee.id}`}});return Te.map((ee,de)=>({...ee,order:de}))})(),P=u?m?(b.data??[]).map((be,ie)=>({id:`team-chat-${be.name}`,kind:"team",group:"teams",name:kf(be),hint:x("ui.command_palette.use_palette_sources.team_chat"),icon:"team",keywords:[be.name,...be.aliases??[]],target:{type:"draft",kind:"team",name:be.name},featured:a.length===0,order:ie})):[]:[],z=fs({queryKey:jqe,queryFn:()=>xt({op:"settings.list"}),enabled:e&&d&&p,staleTime:1e4}),ne=d?[...VVe(Mqe),...WVe((z.data?.settings??[]).map(dT))]:[],fe=Ce(be=>be.activeSessionId),ue=Ce(be=>be.activeDraftKey),le=m&&!!(fe??ue),q=!!fe,we=!m||E?[]:zVe([{id:"info",destination:"info",name:x("ui.command_palette.use_palette_sources.info"),hint:x("ui.command_palette.use_palette_sources.app_backend_and_environment"),icon:"info",keywords:["about","version","environment","diagnostics","host","runtime"]},{id:"usage",destination:"usage",name:x("ui.command_palette.use_palette_sources.provider_usage"),hint:x("ui.command_palette.use_palette_sources.credits_limits_and_spend"),icon:"usage",keywords:["usage","credits","billing","limits","cost","spend","tokens","quota"]},...le&&q?[{id:"session",destination:"session.diagnostics",name:x("ui.command_palette.use_palette_sources.session"),hint:x("ui.command_palette.use_palette_sources.diagnostics_for_this_conversation"),icon:"session",keywords:["diagnostics","report","tokens","context","timings","tool calls"]}]:[],{id:"analytics",destination:"analytics",name:x("ui.command_palette.use_palette_sources.analytics"),hint:x("ui.command_palette.use_palette_sources.usage_over_time"),icon:"analytics",keywords:["usage","charts","trends","cost","spend","tokens","reports"]}]);return{items:[...GVe(k),...$Ve(Vqe({isOnChatPage:n,hasConversation:s,isCanvasOpen:r,canStageDraft:m})),...we,...ne,...U,...P,...re],chats:{awaiting:e&&o&&a.length>0&&f&&!D.refused&&!D.isError&&D.data?.query!==a,unavailable:o&&a.length>0&&!f,unreachable:h.isError,pending:h.isLoading||h.isPending,overLong:D.refused,catalogue:R.length>0?"loaded":A||!M.current?"loading":"empty"}}}function Vqe({isOnChatPage:e,hasConversation:t,isCanvasOpen:n,canStageDraft:s}){return[...s?[{id:"new-chat",name:x("ui.command_palette.use_palette_sources.new_chat"),icon:"new-chat",keywords:["start chat","compose","draft","new conversation"],verb:x("ui.command_palette.use_palette_sources.start"),command:"new-chat",featured:!0}]:[],{id:"connect-provider",name:x("ui.command_palette.use_palette_sources.connect_a_model_provider"),icon:"providers",keywords:["sign in","login","api key","add provider","claude","chatgpt","radient","model"],verb:x("ui.command_palette.use_palette_sources.connect"),command:"connect-provider",featured:!0},{id:"change-interface-language",name:x("ui.settings.language.palette_action"),icon:"language",keywords:["language","locale","interface language","translation","i18n"],verb:x("ui.command_palette.use_palette_sources.change"),command:"change-interface-language"},{id:"create-agent",name:x("ui.command_palette.use_palette_sources.create_agent"),icon:"plus",keywords:["new agent","add agent","make agent"],verb:x("ui.command_palette.use_palette_sources.create"),command:"create-agent",featured:!0},...e?[{id:"toggle-canvas",name:n?x("ui.command_palette.use_palette_sources.close_canvas"):x("ui.command_palette.use_palette_sources.open_canvas"),icon:n?"canvas-close":"canvas-open",keywords:["files","workspace","panel","editor","artifacts"],verb:n?x("ui.command_palette.use_palette_sources.close"):x("ui.command_palette.use_palette_sources.open"),command:"toggle-canvas",featured:!0}]:[],...e&&t?[{id:"clear-conversation",name:x("ui.command_palette.use_palette_sources.clear_conversation"),icon:"trash",keywords:["delete chat","reset","wipe","erase","clear history"],verb:x("ui.command_palette.use_palette_sources.clear"),command:"clear-conversation",destructive:!0,featured:!0}]:[]]}const Wqe={chat:FT,conversation:Sx,agents:Uo,team:Og,projects:bj,hub:kj,network:TB,schedules:mj,browser:qc,settings:Pc,theme:_j,integrations:Sj,providers:kB,backend:Nf,updates:qk,plus:Kc,"new-chat":Are,trash:P0,"canvas-open":fQ,"canvas-close":zc,slider:Nf,info:ap,language:xj,usage:xse,session:gj,analytics:zne},$qe=({name:e})=>{if(e==="account")return c.jsx(Zj,{size:16});const t=Wqe[e];return c.jsx(t,{size:16,"aria-hidden":"true"})},fg="command-palette-input",S3="command-palette-results",zqe={get page(){return x("ui.command_palette.command_palette.go")},get action(){return x("ui.command_palette.command_palette.run")},get panel(){return x("ui.command_palette.command_palette.open")},get chat(){return x("ui.command_palette.command_palette.open")},get agent(){return x("ui.command_palette.command_palette.open")},get team(){return x("ui.command_palette.command_palette.open")},get"settings-section"(){return x("ui.command_palette.command_palette.open")},get setting(){return x("ui.command_palette.command_palette.open")}},qqe=200,E3=()=>{const e=Ce.getState(),t=e.activeDraftKey;return AB(t,t?e.drafts[t]?.sessionId:void 0,e.activeSessionId)},Kqe=()=>{Et();const e=Jr(),t=aT(),n=qe(ee=>ee.isCommandPaletteOpen),s=qe(ee=>ee.closeCommandPalette),r=qe(ee=>ee.commandPaletteQuery),i=qe(ee=>ee.setCommandPaletteQuery),a=qe(ee=>ee.isCanvasOpen),o=qe(ee=>ee.setCanvasOpen),l=qe(ee=>ee.isCreateAgentDialogOpen),u=Lc(ee=>ee.requestPanel),{agentId:d}=Yae(),h=Q4(ee=>ee.getLastAgentId),f=Xj(),[p,m]=g.useState(r),[v,b]=g.useState(0),w=g.useRef(null),[C,y]=g.useState(!1),[k,_]=g.useState(!1),E=g.useDeferredValue(p),R=_p(p,qqe);g.useEffect(()=>{i(R)},[R,i]),g.useEffect(()=>{n&&m(r)},[n,r]);const F=t.pathname.startsWith("/chat"),A=d||h("chat"),{items:N,chats:M}=Gqe({open:n,query:E,isOnChatPage:F,hasConversation:!!A,isCanvasOpen:a}),D=g.useMemo(()=>HVe({items:N,raw:E}),[N,E]),L=g.useMemo(()=>D.sections.flatMap(ee=>ee.items),[D]),V=L.length,j=L[v],te=D.terms.length>0,X=V>0,re=D.scope===null?null:Tk.find(ee=>ee.scope===D.scope)??null,G=vVe({scope:D.scope,hasTerms:te,terms:D.terms,awaiting:M.awaiting,catalogue:M.catalogue}),J=g.useCallback(()=>{s(),e("/agents?create=agent")},[s,e]),ae=g.useCallback(()=>{s(),RB.getState().openConnect()},[s]),O=g.useCallback(()=>{s(),Dk.getState().openLanguage()},[s]),U=g.useCallback(()=>{Ce.getState().stageDraft(void 0,!0),s(),e("/chat")},[s,e]),P=g.useCallback(()=>{o(!a),s()},[a,o,s]),z=g.useCallback(()=>{A&&_(!0)},[A]),ne=g.useCallback(()=>{A&&f.mutate({agentId:A}),_(!1),s()},[A,f,s]),fe=g.useCallback(ee=>{switch(ee){case"create-agent":J();return;case"connect-provider":ae();return;case"change-interface-language":O();return;case"new-chat":U();return;case"toggle-canvas":P();return;case"clear-conversation":z()}},[J,ae,O,U,P,z]),ue=g.useRef(null),le=g.useRef(void 0),q=g.useCallback(ee=>{switch(ee.target.type){case"path":s(),e(ee.target.path);return;case"session":{const{sessionId:de}=ee.target;s(),cp(e,de);return}case"command":fe(ee.target.command);return;case"draft":{const{kind:de,name:De}=ee.target;Ce.getState().stageDraft({kind:de,name:De}),s(),e("/chat");return}case"panel":{const{destination:de}=ee.target;u(de,ue.current),s(),yB(de)&&!t.pathname.startsWith("/chat")&&e("/chat");return}}},[s,e,t.pathname,u,fe]);g.useEffect(()=>{if(!n)return;const ee=document.activeElement;ue.current=ee instanceof HTMLElement?ee:null,le.current=E3()},[n]);const we=g.useCallback(()=>{const ee=ue.current,de=pQ({viewMoved:le.current!==E3(),capturedUsable:!!(ee?.isConnected&&ee!==document.body),caretUntouched:mQ(ee,document.activeElement,document.body)});if(!(de==="composer"&&gQ())&&de!=="leave"){if(de==="captured"&&ee){ee.focus();return}document.querySelector("[data-command-palette-trigger]")?.focus()}},[]);g.useEffect(()=>{n&&document.getElementById(fg)?.focus()},[n]),g.useEffect(()=>{b(0)},[E,n]);const B=g.useCallback(ee=>{if(w.current?.disconnect(),!ee?.parentElement)return;const de=ee.parentElement,De=()=>{const Se=getComputedStyle(de),ge=Number.parseFloat(Se.paddingTop)+Number.parseFloat(Se.paddingBottom);y(ee.offsetHeight+ge>de.clientHeight+1)};De();const Ue=new ResizeObserver(De);Ue.observe(de),Ue.observe(ee),w.current=Ue},[]);if(g.useEffect(()=>{b(ee=>ee>=V?Math.max(V-1,0):ee)},[V]),g.useEffect(()=>{if(!n)return;const ee=de=>{if(k||l||de.target?.id!==fg)return;const De=L.length,Ue=Fqe(de);if(Ue!==null)de.preventDefault(),b(Se=>Dqe(Se,De,Ue)??Se);else if(de.key==="Enter"){de.preventDefault();const Se=L[v];Se&&q(Se.item)}else de.key==="Escape"&&(de.preventDefault(),s())};return window.addEventListener("keydown",ee),()=>window.removeEventListener("keydown",ee)},[n,k,l,L,v,q,s]),g.useEffect(()=>{if(!n)return;const ee=L[v]?.item.id;ee&&document.getElementById(ee)?.scrollIntoView({block:"nearest",behavior:"auto"})},[n,L,v]),!n)return null;const be=j?.item,ie=!te||!X,Te=Pqe(navigator.platform.toUpperCase().indexOf("MAC")>=0);return c.jsxs(c.Fragment,{children:[c.jsx(Wl,{open:n,onOpenChange:ee=>{ee||s()},children:c.jsxs($l,{"data-tour-tag":"command-palette-dialog",showClose:!1,className:"z-[2300] w-160 max-w-[90vw] gap-0 overflow-hidden p-0",overlayClassName:"z-[2300]",onOpenAutoFocus:ee=>{ee.preventDefault();const de=document.getElementById(fg);de instanceof HTMLInputElement&&(de.focus(),de.setSelectionRange(de.value.length,de.value.length))},onCloseAutoFocus:ee=>{ee.preventDefault(),we()},children:[c.jsx(jo,{className:"sr-only",children:x("ui.command_palette.command_palette.command_palette")}),c.jsxs("div",{className:"flex h-13 shrink-0 items-center gap-3 border-hairline border-b px-4",children:[c.jsx(xd,{size:16,"aria-hidden":"true",className:"shrink-0 text-ink-dim"}),c.jsx("input",{id:fg,type:"text",role:"combobox","aria-expanded":X,"aria-controls":X?S3:void 0,"aria-activedescendant":be?.id,"aria-autocomplete":"list",autoComplete:"off",placeholder:x("ui.command_palette.command_palette.search_chats_settings_pages_and_actions"),value:p,onChange:ee=>m(ee.target.value),className:"min-w-0 flex-1 bg-transparent text-body text-ink outline-none! placeholder:text-ink-dim"}),re&&c.jsxs("span",{className:"flex shrink-0 items-center gap-0 text-ink-dim text-meta",children:[c.jsx(Er,{shortcut:re.glyph}),re.label]}),p&&c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":x("ui.command_palette.command_palette.clear_search"),onClick:()=>{m(""),document.getElementById(fg)?.focus()},children:c.jsx(Dn,{"aria-hidden":"true"})})]}),X?c.jsxs("div",{className:"relative",children:[C&&c.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 h-6 bg-gradient-to-t from-elevated to-transparent"}),c.jsxs("div",{role:"listbox",id:S3,"aria-label":x("ui.command_palette.command_palette.results"),tabIndex:-1,className:"max-h-96 overflow-y-auto p-2",children:[c.jsx("div",{ref:B,children:D.sections.map((ee,de)=>c.jsxs(g.Fragment,{children:[c.jsx("div",{role:"presentation",className:T("px-2 pb-1 text-ink-dim text-meta",de===0?"pt-1":"pt-3"),children:NVe[ee.group]}),ee.items.map(De=>c.jsx(Yqe,{match:De,isActive:De.item.id===be?.id,onHover:()=>b(L.indexOf(De)),onRun:()=>q(De.item)},De.item.id))]},ee.group))}),C&&c.jsx("div",{"aria-hidden":"true",className:"h-6"})]})]}):c.jsxs("div",{className:"flex flex-col items-center gap-1 px-6 py-10 text-center",children:[c.jsx("p",{className:"text-body-sm text-ink",children:G.line}),G.hint!==null&&c.jsx("p",{className:"text-ink-dim text-meta",children:G.hint})]}),X&&te&&M.awaiting&&c.jsx("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:x("ui.command_palette.command_palette.searching_conversations")}),te&&M.overLong&&c.jsxs("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:[x("ui.command_palette.command_palette.search_terms_are_limited_to"),lC,x("ui.command_palette.command_palette.characters_so_chats_are_matched_by_name")]}),te&&!M.overLong&&M.unavailable&&!M.pending&&c.jsx("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:M.unreachable?x("ui.command_palette.command_palette.conversation_search_is_unavailable_while_the_backend_is_unreachab"):x("ui.command_palette.command_palette.chats_are_matched_by_name_update_local_operator_to_search_inside_")}),c.jsx("div",{className:"flex shrink-0 items-center gap-4 border-hairline border-t px-4 py-2 text-ink-dim text-meta",children:ie?c.jsxs(c.Fragment,{children:[Tk.map(ee=>c.jsxs("span",{className:"flex items-center gap-0",children:[c.jsx(Er,{shortcut:ee.glyph}),ee.label]},ee.scope)),c.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"esc"}),x("ui.command_palette.command_palette.to_close")]})]}):c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"↑"}),c.jsx(Er,{shortcut:"↓"}),Te.map(ee=>c.jsx(Er,{shortcut:ee,joined:!0},ee)),x("ui.command_palette.command_palette.to_move")]}),c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"↵"}),x("ui.command_palette.command_palette.to_run")]}),c.jsx("span",{className:"flex items-center gap-1.5",children:D.clipped&&c.jsx("span",{children:te?x("ui.command_palette.matches.best",{countText:String(V),total:D.total,totalText:String(D.total)}):x("ui.command_palette.matches.showing",{count:String(V),total:String(D.total)})})}),c.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[c.jsx(Er,{shortcut:"esc"}),x("ui.command_palette.command_palette.to_close")]})]})})]})}),c.jsx(au,{open:k,title:x("ui.command_palette.command_palette.clear_this_conversation"),message:x("ui.command_palette.command_palette.every_message_in_it_is_deleted_from_this_computer_and_there_is_no"),confirmText:x("ui.command_palette.command_palette.clear"),cancelText:x("ui.common.actions.cancel"),isDangerous:!0,onConfirm:ne,onCancel:()=>_(!1)})]})},Yqe=({match:e,isActive:t,onHover:n,onRun:s})=>{const{item:r,soft:i}=e,a=r.verb??zqe[r.kind];return c.jsxs("button",{id:r.id,type:"button",role:"option","aria-selected":t,tabIndex:-1,onClick:s,onMouseMove:n,className:T("flex h-9 w-full items-center gap-3 rounded-sm px-2 text-left","transition-colors duration-fast ease-out-quart",t?"bg-sunken outline-solid outline-1 -outline-offset-1 outline-control":"bg-transparent"),children:[c.jsx("span",{className:T("flex size-4 shrink-0 items-center justify-center",r.destructive?"text-danger":"text-ink-dim"),children:c.jsx($qe,{name:r.icon})}),c.jsx("span",{className:T("shrink-0 truncate text-body-sm",r.destructive?"text-danger":i&&!t?"text-ink-muted":"text-ink"),children:r.name}),r.hint&&c.jsx("span",{className:"min-w-0 flex-1 truncate text-ink-dim text-meta",children:r.hint}),!r.hint&&c.jsx("span",{className:"flex-1"}),t&&c.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-ink-dim text-meta",children:[a,c.jsx(Er,{shortcut:"↵"})]})]})},Xqe="toggle-command-palette",Qqe="toggle-command-palette-commands";function B1(e){const t=qe.getState(),n=Rqe(e,{open:t.isCommandPaletteOpen,query:t.commandPaletteQuery});n.action==="open"?t.toggleCommandPalette(n.query):n.action==="close"?t.closeCommandPalette():t.setCommandPaletteQuery(n.query)}function Jqe(){g.useEffect(()=>{const e=t=>{const n=kqe(t);n&&(t.preventDefault(),B1(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),g.useEffect(()=>{const e=window.electron.ipcRenderer.on(Xqe,()=>B1("everything")),t=window.electron.ipcRenderer.on(Qqe,()=>B1("commands"));return()=>{e?.(),t?.()}},[])}const Zqe=({enabled:e})=>{const t=ZT(e),n=ehe(e&&t==="member",{poll:!0,stamp:()=>Ce.getState().beginAnswer()}),s=Ce(r=>r.settlePeerCatalogue);return g.useEffect(()=>{n.data&&s(n.data.rows.map(ode),n.data.requestedAt)},[n.data,s]),null},eKe={single:"max-w-[min(40rem,calc(100vw-4rem))]"},tKe=({open:e,title:t,stepIndicators:n,children:s,actions:r,width:i="single",className:a,onDismiss:o})=>{const l=g.useRef(null);return c.jsx(Wl,{open:e,onOpenChange:u=>{u||o?.()},children:c.jsxs($l,{"data-onboarding-modal":"",showClose:o!==void 0,onEscapeKeyDown:u=>{o||u.preventDefault()},onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),onOpenAutoFocus:u=>{u.preventDefault(),l.current?.focus()},className:T("max-h-[calc(100vh-4rem)] gap-0 overflow-hidden p-0",eKe[i],a),children:[(t||n)&&c.jsxs("div",{className:T("flex shrink-0 items-center justify-between gap-4 border-hairline border-b px-6 py-4",o&&"pr-14"),children:[t?c.jsx(jo,{className:"text-title",children:t}):c.jsx(jo,{className:"sr-only",children:x("ui.onboarding.dialog.setup")}),n]}),c.jsx("div",{ref:l,tabIndex:-1,className:"min-h-0 flex-1 overflow-y-auto px-6 py-6 outline-none!",children:s}),r&&c.jsx("div",{className:"shrink-0 border-hairline border-t px-6 py-4",children:r})]})})};function nKe(e,t,n=!1){const s=e===kr.DEFAULT_MODEL&&t!==null;return{blocked:s,reason:s?t:null,primaryDisabled:n||s}}const Zb=({value:e,label:t,variant:n="ghost",onCopied:s})=>{Et();const[r,i]=g.useState(!1);return g.useEffect(()=>{if(!r)return;const a=setTimeout(()=>i(!1),2e3);return()=>clearTimeout(a)},[r]),c.jsxs(ce,{variant:n,size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(e),i(!0),s?.()}catch{zt(x("ui.common.actions.copy_failed"))}},children:[r?c.jsx(Bs,{"aria-hidden":"true"}):c.jsx(Gl,{"aria-hidden":"true"}),r?x("ui.common.actions.copied"):t]})},sKe=3e3,Sh={all:["desktop","tunnel","setup"],local:e=>["desktop","tunnel","setup","local",e],fresh:e=>["desktop","tunnel","setup","fresh",e]};function xb(e,t){if(e instanceof Hi){const n=e.code;if(n==="setup_in_progress")return"in-progress";if(n!==void 0&&n!=="setup_intent_corrupt"&&LZ.has(n))return{kind:"backend",message:e.message,code:n};if(t==="run"&&(e.status===null||n===oC.transportFailed||n===QB))return"unconfirmed"}return{kind:"generic",during:t}}function rKe(e){if(!e.enabled)return{kind:"hidden"};if(e.runPending||e.local?.in_progress){const t=e.local?.progress??[];return{kind:"applying",progress:t,setup:e.runPending||t.length>1,account:e.fresh&&(e.runPending||e.local?.active_credential_id===e.fresh.credential_id)?e.fresh:void 0}}return e.failure?{kind:"failure",failure:e.failure}:e.fresh?{kind:"result",result:e.fresh}:e.freshErrored?{kind:"failure",failure:{kind:"generic",during:"check"}}:{kind:"checking"}}const j1=e=>OZ.parse(e);function iKe(){const e=nn(),t=Bn(),n=yt(t.data,"tunnel_setup"),[s,r]=g.useState(null),[i,a]=g.useState(null),[o,l]=g.useState(!1),u=g.useRef(0),d=g.useRef(!1),h=g.useRef(!1),f=g.useRef(!1),p=Kn({retry:!1,mutationFn:async N=>j1(await xt({op:"tunnel.setup.run",credentialId:N.credentialId,acceptMonthlyPrice:N.price})),onSuccess:N=>{f.current=h.current,a(null),e.setQueryData(Sh.fresh(s),N)},onError:N=>{const M=xb(N,"run");M==="unconfirmed"?(u.current=Date.now(),l(!0)):M!=="in-progress"&&a(M)},onSettled:(N,M)=>{d.current=M!==null&&xb(M,"run")==="unconfirmed",e.invalidateQueries({queryKey:Sh.local(s)})}}),m=p.isPending||o,v=fs({queryKey:Sh.local(s),queryFn:async()=>j1(await xt({op:"tunnel.setup.read",credentialId:s??void 0})),enabled:n,retry:!1,staleTime:0,refetchOnWindowFocus:!1,refetchInterval:N=>m||N.state.data?.in_progress?sKe:!1}),b=v.data,w=b?.in_progress===!0||m,C=fs({queryKey:Sh.fresh(s),queryFn:async()=>{try{return j1(await xt({op:"tunnel.setup.plan",credentialId:s??void 0}))}catch(N){throw xb(N,"check")==="in-progress"&&e.invalidateQueries({queryKey:Sh.local(s)}),N}},enabled:n&&v.isSuccess&&!w,retry:!1,staleTime:Number.POSITIVE_INFINITY,gcTime:0,refetchOnWindowFocus:!1,refetchOnMount:"always"}),y=g.useRef(Date.now()),k=C.data&&C.dataUpdatedAt>=y.current?C.data:void 0,_=b?.in_progress===!0;g.useEffect(()=>{h.current&&!_&&(f.current?f.current=!1:d.current||C.refetch()),h.current=_},[_,C.refetch]),g.useEffect(()=>{o&&b&&!b.in_progress&&v.dataUpdatedAt>u.current&&(l(!1),d.current=!1,e.resetQueries({queryKey:Sh.fresh(s)}))},[o,b,v.dataUpdatedAt,e,s]),g.useEffect(()=>{const N=v.error??C.error;if(!N)return;const M=xb(N,"check");M!=="in-progress"&&M!=="unconfirmed"&&a(M)},[v.error,C.error]);const E=rKe({enabled:n,local:b,fresh:k,failure:i,runPending:m,freshErrored:C.isError&&!k}),R=g.useCallback(N=>{a(null),r(N)},[]),F=g.useCallback(()=>{a(null),v.refetch(),C.refetch()},[v.refetch,C.refetch]),A=g.useCallback((N,M)=>{d.current||(d.current=!0,f.current=!1,a(null),p.mutate({credentialId:N,price:M}))},[p.mutate]);return{view:E,selectedId:s,choose:R,check:F,run:A}}const vm=({status:e})=>c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e==="connected"?c.jsx(pT,{size:20,className:"shrink-0 text-success","aria-hidden":"true"}):null,c.jsx("h4",{className:"text-heading text-ink",children:x("ui.providers.phone.heading")}),e==="checking"?c.jsxs("span",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{children:x("ui.providers.phone.status.checking")})]}):null,e==="applying"?c.jsxs("span",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{children:x("ui.providers.phone.status.applying")})]}):null,e==="connected"?c.jsx("output",{className:"text-body-sm text-success",children:x("ui.providers.phone.status.connected")}):null]}),eA=({result:e})=>{if(e.credential_id===null)return null;const t=String(e.credential_id);return c.jsx("p",{className:"break-words text-body-sm text-ink-muted",children:e.identity_label?x("ui.providers.phone.account",{identity:e.identity_label,id:t}):x("ui.providers.phone.account_unlabeled",{id:t})})},Pw=({heading:e,lines:t})=>t.length===0?null:c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("p",{className:"text-meta text-ink-dim",children:e}),c.jsx("ul",{className:"flex list-none flex-col gap-1 p-0",children:t.map((n,s)=>c.jsx("li",{className:"break-words text-body-sm text-ink",children:n},s))})]}),aKe=e=>{const t={not_activated:"ui.providers.phone.outcome.billing_not_activated",already_active:"ui.providers.phone.outcome.billing_already_active",activated:"ui.providers.phone.outcome.billing_activated_status",unconfirmed:"ui.providers.phone.outcome.billing_unconfirmed"},n={saved:"ui.providers.phone.outcome.reservation_saved",existing:"ui.providers.phone.outcome.reservation_existing",unconfirmed:"ui.providers.phone.outcome.reservation_unconfirmed"},s={billing:"ui.providers.phone.outcome.stage_billing",reservation:"ui.providers.phone.outcome.stage_reservation",configuration:"ui.providers.phone.outcome.stage_configuration",installation:"ui.providers.phone.outcome.stage_installation",verification:"ui.providers.phone.outcome.stage_verification",prerequisites:"ui.providers.phone.outcome.stage_prerequisites"},r=[],i=t[e.billing_outcome],a=n[e.reservation_outcome],o=s[e.failure_stage];return i&&r.push(x(i)),a&&r.push(x(a)),o&&r.push(x("ui.providers.phone.outcome.failure_stage",{stage:x(o)})),r},oKe=({failure:e,onCheck:t})=>c.jsxs("div",{className:"flex flex-col items-start gap-3",children:[c.jsx("p",{role:"alert",className:"break-words text-body-sm text-ink",children:e.kind==="backend"?e.message:e.during==="run"?x("ui.providers.phone.failure.run"):x("ui.providers.phone.failure.check")}),c.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:x("ui.providers.phone.action.check_again")})]}),lKe=({result:e})=>c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"verified","data-phone-verified":"true",children:[c.jsx(vm,{status:"connected"}),c.jsx(eA,{result:e}),e.url?c.jsxs("div",{className:"flex flex-col items-start gap-2",children:[c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.providers.phone.address_label")}),c.jsx("code",{className:"break-all text-ink text-mono-sm",children:e.url}),c.jsx(Zb,{value:e.url,label:x("ui.providers.phone.action.copy_address"),variant:"secondary"})]}):null,c.jsx("p",{className:"break-words text-body-sm text-ink-muted",children:x("ui.providers.phone.use_address")}),c.jsx(Pw,{heading:x("ui.providers.phone.receipts_heading"),lines:e.receipts.map(t=>t.text)})]}),cKe=({onDone:e})=>{const{issue:t,start:n,cancel:s}=vQ(),r=t.kind==="signing-in"||t.kind==="input-required",i=g.useRef(!1);return g.useEffect(()=>{i.current&&!r&&e(),i.current=r},[r,e]),r?c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{className:"text-body-sm text-ink-muted",children:x("ui.providers.phone.signing_in")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:x("ui.providers.phone.action.cancel")})]}):c.jsxs(ce,{variant:"primary",size:"sm",onClick:n,children:[x("ui.providers.phone.action.sign_in"),c.jsx(xl,{"aria-hidden":"true"})]})},uKe=({result:e,setup:t,offerSignIn:n})=>{const s=e.remedy?.kind??null,r=e.credential_id,i=e.quote?.monthly_price_usd??null,a=c.jsx(ce,{variant:"secondary",size:"sm",onClick:t.check,children:x("ui.providers.phone.action.check_again")}),o=s==="accept_quote"&&e.ready&&r!==null&&i!==null,l=s==="run"&&e.ready&&r!==null;let u=a,d=null;return o&&r!==null&&i!==null?(u=c.jsx(ce,{variant:"primary",size:"sm",onClick:()=>t.run(r,i),children:x("ui.providers.phone.action.activate",{amount:i})}),d=a):l&&r!==null?(u=c.jsx(ce,{variant:"primary",size:"sm",onClick:()=>t.run(r),children:x("ui.providers.phone.action.set_up")}),d=a):s==="sign_in"&&n&&(u=c.jsx(cKe,{onDone:t.check}),d=a),c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":e.blocked_on,"data-remedy-kind":s??"none",children:[c.jsx(vm,{}),c.jsx(eA,{result:e}),s==="choose_account"?c.jsxs("div",{className:"flex flex-col items-start gap-2",children:[c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.providers.phone.choose_heading")}),e.credential_choices.map(h=>c.jsx(ce,{variant:"secondary",size:"sm",onClick:()=>t.choose(h.id),children:h.identity_label?x("ui.providers.phone.action.choose",{identity:h.identity_label,id:String(h.id)}):x("ui.providers.phone.action.choose_unlabeled",{id:String(h.id)})},h.id))]}):null,e.remedy?c.jsx("p",{className:"break-words text-body-sm text-ink",children:e.remedy.text}):null,o&&i!==null?c.jsx("p",{className:"break-words text-body-sm text-ink",children:x("ui.providers.phone.consent",{amount:i})}):null,c.jsx(Pw,{heading:x("ui.providers.phone.progress_heading"),lines:aKe(e)}),c.jsx(Pw,{heading:x("ui.providers.phone.receipts_heading"),lines:e.receipts.map(h=>h.text)}),s==="choose_account"?null:c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[u,d]})]})},dKe=({offerSignIn:e})=>{const t=iKe(),{view:n}=t;return n.kind==="hidden"?null:c.jsxs("section",{className:"flex flex-col gap-3 border-hairline border-t pt-4","aria-label":x("ui.providers.phone.heading"),"data-phone-block":n.kind,children:[n.kind==="checking"?c.jsx("div",{className:"flex flex-col gap-3","data-phone-state":"checking",children:c.jsx(vm,{status:"checking"})}):null,n.kind==="applying"?c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"applying",children:[c.jsx(vm,{status:n.setup?"applying":"checking"}),n.account?c.jsx(eA,{result:n.account}):null,c.jsx(Pw,{heading:x("ui.providers.phone.progress_heading"),lines:n.progress})]}):null,n.kind==="failure"?c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"failure",children:[c.jsx(vm,{}),c.jsx(oKe,{failure:n.failure,onCheck:t.check})]}):null,n.kind==="result"&&n.result.verified?c.jsx(lKe,{result:n.result}):null,n.kind==="result"&&!n.result.verified?c.jsx(uKe,{result:n.result,setup:t,offerSignIn:e}):null]})},hKe=({offerSignIn:e=!1})=>{const t=Bn();return yt(t.data,"tunnel_setup")?c.jsx(dKe,{offerSignIn:e}):null},bm={phase:"idle",operation:null,opened:!1,openFailed:!1,error:null};let vo=null;const fKe=[[/^Sign-in complete\.?$/,"succeeded"],[/^Sign-in cancelled\.?$/,"cancelled"],[/^Replaced by a new sign-in\.?$/,"cancelled"],[/^Sign-in expired\b/,"expired"],[/^Sign-in failed\b/,"failed"]];function H1(e){if(bc(e.state))return e;for(const[t,n]of fKe)if(t.test(e.message))return{...e,state:n};return e.state!=="starting"&&e.expires_in<=0?{...e,state:"expired"}:e}function pKe(e,t){return{id:e,provider:t,state:"expired",message:"This sign-in is no longer available. Start again.",auth_url:null,instructions:null,input_required:!1,prompt_id:null,expires_in:0}}function k3(e,t){return e instanceof Error&&e.message?e.message:t}function gKe(e){let t=bm,n=null,s=null,r=0,i=!1;const a=f=>{t={...t,...f},i||e.onChange(t)},o=()=>{n?.(),n=null},l=async(f,p)=>{const m=f.auth_url;if(!m||FB(f))return;const v=`${f.id}|${m}`;if(s!==v){s=v;try{await e.open(f.id,!1),p===r&&a({opened:!0,openFailed:!1})}catch{p===r&&a({opened:!1,openFailed:!0})}}},u=(f,p)=>{if(p!==r)return;const m=H1(f),v=s!==null&&s===`${m.id}|${m.auth_url}`;if(bc(m.state)){o(),vo?.id===m.id&&(vo=null),a({phase:"settled",operation:m,opened:v&&t.opened}),m.state==="succeeded"&&e.onSucceeded?.(m);return}a({phase:"active",operation:m,opened:v?t.opened:!1}),l(m,p)},d=(f,p)=>{u(f,p),!(bc(H1(f).state)||p!==r)&&(o(),n=e.poll(f.id,m=>u(m,p),{onGone:()=>{p===r&&(n=null,vo?.id===f.id&&(vo=null),a({phase:"settled",operation:pKe(f.id,f.provider)}))}}))},h=async(f,p)=>{const m=vo;if(!m)return!1;let v=null;try{v=await e.read(m.id)}catch{v=null}if(p!==r)return!0;if(v&&!bc(v.state)&&m.provider===f)return d(v,p),!0;if(v&&!bc(v.state))try{await e.cancel(m.id)}catch{}if(vo=null,p!==r)return!0;const b=await e.start(f);return vo={id:b.id,provider:f},d(b,p),!0};return{async start(f){r+=1;const p=r;o();const m=t.operation;if(s=null,a({phase:"starting",operation:null,opened:!1,openFailed:!1,error:null}),m&&!bc(m.state)){try{await e.cancel(m.id)}catch{}if(p!==r)return}try{const v=await e.start(f);vo={id:v.id,provider:f},d(v,p)}catch(v){if(p!==r)return;if(v instanceof Hi&&v.status===409)try{if(await h(f,p))return}catch(b){if(p!==r)return;a({phase:"settled",error:k3(b,x("ui.providers.sign_in_flow.sign_in_could_not_start"))});return}a({phase:"settled",error:k3(v,x("ui.providers.sign_in_flow.sign_in_could_not_start"))})}},async cancel(){const f=t.operation;if(r+=1,o(),s=null,a({...bm}),!(!f||bc(f.state))){vo?.id===f.id&&(vo=null);try{await e.cancel(f.id)}catch{}}},async reopen(){const f=t.operation;if(!f?.auth_url)return;const p=r;try{await e.open(f.id,!0),s=`${f.id}|${f.auth_url}`,p===r&&a({opened:!0,openFailed:!1})}catch{p===r&&a({openFailed:!0})}},pause(){r+=1,o()},resume(){const f=t.operation;f&&(bc(H1(f).state)||(r+=1,d(f,r)))},reset(){r+=1,o(),s=null,a({...bm})},dispose(){i=!0,r+=1,o()},getState:()=>t}}const Pk=new Map,tA=new Map;function Mg(e){return tA.get(e)??{saved:null,error:null}}function mKe(e,t){tA.set(e,{...Mg(e),...t})}function vKe(e){tA.delete(e)}function bKe(e){return Pk.get(e)?.state??bm}function T3(e,t,n,s){const i=Pk.get(e)??(()=>{const a={flow:null,state:bm,listeners:new Set,deps:t};return a.flow=gKe({start:o=>a.deps.start(o),read:o=>a.deps.read(o),cancel:o=>a.deps.cancel(o),open:(o,l)=>a.deps.open(o,l),poll:(o,l,u)=>a.deps.poll(o,l,u),onChange:o=>{a.state=o;for(const l of a.listeners)l(o)},onSucceeded:o=>a.deps.onSucceeded?.(o)}),Pk.set(e,a),a})();return i.deps={...t,onSucceeded:t.onSucceeded},i.listeners.add(n),{flow:i.flow,getState:()=>i.state,setDeps:a=>{i.deps={...a,onSucceeded:a.onSucceeded}},resume:()=>i.flow.resume(),detach:()=>{i.listeners.delete(n),i.flow.pause()}}}function xKe(e,t){const n=g.useRef(t);n.current=t;const[s,r]=g.useState(()=>bKe(e)),[i,a]=g.useState(()=>T3(e,n.current(),r)),o=g.useRef(e);return g.useEffect(()=>{if(o.current===e)return;i.detach();const l=T3(e,n.current(),r);o.current=e,a(l),r(l.getState()),l.resume()},[e,i]),g.useEffect(()=>(i.setDeps(n.current()),r(i.getState()),i.resume(),()=>i.detach()),[i]),{flow:i.flow,state:s}}const wKe=({provider:e})=>{Et();const[t,n]=g.useState(!1),[s,r]=g.useState(null),i=g.useCallback(async()=>{n(!0);try{r(await xt({op:"auth.probe",provider:e.id}))}catch(o){r({reachable:!1,detail:o instanceof Error?o.message:x("ui.providers.provider_detail.the_connection_could_not_be_tested")})}finally{n(!1)}},[e.id]);g.useEffect(()=>{r(null),i()},[i]);const a=Ri(e);return c.jsxs("div",{className:"flex flex-col items-start gap-2",children:[s===null?c.jsxs("p",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{size:"sm"}),x("ui.providers.provider_detail.checking_whether"),a," ",x("ui.providers.provider_detail.is_running")]}):s.reachable?c.jsxs("p",{className:"text-body-sm text-success",children:[a," ",x("ui.providers.provider_detail.is_running")]}):c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[a," ",x("ui.providers.provider_detail.isn_t_answering"),e.base_url?c.jsxs(c.Fragment,{children:[x("ui.providers.provider_detail.at"),c.jsx("span",{className:"font-mono",children:e.base_url})]}):null]}),c.jsx(ce,{variant:"secondary",size:"sm",onClick:()=>void i(),disabled:t,children:t?x("ui.providers.provider_detail.checking"):x("ui.providers.provider_detail.check_again")})]})},R3=({id:e,value:t,onChange:n,label:s,invalid:r,describedBy:i})=>{Et();const[a,o]=g.useState(!1);return c.jsxs("div",{className:"relative",children:[c.jsx(ps,{id:e,type:a?"text":"password",value:t,onChange:l=>n(l.target.value),autoComplete:"off",spellCheck:!1,"aria-label":s,"aria-invalid":r||void 0,"aria-describedby":i,className:"pr-10 font-mono"}),c.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",className:"absolute top-1/2 right-1 -translate-y-1/2",onClick:()=>o(l=>!l),"aria-label":a?x("ui.providers.provider_detail.hide_key"):x("ui.providers.provider_detail.show_key"),children:a?c.jsx(ase,{"aria-hidden":"true"}):c.jsx(lse,{"aria-hidden":"true"})})]})},CKe=/[.!?]$/,yKe=e=>CKe.test(e.trim())?e:`${e}.`,A3=({brand:e,verb:t,defaults:n,unverified:s,onChangeModel:r,actionLabel:i,onAction:a,primaryAction:o,headline:l,tone:u="success",verdict:d})=>{Et();const h=d?.group==="Needs sign-in",f=g.useRef(null);return g.useEffect(()=>{f.current?.focus()},[]),c.jsxs("div",{className:"flex flex-col gap-3","data-sign-in-state":"succeeded","data-verdict":h?d.tone:void 0,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[h&&d?c.jsx(Qa,{size:20,className:d.tone==="attention"?"text-warning":"text-ink-muted","aria-hidden":"true"}):c.jsx(pT,{size:20,className:u==="unchecked"?"text-ink-muted":"text-success","aria-hidden":"true"}),c.jsx("output",{className:"text-heading text-ink",children:h&&d?d.label:l??(t==="Connected"?x("ui.providers.provider_detail.connected_variant_163",{brand:e}):x("ui.providers.provider_detail.signed_in_to_variant_164",{brand:e}))})]}),h&&d?c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[yKe(d.detail??(d.tone==="attention"?x("ui.providers.provider_detail.is_no_longer_accepting_the_sign_in",{brand:e}):x("ui.providers.provider_detail.this_app_could_not_confirm_the_sign",{brand:e})))," ",x("ui.providers.provider_detail.the_sign_in_itself_finished_what_follows")]}):null,n?.receipt||n?.model_name?c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[n.receipt,!n.receipt&&n.model_name?c.jsxs(c.Fragment,{children:[x("ui.providers.provider_detail.default_model")," ",c.jsx("span",{className:"text-ink",children:n.model_name}),"."]}):null,r?c.jsxs(c.Fragment,{children:[" ",c.jsx(ce,{variant:"link",size:"sm",onClick:r,children:x("ui.providers.provider_detail.change")})]}):null]}):null,n&&!n.hosting&&n.receipt?c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.providers.provider_detail.your_default_model_is_unchanged")}):null,s?c.jsxs("p",{className:u==="unchecked"?"text-body-sm text-ink-muted":"text-ink-dim text-meta",children:[x("ui.providers.provider_detail.saved_but_not_checked_yet"),s]}):null,c.jsx("div",{children:c.jsx(ce,{ref:f,variant:o?"primary":"secondary",size:"sm",onClick:a,children:i})})]})},_Ke=({provider:e,onConnected:t,onDone:n,onChangeModel:s,context:r="settings",readiness:i})=>{Et();const a=nn(),o=DB({retryOnMount:!1}),{accountRead:l,unavailable:u}=Vk({retryOnMount:!1}),d=PB(e.id,o,{accountRead:l,unavailable:u}),h=i!==void 0?i:d===null?null:hT(e,d),[f,p]=g.useState(null),[m,v]=g.useState(""),[b,w]=g.useState(!1),[C,y]=g.useState(()=>Mg(e.id).error),[k,_]=g.useState(()=>Mg(e.id).saved),E=g.useCallback(ee=>{"saved"in ee&&_(ee.saved??null),"error"in ee&&y(ee.error??null),mKe(e.id,ee)},[e.id]),[R,F]=g.useState(""),[A,N]=g.useState(null),M=Ri(e),D=e.auth_methods.find(ee=>ee.method_id===f)??bQ(e.auth_methods),L=g.useCallback(()=>{a.invalidateQueries({queryKey:Bo.providers}),a.invalidateQueries({queryKey:Bo.catalogue}),e.id==="radient"&&xQ(a),a.invalidateQueries({queryKey:["config"]}),a.invalidateQueries({queryKey:wQ}),t?.()},[a,t,e.id]),V=Jj(),j=g.useCallback(async(ee,de,De)=>{const Ue=async()=>{await a.invalidateQueries({queryKey:["config"]}),await a.invalidateQueries({queryKey:["desktop","session-preview"]})};try{if(de!==void 0){await Ue();return}const Se=await xt({op:"config.get"});if(await Ue(),Se?.values?.hosting)return;let ge=Fk(ee);if(ge.length===0&&(await td.getState().fetchModels(Ss.baseUrl,!0),ge=Fk(ee)),ge.length===0)return;const Ae=(De||"").trim()||ge.find(st=>st.recommended)?.id||ge[0].id;await V.mutateAsync({hosting:ee,model_name:Ae}),await Ue()}catch{}},[a,V]),te=g.useRef(j);te.current=j;const X=g.useRef(L);X.current=L;const{flow:re,state:G}=xKe(e.id,()=>({start:ee=>xt({op:"auth.start",provider:ee}),read:ee=>xt({op:"auth.status",id:ee}),cancel:ee=>xt({op:"auth.cancel",id:ee}),open:(ee,de)=>RQ(ee,de),poll:TQ,onSucceeded:ee=>{X.current(),te.current(e.id,ee.defaults_applied,e.suggested_model?.id)}})),J=g.useRef(null);g.useEffect(()=>{const ee=J.current!==null,de=J.current!==e.id;J.current=e.id,ee&&de&&(p(null),v(""),y(Mg(e.id).error),_(Mg(e.id).saved))},[e.id]);const ae=ee=>{p(ee),E({error:null}),_(null),re.reset()},O=g.useCallback(async()=>{const ee=G.operation;if(!(!ee?.prompt_id||!R)){N(null);try{await xt({op:"auth.input",id:ee.id,promptId:ee.prompt_id,value:R}),F("")}catch(de){N(de instanceof Error?de.message:x("ui.providers.provider_detail.the_code_was_not_accepted"))}}},[G.operation,R]),U=g.useCallback(async()=>{if(!(!D||!m.trim())){w(!0),E({error:null});try{const ee=await xt({op:"auth.key",provider:D.id,value:m.trim()})??{};v(""),E({saved:ee}),L(),te.current(e.id,ee?.defaults_applied,e.suggested_model?.id)}catch(ee){E({error:ee instanceof Hi||ee instanceof Error?ee.message:x("ui.providers.provider_detail.the_key_could_not_be_saved")})}finally{w(!1)}}},[D,m,L,E,e.id,e.suggested_model?.id]),P=r==="dialog"?x("ui.providers.provider_detail.continue"):x("ui.providers.provider_detail.done"),z=()=>{vKe(e.id),_(null),re.reset(),n?.()};if(e.local)return c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[x("ui.providers.provider_detail.runs_on_this_computer_and_needs_no"),M,x("ui.providers.provider_detail.then_check_the_connection")]}),c.jsx(wKe,{provider:e})]});if(!D)return c.jsx(Kr,{variant:"warning",children:x("ui.providers.provider_detail.this_provider_has_no_supported_sign_in")});const ne=e.auth_methods.find(ee=>ee.kind==="api_key"),fe=G.operation,ue=`key-help-${e.id}`,le=e.auth_methods.length>1&&G.phase!=="settled"?c.jsx(GB,{value:D.method_id,onValueChange:ae,children:c.jsx(VB,{"aria-label":x("ui.providers.provider_detail.how_to_connect"),children:e.auth_methods.map(ee=>c.jsx(aS,{value:ee.method_id,children:CQ(ee)},ee.method_id))})}):null;if(D.kind==="api_key")return k?c.jsxs("div",{className:"flex flex-col gap-4",children:[le,c.jsx(A3,{brand:M,verb:"Connected",defaults:k.defaults_applied,unverified:k.valid===!0?null:k.reason??x("ui.providers.provider_detail.this_local_operator_does_not_check_keys"),tone:k.valid===!0?"success":"unchecked",headline:k.valid===!0?void 0:x("ui.providers.provider_detail.key_saved",{brand:M}),onChangeModel:s,actionLabel:P,onAction:z,primaryAction:r==="dialog",verdict:h})]}):c.jsxs("div",{className:"flex flex-col gap-4",children:[le,c.jsxs("div",{className:"flex flex-col gap-2","data-sign-in-state":"api-key",children:[c.jsx(nr,{htmlFor:`key-${e.id}`,children:x("ui.providers.provider_catalog.api_key")}),c.jsx(R3,{id:`key-${e.id}`,value:m,onChange:ee=>{v(ee),E({error:null})},label:x("ui.providers.provider_detail.api_key_variant_215",{brand:M}),invalid:C!==null,describedBy:ue}),c.jsx("p",{id:ue,className:C?"text-danger text-meta":"text-ink-dim text-meta",role:C?"alert":void 0,children:C??(e.has_credential?x("ui.providers.provider_detail.a_key_is_saved_paste_a_new",{brand:M}):x("ui.providers.provider_detail.stored_encrypted_on_this_computer_billed_per",{brand:M}))}),c.jsx("div",{children:c.jsxs(ce,{variant:"primary",size:"sm",disabled:!m.trim()||b,onClick:()=>void U(),children:[b?c.jsx(pn,{size:"sm"}):null,b?x("ui.providers.provider_detail.checking_key"):x("ui.providers.provider_detail.save_key")]})})]})]});const q=()=>void re.start(D.id),we=yQ(fe?.auth_url),B=fe?FB(fe):null,be=fe?_Q(fe.expires_in):null,ie=fe?.input_optional??(D.paste_fallback&&!D.requires_secret_input);let Te;if(G.phase==="idle")Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"idle",children:[e.configured&&h?.group==="Needs sign-in"?c.jsxs(Kr,{variant:h.tone==="attention"?"warning":"neutral",children:[c.jsx(FF,{children:h.label}),c.jsx(DF,{children:h.detail??x("ui.providers.provider_detail.is_no_longer_accepting_the_sign_in",{brand:M})})]}):null,c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[SQ(D,e)," ",D.kind==="device"?x("ui.providers.provider_detail.you_ll_get_a_code_to_enter"):x("ui.providers.provider_detail.it_opens_in_your_browser")]}),c.jsx("div",{className:"flex items-center gap-2",children:c.jsxs(ce,{variant:"primary",size:"sm",onClick:q,children:[D.kind==="device"?x("ui.providers.provider_detail.get_a_sign_in_code"):x("ui.providers.provider_detail.continue_in_browser"),D.kind==="device"?null:c.jsx(xl,{"aria-hidden":"true"})]})})]});else if(G.phase==="starting"||G.phase==="active"&&fe&&!fe.auth_url&&!B&&!(fe.input_required&&!ie))Te=c.jsxs("div",{className:"flex items-center gap-3","data-sign-in-state":"starting",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{className:"text-body-sm text-ink-muted",children:D.kind==="device"?x("ui.providers.provider_detail.getting_a_code"):x("ui.providers.provider_detail.opening_your_browser")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]});else if(G.phase==="active"&&fe&&B){const ee=fe.auth_url;Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"device-code",children:[c.jsx("p",{className:"whitespace-pre-line text-body-sm text-ink-muted",children:fe.instructions?.trim()||c.jsxs(c.Fragment,{children:[x("ui.providers.provider_detail.enter_this_code"),we?x("ui.providers.provider_detail.at_variant_248",{host:we}):x("ui.providers.provider_detail.on_the_sign_in_page"),x("ui.providers.provider_detail.this_page_updates_on_its_own_once")]})}),c.jsx("div",{className:"flex items-center gap-3 rounded-md bg-sunken p-3",children:c.jsx("code",{className:"font-mono text-ink text-title tracking-wider",children:B})}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx(Zb,{value:B,label:ee?x("ui.providers.provider_detail.copy_code_and_open_page"):x("ui.providers.provider_detail.copy_code"),variant:"primary",onCopied:()=>{ee&&re.reopen()}}),ee?c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void re.reopen(),children:[c.jsx(xl,{"aria-hidden":"true"}),G.opened?x("ui.providers.provider_detail.open_browser_again"):x("ui.providers.provider_detail.open_sign_in_page")]}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]}),be?c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.providers.provider_detail.code_expiry",{minutes:be})}):null]})}else if(G.phase==="active"&&fe){const ee=de=>fe.input_required?c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx(nr,{htmlFor:`prompt-${fe.id}`,children:we?x("ui.providers.provider_detail.code_from",{host:we}):x("ui.providers.provider_detail.code_from_the_sign_in_page")}),c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex-1",children:c.jsx(R3,{id:`prompt-${fe.id}`,value:R,onChange:De=>{F(De),N(null)},label:x("ui.providers.provider_detail.sign_in_code"),invalid:A!==null})}),c.jsx(ce,{variant:de?"primary":"secondary",size:"md",disabled:!R,onClick:()=>void O(),children:x("ui.providers.provider_detail.continue")})]}),A?c.jsx("p",{className:"text-danger text-meta",role:"alert",children:A}):null]}):null;fe.input_required&&!ie?Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"paste-required",children:[c.jsxs("p",{className:"text-body text-ink",children:[x("ui.providers.provider_detail.paste_the_code"),we??x("ui.providers.provider_detail.the_provider")," ",x("ui.providers.provider_detail.shows_after_you_approve")]}),c.jsx("div",{className:"w-full",children:ee(!0)}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void re.reopen(),children:[c.jsx(xl,{"aria-hidden":"true"}),G.opened?x("ui.providers.provider_detail.open_browser_again"):x("ui.providers.provider_detail.open_sign_in_page")]}),fe.auth_url?c.jsx(Zb,{value:fe.auth_url,label:x("ui.providers.provider_detail.copy_link")}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]})]}):Te=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"waiting",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(pn,{size:"sm"}),c.jsx("output",{className:"text-body text-ink",children:x("ui.providers.provider_detail.finish_signing_in_with_your_browser")})]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:G.opened?x("ui.providers.provider_detail.we_opened_approve_access_there_and_this",{host:we??x("ui.providers.provider_detail.the_sign_in_page")}):G.openFailed?x("ui.providers.provider_detail.your_browser_didn_t_open_open_the"):x("ui.providers.provider_detail.opening_approve_access_there_and_this_page",{host:we??x("ui.providers.provider_detail.the_sign_in_page")})}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void re.reopen(),children:[c.jsx(xl,{"aria-hidden":"true"}),G.opened?x("ui.providers.provider_detail.open_browser_again"):x("ui.providers.provider_detail.open_sign_in_page")]}),fe.auth_url?c.jsx(Zb,{value:fe.auth_url,label:x("ui.providers.provider_detail.copy_link")}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void re.cancel(),children:x("ui.providers.provider_detail.cancel")})]}),be?c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.providers.provider_detail.link_expiry",{minutes:be})}):null,fe.input_required?c.jsx(np,{summary:x("ui.providers.provider_detail.browser_showed_a_code_paste_it_here"),className:"w-full",children:c.jsx("div",{className:"pt-2",children:ee(!1)})}):null]})}else if(G.phase==="settled"&&fe?.state==="succeeded")Te=c.jsx(A3,{brand:M,verb:"Signed in to",defaults:fe.defaults_applied,onChangeModel:s,actionLabel:e.id==="radient"&&h?.group==="Needs sign-in"?"Sign in again":P,onAction:e.id==="radient"&&h?.group==="Needs sign-in"?q:z,primaryAction:r==="dialog",verdict:h});else{const ee=fe?EQ(fe,M):G.error??x("ui.providers.provider_detail.didn_t_confirm_the_sign_in",{brand:M});Te=c.jsxs("div",{className:"flex flex-col gap-3","data-sign-in-state":"unfinished",children:[c.jsxs(Kr,{variant:fe?.state==="cancelled"?"neutral":"warning",children:[c.jsx(FF,{children:x("ui.providers.provider_detail.sign_in_didn_t_finish")}),c.jsx(DF,{children:ee})]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:q,children:[c.jsx(kQ,{"aria-hidden":"true"}),x("ui.providers.provider_detail.try_again")]}),ne?c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>ae(ne.method_id),children:x("ui.providers.provider_detail.use_an_api_key_instead")}):null]})]})}return c.jsxs("div",{className:"flex flex-col gap-4",children:[le,Te,e.id==="radient"&&e.has_credential?c.jsx(hKe,{offerSignIn:!1}):null]})},SKe=()=>x("ui.providers.provider_catalog.one_browser_sign_in_nothing_to_paste");function EKe(e){const t=e.find(n=>n.id===MQ);return t===void 0?null:hT(t).group==="Needs sign-in"?t:null}function kKe(e,t){return t!==null&&e===t}function TKe(e,t,n){const s=t.trim().toLowerCase();return s?e.filter(r=>[r.name,r.id,...r.search_aliases].join(" ").toLowerCase().includes(s)):e}const F3=({provider:e})=>c.jsx("span",{"aria-hidden":"true",className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-elevated font-medium text-body-sm text-ink",children:jQ(Ri(e))}),wb=({children:e,label:t})=>(Et(),c.jsx("ul",{"aria-label":t,className:"flex flex-col divide-y divide-hairline overflow-hidden rounded-[14px] bg-surface",children:e})),GW=({onConnected:e,initialProviderId:t=null,context:n="settings",featuredOnly:s=!1,focusGroup:r=null,onDone:i,onChangeModel:a})=>{Et();const o=R0(!0),{hosting:l,model:u}=IB(),d=nn(),h=DB(),{accountRead:f,unavailable:p}=Vk(),[m,v]=g.useState(t),b=g.useCallback(()=>{a?.(),requestAnimationFrame(()=>{document.getElementById("model-settings")?.focus?.({preventScroll:!0})})},[a]);g.useEffect(()=>{t&&v(t)},[t]);const[w,C]=g.useState(""),[y,k]=g.useState(null),_=g.useRef(null),E=g.useRef(null),R=g.useRef(new Map),F=g.useMemo(()=>o.data??[],[o.data]),A=g.useMemo(()=>AQ(F,l),[F,l]),N=g.useMemo(()=>FQ(F,l,w),[F,l,w]),M=EKe(F)?.id??null,[D,L]=g.useState(null);g.useEffect(()=>{if(D===null)return;const q=B=>B?.isConnected?B:null,we=q(R.current.get(D))??q(_.current)??q(E.current);L(null),we?.focus()},[D]),g.useEffect(()=>{m!==null&&R.current.get(m)?.closest("li")?.scrollIntoView({block:"nearest"})},[m,A.length]);const V=q=>{m===q?(v(null),L(q)):v(q)},j=()=>{const q=m;v(null),q&&L(q),i?.()};g.useEffect(()=>{if(m===null)return;const q=we=>{we.key!=="Escape"||we.defaultPrevented||we.target?.closest('[role="menu"], [role="dialog"], [role="listbox"]')||j()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)});const te=()=>{d.invalidateQueries({queryKey:Bo.providers}),d.invalidateQueries({queryKey:UQ})},X=async q=>{const we=q.suggested_model;try{await HQ.updateConfig("",{hosting:q.id,model_name:we?.id??""}),te()}catch(B){zt(B instanceof Error?B.message:x("ui.providers.provider_grid.the_default_was_not_changed"))}},re=async q=>{k(null);try{await xt({op:"auth.logout",provider:q.id}),await d.invalidateQueries({queryKey:Bo.providers}),e?.()}catch(we){zt(we instanceof Error?we.message:x("ui.providers.provider_grid.sign_out_did_not_complete"))}finally{L(q.id)}};if(o.isLoading)return c.jsx("div",{className:"flex h-40 items-center justify-center",children:c.jsx(pn,{size:"lg",label:x("ui.providers.provider_grid.loading_providers")})});if(o.isError)return c.jsx(Kr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:DQ(o.error)}),c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0",onClick:()=>void o.refetch(),disabled:o.isFetching,children:o.isFetching?x("ui.providers.provider_grid.retrying"):x("ui.providers.provider_grid.retry")})]})});const G=(q,we)=>m===q.id?c.jsx("div",{className:"border-hairline border-t bg-surface px-4 py-4",children:c.jsx(_Ke,{provider:q,onConnected:e,onDone:j,onChangeModel:a,context:n,readiness:we})}):null,J=q=>{const we=kKe(q.id,M),B=q.suggested_model?.name,be=m===q.id;return c.jsxs("li",{"data-provider-id":q.id,children:[c.jsxs("div",{className:"flex min-h-14 items-center gap-3 px-4 py-2",children:[c.jsx(F3,{provider:q}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("span",{className:"flex flex-wrap items-baseline gap-x-2 text-body text-ink",children:[Ri(q),we?c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-ink-dim text-meta",children:"·"}),c.jsx("span",{className:"shrink-0 font-medium text-ink text-meta",children:x("ui.providers.provider_grid.recommended")})]}):null]}),c.jsxs("span",{className:"text-ink-muted text-meta",children:[we?SKe():BQ(q),B?c.jsxs("span",{className:"text-ink-dim",children:[" ",x("ui.providers.provider_grid.suggests"),B]}):null]})]}),c.jsx(ce,{ref:ie=>{R.current.set(q.id,ie)},variant:we&&!be&&m===null&&A.length===0?"primary":"secondary",size:"sm","aria-expanded":be,"aria-label":x("ui.providers.provider_grid.row_action",{action:be?x("ui.providers.provider_grid.close"):CF(q),brand:Ri(q)}),onClick:()=>V(q.id),children:be?x("ui.providers.provider_grid.close"):CF(q)})]}),G(q)]},q.id)},ae=q=>{const we=q.id===l,B=we?NB(q,u):q.suggested_model?.name??null,be=m===q.id,ie=PB(q.id,h,{accountRead:f,unavailable:p}),Te=ie===null?null:hT(q,ie),ee=OQ(q,B,Te?.label??null);return c.jsxs("li",{"data-provider-id":q.id,children:[c.jsxs("div",{className:"flex min-h-14 items-center gap-3 px-4 py-2",children:[c.jsx(F3,{provider:q}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsx("span",{className:"text-body text-ink",children:Ri(q)}),c.jsx("span",{className:`truncate text-meta ${Te?.tone==="attention"?"text-warning":"text-ink-muted"}`,title:Te?.detail,"data-claim":ie===null?"withheld":void 0,"data-claim-tone":Te?.tone,children:ee??" "})]}),we?c.jsx("span",{className:"text-ink-muted text-meta",children:x("ui.providers.provider_grid.default")}):null,y===q.id?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("span",{className:"text-body-sm text-ink",children:[x("ui.providers.provider_grid.sign_out_of"),Ri(q),"?"]}),c.jsx(ce,{variant:"danger",size:"sm",onClick:()=>void re(q),children:x("ui.providers.provider_grid.sign_out")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>{k(null),L(q.id)},children:x("ui.providers.provider_grid.keep")})]}):c.jsxs(Il,{children:[c.jsx(Ho,{asChild:!0,children:c.jsx(ce,{ref:de=>{R.current.set(q.id,de)},variant:"ghost",size:"icon-sm",className:be?"bg-control text-on-accent":void 0,"aria-expanded":be,"aria-label":x("ui.providers.provider_grid.manage",{brand:Ri(q)}),children:c.jsx(nC,{"aria-hidden":"true"})})}),c.jsxs(Nl,{align:"end",onCloseAutoFocus:de=>de.preventDefault(),children:[we?null:c.jsx(Gt,{onSelect:()=>void X(q),children:x("ui.providers.provider_grid.make_default")}),we&&a?c.jsx(Gt,{onClick:()=>b(),onSelect:()=>b(),children:x("ui.providers.provider_grid.change_model")}):null,c.jsx(Gt,{onSelect:()=>V(q.id),"data-panel-toggle":q.id,children:be?x("ui.providers.provider_grid.close"):q.local?x("ui.providers.provider_grid.check_connection"):LQ(q)==="key"?x("ui.providers.provider_grid.replace_key"):x("ui.providers.provider_grid.sign_in_again")}),!q.local&&q.stored_credentials>0?c.jsxs(c.Fragment,{children:[c.jsx(Yr,{}),c.jsx(Gt,{destructive:!0,onSelect:()=>k(q.id),children:x("ui.providers.provider_grid.sign_out_variant_351")})]}):null]})]})]}),be?G(q,Te):null]},q.id)},O=s?PQ:IQ,U=O.every(q=>N[q].length===0),P=c.jsxs("div",{className:"relative w-full sm:w-64",children:[c.jsx(xd,{size:16,className:"pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-ink-dim","aria-hidden":"true"}),c.jsx(ps,{ref:_,value:w,onChange:q=>C(q.target.value),placeholder:x("ui.providers.provider_grid.search_providers"),"aria-label":x("ui.providers.provider_grid.search_providers"),className:"pl-9"})]}),z=x("ui.providers.provider_grid.no_providers_match_this_search"),ne=x("ui.providers.provider_grid.the_matching_providers_are_in_the_suggested"),fe=x("ui.providers.provider_grid.the_matching_providers_are_in_the_connected"),ue=(q,we)=>we?c.jsxs("div",{className:"flex flex-col items-center gap-2 py-6 text-center",children:[c.jsx("p",{className:"text-body-sm text-ink-muted",children:we}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>{C(""),_.current?.focus()},children:[c.jsx(Dn,{"aria-hidden":"true"}),x("ui.providers.provider_grid.clear_search")]})]}):O.map(B=>q[B].length>0?c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("h4",{className:"text-ink-dim text-meta",children:wF[B]}),c.jsx(wb,{label:wF[B],children:q[B].map(J)})]},B):null),le=ue(N,U?z:null);if(s){const q=new Set(TKe(F,w).map(de=>de.id)),we=nS.map(de=>F.find(De=>De.id===de)).filter(de=>de!==void 0&&!A.some(De=>De.id===de.id)&&q.has(de.id)),B=new Set(nS.filter(de=>F.some(De=>De.id===de))),be={subscription:N.subscription.filter(de=>!B.has(de.id)),key:N.key.filter(de=>!B.has(de.id)),local:N.local.filter(de=>!B.has(de.id))},ie=O.reduce((de,De)=>de+be[De].length,0),Te=w.trim().length>0,ee=Te?q.size===0?z:ie===0?we.length>0?ne:fe:null:null;return c.jsxs("div",{ref:E,tabIndex:-1,className:"flex flex-col gap-4","data-provider-grid":"",children:[A.length>0?c.jsx(wb,{label:x("ui.providers.provider_grid.connected"),children:A.map(ae)}):null,we.length>0?c.jsx(wb,{label:x("ui.providers.provider_grid.suggested_providers"),children:we.map(J)}):null,Te||ie>0?c.jsx(np,{summary:NQ(be,O),defaultOpen:r!==null||t!==null,chevron:"trailing",children:c.jsxs("div",{className:"flex flex-col gap-4 pt-3",children:[P,ue(be,ee)]})}):null]})}return c.jsxs("div",{ref:E,tabIndex:-1,className:"flex flex-col gap-6","data-provider-grid":"",children:[A.length>0?c.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"providers-connected",children:[c.jsx("h3",{id:"providers-connected",className:"text-heading text-ink",children:x("ui.providers.provider_grid.connected")}),c.jsx(wb,{children:A.map(ae)})]}):null,c.jsxs("section",{className:"flex flex-col gap-3","aria-labelledby":"providers-add",children:[c.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[c.jsx("h3",{id:"providers-add",className:"text-heading text-ink",children:A.length>0?x("ui.providers.provider_grid.add_a_provider"):x("ui.providers.provider_grid.connect_a_provider")}),P]}),le]})]})},RKe=({onContinue:e})=>c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:x("ui.onboarding.connect.intro")}),c.jsx(GW,{context:"dialog",featuredOnly:!0,onDone:e,onChangeModel:e})]});function D3(e){for(const t of nS){const n=e.find(s=>s.id===t);if(n)return n}return e[0]??null}function AKe(e,t){if(t.hosting)return{kind:"applied",hosting:t.hosting,model:t.model,provider:e.find(a=>a.id===t.hosting)??null};const n=e.filter(a=>!a.local&&GQ(a,null)),s=n.filter(a=>a.suggested_model),r=D3(s);if(r?.suggested_model)return{kind:"proposed",provider:r,model:r.suggested_model};const i=D3(n);return i?{kind:"choose",provider:i}:{kind:"none"}}const FKe="ui.onboarding.default_model.block.pick_a_model",DKe="ui.onboarding.default_model.block.loading_models";function PKe(e){const{choice:t,hosting:n,model:s,catalogue:r}=e,i=n??(t&&(t.kind==="choose"||t.kind==="proposed")?t.provider.id:""),a=s??"",o=t?.kind==="proposed"?t.model.id:"",l=a||o,u=r.ready&&r.providers.includes(i),d=!l&&(t?.kind==="choose"||t?.kind==="applied"&&!t.model);return{shownProvider:i,write:i&&!d&&l?{hosting:i,model_name:l}:null,block:d?u?x(FKe):r.ready?null:x(DKe):null,noCatalogue:d&&r.ready&&!u,modelToWrite:l}}const IKe=({choice:e,onChange:t})=>{if(e.kind==="none")return c.jsx(Kr,{variant:"neutral",children:x("ui.onboarding.default_model.none_connected")});if(e.kind==="choose")return c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.onboarding.default_model.connected_pick",{brand:Ri(e.provider)})});const n=e.kind==="applied"?NB(e.provider,e.model)??x("ui.onboarding.default_model.fallback_name",{brand:e.provider?Ri(e.provider):e.hosting}):e.model.name,s=e.kind==="applied"?e.provider?Ri(e.provider):e.hosting:Ri(e.provider);return c.jsxs("div",{className:"flex flex-col gap-1","data-default-model":e.kind,children:[c.jsx("p",{className:"text-heading text-ink",children:n}),c.jsxs("p",{className:"text-ink-dim text-meta",children:[s," ·"," ",e.kind==="applied"?x("ui.onboarding.default_model.tag.applied"):x("ui.onboarding.default_model.tag.suggested")]}),c.jsx("div",{className:"pt-2",children:c.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:x("ui.onboarding.default_model.change")})})]})},NKe=({onBeforeContinue:e,onBlockReason:t})=>{const n=R0(!0),s=IB(),r=Jj(),[i,a]=g.useState(!1),o=n.isLoading||s.isLoading?null:AKe(n.data??[],s),{refreshModels:l}=cT();g.useEffect(()=>{l()},[]);const u=td(_=>_.isInitialized),d=td(_=>_.models),h=g.useMemo(()=>{const _=new Set;for(const E of d)_.add(E.provider);return[..._]},[d]),f=g.useMemo(()=>PKe({choice:o,hosting:s.hosting,model:s.model,catalogue:{ready:u,providers:h}}),[o,s.hosting,s.model,u,h]),{shownProvider:p,write:m,block:v,noCatalogue:b,modelToWrite:w}=f,C=g.useCallback(_=>{const E=td.getState().models.filter(R=>R.provider===_);return E.find(R=>R.info?.recommended)?.id??E[0]?.id},[]),y=(n.data??[]).find(_=>_.id===p)??null;if(g.useEffect(()=>(e?.(m?async()=>{await r.mutateAsync(m)}:null),()=>e?.(null)),[e,m,r.mutateAsync]),g.useEffect(()=>{if(t)return t(v),()=>t(null)},[t,v]),o===null)return c.jsxs("div",{className:"flex items-center justify-center gap-3 py-8",children:[c.jsx(pn,{size:"sm"}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.onboarding.default_model.loading")})]});const k=c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsx(OW,{value:p,onSave:async _=>{const E=C(_);E&&await r.mutateAsync({hosting:_,model_name:E})},filterByCredentials:!0,allowCustom:!1,allowDefault:!1,emptyHelperText:x("ui.onboarding.default_model.empty_helper")}),c.jsx(LW,{value:w,hostingId:p,onSave:async _=>{await r.mutateAsync({model_name:_})},allowCustom:!0,allowDefault:!1})]});return c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:x("ui.onboarding.default_model.intro")}),b?c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.onboarding.default_model.nothing_saved",{brand:y?Ri(y):x("ui.onboarding.default_model.provider_fallback")})}):null,i||o.kind==="choose"?k:c.jsx(IKe,{choice:o,onChange:()=>a(!0)})]})};var VW=(e=>(e.Hosting="hosting",e.Search="search",e.Oauth="oauth",e))(VW||{});const MKe=[{key:"RADIENT_API_KEY",name:"Radient Pass",get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_your_radient_pass_radient_pass_provides_you_unified_a")},url:"https://radienthq.com",type:"hosting"},{key:"OPENAI_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_openai_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_accessing_openai_models_like_gpt_4o_o3_mini_and_gpt_4")},url:"https://platform.openai.com/api-keys",type:"hosting"},{key:"OPENROUTER_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_openrouter_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_openrouter_which_provides_access_to_various_ai_models")},url:"https://openrouter.ai/keys",type:"hosting"},{key:"DEEPSEEK_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_deepseek_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_deepseek_ai_models_specialized_in_code_generation_and")},url:"https://platform.deepseek.com/",type:"hosting"},{key:"MISTRAL_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_mistral_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_mistral_ai_models_known_for_efficient_and_powerful_la")},url:"https://console.mistral.ai/api-keys/",type:"hosting"},{key:"KIMI_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_kimi_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_kimi_ai_providing_advanced_language_models_with_stron")},url:"https://kimi.moonshot.cn/",type:"hosting"},{key:"ALIBABA_CLOUD_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_alibaba_cloud_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_alibaba_cloud_ai_models_offering_a_range_of_language_")},url:"https://www.alibabacloud.com/product/ai",type:"hosting"},{key:"GOOGLE_AI_STUDIO_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_google_ai_studio_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_google_ai_studio_providing_access_to_gemini_and_other")},url:"https://aistudio.google.com/",type:"hosting"},{key:"GOOGLE_ACCESS_TOKEN",get name(){return x("ui.settings.integrations.credential_manifest.name_google_access_token")},get description(){return x("ui.settings.integrations.credential_manifest.oauth_2_0_access_token_for_google_apis_used_by_local_operator_for")},url:"https://console.cloud.google.com/apis/credentials",internal:!0,type:"oauth"},{key:"GOOGLE_TOKEN_EXPIRY_TIMESTAMP",get name(){return x("ui.settings.integrations.credential_manifest.name_google_token_expiry_timestamp")},get description(){return x("ui.settings.integrations.credential_manifest.timestamp_in_milliseconds_since_epoch_indicating_when_the_current")},url:"",internal:!0,type:"oauth"},{key:"GOOGLE_REFRESH_TOKEN",get name(){return x("ui.settings.integrations.credential_manifest.name_google_refresh_token")},get description(){return x("ui.settings.integrations.credential_manifest.oauth_2_0_refresh_token_for_google_apis_used_to_obtain_new_access")},url:"https://console.cloud.google.com/apis/credentials",internal:!0,type:"oauth"},{key:"ANTHROPIC_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_anthropic_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_anthropic_s_claude_models_known_for_agentic_code_gene")},url:"https://console.anthropic.com/settings/keys",type:"hosting"},{key:"SERP_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_serp_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_search_engine_results_page_api_allowing_access_to_sea")},url:"https://serpapi.com/dashboard",type:"search"},{key:"TAVILY_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_tavily_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_tavily_a_search_api_designed_specifically_for_ai_appl")},url:"https://tavily.com/#api",type:"search"},{key:"BRAVE_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_brave_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_brave_search_an_independent_web_index_with_its_own_cr")},url:"https://api-dashboard.search.brave.com/app/keys",type:"search"},{key:"EXA_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_exa_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_exa_a_search_api_built_for_ai_applications_agents_can")},url:"https://dashboard.exa.ai/api-keys",type:"search"},{key:"PARALLEL_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_parallel_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_parallel_a_web_search_api_for_ai_agents_agents_can_al")},url:"https://platform.parallel.ai/",type:"search"},{key:"PERPLEXITY_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_perplexity_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_perplexity_s_sonar_search_perplexity_is_best_effort_a")},url:"https://console.perplexity.ai/",type:"search"},{key:"FAL_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_fal_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_fal_used_by_agents_for_generating_interpreting_and_un")},url:"https://docs.fal.ai/quick-start",type:"hosting"},{key:"XAI_API_KEY",get name(){return x("ui.settings.integrations.credential_manifest.name_xai_api_key")},get description(){return x("ui.settings.integrations.credential_manifest.api_key_for_xai_providing_access_to_grok_and_other_advanced_xai_m")},url:"https://docs.x.ai/docs/overview",type:"hosting"}],OKe=MKe.filter(e=>e.type===VW.Search),LKe="onboarding-search-mode",BKe="onboarding-search-mode-free",jKe="onboarding-search-mode-keys",P3="onboarding-search-mode-label",HKe=e=>`onboarding-search-key-${e.toLowerCase()}`,I3=({id:e,title:t,recommended:n=!1,checked:s,onSelect:r,children:i})=>c.jsxs("label",{htmlFor:e,className:T("flex cursor-pointer items-start gap-3 rounded-sm p-3","transition-colors duration-fast ease-out-quart","hover:bg-sunken","has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2","has-[:focus-visible]:outline-accent has-[:focus-visible]:outline-offset-2",s&&"bg-sunken"),children:[c.jsx("input",{type:"radio",id:e,name:LKe,className:"sr-only outline-none",checked:s,onChange:r}),c.jsx("span",{"aria-hidden":"true",className:T("mt-1 grid size-4 shrink-0 place-items-center rounded-full","border border-control bg-surface",s&&"border-accent bg-accent"),children:c.jsx("span",{className:T("size-2 rounded-full",s&&"bg-on-accent")})}),c.jsxs("span",{className:"flex min-w-0 flex-col gap-1",children:[c.jsxs("span",{className:T("flex flex-wrap items-baseline gap-x-2 text-body text-ink",s&&"font-medium"),children:[t,n?c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-ink-dim text-meta",children:"·"}),c.jsx("span",{className:"shrink-0 font-medium text-ink text-meta",children:x("ui.onboarding.search.recommended")})]}):null]}),c.jsx("span",{className:"text-body-sm text-ink-muted",children:i})]})]}),UKe=({credential:e,showDescription:t,isStored:n,save:s})=>{const[r,i]=g.useState(""),[a,o]=g.useState(!1),[l,u]=g.useState(!1),[d,h]=g.useState(null),[f,p]=g.useState(null),m=HKe(e.key),v=n||l,b=async()=>{const w=r.trim();if(!(!w||a||w===d))try{o(!0),p(null),await s(e.key,w),h(w),u(!0)}catch(C){const y=C instanceof Error&&C.message?C.message:x("ui.onboarding.search.row.save_failed");p(x("ui.onboarding.search.row.not_saved",{message:y}))}finally{o(!1)}};return c.jsxs("div",{className:"flex flex-col gap-2","data-search-key":e.key,children:[c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx(nr,{htmlFor:m,children:e.name}),c.jsxs("span",{className:"flex items-center gap-2",children:[a?c.jsx(pn,{size:"sm",label:x("ui.onboarding.search.row.saving",{name:e.name})}):null,v?c.jsx(Ml,{variant:"success",children:x("ui.onboarding.search.row.saved")}):null]})]}),c.jsx(ps,{id:m,inputSize:"lg",type:"password",value:r,onChange:w=>{i(w.target.value),u(!1),p(null)},onBlur:b,onKeyDown:w=>{w.key==="Enter"&&r.trim()&&!a&&b()},placeholder:x("ui.onboarding.search.row.placeholder"),disabled:a}),f?c.jsx("p",{className:"text-danger text-meta",role:"alert",children:f}):t?c.jsx("p",{className:"text-ink-dim text-meta",children:e.description}):null,c.jsxs("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex w-fit items-center gap-1 text-accent text-meta underline-offset-4 hover:text-accent-hover hover:underline",children:[x("ui.onboarding.search.row.get_your",{name:e.name}),c.jsx(xl,{size:12,"aria-hidden":"true"})]})]})},GKe=({showCredentialDescription:e=!0})=>{const[t,n]=g.useState("free"),{data:s}=gB(),r=Jae(),i=s?.keys??[],a=async(o,l)=>{await r.mutateAsync({key:o,value:l})};return c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:x("ui.onboarding.search.intro")}),c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{id:P3,className:"sr-only",children:x("ui.onboarding.search.mode.label")}),c.jsxs("div",{role:"radiogroup","aria-labelledby":P3,className:"flex flex-col gap-2",children:[c.jsx(I3,{id:BKe,title:x("ui.onboarding.search.mode.free"),recommended:!0,checked:t==="free",onSelect:()=>n("free"),children:x("ui.onboarding.search.mode.free_detail")}),c.jsx(I3,{id:jKe,title:x("ui.onboarding.search.mode.keys"),checked:t==="keys",onSelect:()=>n("keys"),children:x("ui.onboarding.search.mode.keys_detail")})]})]}),t==="keys"?c.jsxs("div",{className:"flex flex-col gap-5 pl-10",children:[c.jsx("p",{className:"text-ink-dim text-meta",children:x("ui.onboarding.search.each_key_saved")}),OKe.map(o=>c.jsx(UKe,{credential:o,showDescription:e,isStored:i.includes(o.key),save:a},o.key))]}):null]})},VKe=({aidaName:e=null,oweGreeting:t=!0})=>c.jsxs("div",{className:"flex flex-col gap-8",children:[c.jsx(GKe,{showCredentialDescription:!1}),e?c.jsxs("section",{className:"flex flex-col gap-2","aria-labelledby":"onboarding-extras-next",children:[c.jsx("h3",{id:"onboarding-extras-next",className:"text-heading text-ink",children:x("ui.onboarding.extras.next_meet",{name:e})}),c.jsx("p",{className:"text-body text-ink-muted",children:t?x("ui.onboarding.extras.greeting_owed",{name:e}):x("ui.onboarding.extras.greeting_done",{name:e})})]}):null]}),WKe={[kr.CONNECT_PROVIDER]:"ui.onboarding.modal.title.connect_provider",[kr.DEFAULT_MODEL]:"ui.onboarding.modal.title.default_model",[kr.EXTRAS]:"ui.onboarding.modal.title.extras"};function $Ke(e,t){return e===kr.EXTRAS&&t?x("ui.onboarding.modal.title.extras_with_name",{name:t}):x(WKe[e])}const Ma=[kr.CONNECT_PROVIDER,kr.DEFAULT_MODEL,kr.EXTRAS],zKe={},qKe=({open:e})=>{const{currentStep:t,setCurrentStep:n,completeModalOnboarding:s}=ym(),r=Jr(),i=R0(e),a=VQ(i.data??[]),o=Bn(),l=yt(o.data,"aida",1),u=B0(e&&l),d=l&&u.data?.enabled===!0,h=u.data?.name?.trim()||"Aida",f=WQ(u.data),p=$T(),m=g.useMemo(()=>{const O=d?h:null;return Object.fromEntries(Ma.map(U=>[U,$Ke(U,O)]))},[d,h]),[v,b]=g.useState(!1),w=g.useRef(null),[C,y]=g.useState(null),k=g.useCallback(O=>{y(O)},[]),[_,E]=g.useState(!1),R=_||v,F=g.useCallback(O=>{w.current=O},[]);g.useEffect(()=>{Ma.includes(t)||n(kr.CONNECT_PROVIDER)},[t,n]);const[A,N]=g.useState(new Set);g.useEffect(()=>{N(O=>{if(O.has(t))return O;const U=new Set(O);return U.add(t),U})},[t]);const M=m[t]??x("ui.onboarding.modal.title.fallback"),D=g.useCallback(()=>{s(),r("/chat")},[s,r]),L=g.useCallback(async()=>{b(!0);try{const O=await p("greet");if(s(),!O.session_id){r("/chat"),zt(x("ui.onboarding.modal.error.aida_open_failed",{name:h}));return}cp(r,O.session_id);const U=$Q(O,h);U&&Va(U)}catch(O){s(),r("/chat");const U=zQ(O,h);U?.kind==="info"?Va(U.text):U&&zt(U.text)}finally{b(!1)}},[p,h,s,r]),V=g.useCallback(async()=>{const O=Ma.indexOf(t);if(t===kr.DEFAULT_MODEL&&w.current){E(!0);try{await w.current()}catch{E(!1);return}E(!1)}O>=0&&O<Ma.length-1?n(Ma[O+1]):d?await L():D()},[t,n,D,d,L]),j=g.useCallback(()=>{const O=Ma.indexOf(t);O>0&&n(Ma[O-1])},[t,n]),te=g.useMemo(()=>{switch(t){case kr.CONNECT_PROVIDER:return c.jsx(RKe,{onContinue:()=>n(kr.DEFAULT_MODEL)});case kr.DEFAULT_MODEL:return c.jsx(NKe,{onBeforeContinue:F,onBlockReason:k});case kr.EXTRAS:return c.jsx(VKe,{aidaName:d?h:null,oweGreeting:f});default:return null}},[t,n,F,k,d,h,f]),X=t===kr.CONNECT_PROVIDER,re=t===kr.EXTRAS,G=nKe(t,C,R),J=c.jsxs("div",{className:"flex w-full flex-col gap-2",children:[G.reason?c.jsx("p",{className:"text-ink-dim text-meta",children:G.reason}):null,c.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[c.jsx("div",{children:X?c.jsx(ce,{variant:"ghost",size:"lg",onClick:D,children:x("ui.onboarding.modal.action.skip_for_now")}):c.jsx(ce,{variant:"secondary",size:"lg",onClick:j,children:x("ui.onboarding.modal.action.back")})}),c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[re?c.jsx(ce,{variant:"ghost",size:"lg",onClick:D,disabled:v,children:d?x("ui.onboarding.modal.action.skip_to_chat"):x("ui.onboarding.modal.action.skip")}):null,!X||a?c.jsx(ce,{variant:"primary",size:"lg",onClick:()=>void V(),disabled:G.primaryDisabled,children:re?d?x("ui.onboarding.modal.action.meet",{name:h}):x("ui.onboarding.modal.action.finish"):x("ui.onboarding.modal.action.continue")}):null]})]})]}),ae=g.useMemo(()=>{if(!t)return null;const O=Ma.indexOf(t);return c.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[c.jsx("span",{className:"whitespace-nowrap text-ink-dim text-meta",children:O>=0?x("ui.onboarding.modal.step_of",{current:O+1,total:Ma.length}):x("ui.onboarding.modal.steps_total",{total:Ma.length})}),c.jsx("ol",{className:"flex items-center gap-1",children:Ma.map((U,P)=>{const z=t===U,fe=A.has(U)&&!z,ue=P<=O;return c.jsx("li",{className:"flex",children:c.jsx(Je,{content:m[U],children:c.jsx("button",{type:"button","aria-label":m[U],"aria-current":z?"step":void 0,"aria-disabled":!fe,onClick:()=>{fe&&n(U)},className:"flex h-4 w-4 items-center",children:c.jsx("span",{className:T("h-1 w-full rounded-xs transition-colors duration-base ease-out-quart",ue?"bg-accent":"bg-control")})})})},U)})})]})},[t,A,n,m]);return c.jsx(tKe,{open:e,onDismiss:D,title:M,stepIndicators:ae,actions:J,width:zKe[t]??"single",children:te})};var N3={exports:{}},pg={};/**
|
|
675
675
|
* @license React
|
|
676
676
|
* react-jsx-runtime.production.min.js
|
|
677
677
|
*
|
|
@@ -681,7 +681,7 @@ ${QV(r)}`)}const JV=rY;function CL(e){return e.artifact&&iY(e.path)?e.artifact:n
|
|
|
681
681
|
* LICENSE file in the root directory of this source tree.
|
|
682
682
|
*/var M3;function KKe(){if(M3)return pg;M3=1;var e=$e,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,r=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(o,l,u){var d,h={},f=null,p=null;u!==void 0&&(f=""+u),l.key!==void 0&&(f=""+l.key),l.ref!==void 0&&(p=l.ref);for(d in l)s.call(l,d)&&!i.hasOwnProperty(d)&&(h[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)h[d]===void 0&&(h[d]=l[d]);return{$$typeof:t,type:o,key:f,ref:p,props:h,_owner:r.current}}return pg.Fragment=n,pg.jsx=a,pg.jsxs=a,pg}var O3;function YKe(){return O3||(O3=1,N3.exports=KKe()),N3.exports}var XKe=YKe();/*! shepherd.js 14.5.0 */function QKe(e){return e instanceof Element}function Xf(e){return e instanceof HTMLElement}function tu(e){return typeof e=="function"}function y0(e){return typeof e=="string"}function Dr(e){return e===void 0}class nA{on(t,n,s,r=!1){var i;return Dr(this.bindings)&&(this.bindings={}),Dr(this.bindings[t])&&(this.bindings[t]=[]),(i=this.bindings[t])==null||i.push({handler:n,ctx:s,once:r}),this}once(t,n,s){return this.on(t,n,s,!0)}off(t,n){if(Dr(this.bindings)||Dr(this.bindings[t]))return this;if(Dr(n))delete this.bindings[t];else{var s;(s=this.bindings[t])==null||s.forEach((r,i)=>{if(r.handler===n){var a;(a=this.bindings[t])==null||a.splice(i,1)}})}return this}trigger(t,...n){if(!Dr(this.bindings)&&this.bindings[t]){var s;(s=this.bindings[t])==null||s.forEach((r,i)=>{const{ctx:a,handler:o,once:l}=r,u=a||this;if(o.apply(u,n),l){var d;(d=this.bindings[t])==null||d.splice(i,1)}})}return this}}function vi(){return vi=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)({}).hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},vi.apply(null,arguments)}function sA(e,t){if(e==null)return{};var n={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(t.includes(s))continue;n[s]=e[s]}return n}const hu={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")};hu.defaultMerge;function JKe(e,t){return t}function ZKe(e,t){return e.filter(n=>n!==void 0)}var L3;(function(e){e[e.NOT=0]="NOT",e[e.RECORD=1]="RECORD",e[e.ARRAY=2]="ARRAY",e[e.SET=3]="SET",e[e.MAP=4]="MAP",e[e.OTHER=5]="OTHER"})(L3||(L3={}));function B3(e){return typeof e!="object"||e===null?0:Array.isArray(e)?2:nYe(e)?1:e instanceof Set?3:e instanceof Map?4:5}function eYe(e){const t=new Set;for(const n of e)for(const s of[...Object.keys(n),...Object.getOwnPropertySymbols(n)])t.add(s);return t}function tYe(e,t){return typeof e=="object"&&Object.prototype.propertyIsEnumerable.call(e,t)}function WW(e){return{*[Symbol.iterator](){for(const t of e)for(const n of t)yield n}}}const j3=new Set(["[object Object]","[object Module]"]);function nYe(e){if(!j3.has(Object.prototype.toString.call(e)))return!1;const{constructor:t}=e;if(t===void 0)return!0;const n=t.prototype;return!(n===null||typeof n!="object"||!j3.has(Object.prototype.toString.call(n))||!n.hasOwnProperty("isPrototypeOf"))}function sYe(e,t,n){const s={};for(const r of eYe(e)){const i=[];for(const l of e)tYe(l,r)&&i.push(l[r]);if(i.length===0)continue;const a=t.metaDataUpdater(n,{key:r,parents:e}),o=$W(i,t,a);o!==hu.skip&&(r==="__proto__"?Object.defineProperty(s,r,{value:o,configurable:!0,enumerable:!0,writable:!0}):s[r]=o)}return s}function rYe(e){return e.flat()}function iYe(e){return new Set(WW(e))}function aYe(e){return new Map(WW(e))}function oYe(e){return e.at(-1)}const Cb={mergeRecords:sYe,mergeArrays:rYe,mergeSets:iYe,mergeMaps:aYe,mergeOthers:oYe};function rA(...e){return lYe({})(...e)}function lYe(e,t){const n=cYe(e,s);function s(...r){return $W(r,n,t)}return s}function cYe(e,t){var n,s,r;return{defaultMergeFunctions:Cb,mergeFunctions:vi({},Cb,Object.fromEntries(Object.entries(e).filter(([i,a])=>Object.hasOwn(Cb,i)).map(([i,a])=>a===!1?[i,Cb.mergeOthers]:[i,a]))),metaDataUpdater:(n=e.metaDataUpdater)!=null?n:JKe,deepmerge:t,useImplicitDefaultMerging:(s=e.enableImplicitDefaultMerging)!=null?s:!1,filterValues:e.filterValues===!1?void 0:(r=e.filterValues)!=null?r:ZKe,actions:hu}}function $W(e,t,n){var s;const r=(s=t.filterValues==null?void 0:t.filterValues(e,n))!=null?s:e;if(r.length===0)return;if(r.length===1)return U1(r,t,n);const i=B3(r[0]);if(i!==0&&i!==5){for(let a=1;a<r.length;a++)if(B3(r[a])!==i)return U1(r,t,n)}switch(i){case 1:return uYe(r,t,n);case 2:return dYe(r,t,n);case 3:return hYe(r,t,n);case 4:return fYe(r,t,n);default:return U1(r,t,n)}}function uYe(e,t,n){const s=t.mergeFunctions.mergeRecords(e,t,n);return s===hu.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(e,t,n):s}function dYe(e,t,n){const s=t.mergeFunctions.mergeArrays(e,t,n);return s===hu.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(e):s}function hYe(e,t,n){const s=t.mergeFunctions.mergeSets(e,t,n);return s===hu.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(e):s}function fYe(e,t,n){const s=t.mergeFunctions.mergeMaps(e,t,n);return s===hu.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(e):s}function U1(e,t,n){const s=t.mergeFunctions.mergeOthers(e,t,n);return s===hu.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(e):s}function iA(e){const t=Object.getOwnPropertyNames(e.constructor.prototype);for(let n=0;n<t.length;n++){const s=t[n],r=e[s];s!=="constructor"&&typeof r=="function"&&(e[s]=r.bind(e))}return e}function pYe(e,t){return n=>{if(e.isOpen()){const s=e.el&&n.currentTarget===e.el;(!Dr(t)&&n.currentTarget.matches(t)||s)&&e.tour.next()}}}function gYe(e){const{event:t,selector:n}=e.options.advanceOn||{};if(t){const s=pYe(e,n);let r=null;if(!Dr(n)&&(r=document.querySelector(n),!r))return console.error(`No element was found for the selector supplied to advanceOn: ${n}`);r?(r.addEventListener(t,s),e.on("destroy",()=>r.removeEventListener(t,s))):(document.body.addEventListener(t,s,!0),e.on("destroy",()=>document.body.removeEventListener(t,s,!0)))}else return console.error("advanceOn was defined, but no event name was passed.")}class mYe{constructor(t){}}class vYe{constructor(t,n){}}function zW(e){return!y0(e)||e===""?"":e.charAt(e.length-1)!=="-"?`${e}-`:e}function bYe(e){const t=e.options.attachTo||{},n=Object.assign({},t);if(tu(n.element)&&(n.element=n.element.call(e)),y0(n.element)){try{n.element=document.querySelector(n.element)}catch{}n.element||console.error(`The element for this Shepherd step was not found ${t.element}`)}return n}function xYe(e){return e.options.extraHighlights?e.options.extraHighlights.flatMap(t=>Array.from(document.querySelectorAll(t))):[]}function qW(e){return e==null?!0:!e.element||!e.on}function KW(){let e=Date.now();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t=="x"?n:n&3|8).toString(16)})}const wYe=["top","right","bottom","left"],H3=["start","end"],U3=wYe.reduce((e,t)=>e.concat(t,t+"-"+H3[0],t+"-"+H3[1]),[]),Qf=Math.min,gd=Math.max,Iw=Math.round,yb=Math.floor,Lo=e=>({x:e,y:e}),CYe={left:"right",right:"left",bottom:"top",top:"bottom"},yYe={start:"end",end:"start"};function Ik(e,t,n){return gd(e,Qf(t,n))}function jd(e,t){return typeof e=="function"?e(t):e}function Ul(e){return e.split("-")[0]}function Pl(e){return e.split("-")[1]}function aA(e){return e==="x"?"y":"x"}function oA(e){return e==="y"?"height":"width"}function Jf(e){return["top","bottom"].includes(Ul(e))?"y":"x"}function lA(e){return aA(Jf(e))}function YW(e,t,n){n===void 0&&(n=!1);const s=Pl(e),r=lA(e),i=oA(r);let a=r==="x"?s===(n?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Mw(a)),[a,Mw(a)]}function _Ye(e){const t=Mw(e);return[Nw(e),t,Nw(t)]}function Nw(e){return e.replace(/start|end/g,t=>yYe[t])}function SYe(e,t,n){const s=["left","right"],r=["right","left"],i=["top","bottom"],a=["bottom","top"];switch(e){case"top":case"bottom":return n?t?r:s:t?s:r;case"left":case"right":return t?i:a;default:return[]}}function EYe(e,t,n,s){const r=Pl(e);let i=SYe(Ul(e),n==="start",s);return r&&(i=i.map(a=>a+"-"+r),t&&(i=i.concat(i.map(Nw)))),i}function Mw(e){return e.replace(/left|right|bottom|top/g,t=>CYe[t])}function kYe(e){return vi({top:0,right:0,bottom:0,left:0},e)}function XW(e){return typeof e!="number"?kYe(e):{top:e,right:e,bottom:e,left:e}}function Ow(e){const{x:t,y:n,width:s,height:r}=e;return{width:s,height:r,top:n,left:t,right:t+s,bottom:n+r,x:t,y:n}}const TYe=["crossAxis","alignment","allowedPlacements","autoAlignment"],RYe=["mainAxis","crossAxis","fallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment"],AYe=["mainAxis","crossAxis","limiter"];function G3(e,t,n){let{reference:s,floating:r}=e;const i=Jf(t),a=lA(t),o=oA(a),l=Ul(t),u=i==="y",d=s.x+s.width/2-r.width/2,h=s.y+s.height/2-r.height/2,f=s[o]/2-r[o]/2;let p;switch(l){case"top":p={x:d,y:s.y-r.height};break;case"bottom":p={x:d,y:s.y+s.height};break;case"right":p={x:s.x+s.width,y:h};break;case"left":p={x:s.x-r.width,y:h};break;default:p={x:s.x,y:s.y}}switch(Pl(t)){case"start":p[a]-=f*(n&&u?-1:1);break;case"end":p[a]+=f*(n&&u?-1:1);break}return p}const FYe=async(e,t,n)=>{const{placement:s="bottom",strategy:r="absolute",middleware:i=[],platform:a}=n,o=i.filter(Boolean),l=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:r}),{x:d,y:h}=G3(u,s,l),f=s,p={},m=0;for(let v=0;v<o.length;v++){const{name:b,fn:w}=o[v],{x:C,y,data:k,reset:_}=await w({x:d,y:h,initialPlacement:s,placement:f,strategy:r,middlewareData:p,rects:u,platform:a,elements:{reference:e,floating:t}});d=C??d,h=y??h,p=vi({},p,{[b]:vi({},p[b],k)}),_&&m<=50&&(m++,typeof _=="object"&&(_.placement&&(f=_.placement),_.rects&&(u=_.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):_.rects),{x:d,y:h}=G3(u,f,l)),v=-1)}return{x:d,y:h,placement:f,strategy:r,middlewareData:p}};async function cA(e,t){var n;t===void 0&&(t={});const{x:s,y:r,platform:i,rects:a,elements:o,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:d="viewport",elementContext:h="floating",altBoundary:f=!1,padding:p=0}=jd(t,e),m=XW(p),v=o[f?h==="floating"?"reference":"floating":h],b=Ow(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(v)))==null||n?v:v.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:u,rootBoundary:d,strategy:l})),w=h==="floating"?{x:s,y:r,width:a.floating.width,height:a.floating.height}:a.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),y=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},k=Ow(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:w,offsetParent:C,strategy:l}):w);return{top:(b.top-k.top+m.top)/y.y,bottom:(k.bottom-b.bottom+m.bottom)/y.y,left:(b.left-k.left+m.left)/y.x,right:(k.right-b.right+m.right)/y.x}}const DYe=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:s,placement:r,rects:i,platform:a,elements:o,middlewareData:l}=t,{element:u,padding:d=0}=jd(e,t)||{};if(u==null)return{};const h=XW(d),f={x:n,y:s},p=lA(r),m=oA(p),v=await a.getDimensions(u),b=p==="y",w=b?"top":"left",C=b?"bottom":"right",y=b?"clientHeight":"clientWidth",k=i.reference[m]+i.reference[p]-f[p]-i.floating[m],_=f[p]-i.reference[p],E=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let R=E?E[y]:0;(!R||!await(a.isElement==null?void 0:a.isElement(E)))&&(R=o.floating[y]||i.floating[m]);const F=k/2-_/2,A=R/2-v[m]/2-1,N=Qf(h[w],A),M=Qf(h[C],A),D=N,L=R-v[m]-M,V=R/2-v[m]/2+F,j=Ik(D,V,L),te=!l.arrow&&Pl(r)!=null&&V!==j&&i.reference[m]/2-(V<D?N:M)-v[m]/2<0,X=te?V<D?V-D:V-L:0;return{[p]:f[p]+X,data:vi({[p]:j,centerOffset:V-j-X},te&&{alignmentOffset:X}),reset:te}}});function PYe(e,t,n){return(e?[...n.filter(s=>Pl(s)===e),...n.filter(s=>Pl(s)!==e)]:n.filter(s=>Ul(s)===s)).filter(s=>e?Pl(s)===e||(t?Nw(s)!==s:!1):!0)}const IYe=function(e){return e===void 0&&(e={}),{name:"autoPlacement",options:e,async fn(t){var n,s,r;const{rects:i,middlewareData:a,placement:o,platform:l,elements:u}=t,d=jd(e,t),{crossAxis:h=!1,alignment:f,allowedPlacements:p=U3,autoAlignment:m=!0}=d,v=sA(d,TYe),b=f!==void 0||p===U3?PYe(f||null,m,p):p,w=await cA(t,v),C=((n=a.autoPlacement)==null?void 0:n.index)||0,y=b[C];if(y==null)return{};const k=YW(y,i,await(l.isRTL==null?void 0:l.isRTL(u.floating)));if(o!==y)return{reset:{placement:b[0]}};const _=[w[Ul(y)],w[k[0]],w[k[1]]],E=[...((s=a.autoPlacement)==null?void 0:s.overflows)||[],{placement:y,overflows:_}],R=b[C+1];if(R)return{data:{index:C+1,overflows:E},reset:{placement:R}};const F=E.map(N=>{const M=Pl(N.placement);return[N.placement,M&&h?N.overflows.slice(0,2).reduce((D,L)=>D+L,0):N.overflows[0],N.overflows]}).sort((N,M)=>N[1]-M[1]),A=((r=F.filter(N=>N[2].slice(0,Pl(N[0])?2:3).every(M=>M<=0))[0])==null?void 0:r[0])||F[0][0];return A!==o?{data:{index:C+1,overflows:E},reset:{placement:A}}:{}}}},NYe=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:r,middlewareData:i,rects:a,initialPlacement:o,platform:l,elements:u}=t,d=jd(e,t),{mainAxis:h=!0,crossAxis:f=!0,fallbackPlacements:p,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:b=!0}=d,w=sA(d,RYe);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const C=Ul(r),y=Jf(o),k=Ul(o)===o,_=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=p||(k||!b?[Mw(o)]:_Ye(o)),R=v!=="none";!p&&R&&E.push(...EYe(o,b,v,_));const F=[o,...E],A=await cA(t,w),N=[];let M=((s=i.flip)==null?void 0:s.overflows)||[];if(h&&N.push(A[C]),f){const j=YW(r,a,_);N.push(A[j[0]],A[j[1]])}if(M=[...M,{placement:r,overflows:N}],!N.every(j=>j<=0)){var D,L;const j=(((D=i.flip)==null?void 0:D.index)||0)+1,te=F[j];if(te)return{data:{index:j,overflows:M},reset:{placement:te}};let X=(L=M.filter(re=>re.overflows[0]<=0).sort((re,G)=>re.overflows[1]-G.overflows[1])[0])==null?void 0:L.placement;if(!X)switch(m){case"bestFit":{var V;const re=(V=M.filter(G=>{if(R){const J=Jf(G.placement);return J===y||J==="y"}return!0}).map(G=>[G.placement,G.overflows.filter(J=>J>0).reduce((J,ae)=>J+ae,0)]).sort((G,J)=>G[1]-J[1])[0])==null?void 0:V[0];re&&(X=re);break}case"initialPlacement":X=o;break}if(r!==X)return{reset:{placement:X}}}return{}}}},MYe=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:r}=t,i=jd(e,t),{mainAxis:a=!0,crossAxis:o=!1,limiter:l={fn:w=>{let{x:C,y}=w;return{x:C,y}}}}=i,u=sA(i,AYe),d={x:n,y:s},h=await cA(t,u),f=Jf(Ul(r)),p=aA(f);let m=d[p],v=d[f];if(a){const w=p==="y"?"top":"left",C=p==="y"?"bottom":"right",y=m+h[w],k=m-h[C];m=Ik(y,m,k)}if(o){const w=f==="y"?"top":"left",C=f==="y"?"bottom":"right",y=v+h[w],k=v-h[C];v=Ik(y,v,k)}const b=l.fn(vi({},t,{[p]:m,[f]:v}));return vi({},b,{data:{x:b.x-n,y:b.y-s}})}}},OYe=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:s,placement:r,rects:i,middlewareData:a}=t,{offset:o=0,mainAxis:l=!0,crossAxis:u=!0}=jd(e,t),d={x:n,y:s},h=Jf(r),f=aA(h);let p=d[f],m=d[h];const v=jd(o,t),b=typeof v=="number"?{mainAxis:v,crossAxis:0}:vi({mainAxis:0,crossAxis:0},v);if(l){const y=f==="y"?"height":"width",k=i.reference[f]-i.floating[y]+b.mainAxis,_=i.reference[f]+i.reference[y]-b.mainAxis;p<k?p=k:p>_&&(p=_)}if(u){var w,C;const y=f==="y"?"width":"height",k=["top","left"].includes(Ul(r)),_=i.reference[h]-i.floating[y]+(k&&((w=a.offset)==null?void 0:w[h])||0)+(k?0:b.crossAxis),E=i.reference[h]+i.reference[y]+(k?0:((C=a.offset)==null?void 0:C[h])||0)-(k?b.crossAxis:0);m<_?m=_:m>E&&(m=E)}return{[f]:p,[h]:m}}}};function ZC(){return typeof window<"u"}function Sp(e){return QW(e)?(e.nodeName||"").toLowerCase():"#document"}function Oi(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Xo(e){var t;return(t=(QW(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function QW(e){return ZC()?e instanceof Node||e instanceof Oi(e).Node:!1}function Ya(e){return ZC()?e instanceof Element||e instanceof Oi(e).Element:!1}function Wo(e){return ZC()?e instanceof HTMLElement||e instanceof Oi(e).HTMLElement:!1}function V3(e){return!ZC()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Oi(e).ShadowRoot}function iv(e){const{overflow:t,overflowX:n,overflowY:s,display:r}=Xa(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&!["inline","contents"].includes(r)}function LYe(e){return["table","td","th"].includes(Sp(e))}function ey(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function uA(e){const t=dA(),n=Ya(e)?Xa(e):e;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(s=>(n.willChange||"").includes(s))||["paint","layout","strict","content"].some(s=>(n.contain||"").includes(s))}function BYe(e){let t=nu(e);for(;Wo(t)&&!Zf(t);){if(uA(t))return t;if(ey(t))return null;t=nu(t)}return null}function dA(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Zf(e){return["html","body","#document"].includes(Sp(e))}function Xa(e){return Oi(e).getComputedStyle(e)}function ty(e){return Ya(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function nu(e){if(Sp(e)==="html")return e;const t=e.assignedSlot||e.parentNode||V3(e)&&e.host||Xo(e);return V3(t)?t.host:t}function JW(e){const t=nu(e);return Zf(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wo(t)&&iv(t)?t:JW(t)}function _0(e,t,n){var s;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=JW(e),i=r===((s=e.ownerDocument)==null?void 0:s.body),a=Oi(r);if(i){const o=Nk(a);return t.concat(a,a.visualViewport||[],iv(r)?r:[],o&&n?_0(o):[])}return t.concat(r,_0(r,[],n))}function Nk(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function ZW(e){const t=Xa(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const r=Wo(e),i=r?e.offsetWidth:n,a=r?e.offsetHeight:s,o=Iw(n)!==i||Iw(s)!==a;return o&&(n=i,s=a),{width:n,height:s,$:o}}function hA(e){return Ya(e)?e:e.contextElement}function _f(e){const t=hA(e);if(!Wo(t))return Lo(1);const n=t.getBoundingClientRect(),{width:s,height:r,$:i}=ZW(t);let a=(i?Iw(n.width):n.width)/s,o=(i?Iw(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!o||!Number.isFinite(o))&&(o=1),{x:a,y:o}}const jYe=Lo(0);function e$(e){const t=Oi(e);return!dA()||!t.visualViewport?jYe:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HYe(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Oi(e)?!1:t}function Hd(e,t,n,s){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=hA(e);let a=Lo(1);t&&(s?Ya(s)&&(a=_f(s)):a=_f(e));const o=HYe(i,n,s)?e$(i):Lo(0);let l=(r.left+o.x)/a.x,u=(r.top+o.y)/a.y,d=r.width/a.x,h=r.height/a.y;if(i){const f=Oi(i),p=s&&Ya(s)?Oi(s):s;let m=f,v=Nk(m);for(;v&&s&&p!==m;){const b=_f(v),w=v.getBoundingClientRect(),C=Xa(v),y=w.left+(v.clientLeft+parseFloat(C.paddingLeft))*b.x,k=w.top+(v.clientTop+parseFloat(C.paddingTop))*b.y;l*=b.x,u*=b.y,d*=b.x,h*=b.y,l+=y,u+=k,m=Oi(v),v=Nk(m)}}return Ow({width:d,height:h,x:l,y:u})}function fA(e,t){const n=ty(e).scrollLeft;return t?t.left+n:Hd(Xo(e)).left+n}function t$(e,t,n){n===void 0&&(n=!1);const s=e.getBoundingClientRect(),r=s.left+t.scrollLeft-(n?0:fA(e,s)),i=s.top+t.scrollTop;return{x:r,y:i}}function UYe(e){let{elements:t,rect:n,offsetParent:s,strategy:r}=e;const i=r==="fixed",a=Xo(s),o=t?ey(t.floating):!1;if(s===a||o&&i)return n;let l={scrollLeft:0,scrollTop:0},u=Lo(1);const d=Lo(0),h=Wo(s);if((h||!h&&!i)&&((Sp(s)!=="body"||iv(a))&&(l=ty(s)),Wo(s))){const p=Hd(s);u=_f(s),d.x=p.x+s.clientLeft,d.y=p.y+s.clientTop}const f=a&&!h&&!i?t$(a,l,!0):Lo(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+f.x,y:n.y*u.y-l.scrollTop*u.y+d.y+f.y}}function GYe(e){return Array.from(e.getClientRects())}function VYe(e){const t=Xo(e),n=ty(e),s=e.ownerDocument.body,r=gd(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),i=gd(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let a=-n.scrollLeft+fA(e);const o=-n.scrollTop;return Xa(s).direction==="rtl"&&(a+=gd(t.clientWidth,s.clientWidth)-r),{width:r,height:i,x:a,y:o}}function WYe(e,t){const n=Oi(e),s=Xo(e),r=n.visualViewport;let i=s.clientWidth,a=s.clientHeight,o=0,l=0;if(r){i=r.width,a=r.height;const u=dA();(!u||u&&t==="fixed")&&(o=r.offsetLeft,l=r.offsetTop)}return{width:i,height:a,x:o,y:l}}function $Ye(e,t){const n=Hd(e,!0,t==="fixed"),s=n.top+e.clientTop,r=n.left+e.clientLeft,i=Wo(e)?_f(e):Lo(1),a=e.clientWidth*i.x,o=e.clientHeight*i.y,l=r*i.x,u=s*i.y;return{width:a,height:o,x:l,y:u}}function W3(e,t,n){let s;if(t==="viewport")s=WYe(e,n);else if(t==="document")s=VYe(Xo(e));else if(Ya(t))s=$Ye(t,n);else{const r=e$(e);s={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return Ow(s)}function n$(e,t){const n=nu(e);return n===t||!Ya(n)||Zf(n)?!1:Xa(n).position==="fixed"||n$(n,t)}function zYe(e,t){const n=t.get(e);if(n)return n;let s=_0(e,[],!1).filter(o=>Ya(o)&&Sp(o)!=="body"),r=null;const i=Xa(e).position==="fixed";let a=i?nu(e):e;for(;Ya(a)&&!Zf(a);){const o=Xa(a),l=uA(a);!l&&o.position==="fixed"&&(r=null),(i?!l&&!r:!l&&o.position==="static"&&r&&["absolute","fixed"].includes(r.position)||iv(a)&&!l&&n$(e,a))?s=s.filter(u=>u!==a):r=o,a=nu(a)}return t.set(e,s),s}function qYe(e){let{element:t,boundary:n,rootBoundary:s,strategy:r}=e;const i=[...n==="clippingAncestors"?ey(t)?[]:zYe(t,this._c):[].concat(n),s],a=i[0],o=i.reduce((l,u)=>{const d=W3(t,u,r);return l.top=gd(d.top,l.top),l.right=Qf(d.right,l.right),l.bottom=Qf(d.bottom,l.bottom),l.left=gd(d.left,l.left),l},W3(t,a,r));return{width:o.right-o.left,height:o.bottom-o.top,x:o.left,y:o.top}}function KYe(e){const{width:t,height:n}=ZW(e);return{width:t,height:n}}function YYe(e,t,n){const s=Wo(t),r=Xo(t),i=n==="fixed",a=Hd(e,!0,i,t);let o={scrollLeft:0,scrollTop:0};const l=Lo(0);if(s||!s&&!i)if((Sp(t)!=="body"||iv(r))&&(o=ty(t)),s){const f=Hd(t,!0,i,t);l.x=f.x+t.clientLeft,l.y=f.y+t.clientTop}else r&&(l.x=fA(r));const u=r&&!s&&!i?t$(r,o):Lo(0),d=a.left+o.scrollLeft-l.x-u.x,h=a.top+o.scrollTop-l.y-u.y;return{x:d,y:h,width:a.width,height:a.height}}function G1(e){return Xa(e).position==="static"}function $3(e,t){if(!Wo(e)||Xa(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Xo(e)===n&&(n=n.ownerDocument.body),n}function s$(e,t){const n=Oi(e);if(ey(e))return n;if(!Wo(e)){let r=nu(e);for(;r&&!Zf(r);){if(Ya(r)&&!G1(r))return r;r=nu(r)}return n}let s=$3(e,t);for(;s&&LYe(s)&&G1(s);)s=$3(s,t);return s&&Zf(s)&&G1(s)&&!uA(s)?n:s||BYe(e)||n}const XYe=async function(e){const t=this.getOffsetParent||s$,n=this.getDimensions,s=await n(e.floating);return{reference:YYe(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function QYe(e){return Xa(e).direction==="rtl"}const JYe={convertOffsetParentRelativeRectToViewportRelativeRect:UYe,getDocumentElement:Xo,getClippingRect:qYe,getOffsetParent:s$,getElementRects:XYe,getClientRects:GYe,getDimensions:KYe,getScale:_f,isElement:Ya,isRTL:QYe};function ZYe(e,t){let n=null,s;const r=Xo(e);function i(){var o;clearTimeout(s),(o=n)==null||o.disconnect(),n=null}function a(o,l){o===void 0&&(o=!1),l===void 0&&(l=1),i();const{left:u,top:d,width:h,height:f}=e.getBoundingClientRect();if(o||t(),!h||!f)return;const p=yb(d),m=yb(r.clientWidth-(u+h)),v=yb(r.clientHeight-(d+f)),b=yb(u),w={rootMargin:-p+"px "+-m+"px "+-v+"px "+-b+"px",threshold:gd(0,Qf(1,l))||1};let C=!0;function y(k){const _=k[0].intersectionRatio;if(_!==l){if(!C)return a();_?a(!1,_):s=setTimeout(()=>{a(!1,1e-7)},1e3)}C=!1}try{n=new IntersectionObserver(y,vi({},w,{root:r.ownerDocument}))}catch{n=new IntersectionObserver(y,w)}n.observe(e)}return a(!0),i}function eXe(e,t,n,s){s===void 0&&(s={});const{ancestorScroll:r=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:l=!1}=s,u=hA(e),d=r||i?[...u?_0(u):[],..._0(t)]:[];d.forEach(w=>{r&&w.addEventListener("scroll",n,{passive:!0}),i&&w.addEventListener("resize",n)});const h=u&&o?ZYe(u,n):null;let f=-1,p=null;a&&(p=new ResizeObserver(w=>{let[C]=w;C&&C.target===u&&p&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var y;(y=p)==null||y.observe(t)})),n()}),u&&!l&&p.observe(u),p.observe(t));let m,v=l?Hd(e):null;l&&b();function b(){const w=Hd(e);v&&(w.x!==v.x||w.y!==v.y||w.width!==v.width||w.height!==v.height)&&n(),v=w,m=requestAnimationFrame(b)}return n(),()=>{var w;d.forEach(C=>{r&&C.removeEventListener("scroll",n),i&&C.removeEventListener("resize",n)}),h?.(),(w=p)==null||w.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const tXe=IYe,nXe=MYe,sXe=NYe,rXe=DYe,iXe=OYe,aXe=(e,t,n)=>{const s=new Map,r=vi({platform:JYe},n),i=vi({},r.platform,{_c:s});return FYe(e,t,vi({},r,{platform:i}))};function oXe(e){e.cleanup&&e.cleanup();const t=e._getResolvedAttachToOptions();let n=t.element;const s=fXe(t,e),r=qW(t);return r&&(n=document.body,e.shepherdElementComponent.getElement().classList.add("shepherd-centered")),e.cleanup=eXe(n,e.el,()=>{if(!e.el){e.cleanup==null||e.cleanup();return}uXe(n,e,s,r)}),e.target=t.element,s}function lXe(e,t){return{floatingUIOptions:rA(e.floatingUIOptions||{},t.floatingUIOptions||{})}}function cXe(e){e.cleanup&&e.cleanup(),e.cleanup=null}function uXe(e,t,n,s){return aXe(e,t.el,n).then(dXe(t,s)).then(r=>new Promise(i=>{setTimeout(()=>i(r),300)})).then(r=>{r!=null&&r.el&&r.el.focus({preventScroll:!0})})}function dXe(e,t){return({x:n,y:s,placement:r,middlewareData:i})=>(e.el&&(t?Object.assign(e.el.style,{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}):Object.assign(e.el.style,{position:"absolute",left:`${n}px`,top:`${s}px`}),e.el.dataset.popperPlacement=r,hXe(e.el,i)),e)}function hXe(e,t){const n=e.querySelector(".shepherd-arrow");if(Xf(n)&&t.arrow){const{x:s,y:r}=t.arrow;Object.assign(n.style,{left:s!=null?`${s}px`:"",top:r!=null?`${r}px`:""})}}function fXe(e,t){var n,s,r;const i={strategy:"absolute"};i.middleware=[];const a=pXe(t),o=qW(e),l=(n=e.on)==null?void 0:n.includes("auto"),u=(e==null||(s=e.on)==null?void 0:s.includes("-start"))||(e==null||(r=e.on)==null?void 0:r.includes("-end"));if(!o){if(l){var d;i.middleware.push(tXe({crossAxis:!0,alignment:u?e==null||(d=e.on)==null?void 0:d.split("-").pop():null}))}else i.middleware.push(sXe());if(i.middleware.push(nXe({limiter:iXe(),crossAxis:!0})),a){const h=typeof t.options.arrow=="object"?t.options.arrow:{padding:4};i.middleware.push(rXe({element:a,padding:u?h.padding:0}))}l||(i.placement=e.on)}return rA(i,t.options.floatingUIOptions||{})}function pXe(e){return e.options.arrow&&e.el?e.el.querySelector(".shepherd-arrow"):!1}function ji(){}function gXe(e,t){for(const n in t)e[n]=t[n];return e}function r$(e){return e()}function z3(){return Object.create(null)}function av(e){e.forEach(r$)}function pA(e){return typeof e=="function"}function Jl(e,t){return e!=e?t==t:e!==t||e&&typeof e=="object"||typeof e=="function"}function mXe(e){return Object.keys(e).length===0}function ep(e,t){e.appendChild(t)}function no(e,t,n){e.insertBefore(t,n||null)}function ya(e){e.parentNode&&e.parentNode.removeChild(e)}function vXe(e,t){for(let n=0;n<e.length;n+=1)e[n]&&e[n].d(t)}function $o(e){return document.createElement(e)}function q3(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function i$(e){return document.createTextNode(e)}function Lw(){return i$(" ")}function bXe(){return i$("")}function ny(e,t,n,s){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}function Mn(e,t,n){n==null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n)}const xXe=["width","height"];function K3(e,t){const n=Object.getOwnPropertyDescriptors(e.__proto__);for(const s in t)t[s]==null?e.removeAttribute(s):s==="style"?e.style.cssText=t[s]:s==="__value"?e.value=e[s]=t[s]:n[s]&&n[s].set&&xXe.indexOf(s)===-1?e[s]=t[s]:Mn(e,s,t[s])}function wXe(e){return Array.from(e.childNodes)}function Eh(e,t,n){e.classList.toggle(t,!!n)}let S0;function xm(e){S0=e}function a$(){if(!S0)throw new Error("Function called outside component initialization");return S0}function CXe(e){a$().$$.on_mount.push(e)}function gA(e){a$().$$.after_update.push(e)}const Lh=[],tp=[];let Sf=[];const Y3=[],yXe=Promise.resolve();let Mk=!1;function _Xe(){Mk||(Mk=!0,yXe.then(o$))}function Ok(e){Sf.push(e)}const V1=new Set;let kh=0;function o$(){if(kh!==0)return;const e=S0;do{try{for(;kh<Lh.length;){const t=Lh[kh];kh++,xm(t),SXe(t.$$)}}catch(t){throw Lh.length=0,kh=0,t}for(xm(null),Lh.length=0,kh=0;tp.length;)tp.pop()();for(let t=0;t<Sf.length;t+=1){const n=Sf[t];V1.has(n)||(V1.add(n),n())}Sf.length=0}while(Lh.length);for(;Y3.length;)Y3.pop()();Mk=!1,V1.clear(),xm(e)}function SXe(e){if(e.fragment!==null){e.update(),av(e.before_update);const t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(Ok)}}function EXe(e){const t=[],n=[];Sf.forEach(s=>e.indexOf(s)===-1?t.push(s):n.push(s)),n.forEach(s=>s()),Sf=t}const ex=new Set;let Ju;function md(){Ju={r:0,c:[],p:Ju}}function vd(){Ju.r||av(Ju.c),Ju=Ju.p}function Sn(e,t){e&&e.i&&(ex.delete(e),e.i(t))}function ws(e,t,n,s){if(e&&e.o){if(ex.has(e))return;ex.add(e),Ju.c.push(()=>{ex.delete(e),s&&(n&&e.d(1),s())}),e.o(t)}else s&&s()}function X3(e){return e?.length!==void 0?e:Array.from(e)}function kXe(e,t){const n={},s={},r={$$scope:1};let i=e.length;for(;i--;){const a=e[i],o=t[i];if(o){for(const l in a)l in o||(s[l]=1);for(const l in o)r[l]||(n[l]=o[l],r[l]=1);e[i]=o}else for(const l in a)r[l]=1}for(const a in s)a in n||(n[a]=void 0);return n}function th(e){e&&e.c()}function fu(e,t,n){const{fragment:s,after_update:r}=e.$$;s&&s.m(t,n),Ok(()=>{const i=e.$$.on_mount.map(r$).filter(pA);e.$$.on_destroy?e.$$.on_destroy.push(...i):av(i),e.$$.on_mount=[]}),r.forEach(Ok)}function pu(e,t){const n=e.$$;n.fragment!==null&&(EXe(n.after_update),av(n.on_destroy),n.fragment&&n.fragment.d(t),n.on_destroy=n.fragment=null,n.ctx=[])}function TXe(e,t){e.$$.dirty[0]===-1&&(Lh.push(e),_Xe(),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<<t%31}function Zl(e,t,n,s,r,i,a=null,o=[-1]){const l=S0;xm(e);const u=e.$$={fragment:null,ctx:[],props:i,update:ji,not_equal:r,bound:z3(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(l?l.$$.context:[])),callbacks:z3(),dirty:o,skip_bound:!1,root:t.target||l.$$.root};a&&a(u.root);let d=!1;if(u.ctx=n?n(e,t.props||{},(h,f,...p)=>{const m=p.length?p[0]:f;return u.ctx&&r(u.ctx[h],u.ctx[h]=m)&&(!u.skip_bound&&u.bound[h]&&u.bound[h](m),d&&TXe(e,h)),f}):[],u.update(),d=!0,av(u.before_update),u.fragment=s?s(u.ctx):!1,t.target){if(t.hydrate){const h=wXe(t.target);u.fragment&&u.fragment.l(h),h.forEach(ya)}else u.fragment&&u.fragment.c();t.intro&&Sn(e.$$.fragment),fu(e,t.target,t.anchor),o$()}xm(l)}class ec{constructor(){this.$$=void 0,this.$$set=void 0}$destroy(){pu(this,1),this.$destroy=ji}$on(t,n){if(!pA(n))return ji;const s=this.$$.callbacks[t]||(this.$$.callbacks[t]=[]);return s.push(n),()=>{const r=s.indexOf(n);r!==-1&&s.splice(r,1)}}$set(t){this.$$set&&!mXe(t)&&(this.$$.skip_bound=!0,this.$$set(t),this.$$.skip_bound=!1)}}const RXe="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(RXe);function AXe(e){let t,n,s,r,i;return{c(){t=$o("button"),Mn(t,"aria-label",n=e[3]?e[3]:null),Mn(t,"class",s=`${e[1]||""} shepherd-button ${e[4]?"shepherd-button-secondary":""}`),t.disabled=e[2],Mn(t,"tabindex","0"),Mn(t,"type","button")},m(a,o){no(a,t,o),t.innerHTML=e[5],r||(i=ny(t,"click",function(){pA(e[0])&&e[0].apply(this,arguments)}),r=!0)},p(a,[o]){e=a,o&32&&(t.innerHTML=e[5]),o&8&&n!==(n=e[3]?e[3]:null)&&Mn(t,"aria-label",n),o&18&&s!==(s=`${e[1]||""} shepherd-button ${e[4]?"shepherd-button-secondary":""}`)&&Mn(t,"class",s),o&4&&(t.disabled=e[2])},i:ji,o:ji,d(a){a&&ya(t),r=!1,i()}}}function FXe(e,t,n){let{config:s,step:r}=t,i,a,o,l,u,d;function h(f){return tu(f)?f=f.call(r):f}return e.$$set=f=>{"config"in f&&n(6,s=f.config),"step"in f&&n(7,r=f.step)},e.$$.update=()=>{e.$$.dirty&192&&(n(0,i=s.action?s.action.bind(r.tour):null),n(1,a=s.classes),n(2,o=s.disabled?h(s.disabled):!1),n(3,l=s.label?h(s.label):null),n(4,u=s.secondary),n(5,d=s.text?h(s.text):null))},[i,a,o,l,u,d,s,r]}class DXe extends ec{constructor(t){super(),Zl(this,t,FXe,AXe,Jl,{config:6,step:7})}}function Q3(e,t,n){const s=e.slice();return s[2]=t[n],s}function J3(e){let t,n,s=X3(e[1]),r=[];for(let a=0;a<s.length;a+=1)r[a]=Z3(Q3(e,s,a));const i=a=>ws(r[a],1,1,()=>{r[a]=null});return{c(){for(let a=0;a<r.length;a+=1)r[a].c();t=bXe()},m(a,o){for(let l=0;l<r.length;l+=1)r[l]&&r[l].m(a,o);no(a,t,o),n=!0},p(a,o){if(o&3){s=X3(a[1]);let l;for(l=0;l<s.length;l+=1){const u=Q3(a,s,l);r[l]?(r[l].p(u,o),Sn(r[l],1)):(r[l]=Z3(u),r[l].c(),Sn(r[l],1),r[l].m(t.parentNode,t))}for(md(),l=s.length;l<r.length;l+=1)i(l);vd()}},i(a){if(!n){for(let o=0;o<s.length;o+=1)Sn(r[o]);n=!0}},o(a){r=r.filter(Boolean);for(let o=0;o<r.length;o+=1)ws(r[o]);n=!1},d(a){a&&ya(t),vXe(r,a)}}}function Z3(e){let t,n;return t=new DXe({props:{config:e[2],step:e[0]}}),{c(){th(t.$$.fragment)},m(s,r){fu(t,s,r),n=!0},p(s,r){const i={};r&2&&(i.config=s[2]),r&1&&(i.step=s[0]),t.$set(i)},i(s){n||(Sn(t.$$.fragment,s),n=!0)},o(s){ws(t.$$.fragment,s),n=!1},d(s){pu(t,s)}}}function PXe(e){let t,n,s=e[1]&&J3(e);return{c(){t=$o("footer"),s&&s.c(),Mn(t,"class","shepherd-footer")},m(r,i){no(r,t,i),s&&s.m(t,null),n=!0},p(r,[i]){r[1]?s?(s.p(r,i),i&2&&Sn(s,1)):(s=J3(r),s.c(),Sn(s,1),s.m(t,null)):s&&(md(),ws(s,1,1,()=>{s=null}),vd())},i(r){n||(Sn(s),n=!0)},o(r){ws(s),n=!1},d(r){r&&ya(t),s&&s.d()}}}function IXe(e,t,n){let s,{step:r}=t;return e.$$set=i=>{"step"in i&&n(0,r=i.step)},e.$$.update=()=>{e.$$.dirty&1&&n(1,s=r.options.buttons)},[r,s]}class NXe extends ec{constructor(t){super(),Zl(this,t,IXe,PXe,Jl,{step:0})}}function MXe(e){let t,n,s,r,i;return{c(){t=$o("button"),n=$o("span"),n.textContent="×",Mn(n,"aria-hidden","true"),Mn(t,"aria-label",s=e[0].label?e[0].label:"Close Tour"),Mn(t,"class","shepherd-cancel-icon"),Mn(t,"type","button")},m(a,o){no(a,t,o),ep(t,n),r||(i=ny(t,"click",e[1]),r=!0)},p(a,[o]){o&1&&s!==(s=a[0].label?a[0].label:"Close Tour")&&Mn(t,"aria-label",s)},i:ji,o:ji,d(a){a&&ya(t),r=!1,i()}}}function OXe(e,t,n){let{cancelIcon:s,step:r}=t;const i=a=>{a.preventDefault(),r.cancel()};return e.$$set=a=>{"cancelIcon"in a&&n(0,s=a.cancelIcon),"step"in a&&n(2,r=a.step)},[s,i,r]}class LXe extends ec{constructor(t){super(),Zl(this,t,OXe,MXe,Jl,{cancelIcon:0,step:2})}}function BXe(e){let t;return{c(){t=$o("h3"),Mn(t,"id",e[1]),Mn(t,"class","shepherd-title")},m(n,s){no(n,t,s),e[3](t)},p(n,[s]){s&2&&Mn(t,"id",n[1])},i:ji,o:ji,d(n){n&&ya(t),e[3](null)}}}function jXe(e,t,n){let{labelId:s,element:r,title:i}=t;gA(()=>{tu(i)&&n(2,i=i()),n(0,r.innerHTML=i,r)});function a(o){tp[o?"unshift":"push"](()=>{r=o,n(0,r)})}return e.$$set=o=>{"labelId"in o&&n(1,s=o.labelId),"element"in o&&n(0,r=o.element),"title"in o&&n(2,i=o.title)},[r,s,i,a]}class HXe extends ec{constructor(t){super(),Zl(this,t,jXe,BXe,Jl,{labelId:1,element:0,title:2})}}function e4(e){let t,n;return t=new HXe({props:{labelId:e[0],title:e[2]}}),{c(){th(t.$$.fragment)},m(s,r){fu(t,s,r),n=!0},p(s,r){const i={};r&1&&(i.labelId=s[0]),r&4&&(i.title=s[2]),t.$set(i)},i(s){n||(Sn(t.$$.fragment,s),n=!0)},o(s){ws(t.$$.fragment,s),n=!1},d(s){pu(t,s)}}}function t4(e){let t,n;return t=new LXe({props:{cancelIcon:e[3],step:e[1]}}),{c(){th(t.$$.fragment)},m(s,r){fu(t,s,r),n=!0},p(s,r){const i={};r&8&&(i.cancelIcon=s[3]),r&2&&(i.step=s[1]),t.$set(i)},i(s){n||(Sn(t.$$.fragment,s),n=!0)},o(s){ws(t.$$.fragment,s),n=!1},d(s){pu(t,s)}}}function UXe(e){let t,n,s,r=e[2]&&e4(e),i=e[3]&&e[3].enabled&&t4(e);return{c(){t=$o("header"),r&&r.c(),n=Lw(),i&&i.c(),Mn(t,"class","shepherd-header")},m(a,o){no(a,t,o),r&&r.m(t,null),ep(t,n),i&&i.m(t,null),s=!0},p(a,[o]){a[2]?r?(r.p(a,o),o&4&&Sn(r,1)):(r=e4(a),r.c(),Sn(r,1),r.m(t,n)):r&&(md(),ws(r,1,1,()=>{r=null}),vd()),a[3]&&a[3].enabled?i?(i.p(a,o),o&8&&Sn(i,1)):(i=t4(a),i.c(),Sn(i,1),i.m(t,null)):i&&(md(),ws(i,1,1,()=>{i=null}),vd())},i(a){s||(Sn(r),Sn(i),s=!0)},o(a){ws(r),ws(i),s=!1},d(a){a&&ya(t),r&&r.d(),i&&i.d()}}}function GXe(e,t,n){let{labelId:s,step:r}=t,i,a;return e.$$set=o=>{"labelId"in o&&n(0,s=o.labelId),"step"in o&&n(1,r=o.step)},e.$$.update=()=>{e.$$.dirty&2&&(n(2,i=r.options.title),n(3,a=r.options.cancelIcon))},[s,r,i,a]}class VXe extends ec{constructor(t){super(),Zl(this,t,GXe,UXe,Jl,{labelId:0,step:1})}}function WXe(e){let t;return{c(){t=$o("div"),Mn(t,"class","shepherd-text"),Mn(t,"id",e[1])},m(n,s){no(n,t,s),e[3](t)},p(n,[s]){s&2&&Mn(t,"id",n[1])},i:ji,o:ji,d(n){n&&ya(t),e[3](null)}}}function $Xe(e,t,n){let{descriptionId:s,element:r,step:i}=t;gA(()=>{let{text:o}=i.options;tu(o)&&(o=o.call(i)),Xf(o)?r.appendChild(o):n(0,r.innerHTML=o,r)});function a(o){tp[o?"unshift":"push"](()=>{r=o,n(0,r)})}return e.$$set=o=>{"descriptionId"in o&&n(1,s=o.descriptionId),"element"in o&&n(0,r=o.element),"step"in o&&n(2,i=o.step)},[r,s,i,a]}class zXe extends ec{constructor(t){super(),Zl(this,t,$Xe,WXe,Jl,{descriptionId:1,element:0,step:2})}}function n4(e){let t,n;return t=new VXe({props:{labelId:e[1],step:e[2]}}),{c(){th(t.$$.fragment)},m(s,r){fu(t,s,r),n=!0},p(s,r){const i={};r&2&&(i.labelId=s[1]),r&4&&(i.step=s[2]),t.$set(i)},i(s){n||(Sn(t.$$.fragment,s),n=!0)},o(s){ws(t.$$.fragment,s),n=!1},d(s){pu(t,s)}}}function s4(e){let t,n;return t=new zXe({props:{descriptionId:e[0],step:e[2]}}),{c(){th(t.$$.fragment)},m(s,r){fu(t,s,r),n=!0},p(s,r){const i={};r&1&&(i.descriptionId=s[0]),r&4&&(i.step=s[2]),t.$set(i)},i(s){n||(Sn(t.$$.fragment,s),n=!0)},o(s){ws(t.$$.fragment,s),n=!1},d(s){pu(t,s)}}}function r4(e){let t,n;return t=new NXe({props:{step:e[2]}}),{c(){th(t.$$.fragment)},m(s,r){fu(t,s,r),n=!0},p(s,r){const i={};r&4&&(i.step=s[2]),t.$set(i)},i(s){n||(Sn(t.$$.fragment,s),n=!0)},o(s){ws(t.$$.fragment,s),n=!1},d(s){pu(t,s)}}}function qXe(e){let t,n=!Dr(e[2].options.title)||e[2].options.cancelIcon&&e[2].options.cancelIcon.enabled,s,r=!Dr(e[2].options.text),i,a=Array.isArray(e[2].options.buttons)&&e[2].options.buttons.length,o,l=n&&n4(e),u=r&&s4(e),d=a&&r4(e);return{c(){t=$o("div"),l&&l.c(),s=Lw(),u&&u.c(),i=Lw(),d&&d.c(),Mn(t,"class","shepherd-content")},m(h,f){no(h,t,f),l&&l.m(t,null),ep(t,s),u&&u.m(t,null),ep(t,i),d&&d.m(t,null),o=!0},p(h,[f]){f&4&&(n=!Dr(h[2].options.title)||h[2].options.cancelIcon&&h[2].options.cancelIcon.enabled),n?l?(l.p(h,f),f&4&&Sn(l,1)):(l=n4(h),l.c(),Sn(l,1),l.m(t,s)):l&&(md(),ws(l,1,1,()=>{l=null}),vd()),f&4&&(r=!Dr(h[2].options.text)),r?u?(u.p(h,f),f&4&&Sn(u,1)):(u=s4(h),u.c(),Sn(u,1),u.m(t,i)):u&&(md(),ws(u,1,1,()=>{u=null}),vd()),f&4&&(a=Array.isArray(h[2].options.buttons)&&h[2].options.buttons.length),a?d?(d.p(h,f),f&4&&Sn(d,1)):(d=r4(h),d.c(),Sn(d,1),d.m(t,null)):d&&(md(),ws(d,1,1,()=>{d=null}),vd())},i(h){o||(Sn(l),Sn(u),Sn(d),o=!0)},o(h){ws(l),ws(u),ws(d),o=!1},d(h){h&&ya(t),l&&l.d(),u&&u.d(),d&&d.d()}}}function KXe(e,t,n){let{descriptionId:s,labelId:r,step:i}=t;return e.$$set=a=>{"descriptionId"in a&&n(0,s=a.descriptionId),"labelId"in a&&n(1,r=a.labelId),"step"in a&&n(2,i=a.step)},[s,r,i]}class YXe extends ec{constructor(t){super(),Zl(this,t,KXe,qXe,Jl,{descriptionId:0,labelId:1,step:2})}}function i4(e){let t;return{c(){t=$o("div"),Mn(t,"class","shepherd-arrow"),Mn(t,"data-popper-arrow","")},m(n,s){no(n,t,s)},d(n){n&&ya(t)}}}function XXe(e){let t,n,s,r,i,a,o,l,u=e[4].options.arrow&&e[4].options.attachTo&&e[4].options.attachTo.element&&e[4].options.attachTo.on&&i4();s=new YXe({props:{descriptionId:e[2],labelId:e[3],step:e[4]}});let d=[{"aria-describedby":r=Dr(e[4].options.text)?null:e[2]},{"aria-labelledby":i=e[4].options.title?e[3]:null},e[1],{open:"true"}],h={};for(let f=0;f<d.length;f+=1)h=gXe(h,d[f]);return{c(){t=$o("dialog"),u&&u.c(),n=Lw(),th(s.$$.fragment),K3(t,h),Eh(t,"shepherd-has-cancel-icon",e[5]),Eh(t,"shepherd-has-title",e[6]),Eh(t,"shepherd-element",!0)},m(f,p){no(f,t,p),u&&u.m(t,null),ep(t,n),fu(s,t,null),e[13](t),a=!0,o||(l=ny(t,"keydown",e[7]),o=!0)},p(f,[p]){f[4].options.arrow&&f[4].options.attachTo&&f[4].options.attachTo.element&&f[4].options.attachTo.on?u||(u=i4(),u.c(),u.m(t,n)):u&&(u.d(1),u=null);const m={};p&4&&(m.descriptionId=f[2]),p&8&&(m.labelId=f[3]),p&16&&(m.step=f[4]),s.$set(m),K3(t,h=kXe(d,[(!a||p&20&&r!==(r=Dr(f[4].options.text)?null:f[2]))&&{"aria-describedby":r},(!a||p&24&&i!==(i=f[4].options.title?f[3]:null))&&{"aria-labelledby":i},p&2&&f[1],{open:"true"}])),Eh(t,"shepherd-has-cancel-icon",f[5]),Eh(t,"shepherd-has-title",f[6]),Eh(t,"shepherd-element",!0)},i(f){a||(Sn(s.$$.fragment,f),a=!0)},o(f){ws(s.$$.fragment,f),a=!1},d(f){f&&ya(t),u&&u.d(),pu(s),e[13](null),o=!1,l()}}}const QXe=9,JXe=27,ZXe=37,eQe=39;function a4(e){return e.split(" ").filter(t=>!!t.length)}function tQe(e,t,n){let{classPrefix:s,element:r,descriptionId:i,firstFocusableElement:a,focusableElements:o,labelId:l,lastFocusableElement:u,step:d,dataStepId:h}=t,f,p,m;const v=()=>r;CXe(()=>{n(1,h={[`data-${s}shepherd-step-id`]:d.id}),n(9,o=r.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]')),n(8,a=o[0]),n(10,u=o[o.length-1])}),gA(()=>{m!==d.options.classes&&b()});function b(){w(m),m=d.options.classes,C(m)}function w(_){if(y0(_)){const E=a4(_);E.length&&r.classList.remove(...E)}}function C(_){if(y0(_)){const E=a4(_);E.length&&r.classList.add(...E)}}const y=_=>{const{tour:E}=d;switch(_.keyCode){case QXe:if(o.length===0){_.preventDefault();break}_.shiftKey?(document.activeElement===a||document.activeElement.classList.contains("shepherd-element"))&&(_.preventDefault(),u.focus()):document.activeElement===u&&(_.preventDefault(),a.focus());break;case JXe:E.options.exitOnEsc&&(_.preventDefault(),_.stopPropagation(),d.cancel());break;case ZXe:E.options.keyboardNavigation&&(_.preventDefault(),_.stopPropagation(),E.back());break;case eQe:E.options.keyboardNavigation&&(_.preventDefault(),_.stopPropagation(),E.next());break}};function k(_){tp[_?"unshift":"push"](()=>{r=_,n(0,r)})}return e.$$set=_=>{"classPrefix"in _&&n(11,s=_.classPrefix),"element"in _&&n(0,r=_.element),"descriptionId"in _&&n(2,i=_.descriptionId),"firstFocusableElement"in _&&n(8,a=_.firstFocusableElement),"focusableElements"in _&&n(9,o=_.focusableElements),"labelId"in _&&n(3,l=_.labelId),"lastFocusableElement"in _&&n(10,u=_.lastFocusableElement),"step"in _&&n(4,d=_.step),"dataStepId"in _&&n(1,h=_.dataStepId)},e.$$.update=()=>{e.$$.dirty&16&&(n(5,f=d.options&&d.options.cancelIcon&&d.options.cancelIcon.enabled),n(6,p=d.options&&d.options.title))},[r,h,i,l,d,f,p,y,a,o,u,s,v,k]}class nQe extends ec{constructor(t){super(),Zl(this,t,tQe,XXe,Jl,{classPrefix:11,element:0,descriptionId:2,firstFocusableElement:8,focusableElements:9,labelId:3,lastFocusableElement:10,step:4,dataStepId:1,getElement:12})}get getElement(){return this.$$.ctx[12]}}class Lk extends nA{constructor(t,n={}){return super(),this._resolvedAttachTo=void 0,this._resolvedExtraHighlightElements=void 0,this.classPrefix=void 0,this.el=void 0,this.target=void 0,this.tour=void 0,this.tour=t,this.classPrefix=this.tour.options?zW(this.tour.options.classPrefix):"",this.styles=t.styles,this._resolvedAttachTo=null,iA(this),this._setOptions(n),this}cancel(){this.tour.cancel(),this.trigger("cancel")}complete(){this.tour.complete(),this.trigger("complete")}destroy(){cXe(this),Xf(this.el)&&(this.el.remove(),this.el=null),this._updateStepTargetOnHide(),this.trigger("destroy")}getTour(){return this.tour}hide(){var t;(t=this.tour.modal)==null||t.hide(),this.trigger("before-hide"),this.el&&(this.el.hidden=!0),this._updateStepTargetOnHide(),this.trigger("hide")}_resolveExtraHiglightElements(){return this._resolvedExtraHighlightElements=xYe(this),this._resolvedExtraHighlightElements}_resolveAttachToOptions(){return this._resolvedAttachTo=bYe(this),this._resolvedAttachTo}_getResolvedAttachToOptions(){return this._resolvedAttachTo===null?this._resolveAttachToOptions():this._resolvedAttachTo}isOpen(){return!!(this.el&&!this.el.hidden)}show(){return tu(this.options.beforeShowPromise)?Promise.resolve(this.options.beforeShowPromise()).then(()=>this._show()):Promise.resolve(this._show())}updateStepOptions(t){Object.assign(this.options,t),this.shepherdElementComponent&&this.shepherdElementComponent.$set({step:this})}getElement(){return this.el}getTarget(){return this.target}_createTooltipContent(){const t=`${this.id}-description`,n=`${this.id}-label`;return this.shepherdElementComponent=new nQe({target:this.tour.options.stepsContainer||document.body,props:{classPrefix:this.classPrefix,descriptionId:t,labelId:n,step:this,styles:this.styles}}),this.shepherdElementComponent.getElement()}_scrollTo(t){const{element:n}=this._getResolvedAttachToOptions();tu(this.options.scrollToHandler)?this.options.scrollToHandler(n):QKe(n)&&typeof n.scrollIntoView=="function"&&n.scrollIntoView(t)}_getClassOptions(t){const n=this.tour&&this.tour.options&&this.tour.options.defaultStepOptions,s=t.classes?t.classes:"",r=n&&n.classes?n.classes:"",i=[...s.split(" "),...r.split(" ")],a=new Set(i);return Array.from(a).join(" ").trim()}_setOptions(t={}){let n=this.tour&&this.tour.options&&this.tour.options.defaultStepOptions;n=rA({},n||{}),this.options=Object.assign({arrow:!0},n,t,lXe(n,t));const{when:s}=this.options;this.options.classes=this._getClassOptions(t),this.destroy(),this.id=this.options.id||`step-${KW()}`,s&&Object.keys(s).forEach(r=>{this.on(r,s[r],this)})}_setupElements(){Dr(this.el)||this.destroy(),this.el=this._createTooltipContent(),this.options.advanceOn&&gYe(this),oXe(this)}_show(){var t;this.trigger("before-show"),this._resolveAttachToOptions(),this._resolveExtraHiglightElements(),this._setupElements(),this.tour.modal||this.tour.setupModal(),(t=this.tour.modal)==null||t.setupForStep(this),this._styleTargetElementForStep(this),this.el&&(this.el.hidden=!1),this.options.scrollTo&&setTimeout(()=>{this._scrollTo(this.options.scrollTo)}),this.el&&(this.el.hidden=!1);const n=this.shepherdElementComponent.getElement(),s=this.target||document.body,r=this._resolvedExtraHighlightElements;s.classList.add(`${this.classPrefix}shepherd-enabled`),s.classList.add(`${this.classPrefix}shepherd-target`),n.classList.add("shepherd-enabled"),r?.forEach(i=>{i.classList.add(`${this.classPrefix}shepherd-enabled`),i.classList.add(`${this.classPrefix}shepherd-target`)}),this.trigger("show")}_styleTargetElementForStep(t){const n=t.target,s=t._resolvedExtraHighlightElements;if(!n)return;const r=t.options.highlightClass;r&&(n.classList.add(r),s?.forEach(i=>i.classList.add(r))),n.classList.remove("shepherd-target-click-disabled"),s?.forEach(i=>i.classList.remove("shepherd-target-click-disabled")),t.options.canClickTarget===!1&&(n.classList.add("shepherd-target-click-disabled"),s?.forEach(i=>i.classList.add("shepherd-target-click-disabled")))}_updateStepTargetOnHide(){const t=this.target||document.body,n=this._resolvedExtraHighlightElements,s=this.options.highlightClass;s&&(t.classList.remove(s),n?.forEach(r=>r.classList.remove(s))),t.classList.remove("shepherd-target-click-disabled",`${this.classPrefix}shepherd-enabled`,`${this.classPrefix}shepherd-target`),n?.forEach(r=>{r.classList.remove("shepherd-target-click-disabled",`${this.classPrefix}shepherd-enabled`,`${this.classPrefix}shepherd-target`)})}}function sQe(e){if(e){const{steps:t}=e;t.forEach(n=>{n.options&&n.options.canClickTarget===!1&&n.options.attachTo&&(Xf(n.target)&&n.target.classList.remove("shepherd-target-click-disabled"),n._resolvedExtraHighlightElements&&n._resolvedExtraHighlightElements.forEach(s=>{Xf(s)&&s.classList.remove("shepherd-target-click-disabled")}))})}}function rQe(e){let t="";const{innerWidth:n,innerHeight:s}=window;return e.forEach(r=>{const{width:i,height:a,x:o=0,y:l=0,r:u=0}=r,{topLeft:d=0,topRight:h=0,bottomRight:f=0,bottomLeft:p=0}=typeof u=="number"?{topLeft:u,topRight:u,bottomRight:u,bottomLeft:u}:u;t+=`M${o+d},${l} a${d},${d},0,0,0-${d},${d} V${a+l-p} a${p},${p},0,0,0,${p},${p} H${i+o-f} a${f},${f},0,0,0,${f}-${f} V${l+h} a${h},${h},0,0,0-${h}-${h} Z`}),`M${n},${s} H0 V0 H${n} V${s} Z ${t}`.replace(/\s/g,"")}function iQe(e){let t,n,s,r,i;return{c(){t=q3("svg"),n=q3("path"),Mn(n,"d",e[2]),Mn(t,"class",s=`${e[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)},m(a,o){no(a,t,o),ep(t,n),e[11](t),r||(i=ny(t,"touchmove",e[3]),r=!0)},p(a,[o]){o&4&&Mn(n,"d",a[2]),o&2&&s!==(s=`${a[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)&&Mn(t,"class",s)},i:ji,o:ji,d(a){a&&ya(t),e[11](null),r=!1,i()}}}function l$(e){if(!e)return null;const t=e instanceof HTMLElement&&window.getComputedStyle(e).overflowY;return t!=="hidden"&&t!=="visible"&&e.scrollHeight>=e.clientHeight?e:l$(e.parentElement)}function aQe(e){let t={top:0,left:0};if(!e)return t;let n=e.ownerDocument.defaultView;for(;n!==window.top;){var s;const a=(s=n)==null?void 0:s.frameElement;if(a){var r,i;const o=a.getBoundingClientRect();t.top+=o.top+((r=o.scrollTop)!=null?r:0),t.left+=o.left+((i=o.scrollLeft)!=null?i:0)}n=n.parent}return t}function oQe(e,t){const n=e.getBoundingClientRect();let s=n.y||n.top,r=n.bottom||s+n.height;if(t){const a=t.getBoundingClientRect(),o=a.y||a.top,l=a.bottom||o+a.height;s=Math.max(s,o),r=Math.min(r,l)}const i=Math.max(r-s,0);return{y:s,height:i}}function lQe(e,t,n){let{element:s,openingProperties:r}=t,i=!1,a,o;u();const l=()=>s;function u(){n(4,r=[{width:0,height:0,x:0,y:0,r:0}])}function d(){n(1,i=!1),w()}function h(k=0,_=0,E=0,R=0,F,A,N){if(A){const M=[A,...N||[]];n(4,r=[]);for(const D of M){if(!D||M.indexOf(D)!==M.lastIndexOf(D))continue;const{y:L,height:V}=oQe(D,F),{x:j,width:te,left:X}=D.getBoundingClientRect();M.some(re=>{if(re===D)return!1;const G=re.getBoundingClientRect();return j>=G.left&&j+te<=G.right&&L>=G.top&&L+V<=G.bottom})||r.push({width:te+k*2,height:V+k*2,x:(j||X)+E-k,y:L+R-k,r:_})}}else u()}function f(k){w(),k.tour.options.useModalOverlay?(C(k),p()):d()}function p(){n(1,i=!0)}const m=k=>{k.preventDefault()},v=k=>{k.stopPropagation()};function b(){window.addEventListener("touchmove",m,{passive:!1})}function w(){a&&(cancelAnimationFrame(a),a=void 0),window.removeEventListener("touchmove",m,{passive:!1})}function C(k){const{modalOverlayOpeningPadding:_,modalOverlayOpeningRadius:E,modalOverlayOpeningXOffset:R=0,modalOverlayOpeningYOffset:F=0}=k.options,A=aQe(k.target),N=l$(k.target),M=()=>{a=void 0,h(_,E,R+A.left,F+A.top,N,k.target,k._resolvedExtraHighlightElements),a=requestAnimationFrame(M)};M(),b()}function y(k){tp[k?"unshift":"push"](()=>{s=k,n(0,s)})}return e.$$set=k=>{"element"in k&&n(0,s=k.element),"openingProperties"in k&&n(4,r=k.openingProperties)},e.$$.update=()=>{e.$$.dirty&16&&n(2,o=rQe(r))},[s,i,o,v,r,l,u,d,h,f,p,y]}class cQe extends ec{constructor(t){super(),Zl(this,t,lQe,iQe,Jl,{element:0,openingProperties:4,getElement:5,closeModalOpening:6,hide:7,positionModal:8,setupForStep:9,show:10})}get getElement(){return this.$$.ctx[5]}get closeModalOpening(){return this.$$.ctx[6]}get hide(){return this.$$.ctx[7]}get positionModal(){return this.$$.ctx[8]}get setupForStep(){return this.$$.ctx[9]}get show(){return this.$$.ctx[10]}}class uQe extends nA{constructor(){super(),this.activeTour=void 0,iA(this)}}class dQe extends nA{constructor(t={}){super(),this.trackedEvents=["active","cancel","complete","show"],this.classPrefix=void 0,this.currentStep=void 0,this.focusedElBeforeOpen=void 0,this.id=void 0,this.modal=void 0,this.options=void 0,this.steps=void 0,iA(this);const n={exitOnEsc:!0,keyboardNavigation:!0};return this.options=Object.assign({},n,t),this.classPrefix=zW(this.options.classPrefix),this.steps=[],this.addSteps(this.options.steps),["active","cancel","complete","inactive","show","start"].map(s=>{(r=>{this.on(r,i=>{i=i||{},i.tour=this,Zu.trigger(r,i)})})(s)}),this._setTourID(t.id),this}addStep(t,n){let s=t;return s instanceof Lk?s.tour=this:s=new Lk(this,s),Dr(n)?this.steps.push(s):this.steps.splice(n,0,s),s}addSteps(t){return Array.isArray(t)&&t.forEach(n=>{this.addStep(n)}),this}back(){const t=this.steps.indexOf(this.currentStep);this.show(t-1,!1)}async cancel(){if(this.options.confirmCancel){const t=this.options.confirmCancelMessage||"Are you sure you want to stop the tour?";let n;tu(this.options.confirmCancel)?n=await this.options.confirmCancel():n=window.confirm(t),n&&this._done("cancel")}else this._done("cancel")}complete(){this._done("complete")}getById(t){return this.steps.find(n=>n.id===t)}getCurrentStep(){return this.currentStep}hide(){const t=this.getCurrentStep();if(t)return t.hide()}isActive(){return Zu.activeTour===this}next(){const t=this.steps.indexOf(this.currentStep);t===this.steps.length-1?this.complete():this.show(t+1,!0)}removeStep(t){const n=this.getCurrentStep();this.steps.some((s,r)=>{if(s.id===t)return s.isOpen()&&s.hide(),s.destroy(),this.steps.splice(r,1),!0}),n&&n.id===t&&(this.currentStep=void 0,this.steps.length?this.show(0):this.cancel())}show(t=0,n=!0){const s=y0(t)?this.getById(t):this.steps[t];s&&(this._updateStateBeforeShow(),tu(s.options.showOn)&&!s.options.showOn()?this._skipStep(s,n):(this.currentStep=s,this.trigger("show",{step:s,previous:this.currentStep}),s.show()))}async start(){this.trigger("start"),this.focusedElBeforeOpen=document.activeElement,this.currentStep=null,this.setupModal(),this._setupActiveTour(),this.next()}_done(t){const n=this.steps.indexOf(this.currentStep);if(Array.isArray(this.steps)&&this.steps.forEach(s=>s.destroy()),sQe(this),this.trigger(t,{index:n}),Zu.activeTour=null,this.trigger("inactive",{tour:this}),this.modal&&this.modal.hide(),(t==="cancel"||t==="complete")&&this.modal){const s=document.querySelector(".shepherd-modal-overlay-container");s&&(s.remove(),this.modal=null)}Xf(this.focusedElBeforeOpen)&&this.focusedElBeforeOpen.focus()}_setupActiveTour(){this.trigger("active",{tour:this}),Zu.activeTour=this}setupModal(){this.modal=new cQe({target:this.options.modalContainer||document.body,props:{styles:this.styles}})}_skipStep(t,n){const s=this.steps.indexOf(t);if(s===this.steps.length-1)this.complete();else{const r=n?s+1:s-1;this.show(r,n)}}_updateStateBeforeShow(){this.currentStep&&this.currentStep.hide(),this.isActive()||this._setupActiveTour()}_setTourID(t){const n=this.options.tourName||"tour",s=t||KW();this.id=`${n}--${s}`}}const Zu=new uQe,c$=typeof window>"u";Zu.Step=c$?mYe:Lk;Zu.Tour=c$?vYe:dQe;const sy=g.createContext(void 0);sy.Consumer;const hQe=({children:e})=>XKe.jsx(sy.Provider,{value:{Shepherd:Zu},children:e}),fQe=""+new URL("agentic-sequence-CExfswgi.png",import.meta.url).href,pQe=""+new URL("canvas-code-inline-edit-DLji9b0m.png",import.meta.url).href,gQe=""+new URL("canvas-overview-CruGEIRC.png",import.meta.url).href,mQe=""+new URL("canvas-variables-view-DrA20zqs.png",import.meta.url).href,vQe=""+new URL("chat-attachments-_3cRrONU.png",import.meta.url).href,bQe=""+new URL("chat-full-view-e-eJPzrw.png",import.meta.url).href,xQe=""+new URL("chat-input-CU-CA7Se.png",import.meta.url).href,wQe=""+new URL("inline-edit-canvas-O9conTkE.png",import.meta.url).href,CQe=e=>{const t=Array.from(document.querySelectorAll(`[data-tour-tag="${e}"]`));return t.find(n=>n.offsetParent!==null)??t[0]??null},o4=e=>{document.querySelector(`[data-tour-action="${e}"]`)?.click()},l4=[{id:"welcome",title:"Welcome to Local Operator",text:`Local Operator is an AI agents platform that allows you to create a team of proactive AI agents that support you and help to reduce your daily workload.<br/><img src="${bQe}" alt="Chat full view" style="width: 100%; height: 350px; object-fit: contain; border-radius: 8px;"/><br />These agents are different from simple chatbots because they can actually do things for you on your computer like create files, run code and analytics, edit images, videos, and PDFs, organize your system, and much more.<br/><br/>In this walkthrough we'll cover:<ul><li>Creating agents</li><li>Making agents do things</li><li>The canvas workspace</li><li>Customizing agents</li><li>Agent hub for sharing and collaborating</li><li>Schedules for proactive agents</li><li>Settings for customization</li></ul>Let's explore how it works.`,buttons:[{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"agent-list",attachTo:{element:'[data-tour-tag="agent-list-panel"]',on:"right"},title:"Your agents",text:"On the left, you'll see a list of your available AI agents. You can select an agent to start a conversation or manage its settings. Think of this as your messenger contacts list, but for AI agents. There are no limits to how many agents you can have, so create as many as you need to handle all your daily tasks.<br/><br/>Use the create agents button at the top of the toolbar to create a new agent at any time. You can also import agents from the Agent hub, which we will cover later in this tour.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-agent",attachTo:{element:'[data-tour-tag="agent-list-item-button-0"]',on:"right"},title:"Select an agent",text:"Click on an agent to open the chat window to pull up your conversation with it. This will show the messages that you have sent them and the responses and actions that they have taken.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="agent-list-item-button-0"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"chat-input",attachTo:{element:'[data-tour-tag="chat-input-textarea"]',on:"top"},title:"Ask your agent anything",text:`Type your request here. Agents can answer questions, perform tasks, search the web, and much more. When you create a new agent, you'll see suggested prompts for ideas.<br /><br />Some powerful requests that you can try:<br /><br /><ul><li>"Create a spreadsheet in my Documents folder with all the major cities in Canada."</li><li>"Search the web for the latest news on AI and make a thorough report."</li><li>Select an attachment and then "translate this document to French."</li></ul><br /><img src="${xQe}" alt="Chat input" style="width: 100%; height: 200px; object-fit: contain; border-radius: 8px;"/><br />You can also attach files to your message by clicking the paperclip button, which we will cover in the next step.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"attachments",attachTo:{element:'button[data-tour-tag="chat-input-attach-file-button"]',on:"top"},title:"Attach files to your message",text:`You can attach any files, images, or documents to your message by clicking this paperclip button, there are no limitations on the file types. Your agent can process, analyze, or translate these attachments as part of your request.<br /><br />Try attaching a PDF, image, or text file and then ask your agent to summarize, translate, or extract information from it.<br /><img src="${vQe}" alt="Chat attachments" style="width: 100%; height: 200px; object-fit: contain; border-radius: 8px;"/><br />Images like PNGs, JPGs, and PDFs are natively streamed into the model context window, so they can understand them directly without needing to run any code. Other files like Excel, Word, and CSV files are included as file paths on your device to direct the model's attention to work with them using code. You can attach massive files like million line CSVs and have the agent work with them using code.<br /><br />You can also paste images into the chat input, and attach multiple files at once to achieve more complex tasks. Try taking a screenshot of a website and then asking your agent to try to code it.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"agent-capabilities",attachTo:{element:'[data-tour-tag="chat-header"]',on:"top"},title:"More than just chat",text:`Local Operator agents are different from simple chatbots. They can perform actions on your computer, like creating files, running code, or browsing the web, based on your instructions. You'll see them use "tools" like reading, writing, and executing code to get things done. Agents have memory of the conversation, previous steps, learnings, and even store the execution variables of previous steps in code to be able to use them later in the conversation.<br /><img src="${fQe}" alt="Agentic sequence" style="width: 100%; height: 350px; object-fit: contain; border-radius: 8px;"/><br />Local Operator agents are extremely flexible, so they can bounce back and forth with you for simple chatting, and know when they need to embark on a work journey to get things done in multiple steps with tool use.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const{openCommandPalette:e}=qe.getState();e(),setTimeout(()=>{this.next()},500)}}]},{id:"pre-command-palette-open-canvas",title:"Command palette",attachTo:{element:'[data-tour-tag="command-palette-dialog"]',on:"right"},text:`Let's quickly look at another powerful feature: the Command Palette. You can open it anywhere in the app by pressing <code>${ko("everything",!0)}</code> on Mac and <code>${ko("everything",!1)}</code> on Windows or Linux. This is a helpful window that you can open from anywhere in the app to be able to access your chats, agents, settings, pages and actions, and much more, using your keyboard. It can often be faster to access sections in the app this way instead of clicking through menus. Type a word to search everything at once, or start with a prefix to narrow it: <code>#</code> for chats, <code>@</code> for agents and teams, <code>,</code> for settings, and <code>></code> for commands and pages.<br /><br />In a hurry for a conversation? Press <code>${ko("chats",!0)}</code> on Mac and <code>${ko("chats",!1)}</code> on Windows or Linux and the palette opens already searching your chats, so you can jump straight to one — and <code>${ko("commands",!0)}</code> on Mac and <code>${ko("commands",!1)}</code> on Windows or Linux opens it on the app's own commands and pages when that is what you are after. You can also just click Search in the sidebar to open it.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const{closeCommandPalette:e}=qe.getState();e(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const{closeCommandPalette:e}=qe.getState();e(),setTimeout(()=>{this.next()},500)}}]},{id:"canvas-open-button",attachTo:{element:'button[data-tour-tag="open-canvas-button"]',on:"left"},title:"Open the canvas",text:"Click here to open the Canvas, a workspace for files and dynamic visualizations where you can organize, plan, and interact with your agents in a more flexible way.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const{openCommandPalette:e}=qe.getState();e(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="open-canvas-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"canvas-feature",attachTo:{element:'[data-tour-tag="canvas-container"]',on:"left"},title:"The canvas: your visual workspace",text:`This is the Canvas, your workspace for files and dynamic visualizations where you can organize, plan, and interact with your agents in a more flexible way. Any files that your agents create on your device can be opened here by clicking on the file icons that you see as they work.<br/><br/>Agents can make dynamic visualizations like games, charts, maps, and more in HTML files. Any HTML files you open will be rendered dynamically in an iframe. Any markdown files that you open will be rendered in full markdown viewer with support for code blocks, tables, mermaid diagrams, and more.<br/><img src="${gQe}" alt="Canvas overview" style="width: 100%; height: 300px; object-fit: contain; border-radius: 8px;"/>`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="close-canvas-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="canvas-documents-view-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"canvas-documents-view",attachTo:{element:'button[data-tour-tag="canvas-documents-view-button"]',on:"top"},title:"Documents view",text:`The Documents view shows all your open notes, blog articles, code, and visualizations as tabs. You can switch between documents to edit them and see dynamic visualizations in HTML created by your agents. Use this view to work with your notes, reports, and agent-generated content.<br /><br />This is where you can get more precise around your agents' work.<br/><img src="${wQe}" alt="Inline edit canvas" style="width: 100%; height: 200px; object-fit: contain; border-radius: 8px;"/><br />In your documents, highlight any text that you want your agent to improve and press Cmd/Ctrl+K to bring up the inline AI editor.
|
|
683
683
|
<br /><img src="${pQe}" alt="Canvas code inline edit" style="width: 100%; height: 200px; object-fit: cover; object-position: top; border-radius: 8px;"/><br />You can be as precise as you want and the agent will edit the document for you in place, using its memories and context so you don't have to re-explain things.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="canvas-files-view-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"canvas-files-view",attachTo:{element:'button[data-tour-tag="canvas-files-view-button"]',on:"top"},title:"Files view",text:"The Files view lets you browse and open files that your agents have created or that are relevant to your current conversation. Use this to quickly access, preview, and open files in the Canvas workspace.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('button[data-tour-tag="canvas-documents-view-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="canvas-variables-view-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"canvas-variables-view",attachTo:{element:'button[data-tour-tag="canvas-variables-view-button"]',on:"top"},title:"Variables view",text:`The Variables view displays the "code memory" that agents have stored during their work. These are technical variables that include results, intermediate values, and other data that agents use to perform tasks. You can inspect and manage these variables here.<br /><br />This section will be most helpful for more technical users who want to understand how agents are working and what they are doing.<br/><img src="${mQe}" alt="Canvas variables" style="width: 100%; height: 350px; object-fit: contain; border-radius: 8px;"/>`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('button[data-tour-tag="canvas-files-view-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="close-canvas-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"agent-options",attachTo:{element:'button[data-tour-tag="agent-options-button"]',on:"right"},title:"Agent options",text:"Click here to see options for the currently selected agent, like viewing its settings, exporting it, or deleting it.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('button[data-tour-tag="open-canvas-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="agent-options-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"click-view-settings-from-chat",attachTo:{element:'[role="menuitem"][data-tour-tag="view-agent-settings-menu-item"]',on:"right"},title:"View configuration",text:'Click "View agent settings" to see and change how this agent works and change things like its name, description, hosting provider, and AI model.',buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[role="menuitem"][data-tour-tag="view-agent-settings-menu-item"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"view-agent-settings",attachTo:{element:'div[data-tour-tag="agent-settings-details-paper"]',on:"left"},title:"Agent configuration",text:"This is where you can customize and configure your agent. You can change its name, description, the AI model it uses, its temperature for creativity, and other chat settings.<br /><br />The agents will already have default settings that work well for most use cases, but if you want to roll up your sleeves and customize, you can do so here.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-chat"]');e&&e.click(),setTimeout(()=>{const t=document.querySelector('button[data-tour-tag="agent-options-button"]');t&&t.click()},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-provider",attachTo:{element:'[data-tour-tag="agent-settings-hosting-select"]',on:"left"},title:"Select hosting provider",text:`Choose an AI provider for your agent. If you don't pick one here, then the default provider from the settings page will be used. Providers offer different AI models and pricing. Radient is recommended for Local Operator as its "Automatic" mode is optimized for the lowest cost and best performance.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-model",attachTo:{element:'[data-tour-tag="agent-settings-model-select"]',on:"left"},title:"Select AI model",text:"After selecting a provider, choose an AI model. Models marked as 'Recommended' are known to work well with Local Operator. Other models might have inconsistent performance. If a model you expect to be recommended isn't listed, please let us know if it works well for you in Local Operator via GitHub Issues or email.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"modify-security-prompt",attachTo:{element:'[data-tour-tag="agent-settings-security"]',on:"left"},title:"Customize security behaviors",text:"This prompt provides separate instructions to the security agent that reviews this agent's work. You can explicitly allow certain actions that would normally be blocked. If you encounter frequent security interventions, consider adding a note here for the security agent.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"modify-agent-prompt",attachTo:{element:'[data-tour-tag="agent-settings-system-prompt"]',on:"left"},title:"Customize the agent's behavior",text:"This prompt allows you to customize the baseline behavior of the agent. While most customization can happen by talking to the agent (it records learnings in its notebook), you can provide specific workflow instructions here that will be followed separately.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"create-new-agent",attachTo:{element:'button[data-tour-tag="create-new-agent-button"]',on:"bottom"},title:"Create a new agent",text:'Click the "+" button to create a brand new agent from scratch. You can then customize its behavior and capabilities.',buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="agent-list-item-button-0"]');e&&e.click(),setTimeout(()=>{const t=document.querySelector('button[data-tour-tag="agent-options-button"]');t&&t.click()},500),setTimeout(()=>{const t=document.querySelector('[role="menuitem"][data-tour-tag="view-agent-settings-menu-item"]');t&&t.click()},1e3),setTimeout(()=>{this.back()},1500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="create-new-agent-button"]');e&&e.click(),setTimeout(()=>{this.next()},1e3)}}]},{id:"agent-naming-guidelines",attachTo:{element:'[data-tour-tag="create-agent-dialog"]',on:"right"},title:"Naming and describing your agent",text:`Give your agent a clear, descriptive name that reflects its purpose (e.g., "File Organizer" or "Web Researcher").
|
|
684
|
-
A good description helps you and others understand what the agent does and any special instructions. The descriptions are also used by other agents to help them understand how to tag each other in for certain tasks.<br /><br />If you want this agent to be part of the agent-to-agent communication network, it will need to have a description that captures its purpose and capabilities. Be concise and specific.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="create-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="create-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"navigate-agent-hub",attachTo:{element:'[data-tour-tag="nav-item-agent-hub"]',on:"right"},title:"Discover more agents",text:`Let's visit the Agent hub to find community-created agents. Click on the "Agent hub" icon in the navigation bar.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{const t=document.querySelector('[data-tour-tag="create-new-agent-button"]');t&&t.click()},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agent-hub"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"agent-hub-view",attachTo:{element:'[data-tour-tag="agent-hub-sidebar-container"]',on:"right"},title:"The Agent hub",text:"Here you can browse agents by category or search for specific ones. These agents are shared by the community and can perform various specialized tasks.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"download-agent",attachTo:{element:'button[data-tour-tag="agent-hub-download-button"]',on:"bottom"},title:"Download an agent",text:'Find an agent that interests you and click the "Get" button to add it to your local agent list.',buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{this.next()},1e3)}}]},{id:"upload-agent-hub",attachTo:{element:()=>CQe("upload-to-hub-header-button"),on:"bottom"},title:"Share your agents",text:"If you create a useful agent, you can also share it with the community by uploading it to the Agent hub from the agent options menu.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agent-hub"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){o4("open-upload-dialog"),setTimeout(()=>{this.next()},500)}}]},{id:"upload-agent-hub-dialog",attachTo:{element:'[data-tour-tag="upload-agent-dialog"]',on:"right"},title:"Upload agent to hub",text:"This dialog publishes your agent's instruction set to the community. You need a Radient account to publish, which is free to create and costs nothing per agent. You can review the details before confirming. What is published is what describes the agent - its name, description, instructions and tool surface; no conversation, execution history, memory, plan or machine-specific configuration leaves your computer. Make sure your agent meets the required criteria before submitting.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('button[data-tour-tag="upload-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="upload-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"navigate-schedules",attachTo:{element:'[data-tour-tag="nav-item-schedules"]',on:"right"},title:"Automate tasks with schedules",text:"Local Operator can run tasks for you on a regular basis. Let's check out the Schedules section.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{o4("open-upload-dialog")},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-schedules"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"schedules-overview",title:"Proactive agents with schedules",text:"A powerful feature of Local Operator is the ability to ask agents to perform tasks on their own on a recurring basis. This turns them from reactive agent bots to proactive agents that work on their own in the background to support you without you needing to continually ask them to do things.<br /><br />You can simply ask any agent to do something at some point in the future, or to handle some daily task at a certain time, and it will create a prompt for itself that will be executed at the specified times.<br /><br />Here, you can view, create, and manage all your scheduled tasks in one place to streamline your workflow and ensure important actions happen automatically.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"create-schedule",attachTo:{element:'button[data-tour-tag="create-schedule-button"]',on:"bottom"},title:"Set up a recurring task",text:'Click "Create schedule" to ask an agent to perform a task for you regularly, like sending a daily report or checking for news updates.<br /><br />You can also create one-off tasks that only run once at some point in the future.',buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="create-schedule-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"create-schedule-dialog",attachTo:{element:'[data-tour-tag="create-schedule-dialog"]',on:"right"},title:"Configure your schedule",text:"While it is often much easier to simply ask the agent to do a task on a recurring basis for you, you can also manually set up a schedule for a task here or update existing tasks.<br /><br />The prompt is the message that will be sent to the agent at the predefined schedule. You can update the time of day in your local timezone, the frequency of the task, and even specify a specific date or time that the task should stop running at.<br /><br />You can also schedule one-off tasks that only run once at some point in the future.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="create-schedule-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="create-schedule-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"navigate-settings",attachTo:{element:'[data-tour-tag="nav-item-settings"]',on:"right"},title:"Personalize your experience",text:"Now, let's explore the Settings menu to customize Local Operator to your liking.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-schedules"]');e&&e.click(),setTimeout(()=>{const t=document.querySelector('button[data-tour-tag="create-schedule-button"]');t&&t.click()},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-settings"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"general-settings",attachTo:{element:'div[data-tour-tag="settings-general-section"]',on:"right"},title:"General settings",text:"Here you can update your user profile and configure model settings (like default hosting provider and model).",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"appearance-settings",attachTo:{element:'[data-tour-tag="settings-appearance-section"]',on:"right"},title:"Customize appearance",text:"Choose from various themes to change the look and feel of Local Operator. Find one that suits your style.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"radient-account-settings",attachTo:{element:'[data-tour-tag="settings-radient-account-section"]',on:"right"},title:"Radient account",text:"Connect your Radient account to access your Radient Pass details, credits, and unlock unified access to models and tools. Radient is the best way to use Local Operator since it powers the AI models, web search, image generation, and much more with a single integration. You get free credits when you sign up to try it out and bonus credits when you top up.<br /><br />When you sign in for the first time, it will automatically create a Radient Pass for you and save it securely to your computer. This will power your Local Operator agents with Radient Automatic, which mixes and matches AI models to get you the best balance of speed, accuracy, and cost in every step of your agents' workflows.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"integrations-settings",attachTo:{element:'[data-tour-tag="settings-integrations-section"]',on:"right"},title:"Connect your services",text:"Enhance your agents' capabilities by connecting your Google services like Gmail, Calendar, and Drive. This allows agents to access and manage your information with your permission.<br /><br />You need to be logged in to a Radient account to use this feature, however it is free to use and doesn't cost any additional Radient credits per action.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"application-updates-settings",attachTo:{element:'[data-tour-tag="settings-app-updates-section"]',on:"right"},title:"Stay up to date",text:"Check for updates to Local Operator here to ensure you have the latest features and improvements. You can see your current version information below.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"tour-complete",title:"Tour complete",text:"You've now seen the main features of Local Operator. Feel free to explore further and discover all the ways your AI agents can assist you. Happy automating.",buttons:[{text:"Finish",classes:"shepherd-button-primary",action:function(){this.complete()}}]}],yQe=()=>{const e=Jr(),{completeTourOnboarding:t}=ym(),n=g.useContext(sy),s={cancelIcon:{enabled:!0},scrollTo:{behavior:"smooth",block:"center"}},r=!0;return{startTour:a=>{if(n?.tour?.isActive()&&!a?.forceModalCompleted){console.log("Onboarding tour is already active (from context.tour). Not starting another.");return}const o=ym.getState();if(!a?.forceModalCompleted&&!o.isModalComplete){console.log("Onboarding modal not completed (checked via store). Tour will not start.");return}if(o.isTourComplete&&!a?.forceModalCompleted){console.log("Onboarding tour already completed in store and not forced. Not starting again.");return}let l=n?.tour;const u=n?.Shepherd;if(!l&&u&&(l=u.activeTour,!l&&u.Tour&&(console.log("No active Shepherd tour found from context or global. Creating a new one."),l=new u.Tour({useModalOverlay:r,defaultStepOptions:s}))),!l){console.warn("Failed to get or create a Shepherd tour instance.",n);return}if(l.isActive()){console.log("Tour is already active. Not starting again.");return}if(l.options.defaultStepOptions={...l.options.defaultStepOptions||{},...s},l.options.useModalOverlay=r,a?.firstAgentId&&(l.options.firstAgentId=a.firstAgentId),l.off("complete",t),l.on("complete",t),l.off("cancel",t),l.on("cancel",t),a?.forceModalCompleted||!l.isActive()){const d=[...l.steps];for(const h of d)h.id&&l.removeStep(h.id);l.addSteps(l4)}else l.steps.length===0&&l.addSteps(l4);typeof l.start=="function"?(e("/"),l.start()):console.warn("Shepherd tour instance does not have a start method.",l)}}},_Qe=()=>{const{isModalComplete:e,isTourComplete:t}=ym(),{startTour:n}=yQe(),s=$e.useContext(sy),{data:r}=YS(1,1);return g.useEffect(()=>{if(e&&!t&&s){const i=setTimeout(()=>{const a=r?.agents?.[0]?.id;n({firstAgentId:a})},500);return()=>clearTimeout(i)}},[e,t,s,n,r]),null},SQe=({children:e})=>c.jsxs(hQe,{children:[e,c.jsx(_Qe,{})]}),EQe=()=>{Et();const{open:e,focusGroup:t,providerId:n,closeConnect:s}=RB(),r=g.useRef(null);g.useEffect(()=>{e&&(r.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},[e]);const i=Jr();return c.jsx(Wl,{open:e,onOpenChange:a=>{a||s()},children:c.jsxs($l,{className:"max-h-[calc(100vh-4rem)] max-w-[min(40rem,calc(100vw-4rem))] gap-4 overflow-y-auto","data-connect-provider-dialog":"",onCloseAutoFocus:a=>{const o=r.current;r.current=null,o?.isConnected&&(a.preventDefault(),o.focus())},children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx(jo,{className:"text-title",children:x("ui.providers.connect_provider_dialog.connect_a_model_provider")}),c.jsx(ru,{className:"text-body-sm text-ink-muted",children:x("ui.providers.connect_provider_dialog.your_agents_need_a_model_to_think")})]}),e?c.jsx(GW,{context:"dialog",featuredOnly:!0,focusGroup:t,initialProviderId:n,onDone:s,onChangeModel:()=>{s(),i("/settings")}}):null]})})},kQe=({title:e,description:t,icon:n,children:s,titleComponent:r,sectionRef:i,dataTourTag:a,className:o,id:l})=>c.jsxs("div",{ref:i,id:l,tabIndex:l?-1:void 0,"data-tour-tag":a,className:T("w-full",o),children:[r??c.jsxs("h2",{className:"flex items-center gap-2 text-heading text-ink",children:[n&&c.jsx(n,{size:16,className:"shrink-0 text-ink-dim"}),e]}),t&&c.jsx("p",{className:"mt-1 max-w-2xl text-body-sm text-ink-muted",children:t}),c.jsx("div",{className:"mt-4",children:s})]}),met=({label:e,value:t,className:n,valueClassName:s})=>c.jsxs("div",{className:T("min-w-0",n),children:[c.jsx("div",{className:"flex items-center gap-1.5 text-meta text-ink-dim",children:e}),c.jsx("div",{className:T("mt-0.5 break-words text-body-sm",s??"text-ink"),children:t})]}),vet=({children:e,className:t})=>c.jsx("div",{className:T("grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-x-6 gap-y-4",t),children:e});async function u$(e){await xt({op:"settings.edit",key:Ro,value:e.value}),YQ(e.queryClient)}async function TQe(e){await u$(e),e.queryClient.setQueryData(ax.all,t=>t&&{...t,settings:t.settings.map(n=>n.key===Ro?{...n,value:e.value,is_default:e.value===n.default}:n)});try{return await e.queryClient.fetchQuery({queryKey:ax.all,queryFn:()=>xt({op:"settings.list"}),staleTime:0,retry:!1}),"confirmed"}catch{return"readback-unknown"}}const bet=({focus:e=!1})=>{Et();const t=nn(),n=Bn(),s=yt(n.data,"settings"),r=fs({queryKey:ax.all,queryFn:()=>xt({op:"settings.list"}),enabled:s,retry:!1,refetchOnReconnect:!0}),i=r.data?.settings.find(F=>F.key===Ro),[a,o]=g.useState(!1),[l,u]=g.useState(null),[d,h]=g.useState(!1),[f,p]=g.useState(!1),m=g.useRef(!1),v=g.useRef(null),b=g.useRef(!1);g.useEffect(()=>{if(!e){b.current=!1;return}!i||b.current||(v.current?.querySelector("[role=combobox]")?.focus(),b.current=!0)},[e,i]),g.useEffect(()=>{r.isSuccess&&!r.isFetching&&h(!1)},[r.isFetching,r.isSuccess]);const w=async F=>{if(!(!i||m.current||d||!i.choices.some(A=>A.value===F))){m.current=!0,o(!0),u(null),p(!1);try{const A=await TQe({value:F,queryClient:t});h(A==="readback-unknown"),p(A==="confirmed")}catch(A){u({value:F,message:A instanceof Error?A.message:""})}finally{m.current=!1,o(!1)}}},C=async()=>{const[F,A]=await Promise.all([r.refetch(),n.refetch()]);!F.isError&&!A.isError&&h(!1)},y=!r.data&&r.error||!n.data&&n.error,k=n.data&&(!s||r.data&&!i),_=!y&&!k&&!i,E=n.data?.features?.i18n?n.data.language:void 0,R=typeof E=="string"&&E!==""?E:void 0;return c.jsx(kQe,{title:x("ui.settings.language.dialog.title"),icon:xj,description:x("ui.settings.language.general.description"),children:c.jsxs("div",{ref:v,"data-setting-key":Ro,className:"flex flex-col gap-3","aria-busy":a,children:[_&&c.jsx("output",{className:"text-meta text-ink-dim",children:x("ui.settings.language.dialog.loading")}),k&&c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.settings.language.dialog.unavailable")}),i&&c.jsx(MB,{setting:{...dT(i),label:x("ui.settings.language.dialog.title")},value:String(i.value),onValueChange:F=>{w(F)},disabled:a||d,suppressEffectiveNote:!0}),c.jsx("output",{id:qQ(Ro),"aria-live":"polite",className:"text-meta text-ink-dim",children:a?x("ui.settings.language.general.pending"):f?x("ui.settings.language.general.saved"):R?x(d||n.error?"ui.settings.language.general.last_known":"ui.settings.language.general.effective",{locale:KQ(R)?.name??R}):x("ui.settings.language.general.no_resolution")}),(y||l||d)&&c.jsx(Kr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:l?x("ui.settings.language.general.write_error",{message:l.message}):d?x("ui.settings.language.general.readback_error"):x("ui.settings.language.dialog.unavailable")}),c.jsx(ce,{variant:"outline",size:"sm",disabled:a||r.isFetching||n.isFetching,onClick:()=>{l?w(l.value):C()},children:x("ui.settings.language.dialog.retry")})]})})]})})},RQe=()=>{Et();const e=Dk(te=>te.open),t=Dk(te=>te.closeLanguage),n=nn(),s=Bn(),r=yt(s.data,"settings"),i=fs({queryKey:ax.all,queryFn:()=>xt({op:"settings.list"}),enabled:e&&r,staleTime:1e4}),a=g.useRef(null),o=bB(),l=(i.data?.settings??[]).find(te=>te.key===Ro),u=l?dT(l):void 0,[d,h]=g.useState(null),[f,p]=g.useState(!1),[m,v]=g.useState(!1),[b,w]=g.useState(null),C=g.useRef(null);g.useEffect(()=>{e&&h(null)},[e]),g.useEffect(()=>{if(!e||!u)return;const te=String(u.value??"");(d===null||d===C.current)&&h(te),C.current=te},[e,u,d]),g.useEffect(()=>{e&&(v(!1),w(null))},[e]);const y=d??String(u?.value??""),k=!!u&&y!==String(u?.value??""),_=!u||!k||f,E=async()=>{if(!(!u||!k)){p(!0),w(null);try{await u$({value:y,queryClient:n}),v(!0),h(null),await i.refetch()}catch(te){w(te instanceof Error?te.message:x("ui.settings.configuration.language_dialog.the_language_could_not_be_saved"))}finally{p(!1)}}},R=!!s.data,F=R&&!r,A=s.error&&!s.data?s.error:null,N=A??i.error,M=!R&&!N,{sentence:D,remedy:L}=XQ(o??null,x("ui.settings.configuration.language_dialog.your_settings_could_not_be_loaded"),N),V=s.isFetching||i.isFetching,j=u?"combo":N?"retry":"none";return g.useEffect(()=>{!e||j==="none"||requestAnimationFrame(()=>{a.current?.querySelector(j==="combo"?'[role="combobox"]':"[data-language-retry]")?.focus()})},[e,j]),c.jsx(Wl,{open:e,onOpenChange:te=>!te&&t(),children:c.jsxs($l,{ref:a,onOpenAutoFocus:te=>te.preventDefault(),className:"max-w-[min(28rem,calc(100vw-4rem))] gap-4",children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx(jo,{className:"text-title",children:x("ui.settings.language.dialog.title")}),c.jsx(ru,{className:"text-body-sm text-ink-muted",children:x("ui.settings.language.dialog.description")})]}),M?c.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{}),x("ui.settings.language.dialog.loading")]}):F?c.jsx(Kr,{variant:"warning",children:c.jsx("span",{children:x("ui.settings.language.dialog.unavailable")})}):N?c.jsx(Kr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:D}),L&&c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0","data-language-retry":"",onClick:()=>{A?s.refetch():i.refetch()},disabled:V,children:V?x("ui.settings.language.dialog.retrying"):x("ui.settings.language.dialog.retry")})]})}):i.isPending?c.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{}),x("ui.settings.language.dialog.loading")]}):u?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{id:yF(Ro),className:"text-meta text-ink-dim",children:u.help}),c.jsx(MB,{setting:u,value:y,disabled:f,helpId:yF(Ro),effectiveNoteId:QQ(Ro,JQ),onValueChange:te=>{v(!1),h(te)}})]}),b&&c.jsx("p",{className:"text-meta text-danger",children:b}),c.jsx("div",{className:"flex min-h-8 items-center justify-end",children:m&&!k?c.jsxs("output",{"data-language-save":"",className:"inline-flex items-center gap-1.5 text-body-sm text-ink",children:[c.jsx(Bs,{"aria-hidden":"true",className:"size-3.5"}),x("ui.settings.language.dialog.saved")]}):c.jsx(ce,{onClick:E,disabled:_,"data-language-save":"",children:f?`${x("ui.settings.language.dialog.save")}...`:x("ui.settings.language.dialog.save")})})]}):c.jsx(Kr,{variant:"warning",children:c.jsx("span",{children:x("ui.settings.language.dialog.unavailable")})})]})})};function AQe(){const{data:e}=Bn();g.useEffect(()=>{e&&W$(e)},[e]);const t=oT(),n=nn(),s=g.useRef(null);g.useEffect(()=>{const r=t.configChange;if(!r)return;const i=`${r.epoch}:${r.seq}`;s.current!==i&&r.changedKeys.includes(Ro)&&(s.current=i,n.invalidateQueries({queryKey:Bo.capabilities}),n.invalidateQueries({queryKey:Bo.settings}),!ZQ()&&Va(x("ui.settings.language.external_notice",{language:r.language}),{id:"i18n-language-external"}))},[t.configChange,n])}function FQe(e,t){if(e.defaultPrevented||e.repeat||e.isComposing||!(e.metaKey||e.ctrlKey))return null;const n=eJ(e);if(n===null)return null;const s=BZ(t.bindings).get(n);return s===void 0||lT(e.target)||!Sue(d$(s),t.route)?null:s}const d$=e=>e.slice(6);function DQe(e){const t=Ce.getState(),n=t.activeDraftKey?t.drafts[t.activeDraftKey]:void 0,s=ip(t.activeDraftKey,n?.sessionId,t.activeSessionId)??null;Gu(d$(e),{sessionId:s,askScope:s===null?"fleet":"session",via:"chord"})}function PQe(){g.useEffect(()=>{const e=t=>{const n=qe.getState(),s=FQe(t,{bindings:n.shortcutBindings,route:n.rightSlotRoute});s!==null&&(t.preventDefault(),DQe(s))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}const IQe=""+new URL("radient-icon-1024x1024-D_JJedvo.png",import.meta.url).href,h$=op()(KB(e=>({hasBeenNotified:!1,setHasBeenNotified:t=>{e({hasBeenNotified:t})}}),{name:"low-credits-storage"})),NQe=({open:e,onClose:t,onGoToConsole:n})=>{Et();const{setHasBeenNotified:s}=h$(),{prices:r,isLoading:i,error:a}=tJ(),o=d=>typeof d!="number"?"$...":x("ui.common.account.low_credits_dialog.detail",{detail:String(d.toFixed(2))}),l=()=>{s(!0),t()},u=()=>{s(!0),n()};return c.jsx(su,{open:e,onClose:l,title:c.jsxs(c.Fragment,{children:[c.jsx("img",{src:IQe,alt:x("ui.common.account.low_credits_dialog.radient_icon"),className:"size-7"}),x("ui.common.account.low_credits_dialog.running_low_on_radient_credits")]}),maxWidth:"sm",fullWidth:!1,actions:c.jsxs(c.Fragment,{children:[c.jsx(k0,{onClick:l,children:x("ui.common.account.low_credits_dialog.maybe_later")}),c.jsx(T0,{onClick:u,startIcon:c.jsx(xl,{size:18}),className:"min-w-55",children:x("ui.common.account.low_credits_dialog.get_more_credits")})]}),children:c.jsxs("div",{className:"flex flex-col items-center gap-4 py-2 text-center",children:[c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[x("ui.common.account.low_credits_dialog.unlock_the_full_power_of_local_operator_with")," ",c.jsx("span",{className:"font-bold text-accent",children:x("ui.common.account.low_credits_dialog.radient_pass")}),"."]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.common.account.low_credits_dialog.radient_automatic_is_often_cheaper_than_bringing_your_own_key_its")}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.common.account.low_credits_dialog.it_s_pay_as_you_go_with_no_commitments_load_up_what_you_need_star")}),c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[x("ui.common.account.low_credits_dialog.plus_get")," ",c.jsx("span",{className:"font-medium text-ink",children:i?c.jsx(pn,{size:"sm",className:"mr-0.5 align-middle"}):o(r?.default_registration_credits)})," ",x("ui.common.account.low_credits_dialog.in_bonus_credits_with_your_first_purchase"),a&&c.jsx("span",{className:"mt-1 block text-meta text-danger",children:x("ui.common.account.low_credits_dialog.could_not_load_bonus_credit_information")})]}),c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.common.account.low_credits_dialog.you_can_also_reach_the_radient_console_from_settings_at_any_time")})]})})},MQe=(e,t)=>t?$1(e.filter(n=>n.session_id===t)).length:0;function OQe(e){return Ce(t=>MQe(t.sessions,e))}const LQe=(e,t)=>t?e.some(n=>n.session_id===t&&n.status?.code==="busy"):!1;function BQe(e){return Ce(t=>LQe(t.sessions,e))}const jQe=[];function HQe(){const{state:e}=xC(),t=e?.pendingConsent??jQe,n=d5(s=>qP(t,s));return g.useEffect(()=>{t.length>0&&WT()},[t]),qP(t,n)}const f$={approvals:["desktop","mesh","approvals"]},UQe=15e3,GQe=new Set(["requested","approved","connecting","failed"]);function VQe(e){return GQe.has(e)}function WQe(e){return e==="requested"}function $Qe(e){return e.filter(t=>WQe(t.state)).length}function xet(e){return e.state==="requested"&&e.canApproveHere!==!1&&(e.kind==="device"||e.kind==="machine")}function wet(e){return VQe(e)}function Cet(e){switch(e){case"requested":return x("ui.mesh.mesh_approvals.waiting_for_you");case"approved":return x("ui.mesh.mesh_approvals.approved");case"connecting":return x("ui.mesh.mesh_approvals.connecting");case"connected":return x("ui.mesh.mesh_approvals.connected");case"denied":return x("ui.mesh.mesh_approvals.denied");case"expired":return x("ui.mesh.mesh_approvals.expired");case"failed":return x("ui.mesh.mesh_approvals.failed");default:return e}}function Rc(e){return typeof e=="object"&&e!==null}function zQe(e){const t=Rc(e)?e:{};return{deviceId:Ft(t.device_id),name:Ft(t.name),host:Ft(t.host),user:Ft(t.user),transport:Ft(t.transport),hostKeyFp:Ft(t.host_key_fp)}}function qQe(e){const t=Rc(e)?e:{};return{connect:Mo(t.connect,!1),install:Mo(t.install,!1),anchor:Rc(t.anchor),networkId:Ft(t.network_id),role:Ft(t.role),unattended:Mo(t.unattended,!1),grants:Lf(t.grant)}}function KQe(e){const t=Array.isArray(e)?e:e?.approvals??[];if(!Array.isArray(t))return[];const n=[];for(const s of t){if(!Rc(s))continue;const r=Ft(s.approval_id),i=Ft(s.state);if(!r||!i)continue;const a=Rc(s.what)&&Object.prototype.hasOwnProperty.call(s.what,"credential_inheritance"),o=Object.prototype.hasOwnProperty.call(s,"kind")?Ft(s.kind):void 0,l=a||o==="credential_inheritance"?"credential":o!==void 0&&!["device_onboard","local_authority"].includes(o)?"unknown":!Rc(s.device)&&Rc(s.machine)?"machine":"device",u=Rc(s.requested_by)?s.requested_by:{};n.push({approvalId:r,state:i,kind:l,summary:Ft(s.summary)||void 0,details:Array.isArray(s.details)&&s.details.every(d=>typeof d=="string")?s.details.slice():void 0,canApproveHere:Object.prototype.hasOwnProperty.call(s,"can_approve_here")?s.can_approve_here===!0:void 0,approveRemedy:Ft(s.approve_remedy)||void 0,where:zQe(l==="machine"?s.machine:s.device),what:qQe(s.what),requestedBy:{surface:Ft(u.surface),sessionId:Ft(u.session_id),deviceId:Ft(u.device_id)},expiresAt:Ic(s.expires_at)})}return n}function YQe(e){return e.kind==="machine"?x("ui.mesh.mesh_approvals.this_machine"):I5({device_id:e.where.deviceId,name:e.where.name})}function yet(e,t){if(e.kind==="credential"||e.kind==="unknown"||e.canApproveHere===!1){if(e.summary)return e.summary;if(e.kind==="credential"||e.kind==="unknown")return c4(e)}const n=c4(e),s=QQe(e,t).map(r=>r.clause);return s.length?x("ui.mesh.mesh_approvals.approval_title_with_clauses",{head:n,clauses:XQe(s)}):x("ui.mesh.mesh_approvals.approval_title",{head:n})}function c4(e){return e.kind==="credential"?e.summary||x("ui.mesh.approval.credential_title"):e.kind==="unknown"?e.summary||x("ui.mesh.approval.unknown_title"):e.canApproveHere===!1&&e.summary?e.summary:e.kind==="machine"?x("ui.mesh.mesh_approvals.set_up_operator_authority_on_this_machine"):x("ui.mesh.mesh_approvals.onboard_subject",{subject:YQe(e)})}function XQe(e){return e.length===1?e[0]:x("ui.mesh.mesh_approvals.join_clauses",{clauses:e.slice(0,-1).join(", "),last:e[e.length-1]})}function _et(e){if(e.kind==="credential"||e.kind==="unknown")return null;const{user:t,host:n,transport:s,name:r}=e.where,i=[n?t?`${t}@${n}`:n:"",s?x("ui.mesh.mesh_approvals.via_transport",{transport:s}):"",r&&r!==n?`(${r})`:""].filter(Boolean);return i.length?i.join(" "):null}function Eet(e){return e.kind==="credential"||e.kind==="unknown"?null:e.where.hostKeyFp||null}function ket(e){const{surface:t,sessionId:n}=e.requestedBy,s=[t||"",n?x("ui.mesh.mesh_approvals.session_suffix",{suffix:n.slice(-6)}):""].filter(Boolean);return s.length?x("ui.mesh.mesh_approvals.asked_by",{requester:s.join(" · ")}):null}function QQe(e,t){if(e.kind==="credential"||e.kind==="unknown")return[];const{connect:n,install:s,anchor:r,networkId:i,role:a,unattended:o,grants:l}=e.what,u=[];if(n&&u.push({term:"connect",clause:e.where.transport?x("ui.mesh.mesh_approvals.connect_over",{transport:e.where.transport}):x("ui.mesh.mesh_approvals.connect_to_it"),consequence:e.where.transport?x("ui.mesh.mesh_approvals.may_connect_over",{transport:e.where.transport}):x("ui.mesh.mesh_approvals.this_machine_may_connect_to_it")}),s&&u.push({term:"install",clause:e.kind==="machine"?x("ui.mesh.mesh_approvals.install_local_operator"):x("ui.mesh.mesh_approvals.install_local_operator_there"),consequence:e.kind==="machine"?x("ui.mesh.mesh_approvals.local_operator_is_installed_on_this_machine"):x("ui.mesh.mesh_approvals.local_operator_is_installed_on_it")}),r&&u.push({term:x("ui.mesh.mesh_approvals.install_operator_anchor"),clause:x("ui.mesh.mesh_approvals.check_approvals_signed_on_your_machines"),consequence:x("ui.mesh.mesh_approvals.that_device_can_check_approvals_signed_on")}),i){const d=t?.get(i),h=x("ui.mesh.mesh_approvals.join_network",{network:d||i,role:a||"?"});u.push({term:h,clause:h,consequence:x("ui.mesh.mesh_approvals.joins_network",{network:d||i,role:a||"?"})})}o&&u.push({term:x("ui.mesh.mesh_approvals.trust_unattended_sessions"),clause:x("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt"),consequence:x("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")});for(const d of JQe(l,o)){const h=ZQe()[d];u.push({term:h?.term??x("ui.mesh.mesh_approvals.grant_capability",{grant:d}),clause:eJe()[d]??x("ui.mesh.mesh_approvals.use_capability",{grant:d}),consequence:h?.gloss??x("ui.mesh.mesh_approvals.may_use_capability",{grant:d})})}return u}function JQe(e,t){const n=new Set;for(const s of e){const r=String(s??"").trim();r&&(t&&r==="unattended"||n.add(r))}return[...n]}const ZQe=()=>({unattended:{term:x("ui.mesh.mesh_approvals.trust_unattended_sessions"),gloss:x("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")},broker_credential:{term:x("ui.mesh.mesh_approvals.borrow_logins_there"),gloss:x("ui.mesh.mesh_approvals.your_sessions_may_use_the_logins_stored")}}),eJe=()=>({list:x("ui.mesh.mesh_approvals.see_its_sessions"),view:x("ui.mesh.mesh_approvals.watch_a_session_there"),prompt:x("ui.mesh.mesh_approvals.send_prompts_to_a_session_there"),steer:x("ui.mesh.mesh_approvals.steer_a_running_turn_there"),stop:x("ui.mesh.mesh_approvals.stop_a_session_there"),slash:x("ui.mesh.mesh_approvals.run_slash_commands_there"),delete:x("ui.mesh.mesh_approvals.archive_or_delete_a_session_there"),move:x("ui.mesh.mesh_approvals.move_sessions_to_or_from_there"),broker_credential:x("ui.mesh.mesh_approvals.borrow_the_logins_stored_there"),approve:x("ui.mesh.mesh_approvals.answer_approval_prompts_there"),unattended:x("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt")});function Tet(e,t){if(e===null||e<=0)return null;const n=e-t;if(n<=0)return null;if(n<60)return x("ui.mesh.mesh_approvals.expires_in_under_a_minute");const s=Math.ceil(n/60);if(s<90)return x("ui.mesh.mesh_approvals.expires_minutes",{count:s});const r=Math.ceil(s/60);return x("ui.mesh.mesh_approvals.expires_hours",{count:r})}function tJe(e,{poll:t=!0}={}){return fs({queryKey:f$.approvals,enabled:e,queryFn:async()=>KQe(await xt({op:"approvals.list"})),retry:!1,staleTime:t?1e4:Number.POSITIVE_INFINITY,refetchInterval:e&&t?UQe:!1,refetchOnWindowFocus:t})}function Ret(){const e=nn();return Kn({mutationFn:async t=>{const n=t.decision==="approve"?{op:"approvals.approve",approvalId:t.approvalId}:{op:"approvals.deny",approvalId:t.approvalId};await xt(n)},onSettled:()=>{e.invalidateQueries({queryKey:f$.approvals}),e.invalidateQueries({queryKey:Ol.networks}),e.invalidateQueries({queryKey:Ol.peers})}})}function Aet(e){const t=e?.message;return typeof t=="string"&&t.trim()?t.trim():x("ui.mesh.mesh_approvals.the_approvals_could_not_be_read")}function Fet(e){const t=e;return{code:Ft(t?.code)||"approval_refused",sentence:Ft(t?.message)||x("ui.mesh.mesh_approvals.decision_could_not_be_answered")}}const u4=e=>{const t=rJ(e.type),n=typeof e.percent=="number"?`, ${Math.round(e.percent)}%`:"";return`${t} in progress${n}.`},p$=e=>sJ({type:e.type,version:e.offer.version}),nJe=e=>`${e.map(s=>p$(s)).map((s,r)=>r===0?s:`${s.charAt(0).toLowerCase()}${s.slice(1)}`).join(" and ")} available. Show the update notice.`,sJe=({surfaces:e,inflight:t,onShow:n,onDismiss:s})=>{if(Et(),t===null&&e.length===0)return null;if(t!==null)return c.jsx(Je,{side:"top",collisionPadding:8,content:u4(t),children:c.jsx("output",{"data-update-foot-icon":"","data-update-foot-icon-state":"inflight","aria-label":u4(t),className:"flex size-8 shrink-0 items-center justify-center text-accent",children:c.jsx(Ui,{className:"size-4 shrink-0 motion-safe:animate-spin","aria-hidden":"true"})})});const r=e.find(i=>(i.offer.summary??"").trim()!=="");return c.jsx(Je,{side:"top",collisionPadding:8,content:c.jsxs("div",{className:"flex max-w-64 flex-col gap-0.5",children:[e.map(i=>c.jsxs("span",{className:"truncate text-ink",children:[p$(i)," ",x("ui.common.updates.update_foot_icon.available")]},i.type)),r?c.jsx("span",{className:"truncate text-ink-muted",children:(r.offer.summary??"").trim()}):null,c.jsx("span",{className:"whitespace-nowrap text-ink-muted",children:x("ui.common.updates.update_foot_icon.show_the_update_notice")})]}),children:c.jsx("button",{type:"button","data-update-foot-icon":"","data-update-foot-icon-state":"available","aria-label":nJe(e),onClick:n,onKeyDown:i=>{i.key!=="Escape"||!s||(i.stopPropagation(),s())},className:T("flex size-8 shrink-0 items-center justify-center rounded-sm text-accent","transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink"),children:c.jsx(iT,{className:"size-4 shrink-0","aria-hidden":"true"})})})},d4=()=>{const e=Ys(p=>p.followed),t=Ys(p=>p.running),n=Ys(p=>p.offers),s=Ys(p=>p.detailOpen),r=Ys(p=>p.inflight),i=Ys(p=>p.downloadPercent),a=Ys(p=>p.openNotice),o=Ys(p=>p.noticeOpen),l=Ys(p=>p.dismissNotice),u=g.useMemo(()=>{const p={followed:e,running:t,offers:n,detailOpen:s};return y4.filter(m=>nJ(p,m)).map(m=>{const v=n[m];return v?{type:m,offer:v}:null}).filter(m=>m!==null)},[e,t,n,s]),d=g.useMemo(()=>r[ln.BACKEND]?{type:ln.BACKEND,percent:null}:r[ln.UI]?{type:ln.UI,percent:i[ln.UI]}:null,[r,i]),h=g.useCallback(()=>a(),[a]),f=g.useCallback(()=>l(),[l]);return c.jsx(sJe,{surfaces:u,inflight:d,onShow:h,onDismiss:o?f:void 0})},h4=({expanded:e})=>(Et(),c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(M4,{className:"size-6",label:e?void 0:x("ui.shell.collapsible_app_logo.local_operator")}),e&&c.jsx("span",{className:"truncate font-semibold text-body text-ink",children:x("ui.shell.collapsible_app_logo.local_operator")})]})),Bk=$e.memo(({expanded:e,useAuth:t=!1})=>{Et();const n=Jr(),{user:s,isAuthenticated:r,accountRead:i,signOut:a}=OB(),o=i==="checking"?x("ui.shell.user_profile_sidebar.checking_account"):_F(i)?x("ui.shell.user_profile_sidebar.account_unavailable"):null,l=s?.name??o??x("ui.shell.user_profile_sidebar.user"),u=_F(i),d=s?.email??"",h=u?x("ui.shell.user_profile_sidebar.reconnect_radient"):d,f=u?"/settings?section=providers&provider=radient":"/settings",p=u?x("ui.shell.user_profile_sidebar.reconnect_radient"):x("ui.shell.user_profile_sidebar.account_settings"),m=g.useCallback(async()=>{r&&(await a(),window.location.reload())},[r,a]),v=g.useMemo(()=>{const C=s?.name;return C?C.split(" ").map(y=>y.charAt(0)).join("").toUpperCase().substring(0,2):null},[s?.name]),b=c.jsxs("button",{type:"button",onClick:t?void 0:()=>n(f),"aria-label":e?void 0:p,className:T("flex w-full min-w-0 items-center gap-2 rounded-sm transition-colors duration-fast ease-out-quart hover:bg-row-hover",e?"px-2 py-1.5":"justify-center py-1.5"),children:[c.jsx($B,{className:"size-7 shrink-0",children:c.jsx(zB,{className:"border border-control bg-elevated text-ink",children:v??c.jsx(Qre,{size:14,"aria-hidden":"true"})})}),e&&l&&c.jsxs("span",{className:"min-w-0 text-left",children:[c.jsx("span",{className:"block truncate text-body-sm text-ink",children:l}),h&&c.jsx("span",{className:T("block truncate text-meta",u?"text-accent":"text-ink-dim"),children:h})]})]}),w=e?b:c.jsx(Je,{content:p,side:"right",children:b});return t?c.jsxs(Il,{children:[e?c.jsx(Ho,{asChild:!0,children:b}):c.jsx(Je,{content:p,side:"right",children:c.jsx(Ho,{asChild:!0,children:b})}),c.jsxs(Nl,{align:"end",side:"top",className:"min-w-50",children:[u?c.jsxs(Gt,{onSelect:()=>n(f),children:[c.jsx(UB,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.reconnect_radient")]}):null,c.jsxs(Gt,{onSelect:()=>n("/settings"),children:[c.jsx(Pc,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.settings")]}),c.jsxs(Gt,{children:[c.jsx(xre,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.privacy_and_security")]}),c.jsx(Yr,{}),c.jsxs(Gt,{onSelect:m,className:"text-danger focus:bg-danger-wash focus:text-danger",children:[c.jsx(Use,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.sign_out")]})]})]}):w});Bk.displayName="UserProfileSidebar";const rJe=()=>{const e=oT(),t=Bn(),n=Ce(u=>u.setCataloguePageable),s=Ce(u=>u.setCatalogueActivityHead),r=Ce(u=>u.fetchSessions),i=yt(t.data,"session_catalogue_page"),a=yt(t.data,"session_catalogue_sort");g.useEffect(()=>{n(i)},[i,n]),g.useEffect(()=>{s(a)},[a,s]);const o=pa(t.data,"session_catalogue",2)==="enabled",l=g.useCallback(()=>r(i?cB:Ww,i),[r,i]);return g.useEffect(()=>{o&&l()},[o,l,e.catalogueRevision]),null},iJe="flex h-[30px] w-full items-center gap-2 rounded-md px-2 text-body-sm transition-colors duration-fast ease-out-quart",aJe=()=>{Et();const e=Jr(),t=Xae(),{expanded:n,mode:s,onCollapse:r}=iJ(),i=qe(le=>le.openCommandPalette),a=Bn(),o=Ce(le=>le.activeSessionId),l=HQe(),u=pa(a.data,"peers")==="enabled",d=ZT(u),h=pa(a.data,"approvals")==="enabled",f=tJe(d==="member"&&h,{poll:!0}),p=$Qe(f.data??[]),m=yt(a.data,"projects",1),v=yt(a.data,"aida",1),b=B0(v),w=v&&b.data?.enabled===!0,C=b.data?.name??"Aida",y=Cle(),k=OQe(b.data?.session_id),_=BQe(b.data?.session_id),E=()=>{y(e,b.data).catch(le=>zt(Fh(le)))},R=[...w?[{icon:Xne,label:C,path:"/chat",isActive:t==="chat"&&!!b.data?.session_id&&o===b.data?.session_id,tourTag:"nav-item-aida",onSelect:E,attention:k,attentionTag:"nav-aida-badge",attentionName:le=>x("ui.shell.sidebar_navigation.aida_missed",{name:C,count:le}),working:_,workingName:x("ui.shell.sidebar_navigation.aida_working",{name:C})}]:[],{icon:Uo,label:x("ui.shell.sidebar_navigation.agents"),path:"/agents",isActive:t==="agents",tourTag:"nav-item-agents"},...m?[{icon:bj,label:x("ui.shell.sidebar_navigation.projects"),path:"/projects",isActive:t==="projects",tourTag:"nav-item-projects"}]:[],{icon:mj,label:x("ui.shell.sidebar_navigation.schedules"),path:"/schedules",isActive:t==="schedules",tourTag:"nav-item-schedules"},{icon:qc,label:x("ui.shell.sidebar_navigation.browser"),path:"/browser",isActive:t==="browser",tourTag:"nav-item-browser",attention:l,attentionTag:"nav-browser-badge",attentionName:le=>x("ui.shell.sidebar_navigation.browser_waiting",{count:le,countText:String(le)})},{icon:kj,label:x("ui.shell.sidebar_navigation.agent_hub"),path:"/agent-hub",isActive:t==="agent-hub",tourTag:"nav-item-agent-hub"},...d==="member"?[{icon:TB,label:x("ui.shell.sidebar_navigation.mesh"),path:"/mesh",isActive:t==="mesh",tourTag:"nav-item-mesh",attention:p,attentionTag:"nav-mesh-badge",attentionName:le=>x("ui.shell.sidebar_navigation.mesh_waiting",{count:le,countText:String(le)})}]:[]],F=c.jsx(S$e,{selectedConversation:o??void 0,onSelectConversation:le=>void cp(e,le),onStageDraft:(le,q)=>{Ce.getState().stageDraft(le,q),e("/chat")}}),A=le=>{const q=le.attention??0,we=q>0&&le.attentionName?le.attentionName(q):le.label;return le.working&&le.workingName?le.workingName:we},N=le=>{const q=le.attention??0,we=A(le),B=le.isActive?yo:"text-ink-muted hover:bg-row-hover hover:text-ink",be=c.jsx(le.icon,{size:16,"aria-hidden":"true",className:T("shrink-0",le.isActive&&"text-accent")});return c.jsx("li",{className:T("flex h-[30px] w-full items-center rounded-md","transition-colors duration-fast ease-out-quart",B),children:c.jsxs("button",{type:"button",onClick:()=>le.onSelect?le.onSelect():e(le.path),"data-tour-tag":le.tourTag,"aria-current":le.isActive?"page":void 0,"aria-label":n&&we===le.label?void 0:we,className:T("flex h-full min-w-0 flex-1 items-center gap-2 rounded-md",n?"px-2":"justify-center px-0"),children:[n?be:c.jsxs("span",{className:"relative flex size-7 shrink-0 items-center justify-center",children:[be,q>0&&c.jsx("span",{className:"pointer-events-none absolute -top-0.5 -right-0.5 flex",children:c.jsx(Ml,{variant:"attentionQuiet",shape:"pill",size:"count",className:"h-3.5 min-w-3.5 px-0.75 leading-none","data-tour-tag":le.attentionTag,children:q})})]}),n&&c.jsx("span",{className:"truncate",children:le.label}),n&&q>0&&c.jsx("span",{className:"ml-auto inline-flex",children:c.jsx(Ml,{variant:"attentionQuiet",shape:"pill",size:"count","data-tour-tag":le.attentionTag,children:q})}),le.working&&c.jsx("span",{className:T(n&&"ml-auto","inline-flex"),children:c.jsx(Ui,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})})]})},le.tourTag)},M=le=>n?N(le):c.jsx("li",{children:c.jsx(Je,{content:A(le),side:"right",children:N(le)})},le.tourTag),D=s==="overlay"?x("ui.shell.sidebar_navigation.close_sidebar"):n?x("ui.shell.sidebar_navigation.collapse_sidebar"):x("ui.shell.sidebar_navigation.expand_sidebar"),L=s==="overlay"?Dn:n?bd:ga,V=navigator.platform.toUpperCase().indexOf("MAC")>=0,j=yt(a.data,"session_catalogue",2),te=Ce(le=>le.activeDraftKey),X=Ce(le=>le.drafts),re=!!te&&!(te?X[te]:void 0)?.target,G=()=>{Ce.getState().stageDraft(void 0,!0),e("/chat")},J=x("ui.shell.sidebar_navigation.new_chat_shortcut",{shortcut:y3(V).replace("+","")}),ae=x("ui.shell.sidebar_navigation.search_accessible",{everything:ko("everything",V),chats:ko("chats",V)}),O=x("ui.shell.sidebar_navigation.search_tooltip",{everything:ko("everything",V),chats:ko("chats",V)}),U=(le,q,we,B)=>{const be=le;return c.jsxs("button",{type:"button",...B.attrs,onClick:B.onClick,disabled:B.disabled,"aria-label":B.ariaLabel,"aria-current":B.current?"page":void 0,className:T(iJe,B.current?yo:"text-ink-muted hover:bg-row-hover hover:text-ink","disabled:text-ink-disabled disabled:hover:bg-transparent"),children:[c.jsx(be,{size:16,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"truncate",children:q}),c.jsx("span",{"aria-hidden":"true",className:"ml-auto",children:c.jsx(Er,{shortcut:we,joined:!0})})]})},P=U(KS,x("ui.shell.sidebar_navigation.new_chat"),y3(V),{onClick:G,ariaLabel:J,current:re,disabled:!j,attrs:{"data-tour-tag":"nav-item-chat","data-new-chat-row":""}}),z=U(xd,x("ui.shell.sidebar_navigation.search"),Aqe("everything",V),{onClick:i,ariaLabel:ae,attrs:{"data-command-palette-trigger":"",title:O}}),ne=(le,q,we)=>{const B=le;return c.jsx(Je,{content:q,side:"right",children:c.jsx("button",{type:"button",...we.attrs,onClick:we.onClick,disabled:we.disabled,"aria-label":q,className:T("flex size-8 items-center justify-center rounded-sm text-ink-muted","transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink","disabled:text-ink-disabled disabled:hover:bg-transparent"),children:c.jsx(B,{size:16,"aria-hidden":"true"})})})},fe=c.jsx("div",{className:T(s!=="overlay"&&T("pointer-events-none opacity-0 transition-opacity duration-fast ease-out-quart","group-hover/sidebar:pointer-events-auto group-hover/sidebar:opacity-100","group-focus-within/sidebar:pointer-events-auto group-focus-within/sidebar:opacity-100")),children:c.jsx(Je,{content:D,side:"right",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":D,"aria-expanded":s==="overlay"?void 0:n,"aria-keyshortcuts":KF(V),children:c.jsx(L,{"aria-hidden":"true"})})})}),ue=c.jsx(Je,{content:x("ui.shell.sidebar_navigation.settings"),side:"top",children:c.jsx("button",{type:"button","data-tour-tag":"nav-item-settings",onClick:()=>e("/settings"),"aria-current":t==="settings"?"page":void 0,"aria-label":x("ui.shell.sidebar_navigation.settings"),className:T("flex size-8 shrink-0 items-center justify-center rounded-sm text-ink-muted","transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink",t==="settings"&&"text-ink"),children:c.jsx(Pc,{size:16,"aria-hidden":"true"})})});return n?c.jsxs("div",{"data-sidebar-shell":"","data-glass-region":"sidebar",className:"group/sidebar flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[c.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-1 pr-2 pl-4",children:[c.jsx(h4,{expanded:!0}),c.jsx("span",{className:"ml-auto",children:fe})]}),c.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-2 pb-2",children:[c.jsxs("div",{className:"flex flex-col gap-0.5",children:[P,z]}),c.jsx("ul",{className:"flex flex-col gap-0.5",children:R.map(M)})]}),c.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:F}),c.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-1 px-2 pb-2",children:[c.jsx(Bk,{expanded:!0}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(d4,{}),ue]})]})]}):c.jsxs("div",{"data-sidebar-strip":"","data-glass-region":"sidebar",className:"group/sidebar flex h-full min-h-0 flex-col items-center bg-surface",children:[c.jsx(rJe,{}),c.jsx("div",{className:"flex h-10 shrink-0 items-center justify-center",children:c.jsx(h4,{expanded:!1})}),c.jsxs("ul",{className:"flex flex-col items-center gap-1",children:[c.jsx("li",{children:ne(ga,D,{onClick:r,attrs:{"aria-expanded":!1,"aria-keyshortcuts":KF(V)}})}),c.jsx("li",{children:ne(KS,J,{onClick:G,disabled:!j,attrs:{"data-tour-tag":"nav-item-chat"}})}),c.jsx("li",{children:ne(xd,ae,{onClick:i,attrs:{"data-command-palette-trigger":""}})})]}),c.jsx("ul",{className:"mt-4 flex flex-col items-center gap-1",children:R.map(M)}),c.jsxs("div",{className:"mt-auto flex flex-col items-center gap-1 pb-2",children:[c.jsx(d4,{}),ue,c.jsx(Bk,{expanded:!1})]})]})},oJe=1,lJe=()=>{const{isAuthenticated:e,user:t}=OB(),{hasBeenNotified:n,setHasBeenNotified:s}=h$(),[r,i]=g.useState(!1),[a,o]=g.useState(null),l=g.useCallback(async()=>{if(!(!e||!t?.radientUser?.account?.tenant_id))try{const f=await aJ({operation:"credits",tenantId:t.radientUser.account.tenant_id});if(!f||typeof f.balance!="number")throw new Error("Invalid credit balance response format");o(f.balance)}catch(f){console.error("Failed to fetch Radient credits:",f),o(null)}},[e,t?.radientUser?.account?.tenant_id]);return g.useEffect(()=>{e&&l()},[e,l]),g.useEffect(()=>{e&&a!==null?a<oJe?n||i(!0):(i(!1),n&&s(!1)):i(!1)},[e,n,a,s]),{isLowCreditsDialogOpen:r,openRadientConsole:()=>{window.api?.openExternal?window.api.openExternal("https://console.radienthq.com"):window.open("https://console.radienthq.com","_blank"),s(!0),i(!1)},closeLowCreditsDialog:()=>{i(!1)},onLowCreditsDialogClose:()=>{s(!0),i(!1)},currentCredits:a}};function cJe(){const e=Jr();g.useEffect(()=>{const t=r=>{e(r==="back"?-1:1)},n=r=>{const i=ofe(r);i&&(r.preventDefault(),t(i))},s=r=>{const i=lfe(r);i&&(r.preventDefault(),t(i))};return window.addEventListener("keydown",n),window.addEventListener("mouseup",s),()=>{window.removeEventListener("keydown",n),window.removeEventListener("mouseup",s)}},[e])}function uJe(){const e=navigator.windowControlsOverlay;if(!e?.getTitlebarAreaRect)return null;try{const t=e.getTitlebarAreaRect();return t.width<=0&&t.height<=0?null:{x:t.x,y:t.y,width:t.width,height:t.height}}catch{return null}}function dJe(e,t,n){const s=document.documentElement;if(t==="mac"){s.dataset.chromeLeading="true",s.dataset.chromeTrailing="false";return}if(e===null){s.dataset.chromeLeading="false",s.dataset.chromeTrailing="false";return}s.dataset.chromeLeading=e.x<=1?"true":"false",s.dataset.chromeTrailing=Math.abs(e.x+e.width-n)<=1?"true":"false"}function hJe(e){const t=window.api?.windowChrome;if(!t)return;const n=getComputedStyle(document.documentElement),s=n.getPropertyValue("--lo-canvas").trim(),r=n.getPropertyValue("--lo-ink-muted").trim(),i=n.getPropertyValue("--lo-ink-dim").trim();!s||!r||!i||t.report({themeId:e,colors:{ground:s,symbol:r,symbolInactive:i}})}function fJe(){g.useLayoutEffect(()=>{if(!window.api?.windowChrome)return;const t=document.documentElement.dataset.chromePlatform??"linux",n=()=>dJe(uJe(),t,window.innerWidth);n();const s=navigator.windowControlsOverlay;return s?.addEventListener?.("geometrychange",n),window.addEventListener("resize",n),()=>{s?.removeEventListener?.("geometrychange",n),window.removeEventListener("resize",n)}},[]),g.useEffect(()=>{const e=window.api?.windowChrome;if(e)return e.onState(t=>{document.documentElement.dataset.chromeFullscreen=t.fullScreen?"true":"false"})},[])}const pJe=g.lazy(()=>Vl(()=>import("./agent-details-page-Dbd7Qqbd.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(e=>({default:e.AgentDetailsPage}))),gJe=g.lazy(()=>Vl(()=>import("./agent-hub-page-hB4xULfK.js"),__vite__mapDeps([14,1,2,4,5,6,7,15,3,8,9,10,11,16,17,18,19,12,13]),import.meta.url).then(e=>({default:e.AgentHubPage}))),f4=g.lazy(()=>Vl(()=>import("./agents-page-DfuX5-79.js"),__vite__mapDeps([20,4,5,1,2,6,7,8,16,12,13]),import.meta.url).then(e=>({default:e.AgentsPage}))),mJe=g.lazy(()=>Vl(()=>import("./schedules-page-ByfZ04x2.js"),__vite__mapDeps([21,1,2,4,5,6,7,15,18,10,22,12,13]),import.meta.url).then(e=>({default:e.SchedulesPage}))),p4=g.lazy(()=>Vl(()=>import("./projects-page-B4mpUcqQ.js"),__vite__mapDeps([23,1,2,4,5,6,7,15,24,12,13]),import.meta.url).then(e=>({default:e.ProjectsPage}))),vJe=g.lazy(()=>Vl(()=>import("./browser-page-DbFH9sog.js"),__vite__mapDeps([25,1,2,4,5,6,7,12,13]),import.meta.url).then(e=>({default:e.BrowserPage}))),bJe=g.lazy(()=>Vl(()=>import("./mesh-page-Z6_brJoS.js"),__vite__mapDeps([26,1,2,4,5,6,7,15,12,13]),import.meta.url).then(e=>({default:e.MeshPage}))),xJe=g.lazy(()=>Vl(()=>import("./settings-page-DaWmx0G_.js"),__vite__mapDeps([27,1,2,4,5,6,7,15,17,28,11,22,10,18,12,13]),import.meta.url).then(e=>({default:e.SettingsPage}))),wJe=g.lazy(()=>Vl(()=>import("./browser-webauthn-prompt-DW800ko_.js"),__vite__mapDeps([29,1,2,5,6,4,7,12,13]),import.meta.url).then(e=>({default:e.BrowserWebauthnPrompt}))),CJe=()=>{Et(),fJe(),AQe();const{pathname:e}=aT(),t=e.startsWith("/chat")||e.startsWith("/browser"),{isOnboardingActive:n}=Kae(),{isLowCreditsDialogOpen:s,openRadientConsole:r,onLowCreditsDialogClose:i}=lJe(),{isCommandPaletteOpen:a,isCreateAgentDialogOpen:o,isSidebarCollapsed:l,closeCreateAgentDialog:u}=qe();wl(a,"command-palette"),wl(o,"create-agent-dialog"),wl(n,"onboarding"),wl(s,"low-credits");const d=Jr(),h=Bn(),f=yt(h.data,"session_catalogue",2),p=yt(h.data,"session_archive");g.useEffect(()=>{Ce.getState().requestArchiveConfirm(null)},[e]);const m=pa(h.data,"peers"),v=E=>{Ce.getState().stageDraft({kind:"agent",name:E.name}),d("/chat"),u()};Jqe(),PQe(),Oqe(),cJe(),zfe();const b=Ce(E=>E.setActiveSession),w=Ce(E=>{const R=E.activeDraftKey?E.drafts[E.activeDraftKey]:void 0;return ip(E.activeDraftKey,R?.sessionId,E.activeSessionId)}),C=Noe({displayedSessionId:w,archiveEnabled:p}),y=qe(E=>E.setConsolePaneOpen),k=qe(E=>E.setBrowserPaneOpen),_=qe(E=>E.setConsoleActiveSurface);return g.useEffect(()=>{const E=window.api?.desktop?.onOpenConversation?.((R,F)=>{R!==null&&performance.mark("lop:open:requested"),b(R),F!==void 0&&R!==null&&(_(F),y(!0)),d("/chat")});return()=>E?.()},[d,b,y,_]),g.useEffect(()=>{const E=window.api?.console?.onReveal?.(R=>{R.mode!=="none"&&(R.mode==="session"&&R.session_id!==w||(R.mode==="open"&&b(R.session_id),_(R.surface),y(!0)))});return()=>E?.()},[w,b,y,_]),fle(),yqe(),g.useEffect(()=>{const E=window.api?.browser?.onConsentAttention?.(R=>{const F=Boe(R.requesterSessionId,Ce.getState().sessions);if(Moe(R.entryId),F.kind==="browser"){d("/browser");return}b(F.sessionId),k(!0),d("/chat")});return()=>E?.()},[d,b,k]),g.useEffect(()=>{const E=R=>{n||f&&Sqe(R)&&(R.preventDefault(),Ce.getState().stageDraft(void 0,!0),d("/chat"))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[f,n,d]),c.jsx(SQe,{children:c.jsx("div",{className:"relative flex h-screen flex-col overflow-hidden","data-titlebar-sidebar-collapsed":l?"true":"false",children:c.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[a&&c.jsx(Kqe,{}),c.jsx(Eqe,{}),c.jsx(oJ,{}),c.jsx(Zqe,{enabled:m==="enabled"}),c.jsx(qKe,{open:n}),c.jsx(EQe,{}),c.jsx(RQe,{}),p&&c.jsx(vle,{}),c.jsx(xoe,{}),c.jsx(g.Suspense,{fallback:null,children:c.jsx(wJe,{})}),c.jsx(Roe,{blocked:n||s||a||o||C,sessionId:e.startsWith("/chat")?w??null:null}),c.jsx(NQe,{open:s,onClose:i,onGoToConsole:r}),c.jsx(Zae,{open:o,onClose:u,onAgentCreated:v}),c.jsx(lJ,{sidebar:c.jsx(aJe,{}),content:c.jsxs("main",{"data-glass-region":"canvas-backing",className:"flex grow flex-col overflow-hidden",children:[t?null:c.jsx("div",{"data-chrome-route-band":""}),c.jsx(g.Suspense,{fallback:c.jsx("div",{className:"flex grow items-center justify-center",children:c.jsx(pn,{size:"lg",label:x("ui.common.loading.page")})}),children:c.jsxs(cJ,{children:[c.jsx(ri,{path:"/",element:c.jsx(SF,{to:"/chat",replace:!0})}),c.jsx(ri,{path:"/chat",element:c.jsx(w3,{})}),c.jsx(ri,{path:"/chat/:agentId",element:c.jsx(w3,{})}),c.jsx(ri,{path:"/agents",element:c.jsx(f4,{})}),c.jsx(ri,{path:"/agents/:agentId",element:c.jsx(f4,{})}),c.jsx(ri,{path:"/settings",element:c.jsx(xJe,{})}),c.jsx(ri,{path:"/agent-hub",element:c.jsx(gJe,{})}),c.jsx(ri,{path:"/agent-hub/:agentId",element:c.jsx(pJe,{})}),c.jsx(ri,{path:"/schedules",element:c.jsx(mJe,{})}),c.jsx(ri,{path:"/projects",element:c.jsx(p4,{})}),c.jsx(ri,{path:"/projects/:projectId",element:c.jsx(p4,{})}),c.jsx(ri,{path:"/browser",element:c.jsx(vJe,{})}),m==="enabled"&&c.jsx(ri,{path:"/mesh",element:c.jsx(bJe,{})}),c.jsx(ri,{path:"*",element:c.jsx(SF,{to:"/chat",replace:!0})})]})})]})})]})})})};function qu(){return new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))})}const yJe=3,_Je=3e3;function SJe(e){return e instanceof CSSTransition&&e.playState==="running"}function EJe(e){const t=e.effect,n=t instanceof KeyframeEffect?t.target:null,s=e.transitionProperty,i=/^[a-z-]+$/.test(s)&&n instanceof Element?getComputedStyle(n).getPropertyValue(s).trim()||"(empty)":"(unreadable)";return`${s||"(unnamed property)"} on ${E0(n)??"an element no longer in the document"} = ${i}`}async function kJe(e=_Je){const t=performance.now();let n=0;for(;;){await qu();const s=Math.round(performance.now()-t),r=document.getAnimations().filter(SJe);if(n=r.length===0?n+1:0,n>=yJe)return{waitedMs:s,timedOut:!1,pending:[]};if(s>e)return{waitedMs:s,timedOut:!0,pending:r.map(EJe)}}}const TJe=/^#/;function wm(){const e=window.location.hash.replace(TJe,"");return e===""?"/":e}function E0(e){if(!e)return null;const t=e.getAttribute("aria-label")??e.textContent??"";return`${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""} "${t.trim().slice(0,60)}"`}function RJe(e){const t=e.getBoundingClientRect(),n=t.left+t.width/2,s=t.top+t.height/2,r=document.elementFromPoint(n,s),i=r!==null&&(r===e||e.contains(r)),a=document.elementsFromPoint(n,s).slice(0,4).map(l=>E0(l)),o={bubbles:!0,cancelable:!0,composed:!0,button:0,buttons:1,clientX:n,clientY:s,view:window};return e.dispatchEvent(new PointerEvent("pointerdown",{...o,pointerId:1,isPrimary:!0})),e.dispatchEvent(new MouseEvent("mousedown",o)),e.dispatchEvent(new PointerEvent("pointerup",{...o,buttons:0,pointerId:1,isPrimary:!0})),e.dispatchEvent(new MouseEvent("mouseup",{...o,buttons:0})),e.dispatchEvent(new MouseEvent("click",{...o,buttons:0})),{hitTest:i,hit:E0(r),stack:a,disabled:e instanceof HTMLButtonElement?e.disabled:null,rect:{x:t.x,y:t.y,width:t.width,height:t.height}}}function gg(e,t){if(typeof e!="string"||e==="")throw new Error(`${t} must be a non-empty string`);return e}async function AJe(e,t=1e4){const n=Date.now();for(;wm()!==e;){if(Date.now()-n>t)throw new Error(`route did not become ${e} (it is ${wm()})`);await new Promise(s=>setTimeout(s,50))}return await qu(),wm()}const jk=["dev-driver","query-fetch-probe"];let Cm=null;function FJe(){if(Cm)return Cm;const e=[],t=EF.prototype.fetch;return EF.prototype.fetch=function(...s){return e.push({at:Date.now(),key:JSON.stringify(this.queryKey),stack:(new Error().stack??"").split(`
|
|
684
|
+
A good description helps you and others understand what the agent does and any special instructions. The descriptions are also used by other agents to help them understand how to tag each other in for certain tasks.<br /><br />If you want this agent to be part of the agent-to-agent communication network, it will need to have a description that captures its purpose and capabilities. Be concise and specific.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="create-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="create-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"navigate-agent-hub",attachTo:{element:'[data-tour-tag="nav-item-agent-hub"]',on:"right"},title:"Discover more agents",text:`Let's visit the Agent hub to find community-created agents. Click on the "Agent hub" icon in the navigation bar.`,buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{const t=document.querySelector('[data-tour-tag="create-new-agent-button"]');t&&t.click()},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agent-hub"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"agent-hub-view",attachTo:{element:'[data-tour-tag="agent-hub-sidebar-container"]',on:"right"},title:"The Agent hub",text:"Here you can browse agents by category or search for specific ones. These agents are shared by the community and can perform various specialized tasks.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"download-agent",attachTo:{element:'button[data-tour-tag="agent-hub-download-button"]',on:"bottom"},title:"Download an agent",text:'Find an agent that interests you and click the "Get" button to add it to your local agent list.',buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{this.next()},1e3)}}]},{id:"upload-agent-hub",attachTo:{element:()=>CQe("upload-to-hub-header-button"),on:"bottom"},title:"Share your agents",text:"If you create a useful agent, you can also share it with the community by uploading it to the Agent hub from the agent options menu.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agent-hub"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){o4("open-upload-dialog"),setTimeout(()=>{this.next()},500)}}]},{id:"upload-agent-hub-dialog",attachTo:{element:'[data-tour-tag="upload-agent-dialog"]',on:"right"},title:"Upload agent to hub",text:"This dialog publishes your agent's instruction set to the community. You need a Radient account to publish, which is free to create and costs nothing per agent. You can review the details before confirming. What is published is what describes the agent - its name, description, instructions and tool surface; no conversation, execution history, memory, plan or machine-specific configuration leaves your computer. Make sure your agent meets the required criteria before submitting.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('button[data-tour-tag="upload-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="upload-agent-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"navigate-schedules",attachTo:{element:'[data-tour-tag="nav-item-schedules"]',on:"right"},title:"Automate tasks with schedules",text:"Local Operator can run tasks for you on a regular basis. Let's check out the Schedules section.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{o4("open-upload-dialog")},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-schedules"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"schedules-overview",title:"Proactive agents with schedules",text:"A powerful feature of Local Operator is the ability to ask agents to perform tasks on their own on a recurring basis. This turns them from reactive agent bots to proactive agents that work on their own in the background to support you without you needing to continually ask them to do things.<br /><br />You can simply ask any agent to do something at some point in the future, or to handle some daily task at a certain time, and it will create a prompt for itself that will be executed at the specified times.<br /><br />Here, you can view, create, and manage all your scheduled tasks in one place to streamline your workflow and ensure important actions happen automatically.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"create-schedule",attachTo:{element:'button[data-tour-tag="create-schedule-button"]',on:"bottom"},title:"Set up a recurring task",text:'Click "Create schedule" to ask an agent to perform a task for you regularly, like sending a daily report or checking for news updates.<br /><br />You can also create one-off tasks that only run once at some point in the future.',buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('button[data-tour-tag="create-schedule-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"create-schedule-dialog",attachTo:{element:'[data-tour-tag="create-schedule-dialog"]',on:"right"},title:"Configure your schedule",text:"While it is often much easier to simply ask the agent to do a task on a recurring basis for you, you can also manually set up a schedule for a task here or update existing tasks.<br /><br />The prompt is the message that will be sent to the agent at the predefined schedule. You can update the time of day in your local timezone, the frequency of the task, and even specify a specific date or time that the task should stop running at.<br /><br />You can also schedule one-off tasks that only run once at some point in the future.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="create-schedule-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.back()},500)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="create-schedule-dialog-cancel-button"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"navigate-settings",attachTo:{element:'[data-tour-tag="nav-item-settings"]',on:"right"},title:"Personalize your experience",text:"Now, let's explore the Settings menu to customize Local Operator to your liking.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-schedules"]');e&&e.click(),setTimeout(()=>{const t=document.querySelector('button[data-tour-tag="create-schedule-button"]');t&&t.click()},500),setTimeout(()=>{this.back()},1e3)}},{text:"Next",classes:"shepherd-button-primary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-settings"]');e&&e.click(),setTimeout(()=>{this.next()},500)}}]},{id:"general-settings",attachTo:{element:'div[data-tour-tag="settings-general-section"]',on:"right"},title:"General settings",text:"Here you can update your user profile and configure model settings (like default hosting provider and model).",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"appearance-settings",attachTo:{element:'[data-tour-tag="settings-appearance-section"]',on:"right"},title:"Customize appearance",text:"Choose from various themes to change the look and feel of Local Operator. Find one that suits your style.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"radient-account-settings",attachTo:{element:'[data-tour-tag="settings-radient-account-section"]',on:"right"},title:"Radient account",text:"Connect your Radient account to access your Radient Pass details, credits, and unlock unified access to models and tools. Radient is the best way to use Local Operator since it powers the AI models, web search, image generation, and much more with a single integration. You get free credits when you sign up to try it out and bonus credits when you top up.<br /><br />When you sign in for the first time, it will automatically create a Radient Pass for you and save it securely to your computer. This will power your Local Operator agents with Radient Automatic, which mixes and matches AI models to get you the best balance of speed, accuracy, and cost in every step of your agents' workflows.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"integrations-settings",attachTo:{element:'[data-tour-tag="settings-integrations-section"]',on:"right"},title:"Connect your services",text:"Enhance your agents' capabilities by connecting your Google services like Gmail, Calendar, and Drive. This allows agents to access and manage your information with your permission.<br /><br />You need to be logged in to a Radient account to use this feature, however it is free to use and doesn't cost any additional Radient credits per action.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"application-updates-settings",attachTo:{element:'[data-tour-tag="settings-app-updates-section"]',on:"right"},title:"Stay up to date",text:"Check for updates to Local Operator here to ensure you have the latest features and improvements. You can see your current version information below.",buttons:[{text:"Back",classes:"shepherd-button-secondary",action:function(){this.back()}},{text:"Next",classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"tour-complete",title:"Tour complete",text:"You've now seen the main features of Local Operator. Feel free to explore further and discover all the ways your AI agents can assist you. Happy automating.",buttons:[{text:"Finish",classes:"shepherd-button-primary",action:function(){this.complete()}}]}],yQe=()=>{const e=Jr(),{completeTourOnboarding:t}=ym(),n=g.useContext(sy),s={cancelIcon:{enabled:!0},scrollTo:{behavior:"smooth",block:"center"}},r=!0;return{startTour:a=>{if(n?.tour?.isActive()&&!a?.forceModalCompleted){console.log("Onboarding tour is already active (from context.tour). Not starting another.");return}const o=ym.getState();if(!a?.forceModalCompleted&&!o.isModalComplete){console.log("Onboarding modal not completed (checked via store). Tour will not start.");return}if(o.isTourComplete&&!a?.forceModalCompleted){console.log("Onboarding tour already completed in store and not forced. Not starting again.");return}let l=n?.tour;const u=n?.Shepherd;if(!l&&u&&(l=u.activeTour,!l&&u.Tour&&(console.log("No active Shepherd tour found from context or global. Creating a new one."),l=new u.Tour({useModalOverlay:r,defaultStepOptions:s}))),!l){console.warn("Failed to get or create a Shepherd tour instance.",n);return}if(l.isActive()){console.log("Tour is already active. Not starting again.");return}if(l.options.defaultStepOptions={...l.options.defaultStepOptions||{},...s},l.options.useModalOverlay=r,a?.firstAgentId&&(l.options.firstAgentId=a.firstAgentId),l.off("complete",t),l.on("complete",t),l.off("cancel",t),l.on("cancel",t),a?.forceModalCompleted||!l.isActive()){const d=[...l.steps];for(const h of d)h.id&&l.removeStep(h.id);l.addSteps(l4)}else l.steps.length===0&&l.addSteps(l4);typeof l.start=="function"?(e("/"),l.start()):console.warn("Shepherd tour instance does not have a start method.",l)}}},_Qe=()=>{const{isModalComplete:e,isTourComplete:t}=ym(),{startTour:n}=yQe(),s=$e.useContext(sy),{data:r}=YS(1,1);return g.useEffect(()=>{if(e&&!t&&s){const i=setTimeout(()=>{const a=r?.agents?.[0]?.id;n({firstAgentId:a})},500);return()=>clearTimeout(i)}},[e,t,s,n,r]),null},SQe=({children:e})=>c.jsxs(hQe,{children:[e,c.jsx(_Qe,{})]}),EQe=()=>{Et();const{open:e,focusGroup:t,providerId:n,closeConnect:s}=RB(),r=g.useRef(null);g.useEffect(()=>{e&&(r.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},[e]);const i=Jr();return c.jsx(Wl,{open:e,onOpenChange:a=>{a||s()},children:c.jsxs($l,{className:"max-h-[calc(100vh-4rem)] max-w-[min(40rem,calc(100vw-4rem))] gap-4 overflow-y-auto","data-connect-provider-dialog":"",onCloseAutoFocus:a=>{const o=r.current;r.current=null,o?.isConnected&&(a.preventDefault(),o.focus())},children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx(jo,{className:"text-title",children:x("ui.providers.connect_provider_dialog.connect_a_model_provider")}),c.jsx(ru,{className:"text-body-sm text-ink-muted",children:x("ui.providers.connect_provider_dialog.your_agents_need_a_model_to_think")})]}),e?c.jsx(GW,{context:"dialog",featuredOnly:!0,focusGroup:t,initialProviderId:n,onDone:s,onChangeModel:()=>{s(),i("/settings")}}):null]})})},kQe=({title:e,description:t,icon:n,children:s,titleComponent:r,sectionRef:i,dataTourTag:a,className:o,id:l})=>c.jsxs("div",{ref:i,id:l,tabIndex:l?-1:void 0,"data-tour-tag":a,className:T("w-full",o),children:[r??c.jsxs("h2",{className:"flex items-center gap-2 text-heading text-ink",children:[n&&c.jsx(n,{size:16,className:"shrink-0 text-ink-dim"}),e]}),t&&c.jsx("p",{className:"mt-1 max-w-2xl text-body-sm text-ink-muted",children:t}),c.jsx("div",{className:"mt-4",children:s})]}),met=({label:e,value:t,className:n,valueClassName:s})=>c.jsxs("div",{className:T("min-w-0",n),children:[c.jsx("div",{className:"flex items-center gap-1.5 text-meta text-ink-dim",children:e}),c.jsx("div",{className:T("mt-0.5 break-words text-body-sm",s??"text-ink"),children:t})]}),vet=({children:e,className:t})=>c.jsx("div",{className:T("grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-x-6 gap-y-4",t),children:e});async function u$(e){await xt({op:"settings.edit",key:Ro,value:e.value}),YQ(e.queryClient)}async function TQe(e){await u$(e),e.queryClient.setQueryData(ax.all,t=>t&&{...t,settings:t.settings.map(n=>n.key===Ro?{...n,value:e.value,is_default:e.value===n.default}:n)});try{return await e.queryClient.fetchQuery({queryKey:ax.all,queryFn:()=>xt({op:"settings.list"}),staleTime:0,retry:!1}),"confirmed"}catch{return"readback-unknown"}}const bet=({focus:e=!1})=>{Et();const t=nn(),n=Bn(),s=yt(n.data,"settings"),r=fs({queryKey:ax.all,queryFn:()=>xt({op:"settings.list"}),enabled:s,retry:!1,refetchOnReconnect:!0}),i=r.data?.settings.find(F=>F.key===Ro),[a,o]=g.useState(!1),[l,u]=g.useState(null),[d,h]=g.useState(!1),[f,p]=g.useState(!1),m=g.useRef(!1),v=g.useRef(null),b=g.useRef(!1);g.useEffect(()=>{if(!e){b.current=!1;return}!i||b.current||(v.current?.querySelector("[role=combobox]")?.focus(),b.current=!0)},[e,i]),g.useEffect(()=>{r.isSuccess&&!r.isFetching&&h(!1)},[r.isFetching,r.isSuccess]);const w=async F=>{if(!(!i||m.current||d||!i.choices.some(A=>A.value===F))){m.current=!0,o(!0),u(null),p(!1);try{const A=await TQe({value:F,queryClient:t});h(A==="readback-unknown"),p(A==="confirmed")}catch(A){u({value:F,message:A instanceof Error?A.message:""})}finally{m.current=!1,o(!1)}}},C=async()=>{const[F,A]=await Promise.all([r.refetch(),n.refetch()]);!F.isError&&!A.isError&&h(!1)},y=!r.data&&r.error||!n.data&&n.error,k=n.data&&(!s||r.data&&!i),_=!y&&!k&&!i,E=n.data?.features?.i18n?n.data.language:void 0,R=typeof E=="string"&&E!==""?E:void 0;return c.jsx(kQe,{title:x("ui.settings.language.dialog.title"),icon:xj,description:x("ui.settings.language.general.description"),children:c.jsxs("div",{ref:v,"data-setting-key":Ro,className:"flex flex-col gap-3","aria-busy":a,children:[_&&c.jsx("output",{className:"text-meta text-ink-dim",children:x("ui.settings.language.dialog.loading")}),k&&c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.settings.language.dialog.unavailable")}),i&&c.jsx(MB,{setting:{...dT(i),label:x("ui.settings.language.dialog.title")},value:String(i.value),onValueChange:F=>{w(F)},disabled:a||d,suppressEffectiveNote:!0}),c.jsx("output",{id:qQ(Ro),"aria-live":"polite",className:"text-meta text-ink-dim",children:a?x("ui.settings.language.general.pending"):f?x("ui.settings.language.general.saved"):R?x(d||n.error?"ui.settings.language.general.last_known":"ui.settings.language.general.effective",{locale:KQ(R)?.name??R}):x("ui.settings.language.general.no_resolution")}),(y||l||d)&&c.jsx(Kr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:l?x("ui.settings.language.general.write_error",{message:l.message}):d?x("ui.settings.language.general.readback_error"):x("ui.settings.language.dialog.unavailable")}),c.jsx(ce,{variant:"outline",size:"sm",disabled:a||r.isFetching||n.isFetching,onClick:()=>{l?w(l.value):C()},children:x("ui.settings.language.dialog.retry")})]})})]})})},RQe=()=>{Et();const e=Dk(te=>te.open),t=Dk(te=>te.closeLanguage),n=nn(),s=Bn(),r=yt(s.data,"settings"),i=fs({queryKey:ax.all,queryFn:()=>xt({op:"settings.list"}),enabled:e&&r,staleTime:1e4}),a=g.useRef(null),o=bB(),l=(i.data?.settings??[]).find(te=>te.key===Ro),u=l?dT(l):void 0,[d,h]=g.useState(null),[f,p]=g.useState(!1),[m,v]=g.useState(!1),[b,w]=g.useState(null),C=g.useRef(null);g.useEffect(()=>{e&&h(null)},[e]),g.useEffect(()=>{if(!e||!u)return;const te=String(u.value??"");(d===null||d===C.current)&&h(te),C.current=te},[e,u,d]),g.useEffect(()=>{e&&(v(!1),w(null))},[e]);const y=d??String(u?.value??""),k=!!u&&y!==String(u?.value??""),_=!u||!k||f,E=async()=>{if(!(!u||!k)){p(!0),w(null);try{await u$({value:y,queryClient:n}),v(!0),h(null),await i.refetch()}catch(te){w(te instanceof Error?te.message:x("ui.settings.configuration.language_dialog.the_language_could_not_be_saved"))}finally{p(!1)}}},R=!!s.data,F=R&&!r,A=s.error&&!s.data?s.error:null,N=A??i.error,M=!R&&!N,{sentence:D,remedy:L}=XQ(o??null,x("ui.settings.configuration.language_dialog.your_settings_could_not_be_loaded"),N),V=s.isFetching||i.isFetching,j=u?"combo":N?"retry":"none";return g.useEffect(()=>{!e||j==="none"||requestAnimationFrame(()=>{a.current?.querySelector(j==="combo"?'[role="combobox"]':"[data-language-retry]")?.focus()})},[e,j]),c.jsx(Wl,{open:e,onOpenChange:te=>!te&&t(),children:c.jsxs($l,{ref:a,onOpenAutoFocus:te=>te.preventDefault(),className:"max-w-[min(28rem,calc(100vw-4rem))] gap-4",children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx(jo,{className:"text-title",children:x("ui.settings.language.dialog.title")}),c.jsx(ru,{className:"text-body-sm text-ink-muted",children:x("ui.settings.language.dialog.description")})]}),M?c.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{}),x("ui.settings.language.dialog.loading")]}):F?c.jsx(Kr,{variant:"warning",children:c.jsx("span",{children:x("ui.settings.language.dialog.unavailable")})}):N?c.jsx(Kr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:D}),L&&c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0","data-language-retry":"",onClick:()=>{A?s.refetch():i.refetch()},disabled:V,children:V?x("ui.settings.language.dialog.retrying"):x("ui.settings.language.dialog.retry")})]})}):i.isPending?c.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(pn,{}),x("ui.settings.language.dialog.loading")]}):u?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{id:yF(Ro),className:"text-meta text-ink-dim",children:u.help}),c.jsx(MB,{setting:u,value:y,disabled:f,helpId:yF(Ro),effectiveNoteId:QQ(Ro,JQ),onValueChange:te=>{v(!1),h(te)}})]}),b&&c.jsx("p",{className:"text-meta text-danger",children:b}),c.jsx("div",{className:"flex min-h-8 items-center justify-end",children:m&&!k?c.jsxs("output",{"data-language-save":"",className:"inline-flex items-center gap-1.5 text-body-sm text-ink",children:[c.jsx(Bs,{"aria-hidden":"true",className:"size-3.5"}),x("ui.settings.language.dialog.saved")]}):c.jsx(ce,{onClick:E,disabled:_,"data-language-save":"",children:f?`${x("ui.settings.language.dialog.save")}...`:x("ui.settings.language.dialog.save")})})]}):c.jsx(Kr,{variant:"warning",children:c.jsx("span",{children:x("ui.settings.language.dialog.unavailable")})})]})})};function AQe(){const{data:e}=Bn();g.useEffect(()=>{e&&W$(e)},[e]);const t=oT(),n=nn(),s=g.useRef(null);g.useEffect(()=>{const r=t.configChange;if(!r)return;const i=`${r.epoch}:${r.seq}`;s.current!==i&&r.changedKeys.includes(Ro)&&(s.current=i,n.invalidateQueries({queryKey:Bo.capabilities}),n.invalidateQueries({queryKey:Bo.settings}),!ZQ()&&Va(x("ui.settings.language.external_notice",{language:r.language}),{id:"i18n-language-external"}))},[t.configChange,n])}function FQe(e,t){if(e.defaultPrevented||e.repeat||e.isComposing||!(e.metaKey||e.ctrlKey))return null;const n=eJ(e);if(n===null)return null;const s=BZ(t.bindings).get(n);return s===void 0||lT(e.target)||!Sue(d$(s),t.route)?null:s}const d$=e=>e.slice(6);function DQe(e){const t=Ce.getState(),n=t.activeDraftKey?t.drafts[t.activeDraftKey]:void 0,s=ip(t.activeDraftKey,n?.sessionId,t.activeSessionId)??null;Gu(d$(e),{sessionId:s,askScope:s===null?"fleet":"session",via:"chord"})}function PQe(){g.useEffect(()=>{const e=t=>{const n=qe.getState(),s=FQe(t,{bindings:n.shortcutBindings,route:n.rightSlotRoute});s!==null&&(t.preventDefault(),DQe(s))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}const IQe=""+new URL("radient-icon-1024x1024-D_JJedvo.png",import.meta.url).href,h$=op()(KB(e=>({hasBeenNotified:!1,setHasBeenNotified:t=>{e({hasBeenNotified:t})}}),{name:"low-credits-storage"})),NQe=({open:e,onClose:t,onGoToConsole:n})=>{Et();const{setHasBeenNotified:s}=h$(),{prices:r,isLoading:i,error:a}=tJ(),o=d=>typeof d!="number"?"$...":x("ui.common.account.low_credits_dialog.detail",{detail:String(d.toFixed(2))}),l=()=>{s(!0),t()},u=()=>{s(!0),n()};return c.jsx(su,{open:e,onClose:l,title:c.jsxs(c.Fragment,{children:[c.jsx("img",{src:IQe,alt:x("ui.common.account.low_credits_dialog.radient_icon"),className:"size-7"}),x("ui.common.account.low_credits_dialog.running_low_on_radient_credits")]}),maxWidth:"sm",fullWidth:!1,actions:c.jsxs(c.Fragment,{children:[c.jsx(k0,{onClick:l,children:x("ui.common.account.low_credits_dialog.maybe_later")}),c.jsx(T0,{onClick:u,startIcon:c.jsx(xl,{size:18}),className:"min-w-55",children:x("ui.common.account.low_credits_dialog.get_more_credits")})]}),children:c.jsxs("div",{className:"flex flex-col items-center gap-4 py-2 text-center",children:[c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[x("ui.common.account.low_credits_dialog.unlock_the_full_power_of_local_operator_with")," ",c.jsx("span",{className:"font-bold text-accent",children:x("ui.common.account.low_credits_dialog.radient_pass")}),"."]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.common.account.low_credits_dialog.radient_automatic_is_often_cheaper_than_bringing_your_own_key_its")}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:x("ui.common.account.low_credits_dialog.it_s_pay_as_you_go_with_no_commitments_load_up_what_you_need_star")}),c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[x("ui.common.account.low_credits_dialog.plus_get")," ",c.jsx("span",{className:"font-medium text-ink",children:i?c.jsx(pn,{size:"sm",className:"mr-0.5 align-middle"}):o(r?.default_registration_credits)})," ",x("ui.common.account.low_credits_dialog.in_bonus_credits_with_your_first_purchase"),a&&c.jsx("span",{className:"mt-1 block text-meta text-danger",children:x("ui.common.account.low_credits_dialog.could_not_load_bonus_credit_information")})]}),c.jsx("p",{className:"text-meta text-ink-dim",children:x("ui.common.account.low_credits_dialog.you_can_also_reach_the_radient_console_from_settings_at_any_time")})]})})},MQe=(e,t)=>t?$1(e.filter(n=>n.session_id===t)).length:0;function OQe(e){return Ce(t=>MQe(t.sessions,e))}const LQe=(e,t)=>t?e.some(n=>n.session_id===t&&n.status?.code==="busy"):!1;function BQe(e){return Ce(t=>LQe(t.sessions,e))}const jQe=[];function HQe(){const{state:e}=xC(),t=e?.pendingConsent??jQe,n=d5(s=>qP(t,s));return g.useEffect(()=>{t.length>0&&WT()},[t]),qP(t,n)}const f$={approvals:["desktop","mesh","approvals"]},UQe=15e3,GQe=new Set(["requested","approved","connecting","failed"]);function VQe(e){return GQe.has(e)}function WQe(e){return e==="requested"}function $Qe(e){return e.filter(t=>WQe(t.state)).length}function xet(e){return e.state==="requested"&&e.canApproveHere!==!1&&(e.kind==="device"||e.kind==="machine")}function wet(e){return VQe(e)}function Cet(e){switch(e){case"requested":return x("ui.mesh.mesh_approvals.waiting_for_you");case"approved":return x("ui.mesh.mesh_approvals.approved");case"connecting":return x("ui.mesh.mesh_approvals.connecting");case"connected":return x("ui.mesh.mesh_approvals.connected");case"denied":return x("ui.mesh.mesh_approvals.denied");case"expired":return x("ui.mesh.mesh_approvals.expired");case"failed":return x("ui.mesh.mesh_approvals.failed");default:return e}}function Rc(e){return typeof e=="object"&&e!==null}function zQe(e){const t=Rc(e)?e:{};return{deviceId:Ft(t.device_id),name:Ft(t.name),host:Ft(t.host),user:Ft(t.user),transport:Ft(t.transport),hostKeyFp:Ft(t.host_key_fp)}}function qQe(e){const t=Rc(e)?e:{};return{connect:Mo(t.connect,!1),install:Mo(t.install,!1),anchor:Rc(t.anchor),networkId:Ft(t.network_id),role:Ft(t.role),unattended:Mo(t.unattended,!1),grants:Lf(t.grant)}}function KQe(e){const t=Array.isArray(e)?e:e?.approvals??[];if(!Array.isArray(t))return[];const n=[];for(const s of t){if(!Rc(s))continue;const r=Ft(s.approval_id),i=Ft(s.state);if(!r||!i)continue;const a=Rc(s.what)&&Object.prototype.hasOwnProperty.call(s.what,"credential_inheritance"),o=Object.prototype.hasOwnProperty.call(s,"kind")?Ft(s.kind):void 0,l=a||o==="credential_inheritance"?"credential":o!==void 0&&!["device_onboard","local_authority"].includes(o)?"unknown":!Rc(s.device)&&Rc(s.machine)?"machine":"device",u=Rc(s.requested_by)?s.requested_by:{};n.push({approvalId:r,state:i,kind:l,summary:Ft(s.summary)||void 0,details:Array.isArray(s.details)&&s.details.every(d=>typeof d=="string")?s.details.slice():void 0,canApproveHere:Object.prototype.hasOwnProperty.call(s,"can_approve_here")?s.can_approve_here===!0:void 0,approveRemedy:Ft(s.approve_remedy)||void 0,where:zQe(l==="machine"?s.machine:s.device),what:qQe(s.what),requestedBy:{surface:Ft(u.surface),sessionId:Ft(u.session_id),deviceId:Ft(u.device_id)},expiresAt:Ic(s.expires_at)})}return n}function YQe(e){return e.kind==="machine"?x("ui.mesh.mesh_approvals.this_machine"):I5({device_id:e.where.deviceId,name:e.where.name})}function yet(e,t){if(e.kind==="credential"||e.kind==="unknown"||e.canApproveHere===!1){if(e.summary)return e.summary;if(e.kind==="credential"||e.kind==="unknown")return c4(e)}const n=c4(e),s=QQe(e,t).map(r=>r.clause);return s.length?x("ui.mesh.mesh_approvals.approval_title_with_clauses",{head:n,clauses:XQe(s)}):x("ui.mesh.mesh_approvals.approval_title",{head:n})}function c4(e){return e.kind==="credential"?e.summary||x("ui.mesh.approval.credential_title"):e.kind==="unknown"?e.summary||x("ui.mesh.approval.unknown_title"):e.canApproveHere===!1&&e.summary?e.summary:e.kind==="machine"?x("ui.mesh.mesh_approvals.set_up_operator_authority_on_this_machine"):x("ui.mesh.mesh_approvals.onboard_subject",{subject:YQe(e)})}function XQe(e){return e.length===1?e[0]:x("ui.mesh.mesh_approvals.join_clauses",{clauses:e.slice(0,-1).join(", "),last:e[e.length-1]})}function _et(e){if(e.kind==="credential"||e.kind==="unknown")return null;const{user:t,host:n,transport:s,name:r}=e.where,i=[n?t?`${t}@${n}`:n:"",s?x("ui.mesh.mesh_approvals.via_transport",{transport:s}):"",r&&r!==n?`(${r})`:""].filter(Boolean);return i.length?i.join(" "):null}function Eet(e){return e.kind==="credential"||e.kind==="unknown"?null:e.where.hostKeyFp||null}function ket(e){const{surface:t,sessionId:n}=e.requestedBy,s=[t||"",n?x("ui.mesh.mesh_approvals.session_suffix",{suffix:n.slice(-6)}):""].filter(Boolean);return s.length?x("ui.mesh.mesh_approvals.asked_by",{requester:s.join(" · ")}):null}function QQe(e,t){if(e.kind==="credential"||e.kind==="unknown")return[];const{connect:n,install:s,anchor:r,networkId:i,role:a,unattended:o,grants:l}=e.what,u=[];if(n&&u.push({term:"connect",clause:e.where.transport?x("ui.mesh.mesh_approvals.connect_over",{transport:e.where.transport}):x("ui.mesh.mesh_approvals.connect_to_it"),consequence:e.where.transport?x("ui.mesh.mesh_approvals.may_connect_over",{transport:e.where.transport}):x("ui.mesh.mesh_approvals.this_machine_may_connect_to_it")}),s&&u.push({term:"install",clause:e.kind==="machine"?x("ui.mesh.mesh_approvals.install_local_operator"):x("ui.mesh.mesh_approvals.install_local_operator_there"),consequence:e.kind==="machine"?x("ui.mesh.mesh_approvals.local_operator_is_installed_on_this_machine"):x("ui.mesh.mesh_approvals.local_operator_is_installed_on_it")}),r&&u.push({term:x("ui.mesh.mesh_approvals.install_operator_anchor"),clause:x("ui.mesh.mesh_approvals.check_approvals_signed_on_your_machines"),consequence:x("ui.mesh.mesh_approvals.that_device_can_check_approvals_signed_on")}),i){const d=t?.get(i),h=x("ui.mesh.mesh_approvals.join_network",{network:d||i,role:a||"?"});u.push({term:h,clause:h,consequence:x("ui.mesh.mesh_approvals.joins_network",{network:d||i,role:a||"?"})})}o&&u.push({term:x("ui.mesh.mesh_approvals.trust_unattended_sessions"),clause:x("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt"),consequence:x("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")});for(const d of JQe(l,o)){const h=ZQe()[d];u.push({term:h?.term??x("ui.mesh.mesh_approvals.grant_capability",{grant:d}),clause:eJe()[d]??x("ui.mesh.mesh_approvals.use_capability",{grant:d}),consequence:h?.gloss??x("ui.mesh.mesh_approvals.may_use_capability",{grant:d})})}return u}function JQe(e,t){const n=new Set;for(const s of e){const r=String(s??"").trim();r&&(t&&r==="unattended"||n.add(r))}return[...n]}const ZQe=()=>({unattended:{term:x("ui.mesh.mesh_approvals.trust_unattended_sessions"),gloss:x("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")},broker_credential:{term:x("ui.mesh.mesh_approvals.borrow_logins_there"),gloss:x("ui.mesh.mesh_approvals.your_sessions_may_use_the_logins_stored")}}),eJe=()=>({list:x("ui.mesh.mesh_approvals.see_its_sessions"),view:x("ui.mesh.mesh_approvals.watch_a_session_there"),prompt:x("ui.mesh.mesh_approvals.send_prompts_to_a_session_there"),steer:x("ui.mesh.mesh_approvals.steer_a_running_turn_there"),stop:x("ui.mesh.mesh_approvals.stop_a_session_there"),slash:x("ui.mesh.mesh_approvals.run_slash_commands_there"),delete:x("ui.mesh.mesh_approvals.archive_or_delete_a_session_there"),move:x("ui.mesh.mesh_approvals.move_sessions_to_or_from_there"),broker_credential:x("ui.mesh.mesh_approvals.borrow_the_logins_stored_there"),approve:x("ui.mesh.mesh_approvals.answer_approval_prompts_there"),unattended:x("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt")});function Tet(e,t){if(e===null||e<=0)return null;const n=e-t;if(n<=0)return null;if(n<60)return x("ui.mesh.mesh_approvals.expires_in_under_a_minute");const s=Math.ceil(n/60);if(s<90)return x("ui.mesh.mesh_approvals.expires_minutes",{count:s});const r=Math.ceil(s/60);return x("ui.mesh.mesh_approvals.expires_hours",{count:r})}function tJe(e,{poll:t=!0}={}){return fs({queryKey:f$.approvals,enabled:e,queryFn:async()=>KQe(await xt({op:"approvals.list"})),retry:!1,staleTime:t?1e4:Number.POSITIVE_INFINITY,refetchInterval:e&&t?UQe:!1,refetchOnWindowFocus:t})}function Ret(){const e=nn();return Kn({mutationFn:async t=>{const n=t.decision==="approve"?{op:"approvals.approve",approvalId:t.approvalId}:{op:"approvals.deny",approvalId:t.approvalId};await xt(n)},onSettled:()=>{e.invalidateQueries({queryKey:f$.approvals}),e.invalidateQueries({queryKey:Ol.networks}),e.invalidateQueries({queryKey:Ol.peers})}})}function Aet(e){const t=e?.message;return typeof t=="string"&&t.trim()?t.trim():x("ui.mesh.mesh_approvals.the_approvals_could_not_be_read")}function Fet(e){const t=e;return{code:Ft(t?.code)||"approval_refused",sentence:Ft(t?.message)||x("ui.mesh.mesh_approvals.decision_could_not_be_answered")}}const u4=e=>{const t=rJ(e.type),n=typeof e.percent=="number"?`, ${Math.round(e.percent)}%`:"";return`${t} in progress${n}.`},p$=e=>sJ({type:e.type,version:e.offer.version}),nJe=e=>`${e.map(s=>p$(s)).map((s,r)=>r===0?s:`${s.charAt(0).toLowerCase()}${s.slice(1)}`).join(" and ")} available. Show the update notice.`,sJe=({surfaces:e,inflight:t,onShow:n,onDismiss:s})=>{if(Et(),t===null&&e.length===0)return null;if(t!==null)return c.jsx(Je,{side:"top",collisionPadding:8,content:u4(t),children:c.jsx("output",{"data-update-foot-icon":"","data-update-foot-icon-state":"inflight","aria-label":u4(t),className:"flex size-8 shrink-0 items-center justify-center text-accent",children:c.jsx(Ui,{className:"size-4 shrink-0 motion-safe:animate-spin","aria-hidden":"true"})})});const r=e.find(i=>(i.offer.summary??"").trim()!=="");return c.jsx(Je,{side:"top",collisionPadding:8,content:c.jsxs("div",{className:"flex max-w-64 flex-col gap-0.5",children:[e.map(i=>c.jsxs("span",{className:"truncate text-ink",children:[p$(i)," ",x("ui.common.updates.update_foot_icon.available")]},i.type)),r?c.jsx("span",{className:"truncate text-ink-muted",children:(r.offer.summary??"").trim()}):null,c.jsx("span",{className:"whitespace-nowrap text-ink-muted",children:x("ui.common.updates.update_foot_icon.show_the_update_notice")})]}),children:c.jsx("button",{type:"button","data-update-foot-icon":"","data-update-foot-icon-state":"available","aria-label":nJe(e),onClick:n,onKeyDown:i=>{i.key!=="Escape"||!s||(i.stopPropagation(),s())},className:T("flex size-8 shrink-0 items-center justify-center rounded-sm text-accent","transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink"),children:c.jsx(iT,{className:"size-4 shrink-0","aria-hidden":"true"})})})},d4=()=>{const e=Ys(p=>p.followed),t=Ys(p=>p.running),n=Ys(p=>p.offers),s=Ys(p=>p.detailOpen),r=Ys(p=>p.inflight),i=Ys(p=>p.downloadPercent),a=Ys(p=>p.openNotice),o=Ys(p=>p.noticeOpen),l=Ys(p=>p.dismissNotice),u=g.useMemo(()=>{const p={followed:e,running:t,offers:n,detailOpen:s};return y4.filter(m=>nJ(p,m)).map(m=>{const v=n[m];return v?{type:m,offer:v}:null}).filter(m=>m!==null)},[e,t,n,s]),d=g.useMemo(()=>r[ln.BACKEND]?{type:ln.BACKEND,percent:null}:r[ln.UI]?{type:ln.UI,percent:i[ln.UI]}:null,[r,i]),h=g.useCallback(()=>a(),[a]),f=g.useCallback(()=>l(),[l]);return c.jsx(sJe,{surfaces:u,inflight:d,onShow:h,onDismiss:o?f:void 0})},h4=({expanded:e})=>(Et(),c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(M4,{className:"size-6",label:e?void 0:x("ui.shell.collapsible_app_logo.local_operator")}),e&&c.jsx("span",{className:"truncate font-semibold text-body text-ink",children:x("ui.shell.collapsible_app_logo.local_operator")})]})),Bk=$e.memo(({expanded:e,useAuth:t=!1})=>{Et();const n=Jr(),{user:s,isAuthenticated:r,accountRead:i,signOut:a}=OB(),o=i==="checking"?x("ui.shell.user_profile_sidebar.checking_account"):_F(i)?x("ui.shell.user_profile_sidebar.account_unavailable"):null,l=s?.name??o??x("ui.shell.user_profile_sidebar.user"),u=_F(i),d=s?.email??"",h=u?x("ui.shell.user_profile_sidebar.reconnect_radient"):d,f=u?"/settings?section=providers&provider=radient":"/settings",p=u?x("ui.shell.user_profile_sidebar.reconnect_radient"):x("ui.shell.user_profile_sidebar.account_settings"),m=g.useCallback(async()=>{r&&(await a(),window.location.reload())},[r,a]),v=g.useMemo(()=>{const C=s?.name;return C?C.split(" ").map(y=>y.charAt(0)).join("").toUpperCase().substring(0,2):null},[s?.name]),b=c.jsxs("button",{type:"button",onClick:t?void 0:()=>n(f),"aria-label":e?void 0:p,className:T("flex w-full min-w-0 items-center gap-2 rounded-sm transition-colors duration-fast ease-out-quart hover:bg-row-hover",e?"px-2 py-1.5":"justify-center py-1.5"),children:[c.jsx($B,{className:"size-7 shrink-0",children:c.jsx(zB,{className:"border border-control bg-elevated text-ink",children:v??c.jsx(Qre,{size:14,"aria-hidden":"true"})})}),e&&l&&c.jsxs("span",{className:"min-w-0 text-left",children:[c.jsx("span",{className:"block truncate text-body-sm text-ink",children:l}),h&&c.jsx("span",{className:T("block truncate text-meta",u?"text-accent":"text-ink-dim"),children:h})]})]}),w=e?b:c.jsx(Je,{content:p,side:"right",children:b});return t?c.jsxs(Il,{children:[e?c.jsx(Ho,{asChild:!0,children:b}):c.jsx(Je,{content:p,side:"right",children:c.jsx(Ho,{asChild:!0,children:b})}),c.jsxs(Nl,{align:"end",side:"top",className:"min-w-50",children:[u?c.jsxs(Gt,{onSelect:()=>n(f),children:[c.jsx(UB,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.reconnect_radient")]}):null,c.jsxs(Gt,{onSelect:()=>n("/settings"),children:[c.jsx(Pc,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.settings")]}),c.jsxs(Gt,{children:[c.jsx(xre,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.privacy_and_security")]}),c.jsx(Yr,{}),c.jsxs(Gt,{onSelect:m,className:"text-danger focus:bg-danger-wash focus:text-danger",children:[c.jsx(Use,{size:16,"aria-hidden":"true"}),x("ui.shell.user_profile_sidebar.sign_out")]})]})]}):w});Bk.displayName="UserProfileSidebar";const rJe=()=>{const e=oT(),t=Bn(),n=Ce(u=>u.setCataloguePageable),s=Ce(u=>u.setCatalogueActivityHead),r=Ce(u=>u.fetchSessions),i=yt(t.data,"session_catalogue_page"),a=yt(t.data,"session_catalogue_sort");g.useEffect(()=>{n(i)},[i,n]),g.useEffect(()=>{s(a)},[a,s]);const o=pa(t.data,"session_catalogue",2)==="enabled",l=g.useCallback(()=>r(i?cB:Ww,i),[r,i]);return g.useEffect(()=>{o&&l()},[o,l,e.catalogueRevision]),null},iJe="flex h-[30px] w-full items-center gap-2 rounded-md px-2 text-body-sm transition-colors duration-fast ease-out-quart",aJe=()=>{Et();const e=Jr(),t=Xae(),{expanded:n,mode:s,onCollapse:r}=iJ(),i=qe(le=>le.openCommandPalette),a=Bn(),o=Ce(le=>le.activeSessionId),l=HQe(),u=pa(a.data,"peers")==="enabled",d=ZT(u),h=pa(a.data,"approvals")==="enabled",f=tJe(d==="member"&&h,{poll:!0}),p=$Qe(f.data??[]),m=yt(a.data,"projects",1),v=yt(a.data,"aida",1),b=B0(v),w=v&&b.data?.enabled===!0,C=b.data?.name??"Aida",y=Cle(),k=OQe(b.data?.session_id),_=BQe(b.data?.session_id),E=()=>{y(e,b.data).catch(le=>zt(Fh(le)))},R=[...w?[{icon:Xne,label:C,path:"/chat",isActive:t==="chat"&&!!b.data?.session_id&&o===b.data?.session_id,tourTag:"nav-item-aida",onSelect:E,attention:k,attentionTag:"nav-aida-badge",attentionName:le=>x("ui.shell.sidebar_navigation.aida_missed",{name:C,count:le}),working:_,workingName:x("ui.shell.sidebar_navigation.aida_working",{name:C})}]:[],{icon:Uo,label:x("ui.shell.sidebar_navigation.agents"),path:"/agents",isActive:t==="agents",tourTag:"nav-item-agents"},...m?[{icon:bj,label:x("ui.shell.sidebar_navigation.projects"),path:"/projects",isActive:t==="projects",tourTag:"nav-item-projects"}]:[],{icon:mj,label:x("ui.shell.sidebar_navigation.schedules"),path:"/schedules",isActive:t==="schedules",tourTag:"nav-item-schedules"},{icon:qc,label:x("ui.shell.sidebar_navigation.browser"),path:"/browser",isActive:t==="browser",tourTag:"nav-item-browser",attention:l,attentionTag:"nav-browser-badge",attentionName:le=>x("ui.shell.sidebar_navigation.browser_waiting",{count:le,countText:String(le)})},{icon:kj,label:x("ui.shell.sidebar_navigation.agent_hub"),path:"/agent-hub",isActive:t==="agent-hub",tourTag:"nav-item-agent-hub"},...d==="member"?[{icon:TB,label:x("ui.shell.sidebar_navigation.mesh"),path:"/mesh",isActive:t==="mesh",tourTag:"nav-item-mesh",attention:p,attentionTag:"nav-mesh-badge",attentionName:le=>x("ui.shell.sidebar_navigation.mesh_waiting",{count:le,countText:String(le)})}]:[]],F=c.jsx(S$e,{selectedConversation:o??void 0,onSelectConversation:le=>void cp(e,le),onStageDraft:(le,q)=>{Ce.getState().stageDraft(le,q),e("/chat")}}),A=le=>{const q=le.attention??0,we=q>0&&le.attentionName?le.attentionName(q):le.label;return le.working&&le.workingName?le.workingName:we},N=le=>{const q=le.attention??0,we=A(le),B=le.isActive?yo:"text-ink-muted hover:bg-row-hover hover:text-ink",be=c.jsx(le.icon,{size:16,"aria-hidden":"true",className:T("shrink-0",le.isActive&&"text-accent")});return c.jsx("li",{className:T("flex h-[30px] w-full items-center rounded-md","transition-colors duration-fast ease-out-quart",B),children:c.jsxs("button",{type:"button",onClick:()=>le.onSelect?le.onSelect():e(le.path),"data-tour-tag":le.tourTag,"aria-current":le.isActive?"page":void 0,"aria-label":n&&we===le.label?void 0:we,className:T("flex h-full min-w-0 flex-1 items-center gap-2 rounded-md",n?"px-2":"justify-center px-0"),children:[n?be:c.jsxs("span",{className:"relative flex size-7 shrink-0 items-center justify-center",children:[be,q>0&&c.jsx("span",{className:"pointer-events-none absolute -top-0.5 -right-0.5 flex",children:c.jsx(Ml,{variant:"attentionQuiet",shape:"pill",size:"count",className:"h-3.5 min-w-3.5 px-0.75 leading-none","data-tour-tag":le.attentionTag,children:q})})]}),n&&c.jsx("span",{className:"truncate",children:le.label}),n&&q>0&&c.jsx("span",{className:"ml-auto inline-flex",children:c.jsx(Ml,{variant:"attentionQuiet",shape:"pill",size:"count","data-tour-tag":le.attentionTag,children:q})}),le.working&&c.jsx("span",{className:T(n&&"ml-auto","inline-flex"),children:c.jsx(Ui,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})})]})},le.tourTag)},M=le=>n?N(le):c.jsx("li",{children:c.jsx(Je,{content:A(le),side:"right",children:N(le)})},le.tourTag),D=s==="overlay"?x("ui.shell.sidebar_navigation.close_sidebar"):n?x("ui.shell.sidebar_navigation.collapse_sidebar"):x("ui.shell.sidebar_navigation.expand_sidebar"),L=s==="overlay"?Dn:n?bd:ga,V=navigator.platform.toUpperCase().indexOf("MAC")>=0,j=yt(a.data,"session_catalogue",2),te=Ce(le=>le.activeDraftKey),X=Ce(le=>le.drafts),re=!!te&&!(te?X[te]:void 0)?.target,G=()=>{Ce.getState().stageDraft(void 0,!0),e("/chat")},J=x("ui.shell.sidebar_navigation.new_chat_shortcut",{shortcut:y3(V).replace("+","")}),ae=x("ui.shell.sidebar_navigation.search_accessible",{everything:ko("everything",V),chats:ko("chats",V)}),O=x("ui.shell.sidebar_navigation.search_tooltip",{everything:ko("everything",V),chats:ko("chats",V)}),U=(le,q,we,B)=>{const be=le;return c.jsxs("button",{type:"button",...B.attrs,onClick:B.onClick,disabled:B.disabled,"aria-label":B.ariaLabel,"aria-current":B.current?"page":void 0,className:T(iJe,B.current?yo:"text-ink-muted hover:bg-row-hover hover:text-ink","disabled:text-ink-disabled disabled:hover:bg-transparent"),children:[c.jsx(be,{size:16,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"truncate",children:q}),c.jsx("span",{"aria-hidden":"true",className:"ml-auto",children:c.jsx(Er,{shortcut:we,joined:!0})})]})},P=U(KS,x("ui.shell.sidebar_navigation.new_chat"),y3(V),{onClick:G,ariaLabel:J,current:re,disabled:!j,attrs:{"data-tour-tag":"nav-item-chat","data-new-chat-row":""}}),z=U(xd,x("ui.shell.sidebar_navigation.search"),Aqe("everything",V),{onClick:i,ariaLabel:ae,attrs:{"data-command-palette-trigger":"",title:O}}),ne=(le,q,we)=>{const B=le;return c.jsx(Je,{content:q,side:"right",children:c.jsx("button",{type:"button",...we.attrs,onClick:we.onClick,disabled:we.disabled,"aria-label":q,className:T("flex size-8 items-center justify-center rounded-sm text-ink-muted","transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink","disabled:text-ink-disabled disabled:hover:bg-transparent"),children:c.jsx(B,{size:16,"aria-hidden":"true"})})})},fe=c.jsx("div",{className:T(s!=="overlay"&&T("pointer-events-none opacity-0 transition-opacity duration-fast ease-out-quart","group-hover/sidebar:pointer-events-auto group-hover/sidebar:opacity-100","group-focus-within/sidebar:pointer-events-auto group-focus-within/sidebar:opacity-100")),children:c.jsx(Je,{content:D,side:"right",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":D,"aria-expanded":s==="overlay"?void 0:n,"aria-keyshortcuts":KF(V),children:c.jsx(L,{"aria-hidden":"true"})})})}),ue=c.jsx(Je,{content:x("ui.shell.sidebar_navigation.settings"),side:"top",children:c.jsx("button",{type:"button","data-tour-tag":"nav-item-settings",onClick:()=>e("/settings"),"aria-current":t==="settings"?"page":void 0,"aria-label":x("ui.shell.sidebar_navigation.settings"),className:T("flex size-8 shrink-0 items-center justify-center rounded-sm text-ink-muted","transition-colors duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink",t==="settings"&&"text-ink"),children:c.jsx(Pc,{size:16,"aria-hidden":"true"})})});return n?c.jsxs("div",{"data-sidebar-shell":"","data-glass-region":"sidebar",className:"group/sidebar flex h-full min-h-0 flex-col overflow-hidden bg-surface",children:[c.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-1 pr-2 pl-4",children:[c.jsx(h4,{expanded:!0}),c.jsx("span",{className:"ml-auto",children:fe})]}),c.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-2 pb-2",children:[c.jsxs("div",{className:"flex flex-col gap-0.5",children:[P,z]}),c.jsx("ul",{className:"flex flex-col gap-0.5",children:R.map(M)})]}),c.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:F}),c.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-1 px-2 pb-2",children:[c.jsx(Bk,{expanded:!0}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(d4,{}),ue]})]})]}):c.jsxs("div",{"data-sidebar-strip":"","data-glass-region":"sidebar",className:"group/sidebar flex h-full min-h-0 flex-col items-center bg-surface",children:[c.jsx(rJe,{}),c.jsx("div",{className:"flex h-10 shrink-0 items-center justify-center",children:c.jsx(h4,{expanded:!1})}),c.jsxs("ul",{className:"flex flex-col items-center gap-1",children:[c.jsx("li",{children:ne(ga,D,{onClick:r,attrs:{"aria-expanded":!1,"aria-keyshortcuts":KF(V)}})}),c.jsx("li",{children:ne(KS,J,{onClick:G,disabled:!j,attrs:{"data-tour-tag":"nav-item-chat"}})}),c.jsx("li",{children:ne(xd,ae,{onClick:i,attrs:{"data-command-palette-trigger":""}})})]}),c.jsx("ul",{className:"mt-4 flex flex-col items-center gap-1",children:R.map(M)}),c.jsxs("div",{className:"mt-auto flex flex-col items-center gap-1 pb-2",children:[c.jsx(d4,{}),ue,c.jsx(Bk,{expanded:!1})]})]})},oJe=1,lJe=()=>{const{isAuthenticated:e,user:t}=OB(),{hasBeenNotified:n,setHasBeenNotified:s}=h$(),[r,i]=g.useState(!1),[a,o]=g.useState(null),l=g.useCallback(async()=>{if(!(!e||!t?.radientUser?.account?.tenant_id))try{const f=await aJ({operation:"credits",tenantId:t.radientUser.account.tenant_id});if(!f||typeof f.balance!="number")throw new Error("Invalid credit balance response format");o(f.balance)}catch(f){console.error("Failed to fetch Radient credits:",f),o(null)}},[e,t?.radientUser?.account?.tenant_id]);return g.useEffect(()=>{e&&l()},[e,l]),g.useEffect(()=>{e&&a!==null?a<oJe?n||i(!0):(i(!1),n&&s(!1)):i(!1)},[e,n,a,s]),{isLowCreditsDialogOpen:r,openRadientConsole:()=>{window.api?.openExternal?window.api.openExternal("https://console.radienthq.com"):window.open("https://console.radienthq.com","_blank"),s(!0),i(!1)},closeLowCreditsDialog:()=>{i(!1)},onLowCreditsDialogClose:()=>{s(!0),i(!1)},currentCredits:a}};function cJe(){const e=Jr();g.useEffect(()=>{const t=r=>{e(r==="back"?-1:1)},n=r=>{const i=ofe(r);i&&(r.preventDefault(),t(i))},s=r=>{const i=lfe(r);i&&(r.preventDefault(),t(i))};return window.addEventListener("keydown",n),window.addEventListener("mouseup",s),()=>{window.removeEventListener("keydown",n),window.removeEventListener("mouseup",s)}},[e])}function uJe(){const e=navigator.windowControlsOverlay;if(!e?.getTitlebarAreaRect)return null;try{const t=e.getTitlebarAreaRect();return t.width<=0&&t.height<=0?null:{x:t.x,y:t.y,width:t.width,height:t.height}}catch{return null}}function dJe(e,t,n){const s=document.documentElement;if(t==="mac"){s.dataset.chromeLeading="true",s.dataset.chromeTrailing="false";return}if(e===null){s.dataset.chromeLeading="false",s.dataset.chromeTrailing="false";return}s.dataset.chromeLeading=e.x<=1?"true":"false",s.dataset.chromeTrailing=Math.abs(e.x+e.width-n)<=1?"true":"false"}function hJe(e){const t=window.api?.windowChrome;if(!t)return;const n=getComputedStyle(document.documentElement),s=n.getPropertyValue("--lo-canvas").trim(),r=n.getPropertyValue("--lo-ink-muted").trim(),i=n.getPropertyValue("--lo-ink-dim").trim();!s||!r||!i||t.report({themeId:e,colors:{ground:s,symbol:r,symbolInactive:i}})}function fJe(){g.useLayoutEffect(()=>{if(!window.api?.windowChrome)return;const t=document.documentElement.dataset.chromePlatform??"linux",n=()=>dJe(uJe(),t,window.innerWidth);n();const s=navigator.windowControlsOverlay;return s?.addEventListener?.("geometrychange",n),window.addEventListener("resize",n),()=>{s?.removeEventListener?.("geometrychange",n),window.removeEventListener("resize",n)}},[]),g.useEffect(()=>{const e=window.api?.windowChrome;if(e)return e.onState(t=>{document.documentElement.dataset.chromeFullscreen=t.fullScreen?"true":"false"})},[])}const pJe=g.lazy(()=>Vl(()=>import("./agent-details-page-B_mPfefi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(e=>({default:e.AgentDetailsPage}))),gJe=g.lazy(()=>Vl(()=>import("./agent-hub-page-BYHsrmlA.js"),__vite__mapDeps([14,1,2,4,5,6,7,15,3,8,9,10,11,16,17,18,19,12,13]),import.meta.url).then(e=>({default:e.AgentHubPage}))),f4=g.lazy(()=>Vl(()=>import("./agents-page-DOt4Ktjv.js"),__vite__mapDeps([20,4,5,1,2,6,7,8,16,12,13]),import.meta.url).then(e=>({default:e.AgentsPage}))),mJe=g.lazy(()=>Vl(()=>import("./schedules-page-5j5ANXIf.js"),__vite__mapDeps([21,1,2,4,5,6,7,15,18,10,22,12,13]),import.meta.url).then(e=>({default:e.SchedulesPage}))),p4=g.lazy(()=>Vl(()=>import("./projects-page-ygyrTO2Y.js"),__vite__mapDeps([23,1,2,4,5,6,7,15,24,12,13]),import.meta.url).then(e=>({default:e.ProjectsPage}))),vJe=g.lazy(()=>Vl(()=>import("./browser-page-BpsxcPyu.js"),__vite__mapDeps([25,1,2,4,5,6,7,12,13]),import.meta.url).then(e=>({default:e.BrowserPage}))),bJe=g.lazy(()=>Vl(()=>import("./mesh-page-GPZRPR4j.js"),__vite__mapDeps([26,1,2,4,5,6,7,15,12,13]),import.meta.url).then(e=>({default:e.MeshPage}))),xJe=g.lazy(()=>Vl(()=>import("./settings-page-rEYr23iA.js"),__vite__mapDeps([27,1,2,4,5,6,7,15,17,28,11,22,10,18,12,13]),import.meta.url).then(e=>({default:e.SettingsPage}))),wJe=g.lazy(()=>Vl(()=>import("./browser-webauthn-prompt-DbKuqaik.js"),__vite__mapDeps([29,1,2,5,6,4,7,12,13]),import.meta.url).then(e=>({default:e.BrowserWebauthnPrompt}))),CJe=()=>{Et(),fJe(),AQe();const{pathname:e}=aT(),t=e.startsWith("/chat")||e.startsWith("/browser"),{isOnboardingActive:n}=Kae(),{isLowCreditsDialogOpen:s,openRadientConsole:r,onLowCreditsDialogClose:i}=lJe(),{isCommandPaletteOpen:a,isCreateAgentDialogOpen:o,isSidebarCollapsed:l,closeCreateAgentDialog:u}=qe();wl(a,"command-palette"),wl(o,"create-agent-dialog"),wl(n,"onboarding"),wl(s,"low-credits");const d=Jr(),h=Bn(),f=yt(h.data,"session_catalogue",2),p=yt(h.data,"session_archive");g.useEffect(()=>{Ce.getState().requestArchiveConfirm(null)},[e]);const m=pa(h.data,"peers"),v=E=>{Ce.getState().stageDraft({kind:"agent",name:E.name}),d("/chat"),u()};Jqe(),PQe(),Oqe(),cJe(),zfe();const b=Ce(E=>E.setActiveSession),w=Ce(E=>{const R=E.activeDraftKey?E.drafts[E.activeDraftKey]:void 0;return ip(E.activeDraftKey,R?.sessionId,E.activeSessionId)}),C=Noe({displayedSessionId:w,archiveEnabled:p}),y=qe(E=>E.setConsolePaneOpen),k=qe(E=>E.setBrowserPaneOpen),_=qe(E=>E.setConsoleActiveSurface);return g.useEffect(()=>{const E=window.api?.desktop?.onOpenConversation?.((R,F)=>{R!==null&&performance.mark("lop:open:requested"),b(R),F!==void 0&&R!==null&&(_(F),y(!0)),d("/chat")});return()=>E?.()},[d,b,y,_]),g.useEffect(()=>{const E=window.api?.console?.onReveal?.(R=>{R.mode!=="none"&&(R.mode==="session"&&R.session_id!==w||(R.mode==="open"&&b(R.session_id),_(R.surface),y(!0)))});return()=>E?.()},[w,b,y,_]),fle(),yqe(),g.useEffect(()=>{const E=window.api?.browser?.onConsentAttention?.(R=>{const F=Boe(R.requesterSessionId,Ce.getState().sessions);if(Moe(R.entryId),F.kind==="browser"){d("/browser");return}b(F.sessionId),k(!0),d("/chat")});return()=>E?.()},[d,b,k]),g.useEffect(()=>{const E=R=>{n||f&&Sqe(R)&&(R.preventDefault(),Ce.getState().stageDraft(void 0,!0),d("/chat"))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[f,n,d]),c.jsx(SQe,{children:c.jsx("div",{className:"relative flex h-screen flex-col overflow-hidden","data-titlebar-sidebar-collapsed":l?"true":"false",children:c.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[a&&c.jsx(Kqe,{}),c.jsx(Eqe,{}),c.jsx(oJ,{}),c.jsx(Zqe,{enabled:m==="enabled"}),c.jsx(qKe,{open:n}),c.jsx(EQe,{}),c.jsx(RQe,{}),p&&c.jsx(vle,{}),c.jsx(xoe,{}),c.jsx(g.Suspense,{fallback:null,children:c.jsx(wJe,{})}),c.jsx(Roe,{blocked:n||s||a||o||C,sessionId:e.startsWith("/chat")?w??null:null}),c.jsx(NQe,{open:s,onClose:i,onGoToConsole:r}),c.jsx(Zae,{open:o,onClose:u,onAgentCreated:v}),c.jsx(lJ,{sidebar:c.jsx(aJe,{}),content:c.jsxs("main",{"data-glass-region":"canvas-backing",className:"flex grow flex-col overflow-hidden",children:[t?null:c.jsx("div",{"data-chrome-route-band":""}),c.jsx(g.Suspense,{fallback:c.jsx("div",{className:"flex grow items-center justify-center",children:c.jsx(pn,{size:"lg",label:x("ui.common.loading.page")})}),children:c.jsxs(cJ,{children:[c.jsx(ri,{path:"/",element:c.jsx(SF,{to:"/chat",replace:!0})}),c.jsx(ri,{path:"/chat",element:c.jsx(w3,{})}),c.jsx(ri,{path:"/chat/:agentId",element:c.jsx(w3,{})}),c.jsx(ri,{path:"/agents",element:c.jsx(f4,{})}),c.jsx(ri,{path:"/agents/:agentId",element:c.jsx(f4,{})}),c.jsx(ri,{path:"/settings",element:c.jsx(xJe,{})}),c.jsx(ri,{path:"/agent-hub",element:c.jsx(gJe,{})}),c.jsx(ri,{path:"/agent-hub/:agentId",element:c.jsx(pJe,{})}),c.jsx(ri,{path:"/schedules",element:c.jsx(mJe,{})}),c.jsx(ri,{path:"/projects",element:c.jsx(p4,{})}),c.jsx(ri,{path:"/projects/:projectId",element:c.jsx(p4,{})}),c.jsx(ri,{path:"/browser",element:c.jsx(vJe,{})}),m==="enabled"&&c.jsx(ri,{path:"/mesh",element:c.jsx(bJe,{})}),c.jsx(ri,{path:"*",element:c.jsx(SF,{to:"/chat",replace:!0})})]})})]})})]})})})};function qu(){return new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))})}const yJe=3,_Je=3e3;function SJe(e){return e instanceof CSSTransition&&e.playState==="running"}function EJe(e){const t=e.effect,n=t instanceof KeyframeEffect?t.target:null,s=e.transitionProperty,i=/^[a-z-]+$/.test(s)&&n instanceof Element?getComputedStyle(n).getPropertyValue(s).trim()||"(empty)":"(unreadable)";return`${s||"(unnamed property)"} on ${E0(n)??"an element no longer in the document"} = ${i}`}async function kJe(e=_Je){const t=performance.now();let n=0;for(;;){await qu();const s=Math.round(performance.now()-t),r=document.getAnimations().filter(SJe);if(n=r.length===0?n+1:0,n>=yJe)return{waitedMs:s,timedOut:!1,pending:[]};if(s>e)return{waitedMs:s,timedOut:!0,pending:r.map(EJe)}}}const TJe=/^#/;function wm(){const e=window.location.hash.replace(TJe,"");return e===""?"/":e}function E0(e){if(!e)return null;const t=e.getAttribute("aria-label")??e.textContent??"";return`${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""} "${t.trim().slice(0,60)}"`}function RJe(e){const t=e.getBoundingClientRect(),n=t.left+t.width/2,s=t.top+t.height/2,r=document.elementFromPoint(n,s),i=r!==null&&(r===e||e.contains(r)),a=document.elementsFromPoint(n,s).slice(0,4).map(l=>E0(l)),o={bubbles:!0,cancelable:!0,composed:!0,button:0,buttons:1,clientX:n,clientY:s,view:window};return e.dispatchEvent(new PointerEvent("pointerdown",{...o,pointerId:1,isPrimary:!0})),e.dispatchEvent(new MouseEvent("mousedown",o)),e.dispatchEvent(new PointerEvent("pointerup",{...o,buttons:0,pointerId:1,isPrimary:!0})),e.dispatchEvent(new MouseEvent("mouseup",{...o,buttons:0})),e.dispatchEvent(new MouseEvent("click",{...o,buttons:0})),{hitTest:i,hit:E0(r),stack:a,disabled:e instanceof HTMLButtonElement?e.disabled:null,rect:{x:t.x,y:t.y,width:t.width,height:t.height}}}function gg(e,t){if(typeof e!="string"||e==="")throw new Error(`${t} must be a non-empty string`);return e}async function AJe(e,t=1e4){const n=Date.now();for(;wm()!==e;){if(Date.now()-n>t)throw new Error(`route did not become ${e} (it is ${wm()})`);await new Promise(s=>setTimeout(s,50))}return await qu(),wm()}const jk=["dev-driver","query-fetch-probe"];let Cm=null;function FJe(){if(Cm)return Cm;const e=[],t=EF.prototype.fetch;return EF.prototype.fetch=function(...s){return e.push({at:Date.now(),key:JSON.stringify(this.queryKey),stack:(new Error().stack??"").split(`
|
|
685
685
|
`).slice(2).join(" | ")}),t.apply(this,s)},Cm=e,e}function DJe(e){const t=Cm??[],n=JSON.stringify(jk),s=t.filter(i=>i.key!==n&&(e===void 0||i.key.includes(e))),r=new Map;for(const i of s){const a=r.get(i.stack)??{key:i.key,count:0,firstAt:i.at,lastAt:i.at};a.count+=1,a.lastAt=i.at,r.set(i.stack,a)}return{armed:Cm!==null,total:s.length,probeRecords:t.filter(i=>i.key===n).length,callers:[...r.entries()].map(([i,a])=>({stack:i,...a})).sort((i,a)=>i.firstAt-a.firstAt)}}function PJe(){const e=window.__loDevDriver;return e?.armed?e.install({hello:()=>({armed:!0,outDir:e.outDir,title:document.title,route:wm(),href:window.location.href,theme:qe.getState().themeName,viewport:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio},visibilityState:document.visibilityState,hasFocus:document.hasFocus(),apiBaseUrl:Ss.baseUrl,userAgent:navigator.userAgent}),filesFacts:()=>uJ(),state:()=>{const t=qe.getState(),n=Ce.getState();return{route:wm(),theme:t.themeName,commandPaletteOpen:t.isCommandPaletteOpen,canvasOpen:t.isCanvasOpen,runPanelOpen:t.isRunPanelOpen,browserPaneOpen:t.isBrowserPaneOpen,rightSlotWidth:t.rightSlotWidth,rightSlotKey:t.rightSlotKey??null,rightSlotMemory:t.rightSlotMemory.map(([s,r])=>[s,r]),activeSessionId:n.activeSessionId,activeDraftKey:n.activeDraftKey,drafts:Object.fromEntries(Object.entries(n.drafts).map(([s,r])=>[s,{sessionId:r.sessionId??null,error:r.error!==void 0,undelivered:r.undelivered!==void 0,submitted:r.submittedText!==void 0,admissionAttempted:r.admissionAttempted===!0}])),sessionCount:n.sessions.length,cataloguePinnedCount:n.sessions.filter(s=>s.pinned===!0).length,cataloguePageable:n.cataloguePageable,catalogueActivityHead:n.catalogueActivityHead,scopes:Object.fromEntries(Object.entries(n.scopes).map(([s,r])=>[s,{ids:r.ids.length,nextCursor:r.nextCursor,loading:r.loading,error:r.error}])),countsTotal:n.counts?.total??null,archiveAttempts:n.answerSeq,archiveFailure:n.archiveFailure?{sessionId:n.archiveFailure.sessionId,archived:n.archiveFailure.archived}:null,onboardingVisible:!!document.querySelector("[data-onboarding-modal]")}},queries:()=>ox.getQueryCache().getAll().map(t=>({key:JSON.stringify(t.queryKey),status:t.state.status,fetchStatus:t.state.fetchStatus,isLoading:t.state.status==="pending"&&t.state.fetchStatus==="fetching",error:t.state.error instanceof Error?t.state.error.message:null,hasData:t.state.data!==void 0,updatedAt:t.state.dataUpdatedAt,failureCount:t.state.fetchFailureCount,observers:t.getObserversCount()})),queryFetches:async t=>{const n=t??{};if(!n.arm)return DJe(n.key);const s=FJe(),r=JSON.stringify(jk),i=s.length;return await ox.fetchQuery({queryKey:jk,queryFn:()=>null,retry:!1,staleTime:0}),{armed:!0,validated:s.slice(i).some(a=>a.key===r)}},navigate:async t=>{const n=gg(t,"navigate path");if(!n.startsWith("/"))throw new Error(`navigate path must start with "/" (got "${n}")`);return window.location.hash=`#${n}`,{route:await AJe(n)}},setTheme:async t=>{const n=gg(t,"theme name");qe.getState().setTheme(n),await qu();const s=document.documentElement.getAttribute("data-theme"),r=await kJe();return{theme:qe.getState().themeName,dataTheme:s,settledAfterMs:r.waitedMs,settleTimedOut:r.timedOut,settlePending:r.pending}},setSidebarWidth:async t=>{const n=Number(t?.width);if(!Number.isFinite(n))throw new Error("sidebar width must be a number");const s=jZ(n);return qe.getState().setChatSidebarWidth(s),await qu(),{width:qe.getState().chatSidebarWidth,clamped:s!==n}},measure:async t=>{const n=typeof t=="string"?{selector:t}:t,s=gg(n?.selector,"measure selector"),r=typeof n?.timeoutMs=="number"?n.timeoutMs:1e4,i=Date.now();let a=null;for(;a===null&&(a=document.querySelector(s),a===null);){if(Date.now()-i>r)throw new Error(`nothing matches ${s} after ${r}ms of waiting`);await new Promise(d=>setTimeout(d,100))}const o=a.getBoundingClientRect(),l={x:Math.round(o.left+o.width/2),y:Math.round(o.top+o.height/2)},u=document.elementFromPoint(l.x,l.y);return{selector:s,target:E0(a),centre:l,rect:{x:Math.round(o.x),y:Math.round(o.y),width:Math.round(o.width),height:Math.round(o.height)},hitTest:u!==null&&(u===a||a.contains(u)),focused:a===document.activeElement,inViewport:o.top>=0&&o.left>=0&&o.bottom<=window.innerHeight&&o.right<=window.innerWidth}},press:async t=>{const n=typeof t=="string"?{selector:t}:t,s=gg(n?.selector,"press selector"),r=typeof n?.timeoutMs=="number"?n.timeoutMs:1e4,i=Date.now();let a=null;for(;a===null&&(a=document.querySelector(s),a===null);){if(Date.now()-i>r)throw new Error(`nothing matches ${s} after ${r}ms of waiting`);await new Promise(l=>setTimeout(l,100))}const o=RJe(a);return await qu(),{selector:s,target:E0(a),...o}},openCanvasDocument:async t=>{const n=t,s=gg(n?.path,"canvas document path"),r=typeof n?.title=="string"?n.title:void 0,[i]=await window.api.probeFiles([s]);if(!i||!i.exists||!i.isFile)throw new Error(`no file at ${i?.resolved??s}`);const a=i.resolved??s,o=Ac(a,{title:r,type:Ef(a),availability:"present",sizeBytes:i.sizeBytes??void 0,lastAgentModified:i.mtimeMs??void 0,readMtimeMs:i.mtimeMs??void 0}),l=Zw[rp(a,o.type)??"code"];if(l==="utf-8"||l==="base64"){const h=await window.api.readFile(o.path,l);if(!h.success)throw new Error(`could not read ${o.path}`);o.content=h.data}const u=Ce.getState(),d=uT(u.activeDraftKey,u.activeSessionId)??u.stageDraft();return qe.getState().setCanvasOpen(!0),ls.getState().addFileAndSelect(d,o),n?.mention===!0&&ls.getState().addMentionedFile(d,o),await qu(),{conversationId:d,documentId:o.id,readMtimeMs:o.readMtimeMs??null,contentLength:o.content.length,encoding:l}},stageLiveConsents:async t=>{const s=t?.count;if(typeof s!="number"||!Number.isInteger(s)||s<0)throw new Error(`stageLiveConsents count must be a non-negative integer (got ${JSON.stringify(s)})`);const r=Date.now();return Joe({tabs:[],activeTabId:null,url:"",title:"",loading:!1,canGoBack:!1,canGoForward:!1,pendingConsent:Array.from({length:s},(i,a)=>({entryId:`dev-driver-probe-${a+1}`,origin:`https://dev-driver-probe-${a+1}.example.com`,authority:`dev-driver-probe-${a+1}.example.com`,broad:null,expiresAt:r+10*6e4,requesterSessionId:null})),approvals:[],navFailure:null}),await qu(),{count:s}}}):[]}function IJe(){const e=g.useMemo($k,[]),t=g.useRef(null);return g.useEffect(()=>{const n=window.api?.miniView;if(!n?.onRegistration)return;let s=!1;const r=a=>{if(s)return;const o=t.current;if(t.current=a.status,o===null||a.status===o||a.status==="registered")return;const l=HZ(a.value,e);zt(dJ(a.status,l))};n.getRegistration?.()?.then(r)?.catch(()=>{});const i=n.onRegistration(r);return()=>{s=!0,i?.()}},[e]),null}const NJe=`
|
|
686
686
|
/*
|
|
687
687
|
* A transition declared on ::-webkit-scrollbar-thumb does not animate in
|