local-operator-ui 0.47.0 → 0.47.2

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.
Files changed (95) hide show
  1. package/out/main/index.js +804 -101
  2. package/out/renderer/assets/{_basePickBy-cBt3C7Mm.js → _basePickBy-EqA-lyNr.js} +1 -1
  3. package/out/renderer/assets/{_baseUniq-BPAvTjjw.js → _baseUniq-BLgoOCrk.js} +1 -1
  4. package/out/renderer/assets/{agent-details-page-B9WQ68z3.js → agent-details-page-2H3QKmn4.js} +1 -1
  5. package/out/renderer/assets/{agent-hub-page-C-UV58tJ.js → agent-hub-page-C9NPxFvM.js} +1 -1
  6. package/out/renderer/assets/{agents-page-CSQOyTDS.js → agents-page-BQ52N82v.js} +3 -3
  7. package/out/renderer/assets/{arc-RoFzSfxq.js → arc-9AYlAgb-.js} +1 -1
  8. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-KlQWIO4I.js → architectureDiagram-IEHRJDOE-DQdvlWFp.js} +1 -1
  9. package/out/renderer/assets/{blockDiagram-JOT3LUYC-CUIG5pQc.js → blockDiagram-JOT3LUYC-BW3miOqQ.js} +1 -1
  10. package/out/renderer/assets/{book-open-CJGaJB5s.js → book-open-BN9Q0QD0.js} +1 -1
  11. package/out/renderer/assets/browser-page-Bw_APhwi.js +1 -0
  12. package/out/renderer/assets/{browser-webauthn-prompt-CH3nbvN4.js → browser-webauthn-prompt-CJWzdqpH.js} +1 -1
  13. package/out/renderer/assets/{building-2-CbHZ2q0R.js → building-2-DYJ6F3fw.js} +1 -1
  14. package/out/renderer/assets/{c4Diagram-VJAJSXHY-BtzkHJj8.js → c4Diagram-VJAJSXHY-DhEmnoe8.js} +1 -1
  15. package/out/renderer/assets/channel-CSFvOzgB.js +1 -0
  16. package/out/renderer/assets/{chunk-4BMEZGHF-rvmjs7-X.js → chunk-4BMEZGHF-mcXDS2wE.js} +1 -1
  17. package/out/renderer/assets/{chunk-A2AXSNBT-CDQJ7DrH.js → chunk-A2AXSNBT-Dq3Y8VUK.js} +1 -1
  18. package/out/renderer/assets/{chunk-AEK57VVT-BblqzOjK.js → chunk-AEK57VVT-DpibnjST.js} +1 -1
  19. package/out/renderer/assets/{chunk-D6G4REZN-CwhcoQLc.js → chunk-D6G4REZN-B_Juz_Ld.js} +1 -1
  20. package/out/renderer/assets/{chunk-RZ5BOZE2-CeARX8pW.js → chunk-RZ5BOZE2-Cqs_zckD.js} +1 -1
  21. package/out/renderer/assets/{chunk-XZIHB7SX-C2Z6kJVH.js → chunk-XZIHB7SX-DuUMP_AP.js} +1 -1
  22. package/out/renderer/assets/classDiagram-GIVACNV2-DeVLljAJ.js +1 -0
  23. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DeVLljAJ.js +1 -0
  24. package/out/renderer/assets/clone-gMaoIpSm.js +1 -0
  25. package/out/renderer/assets/{console-mirror-Df9e_9IL.js → console-mirror-QYMQ2oMk.js} +1 -1
  26. package/out/renderer/assets/{consoleCapture-CEWo4h66.js → consoleCapture-BmEfl0qP.js} +1 -1
  27. package/out/renderer/assets/{conversation-input-sync-BsdkPoIA.js → conversation-input-sync-BXe0XySA.js} +4 -4
  28. package/out/renderer/assets/{dagre-OKDRZEBW-jshmXRqe.js → dagre-OKDRZEBW-Dh9tNLaI.js} +1 -1
  29. package/out/renderer/assets/{diagram-SSKATNLV-B6z3h0LO.js → diagram-SSKATNLV-By1kP-Qy.js} +1 -1
  30. package/out/renderer/assets/{diagram-VNBRO52H-C1EoDciD.js → diagram-VNBRO52H-DZ2-6zmm.js} +1 -1
  31. package/out/renderer/assets/{erDiagram-Q7BY3M3F-cbQwdE8b.js → erDiagram-Q7BY3M3F-hEItxZIQ.js} +1 -1
  32. package/out/renderer/assets/{error-boundary-ByCPkFsK.js → error-boundary-BMkaJRQG.js} +1 -1
  33. package/out/renderer/assets/{flowDiagram-4HSFHLVR-bLcnhccs.js → flowDiagram-4HSFHLVR-CSo4rOLb.js} +1 -1
  34. package/out/renderer/assets/{ganttDiagram-APWFNJXF-CQ1hiJNI.js → ganttDiagram-APWFNJXF-CJ658-n4.js} +1 -1
  35. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-Djrozblc.js → gitGraphDiagram-7IBYFJ6S-CXbIBabL.js} +1 -1
  36. package/out/renderer/assets/{graph-BDU7ZxXp.js → graph-C6bGJrBt.js} +1 -1
  37. package/out/renderer/assets/{hash-CY36bXoG.js → hash-DiimSDl0.js} +1 -1
  38. package/out/renderer/assets/{heart-DTUFqrqu.js → heart-CqKaBtlh.js} +1 -1
  39. package/out/renderer/assets/{image-plus-DmG9Cnvq.js → image-plus-lDPgOpNP.js} +1 -1
  40. package/out/renderer/assets/{index-Dz49kEuI.js → index-Cl6-DwcF.js} +1 -1
  41. package/out/renderer/assets/index-DNOzYQss.css +1 -0
  42. package/out/renderer/assets/{index-BABrThFM.js → index-DonfgCam.js} +4 -4
  43. package/out/renderer/assets/{index-BwVoBwoc.js → index-Dw40dBjw.js} +1 -1
  44. package/out/renderer/assets/infoDiagram-PH2N3AL5-VbDpNl_C.js +2 -0
  45. package/out/renderer/assets/{installer-DBgMBOUt.js → installer-C5WMkCnz.js} +1 -1
  46. package/out/renderer/assets/{journeyDiagram-U35MCT3I-B9EaYOUJ.js → journeyDiagram-U35MCT3I-Dxo2XRpD.js} +1 -1
  47. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-D_w2NByn.js → kanban-definition-NDS4AKOZ-_iR1Keaq.js} +1 -1
  48. package/out/renderer/assets/{layout-CWAYrBQg.js → layout-DkSGJUjL.js} +1 -1
  49. package/out/renderer/assets/{legacy-agents-page-B9wR_UC9.js → legacy-agents-page-BsTxWWCJ.js} +1 -1
  50. package/out/renderer/assets/{library-page-D-CE1ZCg.js → library-page-DYuFgJMi.js} +3 -3
  51. package/out/renderer/assets/{mermaid.core-CynzcDYk.js → mermaid.core-BLqJs5Mm.js} +5 -5
  52. package/out/renderer/assets/{mesh-page-CR_KErFC.js → mesh-page-CGfJy25z.js} +1 -1
  53. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-BA2W15tE.js → mindmap-definition-ALO5MXBD-DE3jYvdg.js} +1 -1
  54. package/out/renderer/assets/{mini-BpsHkXJs.js → mini-8paKkmHy.js} +1 -1
  55. package/out/renderer/assets/{notebook-pen-jwZCAOYl.js → notebook-pen-BO1weM_5.js} +1 -1
  56. package/out/renderer/assets/{notifications-page-SK5NqB-7.js → notifications-page-CR9hkgko.js} +1 -1
  57. package/out/renderer/assets/{org-access-Bg27Z8x2.js → org-access-RJercT9z.js} +1 -1
  58. package/out/renderer/assets/{org-surface-gate-CQxklQ-G.js → org-surface-gate-D0vYcdDx.js} +1 -1
  59. package/out/renderer/assets/{page-header-BHM4h2fS.js → page-header-DKHWJJoS.js} +1 -1
  60. package/out/renderer/assets/{path-utils-Bf8RCJbS.js → path-utils-CgkpwzSI.js} +1 -1
  61. package/out/renderer/assets/{pieDiagram-IB7DONF6-DW77nNiO.js → pieDiagram-IB7DONF6-Bw2WGAQd.js} +1 -1
  62. package/out/renderer/assets/{project-markdown-BTsnM7OU.js → project-markdown-DP8F_D7W.js} +1 -1
  63. package/out/renderer/assets/{projects-page-Br5DSkr6.js → projects-page-CAziBDff.js} +1 -1
  64. package/out/renderer/assets/{publication-validation-BPaO06Dy.js → publication-validation-BTZxXgFZ.js} +1 -1
  65. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-CDj60YNy.js → quadrantDiagram-7GDLP6J5-NExo9jd9.js} +1 -1
  66. package/out/renderer/assets/{radar-MK3ICKWK-CyccF--S.js → radar-MK3ICKWK-CVdP1QHU.js} +1 -1
  67. package/out/renderer/assets/{radient-auth-buttons-BCtJNYf5.js → radient-auth-buttons-x4nqFWHZ.js} +1 -1
  68. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-sFj0_2m1.js → requirementDiagram-KVF5MWMF-D3iNwTbN.js} +1 -1
  69. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-DsEIhN9c.js → sankeyDiagram-QLVOVGJD-nrZJ05oE.js} +1 -1
  70. package/out/renderer/assets/{schedules-page-DAwa60MB.js → schedules-page-D1DyGowS.js} +1 -1
  71. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-CZ0uz7Vj.js → sequenceDiagram-X6HHIX6F-D-zvwDzx.js} +1 -1
  72. package/out/renderer/assets/{settings-page-Db00UHjC.js → settings-page-AJ0WetEN.js} +1 -1
  73. package/out/renderer/assets/{smartart-D5JzCfoV.js → smartart-DIvtzeyi.js} +1 -1
  74. package/out/renderer/assets/{stateDiagram-DGXRK772-BJy4s7Hy.js → stateDiagram-DGXRK772-Dxg8pb6V.js} +1 -1
  75. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BCsjs512.js +1 -0
  76. package/out/renderer/assets/{team-bridge-page-HYbbsoUb.js → team-bridge-page-D7gX4utS.js} +1 -1
  77. package/out/renderer/assets/{timeline-definition-BDJGKUSR-rp4x17fE.js → timeline-definition-BDJGKUSR-RuykyZ_l.js} +1 -1
  78. package/out/renderer/assets/{use-default-on-banner-bwSRinka.js → use-default-on-banner-Bd7U99zb.js} +1 -1
  79. package/out/renderer/assets/{use-download-agent-mutation-Dgwa2p9-.js → use-download-agent-mutation-C6dhzXX0.js} +1 -1
  80. package/out/renderer/assets/{use-session-snapshot-QkR7pjNd.js → use-session-snapshot-CLpUx0Y3.js} +1 -1
  81. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-CDpmuteS.js → xychartDiagram-VJFVF3MP-5ObNWT45.js} +1 -1
  82. package/out/renderer/console-capture.html +5 -5
  83. package/out/renderer/index.html +7 -7
  84. package/out/renderer/installer.html +4 -4
  85. package/out/renderer/mini.html +7 -7
  86. package/package.json +2 -2
  87. package/out/renderer/assets/browser-page-Db4cYtxn.js +0 -1
  88. package/out/renderer/assets/channel-QUwfyg33.js +0 -1
  89. package/out/renderer/assets/classDiagram-GIVACNV2-BGCwsHyk.js +0 -1
  90. package/out/renderer/assets/classDiagram-v2-COTLJTTW-BGCwsHyk.js +0 -1
  91. package/out/renderer/assets/clone-B3p2Fvp_.js +0 -1
  92. package/out/renderer/assets/index-C8UzEgJt.css +0 -1
  93. package/out/renderer/assets/infoDiagram-PH2N3AL5-C5S1bkLb.js +0 -2
  94. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-DyjFY3o5.js +0 -1
  95. /package/out/renderer/assets/{index-D312rJYs.js → index--tr15tXr.js} +0 -0
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./agent-details-page-B9WQ68z3.js","./index-D312rJYs.js","./messages-CYpcciYD.js","./index-C8UzEgJt.css","./publication-validation-BPaO06Dy.js","./path-utils-Bf8RCJbS.js","./conversation-input-sync-BsdkPoIA.js","./error-boundary-ByCPkFsK.js","./conversation-input-sync-Dp97JwKx.css","./use-download-agent-mutation-Dgwa2p9-.js","./book-open-CJGaJB5s.js","./en-US-CW_dDnkH.js","./heart-DTUFqrqu.js","./console-mirror-Df9e_9IL.js","./console-mirror-DOrYoP_4.css","./agent-hub-page-C-UV58tJ.js","./page-header-BHM4h2fS.js","./org-access-Bg27Z8x2.js","./radient-auth-buttons-BCtJNYf5.js","./org-surface-gate-CQxklQ-G.js","./building-2-CbHZ2q0R.js","./agents-page-CSQOyTDS.js","./image-plus-DmG9Cnvq.js","./project-markdown-BTsnM7OU.js","./schedules-page-DAwa60MB.js","./parseISO-CxPiCKvF.js","./projects-page-Br5DSkr6.js","./use-session-snapshot-QkR7pjNd.js","./library-page-D-CE1ZCg.js","./hash-CY36bXoG.js","./notifications-page-SK5NqB-7.js","./team-bridge-page-HYbbsoUb.js","./use-default-on-banner-bwSRinka.js","./browser-page-Db4cYtxn.js","./mesh-page-CR_KErFC.js","./settings-page-Db00UHjC.js","./notebook-pen-jwZCAOYl.js","./browser-webauthn-prompt-CH3nbvN4.js"])))=>i.map(i=>d[i]);
2
- import{r as m,j as c,c as R,b as it,h as II,p as OX,z as LX,o as BX,A as jX,u as _u,B as HX,C as UX,E as GX,F as w_,a as VX,R as WX}from"./index-D312rJYs.js";import{t as h,c as Bm,a as $X,L as hl,b as zX}from"./messages-CYpcciYD.js";import{aA as qX,aB as y_,aC as r5,aD as i5,u as Mt,aE as KX,aF as YX,aG as XX,aH as QX,aI as JX,aJ as ZX,aK as NI,aL as PI,aM as eQ,aN as tQ,w as Fe,aO as nQ,aP as Yk,aQ as dy,aR as Fd,i as Dn,a as ss,c as Et,e as Pv,n as a5,o as oi,X as o5,aS as Da,a4 as sg,a7 as l5,C as Ua,d as rt,aT as sQ,aU as MI,aV as XC,aW as c5,aX as Xk,an as Qk,aY as rQ,G as Fi,r as Mv,aZ as $f,a_ as u5,a$ as iQ,h as zi,b0 as QC,b1 as Ov,F as No,B as nt,b2 as d5,b3 as h5,b4 as hy,b5 as Jk,b6 as aQ,S as jm,b7 as f5,b8 as oQ,b9 as lQ,ba as cQ,O as Ou,bb as uQ,M as uA,K as Lv,bc as JC,bd as qn,be as Zk,bf as OI,bg as eE,L as dQ,bh as hQ,bi as fQ,bj as pQ,g as p5,bk as gQ,bl as mQ,bm as vQ,q as Gr,bn as ac,aw as fy,b as g5,bo as LI,bp as bQ,bq as BI,br as xQ,bs as dA,a2 as _Q,bt as wQ,bu as yQ,bv as CQ,bw as SQ,bx as jI,v as hA,by as m5,ah as kQ,bz as HI,bA as py,bB as EQ,bC as TQ,bD as RQ,bE as AQ,bF as FQ,bG as v5,bH as ZC,bI as bm,bJ as DQ,bK as b5,bL as IQ,bM as UI,bN as GI,bO as Lx,bP as Bx,bQ as tE,$ as fA,bR as x5,bS as NQ,_ as PQ,Z as MQ,bT as OQ,bU as VI,bV as LQ,bW as wd,bX as kb,bY as BQ,bZ as jQ,b_ as HQ,b$ as WI,c0 as $I,c1 as UQ,c2 as GQ,c3 as VQ,c4 as WQ,c5 as zI,c6 as qI,c7 as KI,c8 as YI,c9 as $Q,ca as zQ,cb as qQ,cc as KQ,cd as YQ,ce as XI,cf as XQ,cg as QQ,ch as JQ,ci as C_,cj as ZQ,ck as QI,cl as eJ,cm as tJ,cn as nJ,co as sJ,cp as Eb,cq as rJ,cr as iJ,cs as aJ,ct as oJ,cu as _5,cv as lJ,a0 as pA,az as JI,cw as cJ,cx as uJ,cy as dJ,ay as hJ,cz as ZI,t as eN,cA as Hm,cB as fJ,cC as pJ,cD as gJ,cE as Tb,cF as mJ,cG as Rb,cH as vJ,cI as Ab,cJ as tN,cK as bJ,cL as xJ,cM as nN,cN as Fb,cO as sN,cP as Db,cQ as _J,cR as jx,x as S_,y as w5,z as wJ,ai as nE,cS as yJ,cT as CJ,cU as SJ,cV as kJ,cW as EJ,cX as TJ,cY as RJ,cZ as AJ,c_ as y5,c$ as FJ,Y as Bv,d0 as DJ,d1 as gA,a5 as IJ,d2 as NJ,d3 as PJ,a3 as MJ,d4 as OJ,d5 as LJ,d6 as rN,d7 as e1,d8 as iN,d9 as BJ,da as jJ,db as HJ,dc as UJ,dd as GJ,de as VJ,df as aN,U as WJ,dg as $J,dh as zJ,di as qJ,dj as KJ,A as YJ,dk as XJ,a1 as QJ,dl as C5,dm as JJ,dn as ZJ,dp as eZ,dq as tZ,dr as gy,ds as mA,dt as S5,du as k5,s as nZ,dv as sZ,ax as rZ,ak as je,aa as t1,am as iZ,dw as aZ,dx as oZ,dy as n1,dz as lZ,a9 as cZ,dA as oN,dB as uZ,dC as pr,W as lN,dD as dZ,dE as cN,dF as hZ,dG as E5,dH as uN,dI as fZ}from"./path-utils-Bf8RCJbS.js";import{u as Ve,c as _t,z as Zu,S as On,G as Bo,B as ce,L as dr,K as bs,T as vA,b as Js,X as Xn,af as sE,ar as pZ,o as Tc,p as Rc,q as wl,J as Vi,l as Ei,r as rg,s as Fp,ak as jv,w as vt,a6 as ig,y as my,A as Rr,F as vy,Q as E0,R as T0,U as R0,V as A0,W as F0,D as Po,d as eo,e as Mo,H as dN,I as Nr,f as Jt,h as Hv,j as Lu,k as k_,as as s1,al as T5,M as R5,N as A5,O as rE,g as Hx,at as ep,aq as gZ,a7 as xh,a8 as by,a9 as Bu,au as mZ,_ as E_,t as F5,ab as xy,v as _y,av as vZ,Z as bA,C as hN,aa as bZ,ai as iE,i as xZ,aw as Ug,ax as xA,$ as _A,P as _Z,ac as wZ,ad as yZ,ae as CZ,m as SZ,n as kZ,ag as EZ,ah as TZ,ay as RZ,az as AZ,aA as D5,a as fN,x as pN,aB as Ld,am as Ib,E as FZ}from"./error-boundary-ByCPkFsK.js";import{cW as Ux,bX as Ru,ax as da,ct as wA,a$ as so,b0 as Zs,aD as nn,bn as fn,aw as Hs,aP as Ac,br as Uv,cX as DZ,bs as Gv,fA as I5,fB as IZ,fC as D0,fD as NZ,fE as PZ,fF as MZ,fG as OZ,fH as r1,fI as i1,a0 as wu,cB as Vv,eH as ed,ep as Gx,eo as LZ,en as kr,eq as Rn,fJ as N5,fK as BZ,cj as aE,bu as Uh,fL as yA,ew as wy,eU as jZ,fM as gN,fN as HZ,fO as UZ,fP as oE,fQ as GZ,fR as VZ,fS as WZ,fT as $Z,fU as T_,aU as R_,be as tp,fV as mN,fW as vN,W as I0,fX as zZ,fY as qZ,fZ as KZ,f_ as P5,f$ as YZ,g0 as XZ,g1 as M5,g2 as yy,g3 as Cy,g4 as QZ,g5 as JZ,g6 as ZZ,g7 as bN,g8 as eee,g9 as tee,ga as nee,gb as see,gc as ree,gd as iee,ge as aee,gf as oee,cL as O5,gg as lee,gh as L5,gi as cee,gj as xN,gk as uee,gl as dee,cI as ri,gm as N0,dY as B5,gn as hee,go as fee,gp as _N,gq as pee,gr as gee,gs as mee,gt as vee,gu as bee,a2 as Bd,c8 as j5,gv as Um,gw as H5,gx as xee,gy as _ee,gz as wee,gA as yee,gB as Cee,gC as See,gD as kee,bV as ju,gE as Hu,gF as Eee,aY as ag,gG as wN,gH as Tee,gI as Ree,gJ as Aee,gK as Fee,gL as Dee,gM as Iee,gN as Of,eM as Nee,gO as Pee,gP as Mee,eP as Oee,gQ as Lee,gR as Bee,gS as U5,dP as a1,gT as CA,bw as G5,gU as Sy,gV as jee,ci as lE,bp as SA,gW as V5,a1 as oc,gX as W5,bW as _h,cA as ky,gY as $5,cz as P0,gZ as Hee,c0 as Uu,cD as Ey,g_ as o1,g$ as Uee,h0 as Gee,h1 as Vee,h2 as Wee,h3 as $ee,h4 as zee,h5 as qee,h6 as Kee,h7 as Yee,h8 as yN,h9 as Xee,ha as Qee,hb as kA,hc as CN,eR as Jee,hd as Zee,he as z5,hf as ete,hg as tte,hh as q5,hi as cE,hj as nte,di as np,hk as og,hl as SN,hm as l1,hn as ste,cE as Ty,ho as rte,hp as K5,hq as uE,hr as ite,hs as Y5,ht as ate,hu as A_,hv as ote,hw as lte,hx as cte,hy as ute,hz as dte,hA as hte,hB as fte,b9 as Fs,hC as X5,b8 as So,hD as Q5,hE as pte,hF as gte,hG as kN,hH as J5,hI as Z5,hJ as e8,bZ as EA,hK as t8,hL as Gu,hM as n8,y as gt,hN as Qn,hO as F_,hP as _n,hQ as s8,hR as r8,hS as TA,hT as D_,hU as i8,hV as Ry,hW as Wv,hX as wh,O as RA,hY as dE,hZ as AA,h_ as c1,h$ as Ay,i0 as mte,i1 as ro,i2 as vte,i3 as bte,i4 as zf,i5 as hE,i6 as a8,i7 as xte,i8 as M0,i9 as Fy,ia as FA,ib as _te,ic as wte,id as yte,ie as Mn,ig as O0,ih as o8,ii as Va,ij as Cte,ik as Ste,il as l8,im as kte,io as Ete,ip as Tte,iq as Rte,ir as Ate,is as Fte,it as Dte,iu as Ite,iv as Nte,iw as Pte,ix as Mte,iy as Ote,iz as Lte,iA as Bte,iB as jte,iC as Hte,iD as Ute,iE as DA,iF as Gte,iG as EN,iH as IA,iI as Vte,iJ as c8,iK as NA,iL as Wte,cK as u8,d1 as Dy,d4 as Iy,iM as Ny,iN as lg,cs as d8,cv as $te,iO as TN,c4 as h8,iP as zte,iQ as qte,iR as Kte,iS as Yte,iT as Xte,iU as Qte,iV as Jte,iW as Zte,iX as ene,bc as Lr,dn as tne,iY as nne,iZ as sne,i_ as rne,i$ as ine,j0 as ane,j1 as one,j2 as lne,j3 as f8,j4 as cne,j5 as une,j6 as L0,j7 as PA,j8 as Py,j9 as MA,ja as dne,jb as hne,jc as fne,jd as p8,je as pne,jf as RN,jg as gne,jh as OA,ji as mne,jj as LA,jk as $v,jl as zv,jm as vne,jn as g8,jo as B0,jp as bne,jq as xne,jr as _ne,js as wne,jt as yne,ju as Cne,jv as AN,jw as m8,r as v8,jx as Sne,jy as kne,jz as Ene,jA as Tne,cH as Rne,jB as Ane,jC as sc,jD as FN,jE as Gm,jF as Gg,jG as Fne,jH as DN,jI as IN,jJ as Dne,aa as b8,c2 as Vm,jK as Ine,jL as Nne,jM as My,d7 as Pne,bo as cg,jN as Mne,jO as fE,jP as One,jQ as Lne,bt as Di,bm as Oy,dQ as ug,jR as x8,jS as BA,cw as Ly,jT as Bne,dd as jne,jU as Hne,jV as _8,jW as Au,jX as jA,jY as HA,jZ as Une,cm as w8,cn as By,j_ as Gne,cl as Dp,d8 as u1,j$ as Vne,k0 as Wne,k1 as $ne,k2 as zne,k3 as qne,k4 as Kne,k5 as Yne,k6 as zl,k7 as NN,k8 as Xne,c1 as Qne,k9 as Jne,ka as Zne,kb as ese,kc as tse,kd as nse,ke as sse,kf as pE,dw as y8,dx as I_,kg as rse,kh as C8,cN as ise,cJ as ase,ki as ose,kj as S8,kk as lse,kl as cse,cR as use,km as dse,kn as hse,ko as fse,kp as pse,kq as gse,kr as mse,eG as vse,$ as bse,ks as k8,kt as xse,ku as _se,kv as Nb,kw as E8,eD as wse,kx as th,fa as T8,fb as UA,ky as yse,kz as Cse,kA as Sse,kB as R8,M as kse,kC as Ese,bf as A8,f9 as Tse,kD as Rse,b$ as F8,kE as Ase,a4 as Fse,kF as Dse,kG as Ise,kH as Nse,kI as Pse,kJ as Mse,kK as PN,kL as d1,kM as Ose,c5 as h1,c6 as f1,c7 as p1,bd as Lse,kN as Bse,kO as jse,kP as Hse,cT as vf,kQ as bf,kR as Use,kS as Gse,kT as Vse,kU as Wse,kV as $se,kW as zse,kX as D8,kY as qse,kZ as I8,k_ as gE,k$ as mE,l0 as g1,l1 as Kse,l2 as Yse,l3 as Lf,l4 as Xse,aW as MN,l5 as ON,l6 as N8,l7 as vE,l8 as P8,l9 as M8,la as Qse,lb as Jse,lc as Zse,ld as ere,le as tre,a3 as nre,lf as sre,lg as rre,lh as ire,li as are,lj as ore,lk as lre,ll as cre,lm as ure,ln as dre,lo as hre,lp as fre,a9 as pre,a7 as gre,lq as LN,lr as mre,a8 as vre,ls as bre,lt as xre,lu as _re,a5 as wre,lv as yre,lw as Cre,lx as Sre,b3 as kre,b4 as Ere,b5 as Tre,b6 as Rre,b7 as Are,ly as Fre,lz as Dre,lA as Ire,lB as BN,eQ as O8,lC as GA,lD as Nre,bv as L8,lE as B8,lF as Pre,lG as Mre,lH as Ore,lI as Qr,lJ as Lre,lK as cu,lL as j8,lM as H8,lN as U8,lO as VA,lP as ra,lQ as Bre,lR as jre,lS as Hre,lT as Ure,lU as Gre,lV as Vre,lW as Wre,lX as $re,cc as zre,lY as qre,cY as Kre,lZ as G8,l_ as Yre,l$ as Xre,m0 as Qre,m1 as Jre,m2 as Zre,m3 as bE,m4 as eie,m5 as tie,m6 as jN,m7 as V8,m8 as nie,m9 as sie,ma as rie,mb as HN,mc as iie,md as aie,me as oie,mf as lie,mg as cie,mh as uie,mi as die,mj as hie,mk as WA,ml as fie,mm as UN,mn as Dd,mo as W8,mp as xE,mq as N_,mr as pie,ms as gie,mt as Pb,mu as xm,mv as $A,mw as $8,mx as mie,my as vie,mz as bie,mA as z8,mB as xie,mC as _ie,eF as P_,mD as wie,mE as GN,mF as yie,mG as Cie,dT as zA,dS as $r,mH as qA,dR as sp,dp as q8,dK as KA,e2 as Sie,dN as K8,du as $t,dI as Vu,dW as _E,mI as kie,mJ as Eie,mK as Tie,mL as Rie,mM as Aie,mN as Fie,mO as Die,mP as Y8,mQ as Iie,em as VN,mR as Nie,eh as Pie,df as Mie,mS as Oie,eW as Lie,mT as Bie,mU as jie,mV as Hie,eV as WN,mW as Uie,mX as Gie,mY as Vie,mZ as Wie,aZ as $ie,cr as va,m_ as zie,m$ as qie,n0 as Kie,n1 as Yie,n2 as Xie,n3 as xf,n4 as Qie,n5 as Jie,n6 as M_,n7 as Zie,n8 as eae,n9 as m1,na as v1,nb as $N,nc as b1,nd as zN,ne as X8,bl as tae,nf as Q8,ng as nae,bi as sae,bj as rae,bg as iae,bh as aae,nh as oae,bk as lae}from"./conversation-input-sync-BsdkPoIA.js";import{u as J8,o as dg,b as cae,c as uae,r as Z8,d as eH,e as j0,f as dae,g as hae,s as YA,n as wE,h as fae,i as pae,p as gae,j as mae,k as vae,l as bae,q as xae,v as _ae,w as qN,x as KN,y as wae,z as yae,A as Cae,C as Sae,B as kae,D as Eae,E as Tae,F as Rae,G as Aae,H as Fae}from"./console-mirror-Df9e_9IL.js";function YN(e,t){return e.filter(n=>!t.includes(n))}function Dae(e,t,n){const s=e.slice(0);return s[t]=n,s}var Iae=class extends qX{#s;#e;#r;#i;#t;#n;#a;#o;#l=[];constructor(e,t,n){super(),this.#s=e,this.#i=n,this.#r=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#h(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#r=e,this.#i=t,y_.batch(()=>{const n=this.#t,s=this.#d(this.#r);this.#l=s,s.forEach(o=>o.observer.setOptions(o.defaultedQueryOptions));const r=s.map(o=>o.observer),i=r.map(o=>o.getCurrentResult()),a=r.some((o,l)=>o!==n[l]);n.length===r.length&&!a||(this.#t=r,this.#e=i,this.hasListeners()&&(YN(n,r).forEach(o=>{o.destroy()}),YN(r,n).forEach(o=>{o.subscribe(l=>{this.#h(o,l)})}),this.#f()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const n=this.#d(e),s=n.map(r=>r.observer.getOptimisticResult(r.defaultedQueryOptions));return[s,r=>this.#u(r??s,t),()=>this.#c(s,n)]}#c(e,t){return t.map((n,s)=>{const r=e[s];return n.defaultedQueryOptions.notifyOnChangeProps?r:n.observer.trackResult(r,i=>{t.forEach(a=>{a.observer.trackProp(i)})})})}#u(e,t){return t?((!this.#n||this.#e!==this.#o||t!==this.#a)&&(this.#a=t,this.#o=this.#e,this.#n=r5(this.#n,t(e))),this.#n):e}#d(e){const t=new Map(this.#t.map(s=>[s.options.queryHash,s])),n=[];return e.forEach(s=>{const r=this.#s.defaultQueryOptions(s),i=t.get(r.queryHash);i?n.push({defaultedQueryOptions:r,observer:i}):n.push({defaultedQueryOptions:r,observer:new i5(this.#s,r)})}),n}#h(e,t){const n=this.#t.indexOf(e);n!==-1&&(this.#e=Dae(this.#e,n,t),this.#f())}#f(){if(this.hasListeners()){const e=this.#n,t=this.#c(this.#e,this.#l),n=this.#u(t,this.#i?.combine);e!==n&&y_.batch(()=>{this.listeners.forEach(s=>{s(this.#e)})})}}};function tH({queries:e,...t},n){const s=Mt(n),r=KX(),i=YX(),a=m.useMemo(()=>e.map(b=>{const x=s.defaultQueryOptions(b);return x._optimisticResults=r?"isRestoring":"optimistic",x}),[e,s,r]);a.forEach(b=>{XX(b),QX(b,i)}),JX(i);const[o]=m.useState(()=>new Iae(s,a,t)),[l,u,d]=o.getOptimisticResult(a,t.combine),f=!r&&t.subscribed!==!1;m.useSyncExternalStore(m.useCallback(b=>f?o.subscribe(y_.batchCalls(b)):ZX,[o,f]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),m.useEffect(()=>{o.setQueries(a,t)},[a,t,o]);const g=l.some((b,x)=>NI(a[x],b))?l.flatMap((b,x)=>{const _=a[x];if(_){const w=new i5(s,_);if(NI(_,b))return PI(_,w,i);eQ(b,r)&&PI(_,w,i)}return[]}):[];if(g.length>0)throw Promise.all(g);const v=l.find((b,x)=>{const _=a[x];return _&&tQ({result:b,errorResetBoundary:i,throwOnError:_.throwOnError,query:s.getQueryCache().get(_.queryHash),suspense:_.suspense})});if(v?.error)throw v.error;return u(d())}function XN(e,t){return e.findAll(t.filters).map(n=>t.select?t.select(n):n.state)}function Nae(e={},t){const n=Mt(t).getMutationCache(),s=m.useRef(e),r=m.useRef(null);return r.current||(r.current=XN(n,e)),m.useEffect(()=>{s.current=e}),m.useSyncExternalStore(m.useCallback(i=>n.subscribe(()=>{const a=r5(r.current,XN(n,s.current));r.current!==a&&(r.current=a,y_.schedule(i))}),[n]),()=>r.current,()=>r.current)}const Vx=8e3,nH=1e4;function Pae(e){return e?h("ui.notices.chat.archive_offered_title",{title:e}):h("ui.notices.chat.archive_offered_no_name")}const Mae=()=>h("ui.notices.chat.archive_offered_verb");function Oae(e){return Fe.getState().archiveFacts[e]}function Lae(e){const t=Fe.getState(),n=t.archiveFacts[e];return n?n.archived:t.sessions.find(s=>s.session_id===e)?.archived}function Bae(){const e=Fe(t=>t.archiveUndo);m.useEffect(()=>{if(e===null)return;let t=!1;const n=()=>{t||(t=!0,r())},s=()=>{n();const i=Fe.getState().archiveUndo;i!==null&&i.sessionId===e.sessionId&&i.at===e.at&&Fe.getState().setArchiveUndo(null)},r=Fe.subscribe(()=>{const i=Oae(e.sessionId);i!==void 0&&!i.answered||nQ(e.archived,Lae(e.sessionId))||s()});return n},[e])}function jae(e){return h("ui.notices.chat.drafts_offered_name",{count:e})}const Hae=e=>h("ui.notices.chat.drafts_offered_verb",{count:e}),Uae=e=>{const t=Yk(e),n=t.length,s=t.filter(o=>!o.active).length,r=n===1?"chat":"chats",i=e.filter(o=>dy(o)!==null&&Yk([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`:""}},sH=e=>h("ui.notices.chat.mark_all_read_deferred",{count:e}),Gae=e=>{if(e.attempted===0)return{tone:"success",message:h("ui.notices.chat.mark_all_read_nothing")};const t=e.unknown-e.deferred,n=[e.superseded>0?h("ui.notices.chat.mark_all_read_superseded",{count:e.superseded}):null,t>0?h("ui.notices.chat.mark_all_read_unknown",{count:t}):null,e.deferred>0?sH(e.deferred):null].filter(s=>s!==null);return e.cleared===0?{tone:"warning",message:[h("ui.notices.chat.mark_all_read_none_cleared"),...n].join(" ")}:{tone:"success",message:[h("ui.notices.chat.mark_all_read_cleared",{count:e.cleared}),...n].join(" ")}},x1="archive",QN="drafts-undo",JN="bulk-read-deferral",Vae=8e3;function Wae(){const e=Ve(),t=Fe(b=>b.archiveFailure),n=Fe(b=>b.archiveUndo),s=Fe(b=>b.draftsUndo),r=Fe(b=>b.bulkReadDeferral),i=Fe(b=>b.clearArchiveFailure),a=Fe(b=>b.setArchiveUndo),o=Fe(b=>b.setSessionArchived),l=Fe(b=>b.restoreDraftsUndo);Bae();const u=Fd(t?.title),d=m.useRef(null),f=m.useRef(null);m.useEffect(()=>{if(t===null&&n===null){if(d.current===null)return;d.current=null,f.current=null,Ux(x1);return}const b=t&&n?n.at>t.at?"offer":"failure":t?"failure":"offer",x=b==="offer"?n?.at??0:t?.at??0,_=d.current;d.current={kind:b,at:x},_!==null&&_.kind!==b&&x>_.at&&(b==="failure"?a(null):i());const w=(y,S)=>()=>{const C=Fe.getState();y==="offer"?C.archiveUndo?.at===S&&C.setArchiveUndo(null):C.archiveFailure?.at===S&&C.clearArchiveFailure();const E=d.current;E!==null&&E.kind===y&&E.at===S&&(d.current=null)};if(b==="failure"&&t){const y=f.current,S=y!==null&&y.kind==="failure"&&y.at===t.at;if(S&&y.locale===e)return;const C=S?y.raisedAt+y.duration-Date.now():nH;if(C<=0)return;f.current=S?{...y,locale:e}:{kind:"failure",at:t.at,raisedAt:Date.now(),duration:C,locale:e},Ru(`${t.archived?h("ui.notices.chat.archive_failed",{title:u}):h("ui.notices.chat.unarchive_failed",{title:u})}${t.detail?` ${t.detail}`:""}`,{id:x1,duration:C,onAutoClose:w("failure",t.at),onDismiss:w("failure",t.at),action:{label:h("ui.common.actions.retry"),onClick:E=>{E.preventDefault(),o(t.sessionId,t.archived,t.title)}}});return}if(n){const y=f.current,S=y!==null&&y.kind==="offer"&&y.at===n.at;if(S&&y.locale===e)return;const C=S?y.raisedAt+y.duration-Date.now():Vx;if(C<=0)return;f.current=S?{...y,locale:e}:{kind:"offer",at:n.at,raisedAt:Date.now(),duration:C,locale:e},da(c.jsxs("span",{className:R("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:R("min-w-0 truncate"),children:Pae(n.title)}),c.jsx("span",{className:R("shrink-0"),children:Mae()})]}),{id:x1,duration:C,classNames:{content:"min-w-0"},onAutoClose:w("offer",n.at),onDismiss:w("offer",n.at),action:{label:h("ui.notices.chat.undo"),onClick:E=>{E.preventDefault(),o(n.sessionId,!n.archived,n.title)}}})}},[e,u,t,n,a,i,o]);const p=m.useRef(!1),g=m.useRef(null);m.useEffect(()=>{if(s===null){if(!p.current)return;p.current=!1,g.current=null,Ux(QN);return}p.current=!0;const b=g.current,x=b!==null&&b.at===s.at;if(x&&b.locale===e)return;const _=x?b.raisedAt+Vx-Date.now():Vx;if(_<=0)return;g.current=x?{...b,locale:e}:{at:s.at,raisedAt:Date.now(),locale:e};const w=()=>{const y=Fe.getState();y.draftsUndo?.at===s.at&&(y.setDraftsUndo(null),p.current=!1)};da(c.jsxs("span",{className:R("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:R("min-w-0 truncate"),children:jae(s.keys.length)}),c.jsx("span",{className:R("shrink-0"),children:Hae(s.keys.length)})]}),{id:QN,duration:_,classNames:{content:"min-w-0"},onAutoClose:w,onDismiss:w,action:{label:h("ui.notices.chat.undo"),onClick:y=>{y.preventDefault(),l();const S=Fe.getState(),C=S.stagedByDiscard;S.setStagedByDiscard(null),s.keys.length===1&&C!==null&&Fe.getState().activeDraftKey===C&&Fe.getState().openDraft(s.keys[0])}}})},[e,s,l]);const v=m.useRef(!1);return m.useEffect(()=>{if(r===null){if(!v.current)return;v.current=!1,Ux(JN);return}v.current=!0;const b=()=>{const x=Fe.getState();x.bulkReadDeferral?.at===r.at&&(x.clearBulkReadDeferral(),v.current=!1)};da(sH(r.count),{id:JN,duration:Vae,onAutoClose:b,onDismiss:b})},[r]),null}var Co,qe=typeof window<"u"?window:void 0,ji=typeof globalThis<"u"?globalThis:qe,rH=Array.prototype,ZN=rH.forEach,eP=rH.indexOf,ca=ji?.navigator,Pt=ji?.document,Li=ji?.location,yE=ji?.fetch,CE=ji!=null&&ji.XMLHttpRequest&&"withCredentials"in new ji.XMLHttpRequest?ji.XMLHttpRequest:void 0,tP=ji?.AbortController,or=ca?.userAgent,tn=qe??{},Jl={DEBUG:!1,LIB_VERSION:"1.235.6"},_1="$copy_autocapture",$ae=["$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"})(Co||(Co={}));var zae=["fatal","error","warning","log","info","debug"];function xn(e,t){return e.indexOf(t)!==-1}var jy=function(e){return e.trim()},XA=function(e){return e.replace(/^\$/,"")},qae=Array.isArray,iH=Object.prototype,aH=iH.hasOwnProperty,Hy=iH.toString,Ls=qae||function(e){return Hy.call(e)==="[object Array]"},Ro=e=>typeof e=="function",Bs=e=>e===Object(e)&&!Ls(e),qf=e=>{if(Bs(e)){for(var t in e)if(aH.call(e,t))return!1;return!0}return!1},Rt=e=>e===void 0,cr=e=>Hy.call(e)=="[object String]",SE=e=>cr(e)&&e.trim().length===0,td=e=>e===null,Yn=e=>Rt(e)||td(e),ki=e=>Hy.call(e)=="[object Number]",ec=e=>Hy.call(e)==="[object Boolean]",Kae=e=>e instanceof FormData,Yae=e=>xn($ae,e),oH=e=>{var t={_log:function(n){if(qe&&(Jl.DEBUG||tn.POSTHOG_DEBUG)&&!Rt(qe.console)&&qe.console){for(var s=("__rrweb_original__"in qe.console[n])?qe.console[n].__rrweb_original__:qe.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=>oH("".concat(e," ").concat(n))};return t},Ht=oH("[PostHog.js]"),li=Ht.createLogger,Xae=li("[ExternalScriptsLoader]"),nP=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return Xae.warn("".concat(t," was requested but loading of external scripts is disabled.")),n("Loading of external scripts is disabled");var s=Pt?.querySelectorAll("script");if(s){for(var r=0;r<s.length;r++)if(s[r].src===t)return n()}var i=()=>{if(!Pt)return n("document not found");var a=Pt.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=Pt.querySelectorAll("body > script");l.length>0?(o=l[0].parentNode)===null||o===void 0||o.insertBefore(a,l[0]):Pt.body.appendChild(a)};Pt!=null&&Pt.body?i():Pt?.addEventListener("DOMContentLoaded",i)};function sP(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 Ze(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?sP(Object(n),!0).forEach(function(s){yt(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sP(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function yt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lH(e,t){if(e==null)return{};var n,s,r=function(a,o){if(a==null)return{};var l,u,d={},f=Object.keys(a);for(u=0;u<f.length;u++)l=f[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}tn.__PosthogExtensions__=tn.__PosthogExtensions__||{},tn.__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);nP(e,a,n)},tn.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var s=e.requestRouter.endpointFor("api",t);nP(e,s,n)};var O_={};function Fu(e,t,n){if(Ls(e)){if(ZN&&e.forEach===ZN)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)===O_)return}}}function as(e,t,n){if(!Yn(e)){if(Ls(e))return Fu(e,t,n);if(Kae(e)){for(var s of e.entries())if(t.call(n,s[1],s[0])===O_)return}else for(var r in e)if(aH.call(e,r)&&t.call(n,e[r],r)===O_)return}}var qs=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 Fu(n,function(r){for(var i in r)r[i]!==void 0&&(e[i]=r[i])}),e},Wx=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 Fu(n,function(r){Fu(r,function(i){e.push(i)})}),e};function $x(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 rP=function(e){try{return e()}catch{return}},Qae=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){Ht.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ht.critical(r)}}},H0=function(e){var t={};return as(e,function(n,s){cr(n)&&n.length>0&&(t[s]=n)}),t};function Jae(e,t){return n=e,s=i=>cr(i)&&!td(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),Ls(a)?(l=[],Fu(a,u=>{l.push(i(u))})):(l={},as(a,(u,d)=>{r.has(u)||(l[d]=i(u,d))})),l);var l}(n);var n,s,r}var Zae=["herokuapp.com","vercel.app","netlify.app"];function eoe(e){var t=e?.hostname;if(!cr(t))return!1;var n=t.split(".").slice(-2).join(".");for(var s of Zae)if(n===s)return!1;return!0}function cH(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n]}function Ys(e,t,n,s){var{capture:r=!1,passive:i=!0}=s??{};e?.addEventListener(t,n,{capture:r,passive:i})}var uH="$people_distinct_id",_m="__alias",wm="__timers",iP="$autocapture_disabled_server_side",kE="$heatmaps_enabled_server_side",aP="$exception_capture_enabled_server_side",oP="$web_vitals_enabled_server_side",dH="$dead_clicks_enabled_server_side",lP="$web_vitals_allowed_metrics",EE="$session_recording_enabled_server_side",cP="$console_log_recording_enabled_server_side",uP="$session_recording_network_payload_capture",dP="$session_recording_masking",hP="$session_recording_canvas_recording",fP="$replay_sample_rate",pP="$replay_minimum_duration",gP="$replay_script_config",L_="$sesid",ym="$session_is_sampled",w1="$session_recording_url_trigger_activated_session",y1="$session_recording_event_trigger_activated_session",Kf="$enabled_feature_flags",zx="$early_access_features",TE="$feature_flag_details",Cm="$stored_person_properties",Id="$stored_group_properties",RE="$surveys",Mb="$surveys_activated",B_="$flag_call_reported",Yl="$user_state",AE="$client_session_props",FE="$capture_rate_limit",DE="$initial_campaign_params",IE="$initial_referrer_info",NE="$initial_person_info",j_="$epp",hH="__POSTHOG_TOOLBAR__",mP="$posthog_cookieless",toe=[uH,_m,"__cmpns",wm,EE,kE,L_,Kf,Yl,zx,TE,Id,Cm,RE,B_,AE,FE,DE,IE,j_];function vP(e){var t;return e instanceof Element&&(e.id===hH||!((t=e.closest)===null||t===void 0||!t.call(e,".toolbar-global-fade-container")))}function Uy(e){return!!e&&e.nodeType===1}function Du(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function fH(e){return!!e&&e.nodeType===3}function pH(e){return!!e&&e.nodeType===11}function QA(e){return e?jy(e).split(/\s+/):[]}function bP(e){var t=qe?.location.href;return!!(t&&e&&e.some(n=>t.match(n)))}function H_(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 QA(t)}function gH(e){return Yn(e)?null:jy(e).split(/(\s+)/).filter(t=>Ip(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Gy(e){var t="";return ME(e)&&!bH(e)&&e.childNodes&&e.childNodes.length&&as(e.childNodes,function(n){var s;fH(n)&&n.textContent&&(t+=(s=gH(n.textContent))!==null&&s!==void 0?s:"")}),jy(t)}function mH(e){return Rt(e.target)?e.srcElement||null:(t=e.target)!==null&&t!==void 0&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var PE=["a","button","form","input","select","textarea","label"];function vH(e){var t=e.parentNode;return!(!t||!Uy(t))&&t}function noe(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(!qe||!e||Du(e,"html")||!Uy(e)||n!=null&&n.url_allowlist&&!bP(n.url_allowlist)||n!=null&&n.url_ignorelist&&bP(n.url_ignorelist))return!1;if(n!=null&&n.dom_event_allowlist){var i=n.dom_event_allowlist;if(i&&!i.some(g=>t.type===g))return!1}for(var a=!1,o=[e],l=!0,u=e;u.parentNode&&!Du(u,"body");)if(pH(u.parentNode))o.push(u.parentNode.host),u=u.parentNode.host;else{if(!(l=vH(u)))break;if(s||PE.indexOf(l.tagName.toLowerCase())>-1)a=!0;else{var d=qe.getComputedStyle(l);d&&d.getPropertyValue("cursor")==="pointer"&&(a=!0)}o.push(l),u=l}if(!function(g,v){var b=v?.element_allowlist;if(Rt(b))return!0;var x=function(y){if(b.some(S=>y.tagName.toLowerCase()===S))return{v:!0}};for(var _ of g){var w=x(_);if(typeof w=="object")return w.v}return!1}(o,n)||!function(g,v){var b=v?.css_selector_allowlist;if(Rt(b))return!0;var x=function(y){if(b.some(S=>y.matches(S)))return{v:!0}};for(var _ of g){var w=x(_);if(typeof w=="object")return w.v}return!1}(o,n))return!1;var f=qe.getComputedStyle(e);if(f&&f.getPropertyValue("cursor")==="pointer"&&t.type==="click")return!0;var p=e.tagName.toLowerCase();switch(p){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&&(PE.indexOf(p)>-1||e.getAttribute("contenteditable")==="true")}}function ME(e){for(var t=e;t.parentNode&&!Du(t,"body");t=t.parentNode){var n=H_(t);if(xn(n,"ph-sensitive")||xn(n,"ph-no-capture"))return!1}if(xn(H_(e),"ph-include"))return!0;var s=e.type||"";if(cr(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var r=e.name||e.id||"";return!(cr(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 bH(e){return!!(Du(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Du(e,"select")||Du(e,"textarea")||e.getAttribute("contenteditable")==="true")}var xH="(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})",soe=new RegExp("^(?:".concat(xH,")$")),roe=new RegExp(xH),_H="\\d{3}-?\\d{2}-?\\d{4}",ioe=new RegExp("^(".concat(_H,")$")),aoe=new RegExp("(".concat(_H,")"));function Ip(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return!(Yn(e)||cr(e)&&(e=jy(e),(t?soe:roe).test((e||"").replace(/[- ]/g,""))||(t?ioe:aoe).test(e)))}function wH(e){var t=Gy(e);return Ip(t="".concat(t," ").concat(yH(e)).trim())?t:""}function yH(e){var t="";return e&&e.childNodes&&e.childNodes.length&&as(e.childNodes,function(n){var s;if(n&&((s=n.tagName)===null||s===void 0?void 0:s.toLowerCase())==="span")try{var r=Gy(n);t="".concat(t," ").concat(r).trim(),n.childNodes&&n.childNodes.length&&(t="".concat(t," ").concat(yH(n)).trim())}catch(i){Ht.error("[AutoCapture]",i)}}),t}function ooe(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=Ze(Ze(Ze(Ze({},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 $x(l).sort((d,f)=>{var[p]=d,[g]=f;return p.localeCompare(g)}).forEach(d=>{var[f,p]=d;return u[xP(f.toString())]=xP(p.toString())}),a+=":",a+=$x(l).map(d=>{var[f,p]=d;return"".concat(f,'="').concat(p,'"')}).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:loe(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return $x(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 xP(e){return e.replace(/"|\\"/g,'\\"')}function loe(e){var t=e.attr__class;return t?Ls(t)?t:QA(t):void 0}class CH{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 coe=["localhost","127.0.0.1"],rp=e=>{var t=Pt?.createElement("a");return Rt(t)?null:(t.href=e,t)},uoe=function(e){var t,n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",r=[];return as(e,function(i,a){Rt(i)||Rt(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)},U_=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(!Ls(n)||n.length<2)return"";var a=n[1];try{a=decodeURIComponent(a)}catch{Ht.error("Skipping decoding for malformed query param: "+a)}return a.replace(/\+/g," ")},C1=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=[],f=0;f<u.length;f++){var p=u[f].split("=");Ls(p)&&(t.includes(p[0])?d.push(p[0]+"="+n):d.push(u[f]))}var g=l;return o!=null&&(g+="?"+d.join("&")),i!=null&&(g+="#"+i),g},G_=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},_P=li("[AutoCapture]");function S1(e,t){return t.length>e?t.slice(0,e)+"...":t}function doe(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!Uy(t));return t}function hoe(e,t,n,s){var r=e.tagName.toLowerCase(),i={tag_name:r};PE.indexOf(r)>-1&&!n&&(r.toLowerCase()==="a"||r.toLowerCase()==="button"?i.$el_text=S1(1024,wH(e)):i.$el_text=S1(1024,Gy(e)));var a=H_(e);a.length>0&&(i.classes=a.filter(function(d){return d!==""})),as(e.attributes,function(d){var f;if((!bH(e)||["name","id","class","aria-label"].indexOf(d.name)!==-1)&&(s==null||!s.includes(d.name))&&!t&&Ip(d.value)&&(f=d.name,!cr(f)||f.substring(0,10)!=="_ngcontent"&&f.substring(0,7)!=="_nghost")){var p=d.value;d.name==="class"&&(p=QA(p).join(" ")),i["attr__"+d.name]=S1(1024,p)}});for(var o=1,l=1,u=e;u=doe(u);)o++,u.tagName===e.tagName&&l++;return i.nth_child=o,i.nth_of_type=l,i}function foe(e,t){for(var n,s,{e:r,maskAllElementAttributes:i,maskAllText:a,elementAttributeIgnoreList:o,elementsChainAsString:l}=t,u=[e],d=e;d.parentNode&&!Du(d,"body");)pH(d.parentNode)?(u.push(d.parentNode.host),d=d.parentNode.host):(u.push(d.parentNode),d=d.parentNode);var f,p=[],g={},v=!1,b=!1;if(as(u,S=>{var C=ME(S);S.tagName.toLowerCase()==="a"&&(v=S.getAttribute("href"),v=C&&v&&Ip(v)&&v),xn(H_(S),"ph-no-capture")&&(b=!0),p.push(hoe(S,i,a,o));var E=function(k){if(!ME(k))return{};var F={};return as(k.attributes,function(A){if(A.name&&A.name.indexOf("data-ph-capture-attribute")===0){var I=A.name.replace("data-ph-capture-attribute-",""),N=A.value;I&&N&&Ip(N)&&(F[I]=N)}}),F}(S);qs(g,E)}),b)return{props:{},explicitNoCapture:b};if(a||(e.tagName.toLowerCase()==="a"||e.tagName.toLowerCase()==="button"?p[0].$el_text=wH(e):p[0].$el_text=Gy(e)),v){var x,_;p[0].attr__href=v;var w=(x=rp(v))===null||x===void 0?void 0:x.host,y=qe==null||(_=qe.location)===null||_===void 0?void 0:_.host;w&&y&&w!==y&&(f=v)}return{props:qs({$event_type:r.type,$ce_version:1},l?{}:{$elements:p},{$elements_chain:ooe(p)},(n=p[0])!==null&&n!==void 0&&n.$el_text?{$el_text:(s=p[0])===null||s===void 0?void 0:s.$el_text}:{},f&&r.type==="click"?{$external_click_url:f}:{},g)}}let poe=class{constructor(t){yt(this,"_initialized",!1),yt(this,"_isDisabledServerSide",null),yt(this,"rageclicks",new CH),yt(this,"_elementsChainAsString",!1),this.instance=t,this._elementSelectors=null}get config(){var t,n,s=Bs(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(qe&&Pt){var t=s=>{s=s||qe?.event;try{this._captureEvent(s)}catch(r){_P.error("Failed to capture event",r)}};if(Ys(Pt,"submit",t,{capture:!0}),Ys(Pt,"change",t,{capture:!0}),Ys(Pt,"click",t,{capture:!0}),this.config.capture_copied_text){var n=s=>{s=s||qe?.event,this._captureEvent(s,_1)};Ys(Pt,"copy",n,{capture:!0}),Ys(Pt,"cut",n,{capture:!0})}}}else _P.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({[iP]:!!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=Pt?.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[iP],r=this._isDisabledServerSide;if(td(r)&&!ec(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=mH(t);fH(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===_1;if(r&&noe(r,t,this.config,i,i?["copy","cut"]:void 0)){var{props:a,explicitNoCapture:o}=foe(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===_1){var u,d=gH(qe==null||(u=qe.getSelection())===null||u===void 0?void 0:u.toString()),f=t.type||"clipboard";if(!d)return!1;a.$selected_content=d,a.$copy_type=f}return this.instance.capture(n,a),!0}}}isBrowserSupported(){return Ro(Pt?.querySelectorAll)}};Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return ki(e)&&isFinite(e)&&Math.floor(e)===e});var wP="0123456789abcdef";let goe=class OE{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 OE(i)}toString(){for(var t="",n=0;n<this.bytes.length;n++)t=t+wP.charAt(this.bytes[n]>>>4)+wP.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 OE(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}},moe=class{constructor(){yt(this,"timestamp",0),yt(this,"counter",0),yt(this,"random",new voe)}generate(){var t=this.generateOrAbort();if(Rt(t)){this.timestamp=0;var n=this.generateOrAbort();if(Rt(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 goe.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 yP,SH=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};qe&&!Rt(qe.crypto)&&crypto.getRandomValues&&(SH=e=>crypto.getRandomValues(e));let voe=class{constructor(){yt(this,"buffer",new Uint32Array(8)),yt(this,"cursor",1/0)}nextUint32(){return this.cursor>=this.buffer.length&&(SH(this.buffer),this.cursor=0),this.buffer[this.cursor++]}};var yu=()=>boe().toString(),boe=()=>(yP||(yP=new moe)).generate(),xoe="Thu, 01 Jan 1970 00:00:00 GMT",Vg="",_oe=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function woe(e,t){if(t){var n=function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt;if(Vg)return Vg;if(!i||["localhost","127.0.0.1"].includes(r))return"";for(var a=r.split("."),o=Math.min(a.length,8),l="dmn_chk_"+yu(),u=new RegExp("(^|;)\\s*"+l+"=1");!Vg&&o--;){var d=a.slice(o).join("."),f=l+"=1;domain=."+d;i.cookie=f,u.test(i.cookie)&&(i.cookie=f+";expires="+xoe,Vg=d)}return Vg}(e);if(!n){var s=(r=>{var i=r.match(_oe);return i?i[0]:""})(e);s!==n&&Ht.info("Warning: cookie subdomain discovery mismatch",s,n),n=s}return n?"; domain=."+n:""}return""}var gu,lc={is_supported:()=>!!Pt,error:function(e){Ht.error("cookieStore error: "+e)},get:function(e){if(Pt){try{for(var t=e+"=",n=Pt.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(lc.get(e))||{}}catch{}return t},set:function(e,t,n,s,r){if(Pt)try{var i="",a="",o=woe(Pt.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&&Ht.warn("cookieStore warning: large cookie, len="+u.length),Pt.cookie=u,u}catch{return}},remove:function(e,t){try{lc.set(e,"",-1,t)}catch{return}}},k1=null,gr={is_supported:function(){if(!td(k1))return k1;var e=!0;if(Rt(qe))e=!1;else try{var t="__mplssupport__";gr.set(t,"xyz"),gr.get(t)!=='"xyz"'&&(e=!1),gr.remove(t)}catch{e=!1}return e||Ht.error("localStorage unsupported; falling back to cookie store"),k1=e,e},error:function(e){Ht.error("localStorage error: "+e)},get:function(e){try{return qe?.localStorage.getItem(e)}catch(t){gr.error(t)}return null},parse:function(e){try{return JSON.parse(gr.get(e))||{}}catch{}return null},set:function(e,t){try{qe?.localStorage.setItem(e,JSON.stringify(t))}catch(n){gr.error(n)}},remove:function(e){try{qe?.localStorage.removeItem(e)}catch(t){gr.error(t)}}},yoe=["distinct_id",L_,ym,j_,NE],Ob=Ze(Ze({},gr),{},{parse:function(e){try{var t={};try{t=lc.parse(e)||{}}catch{}var n=qs(t,JSON.parse(gr.get(e)||"{}"));return gr.set(e,n),n}catch{}return null},set:function(e,t,n,s,r,i){try{gr.set(e,t,void 0,void 0,i);var a={};yoe.forEach(o=>{t[o]&&(a[o]=t[o])}),Object.keys(a).length&&lc.set(e,a,n,s,r,i)}catch(o){gr.error(o)}},remove:function(e,t){try{qe?.localStorage.removeItem(e),lc.remove(e,t)}catch(n){gr.error(n)}}}),Lb={},Coe={is_supported:function(){return!0},error:function(e){Ht.error("memoryStorage error: "+e)},get:function(e){return Lb[e]||null},parse:function(e){return Lb[e]||null},set:function(e,t){Lb[e]=t},remove:function(e){delete Lb[e]}},yd=null,Br={is_supported:function(){if(!td(yd))return yd;if(yd=!0,Rt(qe))yd=!1;else try{var e="__support__";Br.set(e,"xyz"),Br.get(e)!=='"xyz"'&&(yd=!1),Br.remove(e)}catch{yd=!1}return yd},error:function(e){Ht.error("sessionStorage error: ",e)},get:function(e){try{return qe?.sessionStorage.getItem(e)}catch(t){Br.error(t)}return null},parse:function(e){try{return JSON.parse(Br.get(e))||null}catch{}return null},set:function(e,t){try{qe?.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){Br.error(n)}},remove:function(e){try{qe?.sessionStorage.removeItem(e)}catch(t){Br.error(t)}}};(function(e){e[e.PENDING=-1]="PENDING",e[e.DENIED=0]="DENIED",e[e.GRANTED=1]="GRANTED"})(gu||(gu={}));let Soe=class{constructor(t){this.instance=t}get config(){return this.instance.config}get consent(){return this.getDnt()?gu.DENIED:this.storedConsent}isOptedOut(){return this.consent===gu.DENIED||this.consent===gu.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"?gu.GRANTED:t==="0"?gu.DENIED:gu.PENDING}get storage(){if(!this._storage){var t=this.config.opt_out_capturing_persistence_type;this._storage=t==="localStorage"?gr:lc;var n=t==="localStorage"?lc:gr;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&&!!cH([ca?.doNotTrack,ca?.msDoNotTrack,tn.doNotTrack],t=>xn([!0,1,"1","yes"],t))}};var Bb=li("[Dead Clicks]"),koe=()=>!0,Eoe=e=>{var t,n=!((t=e.instance.persistence)===null||t===void 0||!t.get_property(dH)),s=e.instance.config.capture_dead_clicks;return ec(s)?s:n};let kH=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({[dH]:t?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.loadScript(()=>{this.start()})}loadScript(t){var n,s,r;(n=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.initDeadClicksAutocapture&&t(),(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"dead-clicks-autocapture",i=>{i?Bb.error("failed to load script",i):t()})}start(){var t;if(Pt){if(!this._lazyLoadedDeadClicksAutocapture&&(t=tn.__PosthogExtensions__)!==null&&t!==void 0&&t.initDeadClicksAutocapture){var n=Bs(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this._lazyLoadedDeadClicksAutocapture=tn.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this._lazyLoadedDeadClicksAutocapture.start(Pt),Bb.info("starting...")}}else Bb.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,Bb.info("stopping..."))}};var E1=li("[ExceptionAutocapture]");let Toe=class{constructor(t){var n;yt(this,"startCapturing",()=>{var s;if(qe&&this.isEnabled&&(s=tn.__PosthogExtensions__)!==null&&s!==void 0&&s.errorWrappingFunctions){var r=tn.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=tn.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=tn.__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){E1.error("failed to start",o),this.stopCapturing()}}}),this.instance=t,this.remoteEnabled=!((n=this.instance.persistence)===null||n===void 0||!n.props[aP]),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 Bs(t)?n=Ze(Ze({},n),t):(Rt(t)?this.remoteEnabled:t)&&(n=Ze(Ze({},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&&(E1.info("enabled"),this.loadScript(this.startCapturing))}loadScript(t){var n,s,r;(n=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.errorWrappingFunctions&&t(),(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"exception-autocapture",i=>{if(i)return E1.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({[aP]: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 EH(e){return!Rt(Event)&&TH(e,Event)}function TH(e,t){try{return e instanceof t}catch{return!1}}function qx(e,t){return Object.prototype.toString.call(e)==="[object ".concat(t,"]")}function T1(e){return qx(e,"DOMError")}var CP=/\(error: (.*)\)/,SP=50,Yf="?";function R1(e,t,n,s){var r={platform:"web:javascript",filename:e,function:t==="<anonymous>"?Yf:t,in_app:!0};return Rt(n)||(r.lineno=n),Rt(s)||(r.colno=s),r}var Roe=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Aoe=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Foe=/\((\S*)(?::(\d+))(?::(\d+))\)/,Doe=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ioe=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Noe=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-2H3QKmn4.js","./index--tr15tXr.js","./messages-CYpcciYD.js","./index-DNOzYQss.css","./publication-validation-BTZxXgFZ.js","./path-utils-CgkpwzSI.js","./conversation-input-sync-BXe0XySA.js","./error-boundary-BMkaJRQG.js","./conversation-input-sync-Dp97JwKx.css","./use-download-agent-mutation-C6dhzXX0.js","./book-open-BN9Q0QD0.js","./en-US-CW_dDnkH.js","./heart-CqKaBtlh.js","./console-mirror-QYMQ2oMk.js","./console-mirror-DOrYoP_4.css","./agent-hub-page-C9NPxFvM.js","./page-header-DKHWJJoS.js","./org-access-RJercT9z.js","./radient-auth-buttons-x4nqFWHZ.js","./org-surface-gate-D0vYcdDx.js","./building-2-DYJ6F3fw.js","./agents-page-BQ52N82v.js","./image-plus-lDPgOpNP.js","./project-markdown-DP8F_D7W.js","./schedules-page-D1DyGowS.js","./parseISO-CxPiCKvF.js","./projects-page-CAziBDff.js","./use-session-snapshot-CLpUx0Y3.js","./library-page-DYuFgJMi.js","./hash-DiimSDl0.js","./notifications-page-CR9hkgko.js","./team-bridge-page-D7gX4utS.js","./use-default-on-banner-Bd7U99zb.js","./browser-page-Bw_APhwi.js","./mesh-page-CGfJy25z.js","./settings-page-AJ0WetEN.js","./notebook-pen-BO1weM_5.js","./browser-webauthn-prompt-CJWzdqpH.js"])))=>i.map(i=>d[i]);
2
+ import{r as m,j as c,c as R,b as it,h as II,p as OX,z as LX,o as BX,A as jX,u as _u,B as HX,C as UX,E as GX,F as w_,a as VX,R as WX}from"./index--tr15tXr.js";import{t as h,c as Bm,a as $X,L as hl,b as zX}from"./messages-CYpcciYD.js";import{aA as qX,aB as y_,aC as r5,aD as i5,u as Mt,aE as KX,aF as YX,aG as XX,aH as QX,aI as JX,aJ as ZX,aK as NI,aL as PI,aM as eQ,aN as tQ,w as Fe,aO as nQ,aP as Yk,aQ as dy,aR as Fd,i as Dn,a as ss,c as Et,e as Pv,n as a5,o as oi,X as o5,aS as Da,a4 as sg,a7 as l5,C as Ua,d as rt,aT as sQ,aU as MI,aV as XC,aW as c5,aX as Xk,an as Qk,aY as rQ,G as Fi,r as Mv,aZ as $f,a_ as u5,a$ as iQ,h as zi,b0 as QC,b1 as Ov,F as No,B as nt,b2 as d5,b3 as h5,b4 as hy,b5 as Jk,b6 as aQ,S as jm,b7 as f5,b8 as oQ,b9 as lQ,ba as cQ,O as Ou,bb as uQ,M as uA,K as Lv,bc as JC,bd as qn,be as Zk,bf as OI,bg as eE,L as dQ,bh as hQ,bi as fQ,bj as pQ,g as p5,bk as gQ,bl as mQ,bm as vQ,q as Gr,bn as ac,aw as fy,b as g5,bo as LI,bp as bQ,bq as BI,br as xQ,bs as dA,a2 as _Q,bt as wQ,bu as yQ,bv as CQ,bw as SQ,bx as jI,v as hA,by as m5,ah as kQ,bz as HI,bA as py,bB as EQ,bC as TQ,bD as RQ,bE as AQ,bF as FQ,bG as v5,bH as ZC,bI as bm,bJ as DQ,bK as b5,bL as IQ,bM as UI,bN as GI,bO as Lx,bP as Bx,bQ as tE,$ as fA,bR as x5,bS as NQ,_ as PQ,Z as MQ,bT as OQ,bU as VI,bV as LQ,bW as wd,bX as kb,bY as BQ,bZ as jQ,b_ as HQ,b$ as WI,c0 as $I,c1 as UQ,c2 as GQ,c3 as VQ,c4 as WQ,c5 as zI,c6 as qI,c7 as KI,c8 as YI,c9 as $Q,ca as zQ,cb as qQ,cc as KQ,cd as YQ,ce as XI,cf as XQ,cg as QQ,ch as JQ,ci as C_,cj as ZQ,ck as QI,cl as eJ,cm as tJ,cn as nJ,co as sJ,cp as Eb,cq as rJ,cr as iJ,cs as aJ,ct as oJ,cu as _5,cv as lJ,a0 as pA,az as JI,cw as cJ,cx as uJ,cy as dJ,ay as hJ,cz as ZI,t as eN,cA as Hm,cB as fJ,cC as pJ,cD as gJ,cE as Tb,cF as mJ,cG as Rb,cH as vJ,cI as Ab,cJ as tN,cK as bJ,cL as xJ,cM as nN,cN as Fb,cO as sN,cP as Db,cQ as _J,cR as jx,x as S_,y as w5,z as wJ,ai as nE,cS as yJ,cT as CJ,cU as SJ,cV as kJ,cW as EJ,cX as TJ,cY as RJ,cZ as AJ,c_ as y5,c$ as FJ,Y as Bv,d0 as DJ,d1 as gA,a5 as IJ,d2 as NJ,d3 as PJ,a3 as MJ,d4 as OJ,d5 as LJ,d6 as rN,d7 as e1,d8 as iN,d9 as BJ,da as jJ,db as HJ,dc as UJ,dd as GJ,de as VJ,df as aN,U as WJ,dg as $J,dh as zJ,di as qJ,dj as KJ,A as YJ,dk as XJ,a1 as QJ,dl as C5,dm as JJ,dn as ZJ,dp as eZ,dq as tZ,dr as gy,ds as mA,dt as S5,du as k5,s as nZ,dv as sZ,ax as rZ,ak as je,aa as t1,am as iZ,dw as aZ,dx as oZ,dy as n1,dz as lZ,a9 as cZ,dA as oN,dB as uZ,dC as pr,W as lN,dD as dZ,dE as cN,dF as hZ,dG as E5,dH as uN,dI as fZ}from"./path-utils-CgkpwzSI.js";import{u as Ve,c as _t,z as Zu,S as On,G as Bo,B as ce,L as dr,K as bs,T as vA,b as Js,X as Xn,af as sE,ar as pZ,o as Tc,p as Rc,q as wl,J as Vi,l as Ei,r as rg,s as Fp,ak as jv,w as vt,a6 as ig,y as my,A as Rr,F as vy,Q as E0,R as T0,U as R0,V as A0,W as F0,D as Po,d as eo,e as Mo,H as dN,I as Nr,f as Jt,h as Hv,j as Lu,k as k_,as as s1,al as T5,M as R5,N as A5,O as rE,g as Hx,at as ep,aq as gZ,a7 as xh,a8 as by,a9 as Bu,au as mZ,_ as E_,t as F5,ab as xy,v as _y,av as vZ,Z as bA,C as hN,aa as bZ,ai as iE,i as xZ,aw as Ug,ax as xA,$ as _A,P as _Z,ac as wZ,ad as yZ,ae as CZ,m as SZ,n as kZ,ag as EZ,ah as TZ,ay as RZ,az as AZ,aA as D5,a as fN,x as pN,aB as Ld,am as Ib,E as FZ}from"./error-boundary-BMkaJRQG.js";import{cW as Ux,bX as Ru,ax as da,ct as wA,a$ as so,b0 as Zs,aD as nn,bn as fn,aw as Hs,aP as Ac,br as Uv,cX as DZ,bs as Gv,fA as I5,fB as IZ,fC as D0,fD as NZ,fE as PZ,fF as MZ,fG as OZ,fH as r1,fI as i1,a0 as wu,cB as Vv,eH as ed,ep as Gx,eo as LZ,en as kr,eq as Rn,fJ as N5,fK as BZ,cj as aE,bu as Uh,fL as yA,ew as wy,eU as jZ,fM as gN,fN as HZ,fO as UZ,fP as oE,fQ as GZ,fR as VZ,fS as WZ,fT as $Z,fU as T_,aU as R_,be as tp,fV as mN,fW as vN,W as I0,fX as zZ,fY as qZ,fZ as KZ,f_ as P5,f$ as YZ,g0 as XZ,g1 as M5,g2 as yy,g3 as Cy,g4 as QZ,g5 as JZ,g6 as ZZ,g7 as bN,g8 as eee,g9 as tee,ga as nee,gb as see,gc as ree,gd as iee,ge as aee,gf as oee,cL as O5,gg as lee,gh as L5,gi as cee,gj as xN,gk as uee,gl as dee,cI as ri,gm as N0,dY as B5,gn as hee,go as fee,gp as _N,gq as pee,gr as gee,gs as mee,gt as vee,gu as bee,a2 as Bd,c8 as j5,gv as Um,gw as H5,gx as xee,gy as _ee,gz as wee,gA as yee,gB as Cee,gC as See,gD as kee,bV as ju,gE as Hu,gF as Eee,aY as ag,gG as wN,gH as Tee,gI as Ree,gJ as Aee,gK as Fee,gL as Dee,gM as Iee,gN as Of,eM as Nee,gO as Pee,gP as Mee,eP as Oee,gQ as Lee,gR as Bee,gS as U5,dP as a1,gT as CA,bw as G5,gU as Sy,gV as jee,ci as lE,bp as SA,gW as V5,a1 as oc,gX as W5,bW as _h,cA as ky,gY as $5,cz as P0,gZ as Hee,c0 as Uu,cD as Ey,g_ as o1,g$ as Uee,h0 as Gee,h1 as Vee,h2 as Wee,h3 as $ee,h4 as zee,h5 as qee,h6 as Kee,h7 as Yee,h8 as yN,h9 as Xee,ha as Qee,hb as kA,hc as CN,eR as Jee,hd as Zee,he as z5,hf as ete,hg as tte,hh as q5,hi as cE,hj as nte,di as np,hk as og,hl as SN,hm as l1,hn as ste,cE as Ty,ho as rte,hp as K5,hq as uE,hr as ite,hs as Y5,ht as ate,hu as A_,hv as ote,hw as lte,hx as cte,hy as ute,hz as dte,hA as hte,hB as fte,b9 as Fs,hC as X5,b8 as So,hD as Q5,hE as pte,hF as gte,hG as kN,hH as J5,hI as Z5,hJ as e8,bZ as EA,hK as t8,hL as Gu,hM as n8,y as gt,hN as Qn,hO as F_,hP as _n,hQ as s8,hR as r8,hS as TA,hT as D_,hU as i8,hV as Ry,hW as Wv,hX as wh,O as RA,hY as dE,hZ as AA,h_ as c1,h$ as Ay,i0 as mte,i1 as ro,i2 as vte,i3 as bte,i4 as zf,i5 as hE,i6 as a8,i7 as xte,i8 as M0,i9 as Fy,ia as FA,ib as _te,ic as wte,id as yte,ie as Mn,ig as O0,ih as o8,ii as Va,ij as Cte,ik as Ste,il as l8,im as kte,io as Ete,ip as Tte,iq as Rte,ir as Ate,is as Fte,it as Dte,iu as Ite,iv as Nte,iw as Pte,ix as Mte,iy as Ote,iz as Lte,iA as Bte,iB as jte,iC as Hte,iD as Ute,iE as DA,iF as Gte,iG as EN,iH as IA,iI as Vte,iJ as c8,iK as NA,iL as Wte,cK as u8,d1 as Dy,d4 as Iy,iM as Ny,iN as lg,cs as d8,cv as $te,iO as TN,c4 as h8,iP as zte,iQ as qte,iR as Kte,iS as Yte,iT as Xte,iU as Qte,iV as Jte,iW as Zte,iX as ene,bc as Lr,dn as tne,iY as nne,iZ as sne,i_ as rne,i$ as ine,j0 as ane,j1 as one,j2 as lne,j3 as f8,j4 as cne,j5 as une,j6 as L0,j7 as PA,j8 as Py,j9 as MA,ja as dne,jb as hne,jc as fne,jd as p8,je as pne,jf as RN,jg as gne,jh as OA,ji as mne,jj as LA,jk as $v,jl as zv,jm as vne,jn as g8,jo as B0,jp as bne,jq as xne,jr as _ne,js as wne,jt as yne,ju as Cne,jv as AN,jw as m8,r as v8,jx as Sne,jy as kne,jz as Ene,jA as Tne,cH as Rne,jB as Ane,jC as sc,jD as FN,jE as Gm,jF as Gg,jG as Fne,jH as DN,jI as IN,jJ as Dne,aa as b8,c2 as Vm,jK as Ine,jL as Nne,jM as My,d7 as Pne,bo as cg,jN as Mne,jO as fE,jP as One,jQ as Lne,bt as Di,bm as Oy,dQ as ug,jR as x8,jS as BA,cw as Ly,jT as Bne,dd as jne,jU as Hne,jV as _8,jW as Au,jX as jA,jY as HA,jZ as Une,cm as w8,cn as By,j_ as Gne,cl as Dp,d8 as u1,j$ as Vne,k0 as Wne,k1 as $ne,k2 as zne,k3 as qne,k4 as Kne,k5 as Yne,k6 as zl,k7 as NN,k8 as Xne,c1 as Qne,k9 as Jne,ka as Zne,kb as ese,kc as tse,kd as nse,ke as sse,kf as pE,dw as y8,dx as I_,kg as rse,kh as C8,cN as ise,cJ as ase,ki as ose,kj as S8,kk as lse,kl as cse,cR as use,km as dse,kn as hse,ko as fse,kp as pse,kq as gse,kr as mse,eG as vse,$ as bse,ks as k8,kt as xse,ku as _se,kv as Nb,kw as E8,eD as wse,kx as th,fa as T8,fb as UA,ky as yse,kz as Cse,kA as Sse,kB as R8,M as kse,kC as Ese,bf as A8,f9 as Tse,kD as Rse,b$ as F8,kE as Ase,a4 as Fse,kF as Dse,kG as Ise,kH as Nse,kI as Pse,kJ as Mse,kK as PN,kL as d1,kM as Ose,c5 as h1,c6 as f1,c7 as p1,bd as Lse,kN as Bse,kO as jse,kP as Hse,cT as vf,kQ as bf,kR as Use,kS as Gse,kT as Vse,kU as Wse,kV as $se,kW as zse,kX as D8,kY as qse,kZ as I8,k_ as gE,k$ as mE,l0 as g1,l1 as Kse,l2 as Yse,l3 as Lf,l4 as Xse,aW as MN,l5 as ON,l6 as N8,l7 as vE,l8 as P8,l9 as M8,la as Qse,lb as Jse,lc as Zse,ld as ere,le as tre,a3 as nre,lf as sre,lg as rre,lh as ire,li as are,lj as ore,lk as lre,ll as cre,lm as ure,ln as dre,lo as hre,lp as fre,a9 as pre,a7 as gre,lq as LN,lr as mre,a8 as vre,ls as bre,lt as xre,lu as _re,a5 as wre,lv as yre,lw as Cre,lx as Sre,b3 as kre,b4 as Ere,b5 as Tre,b6 as Rre,b7 as Are,ly as Fre,lz as Dre,lA as Ire,lB as BN,eQ as O8,lC as GA,lD as Nre,bv as L8,lE as B8,lF as Pre,lG as Mre,lH as Ore,lI as Qr,lJ as Lre,lK as cu,lL as j8,lM as H8,lN as U8,lO as VA,lP as ra,lQ as Bre,lR as jre,lS as Hre,lT as Ure,lU as Gre,lV as Vre,lW as Wre,lX as $re,cc as zre,lY as qre,cY as Kre,lZ as G8,l_ as Yre,l$ as Xre,m0 as Qre,m1 as Jre,m2 as Zre,m3 as bE,m4 as eie,m5 as tie,m6 as jN,m7 as V8,m8 as nie,m9 as sie,ma as rie,mb as HN,mc as iie,md as aie,me as oie,mf as lie,mg as cie,mh as uie,mi as die,mj as hie,mk as WA,ml as fie,mm as UN,mn as Dd,mo as W8,mp as xE,mq as N_,mr as pie,ms as gie,mt as Pb,mu as xm,mv as $A,mw as $8,mx as mie,my as vie,mz as bie,mA as z8,mB as xie,mC as _ie,eF as P_,mD as wie,mE as GN,mF as yie,mG as Cie,dT as zA,dS as $r,mH as qA,dR as sp,dp as q8,dK as KA,e2 as Sie,dN as K8,du as $t,dI as Vu,dW as _E,mI as kie,mJ as Eie,mK as Tie,mL as Rie,mM as Aie,mN as Fie,mO as Die,mP as Y8,mQ as Iie,em as VN,mR as Nie,eh as Pie,df as Mie,mS as Oie,eW as Lie,mT as Bie,mU as jie,mV as Hie,eV as WN,mW as Uie,mX as Gie,mY as Vie,mZ as Wie,aZ as $ie,cr as va,m_ as zie,m$ as qie,n0 as Kie,n1 as Yie,n2 as Xie,n3 as xf,n4 as Qie,n5 as Jie,n6 as M_,n7 as Zie,n8 as eae,n9 as m1,na as v1,nb as $N,nc as b1,nd as zN,ne as X8,bl as tae,nf as Q8,ng as nae,bi as sae,bj as rae,bg as iae,bh as aae,nh as oae,bk as lae}from"./conversation-input-sync-BXe0XySA.js";import{u as J8,o as dg,b as cae,c as uae,r as Z8,d as eH,e as j0,f as dae,g as hae,s as YA,n as wE,h as fae,i as pae,p as gae,j as mae,k as vae,l as bae,q as xae,v as _ae,w as qN,x as KN,y as wae,z as yae,A as Cae,C as Sae,B as kae,D as Eae,E as Tae,F as Rae,G as Aae,H as Fae}from"./console-mirror-QYMQ2oMk.js";function YN(e,t){return e.filter(n=>!t.includes(n))}function Dae(e,t,n){const s=e.slice(0);return s[t]=n,s}var Iae=class extends qX{#s;#e;#r;#i;#t;#n;#a;#o;#l=[];constructor(e,t,n){super(),this.#s=e,this.#i=n,this.#r=[],this.#t=[],this.#e=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#t.forEach(e=>{e.subscribe(t=>{this.#h(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#t.forEach(e=>{e.destroy()})}setQueries(e,t){this.#r=e,this.#i=t,y_.batch(()=>{const n=this.#t,s=this.#d(this.#r);this.#l=s,s.forEach(o=>o.observer.setOptions(o.defaultedQueryOptions));const r=s.map(o=>o.observer),i=r.map(o=>o.getCurrentResult()),a=r.some((o,l)=>o!==n[l]);n.length===r.length&&!a||(this.#t=r,this.#e=i,this.hasListeners()&&(YN(n,r).forEach(o=>{o.destroy()}),YN(r,n).forEach(o=>{o.subscribe(l=>{this.#h(o,l)})}),this.#f()))})}getCurrentResult(){return this.#e}getQueries(){return this.#t.map(e=>e.getCurrentQuery())}getObservers(){return this.#t}getOptimisticResult(e,t){const n=this.#d(e),s=n.map(r=>r.observer.getOptimisticResult(r.defaultedQueryOptions));return[s,r=>this.#u(r??s,t),()=>this.#c(s,n)]}#c(e,t){return t.map((n,s)=>{const r=e[s];return n.defaultedQueryOptions.notifyOnChangeProps?r:n.observer.trackResult(r,i=>{t.forEach(a=>{a.observer.trackProp(i)})})})}#u(e,t){return t?((!this.#n||this.#e!==this.#o||t!==this.#a)&&(this.#a=t,this.#o=this.#e,this.#n=r5(this.#n,t(e))),this.#n):e}#d(e){const t=new Map(this.#t.map(s=>[s.options.queryHash,s])),n=[];return e.forEach(s=>{const r=this.#s.defaultQueryOptions(s),i=t.get(r.queryHash);i?n.push({defaultedQueryOptions:r,observer:i}):n.push({defaultedQueryOptions:r,observer:new i5(this.#s,r)})}),n}#h(e,t){const n=this.#t.indexOf(e);n!==-1&&(this.#e=Dae(this.#e,n,t),this.#f())}#f(){if(this.hasListeners()){const e=this.#n,t=this.#c(this.#e,this.#l),n=this.#u(t,this.#i?.combine);e!==n&&y_.batch(()=>{this.listeners.forEach(s=>{s(this.#e)})})}}};function tH({queries:e,...t},n){const s=Mt(n),r=KX(),i=YX(),a=m.useMemo(()=>e.map(b=>{const x=s.defaultQueryOptions(b);return x._optimisticResults=r?"isRestoring":"optimistic",x}),[e,s,r]);a.forEach(b=>{XX(b),QX(b,i)}),JX(i);const[o]=m.useState(()=>new Iae(s,a,t)),[l,u,d]=o.getOptimisticResult(a,t.combine),f=!r&&t.subscribed!==!1;m.useSyncExternalStore(m.useCallback(b=>f?o.subscribe(y_.batchCalls(b)):ZX,[o,f]),()=>o.getCurrentResult(),()=>o.getCurrentResult()),m.useEffect(()=>{o.setQueries(a,t)},[a,t,o]);const g=l.some((b,x)=>NI(a[x],b))?l.flatMap((b,x)=>{const _=a[x];if(_){const w=new i5(s,_);if(NI(_,b))return PI(_,w,i);eQ(b,r)&&PI(_,w,i)}return[]}):[];if(g.length>0)throw Promise.all(g);const v=l.find((b,x)=>{const _=a[x];return _&&tQ({result:b,errorResetBoundary:i,throwOnError:_.throwOnError,query:s.getQueryCache().get(_.queryHash),suspense:_.suspense})});if(v?.error)throw v.error;return u(d())}function XN(e,t){return e.findAll(t.filters).map(n=>t.select?t.select(n):n.state)}function Nae(e={},t){const n=Mt(t).getMutationCache(),s=m.useRef(e),r=m.useRef(null);return r.current||(r.current=XN(n,e)),m.useEffect(()=>{s.current=e}),m.useSyncExternalStore(m.useCallback(i=>n.subscribe(()=>{const a=r5(r.current,XN(n,s.current));r.current!==a&&(r.current=a,y_.schedule(i))}),[n]),()=>r.current,()=>r.current)}const Vx=8e3,nH=1e4;function Pae(e){return e?h("ui.notices.chat.archive_offered_title",{title:e}):h("ui.notices.chat.archive_offered_no_name")}const Mae=()=>h("ui.notices.chat.archive_offered_verb");function Oae(e){return Fe.getState().archiveFacts[e]}function Lae(e){const t=Fe.getState(),n=t.archiveFacts[e];return n?n.archived:t.sessions.find(s=>s.session_id===e)?.archived}function Bae(){const e=Fe(t=>t.archiveUndo);m.useEffect(()=>{if(e===null)return;let t=!1;const n=()=>{t||(t=!0,r())},s=()=>{n();const i=Fe.getState().archiveUndo;i!==null&&i.sessionId===e.sessionId&&i.at===e.at&&Fe.getState().setArchiveUndo(null)},r=Fe.subscribe(()=>{const i=Oae(e.sessionId);i!==void 0&&!i.answered||nQ(e.archived,Lae(e.sessionId))||s()});return n},[e])}function jae(e){return h("ui.notices.chat.drafts_offered_name",{count:e})}const Hae=e=>h("ui.notices.chat.drafts_offered_verb",{count:e}),Uae=e=>{const t=Yk(e),n=t.length,s=t.filter(o=>!o.active).length,r=n===1?"chat":"chats",i=e.filter(o=>dy(o)!==null&&Yk([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`:""}},sH=e=>h("ui.notices.chat.mark_all_read_deferred",{count:e}),Gae=e=>{if(e.attempted===0)return{tone:"success",message:h("ui.notices.chat.mark_all_read_nothing")};const t=e.unknown-e.deferred,n=[e.superseded>0?h("ui.notices.chat.mark_all_read_superseded",{count:e.superseded}):null,t>0?h("ui.notices.chat.mark_all_read_unknown",{count:t}):null,e.deferred>0?sH(e.deferred):null].filter(s=>s!==null);return e.cleared===0?{tone:"warning",message:[h("ui.notices.chat.mark_all_read_none_cleared"),...n].join(" ")}:{tone:"success",message:[h("ui.notices.chat.mark_all_read_cleared",{count:e.cleared}),...n].join(" ")}},x1="archive",QN="drafts-undo",JN="bulk-read-deferral",Vae=8e3;function Wae(){const e=Ve(),t=Fe(b=>b.archiveFailure),n=Fe(b=>b.archiveUndo),s=Fe(b=>b.draftsUndo),r=Fe(b=>b.bulkReadDeferral),i=Fe(b=>b.clearArchiveFailure),a=Fe(b=>b.setArchiveUndo),o=Fe(b=>b.setSessionArchived),l=Fe(b=>b.restoreDraftsUndo);Bae();const u=Fd(t?.title),d=m.useRef(null),f=m.useRef(null);m.useEffect(()=>{if(t===null&&n===null){if(d.current===null)return;d.current=null,f.current=null,Ux(x1);return}const b=t&&n?n.at>t.at?"offer":"failure":t?"failure":"offer",x=b==="offer"?n?.at??0:t?.at??0,_=d.current;d.current={kind:b,at:x},_!==null&&_.kind!==b&&x>_.at&&(b==="failure"?a(null):i());const w=(y,S)=>()=>{const C=Fe.getState();y==="offer"?C.archiveUndo?.at===S&&C.setArchiveUndo(null):C.archiveFailure?.at===S&&C.clearArchiveFailure();const E=d.current;E!==null&&E.kind===y&&E.at===S&&(d.current=null)};if(b==="failure"&&t){const y=f.current,S=y!==null&&y.kind==="failure"&&y.at===t.at;if(S&&y.locale===e)return;const C=S?y.raisedAt+y.duration-Date.now():nH;if(C<=0)return;f.current=S?{...y,locale:e}:{kind:"failure",at:t.at,raisedAt:Date.now(),duration:C,locale:e},Ru(`${t.archived?h("ui.notices.chat.archive_failed",{title:u}):h("ui.notices.chat.unarchive_failed",{title:u})}${t.detail?` ${t.detail}`:""}`,{id:x1,duration:C,onAutoClose:w("failure",t.at),onDismiss:w("failure",t.at),action:{label:h("ui.common.actions.retry"),onClick:E=>{E.preventDefault(),o(t.sessionId,t.archived,t.title)}}});return}if(n){const y=f.current,S=y!==null&&y.kind==="offer"&&y.at===n.at;if(S&&y.locale===e)return;const C=S?y.raisedAt+y.duration-Date.now():Vx;if(C<=0)return;f.current=S?{...y,locale:e}:{kind:"offer",at:n.at,raisedAt:Date.now(),duration:C,locale:e},da(c.jsxs("span",{className:R("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:R("min-w-0 truncate"),children:Pae(n.title)}),c.jsx("span",{className:R("shrink-0"),children:Mae()})]}),{id:x1,duration:C,classNames:{content:"min-w-0"},onAutoClose:w("offer",n.at),onDismiss:w("offer",n.at),action:{label:h("ui.notices.chat.undo"),onClick:E=>{E.preventDefault(),o(n.sessionId,!n.archived,n.title)}}})}},[e,u,t,n,a,i,o]);const p=m.useRef(!1),g=m.useRef(null);m.useEffect(()=>{if(s===null){if(!p.current)return;p.current=!1,g.current=null,Ux(QN);return}p.current=!0;const b=g.current,x=b!==null&&b.at===s.at;if(x&&b.locale===e)return;const _=x?b.raisedAt+Vx-Date.now():Vx;if(_<=0)return;g.current=x?{...b,locale:e}:{at:s.at,raisedAt:Date.now(),locale:e};const w=()=>{const y=Fe.getState();y.draftsUndo?.at===s.at&&(y.setDraftsUndo(null),p.current=!1)};da(c.jsxs("span",{className:R("flex min-w-0 items-baseline gap-1"),children:[c.jsx("span",{className:R("min-w-0 truncate"),children:jae(s.keys.length)}),c.jsx("span",{className:R("shrink-0"),children:Hae(s.keys.length)})]}),{id:QN,duration:_,classNames:{content:"min-w-0"},onAutoClose:w,onDismiss:w,action:{label:h("ui.notices.chat.undo"),onClick:y=>{y.preventDefault(),l();const S=Fe.getState(),C=S.stagedByDiscard;S.setStagedByDiscard(null),s.keys.length===1&&C!==null&&Fe.getState().activeDraftKey===C&&Fe.getState().openDraft(s.keys[0])}}})},[e,s,l]);const v=m.useRef(!1);return m.useEffect(()=>{if(r===null){if(!v.current)return;v.current=!1,Ux(JN);return}v.current=!0;const b=()=>{const x=Fe.getState();x.bulkReadDeferral?.at===r.at&&(x.clearBulkReadDeferral(),v.current=!1)};da(sH(r.count),{id:JN,duration:Vae,onAutoClose:b,onDismiss:b})},[r]),null}var Co,qe=typeof window<"u"?window:void 0,ji=typeof globalThis<"u"?globalThis:qe,rH=Array.prototype,ZN=rH.forEach,eP=rH.indexOf,ca=ji?.navigator,Pt=ji?.document,Li=ji?.location,yE=ji?.fetch,CE=ji!=null&&ji.XMLHttpRequest&&"withCredentials"in new ji.XMLHttpRequest?ji.XMLHttpRequest:void 0,tP=ji?.AbortController,or=ca?.userAgent,tn=qe??{},Jl={DEBUG:!1,LIB_VERSION:"1.235.6"},_1="$copy_autocapture",$ae=["$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"})(Co||(Co={}));var zae=["fatal","error","warning","log","info","debug"];function xn(e,t){return e.indexOf(t)!==-1}var jy=function(e){return e.trim()},XA=function(e){return e.replace(/^\$/,"")},qae=Array.isArray,iH=Object.prototype,aH=iH.hasOwnProperty,Hy=iH.toString,Ls=qae||function(e){return Hy.call(e)==="[object Array]"},Ro=e=>typeof e=="function",Bs=e=>e===Object(e)&&!Ls(e),qf=e=>{if(Bs(e)){for(var t in e)if(aH.call(e,t))return!1;return!0}return!1},Rt=e=>e===void 0,cr=e=>Hy.call(e)=="[object String]",SE=e=>cr(e)&&e.trim().length===0,td=e=>e===null,Yn=e=>Rt(e)||td(e),ki=e=>Hy.call(e)=="[object Number]",ec=e=>Hy.call(e)==="[object Boolean]",Kae=e=>e instanceof FormData,Yae=e=>xn($ae,e),oH=e=>{var t={_log:function(n){if(qe&&(Jl.DEBUG||tn.POSTHOG_DEBUG)&&!Rt(qe.console)&&qe.console){for(var s=("__rrweb_original__"in qe.console[n])?qe.console[n].__rrweb_original__:qe.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=>oH("".concat(e," ").concat(n))};return t},Ht=oH("[PostHog.js]"),li=Ht.createLogger,Xae=li("[ExternalScriptsLoader]"),nP=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return Xae.warn("".concat(t," was requested but loading of external scripts is disabled.")),n("Loading of external scripts is disabled");var s=Pt?.querySelectorAll("script");if(s){for(var r=0;r<s.length;r++)if(s[r].src===t)return n()}var i=()=>{if(!Pt)return n("document not found");var a=Pt.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=Pt.querySelectorAll("body > script");l.length>0?(o=l[0].parentNode)===null||o===void 0||o.insertBefore(a,l[0]):Pt.body.appendChild(a)};Pt!=null&&Pt.body?i():Pt?.addEventListener("DOMContentLoaded",i)};function sP(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 Ze(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?sP(Object(n),!0).forEach(function(s){yt(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sP(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function yt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lH(e,t){if(e==null)return{};var n,s,r=function(a,o){if(a==null)return{};var l,u,d={},f=Object.keys(a);for(u=0;u<f.length;u++)l=f[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}tn.__PosthogExtensions__=tn.__PosthogExtensions__||{},tn.__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);nP(e,a,n)},tn.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var s=e.requestRouter.endpointFor("api",t);nP(e,s,n)};var O_={};function Fu(e,t,n){if(Ls(e)){if(ZN&&e.forEach===ZN)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)===O_)return}}}function as(e,t,n){if(!Yn(e)){if(Ls(e))return Fu(e,t,n);if(Kae(e)){for(var s of e.entries())if(t.call(n,s[1],s[0])===O_)return}else for(var r in e)if(aH.call(e,r)&&t.call(n,e[r],r)===O_)return}}var qs=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 Fu(n,function(r){for(var i in r)r[i]!==void 0&&(e[i]=r[i])}),e},Wx=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 Fu(n,function(r){Fu(r,function(i){e.push(i)})}),e};function $x(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 rP=function(e){try{return e()}catch{return}},Qae=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){Ht.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ht.critical(r)}}},H0=function(e){var t={};return as(e,function(n,s){cr(n)&&n.length>0&&(t[s]=n)}),t};function Jae(e,t){return n=e,s=i=>cr(i)&&!td(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),Ls(a)?(l=[],Fu(a,u=>{l.push(i(u))})):(l={},as(a,(u,d)=>{r.has(u)||(l[d]=i(u,d))})),l);var l}(n);var n,s,r}var Zae=["herokuapp.com","vercel.app","netlify.app"];function eoe(e){var t=e?.hostname;if(!cr(t))return!1;var n=t.split(".").slice(-2).join(".");for(var s of Zae)if(n===s)return!1;return!0}function cH(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n]}function Ys(e,t,n,s){var{capture:r=!1,passive:i=!0}=s??{};e?.addEventListener(t,n,{capture:r,passive:i})}var uH="$people_distinct_id",_m="__alias",wm="__timers",iP="$autocapture_disabled_server_side",kE="$heatmaps_enabled_server_side",aP="$exception_capture_enabled_server_side",oP="$web_vitals_enabled_server_side",dH="$dead_clicks_enabled_server_side",lP="$web_vitals_allowed_metrics",EE="$session_recording_enabled_server_side",cP="$console_log_recording_enabled_server_side",uP="$session_recording_network_payload_capture",dP="$session_recording_masking",hP="$session_recording_canvas_recording",fP="$replay_sample_rate",pP="$replay_minimum_duration",gP="$replay_script_config",L_="$sesid",ym="$session_is_sampled",w1="$session_recording_url_trigger_activated_session",y1="$session_recording_event_trigger_activated_session",Kf="$enabled_feature_flags",zx="$early_access_features",TE="$feature_flag_details",Cm="$stored_person_properties",Id="$stored_group_properties",RE="$surveys",Mb="$surveys_activated",B_="$flag_call_reported",Yl="$user_state",AE="$client_session_props",FE="$capture_rate_limit",DE="$initial_campaign_params",IE="$initial_referrer_info",NE="$initial_person_info",j_="$epp",hH="__POSTHOG_TOOLBAR__",mP="$posthog_cookieless",toe=[uH,_m,"__cmpns",wm,EE,kE,L_,Kf,Yl,zx,TE,Id,Cm,RE,B_,AE,FE,DE,IE,j_];function vP(e){var t;return e instanceof Element&&(e.id===hH||!((t=e.closest)===null||t===void 0||!t.call(e,".toolbar-global-fade-container")))}function Uy(e){return!!e&&e.nodeType===1}function Du(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function fH(e){return!!e&&e.nodeType===3}function pH(e){return!!e&&e.nodeType===11}function QA(e){return e?jy(e).split(/\s+/):[]}function bP(e){var t=qe?.location.href;return!!(t&&e&&e.some(n=>t.match(n)))}function H_(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 QA(t)}function gH(e){return Yn(e)?null:jy(e).split(/(\s+)/).filter(t=>Ip(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Gy(e){var t="";return ME(e)&&!bH(e)&&e.childNodes&&e.childNodes.length&&as(e.childNodes,function(n){var s;fH(n)&&n.textContent&&(t+=(s=gH(n.textContent))!==null&&s!==void 0?s:"")}),jy(t)}function mH(e){return Rt(e.target)?e.srcElement||null:(t=e.target)!==null&&t!==void 0&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var PE=["a","button","form","input","select","textarea","label"];function vH(e){var t=e.parentNode;return!(!t||!Uy(t))&&t}function noe(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(!qe||!e||Du(e,"html")||!Uy(e)||n!=null&&n.url_allowlist&&!bP(n.url_allowlist)||n!=null&&n.url_ignorelist&&bP(n.url_ignorelist))return!1;if(n!=null&&n.dom_event_allowlist){var i=n.dom_event_allowlist;if(i&&!i.some(g=>t.type===g))return!1}for(var a=!1,o=[e],l=!0,u=e;u.parentNode&&!Du(u,"body");)if(pH(u.parentNode))o.push(u.parentNode.host),u=u.parentNode.host;else{if(!(l=vH(u)))break;if(s||PE.indexOf(l.tagName.toLowerCase())>-1)a=!0;else{var d=qe.getComputedStyle(l);d&&d.getPropertyValue("cursor")==="pointer"&&(a=!0)}o.push(l),u=l}if(!function(g,v){var b=v?.element_allowlist;if(Rt(b))return!0;var x=function(y){if(b.some(S=>y.tagName.toLowerCase()===S))return{v:!0}};for(var _ of g){var w=x(_);if(typeof w=="object")return w.v}return!1}(o,n)||!function(g,v){var b=v?.css_selector_allowlist;if(Rt(b))return!0;var x=function(y){if(b.some(S=>y.matches(S)))return{v:!0}};for(var _ of g){var w=x(_);if(typeof w=="object")return w.v}return!1}(o,n))return!1;var f=qe.getComputedStyle(e);if(f&&f.getPropertyValue("cursor")==="pointer"&&t.type==="click")return!0;var p=e.tagName.toLowerCase();switch(p){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&&(PE.indexOf(p)>-1||e.getAttribute("contenteditable")==="true")}}function ME(e){for(var t=e;t.parentNode&&!Du(t,"body");t=t.parentNode){var n=H_(t);if(xn(n,"ph-sensitive")||xn(n,"ph-no-capture"))return!1}if(xn(H_(e),"ph-include"))return!0;var s=e.type||"";if(cr(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var r=e.name||e.id||"";return!(cr(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 bH(e){return!!(Du(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Du(e,"select")||Du(e,"textarea")||e.getAttribute("contenteditable")==="true")}var xH="(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})",soe=new RegExp("^(?:".concat(xH,")$")),roe=new RegExp(xH),_H="\\d{3}-?\\d{2}-?\\d{4}",ioe=new RegExp("^(".concat(_H,")$")),aoe=new RegExp("(".concat(_H,")"));function Ip(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return!(Yn(e)||cr(e)&&(e=jy(e),(t?soe:roe).test((e||"").replace(/[- ]/g,""))||(t?ioe:aoe).test(e)))}function wH(e){var t=Gy(e);return Ip(t="".concat(t," ").concat(yH(e)).trim())?t:""}function yH(e){var t="";return e&&e.childNodes&&e.childNodes.length&&as(e.childNodes,function(n){var s;if(n&&((s=n.tagName)===null||s===void 0?void 0:s.toLowerCase())==="span")try{var r=Gy(n);t="".concat(t," ").concat(r).trim(),n.childNodes&&n.childNodes.length&&(t="".concat(t," ").concat(yH(n)).trim())}catch(i){Ht.error("[AutoCapture]",i)}}),t}function ooe(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=Ze(Ze(Ze(Ze({},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 $x(l).sort((d,f)=>{var[p]=d,[g]=f;return p.localeCompare(g)}).forEach(d=>{var[f,p]=d;return u[xP(f.toString())]=xP(p.toString())}),a+=":",a+=$x(l).map(d=>{var[f,p]=d;return"".concat(f,'="').concat(p,'"')}).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:loe(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return $x(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 xP(e){return e.replace(/"|\\"/g,'\\"')}function loe(e){var t=e.attr__class;return t?Ls(t)?t:QA(t):void 0}class CH{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 coe=["localhost","127.0.0.1"],rp=e=>{var t=Pt?.createElement("a");return Rt(t)?null:(t.href=e,t)},uoe=function(e){var t,n,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",r=[];return as(e,function(i,a){Rt(i)||Rt(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)},U_=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(!Ls(n)||n.length<2)return"";var a=n[1];try{a=decodeURIComponent(a)}catch{Ht.error("Skipping decoding for malformed query param: "+a)}return a.replace(/\+/g," ")},C1=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=[],f=0;f<u.length;f++){var p=u[f].split("=");Ls(p)&&(t.includes(p[0])?d.push(p[0]+"="+n):d.push(u[f]))}var g=l;return o!=null&&(g+="?"+d.join("&")),i!=null&&(g+="#"+i),g},G_=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},_P=li("[AutoCapture]");function S1(e,t){return t.length>e?t.slice(0,e)+"...":t}function doe(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!Uy(t));return t}function hoe(e,t,n,s){var r=e.tagName.toLowerCase(),i={tag_name:r};PE.indexOf(r)>-1&&!n&&(r.toLowerCase()==="a"||r.toLowerCase()==="button"?i.$el_text=S1(1024,wH(e)):i.$el_text=S1(1024,Gy(e)));var a=H_(e);a.length>0&&(i.classes=a.filter(function(d){return d!==""})),as(e.attributes,function(d){var f;if((!bH(e)||["name","id","class","aria-label"].indexOf(d.name)!==-1)&&(s==null||!s.includes(d.name))&&!t&&Ip(d.value)&&(f=d.name,!cr(f)||f.substring(0,10)!=="_ngcontent"&&f.substring(0,7)!=="_nghost")){var p=d.value;d.name==="class"&&(p=QA(p).join(" ")),i["attr__"+d.name]=S1(1024,p)}});for(var o=1,l=1,u=e;u=doe(u);)o++,u.tagName===e.tagName&&l++;return i.nth_child=o,i.nth_of_type=l,i}function foe(e,t){for(var n,s,{e:r,maskAllElementAttributes:i,maskAllText:a,elementAttributeIgnoreList:o,elementsChainAsString:l}=t,u=[e],d=e;d.parentNode&&!Du(d,"body");)pH(d.parentNode)?(u.push(d.parentNode.host),d=d.parentNode.host):(u.push(d.parentNode),d=d.parentNode);var f,p=[],g={},v=!1,b=!1;if(as(u,S=>{var C=ME(S);S.tagName.toLowerCase()==="a"&&(v=S.getAttribute("href"),v=C&&v&&Ip(v)&&v),xn(H_(S),"ph-no-capture")&&(b=!0),p.push(hoe(S,i,a,o));var E=function(k){if(!ME(k))return{};var F={};return as(k.attributes,function(A){if(A.name&&A.name.indexOf("data-ph-capture-attribute")===0){var I=A.name.replace("data-ph-capture-attribute-",""),N=A.value;I&&N&&Ip(N)&&(F[I]=N)}}),F}(S);qs(g,E)}),b)return{props:{},explicitNoCapture:b};if(a||(e.tagName.toLowerCase()==="a"||e.tagName.toLowerCase()==="button"?p[0].$el_text=wH(e):p[0].$el_text=Gy(e)),v){var x,_;p[0].attr__href=v;var w=(x=rp(v))===null||x===void 0?void 0:x.host,y=qe==null||(_=qe.location)===null||_===void 0?void 0:_.host;w&&y&&w!==y&&(f=v)}return{props:qs({$event_type:r.type,$ce_version:1},l?{}:{$elements:p},{$elements_chain:ooe(p)},(n=p[0])!==null&&n!==void 0&&n.$el_text?{$el_text:(s=p[0])===null||s===void 0?void 0:s.$el_text}:{},f&&r.type==="click"?{$external_click_url:f}:{},g)}}let poe=class{constructor(t){yt(this,"_initialized",!1),yt(this,"_isDisabledServerSide",null),yt(this,"rageclicks",new CH),yt(this,"_elementsChainAsString",!1),this.instance=t,this._elementSelectors=null}get config(){var t,n,s=Bs(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(qe&&Pt){var t=s=>{s=s||qe?.event;try{this._captureEvent(s)}catch(r){_P.error("Failed to capture event",r)}};if(Ys(Pt,"submit",t,{capture:!0}),Ys(Pt,"change",t,{capture:!0}),Ys(Pt,"click",t,{capture:!0}),this.config.capture_copied_text){var n=s=>{s=s||qe?.event,this._captureEvent(s,_1)};Ys(Pt,"copy",n,{capture:!0}),Ys(Pt,"cut",n,{capture:!0})}}}else _P.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({[iP]:!!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=Pt?.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[iP],r=this._isDisabledServerSide;if(td(r)&&!ec(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=mH(t);fH(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===_1;if(r&&noe(r,t,this.config,i,i?["copy","cut"]:void 0)){var{props:a,explicitNoCapture:o}=foe(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===_1){var u,d=gH(qe==null||(u=qe.getSelection())===null||u===void 0?void 0:u.toString()),f=t.type||"clipboard";if(!d)return!1;a.$selected_content=d,a.$copy_type=f}return this.instance.capture(n,a),!0}}}isBrowserSupported(){return Ro(Pt?.querySelectorAll)}};Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return ki(e)&&isFinite(e)&&Math.floor(e)===e});var wP="0123456789abcdef";let goe=class OE{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 OE(i)}toString(){for(var t="",n=0;n<this.bytes.length;n++)t=t+wP.charAt(this.bytes[n]>>>4)+wP.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 OE(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}},moe=class{constructor(){yt(this,"timestamp",0),yt(this,"counter",0),yt(this,"random",new voe)}generate(){var t=this.generateOrAbort();if(Rt(t)){this.timestamp=0;var n=this.generateOrAbort();if(Rt(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 goe.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 yP,SH=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};qe&&!Rt(qe.crypto)&&crypto.getRandomValues&&(SH=e=>crypto.getRandomValues(e));let voe=class{constructor(){yt(this,"buffer",new Uint32Array(8)),yt(this,"cursor",1/0)}nextUint32(){return this.cursor>=this.buffer.length&&(SH(this.buffer),this.cursor=0),this.buffer[this.cursor++]}};var yu=()=>boe().toString(),boe=()=>(yP||(yP=new moe)).generate(),xoe="Thu, 01 Jan 1970 00:00:00 GMT",Vg="",_oe=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function woe(e,t){if(t){var n=function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt;if(Vg)return Vg;if(!i||["localhost","127.0.0.1"].includes(r))return"";for(var a=r.split("."),o=Math.min(a.length,8),l="dmn_chk_"+yu(),u=new RegExp("(^|;)\\s*"+l+"=1");!Vg&&o--;){var d=a.slice(o).join("."),f=l+"=1;domain=."+d;i.cookie=f,u.test(i.cookie)&&(i.cookie=f+";expires="+xoe,Vg=d)}return Vg}(e);if(!n){var s=(r=>{var i=r.match(_oe);return i?i[0]:""})(e);s!==n&&Ht.info("Warning: cookie subdomain discovery mismatch",s,n),n=s}return n?"; domain=."+n:""}return""}var gu,lc={is_supported:()=>!!Pt,error:function(e){Ht.error("cookieStore error: "+e)},get:function(e){if(Pt){try{for(var t=e+"=",n=Pt.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(lc.get(e))||{}}catch{}return t},set:function(e,t,n,s,r){if(Pt)try{var i="",a="",o=woe(Pt.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&&Ht.warn("cookieStore warning: large cookie, len="+u.length),Pt.cookie=u,u}catch{return}},remove:function(e,t){try{lc.set(e,"",-1,t)}catch{return}}},k1=null,gr={is_supported:function(){if(!td(k1))return k1;var e=!0;if(Rt(qe))e=!1;else try{var t="__mplssupport__";gr.set(t,"xyz"),gr.get(t)!=='"xyz"'&&(e=!1),gr.remove(t)}catch{e=!1}return e||Ht.error("localStorage unsupported; falling back to cookie store"),k1=e,e},error:function(e){Ht.error("localStorage error: "+e)},get:function(e){try{return qe?.localStorage.getItem(e)}catch(t){gr.error(t)}return null},parse:function(e){try{return JSON.parse(gr.get(e))||{}}catch{}return null},set:function(e,t){try{qe?.localStorage.setItem(e,JSON.stringify(t))}catch(n){gr.error(n)}},remove:function(e){try{qe?.localStorage.removeItem(e)}catch(t){gr.error(t)}}},yoe=["distinct_id",L_,ym,j_,NE],Ob=Ze(Ze({},gr),{},{parse:function(e){try{var t={};try{t=lc.parse(e)||{}}catch{}var n=qs(t,JSON.parse(gr.get(e)||"{}"));return gr.set(e,n),n}catch{}return null},set:function(e,t,n,s,r,i){try{gr.set(e,t,void 0,void 0,i);var a={};yoe.forEach(o=>{t[o]&&(a[o]=t[o])}),Object.keys(a).length&&lc.set(e,a,n,s,r,i)}catch(o){gr.error(o)}},remove:function(e,t){try{qe?.localStorage.removeItem(e),lc.remove(e,t)}catch(n){gr.error(n)}}}),Lb={},Coe={is_supported:function(){return!0},error:function(e){Ht.error("memoryStorage error: "+e)},get:function(e){return Lb[e]||null},parse:function(e){return Lb[e]||null},set:function(e,t){Lb[e]=t},remove:function(e){delete Lb[e]}},yd=null,Br={is_supported:function(){if(!td(yd))return yd;if(yd=!0,Rt(qe))yd=!1;else try{var e="__support__";Br.set(e,"xyz"),Br.get(e)!=='"xyz"'&&(yd=!1),Br.remove(e)}catch{yd=!1}return yd},error:function(e){Ht.error("sessionStorage error: ",e)},get:function(e){try{return qe?.sessionStorage.getItem(e)}catch(t){Br.error(t)}return null},parse:function(e){try{return JSON.parse(Br.get(e))||null}catch{}return null},set:function(e,t){try{qe?.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){Br.error(n)}},remove:function(e){try{qe?.sessionStorage.removeItem(e)}catch(t){Br.error(t)}}};(function(e){e[e.PENDING=-1]="PENDING",e[e.DENIED=0]="DENIED",e[e.GRANTED=1]="GRANTED"})(gu||(gu={}));let Soe=class{constructor(t){this.instance=t}get config(){return this.instance.config}get consent(){return this.getDnt()?gu.DENIED:this.storedConsent}isOptedOut(){return this.consent===gu.DENIED||this.consent===gu.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"?gu.GRANTED:t==="0"?gu.DENIED:gu.PENDING}get storage(){if(!this._storage){var t=this.config.opt_out_capturing_persistence_type;this._storage=t==="localStorage"?gr:lc;var n=t==="localStorage"?lc:gr;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&&!!cH([ca?.doNotTrack,ca?.msDoNotTrack,tn.doNotTrack],t=>xn([!0,1,"1","yes"],t))}};var Bb=li("[Dead Clicks]"),koe=()=>!0,Eoe=e=>{var t,n=!((t=e.instance.persistence)===null||t===void 0||!t.get_property(dH)),s=e.instance.config.capture_dead_clicks;return ec(s)?s:n};let kH=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({[dH]:t?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.loadScript(()=>{this.start()})}loadScript(t){var n,s,r;(n=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.initDeadClicksAutocapture&&t(),(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"dead-clicks-autocapture",i=>{i?Bb.error("failed to load script",i):t()})}start(){var t;if(Pt){if(!this._lazyLoadedDeadClicksAutocapture&&(t=tn.__PosthogExtensions__)!==null&&t!==void 0&&t.initDeadClicksAutocapture){var n=Bs(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this._lazyLoadedDeadClicksAutocapture=tn.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this._lazyLoadedDeadClicksAutocapture.start(Pt),Bb.info("starting...")}}else Bb.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,Bb.info("stopping..."))}};var E1=li("[ExceptionAutocapture]");let Toe=class{constructor(t){var n;yt(this,"startCapturing",()=>{var s;if(qe&&this.isEnabled&&(s=tn.__PosthogExtensions__)!==null&&s!==void 0&&s.errorWrappingFunctions){var r=tn.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=tn.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=tn.__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){E1.error("failed to start",o),this.stopCapturing()}}}),this.instance=t,this.remoteEnabled=!((n=this.instance.persistence)===null||n===void 0||!n.props[aP]),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 Bs(t)?n=Ze(Ze({},n),t):(Rt(t)?this.remoteEnabled:t)&&(n=Ze(Ze({},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&&(E1.info("enabled"),this.loadScript(this.startCapturing))}loadScript(t){var n,s,r;(n=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.errorWrappingFunctions&&t(),(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"exception-autocapture",i=>{if(i)return E1.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({[aP]: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 EH(e){return!Rt(Event)&&TH(e,Event)}function TH(e,t){try{return e instanceof t}catch{return!1}}function qx(e,t){return Object.prototype.toString.call(e)==="[object ".concat(t,"]")}function T1(e){return qx(e,"DOMError")}var CP=/\(error: (.*)\)/,SP=50,Yf="?";function R1(e,t,n,s){var r={platform:"web:javascript",filename:e,function:t==="<anonymous>"?Yf:t,in_app:!0};return Rt(n)||(r.lineno=n),Rt(s)||(r.colno=s),r}var Roe=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Aoe=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Foe=/\((\S*)(?::(\d+))(?::(\d+))\)/,Doe=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ioe=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Noe=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=CP.test(u)?u.replace(CP,"$1"):u;if(!d.match(/\S*Error: /)){for(var f of s){var p=f(d);if(p){a.push(p);break}}if(a.length>=SP)break}}}return function(g){if(!g.length)return[];var v=Array.from(g);return v.reverse(),v.slice(0,SP).map(b=>Ze(Ze({},b),{},{filename:b.filename||Poe(v).filename,function:b.function||Yf}))}(a)}}([30,e=>{var t=Roe.exec(e);if(t){var[,n,s,r]=t;return R1(n,Yf,+s,+r)}var i=Aoe.exec(e);if(i){if(i[2]&&i[2].indexOf("eval")===0){var a=Foe.exec(i[2]);a&&(i[2]=a[1],i[3]=a[2],i[4]=a[3])}var[o,l]=EP(i[1]||Yf,i[2]);return R1(l,o,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}}],[50,e=>{var t=Doe.exec(e);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){var n=Ioe.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]||Yf;return[r,s]=EP(r,s),R1(s,r,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]);function Poe(e){return e[e.length-1]||{}}var jb,kP,A1,EP=(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]:Yf,n?"safari-extension:".concat(t):"safari-web-extension:".concat(t)]:[e,t]},Moe=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;function JA(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=e.stacktrace||e.stack||"",s=function(a){return a&&Ooe.test(a.message)?1:0}(e);try{var r=Noe,i=function(a,o){var l=function(u){var d=globalThis._posthogChunkIds;if(!d)return{};var f=Object.keys(d);return A1&&f.length===kP||(kP=f.length,A1=f.reduce((p,g)=>{jb||(jb={});var v=jb[g];if(v)p[v[0]]=v[1];else for(var b=u(g),x=b.length-1;x>=0;x--){var _=b[x],w=_?.filename,y=d[g];if(w&&y){p[w]=y,jb[g]=[w,y];break}}return p},{})),A1}(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 Ooe=/Minified React error #\d+;/i;function F1(e,t){var n,s,r=JA(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 D1(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=JA(t.syntheticException,1);l.length&&(o.stacktrace={frames:l,type:"raw"})}return{$exception_list:[o],$exception_level:"error"}}function Loe(e){return cr(e)&&!SE(e)&&zae.indexOf(e)>=0}function Boe(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:EH(e)?e.constructor.name:"Error",o="Non-Error 'exception' captured with keys: ".concat(function(d){var f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:40,p=Object.keys(d);if(p.sort(),!p.length)return"[object has no keys]";for(var g=p.length;g>0;g--){var v=p.slice(0,g).join(", ");if(!(v.length>f))return g===p.length||v.length<=f?v:"".concat(v.slice(0,f),"...")}return""}(e)),l={type:a,value:o,mechanism:{handled:r,synthetic:i}};if(t!=null&&t.syntheticException){var u=JA(t?.syntheticException,1);u.length&&(l.stacktrace={frames:u,type:"raw"})}return{$exception_list:[l],$exception_level:Loe(e.level)?e.level:"error"}}function joe(e,t){var{error:n,event:s}=e,r={$exception_list:[]},i=n||s;if(T1(i)||function(g){return qx(g,"DOMException")}(i)){var a=i;if(function(g){return"stack"in g}(i))r=F1(i,t);else{var o=a.name||(T1(a)?"DOMError":"DOMException"),l=a.message?"".concat(o,": ").concat(a.message):o,u=T1(a)?"DOMError":"DOMException";r=D1(l,Ze(Ze({},t),{},{overrideExceptionType:u,defaultExceptionMessage:l}))}return"code"in a&&(r.$exception_DOMException_code="".concat(a.code)),r}if(function(g){return qx(g,"ErrorEvent")}(i)&&i.error)return F1(i.error,t);if(function(g){switch(Object.prototype.toString.call(g)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":return!0;default:return TH(g,Error)}}(i))return F1(i,t);if(function(g){return qx(g,"Object")}(i)||EH(i))return Boe(i,t);if(Rt(n)&&cr(s)){var d="Error",f=s,p=s.match(Moe);return p&&(d=p[1],f=p[2]),D1(f,Ze(Ze({},t),{},{overrideExceptionType:d,defaultExceptionMessage:f}))}return D1(i,t)}function V_(e){var t,n;return((t=JSON.stringify(e,(n=[],function(s,r){if(Bs(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 LE(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[LE({size:V_(s),data:s,sessionId:e.sessionId,windowId:e.windowId}),LE({size:V_(r),data:r,sessionId:e.sessionId,windowId:e.windowId})].flatMap(i=>i)}return[e]}var Xl=(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))(Xl||{}),_o=(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))(_o||{}),BE="[SessionRecording]",jE="redacted",Hb={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"]},Hoe=["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"],Uoe=["password","secret","passwd","api_key","apikey","auth","credentials","mysql_pwd","privatekey","private_key","token"],Goe=["/s/","/e/","/i/"];function TP(e,t,n,s){if(Yn(e))return e;var r=t?.["content-length"]||function(i){return new Blob([i]).size}(e);return cr(r)&&(r=parseInt(r)),r>n?BE+" ".concat(s," body too large to record (").concat(r," bytes)"):e}function RP(e,t){if(Yn(e))return e;var n=e;return Ip(n,!1)||(n=BE+" "+t+" body "+jE),as(Uoe,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=BE+" "+t+" body "+jE+" as might contain: "+s)}),n}var Voe=(e,t)=>{var n,s,r,i={payloadSizeLimitBytes:Hb.payloadSizeLimitBytes,performanceEntryTypeToObserve:[...Hb.performanceEntryTypeToObserve],payloadHostDenyList:[...t.payloadHostDenyList||[],...Hb.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),p=>(p!=null&&p.requestBody&&(p.requestBody=TP(p.requestBody,p.requestHeaders,r,"Request")),p!=null&&p.responseBody&&(p.responseBody=TP(p.responseBody,p.responseHeaders,r,"Response")),p)),d=p=>{return u(((b,x)=>{var _,w=rp(b.name),y=x.indexOf("http")===0?(_=rp(x))===null||_===void 0?void 0:_.pathname:x;y==="/"&&(y="");var S=w?.pathname.replace(y||"","");if(!(w&&S&&Goe.some(C=>S.indexOf(C)===0)))return b})((v=(g=p).requestHeaders,Yn(v)||as(Object.keys(v??{}),b=>{Hoe.includes(b.toLowerCase())&&(v[b]=jE)}),g),e.api_host));var g,v},f=Ro(e.session_recording.maskNetworkRequestFn);return f&&Ro(e.session_recording.maskCapturedNetworkRequestFn)&&Ht.warn("Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored."),f&&(e.session_recording.maskCapturedNetworkRequestFn=p=>{var g=e.session_recording.maskNetworkRequestFn({url:p.name});return Ze(Ze({},p),{},{name:g?.url})}),i.maskRequestFn=Ro(e.session_recording.maskCapturedNetworkRequestFn)?p=>{var g,v,b,x=d(p);return x&&(g=(v=(b=e.session_recording).maskCapturedNetworkRequestFn)===null||v===void 0?void 0:v.call(b,x))!==null&&g!==void 0?g:void 0}:p=>function(g){if(!Rt(g))return g.requestBody=RP(g.requestBody,"Request"),g.responseBody=RP(g.responseBody,"Response"),g}(d(p)),Ze(Ze(Ze({},Hb),i),{},{recordHeaders:a,recordBody:o,recordPerformance:l,recordInitialRequests:l})};function Wa(e,t,n,s,r){return t>n&&(Ht.warn("min cannot be greater than max."),t=n),ki(e)?e>n?(s&&Ht.warn(s+" cannot be greater than max: "+n+". Using max value instead."),n):e<t?(s&&Ht.warn(s+" cannot be less than min: "+t+". Using min value instead."),t):e:(s&&Ht.warn(s+" must be a number. using max or fallback. max: "+n+", fallback: "+r),Wa(r||n,t,n,s))}let Woe=class{constructor(t){var n,s,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};yt(this,"bucketSize",100),yt(this,"refillRate",10),yt(this,"mutationBuckets",{}),yt(this,"loggedTracker",{}),yt(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]})}),yt(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]}),yt(this,"numberOfChanges",i=>{var a,o,l,u,d,f,p,g;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=(f=i.texts)===null||f===void 0?void 0:f.length)!==null&&d!==void 0?d:0)+((p=(g=i.adds)===null||g===void 0?void 0:g.length)!==null&&p!==void 0?p:0)}),yt(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,f,p,[g,v]=this.getNodeOrRelevantParent(u.id);return this.mutationBuckets[g]===0?!1:(this.mutationBuckets[g]=(d=this.mutationBuckets[g])!==null&&d!==void 0?d:this.bucketSize,this.mutationBuckets[g]=Math.max(this.mutationBuckets[g]-1,0),this.mutationBuckets[g]===0&&(this.loggedTracker[g]||(this.loggedTracker[g]=!0,(f=(p=this.options).onBlockedNode)===null||f===void 0||f.call(p,g,v))),u)}));var l=this.numberOfChanges(a);return l!==0||o===l?i:void 0}),this.rrweb=t,this.options=r,this.refillRate=Wa((n=this.options.refillRate)!==null&&n!==void 0?n:this.refillRate,0,100,"mutation throttling refill rate"),this.bucketSize=Wa((s=this.options.bucketSize)!==null&&s!==void 0?s:this.bucketSize,0,100,"mutation throttling bucket size"),setInterval(()=>{this.refillBuckets()},1e3)}};var Ya=Uint8Array,Hi=Uint16Array,Np=Uint32Array,ZA=new Ya([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]),e2=new Ya([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]),AP=new Ya([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),RH=function(e,t){for(var n=new Hi(31),s=0;s<31;++s)n[s]=t+=1<<e[s-1];var r=new Np(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]},AH=RH(ZA,2),$oe=AH[0],HE=AH[1];$oe[28]=258,HE[258]=28;for(var FP=RH(e2,0)[1],FH=new Hi(32768),fs=0;fs<32768;++fs){var Cd=(43690&fs)>>>1|(21845&fs)<<1;Cd=(61680&(Cd=(52428&Cd)>>>2|(13107&Cd)<<2))>>>4|(3855&Cd)<<4,FH[fs]=((65280&Cd)>>>8|(255&Cd)<<8)>>>1}var Wm=function(e,t,n){for(var s=e.length,r=0,i=new Hi(t);r<s;++r)++i[e[r]-1];var a,o=new Hi(t);for(r=0;r<t;++r)o[r]=o[r-1]+i[r-1]<<1;for(a=new Hi(s),r=0;r<s;++r)a[r]=FH[o[e[r]-1]++]>>>15-e[r];return a},yh=new Ya(288);for(fs=0;fs<144;++fs)yh[fs]=8;for(fs=144;fs<256;++fs)yh[fs]=9;for(fs=256;fs<280;++fs)yh[fs]=7;for(fs=280;fs<288;++fs)yh[fs]=8;var W_=new Ya(32);for(fs=0;fs<32;++fs)W_[fs]=5;var zoe=Wm(yh,9),qoe=Wm(W_,5),DH=function(e){return(e/8>>0)+(7&e&&1)},IH=function(e,t,n){(n==null||n>e.length)&&(n=e.length);var s=new(e instanceof Hi?Hi:e instanceof Np?Np:Ya)(n-t);return s.set(e.subarray(t,n)),s},ql=function(e,t,n){n<<=7&t;var s=t/8>>0;e[s]|=n,e[s+1]|=n>>>8},Wg=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},I1=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 Ya(0),0];if(r==1){var a=new Ya(n[0].s+1);return a[n[0].s]=1,[a,1]}n.sort(function(C,E){return C.f-E.f}),n.push({s:-1,f:25001});var o=n[0],l=n[1],u=0,d=1,f=2;for(n[0]={s:-1,f:o.f+l.f,l:o,r:l};d!=r-1;)o=n[n[u].f<n[f].f?u++:f++],l=n[u!=d&&n[u].f<n[f].f?u++:f++],n[d++]={s:-1,f:o.f+l.f,l:o,r:l};var p=i[0].s;for(s=1;s<r;++s)i[s].s>p&&(p=i[s].s);var g=new Hi(p+1),v=UE(n[d-1],g,0);if(v>t){s=0;var b=0,x=v-t,_=1<<x;for(i.sort(function(C,E){return g[E.s]-g[C.s]||C.f-E.f});s<r;++s){var w=i[s].s;if(!(g[w]>t))break;b+=_-(1<<v-g[w]),g[w]=t}for(b>>>=x;b>0;){var y=i[s].s;g[y]<t?b-=1<<t-g[y]++-1:++s}for(;s>=0&&b;--s){var S=i[s].s;g[S]==t&&(--g[S],++b)}v=t}return[new Ya(g),v]},UE=function(e,t,n){return e.s==-1?Math.max(UE(e.l,t,n+1),UE(e.r,t,n+1)):t[e.s]=n},DP=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Hi(++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]},$g=function(e,t){for(var n=0,s=0;s<t.length;++s)n+=e[s]*t[s];return n},GE=function(e,t,n){var s=n.length,r=DH(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)},IP=function(e,t,n,s,r,i,a,o,l,u,d){ql(t,d++,n),++r[256];for(var f=I1(r,15),p=f[0],g=f[1],v=I1(i,15),b=v[0],x=v[1],_=DP(p),w=_[0],y=_[1],S=DP(b),C=S[0],E=S[1],k=new Hi(19),F=0;F<w.length;++F)k[31&w[F]]++;for(F=0;F<C.length;++F)k[31&C[F]]++;for(var A=I1(k,7),I=A[0],N=A[1],P=19;P>4&&!I[AP[P-1]];--P);var M,Y,O,X,Q=u+5<<3,ie=$g(r,yh)+$g(i,W_)+a,G=$g(r,p)+$g(i,b)+a+14+3*P+$g(k,I)+(2*k[16]+3*k[17]+7*k[18]);if(Q<=ie&&Q<=G)return GE(t,d,e.subarray(l,l+u));if(ql(t,d,1+(G<ie)),d+=2,G<ie){M=Wm(p,g),Y=p,O=Wm(b,x),X=b;var ne=Wm(I,N);for(ql(t,d,y-257),ql(t,d+5,E-1),ql(t,d+10,P-4),d+=14,F=0;F<P;++F)ql(t,d+3*F,I[AP[F]]);d+=3*P;for(var oe=[w,C],B=0;B<2;++B){var H=oe[B];for(F=0;F<H.length;++F){var U=31&H[F];ql(t,d,ne[U]),d+=I[U],U>15&&(ql(t,d,H[F]>>>5&127),d+=H[F]>>>12)}}}else M=zoe,Y=yh,O=qoe,X=W_;for(F=0;F<o;++F)if(s[F]>255){U=s[F]>>>18&31,Wg(t,d,M[U+257]),d+=Y[U+257],U>7&&(ql(t,d,s[F]>>>23&31),d+=ZA[U]);var z=31&s[F];Wg(t,d,O[z]),d+=X[z],z>3&&(Wg(t,d,s[F]>>>5&8191),d+=e2[z])}else Wg(t,d,M[s[F]]),d+=Y[s[F]];return Wg(t,d,M[256]),d+Y[256]},Koe=new Np([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Yoe=function(){for(var e=new Np(256),t=0;t<256;++t){for(var n=t,s=9;--s;)n=(1&n&&3988292384)^n>>>1;e[t]=n}return e}(),Xoe=function(){var e=4294967295;return{p:function(t){for(var n=e,s=0;s<t.length;++s)n=Yoe[255&n^t[s]]^n>>>8;e=n},d:function(){return 4294967295^e}}},Qoe=function(e,t,n,s,r){return function(i,a,o,l,u,d){var f=i.length,p=new Ya(l+f+5*(1+Math.floor(f/7e3))+u),g=p.subarray(l,p.length-u),v=0;if(!a||f<8)for(var b=0;b<=f;b+=65535){var x=b+65535;x<f?v=GE(g,v,i.subarray(b,x)):(g[b]=d,v=GE(g,v,i.subarray(b,f)))}else{for(var _=Koe[a-1],w=_>>>13,y=8191&_,S=(1<<o)-1,C=new Hi(32768),E=new Hi(S+1),k=Math.ceil(o/3),F=2*k,A=function(he){return(i[he]^i[he+1]<<k^i[he+2]<<F)&S},I=new Np(25e3),N=new Hi(288),P=new Hi(32),M=0,Y=0,O=(b=0,0),X=0,Q=0;b<f;++b){var ie=A(b),G=32767&b,ne=E[ie];if(C[G]=ne,E[ie]=G,X<=b){var oe=f-b;if((M>7e3||O>24576)&&oe>423){v=IP(i,g,0,I,N,P,Y,O,Q,b-Q,v),O=M=Y=0,Q=b;for(var B=0;B<286;++B)N[B]=0;for(B=0;B<30;++B)P[B]=0}var H=2,U=0,z=y,te=G-ne&32767;if(oe>2&&ie==A(b-te))for(var fe=Math.min(w,oe)-1,J=Math.min(32767,b),Se=Math.min(258,oe);te<=J&&--z&&G!=ne;){if(i[b+H]==i[b+H-te]){for(var W=0;W<Se&&i[b+W]==i[b+W-te];++W);if(W>H){if(H=W,U=te,W>fe)break;var Ce=Math.min(te,W-2),K=0;for(B=0;B<Ce;++B){var me=b-te+B+32768&32767,Ee=me-C[me]+32768&32767;Ee>K&&(K=Ee,ne=me)}}}te+=(G=ne)-(ne=C[G])+32768&32767}if(U){I[O++]=268435456|HE[H]<<18|FP[U];var Ae=31&HE[H],se=31&FP[U];Y+=ZA[Ae]+e2[se],++N[257+Ae],++P[se],X=b+H,++M}else I[O++]=i[b],++N[i[b]]}}v=IP(i,g,d,I,N,P,Y,O,Q,b-Q,v)}return IH(p,0,l+DH(v)+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)},VE=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8},Joe=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&&VE(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)}},Zoe=function(e){return 10+(e.filename&&e.filename.length+1||0)};function NH(e,t){t===void 0&&(t={});var n=Xoe(),s=e.length;n.p(e);var r=Qoe(e,t,Zoe(t),8),i=r.length;return Joe(r,t),VE(r,i-8,n.d()),VE(r,i-4,s),r}function PH(e,t){var n=e.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(e);for(var s=new Ya(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 Ya(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 IH(s,0,r)}function ele(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<Wa(100*t,0,100)}var Sm="[SessionRecording]",Kr=li(Sm);function Ub(){var e,t;return tn==null||(e=tn.__PosthogExtensions__)===null||e===void 0||(t=e.rrweb)===null||t===void 0?void 0:t.record}var tle=3e5,nle=[_o.MouseMove,_o.MouseInteraction,_o.Scroll,_o.ViewportResize,_o.Input,_o.TouchMove,_o.MediaInteraction,_o.Drag],NP=e=>({rrwebMethod:e,enqueuedAt:Date.now(),attempt:1});function Sd(e){return function(t,n){for(var s="",r=0;r<t.length;){var i=t[r++];s+=String.fromCharCode(i)}return s}(NH(PH(JSON.stringify(e))))}function PP(e){return e.type===Xl.Custom&&e.data.tag==="sessionIdle"}function MP(e,t){return t.some(n=>n.matching==="regex"&&new RegExp(n.url).test(e))}let sle=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(Sm+" 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:tle}get isSampled(){var t=this.instance.get_property(ym);return ec(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(EE),n=!this.instance.config.disable_session_recording;return qe&&t&&n}get isConsoleLogCaptureEnabled(){var t=!!this.instance.get_property(cP),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(hP),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,f=(i=(a=o?.canvasQuality)!==null&&a!==void 0?a:l?.quality)!==null&&i!==void 0?i:.4;if(typeof f=="string"){var p=parseFloat(f);f=isNaN(p)?.4:p}return{enabled:u,fps:Wa(d,0,12,"canvas recording fps",4),quality:Wa(f,0,1,"canvas recording quality",.4)}}get networkPayloadCapture(){var t,n,s=this.instance.get_property(uP),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=Bs(this.instance.config.capture_performance)?this.instance.config.capture_performance.network_timing:this.instance.config.capture_performance,l=!!(ec(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(dP),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,f=(a=l?.blockSelector)!==null&&a!==void 0?a:o?.blockSelector;return Rt(u)&&Rt(d)&&Rt(f)?void 0:{maskAllInputs:u==null||u,maskTextSelector:d,blockSelector:f}}get sampleRate(){var t=this.instance.get_property(fP);return ki(t)?t:null}get minimumDuration(){var t=this.instance.get_property(pP);return ki(t)?t:null}get status(){return this.receivedDecide?this.isRecordingEnabled?this.isSampled===!1?"disabled":this._urlBlocked?"paused":Yn(this._linkedFlag)||this._linkedFlagSeen?this.triggerStatus==="trigger_pending"?"buffering":ec(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(w1))===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(y1))===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(yt(this,"queuedRRWebEvents",[]),yt(this,"isIdle","unknown"),yt(this,"_linkedFlagSeen",!1),yt(this,"_lastActivityTimestamp",Date.now()),yt(this,"_linkedFlag",null),yt(this,"_removePageViewCaptureHook",void 0),yt(this,"_onSessionIdListener",void 0),yt(this,"_persistDecideOnSessionListener",void 0),yt(this,"_samplingSessionListener",void 0),yt(this,"_urlTriggers",[]),yt(this,"_urlBlocklist",[]),yt(this,"_urlBlocked",!1),yt(this,"_eventTriggers",[]),yt(this,"_removeEventTriggerCaptureHook",void 0),yt(this,"_forceAllowLocalhostNetworkCapture",!1),yt(this,"_onBeforeUnload",()=>{this._flushBuffer()}),yt(this,"_onOffline",()=>{this._tryAddCustomEvent("browser offline",{})}),yt(this,"_onOnline",()=>{this._tryAddCustomEvent("browser online",{})}),yt(this,"_onVisibilityChange",()=>{if(Pt!=null&&Pt.visibilityState){var r="window "+Pt.visibilityState;this._tryAddCustomEvent(r,{})}}),this.instance=t,this._captureStarted=!1,this._endpoint="/s/",this.stopRrweb=void 0,this.receivedDecide=!1,!this.instance.sessionManager)throw Kr.error("started without valid sessionManager"),new Error(Sm+" started without valid sessionManager. This is a bug.");if(this.instance.config.__preview_experimental_cookieless_mode)throw new Error(Sm+" 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&&Kr.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),Ys(qe,"beforeunload",this._onBeforeUnload),Ys(qe,"offline",this._onOffline),Ys(qe,"online",this._onOnline),Ys(qe,"visibilitychange",this._onVisibilityChange),this._setupSampling(),this._addEventTriggerListener(),Yn(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){Kr.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(y1),(o=this.instance)===null||o===void 0||(l=o.persistence)===null||l===void 0||l.unregister(w1))}))):this.stopRecording()}stopRecording(){var t,n,s,r;this._captureStarted&&this.stopRrweb&&(this.stopRrweb(),this.stopRrweb=void 0,this._captureStarted=!1,qe?.removeEventListener("beforeunload",this._onBeforeUnload),qe?.removeEventListener("offline",this._onOffline),qe?.removeEventListener("online",this._onOnline),qe?.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,Kr.info("stopped"))}_resetSampling(){var t;(t=this.instance.persistence)===null||t===void 0||t.unregister(ym)}makeSamplingDecision(t){var n,s=this.sessionId!==t,r=this.sampleRate;if(ki(r)){var i=this.isSampled,a=s||!ec(i),o=a?ele(t,r):i;a&&(o?this._reportStarted("sampled"):Kr.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({[ym]: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(),!Yn(this._linkedFlag)&&!this._linkedFlagSeen){var l=cr(this._linkedFlag)?this._linkedFlag:this._linkedFlag.flag,u=cr(this._linkedFlag)?null:this._linkedFlag.variant;this.instance.onFeatureFlags((d,f)=>{var p=Bs(f)&&l in f,g=u?f[l]===u:p;g&&this._reportStarted("linked_flag_matched",{linkedFlag:l,linkedVariant:u}),this._linkedFlagSeen=g})}(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(){ki(this.sampleRate)&&Yn(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,f,p,g,v=(i=t.sessionRecording)===null||i===void 0?void 0:i.sampleRate,b=Yn(v)?null:parseFloat(v);Yn(b)&&this._resetSampling();var x=(a=t.sessionRecording)===null||a===void 0?void 0:a.minimumDurationMilliseconds;s.register({[EE]:!!t.sessionRecording,[cP]:(o=t.sessionRecording)===null||o===void 0?void 0:o.consoleLogRecordingEnabled,[uP]:Ze({capturePerformance:t.capturePerformance},(l=t.sessionRecording)===null||l===void 0?void 0:l.networkPayloadCapture),[dP]:(u=t.sessionRecording)===null||u===void 0?void 0:u.masking,[hP]:{enabled:(d=t.sessionRecording)===null||d===void 0?void 0:d.recordCanvas,fps:(f=t.sessionRecording)===null||f===void 0?void 0:f.canvasFps,quality:(p=t.sessionRecording)===null||p===void 0?void 0:p.canvasQuality},[fP]:b,[pP]:Rt(x)?null:x,[gP]:(g=t.sessionRecording)===null||g===void 0?void 0:g.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(!Rt(Object.assign)&&!Rt(Array.from)&&!(this._captureStarted||this.instance.config.disable_session_recording||this.instance.consent.isOptedOut())){var n,s;this._captureStarted=!0,this.sessionManager.checkAndGetSessionAndWindowId(),Ub()?this._onScriptLoaded():(n=tn.__PosthogExtensions__)===null||n===void 0||(s=n.loadExternalDependency)===null||s===void 0||s.call(n,this.instance,this.scriptName,r=>{if(r)return Kr.error("could not load recorder",r);this._onScriptLoaded()}),Kr.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(gP))===null||s===void 0?void 0:s.script)||"recorder"}isInteractiveEvent(t){var n;return t.type===3&&nle.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}):Kr.warn("could not emit queued rrweb event.",n,t),!1}}_tryAddCustomEvent(t,n){return this._tryRRWebMethod(NP(()=>Ub().addCustomEvent(t,n)))}_tryTakeFullSnapshot(){return this._tryRRWebMethod(NP(()=>Ub().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=Ze({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=Ub();if(u){this.mutationRateLimiter=(t=this.mutationRateLimiter)!==null&&t!==void 0?t:new Woe(u,{refillRate:this.instance.config.session_recording.__mutationRateLimiterRefillRate,bucketSize:this.instance.config.session_recording.__mutationRateLimiterBucketSize,onBlockedNode:(f,p)=>{var g="Too many mutations on node '".concat(f,"'. Rate limiting. This could be due to SVG animations or something similar");Kr.info(g,{node:p}),this.log(Sm+" "+g,"warn")}});var d=this._gatherRRWebPlugins();this.stopRrweb=u(Ze({emit:f=>{this.onRRwebEmit(f)},plugins:d},i)),this._lastActivityTimestamp=Date.now(),this.isIdle=ec(this.isIdle)?this.isIdle:"unknown",this._tryAddCustomEvent("$session_options",{sessionRecordingOptions:i,activePlugins:d.map(f=>f?.name)}),this._tryAddCustomEvent("$posthog_config",{config:this.instance.config})}else Kr.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=tn.__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=tn.__PosthogExtensions__)===null||s===void 0||(r=s.rrwebPlugins)===null||r===void 0?void 0:r.getRecordNetworkPlugin;return this.networkPayloadCapture&&Ro(o)&&(!coe.includes(location.hostname)||this._forceAllowLocalhostNetworkCapture?i.push(o(Voe(this.instance.config,this.networkPayloadCapture))):Kr.info("NetworkCapture not started because we are on localhost.")),i}onRRwebEmit(t){var n;if(this._processQueuedEvents(),t&&Bs(t)){if(t.type===Xl.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(f){return f.type===Xl.Custom&&f.data.tag==="recording paused"}(t)){t.type===Xl.FullSnapshot&&this._scheduleFullSnapshot(),t.type===Xl.FullSnapshot&&this.triggerStatus==="trigger_pending"&&this.clearBuffer();var r=this.mutationRateLimiter?this.mutationRateLimiter.throttleMutations(t):t;if(r){var i=function(f){var p=f;if(p&&Bs(p)&&p.type===6&&Bs(p.data)&&p.data.plugin==="rrweb/console@1"){p.data.payload.payload.length>10&&(p.data.payload.payload=p.data.payload.payload.slice(0,10),p.data.payload.payload.push("...[truncated]"));for(var g=[],v=0;v<p.data.payload.payload.length;v++)p.data.payload.payload[v]&&p.data.payload.payload[v].length>2e3?g.push(p.data.payload.payload[v].slice(0,2e3)+"...[truncated]"):g.push(p.data.payload.payload[v]);return p.data.payload.payload=g,f}return f}(r);if(this._updateWindowAndSessionIds(i),this.isIdle!==!0||PP(i)){if(PP(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(f){if(V_(f)<1024)return f;try{if(f.type===Xl.FullSnapshot)return Ze(Ze({},f),{},{data:Sd(f.data),cv:"2024-10"});if(f.type===Xl.IncrementalSnapshot&&f.data.source===_o.Mutation)return Ze(Ze({},f),{},{cv:"2024-10",data:Ze(Ze({},f.data),{},{texts:Sd(f.data.texts),attributes:Sd(f.data.attributes),removes:Sd(f.data.removes),adds:Sd(f.data.adds)})});if(f.type===Xl.IncrementalSnapshot&&f.data.source===_o.StyleSheetRule)return Ze(Ze({},f),{},{cv:"2024-10",data:Ze(Ze({},f.data),{},{adds:f.data.adds?Sd(f.data.adds):void 0,removes:f.data.removes?Sd(f.data.removes):void 0})})}catch(p){Kr.error("could not compress event - will use uncompressed event",p)}return f}(i):i,d={$snapshot_bytes:V_(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&&qe){var t=this._maskUrl(qe.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=ki(n)&&n>=0,r=ki(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&&LE(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:Jl.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(qe!==void 0&&qe.location.href){var t=qe.location.href,n=this._urlBlocked,s=MP(t,this._urlBlocklist);s&&!n?this._pauseRecording():!s&&n&&this._resumeRecording(),MP(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"?w1:y1]:this.sessionId}),this._flushBuffer(),this._reportStarted(t+"_trigger_matched"))}_pauseRecording(){this._urlBlocked||(this._urlBlocked=!0,clearInterval(this._fullSnapshotTimer),Kr.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"}),Kr.info("recording resumed"))}_addEventTriggerListener(){this._eventTriggers.length!==0&&Yn(this._removeEventTriggerCaptureHook)&&(this._removeEventTriggerCaptureHook=this.instance.on("eventCaptured",t=>{try{this._eventTriggers.includes(t.event)&&this._activateTrigger("event")}catch(n){Kr.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({[ym]:!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}),Kr.info(t.replace("_"," "),n),xn(["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 N1=li("[SegmentIntegration]");function rle(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()||yu();s.config.get_device_id=u,l.id()&&(s.register({distinct_id:l.id(),$device_id:u()}),s.persistence.set_property(Yl,"identified")),r()},o=i.user();"then"in o&&Ro(o.then)?o.then(l=>a(l)):a(o)})(e,()=>{n.register((s=>{Promise&&Promise.resolve||N1.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()||(N1.info("No userId set, resetting PostHog"),s.reset()),i.event.userId&&i.event.userId!==s.get_distinct_id()&&(N1.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 MH="posthog-js";function OH(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 f=e.requestRouter.endpointFor("ui","/project/".concat(e.config.token,"/person/").concat(e.get_distinct_id()));i.tags["PostHog Person URL"]=f,e.sessionRecordingStarted()&&(i.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var p=((a=i.exception)===null||a===void 0?void 0:a.values)||[],g=p.map(b=>Ze(Ze({},b),{},{stacktrace:b.stacktrace?Ze(Ze({},b.stacktrace),{},{type:"raw",frames:(b.stacktrace.frames||[]).map(x=>Ze(Ze({},x),{},{platform:"web:javascript"}))}):void 0})),v={$exception_message:((o=p[0])===null||o===void 0?void 0:o.value)||i.message,$exception_type:(l=p[0])===null||l===void 0?void 0:l.type,$exception_personURL:f,$exception_level:i.level,$exception_list:g,$sentry_event_id:i.event_id,$sentry_exception:i.exception,$sentry_exception_message:((u=p[0])===null||u===void 0?void 0:u.value)||i.message,$sentry_exception_type:(d=p[0])===null||d===void 0?void 0:d.type,$sentry_tags:i.tags};return t&&n&&(v.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+n+"&query="+i.event_id),e.exceptions.sendExceptionEvent(v),i}}let ile=class{constructor(t,n,s,r,i){this.name=MH,this.setupOnce=function(a){a(OH(t,{organization:n,projectId:s,prefix:r,severityAllowList:i}))}}};var Ql,ale=qe!=null&&qe.location?G_(qe.location.hash,"__posthog")||G_(location.hash,"state"):null,OP="_postHogToolbarParams",LP=li("[Toolbar]");(function(e){e[e.UNINITIALIZED=0]="UNINITIALIZED",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED"})(Ql||(Ql={}));class ole{constructor(t){this.instance=t}setToolbarState(t){tn.ph_toolbar_state=t}getToolbarState(){var t;return(t=tn.ph_toolbar_state)!==null&&t!==void 0?t:Ql.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(!qe||!Pt)return!1;s=(t=s)!==null&&t!==void 0?t:qe.location,i=(n=i)!==null&&n!==void 0?n:qe.history;try{if(!r){try{qe.localStorage.setItem("test","test"),qe.localStorage.removeItem("test")}catch{return!1}r=qe?.localStorage}var a,o=ale||G_(s.hash,"__posthog")||G_(s.hash,"state"),l=o?rP(()=>JSON.parse(atob(decodeURIComponent(o))))||rP(()=>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(OP)||"{}")).source="localstorage",delete a.userIntent),!(!a.token||this.instance.config.token!==a.token)&&(this.loadToolbar(a),!0)}catch{return!1}}_callLoadToolbar(t){var n=tn.ph_load_toolbar||tn.ph_load_editor;!Yn(n)&&Ro(n)?n(t,this.instance):LP.warn("No toolbar load function found")}loadToolbar(t){var n=!(Pt==null||!Pt.getElementById(hH));if(!qe||n)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=Ze(Ze({token:this.instance.config.token},t),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(qe.localStorage.setItem(OP,JSON.stringify(Ze(Ze({},r),{},{source:void 0}))),this.getToolbarState()===Ql.LOADED)this._callLoadToolbar(r);else if(this.getToolbarState()===Ql.UNINITIALIZED){var i,a;this.setToolbarState(Ql.LOADING),(i=tn.__PosthogExtensions__)===null||i===void 0||(a=i.loadExternalDependency)===null||a===void 0||a.call(i,this.instance,"toolbar",o=>{if(o)return LP.error("[Toolbar] Failed to load",o),void this.setToolbarState(Ql.UNINITIALIZED);this.setToolbarState(Ql.LOADED),this._callLoadToolbar(r)}),Ys(qe,"turbolinks:load",()=>{this.setToolbarState(Ql.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 lle=li("[TracingHeaders]");class cle{constructor(t){yt(this,"_restoreXHRPatch",void 0),yt(this,"_restoreFetchPatch",void 0),yt(this,"_startCapturing",()=>{var n,s,r,i;Rt(this._restoreXHRPatch)&&((n=tn.__PosthogExtensions__)===null||n===void 0||(s=n.tracingHeadersPatchFns)===null||s===void 0||s._patchXHR(this.instance.sessionManager)),Rt(this._restoreFetchPatch)&&((r=tn.__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=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.tracingHeadersPatchFns&&t(),(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"tracing-headers",i=>{if(i)return lle.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 nu=li("[Web Vitals]"),BP=9e5;class ule{constructor(t){var n;yt(this,"_enabledServerSide",!1),yt(this,"_initialized",!1),yt(this,"buffer",{url:void 0,metrics:[],firstMetricTimestamp:void 0}),yt(this,"_flushToCapture",()=>{clearTimeout(this._delayedFlushTimer),this.buffer.metrics.length!==0&&(this.instance.capture("$web_vitals",this.buffer.metrics.reduce((s,r)=>Ze(Ze({},s),{},{["$web_vitals_".concat(r.name,"_event")]:Ze({},r),["$web_vitals_".concat(r.name,"_value")]:r.value}),{})),this.buffer={url:void 0,metrics:[],firstMetricTimestamp:void 0})}),yt(this,"_addToBuffer",s=>{var r,i=(r=this.instance.sessionManager)===null||r===void 0?void 0:r.checkAndGetSessionAndWindowId(!0);if(Rt(i))nu.error("Could not read session ID. Dropping metrics!");else{this.buffer=this.buffer||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var a=this._currentURL();Rt(a)||(Yn(s?.name)||Yn(s?.value)?nu.error("Invalid metric received",s):this._maxAllowedValue&&s.value>=this._maxAllowedValue?nu.error("Ignoring metric with value >= "+this._maxAllowedValue,s):(this.buffer.url!==a&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),Rt(this.buffer.url)&&(this.buffer.url=a),this.buffer.firstMetricTimestamp=Rt(this.buffer.firstMetricTimestamp)?Date.now():this.buffer.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0),this.buffer.metrics.push(Ze(Ze({},s),{},{$current_url:a,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()))}}),yt(this,"_startCapturing",()=>{var s,r,i,a,o=tn.__PosthogExtensions__;Rt(o)||Rt(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):nu.error("web vitals callbacks not loaded - not starting")}),this.instance=t,this._enabledServerSide=!((n=this.instance.persistence)===null||n===void 0||!n.props[oP]),this.startIfEnabled()}get allowedMetrics(){var t,n,s=Bs(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 Rt(s)?((n=this.instance.persistence)===null||n===void 0?void 0:n.props[lP])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(Bs(this.instance.config.capture_performance)?this.instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get _maxAllowedValue(){var t=Bs(this.instance.config.capture_performance)&&ki(this.instance.config.capture_performance.__web_vitals_max_value)?this.instance.config.capture_performance.__web_vitals_max_value:BP;return 0<t&&t<=6e4?BP:t}get isEnabled(){var t=Li?.protocol;if(t!=="http:"&&t!=="https:")return nu.info("Web Vitals are disabled on non-http/https protocols"),!1;var n=Bs(this.instance.config.capture_performance)?this.instance.config.capture_performance.web_vitals:ec(this.instance.config.capture_performance)?this.instance.config.capture_performance:void 0;return ec(n)?n:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(nu.info("enabled, starting..."),this.loadScript(this._startCapturing))}onRemoteConfig(t){var n=Bs(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=Bs(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this.instance.persistence&&(this.instance.persistence.register({[oP]:n}),this.instance.persistence.register({[lP]:s})),this._enabledServerSide=n,this.startIfEnabled()}loadScript(t){var n,s,r;(n=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.postHogWebVitalsCallbacks&&t(),(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"web-vitals",i=>{i?nu.error("failed to load script",i):t()})}_currentURL(){var t=qe?qe.location.href:void 0;return t||nu.error("Could not determine current URL"),t}}var dle=li("[Heatmaps]");function jP(e){return Bs(e)&&"clientX"in e&&"clientY"in e&&ki(e.clientX)&&ki(e.clientY)}class hle{constructor(t){var n;yt(this,"rageclicks",new CH),yt(this,"_enabledServerSide",!1),yt(this,"_initialized",!1),yt(this,"_flushInterval",null),this.instance=t,this._enabledServerSide=!((n=this.instance.persistence)===null||n===void 0||!n.props[kE])}get flushIntervalMilliseconds(){var t=5e3;return Bs(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 Rt(this.instance.config.capture_heatmaps)?Rt(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;dle.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({[kE]: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(){qe&&Pt&&(Ys(qe,"beforeunload",this.flush.bind(this)),Ys(Pt,"click",t=>this._onClick(t||qe?.event),{capture:!0}),Ys(Pt,"mousemove",t=>this._onMouseMove(t||qe?.event),{capture:!0}),this.deadClicksCapture=new kH(this.instance,koe,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&&Uy(d)&&!Du(d,"body");){if(d===u)return!1;if(xn(l,qe?.getComputedStyle(d).position))return!0;d=vH(d)}return!1}(mH(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(!vP(t.target)&&jP(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(Ze(Ze({},r),{},{type:"rageclick"})),this._capture(r)}}_onMouseMove(t){!vP(t.target)&&jP(t)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout(()=>{this._capture(this._getProperties(t,"mousemove"))},500))}_capture(t){if(qe){var n=qe.location.href;this.buffer=this.buffer||{},this.buffer[n]||(this.buffer[n]=[]),this.buffer[n].push(t)}}flush(){this.buffer&&!qf(this.buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class fle{constructor(t){this._instance=t}doPageView(t,n){var s,r=this._previousPageViewProperties(t,n);return this._currentPageview={pathname:(s=qe?.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:f}=i;if(!(Rt(a)||Rt(o)||Rt(l)||Rt(u)||Rt(d)||Rt(f))){a=Math.ceil(a),o=Math.ceil(o),l=Math.ceil(l),u=Math.ceil(u),d=Math.ceil(d),f=Math.ceil(f);var p=a<=1?1:Wa(o/a,0,1),g=a<=1?1:Wa(l/a,0,1),v=u<=1?1:Wa(d/u,0,1),b=u<=1?1:Wa(f/u,0,1);r=qs(r,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:p,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:g,$prev_pageview_last_content:d,$prev_pageview_last_content_percentage:v,$prev_pageview_max_content:f,$prev_pageview_max_content_percentage:b})}}return s.pathname&&(r.$prev_pageview_pathname=s.pathname),s.timestamp&&(r.$prev_pageview_duration=(t.getTime()-s.timestamp.getTime())/1e3),r}}let ple=class{constructor(t){this.instance=t}sendExceptionEvent(t){this.instance.capture("$exception",t,{_noTruncate:!0,_batchKey:"exceptionEvent"})}};var Xa="Mobile",$_="iOS",fl="Android",U0="Tablet",LH=fl+" "+U0,BH="iPad",jH="Apple",HH=jH+" Watch",G0="Safari",Pp="BlackBerry",UH="Samsung",GH=UH+"Browser",VH=UH+" Internet",Ch="Chrome",gle=Ch+" OS",WH=Ch+" "+$_,t2="Internet Explorer",$H=t2+" "+Xa,n2="Opera",mle=n2+" Mini",s2="Edge",zH="Microsoft "+s2,ip="Firefox",qH=ip+" "+$_,V0="Nintendo",W0="PlayStation",ap="Xbox",KH=fl+" "+Xa,YH=Xa+" "+G0,km="Windows",WE=km+" Phone",HP="Nokia",$E="Ouya",XH="Generic",vle=XH+" "+Xa.toLowerCase(),QH=XH+" "+U0.toLowerCase(),zE="Konqueror",wi="(\\d+(\\.\\d+)?)",P1=new RegExp("Version/"+wi),ble=new RegExp(ap,"i"),xle=new RegExp(W0+" \\w+","i"),_le=new RegExp(V0+" \\w+","i"),r2=new RegExp(Pp+"|PlayBook|BB10","i"),wle={"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"},qE,yle=(e,t)=>t&&xn(t,jH)||function(n){return xn(n,G0)&&!xn(n,Ch)&&!xn(n,fl)}(e),UP=function(e,t){return t=t||"",xn(e," OPR/")&&xn(e,"Mini")?mle:xn(e," OPR/")?n2:r2.test(e)?Pp:xn(e,"IE"+Xa)||xn(e,"WPDesktop")?$H:xn(e,GH)?VH:xn(e,s2)||xn(e,"Edg/")?zH:xn(e,"FBIOS")?"Facebook "+Xa:xn(e,"UCWEB")||xn(e,"UCBrowser")?"UC Browser":xn(e,"CriOS")?WH:xn(e,"CrMo")||xn(e,Ch)?Ch:xn(e,fl)&&xn(e,G0)?KH:xn(e,"FxiOS")?qH:xn(e.toLowerCase(),zE.toLowerCase())?zE:yle(e,t)?xn(e,Xa)?YH:G0:xn(e,ip)?ip:xn(e,"MSIE")||xn(e,"Trident/")?t2:xn(e,"Gecko")?ip:""},Cle={[$H]:[new RegExp("rv:"+wi)],[zH]:[new RegExp(s2+"?\\/"+wi)],[Ch]:[new RegExp("("+Ch+"|CrMo)\\/"+wi)],[WH]:[new RegExp("CriOS\\/"+wi)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+wi)],[G0]:[P1],[YH]:[P1],[n2]:[new RegExp("(Opera|OPR)\\/"+wi)],[ip]:[new RegExp(ip+"\\/"+wi)],[qH]:[new RegExp("FxiOS\\/"+wi)],[zE]:[new RegExp("Konqueror[:/]?"+wi,"i")],[Pp]:[new RegExp(Pp+" "+wi),P1],[KH]:[new RegExp("android\\s"+wi,"i")],[VH]:[new RegExp(GH+"\\/"+wi)],[t2]:[new RegExp("(rv:|MSIE )"+wi)],Mozilla:[new RegExp("rv:"+wi)]},GP=[[new RegExp(ap+"; "+ap+" (.*?)[);]","i"),e=>[ap,e&&e[1]||""]],[new RegExp(V0,"i"),[V0,""]],[new RegExp(W0,"i"),[W0,""]],[r2,[Pp,""]],[new RegExp(km,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[WE,""];if(new RegExp(Xa).test(t)&&!/IEMobile\b/.test(t))return[km+" "+Xa,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var s=n[1],r=wle[s]||"";return/arm/i.test(t)&&(r="RT"),[km,r]}return[km,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){var t=[e[3],e[4],e[5]||"0"];return[$_,t.join(".")]}return[$_,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=Rt(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+fl+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+fl+")","i"),e=>{if(e&&e[2]){var t=[e[2],e[3],e[4]||"0"];return[fl,t.join(".")]}return[fl,""]}],[/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/,[gle,""]],[/Linux|debian/i,["Linux",""]]],VP=function(e){return _le.test(e)?V0:xle.test(e)?W0:ble.test(e)?ap:new RegExp($E,"i").test(e)?$E:new RegExp("("+WE+"|WPDesktop)","i").test(e)?WE:/iPad/.test(e)?BH:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?HH:r2.test(e)?Pp:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(HP,"i").test(e)?HP:/(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(Xa).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)?fl:LH:fl:new RegExp("(pda|"+Xa+")","i").test(e)?vle:new RegExp(U0,"i").test(e)&&!new RegExp(U0+" pc","i").test(e)?QH:""},Gb="https?://(.*)",Kx=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","irclid","_kx"],Sle=Wx(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],Kx),M1="<masked>",ks={campaignParams:function(){var{customTrackedParams:e,maskPersonalDataProperties:t,customPersonalDataProperties:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!Pt)return{};var s=t?Wx([],Kx,n||[]):[];return this._campaignParamsFromUrl(C1(Pt.URL,s,M1),e)},_campaignParamsFromUrl:function(e,t){var n=Sle.concat(t||[]),s={};return as(n,function(r){var i=U_(e,r);s[r]=i||null}),s},_searchEngine:function(e){return e?e.search(Gb+"google.([^/?]*)")===0?"google":e.search(Gb+"bing.com")===0?"bing":e.search(Gb+"yahoo.com")===0?"yahoo":e.search(Gb+"duckduckgo.com")===0?"duckduckgo":null:null},_searchInfoFromReferrer:function(e){var t=ks._searchEngine(e),n=t!="yahoo"?"q":"p",s={};if(!td(t)){s.$search_engine=t;var r=Pt?U_(Pt.referrer,n):"";r.length&&(s.ph_keyword=r)}return s},searchInfo:function(){var e=Pt?.referrer;return e?this._searchInfoFromReferrer(e):{}},browser:UP,browserVersion:function(e,t){var n=UP(e,t),s=Cle[n];if(Rt(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<GP.length;t++){var[n,s]=GP[t],r=n.exec(e),i=r&&(Ro(s)?s(r,e):s);if(i)return i}return["",""]},device:VP,deviceType:function(e){var t=VP(e);return t===BH||t===LH||t==="Kobo"||t==="Kindle Fire"||t===QH?U0:t===V0||t===ap||t===W0||t===$E?"Console":t===HH?"Wearable":t?Xa:"Desktop"},referrer:function(){return Pt?.referrer||"$direct"},referringDomain:function(){var e;return Pt!=null&&Pt.referrer&&((e=rp(Pt.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?Wx([],Kx,t||[]):[],s=Li?.href.substring(0,1e3);return{r:this.referrer().substring(0,1e3),u:s?C1(s,n,M1):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=rp(n))===null||t===void 0?void 0:t.host};if(s){r.$current_url=s;var i=rp(s);r.$host=i?.host,r.$pathname=i?.pathname;var a=this._campaignParamsFromUrl(s);qs(r,a)}if(n){var o=this._searchInfoFromReferrer(n);qs(r,o)}return r},initialPersonPropsFromInfo:function(e){var t=this.personPropsFromInfo(e),n={};return as(t,function(s,r){n["$initial_".concat(XA(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(!or)return{};var n=e?Wx([],Kx,t||[]):[],[s,r]=ks.os(or);return qs(H0({$os:s,$os_version:r,$browser:ks.browser(or,navigator.vendor),$device:ks.device(or),$device_type:ks.deviceType(or),$timezone:ks.timezone(),$timezone_offset:ks.timezoneOffset()}),{$current_url:C1(Li?.href,n,M1),$host:Li?.host,$pathname:Li?.pathname,$raw_user_agent:or.length>1e3?or.substring(0,997)+"...":or,$browser_version:ks.browserVersion(or,navigator.vendor),$browser_language:ks.browserLanguage(),$browser_language_prefix:ks.browserLanguagePrefix(),$screen_height:qe?.screen.height,$screen_width:qe?.screen.width,$viewport_height:qe?.innerHeight,$viewport_width:qe?.innerWidth,$lib:"web",$lib_version:Jl.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(!or)return{};var[e,t]=ks.os(or);return qs(H0({$os:e,$os_version:t,$browser:ks.browser(or,navigator.vendor)}),{$browser_version:ks.browserVersion(or,navigator.vendor)})}},sl=li("[FeatureFlags]"),O1="$active_feature_flags",_f="$override_feature_flags",WP="$feature_flag_payloads",zg="$override_feature_flag_payloads",$P="$feature_flag_request_id",zP=e=>{var t={};for(var[n,s]of $x(e||{}))s&&(t[n]=s);return t},kle=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]}))):sl.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"})(qE||(qE={}));class Ele{constructor(t){yt(this,"_override_warning",!1),yt(this,"_hasLoadedFlags",!1),yt(this,"_requestInFlight",!1),yt(this,"_reloadingDisabled",!1),yt(this,"_additionalReloadRequested",!1),yt(this,"_decideCalled",!1),yt(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(TE),n=this.instance.get_property(_f),s=this.instance.get_property(zg);if(!s&&!n)return t||{};var r=qs({},t||{}),i=[...new Set([...Object.keys(s||{}),...Object.keys(n||{})])];for(var a of i){var o,l,u=r[a],d=n?.[a],f=Rt(d)?(o=u?.enabled)!==null&&o!==void 0&&o:!!d,p=Rt(d)?u.variant:typeof d=="string"?d:void 0,g=s?.[a],v=Ze(Ze({},u),{},{enabled:f,variant:f?p??u?.variant:void 0});f!==u?.enabled&&(v.original_enabled=u?.enabled),p!==u?.variant&&(v.original_variant=u?.variant),g&&(v.metadata=Ze(Ze({},u?.metadata),{},{payload:g,original_payload:u==null||(l=u.metadata)===null||l===void 0?void 0:l.payload})),r[a]=v}return this._override_warning||(sl.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this._override_warning=!0),r}getFlagVariants(){var t=this.instance.get_property(Kf),n=this.instance.get_property(_f);if(!n)return t||{};for(var s=qs({},t),r=Object.keys(n),i=0;i<r.length;i++)s[r[i]]=n[r[i]];return this._override_warning||(sl.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:n,finalFlags:s}),this._override_warning=!0),s}getFlagPayloads(){var t=this.instance.get_property(WP),n=this.instance.get_property(zg);if(!n)return t||{};for(var s=qs({},t||{}),r=Object.keys(n),i=0;i<r.length;i++)s[r[i]]=n[r[i]];return this._override_warning||(sl.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:Ze(Ze({},((n=this.instance.persistence)===null||n===void 0?void 0:n.get_initial_props())||{}),this.instance.get_property(Cm)||{}),group_properties:this.instance.get_property(Id)};(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=ks.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:Co.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(qE.FeatureFlags)?sl.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($P)||void 0,a=this.instance.get_property(B_)||{};if((n.send_event||!("send_event"in n))&&(!(t in a)||!a[t].includes(r))){var o,l,u,d,f,p,g,v,b,x,_;Ls(a[t])?a[t].push(r):a[t]=[r],(o=this.instance.persistence)===null||o===void 0||o.register({[B_]:a});var w=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||(f=d.featureFlagPayloads)===null||f===void 0?void 0:f[t])||null,$used_bootstrap_value:!this._flagsLoadedFromRemote};Rt(w==null||(p=w.metadata)===null||p===void 0?void 0:p.version)||(y.$feature_flag_version=w.metadata.version);var S,C=(g=w==null||(v=w.reason)===null||v===void 0?void 0:v.description)!==null&&g!==void 0?g:w==null||(b=w.reason)===null||b===void 0?void 0:b.code;C&&(y.$feature_flag_reason=C),w!=null&&(x=w.metadata)!==null&&x!==void 0&&x.id&&(y.$feature_flag_id=w.metadata.id),Rt(w?.original_variant)&&Rt(w?.original_enabled)||(y.$feature_flag_original_response=Rt(w.original_variant)?w.original_enabled:w.original_variant),w!=null&&(_=w.metadata)!==null&&_!==void 0&&_.original_payload&&(y.$feature_flag_original_payload=w==null||(S=w.metadata)===null||S===void 0?void 0:S.original_payload),this.instance.capture("$feature_flag_called",y)}return s}sl.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:Co.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);sl.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]:{},f=kle(a),p=f.flags,g=f.featureFlags,v=f.featureFlagPayloads;if(g){var b=a.requestId;if(Ls(g)){sl.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var x={};if(g)for(var _=0;_<g.length;_++)x[g[_]]=!0;o&&o.register({[O1]:g,[Kf]:x})}else{var w=g,y=v,S=p;a.errorsWhileComputingFlags&&(w=Ze(Ze({},l),w),y=Ze(Ze({},u),y),S=Ze(Ze({},d),S)),o&&o.register(Ze({[O1]:Object.keys(zP(w)),[Kf]:w||{},[WP]:y||{},[TE]:S||{}},b?{[$P]:b}:{}))}}})(t,this.instance.persistence,s,r,i),this._fireFeatureFlagsCallbacks(n)}}override(t){var n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];sl.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:n})}overrideFeatureFlags(t){if(!this.instance.__loaded||!this.instance.persistence)return sl.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(t===!1)return this.instance.persistence.unregister(_f),this.instance.persistence.unregister(zg),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(_f);else if(s.flags)if(Ls(s.flags)){for(var r={},i=0;i<s.flags.length;i++)r[s.flags[i]]=!0;this.instance.persistence.register({[_f]:r})}else this.instance.persistence.register({[_f]:s.flags})}return"payloads"in s&&(s.payloads===!1?this.instance.persistence.unregister(zg):s.payloads&&this.instance.persistence.register({[zg]: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(zx)||[]).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=Ze(Ze({},this.getFlagVariants()),{},{[t]:n});(s=this.instance.persistence)===null||s===void 0||s.register({[O1]:Object.keys(zP(o)),[Kf]: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(zx),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({[zx]: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(Cm)||{};this.instance.register({[Cm]:Ze(Ze({},s),t)}),n&&this.instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this.instance.unregister(Cm)}setGroupPropertiesForFlags(t){var n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],s=this.instance.get_property(Id)||{};Object.keys(s).length!==0&&Object.keys(s).forEach(r=>{s[r]=Ze(Ze({},s[r]),t[r]),delete t[r]}),this.instance.register({[Id]:Ze(Ze({},s),t)}),n&&this.instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var n=this.instance.get_property(Id)||{};this.instance.register({[Id]:Ze(Ze({},n),{},{[t]:{}})})}else this.instance.unregister(Id)}}var Tle=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class L1{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&&Ht.info("Persistence loaded",t.persistence,Ze({},this.props)),this.update_config(t,t),this.save()}buildStorage(t){Tle.indexOf(t.persistence.toLowerCase())===-1&&(Ht.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");var n=t.persistence.toLowerCase();return n==="localstorage"&&gr.is_supported()?gr:n==="localstorage+cookie"&&Ob.is_supported()?Ob:n==="sessionstorage"&&Br.is_supported()?Br:n==="memory"?Coe:n==="cookie"?lc:Ob.is_supported()?Ob:lc}properties(){var t={};return as(this.props,function(n,s){if(s===Kf&&Bs(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,(td(a=toe)?l:eP&&a.indexOf===eP?a.indexOf(o)!=-1:(as(a,function(u){if(l||(l=u===o))return O_}),l))||(t[s]=n);var a,o,l}),t}load(){if(!this.disabled){var t=this.storage.parse(this.name);t&&(this.props=qs({},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(Bs(t)){Rt(n)&&(n="None"),this.expire_days=Rt(s)?this.default_expiry:s;var r=!1;if(as(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(Bs(t)){this.expire_days=Rt(n)?this.default_expiry:n;var s=!1;if(as(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=ks.campaignParams({customTrackedParams:this.config.custom_campaign_params,maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties});qf(H0(t))||this.register(t),this.campaign_params_saved=!0}}update_search_keyword(){this.register(ks.searchInfo())}update_referrer_info(){this.register_once(ks.referrerInfo(),void 0)}set_initial_person_info(){this.props[DE]||this.props[IE]||this.register_once({[NE]:ks.personInfo({maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties})},void 0)}get_referrer_info(){return H0({$referrer:this.props.$referrer,$referring_domain:this.props.$referring_domain})}get_initial_props(){var t={};as([IE,DE],r=>{var i=this.props[r];i&&as(i,function(a,o){t["$initial_"+XA(o)]=a})});var n=this.props[NE];if(n){var s=ks.initialPersonPropsFromInfo(n);qs(t,s)}return t}safe_merge(t){return as(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[wm]||{};s[t]=n,this.props[wm]=s,this.save()}remove_event_timer(t){var n=(this.props[wm]||{})[t];return Rt(n)||(delete this.props[wm][t],this.save()),n}get_property(t){return this.props[t]}set_property(t,n){this.props[t]=n,this.save()}}var JH,js,ZH,jd,qP,eU,KE,tU,KP,YE,YP,XP,QP,JP,XE={},nU=[],Rle=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,i2=Array.isArray;function Cu(e,t){for(var n in t)e[n]=t[n];return e}function sU(e){var t=e.parentNode;t&&t.removeChild(e)}function B1(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??++ZH,__i:-1,__u:0};return r==null&&js.vnode!=null&&js.vnode(i),i}function a2(e){return e.children}function Yx(e,t){this.props=e,this.context=t}function Mp(e,t){if(t==null)return e.__?Mp(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"?Mp(e):null}function rU(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 rU(e)}}function QE(e){(!e.__d&&(e.__d=!0)&&jd.push(e)&&!z_.__r++||qP!==js.debounceRendering)&&((qP=js.debounceRendering)||eU)(z_)}function z_(){var e,t,n,s,r,i,a,o,l;for(jd.sort(KE);e=jd.shift();)e.__d&&(t=jd.length,s=void 0,i=(r=(n=e).__v).__e,o=[],l=[],(a=n.__P)&&((s=Cu({},r)).__v=r.__v+1,js.vnode&&js.vnode(s),oU(a,s,r,n.__n,a.ownerSVGElement!==void 0,32&r.__u?[i]:null,o,i??Mp(r),!!(32&r.__u),l),s.__.__k[s.__i]=s,Dle(o,s,l),s.__e!=i&&rU(s)),jd.length>t&&jd.sort(KE));z_.__r=0}function iU(e,t,n,s,r,i,a,o,l,u,d){var f,p,g,v,b,x=s&&s.__k||nU,_=t.length;for(n.__d=l,Ale(n,t,x),l=n.__d,f=0;f<_;f++)(g=n.__k[f])!=null&&typeof g!="boolean"&&typeof g!="function"&&(p=g.__i===-1?XE:x[g.__i]||XE,g.__i=f,oU(e,g,p,r,i,a,o,l,u,d),v=g.__e,g.ref&&p.ref!=g.ref&&(p.ref&&o2(p.ref,null,g),d.push(g.ref,g.__c||v,g)),b==null&&v!=null&&(b=v),65536&g.__u||p.__k===g.__k?l=aU(g,l,e):typeof g.type=="function"&&g.__d!==void 0?l=g.__d:v&&(l=v.nextSibling),g.__d=void 0,g.__u&=-196609);n.__d=l,n.__e=b}function Ale(e,t,n){var s,r,i,a,o,l=t.length,u=n.length,d=u,f=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?B1(null,r,null,null,r):i2(r)?B1(a2,{children:r},null,null,null):r.constructor===void 0&&r.__b>0?B1(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r)!=null?(r.__=e,r.__b=e.__b+1,o=Fle(r,n,a=s+f,d),r.__i=o,i=null,o!==-1&&(d--,(i=n[o])&&(i.__u|=131072)),i==null||i.__v===null?(o==-1&&f--,typeof r.type!="function"&&(r.__u|=65536)):o!==a&&(o===a+1?f++:o>a?d>l-a?f+=o-a:f--:f=o<a&&o==a-1?o-a:0,o!==s+f&&(r.__u|=65536))):(i=n[s])&&i.key==null&&i.__e&&(i.__e==e.__d&&(e.__d=Mp(i)),JE(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=Mp(i)),JE(i,i))}function aU(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=aU(s[r],t,n));return t}return e.__e!=t&&(n.insertBefore(e.__e,t||null),t=e.__e),t&&t.nextSibling}function Fle(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 ZP(e,t,n){t[0]==="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Rle.test(t)?n:n+"px"}function Vb(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||ZP(e.style,t,"");if(n)for(t in n)s&&n[t]===s[t]||ZP(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?tM:eM,i)):e.removeEventListener(t,i?tM:eM,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 eM(e){var t=this.l[e.type+!1];if(e.t){if(e.t<=t.u)return}else e.t=Date.now();return t(js.event?js.event(e):e)}function tM(e){return this.l[e.type+!0](js.event?js.event(e):e)}function oU(e,t,n,s,r,i,a,o,l,u){var d,f,p,g,v,b,x,_,w,y,S,C,E,k,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=js.__b)&&d(t);e:if(typeof A=="function")try{if(_=t.props,w=(d=A.contextType)&&s[d.__c],y=d?w?w.props.value:d.__:s,n.__c?x=(f=t.__c=n.__c).__=f.__E:("prototype"in A&&A.prototype.render?t.__c=f=new A(_,y):(t.__c=f=new Yx(_,y),f.constructor=A,f.render=Nle),w&&w.sub(f),f.props=_,f.state||(f.state={}),f.context=y,f.__n=s,p=f.__d=!0,f.__h=[],f._sb=[]),f.__s==null&&(f.__s=f.state),A.getDerivedStateFromProps!=null&&(f.__s==f.state&&(f.__s=Cu({},f.__s)),Cu(f.__s,A.getDerivedStateFromProps(_,f.__s))),g=f.props,v=f.state,f.__v=t,p)A.getDerivedStateFromProps==null&&f.componentWillMount!=null&&f.componentWillMount(),f.componentDidMount!=null&&f.__h.push(f.componentDidMount);else{if(A.getDerivedStateFromProps==null&&_!==g&&f.componentWillReceiveProps!=null&&f.componentWillReceiveProps(_,y),!f.__e&&(f.shouldComponentUpdate!=null&&f.shouldComponentUpdate(_,f.__s,y)===!1||t.__v===n.__v)){for(t.__v!==n.__v&&(f.props=_,f.state=f.__s,f.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.forEach(function(I){I&&(I.__=t)}),S=0;S<f._sb.length;S++)f.__h.push(f._sb[S]);f._sb=[],f.__h.length&&a.push(f);break e}f.componentWillUpdate!=null&&f.componentWillUpdate(_,f.__s,y),f.componentDidUpdate!=null&&f.__h.push(function(){f.componentDidUpdate(g,v,b)})}if(f.context=y,f.props=_,f.__P=e,f.__e=!1,C=js.__r,E=0,"prototype"in A&&A.prototype.render){for(f.state=f.__s,f.__d=!1,C&&C(t),d=f.render(f.props,f.state,f.context),k=0;k<f._sb.length;k++)f.__h.push(f._sb[k]);f._sb=[]}else do f.__d=!1,C&&C(t),d=f.render(f.props,f.state,f.context),f.state=f.__s;while(f.__d&&++E<25);f.state=f.__s,f.getChildContext!=null&&(s=Cu(Cu({},s),f.getChildContext())),p||f.getSnapshotBeforeUpdate==null||(b=f.getSnapshotBeforeUpdate(g,v)),iU(e,i2(F=d!=null&&d.type===a2&&d.key==null?d.props.children:d)?F:[F],t,n,s,r,i,a,o,l,u),f.base=t.__e,t.__u&=-161,f.__h.length&&a.push(f),x&&(f.__E=f.__=null)}catch(I){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),js.__e(I,t,n)}else i==null&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=Ile(n.__e,t,n,s,r,i,a,l,u);(d=js.diffed)&&d(t)}function Dle(e,t,n){t.__d=void 0;for(var s=0;s<n.length;s++)o2(n[s],n[++s],n[++s]);js.__c&&js.__c(t,e),e.some(function(r){try{e=r.__h,r.__h=[],e.some(function(i){i.call(r)})}catch(i){js.__e(i,r.__v)}})}function Ile(e,t,n,s,r,i,a,o,l){var u,d,f,p,g,v,b,x=n.props,_=t.props,w=t.type;if(w==="svg"&&(r=!0),i!=null){for(u=0;u<i.length;u++)if((g=i[u])&&"setAttribute"in g==!!w&&(w?g.localName===w:g.nodeType===3)){e=g,i[u]=null;break}}if(e==null){if(w===null)return document.createTextNode(_);e=r?document.createElementNS("http://www.w3.org/2000/svg",w):document.createElement(w,_.is&&_),i=null,o=!1}if(w===null)x===_||o&&e.data===_||(e.data=_);else{if(i=i&&JH.call(e.childNodes),x=n.props||XE,!o&&i!=null)for(x={},u=0;u<e.attributes.length;u++)x[(g=e.attributes[u]).name]=g.value;for(u in x)g=x[u],u=="children"||(u=="dangerouslySetInnerHTML"?f=g:u==="key"||u in _||Vb(e,u,null,g,r));for(u in _)g=_[u],u=="children"?p=g:u=="dangerouslySetInnerHTML"?d=g:u=="value"?v=g:u=="checked"?b=g:u==="key"||o&&typeof g!="function"||x[u]===g||Vb(e,u,g,x[u],r);if(d)o||f&&(d.__html===f.__html||d.__html===e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(f&&(e.innerHTML=""),iU(e,i2(p)?p:[p],t,n,s,r&&w!=="foreignObject",i,a,i?i[0]:n.__k&&Mp(n,0),o,l),i!=null)for(u=i.length;u--;)i[u]!=null&&sU(i[u]);o||(u="value",v!==void 0&&(v!==e[u]||w==="progress"&&!v||w==="option"&&v!==x[u])&&Vb(e,u,v,x[u],!1),u="checked",b!==void 0&&b!==e[u]&&Vb(e,u,b,x[u],!1))}return e}function o2(e,t,n){try{typeof e=="function"?e(t):e.current=t}catch(s){js.__e(s,n)}}function JE(e,t,n){var s,r;if(js.unmount&&js.unmount(e),(s=e.ref)&&(s.current&&s.current!==e.__e||o2(s,null,t)),(s=e.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(i){js.__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]&&JE(s[r],t,n||typeof e.type!="function");n||e.__e==null||sU(e.__e),e.__=e.__e=e.__d=void 0}function Nle(e,t,n){return this.constructor(e,n)}JH=nU.slice,js={__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}},ZH=0,Yx.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=Cu({},this.state),typeof e=="function"&&(e=e(Cu({},n),this.props)),e&&Cu(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),QE(this))},Yx.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),QE(this))},Yx.prototype.render=a2,jd=[],eU=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,KE=function(e,t){return e.__v.__b-t.__v.__b},z_.__r=0,tU=0,function(e){e.Button="button",e.Tab="tab",e.Selector="selector"}(KP||(KP={})),function(e){e.Left="left",e.Center="center",e.Right="right",e.NextToTrigger="next_to_trigger"}(YE||(YE={})),function(e){e.Popover="popover",e.API="api",e.Widget="widget"}(YP||(YP={})),function(e){e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link"}(XP||(XP={})),function(e){e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question"}(QP||(QP={})),function(e){e.Once="once",e.Recurring="recurring",e.Always="always"}(JP||(JP={}));var Op=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}},Mr=li("[Surveys]"),nM={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=>Op(t,n)),not_regex:(e,t)=>e.every(n=>!Op(t,n)),exact:(e,t)=>e.some(n=>t===n),is_not:(e,t)=>e.every(n=>t!==n)};function sM(e){return e??"icontains"}YE.Right;(function(e,t){var n={__c:t="__cC"+tU++,__: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,QE(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 lU=class{constructor(){yt(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)}},Ple=class Bf{constructor(t){yt(this,"_debugEventEmitter",new lU),yt(this,"checkStep",(n,s)=>this.checkStepEvent(n,s)&&this.checkStepUrl(n,s)&&this.checkStepElement(n,s)),yt(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(!Rt((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(!Rt((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"||!Bf.matchString(r,n?.url,n?.url_matching||"contains"))return!1}return!0}static matchString(t,n,s){switch(s){case"regex":return!!qe&&Op(t,n);case"exact":return n===t;case"contains":var r=Bf.escapeStringRegexp(n).replace(/_/g,".").replace(/%/g,".*");return Op(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&&!Bf.matchString(i.href||"",n?.href,n?.href_matching||"exact"))&&(n==null||!n.tag_name||i.tag_name===n?.tag_name)&&!(n!=null&&n.text&&!Bf.matchString(i.text||"",n?.text,n?.text_matching||"exact")&&!Bf.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}},ZE=class cU{constructor(t){this.instance=t,this.eventToSurveys=new Map,this.actionToSurveys=new Map}register(t){var n;Rt((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 Ple(this.instance),this.actionMatcher.init(),this.actionMatcher._addActionHook(s=>{this.onAction(s)})),n.forEach(s=>{var r,i,a,o,l,u,d,f,p,g;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),(f=s.conditions)===null||f===void 0||(p=f.actions)===null||p===void 0||(g=p.values)===null||g===void 0||g.forEach(v=>{if(v&&v.name){var b=this.actionToSurveys.get(v.name);b&&b.push(s.id),this.actionToSurveys.set(v.name,b||[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[Mb])||[];if(cU.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[Mb])||[];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({[Mb]:[...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[Mb];return s||[]}getEventToSurveys(){return this.eventToSurveys}_getActionMatcher(){return this.actionMatcher}};yt(ZE,"SURVEY_SHOWN_EVENT_NAME","survey shown");let Mle=class{constructor(t){yt(this,"_isFetchingSurveys",!1),yt(this,"_isInitializingSurveys",!1),yt(this,"_surveyCallbacks",[]),this.instance=t,this._surveyEventReceiver=null}onRemoteConfig(t){var n=t.surveys;if(Yn(n))return Mr.warn("Decide not loaded yet. Not loading surveys.");var s=Ls(n);this._hasSurveys=s?n.length>0:n,Mr.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)Mr.info("Already initializing surveys, skipping...");else if(this.instance.config.disable_surveys)Mr.info("Disabled. Not loading surveys.");else{var t=tn?.__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 ZE(this.instance),Mr.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 Mr.error("Could not load surveys script",i),void(this._isInitializingSurveys=!1);this._surveyManager=t.generateSurveys(this.instance),this._isInitializingSurveys=!1,this._surveyEventReceiver=new ZE(this.instance),Mr.info("Surveys loaded successfully"),this._notifySurveyCallbacks({isLoaded:!0})});else{var r="PostHog loadExternalDependency extension not found. Cannot load remote config.";Mr.error(r),this._isInitializingSurveys=!1,this._notifySurveyCallbacks({isLoaded:!1,error:r})}}}catch(i){throw Mr.error("Error initializing surveys",i),this._isInitializingSurveys=!1,this._notifySurveyCallbacks({isLoaded:!1,error:"Error initializing surveys"}),i}}else Mr.info("No surveys to load.");else Mr.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 Mr.info("Disabled. Not loading surveys."),t([]);var s=this.instance.get_property(RE);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 Mr.error(o),t([],{isLoaded:!1,error:o})}var l,u=r.json.surveys||[],d=u.filter(f=>{var p,g,v,b,x,_,w,y,S,C,E,k;return((p=f.conditions)===null||p===void 0?void 0:p.events)&&((g=f.conditions)===null||g===void 0||(v=g.events)===null||v===void 0?void 0:v.values)&&((b=f.conditions)===null||b===void 0||(x=b.events)===null||x===void 0||(_=x.values)===null||_===void 0?void 0:_.length)>0||((w=f.conditions)===null||w===void 0?void 0:w.actions)&&((y=f.conditions)===null||y===void 0||(S=y.actions)===null||S===void 0?void 0:S.values)&&((C=f.conditions)===null||C===void 0||(E=C.actions)===null||E===void 0||(k=E.values)===null||k===void 0?void 0:k.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({[RE]: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){Mr.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(g){var v,b,x;if((v=g.conditions)===null||v===void 0||!v.url)return!0;var _=qe==null||(b=qe.location)===null||b===void 0?void 0:b.href;if(!_)return!1;var w=[g.conditions.url];return nM[sM((x=g.conditions)===null||x===void 0?void 0:x.urlMatchType)](w,_)}(l),f=(u=l.conditions)===null||u===void 0||!u.selector||Pt?.querySelector(l.conditions.selector),p=function(g){var v,b,x;if((v=g.conditions)===null||v===void 0||!v.deviceTypes||((b=g.conditions)===null||b===void 0?void 0:b.deviceTypes.length)===0)return!0;if(!or)return!1;var _=ks.deviceType(or);return nM[sM((x=g.conditions)===null||x===void 0?void 0:x.deviceTypesMatchType)](g.conditions.deviceTypes,_)}(l);return d&&f&&p}),a=(r=this._surveyEventReceiver)===null||r===void 0?void 0:r.getSurveys(),o=i.filter(l=>{var u,d,f,p,g,v,b,x,_;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 w=this.isSurveyFeatureFlagEnabled(l.linked_flag_key),y=this.isSurveyFeatureFlagEnabled(l.targeting_flag_key),S=((d=(f=l.conditions)===null||f===void 0||(p=f.events)===null||p===void 0||(g=p.values)===null||g===void 0?void 0:g.length)!==null&&d!==void 0?d:0)>0,C=((v=(b=l.conditions)===null||b===void 0||(x=b.actions)===null||x===void 0||(_=x.values)===null||_===void 0?void 0:_.length)!==null&&v!==void 0?v:0)>0,E=!S&&!C||a?.includes(l.id),k=this._canActivateRepeatedly(l)||this.isSurveyFeatureFlagEnabled(l.internal_targeting_flag_key),F=this.checkFlags(l);return w&&y&&k&&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 Yn((n=tn.__PosthogExtensions__)===null||n===void 0?void 0:n.canActivateRepeatedly)?(Mr.warn("init was not called"),!1):tn.__PosthogExtensions__.canActivateRepeatedly(t)}canRenderSurvey(t){if(Yn(this._surveyManager))return Mr.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?Ze({},this._surveyManager.canRenderSurvey(r)):{visible:!1,disabledReason:"Survey not found"}}),n}renderSurvey(t,n){Yn(this._surveyManager)?Mr.warn("init was not called"):this.getSurveys(s=>{var r=s.filter(i=>i.id===t)[0];this._surveyManager.renderSurvey(r,Pt?.querySelector(n))})}};var rM=li("[RateLimiter]");let Ole=class{constructor(t){var n,s;yt(this,"serverLimits",{}),yt(this,"lastEventRateLimited",!1),yt(this,"checkForLimiting",r=>{var i=r.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach(a=>{rM.info("".concat(a||"events"," is quota limited.")),this.serverLimits[a]=new Date().getTime()+6e4})}catch(a){return void rM.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(FE))!==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(FE,a),{isRateLimited:o,remainingTokens:a.tokens}}isServerRateLimited(t){var n=this.serverLimits[t||"events"]||!1;return n!==!1&&new Date().getTime()<n}};var kd=li("[RemoteConfig]");let Lle=class{constructor(t){this.instance=t}get remoteConfig(){var t,n;return(t=tn._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=tn.__PosthogExtensions__)!==null&&n!==void 0&&n.loadExternalDependency?(s=tn.__PosthogExtensions__)===null||s===void 0||(r=s.loadExternalDependency)===null||r===void 0||r.call(s,this.instance,"remote-config",()=>t(this.remoteConfig)):(kd.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 kd.info("Using preloaded remote config",this.remoteConfig),void this.onRemoteConfig(this.remoteConfig);if(this.instance.config.advanced_disable_decide)return void kd.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs(t=>{if(!t)return kd.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){kd.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()):kd.info("__preview_remote_config is disabled. Logging config instead",t):kd.error("Failed to fetch remote config from PostHog.")}};var Ble=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),td(o)||(n>t&&(i+=e.substring(t,n)),i+=o,t=n=r+1)}return n>t&&(i+=e.substring(t,e.length)),i},jle=!!CE||!!yE,iM="text/plain",q_=(e,t)=>{var[n,s]=e.split("?"),r=Ze({},t);s?.split("&").forEach(a=>{var[o]=a.split("=");delete r[o]});var i=uoe(r);return i=i?(s?s+"&":"")+i:s,"".concat(n,"?").concat(i)},Em=(e,t)=>JSON.stringify(e,(n,s)=>typeof s=="bigint"?s.toString():s,t),j1=e=>{var{data:t,compression:n}=e;if(t){if(n===Co.GZipJS){var s=NH(PH(Em(t)),{mtime:0}),r=new Blob([s],{type:iM});return{contentType:iM,body:r,estimatedSize:r.size}}if(n===Co.Base64){var i=function(l){var u,d,f,p,g,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,x=0,_="",w=[];if(!l)return l;l=Ble(l);do u=(g=l.charCodeAt(b++)<<16|l.charCodeAt(b++)<<8|l.charCodeAt(b++))>>18&63,d=g>>12&63,f=g>>6&63,p=63&g,w[x++]=v.charAt(u)+v.charAt(d)+v.charAt(f)+v.charAt(p);while(b<l.length);switch(_=w.join(""),l.length%3){case 1:_=_.slice(0,-2)+"==";break;case 2:_=_.slice(0,-1)+"="}return _}(Em(t)),a=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Em(l)))(i);return{contentType:"application/x-www-form-urlencoded",body:a,estimatedSize:new Blob([a]).size}}var o=Em(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},$m=[];yE&&$m.push({transport:"fetch",method:e=>{var t,n,{contentType:s,body:r,estimatedSize:i}=(t=j1(e))!==null&&t!==void 0?t:{},a=new Headers;as(e.headers,function(d,f){a.append(f,d)}),s&&a.append("Content-Type",s);var o=e.url,l=null;if(tP){var u=new tP;l={signal:u.signal,timeout:setTimeout(()=>u.abort(),e.timeout)}}yE(o,Ze({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(f=>{var p,g={statusCode:d.status,text:f};if(d.status===200)try{g.json=JSON.parse(f)}catch(v){Ht.error(v)}(p=e.callback)===null||p===void 0||p.call(e,g)})).catch(d=>{var f;Ht.error(d),(f=e.callback)===null||f===void 0||f.call(e,{statusCode:0,text:d})}).finally(()=>l?clearTimeout(l.timeout):null)}}),CE&&$m.push({transport:"XHR",method:e=>{var t,n=new CE;n.open(e.method||"GET",e.url,!0);var{contentType:s,body:r}=(t=j1(e))!==null&&t!==void 0?t:{};as(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)}}),ca!=null&&ca.sendBeacon&&$m.push({transport:"sendBeacon",method:e=>{var t=q_(e.url,{beacon:"1"});try{var n,{contentType:s,body:r}=(n=j1(e))!==null&&n!==void 0?n:{},i=typeof r=="string"?new Blob([r],{type:s}):r;ca.sendBeacon(t,i)}catch{}}});var eT=3e3;let Hle=class{constructor(t,n){yt(this,"isPaused",!0),yt(this,"queue",[]),this.flushTimeoutMs=Wa(n?.flush_interval_ms||eT,250,5e3,"flush interval",eT),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(Ze(Ze({},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&&Ls(a.data)&&as(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 as(this.queue,n=>{var s,r=n,i=(r?r.batchKey:null)||r.url;Rt(t[i])&&(t[i]=Ze(Ze({},r),{},{data:[]})),(s=t[i].data)===null||s===void 0||s.push(r.data)}),this.queue=[],t}};var Ule=["retriesPerformedSoFar"];let Gle=class{constructor(t){yt(this,"isPolling",!1),yt(this,"pollIntervalMs",3e3),yt(this,"queue",[]),this.instance=t,this.queue=[],this.areWeOnline=!0,!Rt(qe)&&"onLine"in qe.navigator&&(this.areWeOnline=qe.navigator.onLine,Ys(qe,"online",()=>{this.areWeOnline=!0,this.flush()}),Ys(qe,"offline",()=>{this.areWeOnline=!1}))}retriableRequest(t){var{retriesPerformedSoFar:n}=t,s=lH(t,Ule);ki(n)&&n>0&&(s.url=q_(s.url,{retry_count:n})),this.instance._send_request(Ze(Ze({},s),{},{callback:r=>{var i;r.statusCode!==200&&(r.statusCode<400||r.statusCode>=500)&&(n??0)<10?this.enqueue(Ze({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)"),Ht.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(Ze(Ze({},t),{},{transport:"sendBeacon"}))}catch(n){Ht.error(n)}this.queue=[]}},Vle=class{constructor(t){yt(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(){Ys(qe,"scroll",this._updateScrollData,{capture:!0}),Ys(qe,"scrollend",this._updateScrollData,{capture:!0}),Ys(qe,"resize",this._updateScrollData)}scrollElement(){if(!this.instance.config.scroll_root_selector)return qe?.document.documentElement;var t=Ls(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=qe?.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 qe&&(qe.scrollY||qe.pageYOffset||qe.document.documentElement.scrollTop)||0}scrollX(){if(this.instance.config.scroll_root_selector){var t=this.scrollElement();return t&&t.scrollLeft||0}return qe&&(qe.scrollX||qe.pageXOffset||qe.document.documentElement.scrollLeft)||0}};var Wle=e=>ks.personInfo({maskPersonalDataProperties:e?.config.mask_personal_data_properties,customPersonalDataProperties:e?.config.custom_personal_data_properties});let $le=class{constructor(t,n,s,r){yt(this,"_onSessionIdCallback",i=>{var a=this._getStored();if(!a||a.sessionId!==i){var o={sessionId:i,props:this._sessionSourceParamGenerator(this.instance)};this._persistence.register({[AE]:o})}}),this.instance=t,this._sessionIdManager=n,this._persistence=s,this._sessionSourceParamGenerator=r||Wle,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[AE]}getSetOnceProps(){var t,n=(t=this._getStored())===null||t===void 0?void 0:t.props;return n?"r"in n?ks.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 as(H0(this.getSetOnceProps()),(n,s)=>{s==="$current_url"&&(s="url"),t["$session_entry_".concat(XA(s))]=n}),t}};var aM=li("[SessionId]");let zle=class{constructor(t,n,s){var r;if(yt(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||yu,this._windowIdGenerator=s||yu;var i=this.config.persistence_name||this.config.token,a=this.config.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Wa(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=Br.parse(this._window_id_storage_key),l=Br.parse(this._primary_window_exists_storage_key);o&&!l?this._windowId=o:Br.remove(this._window_id_storage_key),Br.set(this._primary_window_exists_storage_key,!0)}if((r=this.config.bootstrap)!==null&&r!==void 0&&r.sessionID)try{var u=(d=>{var f=d.replace(/-/g,"");if(f.length!==32)throw new Error("Not a valid UUID");if(f[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(f.substring(0,12),16)})(this.config.bootstrap.sessionID);this._setSessionId(this.config.bootstrap.sessionID,new Date().getTime(),u)}catch(d){aM.error("Invalid sessionID in bootstrap",d)}this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return Rt(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&&Br.is_supported()}_setWindowId(t){t!==this._windowId&&(this._windowId=t,this._canUseSessionStorage()&&Br.set(this._window_id_storage_key,t))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?Br.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({[L_]:[n,t,s]}))}_getSessionId(){if(this._sessionId&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this._sessionId,this._sessionStartTimestamp];var t=this.persistence.props[L_];return Ls(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this._setSessionId(null,null,null)}_listenToReloadWindow(){Ys(qe,"beforeunload",()=>{this._canUseSessionStorage()&&Br.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=ki(a)&&a>0&&Math.abs(s-a)>864e5,u=!1,d=!i,f=!t&&Math.abs(s-r)>this.sessionTimeoutMs;d||f||l?(i=this._sessionIdGenerator(),o=this._windowIdGenerator(),aM.info("new session ID generated",{sessionId:i,windowId:o,changeReason:{noSessionId:d,activityTimeout:f,sessionPastMaximumLength:l}}),a=s,u=!0):o||(o=this._windowIdGenerator(),u=!0);var p=r===0||!t||l?s:r,g=a===0?new Date().getTime():a;return this._setWindowId(o),this._setSessionId(i,p,g),t||this.resetIdleTimer(),u&&this._sessionIdChangedHandlers.forEach(v=>v(i,o,u?{noSessionId:d,activityTimeout:f,sessionPastMaximumLength:l}:void 0)),{sessionId:i,windowId:o,sessionStartTimestamp:g,changeReason:u?{noSessionId:d,activityTimeout:f,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:r}}resetIdleTimer(){clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout(()=>{this.resetSessionId()},1.1*this.sessionTimeoutMs)}};var qle=["$set_once","$set"],su=li("[SiteApps]");let Kle=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=tn._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")||[],f=this.instance.get_property("$stored_group_properties")||{};for(var[p,g]of Object.entries(f))u[p]={id:d[p],type:p,properties:g};var{$set_once:v,$set:b}=t;return{event:Ze(Ze({},lH(t,qle)),{},{properties:Ze(Ze(Ze({},t.properties),b?{$set:Ze(Ze({},(n=(s=t.properties)===null||s===void 0?void 0:s.$set)!==null&&n!==void 0?n:{}),b)}:{}),v?{$set_once:Ze(Ze({},(r=(i=t.properties)===null||i===void 0?void 0:i.$set_once)!==null&&r!==void 0?r:{}),v)}:{}),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&&(su.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,su.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){su.error("Error while initializing PostHog app with config id ".concat(t.id),o),i(!1)}if(r&&n.loaded)try{s()}catch(o){su.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){su.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 su.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 f,p;tn["__$$ph_site_app_".concat(u)]=i.instance,(f=tn.__PosthogExtensions__)===null||f===void 0||(p=f.loadSiteApp)===null||p===void 0||p.call(f,i.instance,d,g=>{if(g)return su.error("Error while initializing PostHog app with config id ".concat(u),g)})};for(var{id:o,url:l}of t.siteApps)a(o,l)}else su.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}};var Yd,Yle=["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"],oM=function(e,t){if(!e)return!1;var n=e.toLowerCase();return Yle.concat(t||[]).some(s=>{var r=s.toLowerCase();return n.indexOf(r)!==-1})},uU=function(e,t){if(!e)return!1;var n=e.userAgent;if(n&&oM(n,t))return!0;try{var s=e?.userAgentData;if(s!=null&&s.brands&&s.brands.some(r=>oM(r?.brand,t)))return!0}catch{}return!!e.webdriver};function lM(e,t,n){return Em({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:n})}(function(e){e.US="us",e.EU="eu",e.CUSTOM="custom"})(Yd||(Yd={}));var cM="i.posthog.com";let Xle=class{constructor(t){yt(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(cM),".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]=Yd.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this._regionCache[this.apiHost]=Yd.EU:this._regionCache[this.apiHost]=Yd.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===Yd.CUSTOM)return this.apiHost+n;var s=cM+n;switch(t){case"assets":return"https://".concat(this.region,"-assets.").concat(s);case"api":return"https://".concat(this.region,".").concat(s)}}};var Qle={icontains:(e,t)=>!!qe&&t.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>!!qe&&t.href.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>!!qe&&Op(t.href,e),not_regex:(e,t)=>!!qe&&!Op(t.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};let Jle=class yi{constructor(t){var n=this;yt(this,"getWebExperimentsAndEvaluateDisplayLogic",function(){var s=arguments.length>0&&arguments[0]!==void 0&&arguments[0];n.getWebExperiments(r=>{yi.logInfo("retrieved web experiments from the server"),n._flagToExperiments=new Map,r.forEach(i=>{if(i.feature_flag_key){var a;n._flagToExperiments&&(yi.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);cr(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];yi.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())yi.logInfo("Refusing to render web experiment since the viewer is a likely bot");else if(!this.instance.config.disable_web_experiments){if(Yn(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();yi.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=yi.getWindowLocation();if(t!=null&&t.search){var n=U_(t?.search,"__experiment_id"),s=U_(t?.search,"__experiment_variant");n&&s&&(yi.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&&(yi.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!Yn(t.conditions)&&yi.matchUrlConditions(t)&&yi.matchUTMConditions(t)}static matchUrlConditions(t){var n;if(Yn(t.conditions)||Yn((n=t.conditions)===null||n===void 0?void 0:n.url))return!0;var s,r,i,a=yi.getWindowLocation();return!!a&&((s=t.conditions)===null||s===void 0||!s.url||Qle[(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 qe?.location}static matchUTMConditions(t){var n;if(Yn(t.conditions)||Yn((n=t.conditions)===null||n===void 0?void 0:n.utm))return!0;var s=ks.campaignParams();if(s.utm_source){var r,i,a,o,l,u,d,f,p,g,v,b,x,_,w,y,S=(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,C=(l=t.conditions)===null||l===void 0||(u=l.utm)===null||u===void 0||!u.utm_source||((d=t.conditions)===null||d===void 0||(f=d.utm)===null||f===void 0?void 0:f.utm_source)==s.utm_source,E=(p=t.conditions)===null||p===void 0||(g=p.utm)===null||g===void 0||!g.utm_medium||((v=t.conditions)===null||v===void 0||(b=v.utm)===null||b===void 0?void 0:b.utm_medium)==s.utm_medium,k=(x=t.conditions)===null||x===void 0||(_=x.utm)===null||_===void 0||!_.utm_term||((w=t.conditions)===null||w===void 0||(y=w.utm)===null||y===void 0?void 0:y.utm_term)==s.utm_term;return S&&E&&k&&C}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];Ht.info("[WebExperiments] ".concat(t),s)}applyTransforms(t,n,s){this._is_bot()?yi.logInfo("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?s.forEach(r=>{if(r.selector){var i;yi.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)})}}):yi.logInfo("Control variants leave the page unmodified.")}_is_bot(){return ca&&this.instance?uU(ca,this.instance.config.custom_blocked_useragents):void 0}};var zm={},tT=()=>{},jf="posthog",dU=!jle&&or?.indexOf("MSIE")===-1&&or?.indexOf("Mozilla")===-1,uM=()=>{var e;return{api_host:"https://us.i.posthog.com",ui_host:null,token:"",autocapture:!0,rageclick:!0,cross_subdomain_cookie:eoe(Pt?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:tT,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:!0,capture_pageleave:"if_capture_pageview",debug:Li&&cr(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:(qe==null||(e=qe.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;Ht.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:eT},_onCapture:tT}},dM=e=>{var t={};Rt(e.process_person)||(t.person_profiles=e.process_person),Rt(e.xhr_headers)||(t.request_headers=e.xhr_headers),Rt(e.cookie_name)||(t.persistence_name=e.cookie_name),Rt(e.disable_cookie)||(t.disable_persistence=e.disable_cookie),Rt(e.store_google)||(t.save_campaign_params=e.store_google),Rt(e.verbose)||(t.debug=e.verbose);var n=qs({},t,e);return Ls(e.property_blacklist)&&(Rt(e.property_denylist)?n.property_denylist=e.property_blacklist:Ls(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:Ht.error("Invalid value for property_denylist config: "+e.property_denylist)),n};class Zle{constructor(){yt(this,"__forceAllowLocalhost",!1)}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(t){Ht.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}}class Vy{get decideEndpointWasHit(){var t,n;return(t=(n=this.featureFlags)===null||n===void 0?void 0:n.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){yt(this,"webPerformance",new Zle),yt(this,"_personProcessingSetOncePropertiesSent",!1),yt(this,"version",Jl.LIB_VERSION),yt(this,"_internalEventEmitter",new lU),this.config=uM(),this.SentryIntegration=ile,this.sentryIntegration=t=>function(n,s){var r=OH(n,s);return{name:MH,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 Ele(this),this.toolbar=new ole(this),this.scrollManager=new Vle(this),this.pageViewManager=new fle(this),this.surveys=new Mle(this),this.experiments=new Jle(this),this.exceptions=new ple(this),this.rateLimiter=new Ole(this),this.requestRouter=new Xle(this),this.consent=new Soe(this),this.people={set:(t,n,s)=>{var r=cr(t)?{[t]:n}:t;this.setPersonProperties(r),s?.({})},set_once:(t,n,s)=>{var r=cr(t)?{[t]:n}:t;this.setPersonProperties(void 0,r),s?.({})}},this.on("eventCaptured",t=>Ht.info('send "'.concat(t?.event,'"'),t))}init(t,n,s){if(s&&s!==jf){var r,i=(r=zm[s])!==null&&r!==void 0?r:new Vy;return i._init(t,n,s),zm[s]=i,zm[jf][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(Rt(t)||SE(t))return Ht.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 Ht.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(qs({},uM(),dM(r),{name:i,token:t})),this.config.on_xhr_error&&Ht.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=r.disable_compression?void 0:Co.GZipJS,this.persistence=new L1(this.config),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new L1(Ze(Ze({},this.config),{},{persistence:"sessionStorage"}));var a=Ze({},this.persistence.props),o=Ze({},this.sessionPersistence.props);if(this._requestQueue=new Hle(_=>this._send_retriable_request(_),this.config.request_queue_config),this._retryQueue=new Gle(this),this.__request_queue=[],this.config.__preview_experimental_cookieless_mode||(this.sessionManager=new zle(this),this.sessionPropsManager=new $le(this,this.sessionManager,this.persistence)),new cle(this).startIfEnabledOrStop(),this.siteApps=new Kle(this),(n=this.siteApps)===null||n===void 0||n.init(),this.config.__preview_experimental_cookieless_mode||(this.sessionRecording=new sle(this),this.sessionRecording.startIfEnabledOrStop()),this.config.disable_scroll_properties||this.scrollManager.startMeasuringScrollPosition(),this.autocapture=new poe(this),this.autocapture.startIfEnabled(),this.surveys.loadIfEnabled(),this.heatmaps=new hle(this),this.heatmaps.startIfEnabled(),this.webVitalsAutocapture=new ule(this),this.exceptionObserver=new Toe(this),this.exceptionObserver.startIfEnabled(),this.deadClicksAutocapture=new kH(this,Eoe),this.deadClicksAutocapture.startIfEnabled(),Jl.DEBUG=Jl.DEBUG||this.config.debug,Jl.DEBUG&&Ht.info("Starting in debug mode",{this:this,config:r,thisC:Ze({},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(yu()),f=(l=r.bootstrap)!==null&&l!==void 0&&l.isIdentifiedID?d:r.bootstrap.distinctID;this.persistence.set_property(Yl,(u=r.bootstrap)!==null&&u!==void 0&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:r.bootstrap.distinctID,$device_id:f})}if(this._hasBootstrappedFeatureFlags()){var p,g,v=Object.keys(((p=r.bootstrap)===null||p===void 0?void 0:p.featureFlags)||{}).filter(_=>{var w,y;return!((w=r.bootstrap)===null||w===void 0||(y=w.featureFlags)===null||y===void 0||!y[_])}).reduce((_,w)=>{var y,S;return _[w]=((y=r.bootstrap)===null||y===void 0||(S=y.featureFlags)===null||S===void 0?void 0:S[w])||!1,_},{}),b=Object.keys(((g=r.bootstrap)===null||g===void 0?void 0:g.featureFlagPayloads)||{}).filter(_=>v[_]).reduce((_,w)=>{var y,S,C,E;return(y=r.bootstrap)!==null&&y!==void 0&&(S=y.featureFlagPayloads)!==null&&S!==void 0&&S[w]&&(_[w]=(C=r.bootstrap)===null||C===void 0||(E=C.featureFlagPayloads)===null||E===void 0?void 0:E[w]),_},{});this.featureFlags.receivedFeatureFlags({featureFlags:v,featureFlagPayloads:b})}if(this.config.__preview_experimental_cookieless_mode)this.register_once({distinct_id:mP,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(yu());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(Yl,"anonymous")}return Ys(qe,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),r.segment?rle(this,()=>this._loaded()):this._loaded(),Ro(this.config._onCapture)&&this.config._onCapture!==tT&&(Ht.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",_=>this.config._onCapture(_.event,_))),this}_onRemoteConfig(t){var n,s,r,i,a,o,l,u;if(!Pt||!Pt.body)return Ht.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=xn(t.supportedCompression,Co.GZipJS)?Co.GZipJS:xn(t.supportedCompression,Co.Base64)?Co.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){Ht.critical("`loaded` function failed",t)}this._start_queue_if_opted_in(),this.config.capture_pageview&&setTimeout(()=>{this.consent.isOptedIn()&&this._captureInitialPageview()},1),new Lle(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()||Fu(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&&(dU?this.__request_queue.push(t):this.rateLimiter.isServerRateLimited(t.batchKey)||(t.transport=t.transport||this.config.api_transport,t.url=q_(t.url,{ip:this.config.ip?1:0}),t.headers=Ze({},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=Ze({},n);a.timeout=a.timeout||6e4,a.url=q_(a.url,{_:new Date().getTime().toString(),ver:Jl.LIB_VERSION,compression:a.compression});var o=(s=a.transport)!==null&&s!==void 0?s:"fetch",l=(r=(i=cH($m,u=>u.transport===o))===null||i===void 0?void 0:i.method)!==null&&r!==void 0?r:$m[0].method;if(!l)throw new Error("No available transport method");l(a)})(Ze(Ze({},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=[];Fu(t,o=>{o&&(n=o[0],Ls(n)?i.push(o):Ro(o)?o.call(this):Ls(o)&&n==="alias"?s.push(o):Ls(o)&&n.indexOf("capture")!==-1&&Ro(this[n])?i.push(o):r.push(o))});var a=function(o,l){Fu(o,function(u){if(Ls(u[0])){var d=l;as(u,function(f){d=d[f[0]].apply(d,f.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(!Rt(t)&&cr(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&&!cr(n?.$current_url)&&(Ht.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=yu(),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=Jae(u,s!=null&&s._noTruncate?null:this.config.properties_string_max_length)).timestamp=o,Rt(s?.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=a);var f=Ze(Ze({},u.properties.$set),u.$set);if(qf(f)||this.setPersonPropertiesForFlags(f),!Yn(this.config.before_send)){var p=this._runBeforeSend(u);if(!p)return;u=p}this._internalEventEmitter.emit("eventCaptured",u);var g={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(g):this._requestQueue.enqueue(g),u}Ht.critical("This capture call is ignored due to client rate limiting.")}}else Ht.error("No event name provided to posthog.capture")}else Ht.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=Ze({},n);if(a.token=this.config.token,this.config.__preview_experimental_cookieless_mode&&(a.$cookieless_mode=!0),t==="$snapshot"){var o=Ze(Ze({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=o.distinct_id,(!cr(a.distinct_id)&&!ki(a.distinct_id)||SE(a.distinct_id))&&Ht.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var l,u=ks.properties({maskPersonalDataProperties:this.config.mask_personal_data_properties,customPersonalDataProperties:this.config.custom_personal_data_properties});if(this.sessionManager){var{sessionId:d,windowId:f}=this.sessionManager.checkAndGetSessionAndWindowId();a.$session_id=d,a.$window_id=f}this.sessionPropsManager&&qs(a,this.sessionPropsManager.getSessionProps());try{var p,g;this.sessionRecording&&qs(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this._retryQueue)===null||p===void 0||(g=p.queue)===null||g===void 0?void 0:g.length}catch(_){a.$sdk_debug_error_capturing_properties=String(_)}if(this.requestRouter.region===Yd.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=qs(a,l),t==="$pageview"&&Pt&&(a.title=Pt.title),!Rt(i)){var v=s.getTime()-i;a.$duration=parseFloat((v/1e3).toFixed(3))}or&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=qs({},u,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),Ls(this.config.property_denylist)?as(this.config.property_denylist,function(_){delete a[_]}):Ht.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(Ht.error("sanitize_properties is deprecated. Use before_send instead"),a=b(a,t));var x=this._hasPersonProcessing();return a.$process_person_profile=x,x&&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=qs({},s,r||{},t||{}),a=this.config.sanitize_properties;return a&&(Ht.error("sanitize_properties is deprecated. Use before_send instead"),i=a(i,"$set_once")),this._personProcessingSetOncePropertiesSent=!0,qf(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 Ht.uninitializedWarning("posthog.identify");if(ki(t)&&(t=t.toString(),Ht.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()))Ht.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(_m)&&(this.unregister(_m),this.register({distinct_id:t}));var a=(this.persistence.get_property(Yl)||"anonymous")==="anonymous";t!==r&&a?(this.persistence.set_property(Yl,"identified"),this.setPersonPropertiesForFlags(Ze(Ze({},s||{}),n||{}),!1),this.capture("$identify",{distinct_id:t,$anon_distinct_id:r},{$set:n||{},$set_once:s||{}}),this._cachedPersonProperties=lM(t,n,s),this.featureFlags.setAnonymousDistinctId(r)):(n||s)&&this.setPersonProperties(n,s),t!==r&&(this.reloadFeatureFlags(),this.unregister(B_))}}else Ht.error("Unique user id has not been set in posthog.identify")}setPersonProperties(t,n){if((t||n)&&this._requirePersonProcessing("posthog.setPersonProperties")){var s=lM(this.get_distinct_id(),t,n);this._cachedPersonProperties!==s?(this.setPersonPropertiesForFlags(Ze(Ze({},n||{}),t||{})),this.capture("$set",{$set:t||{},$set_once:n||{}}),this._cachedPersonProperties=s):Ht.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:Ze(Ze({},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 Ht.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(Ht.info("reset"),!this.__loaded)return Ht.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(Yl,"anonymous"),(i=this.sessionManager)===null||i===void 0||i.resetSessionId(),this._cachedPersonProperties=null,this.config.__preview_experimental_cookieless_mode)this.register_once({distinct_id:mP,$device_id:null},"");else{var o=this.config.get_device_id(yu());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(uH)?(Ht.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(Rt(n)&&(n=this.get_distinct_id()),t!==n?(this._register_single(_m,t),this.capture("$create_alias",{alias:t,distinct_id:n})):(Ht.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){var n,s,r,i,a=Ze({},this.config);Bs(t)&&(qs(this.config,dM(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 L1(Ze(Ze({},this.config),{},{persistence:"sessionStorage"})),gr.is_supported()&&gr.get("ph_debug")==="true"&&(this.config.debug=!0),this.config.debug&&(Jl.DEBUG=!0,Ht.info("set_config",JSON.stringify({config:t,oldConfig:a,newConfig:Ze({},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(Ze(Ze({},joe((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:jf;return n!==jf&&(n=jf+"."+n),n}_isIdentified(){var t,n;return((t=this.persistence)===null||t===void 0?void 0:t.get_property(Yl))==="identified"||((n=this.sessionPersistence)===null||n===void 0?void 0:n.get_property(Yl))==="identified"}_hasPersonProcessing(){var t,n,s,r;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&qf(this.getGroups())&&((t=this.persistence)===null||t===void 0||(n=t.props)===null||n===void 0||!n[_m])&&((s=this.persistence)===null||s===void 0||(r=s.props)===null||r===void 0||!r[j_]))}_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"?(Ht.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._register_single(j_,!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(),(Rt(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 ca?uU(ca,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Pt&&!this._initialPageviewCaptured&&(this._initialPageviewCaptured=!0,this.capture("$pageview",{title:Pt.title},{send_instantly:!0}))}debug(t){t===!1?(qe?.console.log("You've disabled debug mode."),localStorage&&localStorage.removeItem("ph_debug"),this.set_config({debug:!1})):(qe?.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(Yn(this.config.before_send))return t;var n=Ls(this.config.before_send)?this.config.before_send:[this.config.before_send],s=t;for(var r of n){if(s=r(s),Yn(s)){var i="Event '".concat(t.event,"' was rejected in beforeSend function");return Yae(t.event)?Ht.warn("".concat(i,". This can cause unexpected behavior.")):Ht.info(i),null}s.properties&&!qf(s.properties)||Ht.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]]=Qae(e.prototype[t[n]])})(Vy,["identify"]);var hM,Hd=(hM=zm[jf]=new Vy,function(){function e(){e.done||(e.done=!0,dU=!1,as(zm,function(t){t._dom_loaded()}))}Pt!=null&&Pt.addEventListener?Pt.readyState==="complete"?e():Ys(Pt,"DOMContentLoaded",e,{capture:!1}):qe&&Ht.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),hM),l2=m.createContext({client:Hd});function hU(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)||!hU(e[o],t[o],n))return!1}return!0}function ece(e){var t=e.children,n=e.client,s=e.apiKey,r=e.options,i=m.useRef(null),a=m.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."),Hd)},[n,s,JSON.stringify(r)]);return m.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&&!hU(r,o.options)&&Hd.set_config(r),i.current={apiKey:s,options:r??{}}):(Hd.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),Hd.init(s,r),i.current={apiKey:s,options:r??{}})}},[n,s,JSON.stringify(r)]),it.createElement(l2.Provider,{value:{client:a}},t)}var tce=function(){var e=m.useContext(l2).client;return e};function H1(e){var t=tce(),n=m.useState(function(){return t.isFeatureEnabled(e)}),s=n[0],r=n[1];return m.useEffect(function(){return t.onFeatureFlags(function(){r(t.isFeatureEnabled(e))})},[t,e]),s}var nT=function(e,t){return nT=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])},nT(e,t)};function nce(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");nT(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var U1=function(e){return typeof e=="function"},sce={componentStack:null,error:null},rce={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};(function(e){nce(t,e);function t(n){var s=e.call(this,n)||this;return s.state=sce,s}return t.prototype.componentDidCatch=function(n,s){var r=s.componentStack,i=this.props.additionalProperties;this.setState({error:n,componentStack:r});var a;U1(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 U1(s)?s():s;var a=U1(r)?it.createElement(r,{error:i.error,componentStack:i.componentStack}):r;return it.isValidElement(a)?a:(console.warn(rce.INVALID_FALLBACK),it.createElement(it.Fragment,null))},t.contextType=l2,t})(it.Component);/**
@@ -680,7 +680,7 @@ If you are trying to annotate ${s} with application data, use the '${s}.context'
680
680
  `),V=Pe.indexOf(L);if(V===-1){console.error("Diff not found in markdown content",{diff:Ie});return}const j=(Te,ae)=>Te.slice(0,ae).split(`
681
681
  `).length,q=j(Pe,V),Z=j(Pe,V+L.length),ee=W.current.querySelectorAll("[data-line]"),_e=[];for(const Te of ee){const ae=Te.getAttribute("data-line");if(!ae)continue;const we=Number.parseInt(ae,10);we>=q&&we<=Z&&_e.push(Te)}if(_e.length===0){const Te=W.current.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, td, th");for(const ae of Te)if(ae.textContent?.includes(L.trim())){_e.push(ae);break}}if(_e.length===0){console.warn("No HTML elements match diff range",{startLine:q,endLine:Z,diff:Ie});const Te=OB(Ie);W.current.appendChild(Te),Te.scrollIntoView({behavior:"smooth",block:"center"});return}const Re=window.document.createRange();Re.setStartBefore(_e[0]),Re.setEndAfter(_e[_e.length-1]);const ye=OB(Ie);Re.deleteContents(),Re.insertNode(ye),ye.scrollIntoView({behavior:"smooth",block:"center"})}catch(Pe){console.error("Failed to show diff inline:",Pe,{diff:Ie})}},[i]);m.useEffect(()=>{if(!G||!W.current)return;const{diffs:Ie,currentIndex:ge,approvedDiffs:Pe,originalContent:L}=G;let V=L;for(const{find:ee,replace:_e}of Pe)V=V.replace(ee,_e);W.current.innerHTML=Mm(V);let j=!0,q;const Z=setTimeout(()=>{const ee=Ie[ge];if(dn(ee,V),ee.find!=="")return;const _e=fe.current,Re=W.current?.querySelector("[data-diff-container]");if(!_e||!Re)return;const ye=()=>{if(!j||!Re.isConnected)return;const Te=Re.getBoundingClientRect().bottom-_e.getBoundingClientRect().top+_e.scrollTop+8;B(ae=>ae?.diff===ee&&ae.top===Te?ae:{diff:ee,top:Te})};ye(),q=new ResizeObserver(ye),q.observe(Re),q.observe(_e)},0);return()=>{j=!1,clearTimeout(Z),q?.disconnect()}},[G,dn]);const tr=Ie=>{W.current&&ne({diffs:Ie,currentIndex:0,approvedDiffs:[],originalContent:a})},Sn=(Ie,ge,Pe,L)=>{const V=fe.current;if(!V||!W.current)return;const j=V.getBoundingClientRect();let q;if(!Ie&&Pe.collapsed)try{q=NB(W.current,Pe)}catch(ee){console.warn("Failed to calculate cursor position in handleEdit:",ee),q=void 0}const Z=PB(a,Ie,q,W.current,Pe);ie({selection:Z,position:{top:ge.top-j.top,left:0},range:Pe}),L(),window.getSelection()?.removeAllRanges()};return c.jsxs("div",{"data-glass-plane":"clear",className:R("@container relative flex h-full w-full flex-col overflow-hidden bg-surface"),children:[c.jsxs("div",{"data-glass-plane":"band",className:R("flex h-10 shrink-0 flex-nowrap items-center gap-2","border-hairline border-b bg-surface px-2"),children:[c.jsx(sXe,{currentTextType:d,onTextTypeChange:cn}),c.jsx("div",{className:R("flex shrink-0 items-center gap-1"),children:uXe().map(({value:Ie,label:ge,Icon:Pe})=>{const L=p.includes(Ie);return c.jsx(vt,{content:ge,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":ge,"aria-pressed":L,onClick:()=>kn(Ie),className:R(L&&cXe),children:c.jsx(Pe,{})})},Ie)})}),c.jsxs("div",{className:R("flex shrink-0 items-center gap-1","@max-[520px]:hidden"),children:[c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.bullet_list"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.bullet_list"),onClick:()=>Ft("unordered"),children:c.jsx(rT,{})})}),c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.numbered_list"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.numbered_list"),onClick:()=>Ft("ordered"),children:c.jsx(gM,{})})}),c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.checklist"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.checklist"),onClick:()=>Ft("task"),children:c.jsx(vM,{})})})]}),c.jsxs("div",{className:R("flex shrink-0 items-center gap-1"),children:[c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.insert_link"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.insert_link"),onClick:ws,children:c.jsx(Ene,{})})}),c.jsxs(Po,{defaultOpen:s,children:[c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.more_formatting"),children:c.jsx(eo,{asChild:!0,children:c.jsx(ce,{ref:E,variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.more_formatting"),children:c.jsx(oc,{})})})}),c.jsxs(Mo,{align:"start",className:R("w-44"),children:[dXe().map(({value:Ie,label:ge,Icon:Pe})=>c.jsxs(Jt,{onSelect:()=>kn(Ie),children:[c.jsx(Pe,{"aria-hidden":"true"}),ge]},Ie)),c.jsx(Nr,{}),c.jsxs(Jt,{onSelect:()=>Ft("unordered"),children:[c.jsx(rT,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.bullet_list")]}),c.jsxs(Jt,{onSelect:()=>Ft("ordered"),children:[c.jsx(gM,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.numbered_list")]}),c.jsxs(Jt,{onSelect:()=>Ft("task"),children:[c.jsx(vM,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.checklist")]}),c.jsx(Nr,{}),c.jsxs(Jt,{onSelect:()=>rn("blockquote"),children:[c.jsx(Tne,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.quote")]}),c.jsxs(Jt,{onSelect:()=>rn("pre"),children:[c.jsx(gU,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.code_block")]}),c.jsx(Nr,{}),c.jsxs(Jt,{onSelect:cs,children:[c.jsx(Rne,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.insert_image")]}),c.jsxs(Jt,{onSelect:()=>{E.current&&zr(E.current)},children:[c.jsx(xde,{"aria-hidden":"true"}),h("ui.canvas.wysiwyg_markdown_editor.insert_table")]})]})]})]}),c.jsxs("div",{className:R("ms-auto flex shrink-0 items-center gap-1"),children:[c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.undo_ctrl_z"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.undo"),onClick:()=>{if(xe.current?.canUndo()){if(xe.current.undo(),W.current){const Ie=W.current.innerHTML,ge=nc(Ie);o(ge),u(!0)}Ee(xe.current.canUndo()),se(xe.current.canRedo())}},disabled:!me,children:c.jsx(kde,{})})}),c.jsx(vt,{content:h("ui.canvas.wysiwyg_markdown_editor.redo_ctrl_shift_z"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.wysiwyg_markdown_editor.redo"),onClick:()=>{if(xe.current?.canRedo()){if(xe.current.redo(),W.current){const Ie=W.current.innerHTML,ge=nc(Ie);o(ge),u(!0)}Ee(xe.current.canUndo()),se(xe.current.canRedo())}},disabled:!Ae,children:c.jsx(Hue,{})})})]})]}),c.jsx("div",{ref:te,"data-glass-plane":"clear",className:R("flex-1 overflow-y-auto bg-surface px-6 py-6 @min-[560px]:px-8 @min-[560px]:py-8",rXe),children:c.jsxs("div",{className:R("relative mx-auto w-full",r==="fill"?"max-w-none":"max-w-160"),ref:fe,children:[c.jsx("div",{ref:W,"data-undo-scope":"true",contentEditable:!G,onInput:ue,onKeyDown:un,onClick:Vs,onDoubleClick:En,suppressContentEditableWarning:!0,onBlur:()=>{Q&&(z.current=Q.range)}}),Q?.range&&!G&&c.jsx("span",{"aria-hidden":!0,className:R("pointer-events-none absolute rounded-xs bg-accent-wash"),style:{left:Q.range.getBoundingClientRect().left-(fe.current?.getBoundingClientRect().left??0),top:Q.range.getBoundingClientRect().top-(fe.current?.getBoundingClientRect().top??0),width:Q.range.getBoundingClientRect().width,height:Q.range.getBoundingClientRect().height}}),c.jsx(f8,{targetRef:W,scrollableContainerRef:te,showSpeech:!0,showCopy:!0,showEdit:!0,showRefer:!!e.path,onEdit:Sn,agentId:n??void 0,filePath:e.path,conversationId:t}),Q&&e.path&&U&&c.jsx(n7,{fileContent:a,selection:Q.selection,position:H?.find===""&&oe?.diff===H?{...Q.position,top:oe.top}:Q.position,filePath:e.path,onClose:()=>{ie(null),z.current=null,G&&It(G.approvedDiffs)},onApplyChanges:tr,agentId:n,reviewState:G,onApplyAll:()=>{G&&It(G.diffs)},onRejectAll:()=>{G&&It([])},onAcceptDiff:()=>{if(!G)return;const Ie=G.diffs[G.currentIndex],ge=[...G.approvedDiffs,Ie];G.currentIndex>=G.diffs.length-1?It(ge):ne({...G,approvedDiffs:ge,currentIndex:G.currentIndex+1})},onRejectDiff:()=>{G&&(G.currentIndex>=G.diffs.length-1?It(G.approvedDiffs):ne({...G,currentIndex:G.currentIndex+1}))},onNavigateDiff:Ie=>{if(!G)return;const ge=Ie==="next"?G.currentIndex+1:G.currentIndex-1;ge>=0&&ge<G.diffs.length&&ne({...G,currentIndex:ge})}})]})}),c.jsx(QYe,{show:k,initialMode:A,onClose:()=>{F(!1),Le(),W.current?.focus()},onFind:Ne,onNavigate:Ue,onReplace:dt,onReplaceAll:St,matchCount:M.length,currentMatch:O+1,containerClassName:"top-14 right-4",findValue:N,onFindValueChange:P}),c.jsx(eXe,{open:v,onClose:()=>b(!1),onInsert:Vt,initialData:x}),c.jsx(ZYe,{open:w,onClose:()=>y(!1),onInsert:Vn}),c.jsx(tXe,{anchorEl:S,onClose:()=>C(null),onInsert:ls})]})},fXe=(e,t)=>{if(e.conversationId!==t.conversationId||e.agentId!==t.agentId||e.measure!==t.measure)return!1;const n=e.document,s=t.document;return n.id===s.id&&n.title===s.title&&n.content===s.content&&n.path===s.path&&n.type===s.type&&n.lastAgentModified===s.lastAgentModified},pXe=m.memo(hXe,fXe),gXe=({document:e,conversationId:t,agentId:n})=>{const s=lg(e.path,e.type);if(e.artifact&&s!=="image"&&s!=="audio"&&s!=="video"&&s!=="pdf")return c.jsx(m1e,{document:e});switch(s){case"markdown":return c.jsx(pXe,{document:e,conversationId:t,agentId:n});case"html":return c.jsx(K1e,{document:e,conversationId:t});case"spreadsheet":return c.jsx(RWe,{document:e,conversationId:t,agentId:n});case"pdf":return c.jsx(eSe,{document:e});case"image":return c.jsx(J1e,{document:e});case"audio":return c.jsx(_1e,{document:e});case"video":return c.jsx(PWe,{document:e});default:return c.jsx(s7,{document:e,conversationId:t,agentId:n})}},mXe=m.memo(gXe),PR=({title:e,description:t,children:n})=>c.jsxs("div",{"data-glass-region":"pane-leaf",className:R("flex h-full flex-col items-center justify-center gap-2 bg-elevated p-6 text-center"),children:[c.jsx("h3",{className:R("text-heading text-ink"),children:e}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:t}),n?c.jsx("div",{className:R("mt-2 flex w-full flex-wrap items-center justify-center gap-2"),children:n}):null]}),vXe=e=>e.map(t=>t.name).sort().join(`
682
682
  `),bXe=(e,t)=>typeof e=="string"&&t.length>0&&e===t,xXe=async(e,t)=>{try{const n=await t(e);return{name:e,result:n?.already_installed?"already_present":"installed"}}catch(n){return n instanceof Fi&&n.status===409?{name:e,result:"skipped"}:{name:e,result:"failed",message:n instanceof Error&&n.message?n.message:h("ui.agents.starters.server_unanswered")}}},_Xe=async(e,t,n)=>{const s=[];for(const r of e)n?.({done:s.length,current:r}),s.push(await xXe(r,t)),n?.({done:s.length,current:null});return wXe(s)},wXe=e=>{const t={installed:0,alreadyPresent:0,skipped:[],failed:[]};for(const n of e)n.result==="installed"&&(t.installed+=1),n.result==="already_present"&&(t.alreadyPresent+=1),n.result==="skipped"&&t.skipped.push(n.name),n.result==="failed"&&t.failed.push({name:n.name,message:n.message});return t},yXe=e=>{const t=[];return e.installed>0&&t.push(h("ui.agents.starters.summary.installed",{count:e.installed})),e.alreadyPresent>0&&t.push(h("ui.agents.starters.summary.already_present",{count:e.alreadyPresent})),e.skipped.length>0&&t.push(h("ui.agents.starters.summary.skipped",{count:e.skipped.length})),e.failed.length>0&&t.push(h("ui.agents.starters.summary.failed",{count:e.failed.length})),t.length===0&&t.push(h("ui.agents.starters.summary.empty")),h("ui.agents.starters.summary.sentence",{parts:t.join(h("ui.agents.starters.summary.separator"))})},CXe=e=>{if(e.skipped.length===0)return null;const t=e.skipped.map(n=>`"${n}"`).join(", ");return h("ui.agents.starters.summary.collisions",{count:e.skipped.length,names:t})},SXe=({builtins:e,presentation:t="row",className:n,onBusyChange:s})=>{Ve();const r=Mt(),[i,a]=m.useState(!1),[o,l]=m.useState(0),[u,d]=m.useState(null),[f,p]=m.useState(null),g=m.useRef(null),v=m.useRef(null),b=m.useRef(null),x=m.useRef(!1);m.useEffect(()=>{f&&g.current?.focus()},[f]),m.useEffect(()=>{i&&b.current?.focus()},[i]),m.useEffect(()=>{f||!x.current||(x.current=!1,v.current?.focus())},[f]);const _=i||f!==null;m.useLayoutEffect(()=>{s?.(_)},[s,_]),m.useLayoutEffect(()=>()=>s?.(!1),[s]);const w=m.useCallback(async()=>{if(i||e.length===0)return;a(!0),p(null),l(0);const k=await _Xe(e.map(F=>F.name),F=>rt({op:"profiles.install",name:F,requestId:crypto.randomUUID()}),F=>{l(F.done),d(F.current)});d(null),p(k),a(!1),await r.invalidateQueries({queryKey:["desktop","profiles"]})},[e,r,i]);if(e.length===0&&!f)return null;const y=e.length,S=o+(u?1:0),C=f?CXe(f):null,E=t==="row"?"px-3":void 0;return c.jsxs("div",{className:R("flex flex-col gap-2",n),children:[!i&&!f&&(t==="primary"?c.jsx(ce,{ref:v,variant:"secondary",className:"w-full",onClick:()=>void w(),children:h("ui.agents.starters.action.all_builtins")}):c.jsxs("button",{ref:v,type:"button",onClick:()=>void w(),className:R("flex w-full cursor-pointer items-center gap-2 rounded-sm px-3 py-1.5","text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart","hover:bg-elevated"),"data-testid":"install-all-builtins-row",children:[c.jsx(xU,{className:"size-4 shrink-0","aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 flex-1",children:h("ui.agents.starters.available",{count:y})}),c.jsx("span",{className:"shrink-0 font-medium text-accent",children:h("ui.agents.starters.action.all_count",{count:y})})]})),c.jsxs("output",{ref:b,"aria-live":"polite",tabIndex:-1,"data-testid":"install-builtins-live",className:R("flex flex-col gap-2",!i&&!f&&"sr-only"),children:[i&&c.jsxs("div",{className:R("flex flex-col gap-1.5",E),"data-testid":"install-builtins-progress",children:[c.jsx(sE,{value:S,max:y,"aria-label":h("ui.agents.starters.progress.accessible",{step:String(S),total:String(y)}),className:"h-1.5 border border-control"}),c.jsx("p",{className:"text-meta text-ink-muted",children:u?h("ui.agents.starters.progress.named",{step:String(S),total:String(y),name:u}):h("ui.agents.starters.progress.count",{done:String(o),total:String(y)})})]}),f&&c.jsxs("div",{className:R("flex flex-col gap-2",E),"data-testid":"install-builtins-summary",children:[c.jsxs("p",{className:"flex items-center gap-1.5 text-body-sm text-ink",children:[c.jsx(Js,{className:"size-3.5 shrink-0 text-success","aria-hidden":"true"}),c.jsx("span",{children:yXe(f)})]}),C&&c.jsx("p",{className:"text-body-sm text-ink-muted",children:C}),f.failed.map(k=>c.jsxs("p",{className:"text-body-sm text-danger",children:[k.name,": ",k.message]},k.name)),c.jsx(ce,{ref:g,variant:"ghost",size:"sm",className:"w-fit",onClick:()=>{x.current=!0,p(null)},children:h("ui.agents.starters.action.done")})]})]})]})},kXe="max-h-[min(var(--radix-context-menu-content-available-height),50dvh)] overflow-y-auto [&_[role=menuitem]]:min-h-8";async function wk(e,t,n){const s=Ane(e,t);if(!s){n("");return}const r=sc.getState();try{const i=await r.assignSessionTags(e.session_id,s.ids,s.primary,e.tags_revision??null);if(!i)return;const a=r.categories.find(l=>l.id===t)?.name??t,o=t==="untagged"?h("ui.chat.tags.removed_all"):h("ui.chat.tags.dropped_on",{name:a});n(o),Hs(o,{action:{label:h("ui.chat.tags.undo"),onClick:()=>{r.assignSessionTags(e.session_id,(e.tags??[]).map(l=>l.id),e.primary??null,i.tags_revision??null).then(()=>{n(h("ui.chat.tags.move_undone"))}).catch(l=>{const u=FN(l)?h("ui.chat.tags.changed_elsewhere"):h("ui.chat.tags.move_failed");n(u),Ru(u)})}}})}catch(i){const a=FN(i)?h("ui.chat.tags.changed_elsewhere"):h("ui.chat.tags.move_failed");throw n(a),Ru(a),i}}function MR(e,t,n,s,r,i=!0){const a=e.getBoundingClientRect();return t<a.left||t>a.right||n<a.top||n>a.bottom?null:Array.from(e.querySelectorAll(i?"[data-tag-drop-target]":"[data-tag-drop-target]:not([data-tag-drop-body])")).find(o=>{const l=o.getBoundingClientRect();return(o.closest("[data-chat-section]")===s||r==="untagged"&&o.dataset.tagDropTarget!=="untagged"||i&&o.dataset.tagUnusedSlot!==void 0)&&!(o.dataset.tagDropBody!==void 0&&o.dataset.tagDropTarget===r)&&l.height>0&&t>=l.left&&t<=l.right&&n>=l.top&&n<=l.bottom})??null}function EXe(e,t,n,s){return MR(e,t,n,s,void 0,!1)}function TXe(e){const t=m.useRef(e);t.current=e;const n=m.useRef(null),s=m.useRef(null),[r,i]=m.useState(null),[a,o]=m.useState(null),l=m.useRef(null),u=m.useRef(()=>{}),d=m.useCallback(()=>{const g=n.current;if(!g?.armed)return;const v=MR(g.owner,g.lastX,g.lastY,g.section,g.bucket);o(v),t.current.move(g.id,g.lastY,document.elementFromPoint(g.lastX,g.lastY),v?.dataset.tagDropTarget??null)},[]),f=()=>{const g=n.current;if(!g?.armed)return;const v=g.owner.getBoundingClientRect(),b=g.lastY;b>=v.top&&b<=v.bottom&&g.lastX>=v.left&&g.lastX<=v.right&&(b-v.top<DN?g.owner.scrollTop-=IN:v.bottom-b<DN&&(g.owner.scrollTop+=IN)),d(),l.current=requestAnimationFrame(f)},p=m.useRef(()=>{});return p.current=g=>{if(!(n.current!==g||g.armed)){g.armed=!0,s.current=g.id;try{g.capture.setPointerCapture(g.pointer)}catch{}i(g.id),t.current.arm(g.id),d(),l.current=requestAnimationFrame(f)}},u.current=g=>{const v=n.current;if(!v)return;n.current=null,g||(s.current=v.id),v.timer!==null&&clearTimeout(v.timer),l.current!==null&&cancelAnimationFrame(l.current),l.current=null;const b=g&&v.armed?MR(v.owner,v.lastX,v.lastY,v.section,v.bucket):null;v.capture.hasPointerCapture(v.pointer)&&v.capture.releasePointerCapture(v.pointer),o(null),v.armed&&(t.current.settle(v.id,b?.dataset.tagDropTarget??null,g),requestAnimationFrame(()=>i(null)))},m.useEffect(()=>{const g=w=>{const y=n.current;if(!(!y||y.pointer!==w.pointerId)){if(!y.armed&&Gg(performance.now()-y.started,Math.hypot(y.lastX-y.x,y.lastY-y.y))==="armed"&&p.current(y),y.lastX=w.clientX,y.lastY=w.clientY,!y.armed){Gg(performance.now()-y.started,Math.hypot(w.clientX-y.x,w.clientY-y.y))==="cancelled"&&(s.current=y.id,u.current(!1));return}w.preventDefault(),d()}},v=w=>{if(n.current?.pointer!==w.pointerId)return;const y=n.current;if(!y.armed&&Gg(performance.now()-y.started,Math.hypot(y.lastX-y.x,y.lastY-y.y))==="armed"&&p.current(y),n.current.lastX=w.clientX,n.current.lastY=w.clientY,!n.current.armed&&Gg(performance.now()-n.current.started,Math.hypot(w.clientX-n.current.x,w.clientY-n.current.y))==="cancelled"){u.current(!1);return}d(),u.current(!0)},b=w=>{n.current?.armed&&w.preventDefault()},x=()=>u.current(!1),_=w=>{w.key==="Escape"&&n.current&&(w.preventDefault(),x())};return window.addEventListener("pointermove",g,{passive:!1}),window.addEventListener("touchmove",b,{passive:!1}),window.addEventListener("pointerup",v),window.addEventListener("pointercancel",x),window.addEventListener("blur",x),window.addEventListener("keydown",_),()=>{x(),window.removeEventListener("pointermove",g),window.removeEventListener("touchmove",b),window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",x),window.removeEventListener("blur",x),window.removeEventListener("keydown",_)}},[d]),m.useEffect(()=>{e.enabled||u.current(!1)},[e.enabled]),m.useEffect(()=>{if(!a)return;const g=a.closest("[data-chat-tag-group]")??a;return g.dataset.tagDropPreview="true",g.classList.add(...Gm),a.classList.add("bg-row-selected"),()=>{delete g.dataset.tagDropPreview,g.classList.remove(...Gm),a.classList.remove("bg-row-selected")}},[a]),{armedId:r,consumeClick(g,v){return v===0||s.current!==g?!1:(s.current=null,!0)},start(g,v){if(!t.current.enabled||v.button!==0||!v.isPrimary)return;const b=v.target;if(b.closest("a,input,select,textarea,[role=button],[role=checkbox],[data-pin-grip],[data-tag-chip]")||b.closest("button")!==v.currentTarget)return;const x=v.currentTarget.closest("[data-tag-drag-list]"),_=v.currentTarget.closest("[data-chat-section]");if(!x||!_||!v.currentTarget.closest("[data-chat-tag-group]"))return;u.current(!1),s.current=null;const w={id:g,pointer:v.pointerId,x:v.clientX,y:v.clientY,lastX:v.clientX,lastY:v.clientY,started:performance.now(),armed:!1,owner:x,section:_,bucket:v.currentTarget.closest("[data-chat-tag-group]")?.dataset.chatTagGroup??"",capture:v.currentTarget,timer:null};w.timer=setTimeout(()=>{Gg(performance.now()-w.started,Math.hypot(w.lastX-w.x,w.lastY-w.y))==="armed"&&p.current(w)},Fne),n.current=w}}}const RXe={info:15e3,error:45e3},AXe=3e4,x0=new Map,kx=e=>{const t=x0.get(e);t!==void 0&&clearTimeout(t),x0.delete(e)},vl=sg()((e,t)=>({pending:new Set,notes:{},rollups:{},begin:n=>{kx(`note:${n}`),e(s=>{const r={...s.notes};return delete r[n],{pending:new Set(s.pending).add(n),notes:r}})},end:n=>e(s=>{const r=new Set(s.pending);return r.delete(n),{pending:r}}),setNote:(n,s)=>{if(kx(`note:${n}`),!s){e(r=>{if(!(n in r.notes))return r;const{[n]:i,...a}=r.notes;return{notes:a}});return}e(r=>({notes:{...r.notes,[n]:s}})),x0.set(`note:${n}`,setTimeout(()=>t().setNote(n,null),RXe[s.tone]))},setRollup:(n,s)=>{if(kx(`rollup:${n}`),s===null){e(r=>{if(!(n in r.rollups))return r;const{[n]:i,...a}=r.rollups;return{rollups:a}});return}e(r=>({rollups:{...r.rollups,[n]:s}})),x0.set(`rollup:${n}`,setTimeout(()=>t().setRollup(n,null),AXe))},pruneNotes:n=>{const{notes:s,pending:r}=t(),i=Object.entries(s).filter(([a,o])=>o.tone==="error"&&!a.startsWith("all:")&&a!=="check"&&!n.has(a)&&!r.has(a)).map(([a])=>a);for(const a of i)t().setNote(a,null)},reset:()=>{for(const n of[...x0.keys()])kx(n);e({pending:new Set,notes:{},rollups:{}})}})),Jq="0.72.1",FXe=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function DXe(e){const t=typeof e=="string"?FXe.exec(e):null;if(!t)return!1;const n=[Number(t[1]),Number(t[2]),Number(t[3])];if(!n.every(Number.isSafeInteger))return!1;const s=[0,72,1];for(let r=0;r<s.length;r++)if(n[r]!==s[r])return n[r]>s[r];return!0}function OR(e){return!!e&&e.state==="attached"&&!!e.url&&!!e.instanceId&&Number.isSafeInteger(e.pid)&&(e.pid??0)>0&&DXe(e.version)}const Zq=()=>h("ui.hub.status.core_update_required",{minimum:Jq});class gh extends Error{constructor(){super(Zq()),this.name="HubMutationUpgradeRequired"}}const jB=(e,t)=>e.url===t.url&&e.instanceId===t.instanceId&&e.pid===t.pid;async function FC(e,t,n=typeof window>"u"?void 0:window.api?.backend){if(!OR(t)||!n?.getStatus||!n.onStatusChange)throw new gh;let s=null,r=!1;const i=n.onStatusChange(a=>{s=a,t&&!jB(t,a)&&(r=!0)});try{let a;try{a=await n.getStatus()}catch{throw new gh}const o=s??a;if(r||!OR(o)||!jB(t,o))throw new gh;return await e()}finally{i()}}function DC(){const e=og(),t=e.data?.snapshot,n=!!window.api?.backend&&!e.isError&&!e.isPlaceholderData&&OR(t),s=!window.api?.backend||e.isError||!!t&&t.state!=="attached",r=!s&&(!t||e.isPlaceholderData);return{canWrite:n,snapshot:t,upgradeMessage:n?null:r?h("ui.hub.status.backend_checking"):s?h("ui.hub.status.backend_disconnected",{minimum:Jq}):Zq()}}const IXe={agent:"agents",team:"teams",skill:"skills"},Ev=(e,t)=>`${e}:${t}`;function NXe(e){const t=new Map;for(const n of e?.items??[])t.set(Ev(n.kind,n.name),n);return t}const PXe={get"provider-error"(){return h("ui.hub.updates.error.provider")},get"model-unavailable"(){return h("ui.hub.updates.error.model_unavailable")},get"prompt-too-long"(){return h("ui.hub.updates.error.prompt_too_long")},get"merge-refused"(){return h("ui.hub.updates.error.merge_refused")},get"concurrent-edit"(){return h("ui.hub.updates.error.concurrent_edit")},get"hub-item-missing"(){return h("ui.hub.updates.error.item_missing")},get"no-credential"(){return h("ui.hub.updates.error.no_credential")},get"hub-error"(){return h("ui.hub.updates.error.hub")}},MXe=()=>h("ui.hub.updates.error.generic");function Tv(e){return(e?PXe[e.split("/")[0]]:null)??MXe()}function HB(e){return Tv(e.error_class)}const OXe=new Set(["hub-item-missing","prompt-too-long"]),UB=e=>({kind:"failed",retryable:!(e.error_class&&OXe.has(e.error_class))}),eK=e=>e.classification==="both-changed"||e.classification==="baseline-unknown";function tK(e){if(!e||e.error_class==="no-credential")return null;if(e.error_class==="merge-refused")return{kind:"review"};switch(e.state){case"updating":return{kind:"updating"};case"applied":return{kind:"applied"};case"failed":return UB(e);case"available":return e.error_class?UB(e):eK(e)?{kind:"review"}:{kind:"available",auto:e.auto_will_apply===!0};default:return null}}function LXe(e,t){switch(t.kind){case"available":return h("ui.hub.updates.mark.update",{name:e});case"review":return h("ui.hub.updates.mark.review",{name:e});case"failed":return t.retryable?h("ui.hub.updates.mark.retry",{name:e}):h("ui.hub.updates.mark.failure_details",{name:e});case"updating":return h("ui.hub.updates.mark.updating",{name:e});case"applied":return h("ui.hub.updates.mark.applied",{name:e})}}function BXe(e){switch(e.kind){case"available":return h("ui.hub.updates.action.update");case"review":return h("ui.hub.updates.action.review");case"failed":return e.retryable?h("ui.hub.updates.action.retry"):h("ui.hub.updates.action.details");default:return null}}function jXe(e,t=Date.now()){if(!e)return null;const n=Date.parse(e);if(!Number.isFinite(n))return null;const s=Math.max(0,Math.floor((t-n)/6e4));if(s<1)return h("ui.hub.updates.ago.now");if(s<60)return h("ui.hub.updates.ago.minutes",{count:s});const r=Math.floor(s/60);return r<24?h("ui.hub.updates.ago.hours",{count:r}):null}function HXe(e,t,n=Date.now()){switch(t.kind){case"available":return t.auto?h("ui.hub.updates.detail.available_auto"):eK(e)?h("ui.hub.updates.detail.needs_decision"):h("ui.hub.updates.detail.available");case"review":return e.error_class?HB(e):e.classification==="baseline-unknown"?h("ui.hub.updates.detail.baseline_unknown"):h("ui.hub.updates.detail.needs_decision");case"failed":return HB(e);case"updating":return h("ui.hub.updates.detail.updating");case"applied":{const s=jXe(e.last_applied_at,n);return s?h("ui.hub.updates.detail.applied_ago",{ago:s}):h("ui.hub.updates.detail.applied")}}}function UXe(e,t){return(e?.items??[]).filter(n=>n.kind===t&&tK(n)?.kind==="available").length}const GXe=()=>h("ui.hub.updates.sign_in");function VXe(e){return(e?.items??[]).some(n=>n.error_class==="no-credential")?GXe():null}function WXe(e,t){switch(e.outcome){case"merged":return e.applied?t?{message:t==="local"?h("ui.hub.updates.report.merged_local"):h("ui.hub.updates.report.merged_remote"),tone:"info"}:e.classification==="both-changed"||e.classification==="baseline-unknown"?{message:h("ui.hub.updates.report.merged_edits"),tone:"info"}:null:null;case"unchanged":case"up-to-date":return{message:h("ui.hub.updates.report.unchanged"),tone:"info"};case"would-merge":return{message:h("ui.hub.updates.report.would_merge"),tone:"info"};case"needs-review":return{message:e.classification==="baseline-unknown"?h("ui.hub.updates.report.review_baseline"):h("ui.hub.updates.error.merge_refused"),tone:"info"};case"skipped":return{message:h("ui.hub.updates.report.skipped",{reason:Tv(e.skipped_reason)}),tone:"error"};default:return{message:Tv(e.error_class),tone:"error"}}}const $Xe=new Set(["merge-refused"]);function zXe(e){let t=0,n=0,s=0,r=0,i=0;const a=[];let o=null;for(const u of e){const d=u.error_class??null,f=u.outcome==="needs-review"&&(!d||$Xe.has(d));u.applied?t+=1:f?a.push(u.name):u.outcome==="would-merge"?n+=1:u.outcome==="skipped"?(r+=1,o??=Tv(u.skipped_reason)):u.outcome==="unchanged"||u.outcome==="up-to-date"?i+=1:(s+=1,o??=Tv(d))}const l=[];if(t&&l.push(h("ui.hub.updates.rollup.updated",{count:t})),n&&l.push(h("ui.hub.updates.rollup.ready",{count:n})),a.length){const u=a.filter(Boolean),d=u.length?` (${u.slice(0,2).join(", ")}${u.length>2?` +${u.length-2}`:""})`:"";l.push(h("ui.hub.updates.rollup.review",{count:a.length,who:d}))}return s&&l.push(h("ui.hub.updates.rollup.failed",{count:s})),r&&l.push(h("ui.hub.updates.rollup.skipped",{count:r})),l.length?`${l.join(", ")}${o?`. ${o}`:""}`:i?h("ui.hub.updates.rollup.all_current"):h("ui.hub.updates.rollup.nothing")}function qXe(e){const t=(e?.items??[]).filter(n=>n.state==="available").length;return e?e.credential==="none"&&t===0?h("ui.hub.updates.check.sign_in"):t?h("ui.hub.updates.check.waiting",{count:t}):h("ui.hub.updates.check.current"):h("ui.hub.updates.check.checked")}const p_=["desktop","hub-updates"];function KXe(e){const t=Dn({queryKey:p_,enabled:e,queryFn:()=>rt({op:"hub.updates"}),staleTime:3e4,retry:Mv,refetchInterval:6e4,refetchIntervalInBackground:!1}),n=t.data;return m.useEffect(()=>{n&&vl.getState().pruneNotes(new Set(n.items.map(s=>Ev(s.kind,s.name))))},[n]),t}const YXe=()=>h("ui.hub.updates.slow_note");function XXe(){const e=Mt(),t=DC(),n=vl(u=>u.pending),s=vl(u=>u.notes),r=vl(u=>u.rollups),i=vl,a=u=>{if(u.status&&e.setQueryData(p_,u.status),e.invalidateQueries({queryKey:p_}),u.reports?.some(d=>d.applied))for(const d of["profiles","profile","teams","team"])e.invalidateQueries({queryKey:["desktop",d]})},o=async(u,d,f)=>{i.getState().begin(u);try{const p=await FC(d,t.snapshot);return a(p),p}catch(p){return HI(p)&&e.invalidateQueries({queryKey:p_}),i.getState().setNote(u,{message:p instanceof gh?p.message:HI(p)?YXe():zi(p,f),tone:"error"}),null}finally{i.getState().end(u)}},l=(u,d,f,p)=>{const g=d?.find(f);i.getState().setNote(u,g?WXe(g,p):null)};return{...t,pending:n,notes:s,rollups:r,applyItem:async(u,d,f={})=>{const p=Ev(u,d),g=await o(p,()=>rt({op:"hub.apply",requestId:crypto.randomUUID(),kind:u,name:d,...f.prefer?{prefer:f.prefer}:{},...f.acknowledgeUnknownBaseline?{acknowledgeUnknownBaseline:!0}:{},...f.dryRun?{dryRun:!0}:{}}),h("ui.hub.updates.error.update_named",{name:d}));return g&&!f.dryRun&&l(p,g.reports,v=>v.kind===u&&v.name===d,f.prefer),g?.reports??null},retryItem:async(u,d)=>{const f=Ev(u,d),p=await o(f,()=>rt({op:"hub.retry",requestId:crypto.randomUUID(),kind:u,name:d}),h("ui.hub.updates.error.retry_named",{name:d}));return p&&l(f,p.reports,g=>g.kind===u&&g.name===d),p?.reports??null},checkNow:async()=>{const u=await o("check",()=>rt({op:"hub.check",requestId:crypto.randomUUID()}),h("ui.hub.updates.error.check"));u&&i.getState().setNote("check",{message:qXe(u.status),tone:"info"})},applyAll:async u=>{const d=`all:${u}`,f=await o(d,()=>rt({op:"hub.applyAll",requestId:crypto.randomUUID(),kind:u}),h("ui.hub.updates.error.update_all"));return f&&i.getState().setRollup(u,zXe(f.reports??[])),f?.reports??null},clearRollup:u=>i.getState().setRollup(u,null),clearNote:u=>i.getState().setNote(u,null)}}const Xu=["desktop","hub-links"];function QXe(e){return Dn({queryKey:Xu,enabled:e,queryFn:async()=>{const t=await rt({op:"hub.links"});if(!Array.isArray(t?.links)||!Array.isArray(t.unresolved))throw new Error("hub-links-inventory-invalid");return t},staleTime:3e4,refetchInterval:6e4,refetchIntervalInBackground:!1,retry:Mv})}function JXe(){const e=Mt(),t=DC();return{...fn({mutationFn:({link:s,patch:r})=>FC(()=>rt({op:"hub.policy",requestId:crypto.randomUUID(),linkId:s.link_id,expectedPolicyRevision:s.policy.revision,...r.subscribe!==void 0?{subscribe:r.subscribe}:{},...r.auto_push!==void 0?{autoPush:r.auto_push}:{},...r.confirm_public_egress!==void 0?{confirmPublicEgress:r.confirm_public_egress}:{}}),t.snapshot),onSuccess:({link_id:s,policy:r})=>{e.setQueryData(Xu,i=>i&&{...i,links:i.links.map(a=>a.link_id===s?{...a,policy:r}:a)})},onSettled:()=>{e.invalidateQueries({queryKey:Xu}),e.invalidateQueries({queryKey:["desktop","hub-updates"]})}}),...t}}const udt=e=>"link_id"in e;function ZXe(e,t,n){return n?{kind:e.kind,localId:e.local_id}:{kind:e.kind,name:t?.trim()?t:e.name}}function GB(e){const t=new Map;for(const n of e??[]){const s=n.name.trim().toLowerCase();t.set(s,(t.get(s)??0)+1)}return t}function eQe(e,t={}){const n=Mt(),s=ZXe(e,t.displayName,t.itemsById===!0),r=DC(),i=e.link_id,a=`link:${i}`,o=vl(u=>u.pending.has(a)),l=fn({onMutate:u=>{const d=vl.getState();if(u.linkId!==i||d.pending.has(a))throw new Error("hub-action-busy");return d.begin(a),a},mutationFn:u=>FC(async()=>{const d=crypto.randomUUID();switch(u.action){case"check":return rt({op:"hub.check",requestId:d,...s});case"apply":return rt({op:"hub.apply",requestId:d,...s,...u.preview?{dryRun:!0}:{},...u.prefer?{prefer:u.prefer}:{},...u.acknowledgeUnknownBaseline?{acknowledgeUnknownBaseline:!0}:{}});case"retry":return rt({op:"hub.retry",requestId:d,...s});case"preview":return rt({op:"hub.push",requestId:d,linkId:u.linkId,direction:"push",dryRun:!0});case"confirm":return rt({op:"hub.push",requestId:d,linkId:u.linkId,direction:"push",dryRun:!1,previewReceipt:u.previewReceipt,confirmPublish:!0})}},r.snapshot),onSuccess:u=>{if(u.links&&n.setQueryData(Xu,u.links),n.setQueryData(["desktop","hub-updates"],u.status),u.reports.some(d=>d.applied))for(const d of["profiles","teams","skills"])n.invalidateQueries({queryKey:["desktop",d]})},onSettled:(u,d,f,p)=>{p&&vl.getState().end(p),n.invalidateQueries({queryKey:Xu})}});return{...l,...r,isPending:l.isPending||o}}function ddt(e){const t=Mt(),n=DC();return{...fn({onMutate:r=>{const i=`resolve:${r.kind}:${r.localId}`,a=vl.getState();if(a.pending.has(i))throw new Error("hub-action-busy");return a.begin(i),i},mutationFn:r=>FC(()=>rt({op:"hub.apply",requestId:crypto.randomUUID(),kind:r.kind,name:r.name,resolveSource:!0,hubSource:r.hubSource,visibility:r.visibility,tenantId:r.tenantId,acknowledgeUnknownBaseline:!0}),n.snapshot),onSuccess:r=>{Hs(h("ui.hub.links.resolve_action_done")),e?.(),r.links&&t.setQueryData(Xu,r.links),t.setQueryData(["desktop","hub-updates"],r.status)},onSettled:(r,i,a,o)=>{o&&vl.getState().end(o),t.invalidateQueries({queryKey:Xu})}}),...n}}function tQe(e){return e!=="adopt-unknown"}function hdt(e){return e.content_state==="absent"?"absent":"present"}function nQe(e,t,n,s){return(e?.links??[]).filter(r=>r.kind===t&&(n?r.local_id===n:r.name===s))}function sQe(e,t,n,s){return(e?.unresolved??[]).filter(r=>r.kind===t&&(n?r.local_id===n:r.name===s))}const rQe=0,Zw=rQe;function iQe(e,t){const n=e.binding?.team??"";return`${e.title??""} ${e.binding?.agent??""} ${n} ${n&&t?t(n):""}`.toLocaleLowerCase()}function nK(e,t,n){const s=t.trim().toLocaleLowerCase();return s?iQe(e,n).includes(s):!1}const aQe={include:!1,facts:{},forgotten:new Set},oQe=new Set;function LR(e,t,n,s={},r=aQe,i,a){const o=t.trim(),l=r.forgotten??oQe,u=l.size===0?e:e.filter(_=>!l.has(_.session_id)),d=n===null||l.size===0?n:n.filter(_=>!l.has(_.id));if(!o)return{rows:u,conversationMatches:new Set,synthesized:new Set};const f=(_,w)=>r.facts[_]??w===!0,p=new Map((d??[]).map(_=>[_.id,_])),g=new Set,v=[],b=new Set;for(const _ of u){const w=p.get(_.session_id),y=nK(_,o,a);!w&&!y||(b.add(_.session_id),w?.body_match&&!y&&g.add(_.session_id),v.push({row:_,rank:Math.min(w?.rank??Zw,y?Zw:Number.POSITIVE_INFINITY)}))}const x=new Set;for(const _ of d??[]){if(b.has(_.id))continue;const w=f(_.id,_.archived);if(w&&!r.include)continue;x.add(_.id);const y=s[_.id],S=i?.(_.id),C={session_id:_.id,title:_.name,updated_at:_.mtime,...S===void 0?{}:{binding:S},...(()=>{const E=y??_.pinned;return typeof E=="boolean"?{pinned:E}:{}})(),archived:w};_.body_match&&g.add(_.id),v.push({row:C,rank:_.rank})}return{rows:v.map((_,w)=>({entry:_,index:w})).sort((_,w)=>_.entry.rank-w.entry.rank||(w.entry.row.updated_at??0)-(_.entry.row.updated_at??0)||_.index-w.index).map(({entry:_})=>_.row),conversationMatches:g,synthesized:x}}function lQe(e){return e.marked?"conversation":e.unstarted?"not_sent":e.agentOpened?e.team?"team":"none":!e.nested&&e.binding?"binding":"none"}function VB(e,t){return e>t}function WB(e,t){const n=t.trim();return!e||!n?!1:e.query===n}function BR(e,t=py){return e.trim().length>t}function cQe(e,t,n=py){const s=e.trim(),r=t.trim();return BR(r,n)?BR(s,n)?r:s:r}function uQe(e,t){return typeof t=="number"&&t>0&&e>=t}const sK=150;function dQe(e,t=!1){return["desktop","sessions","search",e,t]}function rK(e,t,n=!1){const s=Eg(e.trim(),sK),r=cQe(e,s),i=BR(r),a=Dn({queryKey:dQe(r,n),enabled:t&&r.length>0&&!i,queryFn:async()=>{const o=Fe.getState().beginAnswer(),l=await rt({op:"sessions.search",q:r,limit:TQ,...n?{include_archived:!0}:{}});return Fe.getState().applySearchAnswer(o,l.sessions??[]),l},staleTime:3e4,placeholderData:EQ,retry:!1});return{settled:r,refused:i,...a}}function hQe(e){const{scope:t,hasTerms:n,terms:s,awaiting:r,catalogue:i}=e;if(r)return{line:h("ui.command_palette.palette_search.searching_conversations"),hint:null};if(t==="chat"&&!n)return i==="loading"?{line:h("ui.command_palette.palette_search.loading_conversations"),hint:null}:{line:h("ui.command_palette.palette_search.no_conversations_yet"),hint:h("ui.command_palette.palette_search.start_a_chat_and_it_will_show_up_here")};if(n){const a=jR.find(o=>o.scope===t)?.glyph;return{line:h("ui.command_palette.empty.no_matches",{terms:s}),hint:a?h("ui.command_palette.empty.backspace",{glyph:a}):h("ui.command_palette.palette_search.try_another_word_or_narrow_the_search_with_a_prefix_below")}}return{line:h("ui.command_palette.palette_search.nothing_to_show_yet"),hint:h("ui.command_palette.palette_search.search_for_a_chat_an_agent_or_team_by_name_a_setting_or_a_page_su")}}const fQe={">":"command","#":"chat","@":"agent",",":"setting"},pQe={command:"command",commands:"command",action:"command",actions:"command",page:"command",pages:"command",go:"command",chat:"chat",chats:"chat",conversation:"chat",conversations:"chat",session:"chat",sessions:"chat",agent:"agent",agents:"agent",bot:"agent",bots:"agent",team:"agent",teams:"agent",setting:"setting",settings:"setting",preference:"setting",preferences:"setting",config:"setting"},$B={command:["navigation","actions","panels"],chat:["chats"],agent:["agents","teams"],setting:["settings"]},jR=[{glyph:">",scope:"command",get label(){return h("ui.command_palette.palette_search.commands_and_pages")}},{glyph:"#",scope:"chat",get label(){return h("ui.command_palette.palette_search.chats")}},{glyph:"@",scope:"agent",get label(){return h("ui.command_palette.palette_search.agents_and_teams")}},{glyph:",",scope:"setting",get label(){return h("ui.command_palette.palette_search.settings")}}],gQe="#",mQe="@",vQe=">";function ey(e){const t=e.trim();if(!t)return{scope:null,terms:""};const n=fQe[t[0]];if(n)return{scope:n,terms:t.slice(1).trim()};const[s,...r]=t.split(_Qe),i=r.length>0?pQe[zd(s)]:void 0;return i?{scope:i,terms:r.join(" ").trim()}:{scope:null,terms:t}}const bQe=new RegExp("\\p{M}","gu"),xQe=/[^a-z0-9]+/g,_Qe=/\s+/;function zd(e){return e.normalize("NFD").replace(bQe,"").toLowerCase().replace(xQe," ").trim()}function wQe(e){const t=zd(e);return t?t.split(" "):[]}const yQe={exact:1,prefix:.9,substring:.55,subsequence:.3};function CQe(e,t){if(!e||!t)return null;if(e===t)return"exact";const n=e.split(" ");for(const r of n)if(r===t)return"exact";for(const r of n)if(r.startsWith(t))return"prefix";if(e.includes(t))return"substring";if(t.length<3)return null;let s=0;for(const r of e)if(r===t[s]&&(s+=1),s===t.length)return"subsequence";return null}const cm={name:1,keywords:.85,hint:.5,group:.4,soft:.3};function SQe(e){return{name:zd(e.name),keywords:(e.keywords??[]).map(zd).join(" ").trim(),hint:zd(e.hint??""),group:FQe[e.group].map(zd),soft:zd(e.soft??"")}}function kQe(e,t){if(t.length===0)return{score:0,soft:!1};let n=0,s=!1;for(const r of t){let i=0,a=null;const o=(l,u)=>{const d=CQe(l,r);if(!d)return;const f=yQe[d]*u;f>i&&(i=f,a=d)};o(e.name,cm.name),o(e.keywords,cm.keywords),o(e.hint,cm.hint);for(const l of e.group)o(l,cm.group);if(o(e.soft,cm.soft),!a)return null;a==="subsequence"&&(s=!0),n+=i}return{score:n/t.length,soft:s}}const EQe={0:.5,1:.35,2:.12,3:-.05},TQe=.55,_0=3;function RQe(e,t,n){const s=kQe(t,n),r=e.tier===void 0?0:EQe[e.tier]??0;if(!s)return e.tier===void 0?null:{item:e,score:TQe+r,soft:e.tier===_0};const i=n.join(" ");let a=0;return t.name===i?a+=.3:(t.name.startsWith(`${i} `)||t.name.startsWith(i))&&(a+=.15),{item:e,score:s.score+r+a,soft:s.soft||e.tier===_0}}const Rd={get navigation(){return h("ui.command_palette.palette_search.go_to")},get chats(){return h("ui.command_palette.palette_search.chats")},get agents(){return h("ui.command_palette.palette_search.agents")},get teams(){return h("ui.command_palette.palette_search.teams")},get actions(){return h("ui.command_palette.palette_search.actions")},get panels(){return h("ui.command_palette.palette_search.panels")},get settings(){return h("ui.command_palette.palette_search.settings")}},AQe={get navigation(){return Rd.navigation},get chats(){return Rd.chats},get agents(){return Rd.agents},get teams(){return Rd.teams},get actions(){return Rd.actions},get panels(){return Rd.panels},get settings(){return Rd.settings},get unread(){return h("ui.command_palette.palette_search.unread")},get recents(){return h("ui.command_palette.palette_search.recents")}},FQe={navigation:["Go to","Pages","Navigation","Tab"],chats:["Chats","Conversations","Chat"],agents:["Agents","Bots"],teams:["Teams","Team"],actions:["Actions","Commands"],panels:["Panels","Panels and reports","Views"],settings:["Settings","Preferences"]},yk=["navigation","chats","agents","teams","actions","panels","settings"],DQe=6,IQe=24,um=48,NQe=5,PQe={navigation:6,chats:5,agents:5,teams:5,actions:5,panels:5,settings:8};function MQe({items:e,raw:t}){const{scope:n,terms:s}=ey(t),r=n?$B[n]:null,i=wQe(s),a=e.filter(g=>!r||r.includes(g.group));if(i.length===0){const g=[];let v=0,b=0;const x=new Set;if(n==="chat"){const _=a.filter(y=>y.group==="chats"&&y.unread===!0&&y.featured).sort(Ex);if(_.length>0){v+=_.length;const y=Math.max(0,Math.min(_.length,um-b));if(y>0){const S=_.slice(0,y);g.push({group:"unread",items:S.map(C=>({item:C,score:0,soft:C.tier===_0}))}),b+=S.length}for(const S of _)x.add(S.id)}const w=a.filter(y=>y.group==="chats"&&y.featured&&y.recentRank!==void 0&&y.current!==!0&&y.archived!==!0&&!x.has(y.id)).sort((y,S)=>(y.recentRank??0)-(S.recentRank??0)||Ex(y,S));if(w.length>0){const y=w.slice(0,NQe);v+=y.length;const S=Math.max(0,um-b);if(S>0){const C=y.slice(0,S);g.push({group:"recents",items:C.map(E=>({item:E,score:0,soft:E.tier===_0}))}),b+=C.length}for(const C of y)x.add(C.id)}}for(const _ of yk){if(r&&!r.includes(_))continue;const w=a.filter(E=>E.group===_&&E.featured&&!x.has(E.id)).sort(Ex);if(w.length===0)continue;v+=w.length;const y=PQe[_],S=Math.max(0,Math.min(y,um-b));if(S===0)continue;const C=w.slice(0,S).map(E=>({item:E,score:0,soft:E.tier===_0}));g.push({group:_,items:C}),b+=C.length}return{sections:g,scope:n,terms:"",total:v,clipped:b<v}}const o=new Map;let l=0;for(const g of a){const v=SQe(g),b=RQe(g,v,i);if(!b)continue;l+=1;const x=o.get(g.group);x?x.push(b):o.set(g.group,[b])}const u=g=>n&&$B[n].includes(g)?IQe:DQe,d=[...o.entries()].sort((g,v)=>{const b=zB(v[1])-zB(g[1]);return b!==0?b:yk.indexOf(g[0])-yk.indexOf(v[0])}),f=[];let p=0;for(const[g,v]of d){v.sort((_,w)=>w.score-_.score||Ex(_.item,w.item));const b=u(g),x=Math.max(0,Math.min(b,um-p));if(x!==0&&(f.push({group:g,items:v.slice(0,x)}),p+=f[f.length-1].items.length,p>=um))break}return{sections:f,scope:n,terms:s,total:l,clipped:p<l}}function zB(e){let t=Number.NEGATIVE_INFINITY;for(const n of e)n.score>t&&(t=n.score);return t}function Ex(e,t){return(e.order??0)-(t.order??0)||e.id.localeCompare(t.id)}const OQe={general:{icon:"settings",keywords:["basics","startup","launch","language","profile","user"]},appearance:{icon:"theme",keywords:["theme","dark mode","light mode","colours","colors","font","zoom","palette"]},radient:{icon:"account",keywords:["account","login","sign in","credits","billing","plan","usage"]},integrations:{icon:"integrations",keywords:["slack","google","notion","connections","mcp","apps"]},providers:{icon:"providers",keywords:["models","llm","openai","anthropic","google","ollama","model provider","api provider","api key","api keys","keys","tokens","credentials"]},backend:{icon:"backend",keywords:["server","advanced","registry","daemon","web search","temperature"]},updates:{icon:"updates",keywords:["upgrade","version","release","changelog","auto update"]}};function LQe(e){return e.map((t,n)=>({id:`page-${t.id}`,kind:"page",group:"navigation",name:t.name,icon:t.icon,keywords:t.keywords,target:{type:"path",path:t.path},order:n,featured:!0}))}function BQe(e){return e.map((t,n)=>{const s=OQe[t.id];return{id:`settings-section-${t.id}`,kind:"settings-section",group:"settings",name:t.label,icon:s?.icon??"settings",keywords:s?.keywords,target:{type:"path",path:`/settings?section=${t.id}`},order:n,featured:!0}})}function jQe(e){return e.map((t,n)=>({id:`setting-${t.key}`,kind:"setting",group:"settings",name:t.label,icon:"slider",keywords:[t.key,t.kind??""].filter(Boolean),soft:t.help,hint:t.section,target:{type:"path",path:`/settings?setting=${encodeURIComponent(t.key)}`},order:n}))}function HQe(e){return e.map((t,n)=>({id:`action-${t.id}`,kind:"action",group:"actions",name:t.name,icon:t.icon,keywords:t.keywords,verb:t.verb,target:{type:"command",command:t.command},order:n,featured:t.featured,destructive:t.destructive}))}function UQe(e){return e.map((t,n)=>({id:`panel-${t.id}`,kind:"panel",group:"panels",name:t.name,hint:t.hint,icon:t.icon,keywords:t.keywords,verb:h("ui.command_palette.palette_search.open"),target:{type:"panel",destination:t.destination},order:n,featured:!0}))}function GQe(e,t){const n=e.binding?.team,s=n?t?.get(n)??n:e.binding?.agent??"";return{id:`chat-${e.session_id}`,kind:"chat",group:"chats",name:e.title?.trim()||h("ui.command_palette.palette_search.untitled_chat"),icon:"conversation",hint:s||void 0,target:{type:"session",sessionId:e.session_id}}}const iK=6;function VQe(e,t,n,s=iK){return t===null?{drop:!1,record:e}:e!==null&&Math.hypot(t.x-e.x,t.y-e.y)<=s&&e.sessionId!==n?{drop:!0,record:e}:{drop:!1,record:{...t,sessionId:n}}}function WQe(e,t,n=iK){return e===null?!1:Math.hypot(t.x-e.x,t.y-e.y)>n}function Yp(e,t){const n=new Set(e),s=new Set(t),r=new Set,i=[];for(const a of t)!n.has(a)||r.has(a)||(i.push(a),r.add(a));for(const a of e)s.has(a)||r.has(a)||(i.push(a),r.add(a));return i}function $Qe(e,t,n){const s=e.filter(r=>r!==n);return[...Yp(s,t),n]}function zQe(e,t){const n=new Map(e.map(r=>[r.session_id,r])),s=[];for(const r of Yp(e.map(i=>i.session_id),t)){const i=n.get(r);i!==void 0&&s.push(i)}return s}function Ck(e,t,n){const s=e.indexOf(t);return s<0?!1:e[s+n]!==void 0}function qQe(e,t,n,s,r){const i=n.indexOf(s);if(i<0)return null;const a=n[i+r];if(a===void 0)return null;const o=new Set(e),l=new Map;let u=[];for(const b of n)o.has(b)?u.length>0&&(l.set(b,u),u=[]):u.push(b);const d=[];for(const b of e)d.push(...l.get(b)??[],b);d.push(...u);const f=Yp(d,t),p=f.indexOf(s),g=f.indexOf(a);if(p<0||g<0)return null;const v=[...f];return v[p]=a,v[g]=s,v}function KQe(e,t,n,s,r){const i=n.indexOf(s);if(i<0||n.length===0)return null;const a=Math.max(0,Math.min(n.length-1,Math.round(r)));if(a===i)return null;const o=new Set(e),l=[...n.filter(d=>!o.has(d)),...e],u=Yp(l,t);for(let d=i;d!==a;){d+=d<a?1:-1;const f=n[d],p=u.indexOf(s),g=u.indexOf(f);if(f===void 0||p<0||g<0)return null;u[p]=f,u[g]=s}return u}function aK(e,t,n){let s=0;for(const r of e)r.id!==t&&n>(r.top+r.bottom)/2&&(s+=1);return s}function YQe(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e]}function qB(e,t,n){return`Moved “${e}” to position ${t+1} of ${n}.`}function XQe(e,t,n){return n<=1?`“${e}” is the only pinned chat.`:t<=0?`“${e}” is already the first pinned chat.`:`“${e}” is already the last pinned chat.`}function QQe(e){return`“${e}” is not pinned.`}const JQe=e=>!(e.metaKey||e.ctrlKey)||!e.shiftKey||e.altKey?null:e.key==="ArrowUp"?-1:e.key==="ArrowDown"?1:null,ZQe=(e,t)=>{const n=e===-1?"↑":"↓";return t?`⌘⇧${n}`:`Ctrl+Shift+${n}`},KB=(e,t)=>t?`⌘+⇧+${e===-1?"↑":"↓"}`:ZQe(e,t),eJe=e=>{const t=e;return typeof t?.closest!="function"?null:t.closest("[data-session-row]")?.getAttribute("data-session-row")??null};function tJe(e){return TG(typeof e.owner_device_name=="string"?e.owner_device_name:"",typeof e.owner_device=="string"?e.owner_device:"")||"another device"}function nJe(e){const t=new Map,n=e?.networks;if(!Array.isArray(n))return t;for(const s of n){if(s===null||typeof s!="object")continue;const r=s,i=typeof r.name=="string"?r.name.trim():"";if(!(!i||!Array.isArray(r.members)))for(const a of r.members){if(a===null||typeof a!="object")continue;const o=a.device_id;typeof o!="string"||o===""||t.has(o)||t.set(o,i)}}return t}function sJe(e,t){const n=tJe(e),s=(t??"").trim();return s?`on ${n} · ${s}`:`on ${n}`}function rJe(e){return e.reachable!==!1?"":`unreachable · ${(typeof e.unreachable_reason=="string"?e.unreachable_reason.trim():"")||"it did not answer"}`}function Tx(e,t){return t?e.filter(n=>n.pinned===!0):[]}function iJe(e,t){return t?e.filter(n=>n.pinned!==!0):e}const aJe="delegating",HR=e=>typeof e=="number"&&Number.isFinite(e)&&e>0,Sk=e=>Math.max(1,Math.floor(e)),YB=e=>`${e} subagent${e===1?"":"s"}`,oK=e=>e===aJe;function lK(e){return{running:HR(e.subagents_running)&&!oK(e.status?.code),queued:HR(e.subagents_queued)}}function oJe(e){if(oK(e.status?.code))return"";const{running:t,queued:n}=lK(e);if(!t&&!n)return"";const s=[];return t&&s.push(`${YB(Sk(e.subagents_running))} running`),n&&s.push(t?`${Sk(e.subagents_queued)} queued`:`${YB(Sk(e.subagents_queued))} queued`),`, ${s.join(" · ")}`}function lJe(e,t){const n=t.trim().toLocaleLowerCase();return n?e.filter(s=>s.name.toLocaleLowerCase().includes(n)||(s.tags??[]).some(r=>r.toLocaleLowerCase().includes(n))):[...e]}function cJe(e,t){let n=null;for(const s of e){if(s.binding?.team||s.binding?.agent!==t)continue;const r=RQ(s,"active");r!==null&&(n===null||r>n)&&(n=r)}return n}function XB(e){const t=[],n=[];for(const r of e)r.at===null?n.push(r.row):t.push({row:r.row,at:r.at});const s=[];for(const r of t){let i=0;for(;i<s.length&&s[i].at>=r.at;)i+=1;s.splice(i,0,r)}return[...s.map(r=>r.row),...n]}function uJe(e,t){const n=new Set(t.pinned),s=[],r=[];for(const i of e){const a={row:i,at:t.recency(i)};(n.has(i.id)?s:r).push(a)}return[...XB(s),...XB(r)]}function dJe(e,t){const n=e.pinnedAgents.includes(t)?e.pinnedAgents.filter(s=>s!==t):[...e.pinnedAgents,t].slice(-64);return{...e,pinnedAgents:n}}async function cK(e){if(e.trim()==="")return!1;try{return await navigator.clipboard.writeText(e),Hs(h("ui.notices.sessions.id_copied")),!0}catch(t){return console.error("Failed to copy session id: ",t),nn(h("ui.notices.sessions.id_copy_failed")),!1}}const UR="Draft: ",hJe=new Set,fJe=e=>{const n=(e.split(`
683
- `).find(r=>r.trim().length>0)??"").trim(),s=48;return n.length>s?`${n.slice(0,s).trimEnd()}…`:n},QB=e=>`Discard draft “${e.startsWith(UR)?e.slice(UR.length):e}”`;function pJe(e,t){const n=e.indexOf(t);return Math.max(n,0)}function gJe(e,t,n=hJe){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:`${UR}${fJe(l)}`,text:l,pending:i.pending===!0})}return s.reverse()}const mJe="click the chat to try again",Om="Click the chat to try again.",uK={pending:"marking read",offscreen:"scroll to the result to mark this chat read",unsettled:mJe,remote:"lives on another device, and it clears when that device updates"},TD={pending:"Marking this chat read.",offscreen:"Scroll to the result to mark this chat read.",unsettled:`Not marked read. ${Om}`,remote:"The unread mark lives on another device. It clears when that device updates."},vJe=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:uK.remote,description:TD.remote}},bJe=(e,t,n)=>!e||e.sessionId!==t?null:e.kind==="remote"?vJe(n):{clause:uK[e.kind],description:TD[e.kind]},xJe=e=>e instanceof Fi?e.code===AQ?"busy":FQ(e.code)?"refused":v5(e)?"remote":"unreachable":"unreported",_Je="The app could not reach the backend.",wJe={busy:()=>`The read state is busy, so the unread mark was not cleared. ${Om}`,refused:()=>`The read state could not be written, so the unread mark was not cleared. ${Om}`,remote:()=>TD.remote,unreachable:e=>`${zi(e,_Je)} The unread mark was not cleared. ${Om}`,unreported:()=>`The unread mark was not cleared. ${Om}`},yJe=e=>wJe[xJe(e.reason)](e.reason);function CJe({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,f=(r||i>0)&&(n||u),p=f&&i>0;return{withdrawn:u,stale:f,showList:l||f,lastKnownRows:p,notice:u&&!a&&!o?g5(e,t)??`Update the backend to use canonical chats. Existing histories are unchanged.${p?" Showing the last chats and teams that loaded.":""}`:null}}const SJe=1,kJe="They may be archived. Search with Include archived.";function EJe(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:kJe,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?ZC:e.total-e.held,r=s<=0?ZC:Math.min(ZC,s);return{state:"rows",sentence:t.error,retry:t.error!==null,more:t.nextCursor!==null,addCount:t.nextCursor===null?0:r,forbidden:!1}}function TJe(e){return!e.pageable||e.searching||e.total===null?e.held:e.total}function kk(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 JB(e){return h("ui.chat.sidebar.groups.badge",{badge:e})}function RJe(e){if(!e.pageable||e.total===null||e.shown>e.total)return null;if(e.searching===!0){const t={shown:e.shown,total:e.total};return e.clipped===!0?h("ui.chat.sidebar.catalogue.total_search_clipped",t):h("ui.chat.sidebar.catalogue.total_search",t)}return h("ui.chat.sidebar.catalogue.total",{shown:e.shown,total:e.total})}function AJe(e){return e<=0?null:e===1?"1 more chat arrived.":`${e} more chats arrived.`}function FJe(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 DJe(e){return!e.pageable||e.error!==null||e.loading||e.nextCursor===null?!1:e.scrollHeight-e.scrollTop-e.clientHeight<=e.clientHeight*SJe}const IJe=e=>{const t=e.map(s=>s.name),n=t.reduce((s,r,i)=>i===0?r:h("ui.chat.sidebar.agents.list_join",{position:t.length===2?"pair":i===t.length-1?"end":"middle",head:s,tail:r}),"");return h("ui.chat.sidebar.agents.builtin_offer",{count:t.length,list:n})},NJe=({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"})]}),ZB="data-session-hover-intent";function PJe(){const e=m.useRef(null),t=m.useRef(null),n=m.useRef(null),s=m.useCallback(()=>{t.current!==null&&(window.clearTimeout(t.current),t.current=null),e.current?.removeAttribute(ZB)},[]),r=m.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(ZB,"")},Dne)},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 m.useEffect(()=>()=>n.current?.(),[]),c.jsx("span",{ref:r,hidden:!0})}const MJe=32,OJe=8e3,ej=12,LJe="(prefers-reduced-motion: reduce)";function BJe({text:e}){const t=m.useRef(null),n=m.useRef(null),s=m.useRef(null),r=m.useRef(null),i=m.useRef(null),[a,o]=m.useState(!1),l=b8(LJe),u=m.useRef(l),d=m.useCallback(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null)},[]),f=m.useCallback(()=>{d();const x=n.current;x&&(x.style.transform="");const _=t.current;_&&(_.style.removeProperty("mask-image"),_.style.removeProperty("-webkit-mask-image")),o(!1)},[d]),p=m.useCallback((x,_,w)=>{const y=Math.max(MJe,w/(OJe/1e3)),S=performance.now(),C=E=>{const k=Math.min(w,(E-S)/1e3*y);_.style.transform=`translateX(${-k}px)`;const F=`linear-gradient(to right, transparent 0, black ${Math.min(ej,k)}px, black calc(100% - ${ej}px), transparent 100%)`;x.style.setProperty("mask-image",F),x.style.setProperty("-webkit-mask-image",F),i.current=k<w?window.requestAnimationFrame(C):null};i.current=window.requestAnimationFrame(C)},[]),g=m.useCallback(()=>{const x=t.current;x&&(x.scrollWidth-x.clientWidth<=.5||(o(!0),i.current=window.requestAnimationFrame(()=>{i.current=null;const _=n.current;if(!_)return;const w=_.getBoundingClientRect().width-x.clientWidth;if(w<=.5){o(!1);return}p(x,_,w)})))},[p]),v=m.useCallback(()=>{f(),!u.current&&(r.current=window.setTimeout(g,mZ))},[f,g]);m.useEffect(()=>{u.current=l,l&&f()},[l,f]),m.useEffect(()=>f,[f]);const b=m.useCallback(x=>{if(t.current=x,s.current?.(),s.current=null,!x)return;const _=x.closest("[data-session-row]")??x.closest("button[data-chat-row]");if(!_)return;const w=()=>v(),y=()=>f();_.addEventListener("pointerenter",w),_.addEventListener("pointerleave",y),s.current=()=>{_.removeEventListener("pointerenter",w),_.removeEventListener("pointerleave",y),f()}},[v,f]);return c.jsx("span",{ref:b,"data-session-title":!0,className:R("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 Ek=e=>h(Lx[e]),Rx=(e,t=!1)=>c.jsx("div",{className:R("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}),Tk=(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:R("flex h-7 w-full items-center gap-2 rounded-md px-1 text-start 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(Js,{"aria-hidden":"true",className:R("size-3.5 shrink-0",!s&&"opacity-0")})]},e);function jJe({view:e,counts:t,onView:n,tagsAvailable:s=!1,autoTagAvailable:r=!1}){Ve();const i=t?u=>(t[u]??0)>0:void 0,a=[{key:"section",label:h("ui.chat.sidebar_view.time_section"),icon:c.jsx(xU,{"aria-hidden":"true",className:"size-3.5"})},{key:"agent",label:h("ui.chat.sidebar_view.agent_team"),icon:c.jsx(yl,{"aria-hidden":"true",className:"size-3.5"})},{key:"flat",label:h("ui.chat.sidebar_view.one_list"),icon:c.jsx(rT,{"aria-hidden":"true",className:"size-3.5"})}],o=[{key:"active",label:h("ui.chat.sidebar_view.last_active"),icon:c.jsx(c2,{"aria-hidden":"true",className:"size-3.5"})},{key:"created",label:h("ui.chat.sidebar_view.created"),icon:c.jsx(Ece,{"aria-hidden":"true",className:"size-3.5"})}],l=[{key:"active-first",label:h("ui.chat.sidebar_view.active_first"),icon:c.jsx(fU,{"aria-hidden":"true",className:"size-3.5"})},{key:"recent",label:h("ui.chat.sidebar_view.most_recent"),icon:c.jsx(Ei,{"aria-hidden":"true",className:"size-3.5"})}];return c.jsxs("div",{"data-sidebar-view-menu":!0,className:"w-full",children:[Rx(h("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:h("ui.chat.sidebar_view.group_by")}),a.map(u=>Tk(u.key,u.icon,u.label,e.groupBy===u.key,()=>n({...e,groupBy:u.key})))]}),Rx(h("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:h("ui.chat.sidebar_view.time_basis")}),o.map(u=>Tk(u.key,u.icon,u.label,e.basis===u.key,()=>n({...e,basis:u.key}),{"data-sidebar-view-basis":u.key}))]}),c.jsx("p",{className:"px-1 pt-0.5 pb-1 text-meta text-ink-dim",children:h("ui.chat.sidebar_view.clock_hint")}),Rx(h("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:h("ui.chat.sidebar_view.order_by")}),l.map(u=>Tk(u.key,u.icon,u.label,e.orderBy===u.key,()=>n({...e,orderBy:u.key})))]}),s&&c.jsxs("div",{className:"border-hairline border-b","data-sidebar-tags-options":!0,children:[c.jsxs("div",{className:"flex h-[39px] items-center gap-2 px-1",children:[c.jsx("label",{htmlFor:"sidebar-tags-switch",className:"flex-1 text-meta text-ink-dim",children:h("ui.chat.tags.group")}),c.jsx(E_,{id:"sidebar-tags-switch","aria-describedby":"sidebar-tags-help",checked:e.tagsEnabled,onCheckedChange:u=>n({...e,tagsEnabled:u})})]}),e.tagsEnabled&&r&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex min-h-7 items-center gap-2 px-1 py-0.5",children:[c.jsx("span",{className:"min-w-0 flex-1 text-meta text-ink-dim",children:h("ui.chat.tags.auto_tag")}),c.jsx(E_,{"data-sidebar-auto-tag":!0,"aria-label":h("ui.chat.tags.auto_tag"),"aria-describedby":"sidebar-auto-tag-help",checked:e.autoTagForks,onCheckedChange:u=>n({...e,autoTagForks:u})})]}),c.jsx("p",{id:"sidebar-auto-tag-help",className:"px-1 pb-1 text-meta text-ink-dim",children:h("ui.chat.tags.auto_tag_help")})]}),c.jsx("span",{id:"sidebar-tags-help",className:"sr-only",children:h("ui.chat.tags.discovery")}),e.groupBy!=="section"&&c.jsxs("div",{className:"px-1 text-meta text-ink-muted",children:[c.jsx("p",{children:h("ui.chat.tags.mode_hint")}),c.jsx(ce,{variant:"ghost",className:"h-7 px-1 text-meta",onClick:()=>n({...e,groupBy:"section"}),children:h("ui.chat.tags.use_time")})]})]}),Rx(h("ui.chat.sidebar_view.sections")),c.jsx("div",{className:"space-y-0.5",children:e.order.map(u=>{const d=bm(e,u);return c.jsxs("div",{className:"flex h-7 items-center gap-1 rounded-md ps-1 text-body-sm",children:[c.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,"data-sidebar-view-section":u,onClick:()=>n(IQ(e,u)),className:R("flex h-7 min-w-0 flex-1 items-center gap-2 text-start",d?"text-ink":"text-ink-muted"),children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:b5(u)?c.jsx(Vm,{"aria-hidden":"true",className:"size-3.5"}):c.jsx(Lp,{"aria-hidden":"true",className:"size-3.5"})}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:Ek(u)}),t?.[u]?c.jsx("span",{className:"shrink-0 font-mono text-ink-dim text-mono-sm",children:t[u]}):null,c.jsx(Js,{"aria-hidden":"true",className:R("size-3.5 shrink-0",!d&&"opacity-0")})]}),DQ(u)&&c.jsxs(c.Fragment,{children:[c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-move":`${u}:up`,"aria-label":h("ui.chat.sidebar_view.move_up",{section:Ek(u)}),disabled:!GI(e,u,-1,i),className:"size-6",onClick:()=>n(UI(e,u,-1)),children:c.jsx(Hv,{"aria-hidden":"true",className:"size-3"})}),c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-move":`${u}:down`,"aria-label":h("ui.chat.sidebar_view.move_down",{section:Ek(u)}),disabled:!GI(e,u,1,i),className:"size-6",onClick:()=>n(UI(e,u,1)),children:c.jsx(Ei,{"aria-hidden":"true",className:"size-3"})})]})]},u)})}),e.hidden.length>0&&c.jsx("p",{className:"mt-2 px-1 text-meta text-ink-dim",children:h("ui.chat.sidebar_view.hidden",{count:e.hidden.length})})]})}class Rk extends Error{}function ty(e,t){const n=Ine(e);if(n==="reserved")return h("ui.chat.tags.name_reserved");if(n==="long"||n==="blank")return h("ui.chat.tags.name_long");const s=e.trim().toLocaleLowerCase();return sc.getState().categories.some(i=>i.id!==t&&i.name.toLocaleLowerCase()===s)?h("ui.chat.tags.duplicate_name",{name:e.trim()}):null}function dK(){const e=sc(a=>a.replaceCategories),[t,n]=m.useState(!1),s=a=>[...a].sort((o,l)=>o.order-l.order).map(({id:o,name:l})=>({id:o,name:l})),r=async a=>{if(t)return{ok:!1,error:h("ui.chat.tags.save_failed"),retryable:!0};n(!0);try{return await e(a),{ok:!0}}catch(o){return{ok:!1,error:o instanceof Rk?o.message:h("ui.chat.tags.save_failed"),retryable:!(o instanceof Rk)}}finally{n(!1)}},i=a=>{throw new Rk(a)};return{pending:t,create:a=>r(o=>{const l=ty(a);return l?i(l):o.length>=My?i(h("ui.chat.tags.registry_limit")):[...s(o),{name:a.trim()}]}),rename:(a,o)=>r(l=>{const u=s(l),d=u.find(p=>p.id===a);if(!d)return i(h("ui.chat.tags.registry_changed"));if(d.name===o.trim())return null;const f=ty(o,a);return f?i(f):u.map(p=>p.id===a?{...p,name:o.trim()}:p)}),move:(a,o,l)=>r(u=>{const d=Nne(u,a,o,l);return d||i(h("ui.chat.tags.registry_changed"))}),remove:a=>r(o=>{const l=s(o);return l.some(u=>u.id===a)?l.filter(u=>u.id!==a):i(h("ui.chat.tags.registry_changed"))})}}const GR="data-chat-tag-header";function HJe(e){return e.metaKey||e.ctrlKey?null:e.key==="F2"&&!e.altKey&&!e.shiftKey?"rename":e.altKey&&!e.shiftKey&&e.key==="ArrowUp"?"up":e.altKey&&!e.shiftKey&&e.key==="ArrowDown"?"down":e.key==="ContextMenu"||e.shiftKey&&e.key==="F10"?"menu":null}function hK({initial:e,label:t,placeholder:n,error:s,errorId:r,busy:i,keepOpen:a,renameId:o,onCommit:l,onCancel:u}){const[d,f]=m.useState(e),p=m.useRef(null),g=m.useRef(!1);m.useEffect(()=>{p.current?.focus(),p.current?.select()},[]);const v=async()=>{if(i)return;await l(d)&&a&&(f(""),p.current?.focus())};return c.jsx(bs,{ref:p,inputSize:"sm","aria-label":t,placeholder:n,"aria-invalid":s!==null,"aria-describedby":s?r:void 0,"aria-busy":i,readOnly:i,value:d,className:R("min-w-0 flex-1",i&&"text-ink-dim"),onChange:b=>f(b.target.value),onKeyDown:b=>{b.stopPropagation(),!(b.nativeEvent.isComposing||b.keyCode===229)&&(b.key==="Enter"?(b.preventDefault(),v()):b.key==="Escape"&&(b.preventDefault(),g.current=!0,u(!0)))},onBlur:()=>{if(!(g.current||i)){if(a){u(!1);return}!d.trim()||d.trim()===e.trim()||ty(d,o)?u():l(d,!1).then(b=>{b||p.current?.focus({preventScroll:!0})})}}})}function fK({id:e,message:t,onRetry:n}){return c.jsxs("div",{id:e,role:"alert",className:"flex min-h-6 items-center gap-2 px-2 text-meta text-danger",children:[c.jsx("span",{className:"min-w-0 flex-1",children:t}),n&&c.jsx(ce,{variant:"ghost",className:"h-6 px-1 text-meta",onClick:n,children:h("ui.chat.tags.retry")})]})}function pK({id:e,name:t,count:n,above:s,below:r,announce:i,unused:a=!1}){Ve();const o=dK(),[l,u]=m.useState(!1),[d,f]=m.useState(!1),[p,g]=m.useState(!1),[v,b]=m.useState(null),[x,_]=m.useState(null),w=m.useId(),y=m.useRef(null),S=m.useRef(null),C=m.useRef(null),E=e!=="untagged",k=e==="untagged"?h("ui.chat.tags.untagged"):t,F=m.useRef(null);m.useEffect(()=>()=>{F.current!==null&&cancelAnimationFrame(F.current)},[]);const A=()=>{F.current!==null&&cancelAnimationFrame(F.current),F.current=requestAnimationFrame(()=>{const Q=y.current?.isConnected?y.current:document.querySelector(`[${GR}="${CSS.escape(r??s??e)}"], [data-tag-new]`);F.current=null,Q?.focus({preventScroll:!0})})},I=(Q,ie,G)=>Q.ok?(b(null),_(null),i(ie),!0):(b(Q.error),_(()=>Q.retryable?G:null),!1),N=async Q=>{const ie=Q==="up"?s:r;if(!ie||o.pending){i(h(Q==="up"?"ui.chat.tags.header_first":"ui.chat.tags.header_last",{name:k}));return}const G=await o.move(e,ie,Q);I(G,h("ui.chat.tags.moved_tag",{name:k}),()=>void N(Q))&&A()},P=async()=>{const Q=await o.remove(e);g(!1),I(Q,h("ui.chat.tag_dialogs.deleted_name",{name:k}),()=>void P())&&A()},M=()=>{const Q=sc.getState().categories.find(ie=>ie.id===e);if(!Q){b(h("ui.chat.tags.registry_changed"));return}Q.conversations===0?P():g(!0)},Y=async(Q,ie=!0)=>{const G=await o.rename(e,Q),ne=I(G,h("ui.chat.tags.renamed_name",{name:Q.trim()}),()=>void Y(Q));return ne&&(u(!1),ie&&A()),ne},O=Q=>{if(!E)return;const ie=HJe(Q);if(ie===null){["ArrowUp","ArrowDown","Home","End"].includes(Q.key)&&Q.preventDefault();return}Q.preventDefault(),Q.stopPropagation(),ie==="rename"?u(!0):ie==="menu"?f(!0):N(ie)},X=sc(Q=>Q.categories.find(ie=>ie.id===e)?.conversations)??n;return c.jsxs("div",{ref:C,"aria-busy":o.pending,children:[c.jsxs("div",{"data-tag-drop-target":e,...a?{"data-tag-unused-slot":""}:{},className:"group/header relative flex h-7 items-center gap-2 px-2 text-meta text-ink-dim hover:bg-row-hover",onContextMenu:Q=>{E&&(Q.preventDefault(),f(!0))},children:[l?c.jsx(hK,{initial:t,renameId:e,label:h("ui.chat.tags.rename_label",{name:t}),error:v,errorId:w,busy:o.pending,onCommit:Y,onCancel:Q=>{u(!1),b(null),Q&&A()}}):c.jsx("span",{className:"min-w-0 flex-1 truncate",title:k,onDoubleClick:()=>E&&u(!0),children:k}),c.jsx("span",{className:"shrink-0",children:n}),E&&!l&&c.jsx(Po,{open:d,onOpenChange:f,children:c.jsxs(xh,{open:p,onOpenChange:g,children:[c.jsx(by,{asChild:!0,children:c.jsx(eo,{asChild:!0,children:c.jsx("button",{ref:y,type:"button",tabIndex:-1,[GR]:e,"aria-label":h("ui.chat.tags.header_actions",{name:k}),title:h("ui.chat.tags.header_actions",{name:k}),onKeyDown:O,className:R("absolute end-2 flex size-6 shrink-0 items-center justify-center rounded-sm text-ink-dim opacity-0 hover:bg-row-hover hover:text-ink","group-hover/header:static group-hover/header:opacity-100 group-focus-within/header:static group-focus-within/header:opacity-100 focus-visible:outline-2 focus-visible:outline-accent",(d||p)&&"static opacity-100"),children:c.jsx(oc,{"aria-hidden":"true",className:"size-4"})})})}),c.jsxs(Mo,{align:"end",className:"min-w-44",onCloseAutoFocus:Q=>{(l||p)&&Q.preventDefault()},children:[c.jsxs(Jt,{onSelect:()=>u(!0),children:[c.jsx(Vv,{"aria-hidden":"true"}),h("ui.chat.tags.rename")]}),c.jsxs(c.Fragment,{children:[c.jsxs(Jt,{"aria-disabled":!s,className:"aria-disabled:text-ink-muted!",onSelect:()=>void N("up"),children:[c.jsx(pce,{"aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 truncate",children:h("ui.chat.tags.move_up",{name:k})})]}),c.jsxs(Jt,{"aria-disabled":!r,className:"aria-disabled:text-ink-muted!",onSelect:()=>void N("down"),children:[c.jsx(Pne,{"aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 truncate",children:h("ui.chat.tags.move_down",{name:k})})]})]}),c.jsx(Nr,{}),c.jsxs(Jt,{destructive:!0,onSelect:M,children:[c.jsx(cg,{"aria-hidden":"true"}),h("ui.chat.tags.delete")]})]}),c.jsxs(Bu,{role:"alertdialog",align:"end",className:"w-64 space-y-2 p-3","aria-labelledby":`${w}-title`,"aria-describedby":`${w}-description`,onOpenAutoFocus:Q=>{Q.preventDefault(),S.current?.focus()},onCloseAutoFocus:Q=>{Q.preventDefault(),A()},onKeyDown:Q=>{Q.key==="Escape"&&Q.stopPropagation()},children:[c.jsx("p",{id:`${w}-title`,className:"text-body-sm text-ink",children:h("ui.chat.tags.delete_title",{name:k})}),c.jsx("p",{id:`${w}-description`,className:"text-meta text-ink-dim",children:h("ui.chat.tags.delete_description",{count:X})}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx(ce,{"data-tag-delete-cancel":!0,ref:S,variant:"ghost",className:"h-7 px-2 text-meta",onClick:()=>g(!1),children:h("ui.chat.tags.cancel")}),c.jsx(ce,{variant:"ghost",className:"h-7 px-2 text-meta text-danger hover:bg-danger-wash",disabled:o.pending,onClick:()=>void P(),children:h("ui.chat.tags.delete_tag")})]})]})]})})]}),v&&c.jsx(fK,{id:w,message:v,onRetry:x??void 0})]})}function UJe({unused:e,total:t,dragArmed:n,announce:s,chord:r}){Ve();const i=dK(),[a,o]=m.useState(!1),[l,u]=m.useState(!1),[d,f]=m.useState(null),p=m.useId(),g=l||n,v=m.useId(),b=async _=>{const w=await i.create(_);return w.ok?(f(null),u(!0),s(h("ui.chat.tags.created_name",{name:_.trim()})),!0):(f(w.error),!1)},x=t>=My?c.jsx("p",{className:"flex h-7 items-center px-2 text-meta text-ink-dim",children:h("ui.chat.tags.registry_limit")}):a?c.jsx("div",{className:"flex h-7 items-center gap-2 px-1",children:c.jsx(hK,{initial:"",label:h("ui.chat.tags.new_name"),placeholder:h("ui.chat.tags.name_placeholder"),error:d,errorId:p,busy:i.pending,keepOpen:!0,onCommit:b,onCancel:_=>{o(!1),f(null),_&&requestAnimationFrame(()=>document.querySelector("[data-tag-new]")?.focus())}})}):c.jsxs("button",{type:"button","data-tag-new":!0,className:"flex h-7 w-full items-center gap-2 rounded-md px-2 text-start text-meta text-ink-dim hover:bg-row-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-accent",onClick:()=>o(!0),children:[c.jsx(Cl,{"aria-hidden":"true",className:"size-3.5"}),h("ui.chat.tags.new_tag")]});return c.jsxs("div",{"data-chat-tag-footer":!0,className:"mt-2 border-hairline border-t pt-1",children:[t===0&&c.jsxs("div",{"data-chat-tag-empty":!0,className:"px-2 py-1 text-meta",children:[c.jsx("p",{className:"text-ink",children:h("ui.chat.tags.empty_title")}),c.jsx("p",{className:"text-ink-dim",children:h("ui.chat.tags.empty_hint",{chord:r})})]}),x,d&&c.jsx(fK,{id:p,message:d}),e.length>0&&c.jsxs(c.Fragment,{children:[c.jsxs("button",{type:"button","aria-expanded":g,"aria-controls":v,className:"flex h-7 w-full items-center gap-1 rounded-md px-2 text-start text-meta text-ink-dim hover:bg-row-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-accent",onClick:()=>u(_=>!_),children:[c.jsx(Vi,{"aria-hidden":"true",className:R("size-3.5 shrink-0",g&&"rotate-90")}),h("ui.chat.tags.unused",{count:String(e.length)})]}),c.jsx("div",{id:v,hidden:!g,"data-chat-tag-unused":!0,children:e.map(_=>c.jsx("div",{"data-chat-tag-group":_.id,children:c.jsx(pK,{id:_.id,name:_.name,count:0,above:e[e.indexOf(_)-1]?.id??null,below:e[e.indexOf(_)+1]?.id??null,announce:s,unused:!0})},_.id))})]})]})}function GJe({categories:e,selected:t,primary:n,query:s,setQuery:r,disabled:i,unready:a,input:o,toggle:l,showUnder:u,create:d,createIssue:f}){const p=m.useId(),[g,v]=m.useState(-1),b=m.useRef(null),x=s.trim(),_=a?[]:Mne(e,s),w=_.some(O=>O.name.trim().toLowerCase()===x.toLowerCase()),y=e.length>=My,S=!a&&x!==""&&!w&&!y,C=_.length+(S?1:0),E=C?Math.min(g,C-1):-1,k=O=>`${p}-${O}`,F=t.length>=fE,A=t.length>=2;m.useEffect(()=>{v(s.trim()?0:-1)},[s]),m.useEffect(()=>{E>=0&&b.current?.children[E]?.scrollIntoView?.({block:"nearest"})},[E]);const I=O=>i||a||!t.includes(O)&&F,N=O=>{I(O)||(l(O),r(""),v(-1),o.current?.focus({preventScroll:!0}))},P=O=>{I(O)||(u(O),r(""),v(-1),o.current?.focus({preventScroll:!0}))},M=()=>{i||a||f||d()},Y=(O,X)=>{if(O<_.length){const Q=_[O].id;X?P(Q):N(Q)}else S&&M()};return c.jsxs(c.Fragment,{children:[c.jsx(bs,{ref:o,role:"combobox","aria-label":h("ui.chat.tags.search"),"aria-autocomplete":"list","aria-expanded":!a,"aria-controls":p,"aria-activedescendant":E>=0?k(E):void 0,placeholder:h("ui.chat.tags.search"),value:s,readOnly:i||a,className:"h-8",onChange:O=>r(O.target.value),onKeyDown:O=>{O.nativeEvent.isComposing||O.nativeEvent.keyCode===229||(O.key==="ArrowDown"||O.key==="ArrowUp"?(O.preventDefault(),v(One(E,O.key==="ArrowDown"?1:-1,C))):O.key==="Home"||O.key==="End"?(O.preventDefault(),v(C?O.key==="Home"?0:C-1:-1)):O.key==="Enter"&&(O.preventDefault(),E>=0&&Y(E,O.shiftKey)))}}),!a&&x&&!_.length&&c.jsx("p",{className:"px-2 py-1 text-meta text-ink-dim",children:h("ui.chat.tags.no_matches",{query:x})}),c.jsxs("div",{ref:b,id:p,role:"listbox",tabIndex:-1,"aria-label":h("ui.chat.tags.label"),"aria-multiselectable":"true",hidden:a||C===0,className:"mt-1 min-h-0 max-h-56 overflow-y-auto",children:[_.map((O,X)=>{const Q=t.includes(O.id),ie=E===X,G=I(O.id),ne=A&&Q&&O.id!==n&&!i;return c.jsxs("div",{id:k(X),role:"option","aria-selected":Q,"aria-disabled":G,tabIndex:-1,title:O.name,className:R("group/option flex h-8 cursor-default items-center gap-2 rounded-sm px-2 text-body-sm",G?"text-ink-muted":"text-ink",!G&&"hover:bg-row-hover",ie&&"bg-accent-wash"),onMouseDown:oe=>oe.preventDefault(),onMouseEnter:()=>v(X),onClick:()=>N(O.id),children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center",children:Q&&c.jsx(Js,{"aria-hidden":"true",className:"size-4"})}),c.jsx("bdi",{className:"min-w-0 flex-1 truncate",children:O.name}),ne&&c.jsx("span",{"data-tag-show-under":!0,className:R("shrink-0 rounded-sm px-1 text-meta text-ink-dim hover:text-ink",ie?"inline":"hidden group-hover/option:inline"),onClick:oe=>{oe.stopPropagation(),P(O.id)},children:h("ui.chat.tags.show_under")})]},O.id)}),S&&c.jsxs("div",{id:k(_.length),role:"option","aria-selected":!1,"aria-disabled":i||f!==null,tabIndex:-1,"data-tag-create":!0,className:R("flex min-h-8 cursor-default items-center gap-2 rounded-sm px-2 py-1 text-body-sm",f?"text-ink-muted":"text-ink hover:bg-row-hover",E===_.length&&"bg-accent-wash"),onMouseDown:O=>O.preventDefault(),onMouseEnter:()=>v(_.length),onClick:M,children:[c.jsx(Cl,{"aria-hidden":"true",className:"size-4 shrink-0"}),c.jsxs("span",{className:"flex min-w-0 flex-col",children:[c.jsx("bdi",{className:"truncate",children:h("ui.chat.tags.create_name",{name:x})}),c.jsx("span",{className:"text-meta text-ink-dim",children:f??h("ui.chat.tags.create_helper")})]})]})]}),!a&&x&&!w&&y&&c.jsx("p",{className:"px-2 py-1 text-meta text-ink-muted",children:h("ui.chat.tags.registry_limit")}),!a&&!x&&C===0&&c.jsx("p",{className:"px-2 py-2 text-body-sm text-ink-muted",children:x?h("ui.chat.tags.no_matches",{query:x}):h("ui.chat.tags.empty")})]})}function VJe({row:e,onClose:t,returnFocus:n,grouped:s,onShowGroups:r}){Ve();const{categories:i,loading:a,loadError:o,fetchCategories:l,selected:u,primary:d,pending:f,error:p,notice:g,toggle:v,showUnder:b,createAndAssign:x}=Lne({sessionId:e.session_id,tags:e.tags,primary:e.primary??null,revision:e.tags_revision??null}),[_,w]=m.useState(""),y=m.useRef(null),S=m.useRef(!0),C=m.useRef(new DOMRect),E=m.useRef({getBoundingClientRect:()=>{const N=document.querySelector(`[data-session-row="${CSS.escape(e.session_id)}"]`);return N&&(C.current=N.getBoundingClientRect()),C.current}}),k=a||o!==null,F=i.length>=My?h("ui.chat.tags.registry_limit"):u.length>=fE?h("ui.chat.tags.selection_limit"):_.trim()?ty(_):null,A=async()=>{f||F||k||!await x(_.trim())||(w(""),y.current?.focus({preventScroll:!0}))},I=i.find(N=>N.id===d)?.name;return c.jsxs(xh,{open:!0,onOpenChange:N=>{!N&&!f&&t()},children:[c.jsx(by,{virtualRef:E}),c.jsxs(Bu,{"data-chat-tag-popover":!0,role:"region",side:"right",align:"start",sideOffset:2,collisionPadding:8,"aria-label":h("ui.chat.tags.label"),className:"flex max-h-[min(360px,var(--radix-popover-content-available-height))] w-auto min-w-56 max-w-[280px] flex-col p-1",onOpenAutoFocus:N=>{N.preventDefault(),y.current?.focus({preventScroll:!0})},onCloseAutoFocus:N=>{N.preventDefault(),S.current&&n()},onInteractOutside:N=>{f?N.preventDefault():S.current=!1},onEscapeKeyDown:N=>{N.preventDefault(),!N.isComposing&&N.keyCode!==229&&!f&&t()},onKeyDown:N=>{N.key==="Escape"&&N.stopPropagation(),N.key==="Tab"&&!f&&(N.preventDefault(),t())},children:[c.jsx(GJe,{categories:i,selected:u,primary:d,query:_,setQuery:w,disabled:f,unready:k,input:y,toggle:N=>void v(N),showUnder:N=>void b(N),create:()=>void A(),createIssue:F}),a?c.jsx("output",{className:"flex h-24 items-center px-2 text-body-sm text-ink-muted",children:h("ui.chat.tags.loading")}):null,o&&c.jsxs("div",{role:"alert",className:"space-y-1 px-2 py-2 text-body-sm",children:[c.jsx("p",{children:h("ui.chat.tags.load_failed")}),c.jsx(ce,{variant:"ghost",className:"h-7 px-1 text-meta",onClick:()=>void l(),children:h("ui.chat.tags.retry")})]}),p&&c.jsx("p",{role:"alert",className:"px-2 py-1 text-meta text-danger",children:p}),!k&&u.length>=fE&&c.jsx("p",{className:"px-2 py-1 text-meta text-ink-muted",children:h("ui.chat.tags.selection_limit")}),!k&&c.jsxs("div",{className:"mt-1 flex min-h-7 items-center gap-2 border-hairline border-t px-2 pt-1 text-meta text-ink-dim",children:[s?c.jsx("span",{className:"min-w-0 flex-1 truncate",children:I?h("ui.chat.tags.shown_under",{tag:I}):h("ui.chat.tags.shown_untagged")}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 flex-1",children:h("ui.chat.tags.hidden")}),c.jsx(ce,{variant:"ghost",className:"h-6 px-1 text-meta",onClick:r,children:h("ui.chat.tags.show_groups")})]}),c.jsx("span",{children:h("ui.chat.tags.selection_count",{count:String(u.length)})})]}),c.jsx("output",{"aria-live":"polite",className:"sr-only",children:g})]})]})}function RD(e,t){switch(e?.split("/")[0]){case"unsupported-precondition":return h("ui.hub.status.unsupported");case"baseline-unknown":return h("ui.hub.status.baseline_unknown");case"alias-occupied":return h("ui.hub.skills.local_exists");case"mixed-lineage":case"origin-conflict":return h("ui.hub.status.mixed_lineage");case"no-credential":return h("ui.hub.status.no_credential");case"access-lost":case"unauthorized":case"forbidden":return h("ui.hub.status.access_lost");case"provider-error":return h("ui.hub.status.provider_error");case"model-unavailable":return h("ui.hub.status.model_unavailable");case"merge-refused":case"concurrent-edit":case"local-concurrent-edit":case"remote-revision-changed":return h("ui.hub.status.conflict");case"prompt-too-long":case"skill-too-large":return h("ui.hub.status.too_large");case"skill-validation":return h("ui.hub.status.skill_validation");case"unsafe-publication":return h("ui.hub.status.unsafe_publication");case"hub-error":case"transport":return h("ui.hub.status.transport_error");default:return t??h("ui.hub.status.other_error")}}function WJe(e){const t=e.safe_message?.trim();return t?h("ui.hub.links.incoming_failed_reason",{reason:t}):RD(e.error_class,h("ui.hub.links.incoming_failed_no_reason"))}function fdt(e){switch(e){case"would-merge":return h("ui.hub.links.outcome_would_merge");case"needs-review":return h("ui.hub.links.outcome_needs_review");case"up-to-date":return h("ui.hub.links.outcome_up_to_date");case"unchanged":return h("ui.hub.links.outcome_unchanged");case"failed":return h("ui.hub.links.outcome_failed");case"skipped":return h("ui.hub.links.outcome_skipped");case"unavailable":return h("ui.hub.links.outcome_unavailable");default:return e}}function pdt(e){switch(e.state){case"idle":return h(e.last_checked_at?"ui.hub.status.idle":"ui.hub.status.not_checked");case"checking":return h("ui.hub.status.checking");case"available":return h("ui.hub.status.available");case"merging":return h("ui.hub.status.merging");case"applying":return h("ui.hub.status.applying");case"pushing":return h("ui.hub.status.pushing");case"retry-wait":return h("ui.hub.status.retry_wait");case"needs-review":return h("ui.hub.status.needs_review");case"failed":return h("ui.hub.status.failed");case"missing":return h("ui.hub.status.missing");default:return h("ui.hub.status.other_error")}}function gdt(e,t){return e==="check"?h("ui.hub.links.check_failed",{item:t.item,source:t.source}):h("ui.hub.links.action_failed",{direction:t.direction,item:t.item,source:t.source})}const $Je=/lop login radient/i;function zJe(e){if(!(e instanceof Error))return!1;const t=e.status;return(t===401||t===403)&&$Je.test(e.message)}function tj(e,t,n){return n&&e instanceof n?e.message:zJe(e)?h("ui.hub.links.sign_in_required"):t}function ld(){return crypto.randomUUID()}async function mdt(e=1,t=20,n){const s={page:e,per_page:t};if(n)for(const[r,i]of Object.entries(n))i&&(s[r]=i);return Di({operation:"agents.list",query:s})}async function vdt(e){return Di({operation:"agents.get",agentId:e})}async function bdt(e){return Di({operation:"agents.delete",agentId:e,requestId:ld(),confirmed:!0})}async function xdt(e){return Di({operation:"agents.like",agentId:e,requestId:ld()})}async function _dt(e){return Di({operation:"agents.unlike",agentId:e,requestId:ld(),confirmed:!0})}async function wdt(e){return Di({operation:"agents.favourite",agentId:e,requestId:ld()})}async function ydt(e){return Di({operation:"agents.unfavourite",agentId:e,requestId:ld(),confirmed:!0})}async function Cdt(e,t){return Di({operation:"comments.create",agentId:e,payload:t,requestId:ld()})}async function Sdt(e,t=1,n=20){return Di({operation:"comments.list",agentId:e,query:{page:t,per_page:n}})}async function kdt(e,t,n){return Di({operation:"comments.update",agentId:e,commentId:t,payload:n,requestId:ld()})}async function Edt(e,t){return Di({operation:"comments.delete",agentId:e,commentId:t,requestId:ld(),confirmed:!0})}async function Tdt(e){return Di({operation:"agents.statuses",query:{agent_ids:e.join(",")}})}async function qJe(){return Di({operation:"memberships.list"})}async function Rdt(e,t=1,n=20,s){const r={page:t,per_page:n};if(s)for(const[i,a]of Object.entries(s))a&&(r[i]=a);return Di({operation:"org_agents.list",tenantId:e,query:r})}async function Adt(e){return Di({operation:"org_teams.list",tenantId:e})}class Ax extends Error{status;reason;constructor(t,n,s){super(t),this.name="PublicHubError",this.status=n,this.reason=s}}const KJe=/\/+$/,YJe=(e,t,n)=>{const s=e.replace(KJe,"");return n?`${s}/v1/${t}/${encodeURIComponent(n)}`:`${s}/v1/${t}`},gK=(e,t)=>YJe(e,"teams",t),mK=async e=>{let t;try{t=await fetch(e,{method:"GET",headers:{Accept:"application/json"},redirect:"error"})}catch(s){throw console.error("The public hub could not be reached:",s),new Ax(h("ui.common.errors.public_hub_unreachable"),null,s)}if(!t.ok)throw new Ax(h("ui.common.errors.public_hub_status",{status:t.status}),t.status);let n;try{n=await t.json()}catch{throw new Ax(h("ui.common.errors.public_hub_json"),t.status)}if(!n||typeof n!="object"||!("result"in n))throw new Ax(h("ui.common.errors.public_hub_body"),t.status);return n};async function Fdt(e,t=1,n=12){const s=`${gK(e)}?page=${t}&per_page=${n}`;return mK(s)}async function Ddt(e,t){return mK(gK(e,t))}const XJe={all:["memberships"],account:e=>["memberships","account",e??"unresolved-owner"]},vK=({enabled:e=!0}={})=>{const{isAuthenticated:t}=Oy(),n=Mt(),{accountId:s}=ug(),r=Dn({queryKey:XJe.account(s),queryFn:async()=>(await x8(n,s,()=>qJe())).result??{memberships:[]},enabled:e&&t&&!!s,staleTime:5*60*1e3,gcTime:10*60*1e3,refetchOnWindowFocus:!1,retry:Mv});return{...r,memberships:r.data?.memberships??[]}};function QJe(e,t=[]){if(e.visibility==="public")return h("ui.hub.links.source_label_public");const n=t.find(s=>s.tenant_id===e.tenant_id&&s.status==="active")?.tenant_name;return n?h("ui.hub.links.source_label_org",{organization:n}):null}function bK(e,t=!0){const{isAuthenticated:n}=Oy(),{accountId:s}=ug(),r=n&&!!s,i=vK({enabled:t&&e.visibility==="org"&&r}),a=r&&i.isSuccess&&!i.isFetching&&!i.isPlaceholderData?i.memberships:[],o=a.find(l=>l.tenant_id===e.tenant_id&&l.status==="active")?.tenant_name;return{source:QJe(e,a),organization:o,memberships:i,mayReadMemberships:r}}const xK=new Set(["needs-review","missing","blocked"]),_K=new Set(["checking","merging","applying","pushing"]),JJe=new Set(["idle","available","retry-wait","failed","applied","published",...xK,..._K]);function wK(e){const t=["pull","push"];for(const n of t){const s=e[n];if(!JJe.has(s.state)||xK.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(_K.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 AD(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 ZJe(e){const{unavailable:t}=AD(e);return e.policy.auto_push?!e.eligibility.can_auto_push||t?"paused":"none":t?"unavailable":"none"}function eZe(e){return e.visibility==="public"?h("ui.hub.links.source_public"):e.tenant_name?h("ui.hub.links.source_private",{organization:e.tenant_name}):h("ui.hub.links.source_unavailable")}function tZe(e){return!e||e.split("/")[0]==="unsupported-precondition"?h("ui.hub.subscriptions.auto_push_unverified"):RD(e)}function yK({link:e,onConsentChange:t,item:n,source:s}){Ve();const r=JXe(),i=m.useId(),a=m.useRef(null),o=bK(e,s===void 0),l=s!==void 0?s:o.source,u=o.organization,d=n?.trim()?n:e.name,[f,p]=m.useState("subscribe"),[g,v]=m.useState(null);m.useEffect(()=>{g&&(g.linkId!==e.link_id||g.revision!==e.policy.revision||g.source!==l)&&(t?.(!1),v(null))},[e.link_id,e.policy.revision,l,g,t]);const b=()=>{t?.(!1),v(null)},x=(E,k)=>{r.isPending||(p(k),r.mutate({link:e,patch:E},{onSuccess:b}))},{unavailable:_}=AD(e),w=_||l===null,y=l===null?"unavailable":ZJe(e),S=l===null?h("ui.hub.subscriptions.auto_push_source_unknown"):tZe(e.eligibility.reason),C=h(f==="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:[r.upgradeMessage&&c.jsx("output",{className:"block text-meta text-warning","data-hub-core-upgrade":!0,children:r.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:`${i}-subscribe`,className:"text-body-sm text-ink",children:h("ui.hub.subscriptions.subscribe")}),c.jsx("p",{className:"text-meta text-ink-muted",children:l?h(r.canWrite?"ui.hub.subscriptions.subscribe_description":"ui.hub.subscriptions.subscribe_description_blocked",{source:l}):h(r.canWrite?"ui.hub.subscriptions.subscribe_description_unsourced":"ui.hub.subscriptions.subscribe_description_blocked_unsourced")})]}),c.jsx(E_,{id:`${i}-subscribe`,checked:e.policy.subscribe,disabled:r.isPending||!r.canWrite,"aria-label":l?`${h("ui.hub.subscriptions.subscribe")}: ${l}`:h("ui.hub.subscriptions.subscribe"),onCheckedChange:E=>x({subscribe:E},"subscribe")})]}),!e.policy.subscribe&&r.canWrite&&c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.hub.subscriptions.manual_available")}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("label",{htmlFor:`${i}-push`,className:"text-body-sm text-ink",children:h("ui.hub.subscriptions.auto_push")}),c.jsx("p",{className:"text-meta text-ink-muted",children:l?h("ui.hub.subscriptions.auto_push_description",{source:l}):h("ui.hub.subscriptions.auto_push_description_unsourced")})]}),c.jsx("span",{className:"inline-flex shrink-0","data-hub-auto-push-reason":y!=="none"?"":void 0,title:y==="unavailable"?S:void 0,children:c.jsx(E_,{id:`${i}-push`,"aria-describedby":y!=="none"?`${i}-push-line`:void 0,checked:e.policy.auto_push,disabled:r.isPending||!r.canWrite||!e.policy.auto_push&&w,"aria-label":l?`${h("ui.hub.subscriptions.auto_push")}: ${l}`:h("ui.hub.subscriptions.auto_push"),onCheckedChange:E=>{E?!w&&l&&(t?.(!0),v({linkId:e.link_id,revision:e.policy.revision,source:l})):x({auto_push:!1},"auto_push")}})})]}),y!=="none"&&c.jsx("p",{id:`${i}-push-line`,className:R("text-meta",y==="paused"?"text-warning":"text-ink-muted"),children:y==="paused"?h("ui.hub.subscriptions.effective_paused",{reason:S}):S})]}),r.isPending&&c.jsx("output",{className:"text-meta text-ink-muted",children:l?h("ui.hub.subscriptions.saving",{setting:C,source:l}):h("ui.hub.subscriptions.saving_unsourced",{setting:C})}),r.error&&c.jsx("p",{role:"alert",className:"text-meta text-danger",children:r.error instanceof gh?r.error.message:r.error instanceof Fi&&r.error.code==="policy-revision-changed"?h("ui.hub.subscriptions.policy_changed"):l?h("ui.hub.subscriptions.save_failed",{setting:C,source:l}):h("ui.hub.subscriptions.save_failed_unsourced",{setting:C})}),c.jsx(Tc,{open:g!==null&&l!==null,onOpenChange:E=>{!E&&!r.isPending&&b()},children:c.jsxs(Rc,{onOpenAutoFocus:E=>{E.preventDefault(),a.current?.focus()},closeDisabled:r.isPending,onEscapeKeyDown:E=>{r.isPending&&E.preventDefault()},children:[c.jsxs(my,{children:[c.jsx(wl,{children:h("ui.hub.subscriptions.enable_title",{source:l??""})}),c.jsx(Zu,{children:e.visibility==="public"?h("ui.hub.subscriptions.enable_public",{item:d}):h("ui.hub.subscriptions.enable_private",{item:d,organization:u??l??""})})]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("ui.hub.subscriptions.enable_safety")}),r.upgradeMessage&&c.jsx("p",{role:"alert",className:"text-body-sm text-warning","data-hub-core-upgrade":!0,children:r.upgradeMessage}),r.error&&c.jsx("p",{role:"alert",className:"text-body-sm text-danger",children:h("ui.hub.subscriptions.save_failed",{setting:C,source:l??""})}),c.jsxs(vy,{children:[c.jsx(ce,{ref:a,variant:"outline",disabled:r.isPending,onClick:b,children:h("ui.hub.subscriptions.cancel")}),c.jsx(ce,{disabled:r.isPending||!r.canWrite||w||g?.linkId!==e.link_id||g?.revision!==e.policy.revision||g?.source!==l,onClick:()=>x({auto_push:!0,...e.visibility==="public"?{confirm_public_egress:!0}:{}},"auto_push"),children:h("ui.hub.subscriptions.enable")})]})]})})]})}const nZe=new Set(["provider-error","model-unavailable","prompt-too-long","concurrent-edit","local-concurrent-edit","remote-revision-changed","hub-error"]);function nj(e,t,n,s){return{state:e.state,effective:t,reason:n,retryable:e.error_class!==null&&nZe.has(e.error_class.split("/")[0]),canApply:s,lastSuccess:e.last_success_at,modelUsed:e.model_used,operationId:e.operation_id}}function CK(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:!AD(e).unavailable&&t.visibility!=="unavailable",autoPushUnavailableReason:e.eligibility.reason,canEditPolicy:!0,pull:nj(e.pull,e.auto_will_apply,null,tQe(e.baseline_state)&&e.pull.classification==="remote-only"),push:nj(e.push,e.auto_will_push,e.eligibility.reason,!1)}}const SK={healthy:_U,review:rg,available:BA,failed:Bo,busy:ri,applied:Js},kK={healthy:"text-ink-dim",review:"text-warning",available:"text-accent",failed:"text-danger",busy:"text-ink-dim",applied:"text-success"},sZe=8;function rZe({link:e,staged:t,onDetail:n,itemName:s,displayName:r,itemsById:i=!1,nameAmbiguous:a=!0}){Ve();const o=Mt(),l=eQe(e,{displayName:s,itemsById:i}),[u,d]=m.useState(!1),[f,p]=m.useState(!1),g=m.useRef(null),v=m.useId(),b=m.useId(),x=m.useId(),_=m.useId(),w=m.useId(),y=r?.trim()?r:e.name,{source:S,memberships:C,mayReadMemberships:E}=bK(e),k=!i&&(a||!s?.trim()),F=wK(CK(e)),A=l.isPending?ri:SK[F.kind],I=h(F.direction==="pull"?"ui.hub.links.direction_pull":"ui.hub.links.direction_push"),N=G=>h(G?"ui.hub.subscriptions.configured_on":"ui.hub.subscriptions.configured_off"),P=S?h("ui.hub.links.healthy",{item:y,source:S,subscribe:N(e.policy.subscribe),autoPush:N(e.policy.auto_push)}):h("ui.hub.links.healthy_unsourced",{item:y,subscribe:N(e.policy.subscribe),autoPush:N(e.policy.auto_push)}),M=F.kind==="available"?S?h("ui.hub.links.available",{item:y,source:S}):h("ui.hub.links.available_unsourced",{item:y}):F.kind==="failed"?S?h("ui.hub.links.failed",{direction:I,item:y,source:S}):h("ui.hub.links.failed_unsourced",{direction:I,item:y}):F.kind==="busy"?S?h("ui.hub.links.busy",{direction:I,item:y,source:S}):h("ui.hub.links.busy_unsourced",{direction:I,item:y}):F.kind==="applied"?F.direction==="pull"?S?h("ui.hub.links.updated",{item:y,source:S}):h("ui.hub.links.updated_unsourced",{item:y}):S?h("ui.hub.links.published",{item:y,source:S}):h("ui.hub.links.published_unsourced",{item:y}):P,Y=e.pull.state==="failed"||e.pull.state==="retry-wait"&&e.pull.error_class!==null,O=()=>{if(k||!l.canWrite||l.isPending){d(!0);return}l.mutate({action:"retry",linkId:e.link_id,direction:"pull"},{onError:()=>d(!0)})},X=l.error!==null&&l.variables?.action==="retry",Q=()=>{E&&C.refetch(),o.invalidateQueries({queryKey:Xu})},ie=`${M} ${P}${e.policy.auto_push&&e.eligibility.reason?` ${h("ui.hub.subscriptions.effective_paused",{reason:RD(e.eligibility.reason)})}`:""}`;return c.jsxs(xh,{open:u,onOpenChange:G=>{(G||!f)&&d(G)},children:[c.jsx(vt,{content:ie,side:"top",disableHoverableContent:!0,children:c.jsx(by,{asChild:!0,children:c.jsxs("button",{ref:g,type:"button","data-hub-mark":l.isPending?"busy":F.kind,"data-testid":`hub-mark-${e.kind}-${e.name}`,"aria-label":M,"aria-disabled":(!l.canWrite||k)&&(F.action==="apply"||F.action==="retry")||void 0,"aria-describedby":b,"aria-haspopup":"dialog","aria-expanded":u,className:R("flex size-6 shrink-0 items-center justify-center rounded-md",kK[F.kind],!t&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onContextMenu:G=>{G.preventDefault(),G.stopPropagation(),d(!0)},onKeyDown:G=>{(G.key==="ContextMenu"||G.shiftKey&&G.key==="F10")&&(G.preventDefault(),G.stopPropagation(),d(!0))},onClick:G=>{if(G.stopPropagation(),l.isPending||F.action==="policy"||(!l.canWrite||k)&&(F.action==="apply"||F.action==="retry")){d(!0);return}if(F.action==="detail"){n();return}if(F.action==="retry"&&F.direction==="pull"){O();return}l.mutate(F.action==="apply"?{action:"apply",linkId:e.link_id}:{action:"retry",linkId:e.link_id,direction:F.direction},{onError:()=>d(!0)})},children:[c.jsx("span",{id:b,className:"sr-only",children:ie}),c.jsx(A,{"aria-hidden":"true",className:R("size-3.5",(l.isPending||F.kind==="busy")&&"motion-safe:animate-spin")})]})})}),c.jsxs(Bu,{side:"right",align:"start",avoidCollisions:!0,collisionPadding:sZe,"aria-labelledby":v,"data-hub-link-popover":e.link_id,className:"max-h-[var(--radix-popover-content-available-height)] max-w-[min(20rem,var(--radix-popover-content-available-width))] overflow-y-auto",onInteractOutside:G=>{f&&G.preventDefault()},onCloseAutoFocus:G=>{G.preventDefault(),g.current?.focus()},children:[c.jsx("h4",{id:v,className:"break-words text-heading text-ink",children:h("ui.hub.links.policy_title",{item:y})}),S?c.jsx("p",{className:"mb-3 break-words text-meta text-ink-muted","data-hub-link-source":"",children:S}):c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3","data-hub-link-source-unresolved":"",children:[c.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[c.jsx("p",{id:x,className:"text-meta text-ink-muted",children:h("ui.hub.links.source_unresolved")}),!E&&c.jsx("p",{id:_,className:"text-meta text-ink-muted",children:h("ui.hub.links.sign_in_required")})]}),c.jsx(ce,{variant:"outline",size:"sm",disabled:C.isFetching||!E,"aria-describedby":E?x:`${x} ${_}`,onClick:Q,children:h(C.isFetching?"ui.hub.links.retrying":"ui.hub.links.retry")})]}),k&&c.jsxs("output",{"data-hub-legacy-blocked":"",className:"mb-3 text-meta text-warning",children:[a&&c.jsx("span",{className:"block",children:h("ui.hub.links.name_ambiguous")}),(!s?.trim()||a)&&h("ui.hub.links.legacy_retry_unverified")]}),Y&&c.jsxs("div",{className:"mb-3 flex flex-col gap-2 rounded-md border border-hairline bg-sunken p-3","data-hub-link-incoming-failed":"",children:[c.jsx("p",{id:w,className:"text-body-sm text-warning",children:h("ui.hub.links.incoming_update_failed")}),c.jsx("p",{className:"text-meta text-ink-muted",children:WJe(e.pull)}),X&&c.jsx("p",{role:"alert",className:"text-meta text-danger",children:tj(l.error,h("ui.hub.links.retry_failed"),gh)}),c.jsx("div",{children:c.jsx(ce,{variant:"outline",size:"sm",disabled:l.isPending||!l.canWrite||k,"aria-describedby":w,onClick:O,children:h(l.isPending?"ui.hub.links.retrying":"ui.hub.links.retry_update")})})]}),c.jsx(yK,{link:e,item:y,source:S,onConsentChange:p},e.link_id),l.error&&!X&&c.jsx("p",{role:"alert",className:"mt-3 text-meta text-danger",children:tj(l.error,S?h("ui.hub.links.action_failed",{direction:I,item:y,source:S}):h("ui.hub.links.action_failed_unsourced",{direction:I,item:y}),gh)})]})]})}function iZe({item:e,staged:t,onResolve:n}){Ve();const s=h("ui.hub.links.unresolved_mark",{item:e});return c.jsx(vt,{content:s,side:"top",disableHoverableContent:!0,children:c.jsx("button",{type:"button","data-hub-mark":"unresolved","data-testid":"hub-mark-unresolved","aria-label":s,className:R("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(N0,{"aria-hidden":"true",className:"size-3.5"})})})}function aZe({link:e}){return Ve(),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:eZe(e)}),c.jsx(yK,{link:e})]})}function oZe({links:e,staged:t,onDetail:n}){Ve();const s={healthy:0,applied:1,available:2,busy:3,failed:4,review:5},i=e.map(u=>wK(CK(u))).reduce((u,d)=>s[d.kind]>s[u]?d.kind:u,"healthy"),a=SK[i]??_U,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=h("ui.hub.links.aggregate_mark",{count:e.length,state:h(o[i]??"ui.hub.links.mark_healthy")});return c.jsx(vt,{content:l,side:"top",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:R("relative flex size-6 shrink-0 items-center justify-center rounded-md",kK[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 lZe=2,EK={available:BA,review:rg,failed:Bo,updating:ri,applied:Js},TK={available:"text-accent",review:"text-warning",failed:"text-danger",updating:"text-ink-dim",applied:"text-success"};function Idt({mark:e,className:t}){const n=EK[e.kind];return c.jsx(n,{"aria-hidden":"true",className:R("size-3.5 shrink-0",TK[e.kind],t)})}function cZe({item:e,mark:t,busy:n,blocked:s=!1,staged:r,onPress:i}){const a=m.useId(),o=n?{kind:"updating"}:t,l=o.kind,u=EK[l],d=HXe(e,o),f=BXe(o),p=s||l==="updating"||l==="applied";return c.jsx(vt,{content:f?`${d} ${f}`:d,side:"top",align:"center",disableHoverableContent:!0,children:c.jsxs("button",{type:"button","data-hub-mark":l,"data-testid":`hub-mark-${e.kind}-${e.name}`,className:R("flex size-6 shrink-0 items-center justify-center rounded-md",TK[l],!r&&!p&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),"aria-label":LXe(e.name,o),"aria-describedby":a,"aria-disabled":p||void 0,onClick:()=>{p||i()},children:[c.jsx(u,{className:R("size-3.5",l==="updating"&&"motion-safe:animate-spin"),"aria-hidden":"true"}),c.jsx("span",{id:a,className:"sr-only",children:f?`${d} ${f}`:d})]})})}function uZe({note:e}){return c.jsx("p",{role:e.tone==="error"?"alert":"status",className:R("pb-1 pl-13 pr-2 text-meta",e.tone==="error"?"text-danger":"text-ink-muted"),children:e.message})}function dZe({kind:e,available:t,busy:n,blocked:s=!1,onUpdateAll:r,onCheck:i,checking:a}){Ve();const o=t>=lZe;return!o&&!i?null:c.jsxs(c.Fragment,{children:[o&&c.jsx("button",{type:"button","data-testid":`hub-update-all-${e}`,"aria-label":h("ui.chat.hub_update.update_all_label",{count:t,kind:e==="team"?"teams":e==="skill"?"skills":"agents"}),"aria-disabled":n||s||void 0,className:R("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?h("ui.chat.hub_update.updating"):h("ui.chat.hub_update.update_all",{count:t})}),i&&c.jsx(vt,{content:h("ui.chat.hub_update.check_now"),side:"top",children:c.jsx("button",{type:"button","data-testid":"hub-check-now","aria-label":h("ui.chat.hub_update.check_now"),"aria-disabled":a||s||void 0,className:R("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(Wy,{className:R("size-3.5",a&&"motion-safe:animate-spin"),"aria-hidden":"true"})})})]})}function hZe({kind:e,reserve:t,signIn:n,signInHref:s,rollup:r,note:i,onDismissRollup:a}){return Ve(),!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(B5,{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":h("ui.chat.hub_update.dismiss_summary"),className:"shrink-0 rounded-sm px-1 hover:text-ink",onClick:a,children:h("ui.chat.hub_update.dismiss")})]})]})}const fZe=/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;function pZe(e){const t=e.split(fZe).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 RK=({name:e,imageUrl:t,slug:n,showTooltip:s=!0,onActivate:r,className:i})=>{const a=pZe(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:R(vZ({variant:"attentionQuiet",shape:"pill",size:"count"}),i),children:c.jsxs(F5,{className:"h-4 w-fit",children:[t?c.jsx(xy,{src:t,alt:"",className:"size-4"}):null,c.jsx(_y,{className:"h-full w-auto bg-transparent font-normal text-inherit text-meta-sm",children:a})]})});return s?c.jsx(vt,{content:c.jsx("span",{"aria-hidden":"true",children:e}),children:o}):o},AK=e=>{const n=e.getBoundingClientRect().top+e.clientTop;return{top:n,bottom:n+e.clientHeight}},VR=(e,t)=>{const n=AK(t),s=e.getBoundingClientRect();return s.bottom<=n.top||s.top>=n.bottom?"outside":s.top>=n.top&&s.bottom<=n.bottom?"inside":"partly"},gZe=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)},sj=(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=VR(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=AK(e),u=s.getBoundingClientRect(),d=u.top-l.top,f=l.bottom-u.bottom,p=gZe(s);e.scrollTop=Math.min(Math.max(e.scrollTop+(d<0?d-p:-f+p),0),e.scrollHeight-e.clientHeight),t.current={node:s,index:r,visibility:VR(s,e),clipHeight:e.clientHeight}},rj=(e,t)=>{const n=t.current.node;!e||!n||!n.isConnected||!e.contains(n)||n===document.activeElement&&(t.current={...t.current,visibility:VR(n,e),clipHeight:e.clientHeight})};function mZe(e){const t=new URLSearchParams({kind:"agent",name:e.agentName,edit:"picture"});return e.agentId&&t.set("agent",e.agentId),`/agents?${t}`}function FK({agentName:e,agentId:t,owned:n,editHref:s,children:r,className:i,pencilClassName:a="size-2",linkProps:o,overlay:l=!1}){const u=oi();if(!n)return c.jsx("span",{className:R("relative inline-flex shrink-0",i),children:r});const d=s??mZe({agentName:e,agentId:t}),f=h("ui.agents.avatar.edit_link",{name:e});return c.jsxs("a",{href:`#${d}`,"aria-label":f,title:f,"data-agent-avatar-edit":"",onClick:p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.button||(p.preventDefault(),p.stopPropagation(),u(d))},className:R("group/avatar-edit relative inline-flex shrink-0 rounded-full",l&&"pointer-events-none opacity-0 group-hover/row:pointer-events-auto group-hover/row:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1",i,o?.className),style:o?.style,children:[r,c.jsx("span",{"aria-hidden":"true",className:R("pointer-events-none absolute inset-0 flex items-center justify-center rounded-full bg-scrim opacity-0","transition-opacity duration-fast ease-out-quart","group-hover/avatar-edit:opacity-100 group-focus-visible/avatar-edit:opacity-100"),children:c.jsx("span",{className:"flex items-center justify-center rounded-full bg-accent p-px text-on-accent",children:c.jsx(Vv,{className:a,strokeWidth:2.5})})})]})}function DK({agentId:e,sha256:t,className:n,fallback:s,src:r,glyph:i=null,onPresence:a}){const o=Ly(r===void 0?e:null,t),l=r===void 0?o:r,u=!!l;return m.useEffect(()=>{a?.(u)},[a,u]),l?c.jsxs(bA,{className:R("shrink-0",n),"data-agent-mark":"",children:[c.jsx(xy,{src:l,alt:""}),c.jsx(_y,{children:i})]}):c.jsx(c.Fragment,{children:s})}function vZe(e,t){return Ly(e,t)!==null}const bZe=new Set(["idle","recent"]);function xZe({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":`${Hne(n)} outstanding. The agent is not blocked on you.`,className:R("inline-flex shrink-0 items-center gap-0.5"),children:[c.jsx(I0,{"aria-hidden":"true",size:14,className:R("text-accent")}),c.jsx("span",{className:R("tabular-nums text-ink-muted text-xs"),children:n})]})}function _Ze({className:e,mark:t}){return c.jsx("span",{"aria-hidden":"true","data-subagent-mark":t,className:R("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 wZe(e,t,n){return`${n.linkDown?tE(e,t):n.uncertainLabel??e.status?.label??"Recent"}${n.unreadMark!==null?", unread":""}`}function yZe(e){const t=e.status?.code,n=e.locality==="remote"&&e.link_down===!0,s=n&&e.link_reconnecting===!0,r=Bx(e),i=!r&&!n&&t==="delegating",o=lK(e).queued&&!HR(e.subagents_running),l=dy(e),u=l==="complete",d=r?N0:n?Mde:t==="waiting"?Bne:t==="busy"?ri:t==="approval"||t==="answer"?I0:t==="error"?rg:t==="wedged"?Lce:t==="interrupted"||t==="dormant"?Fue:t==="complete"?u?Js:hN:t==="scheduled"?jne:t==="attached"?u2:bZe.has(t??"recent")?hN:N0;return{code:t,linkDown:n,reconnecting:s,uncertainLabel:r,delegating:i,queuedOnly:o,unreadMark:l,Icon:d,ink:r?"text-ink-dim":n?s?"text-ink-dim":"text-warning":t==="waiting"?"text-accent":t==="busy"?"text-accent motion-safe:animate-spin":t==="wedged"?"text-warning":t==="error"?"text-danger":t==="approval"||t==="answer"||t==="interrupted"?"text-warning":u?"text-success":t==="delegating"?"text-accent":"text-ink-dim"}}function WR({row:e,nowSeconds:t=Date.now()/1e3}){const n=yZe(e),{Icon:s,ink:r,delegating:i,queuedOnly:a}=n;return c.jsxs("span",{className:"flex size-4 shrink-0",children:[i?a?c.jsx(Cde,{"aria-hidden":"true","data-subagent-mark":"queued",className:"size-4 text-ink-muted"}):c.jsx(_Ze,{className:R("size-4",r),mark:"running"}):c.jsx(s,{className:R("size-4",r),"aria-hidden":"true"}),c.jsx("span",{className:"sr-only",children:wZe(e,t,n)})]})}const CZe="beside",Rv="size-4";function SZe({row:e,nowSeconds:t}){const n=e.agent_id??null,s=e.avatar_sha256??null;return!n||!s?c.jsx(WR,{row:e,nowSeconds:t}):c.jsxs("span",{"data-session-mark":"avatar","data-avatar-variant":CZe,className:R("relative flex shrink-0 items-center gap-1.5"),children:[c.jsxs("span",{className:R("relative flex shrink-0",Rv),children:[c.jsx(DK,{agentId:n,sha256:s,className:R(Rv,"rounded-full"),fallback:c.jsx(kZe,{}),glyph:c.jsx(yl,{className:"size-2.5","aria-hidden":"true"})}),null]}),c.jsx(WR,{row:e,nowSeconds:t})]})}function kZe(){return c.jsx(bA,{"aria-hidden":"true",className:R(Rv,"rounded-full"),"data-agent-mark":"",children:c.jsx(_y,{children:c.jsx(yl,{className:"size-2.5","aria-hidden":"true"})})})}function ij({row:e,className:t}){const n=_8(e);if(!n?.owned||!n.agentName)return null;const{agentId:s,agentName:r,owned:i}=n;return c.jsx(FK,{agentName:r,agentId:s,owned:i,overlay:!0,linkProps:{className:"before:absolute before:-inset-1 before:content-['']"},className:R(Rv,"absolute start-1 top-1/2 -translate-y-1/2",t),children:c.jsx("span",{"aria-hidden":"true",className:R(Rv,"block")})})}const EZe="chat-sidebar-entities",TZe="chat-sidebar-chats",dm="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",Ak="group/row relative flex h-8 items-center gap-1 rounded-md",RZe="@max-[253px]/chatheading:sr-only",aj="read-ack",oj="Sending - this draft can be discarded when the send settles",lj=e=>`draft-discard-why-${e}`,cj="Drafts are sending - they can be cleared when the sends settle",uj="drafts-clear-all-why",yo="bg-row-selected font-medium text-ink hover:bg-row-selected",IK="bg-row-selected text-ink hover:bg-row-selected hover:text-ink",NK="outline outline-1 outline-offset-[-1px] outline-ink-dim",AZe=5e3,FZe=3e4,dj="chat-search-include-archived",hj="/stop if it stays silent.",fj=e=>`chat-row-remedy-${e}`,pj=e=>`chat-row-read-ack-${e}`,gj=()=>navigator.platform.toUpperCase().indexOf("MAC")>=0,DZe=({id:e,openMenuRowIdRef:t,setOpenMenuRowId:n,openedByKeyboard:s})=>(m.useEffect(()=>()=>{t.current===e&&(n(null),s.current=!1)},[e,t,n,s]),null),IZe=({agentId:e,glyph:t})=>{const n=Ly(e);return n===null?c.jsx(t,{className:"size-4 shrink-0"}):c.jsx(bA,{className:"size-4 shrink-0",children:c.jsx(xy,{src:n,alt:""})})},NZe=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.",mj=e=>`chat-row-menu-${e}`,vj=(e,t)=>{document.querySelector(`[data-session-row="${CSS.escape(e)}"]`)?.querySelector(`[${sse[t]}]`)?.click()},PZe=8;function MZe({selectedConversation:e,onSelectConversation:t,onStageDraft:n}){Ve();const s=oi(),r=fA(),i=Au(D=>D.requestPanel),a=ss(),o=jA(),l=HA(),u=m.useMemo(()=>l.rows===null?null:Une(l.rows),[l.rows]),d=Fe(D=>D.sessions),f=Fe(D=>D.error),p=Gr(a.data,"session_catalogue",2),g=p==="enabled",v=Gr(a.data,"peers")==="enabled",b=Qy(v,{poll:!1}),x=m.useMemo(()=>nJe(b.data),[b.data]),{data:_}=og(),w=A2(_?.online===!1),y=_?.snapshot&&!_.snapshot.pairing.available?_.snapshot.pairing.cause??"unpaired":null,S=dA(a.data,y),C=m.useRef(null),E=Et(a.data,"session_pins"),k=Et(a.data,"session_catalogue_page"),F=Fe(D=>D.setCataloguePageable);m.useEffect(()=>{F(k)},[k,F]);const A=Et(a.data,"session_catalogue_sort"),I=Fe(D=>D.setCatalogueActivityHead);m.useEffect(()=>{I(A)},[A,I]);const N=Fe(D=>D.scopes),P=Fe(D=>D.head),M=Fe(D=>D.counts),Y=Fe(D=>D.fetchScopePage),O=Fe(D=>D.clearScope),X=Fe(D=>D.fetchCatalogueTail),Q=m.useRef(null),ie=m.useRef(null),G=Fe(D=>D.pinFailure),ne=Fe(D=>D.pinFacts),oe=m.useMemo(()=>{const D={};for(const[ve,Ge]of Object.entries(ne))D[ve]=Ge.pinned;return D},[ne]),B=Fe(D=>D.setSessionPin),H=m.useRef(!1);g&&(H.current=!0);const{stale:U,showList:z,notice:te}=CJe({state:p,cause:y,failed:!!a.error,answered:!!a.data,wasReady:H.current,rows:d.length,storeFailed:!!f,coveredByCompatibilityBanner:S}),fe=w8(g&&Et(a.data,"profile_catalogue")),J=(fe.data??[]).filter(D=>D.source!=="builtin"),Se=(fe.data??[]).filter(D=>D.source==="builtin"),W=!fe.isLoading&&J.length===0,Ce=nt(D=>D.dismissedBuiltinOfferSignature),K=nt(D=>D.dismissBuiltinOffer),me=vXe(Se),Ee=bXe(Ce,me),Ae=W&&Se.length>0&&!Ee,se=W&&Se.length>0&&Ee,[he,xe]=m.useState(!1),Je=m.useRef(!1),pe=m.useRef(null);m.useEffect(()=>{!Je.current||Ae||(Je.current=!1,pe.current?.focus())},[Ae]);const Xe=By(g&&Et(a.data,"team_catalogue")),le=Et(a.data,"session_tags"),Qe=Gne(a.data),et=sc(D=>D.categories),ue=sc(D=>D.loading),Le=sc(D=>D.error),Ne=sc(D=>D.fetchCategories),[Ue,dt]=m.useState(null),St=m.useRef(null);m.useEffect(()=>{g&&le&&Ne()},[g,le,Ne]);const Dt=()=>{requestAnimationFrame(()=>{const D=St.current;if(!D)return;const ve=document.querySelector(`[data-session-row="${CSS.escape(D)}"] [data-chat-row]`);ve?.focus(),ve?.scrollIntoView({block:"nearest"})})},sn=D=>{St.current=D.session_id,dt(D)},Kt=m.useMemo(()=>new Map((Xe.data??[]).map(D=>[D.name,Dp(D)])),[Xe.data]),ut=m.useMemo(()=>D=>Kt.get(D)??D,[Kt]),Ft=m.useMemo(()=>({agent:GB(fe.data),team:GB(Xe.data)}),[fe.data,Xe.data]),At=KXe(g&&Et(a.data,"hub_updates")),cn=NXe(At.data),rn=Et(a.data,"hub_links"),kn=Et(a.data,"hub_items_by_id"),ws=QXe(g&&rn),Vt=XXe(),cs=(At.data?.items.length??0)>0||Object.values(At.data?.counts??{}).some(D=>D>0),Vn=Fe(D=>D.fetchSessions),zr=Fe(D=>D.loading),ls=Fe(D=>D.truncated),Vs=Fe(D=>D.statusUnavailable).includes("liveness"),un=Fe(D=>D.activeDraftKey),It=Fe(D=>D.drafts),dn=Fe(D=>D.openDraft),tr=Fe(D=>D.discardDraft),Sn=Fe(D=>D.discardDrafts),Ie=Ua(D=>D.inputByConversation),ge=Fe(D=>D.markAllRead),Pe=Fe(D=>D.readAckNotice),L=m.useRef(Pe?`${Pe.sessionId}:${Pe.revision}`:null);m.useEffect(()=>{const D=Pe?`${Pe.sessionId}:${Pe.revision}`:null,ve=L.current!==D;if(L.current=D,Pe?.kind!=="unsettled"){Ux(aj);return}ve&&Ru(yJe(Pe),{id:aj,duration:nH})},[Pe]);const[V,j]=m.useState(""),[q,Z]=m.useState(!1),ee=q||V.length>0,_e=m.useRef(null),[Re,ye]=m.useState(""),[Te,ae]=m.useState(()=>Date.now());m.useEffect(()=>{const D=window.setInterval(()=>ae(Date.now()),6e4);return()=>window.clearInterval(D)},[]);const we=nt(D=>D.chatSidebarView),De=nt(D=>D.setChatSidebarView),$e=nt(D=>D.openCommandPalette),ke=nt(D=>D.setCommandPaletteQuery),[tt,ht]=m.useState(!1),[Ot,Ut]=m.useState(!1),[en,yn]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("chat-sidebar-disclosures")??"{}")}catch{return{}}}),wn=m.useRef(null),Ps=m.useRef(null),ys=(D,ve,Ge,st="pin",lt=!0)=>{const bt=Array.from(wn.current?.querySelectorAll("[data-session-row]")??[]),Cn=bt.findIndex(es=>es.getAttribute("data-session-row")===D);if(Cn<0){Ps.current=null;return}const rs=bt[Cn+1]??bt[Cn-1]??null;Ps.current={id:D,top:bt[Cn].getBoundingClientRect().top,follow:ve,pointer:Ge,caret:st,scroll:lt,anchorId:rs?.getAttribute("data-session-row")??null,anchorTop:rs?rs.getBoundingClientRect().top:0}};m.useEffect(()=>{const D=Ps.current,ve=wn.current;if(!D||!ve)return;const Ge=ve.querySelector(`[data-session-row="${D.id}"]`);if(!Ge){Ps.current=null;return}if(D.follow){if(D.scroll){const es=Ge.getBoundingClientRect().top-D.top;es!==0&&(ve.scrollTop+=es)}const st=ve.getBoundingClientRect(),lt=Ge.getBoundingClientRect();lt.top<st.top?ve.scrollTop-=st.top-lt.top:lt.bottom>st.bottom&&(ve.scrollTop+=lt.bottom-st.bottom);const bt=Ge.querySelector("[data-session-pin]"),Cn=Ge.querySelector("[data-chat-row]");(D.caret==="row"?Cn:bt!==null&&bt.getBoundingClientRect().width>0?bt:Cn)?.focus({preventScroll:!0})}else if(D.anchorId!==null&&D.scroll){const st=ve.querySelector(`[data-session-row="${D.anchorId}"]`);if(st){const lt=st.getBoundingClientRect().top-D.anchorTop;lt!==0&&(ve.scrollTop+=lt)}}Ps.current=null});const Ts=m.useRef(null),an=6,ba=(D,ve)=>{const Ge=Ts.current;return D===null?!1:Ge!==null&&Math.hypot(D.x-Ge.x,D.y-Ge.y)<=an&&Ge.sessionId!==ve?!0:(Ts.current={...D,sessionId:ve},!1)},fi=(D,ve=!1)=>en[D]??ve,Ms=k&&V.trim().length===0,Ii=m.useCallback(D=>{for(const[ve,Ge]of Object.entries(N)){if(!Ge.ids.includes(D))continue;const[st,...lt]=ve.split(":"),bt=lt.join(":");return st==="agent"?{agent:bt,team:null}:{agent:null,team:bt}}},[N]),co=(D,ve=!1)=>{const Ge=ZQ(en,Mg,D,ve,!!V);yn(Ge.expanded),yI(Ge.caps)},Yi=Uae(d),Nl=Fe(D=>D.raiseBulkReadDeferral),[Oe,kt]=m.useState(!1),jt=Yi.count>0&&!V.trim()&&Et(a.data,"completion_ack_bulk"),pi=async()=>{kt(!0);try{const{tone:D,message:ve}=Gae(await ge());D==="success"?Hs(ve):Ru(ve)}catch(D){v5(D)?Nl(Yi.count):Ru(h("ui.notices.chat.unread_not_cleared",{reason:zi(D,h("ui.notices.chat.unread_backend_silent"))}))}finally{kt(!1)}},xa=m.useRef(jt);m.useEffect(()=>{if(xa.current&&!jt){const D=document.activeElement;(D===null||D===document.body)&&wn.current?.querySelector('[data-sidebar-region="chats"] [data-chat-row]')?.focus()}xa.current=jt},[jt]);const Ws=jt?c.jsxs(ce,{size:"sm",variant:"ghost","data-chat-row":!0,"data-tour-tag":"mark-all-read","aria-disabled":Oe||void 0,title:Yi.scope,onClick:()=>{Oe||pi()},className:"shrink-0 text-ink-dim hover:bg-row-hover",children:[Oe?c.jsx(ri,{className:"text-ink-disabled motion-safe:animate-spin","aria-hidden":"true"}):c.jsx(Fce,{"aria-hidden":"true"}),c.jsx("span",{className:R("truncate",RZe),children:Yi.label}),Yi.nameSuffix?c.jsx("span",{className:"sr-only",children:Yi.nameSuffix}):null]}):null;m.useEffect(()=>{localStorage.setItem("chat-sidebar-disclosures",JSON.stringify(en))},[en]);const Cs=m.useCallback(()=>Vn(k?x5:fy,k),[Vn,k]);m.useEffect(()=>{if(!g)return;if(Cs(),!o.available){const Ge=window.setInterval(()=>{document.visibilityState==="visible"&&Cs()},AZe);return()=>window.clearInterval(Ge)}const D=window.setInterval(()=>{Cs()},FZe),ve=()=>void Cs();return window.addEventListener("focus",ve),()=>{window.clearInterval(D),window.removeEventListener("focus",ve)}},[g,Cs,o.available,o.catalogueRevision,o.activityRevision]),m.useEffect(()=>{if(!(!g||!Ms))for(const[D,ve]of Object.entries(en)){const Ge=D.startsWith("team:")?"team":D.startsWith("agent:")?"agent":null;if(Ge===null)continue;const st=D.slice(Ge.length+1);if(st.length!==0){if(ve){N[D]===void 0&&Y(Ge,st,null);continue}N[D]!==void 0&&O(Ge,st)}}},[en,g,Ms,N,Y,O]);const uo=Et(a.data,"session_search"),hr=Et(a.data,"session_archive"),[_a,hd]=m.useState(!1),gi=NQ(_a,V,hr),Wo=Fe(D=>D.archiveFacts),sf=Fe(D=>D.forgotten),wa=Fe(D=>D.setStagedByDiscard),mi=Fe(D=>D.setSessionArchived),jc=Fe(D=>D.requestArchiveConfirm),fd=m.useMemo(()=>{const D={};for(const[ve,Ge]of Object.entries(Wo))Ge.answered&&(D[ve]=Ge.archived);return D},[Wo]),Hc=m.useMemo(()=>({include:gi,facts:fd,forgotten:new Set(Object.keys(sf))}),[gi,fd,sf]),Pl=m.useRef(null),nr=rK(V,g&&uo,gi),ya=nr.refused,Uc=m.useMemo(()=>PQ(d,Wo),[d,Wo]),vi=m.useMemo(()=>MQ(Uc,hr&&!gi),[Uc,hr,gi]),Gc=WB(nr.data,V)?nr.data.sessions:null,xr=m.useMemo(()=>{const D=new Set(d.map(Ge=>Ge.session_id)),ve=[];for(const[Ge,st]of Object.entries(ne))!st.pinned||D.has(Ge)||ve.push({session_id:Ge,title:st.title||"",updated_at:st.updated_at,pinned:!0});return ve},[ne,d]),{rows:_r,conversationMatches:rf,synthesized:pd}=m.useMemo(()=>LR([...vi,...xr],V,Gc,oe,Hc,Ii,ut),[vi,xr,V,Gc,oe,Hc,Ii,ut]),Ni=Gc!==null&&uQe(Gc.length,nr.data?.limit),gd=RJe({pageable:k,shown:_r.length,total:M?.total??null,searching:V.trim().length>0,clipped:Ni}),Ml=(D,ve)=>_r.filter(Ge=>D==="team"?Ge.binding?.team===ve:!Ge.binding?.team&&Ge.binding?.agent===ve),Vc=(D,ve)=>{if(!Ms)return Ml(D,ve);const Ge=N[zI(D,ve)]?.ids;if(Ge===void 0)return[];const st=new Map(_r.map(bt=>[bt.session_id,bt])),lt=[];for(const bt of Ge){const Cn=st.get(bt);Cn!==void 0&&lt.push(Cn)}return lt},$o=Ms,Ol=m.useRef(null),Wc=m.useRef(!1),[$c,Ll]=m.useState(null),zc=m.useCallback(()=>{if(!$o||Wc.current||P.tailCursor!==null&&P.tailCursor===Ol.current)return;const D=wn.current;D!==null&&DJe({pageable:$o,nextCursor:P.tailCursor,loading:P.loading,error:P.error,scrollTop:D.scrollTop,clientHeight:D.clientHeight,scrollHeight:D.scrollHeight})&&(zo.current=!0,X())},[$o,P,X]);m.useEffect(()=>{P.error!==null&&P.tailCursor!==null&&(Ol.current=P.tailCursor,Ll({cursor:P.tailCursor,sentence:P.error}))},[P.error,P.tailCursor]),m.useLayoutEffect(()=>{zc()},[zc,d.length]);const zo=m.useRef(!1),[af,mb]=m.useState(null),qc=m.useRef(d.length);m.useEffect(()=>{const D=qc.current;if(qc.current=d.length,!zo.current||d.length<=D)return;zo.current=!1,mb(AJe(d.length-D));const ve=window.setTimeout(()=>mb(null),4e3);return()=>window.clearTimeout(ve)},[d.length]);const[qo,Kc]=m.useState(""),Yc=m.useRef(null),Bl=m.useRef(""),Xi=m.useRef(null),Wn=D=>{Xi.current!==null&&(window.cancelAnimationFrame(Xi.current),Xi.current=null),D!==""&&D===Bl.current?(Kc(""),Xi.current=window.requestAnimationFrame(()=>{Xi.current=null,Kc(D)})):Kc(D),Bl.current=D,Yc.current!==null&&window.clearTimeout(Yc.current),Yc.current=window.setTimeout(()=>{Yc.current=null,Bl.current="",Kc("")},4e3)},Xc=m.useRef(null),md=m.useCallback((D,ve,Ge,st,lt)=>{Xc.current={key:Ge,name:ve,at:st},zo.current=!1,Y(D,ve,N[Ge]?.nextCursor??null,lt)},[N,Y]);m.useEffect(()=>{const D=Xc.current;if(D===null)return;const ve=N[D.key]?.ids;if(ve===void 0||ve.length<=D.at)return;Xc.current=null;const Ge=ve[D.at],st=[ff.current,wn.current],lt=Ge===void 0?null:st.map(es=>es?.querySelector(`[data-session-row="${CSS.escape(Ge)}"]`)??null).find(es=>es!==null)??null,bt=ff.current,Cn=bt===null?null:bt.querySelector(`[data-disclosure][data-entity-key="${CSS.escape(D.key)}"]`);(lt?.querySelector("[data-chat-row]")??lt??Cn??null)?.focus()},[N]);const ho=FJe({pageable:$o,nextCursor:$o?P.tailCursor:null,loading:P.loading,error:P.error??($c!==null&&P.tailCursor===$c.cursor?$c.sentence:null)});m.useEffect(()=>{const D=ie.current;if(D!==null){if(ho.kind==="error"){ie.current=null,Q.current?.focus();return}if(P.tailCursor!==D.cursor){ie.current=null;const Ge=wn.current?.querySelectorAll("[data-session-row]"),st=Ge===void 0||Ge.length===0?null:Ge[Ge.length-1];(st?.querySelector("[data-chat-row]")??st)?.focus();return}Date.now()>D.deadline&&(ie.current=null)}},[ho.kind,P.tailCursor]);const of=ho.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:ho.kind==="loading"?"Loading more chats…":ho.sentence}),ho.kind==="error"&&c.jsx("p",{className:"pt-1",children:c.jsx("button",{ref:Q,type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>{ie.current={deadline:Date.now()+2e4,cursor:P.tailCursor},Ol.current=null,Ll(null),X()},children:h("ui.common.actions.retry")})})]}),Hn=Tx(_r,E),Qc=iJe(_r,E),Nt=OQ(we),lf=le&&Nt.tagsEnabled&&Nt.groupBy==="section",fo=D=>De({...Nt,pins:$Qe(Tx([...vi,...xr],E).map(ve=>ve.session_id),Nt.pins,D)}),Ca=Hn.map(D=>D.session_id),bi=D=>Fd(_r.find(ve=>ve.session_id===D)?.title),Ko=zQe(Hn,Nt.pins),Qi=Ko.map(D=>D.session_id),Sa=new Map(Qi.map((D,ve)=>[D,ve])),jl=D=>XQe(bi(D),Sa.get(D)??0,Qi.length),vd=(D,ve,Ge)=>{if(Sa.get(D)===void 0)return;const lt=bi(D);if(!Ck(Qi,D,ve)){Wn(jl(D));return}const bt=qQe(Tx([...vi,...xr],E).map(rs=>rs.session_id),Nt.pins,Qi,D,ve);if(bt===null)return;De({...Nt,pins:bt}),ys(D,Ge,null,"row",!1);const Cn=Yp(Ca,bt);Wn(qB(lt,Cn.indexOf(D),Cn.length))},Me=(D,ve=!1)=>E&&Nt.groupBy==="section"&&!ve&&Sa.has(D),mt=m.useRef(null),Zt=m.useRef(null),Lt=m.useRef(null),[Un,fr]=m.useState(null),[Hl,Yo]=m.useState(null),[Ag,bd]=m.useState(null),$s=m.useRef(null),Xo=m.useRef(0),Qo=D=>zne(Ko,et,le&&Nt.tagsEnabled&&Nt.groupBy==="section"&&!V.trim(),D),Ul=m.useRef(null),[He,Tn]=m.useState(!1),Rs=m.useRef(!0),qr=m.useRef(0),Ji=m.useRef(null),Jo=(D,ve)=>{const Ge=Lt.current;if(!Ge)return;const st=wn.current,lt=mt.current,bt=st&&lt?EXe(st,D,ve,lt):null;Tn(bt!==null),Ji.current?.classList.remove(...Gm),Ji.current=bt,bt?.classList.add(...Gm),Ul.current=bt?.dataset.tagDropTarget??null;const Cn=document.elementFromPoint(D,ve)?.closest("[data-session-row]");Rs.current=!!Cn&&Cn.closest("[data-chat-section]")===mt.current&&Qo(Ge.id).includes(Cn.dataset.sessionRow??"")},xd=()=>{const D=mt.current;if(D===null)return[];const ve=Lt.current?new Set(Qo(Lt.current.id)):null;return Array.from(D.querySelectorAll("[data-session-row]")).filter(Ge=>!ve||ve.has(Ge.dataset.sessionRow??"")).map(Ge=>{const st=Ge.getBoundingClientRect();return{id:Ge.getAttribute("data-session-row")??"",top:st.top,bottom:st.bottom}})},Jc=D=>{const ve=Lt.current;if(ve===null||!ve.armed)return;const Ge=aK(xd(),ve.id,D);ve.slot!==Ge&&(ve.slot=Ge,fr({id:ve.id,slot:Ge}))},ka=(D,ve)=>{const Ge=mt.current,st=Zt.current;if(Ge===null||st===null)return;const lt=xd().filter(rs=>rs.id!==D),bt=Ge.getBoundingClientRect().top,Cn=ve<=0?lt[0]?.top??bt+Ge.offsetHeight:lt[ve-1]?.bottom??bt;st.style.top=`${Math.round(Cn-bt)}px`},cf=32,wr=12,Fg=()=>{$s.current=null;const D=Lt.current,ve=wn.current;if(D===null||!D.armed||ve===null)return;const Ge=ve.getBoundingClientRect(),st=Xo.current,lt=ve.scrollHeight-ve.clientHeight;let bt=0;st-Ge.top<cf&&ve.scrollTop>0?bt=-1:Ge.bottom-st<cf&&ve.scrollTop<lt&&(bt=1),bt!==0&&(ve.scrollTop+=bt*wr),Jo(qr.current,st),Jc(st),$s.current=requestAnimationFrame(Fg)},HC=()=>{$s.current!==null&&(cancelAnimationFrame($s.current),$s.current=null)},lX=(D,ve,Ge)=>{if(Ge.button===0){Ge.preventDefault(),Ge.stopPropagation();try{Ge.currentTarget.setPointerCapture(Ge.pointerId)}catch{}Lt.current={pointerId:Ge.pointerId,id:D,label:ve,armed:!1,slot:-1},Xo.current=Ge.clientY,qr.current=Ge.clientX,Jo(Ge.clientX,Ge.clientY)}},cX=D=>{const ve=Lt.current;ve===null||D.pointerId!==ve.pointerId||(Xo.current=D.clientY,qr.current=D.clientX,Jo(D.clientX,D.clientY),ve.armed||(ve.armed=!0,fr({id:ve.id,slot:ve.slot}),Wn(h("ui.chat.tags.move_armed",{name:ve.label})),$s.current===null&&($s.current=requestAnimationFrame(Fg))),Jc(D.clientY))},uX=(D,ve)=>{const Ge=bi(D),st=KQe(Tx([...vi,...xr],E).map(bt=>bt.session_id),Nt.pins,Qo(D),D,ve);if(st===null){Wn("");return}De({...Nt,pins:st}),ys(D,!1,null,"row",!1);const lt=Yp(Ca,st);Wn(qB(Ge,lt.indexOf(D),lt.length))},vb=(D,ve)=>{ve&&Jo(ve.x,ve.y);const Ge=Lt.current;if(Lt.current=null,HC(),Ji.current?.classList.remove(...Gm),Ji.current=null,fr(null),Tn(!1),Ge===null||!Ge.armed)return;const st=Ul.current;if(Ul.current=null,D&&st){const lt=[...vi,...xr].find(bt=>bt.session_id===Ge.id);lt&&wk(lt,st,Wn).catch(()=>{});return}if(!D||!Rs.current){Wn(h("ui.chat.tags.move_cancelled"));return}uX(Ge.id,Ge.slot)},Dg=m.useRef(vb);Dg.current=vb;const _d=TXe({enabled:le&&Nt.tagsEnabled&&Nt.groupBy==="section"&&!V.trim(),arm:D=>{Wn(h("ui.chat.tags.move_armed",{name:bi(D)})),Qi.includes(D)&&(Lt.current={id:D,label:bi(D),pointerId:-1,armed:!0,slot:-1},fr({id:D,slot:-1}))},move:(D,ve,Ge,st)=>{if(!Lt.current||Lt.current.id!==D)return;Ul.current=st,Tn(st!==null);const lt=Ge?.closest("[data-session-row]");Rs.current=!!lt&&lt.closest("[data-chat-section]")===mt.current&&Qo(D).includes(lt.dataset.sessionRow??""),!st&&Rs.current&&Jc(ve)},settle:(D,ve,Ge)=>{if(Lt.current?.id===D){Dg.current(Ge);return}const st=[...vi,...xr].find(lt=>lt.session_id===D);Ge&&ve&&st?wk(st,ve,Wn).catch(()=>{}):Wn(h("ui.chat.tags.move_cancelled"))}});m.useEffect(()=>{if(Un===null)return;const D=ve=>{ve.key==="Escape"&&(Dg.current(!1),ve.preventDefault())};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[Un!==null]),m.useEffect(()=>{if(Un===null)return;const D=Ge=>{Lt.current?.pointerId===Ge.pointerId&&Dg.current(!0,{x:Ge.clientX,y:Ge.clientY})},ve=()=>Dg.current(!1);return window.addEventListener("pointerup",D),window.addEventListener("pointercancel",ve),window.addEventListener("blur",ve),()=>{window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",ve),window.removeEventListener("blur",ve)}},[Un!==null]),m.useEffect(()=>()=>{$s.current!==null&&cancelAnimationFrame($s.current)},[]),m.useLayoutEffect(()=>{Un!==null&&ka(Un.id,Un.slot)},[Un]);const iI=m.useMemo(()=>new Set(_r.map(D=>D.session_id)),[_r]),UC=m.useMemo(()=>gJe(It,Ie,iI),[It,Ie,iI]),uf=UC.filter(D=>!D.pending),bb=V.trim().length>0,aI=bb?Qc:VI(Qc,Nt.orderBy,Nt.basis),Gl=LQ(aI,{limit:wd(Nt.loads),currentId:e,searching:bb}),oI=Gl.lifted?Gl.rows[0]:null,lI=Gl.lifted?Gl.rows.slice(1):Gl.rows;Wc.current=Gl.remaining>0||Nt.hidden.length>0;const dX=wd(Nt.loads+1)-wd(Nt.loads),hX=Ms&&P.tailCursor!==null,fX=()=>{const D=Nt.loads+1;De({...Nt,loads:D}),Ms&&wd(D)>Qc.length&&X()},pX=Nt.groupBy!==kb.groupBy||Nt.basis!==kb.basis||Nt.orderBy!==kb.orderBy||Nt.hidden.length>0||Nt.loads>0||Nt.pins.length>0||Nt.pinnedAgents.length>0||Nt.order.some((D,ve)=>D!==kb.order[ve]),df=BQ(lI,Te,Nt.basis),cI=jQ(Nt).filter(D=>D!=="pinned"&&!b5(D)),gX=bm(Nt,"pinned"),mX=cI.find(D=>df[D].length>0)??null,vX={pinned:Hn.length,running:df.running.length,today:df.today.length,week:df.week.length,older:df.older.length,agents:J.length,teams:Xe.data?.length??0},GC=m.useMemo(()=>uJe(J.map(D=>({id:D.name,name:D.name})),{pinned:Nt.pinnedAgents,recency:D=>cJe(d,D.name)}),[J,Nt.pinnedAgents,d]),VC=HQ(fi("agents",!0),V,Re,J.length),bX=m.useMemo(()=>lJe(GC,Re),[GC,Re]),uI=VC&&Re.trim()?bX.filter(D=>WI(D.name,Vc("agent",D.name).length,V)):[],xb=Nt,dI=un?It[un]:void 0,hI=D=>D.binding?.team||D.binding?.agent||"",WC=D=>D.binding?.team??"",fI=D=>{const ve=D.binding?.team;return ve?ut(ve):D.binding?.agent??""},pI=D=>D.opened_by!=null,gI=D=>`opened by ${D.opened_by?.agent?.trim()||"an agent"}`,xX=D=>{if(!D.opened_by)return"";const ve=D.opened_by.label?.trim();return`, ${gI(D)}${ve?` in “${ve}”`:""}`},_X=D=>{const ve=hI(D);return!ve||D.opened_by?.agent?.trim()===ve?"":` (${fI(D)})`},Ig=WB(nr.data,V),mI=m.useMemo(()=>Ig||!nr.data||!V.trim()?null:LR([...vi,...xr],nr.data.query,nr.data.sessions,oe,Hc,Ii,ut),[Ig,nr.data,vi,xr,oe,Hc,Ii,ut,V]),vI=!!V.trim()&&g&&uo&&!ya&&!nr.isError&&!Ig,$C=m.useMemo(()=>new Set(Object.values(It).filter(D=>D.sessionId).map(D=>D.sessionId)),[It]),bI=D=>{const ve=Zne(D,et,le&&Nt.tagsEnabled&&Nt.groupBy==="section"&&!V.trim());if(!ve)return D.map(st=>Ng(st));const Ge=ve.map(st=>st.id).filter(st=>st!=="untagged");return ve.map(st=>c.jsxs("div",{"data-chat-tag-group":st.id,className:"[&[data-tag-drop-preview]_[data-chat-row]]:bg-row-selected [&[data-tag-drop-preview]_[data-session-row]]:bg-row-selected",children:[c.jsx(pK,{id:st.id,name:st.name,count:st.rows.length,above:Ge[Ge.indexOf(st.id)-1]??null,below:Ge[Ge.indexOf(st.id)+1]??null,announce:Wn}),c.jsx("div",{"data-tag-drop-target":st.id,"data-tag-drop-body":!0,children:st.rows.map(lt=>Ng(lt,!1,!0))})]},st.id))},Ng=(D,ve=!1,Ge=!1)=>{const st=lQe({marked:rf.has(D.session_id),unstarted:$C.has(D.session_id),nested:ve,binding:hI(D),team:WC(D),agentOpened:pI(D)}),lt=D.pinned===!0,bt=D.locality==="remote",Cn=bt?sJe(D,x.get(typeof D.owner_device=="string"?D.owner_device:"")):"",rs=bt?rJe(D):"",es=Yt=>{ba(Yt,D.session_id)||t(D.session_id)},Nn=(Yt,xi)=>c.jsx("span",{className:"ms-1 inline-flex shrink-0",onPointerEnter:()=>Yo(D.session_id),onPointerLeave:()=>Yo(null),onFocus:()=>bd(D.session_id),onBlur:()=>bd(null),children:c.jsx(RK,{name:Yt,slug:xi,onActivate:()=>es(null)})}),us=oJe(D),ts=Fd(D.title),po=fd[D.session_id]??D.archived===!0,Zi=e===D.session_id&&!un,pf=E||hr||le,gf=!$C.has(D.session_id),Zc=gj(),eu=_b===D.session_id,ea=Un?.id===D.session_id||_d.armedId===D.session_id,go=D.status?.code==="wedged",mo=bJe(Pe,D.session_id,typeof D.owner_device_name=="string"?D.owner_device_name:null),jg=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"block",children:[Fd(D.title),_X(D)]}),c.jsxs("span",{className:"block",children:[D.link_down===!0?tE(D,Te/1e3):Bx(D)??D.status?.label??(pd.has(D.session_id)?"found by search, beyond the chats listed here":"Recent"),go?` · ${hj}`:"",xX(D),$C.has(D.session_id)?", not sent yet":"",dy(D)!==null?", unread":"",po?", archived":"",us,mo?` · ${mo.clause}`:""]}),bt&&c.jsx("span",{className:"block",children:Cn}),rs&&c.jsx("span",{className:"block",children:rs})]}),Wl=c.jsxs("button",{type:"button","data-chat-row":!0,"data-tour-tag":"chat-session-row","data-child":ve||void 0,"data-session-archived":po?"true":void 0,className:R(dm,"min-w-0 grow text-start",Ge&&(_d.armedId===D.session_id?"cursor-grabbing":"cursor-grab active:cursor-grabbing"),ve&&"ps-7",Zi&&yo),"aria-current":Zi?"page":void 0,...go||mo||pf?{"aria-describedby":[go?fj(D.session_id):null,mo?pj(D.session_id):null,pf?mj(D.session_id):null].filter(Boolean).join(" ")}:{},onPointerDown:Yt=>{bt||_d.start(D.session_id,Yt)},onClick:Yt=>{if(_d.consumeClick(D.session_id,Yt.detail)){Yt.preventDefault();return}es(Yt.detail===0?null:{x:Yt.clientX,y:Yt.clientY})},children:[c.jsx("span",{"aria-hidden":"true",className:"flex size-3.5 shrink-0 items-center justify-center",children:D.locality==="remote"&&c.jsx(NJe,{unreachable:D.link_down===!0||D.reachable===!1})}),c.jsx(SZe,{row:D,nowSeconds:Te/1e3}),c.jsx(xZe,{row:D,open:u?.get(D.session_id)}),hr&&po&&c.jsxs(c.Fragment,{children:[c.jsx(np,{"aria-hidden":"true",className:"ms-1 size-3.5 shrink-0 text-ink-dim"}),c.jsx("span",{className:"sr-only",children:h("ui.chat.sidebar.row.archived_suffix")})]}),c.jsx(BJe,{text:Fd(D.title)}),st==="team"&&Nn(ut(WC(D)),WC(D)),st==="binding"&&(D.binding?.team?Nn(ut(D.binding.team),D.binding.team):c.jsxs("span",{className:"ms-1 max-w-[45%] shrink-0 truncate text-meta text-ink-muted",children:["· ",fI(D)]})),st==="not_sent"&&c.jsxs("span",{className:"ms-1 shrink-0 text-meta text-ink-muted",children:["· ",h("ui.chat.sidebar.row.not_sent")]}),st==="conversation"&&c.jsxs(c.Fragment,{children:[c.jsxs("span",{"aria-hidden":"true",className:"ms-1 shrink-0 whitespace-nowrap text-meta text-ink-muted",children:["· ",h("ui.chat.sidebar.row.in_conversation")]}),c.jsx("span",{className:"sr-only",children:h("ui.chat.sidebar.row.matched_in_conversation")})]}),bt&&c.jsxs("span",{className:"sr-only",children:[", ",Cn]}),rs&&c.jsxs("span",{className:"sr-only",children:[", ",rs]}),pI(D)&&(st==="team"||st==="none")&&c.jsxs("span",{className:"sr-only",children:[", ",gI(D)]}),us!==""&&c.jsx("span",{className:"sr-only",children:us}),Bx(D)?c.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:Bx(D)}):D.link_down===!0?c.jsx("span",{className:R("shrink-0 text-meta",D.link_reconnecting===!0?"text-ink-dim":"text-warning"),title:tE(D,Te/1e3),children:XQ(D,Te/1e3)}):!QQ(D)&&XI(D,Te,Nt.basis)&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true","data-session-time":!0,className:"ms-auto shrink-0 ps-2 font-mono text-ink-dim text-mono-sm tabular-nums group-has-[:focus-visible]:hidden group-data-[session-hover-intent]:hidden",children:XI(D,Te,Nt.basis)}),c.jsxs("span",{className:"sr-only",children:[", ",JQ(D,Te,Nt.basis)]})]})]}),mf=go?c.jsx("span",{id:fj(D.session_id),className:"sr-only",children:hj}):null,$l=mo?c.jsx("span",{id:pj(D.session_id),className:"sr-only",children:mo.description}):null,yb=pf?c.jsx("span",{id:mj(D.session_id),className:"sr-only",children:NZe(Zc)}):null,Hg=Yt=>{const xi=Yt.relatedTarget;xi&&Yt.currentTarget.contains(xi)&&Yt.preventDefault()},Cb=(Yt,xi)=>c.jsx(vt,{content:jg,side:"bottom",align:"start",disableHoverableContent:!0,collisionPadding:PZe,className:"w-(--radix-tooltip-trigger-width) max-w-none",suppressed:Un!==null||_d.armedId!==null||Ue!==null||Hl===D.session_id||Ag===D.session_id,children:Yt},xi);if(!pf)return Cb(c.jsxs("div",{onBlur:Hg,className:R(Ak,Zi&&yo),children:[Wl,c.jsx(ij,{row:D}),mf,$l]}),D.session_id);const Pr=E&&hr,tu=Ck(Qi,D.session_id,-1),Sb=Ck(Qi,D.session_id,1),FI=Me(D.session_id,ve),DI=c.jsxs(c.Fragment,{children:[FI&&c.jsx(c.Fragment,{children:Qi.length>=2&&c.jsx("button",{type:"button","data-session-pin-grip":!0,tabIndex:-1,"aria-hidden":"true",title:h("ui.chat.sidebar.pins.drag_title"),onPointerDown:Yt=>lX(D.session_id,ts,Yt),onPointerMove:cX,onPointerUp:Yt=>vb(!0,{x:Yt.clientX,y:Yt.clientY}),onPointerCancel:()=>vb(!1),className:R("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",eu&&"flex text-ink-muted","hover:text-ink!",!Zi&&"hover:bg-row-hover"),children:c.jsx(Zce,{"aria-hidden":"true",className:"size-4"})})}),D.pinned!==void 0&&c.jsx("button",{type:"button","data-session-pin":!0,tabIndex:-1,"aria-pressed":lt,"aria-label":lt?h("ui.chat.sidebar.pins.unpin_label",{title:ts}):h("ui.chat.sidebar.pins.pin_label",{title:ts}),title:lt?h("ui.chat.sidebar.pins.unpin_label",{title:ts}):h("ui.chat.sidebar.pins.pin_label",{title:ts}),onClick:Yt=>{ba(Yt.detail===0?null:{x:Yt.clientX,y:Yt.clientY},D.session_id)||(ys(D.session_id,Yt.detail===0,{x:Yt.clientX,y:Yt.clientY}),B(D.session_id,!lt,{title:D.title??void 0,updated_at:D.updated_at??void 0}),lt||fo(D.session_id),lt&&Nt.pins.includes(D.session_id)&&De({...Nt,pins:YQe(Nt.pins,D.session_id)}))},className:R("size-6 shrink-0 items-center justify-center rounded-md",lt?"flex text-ink":R("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",eu&&"flex text-ink-muted","hover:text-ink!"),!Zi&&"hover:bg-row-hover"),children:c.jsx(G1,{"aria-hidden":"true",className:"size-4",fill:lt?"currentColor":"none"})}),hr&&c.jsx("button",{type:"button","data-session-archive":!0,tabIndex:-1,"aria-label":C_(ts,po),title:C_(ts,po),onClick:Yt=>{const xi=VQe(Pl.current,Yt.detail===0?null:{x:Yt.clientX,y:Yt.clientY},D.session_id);if(Pl.current=xi.record,xi.drop)return;if(!po){jc({sessionId:D.session_id,fromRow:!0});return}const PX=fG(Yt.currentTarget);mi(D.session_id,!1,D.title??void 0).then(MX=>{MX&&PX()})},className:R(R("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",eu&&"flex text-ink-muted"),"hover:text-ink!",!Zi&&"hover:bg-row-hover"),children:po?c.jsx(K_,{"aria-hidden":"true",className:"size-4"}):c.jsx(np,{"aria-hidden":"true",className:"size-4"})})]}),NX=c.jsxs("div",{"data-session-row":D.session_id,"data-session-menu-trigger":!0,onKeyDown:SX,onPointerDownCapture:kX,"data-dragging":ea?"":void 0,onBlur:Hg,className:R((E||hr)&&"group",(E||hr)&&!Zi&&"hover:bg-row-hover",eu&&!Zi&&"bg-row-hover",Ak,Zi&&yo,ea&&IK,ea&&NK),children:[(E||hr)&&c.jsx(PJe,{}),Wl,c.jsx(ij,{row:D}),mf,$l,yb,Pr?c.jsx("div",{"data-session-control-pair":!0,className:R("items-center gap-1",lt||eu?"flex":"hidden group-data-[session-hover-intent]:flex group-has-[:focus-visible]:flex"),children:DI}):DI]});return c.jsxs(qne,{open:eu,onOpenChange:Yt=>{Yt&&(Un!==null||_d.armedId!==null)||(Yt&&Bg.current===null&&(Bg.current=document.activeElement instanceof HTMLElement?document.activeElement:null),TI(xi=>Yt?D.session_id:xi===D.session_id?null:xi))},children:[c.jsx(DZe,{id:D.session_id,openMenuRowIdRef:YC,setOpenMenuRowId:TI,openedByKeyboard:Lg}),Cb(c.jsx(Kne,{asChild:!0,children:NX}),D.session_id),c.jsxs(Yne,{className:kXe,onFocus:Yt=>{Lg.current&&Yt.target===Yt.currentTarget&&Yt.currentTarget.querySelector('[role="menuitem"]')?.focus()},onCloseAutoFocus:Yt=>{if(Yt.preventDefault(),Ue)return;const xi=Bg.current;if(Bg.current=null,!Lg.current){xi?.isConnected?xi.focus():document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`)?.focus();return}Lg.current=!1,document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`)?.focus()},children:[hr&&c.jsxs(zl,{onSelect:()=>vj(D.session_id,"archive"),children:[po?c.jsx(K_,{"aria-hidden":"true"}):c.jsx(np,{"aria-hidden":"true"}),c.jsx("span",{children:po?h("ui.chat.sidebar.row_menu.unarchive"):h("ui.chat.sidebar.row_menu.archive")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:NN("archive",Zc),joined:!0})})]}),D.pinned!==void 0&&c.jsxs(zl,{onSelect:()=>vj(D.session_id,"pin"),children:[lt?c.jsx(Nue,{"aria-hidden":"true"}):c.jsx(G1,{"aria-hidden":"true"}),c.jsx("span",{children:lt?h("ui.chat.sidebar.row_menu.unpin"):h("ui.chat.sidebar.row_menu.pin")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:NN("pin",Zc),joined:!0})})]}),gf&&c.jsxs(zl,{onSelect:()=>{i("session.fork",document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`),D.session_id),r.pathname.startsWith("/chat")||s("/chat")},children:[c.jsx(Xne,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.fork")})]}),c.jsxs(zl,{onSelect:()=>void cK(D.session_id),children:[c.jsx(ed,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.copy_id")})]}),c.jsxs(zl,{onSelect:()=>{i("session.rename",document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`),D.session_id,{subjectName:Fd(D.title)}),r.pathname.startsWith("/chat")||s("/chat")},children:[c.jsx(Vv,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.rename")})]}),le&&c.jsxs(zl,{"aria-disabled":D.locality==="remote",title:D.locality==="remote"?h("ui.chat.tags.remote"):void 0,className:"aria-disabled:cursor-default aria-disabled:text-ink-disabled! aria-disabled:hover:bg-transparent!",onSelect:Yt=>{if(D.locality==="remote"){Yt.preventDefault(),Wn(h("ui.chat.tags.remote"));return}sn(D)},children:[c.jsx(Qne,{"aria-hidden":"true",className:"size-3.5"}),c.jsx("span",{children:h("ui.chat.tags.menu")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:Jne(Zc),joined:!0})})]}),le&&(D.tags?.length??0)>0&&c.jsxs(zl,{onSelect:()=>{wk(D,"untagged",Wn).catch(()=>{})},children:[c.jsx(Xn,{"aria-hidden":"true"}),h("ui.chat.tags.remove_all",{count:new Set(D.tags?.map(Yt=>Yt.id)).size})]}),FI&&c.jsxs(c.Fragment,{children:[c.jsxs(zl,{"aria-disabled":!tu,title:tu?void 0:jl(D.session_id),onSelect:()=>vd(D.session_id,-1,!0),className:R("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(Hv,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.move_up")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:KB(-1,Zc),joined:!0})})]}),c.jsxs(zl,{"aria-disabled":!Sb,title:Sb?void 0:jl(D.session_id),onSelect:()=>vd(D.session_id,1,!0),className:R("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(Ei,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.move_down")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:KB(1,Zc),joined:!0})})]})]})]})]},D.session_id)},Pg=(D,ve)=>s(`/agents?kind=${D}&name=${encodeURIComponent(ve)}`),wX=async(D,ve,Ge)=>{if(Ge.kind==="review"||Ge.kind==="failed"&&!Ge.retryable)return Pg(D,ve);(Ge.kind==="failed"?await Vt.retryItem(D,ve):await Vt.applyItem(D,ve))?.some(lt=>lt.outcome==="needs-review")&&Pg(D,ve)},yX=async D=>{await Vt.applyAll(D),requestAnimationFrame(()=>{const ve=document.activeElement;ve&&ve!==document.body||document.querySelector(`[data-chat-section="${IXe[D]}"]`)?.focus()})},xI=D=>c.jsx(dZe,{kind:D,available:UXe(At.data,D),busy:Vt.pending.has(`all:${D}`),blocked:!Vt.canWrite,onUpdateAll:()=>void yX(D),onCheck:D==="agent"&&cs?()=>void Vt.checkNow():void 0,checking:Vt.pending.has("check")}),_I=D=>c.jsx(hZe,{kind:D,reserve:D==="agent"&&(cs||At.data?.credential==="none"),signIn:D==="agent"?VXe(At.data):null,signInHref:"/settings?section=radient",rollup:Vt.rollups[D],note:Vt.notes[`all:${D}`]??(D==="agent"?Vt.notes.check:void 0)??(D==="agent"&&cs&&Vt.upgradeMessage?{message:Vt.upgradeMessage,tone:"info"}:void 0),onDismissRollup:()=>Vt.clearRollup(D)}),zC=(D,ve,Ge=ve)=>{const st=Vc(D,ve),lt=zI(D,ve),bt=D==="team"?ut(ve):ve,Cn=bt!==ve?`${bt} (${ve})`:bt,rs=!!V||fi(lt),es=KQ(bb?st:VI(st,xb.orderBy,xb.basis),{loads:CI[lt]??0,currentId:e,searching:bb}),Nn=es.rows,us=TJe({pageable:Ms,total:Ms?kk(M,D,ve):null,held:st.length,searching:!!V.trim()}),ts=EJe({pageable:Ms,scope:N[lt],held:N[lt]?.ids.length??st.length,total:Ms?kk(M,D,ve):null}),po=Ms?kk(M,D,ve)??st.length:st.length,Zi=CI[lt]??0,pf=wd(Zi+1)-wd(Zi),gf=YQ({add:es.hidden>0?Math.min(pf,es.hidden):Ms&&ts.more?ts.addCount:0,drawn:Nn.length,total:po}),Zc=()=>{const Pr=Zi+1;if(SI(Sb=>({...Sb,[lt]:Pr})),!Ms)return;const tu=N[lt]?.ids.length??0;N[lt]?.nextCursor!==null&&wd(Pr)>=tu&&md(D,ve,lt,tu,ts.addCount)};if(!WI(ve,st.length,V,bt))return null;const eu=D==="team"?Vm:yl,ea=dI?.target?.kind===D&&dI.target.name===ve,go=D==="agent"&&xb.pinnedAgents.includes(Ge),mo=Ev(D,ve),jg=cn.get(mo),Wl=tK(jg),mf=D==="team"?Xe.data?.find(Pr=>Pr.name===ve)?.id:fe.data?.find(Pr=>Pr.name===ve)?.agent_id??void 0,$l=rn?nQe(ws.data,D,mf,ve):[],yb=$l.length===1?$l[0]:void 0,Hg=$l.length>1?$l:null,Cb=rn&&$l.length===0?sQe(ws.data,D,mf,ve):[];return c.jsxs("div",{"data-entity":!0,children:[c.jsxs("div",{className:R("group flex h-8 items-center gap-1 rounded-md",ea&&yo),children:[c.jsx("button",{type:"button","data-disclosure":!0,"data-entity-key":lt,"aria-label":rs?h("ui.chat.sidebar.entity.collapse_chats",{name:bt}):h("ui.chat.sidebar.entity.expand_chats",{name:bt}),"aria-expanded":rs,className:R("flex size-6 shrink-0 items-center justify-center rounded-md",!ea&&"hover:bg-row-hover"),onClick:()=>{rs&&SI(Pr=>{if(Pr[lt]===void 0)return Pr;const tu={...Pr};return delete tu[lt],tu}),co(lt)},children:rs?c.jsx(Ei,{className:"size-3.5"}):c.jsx(Vi,{className:"size-3.5"})}),c.jsxs("button",{type:"button","data-chat-row":!0,"data-entity-name":!0,className:R(dm,"flex-1 text-start",ea&&yo),onClick:()=>n({kind:D,name:ve}),"aria-label":h("ui.chat.header.new_chat_with",{target:bt}),title:h("ui.chat.header.new_chat_with",{target:bt}),children:[c.jsx(IZe,{agentId:D==="agent"?mf??null:null,glyph:eu}),c.jsx("span",{className:"min-w-0 flex-1 truncate",title:Cn,children:bt}),c.jsx(iT,{className:R("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:us>0?JB(us):void 0,className:"min-w-4 shrink-0 text-end text-meta tabular-nums text-ink-dim",children:us||""})]}),us>0&&c.jsx("span",{className:"sr-only",children:JB(us)}),D==="agent"&&c.jsx(vt,{content:go?h("ui.chat.sidebar.entity.unpin",{name:ve}):h("ui.chat.sidebar.entity.pin",{name:ve}),children:c.jsx("button",{type:"button","data-agent-pin":Ge,className:R("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim hover:text-ink-muted",!ea&&"hover:bg-row-hover",go?"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":go,"aria-label":h(go?"ui.chat.sidebar.entity.unpin":"ui.chat.sidebar.entity.pin",{name:ve}),onClick:()=>De(dJe(xb,Ge)),children:c.jsx(G1,{"aria-hidden":"true",className:R("size-4",go&&"text-ink"),fill:go?"currentColor":"none"})})}),yb&&c.jsx(rZe,{link:yb,staged:ea,onDetail:()=>Pg(D,ve),itemName:ve,displayName:bt,itemsById:kn,nameAmbiguous:!(D==="team"?Xe.isSuccess&&!Xe.isFetching:fe.isSuccess&&!fe.isFetching)||(Ft[D==="team"?"team":"agent"].get(ve.trim().toLowerCase())??0)!==1}),Hg&&c.jsx(oZe,{links:Hg,staged:ea,onDetail:()=>Pg(D,ve)}),Cb.length>0&&c.jsx(iZe,{item:ve,staged:ea,onResolve:()=>s(`/agents?kind=${D}&name=${encodeURIComponent(ve)}&resolve=${Date.now()}`)}),!rn&&Wl&&jg&&c.jsx(cZe,{item:jg,mark:Wl,busy:Vt.pending.has(mo),blocked:!Vt.canWrite&&(Wl.kind==="available"||Wl.kind==="failed"&&Wl.retryable),staged:ea,onPress:()=>wX(D,ve,Wl)}),c.jsx("button",{type:"button",className:R("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim hover:text-ink-muted",!ea&&"hover:bg-row-hover"),"aria-label":h("ui.chat.sidebar.entity.manage",{name:bt}),onClick:()=>s(`/agents?kind=${D}&name=${encodeURIComponent(ve)}`),children:c.jsx(oc,{className:"size-4"})})]}),Vt.notes[mo]&&c.jsx(uZe,{note:Vt.notes[mo]}),rs&&c.jsxs("div",{children:[$l.map(Pr=>c.jsx(aZe,{link:Pr},Pr.link_id)),es.lifted&&hf(h("ui.chat.sidebar.section.current_chat")),Nn.map(Pr=>Ng(Pr,!0))," ",c.jsxs("div",{"aria-live":"polite",className:ts.state!=="rows"&&ts.sentence!==null?"py-1 ps-7":"sr-only",children:[ts.state!=="rows"&&ts.sentence!==null&&c.jsx("p",{className:"line-clamp-2 text-meta text-ink-dim",title:ts.sentence,children:ts.sentence}),ts.state!=="rows"&&ts.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 Y(D,ve,null),children:h("ui.common.actions.retry")})})]}),ts.state==="rows"&&(N[lt]?.loading?c.jsx("p",{className:"py-1 ps-7 text-meta text-ink-dim","aria-live":"polite",children:h("ui.chat.sidebar.list.loading_more")}):ts.retry?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"line-clamp-2 py-1 ps-7 text-meta text-ink-dim","aria-live":"polite",children:ts.sentence}),c.jsx("p",{className:"py-1 ps-7",children:c.jsx("button",{type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>md(D,ve,lt,N[lt]?.ids.length??st.length,ts.addCount),children:h("ui.common.actions.retry")})})]}):gf?c.jsx("button",{type:"button","data-scope-more":lt,"data-chat-row":!0,"data-entity-more":lt,"aria-label":`${gf.aria} in ${bt}`,title:`${gf.aria} in ${bt}`,className:"block w-full py-1 ps-7 text-start text-meta text-ink-dim underline hover:text-ink",onClick:Zc,children:gf.label}):null)]})]},lt)},wI=(D,ve,Ge,st,lt,bt,Cn,rs)=>{const es=qI(Mg[D])?KI:null;return c.jsxs("div",{className:R("@container/chatheading flex h-7 items-center gap-1",bt),children:[c.jsxs("button",{ref:Cn,type:"button","data-chat-row":!0,"data-chat-section":D,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":V?!0:fi(D,Ge),title:es??void 0,"aria-describedby":es?YI(D):void 0,onClick:()=>co(D,Ge),children:[V||fi(D,Ge)?c.jsx(Ei,{className:"size-3.5"}):c.jsx(Vi,{className:"size-3.5"}),lt?m.createElement(lt,{"aria-hidden":!0,className:"size-3.5 shrink-0 text-ink-dim"}):null,c.jsx("span",{className:"min-w-0 flex-1 truncate text-start",children:ve}),st!==void 0]}),es&&c.jsx("span",{id:YI(D),className:"sr-only",children:es}),bt,rs]})},[Mg,yI]=m.useState({}),[CI,SI]=m.useState({}),qC=m.useRef(null),kI=(D,ve)=>{const Ge=Mg[D]??$I,st=ve.length-Ge,lt=zQ(st,D);return c.jsxs(c.Fragment,{children:[ve.slice(0,Ge),st>0&&c.jsx("button",{type:"button","data-sidebar-section-more":D,"data-chat-row":!0,"aria-label":lt,title:qI(Ge)?`${lt} - ${KI}`:lt,onClick:()=>{qC.current={key:D,at:Ge},yI(bt=>qQ(bt,D))},className:"flex h-7 w-full items-center rounded-md px-2 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:$Q(st)})]})},hf=(D,ve)=>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:D}),ve]}),EI=m.useRef(null),KC=`[data-chat-row], [${GR}]`,Og=D=>{const ve=Vl.current;if(ve===null)return;const Ge=[...ve.querySelectorAll(KC)],st=Ge.filter(bt=>!bt.disabled&&bt.closest("[hidden]")===null);if(st.length===0)return;const lt=D!==null&&st.includes(D)?D:st[0];EI.current=lt;for(const bt of Ge)bt.tabIndex=st.includes(bt)&&bt===lt?0:-1,bt.toggleAttribute($ne,st.includes(bt)&&bt===lt)};m.useLayoutEffect(()=>{Og(EI.current)});const CX=D=>{const ve=D.target.closest?.(KC);ve!=null&&Vl.current?.contains(ve)&&Og(ve)},[_b,TI]=m.useState(null),Lg=m.useRef(!1),Bg=m.useRef(null),YC=m.useRef(null);m.useEffect(()=>{YC.current=_b},[_b]);const SX=D=>{if(D.key!=="ContextMenu"&&!(D.shiftKey&&D.key==="F10"))return;const ve=D.currentTarget;D.preventDefault(),Lg.current=!0;const Ge=ve.getBoundingClientRect();ve.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:Ge.left,clientY:Ge.bottom-1}))},kX=()=>{YC.current===null&&(Bg.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},EX=D=>{if(_b!==null||!D.currentTarget.contains(D.target))return;const ve=D.target;if(le&&ese(D)&&ve.hasAttribute("data-chat-row")){const Nn=ve.closest("[data-session-row]")?.dataset.sessionRow,us=[...vi,...xr].find(ts=>ts.session_id===Nn);us&&(D.preventDefault(),us.locality==="remote"?Wn(h("ui.chat.tags.remote")):sn(us));return}const Ge=tse(D);if(Ge!==null){const Nn=nse(ve,Ge);Nn!==null&&(D.preventDefault(),Nn.click());return}const st=JQe(D);if(st!==null){const Nn=eJe(ve);if(Nn===null)return;Me(Nn)?(D.preventDefault(),vd(Nn,st,!0)):Ca.includes(Nn)||Wn(QQe(bi(Nn)));return}if(ve===C.current){const Nn=()=>D.currentTarget.querySelector('[data-sidebar-region="chats"] [data-chat-row]');if(D.key==="ArrowDown"){const us=Nn();us&&(D.preventDefault(),us.focus(),Og(us));return}if(D.key==="Escape"){j(""),Z(!1);const us=Nn();us?(us.focus(),Og(us)):ve.blur()}return}if(D.key.length===1&&D.key!==" "&&!D.metaKey&&!D.ctrlKey&&!D.altKey&&ve.hasAttribute("data-chat-row")){D.preventDefault(),Z(!0),j(Nn=>Nn+D.key),window.requestAnimationFrame(()=>C.current?.focus());return}if(D.key==="Escape"){D.preventDefault(),ee&&C.current?.focus();return}if(D.key==="ArrowUp"&&ve.hasAttribute("data-entity-name")){const Nn=ve.closest("[data-entity]"),us=Nn?.closest("section");if(Nn&&us&&us.querySelector("[data-entity]")===Nn){const ts=us.querySelector("[data-roster-filter]");if(ts){D.preventDefault(),ts.focus();return}}}const lt=[...D.currentTarget.querySelectorAll(KC)].filter(Nn=>!Nn.disabled&&Nn.closest("[hidden]")===null),bt=lt.indexOf(ve),Cn=D.key==="ArrowDown"?Math.min(lt.length-1,bt+1):D.key==="ArrowUp"?Math.max(0,bt-1):D.key==="Home"?0:D.key==="End"?lt.length-1:-1;if(Cn>=0){D.preventDefault();const Nn=lt[Cn];Nn?.focus(),Nn!==void 0&&Og(Nn);return}const rs=ve.closest("[data-entity]"),es=rs?.querySelector("[data-disclosure]");D.key==="ArrowRight"&&es&&(D.preventDefault(),es.getAttribute("aria-expanded")==="false"?es.click():rs?.querySelector("[data-child]")?.focus()),D.key==="ArrowLeft"&&es&&(D.preventDefault(),ve.hasAttribute("data-child")?rs?.querySelector("[data-entity-name]")?.focus():es.getAttribute("aria-expanded")==="true"&&es.click())},ff=m.useRef(null),RI=m.useRef({node:null,index:-1,visibility:"outside",clipHeight:0}),AI=m.useRef({node:null,index:-1,visibility:"outside",clipHeight:0}),TX=m.useCallback(D=>{ff.current=D,wn.current=D},[]);m.useLayoutEffect(()=>{sj(ff.current,RI),sj(wn.current,AI)}),m.useEffect(()=>{const D=qC.current;if(D===null)return;qC.current=null;const ve=ff.current;if(ve===null)return;const Ge=ve.querySelector(`[data-chat-section="${CSS.escape(D.key)}"]`),st=Ge?.closest("section")??null,lt=st===null?[]:[...st.querySelectorAll("[data-entity]")],Cn=(Mg[D.key]??$I)>D.at?lt[D.at]??null:null;(Cn?.querySelector("[data-chat-row]")??Cn??Ge??null)?.focus()},[Mg]);const Vl=m.useRef(null),RX=m.useRef(null),AX=z,FX=c.jsxs("div",{id:EZe,"data-sidebar-region":"entities",className:R("relative space-y-4"),children:[a.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:h("ui.chat.sidebar.list.connecting")}),a.error&&!w&&!S&&c.jsxs("div",{className:"space-y-1 text-meta text-ink-muted",children:[c.jsxs("p",{children:[a.error.message,U?" Showing the last chats loaded.":""]}),c.jsx("button",{type:"button",className:"underline",onClick:()=>void a.refetch(),children:h("ui.chat.sidebar.list.retry_refresh")})]}),te&&!w&&c.jsxs("div",{className:"space-y-1 text-meta text-ink-muted",children:[c.jsx("p",{children:te}),c.jsx("button",{type:"button",className:"underline",onClick:()=>void a.refetch(),children:h("ui.chat.sidebar.list.retry_refresh")})]}),z&&c.jsxs("div",{className:"pb-2",children:[bm(Nt,"agents")&&c.jsxs("section",{children:[wI("agents",h(Lx.agents),!0,void 0,yl,void 0,void 0,xI("agent")),(V||fi("agents",!0))&&c.jsxs(c.Fragment,{children:[fe.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:h("ui.chat.sidebar.agents.loading")}),_I("agent"),VC&&c.jsxs("div",{className:"relative mt-1 mb-2",children:[c.jsx("input",{ref:_e,"data-roster-filter":!0,"aria-label":h("ui.chat.sidebar.agents.filter"),placeholder:h("ui.chat.sidebar.agents.filter"),className:"h-8 w-full rounded-md bg-row-hover pe-9 ps-2 text-body-sm",value:Re,onChange:D=>ye(D.target.value),onKeyDown:D=>{if(D.key==="Escape"){D.preventDefault(),D.stopPropagation(),Re&&u1(_e.current,ye);return}if(D.key==="ArrowDown"){D.preventDefault(),D.stopPropagation(),Vl.current?.querySelector("[data-agent-pin]")?.closest("[data-entity]")?.querySelector("[data-entity-name]")?.focus();return}(D.key==="ArrowUp"||D.key==="Home"||D.key==="End")&&D.stopPropagation()}}),Re&&c.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 end-1 -translate-y-1/2 focus-visible:outline-offset-[-2px]!",onClick:()=>u1(_e.current,ye),"aria-label":h("ui.chat.sidebar.agents.clear_filter"),children:c.jsx(Xn,{"aria-hidden":"true"})})]}),!se&&c.jsxs("div",{className:R(W?"flex flex-col gap-2 px-3 py-2":"contents"),"data-testid":W?"agents-sidebar-empty":void 0,children:[c.jsx("div",{className:"contents",children:W?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:h("ui.chat.sidebar.agents.empty")}),Ae&&!he&&c.jsx(ce,{variant:"ghost",size:"icon-sm","data-testid":"agents-offer-dismiss","aria-label":h("ui.chat.sidebar.agents.dismiss_offer"),onClick:()=>{Je.current=!0,K(me)},children:c.jsx(Xn,{"aria-hidden":"true"})})]}),Se.length>0&&c.jsx("p",{className:"text-meta text-ink-muted",children:IJe(Se)})]}):VC&&Re.trim()?uI.length>0?uI.map(D=>zC("agent",D.name,D.id)):c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.agents.no_match")}):kI("agents",GC.map(D=>zC("agent",D.name,D.id)))}),c.jsx(SXe,{builtins:Se,presentation:W?"primary":"row",onBusyChange:xe})]}),c.jsxs("button",{ref:pe,type:"button",className:R(dm,"w-full text-ink-muted"),onClick:()=>s("/agents?create=agent"),children:[c.jsx(Cl,{className:"size-4"}),h("ui.chat.sidebar.agents.create")]})]})]}),bm(Nt,"teams")&&c.jsxs("section",{className:UQ(bm(Nt,"agents")&&(!!V||fi("agents",!0))),children:[wI("teams",h(Lx.teams),!0,void 0,Vm,void 0,void 0,xI("team")),(V||fi("teams",!0))&&c.jsxs(c.Fragment,{children:[Xe.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:h("ui.chat.sidebar.teams.loading")}),_I("team"),Xe.data&&kI("teams",Xe.data.map(D=>zC("team",D.name))),c.jsxs("button",{type:"button",className:R(dm,"w-full text-ink-muted"),onClick:()=>s("/agents?create=team"),children:[c.jsx(Cl,{className:"size-4"}),h("ui.chat.sidebar.teams.create")]})]})]})]})]},"entities"),DX=G?c.jsxs("p",{ref:RX,className:"pb-2 text-meta text-warning",children:[h("ui.chat.sidebar.pins.failure",{action:G.pinned?"pin":"unpin",title:Fd(G.title,"this_chat")}),G.detail?` ${G.detail}`:""," ",c.jsx("button",{type:"button",className:"underline",onClick:()=>void B(G.sessionId,G.pinned),children:h("ui.common.actions.retry")})]}):null,wb=lf&&!V.trim()&&!ue&&Le===null?c.jsx(UJe,{unused:Wne(et),total:et.length,dragArmed:_d.armedId!==null,announce:Wn,chord:Vne(gj())}):null,IX=c.jsxs("div",{"data-sidebar-region":"chats",onPointerMove:D=>{const ve=Ts.current;ve!==null&&Math.hypot(D.clientX-ve.x,D.clientY-ve.y)>an&&(Ts.current=null),WQe(Pl.current,{x:D.clientX,y:D.clientY})&&(Pl.current=null)},onPointerLeave:()=>{Ts.current=null,Pl.current=null},className:R("relative space-y-4"),children:[oI&&c.jsxs("section",{"data-chat-section":"current",children:[hf(h("ui.chat.sidebar.section.current_chat")),Ng(oI)]}),UC.length>0&&!V.trim()&&c.jsxs("section",{"data-chat-section":"drafts",children:[UC.map(D=>{const ve=D.key===un;return c.jsxs("div",{className:R(Ak,"group",!ve&&"hover:bg-row-hover",ve&&yo),children:[c.jsxs("button",{type:"button","data-chat-row":!0,"data-draft-row":D.key,"aria-label":`Open ${D.label}`,title:D.label,onClick:()=>{dn(D.key),s("/chat")},className:R(dm,"min-w-0 flex-1 text-start",ve&&yo),children:[c.jsx(Ty,{className:"size-4 shrink-0 text-ink-dim","aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.label})]}),D.pending&&c.jsx("span",{id:lj(D.key),className:"sr-only",children:oj}),c.jsx("button",{type:"button","data-draft-discard":D.key,"aria-disabled":D.pending,"aria-describedby":D.pending?lj(D.key):void 0,"aria-label":QB(D.label),title:D.pending?oj:QB(D.label),onClick:Ge=>{if(D.pending){Ge.preventDefault();return}if(ba(Ge.detail===0?null:{x:Ge.clientX,y:Ge.clientY},D.key))return;const st=[...Vl.current?.querySelectorAll("[data-draft-row]")??[]].map(bt=>bt.getAttribute("data-draft-row")??""),lt=pJe(st,D.key);tr(D.key),un===D.key?(n(void 0,!0),wa(Fe.getState().activeDraftKey)):wa(null),requestAnimationFrame(()=>{const bt=[...Vl.current?.querySelectorAll("[data-draft-row]")??[]];(bt[Math.min(Math.max(lt,0),bt.length-1)]??Vl.current?.querySelector("[data-chat-row]"))?.focus()})},className:R("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(cg,{className:"size-4","aria-hidden":"true"})})]},D.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":uf.length===0,"aria-describedby":uf.length===0?uj:void 0,"aria-label":h("ui.chat.sidebar.drafts.clear_all_label"),title:uf.length===0?cj:"Clear all drafts",onClick:D=>{if(uf.length===0){D.preventDefault();return}const ve=D.currentTarget;if(ba(D.detail===0?null:{x:D.clientX,y:D.clientY},"drafts:clear-all"))return;const Ge=[...Vl.current?.querySelectorAll("[data-chat-row]")??[]].indexOf(ve),st=uf.map(lt=>lt.key);Sn(st),un!==null&&st.includes(un)?(n(void 0,!0),wa(Fe.getState().activeDraftKey)):wa(null),requestAnimationFrame(()=>{const lt=[...Vl.current?.querySelectorAll("[data-chat-row]")??[]];lt[Math.min(Math.max(Ge,0),lt.length-1)]?.focus()})},className:R("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:h("ui.chat.sidebar.drafts.clear_all")}),uf.length===0&&c.jsx("span",{id:uj,className:"sr-only",children:cj})]})]}),wb&&et.length===0&&wb,Nt.groupBy!=="section"&&(GQ([...Hn,...lI],Nt.groupBy)??[]).map(D=>c.jsxs("section",{"data-chat-section":D.key,children:[D.label?hf(D.label):null,D.rows.map(ve=>Ng(ve))]},D.key)),E&&c.jsx("span",{className:"sr-only","aria-live":"polite","data-sidebar-pin-order-announcement":!0,children:qo}),gX&&Nt.groupBy==="section"&&Hn.length>0&&c.jsxs("section",{ref:mt,"data-chat-section":"pinned",className:"relative",children:[hf(h(Lx.pinned)),bI(Ko),Un!==null&&!He&&c.jsx("div",{ref:Zt,"aria-hidden":"true","data-session-pin-indicator":"",className:"pointer-events-none absolute start-1 end-1 h-0.5 rounded-full bg-accent"})]}),Nt.groupBy==="section"&&cI.map(D=>{const ve=df[D];return D==="running"&&ve.length===0&&Vs?c.jsxs("section",{children:[hf(h(QI[D])),c.jsx("p",{className:"px-2 text-meta text-ink-dim",children:Vs?"The daemon could not read which chats are running, so this list may be incomplete.":"Nothing running right now."})]},D):ve.length===0?null:c.jsxs("section",{"data-chat-section":D,children:[hf(h(QI[D]),D===mX?Ws:void 0),bI(ve)]},D)}),!V.trim()&&(Gl.remaining>0||hX)&&c.jsx("button",{type:"button","data-sidebar-page-more":!0,onClick:fX,className:"flex h-7 w-full items-center rounded-md px-2 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:VQ(Nt.loads,Gl.remaining>0?WQ(aI,Nt.loads,Gl.remaining):dX)}),of,af!==null&&c.jsx("span",{className:"sr-only","aria-live":"polite",children:af}),wb&&et.length>0&&wb,!d.length&&!_r.length&&!zr&&!V.trim()&&(M===null||M.total===0)&&c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.list.empty")}),gd!==null&&c.jsx("p",{className:"text-meta text-ink-muted",children:gd}),ls&&!k&&c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.list.truncated_legacy")}),o.available&&o.reported&&!o.connected&&!f&&!w&&c.jsx("p",{className:R("text-meta",d.some(D=>D.active)?"text-ink-dim":"text-warning"),children:h("ui.chat.sidebar.list.offline")})]},"chats");return c.jsxs("nav",{ref:Vl,"aria-label":h("ui.chat.sidebar.nav.chats"),"data-chat-region":"sidebar",tabIndex:-1,onFocus:CX,"data-glass-region":"sidebar",className:"relative flex h-full min-h-0 flex-col bg-surface p-2 text-ink",onKeyDown:EX,children:[le&&Ue&&c.jsx(VJe,{row:Ue,grouped:lf,onShowGroups:()=>De({...Nt,tagsEnabled:!0,groupBy:"section"}),onClose:()=>dt(null),returnFocus:Dt},Ue.session_id),c.jsxs(bZ,{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(vt,{content:"Search chats and agents",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-search":!0,"aria-label":h("ui.chat.sidebar.header.search"),onClick:()=>{Z(!0),window.requestAnimationFrame(()=>C.current?.focus())},children:c.jsx(_h,{"aria-hidden":"true"})})}),c.jsxs(xh,{open:tt,onOpenChange:ht,children:[c.jsx(vt,{content:"View options",children:c.jsx(iE,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-options":!0,"aria-label":h("ui.chat.sidebar.header.view_options"),"aria-expanded":tt,className:R(pX&&"bg-row-selected text-ink hover:bg-row-selected"),children:c.jsx(Lp,{"aria-hidden":"true"})})})}),c.jsx(Bu,{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(jJe,{view:Nt,counts:vX,tagsAvailable:le,autoTagAvailable:Qe,onView:De})})]}),c.jsxs(xh,{open:Ot,onOpenChange:Ut,children:[c.jsx(vt,{content:"New agent or team",children:c.jsx(iE,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-create":!0,"aria-label":h("ui.chat.sidebar.header.create"),"aria-expanded":Ot,children:c.jsx(qce,{"aria-hidden":"true"})})})}),c.jsxs(Bu,{align:"end",className:"w-44 p-1","data-sidebar-create-panel":!0,children:[c.jsxs("button",{type:"button","data-sidebar-create-agent":!0,onClick:()=>{Ut(!1),s("/agents?create=agent")},className:"flex h-7 w-full items-center gap-2 rounded-md px-1 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:[c.jsx(Ade,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:h("ui.chat.sidebar.header.create_agent")})]}),c.jsxs("button",{type:"button","data-sidebar-create-team":!0,onClick:()=>{Ut(!1),s("/agents?create=team")},className:"flex h-7 w-full items-center gap-2 rounded-md px-1 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:[c.jsx(Vm,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:h("ui.chat.sidebar.header.create_team")})]})]})]}),c.jsx(vt,{content:"Open agent…",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-open-agent":!0,"aria-label":h("ui.chat.sidebar.header.open_agent"),onClick:()=>{$e(),ke(mQe)},children:c.jsx(mce,{"aria-hidden":"true"})})})]}),c.jsxs("div",{className:R("relative mb-2",!ee&&"hidden"),children:[c.jsx("input",{ref:C,"aria-label":h("ui.chat.sidebar.header.search"),placeholder:h("ui.chat.sidebar.search.placeholder"),className:"h-8 w-full rounded-md bg-row-hover pe-9 ps-2 text-body-sm",value:V,onChange:D=>j(D.target.value),onBlur:()=>{V||Z(!1)}}),V&&c.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 end-1 -translate-y-1/2 focus-visible:outline-offset-[-2px]!",onClick:()=>u1(C.current,j),"aria-label":h("ui.chat.sidebar.search.clear"),children:c.jsx(Xn,{"aria-hidden":"true"})})]}),hr&&V.trim()&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(xZ,{id:dj,checked:_a,onCheckedChange:D=>hd(D===!0)}),c.jsx(dr,{htmlFor:dj,className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.search.include_archived")})]}),ya&&g&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.too_long",{max:py})}),V&&g&&!uo&&!ya&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.names_only")}),V&&uo&&nr.isError&&c.jsxs("p",{className:"pb-2 text-meta text-ink-muted",children:[h("ui.chat.sidebar.search.unavailable")," ",c.jsx(ce,{variant:"link",size:"sm",type:"button",onClick:()=>void nr.refetch(),children:h("ui.common.actions.retry")})]}),V.trim()&&z&&!_r.length&&Ig&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.no_match",{query:V.trim()})}),vI&&VB(mI?.rows.length??0,_r.length)&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.searching")}),c.jsx("p",{"aria-live":"polite",className:"sr-only",children:vI&&VB(mI?.rows.length??0,_r.length)?"Searching conversations.":V.trim()&&z&&!_r.length&&Ig?`Nothing in your chats matches ${V.trim()}.`:""}),c.jsxs("div",{ref:TX,id:TZe,tabIndex:-1,"data-sidebar-region":"scroller","data-tag-drag-list":"","data-lo-sidebar-edge-cues":!0,onScroll:()=>{rj(ff.current,RI),rj(wn.current,AI),zc()},className:"relative min-h-0 flex-1 space-y-4 overflow-y-auto p-1 [overflow-anchor:none] [scrollbar-gutter:stable]",children:[FX,DX,AX&&IX]}),(f||fe.error||Xe.error)&&!w&&!S&&c.jsxs("div",{className:"pt-2 text-meta text-ink-muted",children:[c.jsx("p",{children:f||fe.error?.message||Xe.error?.message}),c.jsx("button",{type:"button",className:"mt-1 underline",onClick:()=>{Cs(),fe.refetch(),Xe.refetch()},children:h("ui.chat.sidebar.list.retry_refresh")})]})]})]})}const Fx={recent:()=>h("ui.canvas.files.recent"),name:()=>h("ui.canvas.files.name"),kind:()=>h("ui.canvas.files.kind"),modified:()=>h("ui.canvas.files.modified"),created:()=>h("ui.canvas.files.created"),size:()=>h("ui.canvas.files.size")},OZe={Highlights:()=>h("ui.canvas.files.highlights"),"Working files":()=>h("ui.canvas.files.working"),Images:()=>h("ui.canvas.files.images"),Videos:()=>h("ui.canvas.files.videos"),Sounds:()=>h("ui.canvas.files.audio"),Documents:()=>h("ui.canvas.files.documents"),Spreadsheets:()=>h("ui.canvas.files.spreadsheets"),Other:()=>h("ui.canvas.files.other"),Files:()=>h("ui.canvas.files.files"),Attachments:()=>h("ui.canvas.files.attachments")},Fk=e=>{switch(e){case"images":return h("ui.canvas.files.images");case"video":return h("ui.canvas.files.videos");case"documents":return h("ui.canvas.files.documents");case"spreadsheets":return h("ui.canvas.files.spreadsheets");case"audio":return h("ui.canvas.files.audio");case"code":return h("ui.canvas.files.code");case"presentations":return h("ui.canvas.files.presentations");case"archives":return h("ui.canvas.files.archives");default:return h("ui.canvas.files.other")}},LZe=/[/\\]/,BZe=300;function jZe(e){try{return e.matches(":focus-visible")}catch{return!1}}const bj="pointer-events-none absolute top-1 end-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",HZe={items:[],complete:!0,state:"ready",capable:!1,retry:()=>{}};function UZe({conversationId:e,items:t,index:n,cwd:s,onOpen:r,materialise:i,legacyScan:a,attachments:o=HZe}){const l=Ve(),u=Fs(le=>le.conversations[e]?.selectedTabId),[d,f]=m.useState(t),[p,g]=m.useState(!1),v=nt(le=>le.finderFiles),b=nt(le=>le.setFinderFiles),[x,_]=m.useState(""),w=m.useMemo(()=>new Set(v.closedSections),[v.closedSections]),[y,S]=m.useState(null),C=m.useRef(!1),[E,k]=m.useState({width:400,height:700,top:0}),F=m.useRef(null),A=m.useRef(null),I=m.useRef(new Map),N=m.useRef(new Map),[P,M]=m.useState(null),Y=m.useRef(null),[O,X]=m.useState(!1),Q=m.useRef(0),ie=m.useRef(null),G=m.useRef(!1);m.useEffect(()=>{if(!O||o.state==="loading")return;const le=window.setTimeout(()=>X(!1),Math.max(0,BZe-(Date.now()-Q.current)));return()=>window.clearTimeout(le)},[O,o.state]),m.useEffect(()=>{O||!G.current||o.state!=="loading"&&(G.current=!1,o.state==="error"&&ie.current?.focus({preventScroll:!0}))},[O,o.state]),m.useEffect(()=>{n.localReadAllowed===!1?(f([]),M(null)):(!p||d.length===0)&&P===null&&f(t)},[t,p,P,n.localReadAllowed,d.length]);const[ne,oe]=m.useState(),[B,H]=m.useState(!1),U=m.useRef({text:"",at:0}),z=n.localReadAllowed===!1?[]:d,te=!!(x.trim()||v.kinds.length),fe=m.useMemo(()=>{const le=new Set(cL(z.map(Qe=>Qe.row),{query:x,kinds:v.kinds}).map(Qe=>Qe.document.id));return eJ(z.filter(Qe=>le.has(Qe.row.document.id)),v)},[z,x,v]),J=m.useMemo(()=>{if(n.localReadAllowed===!1&&!o.items.length)return[];const le=new Set(cL(o.items.map(Qe=>Qe.row),{query:x,kinds:v.kinds}).map(Qe=>Qe.document.id));return o.items.filter(Qe=>le.has(Qe.row.document.id))},[o.items,x,v.kinds,n.localReadAllowed]),Se=m.useMemo(()=>tJ(fe,v,te,w,J),[fe,v,te,w,l,J]),W=m.useMemo(()=>nJ(Se,E.width,v.group),[Se,E.width,v.group]);m.useEffect(()=>{C.current&&y&&W.positions.has(y)&&document.activeElement===document.body&&I.current.get(y)?.focus({preventScroll:!0})},[W,y]);const Ce=W.bands.find(le=>le.items.length)?.items[0]?.row.document.id??null,K=y?.startsWith("header:")||y&&W.positions.has(y)?y:W.bands.find(le=>le.items.length)?.items[0]?.row.document.id??(Se[0]?`header:${Se[0].id}`:null),me=m.useMemo(()=>new Set(sJ(W,E.top,E.height,K)),[W,E.top,E.height,K]),Ee=m.useMemo(()=>[...J,...fe].filter(le=>le.row.media==="image"&&W.positions.has(le.row.document.id)),[fe,J,W]),Ae=Ee.find(le=>le.row.document.id===P);m.useEffect(()=>{if(!Ae){oe(void 0),H(!1);return}let le=!0,Qe;return oe(void 0),pE(Ae.row.document).then(async et=>{le&&(Qe=y8(await et.arrayBuffer(),et.type),le?oe(Qe):I_(Qe))}).catch(()=>{le&&(oe(void 0),H(!0))}),()=>{le=!1,Qe&&I_(Qe)}},[Ae]),m.useEffect(()=>{const le=F.current;if(!le)return;const Qe=()=>k(ue=>({...ue,width:le.clientWidth,height:le.clientHeight}));Qe();const et=new ResizeObserver(Qe);return et.observe(le),()=>et.disconnect()},[]);const se=m.useCallback(le=>{const Qe=W.positions.get(le),et=F.current;if(!Qe||!et)return;const ue=W.bands[Qe.band];ue.top<et.scrollTop?et.scrollTop=Math.max(0,ue.top-Eb-rJ):ue.top+ue.height>et.scrollTop+et.clientHeight&&(et.scrollTop=ue.top+ue.height-et.clientHeight),S(le),k(Le=>({...Le,top:et.scrollTop})),requestAnimationFrame(()=>I.current.get(le)?.focus())},[W]),he=(le,Qe)=>{if(le.target===le.currentTarget){if(le.key==="Escape"&&(x||v.kinds.length)){le.preventDefault(),le.stopPropagation(),_(""),b({kinds:[]});return}if(le.key==="/"){le.preventDefault(),A.current?.focus();return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(le.key)){le.preventDefault();const et=W.positions.get(Qe.row.document.id);if(et&&["ArrowUp","ArrowDown"].includes(le.key)){const Le=W.bands[et.band+(le.key==="ArrowUp"?-1:1)];if(Le?.kind==="header"){le.preventDefault(),S(`header:${Le.section.id}`),N.current.get(Le.section.id)?.focus();return}}const ue=oJ(W,Qe.row.document.id,le.key,E.height);ue&&se(ue);return}if(le.key.length===1&&!le.ctrlKey&&!le.metaKey&&le.key!==" "){const et=Date.now(),ue=(et-U.current.at<500?U.current.text:"")+le.key.toLocaleLowerCase();U.current={text:ue,at:et};const Le=fe.findIndex(Ne=>Ne.row.document.id===Qe.row.document.id);for(let Ne=1;Ne<=fe.length;Ne++){const Ue=fe[(Le+Ne)%fe.length];if(W.positions.has(Ue.row.document.id)&&ep(Ue.row.name).startsWith(ep(ue))){le.preventDefault(),se(Ue.row.document.id);break}}}}},xe=le=>{if(le==="Working files"){te||b({workingOpen:!v.workingOpen});return}if(te)return;const Qe=new Set(w);Qe.has(le)?Qe.delete(le):Qe.add(le),b({closedSections:[...Qe]})},Je=()=>{_(""),b({kinds:[]}),A.current?.focus()},pe=m.useRef(null);m.useEffect(()=>()=>{pe.current!==null&&cancelAnimationFrame(pe.current)},[]);const Xe=()=>{pe.current===null&&(pe.current=requestAnimationFrame(()=>{pe.current=null;const le=F.current;le&&k(Qe=>({...Qe,top:le.scrollTop}))}))};return c.jsxs("div",{onKeyDownCapture:le=>{const Qe=le.target;le.key==="/"&&!le.ctrlKey&&!le.metaKey&&Qe instanceof HTMLElement&&!Qe.closest("input,textarea,[contenteditable=true]")&&(le.preventDefault(),le.stopPropagation(),A.current?.focus())},className:R("@container/fileslist flex min-h-0 flex-1 flex-col"),children:[c.jsxs("div",{className:R("shrink-0 space-y-1 px-2 py-2"),"data-tour-tag":"files-scanner-head",children:[c.jsxs("div",{className:R("flex items-center gap-2"),children:[c.jsx(bs,{ref:A,value:x,placeholder:h("ui.canvas.finder_files_view.ui_canvas_files_searchplaceholder"),"aria-label":h("ui.canvas.files.search"),className:R("min-w-0 flex-1"),onChange:le=>_(le.target.value),onKeyDown:le=>{le.key==="ArrowDown"||le.key==="Escape"&&!x&&!v.kinds.length?(le.preventDefault(),le.stopPropagation(),Ce&&se(Ce)):le.key==="Escape"&&(le.preventDefault(),le.stopPropagation(),_(""),b({kinds:[]}))}}),c.jsxs(Po,{children:[c.jsx(eo,{asChild:!0,children:c.jsxs(ce,{variant:"outline",size:"md","aria-label":`${h("ui.canvas.files.sort")}: ${Fx[v.sort]()}, ${v.order==="asc"?h("ui.canvas.files.asc"):h("ui.canvas.files.desc")}`,children:[c.jsx(uce,{"aria-hidden":"true"}),c.jsx("span",{className:"hidden @min-[440px]/fileslist:inline",children:Fx[v.sort]()}),c.jsx("span",{"aria-hidden":"true",children:v.order==="asc"?"↑":"↓"})]})}),c.jsxs(Mo,{align:"end",children:[Object.keys(Fx).map(le=>c.jsx(Ug,{checked:v.sort===le,onCheckedChange:()=>b({sort:le,order:["modified","created","size"].includes(le)?"desc":"asc"}),children:Fx[le]()},le)),c.jsx(Nr,{}),c.jsx(Ug,{checked:v.order==="asc",onCheckedChange:()=>b({order:"asc"}),children:h("ui.canvas.files.asc")}),c.jsx(Ug,{checked:v.order==="desc",onCheckedChange:()=>b({order:"desc"}),children:h("ui.canvas.files.desc")}),c.jsx(Nr,{}),c.jsx(Ug,{checked:v.group,onCheckedChange:le=>b({group:le}),children:h("ui.canvas.files.group")})]})]}),c.jsxs(Po,{children:[c.jsx(eo,{asChild:!0,children:c.jsxs(ce,{variant:"outline",size:"md",className:R(v.kinds.length>0&&"bg-accent-wash"),"aria-label":`${h("ui.canvas.files.filter")}: ${v.kinds.map(Fk).join(", ")||h("ui.canvas.files.files")}`,children:[c.jsx(Yce,{"aria-hidden":"true"}),v.kinds.length?`${v.kinds.length}`:h("ui.canvas.files.filter")]})}),c.jsxs(Mo,{align:"end",children:[Gwe.map(le=>c.jsx(Ug,{checked:v.kinds.includes(le.id),onCheckedChange:Qe=>b({kinds:Qe?[...v.kinds,le.id]:v.kinds.filter(et=>et!==le.id)}),children:Fk(le.id)},le.id)),c.jsx(Nr,{}),c.jsx(Jt,{onSelect:()=>b({kinds:[]}),children:h("ui.canvas.files.reset")})]})]})]}),c.jsxs("div",{className:R("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?"":te?h("ui.canvas.files.narrowCount",{shown:Bd(fe.length+J.length),total:Bd(t.length+o.items.length)}):o.state==="loading"&&!t.length&&!O?h("ui.canvas.files.loading"):h("ui.canvas.files.count",{count:t.length+o.items.length}),n.mode==="index"&&(n.state==="loading"||n.state==="building")&&n.pendingTotal>0?`${t.length?" · ":""}${h("ui.canvas.files.progress",{loaded:Bd(n.loadedRows),total:Bd(n.pendingTotal)})}`:"",n.state==="loading"&&t.length>0?` · ${h("ui.canvas.files.loading")}`:n.state==="building"?` · ${h("ui.canvas.files.building")}`:n.statComplete?"":` · ${h("ui.canvas.files.readingStats")}`]}),s&&c.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>void rse(s),children:[c.jsx(ky,{"aria-hidden":"true"}),h("ui.canvas.files.folder")]})]}),v.kinds.length>0&&c.jsxs("div",{className:R("flex items-center gap-2 text-meta text-ink-muted"),children:[c.jsx("span",{children:v.kinds.map(Fk).join(", ")}),c.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>b({kinds:[]}),children:[c.jsx(Xn,{"aria-hidden":"true"}),h("ui.canvas.files.reset")]})]}),o.state==="error"&&!O?c.jsxs("output",{title:h("ui.canvas.files.attachmentsErrorReason"),className:R("text-body-sm text-ink-muted"),children:[h("ui.canvas.files.attachmentsError"),c.jsx(ce,{ref:ie,variant:"ghost",size:"sm",onClick:le=>{G.current=document.activeElement===le.currentTarget,Q.current=Date.now(),X(!0),o.retry()},children:h("ui.canvas.files.retry")})]}):O?c.jsx("output",{className:R("text-body-sm text-ink-dim"),children:h("ui.canvas.files.loading")}):null,n.error&&fe.length>0&&c.jsxs("output",{className:R("text-body-sm text-ink-muted"),children:[n.error,c.jsx(ce,{variant:"ghost",size:"sm",onClick:n.refresh,children:n.state==="building"?h("ui.canvas.files.continue"):h("ui.canvas.files.retry")})]})]}),c.jsx("section",{ref:F,"aria-label":h("ui.canvas.files.region"),"data-tour-tag":"files-scroller","data-glass-plane":"clear",className:R("min-h-0 flex-1 overflow-auto bg-surface px-2 pb-2"),onScroll:Xe,onKeyDown:le=>{!le.defaultPrevented&&le.key==="Escape"&&(x||v.kinds.length)&&(le.preventDefault(),le.stopPropagation(),_(""),b({kinds:[]}))},onPointerEnter:()=>g(!0),onPointerLeave:()=>{F.current?.contains(document.activeElement)||g(!1)},onFocusCapture:()=>{C.current=!0,g(!0)},onBlurCapture:le=>{le.relatedTarget&&!le.currentTarget.contains(le.relatedTarget)&&(C.current=!1,g(!1))},children:!fe.length&&!J.length?c.jsxs("div",{className:R("flex min-h-40 flex-col items-center justify-center gap-2 p-4 text-center"),children:[c.jsx("p",{className:R("text-heading text-ink"),children:n.state==="error"?n.error??h("ui.canvas.files.error"):n.state==="unsupported"?n.error??h("ui.canvas.files.remote"):n.state==="loading"||o.state==="loading"?h("ui.canvas.files.loading"):n.state==="building"?h("ui.canvas.files.building"):te?h("ui.canvas.files.noMatch"):h("ui.canvas.files.empty")}),n.state==="ready"&&o.state!=="loading"&&!te&&c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.files.emptyDetail")}),n.error&&c.jsx(ce,{variant:"outline",size:"sm",onClick:n.refresh,children:n.state==="building"?h("ui.canvas.files.continue"):h("ui.canvas.files.retry")}),te&&c.jsx(ce,{variant:"outline",size:"sm",onClick:Je,children:h("ui.canvas.files.clear")})]}):Se.map(le=>{const Qe=W.bands.map((Ne,Ue)=>Ne.section.id===le.id?Ue:-1).filter(Ne=>Ne>=0),et=W.bands[Qe[0]],ue=W.bands[Qe.at(-1)??0],Le=ue.top+ue.height-et.top-Eb;return c.jsxs("section",{style:{height:Le+Eb},children:[c.jsx("h3",{"data-glass-plane":"band-backdrop",className:R("sticky top-0 z-10 h-8 bg-surface"),children:c.jsxs("button",{type:"button",ref:Ne=>{Ne?N.current.set(le.id,Ne):N.current.delete(le.id)},tabIndex:K===`header:${le.id}`?0:-1,onFocus:()=>S(`header:${le.id}`),onKeyDown:Ne=>{if(Ne.key==="ArrowRight"&&!le.open||Ne.key==="ArrowLeft"&&le.open)Ne.preventDefault(),xe(le.id);else if(Ne.key==="ArrowDown"||Ne.key==="ArrowUp")if(Ne.preventDefault(),Ne.key==="ArrowDown"&&le.open&&le.items.length)se(le.items[0].row.document.id);else{const Ue=Se[Se.indexOf(le)+(Ne.key==="ArrowDown"?1:-1)];Ue&&(S(`header:${Ue.id}`),N.current.get(Ue.id)?.focus())}},"aria-expanded":le.open,"aria-disabled":te,onClick:()=>xe(le.id),className:R("flex h-8 w-full items-center gap-2 rounded-sm px-2 text-start font-medium text-body-sm text-ink hover:bg-row-hover",te&&"cursor-default hover:bg-surface",le.id!=="Working files"&&!le.highlights&&Se.some(Ne=>Ne.id==="Working files")&&"ps-4"),children:[le.open?c.jsx(Ei,{size:14,"aria-hidden":"true"}):c.jsx(Vi,{size:14,"aria-hidden":"true",className:"rtl:-scale-x-100"}),OZe[le.id]?.()??le.label,c.jsx("span",{className:R("text-meta text-ink-muted"),children:Bd(le.items.length||(le.id==="Working files"?fe.filter(Ne=>!Ne.highlighted).length:0))}),le.id===iJ&&(o.state==="loading"?O?null:c.jsx("span",{className:R("text-meta text-ink-dim"),children:h("ui.canvas.files.loading")}):o.state==="ready"&&!o.complete?c.jsx("span",{title:h("ui.canvas.files.attachmentsPartialReason"),className:R("text-meta text-ink-dim"),children:h("ui.canvas.files.attachmentsPartial")}):null)]})}),c.jsx("ul",{"data-tour-tag":"files-grid",className:R("relative"),style:{height:Le},children:Qe.filter(Ne=>W.bands[Ne].kind!=="header"&&me.has(Ne)).map(Ne=>{const Ue=W.bands[Ne];return c.jsx("li",{style:{position:"absolute",top:Ue.top-et.top-Eb,height:Ue.height,left:0,right:0},children:c.jsx("div",{className:R("grid gap-1"),style:{gridTemplateColumns:`repeat(${Ue.cols},minmax(0,1fr))`},children:Ue.items.map(dt=>c.jsx(GZe,{item:dt,current:u===dt.row.document.id||u===dt.row.document.path,band:Ue,tabIndex:dt.row.document.id===K?0:-1,onFocus:()=>S(dt.row.document.id),buttonRef:St=>{St?I.current.set(dt.row.document.id,St):I.current.delete(dt.row.document.id)},onKeyDown:St=>he(St,dt),onOpen:()=>r(dt.row.document),onExpand:()=>{Y.current=I.current.get(dt.row.document.id)??null,M(dt.row.document.id)},materialise:dt.attachment&&!C8(o.capable,dt.attachment.materialisable)?void 0:()=>i(dt.row.document)},dt.row.document.id))})},Ue.items[0].row.document.id)})})]},le.id)})}),n.mode==="fallback"&&a?.stopped&&c.jsx(ce,{variant:"ghost",size:"sm",onClick:a.resume,children:h("ui.canvas.files.earlier")}),Ae&&c.jsx(ise,{open:!0,src:ne,pending:!ne&&!B,fallback:c.jsx("span",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.files.unreadable")}),label:Ae.row.name,onOpenChange:le=>{le||M(null)},restoreFocusTo:Y,group:{index:Ee.indexOf(Ae),count:Ee.length,onPrev:()=>M(Ee[(Ee.indexOf(Ae)+Ee.length-1)%Ee.length].row.document.id),onNext:()=>M(Ee[(Ee.indexOf(Ae)+1)%Ee.length].row.document.id)}})]})}function GZe({item:e,current:t,band:n,tabIndex:s,onFocus:r,buttonRef:i,onKeyDown:a,onOpen:o,onExpand:l,materialise:u}){Ve();const d=e.row.document,f=e.attachment?.materialisable===!1,p=e.attachment?.materialisable==="pending",g=f||p,[v,b]=ase("200px"),x=ose(d,b&&e.row.media==="image"&&!e.row.missing),[_,w]=m.useState(!1),y=m.useRef(null),S=n.kind==="tiles"||n.kind==="video",C=S?aJ(n):n.kind==="highlight"?40:28,E=d.artifact?e.attachment?h("ui.canvas.files.attachmentTooltip",{name:d.title,digest:d.artifact.digest.slice(0,J5)}):S8({...d.artifact,title:d.title}):d.path,k=Ywe(E,e.attachment?.status,f),[F,A]=m.useState(!1),I=f&&F?h("ui.canvas.files.attachmentRefused"):null,N=!!(e.attachment?.status||I),P=()=>{f&&!ie?da(h("ui.canvas.files.attachmentRefused")):ie&&w(!0)},M=!(e.attachment&&e.row.missing&&!LZe.test(d.path)||g&&!d.artifact),Y=lg(d.path,d.type)===null||g?void 0:o,O=d.artifact&&!e.attachment?PA(d.artifact):void 0,X=d.artifact&&!e.row.missing?u:void 0,Q=e.row.missing&&!d.artifact,ie=M&&lse({file:d.path,resolvePath:X,missing:Q,onShowInCanvas:Y,mediaKind:n.kind==="audio"?"audio":e.row.media==="image"?"image":"video",onExpand:n.kind!=="audio"&&e.row.media==="image"?l:void 0,saveName:O}).length>0,G=nt(H=>H.finderFiles.sort),ne=G==="created"?e.created:e.modified,oe=ne===null?"":EA(ne*1e3,{month:"short",day:"numeric"}),B=e.attachment?e.attachment.note:e.row.missing?d.artifact?h("ui.canvas.files.gone"):h("ui.canvas.files.missing"):G==="modified"||G==="created"?oe:G==="size"?e.row.size??"":d.artifact?h("ui.canvas.files.sessionOnly"):e.row.size??"";return n.kind==="audio"?c.jsxs("div",{ref:v,className:R("group relative min-w-0 rounded-sm px-1 py-0.5",t?yo:"hover:bg-row-hover"),"data-tour-tag":"file-row","data-file-id":d.id,onContextMenu:H=>{H.preventDefault(),w(!0)},children:[c.jsxs("div",{className:R("flex min-w-0 items-center gap-2 pe-8"),children:[c.jsx("button",{type:"button",ref:H=>{y.current=H,i(H)},tabIndex:s,onFocus:r,title:k,onClick:o,onKeyDown:H=>{H.shiftKey&&H.key==="F10"||H.key==="ContextMenu"?(H.preventDefault(),P()):a(H)},className:R("min-w-0 flex-1 truncate rounded-sm py-1 text-start text-body-sm",e.row.missing?"text-ink-muted":"text-ink"),children:e.row.name}),c.jsx("span",{title:ne===null?void 0:lE(ne*1e3),className:R("shrink-0 text-meta text-ink-dim"),children:B})]}),c.jsx(X9,{doc:d,label:e.row.name}),c.jsx("div",{className:bj,onKeyDown:H=>H.stopPropagation(),children:c.jsx(L0,{file:d.path,tooltip:h("ui.canvas.finder_files_view.ui_canvas_files_fileactions"),label:d.title,open:_,onOpenChange:w,onCloseAutoFocus:H=>{H.preventDefault(),y.current?.focus({preventScroll:!0})},triggerTabIndex:-1,mediaKind:"audio",onShowInCanvas:Y,resolveBytes:()=>pE(d),saveName:O,resolvePath:X,missing:Q})})]}):c.jsxs("div",{ref:v,className:R("group relative min-w-0 rounded-sm",t?yo:"hover:bg-row-hover"),"data-tour-tag":"file-row","data-file-id":d.id,onContextMenu:H=>{H.preventDefault(),w(!0)},children:[c.jsxs("button",{type:"button",ref:H=>{y.current=H,i(H)},tabIndex:s,onFocus:H=>{f&&A(jZe(H.currentTarget)),r()},onBlur:()=>A(!1),title:k,onClick:S&&e.row.media==="image"?l:o,onKeyDown:H=>{H.shiftKey&&H.key==="F10"||H.key==="ContextMenu"?(H.preventDefault(),P()):a(H)},className:R("w-full min-w-0 rounded-sm p-1 text-start",!S&&"flex items-center gap-2 pe-8",e.row.missing&&"text-ink-muted"),style:{height:n.height-(S?4:0)},children:[c.jsx("span",{style:{height:C,width:S?"100%":C},className:R("flex shrink-0 items-center justify-center overflow-hidden rounded-sm bg-media-surface",S&&"mb-1"),children:x.state==="ready"&&e.row.media==="image"?c.jsx("img",{src:x.url,alt:"",className:R("h-full w-full object-contain outline-1 -outline-offset-1 outline-hairline")}):d.type==="video"?c.jsxs("span",{className:R("flex flex-col items-center gap-1 text-ink-muted"),children:[c.jsx(cse,{"aria-hidden":"true"}),S&&c.jsx("span",{className:R("text-meta"),children:h("ui.canvas.files.play")})]}):x.state==="loading"&&e.row.media==="image"&&!e.row.missing?null:c.jsx(Ey,{size:16,"aria-hidden":"true"})}),c.jsxs("span",{className:R("flex min-w-0 flex-1 flex-col",S?"text-meta":"text-body-sm"),children:[c.jsxs("span",{className:R("flex min-w-0 gap-2",S&&e.attachment?"flex-col gap-0":"items-center justify-between"),children:[c.jsx("span",{className:R("min-w-0 truncate",!S&&N?"min-w-[min(6rem,50%)] shrink":"flex-1",e.row.missing?"text-ink-muted":"text-ink"),children:e.row.name}),!S&&e.row.showParent&&e.row.parent&&c.jsx("span",{className:R("min-w-0 shrink truncate text-mono-sm text-ink-dim"),children:e.row.parent}),c.jsx("span",{title:ne===null||N?void 0:lE(ne*1e3),className:R("text-meta text-ink-dim",S&&e.attachment?"min-w-0 truncate":N?"min-w-[min(13rem,50%)] flex-1 truncate text-end":"shrink-0"),children:I?c.jsx("bdi",{children:I}):e.attachment&&!e.attachment.status?c.jsxs(c.Fragment,{children:[c.jsx("bdi",{children:e.attachment.size}),e.attachment.size&&e.attachment.when?c.jsx("span",{"aria-hidden":"true",children:" · "}):null,c.jsx("bdi",{children:e.attachment.when})]}):S&&d.artifact&&!e.attachment?h("ui.canvas.files.inSession"):c.jsx("bdi",{children:S&&e.attachment?e.attachment.tileStatus:B})})]}),n.kind==="highlight"&&e.why&&c.jsx("span",{className:R("line-clamp-2 text-meta text-ink-muted"),children:e.why})]})]}),c.jsxs("div",{className:bj,onKeyDown:H=>H.stopPropagation(),children:[S&&e.row.media==="image"&&c.jsx(vt,{content:`${h("ui.canvas.files.expand")}: ${d.title}`,children:c.jsx(ce,{variant:"ghost",size:"icon-sm",tabIndex:-1,className:R("bg-accent-wash"),"aria-label":`${h("ui.canvas.files.expand")}: ${d.title}`,onClick:l,children:c.jsx(use,{"aria-hidden":"true"})})}),M&&c.jsx(L0,{file:d.path,tooltip:e.row.media==="image"?h("ui.canvas.finder_files_view.ui_canvas_files_imageactions"):h("ui.canvas.finder_files_view.ui_canvas_files_fileactions"),label:d.title,open:_,onOpenChange:w,onCloseAutoFocus:H=>{H.preventDefault(),y.current?.focus({preventScroll:!0})},triggerTabIndex:-1,mediaKind:e.row.media==="image"?"image":"video",onShowInCanvas:Y,onExpand:e.row.media==="image"?l:void 0,resolveBytes:()=>pE(d),saveName:O,resolvePath:X,missing:Q})]})]})}const xj=[],VZe=({conversationId:e,sessionId:t,cwd:n,index:s,onSwitchToDocumentView:r,scan:i=null,attachments:a=null})=>{const o=Fs(k=>k.conversations[e]?.mentionedFiles??xj),l=m.useMemo(()=>s.mode==="index"?s.rows.map(k=>ywe(k,t??"")):s.mode==="fallback"?o:xj,[s.mode,s.rows,o,t]),u=Fs(k=>k.setFiles),d=Fs(k=>k.setOpenTabs),f=Fs(k=>k.setSelectedTab),p=Fs(k=>k.setViewMode),g=m.useMemo(()=>t9(l),[l]),v=m.useCallback(async k=>{const F=k.title,A=Q=>{const G=Fs.getState().conversations?.[e],ne=G?.files??[],oe=G?.openTabs??[],B=ne.findIndex(te=>te.id===Q.id),H=B!==-1?[...ne.slice(0,B),Q,...ne.slice(B+1)]:[...ne,Q];u(e,H);const z=oe.some(te=>te.id===Q.id)?oe:[...oe,{id:Q.id,title:Q.title}];d(e,z),f(e,Q.id),p(e,"documents"),r(Q.id)},I=Q=>{Q&&console.error("Error processing file:",Q);try{k.path.startsWith("data:")?console.warn("Opening data URI with OS default is not directly supported here.",`${k.path.substring(0,50)}...`):window.api.openFile(k.path)}catch(ie){console.error("Error opening file natively:",ie)}},N=lg(k.path,k.type);if(k.artifact){A({...k,content:""});return}if(k.path.startsWith("data:")){if(N===null)return I();A(So(k.path,{title:F,content:k.path,type:Gu(F)}));return}const P=e8(k.path),M=typeof window.api?.probeFiles=="function"?(await window.api.probeFiles([P]))[0]??null:null,Y=!!(M?.exists&&M.isFile);if(k.availability==="missing"&&!Y&&M?.error===void 0){nn(h("ui.canvas.file_viewer.file_no_longer_exists_at",{value:M?.resolved??P}),{description:h(k.id.startsWith(e_)?"ui.canvas.files.attachmentGoneRecovery":"ui.canvas.file_viewer.copy_its_path_from_the_row_s_menu_to_look_for_it_or_check_whether_the_ag")});return}if(N===null)return I();const O={title:F,type:Gu(P),lastAgentModified:M?.mtimeMs??k.lastAgentModified,readMtimeMs:M?.mtimeMs??void 0,availability:Y?"present":void 0,sizeBytes:M?.sizeBytes??k.sizeBytes},X=Ny[N];if(X==="bytes"||X==="range"){A(So(P,O));return}try{const Q=await window.api.readFile(P,X);if(!Q.success){const ie=Q.error?Q.error instanceof Error?Q.error.message:String(Q.error):h("ui.canvas.file_viewer.unknown_error_reading_file");return I(ie)}A(So(P,{...O,content:Q.data}))}catch(Q){const ie=Q instanceof Error?Q.message:String(Q??h("ui.canvas.file_viewer.unknown_error_reading_file"));return I(ie)}},[e,u,d,f,p,r]),b=m.useMemo(()=>Qwe(a?.items??[],t??""),[a?.items,t]),x=m.useMemo(()=>dse({items:a?.items??[]}),[a?.items]),_=g.map((k,F)=>{const A=s.mode==="index"?s.rows[F]:void 0;return{row:k,highlighted:A?.highlighted??!1,why:A?.highlight_why??"",created:A?.created_at??null,modified:A?.modified_at??(k.document.lastAgentModified===void 0?null:k.document.lastAgentModified/1e3),mentioned:A?.first_ts??A?.first_seq??F}}),w=Jwe(_,k=>k.row.artifact?.digest,x),y=a?.capable??!1,S=m.useMemo(()=>new Set(b.filter(k=>k.attachment?.materialisable===!1||k.attachment?.materialisable==="pending").map(k=>k.row.document.id)),[b]),C=k=>C8(y,S.has(k.id)?!1:null),E=async k=>{if(k.id.startsWith(e_)&&k.artifact){if(!C(k))throw new Error("Backend cannot materialise this attachment");if(!t)throw new Error("No session for the attachment");return hse(t,k.artifact.digest)}if(!t||s.mode!=="index")throw new Error("No indexed artifact owner");const F=await m5({op:"sessions.files.materialise",sessionId:t,fileId:k.indexedFileId??k.id}),A=F.body.result;if(F.status!==200||!A?.path)throw new Error(h("ui.canvas.files.saveError"));return A.path};return c.jsx(UZe,{items:w,conversationId:e,index:s.mode==="fallback"?{...s,state:"ready"}:s,legacyScan:i,cwd:s.state==="unsupported"?void 0:n,materialise:E,attachments:{items:b,complete:(a?.complete??!0)&&!a?.truncated,state:a?.state??"ready",capable:y,retry:a?.retry??(()=>{})},onOpen:k=>{S.has(k.id)&&!k.artifact||(k.artifact&&(C(k)||!k.id.startsWith(e_))&&k.type!=="image"&&k.type!=="video"&&k.type!=="audio"?E(k).then(F=>v(So(F,{title:k.title,type:k.type}))).catch(()=>nn(h("ui.canvas.file_viewer.ui_canvas_files_saveerror"))):v(k))}})},WZe=m.memo(VZe),$Ze=({entries:e,truncated:t,goalPresent:n})=>(Ve(),e.length===0&&!t?c.jsx(PR,{title:h("ui.canvas.goals_viewer.no_goals_completed_yet"),description:n?h("ui.canvas.goals_viewer.goals_appear_here_once_they_are_finished"):h("ui.canvas.goals_viewer.no_goal_set_goal_text_to_set_one_finished_goals_are_kept_here")}):c.jsxs("section",{className:R("flex min-h-0 flex-1 flex-col overflow-y-auto"),children:[c.jsxs("div",{className:R("flex items-baseline justify-between gap-2 px-3 pt-2 pb-1"),children:[c.jsx("span",{className:R("shrink-0 text-meta text-ink-muted"),children:h("ui.canvas.goals_viewer.goals")}),c.jsx("span",{className:R("min-w-0 flex-1 truncate text-right text-meta text-ink-dim"),children:t?h("ui.canvas.goals_viewer.count_shown",{count:e.length}):h("ui.canvas.goals_viewer.count",{count:e.length})})]}),t&&c.jsx("p",{className:R("max-w-80 px-3 pb-1 text-meta text-ink-dim"),children:h("ui.canvas.goals_viewer.older_settled_goals_are_not_carried_here_this_list_is_capped")}),c.jsx("ul",{className:R("flex flex-col pb-1.5"),children:e.map(s=>c.jsx(zZe,{entry:s},s.id))})]})),zZe=({entry:e})=>{const t=e.status==="done",n=t?xA:c2,s=qZe(e),r=!!(e.reason?.trim()||e.settled_at);return c.jsx("li",{className:R("flex flex-col"),children:c.jsx(Uh,{disabled:!r,rowClassName:R("h-6 rounded-sm px-3 py-0"),summaryAlign:"center",triggerLabel:`${e.text} — ${s}`,triggerTooltip:e.text,summary:c.jsxs("span",{className:R("flex min-w-0 flex-1 items-center gap-2"),children:[c.jsx("span",{"aria-hidden":!0,className:R("flex size-4 shrink-0 items-center justify-center text-ink-dim"),children:c.jsx(n,{className:R("size-4")})}),c.jsx("span",{className:R("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:R("shrink-0 text-meta text-ink-dim"),title:s,children:s})]}),children:c.jsxs("div",{className:R("flex flex-col gap-1 px-3 pb-1.5"),children:[e.reason?.trim()&&c.jsx("span",{"aria-hidden":!0,className:R("line-clamp-2 text-ink-muted text-meta leading-4"),title:e.reason,children:e.reason}),e.reason?.trim()&&c.jsx("span",{className:R("sr-only"),children:e.reason}),e.settled_at&&c.jsx("span",{className:R("text-mono text-2xs text-ink-dim"),children:e.settled_at})]})})})},qZe=(e,t=new Date)=>{const n=fse(e.settled_at,t);return n?`${e.status} · ${n}`:e.status};function FD(e,t){const n=e.findIndex(s=>s.id===t);return n===-1?null:e[n+1]??e[n-1]??null}const PK="canvas-selected-tab",MK="canvas-document-panel",KZe=({documents:e,activeDocumentId:t,onChangeActiveDocument:n,onCloseDocument:s})=>{Ve();const r=m.useRef(new Map),i=m.useRef(null),[a,o]=m.useState(!1);m.useEffect(()=>{const p=i.current;if(!p)return;const g=()=>{o(p.scrollWidth-p.clientWidth-p.scrollLeft>1)};g(),p.addEventListener("scroll",g,{passive:!0});const v=new ResizeObserver(g);return v.observe(p),()=>{p.removeEventListener("scroll",g),v.disconnect()}},[e]);const l=m.useMemo(()=>pse(e),[e]),u=t&&e.some(p=>p.id===t)?t:e[0]?.id??null;m.useEffect(()=>{if(!u)return;const p=r.current.get(u);(p?.parentElement??p)?.scrollIntoView({block:"nearest",inline:"nearest"})},[u]);const d=m.useCallback((p,g)=>{p.stopPropagation(),s(g);const v=FD(e,g);v&&r.current.get(v.id)?.focus()},[e,s]),f=m.useCallback((p,g)=>{const v=e.length-1;let b;switch(p.key){case"ArrowRight":b=g===v?0:g+1;break;case"ArrowLeft":b=g===0?v:g-1;break;case"Home":b=0;break;case"End":b=v;break;default:return}p.preventDefault();const x=e[b];x&&(r.current.get(x.id)?.focus(),n(x.id))},[e,n]);return e.length===0?null:c.jsxs("div",{className:R("flex shrink-0 items-stretch border-hairline border-b"),children:[c.jsx("div",{ref:i,role:"tablist","aria-label":h("ui.canvas.tabs.open_documents"),"aria-orientation":"horizontal","data-glass-plane":"clear",className:R("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((p,g)=>{const v=p.id===u;return c.jsxs("div",{role:"presentation",className:R("group flex h-6 shrink-0 items-center rounded-sm pe-0.5","transition-colors duration-fast ease-out-quart",v?"bg-surface":"hover:bg-row-hover"),children:[c.jsx("button",{type:"button",role:"tab","aria-selected":v,id:v?PK:void 0,"aria-controls":v?MK:void 0,tabIndex:v?0:-1,title:p.artifact?S8({...p.artifact,title:p.title}):p.path??p.title,ref:b=>{b?r.current.set(p.id,b):r.current.delete(p.id)},onClick:()=>n(p.id),onKeyDown:b=>f(b,g),className:R("max-w-45 truncate rounded-sm py-1 pe-1 ps-2","text-start font-medium text-body-sm","transition-colors duration-fast ease-out-quart",v?"text-ink":"text-ink-muted"),children:l.get(p.id)??p.title}),c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.tabs.close",{value:l.get(p.id)??p.title}),onClick:b=>d(b,p.id),className:R("size-5 [&_svg]:size-3","hover:bg-danger-wash hover:text-danger",!v&&["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(Xn,{"aria-hidden":"true"})})]},p.id)})}),e.length>1&&c.jsxs(Po,{children:[c.jsx(vt,{content:h("ui.canvas.tabs.all_open_files"),children:c.jsx(eo,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.tabs.all_open_files"),className:R("me-1 shrink-0 self-center"),children:c.jsx(Ei,{"aria-hidden":"true"})})})}),c.jsx(Mo,{align:"end",className:R("max-w-80"),children:e.map(p=>c.jsxs(Jt,{onSelect:()=>n(p.id),children:[c.jsx(Js,{"aria-hidden":"true",className:R(p.id!==u&&"invisible")}),c.jsx("span",{className:R("truncate"),children:l.get(p.id)??p.title})]},p.id))})]})]})},YZe=m.memo(KZe),OK=["str","int","float","bool","list","dict"],DD=e=>["desktop","sessions",e??"","variables"];async function XZe(e){return(await rt({op:"sessions.variables.list",sessionId:e})).data}async function QZe(e,t){return(await rt({op:"sessions.variables.create",sessionId:e,key:t.key,value:t.value,type:t.type})).data.variable}async function JZe(e,t){return(await rt({op:"sessions.variables.update",sessionId:e,key:t.key,value:t.value,type:t.type})).data.variable}async function ZZe(e,t){await rt({op:"sessions.variables.delete",sessionId:e,key:t})}function LK(e){return e instanceof Fi&&e.status===404&&/^not found$/i.test(e.message.trim())}function eet(e){return e instanceof Fi&&e.status===404&&!LK(e)}const tet=(e,t)=>Dn({queryKey:DD(e),queryFn:async()=>{if(!e)throw new Error(h("ui.common.errors.session_id_required"));return XZe(e)},enabled:t&&!!e,refetchInterval:n=>n.state.data?.state==="busy"?1500:!1,refetchOnMount:"always",retry:!1}),ID=e=>async(t,n,s)=>{await e.invalidateQueries({queryKey:DD(s.sessionId)})},net=()=>{const e=Mt();return fn({mutationFn:({sessionId:t,...n})=>QZe(t,n),onSuccess:async()=>{Hs(h("ui.notices.variables.created"))},onError:t=>{nn(zi(t,h("ui.notices.variables.create_failed")))},onSettled:ID(e)})},set=()=>{const e=Mt();return fn({mutationFn:({sessionId:t,...n})=>JZe(t,n),onSuccess:async()=>{Hs(h("ui.notices.variables.updated"))},onError:t=>{nn(zi(t,h("ui.notices.variables.update_failed")))},onSettled:ID(e)})},ret=()=>{const e=Mt();return fn({mutationFn:({sessionId:t,key:n})=>ZZe(t,n),onSuccess:async()=>{Hs(h("ui.notices.variables.deleted"))},onError:t=>{nn(zi(t,h("ui.notices.variables.delete_failed")))},onSettled:ID(e)})},BK=e=>OK.includes(e),iet={already_exists:"key",reserved_name:"key",invalid_value:"value",too_large:"value"},aet=e=>({code:e instanceof Fi?e.code:void 0,message:zi(e,h("ui.canvas.variable_form_dialog.the_variable_could_not_be_saved_try_again"))}),_j=e=>{if(e){const t=BK(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:""}},Dk=()=>c.jsx("span",{className:R("text-danger"),"aria-hidden":"true",children:"*"}),oet=({open:e,onClose:t,onSubmit:n,initialData:s})=>{Ve();const[r,i]=m.useState(_j(s)),[a,o]=m.useState(!1),[l,u]=m.useState(null),d=!!s;m.useEffect(()=>{e&&(i(_j(s)),u(null))},[e,s]);const f=async()=>{if(u(null),!_5(r.key)){u({field:"key",message:h("ui.canvas.variable_form_dialog.this_name_cannot_be_sent_use_up_to_128_characters_without_control_charac")});return}o(!0);try{const _={key:r.key,type:r.type,value:r.value};await n(_),t()}catch(_){console.error("Failed to submit variable:",_),u(aet(_))}finally{o(!1)}},p=l?.field??(l?.code?iet[l.code]:void 0),g=d?h("ui.canvas.variable_form_dialog.edit_variable"):h("ui.canvas.variable_form_dialog.new_variable"),v=c.jsxs(c.Fragment,{children:[c.jsx(Uv,{onClick:t,disabled:a,startIcon:c.jsx(hde,{size:18,"aria-hidden":"true"}),children:h("ui.canvas.variable_form_dialog.cancel")}),c.jsx(Gv,{onClick:()=>void f(),disabled:a||!r.key.trim(),startIcon:a?c.jsx(On,{}):c.jsx(que,{size:18,"aria-hidden":"true"}),children:a?h("ui.canvas.variable_form_dialog.saving"):d?h("ui.canvas.variable_form_dialog.save"):h("ui.canvas.variable_form_dialog.create")})]}),b=(()=>{switch(r.type){case"dict":return h("ui.canvas.variable_form_dialog.value_json_object");case"list":return h("ui.canvas.variable_form_dialog.value_json_array");case"bool":return h("ui.canvas.variable_form_dialog.value_true_false");default:return h("ui.canvas.variable_form_dialog.value")}})(),x=r.type==="dict"||r.type==="list";return c.jsx(Ac,{open:e,onClose:t,title:g,actions:v,maxWidth:"sm",fullWidth:!0,children:c.jsxs("div",{className:R("flex flex-col gap-5 pt-2"),children:[c.jsxs("div",{className:R("flex flex-col gap-1.5"),children:[c.jsxs("div",{className:R("flex items-center gap-1"),children:[c.jsxs(dr,{htmlFor:"variable-key",children:[h("ui.canvas.variable_form_dialog.name_key"),c.jsx(Dk,{})]}),c.jsx(vt,{content:h("ui.canvas.variable_form_dialog.the_unique_identifier_for_the_variable_e_g_api_key_user_preference_canno"),children:c.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",className:R("text-info"),"aria-label":h("ui.canvas.variable_form_dialog.about_the_variable_name"),children:c.jsx(ig,{"aria-hidden":"true"})})})]}),c.jsx(bs,{id:"variable-key",value:r.key,onChange:_=>i(w=>({...w,key:_.target.value})),required:!0,disabled:a||d,placeholder:h("ui.canvas.variable_form_dialog.e_g_my_variable_name"),"aria-invalid":p==="key","aria-describedby":p==="key"?"variable-key-refusal":void 0,className:R(p==="key"&&"border-danger")}),p==="key"&&c.jsx("p",{id:"variable-key-refusal",role:"alert",className:R("text-body-sm text-ink"),children:l?.message})]}),c.jsxs("div",{className:R("flex flex-col gap-1.5"),children:[c.jsxs(dr,{htmlFor:"variable-type-select",children:[h("ui.canvas.variable_form_dialog.type"),c.jsx(Dk,{})]}),c.jsxs(E0,{value:r.type,onValueChange:_=>{BK(_)&&i(w=>({...w,type:_}))},disabled:a,children:[c.jsx(T0,{id:"variable-type-select",children:c.jsx(R0,{})}),c.jsx(A0,{children:OK.map(_=>c.jsx(F0,{value:_,children:_},_))})]})]}),c.jsxs("div",{className:R("flex flex-col gap-1.5"),children:[c.jsxs(dr,{htmlFor:"variable-value",children:[b,c.jsx(Dk,{})]}),c.jsx(vA,{id:"variable-value",value:r.value,onChange:_=>i(w=>({...w,value:_.target.value})),required:!0,disabled:a,rows:x?5:2,"aria-describedby":[x&&"variable-value-hint",p==="value"&&"variable-value-refusal"].filter(Boolean).join(" ")||void 0,"aria-invalid":p==="value",className:R(p==="value"&&"border-danger"),placeholder:r.type==="dict"?h("ui.canvas.variable_form_dialog.example_key_example_value"):r.type==="list"?h("ui.canvas.variable_form_dialog.item1_item2"):r.type==="bool"?h("ui.canvas.variable_form_dialog.true_or_false"):h("ui.canvas.variable_form_dialog.enter_variable_value")}),x&&c.jsx("p",{id:"variable-value-hint",className:R("text-ink-muted text-meta"),children:h("ui.canvas.variable_form_dialog.enter_a_valid_json_structure")}),p==="value"&&c.jsx("p",{id:"variable-value-refusal",role:"alert",className:R("text-body-sm text-ink"),children:l?.message})]}),l&&!p&&c.jsx("p",{role:"alert",className:R("text-body-sm text-ink"),children:l.message})]})})},wj=()=>h("ui.canvas.variables_viewer.the_backend_did_not_answer_so_this_chat_s_code_memory_could_not_be_read"),Aa=({children:e})=>c.jsx("div",{className:R("flex h-full flex-col items-center justify-center gap-2 p-6 text-center"),children:e}),yj=(e,t)=>e.length<=t?e:`${e.substring(0,t)}…`,jK=m.memo(({variable:e,onEdit:t,onDelete:n})=>{Ve();const[s,r]=m.useState(!1),[i,a]=m.useState(!1),o=m.useId(),l=_5(e.key),u=e.editable&&l,d=l,f=m.useMemo(()=>String(e.value),[e.value]),p=m.useMemo(()=>yj(f,200),[f]),g=m.useMemo(()=>yj(f,1e3),[f]),v=e.type,b=m.useCallback(()=>{r(y=>!y)},[]),x=m.useCallback(y=>{y.stopPropagation(),t(e)},[t,e]),_=m.useCallback(y=>{y.stopPropagation(),n(e.key)},[n,e.key]),w=m.useCallback(async y=>{y.stopPropagation();try{await navigator.clipboard.writeText(f),a(!0),setTimeout(()=>a(!1),2e3)}catch(S){console.error("Failed to copy to clipboard:",S)}},[f]);return c.jsxs("div",{className:R("group border-hairline border-b last:border-b-0"),children:[c.jsxs("div",{className:R("flex min-h-8 items-center gap-1 pe-1","transition-colors duration-fast ease-out-quart hover:bg-surface"),children:[c.jsxs("button",{type:"button",onClick:b,"aria-expanded":s,"aria-controls":o,className:R("flex min-w-0 flex-1 cursor-pointer select-none items-center gap-2 px-2 py-1 text-start font-mono text-mono-sm"),children:[s?c.jsx(Ei,{"aria-hidden":"true",className:"size-3 shrink-0 text-ink-dim rtl:-scale-x-100"}):c.jsx(Vi,{"aria-hidden":"true",className:"size-3 shrink-0 text-ink-dim rtl:-scale-x-100"}),c.jsx("span",{className:R("shrink-0 font-medium text-ink"),children:e.key}),c.jsx("span",{className:R("shrink-0 text-ink-dim"),children:v}),c.jsx(vt,{content:g,align:"start",children:c.jsx("span",{className:R("min-w-0 flex-1 truncate text-ink-muted"),children:p})})]}),c.jsxs("div",{className:R("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(vt,{content:i?h("ui.canvas.variables_viewer.copied"):h("ui.canvas.variables_viewer.copy_value"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:w,"aria-label":h("ui.canvas.variables_viewer.copy_value"),children:c.jsx(ed,{})})}),u?c.jsx(vt,{content:h("ui.canvas.variables_viewer.edit_variable"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:x,"aria-label":h("ui.canvas.variables_viewer.edit_variable"),children:c.jsx(mM,{})})}):c.jsx(vt,{content:l?h("ui.canvas.variables_viewer.this_variable_can_t_be_edited_because_its_type_is_not_yet_supported_for"):h("ui.canvas.variables_viewer.this_variable_s_name_can_t_be_edited_from_here_copy_it_to_the_session_un"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-disabled":"true","aria-label":h("ui.canvas.variables_viewer.edit_variable"),className:R("cursor-default text-ink-disabled hover:bg-transparent hover:text-ink-disabled"),children:c.jsx(mM,{})})}),d&&c.jsx(vt,{content:h("ui.canvas.variables_viewer.delete_variable"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:_,"aria-label":h("ui.canvas.variables_viewer.delete_variable"),className:R("hover:bg-danger-wash hover:text-danger"),children:c.jsx(cg,{})})})]})]}),s?c.jsx("div",{id:o,className:R("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:f}):null]})});jK.displayName="VariableRow";const HK=m.memo(({sessionId:e,turnTerminal:t})=>{Ve();const[n,s]=m.useState(!1),[r,i]=m.useState(null),[a,o]=m.useState(!1),[l,u]=m.useState(null),d=ss(),f=Et(d.data,"session_variables"),{data:p,isLoading:g,error:v,isError:b}=tet(e,f),x=Mt(),_=m.useRef(t);m.useEffect(()=>{const O=_.current;_.current=t,!(O===void 0||t===void 0)&&(t<=O||!e||!f||x.invalidateQueries({queryKey:DD(e)}))},[t,e,f,x]);const w=net(),y=set(),S=ret(),C=m.useRef(null);m.useEffect(()=>{p?.state==="observed"&&(C.current=p)},[p]);const E=p?.state==="observed"?p:C.current,k=p?.state==="busy",F=m.useMemo(()=>E?.variables??[],[E]),A=m.useCallback(()=>{i(null),s(!0)},[]),I=m.useCallback(O=>{i(O),s(!0)},[]),N=m.useCallback(()=>{s(!1),i(null)},[]),P=m.useCallback(async O=>{if(e)try{r?await y.mutateAsync({sessionId:e,...O,key:r.key}):await w.mutateAsync({sessionId:e,...O})}catch(X){throw console.error("Submission failed in component:",X),X}},[e,r,w,y]),M=m.useCallback(O=>{u(O),o(!0)},[]),Y=m.useCallback(async()=>{if(!e||!l){o(!1),u(null);return}try{await S.mutateAsync({sessionId:e,key:l})}catch(O){console.error("Deletion failed during confirmation:",O)}finally{o(!1),u(null)}},[e,l,S]);if(d.isLoading)return c.jsxs(Aa,{children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.loading_variables")})]});if(d.isError)return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.could_not_reach_the_backend")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:zi(d.error,wj())})]});if(!f)return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.update_the_backend_to_read_code_memory")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.this_app_can_read_code_memory_the_backend_it_is_running_against_is_older")})]});if(!e)return c.jsx(Aa,{children:c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.code_memory_starts_when_you_send_your_first_message")})});if(g)return c.jsxs(Aa,{children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.loading_variables")})]});if(b)return LK(v)?c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.update_the_backend_to_read_code_memory")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.settings_then_application_updates_and_info_installs_the_newer_backend")})]}):eet(v)?c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.could_not_load_variables")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:zi(v,h("ui.canvas.variables_viewer.the_backend_does_not_have_a_chat_with_this_session_id"))})]}):c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.could_not_load_variables")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:wj()})]});if(p?.state==="unsupported")return c.jsx(Aa,{children:c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.this_chat_cannot_read_code_memory")})});if(F.length===0){if(k)return c.jsxs(Aa,{children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.reading")})]});if(E?.truncated&&F.length===0&&!k)return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.too_large_to_show_here")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.this_chat_keeps_a_value_bigger_than_this_panel_can_list_so_nothing_is_sh")})]});const O=E?.kernel==="absent"||E?.runtime==="absent";return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:O?h("ui.canvas.variables_viewer.no_code_memory_yet"):h("ui.canvas.variables_viewer.nothing_stored_yet")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:O?h("ui.canvas.variables_viewer.it_fills_in_when_code_runs_in_this_chat"):h("ui.canvas.variables_viewer.when_the_agent_runs_code_for_you_the_values_it_keeps_around_between_step")}),O?null:c.jsxs(ce,{variant:"secondary",size:"sm",onClick:A,children:[c.jsx(Cl,{"aria-hidden":"true"}),h("ui.canvas.variables_viewer.new_variable")]})]})}return c.jsxs("div",{className:R("flex h-full min-h-0 flex-col"),children:[c.jsxs("div",{className:R("flex h-10 shrink-0 items-center justify-between gap-3 border-hairline border-b px-3"),children:[c.jsxs("p",{className:R("flex min-w-0 items-center truncate text-body-sm text-ink-muted"),children:[c.jsx("span",{className:R("font-medium text-ink"),children:h("ui.canvas.variables_viewer.code_memory")}),c.jsx("span",{className:R("mx-1.5 text-ink-dim"),children:"·"}),h("ui.canvas.variables_viewer.count",{count:F.length}),k?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:R("mx-1.5 text-ink-dim"),children:"·"}),c.jsx(On,{size:"xs"}),c.jsx("span",{className:R("ms-1.5"),children:h("ui.canvas.variables_viewer.reading")})]}):null]}),c.jsxs(ce,{variant:"ghost",size:"sm",onClick:A,children:[c.jsx(Cl,{"aria-hidden":"true"}),h("ui.canvas.variables_viewer.new_variable")]})]}),c.jsx("div",{className:R("min-h-0 flex-1 overflow-auto"),children:F.map(O=>c.jsx(jK,{variable:O,onEdit:I,onDelete:M},O.key))}),c.jsx(oet,{open:n,onClose:N,onSubmit:P,initialData:r}),l&&c.jsx(nd,{open:a,title:h("ui.canvas.variables_viewer.delete_variable"),message:c.jsxs(c.Fragment,{children:[h("ui.canvas.variables_viewer.are_you_sure_you_want_to_delete_the_variable")," ",c.jsx("strong",{className:R("font-mono text-ink"),children:l}),h("ui.canvas.variables_viewer.this_action_cannot_be_undone")]}),confirmText:h("ui.canvas.variables_viewer.delete"),cancelText:h("ui.canvas.variables_viewer.cancel"),isDangerous:!0,onConfirm:Y,onCancel:()=>{o(!1),u(null)}})]})});HK.displayName="CanvasVariablesViewer";const cet=(e,t,n,s,r=!1)=>r?h("ui.canvas.view_name.view_shown_this_list_is_capped",{label:e,counted:s,noun:t,pluralnoun:n}):s>0?h("ui.canvas.view_name.view_count",{label:e,counted:s,noun:t,pluralnoun:n}):h("ui.canvas.view_name.view_empty",{label:e}),Cj="mb-1.5 flex w-fit items-center gap-2 font-normal text-ink-muted",Sj=()=>[{id:"md",name:h("ui.canvas.create_file_dialog.markdown_md"),group:h("ui.canvas.create_file_dialog.general")},{id:"txt",name:h("ui.canvas.create_file_dialog.plain_text_txt"),group:h("ui.canvas.create_file_dialog.general")},{id:"html",name:h("ui.canvas.create_file_dialog.html_html"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"css",name:h("ui.canvas.create_file_dialog.css_css"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"js",name:h("ui.canvas.create_file_dialog.javascript_js"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"jsx",name:h("ui.canvas.create_file_dialog.jsx_jsx"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"ts",name:h("ui.canvas.create_file_dialog.typescript_ts"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"tsx",name:h("ui.canvas.create_file_dialog.tsx_tsx"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"py",name:h("ui.canvas.create_file_dialog.python_py"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"go",name:h("ui.canvas.create_file_dialog.go_go"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"java",name:h("ui.canvas.create_file_dialog.java_java"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"cs",name:h("ui.canvas.create_file_dialog.c_cs"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"php",name:h("ui.canvas.create_file_dialog.php_php"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"rb",name:h("ui.canvas.create_file_dialog.ruby_rb"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"rs",name:h("ui.canvas.create_file_dialog.rust_rs"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"sh",name:h("ui.canvas.create_file_dialog.shell_script_sh"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"json",name:h("ui.canvas.create_file_dialog.json_json"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"yaml",name:h("ui.canvas.create_file_dialog.yaml_yaml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"yml",name:h("ui.canvas.create_file_dialog.yaml_yml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"xml",name:h("ui.canvas.create_file_dialog.xml_xml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"toml",name:h("ui.canvas.create_file_dialog.toml_toml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"ini",name:h("ui.canvas.create_file_dialog.ini_ini"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"env",name:h("ui.canvas.create_file_dialog.env"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"dockerfile",name:h("ui.canvas.create_file_dialog.dockerfile"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"c",name:h("ui.canvas.create_file_dialog.c_c"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"cpp",name:h("ui.canvas.create_file_dialog.c_cpp"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"swift",name:h("ui.canvas.create_file_dialog.swift_swift"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"kt",name:h("ui.canvas.create_file_dialog.kotlin_kt"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"scala",name:h("ui.canvas.create_file_dialog.scala_scala"),group:h("ui.canvas.create_file_dialog.other_languages")}],uet=({open:e,onClose:t,onSave:n,isSaving:s,currentWorkingDirectory:r="~"})=>{Ve();const[i,a]=m.useState(""),[o,l]=m.useState("md"),[u,d]=m.useState(!1);m.useEffect(()=>{e&&(a(""),l("md"))},[e]);const f=Sj().find(b=>b.id===o)??(o?{id:o,name:o}:null),p=i.trim()!==""&&!s,g=async(b=!1)=>{if(!p)return;const x=`${r}/${i}.${o}`;if(await window.api.fileExists(x)&&!b){d(!0);return}n({name:i,type:o,location:r},b)},v=c.jsxs(c.Fragment,{children:[c.jsx(Uv,{onClick:t,disabled:s,children:h("ui.canvas.create_file_dialog.cancel")}),c.jsx(Gv,{onClick:()=>void g(),disabled:!p,startIcon:s?c.jsx(On,{}):null,children:s?h("ui.canvas.create_file_dialog.creating"):h("ui.canvas.create_file_dialog.create_file")})]});return c.jsxs(c.Fragment,{children:[c.jsx(Ac,{open:e&&!u,onClose:t,title:h("ui.canvas.create_file_dialog.create_new_file"),actions:v,maxWidth:"sm",fullWidth:!0,children:c.jsxs("div",{className:R("flex flex-col gap-4 pt-2"),children:[c.jsxs("div",{children:[c.jsxs(dr,{htmlFor:"create-file-name",className:R(Cj),children:[c.jsx(Ey,{size:16,"aria-hidden":"true"}),h("ui.canvas.create_file_dialog.file_name")]}),c.jsx(bs,{id:"create-file-name",value:i,onChange:b=>a(b.target.value),required:!0,autoFocus:!0,disabled:s,placeholder:h("ui.canvas.create_file_dialog.enter_file_name_e_g_my_new_script"),onKeyDown:b=>{b.key==="Enter"&&p&&g()}})]}),c.jsx(_A,{label:h("ui.canvas.create_file_dialog.file_type"),icon:c.jsx(gU,{size:16,"aria-hidden":"true"}),labelTooltip:h("ui.canvas.create_file_dialog.pick_an_extension_or_type_one_that_is_not_listed"),placeholder:h("ui.canvas.create_file_dialog.select_or_type_an_extension"),options:Sj(),selected:f,onSelect:b=>l(b.id),onCustomSubmit:b=>l(b),busyLabel:h("ui.canvas.create_file_dialog.loading_file_types"),disabled:s}),c.jsxs("div",{children:[c.jsxs("p",{className:R(Cj,"text-body-sm"),children:[c.jsx(gse,{size:16,"aria-hidden":"true"}),h("ui.canvas.create_file_dialog.location")]}),c.jsx(mse,{currentWorkingDirectory:r,readOnlyReason:h("ui.canvas.create_file_dialog.change_the_working_directory_from_the_composer_to_create_the_file_elsewh")}),c.jsx("p",{className:R("mt-2 text-ink-muted text-meta"),children:h("ui.canvas.create_file_dialog.the_file_will_be_created_in_this_working_directory")})]})]})}),c.jsx(nd,{open:u,title:h("ui.canvas.create_file_dialog.file_already_exists"),message:h("ui.canvas.create_file_dialog.a_file_named_already_exists_do_you_want_to_overwrite_it",{filename:i,filetype:o}),confirmText:h("ui.canvas.create_file_dialog.overwrite"),onConfirm:()=>{d(!1),g(!0)},onCancel:()=>d(!1),isDangerous:!0})]})},det=2e3,het={get missing(){return h("ui.canvas.use_file_freshness.no_longer_on_disk_showing_the_version_we_last_read")},get unreadable(){return h("ui.canvas.use_file_freshness.could_not_be_read_showing_the_version_we_last_read")},get failed(){return h("ui.canvas.use_file_freshness.could_not_be_re_read_showing_the_version_we_last_read")},get"disk-changed"(){return h("ui.canvas.use_file_freshness.changed_on_disk_load_it_or_save_to_replace_it")},get"save-replaced"(){return h("ui.canvas.use_file_freshness.your_save_replaced_the_change_on_disk")}},fet={get missing(){return h("ui.canvas.use_file_freshness.this_file_is_no_longer_on_disk_the_last_version_we_read_is_still_shown_a")},get unreadable(){return h("ui.canvas.use_file_freshness.this_file_could_not_be_read_the_last_version_we_read_is_still_shown_and")},get failed(){return h("ui.canvas.use_file_freshness.this_file_could_not_be_re_read_so_the_version_we_last_read_is_still_show")},get"disk-changed"(){return h("ui.canvas.use_file_freshness.your_unsaved_edits_are_kept_until_the_app_quits_and_saving_is_paused_whi")},get"save-replaced"(){return h("ui.canvas.use_file_freshness.your_save_replaced_the_version_that_had_changed_on_disk_re_read_the_file")}},pet=8e3;function kj(e,t){switch(e.status){case"applied":return"Re-read";case"identical":return h("ui.canvas.use_file_freshness.up_to_date");case"unchanged":return t?h("ui.canvas.use_file_freshness.up_to_date"):void 0;case"unavailable":return t?h("ui.canvas.use_file_freshness.no_local_file_access"):void 0;default:return}}function Ej(e,t){switch(e.status){case"applied":return h("ui.canvas.use_file_freshness.the_file_s_version_was_re_read_from_disk_and_is_now_on_screen");case"identical":case"unchanged":return t?h("ui.canvas.use_file_freshness.already_up_to_date_the_file_is_unchanged"):void 0;case"unavailable":return t?h("ui.canvas.use_file_freshness.local_file_access_is_unavailable_so_there_is_nothing_to_re_read_from"):void 0;default:return}}function Tj(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 get({document:e,conversationId:t}){const n=Fs(x=>x.updateOneFile),s=m.useSyncExternalStore(T1e,()=>rC(e.id),()=>!1),[r,i]=m.useState(!1),a=m.useSyncExternalStore(F1e,()=>A1e(e.id),()=>null),o=m.useRef(null);o.current=a;const[l,u]=m.useState(null);m.useEffect(()=>{u(null)},[e.id]),m.useEffect(()=>{if(!l)return;const x=pet-(Date.now()-l.at),_=window.setTimeout(()=>{u(w=>w?.at===l.at?null:w)},Math.max(0,x));return()=>window.clearTimeout(_)},[l]);const d=m.useRef(e);m.useEffect(()=>{d.current=e});const f=m.useMemo(()=>D1e({probe:x=>e7(x),read:async(x,_)=>{if(typeof window.api?.readFile!="function")return{ok:!1,error:h("ui.canvas.use_file_freshness.local_file_access_is_unavailable_outside_the_desktop_app")};try{const w=await window.api.readFile(x,_);return w.success?{ok:!0,content:w.data}:{ok:!1,error:w.error instanceof Error?w.error.message:String(w.error)}}catch(w){return{ok:!1,error:w instanceof Error?w.message:String(w)}}}}),[]),p=m.useCallback(x=>{if(!t)return;const _=d.current;_.id===x.id&&_.content===x.content&&_.readMtimeMs===x.readMtimeMs&&_.lastAgentModified===x.lastAgentModified&&_.sizeBytes===x.sizeBytes&&_.availability===x.availability||n(t,x)},[t,n]),g=m.useCallback(async x=>{x&&i(!0);const _=hp(e.id);try{const w=await f.check(d.current,x);if(hp(e.id)!==_)return;"document"in w&&p(w.document);const y=Tj(w,o.current);y!==void 0&&wo(e.id,y);const S=kj(w,x);S!==void 0&&u(S?{text:S,detail:Ej(w,x)??null,at:Date.now()}:null)}finally{x&&i(!1)}},[p,e.id,f]),v=m.useCallback(async()=>{i(!0);try{P1e(e.id);const x=await f.load(d.current);"document"in x&&(N1e(x.document.id,x.document.content,x.document.readMtimeMs??null),p(x.document));const _=Tj(x,o.current);_!==void 0&&wo(e.id,_);const w=kj(x,!0);w!==void 0&&u(w?{text:w,detail:Ej(x,!0)??null,at:Date.now()}:null)}finally{i(!1)}},[p,e.id,f]);m.useEffect(()=>{g(!1)},[g,e.id,e.path,t]),m.useEffect(()=>{const x=()=>{window.document.visibilityState==="visible"&&g(!1)};return window.addEventListener("focus",x),window.document.addEventListener("visibilitychange",x),()=>{window.removeEventListener("focus",x),window.document.removeEventListener("visibilitychange",x)}},[g]),m.useEffect(()=>{const x=window.setInterval(()=>{window.document.visibilityState==="visible"&&g(!1)},det);return()=>window.clearInterval(x)},[g]);const b=m.useCallback(()=>{if(o.current==="disk-changed"){v();return}o.current==="save-replaced"&&wo(e.id,null),g(!0)},[g,e.id,v]);return{lastModifiedMs:e.readMtimeMs??null,refreshing:r,note:a?het[a]:l?.text??null,detail:a?fet[a]:l?.detail??l?.text??null,dirty:s,diskChanged:a==="disk-changed",refresh:b}}const met=({document:e,conversationId:t})=>{Ve();const{lastModifiedMs:n,refreshing:s,note:r,detail:i,dirty:a,diskChanged:o,refresh:l}=get({document:e,conversationId:t}),u=m.useId(),d=n===null?null:new Date(n),f=d===null?null:vse(d),p=d===null?null:bse(d,{hour:"numeric",minute:"2-digit"}),g=f!==null&&p!==null&&p.length>0&&f.endsWith(p),v=f===null?null:g?f.slice(0,-p.length).trimEnd():f,b=f===null?h("ui.canvas.document_freshness_bar.not_read_from_disk_yet"):h("ui.canvas.document_freshness_bar.modified",{formatcalendardatetime:f}),x=o?h("ui.canvas.document_freshness_bar.load_the_file_s_version_your_unsaved_edits_are_discarded"):a?h("ui.canvas.document_freshness_bar.check_the_file_your_edits_are_kept"):h("ui.canvas.document_freshness_bar.re_read_from_disk");return c.jsxs("div",{"data-glass-plane":"band",className:R("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(vt,{content:[i,b].filter(Boolean).join(" · "),side:"bottom",delayDuration:1200,children:c.jsxs("div",{tabIndex:0,className:R("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:R("min-w-0 truncate whitespace-nowrap text-meta text-ink-muted tabular-nums"),"data-tour-tag":"canvas-document-modified",children:v===null?b:c.jsxs(c.Fragment,{children:[c.jsx("bdi",{children:h("ui.canvas.files.modified")})," ",c.jsx("bdi",{children:v}),g&&c.jsxs(c.Fragment,{children:[" ",c.jsx("bdi",{dir:"ltr",children:p})]})]})}),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:R("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:R("shrink-0"),children:c.jsx(vt,{content:x,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":x,"aria-describedby":r?u:void 0,disabled:s,onClick:l,"data-tour-tag":"canvas-refresh-file-button",children:c.jsx(Wy,{"aria-hidden":"true"})})})})]})},vet=[],Rj=[{value:"documents",get label(){return h("ui.canvas.shell.documents")},tourTag:"canvas-documents-view-button",Icon:Ty},{value:"files",get label(){return h("ui.canvas.shell.files")},tourTag:"canvas-files-view-button",Icon:ky},{value:"variables",get label(){return h("ui.canvas.shell.variables")},tourTag:"canvas-variables-view-button",Icon:gue},{value:"goals",get label(){return h("ui.canvas.shell.goals")},tourTag:"canvas-goals-view-button",Icon:wde}],bet=e=>e?Rj:Rj.filter(t=>t.value!=="goals"),xet=({current:e,onChange:t,views:n,fileCount:s,goalCount:r,goalTruncated:i})=>(Ve(),c.jsxs("fieldset",{className:R("inline-flex h-7 shrink-0 items-center gap-0.5 border-0 p-0"),children:[c.jsx("legend",{className:R("sr-only"),children:h("ui.canvas.shell.canvas_view")}),n.map(({value:a,label:o,tourTag:l,Icon:u})=>{const d=e===a,f=a==="files"?s:a==="goals"?r:0,p=a==="files"?h("ui.canvas.shell.file"):h("ui.canvas.shell.goal"),g=a==="files"?h("ui.canvas.shell.files"):h("ui.canvas.shell.goals"),v=f===null?o:cet(o,p,g,f,a==="goals"&&i);return c.jsx(vt,{content:v,children:c.jsxs("button",{type:"button","aria-pressed":d,"aria-label":v,"data-tour-tag":l,onClick:()=>t(a),className:R("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:R("ms-1 text-meta"),children:[o,f===null?"":` ${Bd(f)}`]})]})},a)})]})),_et=({activeDocumentId:e,initialDocuments:t=[],onChangeActiveDocument:n,onClose:s,onCloseDocument:r,conversationId:i,sessionId:a,filesSourceReady:o=!0,turnTerminal:l,agentId:u,currentWorkingDirectory:d,fileCount:f=0,fileIndex:p,attachments:g,scan:v=null,goalHistory:b=vet,goalHistoryTruncated:x=!1,goalCapable:_=!1,goalPresent:w=!1})=>{Ve();const y=QG(a,!p,l),S=p??y,C=k8(a,null,l,!g),E=g??C,k=S.mode==="negotiating"?null:S.mode==="index"?S.state==="ready"||S.total>0?S.total:null:f,F=k===null?E.items.length||null:n9(k,S.mode==="index"?S.rows.map(se=>se.ref.type==="artifact"?se.ref.digest:null):[],E),[A,I]=m.useState(!1),[N,P]=m.useState(!1),[M,Y]=m.useState("Ctrl");m.useEffect(()=>{(async()=>{const he=await window.api.systemInfo.getPlatformInfo();Y(he.platform==="darwin"?"⌘":"Ctrl")})()},[]);const{addFileAndSelect:O,setViewMode:X,addMentionedFile:Q}=Fs(),{removeManager:ie}=JG(),G=m.useCallback(async()=>{if(i){const se=await window.api.selectFile();if(se){const he={id:se.path,title:se.path.split("/").pop()||se.path,content:se.content,path:se.path,type:Gu(se.path)};O(i,he),Q(i,he),X(i,"documents")}}},[O,Q,i,X]);m.useEffect(()=>{const se=he=>{const xe=lJ(he);if(xe==="open-file"?(he.preventDefault(),G()):xe==="new-file"&&(he.preventDefault(),I(!0)),he.key==="Escape"&&i){if(he.defaultPrevented||pA(he.target))return;he.preventDefault(),s()}};return window.addEventListener("keydown",se),()=>{window.removeEventListener("keydown",se)}},[G,i,s]);const ne=async(se,he=!1)=>{P(!0);try{if(await Owe(se.name,se.type,se.location,he),i){const xe={id:`${se.location}/${se.name}.${se.type}`,title:`${se.name}.${se.type}`,content:"",path:`${se.location}/${se.name}.${se.type}`};O(i,xe),Q(i,xe)}I(!1)}catch{}finally{P(!1)}},oe=Fs(se=>i?se.conversations[i]:void 0),B=bet(_),H=oe?.viewMode,U=H&&B.some(se=>se.value===H)?H:"documents",z=F??0,te=z>0,fe=m.useCallback(se=>{i&&X(i,se)},[i,X]),J=t,[Se,W]=m.useState(J.length>0?J[0].id:null),Ce=e??Se,K=m.useMemo(()=>J.find(se=>se.id===Ce)||null,[J,Ce]),me=m.useCallback(se=>{n?n(se):W(se)},[n]),Ee=m.useCallback(se=>{fe("documents"),me(se)},[me,fe]),Ae=m.useCallback(se=>{if(r(se),ie(se),Ce===se){const he=FD(J,se)?.id??null;n?n(he):W(he)}},[J,Ce,n,r,ie]);return c.jsxs("section",{"aria-label":h("ui.canvas.shell.canvas"),"data-tour-tag":"canvas-container","data-canvas-shortcuts":!0,"data-glass-region":"pane",className:R("panel-top-pad flex h-full flex-col bg-elevated"),children:[c.jsxs("div",{className:R("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(xet,{current:U,onChange:fe,views:B,fileCount:F,goalCount:b.length,goalTruncated:x}),c.jsxs("div",{className:R("flex shrink-0 items-center gap-0.5"),children:[c.jsx(vt,{content:h("ui.canvas.shell.new_file_n",{modifierkey:M}),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.shell.new_file_n",{modifierkey:M}),onClick:()=>I(!0),"data-tour-tag":"canvas-create-file-button",children:c.jsx(pM,{"aria-hidden":"true"})})}),c.jsx(vt,{content:h("ui.canvas.shell.open_file_from_disk_o",{modifierkey:M}),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.shell.open_file_from_disk_o",{modifierkey:M}),onClick:G,children:c.jsx(sT,{"aria-hidden":"true"})})}),c.jsx(vt,{content:h("ui.canvas.shell.close_canvas"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.shell.close_canvas"),onClick:s,"data-tour-tag":"close-canvas-button",children:c.jsx(Hu,{"aria-hidden":"true",className:"rtl:-scale-x-100"})})})]})]}),U==="documents"&&c.jsxs(c.Fragment,{children:[c.jsx(YZe,{documents:J,activeDocumentId:Ce,onChangeActiveDocument:me,onCloseDocument:Ae}),K&&c.jsxs(_Z,{id:MK,labelledBy:PK,children:[!K.artifact&&c.jsx(met,{document:K,conversationId:i}),c.jsx(mXe,{document:K,conversationId:i,agentId:u},K.id)]}),!K&&J.length===0&&c.jsxs(PR,{title:h("ui.canvas.shell.nothing_open_yet"),description:h("ui.canvas.shell.open_a_file_to_read_or_edit_it_here_files_the_agent_mentions_in_the_conv"),children:[c.jsxs(ce,{variant:te?"primary":"secondary",size:"sm",onClick:()=>fe("files"),children:[c.jsx(ky,{"aria-hidden":"true"}),te?h("ui.canvas.shell.browse_filesc0c547",{filecountvalue:z}):h("ui.canvas.shell.browse_files")]}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:G,children:[c.jsx(sT,{"aria-hidden":"true"}),h("ui.canvas.shell.open_file_from_disk")]}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>I(!0),children:[c.jsx(pM,{"aria-hidden":"true"}),h("ui.canvas.shell.new_file")]})]})]}),U==="files"&&i&&c.jsx(WZe,{conversationId:i,sessionId:a,cwd:o?d:void 0,index:S.mode==="fallback"&&!o?{...S,mode:"negotiating",state:"loading",localReadAllowed:!1}:S,onSwitchToDocumentView:Ee,scan:v,attachments:E},i),U==="variables"&&i&&c.jsx(HK,{sessionId:a,turnTerminal:l}),U==="goals"&&c.jsx($Ze,{entries:b,truncated:x,goalPresent:w}),(U==="files"||U==="variables")&&!i&&c.jsx(PR,{title:h("ui.canvas.shell.no_conversation_open"),description:h("ui.canvas.shell.start_a_conversation_with_an_agent_to_see_the_files_and_variables_it_is")}),u&&c.jsx(uet,{open:A,onClose:()=>I(!1),onSave:ne,isSaving:N,currentWorkingDirectory:d})]})},wet=m.memo(_et),yet="max-h-[min(22rem,var(--radix-popover-content-available-height))]";function Cet(e){return e==="team"?{recents:"Recent teams",all:"All teams"}:{recents:"Recent agents",all:"All agents"}}function UK(e){return!e.loading&&e.loadError===null&&e.rowCount>0}function ket(e){const{rows:t,matches:n,recents:s,kind:r,query:i}=e,a=Cet(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(f=>f.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 Ik(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 Eet(e){return`${e} cannot take the seat.`}const Tet="No profile here can take the seat — clear the search, or switch the team.",Ret="No profile can take the seat — switch the team.";function Aet(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`:Tet:r?i?`${t.total} ${a} in all — scroll, or type to filter`:Ret:null}function GK(e){return e.teamOwnsSeat===!0?!1:e.name===e.manager||e.delegate===!0}function Fet(e){return`${e} is led by its manager; only the manager and profiles that can delegate may take this seat.`}function Det(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 Iet(e){return`Agent seat closed by ${e}`}const Net="Needs a delegating profile here.";function Pet(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:Fet(e.teamLabel)}}const Aj=R("px-2 py-3 text-body-sm"),Met=({kind:e,open:t,listId:n,options:s,recents:r,loading:i,loadError:a,emptyText:o,caption:l,closedReason:u=null,closedNoteId:d,closedTitle:f,onPick:p,onClose:g,onCloseAutoFocus:v})=>{Ve();const[b,x]=m.useState(""),[_,w]=m.useState(0),[y,S]=m.useState(null),[C,E]=m.useState(!1),[k,F]=m.useState(null),A=m.useRef(null),[I,N]=m.useState(null),P=UK({loading:i,loadError:a,rowCount:s.length}),M=m.useMemo(()=>xse(s,b),[s,b]),Y=m.useMemo(()=>ket({rows:s,matches:M,recents:r,kind:e,query:b}),[s,M,r,e,b]),O=m.useMemo(()=>Y.bands.flatMap(te=>te.rows),[Y]);m.useEffect(()=>{w(Ik(O)),S(null),F(null)},[b]),m.useEffect(()=>{w(Ik(O))},[O.length]),m.useEffect(()=>{F(null)},[_]),m.useEffect(()=>{document.getElementById(`${n}-${_}`)?.scrollIntoView({block:"nearest"})},[_,n]),m.useEffect(()=>{const te=I;if(!te){E(!1);return}const fe=()=>E(te.scrollHeight>te.clientHeight+1);fe();let J;if(typeof ResizeObserver<"u"){J=new ResizeObserver(fe),J.observe(te);for(const Se of te.children)J.observe(Se)}return()=>J?.disconnect()},[Y,I]),m.useEffect(()=>{if(!t)return;const te=A.current;!te||document.activeElement===te||te.focus()},[t,P]),m.useEffect(()=>{t&&(x(""),w(Ik(O)),S(null),F(null))},[t]);const X=m.useCallback(te=>{O.length!==0&&w(fe=>(fe+te+O.length)%O.length)},[O.length]),Q=m.useCallback(te=>{if(!te.nativeEvent.isComposing){if(te.key==="Tab"){te.stopPropagation(),g();return}if(te.key==="ArrowDown"){te.preventDefault(),X(1);return}if(te.key==="ArrowUp"){te.preventDefault(),X(-1);return}if(te.key==="Home"&&O.length>0){te.preventDefault(),w(0);return}if(te.key==="End"&&O.length>0){te.preventDefault(),w(O.length-1);return}if(te.key==="Enter"){te.preventDefault();const fe=O[_];fe&&!fe.disabled?p(fe.value):fe?.blocked&&F(Eet(fe.label));return}}},[_,O,X,g,p]),ie=e==="team"?"teams":"agents",G=O.length>0?`${n}-${_}`:void 0,ne=O.some(te=>!te.blocked),oe=Y.matches>0&&!ne,B=Aet({view:Y,kind:e,query:b,overflowing:C,hasSettable:ne}),H=m.useId();let U=-1;const z=c.jsxs("div",{className:"relative px-1 pt-1 pb-1",children:[c.jsx(_h,{className:"-translate-y-1/2 pointer-events-none absolute top-1/2 start-2.5 size-4 text-ink-dim","aria-hidden":"true"}),c.jsx(bs,{ref:A,role:"combobox","aria-expanded":!0,"aria-controls":P?n:void 0,"aria-activedescendant":G,"aria-autocomplete":"list","aria-label":h("ui.chat.header_identity.search",{kind:ie}),value:b,onChange:te=>x(te.target.value),onKeyDown:Q,placeholder:h("ui.chat.header_identity.search",{kind:ie}),className:"ps-8",autoComplete:"off",spellCheck:!1})]});if(u!==null){const te=`${d}-title`;return c.jsxs(Bu,{align:"start",sideOffset:6,collisionPadding:8,className:R("flex w-80 flex-col gap-0.5 p-1"),"data-header-identity-menu":e,"data-header-identity-closed":"",id:d,"aria-labelledby":te,onOpenAutoFocus:fe=>fe.preventDefault(),onCloseAutoFocus:v,children:[c.jsx("p",{id:te,className:"px-2 pt-1 text-body-sm text-ink-muted",children:f}),c.jsx("p",{"data-header-identity-constraint":"",className:"px-2 pb-1.5 text-ink-dim text-meta",children:u})]})}return c.jsx(Bu,{align:"start",sideOffset:6,collisionPadding:8,className:R("flex w-80 flex-col p-1",yet,"overflow-hidden"),"data-header-identity-menu":e,role:"presentation",onMouseDown:te=>te.preventDefault(),onCloseAutoFocus:v,children:P?c.jsxs(c.Fragment,{children:[z,l!==null&&c.jsx("p",{id:H,"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&&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:N,id:n,role:"listbox","aria-label":e==="team"?h("ui.agents.pages.tab.teams"):h("ui.agents.pages.tab.agents"),"aria-describedby":l!==null?H:void 0,tabIndex:-1,onMouseLeave:()=>S(null),className:"min-h-0 flex-1 overflow-y-auto",children:Y.noMatches?c.jsx("p",{className:R(Aj,"text-ink-dim"),"data-header-identity-no-matches":"",children:h("ui.chat.header_identity.no_matches",{query:b.trim()})}):Y.bands.map(te=>c.jsxs(m.Fragment,{children:[te.heading&&c.jsxs("div",{role:"presentation","data-header-identity-band":te.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:te.heading}),c.jsx("div",{className:"h-px flex-1 bg-hairline"})]}),te.rows.map(fe=>{U+=1;const J=U;return c.jsx(_se,{id:`${n}-${J}`,option:fe,index:J,isActive:J===_,isHovered:J===y,isPicked:!1,onHover:Se=>S(Se),onPick:(Se,W)=>{w(W),Se.disabled||p(Se.value)}},`${fe.value}-${J}`)})]},te.heading??"all"))})]}),(B!==null||k!==null)&&c.jsxs("div",{"aria-live":"polite","data-header-identity-footer":"","data-header-identity-resolution":oe?"":void 0,className:"border-hairline border-t px-2 py-1.5 text-ink-dim text-meta",children:[k!==null&&c.jsx("span",{className:"block",children:k}),B!==null&&c.jsx("span",{className:"block",children:B})]})]}):c.jsxs(c.Fragment,{children:[z,c.jsx("div",{className:R(Aj,"text-ink-dim"),children:i?c.jsx("span",{"data-header-identity-loading":"",children:h("ui.chat.header_identity.loading",{kind:ie})}):a?c.jsx("span",{className:"text-danger","data-header-identity-error":"",children:a}):c.jsx("span",{children:o})})]})})};function Oet(e){return e?e.locality==="remote"?e.owner_device?`peer:${e.owner_device}`:null:"":null}function Let(e){return typeof e=="string"&&e.startsWith("cold-")}function VK(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:""}}function Bet(){return h("ui.chat.header_identity.no_team")}function jet(){return h("ui.chat.header_identity.no_agent")}const Nk="manager",Het="its manager";function Uet(e){const t=VK(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?Dp(i??{name:s}):Bet(),o=t===null&&e.hostPublishes===!0;let l=null;if((t!==null||o)&&r&&s){const d=i?i.manager||Nk:null,f=t?.speaker??"",g=f!==""&&!(f===r&&d!==r)?f:d;l={speaker:g??Het,speakerKnown:g!==null,team:r,sentence:Det(r,g),title:Iet(a)}}let u=l?l.speaker:e.activeAgent||e.boundAgent||null;return!u&&s&&(u=i?.manager||Nk),{teamValue:s,teamLabel:a,agentValue:u,agentLabel:u??jet(),teamManager:s&&i?i.manager||Nk:null,seat:l}}function Get(e){return!e.hasSession||e.pending||!e.teamCatalogue?!1:e.identityKnown||e.streamLive}function Vet(e){return e.teamOwnsSeat===!0||e.explicitAgent===null||e.manager===null||e.delegate===null?!1:!GK({name:e.explicitAgent,manager:e.manager,delegate:e.delegate})}const Wet=R("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"),$et=R("inline-flex size-3.5 shrink-0 items-center justify-center");function zet(e){return e??""}const Fj=({kind:e,label:t,current:n,busy:s,open:r,onOpenChange:i,onPick:a,sessionId:o,enabled:l,constraint:u,flagged:d,recents:f,swapRef:p,markSwap:g})=>{const v=u?.closed??null,b=E8(o,e,void 0,l&&v===null),x=b.data?.entities??[],_=n!==null,w=_&&t!==n,y=`header-identity-${e}-list`,S=`header-identity-${e}-closed`,C=m.useRef(null),E=m.useRef(v!==null);m.useEffect(()=>{const P=v!==null;if(P&&!E.current&&r){const M=document.activeElement;(M===null||M===document.body||M.closest("[data-header-identity-menu]")!==null)&&C.current?.focus()}E.current=P},[v,r]);const k=m.useRef(!1),F=r&&UK({loading:b.isLoading,loadError:b.isError?R_(b.error):null,rowCount:x.length}),A=m.useMemo(()=>x.map(P=>{const M=Dp({name:P.name??P.value,label:P.label}),Y=u!==null&&!GK({name:P.value,manager:u.manager,delegate:P.delegate,teamOwnsSeat:u.closed!==void 0});return{value:P.value,label:M,description:Y?Net:M!==P.value?P.description?`${P.value} · ${P.description}`:P.value:P.description,meta:P.kind,current:P.value===zet(n),disabled:s||Y,blocked:Y}}),[x,n,s,u]),I=u?.caption??null,N=v!==null?e==="team"?h("ui.chat.header_identity.aria_team_closed",{label:t,reason:v}):h("ui.chat.header_identity.aria_agent_closed",{label:t,reason:v}):_?e==="team"?h("ui.chat.header_identity.aria_team_switch",{label:t}):h("ui.chat.header_identity.aria_agent_switch",{label:t}):e==="team"?h("ui.chat.header_identity.aria_team_assign",{label:t}):h("ui.chat.header_identity.aria_agent_assign",{label:t});return c.jsxs(xh,{open:r,onOpenChange:i,modal:!1,children:[c.jsx(iE,{asChild:!0,children:c.jsxs("button",{ref:C,type:"button","data-header-identity":e,"data-header-identity-closed":v!==null?"":void 0,className:R(Wet,!_&&"text-ink-dim"),"aria-busy":s||void 0,"aria-haspopup":v===null?"listbox":"dialog","aria-controls":v!==null?r?S:void 0:F?y:void 0,onPointerDown:g,"aria-label":`${N}${v===null&&d&&I?`. ${I}`:""}`,title:v!==null?`${t} — ${v}`:d&&I?`${t} — ${I}`:_?`${t}${w?` (${n})`:""}`:e==="team"?h("ui.chat.header_identity.assign_team"):h("ui.chat.header_identity.assign_agent"),children:[e==="team"&&_&&c.jsx(RK,{name:t,slug:n??void 0,showTooltip:!1}),d&&c.jsx(Bo,{"data-header-identity-cue":"","aria-hidden":"true",className:"size-3 shrink-0 text-warning"}),c.jsx("span",{className:R("min-w-0 max-w-[24ch] truncate",w&&"font-sans"),children:t}),c.jsx("span",{className:R($et),children:s?c.jsx(On,{size:"xs"}):v!==null?c.jsx($0,{className:R("size-3 text-ink-dim"),"aria-hidden":"true"}):c.jsx(Ei,{className:R("size-3 text-ink-dim"),"aria-hidden":"true"})})]})}),c.jsx(Met,{kind:e,open:r,listId:y,options:A,recents:f,loading:b.isLoading,loadError:b.isError?R_(b.error):null,emptyText:e==="team"?"No teams are registered.":"No agents are registered.",caption:u?.caption??null,closedReason:v,closedNoteId:S,closedTitle:u?.closedTitle,onPick:P=>{i(!1),a(P)},onClose:()=>{C.current?.focus(),k.current=!0,i(!1)},onCloseAutoFocus:P=>{(p.current||k.current)&&(p.current=!1,k.current=!1,P.preventDefault())}})]})},qet=({sessionId:e,activeAgent:t,activeTeam:n,boundAgent:s,boundTeam:r,effectiveIdentity:i,hostKey:a=null,frameEpoch:o})=>{const l=n||r||null,u=VK(i)!==null;m.useSyncExternalStore(Nb.subscribe,Nb.version),m.useEffect(()=>{u&&i&&Nb.noteFrame(a,i)},[u,a,i]);const d=u||a!==null&&Nb.has(a),f=By(!!l),p=Uet({activeAgent:t,activeTeam:n,boundAgent:s,boundTeam:r,teams:f.data,effectiveIdentity:i,hostPublishes:d,coldFrame:Let(o)}),g=p.seat!==null,v=t||s||null,b=E8(e,"agent",void 0,!!(l&&v)&&!g),x=m.useMemo(()=>v?b.data?.entities.find(M=>M.value===v)?.delegate??null:null,[v,b.data]),_=Vet({explicitAgent:v,manager:p.teamManager,delegate:x,teamOwnsSeat:g}),w=m.useMemo(()=>Pet({teamLabel:p.teamLabel,manager:p.teamManager,closure:p.seat}),[p.teamLabel,p.teamManager,p.seat]),[y,S]=m.useState(null),C=m.useRef(!1),E=m.useCallback(()=>{C.current=!0,window.setTimeout(()=>{C.current=!1},300)},[]),k=T_(e),F=T_(e),A=nt(P=>P.profileRecents),I=nt(P=>P.rememberProfile),N=m.useCallback(async(P,M,Y)=>{if(Y.busy)return;const{result:O}=await Y.run(P,M,P==="team"?"Could not switch the team":"Could not switch the agent");O.tone==="error"?nn(O.text):O.tone==="warning"?Ru(O.text):O.tone==="success"&&I(P,M)},[I]);return c.jsxs("span",{"data-header-identity-controls":"",className:R("flex shrink-0 items-center gap-1"),children:[c.jsx(Fj,{kind:"agent",label:p.agentLabel,current:p.agentValue,busy:F.busy,constraint:w,flagged:_,swapRef:C,markSwap:E,open:y==="agent",onOpenChange:P=>S(P?"agent":null),onPick:P=>void N("agent",P,F),sessionId:e,enabled:y==="agent",recents:A.agent}),c.jsx(Fj,{kind:"team",label:p.teamLabel,current:p.teamValue,busy:k.busy,constraint:null,flagged:!1,swapRef:C,markSwap:E,open:y==="team",onOpenChange:P=>S(P?"team":null),onPick:P=>void N("team",P,k),sessionId:e,enabled:y==="team",recents:A.team})]})},Ket=40,Yet=({agent:e})=>vZe(e.agentId,e.sha256)?c.jsx("span",{className:"me-1 flex shrink-0 items-center",children:c.jsx(FK,{agentName:e.agentName??"",agentId:e.agentId,owned:e.owned&&e.agentName!==null,className:"size-5",pencilClassName:"size-2.5",children:c.jsx(DK,{agentId:e.agentId,sha256:e.sha256,className:"size-5",fallback:null})})}):null,Xet=({agentName:e="Local Operator",agentAvatar:t=null,description:n="Your on-device AI assistant",descriptionPending:s=!1,identity:r,deviceSlot:i,renameSessionId:a,sessionId:o,onOpenOptions:l,reserveTrailingChrome:u=!1,onToggleBrowser:d,archived:f=!1,archiveEnabled:p=!1,onSetArchived:g,deleteEnabled:v=!1,onRequestDelete:b,onOpenConsole:x,onOpenCodeReview:_,onToggleAsks:w,asksScope:y="session",asksOpen:S=!1})=>{Ve();const C=ss(),E=Gr(C.data,"peers"),k=Gr(C.data,"session_transfer"),F=nS(E)??nS(k)??void 0,A=Y0e(nS(E)!==null?E:k),I=Ga(le=>le.requestPicker),[N,P]=m.useState(!1),M=m.useRef(!1),Y=nt(le=>le.setCanvasOpen),O=nt(le=>le.isCanvasOpen),X=nt(le=>le.isCodeReviewPaneOpen),Q=nt(le=>le.transcriptDisplayMode),ie=JI(Q),G=nt(le=>le.setTranscriptDisplayMode),ne=nt(le=>le.setRunPanelOpen),oe=wse(),B=cJ(n,oe),H=B!=="~"&&B!=="",U=nt(le=>le.isBrowserPaneOpen),z=nt(le=>le.isConsolePaneOpen),te=nt(le=>le.isRunPanelOpen),fe=T_(a??""),J=fe.busy,[Se,W]=m.useState(!1),[Ce,K]=m.useState(""),[me,Ee]=m.useState(null),Ae=m.useRef("closed"),se=m.useRef(null),he=m.useRef(null),xe=m.useRef(null),Je=()=>{if(!a||Se)return;const le=he.current?.getBoundingClientRect();Ee(le?Math.ceil(le.width):null),K(e),Ae.current="edit",W(!0)},pe=le=>{Ae.current="closed",le&&xe.current?.focus(),W(!1)},Xe=async le=>{if(Ae.current!=="edit")return;const Qe=Ce.trim();if(!Qe||Qe===e){pe(le);return}Ae.current="saving";const{result:et}=await fe.run("rename",Qe,"Could not rename the conversation");if(et.tone==="error"){nn(et.text),Ae.current==="saving"&&(Ae.current="edit",se.current?.focus());return}et.tone==="warning"&&Ru(et.text),Ae.current==="saving"&&pe(le)};return m.useEffect(()=>{if(!Se)return;const le=se.current;le&&(le.focus(),le.select())},[Se]),c.jsxs("header",{"data-chat-region":"header","data-region-entry":!0,tabIndex:-1,className:R("@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:R("flex h-5 min-w-0 flex-1 items-baseline gap-x-2 overflow-clip @[13.5rem]/chathdr:min-w-10",!r&&"flex-wrap","has-[[data-device-chip]]:[overflow-clip-margin:4px]"),children:[c.jsxs("span",{className:R("group/title inline-flex min-w-0 max-w-full items-center gap-1"),"data-titlebar-no-drag":"",children:[Se?c.jsx("input",{ref:se,"data-header-rename-input":"",className:R("min-w-0 max-w-full border-0 bg-transparent p-0 outline-none","font-medium text-body text-ink"),style:me===null?void 0:{width:me},value:Ce,readOnly:J,"aria-label":h("ui.chat.header.conversation_name"),onChange:le=>K(le.target.value),onKeyDown:le=>{if(le.key==="Enter")le.preventDefault(),Xe(!0);else if(le.key==="Escape"){if(le.preventDefault(),Ae.current==="saving")return;pe(!0)}},onBlur:()=>void Xe(!1),spellCheck:!1}):c.jsxs(c.Fragment,{children:[t?c.jsx(Yet,{agent:t}):null,c.jsx("h2",{ref:he,"data-header-title":"",onDoubleClick:a?Je:void 0,className:R("min-w-0 max-w-full truncate font-medium text-body text-ink","cursor-default select-none"),children:e})]}),a&&c.jsx("button",{ref:xe,type:"button","data-header-rename":"","aria-label":J?h("ui.chat.header.saving_conversation_name"):Se?h("ui.chat.header.cancel_rename"):h("ui.chat.header.rename_conversation"),title:J?h("ui.chat.header.saving_conversation_name"):Se?h("ui.chat.header.cancel_rename"):h("ui.chat.header.rename_conversation"),"aria-busy":J||void 0,"aria-disabled":J||void 0,onMouseDown:le=>{Se&&le.preventDefault()},onClick:le=>{if(!(le.detail>1)&&Ae.current!=="saving"){if(!Se){Je();return}pe(!0)}},className:R("inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-xs","text-ink-dim","transition-opacity duration-base ease-out-quart",!Se&&"opacity-0 group-hover/title:opacity-100 group-hover/title:duration-fast",!Se&&"group-focus-within/title:opacity-100 group-focus-within/title:duration-fast","hover:text-ink-muted"),children:J?c.jsx(On,{size:"xs"}):Se?c.jsx(Xn,{className:R("size-3"),"aria-hidden":"true"}):c.jsx(Vv,{className:R("size-3"),"aria-hidden":"true"})})]}),s?c.jsx(Hx,{className:R("h-3 w-24 shrink-0 bg-elevated")}):r?c.jsx(qet,{...r}):H?c.jsx("span",{"data-header-path":"",className:R("shrink-0 whitespace-nowrap font-mono text-ink-dim text-mono-sm"),title:n,children:uJ(B,Ket)}):null,i]}),c.jsxs("div",{"data-titlebar-no-drag":"",className:"ms-auto flex items-center gap-2",children:[p&&f&&c.jsxs(c.Fragment,{children:[c.jsxs(Lu,{shape:"pill","data-session-archived-pill":!0,title:h("ui.chat.header.archived_hint"),children:[c.jsx(np,{"aria-hidden":"true"}),h("ui.chat.header.archived")]}),g&&c.jsx(ce,{variant:"ghost",size:"icon",onClick:()=>g(!1),"aria-label":C_(e,!0),title:C_(e,!0),children:c.jsx(K_,{"aria-hidden":"true"})})]}),(p||v||w||d||x||l)&&c.jsxs(Po,{open:N,onOpenChange:P,children:[c.jsx(eo,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon","data-conversation-actions":!0,"aria-label":h("ui.chat.header.actions"),children:c.jsx(oc,{"aria-hidden":"true"})})}),c.jsxs(Mo,{align:"end",className:"min-w-45",onCloseAutoFocus:le=>{M.current&&(M.current=!1,o&&I(o),le.preventDefault())},children:[o&&c.jsxs(Jt,{onSelect:()=>void cK(o),children:[c.jsx(ed,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.header.copy_id")})]}),o&&c.jsxs(Jt,{"data-session-move-action":!0,title:F,"data-move-reason":F,"aria-disabled":F?!0:void 0,onSelect:()=>{F||(M.current=!0)},className:R(F&&"cursor-not-allowed data-[highlighted]:bg-transparent data-[highlighted]:text-ink-muted"),children:[c.jsx(Tue,{"aria-hidden":"true"}),c.jsxs("span",{className:"flex min-w-0 flex-col items-start gap-0.5",children:[c.jsx("span",{children:h("ui.chat.header.move_device")}),F?c.jsx("span",{className:R("max-w-[11rem] whitespace-normal text-meta",A==="dim"?"text-ink-dim":"text-warning"),children:F}):null]})]}),c.jsxs(wZ,{children:[c.jsxs(yZ,{children:[c.jsx($ue,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.header.transcript_display")}),c.jsx("span",{className:"text-body-sm text-ink-dim",children:dJ(ie)})]}),c.jsx(CZ,{children:c.jsx(SZ,{value:ie,onValueChange:le=>G(JI(le)),children:hJ.map(le=>c.jsxs(kZ,{value:le.value,children:[c.jsx("span",{children:le.label}),ie===le.value&&c.jsx(Js,{"aria-hidden":"true",className:"ms-auto text-accent"})]},le.value))})})]}),c.jsx(Nr,{}),p&&c.jsxs(Jt,{"data-session-archive-action":!0,onSelect:()=>g?.(!f),disabled:!g,children:[f?c.jsx(K_,{"aria-hidden":"true"}):c.jsx(np,{"aria-hidden":"true"}),c.jsx("span",{children:f?h("ui.chat.header.restore_conversation"):h("ui.chat.header.archive_conversation")})]}),p&&v&&c.jsx(Nr,{}),v&&c.jsxs(Jt,{"data-session-delete":!0,className:"text-danger",onSelect:()=>b?.(),disabled:!b,children:[c.jsx(cg,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.header.delete")})]}),(w||d||x||_||l)&&c.jsx(Nr,{}),(w||d||x||_||l)&&c.jsxs(Jt,{onSelect:()=>ne(!te),children:[c.jsx(ig,{"aria-hidden":"true"}),c.jsx("span",{children:te?h("ui.chat.header.close_run_details"):h("ui.chat.header.open_run_details")})]}),w&&c.jsxs(Jt,{onSelect:()=>w(),children:[c.jsx(qG,{scope:y,"aria-hidden":!0}),c.jsx("span",{children:S?"Close asks":"Open asks"})]}),d&&c.jsxs(Jt,{onSelect:()=>d(),children:[c.jsx(Uu,{"aria-hidden":"true"}),c.jsx("span",{children:U?"Close browser":"Open browser"})]}),x&&c.jsxs(Jt,{onSelect:()=>x(),children:[c.jsx(h2,{"aria-hidden":"true"}),c.jsx("span",{children:z?"Close console":"Open console"})]}),l&&c.jsxs(Jt,{onSelect:()=>Y(!O),children:[c.jsx(Ty,{"aria-hidden":"true"}),c.jsx("span",{children:O?"Close canvas":"Open canvas"})]}),_&&c.jsxs(Jt,{onSelect:()=>_(),children:[c.jsx(kA,{"aria-hidden":"true"}),c.jsx("span",{children:X?"Close code review":"Open code review"})]})]})]})]}),u?c.jsx("div",{className:"chrome-reserve-trailing"}):null]})},Cr=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)}},Rf=({label:e,description:t,defaultValue:n,onSetValue:s,icon:r})=>(Ve(),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:h("ui.agents.settings.chat.not_set_yet")}),c.jsx(ce,{variant:"outline",size:"sm",onClick:async()=>{await s(n)},children:h("ui.agents.settings.chat.set_to_default",{value:String(n)})})]})]})),Dj=({label:e,description:t,defaultDisplayText:n,onSetValue:s,icon:r})=>(Ve(),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:h("ui.agents.settings.chat.not_set_yet")}),c.jsx(ce,{variant:"outline",size:"sm",onClick:async()=>{await s()},children:h("ui.agents.settings.chat.set_to_default",{value:n})})]})]})),Qet=({agent:e,savingField:t,setSavingField:n,setLocalAgent:s,refetchAgent:r,updateAgentMutation:i})=>(Ve(),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:"me-2 flex items-center rounded-sm bg-accent-wash p-1 text-accent",children:c.jsx(Lp,{size:16,"aria-hidden":"true"})}),h("ui.agents.settings.chat.generation_settings"),c.jsx(vt,{content:h("ui.agents.settings.chat.generation_tooltip"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",type:"button",className:"ms-1 text-accent","aria-label":h("ui.common.actions.more_info"),children:c.jsx(ig,{"aria-hidden":"true"})})})]}),c.jsx("p",{className:"mt-1 text-body-sm text-ink-muted",children:h("ui.agents.settings.chat.set_custom_values_note")})]}),e.temperature===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.temperature"),description:h("ui.agents.settings.chat.controls_randomness_in_responses_0_0_1"),defaultValue:.2,onSetValue:async a=>{await Cr("temperature",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.temperature??.2,label:h("ui.agents.settings.chat.temperature"),description:h("ui.agents.settings.chat.controls_randomness_in_responses_0_0_1"),min:0,max:1,step:.01,isSaving:t==="temperature",onChange:async a=>{await Cr("temperature",a,e.id,i,s,r,n)}}),e.top_p===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.top_p"),description:h("ui.agents.settings.chat.controls_cumulative_probability_of_tokens_to_sample"),defaultValue:.9,onSetValue:async a=>{await Cr("top_p",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.top_p??.9,label:h("ui.agents.settings.chat.top_p"),description:h("ui.agents.settings.chat.controls_cumulative_probability_of_tokens_to_sample"),min:0,max:1,step:.01,isSaving:t==="top_p",onChange:async a=>{await Cr("top_p",a,e.id,i,s,r,n)}}),e.top_k===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.top_k"),description:h("ui.agents.settings.chat.limits_tokens_to_sample_from_at_each"),defaultValue:40,onSetValue:async a=>{await Cr("top_k",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.top_k??40,label:h("ui.agents.settings.chat.top_k"),description:h("ui.agents.settings.chat.limits_tokens_to_sample_from_at_each"),min:1,max:100,step:1,isSaving:t==="top_k",onChange:async a=>{await Cr("top_k",a,e.id,i,s,r,n)}}),e.max_tokens===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.max_tokens"),description:h("ui.agents.settings.chat.maximum_tokens_to_generate_in_response"),defaultValue:4096,onSetValue:async a=>{await Cr("max_tokens",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.max_tokens??4096,label:h("ui.agents.settings.chat.max_tokens"),description:h("ui.agents.settings.chat.maximum_tokens_to_generate_in_response"),min:1,max:8192,step:1,isSaving:t==="max_tokens",onChange:async a=>{await Cr("max_tokens",a,e.id,i,s,r,n)}}),e.stop===null?c.jsx(Dj,{label:h("ui.agents.settings.chat.stop_sequences"),description:h("ui.agents.settings.chat.sequences_that_will_cause_the_model_to"),defaultValue:[],defaultDisplayText:"empty",icon:c.jsx(Su,{size:16,className:"me-2.5","aria-hidden":"true"}),onSetValue:async()=>{await Cr("stop",[],e.id,i,s,r,n)}}):c.jsx(OM,{value:e.stop?.join(`
683
+ `).find(r=>r.trim().length>0)??"").trim(),s=48;return n.length>s?`${n.slice(0,s).trimEnd()}…`:n},QB=e=>`Discard draft “${e.startsWith(UR)?e.slice(UR.length):e}”`;function pJe(e,t){const n=e.indexOf(t);return Math.max(n,0)}function gJe(e,t,n=hJe){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:`${UR}${fJe(l)}`,text:l,pending:i.pending===!0})}return s.reverse()}const mJe="click the chat to try again",Om="Click the chat to try again.",uK={pending:"marking read",offscreen:"scroll to the result to mark this chat read",unsettled:mJe,remote:"lives on another device, and it clears when that device updates"},TD={pending:"Marking this chat read.",offscreen:"Scroll to the result to mark this chat read.",unsettled:`Not marked read. ${Om}`,remote:"The unread mark lives on another device. It clears when that device updates."},vJe=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:uK.remote,description:TD.remote}},bJe=(e,t,n)=>!e||e.sessionId!==t?null:e.kind==="remote"?vJe(n):{clause:uK[e.kind],description:TD[e.kind]},xJe=e=>e instanceof Fi?e.code===AQ?"busy":FQ(e.code)?"refused":v5(e)?"remote":"unreachable":"unreported",_Je="The app could not reach the backend.",wJe={busy:()=>`The read state is busy, so the unread mark was not cleared. ${Om}`,refused:()=>`The read state could not be written, so the unread mark was not cleared. ${Om}`,remote:()=>TD.remote,unreachable:e=>`${zi(e,_Je)} The unread mark was not cleared. ${Om}`,unreported:()=>`The unread mark was not cleared. ${Om}`},yJe=e=>wJe[xJe(e.reason)](e.reason);function CJe({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,f=(r||i>0)&&(n||u),p=f&&i>0;return{withdrawn:u,stale:f,showList:l||f,lastKnownRows:p,notice:u&&!a&&!o?g5(e,t)??`Update the backend to use canonical chats. Existing histories are unchanged.${p?" Showing the last chats and teams that loaded.":""}`:null}}const SJe=1,kJe="They may be archived. Search with Include archived.";function EJe(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:kJe,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?ZC:e.total-e.held,r=s<=0?ZC:Math.min(ZC,s);return{state:"rows",sentence:t.error,retry:t.error!==null,more:t.nextCursor!==null,addCount:t.nextCursor===null?0:r,forbidden:!1}}function TJe(e){return!e.pageable||e.searching||e.total===null?e.held:e.total}function kk(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 JB(e){return h("ui.chat.sidebar.groups.badge",{badge:e})}function RJe(e){if(!e.pageable||e.total===null||e.shown>e.total)return null;if(e.searching===!0){const t={shown:e.shown,total:e.total};return e.clipped===!0?h("ui.chat.sidebar.catalogue.total_search_clipped",t):h("ui.chat.sidebar.catalogue.total_search",t)}return h("ui.chat.sidebar.catalogue.total",{shown:e.shown,total:e.total})}function AJe(e){return e<=0?null:e===1?"1 more chat arrived.":`${e} more chats arrived.`}function FJe(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 DJe(e){return!e.pageable||e.error!==null||e.loading||e.nextCursor===null?!1:e.scrollHeight-e.scrollTop-e.clientHeight<=e.clientHeight*SJe}const IJe=e=>{const t=e.map(s=>s.name),n=t.reduce((s,r,i)=>i===0?r:h("ui.chat.sidebar.agents.list_join",{position:t.length===2?"pair":i===t.length-1?"end":"middle",head:s,tail:r}),"");return h("ui.chat.sidebar.agents.builtin_offer",{count:t.length,list:n})},NJe=({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"})]}),ZB="data-session-hover-intent";function PJe(){const e=m.useRef(null),t=m.useRef(null),n=m.useRef(null),s=m.useCallback(()=>{t.current!==null&&(window.clearTimeout(t.current),t.current=null),e.current?.removeAttribute(ZB)},[]),r=m.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(ZB,"")},Dne)},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 m.useEffect(()=>()=>n.current?.(),[]),c.jsx("span",{ref:r,hidden:!0})}const MJe=32,OJe=8e3,ej=12,LJe="(prefers-reduced-motion: reduce)";function BJe({text:e}){const t=m.useRef(null),n=m.useRef(null),s=m.useRef(null),r=m.useRef(null),i=m.useRef(null),[a,o]=m.useState(!1),l=b8(LJe),u=m.useRef(l),d=m.useCallback(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null)},[]),f=m.useCallback(()=>{d();const x=n.current;x&&(x.style.transform="");const _=t.current;_&&(_.style.removeProperty("mask-image"),_.style.removeProperty("-webkit-mask-image")),o(!1)},[d]),p=m.useCallback((x,_,w)=>{const y=Math.max(MJe,w/(OJe/1e3)),S=performance.now(),C=E=>{const k=Math.min(w,(E-S)/1e3*y);_.style.transform=`translateX(${-k}px)`;const F=`linear-gradient(to right, transparent 0, black ${Math.min(ej,k)}px, black calc(100% - ${ej}px), transparent 100%)`;x.style.setProperty("mask-image",F),x.style.setProperty("-webkit-mask-image",F),i.current=k<w?window.requestAnimationFrame(C):null};i.current=window.requestAnimationFrame(C)},[]),g=m.useCallback(()=>{const x=t.current;x&&(x.scrollWidth-x.clientWidth<=.5||(o(!0),i.current=window.requestAnimationFrame(()=>{i.current=null;const _=n.current;if(!_)return;const w=_.getBoundingClientRect().width-x.clientWidth;if(w<=.5){o(!1);return}p(x,_,w)})))},[p]),v=m.useCallback(()=>{f(),!u.current&&(r.current=window.setTimeout(g,mZ))},[f,g]);m.useEffect(()=>{u.current=l,l&&f()},[l,f]),m.useEffect(()=>f,[f]);const b=m.useCallback(x=>{if(t.current=x,s.current?.(),s.current=null,!x)return;const _=x.closest("[data-session-row]")??x.closest("button[data-chat-row]");if(!_)return;const w=()=>v(),y=()=>f();_.addEventListener("pointerenter",w),_.addEventListener("pointerleave",y),s.current=()=>{_.removeEventListener("pointerenter",w),_.removeEventListener("pointerleave",y),f()}},[v,f]);return c.jsx("span",{ref:b,"data-session-title":!0,className:R("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 Ek=e=>h(Lx[e]),Rx=(e,t=!1)=>c.jsx("div",{className:R("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}),Tk=(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:R("flex h-7 w-full items-center gap-2 rounded-md px-1 text-start 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(Js,{"aria-hidden":"true",className:R("size-3.5 shrink-0",!s&&"opacity-0")})]},e);function jJe({view:e,counts:t,onView:n,tagsAvailable:s=!1,autoTagAvailable:r=!1}){Ve();const i=t?u=>(t[u]??0)>0:void 0,a=[{key:"section",label:h("ui.chat.sidebar_view.time_section"),icon:c.jsx(xU,{"aria-hidden":"true",className:"size-3.5"})},{key:"agent",label:h("ui.chat.sidebar_view.agent_team"),icon:c.jsx(yl,{"aria-hidden":"true",className:"size-3.5"})},{key:"flat",label:h("ui.chat.sidebar_view.one_list"),icon:c.jsx(rT,{"aria-hidden":"true",className:"size-3.5"})}],o=[{key:"active",label:h("ui.chat.sidebar_view.last_active"),icon:c.jsx(c2,{"aria-hidden":"true",className:"size-3.5"})},{key:"created",label:h("ui.chat.sidebar_view.created"),icon:c.jsx(Ece,{"aria-hidden":"true",className:"size-3.5"})}],l=[{key:"active-first",label:h("ui.chat.sidebar_view.active_first"),icon:c.jsx(fU,{"aria-hidden":"true",className:"size-3.5"})},{key:"recent",label:h("ui.chat.sidebar_view.most_recent"),icon:c.jsx(Ei,{"aria-hidden":"true",className:"size-3.5"})}];return c.jsxs("div",{"data-sidebar-view-menu":!0,className:"w-full",children:[Rx(h("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:h("ui.chat.sidebar_view.group_by")}),a.map(u=>Tk(u.key,u.icon,u.label,e.groupBy===u.key,()=>n({...e,groupBy:u.key})))]}),Rx(h("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:h("ui.chat.sidebar_view.time_basis")}),o.map(u=>Tk(u.key,u.icon,u.label,e.basis===u.key,()=>n({...e,basis:u.key}),{"data-sidebar-view-basis":u.key}))]}),c.jsx("p",{className:"px-1 pt-0.5 pb-1 text-meta text-ink-dim",children:h("ui.chat.sidebar_view.clock_hint")}),Rx(h("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:h("ui.chat.sidebar_view.order_by")}),l.map(u=>Tk(u.key,u.icon,u.label,e.orderBy===u.key,()=>n({...e,orderBy:u.key})))]}),s&&c.jsxs("div",{className:"border-hairline border-b","data-sidebar-tags-options":!0,children:[c.jsxs("div",{className:"flex h-[39px] items-center gap-2 px-1",children:[c.jsx("label",{htmlFor:"sidebar-tags-switch",className:"flex-1 text-meta text-ink-dim",children:h("ui.chat.tags.group")}),c.jsx(E_,{id:"sidebar-tags-switch","aria-describedby":"sidebar-tags-help",checked:e.tagsEnabled,onCheckedChange:u=>n({...e,tagsEnabled:u})})]}),e.tagsEnabled&&r&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex min-h-7 items-center gap-2 px-1 py-0.5",children:[c.jsx("span",{className:"min-w-0 flex-1 text-meta text-ink-dim",children:h("ui.chat.tags.auto_tag")}),c.jsx(E_,{"data-sidebar-auto-tag":!0,"aria-label":h("ui.chat.tags.auto_tag"),"aria-describedby":"sidebar-auto-tag-help",checked:e.autoTagForks,onCheckedChange:u=>n({...e,autoTagForks:u})})]}),c.jsx("p",{id:"sidebar-auto-tag-help",className:"px-1 pb-1 text-meta text-ink-dim",children:h("ui.chat.tags.auto_tag_help")})]}),c.jsx("span",{id:"sidebar-tags-help",className:"sr-only",children:h("ui.chat.tags.discovery")}),e.groupBy!=="section"&&c.jsxs("div",{className:"px-1 text-meta text-ink-muted",children:[c.jsx("p",{children:h("ui.chat.tags.mode_hint")}),c.jsx(ce,{variant:"ghost",className:"h-7 px-1 text-meta",onClick:()=>n({...e,groupBy:"section"}),children:h("ui.chat.tags.use_time")})]})]}),Rx(h("ui.chat.sidebar_view.sections")),c.jsx("div",{className:"space-y-0.5",children:e.order.map(u=>{const d=bm(e,u);return c.jsxs("div",{className:"flex h-7 items-center gap-1 rounded-md ps-1 text-body-sm",children:[c.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,"data-sidebar-view-section":u,onClick:()=>n(IQ(e,u)),className:R("flex h-7 min-w-0 flex-1 items-center gap-2 text-start",d?"text-ink":"text-ink-muted"),children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:b5(u)?c.jsx(Vm,{"aria-hidden":"true",className:"size-3.5"}):c.jsx(Lp,{"aria-hidden":"true",className:"size-3.5"})}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:Ek(u)}),t?.[u]?c.jsx("span",{className:"shrink-0 font-mono text-ink-dim text-mono-sm",children:t[u]}):null,c.jsx(Js,{"aria-hidden":"true",className:R("size-3.5 shrink-0",!d&&"opacity-0")})]}),DQ(u)&&c.jsxs(c.Fragment,{children:[c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-move":`${u}:up`,"aria-label":h("ui.chat.sidebar_view.move_up",{section:Ek(u)}),disabled:!GI(e,u,-1,i),className:"size-6",onClick:()=>n(UI(e,u,-1)),children:c.jsx(Hv,{"aria-hidden":"true",className:"size-3"})}),c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-move":`${u}:down`,"aria-label":h("ui.chat.sidebar_view.move_down",{section:Ek(u)}),disabled:!GI(e,u,1,i),className:"size-6",onClick:()=>n(UI(e,u,1)),children:c.jsx(Ei,{"aria-hidden":"true",className:"size-3"})})]})]},u)})}),e.hidden.length>0&&c.jsx("p",{className:"mt-2 px-1 text-meta text-ink-dim",children:h("ui.chat.sidebar_view.hidden",{count:e.hidden.length})})]})}class Rk extends Error{}function ty(e,t){const n=Ine(e);if(n==="reserved")return h("ui.chat.tags.name_reserved");if(n==="long"||n==="blank")return h("ui.chat.tags.name_long");const s=e.trim().toLocaleLowerCase();return sc.getState().categories.some(i=>i.id!==t&&i.name.toLocaleLowerCase()===s)?h("ui.chat.tags.duplicate_name",{name:e.trim()}):null}function dK(){const e=sc(a=>a.replaceCategories),[t,n]=m.useState(!1),s=a=>[...a].sort((o,l)=>o.order-l.order).map(({id:o,name:l})=>({id:o,name:l})),r=async a=>{if(t)return{ok:!1,error:h("ui.chat.tags.save_failed"),retryable:!0};n(!0);try{return await e(a),{ok:!0}}catch(o){return{ok:!1,error:o instanceof Rk?o.message:h("ui.chat.tags.save_failed"),retryable:!(o instanceof Rk)}}finally{n(!1)}},i=a=>{throw new Rk(a)};return{pending:t,create:a=>r(o=>{const l=ty(a);return l?i(l):o.length>=My?i(h("ui.chat.tags.registry_limit")):[...s(o),{name:a.trim()}]}),rename:(a,o)=>r(l=>{const u=s(l),d=u.find(p=>p.id===a);if(!d)return i(h("ui.chat.tags.registry_changed"));if(d.name===o.trim())return null;const f=ty(o,a);return f?i(f):u.map(p=>p.id===a?{...p,name:o.trim()}:p)}),move:(a,o,l)=>r(u=>{const d=Nne(u,a,o,l);return d||i(h("ui.chat.tags.registry_changed"))}),remove:a=>r(o=>{const l=s(o);return l.some(u=>u.id===a)?l.filter(u=>u.id!==a):i(h("ui.chat.tags.registry_changed"))})}}const GR="data-chat-tag-header";function HJe(e){return e.metaKey||e.ctrlKey?null:e.key==="F2"&&!e.altKey&&!e.shiftKey?"rename":e.altKey&&!e.shiftKey&&e.key==="ArrowUp"?"up":e.altKey&&!e.shiftKey&&e.key==="ArrowDown"?"down":e.key==="ContextMenu"||e.shiftKey&&e.key==="F10"?"menu":null}function hK({initial:e,label:t,placeholder:n,error:s,errorId:r,busy:i,keepOpen:a,renameId:o,onCommit:l,onCancel:u}){const[d,f]=m.useState(e),p=m.useRef(null),g=m.useRef(!1);m.useEffect(()=>{p.current?.focus(),p.current?.select()},[]);const v=async()=>{if(i)return;await l(d)&&a&&(f(""),p.current?.focus())};return c.jsx(bs,{ref:p,inputSize:"sm","aria-label":t,placeholder:n,"aria-invalid":s!==null,"aria-describedby":s?r:void 0,"aria-busy":i,readOnly:i,value:d,className:R("min-w-0 flex-1",i&&"text-ink-dim"),onChange:b=>f(b.target.value),onKeyDown:b=>{b.stopPropagation(),!(b.nativeEvent.isComposing||b.keyCode===229)&&(b.key==="Enter"?(b.preventDefault(),v()):b.key==="Escape"&&(b.preventDefault(),g.current=!0,u(!0)))},onBlur:()=>{if(!(g.current||i)){if(a){u(!1);return}!d.trim()||d.trim()===e.trim()||ty(d,o)?u():l(d,!1).then(b=>{b||p.current?.focus({preventScroll:!0})})}}})}function fK({id:e,message:t,onRetry:n}){return c.jsxs("div",{id:e,role:"alert",className:"flex min-h-6 items-center gap-2 px-2 text-meta text-danger",children:[c.jsx("span",{className:"min-w-0 flex-1",children:t}),n&&c.jsx(ce,{variant:"ghost",className:"h-6 px-1 text-meta",onClick:n,children:h("ui.chat.tags.retry")})]})}function pK({id:e,name:t,count:n,above:s,below:r,announce:i,unused:a=!1}){Ve();const o=dK(),[l,u]=m.useState(!1),[d,f]=m.useState(!1),[p,g]=m.useState(!1),[v,b]=m.useState(null),[x,_]=m.useState(null),w=m.useId(),y=m.useRef(null),S=m.useRef(null),C=m.useRef(null),E=e!=="untagged",k=e==="untagged"?h("ui.chat.tags.untagged"):t,F=m.useRef(null);m.useEffect(()=>()=>{F.current!==null&&cancelAnimationFrame(F.current)},[]);const A=()=>{F.current!==null&&cancelAnimationFrame(F.current),F.current=requestAnimationFrame(()=>{const Q=y.current?.isConnected?y.current:document.querySelector(`[${GR}="${CSS.escape(r??s??e)}"], [data-tag-new]`);F.current=null,Q?.focus({preventScroll:!0})})},I=(Q,ie,G)=>Q.ok?(b(null),_(null),i(ie),!0):(b(Q.error),_(()=>Q.retryable?G:null),!1),N=async Q=>{const ie=Q==="up"?s:r;if(!ie||o.pending){i(h(Q==="up"?"ui.chat.tags.header_first":"ui.chat.tags.header_last",{name:k}));return}const G=await o.move(e,ie,Q);I(G,h("ui.chat.tags.moved_tag",{name:k}),()=>void N(Q))&&A()},P=async()=>{const Q=await o.remove(e);g(!1),I(Q,h("ui.chat.tag_dialogs.deleted_name",{name:k}),()=>void P())&&A()},M=()=>{const Q=sc.getState().categories.find(ie=>ie.id===e);if(!Q){b(h("ui.chat.tags.registry_changed"));return}Q.conversations===0?P():g(!0)},Y=async(Q,ie=!0)=>{const G=await o.rename(e,Q),ne=I(G,h("ui.chat.tags.renamed_name",{name:Q.trim()}),()=>void Y(Q));return ne&&(u(!1),ie&&A()),ne},O=Q=>{if(!E)return;const ie=HJe(Q);if(ie===null){["ArrowUp","ArrowDown","Home","End"].includes(Q.key)&&Q.preventDefault();return}Q.preventDefault(),Q.stopPropagation(),ie==="rename"?u(!0):ie==="menu"?f(!0):N(ie)},X=sc(Q=>Q.categories.find(ie=>ie.id===e)?.conversations)??n;return c.jsxs("div",{ref:C,"aria-busy":o.pending,children:[c.jsxs("div",{"data-tag-drop-target":e,...a?{"data-tag-unused-slot":""}:{},className:"group/header relative flex h-7 items-center gap-2 px-2 text-meta text-ink-dim hover:bg-row-hover",onContextMenu:Q=>{E&&(Q.preventDefault(),f(!0))},children:[l?c.jsx(hK,{initial:t,renameId:e,label:h("ui.chat.tags.rename_label",{name:t}),error:v,errorId:w,busy:o.pending,onCommit:Y,onCancel:Q=>{u(!1),b(null),Q&&A()}}):c.jsx("span",{className:"min-w-0 flex-1 truncate",title:k,onDoubleClick:()=>E&&u(!0),children:k}),c.jsx("span",{className:"shrink-0",children:n}),E&&!l&&c.jsx(Po,{open:d,onOpenChange:f,children:c.jsxs(xh,{open:p,onOpenChange:g,children:[c.jsx(by,{asChild:!0,children:c.jsx(eo,{asChild:!0,children:c.jsx("button",{ref:y,type:"button",tabIndex:-1,[GR]:e,"aria-label":h("ui.chat.tags.header_actions",{name:k}),title:h("ui.chat.tags.header_actions",{name:k}),onKeyDown:O,className:R("absolute end-2 flex size-6 shrink-0 items-center justify-center rounded-sm text-ink-dim opacity-0 hover:bg-row-hover hover:text-ink","group-hover/header:static group-hover/header:opacity-100 group-focus-within/header:static group-focus-within/header:opacity-100 focus-visible:outline-2 focus-visible:outline-accent",(d||p)&&"static opacity-100"),children:c.jsx(oc,{"aria-hidden":"true",className:"size-4"})})})}),c.jsxs(Mo,{align:"end",className:"min-w-44",onCloseAutoFocus:Q=>{(l||p)&&Q.preventDefault()},children:[c.jsxs(Jt,{onSelect:()=>u(!0),children:[c.jsx(Vv,{"aria-hidden":"true"}),h("ui.chat.tags.rename")]}),c.jsxs(c.Fragment,{children:[c.jsxs(Jt,{"aria-disabled":!s,className:"aria-disabled:text-ink-muted!",onSelect:()=>void N("up"),children:[c.jsx(pce,{"aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 truncate",children:h("ui.chat.tags.move_up",{name:k})})]}),c.jsxs(Jt,{"aria-disabled":!r,className:"aria-disabled:text-ink-muted!",onSelect:()=>void N("down"),children:[c.jsx(Pne,{"aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 truncate",children:h("ui.chat.tags.move_down",{name:k})})]})]}),c.jsx(Nr,{}),c.jsxs(Jt,{destructive:!0,onSelect:M,children:[c.jsx(cg,{"aria-hidden":"true"}),h("ui.chat.tags.delete")]})]}),c.jsxs(Bu,{role:"alertdialog",align:"end",className:"w-64 space-y-2 p-3","aria-labelledby":`${w}-title`,"aria-describedby":`${w}-description`,onOpenAutoFocus:Q=>{Q.preventDefault(),S.current?.focus()},onCloseAutoFocus:Q=>{Q.preventDefault(),A()},onKeyDown:Q=>{Q.key==="Escape"&&Q.stopPropagation()},children:[c.jsx("p",{id:`${w}-title`,className:"text-body-sm text-ink",children:h("ui.chat.tags.delete_title",{name:k})}),c.jsx("p",{id:`${w}-description`,className:"text-meta text-ink-dim",children:h("ui.chat.tags.delete_description",{count:X})}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx(ce,{"data-tag-delete-cancel":!0,ref:S,variant:"ghost",className:"h-7 px-2 text-meta",onClick:()=>g(!1),children:h("ui.chat.tags.cancel")}),c.jsx(ce,{variant:"ghost",className:"h-7 px-2 text-meta text-danger hover:bg-danger-wash",disabled:o.pending,onClick:()=>void P(),children:h("ui.chat.tags.delete_tag")})]})]})]})})]}),v&&c.jsx(fK,{id:w,message:v,onRetry:x??void 0})]})}function UJe({unused:e,total:t,dragArmed:n,announce:s,chord:r}){Ve();const i=dK(),[a,o]=m.useState(!1),[l,u]=m.useState(!1),[d,f]=m.useState(null),p=m.useId(),g=l||n,v=m.useId(),b=async _=>{const w=await i.create(_);return w.ok?(f(null),u(!0),s(h("ui.chat.tags.created_name",{name:_.trim()})),!0):(f(w.error),!1)},x=t>=My?c.jsx("p",{className:"flex h-7 items-center px-2 text-meta text-ink-dim",children:h("ui.chat.tags.registry_limit")}):a?c.jsx("div",{className:"flex h-7 items-center gap-2 px-1",children:c.jsx(hK,{initial:"",label:h("ui.chat.tags.new_name"),placeholder:h("ui.chat.tags.name_placeholder"),error:d,errorId:p,busy:i.pending,keepOpen:!0,onCommit:b,onCancel:_=>{o(!1),f(null),_&&requestAnimationFrame(()=>document.querySelector("[data-tag-new]")?.focus())}})}):c.jsxs("button",{type:"button","data-tag-new":!0,className:"flex h-7 w-full items-center gap-2 rounded-md px-2 text-start text-meta text-ink-dim hover:bg-row-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-accent",onClick:()=>o(!0),children:[c.jsx(Cl,{"aria-hidden":"true",className:"size-3.5"}),h("ui.chat.tags.new_tag")]});return c.jsxs("div",{"data-chat-tag-footer":!0,className:"mt-2 border-hairline border-t pt-1",children:[t===0&&c.jsxs("div",{"data-chat-tag-empty":!0,className:"px-2 py-1 text-meta",children:[c.jsx("p",{className:"text-ink",children:h("ui.chat.tags.empty_title")}),c.jsx("p",{className:"text-ink-dim",children:h("ui.chat.tags.empty_hint",{chord:r})})]}),x,d&&c.jsx(fK,{id:p,message:d}),e.length>0&&c.jsxs(c.Fragment,{children:[c.jsxs("button",{type:"button","aria-expanded":g,"aria-controls":v,className:"flex h-7 w-full items-center gap-1 rounded-md px-2 text-start text-meta text-ink-dim hover:bg-row-hover hover:text-ink focus-visible:outline-2 focus-visible:outline-accent",onClick:()=>u(_=>!_),children:[c.jsx(Vi,{"aria-hidden":"true",className:R("size-3.5 shrink-0",g&&"rotate-90")}),h("ui.chat.tags.unused",{count:String(e.length)})]}),c.jsx("div",{id:v,hidden:!g,"data-chat-tag-unused":!0,children:e.map(_=>c.jsx("div",{"data-chat-tag-group":_.id,children:c.jsx(pK,{id:_.id,name:_.name,count:0,above:e[e.indexOf(_)-1]?.id??null,below:e[e.indexOf(_)+1]?.id??null,announce:s,unused:!0})},_.id))})]})]})}function GJe({categories:e,selected:t,primary:n,query:s,setQuery:r,disabled:i,unready:a,input:o,toggle:l,showUnder:u,create:d,createIssue:f}){const p=m.useId(),[g,v]=m.useState(-1),b=m.useRef(null),x=s.trim(),_=a?[]:Mne(e,s),w=_.some(O=>O.name.trim().toLowerCase()===x.toLowerCase()),y=e.length>=My,S=!a&&x!==""&&!w&&!y,C=_.length+(S?1:0),E=C?Math.min(g,C-1):-1,k=O=>`${p}-${O}`,F=t.length>=fE,A=t.length>=2;m.useEffect(()=>{v(s.trim()?0:-1)},[s]),m.useEffect(()=>{E>=0&&b.current?.children[E]?.scrollIntoView?.({block:"nearest"})},[E]);const I=O=>i||a||!t.includes(O)&&F,N=O=>{I(O)||(l(O),r(""),v(-1),o.current?.focus({preventScroll:!0}))},P=O=>{I(O)||(u(O),r(""),v(-1),o.current?.focus({preventScroll:!0}))},M=()=>{i||a||f||d()},Y=(O,X)=>{if(O<_.length){const Q=_[O].id;X?P(Q):N(Q)}else S&&M()};return c.jsxs(c.Fragment,{children:[c.jsx(bs,{ref:o,role:"combobox","aria-label":h("ui.chat.tags.search"),"aria-autocomplete":"list","aria-expanded":!a,"aria-controls":p,"aria-activedescendant":E>=0?k(E):void 0,placeholder:h("ui.chat.tags.search"),value:s,readOnly:i||a,className:"h-8",onChange:O=>r(O.target.value),onKeyDown:O=>{O.nativeEvent.isComposing||O.nativeEvent.keyCode===229||(O.key==="ArrowDown"||O.key==="ArrowUp"?(O.preventDefault(),v(One(E,O.key==="ArrowDown"?1:-1,C))):O.key==="Home"||O.key==="End"?(O.preventDefault(),v(C?O.key==="Home"?0:C-1:-1)):O.key==="Enter"&&(O.preventDefault(),E>=0&&Y(E,O.shiftKey)))}}),!a&&x&&!_.length&&c.jsx("p",{className:"px-2 py-1 text-meta text-ink-dim",children:h("ui.chat.tags.no_matches",{query:x})}),c.jsxs("div",{ref:b,id:p,role:"listbox",tabIndex:-1,"aria-label":h("ui.chat.tags.label"),"aria-multiselectable":"true",hidden:a||C===0,className:"mt-1 min-h-0 max-h-56 overflow-y-auto",children:[_.map((O,X)=>{const Q=t.includes(O.id),ie=E===X,G=I(O.id),ne=A&&Q&&O.id!==n&&!i;return c.jsxs("div",{id:k(X),role:"option","aria-selected":Q,"aria-disabled":G,tabIndex:-1,title:O.name,className:R("group/option flex h-8 cursor-default items-center gap-2 rounded-sm px-2 text-body-sm",G?"text-ink-muted":"text-ink",!G&&"hover:bg-row-hover",ie&&"bg-accent-wash"),onMouseDown:oe=>oe.preventDefault(),onMouseEnter:()=>v(X),onClick:()=>N(O.id),children:[c.jsx("span",{className:"flex size-4 shrink-0 items-center",children:Q&&c.jsx(Js,{"aria-hidden":"true",className:"size-4"})}),c.jsx("bdi",{className:"min-w-0 flex-1 truncate",children:O.name}),ne&&c.jsx("span",{"data-tag-show-under":!0,className:R("shrink-0 rounded-sm px-1 text-meta text-ink-dim hover:text-ink",ie?"inline":"hidden group-hover/option:inline"),onClick:oe=>{oe.stopPropagation(),P(O.id)},children:h("ui.chat.tags.show_under")})]},O.id)}),S&&c.jsxs("div",{id:k(_.length),role:"option","aria-selected":!1,"aria-disabled":i||f!==null,tabIndex:-1,"data-tag-create":!0,className:R("flex min-h-8 cursor-default items-center gap-2 rounded-sm px-2 py-1 text-body-sm",f?"text-ink-muted":"text-ink hover:bg-row-hover",E===_.length&&"bg-accent-wash"),onMouseDown:O=>O.preventDefault(),onMouseEnter:()=>v(_.length),onClick:M,children:[c.jsx(Cl,{"aria-hidden":"true",className:"size-4 shrink-0"}),c.jsxs("span",{className:"flex min-w-0 flex-col",children:[c.jsx("bdi",{className:"truncate",children:h("ui.chat.tags.create_name",{name:x})}),c.jsx("span",{className:"text-meta text-ink-dim",children:f??h("ui.chat.tags.create_helper")})]})]})]}),!a&&x&&!w&&y&&c.jsx("p",{className:"px-2 py-1 text-meta text-ink-muted",children:h("ui.chat.tags.registry_limit")}),!a&&!x&&C===0&&c.jsx("p",{className:"px-2 py-2 text-body-sm text-ink-muted",children:x?h("ui.chat.tags.no_matches",{query:x}):h("ui.chat.tags.empty")})]})}function VJe({row:e,onClose:t,returnFocus:n,grouped:s,onShowGroups:r}){Ve();const{categories:i,loading:a,loadError:o,fetchCategories:l,selected:u,primary:d,pending:f,error:p,notice:g,toggle:v,showUnder:b,createAndAssign:x}=Lne({sessionId:e.session_id,tags:e.tags,primary:e.primary??null,revision:e.tags_revision??null}),[_,w]=m.useState(""),y=m.useRef(null),S=m.useRef(!0),C=m.useRef(new DOMRect),E=m.useRef({getBoundingClientRect:()=>{const N=document.querySelector(`[data-session-row="${CSS.escape(e.session_id)}"]`);return N&&(C.current=N.getBoundingClientRect()),C.current}}),k=a||o!==null,F=i.length>=My?h("ui.chat.tags.registry_limit"):u.length>=fE?h("ui.chat.tags.selection_limit"):_.trim()?ty(_):null,A=async()=>{f||F||k||!await x(_.trim())||(w(""),y.current?.focus({preventScroll:!0}))},I=i.find(N=>N.id===d)?.name;return c.jsxs(xh,{open:!0,onOpenChange:N=>{!N&&!f&&t()},children:[c.jsx(by,{virtualRef:E}),c.jsxs(Bu,{"data-chat-tag-popover":!0,role:"region",side:"right",align:"start",sideOffset:2,collisionPadding:8,"aria-label":h("ui.chat.tags.label"),className:"flex max-h-[min(360px,var(--radix-popover-content-available-height))] w-auto min-w-56 max-w-[280px] flex-col p-1",onOpenAutoFocus:N=>{N.preventDefault(),y.current?.focus({preventScroll:!0})},onCloseAutoFocus:N=>{N.preventDefault(),S.current&&n()},onInteractOutside:N=>{f?N.preventDefault():S.current=!1},onEscapeKeyDown:N=>{N.preventDefault(),!N.isComposing&&N.keyCode!==229&&!f&&t()},onKeyDown:N=>{N.key==="Escape"&&N.stopPropagation(),N.key==="Tab"&&!f&&(N.preventDefault(),t())},children:[c.jsx(GJe,{categories:i,selected:u,primary:d,query:_,setQuery:w,disabled:f,unready:k,input:y,toggle:N=>void v(N),showUnder:N=>void b(N),create:()=>void A(),createIssue:F}),a?c.jsx("output",{className:"flex h-24 items-center px-2 text-body-sm text-ink-muted",children:h("ui.chat.tags.loading")}):null,o&&c.jsxs("div",{role:"alert",className:"space-y-1 px-2 py-2 text-body-sm",children:[c.jsx("p",{children:h("ui.chat.tags.load_failed")}),c.jsx(ce,{variant:"ghost",className:"h-7 px-1 text-meta",onClick:()=>void l(),children:h("ui.chat.tags.retry")})]}),p&&c.jsx("p",{role:"alert",className:"px-2 py-1 text-meta text-danger",children:p}),!k&&u.length>=fE&&c.jsx("p",{className:"px-2 py-1 text-meta text-ink-muted",children:h("ui.chat.tags.selection_limit")}),!k&&c.jsxs("div",{className:"mt-1 flex min-h-7 items-center gap-2 border-hairline border-t px-2 pt-1 text-meta text-ink-dim",children:[s?c.jsx("span",{className:"min-w-0 flex-1 truncate",children:I?h("ui.chat.tags.shown_under",{tag:I}):h("ui.chat.tags.shown_untagged")}):c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"min-w-0 flex-1",children:h("ui.chat.tags.hidden")}),c.jsx(ce,{variant:"ghost",className:"h-6 px-1 text-meta",onClick:r,children:h("ui.chat.tags.show_groups")})]}),c.jsx("span",{children:h("ui.chat.tags.selection_count",{count:String(u.length)})})]}),c.jsx("output",{"aria-live":"polite",className:"sr-only",children:g})]})]})}function RD(e,t){switch(e?.split("/")[0]){case"unsupported-precondition":return h("ui.hub.status.unsupported");case"baseline-unknown":return h("ui.hub.status.baseline_unknown");case"alias-occupied":return h("ui.hub.skills.local_exists");case"mixed-lineage":case"origin-conflict":return h("ui.hub.status.mixed_lineage");case"no-credential":return h("ui.hub.status.no_credential");case"access-lost":case"unauthorized":case"forbidden":return h("ui.hub.status.access_lost");case"provider-error":return h("ui.hub.status.provider_error");case"model-unavailable":return h("ui.hub.status.model_unavailable");case"merge-refused":case"concurrent-edit":case"local-concurrent-edit":case"remote-revision-changed":return h("ui.hub.status.conflict");case"prompt-too-long":case"skill-too-large":return h("ui.hub.status.too_large");case"skill-validation":return h("ui.hub.status.skill_validation");case"unsafe-publication":return h("ui.hub.status.unsafe_publication");case"hub-error":case"transport":return h("ui.hub.status.transport_error");default:return t??h("ui.hub.status.other_error")}}function WJe(e){const t=e.safe_message?.trim();return t?h("ui.hub.links.incoming_failed_reason",{reason:t}):RD(e.error_class,h("ui.hub.links.incoming_failed_no_reason"))}function fdt(e){switch(e){case"would-merge":return h("ui.hub.links.outcome_would_merge");case"needs-review":return h("ui.hub.links.outcome_needs_review");case"up-to-date":return h("ui.hub.links.outcome_up_to_date");case"unchanged":return h("ui.hub.links.outcome_unchanged");case"failed":return h("ui.hub.links.outcome_failed");case"skipped":return h("ui.hub.links.outcome_skipped");case"unavailable":return h("ui.hub.links.outcome_unavailable");default:return e}}function pdt(e){switch(e.state){case"idle":return h(e.last_checked_at?"ui.hub.status.idle":"ui.hub.status.not_checked");case"checking":return h("ui.hub.status.checking");case"available":return h("ui.hub.status.available");case"merging":return h("ui.hub.status.merging");case"applying":return h("ui.hub.status.applying");case"pushing":return h("ui.hub.status.pushing");case"retry-wait":return h("ui.hub.status.retry_wait");case"needs-review":return h("ui.hub.status.needs_review");case"failed":return h("ui.hub.status.failed");case"missing":return h("ui.hub.status.missing");default:return h("ui.hub.status.other_error")}}function gdt(e,t){return e==="check"?h("ui.hub.links.check_failed",{item:t.item,source:t.source}):h("ui.hub.links.action_failed",{direction:t.direction,item:t.item,source:t.source})}const $Je=/lop login radient/i;function zJe(e){if(!(e instanceof Error))return!1;const t=e.status;return(t===401||t===403)&&$Je.test(e.message)}function tj(e,t,n){return n&&e instanceof n?e.message:zJe(e)?h("ui.hub.links.sign_in_required"):t}function ld(){return crypto.randomUUID()}async function mdt(e=1,t=20,n){const s={page:e,per_page:t};if(n)for(const[r,i]of Object.entries(n))i&&(s[r]=i);return Di({operation:"agents.list",query:s})}async function vdt(e){return Di({operation:"agents.get",agentId:e})}async function bdt(e){return Di({operation:"agents.delete",agentId:e,requestId:ld(),confirmed:!0})}async function xdt(e){return Di({operation:"agents.like",agentId:e,requestId:ld()})}async function _dt(e){return Di({operation:"agents.unlike",agentId:e,requestId:ld(),confirmed:!0})}async function wdt(e){return Di({operation:"agents.favourite",agentId:e,requestId:ld()})}async function ydt(e){return Di({operation:"agents.unfavourite",agentId:e,requestId:ld(),confirmed:!0})}async function Cdt(e,t){return Di({operation:"comments.create",agentId:e,payload:t,requestId:ld()})}async function Sdt(e,t=1,n=20){return Di({operation:"comments.list",agentId:e,query:{page:t,per_page:n}})}async function kdt(e,t,n){return Di({operation:"comments.update",agentId:e,commentId:t,payload:n,requestId:ld()})}async function Edt(e,t){return Di({operation:"comments.delete",agentId:e,commentId:t,requestId:ld(),confirmed:!0})}async function Tdt(e){return Di({operation:"agents.statuses",query:{agent_ids:e.join(",")}})}async function qJe(){return Di({operation:"memberships.list"})}async function Rdt(e,t=1,n=20,s){const r={page:t,per_page:n};if(s)for(const[i,a]of Object.entries(s))a&&(r[i]=a);return Di({operation:"org_agents.list",tenantId:e,query:r})}async function Adt(e){return Di({operation:"org_teams.list",tenantId:e})}class Ax extends Error{status;reason;constructor(t,n,s){super(t),this.name="PublicHubError",this.status=n,this.reason=s}}const KJe=/\/+$/,YJe=(e,t,n)=>{const s=e.replace(KJe,"");return n?`${s}/v1/${t}/${encodeURIComponent(n)}`:`${s}/v1/${t}`},gK=(e,t)=>YJe(e,"teams",t),mK=async e=>{let t;try{t=await fetch(e,{method:"GET",headers:{Accept:"application/json"},redirect:"error"})}catch(s){throw console.error("The public hub could not be reached:",s),new Ax(h("ui.common.errors.public_hub_unreachable"),null,s)}if(!t.ok)throw new Ax(h("ui.common.errors.public_hub_status",{status:t.status}),t.status);let n;try{n=await t.json()}catch{throw new Ax(h("ui.common.errors.public_hub_json"),t.status)}if(!n||typeof n!="object"||!("result"in n))throw new Ax(h("ui.common.errors.public_hub_body"),t.status);return n};async function Fdt(e,t=1,n=12){const s=`${gK(e)}?page=${t}&per_page=${n}`;return mK(s)}async function Ddt(e,t){return mK(gK(e,t))}const XJe={all:["memberships"],account:e=>["memberships","account",e??"unresolved-owner"]},vK=({enabled:e=!0}={})=>{const{isAuthenticated:t}=Oy(),n=Mt(),{accountId:s}=ug(),r=Dn({queryKey:XJe.account(s),queryFn:async()=>(await x8(n,s,()=>qJe())).result??{memberships:[]},enabled:e&&t&&!!s,staleTime:5*60*1e3,gcTime:10*60*1e3,refetchOnWindowFocus:!1,retry:Mv});return{...r,memberships:r.data?.memberships??[]}};function QJe(e,t=[]){if(e.visibility==="public")return h("ui.hub.links.source_label_public");const n=t.find(s=>s.tenant_id===e.tenant_id&&s.status==="active")?.tenant_name;return n?h("ui.hub.links.source_label_org",{organization:n}):null}function bK(e,t=!0){const{isAuthenticated:n}=Oy(),{accountId:s}=ug(),r=n&&!!s,i=vK({enabled:t&&e.visibility==="org"&&r}),a=r&&i.isSuccess&&!i.isFetching&&!i.isPlaceholderData?i.memberships:[],o=a.find(l=>l.tenant_id===e.tenant_id&&l.status==="active")?.tenant_name;return{source:QJe(e,a),organization:o,memberships:i,mayReadMemberships:r}}const xK=new Set(["needs-review","missing","blocked"]),_K=new Set(["checking","merging","applying","pushing"]),JJe=new Set(["idle","available","retry-wait","failed","applied","published",...xK,..._K]);function wK(e){const t=["pull","push"];for(const n of t){const s=e[n];if(!JJe.has(s.state)||xK.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(_K.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 AD(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 ZJe(e){const{unavailable:t}=AD(e);return e.policy.auto_push?!e.eligibility.can_auto_push||t?"paused":"none":t?"unavailable":"none"}function eZe(e){return e.visibility==="public"?h("ui.hub.links.source_public"):e.tenant_name?h("ui.hub.links.source_private",{organization:e.tenant_name}):h("ui.hub.links.source_unavailable")}function tZe(e){return!e||e.split("/")[0]==="unsupported-precondition"?h("ui.hub.subscriptions.auto_push_unverified"):RD(e)}function yK({link:e,onConsentChange:t,item:n,source:s}){Ve();const r=JXe(),i=m.useId(),a=m.useRef(null),o=bK(e,s===void 0),l=s!==void 0?s:o.source,u=o.organization,d=n?.trim()?n:e.name,[f,p]=m.useState("subscribe"),[g,v]=m.useState(null);m.useEffect(()=>{g&&(g.linkId!==e.link_id||g.revision!==e.policy.revision||g.source!==l)&&(t?.(!1),v(null))},[e.link_id,e.policy.revision,l,g,t]);const b=()=>{t?.(!1),v(null)},x=(E,k)=>{r.isPending||(p(k),r.mutate({link:e,patch:E},{onSuccess:b}))},{unavailable:_}=AD(e),w=_||l===null,y=l===null?"unavailable":ZJe(e),S=l===null?h("ui.hub.subscriptions.auto_push_source_unknown"):tZe(e.eligibility.reason),C=h(f==="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:[r.upgradeMessage&&c.jsx("output",{className:"block text-meta text-warning","data-hub-core-upgrade":!0,children:r.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:`${i}-subscribe`,className:"text-body-sm text-ink",children:h("ui.hub.subscriptions.subscribe")}),c.jsx("p",{className:"text-meta text-ink-muted",children:l?h(r.canWrite?"ui.hub.subscriptions.subscribe_description":"ui.hub.subscriptions.subscribe_description_blocked",{source:l}):h(r.canWrite?"ui.hub.subscriptions.subscribe_description_unsourced":"ui.hub.subscriptions.subscribe_description_blocked_unsourced")})]}),c.jsx(E_,{id:`${i}-subscribe`,checked:e.policy.subscribe,disabled:r.isPending||!r.canWrite,"aria-label":l?`${h("ui.hub.subscriptions.subscribe")}: ${l}`:h("ui.hub.subscriptions.subscribe"),onCheckedChange:E=>x({subscribe:E},"subscribe")})]}),!e.policy.subscribe&&r.canWrite&&c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.hub.subscriptions.manual_available")}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("label",{htmlFor:`${i}-push`,className:"text-body-sm text-ink",children:h("ui.hub.subscriptions.auto_push")}),c.jsx("p",{className:"text-meta text-ink-muted",children:l?h("ui.hub.subscriptions.auto_push_description",{source:l}):h("ui.hub.subscriptions.auto_push_description_unsourced")})]}),c.jsx("span",{className:"inline-flex shrink-0","data-hub-auto-push-reason":y!=="none"?"":void 0,title:y==="unavailable"?S:void 0,children:c.jsx(E_,{id:`${i}-push`,"aria-describedby":y!=="none"?`${i}-push-line`:void 0,checked:e.policy.auto_push,disabled:r.isPending||!r.canWrite||!e.policy.auto_push&&w,"aria-label":l?`${h("ui.hub.subscriptions.auto_push")}: ${l}`:h("ui.hub.subscriptions.auto_push"),onCheckedChange:E=>{E?!w&&l&&(t?.(!0),v({linkId:e.link_id,revision:e.policy.revision,source:l})):x({auto_push:!1},"auto_push")}})})]}),y!=="none"&&c.jsx("p",{id:`${i}-push-line`,className:R("text-meta",y==="paused"?"text-warning":"text-ink-muted"),children:y==="paused"?h("ui.hub.subscriptions.effective_paused",{reason:S}):S})]}),r.isPending&&c.jsx("output",{className:"text-meta text-ink-muted",children:l?h("ui.hub.subscriptions.saving",{setting:C,source:l}):h("ui.hub.subscriptions.saving_unsourced",{setting:C})}),r.error&&c.jsx("p",{role:"alert",className:"text-meta text-danger",children:r.error instanceof gh?r.error.message:r.error instanceof Fi&&r.error.code==="policy-revision-changed"?h("ui.hub.subscriptions.policy_changed"):l?h("ui.hub.subscriptions.save_failed",{setting:C,source:l}):h("ui.hub.subscriptions.save_failed_unsourced",{setting:C})}),c.jsx(Tc,{open:g!==null&&l!==null,onOpenChange:E=>{!E&&!r.isPending&&b()},children:c.jsxs(Rc,{onOpenAutoFocus:E=>{E.preventDefault(),a.current?.focus()},closeDisabled:r.isPending,onEscapeKeyDown:E=>{r.isPending&&E.preventDefault()},children:[c.jsxs(my,{children:[c.jsx(wl,{children:h("ui.hub.subscriptions.enable_title",{source:l??""})}),c.jsx(Zu,{children:e.visibility==="public"?h("ui.hub.subscriptions.enable_public",{item:d}):h("ui.hub.subscriptions.enable_private",{item:d,organization:u??l??""})})]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("ui.hub.subscriptions.enable_safety")}),r.upgradeMessage&&c.jsx("p",{role:"alert",className:"text-body-sm text-warning","data-hub-core-upgrade":!0,children:r.upgradeMessage}),r.error&&c.jsx("p",{role:"alert",className:"text-body-sm text-danger",children:h("ui.hub.subscriptions.save_failed",{setting:C,source:l??""})}),c.jsxs(vy,{children:[c.jsx(ce,{ref:a,variant:"outline",disabled:r.isPending,onClick:b,children:h("ui.hub.subscriptions.cancel")}),c.jsx(ce,{disabled:r.isPending||!r.canWrite||w||g?.linkId!==e.link_id||g?.revision!==e.policy.revision||g?.source!==l,onClick:()=>x({auto_push:!0,...e.visibility==="public"?{confirm_public_egress:!0}:{}},"auto_push"),children:h("ui.hub.subscriptions.enable")})]})]})})]})}const nZe=new Set(["provider-error","model-unavailable","prompt-too-long","concurrent-edit","local-concurrent-edit","remote-revision-changed","hub-error"]);function nj(e,t,n,s){return{state:e.state,effective:t,reason:n,retryable:e.error_class!==null&&nZe.has(e.error_class.split("/")[0]),canApply:s,lastSuccess:e.last_success_at,modelUsed:e.model_used,operationId:e.operation_id}}function CK(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:!AD(e).unavailable&&t.visibility!=="unavailable",autoPushUnavailableReason:e.eligibility.reason,canEditPolicy:!0,pull:nj(e.pull,e.auto_will_apply,null,tQe(e.baseline_state)&&e.pull.classification==="remote-only"),push:nj(e.push,e.auto_will_push,e.eligibility.reason,!1)}}const SK={healthy:_U,review:rg,available:BA,failed:Bo,busy:ri,applied:Js},kK={healthy:"text-ink-dim",review:"text-warning",available:"text-accent",failed:"text-danger",busy:"text-ink-dim",applied:"text-success"},sZe=8;function rZe({link:e,staged:t,onDetail:n,itemName:s,displayName:r,itemsById:i=!1,nameAmbiguous:a=!0}){Ve();const o=Mt(),l=eQe(e,{displayName:s,itemsById:i}),[u,d]=m.useState(!1),[f,p]=m.useState(!1),g=m.useRef(null),v=m.useId(),b=m.useId(),x=m.useId(),_=m.useId(),w=m.useId(),y=r?.trim()?r:e.name,{source:S,memberships:C,mayReadMemberships:E}=bK(e),k=!i&&(a||!s?.trim()),F=wK(CK(e)),A=l.isPending?ri:SK[F.kind],I=h(F.direction==="pull"?"ui.hub.links.direction_pull":"ui.hub.links.direction_push"),N=G=>h(G?"ui.hub.subscriptions.configured_on":"ui.hub.subscriptions.configured_off"),P=S?h("ui.hub.links.healthy",{item:y,source:S,subscribe:N(e.policy.subscribe),autoPush:N(e.policy.auto_push)}):h("ui.hub.links.healthy_unsourced",{item:y,subscribe:N(e.policy.subscribe),autoPush:N(e.policy.auto_push)}),M=F.kind==="available"?S?h("ui.hub.links.available",{item:y,source:S}):h("ui.hub.links.available_unsourced",{item:y}):F.kind==="failed"?S?h("ui.hub.links.failed",{direction:I,item:y,source:S}):h("ui.hub.links.failed_unsourced",{direction:I,item:y}):F.kind==="busy"?S?h("ui.hub.links.busy",{direction:I,item:y,source:S}):h("ui.hub.links.busy_unsourced",{direction:I,item:y}):F.kind==="applied"?F.direction==="pull"?S?h("ui.hub.links.updated",{item:y,source:S}):h("ui.hub.links.updated_unsourced",{item:y}):S?h("ui.hub.links.published",{item:y,source:S}):h("ui.hub.links.published_unsourced",{item:y}):P,Y=e.pull.state==="failed"||e.pull.state==="retry-wait"&&e.pull.error_class!==null,O=()=>{if(k||!l.canWrite||l.isPending){d(!0);return}l.mutate({action:"retry",linkId:e.link_id,direction:"pull"},{onError:()=>d(!0)})},X=l.error!==null&&l.variables?.action==="retry",Q=()=>{E&&C.refetch(),o.invalidateQueries({queryKey:Xu})},ie=`${M} ${P}${e.policy.auto_push&&e.eligibility.reason?` ${h("ui.hub.subscriptions.effective_paused",{reason:RD(e.eligibility.reason)})}`:""}`;return c.jsxs(xh,{open:u,onOpenChange:G=>{(G||!f)&&d(G)},children:[c.jsx(vt,{content:ie,side:"top",disableHoverableContent:!0,children:c.jsx(by,{asChild:!0,children:c.jsxs("button",{ref:g,type:"button","data-hub-mark":l.isPending?"busy":F.kind,"data-testid":`hub-mark-${e.kind}-${e.name}`,"aria-label":M,"aria-disabled":(!l.canWrite||k)&&(F.action==="apply"||F.action==="retry")||void 0,"aria-describedby":b,"aria-haspopup":"dialog","aria-expanded":u,className:R("flex size-6 shrink-0 items-center justify-center rounded-md",kK[F.kind],!t&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),onContextMenu:G=>{G.preventDefault(),G.stopPropagation(),d(!0)},onKeyDown:G=>{(G.key==="ContextMenu"||G.shiftKey&&G.key==="F10")&&(G.preventDefault(),G.stopPropagation(),d(!0))},onClick:G=>{if(G.stopPropagation(),l.isPending||F.action==="policy"||(!l.canWrite||k)&&(F.action==="apply"||F.action==="retry")){d(!0);return}if(F.action==="detail"){n();return}if(F.action==="retry"&&F.direction==="pull"){O();return}l.mutate(F.action==="apply"?{action:"apply",linkId:e.link_id}:{action:"retry",linkId:e.link_id,direction:F.direction},{onError:()=>d(!0)})},children:[c.jsx("span",{id:b,className:"sr-only",children:ie}),c.jsx(A,{"aria-hidden":"true",className:R("size-3.5",(l.isPending||F.kind==="busy")&&"motion-safe:animate-spin")})]})})}),c.jsxs(Bu,{side:"right",align:"start",avoidCollisions:!0,collisionPadding:sZe,"aria-labelledby":v,"data-hub-link-popover":e.link_id,className:"max-h-[var(--radix-popover-content-available-height)] max-w-[min(20rem,var(--radix-popover-content-available-width))] overflow-y-auto",onInteractOutside:G=>{f&&G.preventDefault()},onCloseAutoFocus:G=>{G.preventDefault(),g.current?.focus()},children:[c.jsx("h4",{id:v,className:"break-words text-heading text-ink",children:h("ui.hub.links.policy_title",{item:y})}),S?c.jsx("p",{className:"mb-3 break-words text-meta text-ink-muted","data-hub-link-source":"",children:S}):c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3","data-hub-link-source-unresolved":"",children:[c.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[c.jsx("p",{id:x,className:"text-meta text-ink-muted",children:h("ui.hub.links.source_unresolved")}),!E&&c.jsx("p",{id:_,className:"text-meta text-ink-muted",children:h("ui.hub.links.sign_in_required")})]}),c.jsx(ce,{variant:"outline",size:"sm",disabled:C.isFetching||!E,"aria-describedby":E?x:`${x} ${_}`,onClick:Q,children:h(C.isFetching?"ui.hub.links.retrying":"ui.hub.links.retry")})]}),k&&c.jsxs("output",{"data-hub-legacy-blocked":"",className:"mb-3 text-meta text-warning",children:[a&&c.jsx("span",{className:"block",children:h("ui.hub.links.name_ambiguous")}),(!s?.trim()||a)&&h("ui.hub.links.legacy_retry_unverified")]}),Y&&c.jsxs("div",{className:"mb-3 flex flex-col gap-2 rounded-md border border-hairline bg-sunken p-3","data-hub-link-incoming-failed":"",children:[c.jsx("p",{id:w,className:"text-body-sm text-warning",children:h("ui.hub.links.incoming_update_failed")}),c.jsx("p",{className:"text-meta text-ink-muted",children:WJe(e.pull)}),X&&c.jsx("p",{role:"alert",className:"text-meta text-danger",children:tj(l.error,h("ui.hub.links.retry_failed"),gh)}),c.jsx("div",{children:c.jsx(ce,{variant:"outline",size:"sm",disabled:l.isPending||!l.canWrite||k,"aria-describedby":w,onClick:O,children:h(l.isPending?"ui.hub.links.retrying":"ui.hub.links.retry_update")})})]}),c.jsx(yK,{link:e,item:y,source:S,onConsentChange:p},e.link_id),l.error&&!X&&c.jsx("p",{role:"alert",className:"mt-3 text-meta text-danger",children:tj(l.error,S?h("ui.hub.links.action_failed",{direction:I,item:y,source:S}):h("ui.hub.links.action_failed_unsourced",{direction:I,item:y}),gh)})]})]})}function iZe({item:e,staged:t,onResolve:n}){Ve();const s=h("ui.hub.links.unresolved_mark",{item:e});return c.jsx(vt,{content:s,side:"top",disableHoverableContent:!0,children:c.jsx("button",{type:"button","data-hub-mark":"unresolved","data-testid":"hub-mark-unresolved","aria-label":s,className:R("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(N0,{"aria-hidden":"true",className:"size-3.5"})})})}function aZe({link:e}){return Ve(),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:eZe(e)}),c.jsx(yK,{link:e})]})}function oZe({links:e,staged:t,onDetail:n}){Ve();const s={healthy:0,applied:1,available:2,busy:3,failed:4,review:5},i=e.map(u=>wK(CK(u))).reduce((u,d)=>s[d.kind]>s[u]?d.kind:u,"healthy"),a=SK[i]??_U,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=h("ui.hub.links.aggregate_mark",{count:e.length,state:h(o[i]??"ui.hub.links.mark_healthy")});return c.jsx(vt,{content:l,side:"top",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:R("relative flex size-6 shrink-0 items-center justify-center rounded-md",kK[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 lZe=2,EK={available:BA,review:rg,failed:Bo,updating:ri,applied:Js},TK={available:"text-accent",review:"text-warning",failed:"text-danger",updating:"text-ink-dim",applied:"text-success"};function Idt({mark:e,className:t}){const n=EK[e.kind];return c.jsx(n,{"aria-hidden":"true",className:R("size-3.5 shrink-0",TK[e.kind],t)})}function cZe({item:e,mark:t,busy:n,blocked:s=!1,staged:r,onPress:i}){const a=m.useId(),o=n?{kind:"updating"}:t,l=o.kind,u=EK[l],d=HXe(e,o),f=BXe(o),p=s||l==="updating"||l==="applied";return c.jsx(vt,{content:f?`${d} ${f}`:d,side:"top",align:"center",disableHoverableContent:!0,children:c.jsxs("button",{type:"button","data-hub-mark":l,"data-testid":`hub-mark-${e.kind}-${e.name}`,className:R("flex size-6 shrink-0 items-center justify-center rounded-md",TK[l],!r&&!p&&"hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1"),"aria-label":LXe(e.name,o),"aria-describedby":a,"aria-disabled":p||void 0,onClick:()=>{p||i()},children:[c.jsx(u,{className:R("size-3.5",l==="updating"&&"motion-safe:animate-spin"),"aria-hidden":"true"}),c.jsx("span",{id:a,className:"sr-only",children:f?`${d} ${f}`:d})]})})}function uZe({note:e}){return c.jsx("p",{role:e.tone==="error"?"alert":"status",className:R("pb-1 pl-13 pr-2 text-meta",e.tone==="error"?"text-danger":"text-ink-muted"),children:e.message})}function dZe({kind:e,available:t,busy:n,blocked:s=!1,onUpdateAll:r,onCheck:i,checking:a}){Ve();const o=t>=lZe;return!o&&!i?null:c.jsxs(c.Fragment,{children:[o&&c.jsx("button",{type:"button","data-testid":`hub-update-all-${e}`,"aria-label":h("ui.chat.hub_update.update_all_label",{count:t,kind:e==="team"?"teams":e==="skill"?"skills":"agents"}),"aria-disabled":n||s||void 0,className:R("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?h("ui.chat.hub_update.updating"):h("ui.chat.hub_update.update_all",{count:t})}),i&&c.jsx(vt,{content:h("ui.chat.hub_update.check_now"),side:"top",children:c.jsx("button",{type:"button","data-testid":"hub-check-now","aria-label":h("ui.chat.hub_update.check_now"),"aria-disabled":a||s||void 0,className:R("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(Wy,{className:R("size-3.5",a&&"motion-safe:animate-spin"),"aria-hidden":"true"})})})]})}function hZe({kind:e,reserve:t,signIn:n,signInHref:s,rollup:r,note:i,onDismissRollup:a}){return Ve(),!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(B5,{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":h("ui.chat.hub_update.dismiss_summary"),className:"shrink-0 rounded-sm px-1 hover:text-ink",onClick:a,children:h("ui.chat.hub_update.dismiss")})]})]})}const fZe=/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;function pZe(e){const t=e.split(fZe).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 RK=({name:e,imageUrl:t,slug:n,showTooltip:s=!0,onActivate:r,className:i})=>{const a=pZe(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:R(vZ({variant:"attentionQuiet",shape:"pill",size:"count"}),i),children:c.jsxs(F5,{className:"h-4 w-fit",children:[t?c.jsx(xy,{src:t,alt:"",className:"size-4"}):null,c.jsx(_y,{className:"h-full w-auto bg-transparent font-normal text-inherit text-meta-sm",children:a})]})});return s?c.jsx(vt,{content:c.jsx("span",{"aria-hidden":"true",children:e}),children:o}):o},AK=e=>{const n=e.getBoundingClientRect().top+e.clientTop;return{top:n,bottom:n+e.clientHeight}},VR=(e,t)=>{const n=AK(t),s=e.getBoundingClientRect();return s.bottom<=n.top||s.top>=n.bottom?"outside":s.top>=n.top&&s.bottom<=n.bottom?"inside":"partly"},gZe=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)},sj=(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=VR(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=AK(e),u=s.getBoundingClientRect(),d=u.top-l.top,f=l.bottom-u.bottom,p=gZe(s);e.scrollTop=Math.min(Math.max(e.scrollTop+(d<0?d-p:-f+p),0),e.scrollHeight-e.clientHeight),t.current={node:s,index:r,visibility:VR(s,e),clipHeight:e.clientHeight}},rj=(e,t)=>{const n=t.current.node;!e||!n||!n.isConnected||!e.contains(n)||n===document.activeElement&&(t.current={...t.current,visibility:VR(n,e),clipHeight:e.clientHeight})};function mZe(e){const t=new URLSearchParams({kind:"agent",name:e.agentName,edit:"picture"});return e.agentId&&t.set("agent",e.agentId),`/agents?${t}`}function FK({agentName:e,agentId:t,owned:n,editHref:s,children:r,className:i,pencilClassName:a="size-2",linkProps:o,overlay:l=!1}){const u=oi();if(!n)return c.jsx("span",{className:R("relative inline-flex shrink-0",i),children:r});const d=s??mZe({agentName:e,agentId:t}),f=h("ui.agents.avatar.edit_link",{name:e});return c.jsxs("a",{href:`#${d}`,"aria-label":f,title:f,"data-agent-avatar-edit":"",onClick:p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.button||(p.preventDefault(),p.stopPropagation(),u(d))},className:R("group/avatar-edit relative inline-flex shrink-0 rounded-full",l&&"pointer-events-none opacity-0 group-hover/row:pointer-events-auto group-hover/row:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-1",i,o?.className),style:o?.style,children:[r,c.jsx("span",{"aria-hidden":"true",className:R("pointer-events-none absolute inset-0 flex items-center justify-center rounded-full bg-scrim opacity-0","transition-opacity duration-fast ease-out-quart","group-hover/avatar-edit:opacity-100 group-focus-visible/avatar-edit:opacity-100"),children:c.jsx("span",{className:"flex items-center justify-center rounded-full bg-accent p-px text-on-accent",children:c.jsx(Vv,{className:a,strokeWidth:2.5})})})]})}function DK({agentId:e,sha256:t,className:n,fallback:s,src:r,glyph:i=null,onPresence:a}){const o=Ly(r===void 0?e:null,t),l=r===void 0?o:r,u=!!l;return m.useEffect(()=>{a?.(u)},[a,u]),l?c.jsxs(bA,{className:R("shrink-0",n),"data-agent-mark":"",children:[c.jsx(xy,{src:l,alt:""}),c.jsx(_y,{children:i})]}):c.jsx(c.Fragment,{children:s})}function vZe(e,t){return Ly(e,t)!==null}const bZe=new Set(["idle","recent"]);function xZe({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":`${Hne(n)} outstanding. The agent is not blocked on you.`,className:R("inline-flex shrink-0 items-center gap-0.5"),children:[c.jsx(I0,{"aria-hidden":"true",size:14,className:R("text-accent")}),c.jsx("span",{className:R("tabular-nums text-ink-muted text-xs"),children:n})]})}function _Ze({className:e,mark:t}){return c.jsx("span",{"aria-hidden":"true","data-subagent-mark":t,className:R("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 wZe(e,t,n){return`${n.linkDown?tE(e,t):n.uncertainLabel??e.status?.label??"Recent"}${n.unreadMark!==null?", unread":""}`}function yZe(e){const t=e.status?.code,n=e.locality==="remote"&&e.link_down===!0,s=n&&e.link_reconnecting===!0,r=Bx(e),i=!r&&!n&&t==="delegating",o=lK(e).queued&&!HR(e.subagents_running),l=dy(e),u=l==="complete",d=r?N0:n?Mde:t==="waiting"?Bne:t==="busy"?ri:t==="approval"||t==="answer"?I0:t==="error"?rg:t==="wedged"?Lce:t==="interrupted"||t==="dormant"?Fue:t==="complete"?u?Js:hN:t==="scheduled"?jne:t==="attached"?u2:bZe.has(t??"recent")?hN:N0;return{code:t,linkDown:n,reconnecting:s,uncertainLabel:r,delegating:i,queuedOnly:o,unreadMark:l,Icon:d,ink:r?"text-ink-dim":n?s?"text-ink-dim":"text-warning":t==="waiting"?"text-accent":t==="busy"?"text-accent motion-safe:animate-spin":t==="wedged"?"text-warning":t==="error"?"text-danger":t==="approval"||t==="answer"||t==="interrupted"?"text-warning":u?"text-success":t==="delegating"?"text-accent":"text-ink-dim"}}function WR({row:e,nowSeconds:t=Date.now()/1e3}){const n=yZe(e),{Icon:s,ink:r,delegating:i,queuedOnly:a}=n;return c.jsxs("span",{className:"flex size-4 shrink-0",children:[i?a?c.jsx(Cde,{"aria-hidden":"true","data-subagent-mark":"queued",className:"size-4 text-ink-muted"}):c.jsx(_Ze,{className:R("size-4",r),mark:"running"}):c.jsx(s,{className:R("size-4",r),"aria-hidden":"true"}),c.jsx("span",{className:"sr-only",children:wZe(e,t,n)})]})}const CZe="beside",Rv="size-4";function SZe({row:e,nowSeconds:t}){const n=e.agent_id??null,s=e.avatar_sha256??null;return!n||!s?c.jsx(WR,{row:e,nowSeconds:t}):c.jsxs("span",{"data-session-mark":"avatar","data-avatar-variant":CZe,className:R("relative flex shrink-0 items-center gap-1.5"),children:[c.jsxs("span",{className:R("relative flex shrink-0",Rv),children:[c.jsx(DK,{agentId:n,sha256:s,className:R(Rv,"rounded-full"),fallback:c.jsx(kZe,{}),glyph:c.jsx(yl,{className:"size-2.5","aria-hidden":"true"})}),null]}),c.jsx(WR,{row:e,nowSeconds:t})]})}function kZe(){return c.jsx(bA,{"aria-hidden":"true",className:R(Rv,"rounded-full"),"data-agent-mark":"",children:c.jsx(_y,{children:c.jsx(yl,{className:"size-2.5","aria-hidden":"true"})})})}function ij({row:e,className:t}){const n=_8(e);if(!n?.owned||!n.agentName)return null;const{agentId:s,agentName:r,owned:i}=n;return c.jsx(FK,{agentName:r,agentId:s,owned:i,overlay:!0,linkProps:{className:"before:absolute before:-inset-1 before:content-['']"},className:R(Rv,"absolute start-1 top-1/2 -translate-y-1/2",t),children:c.jsx("span",{"aria-hidden":"true",className:R(Rv,"block")})})}const EZe="chat-sidebar-entities",TZe="chat-sidebar-chats",dm="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",Ak="group/row relative flex h-8 items-center gap-1 rounded-md",RZe="@max-[253px]/chatheading:sr-only",aj="read-ack",oj="Sending - this draft can be discarded when the send settles",lj=e=>`draft-discard-why-${e}`,cj="Drafts are sending - they can be cleared when the sends settle",uj="drafts-clear-all-why",yo="bg-row-selected font-medium text-ink hover:bg-row-selected",IK="bg-row-selected text-ink hover:bg-row-selected hover:text-ink",NK="outline outline-1 outline-offset-[-1px] outline-ink-dim",AZe=5e3,FZe=3e4,dj="chat-search-include-archived",hj="/stop if it stays silent.",fj=e=>`chat-row-remedy-${e}`,pj=e=>`chat-row-read-ack-${e}`,gj=()=>navigator.platform.toUpperCase().indexOf("MAC")>=0,DZe=({id:e,openMenuRowIdRef:t,setOpenMenuRowId:n,openedByKeyboard:s})=>(m.useEffect(()=>()=>{t.current===e&&(n(null),s.current=!1)},[e,t,n,s]),null),IZe=({agentId:e,glyph:t})=>{const n=Ly(e);return n===null?c.jsx(t,{className:"size-4 shrink-0"}):c.jsx(bA,{className:"size-4 shrink-0",children:c.jsx(xy,{src:n,alt:""})})},NZe=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.",mj=e=>`chat-row-menu-${e}`,vj=(e,t)=>{document.querySelector(`[data-session-row="${CSS.escape(e)}"]`)?.querySelector(`[${sse[t]}]`)?.click()},PZe=8;function MZe({selectedConversation:e,onSelectConversation:t,onStageDraft:n}){Ve();const s=oi(),r=fA(),i=Au(D=>D.requestPanel),a=ss(),o=jA(),l=HA(),u=m.useMemo(()=>l.rows===null?null:Une(l.rows),[l.rows]),d=Fe(D=>D.sessions),f=Fe(D=>D.error),p=Gr(a.data,"session_catalogue",2),g=p==="enabled",v=Gr(a.data,"peers")==="enabled",b=Qy(v,{poll:!1}),x=m.useMemo(()=>nJe(b.data),[b.data]),{data:_}=og(),w=A2(_?.online===!1),y=_?.snapshot&&!_.snapshot.pairing.available?_.snapshot.pairing.cause??"unpaired":null,S=dA(a.data,y),C=m.useRef(null),E=Et(a.data,"session_pins"),k=Et(a.data,"session_catalogue_page"),F=Fe(D=>D.setCataloguePageable);m.useEffect(()=>{F(k)},[k,F]);const A=Et(a.data,"session_catalogue_sort"),I=Fe(D=>D.setCatalogueActivityHead);m.useEffect(()=>{I(A)},[A,I]);const N=Fe(D=>D.scopes),P=Fe(D=>D.head),M=Fe(D=>D.counts),Y=Fe(D=>D.fetchScopePage),O=Fe(D=>D.clearScope),X=Fe(D=>D.fetchCatalogueTail),Q=m.useRef(null),ie=m.useRef(null),G=Fe(D=>D.pinFailure),ne=Fe(D=>D.pinFacts),oe=m.useMemo(()=>{const D={};for(const[ve,Ge]of Object.entries(ne))D[ve]=Ge.pinned;return D},[ne]),B=Fe(D=>D.setSessionPin),H=m.useRef(!1);g&&(H.current=!0);const{stale:U,showList:z,notice:te}=CJe({state:p,cause:y,failed:!!a.error,answered:!!a.data,wasReady:H.current,rows:d.length,storeFailed:!!f,coveredByCompatibilityBanner:S}),fe=w8(g&&Et(a.data,"profile_catalogue")),J=(fe.data??[]).filter(D=>D.source!=="builtin"),Se=(fe.data??[]).filter(D=>D.source==="builtin"),W=!fe.isLoading&&J.length===0,Ce=nt(D=>D.dismissedBuiltinOfferSignature),K=nt(D=>D.dismissBuiltinOffer),me=vXe(Se),Ee=bXe(Ce,me),Ae=W&&Se.length>0&&!Ee,se=W&&Se.length>0&&Ee,[he,xe]=m.useState(!1),Je=m.useRef(!1),pe=m.useRef(null);m.useEffect(()=>{!Je.current||Ae||(Je.current=!1,pe.current?.focus())},[Ae]);const Xe=By(g&&Et(a.data,"team_catalogue")),le=Et(a.data,"session_tags"),Qe=Gne(a.data),et=sc(D=>D.categories),ue=sc(D=>D.loading),Le=sc(D=>D.error),Ne=sc(D=>D.fetchCategories),[Ue,dt]=m.useState(null),St=m.useRef(null);m.useEffect(()=>{g&&le&&Ne()},[g,le,Ne]);const Dt=()=>{requestAnimationFrame(()=>{const D=St.current;if(!D)return;const ve=document.querySelector(`[data-session-row="${CSS.escape(D)}"] [data-chat-row]`);ve?.focus(),ve?.scrollIntoView({block:"nearest"})})},sn=D=>{St.current=D.session_id,dt(D)},Kt=m.useMemo(()=>new Map((Xe.data??[]).map(D=>[D.name,Dp(D)])),[Xe.data]),ut=m.useMemo(()=>D=>Kt.get(D)??D,[Kt]),Ft=m.useMemo(()=>({agent:GB(fe.data),team:GB(Xe.data)}),[fe.data,Xe.data]),At=KXe(g&&Et(a.data,"hub_updates")),cn=NXe(At.data),rn=Et(a.data,"hub_links"),kn=Et(a.data,"hub_items_by_id"),ws=QXe(g&&rn),Vt=XXe(),cs=(At.data?.items.length??0)>0||Object.values(At.data?.counts??{}).some(D=>D>0),Vn=Fe(D=>D.fetchSessions),zr=Fe(D=>D.loading),ls=Fe(D=>D.truncated),Vs=Fe(D=>D.statusUnavailable).includes("liveness"),un=Fe(D=>D.activeDraftKey),It=Fe(D=>D.drafts),dn=Fe(D=>D.openDraft),tr=Fe(D=>D.discardDraft),Sn=Fe(D=>D.discardDrafts),Ie=Ua(D=>D.inputByConversation),ge=Fe(D=>D.markAllRead),Pe=Fe(D=>D.readAckNotice),L=m.useRef(Pe?`${Pe.sessionId}:${Pe.revision}`:null);m.useEffect(()=>{const D=Pe?`${Pe.sessionId}:${Pe.revision}`:null,ve=L.current!==D;if(L.current=D,Pe?.kind!=="unsettled"){Ux(aj);return}ve&&Ru(yJe(Pe),{id:aj,duration:nH})},[Pe]);const[V,j]=m.useState(""),[q,Z]=m.useState(!1),ee=q||V.length>0,_e=m.useRef(null),[Re,ye]=m.useState(""),[Te,ae]=m.useState(()=>Date.now());m.useEffect(()=>{const D=window.setInterval(()=>ae(Date.now()),6e4);return()=>window.clearInterval(D)},[]);const we=nt(D=>D.chatSidebarView),De=nt(D=>D.setChatSidebarView),$e=nt(D=>D.openCommandPalette),ke=nt(D=>D.setCommandPaletteQuery),[tt,ht]=m.useState(!1),[Ot,Ut]=m.useState(!1),[en,yn]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("chat-sidebar-disclosures")??"{}")}catch{return{}}}),wn=m.useRef(null),Ps=m.useRef(null),ys=(D,ve,Ge,st="pin",lt=!0)=>{const bt=Array.from(wn.current?.querySelectorAll("[data-session-row]")??[]),Cn=bt.findIndex(es=>es.getAttribute("data-session-row")===D);if(Cn<0){Ps.current=null;return}const rs=bt[Cn+1]??bt[Cn-1]??null;Ps.current={id:D,top:bt[Cn].getBoundingClientRect().top,follow:ve,pointer:Ge,caret:st,scroll:lt,anchorId:rs?.getAttribute("data-session-row")??null,anchorTop:rs?rs.getBoundingClientRect().top:0}};m.useEffect(()=>{const D=Ps.current,ve=wn.current;if(!D||!ve)return;const Ge=ve.querySelector(`[data-session-row="${D.id}"]`);if(!Ge){Ps.current=null;return}if(D.follow){if(D.scroll){const es=Ge.getBoundingClientRect().top-D.top;es!==0&&(ve.scrollTop+=es)}const st=ve.getBoundingClientRect(),lt=Ge.getBoundingClientRect();lt.top<st.top?ve.scrollTop-=st.top-lt.top:lt.bottom>st.bottom&&(ve.scrollTop+=lt.bottom-st.bottom);const bt=Ge.querySelector("[data-session-pin]"),Cn=Ge.querySelector("[data-chat-row]");(D.caret==="row"?Cn:bt!==null&&bt.getBoundingClientRect().width>0?bt:Cn)?.focus({preventScroll:!0})}else if(D.anchorId!==null&&D.scroll){const st=ve.querySelector(`[data-session-row="${D.anchorId}"]`);if(st){const lt=st.getBoundingClientRect().top-D.anchorTop;lt!==0&&(ve.scrollTop+=lt)}}Ps.current=null});const Ts=m.useRef(null),an=6,ba=(D,ve)=>{const Ge=Ts.current;return D===null?!1:Ge!==null&&Math.hypot(D.x-Ge.x,D.y-Ge.y)<=an&&Ge.sessionId!==ve?!0:(Ts.current={...D,sessionId:ve},!1)},fi=(D,ve=!1)=>en[D]??ve,Ms=k&&V.trim().length===0,Ii=m.useCallback(D=>{for(const[ve,Ge]of Object.entries(N)){if(!Ge.ids.includes(D))continue;const[st,...lt]=ve.split(":"),bt=lt.join(":");return st==="agent"?{agent:bt,team:null}:{agent:null,team:bt}}},[N]),co=(D,ve=!1)=>{const Ge=ZQ(en,Mg,D,ve,!!V);yn(Ge.expanded),yI(Ge.caps)},Yi=Uae(d),Nl=Fe(D=>D.raiseBulkReadDeferral),[Oe,kt]=m.useState(!1),jt=Yi.count>0&&!V.trim()&&Et(a.data,"completion_ack_bulk"),pi=async()=>{kt(!0);try{const{tone:D,message:ve}=Gae(await ge());D==="success"?Hs(ve):Ru(ve)}catch(D){v5(D)?Nl(Yi.count):Ru(h("ui.notices.chat.unread_not_cleared",{reason:zi(D,h("ui.notices.chat.unread_backend_silent"))}))}finally{kt(!1)}},xa=m.useRef(jt);m.useEffect(()=>{if(xa.current&&!jt){const D=document.activeElement;(D===null||D===document.body)&&wn.current?.querySelector('[data-sidebar-region="chats"] [data-chat-row]')?.focus()}xa.current=jt},[jt]);const Ws=jt?c.jsxs(ce,{size:"sm",variant:"ghost","data-chat-row":!0,"data-tour-tag":"mark-all-read","aria-disabled":Oe||void 0,title:Yi.scope,onClick:()=>{Oe||pi()},className:"shrink-0 text-ink-dim hover:bg-row-hover",children:[Oe?c.jsx(ri,{className:"text-ink-disabled motion-safe:animate-spin","aria-hidden":"true"}):c.jsx(Fce,{"aria-hidden":"true"}),c.jsx("span",{className:R("truncate",RZe),children:Yi.label}),Yi.nameSuffix?c.jsx("span",{className:"sr-only",children:Yi.nameSuffix}):null]}):null;m.useEffect(()=>{localStorage.setItem("chat-sidebar-disclosures",JSON.stringify(en))},[en]);const Cs=m.useCallback(()=>Vn(k?x5:fy,k),[Vn,k]);m.useEffect(()=>{if(!g)return;if(Cs(),!o.available){const Ge=window.setInterval(()=>{document.visibilityState==="visible"&&Cs()},AZe);return()=>window.clearInterval(Ge)}const D=window.setInterval(()=>{Cs()},FZe),ve=()=>void Cs();return window.addEventListener("focus",ve),()=>{window.clearInterval(D),window.removeEventListener("focus",ve)}},[g,Cs,o.available,o.catalogueRevision,o.activityRevision]),m.useEffect(()=>{if(!(!g||!Ms))for(const[D,ve]of Object.entries(en)){const Ge=D.startsWith("team:")?"team":D.startsWith("agent:")?"agent":null;if(Ge===null)continue;const st=D.slice(Ge.length+1);if(st.length!==0){if(ve){N[D]===void 0&&Y(Ge,st,null);continue}N[D]!==void 0&&O(Ge,st)}}},[en,g,Ms,N,Y,O]);const uo=Et(a.data,"session_search"),hr=Et(a.data,"session_archive"),[_a,hd]=m.useState(!1),gi=NQ(_a,V,hr),Wo=Fe(D=>D.archiveFacts),sf=Fe(D=>D.forgotten),wa=Fe(D=>D.setStagedByDiscard),mi=Fe(D=>D.setSessionArchived),jc=Fe(D=>D.requestArchiveConfirm),fd=m.useMemo(()=>{const D={};for(const[ve,Ge]of Object.entries(Wo))Ge.answered&&(D[ve]=Ge.archived);return D},[Wo]),Hc=m.useMemo(()=>({include:gi,facts:fd,forgotten:new Set(Object.keys(sf))}),[gi,fd,sf]),Pl=m.useRef(null),nr=rK(V,g&&uo,gi),ya=nr.refused,Uc=m.useMemo(()=>PQ(d,Wo),[d,Wo]),vi=m.useMemo(()=>MQ(Uc,hr&&!gi),[Uc,hr,gi]),Gc=WB(nr.data,V)?nr.data.sessions:null,xr=m.useMemo(()=>{const D=new Set(d.map(Ge=>Ge.session_id)),ve=[];for(const[Ge,st]of Object.entries(ne))!st.pinned||D.has(Ge)||ve.push({session_id:Ge,title:st.title||"",updated_at:st.updated_at,pinned:!0});return ve},[ne,d]),{rows:_r,conversationMatches:rf,synthesized:pd}=m.useMemo(()=>LR([...vi,...xr],V,Gc,oe,Hc,Ii,ut),[vi,xr,V,Gc,oe,Hc,Ii,ut]),Ni=Gc!==null&&uQe(Gc.length,nr.data?.limit),gd=RJe({pageable:k,shown:_r.length,total:M?.total??null,searching:V.trim().length>0,clipped:Ni}),Ml=(D,ve)=>_r.filter(Ge=>D==="team"?Ge.binding?.team===ve:!Ge.binding?.team&&Ge.binding?.agent===ve),Vc=(D,ve)=>{if(!Ms)return Ml(D,ve);const Ge=N[zI(D,ve)]?.ids;if(Ge===void 0)return[];const st=new Map(_r.map(bt=>[bt.session_id,bt])),lt=[];for(const bt of Ge){const Cn=st.get(bt);Cn!==void 0&&lt.push(Cn)}return lt},$o=Ms,Ol=m.useRef(null),Wc=m.useRef(!1),[$c,Ll]=m.useState(null),zc=m.useCallback(()=>{if(!$o||Wc.current||P.tailCursor!==null&&P.tailCursor===Ol.current)return;const D=wn.current;D!==null&&DJe({pageable:$o,nextCursor:P.tailCursor,loading:P.loading,error:P.error,scrollTop:D.scrollTop,clientHeight:D.clientHeight,scrollHeight:D.scrollHeight})&&(zo.current=!0,X())},[$o,P,X]);m.useEffect(()=>{P.error!==null&&P.tailCursor!==null&&(Ol.current=P.tailCursor,Ll({cursor:P.tailCursor,sentence:P.error}))},[P.error,P.tailCursor]),m.useLayoutEffect(()=>{zc()},[zc,d.length]);const zo=m.useRef(!1),[af,mb]=m.useState(null),qc=m.useRef(d.length);m.useEffect(()=>{const D=qc.current;if(qc.current=d.length,!zo.current||d.length<=D)return;zo.current=!1,mb(AJe(d.length-D));const ve=window.setTimeout(()=>mb(null),4e3);return()=>window.clearTimeout(ve)},[d.length]);const[qo,Kc]=m.useState(""),Yc=m.useRef(null),Bl=m.useRef(""),Xi=m.useRef(null),Wn=D=>{Xi.current!==null&&(window.cancelAnimationFrame(Xi.current),Xi.current=null),D!==""&&D===Bl.current?(Kc(""),Xi.current=window.requestAnimationFrame(()=>{Xi.current=null,Kc(D)})):Kc(D),Bl.current=D,Yc.current!==null&&window.clearTimeout(Yc.current),Yc.current=window.setTimeout(()=>{Yc.current=null,Bl.current="",Kc("")},4e3)},Xc=m.useRef(null),md=m.useCallback((D,ve,Ge,st,lt)=>{Xc.current={key:Ge,name:ve,at:st},zo.current=!1,Y(D,ve,N[Ge]?.nextCursor??null,lt)},[N,Y]);m.useEffect(()=>{const D=Xc.current;if(D===null)return;const ve=N[D.key]?.ids;if(ve===void 0||ve.length<=D.at)return;Xc.current=null;const Ge=ve[D.at],st=[ff.current,wn.current],lt=Ge===void 0?null:st.map(es=>es?.querySelector(`[data-session-row="${CSS.escape(Ge)}"]`)??null).find(es=>es!==null)??null,bt=ff.current,Cn=bt===null?null:bt.querySelector(`[data-disclosure][data-entity-key="${CSS.escape(D.key)}"]`);(lt?.querySelector("[data-chat-row]")??lt??Cn??null)?.focus()},[N]);const ho=FJe({pageable:$o,nextCursor:$o?P.tailCursor:null,loading:P.loading,error:P.error??($c!==null&&P.tailCursor===$c.cursor?$c.sentence:null)});m.useEffect(()=>{const D=ie.current;if(D!==null){if(ho.kind==="error"){ie.current=null,Q.current?.focus();return}if(P.tailCursor!==D.cursor){ie.current=null;const Ge=wn.current?.querySelectorAll("[data-session-row]"),st=Ge===void 0||Ge.length===0?null:Ge[Ge.length-1];(st?.querySelector("[data-chat-row]")??st)?.focus();return}Date.now()>D.deadline&&(ie.current=null)}},[ho.kind,P.tailCursor]);const of=ho.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:ho.kind==="loading"?"Loading more chats…":ho.sentence}),ho.kind==="error"&&c.jsx("p",{className:"pt-1",children:c.jsx("button",{ref:Q,type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>{ie.current={deadline:Date.now()+2e4,cursor:P.tailCursor},Ol.current=null,Ll(null),X()},children:h("ui.common.actions.retry")})})]}),Hn=Tx(_r,E),Qc=iJe(_r,E),Nt=OQ(we),lf=le&&Nt.tagsEnabled&&Nt.groupBy==="section",fo=D=>De({...Nt,pins:$Qe(Tx([...vi,...xr],E).map(ve=>ve.session_id),Nt.pins,D)}),Ca=Hn.map(D=>D.session_id),bi=D=>Fd(_r.find(ve=>ve.session_id===D)?.title),Ko=zQe(Hn,Nt.pins),Qi=Ko.map(D=>D.session_id),Sa=new Map(Qi.map((D,ve)=>[D,ve])),jl=D=>XQe(bi(D),Sa.get(D)??0,Qi.length),vd=(D,ve,Ge)=>{if(Sa.get(D)===void 0)return;const lt=bi(D);if(!Ck(Qi,D,ve)){Wn(jl(D));return}const bt=qQe(Tx([...vi,...xr],E).map(rs=>rs.session_id),Nt.pins,Qi,D,ve);if(bt===null)return;De({...Nt,pins:bt}),ys(D,Ge,null,"row",!1);const Cn=Yp(Ca,bt);Wn(qB(lt,Cn.indexOf(D),Cn.length))},Me=(D,ve=!1)=>E&&Nt.groupBy==="section"&&!ve&&Sa.has(D),mt=m.useRef(null),Zt=m.useRef(null),Lt=m.useRef(null),[Un,fr]=m.useState(null),[Hl,Yo]=m.useState(null),[Ag,bd]=m.useState(null),$s=m.useRef(null),Xo=m.useRef(0),Qo=D=>zne(Ko,et,le&&Nt.tagsEnabled&&Nt.groupBy==="section"&&!V.trim(),D),Ul=m.useRef(null),[He,Tn]=m.useState(!1),Rs=m.useRef(!0),qr=m.useRef(0),Ji=m.useRef(null),Jo=(D,ve)=>{const Ge=Lt.current;if(!Ge)return;const st=wn.current,lt=mt.current,bt=st&&lt?EXe(st,D,ve,lt):null;Tn(bt!==null),Ji.current?.classList.remove(...Gm),Ji.current=bt,bt?.classList.add(...Gm),Ul.current=bt?.dataset.tagDropTarget??null;const Cn=document.elementFromPoint(D,ve)?.closest("[data-session-row]");Rs.current=!!Cn&&Cn.closest("[data-chat-section]")===mt.current&&Qo(Ge.id).includes(Cn.dataset.sessionRow??"")},xd=()=>{const D=mt.current;if(D===null)return[];const ve=Lt.current?new Set(Qo(Lt.current.id)):null;return Array.from(D.querySelectorAll("[data-session-row]")).filter(Ge=>!ve||ve.has(Ge.dataset.sessionRow??"")).map(Ge=>{const st=Ge.getBoundingClientRect();return{id:Ge.getAttribute("data-session-row")??"",top:st.top,bottom:st.bottom}})},Jc=D=>{const ve=Lt.current;if(ve===null||!ve.armed)return;const Ge=aK(xd(),ve.id,D);ve.slot!==Ge&&(ve.slot=Ge,fr({id:ve.id,slot:Ge}))},ka=(D,ve)=>{const Ge=mt.current,st=Zt.current;if(Ge===null||st===null)return;const lt=xd().filter(rs=>rs.id!==D),bt=Ge.getBoundingClientRect().top,Cn=ve<=0?lt[0]?.top??bt+Ge.offsetHeight:lt[ve-1]?.bottom??bt;st.style.top=`${Math.round(Cn-bt)}px`},cf=32,wr=12,Fg=()=>{$s.current=null;const D=Lt.current,ve=wn.current;if(D===null||!D.armed||ve===null)return;const Ge=ve.getBoundingClientRect(),st=Xo.current,lt=ve.scrollHeight-ve.clientHeight;let bt=0;st-Ge.top<cf&&ve.scrollTop>0?bt=-1:Ge.bottom-st<cf&&ve.scrollTop<lt&&(bt=1),bt!==0&&(ve.scrollTop+=bt*wr),Jo(qr.current,st),Jc(st),$s.current=requestAnimationFrame(Fg)},HC=()=>{$s.current!==null&&(cancelAnimationFrame($s.current),$s.current=null)},lX=(D,ve,Ge)=>{if(Ge.button===0){Ge.preventDefault(),Ge.stopPropagation();try{Ge.currentTarget.setPointerCapture(Ge.pointerId)}catch{}Lt.current={pointerId:Ge.pointerId,id:D,label:ve,armed:!1,slot:-1},Xo.current=Ge.clientY,qr.current=Ge.clientX,Jo(Ge.clientX,Ge.clientY)}},cX=D=>{const ve=Lt.current;ve===null||D.pointerId!==ve.pointerId||(Xo.current=D.clientY,qr.current=D.clientX,Jo(D.clientX,D.clientY),ve.armed||(ve.armed=!0,fr({id:ve.id,slot:ve.slot}),Wn(h("ui.chat.tags.move_armed",{name:ve.label})),$s.current===null&&($s.current=requestAnimationFrame(Fg))),Jc(D.clientY))},uX=(D,ve)=>{const Ge=bi(D),st=KQe(Tx([...vi,...xr],E).map(bt=>bt.session_id),Nt.pins,Qo(D),D,ve);if(st===null){Wn("");return}De({...Nt,pins:st}),ys(D,!1,null,"row",!1);const lt=Yp(Ca,st);Wn(qB(Ge,lt.indexOf(D),lt.length))},vb=(D,ve)=>{ve&&Jo(ve.x,ve.y);const Ge=Lt.current;if(Lt.current=null,HC(),Ji.current?.classList.remove(...Gm),Ji.current=null,fr(null),Tn(!1),Ge===null||!Ge.armed)return;const st=Ul.current;if(Ul.current=null,D&&st){const lt=[...vi,...xr].find(bt=>bt.session_id===Ge.id);lt&&wk(lt,st,Wn).catch(()=>{});return}if(!D||!Rs.current){Wn(h("ui.chat.tags.move_cancelled"));return}uX(Ge.id,Ge.slot)},Dg=m.useRef(vb);Dg.current=vb;const _d=TXe({enabled:le&&Nt.tagsEnabled&&Nt.groupBy==="section"&&!V.trim(),arm:D=>{Wn(h("ui.chat.tags.move_armed",{name:bi(D)})),Qi.includes(D)&&(Lt.current={id:D,label:bi(D),pointerId:-1,armed:!0,slot:-1},fr({id:D,slot:-1}))},move:(D,ve,Ge,st)=>{if(!Lt.current||Lt.current.id!==D)return;Ul.current=st,Tn(st!==null);const lt=Ge?.closest("[data-session-row]");Rs.current=!!lt&&lt.closest("[data-chat-section]")===mt.current&&Qo(D).includes(lt.dataset.sessionRow??""),!st&&Rs.current&&Jc(ve)},settle:(D,ve,Ge)=>{if(Lt.current?.id===D){Dg.current(Ge);return}const st=[...vi,...xr].find(lt=>lt.session_id===D);Ge&&ve&&st?wk(st,ve,Wn).catch(()=>{}):Wn(h("ui.chat.tags.move_cancelled"))}});m.useEffect(()=>{if(Un===null)return;const D=ve=>{ve.key==="Escape"&&(Dg.current(!1),ve.preventDefault())};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[Un!==null]),m.useEffect(()=>{if(Un===null)return;const D=Ge=>{Lt.current?.pointerId===Ge.pointerId&&Dg.current(!0,{x:Ge.clientX,y:Ge.clientY})},ve=()=>Dg.current(!1);return window.addEventListener("pointerup",D),window.addEventListener("pointercancel",ve),window.addEventListener("blur",ve),()=>{window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",ve),window.removeEventListener("blur",ve)}},[Un!==null]),m.useEffect(()=>()=>{$s.current!==null&&cancelAnimationFrame($s.current)},[]),m.useLayoutEffect(()=>{Un!==null&&ka(Un.id,Un.slot)},[Un]);const iI=m.useMemo(()=>new Set(_r.map(D=>D.session_id)),[_r]),UC=m.useMemo(()=>gJe(It,Ie,iI),[It,Ie,iI]),uf=UC.filter(D=>!D.pending),bb=V.trim().length>0,aI=bb?Qc:VI(Qc,Nt.orderBy,Nt.basis),Gl=LQ(aI,{limit:wd(Nt.loads),currentId:e,searching:bb}),oI=Gl.lifted?Gl.rows[0]:null,lI=Gl.lifted?Gl.rows.slice(1):Gl.rows;Wc.current=Gl.remaining>0||Nt.hidden.length>0;const dX=wd(Nt.loads+1)-wd(Nt.loads),hX=Ms&&P.tailCursor!==null,fX=()=>{const D=Nt.loads+1;De({...Nt,loads:D}),Ms&&wd(D)>Qc.length&&X()},pX=Nt.groupBy!==kb.groupBy||Nt.basis!==kb.basis||Nt.orderBy!==kb.orderBy||Nt.hidden.length>0||Nt.loads>0||Nt.pins.length>0||Nt.pinnedAgents.length>0||Nt.order.some((D,ve)=>D!==kb.order[ve]),df=BQ(lI,Te,Nt.basis),cI=jQ(Nt).filter(D=>D!=="pinned"&&!b5(D)),gX=bm(Nt,"pinned"),mX=cI.find(D=>df[D].length>0)??null,vX={pinned:Hn.length,running:df.running.length,today:df.today.length,week:df.week.length,older:df.older.length,agents:J.length,teams:Xe.data?.length??0},GC=m.useMemo(()=>uJe(J.map(D=>({id:D.name,name:D.name})),{pinned:Nt.pinnedAgents,recency:D=>cJe(d,D.name)}),[J,Nt.pinnedAgents,d]),VC=HQ(fi("agents",!0),V,Re,J.length),bX=m.useMemo(()=>lJe(GC,Re),[GC,Re]),uI=VC&&Re.trim()?bX.filter(D=>WI(D.name,Vc("agent",D.name).length,V)):[],xb=Nt,dI=un?It[un]:void 0,hI=D=>D.binding?.team||D.binding?.agent||"",WC=D=>D.binding?.team??"",fI=D=>{const ve=D.binding?.team;return ve?ut(ve):D.binding?.agent??""},pI=D=>D.opened_by!=null,gI=D=>`opened by ${D.opened_by?.agent?.trim()||"an agent"}`,xX=D=>{if(!D.opened_by)return"";const ve=D.opened_by.label?.trim();return`, ${gI(D)}${ve?` in “${ve}”`:""}`},_X=D=>{const ve=hI(D);return!ve||D.opened_by?.agent?.trim()===ve?"":` (${fI(D)})`},Ig=WB(nr.data,V),mI=m.useMemo(()=>Ig||!nr.data||!V.trim()?null:LR([...vi,...xr],nr.data.query,nr.data.sessions,oe,Hc,Ii,ut),[Ig,nr.data,vi,xr,oe,Hc,Ii,ut,V]),vI=!!V.trim()&&g&&uo&&!ya&&!nr.isError&&!Ig,$C=m.useMemo(()=>new Set(Object.values(It).filter(D=>D.sessionId).map(D=>D.sessionId)),[It]),bI=D=>{const ve=Zne(D,et,le&&Nt.tagsEnabled&&Nt.groupBy==="section"&&!V.trim());if(!ve)return D.map(st=>Ng(st));const Ge=ve.map(st=>st.id).filter(st=>st!=="untagged");return ve.map(st=>c.jsxs("div",{"data-chat-tag-group":st.id,className:"[&[data-tag-drop-preview]_[data-chat-row]]:bg-row-selected [&[data-tag-drop-preview]_[data-session-row]]:bg-row-selected",children:[c.jsx(pK,{id:st.id,name:st.name,count:st.rows.length,above:Ge[Ge.indexOf(st.id)-1]??null,below:Ge[Ge.indexOf(st.id)+1]??null,announce:Wn}),c.jsx("div",{"data-tag-drop-target":st.id,"data-tag-drop-body":!0,children:st.rows.map(lt=>Ng(lt,!1,!0))})]},st.id))},Ng=(D,ve=!1,Ge=!1)=>{const st=lQe({marked:rf.has(D.session_id),unstarted:$C.has(D.session_id),nested:ve,binding:hI(D),team:WC(D),agentOpened:pI(D)}),lt=D.pinned===!0,bt=D.locality==="remote",Cn=bt?sJe(D,x.get(typeof D.owner_device=="string"?D.owner_device:"")):"",rs=bt?rJe(D):"",es=Yt=>{ba(Yt,D.session_id)||t(D.session_id)},Nn=(Yt,xi)=>c.jsx("span",{className:"ms-1 inline-flex shrink-0",onPointerEnter:()=>Yo(D.session_id),onPointerLeave:()=>Yo(null),onFocus:()=>bd(D.session_id),onBlur:()=>bd(null),children:c.jsx(RK,{name:Yt,slug:xi,onActivate:()=>es(null)})}),us=oJe(D),ts=Fd(D.title),po=fd[D.session_id]??D.archived===!0,Zi=e===D.session_id&&!un,pf=E||hr||le,gf=!$C.has(D.session_id),Zc=gj(),eu=_b===D.session_id,ea=Un?.id===D.session_id||_d.armedId===D.session_id,go=D.status?.code==="wedged",mo=bJe(Pe,D.session_id,typeof D.owner_device_name=="string"?D.owner_device_name:null),jg=c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"block",children:[Fd(D.title),_X(D)]}),c.jsxs("span",{className:"block",children:[D.link_down===!0?tE(D,Te/1e3):Bx(D)??D.status?.label??(pd.has(D.session_id)?"found by search, beyond the chats listed here":"Recent"),go?` · ${hj}`:"",xX(D),$C.has(D.session_id)?", not sent yet":"",dy(D)!==null?", unread":"",po?", archived":"",us,mo?` · ${mo.clause}`:""]}),bt&&c.jsx("span",{className:"block",children:Cn}),rs&&c.jsx("span",{className:"block",children:rs})]}),Wl=c.jsxs("button",{type:"button","data-chat-row":!0,"data-tour-tag":"chat-session-row","data-child":ve||void 0,"data-session-archived":po?"true":void 0,className:R(dm,"min-w-0 grow text-start",Ge&&(_d.armedId===D.session_id?"cursor-grabbing":"cursor-grab active:cursor-grabbing"),ve&&"ps-7",Zi&&yo),"aria-current":Zi?"page":void 0,...go||mo||pf?{"aria-describedby":[go?fj(D.session_id):null,mo?pj(D.session_id):null,pf?mj(D.session_id):null].filter(Boolean).join(" ")}:{},onPointerDown:Yt=>{bt||_d.start(D.session_id,Yt)},onClick:Yt=>{if(_d.consumeClick(D.session_id,Yt.detail)){Yt.preventDefault();return}es(Yt.detail===0?null:{x:Yt.clientX,y:Yt.clientY})},children:[c.jsx("span",{"aria-hidden":"true",className:"flex size-3.5 shrink-0 items-center justify-center",children:D.locality==="remote"&&c.jsx(NJe,{unreachable:D.link_down===!0||D.reachable===!1})}),c.jsx(SZe,{row:D,nowSeconds:Te/1e3}),c.jsx(xZe,{row:D,open:u?.get(D.session_id)}),hr&&po&&c.jsxs(c.Fragment,{children:[c.jsx(np,{"aria-hidden":"true",className:"ms-1 size-3.5 shrink-0 text-ink-dim"}),c.jsx("span",{className:"sr-only",children:h("ui.chat.sidebar.row.archived_suffix")})]}),c.jsx(BJe,{text:Fd(D.title)}),st==="team"&&Nn(ut(WC(D)),WC(D)),st==="binding"&&(D.binding?.team?Nn(ut(D.binding.team),D.binding.team):c.jsxs("span",{className:"ms-1 max-w-[45%] shrink-0 truncate text-meta text-ink-muted",children:["· ",fI(D)]})),st==="not_sent"&&c.jsxs("span",{className:"ms-1 shrink-0 text-meta text-ink-muted",children:["· ",h("ui.chat.sidebar.row.not_sent")]}),st==="conversation"&&c.jsxs(c.Fragment,{children:[c.jsxs("span",{"aria-hidden":"true",className:"ms-1 shrink-0 whitespace-nowrap text-meta text-ink-muted",children:["· ",h("ui.chat.sidebar.row.in_conversation")]}),c.jsx("span",{className:"sr-only",children:h("ui.chat.sidebar.row.matched_in_conversation")})]}),bt&&c.jsxs("span",{className:"sr-only",children:[", ",Cn]}),rs&&c.jsxs("span",{className:"sr-only",children:[", ",rs]}),pI(D)&&(st==="team"||st==="none")&&c.jsxs("span",{className:"sr-only",children:[", ",gI(D)]}),us!==""&&c.jsx("span",{className:"sr-only",children:us}),Bx(D)?c.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:Bx(D)}):D.link_down===!0?c.jsx("span",{className:R("shrink-0 text-meta",D.link_reconnecting===!0?"text-ink-dim":"text-warning"),title:tE(D,Te/1e3),children:XQ(D,Te/1e3)}):!QQ(D)&&XI(D,Te,Nt.basis)&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true","data-session-time":!0,className:"ms-auto shrink-0 ps-2 font-mono text-ink-dim text-mono-sm tabular-nums group-has-[:focus-visible]:hidden group-data-[session-hover-intent]:hidden",children:XI(D,Te,Nt.basis)}),c.jsxs("span",{className:"sr-only",children:[", ",JQ(D,Te,Nt.basis)]})]})]}),mf=go?c.jsx("span",{id:fj(D.session_id),className:"sr-only",children:hj}):null,$l=mo?c.jsx("span",{id:pj(D.session_id),className:"sr-only",children:mo.description}):null,yb=pf?c.jsx("span",{id:mj(D.session_id),className:"sr-only",children:NZe(Zc)}):null,Hg=Yt=>{const xi=Yt.relatedTarget;xi&&Yt.currentTarget.contains(xi)&&Yt.preventDefault()},Cb=(Yt,xi)=>c.jsx(vt,{content:jg,side:"bottom",align:"start",disableHoverableContent:!0,collisionPadding:PZe,className:"w-(--radix-tooltip-trigger-width) max-w-none",suppressed:Un!==null||_d.armedId!==null||Ue!==null||Hl===D.session_id||Ag===D.session_id,children:Yt},xi);if(!pf)return Cb(c.jsxs("div",{onBlur:Hg,className:R(Ak,Zi&&yo),children:[Wl,c.jsx(ij,{row:D}),mf,$l]}),D.session_id);const Pr=E&&hr,tu=Ck(Qi,D.session_id,-1),Sb=Ck(Qi,D.session_id,1),FI=Me(D.session_id,ve),DI=c.jsxs(c.Fragment,{children:[FI&&c.jsx(c.Fragment,{children:Qi.length>=2&&c.jsx("button",{type:"button","data-session-pin-grip":!0,tabIndex:-1,"aria-hidden":"true",title:h("ui.chat.sidebar.pins.drag_title"),onPointerDown:Yt=>lX(D.session_id,ts,Yt),onPointerMove:cX,onPointerUp:Yt=>vb(!0,{x:Yt.clientX,y:Yt.clientY}),onPointerCancel:()=>vb(!1),className:R("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",eu&&"flex text-ink-muted","hover:text-ink!",!Zi&&"hover:bg-row-hover"),children:c.jsx(Zce,{"aria-hidden":"true",className:"size-4"})})}),D.pinned!==void 0&&c.jsx("button",{type:"button","data-session-pin":!0,tabIndex:-1,"aria-pressed":lt,"aria-label":lt?h("ui.chat.sidebar.pins.unpin_label",{title:ts}):h("ui.chat.sidebar.pins.pin_label",{title:ts}),title:lt?h("ui.chat.sidebar.pins.unpin_label",{title:ts}):h("ui.chat.sidebar.pins.pin_label",{title:ts}),onClick:Yt=>{ba(Yt.detail===0?null:{x:Yt.clientX,y:Yt.clientY},D.session_id)||(ys(D.session_id,Yt.detail===0,{x:Yt.clientX,y:Yt.clientY}),B(D.session_id,!lt,{title:D.title??void 0,updated_at:D.updated_at??void 0}),lt||fo(D.session_id),lt&&Nt.pins.includes(D.session_id)&&De({...Nt,pins:YQe(Nt.pins,D.session_id)}))},className:R("size-6 shrink-0 items-center justify-center rounded-md",lt?"flex text-ink":R("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",eu&&"flex text-ink-muted","hover:text-ink!"),!Zi&&"hover:bg-row-hover"),children:c.jsx(G1,{"aria-hidden":"true",className:"size-4",fill:lt?"currentColor":"none"})}),hr&&c.jsx("button",{type:"button","data-session-archive":!0,tabIndex:-1,"aria-label":C_(ts,po),title:C_(ts,po),onClick:Yt=>{const xi=VQe(Pl.current,Yt.detail===0?null:{x:Yt.clientX,y:Yt.clientY},D.session_id);if(Pl.current=xi.record,xi.drop)return;if(!po){jc({sessionId:D.session_id,fromRow:!0});return}const PX=fG(Yt.currentTarget);mi(D.session_id,!1,D.title??void 0).then(MX=>{MX&&PX()})},className:R(R("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",eu&&"flex text-ink-muted"),"hover:text-ink!",!Zi&&"hover:bg-row-hover"),children:po?c.jsx(K_,{"aria-hidden":"true",className:"size-4"}):c.jsx(np,{"aria-hidden":"true",className:"size-4"})})]}),NX=c.jsxs("div",{"data-session-row":D.session_id,"data-session-menu-trigger":!0,onKeyDown:SX,onPointerDownCapture:kX,"data-dragging":ea?"":void 0,onBlur:Hg,className:R((E||hr)&&"group",(E||hr)&&!Zi&&"hover:bg-row-hover",eu&&!Zi&&"bg-row-hover",Ak,Zi&&yo,ea&&IK,ea&&NK),children:[(E||hr)&&c.jsx(PJe,{}),Wl,c.jsx(ij,{row:D}),mf,$l,yb,Pr?c.jsx("div",{"data-session-control-pair":!0,className:R("items-center gap-1",lt||eu?"flex":"hidden group-data-[session-hover-intent]:flex group-has-[:focus-visible]:flex"),children:DI}):DI]});return c.jsxs(qne,{open:eu,onOpenChange:Yt=>{Yt&&(Un!==null||_d.armedId!==null)||(Yt&&Bg.current===null&&(Bg.current=document.activeElement instanceof HTMLElement?document.activeElement:null),TI(xi=>Yt?D.session_id:xi===D.session_id?null:xi))},children:[c.jsx(DZe,{id:D.session_id,openMenuRowIdRef:YC,setOpenMenuRowId:TI,openedByKeyboard:Lg}),Cb(c.jsx(Kne,{asChild:!0,children:NX}),D.session_id),c.jsxs(Yne,{className:kXe,onFocus:Yt=>{Lg.current&&Yt.target===Yt.currentTarget&&Yt.currentTarget.querySelector('[role="menuitem"]')?.focus()},onCloseAutoFocus:Yt=>{if(Yt.preventDefault(),Ue)return;const xi=Bg.current;if(Bg.current=null,!Lg.current){xi?.isConnected?xi.focus():document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`)?.focus();return}Lg.current=!1,document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`)?.focus()},children:[hr&&c.jsxs(zl,{onSelect:()=>vj(D.session_id,"archive"),children:[po?c.jsx(K_,{"aria-hidden":"true"}):c.jsx(np,{"aria-hidden":"true"}),c.jsx("span",{children:po?h("ui.chat.sidebar.row_menu.unarchive"):h("ui.chat.sidebar.row_menu.archive")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:NN("archive",Zc),joined:!0})})]}),D.pinned!==void 0&&c.jsxs(zl,{onSelect:()=>vj(D.session_id,"pin"),children:[lt?c.jsx(Nue,{"aria-hidden":"true"}):c.jsx(G1,{"aria-hidden":"true"}),c.jsx("span",{children:lt?h("ui.chat.sidebar.row_menu.unpin"):h("ui.chat.sidebar.row_menu.pin")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:NN("pin",Zc),joined:!0})})]}),gf&&c.jsxs(zl,{onSelect:()=>{i("session.fork",document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`),D.session_id),r.pathname.startsWith("/chat")||s("/chat")},children:[c.jsx(Xne,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.fork")})]}),c.jsxs(zl,{onSelect:()=>void cK(D.session_id),children:[c.jsx(ed,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.copy_id")})]}),c.jsxs(zl,{onSelect:()=>{i("session.rename",document.querySelector(`[data-session-row="${CSS.escape(D.session_id)}"] [data-chat-row]`),D.session_id,{subjectName:Fd(D.title)}),r.pathname.startsWith("/chat")||s("/chat")},children:[c.jsx(Vv,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.rename")})]}),le&&c.jsxs(zl,{"aria-disabled":D.locality==="remote",title:D.locality==="remote"?h("ui.chat.tags.remote"):void 0,className:"aria-disabled:cursor-default aria-disabled:text-ink-disabled! aria-disabled:hover:bg-transparent!",onSelect:Yt=>{if(D.locality==="remote"){Yt.preventDefault(),Wn(h("ui.chat.tags.remote"));return}sn(D)},children:[c.jsx(Qne,{"aria-hidden":"true",className:"size-3.5"}),c.jsx("span",{children:h("ui.chat.tags.menu")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:Jne(Zc),joined:!0})})]}),le&&(D.tags?.length??0)>0&&c.jsxs(zl,{onSelect:()=>{wk(D,"untagged",Wn).catch(()=>{})},children:[c.jsx(Xn,{"aria-hidden":"true"}),h("ui.chat.tags.remove_all",{count:new Set(D.tags?.map(Yt=>Yt.id)).size})]}),FI&&c.jsxs(c.Fragment,{children:[c.jsxs(zl,{"aria-disabled":!tu,title:tu?void 0:jl(D.session_id),onSelect:()=>vd(D.session_id,-1,!0),className:R("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(Hv,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.move_up")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:KB(-1,Zc),joined:!0})})]}),c.jsxs(zl,{"aria-disabled":!Sb,title:Sb?void 0:jl(D.session_id),onSelect:()=>vd(D.session_id,1,!0),className:R("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(Ei,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.sidebar.row_menu.move_down")}),c.jsx("span",{className:"ms-auto ps-6",children:c.jsx(Lr,{shortcut:KB(1,Zc),joined:!0})})]})]})]})]},D.session_id)},Pg=(D,ve)=>s(`/agents?kind=${D}&name=${encodeURIComponent(ve)}`),wX=async(D,ve,Ge)=>{if(Ge.kind==="review"||Ge.kind==="failed"&&!Ge.retryable)return Pg(D,ve);(Ge.kind==="failed"?await Vt.retryItem(D,ve):await Vt.applyItem(D,ve))?.some(lt=>lt.outcome==="needs-review")&&Pg(D,ve)},yX=async D=>{await Vt.applyAll(D),requestAnimationFrame(()=>{const ve=document.activeElement;ve&&ve!==document.body||document.querySelector(`[data-chat-section="${IXe[D]}"]`)?.focus()})},xI=D=>c.jsx(dZe,{kind:D,available:UXe(At.data,D),busy:Vt.pending.has(`all:${D}`),blocked:!Vt.canWrite,onUpdateAll:()=>void yX(D),onCheck:D==="agent"&&cs?()=>void Vt.checkNow():void 0,checking:Vt.pending.has("check")}),_I=D=>c.jsx(hZe,{kind:D,reserve:D==="agent"&&(cs||At.data?.credential==="none"),signIn:D==="agent"?VXe(At.data):null,signInHref:"/settings?section=radient",rollup:Vt.rollups[D],note:Vt.notes[`all:${D}`]??(D==="agent"?Vt.notes.check:void 0)??(D==="agent"&&cs&&Vt.upgradeMessage?{message:Vt.upgradeMessage,tone:"info"}:void 0),onDismissRollup:()=>Vt.clearRollup(D)}),zC=(D,ve,Ge=ve)=>{const st=Vc(D,ve),lt=zI(D,ve),bt=D==="team"?ut(ve):ve,Cn=bt!==ve?`${bt} (${ve})`:bt,rs=!!V||fi(lt),es=KQ(bb?st:VI(st,xb.orderBy,xb.basis),{loads:CI[lt]??0,currentId:e,searching:bb}),Nn=es.rows,us=TJe({pageable:Ms,total:Ms?kk(M,D,ve):null,held:st.length,searching:!!V.trim()}),ts=EJe({pageable:Ms,scope:N[lt],held:N[lt]?.ids.length??st.length,total:Ms?kk(M,D,ve):null}),po=Ms?kk(M,D,ve)??st.length:st.length,Zi=CI[lt]??0,pf=wd(Zi+1)-wd(Zi),gf=YQ({add:es.hidden>0?Math.min(pf,es.hidden):Ms&&ts.more?ts.addCount:0,drawn:Nn.length,total:po}),Zc=()=>{const Pr=Zi+1;if(SI(Sb=>({...Sb,[lt]:Pr})),!Ms)return;const tu=N[lt]?.ids.length??0;N[lt]?.nextCursor!==null&&wd(Pr)>=tu&&md(D,ve,lt,tu,ts.addCount)};if(!WI(ve,st.length,V,bt))return null;const eu=D==="team"?Vm:yl,ea=dI?.target?.kind===D&&dI.target.name===ve,go=D==="agent"&&xb.pinnedAgents.includes(Ge),mo=Ev(D,ve),jg=cn.get(mo),Wl=tK(jg),mf=D==="team"?Xe.data?.find(Pr=>Pr.name===ve)?.id:fe.data?.find(Pr=>Pr.name===ve)?.agent_id??void 0,$l=rn?nQe(ws.data,D,mf,ve):[],yb=$l.length===1?$l[0]:void 0,Hg=$l.length>1?$l:null,Cb=rn&&$l.length===0?sQe(ws.data,D,mf,ve):[];return c.jsxs("div",{"data-entity":!0,children:[c.jsxs("div",{className:R("group flex h-8 items-center gap-1 rounded-md",ea&&yo),children:[c.jsx("button",{type:"button","data-disclosure":!0,"data-entity-key":lt,"aria-label":rs?h("ui.chat.sidebar.entity.collapse_chats",{name:bt}):h("ui.chat.sidebar.entity.expand_chats",{name:bt}),"aria-expanded":rs,className:R("flex size-6 shrink-0 items-center justify-center rounded-md",!ea&&"hover:bg-row-hover"),onClick:()=>{rs&&SI(Pr=>{if(Pr[lt]===void 0)return Pr;const tu={...Pr};return delete tu[lt],tu}),co(lt)},children:rs?c.jsx(Ei,{className:"size-3.5"}):c.jsx(Vi,{className:"size-3.5"})}),c.jsxs("button",{type:"button","data-chat-row":!0,"data-entity-name":!0,className:R(dm,"flex-1 text-start",ea&&yo),onClick:()=>n({kind:D,name:ve}),"aria-label":h("ui.chat.header.new_chat_with",{target:bt}),title:h("ui.chat.header.new_chat_with",{target:bt}),children:[c.jsx(IZe,{agentId:D==="agent"?mf??null:null,glyph:eu}),c.jsx("span",{className:"min-w-0 flex-1 truncate",title:Cn,children:bt}),c.jsx(iT,{className:R("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:us>0?JB(us):void 0,className:"min-w-4 shrink-0 text-end text-meta tabular-nums text-ink-dim",children:us||""})]}),us>0&&c.jsx("span",{className:"sr-only",children:JB(us)}),D==="agent"&&c.jsx(vt,{content:go?h("ui.chat.sidebar.entity.unpin",{name:ve}):h("ui.chat.sidebar.entity.pin",{name:ve}),children:c.jsx("button",{type:"button","data-agent-pin":Ge,className:R("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim hover:text-ink-muted",!ea&&"hover:bg-row-hover",go?"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":go,"aria-label":h(go?"ui.chat.sidebar.entity.unpin":"ui.chat.sidebar.entity.pin",{name:ve}),onClick:()=>De(dJe(xb,Ge)),children:c.jsx(G1,{"aria-hidden":"true",className:R("size-4",go&&"text-ink"),fill:go?"currentColor":"none"})})}),yb&&c.jsx(rZe,{link:yb,staged:ea,onDetail:()=>Pg(D,ve),itemName:ve,displayName:bt,itemsById:kn,nameAmbiguous:!(D==="team"?Xe.isSuccess&&!Xe.isFetching:fe.isSuccess&&!fe.isFetching)||(Ft[D==="team"?"team":"agent"].get(ve.trim().toLowerCase())??0)!==1}),Hg&&c.jsx(oZe,{links:Hg,staged:ea,onDetail:()=>Pg(D,ve)}),Cb.length>0&&c.jsx(iZe,{item:ve,staged:ea,onResolve:()=>s(`/agents?kind=${D}&name=${encodeURIComponent(ve)}&resolve=${Date.now()}`)}),!rn&&Wl&&jg&&c.jsx(cZe,{item:jg,mark:Wl,busy:Vt.pending.has(mo),blocked:!Vt.canWrite&&(Wl.kind==="available"||Wl.kind==="failed"&&Wl.retryable),staged:ea,onPress:()=>wX(D,ve,Wl)}),c.jsx("button",{type:"button",className:R("flex size-6 shrink-0 items-center justify-center rounded-md text-ink-dim hover:text-ink-muted",!ea&&"hover:bg-row-hover"),"aria-label":h("ui.chat.sidebar.entity.manage",{name:bt}),onClick:()=>s(`/agents?kind=${D}&name=${encodeURIComponent(ve)}`),children:c.jsx(oc,{className:"size-4"})})]}),Vt.notes[mo]&&c.jsx(uZe,{note:Vt.notes[mo]}),rs&&c.jsxs("div",{children:[$l.map(Pr=>c.jsx(aZe,{link:Pr},Pr.link_id)),es.lifted&&hf(h("ui.chat.sidebar.section.current_chat")),Nn.map(Pr=>Ng(Pr,!0))," ",c.jsxs("div",{"aria-live":"polite",className:ts.state!=="rows"&&ts.sentence!==null?"py-1 ps-7":"sr-only",children:[ts.state!=="rows"&&ts.sentence!==null&&c.jsx("p",{className:"line-clamp-2 text-meta text-ink-dim",title:ts.sentence,children:ts.sentence}),ts.state!=="rows"&&ts.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 Y(D,ve,null),children:h("ui.common.actions.retry")})})]}),ts.state==="rows"&&(N[lt]?.loading?c.jsx("p",{className:"py-1 ps-7 text-meta text-ink-dim","aria-live":"polite",children:h("ui.chat.sidebar.list.loading_more")}):ts.retry?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"line-clamp-2 py-1 ps-7 text-meta text-ink-dim","aria-live":"polite",children:ts.sentence}),c.jsx("p",{className:"py-1 ps-7",children:c.jsx("button",{type:"button",className:"text-meta text-ink-dim underline hover:text-ink",onClick:()=>md(D,ve,lt,N[lt]?.ids.length??st.length,ts.addCount),children:h("ui.common.actions.retry")})})]}):gf?c.jsx("button",{type:"button","data-scope-more":lt,"data-chat-row":!0,"data-entity-more":lt,"aria-label":`${gf.aria} in ${bt}`,title:`${gf.aria} in ${bt}`,className:"block w-full py-1 ps-7 text-start text-meta text-ink-dim underline hover:text-ink",onClick:Zc,children:gf.label}):null)]})]},lt)},wI=(D,ve,Ge,st,lt,bt,Cn,rs)=>{const es=qI(Mg[D])?KI:null;return c.jsxs("div",{className:R("@container/chatheading flex h-7 items-center gap-1",bt),children:[c.jsxs("button",{ref:Cn,type:"button","data-chat-row":!0,"data-chat-section":D,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":V?!0:fi(D,Ge),title:es??void 0,"aria-describedby":es?YI(D):void 0,onClick:()=>co(D,Ge),children:[V||fi(D,Ge)?c.jsx(Ei,{className:"size-3.5"}):c.jsx(Vi,{className:"size-3.5"}),lt?m.createElement(lt,{"aria-hidden":!0,className:"size-3.5 shrink-0 text-ink-dim"}):null,c.jsx("span",{className:"min-w-0 flex-1 truncate text-start",children:ve}),st!==void 0]}),es&&c.jsx("span",{id:YI(D),className:"sr-only",children:es}),bt,rs]})},[Mg,yI]=m.useState({}),[CI,SI]=m.useState({}),qC=m.useRef(null),kI=(D,ve)=>{const Ge=Mg[D]??$I,st=ve.length-Ge,lt=zQ(st,D);return c.jsxs(c.Fragment,{children:[ve.slice(0,Ge),st>0&&c.jsx("button",{type:"button","data-sidebar-section-more":D,"data-chat-row":!0,"aria-label":lt,title:qI(Ge)?`${lt} - ${KI}`:lt,onClick:()=>{qC.current={key:D,at:Ge},yI(bt=>qQ(bt,D))},className:"flex h-7 w-full items-center rounded-md px-2 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:$Q(st)})]})},hf=(D,ve)=>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:D}),ve]}),EI=m.useRef(null),KC=`[data-chat-row], [${GR}]`,Og=D=>{const ve=Vl.current;if(ve===null)return;const Ge=[...ve.querySelectorAll(KC)],st=Ge.filter(bt=>!bt.disabled&&bt.closest("[hidden]")===null);if(st.length===0)return;const lt=D!==null&&st.includes(D)?D:st[0];EI.current=lt;for(const bt of Ge)bt.tabIndex=st.includes(bt)&&bt===lt?0:-1,bt.toggleAttribute($ne,st.includes(bt)&&bt===lt)};m.useLayoutEffect(()=>{Og(EI.current)});const CX=D=>{const ve=D.target.closest?.(KC);ve!=null&&Vl.current?.contains(ve)&&Og(ve)},[_b,TI]=m.useState(null),Lg=m.useRef(!1),Bg=m.useRef(null),YC=m.useRef(null);m.useEffect(()=>{YC.current=_b},[_b]);const SX=D=>{if(D.key!=="ContextMenu"&&!(D.shiftKey&&D.key==="F10"))return;const ve=D.currentTarget;D.preventDefault(),Lg.current=!0;const Ge=ve.getBoundingClientRect();ve.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:Ge.left,clientY:Ge.bottom-1}))},kX=()=>{YC.current===null&&(Bg.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},EX=D=>{if(_b!==null||!D.currentTarget.contains(D.target))return;const ve=D.target;if(le&&ese(D)&&ve.hasAttribute("data-chat-row")){const Nn=ve.closest("[data-session-row]")?.dataset.sessionRow,us=[...vi,...xr].find(ts=>ts.session_id===Nn);us&&(D.preventDefault(),us.locality==="remote"?Wn(h("ui.chat.tags.remote")):sn(us));return}const Ge=tse(D);if(Ge!==null){const Nn=nse(ve,Ge);Nn!==null&&(D.preventDefault(),Nn.click());return}const st=JQe(D);if(st!==null){const Nn=eJe(ve);if(Nn===null)return;Me(Nn)?(D.preventDefault(),vd(Nn,st,!0)):Ca.includes(Nn)||Wn(QQe(bi(Nn)));return}if(ve===C.current){const Nn=()=>D.currentTarget.querySelector('[data-sidebar-region="chats"] [data-chat-row]');if(D.key==="ArrowDown"){const us=Nn();us&&(D.preventDefault(),us.focus(),Og(us));return}if(D.key==="Escape"){j(""),Z(!1);const us=Nn();us?(us.focus(),Og(us)):ve.blur()}return}if(D.key.length===1&&D.key!==" "&&!D.metaKey&&!D.ctrlKey&&!D.altKey&&ve.hasAttribute("data-chat-row")){D.preventDefault(),Z(!0),j(Nn=>Nn+D.key),window.requestAnimationFrame(()=>C.current?.focus());return}if(D.key==="Escape"){D.preventDefault(),ee&&C.current?.focus();return}if(D.key==="ArrowUp"&&ve.hasAttribute("data-entity-name")){const Nn=ve.closest("[data-entity]"),us=Nn?.closest("section");if(Nn&&us&&us.querySelector("[data-entity]")===Nn){const ts=us.querySelector("[data-roster-filter]");if(ts){D.preventDefault(),ts.focus();return}}}const lt=[...D.currentTarget.querySelectorAll(KC)].filter(Nn=>!Nn.disabled&&Nn.closest("[hidden]")===null),bt=lt.indexOf(ve),Cn=D.key==="ArrowDown"?Math.min(lt.length-1,bt+1):D.key==="ArrowUp"?Math.max(0,bt-1):D.key==="Home"?0:D.key==="End"?lt.length-1:-1;if(Cn>=0){D.preventDefault();const Nn=lt[Cn];Nn?.focus(),Nn!==void 0&&Og(Nn);return}const rs=ve.closest("[data-entity]"),es=rs?.querySelector("[data-disclosure]");D.key==="ArrowRight"&&es&&(D.preventDefault(),es.getAttribute("aria-expanded")==="false"?es.click():rs?.querySelector("[data-child]")?.focus()),D.key==="ArrowLeft"&&es&&(D.preventDefault(),ve.hasAttribute("data-child")?rs?.querySelector("[data-entity-name]")?.focus():es.getAttribute("aria-expanded")==="true"&&es.click())},ff=m.useRef(null),RI=m.useRef({node:null,index:-1,visibility:"outside",clipHeight:0}),AI=m.useRef({node:null,index:-1,visibility:"outside",clipHeight:0}),TX=m.useCallback(D=>{ff.current=D,wn.current=D},[]);m.useLayoutEffect(()=>{sj(ff.current,RI),sj(wn.current,AI)}),m.useEffect(()=>{const D=qC.current;if(D===null)return;qC.current=null;const ve=ff.current;if(ve===null)return;const Ge=ve.querySelector(`[data-chat-section="${CSS.escape(D.key)}"]`),st=Ge?.closest("section")??null,lt=st===null?[]:[...st.querySelectorAll("[data-entity]")],Cn=(Mg[D.key]??$I)>D.at?lt[D.at]??null:null;(Cn?.querySelector("[data-chat-row]")??Cn??Ge??null)?.focus()},[Mg]);const Vl=m.useRef(null),RX=m.useRef(null),AX=z,FX=c.jsxs("div",{id:EZe,"data-sidebar-region":"entities",className:R("relative space-y-4"),children:[a.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:h("ui.chat.sidebar.list.connecting")}),a.error&&!w&&!S&&c.jsxs("div",{className:"space-y-1 text-meta text-ink-muted",children:[c.jsxs("p",{children:[a.error.message,U?" Showing the last chats loaded.":""]}),c.jsx("button",{type:"button",className:"underline",onClick:()=>void a.refetch(),children:h("ui.chat.sidebar.list.retry_refresh")})]}),te&&!w&&c.jsxs("div",{className:"space-y-1 text-meta text-ink-muted",children:[c.jsx("p",{children:te}),c.jsx("button",{type:"button",className:"underline",onClick:()=>void a.refetch(),children:h("ui.chat.sidebar.list.retry_refresh")})]}),z&&c.jsxs("div",{className:"pb-2",children:[bm(Nt,"agents")&&c.jsxs("section",{children:[wI("agents",h(Lx.agents),!0,void 0,yl,void 0,void 0,xI("agent")),(V||fi("agents",!0))&&c.jsxs(c.Fragment,{children:[fe.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:h("ui.chat.sidebar.agents.loading")}),_I("agent"),VC&&c.jsxs("div",{className:"relative mt-1 mb-2",children:[c.jsx("input",{ref:_e,"data-roster-filter":!0,"aria-label":h("ui.chat.sidebar.agents.filter"),placeholder:h("ui.chat.sidebar.agents.filter"),className:"h-8 w-full rounded-md bg-row-hover pe-9 ps-2 text-body-sm",value:Re,onChange:D=>ye(D.target.value),onKeyDown:D=>{if(D.key==="Escape"){D.preventDefault(),D.stopPropagation(),Re&&u1(_e.current,ye);return}if(D.key==="ArrowDown"){D.preventDefault(),D.stopPropagation(),Vl.current?.querySelector("[data-agent-pin]")?.closest("[data-entity]")?.querySelector("[data-entity-name]")?.focus();return}(D.key==="ArrowUp"||D.key==="Home"||D.key==="End")&&D.stopPropagation()}}),Re&&c.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 end-1 -translate-y-1/2 focus-visible:outline-offset-[-2px]!",onClick:()=>u1(_e.current,ye),"aria-label":h("ui.chat.sidebar.agents.clear_filter"),children:c.jsx(Xn,{"aria-hidden":"true"})})]}),!se&&c.jsxs("div",{className:R(W?"flex flex-col gap-2 px-3 py-2":"contents"),"data-testid":W?"agents-sidebar-empty":void 0,children:[c.jsx("div",{className:"contents",children:W?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:h("ui.chat.sidebar.agents.empty")}),Ae&&!he&&c.jsx(ce,{variant:"ghost",size:"icon-sm","data-testid":"agents-offer-dismiss","aria-label":h("ui.chat.sidebar.agents.dismiss_offer"),onClick:()=>{Je.current=!0,K(me)},children:c.jsx(Xn,{"aria-hidden":"true"})})]}),Se.length>0&&c.jsx("p",{className:"text-meta text-ink-muted",children:IJe(Se)})]}):VC&&Re.trim()?uI.length>0?uI.map(D=>zC("agent",D.name,D.id)):c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.agents.no_match")}):kI("agents",GC.map(D=>zC("agent",D.name,D.id)))}),c.jsx(SXe,{builtins:Se,presentation:W?"primary":"row",onBusyChange:xe})]}),c.jsxs("button",{ref:pe,type:"button",className:R(dm,"w-full text-ink-muted"),onClick:()=>s("/agents?create=agent"),children:[c.jsx(Cl,{className:"size-4"}),h("ui.chat.sidebar.agents.create")]})]})]}),bm(Nt,"teams")&&c.jsxs("section",{className:UQ(bm(Nt,"agents")&&(!!V||fi("agents",!0))),children:[wI("teams",h(Lx.teams),!0,void 0,Vm,void 0,void 0,xI("team")),(V||fi("teams",!0))&&c.jsxs(c.Fragment,{children:[Xe.isLoading&&c.jsx("p",{"aria-live":"polite",className:"text-meta text-ink-dim",children:h("ui.chat.sidebar.teams.loading")}),_I("team"),Xe.data&&kI("teams",Xe.data.map(D=>zC("team",D.name))),c.jsxs("button",{type:"button",className:R(dm,"w-full text-ink-muted"),onClick:()=>s("/agents?create=team"),children:[c.jsx(Cl,{className:"size-4"}),h("ui.chat.sidebar.teams.create")]})]})]})]})]},"entities"),DX=G?c.jsxs("p",{ref:RX,className:"pb-2 text-meta text-warning",children:[h("ui.chat.sidebar.pins.failure",{action:G.pinned?"pin":"unpin",title:Fd(G.title,"this_chat")}),G.detail?` ${G.detail}`:""," ",c.jsx("button",{type:"button",className:"underline",onClick:()=>void B(G.sessionId,G.pinned),children:h("ui.common.actions.retry")})]}):null,wb=lf&&!V.trim()&&!ue&&Le===null?c.jsx(UJe,{unused:Wne(et),total:et.length,dragArmed:_d.armedId!==null,announce:Wn,chord:Vne(gj())}):null,IX=c.jsxs("div",{"data-sidebar-region":"chats",onPointerMove:D=>{const ve=Ts.current;ve!==null&&Math.hypot(D.clientX-ve.x,D.clientY-ve.y)>an&&(Ts.current=null),WQe(Pl.current,{x:D.clientX,y:D.clientY})&&(Pl.current=null)},onPointerLeave:()=>{Ts.current=null,Pl.current=null},className:R("relative space-y-4"),children:[oI&&c.jsxs("section",{"data-chat-section":"current",children:[hf(h("ui.chat.sidebar.section.current_chat")),Ng(oI)]}),UC.length>0&&!V.trim()&&c.jsxs("section",{"data-chat-section":"drafts",children:[UC.map(D=>{const ve=D.key===un;return c.jsxs("div",{className:R(Ak,"group",!ve&&"hover:bg-row-hover",ve&&yo),children:[c.jsxs("button",{type:"button","data-chat-row":!0,"data-draft-row":D.key,"aria-label":`Open ${D.label}`,title:D.label,onClick:()=>{dn(D.key),s("/chat")},className:R(dm,"min-w-0 flex-1 text-start",ve&&yo),children:[c.jsx(Ty,{className:"size-4 shrink-0 text-ink-dim","aria-hidden":"true"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.label})]}),D.pending&&c.jsx("span",{id:lj(D.key),className:"sr-only",children:oj}),c.jsx("button",{type:"button","data-draft-discard":D.key,"aria-disabled":D.pending,"aria-describedby":D.pending?lj(D.key):void 0,"aria-label":QB(D.label),title:D.pending?oj:QB(D.label),onClick:Ge=>{if(D.pending){Ge.preventDefault();return}if(ba(Ge.detail===0?null:{x:Ge.clientX,y:Ge.clientY},D.key))return;const st=[...Vl.current?.querySelectorAll("[data-draft-row]")??[]].map(bt=>bt.getAttribute("data-draft-row")??""),lt=pJe(st,D.key);tr(D.key),un===D.key?(n(void 0,!0),wa(Fe.getState().activeDraftKey)):wa(null),requestAnimationFrame(()=>{const bt=[...Vl.current?.querySelectorAll("[data-draft-row]")??[]];(bt[Math.min(Math.max(lt,0),bt.length-1)]??Vl.current?.querySelector("[data-chat-row]"))?.focus()})},className:R("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(cg,{className:"size-4","aria-hidden":"true"})})]},D.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":uf.length===0,"aria-describedby":uf.length===0?uj:void 0,"aria-label":h("ui.chat.sidebar.drafts.clear_all_label"),title:uf.length===0?cj:"Clear all drafts",onClick:D=>{if(uf.length===0){D.preventDefault();return}const ve=D.currentTarget;if(ba(D.detail===0?null:{x:D.clientX,y:D.clientY},"drafts:clear-all"))return;const Ge=[...Vl.current?.querySelectorAll("[data-chat-row]")??[]].indexOf(ve),st=uf.map(lt=>lt.key);Sn(st),un!==null&&st.includes(un)?(n(void 0,!0),wa(Fe.getState().activeDraftKey)):wa(null),requestAnimationFrame(()=>{const lt=[...Vl.current?.querySelectorAll("[data-chat-row]")??[]];lt[Math.min(Math.max(Ge,0),lt.length-1)]?.focus()})},className:R("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:h("ui.chat.sidebar.drafts.clear_all")}),uf.length===0&&c.jsx("span",{id:uj,className:"sr-only",children:cj})]})]}),wb&&et.length===0&&wb,Nt.groupBy!=="section"&&(GQ([...Hn,...lI],Nt.groupBy)??[]).map(D=>c.jsxs("section",{"data-chat-section":D.key,children:[D.label?hf(D.label):null,D.rows.map(ve=>Ng(ve))]},D.key)),E&&c.jsx("span",{className:"sr-only","aria-live":"polite","data-sidebar-pin-order-announcement":!0,children:qo}),gX&&Nt.groupBy==="section"&&Hn.length>0&&c.jsxs("section",{ref:mt,"data-chat-section":"pinned",className:"relative",children:[hf(h(Lx.pinned)),bI(Ko),Un!==null&&!He&&c.jsx("div",{ref:Zt,"aria-hidden":"true","data-session-pin-indicator":"",className:"pointer-events-none absolute start-1 end-1 h-0.5 rounded-full bg-accent"})]}),Nt.groupBy==="section"&&cI.map(D=>{const ve=df[D];return D==="running"&&ve.length===0&&Vs?c.jsxs("section",{children:[hf(h(QI[D])),c.jsx("p",{className:"px-2 text-meta text-ink-dim",children:Vs?"The daemon could not read which chats are running, so this list may be incomplete.":"Nothing running right now."})]},D):ve.length===0?null:c.jsxs("section",{"data-chat-section":D,children:[hf(h(QI[D]),D===mX?Ws:void 0),bI(ve)]},D)}),!V.trim()&&(Gl.remaining>0||hX)&&c.jsx("button",{type:"button","data-sidebar-page-more":!0,onClick:fX,className:"flex h-7 w-full items-center rounded-md px-2 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:VQ(Nt.loads,Gl.remaining>0?WQ(aI,Nt.loads,Gl.remaining):dX)}),of,af!==null&&c.jsx("span",{className:"sr-only","aria-live":"polite",children:af}),wb&&et.length>0&&wb,!d.length&&!_r.length&&!zr&&!V.trim()&&(M===null||M.total===0)&&c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.list.empty")}),gd!==null&&c.jsx("p",{className:"text-meta text-ink-muted",children:gd}),ls&&!k&&c.jsx("p",{className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.list.truncated_legacy")}),o.available&&o.reported&&!o.connected&&!f&&!w&&c.jsx("p",{className:R("text-meta",d.some(D=>D.active)?"text-ink-dim":"text-warning"),children:h("ui.chat.sidebar.list.offline")})]},"chats");return c.jsxs("nav",{ref:Vl,"aria-label":h("ui.chat.sidebar.nav.chats"),"data-chat-region":"sidebar",tabIndex:-1,onFocus:CX,"data-glass-region":"sidebar",className:"relative flex h-full min-h-0 flex-col bg-surface p-2 text-ink",onKeyDown:EX,children:[le&&Ue&&c.jsx(VJe,{row:Ue,grouped:lf,onShowGroups:()=>De({...Nt,tagsEnabled:!0,groupBy:"section"}),onClose:()=>dt(null),returnFocus:Dt},Ue.session_id),c.jsxs(bZ,{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(vt,{content:"Search chats and agents",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-search":!0,"aria-label":h("ui.chat.sidebar.header.search"),onClick:()=>{Z(!0),window.requestAnimationFrame(()=>C.current?.focus())},children:c.jsx(_h,{"aria-hidden":"true"})})}),c.jsxs(xh,{open:tt,onOpenChange:ht,children:[c.jsx(vt,{content:"View options",children:c.jsx(iE,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-view-options":!0,"aria-label":h("ui.chat.sidebar.header.view_options"),"aria-expanded":tt,className:R(pX&&"bg-row-selected text-ink hover:bg-row-selected"),children:c.jsx(Lp,{"aria-hidden":"true"})})})}),c.jsx(Bu,{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(jJe,{view:Nt,counts:vX,tagsAvailable:le,autoTagAvailable:Qe,onView:De})})]}),c.jsxs(xh,{open:Ot,onOpenChange:Ut,children:[c.jsx(vt,{content:"New agent or team",children:c.jsx(iE,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-create":!0,"aria-label":h("ui.chat.sidebar.header.create"),"aria-expanded":Ot,children:c.jsx(qce,{"aria-hidden":"true"})})})}),c.jsxs(Bu,{align:"end",className:"w-44 p-1","data-sidebar-create-panel":!0,children:[c.jsxs("button",{type:"button","data-sidebar-create-agent":!0,onClick:()=>{Ut(!1),s("/agents?create=agent")},className:"flex h-7 w-full items-center gap-2 rounded-md px-1 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:[c.jsx(Ade,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:h("ui.chat.sidebar.header.create_agent")})]}),c.jsxs("button",{type:"button","data-sidebar-create-team":!0,onClick:()=>{Ut(!1),s("/agents?create=team")},className:"flex h-7 w-full items-center gap-2 rounded-md px-1 text-start text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart hover:bg-row-hover hover:text-ink",children:[c.jsx(Vm,{"aria-hidden":"true",className:"size-3.5 shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate",children:h("ui.chat.sidebar.header.create_team")})]})]})]}),c.jsx(vt,{content:"Open agent…",children:c.jsx(ce,{variant:"ghost",size:"icon-sm","data-sidebar-open-agent":!0,"aria-label":h("ui.chat.sidebar.header.open_agent"),onClick:()=>{$e(),ke(mQe)},children:c.jsx(mce,{"aria-hidden":"true"})})})]}),c.jsxs("div",{className:R("relative mb-2",!ee&&"hidden"),children:[c.jsx("input",{ref:C,"aria-label":h("ui.chat.sidebar.header.search"),placeholder:h("ui.chat.sidebar.search.placeholder"),className:"h-8 w-full rounded-md bg-row-hover pe-9 ps-2 text-body-sm",value:V,onChange:D=>j(D.target.value),onBlur:()=>{V||Z(!1)}}),V&&c.jsx(ce,{variant:"ghost",size:"icon-sm",className:"absolute top-1/2 end-1 -translate-y-1/2 focus-visible:outline-offset-[-2px]!",onClick:()=>u1(C.current,j),"aria-label":h("ui.chat.sidebar.search.clear"),children:c.jsx(Xn,{"aria-hidden":"true"})})]}),hr&&V.trim()&&c.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[c.jsx(xZ,{id:dj,checked:_a,onCheckedChange:D=>hd(D===!0)}),c.jsx(dr,{htmlFor:dj,className:"text-meta text-ink-muted",children:h("ui.chat.sidebar.search.include_archived")})]}),ya&&g&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.too_long",{max:py})}),V&&g&&!uo&&!ya&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.names_only")}),V&&uo&&nr.isError&&c.jsxs("p",{className:"pb-2 text-meta text-ink-muted",children:[h("ui.chat.sidebar.search.unavailable")," ",c.jsx(ce,{variant:"link",size:"sm",type:"button",onClick:()=>void nr.refetch(),children:h("ui.common.actions.retry")})]}),V.trim()&&z&&!_r.length&&Ig&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.no_match",{query:V.trim()})}),vI&&VB(mI?.rows.length??0,_r.length)&&c.jsx("p",{className:"pb-2 text-meta text-ink-muted",children:h("ui.chat.sidebar.search.searching")}),c.jsx("p",{"aria-live":"polite",className:"sr-only",children:vI&&VB(mI?.rows.length??0,_r.length)?"Searching conversations.":V.trim()&&z&&!_r.length&&Ig?`Nothing in your chats matches ${V.trim()}.`:""}),c.jsxs("div",{ref:TX,id:TZe,tabIndex:-1,"data-sidebar-region":"scroller","data-tag-drag-list":"","data-lo-sidebar-edge-cues":!0,onScroll:()=>{rj(ff.current,RI),rj(wn.current,AI),zc()},className:"relative min-h-0 flex-1 space-y-4 overflow-y-auto p-1 [overflow-anchor:none] [scrollbar-gutter:stable]",children:[FX,DX,AX&&IX]}),(f||fe.error||Xe.error)&&!w&&!S&&c.jsxs("div",{className:"pt-2 text-meta text-ink-muted",children:[c.jsx("p",{children:f||fe.error?.message||Xe.error?.message}),c.jsx("button",{type:"button",className:"mt-1 underline",onClick:()=>{Cs(),fe.refetch(),Xe.refetch()},children:h("ui.chat.sidebar.list.retry_refresh")})]})]})]})}const Fx={recent:()=>h("ui.canvas.files.recent"),name:()=>h("ui.canvas.files.name"),kind:()=>h("ui.canvas.files.kind"),modified:()=>h("ui.canvas.files.modified"),created:()=>h("ui.canvas.files.created"),size:()=>h("ui.canvas.files.size")},OZe={Highlights:()=>h("ui.canvas.files.highlights"),"Working files":()=>h("ui.canvas.files.working"),Images:()=>h("ui.canvas.files.images"),Videos:()=>h("ui.canvas.files.videos"),Sounds:()=>h("ui.canvas.files.audio"),Documents:()=>h("ui.canvas.files.documents"),Spreadsheets:()=>h("ui.canvas.files.spreadsheets"),Other:()=>h("ui.canvas.files.other"),Files:()=>h("ui.canvas.files.files"),Attachments:()=>h("ui.canvas.files.attachments")},Fk=e=>{switch(e){case"images":return h("ui.canvas.files.images");case"video":return h("ui.canvas.files.videos");case"documents":return h("ui.canvas.files.documents");case"spreadsheets":return h("ui.canvas.files.spreadsheets");case"audio":return h("ui.canvas.files.audio");case"code":return h("ui.canvas.files.code");case"presentations":return h("ui.canvas.files.presentations");case"archives":return h("ui.canvas.files.archives");default:return h("ui.canvas.files.other")}},LZe=/[/\\]/,BZe=300;function jZe(e){try{return e.matches(":focus-visible")}catch{return!1}}const bj="pointer-events-none absolute top-1 end-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",HZe={items:[],complete:!0,state:"ready",capable:!1,retry:()=>{}};function UZe({conversationId:e,items:t,index:n,cwd:s,onOpen:r,materialise:i,legacyScan:a,attachments:o=HZe}){const l=Ve(),u=Fs(le=>le.conversations[e]?.selectedTabId),[d,f]=m.useState(t),[p,g]=m.useState(!1),v=nt(le=>le.finderFiles),b=nt(le=>le.setFinderFiles),[x,_]=m.useState(""),w=m.useMemo(()=>new Set(v.closedSections),[v.closedSections]),[y,S]=m.useState(null),C=m.useRef(!1),[E,k]=m.useState({width:400,height:700,top:0}),F=m.useRef(null),A=m.useRef(null),I=m.useRef(new Map),N=m.useRef(new Map),[P,M]=m.useState(null),Y=m.useRef(null),[O,X]=m.useState(!1),Q=m.useRef(0),ie=m.useRef(null),G=m.useRef(!1);m.useEffect(()=>{if(!O||o.state==="loading")return;const le=window.setTimeout(()=>X(!1),Math.max(0,BZe-(Date.now()-Q.current)));return()=>window.clearTimeout(le)},[O,o.state]),m.useEffect(()=>{O||!G.current||o.state!=="loading"&&(G.current=!1,o.state==="error"&&ie.current?.focus({preventScroll:!0}))},[O,o.state]),m.useEffect(()=>{n.localReadAllowed===!1?(f([]),M(null)):(!p||d.length===0)&&P===null&&f(t)},[t,p,P,n.localReadAllowed,d.length]);const[ne,oe]=m.useState(),[B,H]=m.useState(!1),U=m.useRef({text:"",at:0}),z=n.localReadAllowed===!1?[]:d,te=!!(x.trim()||v.kinds.length),fe=m.useMemo(()=>{const le=new Set(cL(z.map(Qe=>Qe.row),{query:x,kinds:v.kinds}).map(Qe=>Qe.document.id));return eJ(z.filter(Qe=>le.has(Qe.row.document.id)),v)},[z,x,v]),J=m.useMemo(()=>{if(n.localReadAllowed===!1&&!o.items.length)return[];const le=new Set(cL(o.items.map(Qe=>Qe.row),{query:x,kinds:v.kinds}).map(Qe=>Qe.document.id));return o.items.filter(Qe=>le.has(Qe.row.document.id))},[o.items,x,v.kinds,n.localReadAllowed]),Se=m.useMemo(()=>tJ(fe,v,te,w,J),[fe,v,te,w,l,J]),W=m.useMemo(()=>nJ(Se,E.width,v.group),[Se,E.width,v.group]);m.useEffect(()=>{C.current&&y&&W.positions.has(y)&&document.activeElement===document.body&&I.current.get(y)?.focus({preventScroll:!0})},[W,y]);const Ce=W.bands.find(le=>le.items.length)?.items[0]?.row.document.id??null,K=y?.startsWith("header:")||y&&W.positions.has(y)?y:W.bands.find(le=>le.items.length)?.items[0]?.row.document.id??(Se[0]?`header:${Se[0].id}`:null),me=m.useMemo(()=>new Set(sJ(W,E.top,E.height,K)),[W,E.top,E.height,K]),Ee=m.useMemo(()=>[...J,...fe].filter(le=>le.row.media==="image"&&W.positions.has(le.row.document.id)),[fe,J,W]),Ae=Ee.find(le=>le.row.document.id===P);m.useEffect(()=>{if(!Ae){oe(void 0),H(!1);return}let le=!0,Qe;return oe(void 0),pE(Ae.row.document).then(async et=>{le&&(Qe=y8(await et.arrayBuffer(),et.type),le?oe(Qe):I_(Qe))}).catch(()=>{le&&(oe(void 0),H(!0))}),()=>{le=!1,Qe&&I_(Qe)}},[Ae]),m.useEffect(()=>{const le=F.current;if(!le)return;const Qe=()=>k(ue=>({...ue,width:le.clientWidth,height:le.clientHeight}));Qe();const et=new ResizeObserver(Qe);return et.observe(le),()=>et.disconnect()},[]);const se=m.useCallback(le=>{const Qe=W.positions.get(le),et=F.current;if(!Qe||!et)return;const ue=W.bands[Qe.band];ue.top<et.scrollTop?et.scrollTop=Math.max(0,ue.top-Eb-rJ):ue.top+ue.height>et.scrollTop+et.clientHeight&&(et.scrollTop=ue.top+ue.height-et.clientHeight),S(le),k(Le=>({...Le,top:et.scrollTop})),requestAnimationFrame(()=>I.current.get(le)?.focus())},[W]),he=(le,Qe)=>{if(le.target===le.currentTarget){if(le.key==="Escape"&&(x||v.kinds.length)){le.preventDefault(),le.stopPropagation(),_(""),b({kinds:[]});return}if(le.key==="/"){le.preventDefault(),A.current?.focus();return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End","PageUp","PageDown"].includes(le.key)){le.preventDefault();const et=W.positions.get(Qe.row.document.id);if(et&&["ArrowUp","ArrowDown"].includes(le.key)){const Le=W.bands[et.band+(le.key==="ArrowUp"?-1:1)];if(Le?.kind==="header"){le.preventDefault(),S(`header:${Le.section.id}`),N.current.get(Le.section.id)?.focus();return}}const ue=oJ(W,Qe.row.document.id,le.key,E.height);ue&&se(ue);return}if(le.key.length===1&&!le.ctrlKey&&!le.metaKey&&le.key!==" "){const et=Date.now(),ue=(et-U.current.at<500?U.current.text:"")+le.key.toLocaleLowerCase();U.current={text:ue,at:et};const Le=fe.findIndex(Ne=>Ne.row.document.id===Qe.row.document.id);for(let Ne=1;Ne<=fe.length;Ne++){const Ue=fe[(Le+Ne)%fe.length];if(W.positions.has(Ue.row.document.id)&&ep(Ue.row.name).startsWith(ep(ue))){le.preventDefault(),se(Ue.row.document.id);break}}}}},xe=le=>{if(le==="Working files"){te||b({workingOpen:!v.workingOpen});return}if(te)return;const Qe=new Set(w);Qe.has(le)?Qe.delete(le):Qe.add(le),b({closedSections:[...Qe]})},Je=()=>{_(""),b({kinds:[]}),A.current?.focus()},pe=m.useRef(null);m.useEffect(()=>()=>{pe.current!==null&&cancelAnimationFrame(pe.current)},[]);const Xe=()=>{pe.current===null&&(pe.current=requestAnimationFrame(()=>{pe.current=null;const le=F.current;le&&k(Qe=>({...Qe,top:le.scrollTop}))}))};return c.jsxs("div",{onKeyDownCapture:le=>{const Qe=le.target;le.key==="/"&&!le.ctrlKey&&!le.metaKey&&Qe instanceof HTMLElement&&!Qe.closest("input,textarea,[contenteditable=true]")&&(le.preventDefault(),le.stopPropagation(),A.current?.focus())},className:R("@container/fileslist flex min-h-0 flex-1 flex-col"),children:[c.jsxs("div",{className:R("shrink-0 space-y-1 px-2 py-2"),"data-tour-tag":"files-scanner-head",children:[c.jsxs("div",{className:R("flex items-center gap-2"),children:[c.jsx(bs,{ref:A,value:x,placeholder:h("ui.canvas.finder_files_view.ui_canvas_files_searchplaceholder"),"aria-label":h("ui.canvas.files.search"),className:R("min-w-0 flex-1"),onChange:le=>_(le.target.value),onKeyDown:le=>{le.key==="ArrowDown"||le.key==="Escape"&&!x&&!v.kinds.length?(le.preventDefault(),le.stopPropagation(),Ce&&se(Ce)):le.key==="Escape"&&(le.preventDefault(),le.stopPropagation(),_(""),b({kinds:[]}))}}),c.jsxs(Po,{children:[c.jsx(eo,{asChild:!0,children:c.jsxs(ce,{variant:"outline",size:"md","aria-label":`${h("ui.canvas.files.sort")}: ${Fx[v.sort]()}, ${v.order==="asc"?h("ui.canvas.files.asc"):h("ui.canvas.files.desc")}`,children:[c.jsx(uce,{"aria-hidden":"true"}),c.jsx("span",{className:"hidden @min-[440px]/fileslist:inline",children:Fx[v.sort]()}),c.jsx("span",{"aria-hidden":"true",children:v.order==="asc"?"↑":"↓"})]})}),c.jsxs(Mo,{align:"end",children:[Object.keys(Fx).map(le=>c.jsx(Ug,{checked:v.sort===le,onCheckedChange:()=>b({sort:le,order:["modified","created","size"].includes(le)?"desc":"asc"}),children:Fx[le]()},le)),c.jsx(Nr,{}),c.jsx(Ug,{checked:v.order==="asc",onCheckedChange:()=>b({order:"asc"}),children:h("ui.canvas.files.asc")}),c.jsx(Ug,{checked:v.order==="desc",onCheckedChange:()=>b({order:"desc"}),children:h("ui.canvas.files.desc")}),c.jsx(Nr,{}),c.jsx(Ug,{checked:v.group,onCheckedChange:le=>b({group:le}),children:h("ui.canvas.files.group")})]})]}),c.jsxs(Po,{children:[c.jsx(eo,{asChild:!0,children:c.jsxs(ce,{variant:"outline",size:"md",className:R(v.kinds.length>0&&"bg-accent-wash"),"aria-label":`${h("ui.canvas.files.filter")}: ${v.kinds.map(Fk).join(", ")||h("ui.canvas.files.files")}`,children:[c.jsx(Yce,{"aria-hidden":"true"}),v.kinds.length?`${v.kinds.length}`:h("ui.canvas.files.filter")]})}),c.jsxs(Mo,{align:"end",children:[Gwe.map(le=>c.jsx(Ug,{checked:v.kinds.includes(le.id),onCheckedChange:Qe=>b({kinds:Qe?[...v.kinds,le.id]:v.kinds.filter(et=>et!==le.id)}),children:Fk(le.id)},le.id)),c.jsx(Nr,{}),c.jsx(Jt,{onSelect:()=>b({kinds:[]}),children:h("ui.canvas.files.reset")})]})]})]}),c.jsxs("div",{className:R("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?"":te?h("ui.canvas.files.narrowCount",{shown:Bd(fe.length+J.length),total:Bd(t.length+o.items.length)}):o.state==="loading"&&!t.length&&!O?h("ui.canvas.files.loading"):h("ui.canvas.files.count",{count:t.length+o.items.length}),n.mode==="index"&&(n.state==="loading"||n.state==="building")&&n.pendingTotal>0?`${t.length?" · ":""}${h("ui.canvas.files.progress",{loaded:Bd(n.loadedRows),total:Bd(n.pendingTotal)})}`:"",n.state==="loading"&&t.length>0?` · ${h("ui.canvas.files.loading")}`:n.state==="building"?` · ${h("ui.canvas.files.building")}`:n.statComplete?"":` · ${h("ui.canvas.files.readingStats")}`]}),s&&c.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>void rse(s),children:[c.jsx(ky,{"aria-hidden":"true"}),h("ui.canvas.files.folder")]})]}),v.kinds.length>0&&c.jsxs("div",{className:R("flex items-center gap-2 text-meta text-ink-muted"),children:[c.jsx("span",{children:v.kinds.map(Fk).join(", ")}),c.jsxs(ce,{variant:"ghost",size:"sm",onClick:()=>b({kinds:[]}),children:[c.jsx(Xn,{"aria-hidden":"true"}),h("ui.canvas.files.reset")]})]}),o.state==="error"&&!O?c.jsxs("output",{title:h("ui.canvas.files.attachmentsErrorReason"),className:R("text-body-sm text-ink-muted"),children:[h("ui.canvas.files.attachmentsError"),c.jsx(ce,{ref:ie,variant:"ghost",size:"sm",onClick:le=>{G.current=document.activeElement===le.currentTarget,Q.current=Date.now(),X(!0),o.retry()},children:h("ui.canvas.files.retry")})]}):O?c.jsx("output",{className:R("text-body-sm text-ink-dim"),children:h("ui.canvas.files.loading")}):null,n.error&&fe.length>0&&c.jsxs("output",{className:R("text-body-sm text-ink-muted"),children:[n.error,c.jsx(ce,{variant:"ghost",size:"sm",onClick:n.refresh,children:n.state==="building"?h("ui.canvas.files.continue"):h("ui.canvas.files.retry")})]})]}),c.jsx("section",{ref:F,"aria-label":h("ui.canvas.files.region"),"data-tour-tag":"files-scroller","data-glass-plane":"clear",className:R("min-h-0 flex-1 overflow-auto bg-surface px-2 pb-2"),onScroll:Xe,onKeyDown:le=>{!le.defaultPrevented&&le.key==="Escape"&&(x||v.kinds.length)&&(le.preventDefault(),le.stopPropagation(),_(""),b({kinds:[]}))},onPointerEnter:()=>g(!0),onPointerLeave:()=>{F.current?.contains(document.activeElement)||g(!1)},onFocusCapture:()=>{C.current=!0,g(!0)},onBlurCapture:le=>{le.relatedTarget&&!le.currentTarget.contains(le.relatedTarget)&&(C.current=!1,g(!1))},children:!fe.length&&!J.length?c.jsxs("div",{className:R("flex min-h-40 flex-col items-center justify-center gap-2 p-4 text-center"),children:[c.jsx("p",{className:R("text-heading text-ink"),children:n.state==="error"?n.error??h("ui.canvas.files.error"):n.state==="unsupported"?n.error??h("ui.canvas.files.remote"):n.state==="loading"||o.state==="loading"?h("ui.canvas.files.loading"):n.state==="building"?h("ui.canvas.files.building"):te?h("ui.canvas.files.noMatch"):h("ui.canvas.files.empty")}),n.state==="ready"&&o.state!=="loading"&&!te&&c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.files.emptyDetail")}),n.error&&c.jsx(ce,{variant:"outline",size:"sm",onClick:n.refresh,children:n.state==="building"?h("ui.canvas.files.continue"):h("ui.canvas.files.retry")}),te&&c.jsx(ce,{variant:"outline",size:"sm",onClick:Je,children:h("ui.canvas.files.clear")})]}):Se.map(le=>{const Qe=W.bands.map((Ne,Ue)=>Ne.section.id===le.id?Ue:-1).filter(Ne=>Ne>=0),et=W.bands[Qe[0]],ue=W.bands[Qe.at(-1)??0],Le=ue.top+ue.height-et.top-Eb;return c.jsxs("section",{style:{height:Le+Eb},children:[c.jsx("h3",{"data-glass-plane":"band-backdrop",className:R("sticky top-0 z-10 h-8 bg-surface"),children:c.jsxs("button",{type:"button",ref:Ne=>{Ne?N.current.set(le.id,Ne):N.current.delete(le.id)},tabIndex:K===`header:${le.id}`?0:-1,onFocus:()=>S(`header:${le.id}`),onKeyDown:Ne=>{if(Ne.key==="ArrowRight"&&!le.open||Ne.key==="ArrowLeft"&&le.open)Ne.preventDefault(),xe(le.id);else if(Ne.key==="ArrowDown"||Ne.key==="ArrowUp")if(Ne.preventDefault(),Ne.key==="ArrowDown"&&le.open&&le.items.length)se(le.items[0].row.document.id);else{const Ue=Se[Se.indexOf(le)+(Ne.key==="ArrowDown"?1:-1)];Ue&&(S(`header:${Ue.id}`),N.current.get(Ue.id)?.focus())}},"aria-expanded":le.open,"aria-disabled":te,onClick:()=>xe(le.id),className:R("flex h-8 w-full items-center gap-2 rounded-sm px-2 text-start font-medium text-body-sm text-ink hover:bg-row-hover",te&&"cursor-default hover:bg-surface",le.id!=="Working files"&&!le.highlights&&Se.some(Ne=>Ne.id==="Working files")&&"ps-4"),children:[le.open?c.jsx(Ei,{size:14,"aria-hidden":"true"}):c.jsx(Vi,{size:14,"aria-hidden":"true",className:"rtl:-scale-x-100"}),OZe[le.id]?.()??le.label,c.jsx("span",{className:R("text-meta text-ink-muted"),children:Bd(le.items.length||(le.id==="Working files"?fe.filter(Ne=>!Ne.highlighted).length:0))}),le.id===iJ&&(o.state==="loading"?O?null:c.jsx("span",{className:R("text-meta text-ink-dim"),children:h("ui.canvas.files.loading")}):o.state==="ready"&&!o.complete?c.jsx("span",{title:h("ui.canvas.files.attachmentsPartialReason"),className:R("text-meta text-ink-dim"),children:h("ui.canvas.files.attachmentsPartial")}):null)]})}),c.jsx("ul",{"data-tour-tag":"files-grid",className:R("relative"),style:{height:Le},children:Qe.filter(Ne=>W.bands[Ne].kind!=="header"&&me.has(Ne)).map(Ne=>{const Ue=W.bands[Ne];return c.jsx("li",{style:{position:"absolute",top:Ue.top-et.top-Eb,height:Ue.height,left:0,right:0},children:c.jsx("div",{className:R("grid gap-1"),style:{gridTemplateColumns:`repeat(${Ue.cols},minmax(0,1fr))`},children:Ue.items.map(dt=>c.jsx(GZe,{item:dt,current:u===dt.row.document.id||u===dt.row.document.path,band:Ue,tabIndex:dt.row.document.id===K?0:-1,onFocus:()=>S(dt.row.document.id),buttonRef:St=>{St?I.current.set(dt.row.document.id,St):I.current.delete(dt.row.document.id)},onKeyDown:St=>he(St,dt),onOpen:()=>r(dt.row.document),onExpand:()=>{Y.current=I.current.get(dt.row.document.id)??null,M(dt.row.document.id)},materialise:dt.attachment&&!C8(o.capable,dt.attachment.materialisable)?void 0:()=>i(dt.row.document)},dt.row.document.id))})},Ue.items[0].row.document.id)})})]},le.id)})}),n.mode==="fallback"&&a?.stopped&&c.jsx(ce,{variant:"ghost",size:"sm",onClick:a.resume,children:h("ui.canvas.files.earlier")}),Ae&&c.jsx(ise,{open:!0,src:ne,pending:!ne&&!B,fallback:c.jsx("span",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.files.unreadable")}),label:Ae.row.name,onOpenChange:le=>{le||M(null)},restoreFocusTo:Y,group:{index:Ee.indexOf(Ae),count:Ee.length,onPrev:()=>M(Ee[(Ee.indexOf(Ae)+Ee.length-1)%Ee.length].row.document.id),onNext:()=>M(Ee[(Ee.indexOf(Ae)+1)%Ee.length].row.document.id)}})]})}function GZe({item:e,current:t,band:n,tabIndex:s,onFocus:r,buttonRef:i,onKeyDown:a,onOpen:o,onExpand:l,materialise:u}){Ve();const d=e.row.document,f=e.attachment?.materialisable===!1,p=e.attachment?.materialisable==="pending",g=f||p,[v,b]=ase("200px"),x=ose(d,b&&e.row.media==="image"&&!e.row.missing),[_,w]=m.useState(!1),y=m.useRef(null),S=n.kind==="tiles"||n.kind==="video",C=S?aJ(n):n.kind==="highlight"?40:28,E=d.artifact?e.attachment?h("ui.canvas.files.attachmentTooltip",{name:d.title,digest:d.artifact.digest.slice(0,J5)}):S8({...d.artifact,title:d.title}):d.path,k=Ywe(E,e.attachment?.status,f),[F,A]=m.useState(!1),I=f&&F?h("ui.canvas.files.attachmentRefused"):null,N=!!(e.attachment?.status||I),P=()=>{f&&!ie?da(h("ui.canvas.files.attachmentRefused")):ie&&w(!0)},M=!(e.attachment&&e.row.missing&&!LZe.test(d.path)||g&&!d.artifact),Y=lg(d.path,d.type)===null||g?void 0:o,O=d.artifact&&!e.attachment?PA(d.artifact):void 0,X=d.artifact&&!e.row.missing?u:void 0,Q=e.row.missing&&!d.artifact,ie=M&&lse({file:d.path,resolvePath:X,missing:Q,onShowInCanvas:Y,mediaKind:n.kind==="audio"?"audio":e.row.media==="image"?"image":"video",onExpand:n.kind!=="audio"&&e.row.media==="image"?l:void 0,saveName:O}).length>0,G=nt(H=>H.finderFiles.sort),ne=G==="created"?e.created:e.modified,oe=ne===null?"":EA(ne*1e3,{month:"short",day:"numeric"}),B=e.attachment?e.attachment.note:e.row.missing?d.artifact?h("ui.canvas.files.gone"):h("ui.canvas.files.missing"):G==="modified"||G==="created"?oe:G==="size"?e.row.size??"":d.artifact?h("ui.canvas.files.sessionOnly"):e.row.size??"";return n.kind==="audio"?c.jsxs("div",{ref:v,className:R("group relative min-w-0 rounded-sm px-1 py-0.5",t?yo:"hover:bg-row-hover"),"data-tour-tag":"file-row","data-file-id":d.id,onContextMenu:H=>{H.preventDefault(),w(!0)},children:[c.jsxs("div",{className:R("flex min-w-0 items-center gap-2 pe-8"),children:[c.jsx("button",{type:"button",ref:H=>{y.current=H,i(H)},tabIndex:s,onFocus:r,title:k,onClick:o,onKeyDown:H=>{H.shiftKey&&H.key==="F10"||H.key==="ContextMenu"?(H.preventDefault(),P()):a(H)},className:R("min-w-0 flex-1 truncate rounded-sm py-1 text-start text-body-sm",e.row.missing?"text-ink-muted":"text-ink"),children:e.row.name}),c.jsx("span",{title:ne===null?void 0:lE(ne*1e3),className:R("shrink-0 text-meta text-ink-dim"),children:B})]}),c.jsx(X9,{doc:d,label:e.row.name}),c.jsx("div",{className:bj,onKeyDown:H=>H.stopPropagation(),children:c.jsx(L0,{file:d.path,tooltip:h("ui.canvas.finder_files_view.ui_canvas_files_fileactions"),label:d.title,open:_,onOpenChange:w,onCloseAutoFocus:H=>{H.preventDefault(),y.current?.focus({preventScroll:!0})},triggerTabIndex:-1,mediaKind:"audio",onShowInCanvas:Y,resolveBytes:()=>pE(d),saveName:O,resolvePath:X,missing:Q})})]}):c.jsxs("div",{ref:v,className:R("group relative min-w-0 rounded-sm",t?yo:"hover:bg-row-hover"),"data-tour-tag":"file-row","data-file-id":d.id,onContextMenu:H=>{H.preventDefault(),w(!0)},children:[c.jsxs("button",{type:"button",ref:H=>{y.current=H,i(H)},tabIndex:s,onFocus:H=>{f&&A(jZe(H.currentTarget)),r()},onBlur:()=>A(!1),title:k,onClick:S&&e.row.media==="image"?l:o,onKeyDown:H=>{H.shiftKey&&H.key==="F10"||H.key==="ContextMenu"?(H.preventDefault(),P()):a(H)},className:R("w-full min-w-0 rounded-sm p-1 text-start",!S&&"flex items-center gap-2 pe-8",e.row.missing&&"text-ink-muted"),style:{height:n.height-(S?4:0)},children:[c.jsx("span",{style:{height:C,width:S?"100%":C},className:R("flex shrink-0 items-center justify-center overflow-hidden rounded-sm bg-media-surface",S&&"mb-1"),children:x.state==="ready"&&e.row.media==="image"?c.jsx("img",{src:x.url,alt:"",className:R("h-full w-full object-contain outline-1 -outline-offset-1 outline-hairline")}):d.type==="video"?c.jsxs("span",{className:R("flex flex-col items-center gap-1 text-ink-muted"),children:[c.jsx(cse,{"aria-hidden":"true"}),S&&c.jsx("span",{className:R("text-meta"),children:h("ui.canvas.files.play")})]}):x.state==="loading"&&e.row.media==="image"&&!e.row.missing?null:c.jsx(Ey,{size:16,"aria-hidden":"true"})}),c.jsxs("span",{className:R("flex min-w-0 flex-1 flex-col",S?"text-meta":"text-body-sm"),children:[c.jsxs("span",{className:R("flex min-w-0 gap-2",S&&e.attachment?"flex-col gap-0":"items-center justify-between"),children:[c.jsx("span",{className:R("min-w-0 truncate",!S&&N?"min-w-[min(6rem,50%)] shrink":"flex-1",e.row.missing?"text-ink-muted":"text-ink"),children:e.row.name}),!S&&e.row.showParent&&e.row.parent&&c.jsx("span",{className:R("min-w-0 shrink truncate text-mono-sm text-ink-dim"),children:e.row.parent}),c.jsx("span",{title:ne===null||N?void 0:lE(ne*1e3),className:R("text-meta text-ink-dim",S&&e.attachment?"min-w-0 truncate":N?"min-w-[min(13rem,50%)] flex-1 truncate text-end":"shrink-0"),children:I?c.jsx("bdi",{children:I}):e.attachment&&!e.attachment.status?c.jsxs(c.Fragment,{children:[c.jsx("bdi",{children:e.attachment.size}),e.attachment.size&&e.attachment.when?c.jsx("span",{"aria-hidden":"true",children:" · "}):null,c.jsx("bdi",{children:e.attachment.when})]}):S&&d.artifact&&!e.attachment?h("ui.canvas.files.inSession"):c.jsx("bdi",{children:S&&e.attachment?e.attachment.tileStatus:B})})]}),n.kind==="highlight"&&e.why&&c.jsx("span",{className:R("line-clamp-2 text-meta text-ink-muted"),children:e.why})]})]}),c.jsxs("div",{className:bj,onKeyDown:H=>H.stopPropagation(),children:[S&&e.row.media==="image"&&c.jsx(vt,{content:`${h("ui.canvas.files.expand")}: ${d.title}`,children:c.jsx(ce,{variant:"ghost",size:"icon-sm",tabIndex:-1,className:R("bg-accent-wash"),"aria-label":`${h("ui.canvas.files.expand")}: ${d.title}`,onClick:l,children:c.jsx(use,{"aria-hidden":"true"})})}),M&&c.jsx(L0,{file:d.path,tooltip:e.row.media==="image"?h("ui.canvas.finder_files_view.ui_canvas_files_imageactions"):h("ui.canvas.finder_files_view.ui_canvas_files_fileactions"),label:d.title,open:_,onOpenChange:w,onCloseAutoFocus:H=>{H.preventDefault(),y.current?.focus({preventScroll:!0})},triggerTabIndex:-1,mediaKind:e.row.media==="image"?"image":"video",onShowInCanvas:Y,onExpand:e.row.media==="image"?l:void 0,resolveBytes:()=>pE(d),saveName:O,resolvePath:X,missing:Q})]})]})}const xj=[],VZe=({conversationId:e,sessionId:t,cwd:n,index:s,onSwitchToDocumentView:r,scan:i=null,attachments:a=null})=>{const o=Fs(k=>k.conversations[e]?.mentionedFiles??xj),l=m.useMemo(()=>s.mode==="index"?s.rows.map(k=>ywe(k,t??"")):s.mode==="fallback"?o:xj,[s.mode,s.rows,o,t]),u=Fs(k=>k.setFiles),d=Fs(k=>k.setOpenTabs),f=Fs(k=>k.setSelectedTab),p=Fs(k=>k.setViewMode),g=m.useMemo(()=>t9(l),[l]),v=m.useCallback(async k=>{const F=k.title,A=Q=>{const G=Fs.getState().conversations?.[e],ne=G?.files??[],oe=G?.openTabs??[],B=ne.findIndex(te=>te.id===Q.id),H=B!==-1?[...ne.slice(0,B),Q,...ne.slice(B+1)]:[...ne,Q];u(e,H);const z=oe.some(te=>te.id===Q.id)?oe:[...oe,{id:Q.id,title:Q.title}];d(e,z),f(e,Q.id),p(e,"documents"),r(Q.id)},I=Q=>{Q&&console.error("Error processing file:",Q);try{k.path.startsWith("data:")?console.warn("Opening data URI with OS default is not directly supported here.",`${k.path.substring(0,50)}...`):window.api.openFile(k.path)}catch(ie){console.error("Error opening file natively:",ie)}},N=lg(k.path,k.type);if(k.artifact){A({...k,content:""});return}if(k.path.startsWith("data:")){if(N===null)return I();A(So(k.path,{title:F,content:k.path,type:Gu(F)}));return}const P=e8(k.path),M=typeof window.api?.probeFiles=="function"?(await window.api.probeFiles([P]))[0]??null:null,Y=!!(M?.exists&&M.isFile);if(k.availability==="missing"&&!Y&&M?.error===void 0){nn(h("ui.canvas.file_viewer.file_no_longer_exists_at",{value:M?.resolved??P}),{description:h(k.id.startsWith(e_)?"ui.canvas.files.attachmentGoneRecovery":"ui.canvas.file_viewer.copy_its_path_from_the_row_s_menu_to_look_for_it_or_check_whether_the_ag")});return}if(N===null)return I();const O={title:F,type:Gu(P),lastAgentModified:M?.mtimeMs??k.lastAgentModified,readMtimeMs:M?.mtimeMs??void 0,availability:Y?"present":void 0,sizeBytes:M?.sizeBytes??k.sizeBytes},X=Ny[N];if(X==="bytes"||X==="range"){A(So(P,O));return}try{const Q=await window.api.readFile(P,X);if(!Q.success){const ie=Q.error?Q.error instanceof Error?Q.error.message:String(Q.error):h("ui.canvas.file_viewer.unknown_error_reading_file");return I(ie)}A(So(P,{...O,content:Q.data}))}catch(Q){const ie=Q instanceof Error?Q.message:String(Q??h("ui.canvas.file_viewer.unknown_error_reading_file"));return I(ie)}},[e,u,d,f,p,r]),b=m.useMemo(()=>Qwe(a?.items??[],t??""),[a?.items,t]),x=m.useMemo(()=>dse({items:a?.items??[]}),[a?.items]),_=g.map((k,F)=>{const A=s.mode==="index"?s.rows[F]:void 0;return{row:k,highlighted:A?.highlighted??!1,why:A?.highlight_why??"",created:A?.created_at??null,modified:A?.modified_at??(k.document.lastAgentModified===void 0?null:k.document.lastAgentModified/1e3),mentioned:A?.first_ts??A?.first_seq??F}}),w=Jwe(_,k=>k.row.artifact?.digest,x),y=a?.capable??!1,S=m.useMemo(()=>new Set(b.filter(k=>k.attachment?.materialisable===!1||k.attachment?.materialisable==="pending").map(k=>k.row.document.id)),[b]),C=k=>C8(y,S.has(k.id)?!1:null),E=async k=>{if(k.id.startsWith(e_)&&k.artifact){if(!C(k))throw new Error("Backend cannot materialise this attachment");if(!t)throw new Error("No session for the attachment");return hse(t,k.artifact.digest)}if(!t||s.mode!=="index")throw new Error("No indexed artifact owner");const F=await m5({op:"sessions.files.materialise",sessionId:t,fileId:k.indexedFileId??k.id}),A=F.body.result;if(F.status!==200||!A?.path)throw new Error(h("ui.canvas.files.saveError"));return A.path};return c.jsx(UZe,{items:w,conversationId:e,index:s.mode==="fallback"?{...s,state:"ready"}:s,legacyScan:i,cwd:s.state==="unsupported"?void 0:n,materialise:E,attachments:{items:b,complete:(a?.complete??!0)&&!a?.truncated,state:a?.state??"ready",capable:y,retry:a?.retry??(()=>{})},onOpen:k=>{S.has(k.id)&&!k.artifact||(k.artifact&&(C(k)||!k.id.startsWith(e_))&&k.type!=="image"&&k.type!=="video"&&k.type!=="audio"?E(k).then(F=>v(So(F,{title:k.title,type:k.type}))).catch(()=>nn(h("ui.canvas.file_viewer.ui_canvas_files_saveerror"))):v(k))}})},WZe=m.memo(VZe),$Ze=({entries:e,truncated:t,goalPresent:n})=>(Ve(),e.length===0&&!t?c.jsx(PR,{title:h("ui.canvas.goals_viewer.no_goals_completed_yet"),description:n?h("ui.canvas.goals_viewer.goals_appear_here_once_they_are_finished"):h("ui.canvas.goals_viewer.no_goal_set_goal_text_to_set_one_finished_goals_are_kept_here")}):c.jsxs("section",{className:R("flex min-h-0 flex-1 flex-col overflow-y-auto"),children:[c.jsxs("div",{className:R("flex items-baseline justify-between gap-2 px-3 pt-2 pb-1"),children:[c.jsx("span",{className:R("shrink-0 text-meta text-ink-muted"),children:h("ui.canvas.goals_viewer.goals")}),c.jsx("span",{className:R("min-w-0 flex-1 truncate text-right text-meta text-ink-dim"),children:t?h("ui.canvas.goals_viewer.count_shown",{count:e.length}):h("ui.canvas.goals_viewer.count",{count:e.length})})]}),t&&c.jsx("p",{className:R("max-w-80 px-3 pb-1 text-meta text-ink-dim"),children:h("ui.canvas.goals_viewer.older_settled_goals_are_not_carried_here_this_list_is_capped")}),c.jsx("ul",{className:R("flex flex-col pb-1.5"),children:e.map(s=>c.jsx(zZe,{entry:s},s.id))})]})),zZe=({entry:e})=>{const t=e.status==="done",n=t?xA:c2,s=qZe(e),r=!!(e.reason?.trim()||e.settled_at);return c.jsx("li",{className:R("flex flex-col"),children:c.jsx(Uh,{disabled:!r,rowClassName:R("h-6 rounded-sm px-3 py-0"),summaryAlign:"center",triggerLabel:`${e.text} — ${s}`,triggerTooltip:e.text,summary:c.jsxs("span",{className:R("flex min-w-0 flex-1 items-center gap-2"),children:[c.jsx("span",{"aria-hidden":!0,className:R("flex size-4 shrink-0 items-center justify-center text-ink-dim"),children:c.jsx(n,{className:R("size-4")})}),c.jsx("span",{className:R("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:R("shrink-0 text-meta text-ink-dim"),title:s,children:s})]}),children:c.jsxs("div",{className:R("flex flex-col gap-1 px-3 pb-1.5"),children:[e.reason?.trim()&&c.jsx("span",{"aria-hidden":!0,className:R("line-clamp-2 text-ink-muted text-meta leading-4"),title:e.reason,children:e.reason}),e.reason?.trim()&&c.jsx("span",{className:R("sr-only"),children:e.reason}),e.settled_at&&c.jsx("span",{className:R("text-mono text-2xs text-ink-dim"),children:e.settled_at})]})})})},qZe=(e,t=new Date)=>{const n=fse(e.settled_at,t);return n?`${e.status} · ${n}`:e.status};function FD(e,t){const n=e.findIndex(s=>s.id===t);return n===-1?null:e[n+1]??e[n-1]??null}const PK="canvas-selected-tab",MK="canvas-document-panel",KZe=({documents:e,activeDocumentId:t,onChangeActiveDocument:n,onCloseDocument:s})=>{Ve();const r=m.useRef(new Map),i=m.useRef(null),[a,o]=m.useState(!1);m.useEffect(()=>{const p=i.current;if(!p)return;const g=()=>{o(p.scrollWidth-p.clientWidth-p.scrollLeft>1)};g(),p.addEventListener("scroll",g,{passive:!0});const v=new ResizeObserver(g);return v.observe(p),()=>{p.removeEventListener("scroll",g),v.disconnect()}},[e]);const l=m.useMemo(()=>pse(e),[e]),u=t&&e.some(p=>p.id===t)?t:e[0]?.id??null;m.useEffect(()=>{if(!u)return;const p=r.current.get(u);(p?.parentElement??p)?.scrollIntoView({block:"nearest",inline:"nearest"})},[u]);const d=m.useCallback((p,g)=>{p.stopPropagation(),s(g);const v=FD(e,g);v&&r.current.get(v.id)?.focus()},[e,s]),f=m.useCallback((p,g)=>{const v=e.length-1;let b;switch(p.key){case"ArrowRight":b=g===v?0:g+1;break;case"ArrowLeft":b=g===0?v:g-1;break;case"Home":b=0;break;case"End":b=v;break;default:return}p.preventDefault();const x=e[b];x&&(r.current.get(x.id)?.focus(),n(x.id))},[e,n]);return e.length===0?null:c.jsxs("div",{className:R("flex shrink-0 items-stretch border-hairline border-b"),children:[c.jsx("div",{ref:i,role:"tablist","aria-label":h("ui.canvas.tabs.open_documents"),"aria-orientation":"horizontal","data-glass-plane":"clear",className:R("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((p,g)=>{const v=p.id===u;return c.jsxs("div",{role:"presentation",className:R("group flex h-6 shrink-0 items-center rounded-sm pe-0.5","transition-colors duration-fast ease-out-quart",v?"bg-surface":"hover:bg-row-hover"),children:[c.jsx("button",{type:"button",role:"tab","aria-selected":v,id:v?PK:void 0,"aria-controls":v?MK:void 0,tabIndex:v?0:-1,title:p.artifact?S8({...p.artifact,title:p.title}):p.path??p.title,ref:b=>{b?r.current.set(p.id,b):r.current.delete(p.id)},onClick:()=>n(p.id),onKeyDown:b=>f(b,g),className:R("max-w-45 truncate rounded-sm py-1 pe-1 ps-2","text-start font-medium text-body-sm","transition-colors duration-fast ease-out-quart",v?"text-ink":"text-ink-muted"),children:l.get(p.id)??p.title}),c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.tabs.close",{value:l.get(p.id)??p.title}),onClick:b=>d(b,p.id),className:R("size-5 [&_svg]:size-3","hover:bg-danger-wash hover:text-danger",!v&&["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(Xn,{"aria-hidden":"true"})})]},p.id)})}),e.length>1&&c.jsxs(Po,{children:[c.jsx(vt,{content:h("ui.canvas.tabs.all_open_files"),children:c.jsx(eo,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.tabs.all_open_files"),className:R("me-1 shrink-0 self-center"),children:c.jsx(Ei,{"aria-hidden":"true"})})})}),c.jsx(Mo,{align:"end",className:R("max-w-80"),children:e.map(p=>c.jsxs(Jt,{onSelect:()=>n(p.id),children:[c.jsx(Js,{"aria-hidden":"true",className:R(p.id!==u&&"invisible")}),c.jsx("span",{className:R("truncate"),children:l.get(p.id)??p.title})]},p.id))})]})]})},YZe=m.memo(KZe),OK=["str","int","float","bool","list","dict"],DD=e=>["desktop","sessions",e??"","variables"];async function XZe(e){return(await rt({op:"sessions.variables.list",sessionId:e})).data}async function QZe(e,t){return(await rt({op:"sessions.variables.create",sessionId:e,key:t.key,value:t.value,type:t.type})).data.variable}async function JZe(e,t){return(await rt({op:"sessions.variables.update",sessionId:e,key:t.key,value:t.value,type:t.type})).data.variable}async function ZZe(e,t){await rt({op:"sessions.variables.delete",sessionId:e,key:t})}function LK(e){return e instanceof Fi&&e.status===404&&/^not found$/i.test(e.message.trim())}function eet(e){return e instanceof Fi&&e.status===404&&!LK(e)}const tet=(e,t)=>Dn({queryKey:DD(e),queryFn:async()=>{if(!e)throw new Error(h("ui.common.errors.session_id_required"));return XZe(e)},enabled:t&&!!e,refetchInterval:n=>n.state.data?.state==="busy"?1500:!1,refetchOnMount:"always",retry:!1}),ID=e=>async(t,n,s)=>{await e.invalidateQueries({queryKey:DD(s.sessionId)})},net=()=>{const e=Mt();return fn({mutationFn:({sessionId:t,...n})=>QZe(t,n),onSuccess:async()=>{Hs(h("ui.notices.variables.created"))},onError:t=>{nn(zi(t,h("ui.notices.variables.create_failed")))},onSettled:ID(e)})},set=()=>{const e=Mt();return fn({mutationFn:({sessionId:t,...n})=>JZe(t,n),onSuccess:async()=>{Hs(h("ui.notices.variables.updated"))},onError:t=>{nn(zi(t,h("ui.notices.variables.update_failed")))},onSettled:ID(e)})},ret=()=>{const e=Mt();return fn({mutationFn:({sessionId:t,key:n})=>ZZe(t,n),onSuccess:async()=>{Hs(h("ui.notices.variables.deleted"))},onError:t=>{nn(zi(t,h("ui.notices.variables.delete_failed")))},onSettled:ID(e)})},BK=e=>OK.includes(e),iet={already_exists:"key",reserved_name:"key",invalid_value:"value",too_large:"value"},aet=e=>({code:e instanceof Fi?e.code:void 0,message:zi(e,h("ui.canvas.variable_form_dialog.the_variable_could_not_be_saved_try_again"))}),_j=e=>{if(e){const t=BK(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:""}},Dk=()=>c.jsx("span",{className:R("text-danger"),"aria-hidden":"true",children:"*"}),oet=({open:e,onClose:t,onSubmit:n,initialData:s})=>{Ve();const[r,i]=m.useState(_j(s)),[a,o]=m.useState(!1),[l,u]=m.useState(null),d=!!s;m.useEffect(()=>{e&&(i(_j(s)),u(null))},[e,s]);const f=async()=>{if(u(null),!_5(r.key)){u({field:"key",message:h("ui.canvas.variable_form_dialog.this_name_cannot_be_sent_use_up_to_128_characters_without_control_charac")});return}o(!0);try{const _={key:r.key,type:r.type,value:r.value};await n(_),t()}catch(_){console.error("Failed to submit variable:",_),u(aet(_))}finally{o(!1)}},p=l?.field??(l?.code?iet[l.code]:void 0),g=d?h("ui.canvas.variable_form_dialog.edit_variable"):h("ui.canvas.variable_form_dialog.new_variable"),v=c.jsxs(c.Fragment,{children:[c.jsx(Uv,{onClick:t,disabled:a,startIcon:c.jsx(hde,{size:18,"aria-hidden":"true"}),children:h("ui.canvas.variable_form_dialog.cancel")}),c.jsx(Gv,{onClick:()=>void f(),disabled:a||!r.key.trim(),startIcon:a?c.jsx(On,{}):c.jsx(que,{size:18,"aria-hidden":"true"}),children:a?h("ui.canvas.variable_form_dialog.saving"):d?h("ui.canvas.variable_form_dialog.save"):h("ui.canvas.variable_form_dialog.create")})]}),b=(()=>{switch(r.type){case"dict":return h("ui.canvas.variable_form_dialog.value_json_object");case"list":return h("ui.canvas.variable_form_dialog.value_json_array");case"bool":return h("ui.canvas.variable_form_dialog.value_true_false");default:return h("ui.canvas.variable_form_dialog.value")}})(),x=r.type==="dict"||r.type==="list";return c.jsx(Ac,{open:e,onClose:t,title:g,actions:v,maxWidth:"sm",fullWidth:!0,children:c.jsxs("div",{className:R("flex flex-col gap-5 pt-2"),children:[c.jsxs("div",{className:R("flex flex-col gap-1.5"),children:[c.jsxs("div",{className:R("flex items-center gap-1"),children:[c.jsxs(dr,{htmlFor:"variable-key",children:[h("ui.canvas.variable_form_dialog.name_key"),c.jsx(Dk,{})]}),c.jsx(vt,{content:h("ui.canvas.variable_form_dialog.the_unique_identifier_for_the_variable_e_g_api_key_user_preference_canno"),children:c.jsx(ce,{type:"button",variant:"ghost",size:"icon-sm",className:R("text-info"),"aria-label":h("ui.canvas.variable_form_dialog.about_the_variable_name"),children:c.jsx(ig,{"aria-hidden":"true"})})})]}),c.jsx(bs,{id:"variable-key",value:r.key,onChange:_=>i(w=>({...w,key:_.target.value})),required:!0,disabled:a||d,placeholder:h("ui.canvas.variable_form_dialog.e_g_my_variable_name"),"aria-invalid":p==="key","aria-describedby":p==="key"?"variable-key-refusal":void 0,className:R(p==="key"&&"border-danger")}),p==="key"&&c.jsx("p",{id:"variable-key-refusal",role:"alert",className:R("text-body-sm text-ink"),children:l?.message})]}),c.jsxs("div",{className:R("flex flex-col gap-1.5"),children:[c.jsxs(dr,{htmlFor:"variable-type-select",children:[h("ui.canvas.variable_form_dialog.type"),c.jsx(Dk,{})]}),c.jsxs(E0,{value:r.type,onValueChange:_=>{BK(_)&&i(w=>({...w,type:_}))},disabled:a,children:[c.jsx(T0,{id:"variable-type-select",children:c.jsx(R0,{})}),c.jsx(A0,{children:OK.map(_=>c.jsx(F0,{value:_,children:_},_))})]})]}),c.jsxs("div",{className:R("flex flex-col gap-1.5"),children:[c.jsxs(dr,{htmlFor:"variable-value",children:[b,c.jsx(Dk,{})]}),c.jsx(vA,{id:"variable-value",value:r.value,onChange:_=>i(w=>({...w,value:_.target.value})),required:!0,disabled:a,rows:x?5:2,"aria-describedby":[x&&"variable-value-hint",p==="value"&&"variable-value-refusal"].filter(Boolean).join(" ")||void 0,"aria-invalid":p==="value",className:R(p==="value"&&"border-danger"),placeholder:r.type==="dict"?h("ui.canvas.variable_form_dialog.example_key_example_value"):r.type==="list"?h("ui.canvas.variable_form_dialog.item1_item2"):r.type==="bool"?h("ui.canvas.variable_form_dialog.true_or_false"):h("ui.canvas.variable_form_dialog.enter_variable_value")}),x&&c.jsx("p",{id:"variable-value-hint",className:R("text-ink-muted text-meta"),children:h("ui.canvas.variable_form_dialog.enter_a_valid_json_structure")}),p==="value"&&c.jsx("p",{id:"variable-value-refusal",role:"alert",className:R("text-body-sm text-ink"),children:l?.message})]}),l&&!p&&c.jsx("p",{role:"alert",className:R("text-body-sm text-ink"),children:l.message})]})})},wj=()=>h("ui.canvas.variables_viewer.the_backend_did_not_answer_so_this_chat_s_code_memory_could_not_be_read"),Aa=({children:e})=>c.jsx("div",{className:R("flex h-full flex-col items-center justify-center gap-2 p-6 text-center"),children:e}),yj=(e,t)=>e.length<=t?e:`${e.substring(0,t)}…`,jK=m.memo(({variable:e,onEdit:t,onDelete:n})=>{Ve();const[s,r]=m.useState(!1),[i,a]=m.useState(!1),o=m.useId(),l=_5(e.key),u=e.editable&&l,d=l,f=m.useMemo(()=>String(e.value),[e.value]),p=m.useMemo(()=>yj(f,200),[f]),g=m.useMemo(()=>yj(f,1e3),[f]),v=e.type,b=m.useCallback(()=>{r(y=>!y)},[]),x=m.useCallback(y=>{y.stopPropagation(),t(e)},[t,e]),_=m.useCallback(y=>{y.stopPropagation(),n(e.key)},[n,e.key]),w=m.useCallback(async y=>{y.stopPropagation();try{await navigator.clipboard.writeText(f),a(!0),setTimeout(()=>a(!1),2e3)}catch(S){console.error("Failed to copy to clipboard:",S)}},[f]);return c.jsxs("div",{className:R("group border-hairline border-b last:border-b-0"),children:[c.jsxs("div",{className:R("flex min-h-8 items-center gap-1 pe-1","transition-colors duration-fast ease-out-quart hover:bg-surface"),children:[c.jsxs("button",{type:"button",onClick:b,"aria-expanded":s,"aria-controls":o,className:R("flex min-w-0 flex-1 cursor-pointer select-none items-center gap-2 px-2 py-1 text-start font-mono text-mono-sm"),children:[s?c.jsx(Ei,{"aria-hidden":"true",className:"size-3 shrink-0 text-ink-dim rtl:-scale-x-100"}):c.jsx(Vi,{"aria-hidden":"true",className:"size-3 shrink-0 text-ink-dim rtl:-scale-x-100"}),c.jsx("span",{className:R("shrink-0 font-medium text-ink"),children:e.key}),c.jsx("span",{className:R("shrink-0 text-ink-dim"),children:v}),c.jsx(vt,{content:g,align:"start",children:c.jsx("span",{className:R("min-w-0 flex-1 truncate text-ink-muted"),children:p})})]}),c.jsxs("div",{className:R("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(vt,{content:i?h("ui.canvas.variables_viewer.copied"):h("ui.canvas.variables_viewer.copy_value"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:w,"aria-label":h("ui.canvas.variables_viewer.copy_value"),children:c.jsx(ed,{})})}),u?c.jsx(vt,{content:h("ui.canvas.variables_viewer.edit_variable"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:x,"aria-label":h("ui.canvas.variables_viewer.edit_variable"),children:c.jsx(mM,{})})}):c.jsx(vt,{content:l?h("ui.canvas.variables_viewer.this_variable_can_t_be_edited_because_its_type_is_not_yet_supported_for"):h("ui.canvas.variables_viewer.this_variable_s_name_can_t_be_edited_from_here_copy_it_to_the_session_un"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-disabled":"true","aria-label":h("ui.canvas.variables_viewer.edit_variable"),className:R("cursor-default text-ink-disabled hover:bg-transparent hover:text-ink-disabled"),children:c.jsx(mM,{})})}),d&&c.jsx(vt,{content:h("ui.canvas.variables_viewer.delete_variable"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:_,"aria-label":h("ui.canvas.variables_viewer.delete_variable"),className:R("hover:bg-danger-wash hover:text-danger"),children:c.jsx(cg,{})})})]})]}),s?c.jsx("div",{id:o,className:R("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:f}):null]})});jK.displayName="VariableRow";const HK=m.memo(({sessionId:e,turnTerminal:t})=>{Ve();const[n,s]=m.useState(!1),[r,i]=m.useState(null),[a,o]=m.useState(!1),[l,u]=m.useState(null),d=ss(),f=Et(d.data,"session_variables"),{data:p,isLoading:g,error:v,isError:b}=tet(e,f),x=Mt(),_=m.useRef(t);m.useEffect(()=>{const O=_.current;_.current=t,!(O===void 0||t===void 0)&&(t<=O||!e||!f||x.invalidateQueries({queryKey:DD(e)}))},[t,e,f,x]);const w=net(),y=set(),S=ret(),C=m.useRef(null);m.useEffect(()=>{p?.state==="observed"&&(C.current=p)},[p]);const E=p?.state==="observed"?p:C.current,k=p?.state==="busy",F=m.useMemo(()=>E?.variables??[],[E]),A=m.useCallback(()=>{i(null),s(!0)},[]),I=m.useCallback(O=>{i(O),s(!0)},[]),N=m.useCallback(()=>{s(!1),i(null)},[]),P=m.useCallback(async O=>{if(e)try{r?await y.mutateAsync({sessionId:e,...O,key:r.key}):await w.mutateAsync({sessionId:e,...O})}catch(X){throw console.error("Submission failed in component:",X),X}},[e,r,w,y]),M=m.useCallback(O=>{u(O),o(!0)},[]),Y=m.useCallback(async()=>{if(!e||!l){o(!1),u(null);return}try{await S.mutateAsync({sessionId:e,key:l})}catch(O){console.error("Deletion failed during confirmation:",O)}finally{o(!1),u(null)}},[e,l,S]);if(d.isLoading)return c.jsxs(Aa,{children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.loading_variables")})]});if(d.isError)return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.could_not_reach_the_backend")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:zi(d.error,wj())})]});if(!f)return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.update_the_backend_to_read_code_memory")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.this_app_can_read_code_memory_the_backend_it_is_running_against_is_older")})]});if(!e)return c.jsx(Aa,{children:c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.code_memory_starts_when_you_send_your_first_message")})});if(g)return c.jsxs(Aa,{children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.loading_variables")})]});if(b)return LK(v)?c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.update_the_backend_to_read_code_memory")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.settings_then_application_updates_and_info_installs_the_newer_backend")})]}):eet(v)?c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.could_not_load_variables")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:zi(v,h("ui.canvas.variables_viewer.the_backend_does_not_have_a_chat_with_this_session_id"))})]}):c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.could_not_load_variables")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:wj()})]});if(p?.state==="unsupported")return c.jsx(Aa,{children:c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.this_chat_cannot_read_code_memory")})});if(F.length===0){if(k)return c.jsxs(Aa,{children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:R("text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.reading")})]});if(E?.truncated&&F.length===0&&!k)return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:h("ui.canvas.variables_viewer.too_large_to_show_here")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:h("ui.canvas.variables_viewer.this_chat_keeps_a_value_bigger_than_this_panel_can_list_so_nothing_is_sh")})]});const O=E?.kernel==="absent"||E?.runtime==="absent";return c.jsxs(Aa,{children:[c.jsx("p",{className:R("text-heading text-ink"),children:O?h("ui.canvas.variables_viewer.no_code_memory_yet"):h("ui.canvas.variables_viewer.nothing_stored_yet")}),c.jsx("p",{className:R("max-w-80 text-body-sm text-ink-muted"),children:O?h("ui.canvas.variables_viewer.it_fills_in_when_code_runs_in_this_chat"):h("ui.canvas.variables_viewer.when_the_agent_runs_code_for_you_the_values_it_keeps_around_between_step")}),O?null:c.jsxs(ce,{variant:"secondary",size:"sm",onClick:A,children:[c.jsx(Cl,{"aria-hidden":"true"}),h("ui.canvas.variables_viewer.new_variable")]})]})}return c.jsxs("div",{className:R("flex h-full min-h-0 flex-col"),children:[c.jsxs("div",{className:R("flex h-10 shrink-0 items-center justify-between gap-3 border-hairline border-b px-3"),children:[c.jsxs("p",{className:R("flex min-w-0 items-center truncate text-body-sm text-ink-muted"),children:[c.jsx("span",{className:R("font-medium text-ink"),children:h("ui.canvas.variables_viewer.code_memory")}),c.jsx("span",{className:R("mx-1.5 text-ink-dim"),children:"·"}),h("ui.canvas.variables_viewer.count",{count:F.length}),k?c.jsxs(c.Fragment,{children:[c.jsx("span",{className:R("mx-1.5 text-ink-dim"),children:"·"}),c.jsx(On,{size:"xs"}),c.jsx("span",{className:R("ms-1.5"),children:h("ui.canvas.variables_viewer.reading")})]}):null]}),c.jsxs(ce,{variant:"ghost",size:"sm",onClick:A,children:[c.jsx(Cl,{"aria-hidden":"true"}),h("ui.canvas.variables_viewer.new_variable")]})]}),c.jsx("div",{className:R("min-h-0 flex-1 overflow-auto"),children:F.map(O=>c.jsx(jK,{variable:O,onEdit:I,onDelete:M},O.key))}),c.jsx(oet,{open:n,onClose:N,onSubmit:P,initialData:r}),l&&c.jsx(nd,{open:a,title:h("ui.canvas.variables_viewer.delete_variable"),message:c.jsxs(c.Fragment,{children:[h("ui.canvas.variables_viewer.are_you_sure_you_want_to_delete_the_variable")," ",c.jsx("strong",{className:R("font-mono text-ink"),children:l}),h("ui.canvas.variables_viewer.this_action_cannot_be_undone")]}),confirmText:h("ui.canvas.variables_viewer.delete"),cancelText:h("ui.canvas.variables_viewer.cancel"),isDangerous:!0,onConfirm:Y,onCancel:()=>{o(!1),u(null)}})]})});HK.displayName="CanvasVariablesViewer";const cet=(e,t,n,s,r=!1)=>r?h("ui.canvas.view_name.view_shown_this_list_is_capped",{label:e,counted:s,noun:t,pluralnoun:n}):s>0?h("ui.canvas.view_name.view_count",{label:e,counted:s,noun:t,pluralnoun:n}):h("ui.canvas.view_name.view_empty",{label:e}),Cj="mb-1.5 flex w-fit items-center gap-2 font-normal text-ink-muted",Sj=()=>[{id:"md",name:h("ui.canvas.create_file_dialog.markdown_md"),group:h("ui.canvas.create_file_dialog.general")},{id:"txt",name:h("ui.canvas.create_file_dialog.plain_text_txt"),group:h("ui.canvas.create_file_dialog.general")},{id:"html",name:h("ui.canvas.create_file_dialog.html_html"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"css",name:h("ui.canvas.create_file_dialog.css_css"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"js",name:h("ui.canvas.create_file_dialog.javascript_js"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"jsx",name:h("ui.canvas.create_file_dialog.jsx_jsx"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"ts",name:h("ui.canvas.create_file_dialog.typescript_ts"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"tsx",name:h("ui.canvas.create_file_dialog.tsx_tsx"),group:h("ui.canvas.create_file_dialog.web_development")},{id:"py",name:h("ui.canvas.create_file_dialog.python_py"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"go",name:h("ui.canvas.create_file_dialog.go_go"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"java",name:h("ui.canvas.create_file_dialog.java_java"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"cs",name:h("ui.canvas.create_file_dialog.c_cs"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"php",name:h("ui.canvas.create_file_dialog.php_php"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"rb",name:h("ui.canvas.create_file_dialog.ruby_rb"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"rs",name:h("ui.canvas.create_file_dialog.rust_rs"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"sh",name:h("ui.canvas.create_file_dialog.shell_script_sh"),group:h("ui.canvas.create_file_dialog.backend_and_scripting")},{id:"json",name:h("ui.canvas.create_file_dialog.json_json"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"yaml",name:h("ui.canvas.create_file_dialog.yaml_yaml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"yml",name:h("ui.canvas.create_file_dialog.yaml_yml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"xml",name:h("ui.canvas.create_file_dialog.xml_xml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"toml",name:h("ui.canvas.create_file_dialog.toml_toml"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"ini",name:h("ui.canvas.create_file_dialog.ini_ini"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"env",name:h("ui.canvas.create_file_dialog.env"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"dockerfile",name:h("ui.canvas.create_file_dialog.dockerfile"),group:h("ui.canvas.create_file_dialog.configuration")},{id:"c",name:h("ui.canvas.create_file_dialog.c_c"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"cpp",name:h("ui.canvas.create_file_dialog.c_cpp"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"swift",name:h("ui.canvas.create_file_dialog.swift_swift"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"kt",name:h("ui.canvas.create_file_dialog.kotlin_kt"),group:h("ui.canvas.create_file_dialog.other_languages")},{id:"scala",name:h("ui.canvas.create_file_dialog.scala_scala"),group:h("ui.canvas.create_file_dialog.other_languages")}],uet=({open:e,onClose:t,onSave:n,isSaving:s,currentWorkingDirectory:r="~"})=>{Ve();const[i,a]=m.useState(""),[o,l]=m.useState("md"),[u,d]=m.useState(!1);m.useEffect(()=>{e&&(a(""),l("md"))},[e]);const f=Sj().find(b=>b.id===o)??(o?{id:o,name:o}:null),p=i.trim()!==""&&!s,g=async(b=!1)=>{if(!p)return;const x=`${r}/${i}.${o}`;if(await window.api.fileExists(x)&&!b){d(!0);return}n({name:i,type:o,location:r},b)},v=c.jsxs(c.Fragment,{children:[c.jsx(Uv,{onClick:t,disabled:s,children:h("ui.canvas.create_file_dialog.cancel")}),c.jsx(Gv,{onClick:()=>void g(),disabled:!p,startIcon:s?c.jsx(On,{}):null,children:s?h("ui.canvas.create_file_dialog.creating"):h("ui.canvas.create_file_dialog.create_file")})]});return c.jsxs(c.Fragment,{children:[c.jsx(Ac,{open:e&&!u,onClose:t,title:h("ui.canvas.create_file_dialog.create_new_file"),actions:v,maxWidth:"sm",fullWidth:!0,children:c.jsxs("div",{className:R("flex flex-col gap-4 pt-2"),children:[c.jsxs("div",{children:[c.jsxs(dr,{htmlFor:"create-file-name",className:R(Cj),children:[c.jsx(Ey,{size:16,"aria-hidden":"true"}),h("ui.canvas.create_file_dialog.file_name")]}),c.jsx(bs,{id:"create-file-name",value:i,onChange:b=>a(b.target.value),required:!0,autoFocus:!0,disabled:s,placeholder:h("ui.canvas.create_file_dialog.enter_file_name_e_g_my_new_script"),onKeyDown:b=>{b.key==="Enter"&&p&&g()}})]}),c.jsx(_A,{label:h("ui.canvas.create_file_dialog.file_type"),icon:c.jsx(gU,{size:16,"aria-hidden":"true"}),labelTooltip:h("ui.canvas.create_file_dialog.pick_an_extension_or_type_one_that_is_not_listed"),placeholder:h("ui.canvas.create_file_dialog.select_or_type_an_extension"),options:Sj(),selected:f,onSelect:b=>l(b.id),onCustomSubmit:b=>l(b),busyLabel:h("ui.canvas.create_file_dialog.loading_file_types"),disabled:s}),c.jsxs("div",{children:[c.jsxs("p",{className:R(Cj,"text-body-sm"),children:[c.jsx(gse,{size:16,"aria-hidden":"true"}),h("ui.canvas.create_file_dialog.location")]}),c.jsx(mse,{currentWorkingDirectory:r,readOnlyReason:h("ui.canvas.create_file_dialog.change_the_working_directory_from_the_composer_to_create_the_file_elsewh")}),c.jsx("p",{className:R("mt-2 text-ink-muted text-meta"),children:h("ui.canvas.create_file_dialog.the_file_will_be_created_in_this_working_directory")})]})]})}),c.jsx(nd,{open:u,title:h("ui.canvas.create_file_dialog.file_already_exists"),message:h("ui.canvas.create_file_dialog.a_file_named_already_exists_do_you_want_to_overwrite_it",{filename:i,filetype:o}),confirmText:h("ui.canvas.create_file_dialog.overwrite"),onConfirm:()=>{d(!1),g(!0)},onCancel:()=>d(!1),isDangerous:!0})]})},det=2e3,het={get missing(){return h("ui.canvas.use_file_freshness.no_longer_on_disk_showing_the_version_we_last_read")},get unreadable(){return h("ui.canvas.use_file_freshness.could_not_be_read_showing_the_version_we_last_read")},get failed(){return h("ui.canvas.use_file_freshness.could_not_be_re_read_showing_the_version_we_last_read")},get"disk-changed"(){return h("ui.canvas.use_file_freshness.changed_on_disk_load_it_or_save_to_replace_it")},get"save-replaced"(){return h("ui.canvas.use_file_freshness.your_save_replaced_the_change_on_disk")}},fet={get missing(){return h("ui.canvas.use_file_freshness.this_file_is_no_longer_on_disk_the_last_version_we_read_is_still_shown_a")},get unreadable(){return h("ui.canvas.use_file_freshness.this_file_could_not_be_read_the_last_version_we_read_is_still_shown_and")},get failed(){return h("ui.canvas.use_file_freshness.this_file_could_not_be_re_read_so_the_version_we_last_read_is_still_show")},get"disk-changed"(){return h("ui.canvas.use_file_freshness.your_unsaved_edits_are_kept_until_the_app_quits_and_saving_is_paused_whi")},get"save-replaced"(){return h("ui.canvas.use_file_freshness.your_save_replaced_the_version_that_had_changed_on_disk_re_read_the_file")}},pet=8e3;function kj(e,t){switch(e.status){case"applied":return"Re-read";case"identical":return h("ui.canvas.use_file_freshness.up_to_date");case"unchanged":return t?h("ui.canvas.use_file_freshness.up_to_date"):void 0;case"unavailable":return t?h("ui.canvas.use_file_freshness.no_local_file_access"):void 0;default:return}}function Ej(e,t){switch(e.status){case"applied":return h("ui.canvas.use_file_freshness.the_file_s_version_was_re_read_from_disk_and_is_now_on_screen");case"identical":case"unchanged":return t?h("ui.canvas.use_file_freshness.already_up_to_date_the_file_is_unchanged"):void 0;case"unavailable":return t?h("ui.canvas.use_file_freshness.local_file_access_is_unavailable_so_there_is_nothing_to_re_read_from"):void 0;default:return}}function Tj(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 get({document:e,conversationId:t}){const n=Fs(x=>x.updateOneFile),s=m.useSyncExternalStore(T1e,()=>rC(e.id),()=>!1),[r,i]=m.useState(!1),a=m.useSyncExternalStore(F1e,()=>A1e(e.id),()=>null),o=m.useRef(null);o.current=a;const[l,u]=m.useState(null);m.useEffect(()=>{u(null)},[e.id]),m.useEffect(()=>{if(!l)return;const x=pet-(Date.now()-l.at),_=window.setTimeout(()=>{u(w=>w?.at===l.at?null:w)},Math.max(0,x));return()=>window.clearTimeout(_)},[l]);const d=m.useRef(e);m.useEffect(()=>{d.current=e});const f=m.useMemo(()=>D1e({probe:x=>e7(x),read:async(x,_)=>{if(typeof window.api?.readFile!="function")return{ok:!1,error:h("ui.canvas.use_file_freshness.local_file_access_is_unavailable_outside_the_desktop_app")};try{const w=await window.api.readFile(x,_);return w.success?{ok:!0,content:w.data}:{ok:!1,error:w.error instanceof Error?w.error.message:String(w.error)}}catch(w){return{ok:!1,error:w instanceof Error?w.message:String(w)}}}}),[]),p=m.useCallback(x=>{if(!t)return;const _=d.current;_.id===x.id&&_.content===x.content&&_.readMtimeMs===x.readMtimeMs&&_.lastAgentModified===x.lastAgentModified&&_.sizeBytes===x.sizeBytes&&_.availability===x.availability||n(t,x)},[t,n]),g=m.useCallback(async x=>{x&&i(!0);const _=hp(e.id);try{const w=await f.check(d.current,x);if(hp(e.id)!==_)return;"document"in w&&p(w.document);const y=Tj(w,o.current);y!==void 0&&wo(e.id,y);const S=kj(w,x);S!==void 0&&u(S?{text:S,detail:Ej(w,x)??null,at:Date.now()}:null)}finally{x&&i(!1)}},[p,e.id,f]),v=m.useCallback(async()=>{i(!0);try{P1e(e.id);const x=await f.load(d.current);"document"in x&&(N1e(x.document.id,x.document.content,x.document.readMtimeMs??null),p(x.document));const _=Tj(x,o.current);_!==void 0&&wo(e.id,_);const w=kj(x,!0);w!==void 0&&u(w?{text:w,detail:Ej(x,!0)??null,at:Date.now()}:null)}finally{i(!1)}},[p,e.id,f]);m.useEffect(()=>{g(!1)},[g,e.id,e.path,t]),m.useEffect(()=>{const x=()=>{window.document.visibilityState==="visible"&&g(!1)};return window.addEventListener("focus",x),window.document.addEventListener("visibilitychange",x),()=>{window.removeEventListener("focus",x),window.document.removeEventListener("visibilitychange",x)}},[g]),m.useEffect(()=>{const x=window.setInterval(()=>{window.document.visibilityState==="visible"&&g(!1)},det);return()=>window.clearInterval(x)},[g]);const b=m.useCallback(()=>{if(o.current==="disk-changed"){v();return}o.current==="save-replaced"&&wo(e.id,null),g(!0)},[g,e.id,v]);return{lastModifiedMs:e.readMtimeMs??null,refreshing:r,note:a?het[a]:l?.text??null,detail:a?fet[a]:l?.detail??l?.text??null,dirty:s,diskChanged:a==="disk-changed",refresh:b}}const met=({document:e,conversationId:t})=>{Ve();const{lastModifiedMs:n,refreshing:s,note:r,detail:i,dirty:a,diskChanged:o,refresh:l}=get({document:e,conversationId:t}),u=m.useId(),d=n===null?null:new Date(n),f=d===null?null:vse(d),p=d===null?null:bse(d,{hour:"numeric",minute:"2-digit"}),g=f!==null&&p!==null&&p.length>0&&f.endsWith(p),v=f===null?null:g?f.slice(0,-p.length).trimEnd():f,b=f===null?h("ui.canvas.document_freshness_bar.not_read_from_disk_yet"):h("ui.canvas.document_freshness_bar.modified",{formatcalendardatetime:f}),x=o?h("ui.canvas.document_freshness_bar.load_the_file_s_version_your_unsaved_edits_are_discarded"):a?h("ui.canvas.document_freshness_bar.check_the_file_your_edits_are_kept"):h("ui.canvas.document_freshness_bar.re_read_from_disk");return c.jsxs("div",{"data-glass-plane":"band",className:R("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(vt,{content:[i,b].filter(Boolean).join(" · "),side:"bottom",delayDuration:1200,children:c.jsxs("div",{tabIndex:0,className:R("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:R("min-w-0 truncate whitespace-nowrap text-meta text-ink-muted tabular-nums"),"data-tour-tag":"canvas-document-modified",children:v===null?b:c.jsxs(c.Fragment,{children:[c.jsx("bdi",{children:h("ui.canvas.files.modified")})," ",c.jsx("bdi",{children:v}),g&&c.jsxs(c.Fragment,{children:[" ",c.jsx("bdi",{dir:"ltr",children:p})]})]})}),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:R("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:R("shrink-0"),children:c.jsx(vt,{content:x,children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":x,"aria-describedby":r?u:void 0,disabled:s,onClick:l,"data-tour-tag":"canvas-refresh-file-button",children:c.jsx(Wy,{"aria-hidden":"true"})})})})]})},vet=[],Rj=[{value:"documents",get label(){return h("ui.canvas.shell.documents")},tourTag:"canvas-documents-view-button",Icon:Ty},{value:"files",get label(){return h("ui.canvas.shell.files")},tourTag:"canvas-files-view-button",Icon:ky},{value:"variables",get label(){return h("ui.canvas.shell.variables")},tourTag:"canvas-variables-view-button",Icon:gue},{value:"goals",get label(){return h("ui.canvas.shell.goals")},tourTag:"canvas-goals-view-button",Icon:wde}],bet=e=>e?Rj:Rj.filter(t=>t.value!=="goals"),xet=({current:e,onChange:t,views:n,fileCount:s,goalCount:r,goalTruncated:i})=>(Ve(),c.jsxs("fieldset",{className:R("inline-flex h-7 shrink-0 items-center gap-0.5 border-0 p-0"),children:[c.jsx("legend",{className:R("sr-only"),children:h("ui.canvas.shell.canvas_view")}),n.map(({value:a,label:o,tourTag:l,Icon:u})=>{const d=e===a,f=a==="files"?s:a==="goals"?r:0,p=a==="files"?h("ui.canvas.shell.file"):h("ui.canvas.shell.goal"),g=a==="files"?h("ui.canvas.shell.files"):h("ui.canvas.shell.goals"),v=f===null?o:cet(o,p,g,f,a==="goals"&&i);return c.jsx(vt,{content:v,children:c.jsxs("button",{type:"button","aria-pressed":d,"aria-label":v,"data-tour-tag":l,onClick:()=>t(a),className:R("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:R("ms-1 text-meta"),children:[o,f===null?"":` ${Bd(f)}`]})]})},a)})]})),_et=({activeDocumentId:e,initialDocuments:t=[],onChangeActiveDocument:n,onClose:s,onCloseDocument:r,conversationId:i,sessionId:a,filesSourceReady:o=!0,turnTerminal:l,agentId:u,currentWorkingDirectory:d,fileCount:f=0,fileIndex:p,attachments:g,scan:v=null,goalHistory:b=vet,goalHistoryTruncated:x=!1,goalCapable:_=!1,goalPresent:w=!1})=>{Ve();const y=QG(a,!p,l),S=p??y,C=k8(a,null,l,!g),E=g??C,k=S.mode==="negotiating"?null:S.mode==="index"?S.state==="ready"||S.total>0?S.total:null:f,F=k===null?E.items.length||null:n9(k,S.mode==="index"?S.rows.map(se=>se.ref.type==="artifact"?se.ref.digest:null):[],E),[A,I]=m.useState(!1),[N,P]=m.useState(!1),[M,Y]=m.useState("Ctrl");m.useEffect(()=>{(async()=>{const he=await window.api.systemInfo.getPlatformInfo();Y(he.platform==="darwin"?"⌘":"Ctrl")})()},[]);const{addFileAndSelect:O,setViewMode:X,addMentionedFile:Q}=Fs(),{removeManager:ie}=JG(),G=m.useCallback(async()=>{if(i){const se=await window.api.selectFile();if(se){const he={id:se.path,title:se.path.split("/").pop()||se.path,content:se.content,path:se.path,type:Gu(se.path)};O(i,he),Q(i,he),X(i,"documents")}}},[O,Q,i,X]);m.useEffect(()=>{const se=he=>{const xe=lJ(he);if(xe==="open-file"?(he.preventDefault(),G()):xe==="new-file"&&(he.preventDefault(),I(!0)),he.key==="Escape"&&i){if(he.defaultPrevented||pA(he.target))return;he.preventDefault(),s()}};return window.addEventListener("keydown",se),()=>{window.removeEventListener("keydown",se)}},[G,i,s]);const ne=async(se,he=!1)=>{P(!0);try{if(await Owe(se.name,se.type,se.location,he),i){const xe={id:`${se.location}/${se.name}.${se.type}`,title:`${se.name}.${se.type}`,content:"",path:`${se.location}/${se.name}.${se.type}`};O(i,xe),Q(i,xe)}I(!1)}catch{}finally{P(!1)}},oe=Fs(se=>i?se.conversations[i]:void 0),B=bet(_),H=oe?.viewMode,U=H&&B.some(se=>se.value===H)?H:"documents",z=F??0,te=z>0,fe=m.useCallback(se=>{i&&X(i,se)},[i,X]),J=t,[Se,W]=m.useState(J.length>0?J[0].id:null),Ce=e??Se,K=m.useMemo(()=>J.find(se=>se.id===Ce)||null,[J,Ce]),me=m.useCallback(se=>{n?n(se):W(se)},[n]),Ee=m.useCallback(se=>{fe("documents"),me(se)},[me,fe]),Ae=m.useCallback(se=>{if(r(se),ie(se),Ce===se){const he=FD(J,se)?.id??null;n?n(he):W(he)}},[J,Ce,n,r,ie]);return c.jsxs("section",{"aria-label":h("ui.canvas.shell.canvas"),"data-tour-tag":"canvas-container","data-canvas-shortcuts":!0,"data-glass-region":"pane",className:R("panel-top-pad flex h-full flex-col bg-elevated"),children:[c.jsxs("div",{className:R("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(xet,{current:U,onChange:fe,views:B,fileCount:F,goalCount:b.length,goalTruncated:x}),c.jsxs("div",{className:R("flex shrink-0 items-center gap-0.5"),children:[c.jsx(vt,{content:h("ui.canvas.shell.new_file_n",{modifierkey:M}),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.shell.new_file_n",{modifierkey:M}),onClick:()=>I(!0),"data-tour-tag":"canvas-create-file-button",children:c.jsx(pM,{"aria-hidden":"true"})})}),c.jsx(vt,{content:h("ui.canvas.shell.open_file_from_disk_o",{modifierkey:M}),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.shell.open_file_from_disk_o",{modifierkey:M}),onClick:G,children:c.jsx(sT,{"aria-hidden":"true"})})}),c.jsx(vt,{content:h("ui.canvas.shell.close_canvas"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.canvas.shell.close_canvas"),onClick:s,"data-tour-tag":"close-canvas-button",children:c.jsx(Hu,{"aria-hidden":"true",className:"rtl:-scale-x-100"})})})]})]}),U==="documents"&&c.jsxs(c.Fragment,{children:[c.jsx(YZe,{documents:J,activeDocumentId:Ce,onChangeActiveDocument:me,onCloseDocument:Ae}),K&&c.jsxs(_Z,{id:MK,labelledBy:PK,children:[!K.artifact&&c.jsx(met,{document:K,conversationId:i}),c.jsx(mXe,{document:K,conversationId:i,agentId:u},K.id)]}),!K&&J.length===0&&c.jsxs(PR,{title:h("ui.canvas.shell.nothing_open_yet"),description:h("ui.canvas.shell.open_a_file_to_read_or_edit_it_here_files_the_agent_mentions_in_the_conv"),children:[c.jsxs(ce,{variant:te?"primary":"secondary",size:"sm",onClick:()=>fe("files"),children:[c.jsx(ky,{"aria-hidden":"true"}),te?h("ui.canvas.shell.browse_filesc0c547",{filecountvalue:z}):h("ui.canvas.shell.browse_files")]}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:G,children:[c.jsx(sT,{"aria-hidden":"true"}),h("ui.canvas.shell.open_file_from_disk")]}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>I(!0),children:[c.jsx(pM,{"aria-hidden":"true"}),h("ui.canvas.shell.new_file")]})]})]}),U==="files"&&i&&c.jsx(WZe,{conversationId:i,sessionId:a,cwd:o?d:void 0,index:S.mode==="fallback"&&!o?{...S,mode:"negotiating",state:"loading",localReadAllowed:!1}:S,onSwitchToDocumentView:Ee,scan:v,attachments:E},i),U==="variables"&&i&&c.jsx(HK,{sessionId:a,turnTerminal:l}),U==="goals"&&c.jsx($Ze,{entries:b,truncated:x,goalPresent:w}),(U==="files"||U==="variables")&&!i&&c.jsx(PR,{title:h("ui.canvas.shell.no_conversation_open"),description:h("ui.canvas.shell.start_a_conversation_with_an_agent_to_see_the_files_and_variables_it_is")}),u&&c.jsx(uet,{open:A,onClose:()=>I(!1),onSave:ne,isSaving:N,currentWorkingDirectory:d})]})},wet=m.memo(_et),yet="max-h-[min(22rem,var(--radix-popover-content-available-height))]";function Cet(e){return e==="team"?{recents:"Recent teams",all:"All teams"}:{recents:"Recent agents",all:"All agents"}}function UK(e){return!e.loading&&e.loadError===null&&e.rowCount>0}function ket(e){const{rows:t,matches:n,recents:s,kind:r,query:i}=e,a=Cet(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(f=>f.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 Ik(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 Eet(e){return`${e} cannot take the seat.`}const Tet="No profile here can take the seat — clear the search, or switch the team.",Ret="No profile can take the seat — switch the team.";function Aet(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`:Tet:r?i?`${t.total} ${a} in all — scroll, or type to filter`:Ret:null}function GK(e){return e.teamOwnsSeat===!0?!1:e.name===e.manager||e.delegate===!0}function Fet(e){return`${e} is led by its manager; only the manager and profiles that can delegate may take this seat.`}function Det(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 Iet(e){return`Agent seat closed by ${e}`}const Net="Needs a delegating profile here.";function Pet(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:Fet(e.teamLabel)}}const Aj=R("px-2 py-3 text-body-sm"),Met=({kind:e,open:t,listId:n,options:s,recents:r,loading:i,loadError:a,emptyText:o,caption:l,closedReason:u=null,closedNoteId:d,closedTitle:f,onPick:p,onClose:g,onCloseAutoFocus:v})=>{Ve();const[b,x]=m.useState(""),[_,w]=m.useState(0),[y,S]=m.useState(null),[C,E]=m.useState(!1),[k,F]=m.useState(null),A=m.useRef(null),[I,N]=m.useState(null),P=UK({loading:i,loadError:a,rowCount:s.length}),M=m.useMemo(()=>xse(s,b),[s,b]),Y=m.useMemo(()=>ket({rows:s,matches:M,recents:r,kind:e,query:b}),[s,M,r,e,b]),O=m.useMemo(()=>Y.bands.flatMap(te=>te.rows),[Y]);m.useEffect(()=>{w(Ik(O)),S(null),F(null)},[b]),m.useEffect(()=>{w(Ik(O))},[O.length]),m.useEffect(()=>{F(null)},[_]),m.useEffect(()=>{document.getElementById(`${n}-${_}`)?.scrollIntoView({block:"nearest"})},[_,n]),m.useEffect(()=>{const te=I;if(!te){E(!1);return}const fe=()=>E(te.scrollHeight>te.clientHeight+1);fe();let J;if(typeof ResizeObserver<"u"){J=new ResizeObserver(fe),J.observe(te);for(const Se of te.children)J.observe(Se)}return()=>J?.disconnect()},[Y,I]),m.useEffect(()=>{if(!t)return;const te=A.current;!te||document.activeElement===te||te.focus()},[t,P]),m.useEffect(()=>{t&&(x(""),w(Ik(O)),S(null),F(null))},[t]);const X=m.useCallback(te=>{O.length!==0&&w(fe=>(fe+te+O.length)%O.length)},[O.length]),Q=m.useCallback(te=>{if(!te.nativeEvent.isComposing){if(te.key==="Tab"){te.stopPropagation(),g();return}if(te.key==="ArrowDown"){te.preventDefault(),X(1);return}if(te.key==="ArrowUp"){te.preventDefault(),X(-1);return}if(te.key==="Home"&&O.length>0){te.preventDefault(),w(0);return}if(te.key==="End"&&O.length>0){te.preventDefault(),w(O.length-1);return}if(te.key==="Enter"){te.preventDefault();const fe=O[_];fe&&!fe.disabled?p(fe.value):fe?.blocked&&F(Eet(fe.label));return}}},[_,O,X,g,p]),ie=e==="team"?"teams":"agents",G=O.length>0?`${n}-${_}`:void 0,ne=O.some(te=>!te.blocked),oe=Y.matches>0&&!ne,B=Aet({view:Y,kind:e,query:b,overflowing:C,hasSettable:ne}),H=m.useId();let U=-1;const z=c.jsxs("div",{className:"relative px-1 pt-1 pb-1",children:[c.jsx(_h,{className:"-translate-y-1/2 pointer-events-none absolute top-1/2 start-2.5 size-4 text-ink-dim","aria-hidden":"true"}),c.jsx(bs,{ref:A,role:"combobox","aria-expanded":!0,"aria-controls":P?n:void 0,"aria-activedescendant":G,"aria-autocomplete":"list","aria-label":h("ui.chat.header_identity.search",{kind:ie}),value:b,onChange:te=>x(te.target.value),onKeyDown:Q,placeholder:h("ui.chat.header_identity.search",{kind:ie}),className:"ps-8",autoComplete:"off",spellCheck:!1})]});if(u!==null){const te=`${d}-title`;return c.jsxs(Bu,{align:"start",sideOffset:6,collisionPadding:8,className:R("flex w-80 flex-col gap-0.5 p-1"),"data-header-identity-menu":e,"data-header-identity-closed":"",id:d,"aria-labelledby":te,onOpenAutoFocus:fe=>fe.preventDefault(),onCloseAutoFocus:v,children:[c.jsx("p",{id:te,className:"px-2 pt-1 text-body-sm text-ink-muted",children:f}),c.jsx("p",{"data-header-identity-constraint":"",className:"px-2 pb-1.5 text-ink-dim text-meta",children:u})]})}return c.jsx(Bu,{align:"start",sideOffset:6,collisionPadding:8,className:R("flex w-80 flex-col p-1",yet,"overflow-hidden"),"data-header-identity-menu":e,role:"presentation",onMouseDown:te=>te.preventDefault(),onCloseAutoFocus:v,children:P?c.jsxs(c.Fragment,{children:[z,l!==null&&c.jsx("p",{id:H,"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&&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:N,id:n,role:"listbox","aria-label":e==="team"?h("ui.agents.pages.tab.teams"):h("ui.agents.pages.tab.agents"),"aria-describedby":l!==null?H:void 0,tabIndex:-1,onMouseLeave:()=>S(null),className:"min-h-0 flex-1 overflow-y-auto",children:Y.noMatches?c.jsx("p",{className:R(Aj,"text-ink-dim"),"data-header-identity-no-matches":"",children:h("ui.chat.header_identity.no_matches",{query:b.trim()})}):Y.bands.map(te=>c.jsxs(m.Fragment,{children:[te.heading&&c.jsxs("div",{role:"presentation","data-header-identity-band":te.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:te.heading}),c.jsx("div",{className:"h-px flex-1 bg-hairline"})]}),te.rows.map(fe=>{U+=1;const J=U;return c.jsx(_se,{id:`${n}-${J}`,option:fe,index:J,isActive:J===_,isHovered:J===y,isPicked:!1,onHover:Se=>S(Se),onPick:(Se,W)=>{w(W),Se.disabled||p(Se.value)}},`${fe.value}-${J}`)})]},te.heading??"all"))})]}),(B!==null||k!==null)&&c.jsxs("div",{"aria-live":"polite","data-header-identity-footer":"","data-header-identity-resolution":oe?"":void 0,className:"border-hairline border-t px-2 py-1.5 text-ink-dim text-meta",children:[k!==null&&c.jsx("span",{className:"block",children:k}),B!==null&&c.jsx("span",{className:"block",children:B})]})]}):c.jsxs(c.Fragment,{children:[z,c.jsx("div",{className:R(Aj,"text-ink-dim"),children:i?c.jsx("span",{"data-header-identity-loading":"",children:h("ui.chat.header_identity.loading",{kind:ie})}):a?c.jsx("span",{className:"text-danger","data-header-identity-error":"",children:a}):c.jsx("span",{children:o})})]})})};function Oet(e){return e?e.locality==="remote"?e.owner_device?`peer:${e.owner_device}`:null:"":null}function Let(e){return typeof e=="string"&&e.startsWith("cold-")}function VK(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:""}}function Bet(){return h("ui.chat.header_identity.no_team")}function jet(){return h("ui.chat.header_identity.no_agent")}const Nk="manager",Het="its manager";function Uet(e){const t=VK(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?Dp(i??{name:s}):Bet(),o=t===null&&e.hostPublishes===!0;let l=null;if((t!==null||o)&&r&&s){const d=i?i.manager||Nk:null,f=t?.speaker??"",g=f!==""&&!(f===r&&d!==r)?f:d;l={speaker:g??Het,speakerKnown:g!==null,team:r,sentence:Det(r,g),title:Iet(a)}}let u=l?l.speaker:e.activeAgent||e.boundAgent||null;return!u&&s&&(u=i?.manager||Nk),{teamValue:s,teamLabel:a,agentValue:u,agentLabel:u??jet(),teamManager:s&&i?i.manager||Nk:null,seat:l}}function Get(e){return!e.hasSession||e.pending||!e.teamCatalogue?!1:e.identityKnown||e.streamLive}function Vet(e){return e.teamOwnsSeat===!0||e.explicitAgent===null||e.manager===null||e.delegate===null?!1:!GK({name:e.explicitAgent,manager:e.manager,delegate:e.delegate})}const Wet=R("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"),$et=R("inline-flex size-3.5 shrink-0 items-center justify-center");function zet(e){return e??""}const Fj=({kind:e,label:t,current:n,busy:s,open:r,onOpenChange:i,onPick:a,sessionId:o,enabled:l,constraint:u,flagged:d,recents:f,swapRef:p,markSwap:g})=>{const v=u?.closed??null,b=E8(o,e,void 0,l&&v===null),x=b.data?.entities??[],_=n!==null,w=_&&t!==n,y=`header-identity-${e}-list`,S=`header-identity-${e}-closed`,C=m.useRef(null),E=m.useRef(v!==null);m.useEffect(()=>{const P=v!==null;if(P&&!E.current&&r){const M=document.activeElement;(M===null||M===document.body||M.closest("[data-header-identity-menu]")!==null)&&C.current?.focus()}E.current=P},[v,r]);const k=m.useRef(!1),F=r&&UK({loading:b.isLoading,loadError:b.isError?R_(b.error):null,rowCount:x.length}),A=m.useMemo(()=>x.map(P=>{const M=Dp({name:P.name??P.value,label:P.label}),Y=u!==null&&!GK({name:P.value,manager:u.manager,delegate:P.delegate,teamOwnsSeat:u.closed!==void 0});return{value:P.value,label:M,description:Y?Net:M!==P.value?P.description?`${P.value} · ${P.description}`:P.value:P.description,meta:P.kind,current:P.value===zet(n),disabled:s||Y,blocked:Y}}),[x,n,s,u]),I=u?.caption??null,N=v!==null?e==="team"?h("ui.chat.header_identity.aria_team_closed",{label:t,reason:v}):h("ui.chat.header_identity.aria_agent_closed",{label:t,reason:v}):_?e==="team"?h("ui.chat.header_identity.aria_team_switch",{label:t}):h("ui.chat.header_identity.aria_agent_switch",{label:t}):e==="team"?h("ui.chat.header_identity.aria_team_assign",{label:t}):h("ui.chat.header_identity.aria_agent_assign",{label:t});return c.jsxs(xh,{open:r,onOpenChange:i,modal:!1,children:[c.jsx(iE,{asChild:!0,children:c.jsxs("button",{ref:C,type:"button","data-header-identity":e,"data-header-identity-closed":v!==null?"":void 0,className:R(Wet,!_&&"text-ink-dim"),"aria-busy":s||void 0,"aria-haspopup":v===null?"listbox":"dialog","aria-controls":v!==null?r?S:void 0:F?y:void 0,onPointerDown:g,"aria-label":`${N}${v===null&&d&&I?`. ${I}`:""}`,title:v!==null?`${t} — ${v}`:d&&I?`${t} — ${I}`:_?`${t}${w?` (${n})`:""}`:e==="team"?h("ui.chat.header_identity.assign_team"):h("ui.chat.header_identity.assign_agent"),children:[e==="team"&&_&&c.jsx(RK,{name:t,slug:n??void 0,showTooltip:!1}),d&&c.jsx(Bo,{"data-header-identity-cue":"","aria-hidden":"true",className:"size-3 shrink-0 text-warning"}),c.jsx("span",{className:R("min-w-0 max-w-[24ch] truncate",w&&"font-sans"),children:t}),c.jsx("span",{className:R($et),children:s?c.jsx(On,{size:"xs"}):v!==null?c.jsx($0,{className:R("size-3 text-ink-dim"),"aria-hidden":"true"}):c.jsx(Ei,{className:R("size-3 text-ink-dim"),"aria-hidden":"true"})})]})}),c.jsx(Met,{kind:e,open:r,listId:y,options:A,recents:f,loading:b.isLoading,loadError:b.isError?R_(b.error):null,emptyText:e==="team"?"No teams are registered.":"No agents are registered.",caption:u?.caption??null,closedReason:v,closedNoteId:S,closedTitle:u?.closedTitle,onPick:P=>{i(!1),a(P)},onClose:()=>{C.current?.focus(),k.current=!0,i(!1)},onCloseAutoFocus:P=>{(p.current||k.current)&&(p.current=!1,k.current=!1,P.preventDefault())}})]})},qet=({sessionId:e,activeAgent:t,activeTeam:n,boundAgent:s,boundTeam:r,effectiveIdentity:i,hostKey:a=null,frameEpoch:o})=>{const l=n||r||null,u=VK(i)!==null;m.useSyncExternalStore(Nb.subscribe,Nb.version),m.useEffect(()=>{u&&i&&Nb.noteFrame(a,i)},[u,a,i]);const d=u||a!==null&&Nb.has(a),f=By(!!l),p=Uet({activeAgent:t,activeTeam:n,boundAgent:s,boundTeam:r,teams:f.data,effectiveIdentity:i,hostPublishes:d,coldFrame:Let(o)}),g=p.seat!==null,v=t||s||null,b=E8(e,"agent",void 0,!!(l&&v)&&!g),x=m.useMemo(()=>v?b.data?.entities.find(M=>M.value===v)?.delegate??null:null,[v,b.data]),_=Vet({explicitAgent:v,manager:p.teamManager,delegate:x,teamOwnsSeat:g}),w=m.useMemo(()=>Pet({teamLabel:p.teamLabel,manager:p.teamManager,closure:p.seat}),[p.teamLabel,p.teamManager,p.seat]),[y,S]=m.useState(null),C=m.useRef(!1),E=m.useCallback(()=>{C.current=!0,window.setTimeout(()=>{C.current=!1},300)},[]),k=T_(e),F=T_(e),A=nt(P=>P.profileRecents),I=nt(P=>P.rememberProfile),N=m.useCallback(async(P,M,Y)=>{if(Y.busy)return;const{result:O}=await Y.run(P,M,P==="team"?"Could not switch the team":"Could not switch the agent");O.tone==="error"?nn(O.text):O.tone==="warning"?Ru(O.text):O.tone==="success"&&I(P,M)},[I]);return c.jsxs("span",{"data-header-identity-controls":"",className:R("flex shrink-0 items-center gap-1"),children:[c.jsx(Fj,{kind:"agent",label:p.agentLabel,current:p.agentValue,busy:F.busy,constraint:w,flagged:_,swapRef:C,markSwap:E,open:y==="agent",onOpenChange:P=>S(P?"agent":null),onPick:P=>void N("agent",P,F),sessionId:e,enabled:y==="agent",recents:A.agent}),c.jsx(Fj,{kind:"team",label:p.teamLabel,current:p.teamValue,busy:k.busy,constraint:null,flagged:!1,swapRef:C,markSwap:E,open:y==="team",onOpenChange:P=>S(P?"team":null),onPick:P=>void N("team",P,k),sessionId:e,enabled:y==="team",recents:A.team})]})},Ket=40,Yet=({agent:e})=>vZe(e.agentId,e.sha256)?c.jsx("span",{className:"me-1 flex shrink-0 items-center",children:c.jsx(FK,{agentName:e.agentName??"",agentId:e.agentId,owned:e.owned&&e.agentName!==null,className:"size-5",pencilClassName:"size-2.5",children:c.jsx(DK,{agentId:e.agentId,sha256:e.sha256,className:"size-5",fallback:null})})}):null,Xet=({agentName:e="Local Operator",agentAvatar:t=null,description:n="Your on-device AI assistant",descriptionPending:s=!1,identity:r,deviceSlot:i,renameSessionId:a,sessionId:o,onOpenOptions:l,reserveTrailingChrome:u=!1,onToggleBrowser:d,archived:f=!1,archiveEnabled:p=!1,onSetArchived:g,deleteEnabled:v=!1,onRequestDelete:b,onOpenConsole:x,onOpenCodeReview:_,onToggleAsks:w,asksScope:y="session",asksOpen:S=!1})=>{Ve();const C=ss(),E=Gr(C.data,"peers"),k=Gr(C.data,"session_transfer"),F=nS(E)??nS(k)??void 0,A=Y0e(nS(E)!==null?E:k),I=Ga(le=>le.requestPicker),[N,P]=m.useState(!1),M=m.useRef(!1),Y=nt(le=>le.setCanvasOpen),O=nt(le=>le.isCanvasOpen),X=nt(le=>le.isCodeReviewPaneOpen),Q=nt(le=>le.transcriptDisplayMode),ie=JI(Q),G=nt(le=>le.setTranscriptDisplayMode),ne=nt(le=>le.setRunPanelOpen),oe=wse(),B=cJ(n,oe),H=B!=="~"&&B!=="",U=nt(le=>le.isBrowserPaneOpen),z=nt(le=>le.isConsolePaneOpen),te=nt(le=>le.isRunPanelOpen),fe=T_(a??""),J=fe.busy,[Se,W]=m.useState(!1),[Ce,K]=m.useState(""),[me,Ee]=m.useState(null),Ae=m.useRef("closed"),se=m.useRef(null),he=m.useRef(null),xe=m.useRef(null),Je=()=>{if(!a||Se)return;const le=he.current?.getBoundingClientRect();Ee(le?Math.ceil(le.width):null),K(e),Ae.current="edit",W(!0)},pe=le=>{Ae.current="closed",le&&xe.current?.focus(),W(!1)},Xe=async le=>{if(Ae.current!=="edit")return;const Qe=Ce.trim();if(!Qe||Qe===e){pe(le);return}Ae.current="saving";const{result:et}=await fe.run("rename",Qe,"Could not rename the conversation");if(et.tone==="error"){nn(et.text),Ae.current==="saving"&&(Ae.current="edit",se.current?.focus());return}et.tone==="warning"&&Ru(et.text),Ae.current==="saving"&&pe(le)};return m.useEffect(()=>{if(!Se)return;const le=se.current;le&&(le.focus(),le.select())},[Se]),c.jsxs("header",{"data-chat-region":"header","data-region-entry":!0,tabIndex:-1,className:R("@container/chathdr flex min-h-10 shrink-0 items-center gap-3 px-4"),"data-tour-tag":"chat-header","data-titlebar-drag":"",children:[c.jsxs("div",{className:R("flex min-w-0 flex-1 items-center gap-x-2 @[13.5rem]/chathdr:min-w-10",r?"min-h-5":"h-5 flex-wrap overflow-clip"),children:[c.jsxs("span",{className:R("group/title inline-flex min-w-0 max-w-full items-center gap-1"),"data-titlebar-no-drag":"",children:[Se?c.jsx("input",{ref:se,"data-header-rename-input":"",className:R("min-w-0 max-w-full border-0 bg-transparent p-0 outline-none","font-medium text-body text-ink"),style:me===null?void 0:{width:me},value:Ce,readOnly:J,"aria-label":h("ui.chat.header.conversation_name"),onChange:le=>K(le.target.value),onKeyDown:le=>{if(le.key==="Enter")le.preventDefault(),Xe(!0);else if(le.key==="Escape"){if(le.preventDefault(),Ae.current==="saving")return;pe(!0)}},onBlur:()=>void Xe(!1),spellCheck:!1}):c.jsxs(c.Fragment,{children:[t?c.jsx(Yet,{agent:t}):null,c.jsx("h2",{ref:he,"data-header-title":"",onDoubleClick:a?Je:void 0,className:R("min-w-0 max-w-full truncate font-medium text-body text-ink","cursor-default select-none"),children:e})]}),a&&c.jsx("button",{ref:xe,type:"button","data-header-rename":"","aria-label":J?h("ui.chat.header.saving_conversation_name"):Se?h("ui.chat.header.cancel_rename"):h("ui.chat.header.rename_conversation"),title:J?h("ui.chat.header.saving_conversation_name"):Se?h("ui.chat.header.cancel_rename"):h("ui.chat.header.rename_conversation"),"aria-busy":J||void 0,"aria-disabled":J||void 0,onMouseDown:le=>{Se&&le.preventDefault()},onClick:le=>{if(!(le.detail>1)&&Ae.current!=="saving"){if(!Se){Je();return}pe(!0)}},className:R("inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-xs","text-ink-dim","transition-opacity duration-base ease-out-quart",!Se&&"opacity-0 group-hover/title:opacity-100 group-hover/title:duration-fast",!Se&&"group-focus-within/title:opacity-100 group-focus-within/title:duration-fast","hover:text-ink-muted"),children:J?c.jsx(On,{size:"xs"}):Se?c.jsx(Xn,{className:R("size-3"),"aria-hidden":"true"}):c.jsx(Vv,{className:R("size-3"),"aria-hidden":"true"})})]}),s?c.jsx(Hx,{className:R("h-3 w-24 shrink-0 bg-elevated")}):r?c.jsx(qet,{...r}):H?c.jsx("span",{"data-header-path":"",className:R("shrink-0 whitespace-nowrap font-mono text-ink-dim text-mono-sm"),title:n,children:uJ(B,Ket)}):null,i]}),c.jsxs("div",{"data-titlebar-no-drag":"",className:"ms-auto flex items-center gap-2",children:[p&&f&&c.jsxs(c.Fragment,{children:[c.jsxs(Lu,{shape:"pill","data-session-archived-pill":!0,title:h("ui.chat.header.archived_hint"),children:[c.jsx(np,{"aria-hidden":"true"}),h("ui.chat.header.archived")]}),g&&c.jsx(ce,{variant:"ghost",size:"icon",onClick:()=>g(!1),"aria-label":C_(e,!0),title:C_(e,!0),children:c.jsx(K_,{"aria-hidden":"true"})})]}),(p||v||w||d||x||l)&&c.jsxs(Po,{open:N,onOpenChange:P,children:[c.jsx(eo,{asChild:!0,children:c.jsx(ce,{variant:"ghost",size:"icon","data-conversation-actions":!0,"aria-label":h("ui.chat.header.actions"),children:c.jsx(oc,{"aria-hidden":"true"})})}),c.jsxs(Mo,{align:"end",className:"min-w-45",onCloseAutoFocus:le=>{M.current&&(M.current=!1,o&&I(o),le.preventDefault())},children:[o&&c.jsxs(Jt,{onSelect:()=>void cK(o),children:[c.jsx(ed,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.header.copy_id")})]}),o&&c.jsxs(Jt,{"data-session-move-action":!0,title:F,"data-move-reason":F,"aria-disabled":F?!0:void 0,onSelect:()=>{F||(M.current=!0)},className:R(F&&"cursor-not-allowed data-[highlighted]:bg-transparent data-[highlighted]:text-ink-muted"),children:[c.jsx(Tue,{"aria-hidden":"true"}),c.jsxs("span",{className:"flex min-w-0 flex-col items-start gap-0.5",children:[c.jsx("span",{children:h("ui.chat.header.move_device")}),F?c.jsx("span",{className:R("max-w-[11rem] whitespace-normal text-meta",A==="dim"?"text-ink-dim":"text-warning"),children:F}):null]})]}),c.jsxs(wZ,{children:[c.jsxs(yZ,{children:[c.jsx($ue,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.header.transcript_display")}),c.jsx("span",{className:"text-body-sm text-ink-dim",children:dJ(ie)})]}),c.jsx(CZ,{children:c.jsx(SZ,{value:ie,onValueChange:le=>G(JI(le)),children:hJ.map(le=>c.jsxs(kZ,{value:le.value,children:[c.jsx("span",{children:le.label}),ie===le.value&&c.jsx(Js,{"aria-hidden":"true",className:"ms-auto text-accent"})]},le.value))})})]}),c.jsx(Nr,{}),p&&c.jsxs(Jt,{"data-session-archive-action":!0,onSelect:()=>g?.(!f),disabled:!g,children:[f?c.jsx(K_,{"aria-hidden":"true"}):c.jsx(np,{"aria-hidden":"true"}),c.jsx("span",{children:f?h("ui.chat.header.restore_conversation"):h("ui.chat.header.archive_conversation")})]}),p&&v&&c.jsx(Nr,{}),v&&c.jsxs(Jt,{"data-session-delete":!0,className:"text-danger",onSelect:()=>b?.(),disabled:!b,children:[c.jsx(cg,{"aria-hidden":"true"}),c.jsx("span",{children:h("ui.chat.header.delete")})]}),(w||d||x||_||l)&&c.jsx(Nr,{}),(w||d||x||_||l)&&c.jsxs(Jt,{onSelect:()=>ne(!te),children:[c.jsx(ig,{"aria-hidden":"true"}),c.jsx("span",{children:te?h("ui.chat.header.close_run_details"):h("ui.chat.header.open_run_details")})]}),w&&c.jsxs(Jt,{onSelect:()=>w(),children:[c.jsx(qG,{scope:y,"aria-hidden":!0}),c.jsx("span",{children:S?"Close asks":"Open asks"})]}),d&&c.jsxs(Jt,{onSelect:()=>d(),children:[c.jsx(Uu,{"aria-hidden":"true"}),c.jsx("span",{children:U?"Close browser":"Open browser"})]}),x&&c.jsxs(Jt,{onSelect:()=>x(),children:[c.jsx(h2,{"aria-hidden":"true"}),c.jsx("span",{children:z?"Close console":"Open console"})]}),l&&c.jsxs(Jt,{onSelect:()=>Y(!O),children:[c.jsx(Ty,{"aria-hidden":"true"}),c.jsx("span",{children:O?"Close canvas":"Open canvas"})]}),_&&c.jsxs(Jt,{onSelect:()=>_(),children:[c.jsx(kA,{"aria-hidden":"true"}),c.jsx("span",{children:X?"Close code review":"Open code review"})]})]})]})]}),u?c.jsx("div",{className:"chrome-reserve-trailing"}):null]})},Cr=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)}},Rf=({label:e,description:t,defaultValue:n,onSetValue:s,icon:r})=>(Ve(),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:h("ui.agents.settings.chat.not_set_yet")}),c.jsx(ce,{variant:"outline",size:"sm",onClick:async()=>{await s(n)},children:h("ui.agents.settings.chat.set_to_default",{value:String(n)})})]})]})),Dj=({label:e,description:t,defaultDisplayText:n,onSetValue:s,icon:r})=>(Ve(),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:h("ui.agents.settings.chat.not_set_yet")}),c.jsx(ce,{variant:"outline",size:"sm",onClick:async()=>{await s()},children:h("ui.agents.settings.chat.set_to_default",{value:n})})]})]})),Qet=({agent:e,savingField:t,setSavingField:n,setLocalAgent:s,refetchAgent:r,updateAgentMutation:i})=>(Ve(),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:"me-2 flex items-center rounded-sm bg-accent-wash p-1 text-accent",children:c.jsx(Lp,{size:16,"aria-hidden":"true"})}),h("ui.agents.settings.chat.generation_settings"),c.jsx(vt,{content:h("ui.agents.settings.chat.generation_tooltip"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",type:"button",className:"ms-1 text-accent","aria-label":h("ui.common.actions.more_info"),children:c.jsx(ig,{"aria-hidden":"true"})})})]}),c.jsx("p",{className:"mt-1 text-body-sm text-ink-muted",children:h("ui.agents.settings.chat.set_custom_values_note")})]}),e.temperature===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.temperature"),description:h("ui.agents.settings.chat.controls_randomness_in_responses_0_0_1"),defaultValue:.2,onSetValue:async a=>{await Cr("temperature",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.temperature??.2,label:h("ui.agents.settings.chat.temperature"),description:h("ui.agents.settings.chat.controls_randomness_in_responses_0_0_1"),min:0,max:1,step:.01,isSaving:t==="temperature",onChange:async a=>{await Cr("temperature",a,e.id,i,s,r,n)}}),e.top_p===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.top_p"),description:h("ui.agents.settings.chat.controls_cumulative_probability_of_tokens_to_sample"),defaultValue:.9,onSetValue:async a=>{await Cr("top_p",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.top_p??.9,label:h("ui.agents.settings.chat.top_p"),description:h("ui.agents.settings.chat.controls_cumulative_probability_of_tokens_to_sample"),min:0,max:1,step:.01,isSaving:t==="top_p",onChange:async a=>{await Cr("top_p",a,e.id,i,s,r,n)}}),e.top_k===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.top_k"),description:h("ui.agents.settings.chat.limits_tokens_to_sample_from_at_each"),defaultValue:40,onSetValue:async a=>{await Cr("top_k",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.top_k??40,label:h("ui.agents.settings.chat.top_k"),description:h("ui.agents.settings.chat.limits_tokens_to_sample_from_at_each"),min:1,max:100,step:1,isSaving:t==="top_k",onChange:async a=>{await Cr("top_k",a,e.id,i,s,r,n)}}),e.max_tokens===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.max_tokens"),description:h("ui.agents.settings.chat.maximum_tokens_to_generate_in_response"),defaultValue:4096,onSetValue:async a=>{await Cr("max_tokens",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.max_tokens??4096,label:h("ui.agents.settings.chat.max_tokens"),description:h("ui.agents.settings.chat.maximum_tokens_to_generate_in_response"),min:1,max:8192,step:1,isSaving:t==="max_tokens",onChange:async a=>{await Cr("max_tokens",a,e.id,i,s,r,n)}}),e.stop===null?c.jsx(Dj,{label:h("ui.agents.settings.chat.stop_sequences"),description:h("ui.agents.settings.chat.sequences_that_will_cause_the_model_to"),defaultValue:[],defaultDisplayText:"empty",icon:c.jsx(Su,{size:16,className:"me-2.5","aria-hidden":"true"}),onSetValue:async()=>{await Cr("stop",[],e.id,i,s,r,n)}}):c.jsx(OM,{value:e.stop?.join(`
684
684
  `)||"",label:h("ui.agents.settings.chat.stop_sequences"),placeholder:h("ui.agents.settings.chat.enter_stop_sequences_one_per_line"),icon:c.jsx(Su,{size:16}),multiline:!0,rows:3,isSaving:t==="stop",onSave:async a=>{const o=a.split(`
685
685
  `).map(l=>l.trim()).filter(l=>l.length>0);await Cr("stop",o.length>0?o:void 0,e.id,i,s,r,n)}}),e.frequency_penalty===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.frequency_penalty"),description:h("ui.agents.settings.chat.reduces_repetition_by_lowering_likelihood_of_repeated"),defaultValue:0,onSetValue:async a=>{await Cr("frequency_penalty",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.frequency_penalty??0,label:h("ui.agents.settings.chat.frequency_penalty"),description:h("ui.agents.settings.chat.reduces_repetition_by_lowering_likelihood_of_repeated"),min:-2,max:2,step:.01,isSaving:t==="frequency_penalty",onChange:async a=>{await Cr("frequency_penalty",a,e.id,i,s,r,n)}}),e.presence_penalty===null?c.jsx(Rf,{label:h("ui.agents.settings.chat.presence_penalty"),description:h("ui.agents.settings.chat.increases_diversity_by_lowering_likelihood_of_prompt"),defaultValue:0,onSetValue:async a=>{await Cr("presence_penalty",a,e.id,i,s,r,n)}}):c.jsx(wf,{value:e.presence_penalty??0,label:h("ui.agents.settings.chat.presence_penalty"),description:h("ui.agents.settings.chat.increases_diversity_by_lowering_likelihood_of_prompt"),min:-2,max:2,step:.01,isSaving:t==="presence_penalty",onChange:async a=>{await Cr("presence_penalty",a,e.id,i,s,r,n)}}),e.seed===null?c.jsx(Dj,{label:h("ui.agents.settings.chat.seed"),description:h("ui.agents.settings.chat.random_number_seed_for_deterministic_generation"),defaultValue:42,defaultDisplayText:"42",icon:c.jsx(Su,{size:16,className:"me-2.5","aria-hidden":"true"}),onSetValue:async()=>{await Cr("seed",42,e.id,i,s,r,n)}}):c.jsx(OM,{value:e.seed?.toString()||"",label:h("ui.agents.settings.chat.seed"),placeholder:h("ui.agents.settings.chat.random_number_seed_for_deterministic_generation"),icon:c.jsx(Su,{size:16}),isSaving:t==="seed",onSave:async a=>{const o=a.trim()?Number.parseInt(a,10):void 0;if(a.trim()&&Number.isNaN(o)){nn(h("ui.notices.chat.seed_invalid"));return}await Cr("seed",o,e.id,i,s,r,n)}})]})),Jet=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}),Zet=(e,t)=>({id:e.id,name:e.name,description:e.description,url:e.url,requiredCredentials:e.requiredCredentials,supportedModels:t.map(Jet)});let Pk=null,Ij=null,Nj=null,Pj=null;const ND=()=>{const e=th.getState(),{providers:t,models:n,isInitialized:s}=e;if(Pk&&Ij===n&&Nj===t&&Pj===s)return Pk;if(!s||t.length===0)return[];const r=t.map(i=>{const a=n.filter(o=>o.provider===i.id);return Zet(i,a)});return Pk=r,Ij=n,Nj=t,Pj=s,r},Xp=e=>ND().find(n=>n.id===e),$R=e=>Xp(e)?.supportedModels||[],ett=e=>ND().filter(n=>n.requiredCredentials.every(s=>e.includes(s))),WK=({value:e,onSave:t,isSaving:n=!1,filterByCredentials:s=!0,emptyHelperText:r=h("ui.common.models.hosting_select.no_hosting_providers_available_sign_in_to_a_provider_or_add_a_pro"),allowCustom:i=!0,allowDefault:a=!0})=>{Ve();const o=ss(),l=Et(o.data,"auth"),u=Pv(l),{data:d}=T8(),f=m.useMemo(()=>d?.keys||[],[d]),{refreshModels:p,isInitialized:g,providers:v}=UA(),[b,x]=m.useState(!1),_=m.useMemo(()=>yse({data:u.data,isError:u.isError}),[u.data,u.isError]),w=l&&_.status==="failed",y=m.useMemo(()=>{const A=ND();return s?l?Cse(A,_):ett(f):A},[s,l,_,f,g,v]),S=(()=>{const A=[];a&&A.push({id:"",name:h("ui.common.models.default"),description:h("ui.common.models.hosting_select.clear_hosting_provider_selection"),provider:void 0});for(const I of y)A.push({id:I.id,name:I.name,description:I.description,provider:I});if(e&&!y.some(I=>I.id===e)){const I=Xp(e);I?A.push({id:I.id,name:I.name,description:w?I.description:h("ui.common.models.hosting_select.detail",{description:String(I.description)}),provider:I}):i&&A.push({id:e,name:e,description:h("ui.common.models.hosting_select.custom_hosting_provider"),provider:{id:e,name:e,description:h("ui.common.models.hosting_select.custom_hosting_provider"),url:"",requiredCredentials:[],supportedModels:[]}})}return A})(),C=(()=>{if(s&&w)return Sse(u.error);if(s&&y.length===0&&!e)return r})(),E=!e&&!a||!a&&y.length===0&&!S.some(A=>A.id===e&&e!=="")?null:!e&&a?S.find(A=>A.id==="")||null:e?S.find(A=>A.id===e)||{id:e,name:e,description:h("ui.common.models.hosting_select.custom_hosting_provider"),provider:void 0}:null,k=async A=>{try{if(x(!0),await t(A),A!==e)try{await p()}catch(I){console.error("Error refreshing models after hosting provider change:",I)}}catch(I){console.error("Error saving hosting provider:",I)}finally{x(!1)}},F=!a&&s&&!w&&y.length===0&&!S.some(A=>A.id===e&&e!=="");return c.jsx(_A,{label:h("ui.common.models.hosting_select.hosting_provider"),icon:c.jsx(R8,{size:16,"aria-hidden":"true"}),labelTooltip:h("ui.common.models.hosting_select.select_the_ai_provider_that_you_want_to_use_each_provider_has_dif"),placeholder:h("ui.common.models.hosting_select.select_a_hosting_provider"),options:S,selected:E,onSelect:A=>{k(A.id)},onCustomSubmit:i?A=>{k(A)}:void 0,helperText:C,busy:n||b,busyLabel:h("ui.common.models.hosting_select.saving_hosting_provider"),disabled:F})},Mj=(e,t,n)=>{const s=e.find(i=>i.id===t);if(s)return s;if(!n||!Xp(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}`)},ttt=e=>{if(!e||typeof e!="string")return"";const t=e.indexOf("/");return t>0?e.substring(0,t):""},Mk=(e,t)=>{if(t==="radient"&&e==="auto")return h("ui.common.models.model_select.auto_recommended");if(e==="")return h("ui.common.models.model_select.general");const n=ttt(e);if(t==="radient"&&n==="radient")return"Radient";const s=Xp(n);return s?s.name:n||h("ui.common.models.model_select.other_models")},ntt=({markdown:e})=>c.jsx("div",{className:"[&_p]:m-0",children:c.jsx(kse,{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})}),stt=()=>(Ve(),c.jsx(vt,{content:h("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(pde,{size:12,"aria-hidden":"true"}),c.jsx("span",{className:"sr-only",children:h("ui.common.models.model_select.recommended")})]})})),$K=({value:e,hostingId:t,onSave:n,isSaving:s=!1,allowCustom:r=!0,allowDefault:i=!0})=>{Ve();const[a,o]=m.useState(!1),l=th(C=>C.models),u=th(C=>C.isInitialized),d=m.useMemo(()=>t?$R(t):[],[t,l,u]),{refreshModels:f,isLoading:p}=UA(),g=m.useRef(null),v=m.useRef(null),b=m.useRef(!0);m.useEffect(()=>{if(b.current){b.current=!1,g.current=t;return}if(t&&g.current!==t)return g.current=t,v.current&&(clearTimeout(v.current),v.current=null),v.current=setTimeout(()=>{p||f().catch(C=>{console.error("Error refreshing models:",C)}),v.current=null},300),()=>{v.current&&(clearTimeout(v.current),v.current=null)}},[t,f,p]);const x=(()=>{const C=[],E=new Set,k=new Set(d.map(I=>I.id)),F=!!Xp(t),A=I=>({id:I.id,name:I.name,keywords:[I.id,...F&&!k.has(`${t}/${I.id}`)?[`${t}/${I.id}`]:[]],description:I.description?c.jsx(ntt,{markdown:I.description}):void 0,adornment:I.recommended?c.jsx(stt,{}):void 0,group:Mk(I.id,t),model:I,recommended:I.recommended});if(t==="radient"){const I=d.find(N=>N.id==="auto");I&&(C.push(A(I)),E.add(I.id))}i&&!E.has("")&&(C.push({id:"",name:h("ui.common.models.default"),description:h("ui.common.models.model_select.clear_model_selection"),group:Mk("",t),model:void 0}),E.add(""));for(const I of d)E.has(I.id)||(C.push(A(I)),E.add(I.id));return e&&e.trim()!==""&&!Mj(C,e,t)&&C.push({id:e,name:e,description:h("ui.common.models.model_select.custom_model"),group:Mk(e,t),model:void 0}),C})(),_=(()=>{if(!t&&!i)return h("ui.common.models.model_select.select_a_hosting_provider_first");if(t&&d.length===0&&!i&&!x.some(C=>C.id===e&&e!==""))return h("ui.common.models.model_select.no_models_available_for_selected_provider");if(d.length===0&&t&&!x.some(C=>C.id===e&&e!=="")){const C=Xp(t);return C?h("ui.common.models.model_select.no_models_for",{name:String(C.name)}):h("ui.common.models.model_select.no_models_available")}})(),w=(()=>{if((!e||e.trim()==="")&&!i&&d.length===0)return null;if((!e||e.trim()==="")&&i)return x.find(E=>E.id==="")||null;if(!e||e.trim()==="")return null;const C=Mj(x,e,t);return C||{id:e,name:e,description:h("ui.common.models.model_select.custom_model"),model:void 0}})(),y=async C=>{try{o(!0),await n(C)}catch(E){console.error("Error saving model:",E)}finally{o(!1)}},S=!!(!t&&!i||t&&d.length===0&&!i&&!x.some(C=>C.id===e&&e!==""));return c.jsx(_A,{label:h("ui.common.models.model_select.model"),icon:c.jsx(Mce,{size:16,"aria-hidden":"true"}),labelTooltip:h("ui.common.models.model_select.select_the_ai_model_that_you_want_to_use_each_model_has_different"),placeholder:h("ui.common.models.model_select.select_a_model"),options:x,selected:w,onSelect:C=>{y(C.id)},onCustomSubmit:r?C=>{y(C)}:void 0,helperText:_,busy:s||a||p,busyLabel:h("ui.common.models.model_select.loading_models"),disabled:S})},rtt=({agent:e,savingField:t,setSavingField:n,setLocalAgent:s,refetchAgent:r,updateAgentMutation:i})=>(Ve(),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:"me-2 flex items-center rounded-sm bg-accent-wash p-1 text-accent",children:c.jsx(R8,{size:16,"aria-hidden":"true"})}),h("ui.agents.settings.chat.model_hosting_heading"),c.jsx(vt,{content:h("ui.agents.settings.chat.model_hosting_tooltip"),children:c.jsx(ce,{variant:"ghost",size:"icon-sm",type:"button",className:"ms-1 text-accent","aria-label":h("ui.common.actions.more_info"),children:c.jsx(ig,{"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(WK,{value:e.hosting||"",isSaving:t==="hosting",onSave:async a=>{await Cr("hosting",a,e.id,i,s,r,n)}}),c.jsx($K,{value:e.model||"",hostingId:e.hosting||"",isSaving:t==="model",onSave:async a=>{await Cr("model",a,e.id,i,s,r,n)}})]})]})),itt=({agentId:e})=>{const[t,n]=m.useState(!1),s=zU(),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(cg,{"aria-hidden":"true"}),h("ui.chat.dialogs.options.clear_conversation")]}),c.jsx(nd,{open:t,title:h("ui.chat.dialogs.options.clear_title"),message:h("ui.chat.dialogs.options.clear_message"),confirmText:h("ui.chat.dialogs.options.clear_confirm"),cancelText:h("ui.common.actions.cancel"),isDangerous:!0,onConfirm:r,onCancel:()=>n(!1)})]})},att=({open:e,onClose:t,agentId:n})=>{Ve();const[s,r]=m.useState(null),i=xfe(),{data:a,refetch:o,isLoading:l}=Ode(n),[u,d]=m.useState(null);return m.useEffect(()=>{a&&d(a)},[a]),!u||l?null:c.jsx(EZ,{open:e,onOpenChange:f=>!f&&t(),children:c.jsxs(TZ,{side:"end",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(RZ,{className:"font-semibold text-heading text-ink",children:h("ui.chat.dialogs.options.title")}),c.jsx(AZ,{className:"text-body-sm text-ink-muted",children:h("ui.chat.dialogs.options.description")})]}),c.jsx(ce,{variant:"ghost",size:"icon",onClick:t,"aria-label":h("ui.common.actions.close"),children:c.jsx(Xn,{"aria-hidden":"true"})})]}),c.jsxs("div",{className:"grow overflow-y-auto px-6 py-4",children:[c.jsx(rtt,{agent:u,savingField:s,setSavingField:r,setLocalAgent:d,refetchAgent:o,updateAgentMutation:i}),c.jsx(Qet,{agent:u,savingField:s,setSavingField:r,setLocalAgent:d,refetchAgent:o,updateAgentMutation:i}),n&&c.jsx(itt,{agentId:n})]})]})})},ott={unreachable:"ui.chat.status.unreachable","credential-refused":"ui.chat.status.credential_refused",degraded:"ui.chat.status.degraded","internet-offline":"ui.chat.status.internet_offline"},Dx=e=>h(ott[e]);function Oj(e){return{state:e.state,reconnecting:e.reconnecting??!1,detail:e.detail??null,pairing:e.pairing??null,addressSubstitution:null}}function ltt(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:Dx("credential-refused"),detail:ZI(Oj(t))?.detail??null,action:"retry",actionLabel:h("ui.common.actions.retry"),dot:"danger"};if(n==="internet_offline"&&e.internetOffline)return{kind:"internet-offline",role:"status",wash:"warning-wash",title:Dx("internet-offline"),detail:null,action:"retry",actionLabel:h("ui.common.actions.retry"),dot:"warning"};if(t!==null&&eN(t.state)&&(t.reconnecting===!0||t.state==="degraded"))return{kind:"degraded",role:"status",wash:"warning-wash",title:Dx("degraded"),detail:null,action:"retry",actionLabel:h("ui.common.actions.retry"),dot:"warning"};const s=t?.pairing??null;return!(s?.available===!1&&s.cause!=="credential-refused")&&(n==="server_offline"||t!==null&&!eN(t.state))?{kind:"unreachable",role:"alert",wash:"danger-wash",title:Dx("unreachable"),detail:t?ZI(Oj(t))?.detail??null:null,action:"retry",actionLabel:h("ui.common.actions.retry"),dot:"danger"}:null}function zK(e){return e?`${e.kind}:${e.cause??""}`:null}const ctt=({display:e,dismissedKey:t,onDismiss:n,onShow:s,retrying:r=!1,outcome:i=null,onRetry:a})=>{Ve();const o=zK(e),l=o!==null&&t===o,u=m.useCallback(d=>{d.key!=="Escape"||!o||(d.stopPropagation(),n(o))},[o,n]);return e?l?c.jsx("div",{className:R("flex items-center px-6 py-1"),"data-lo-status-pill":"",children:c.jsxs("button",{type:"button",onClick:s,className:R("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:R("size-1.5 rounded-full",e.dot==="danger"?"bg-danger":"bg-warning")}),e.kind==="internet-offline"?"Offline":"Connection"]})}):c.jsx("div",{className:R("shrink-0 px-6 py-1"),"data-lo-status-strip":"",onKeyDown:u,children:c.jsx(Rr,{variant:e.wash==="danger-wash"?"danger":"warning",className:Zy,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(ri,{"aria-hidden":"true",className:"animate-spin"}):null,r?"Retrying…":e.actionLabel??"Retry"]}),c.jsx("button",{type:"button",onClick:()=>o&&n(o),className:R("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":h("ui.chat.status_strip.dismiss"),children:c.jsx(Xn,{"aria-hidden":"true",className:"size-3.5"})})]})]})})}):null},utt=()=>{const e=Ve(),{connectivityIssue:t,serverSnapshot:n,refetchServerStatus:s}=Ese(),[r,i]=m.useState(!1),a=m.useRef($U());m.useEffect(()=>{const y=()=>i(gfe(a.current,{isOnline:navigator.onLine,at:Date.now()}).report);return y(),window.addEventListener("offline",y),window.addEventListener("online",y),()=>{window.removeEventListener("offline",y),window.removeEventListener("online",y)}},[]);const o=t==="server_offline"||t==="internet_offline"?t:null,l=m.useMemo(()=>ltt({connectivityIssue:o,server:n,internetOffline:r}),[o,n,r,e]),u=l!==null;m.useEffect(()=>(pO(u),()=>pO(!1)),[u]);const[d,f]=m.useState(null),[p,g]=m.useState(!1),[v,b]=m.useState(null),x=m.useRef(null),_=zK(l);m.useEffect(()=>{v!==null&&x.current!==_&&(x.current=null,b(null))},[_,v]);const w=m.useCallback(async()=>{g(!0),b(null),x.current=_;try{await window.api?.backend?.reconnect?.()}finally{g(!1),b(_?.startsWith("credential-refused")?"The server is running, but this app's credential is still refused.":"Still unreachable."),s()}},[_,s]);return c.jsx(ctt,{display:l,dismissedKey:d,onDismiss:f,onShow:()=>f(null),retrying:p,outcome:v,onRetry:()=>void w()})},dtt="This backend cannot delete conversations. Update the backend and try again.";function htt(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 ftt="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.",ptt=({title:e,hasSubagentRuns:t})=>{Ve();const n=Fe(g=>g.deleteCandidate),s=Fe(g=>g.sessions),r=Fe(g=>g.requestSessionDelete),i=Fe(g=>g.deleteSession),[a,o]=m.useState(null),l=a&&a.candidate===n?a:null,[u,d]=m.useState(0),f=m.useRef(null);m.useEffect(()=>{if(n!==null){f.current=document.activeElement instanceof HTMLElement?document.activeElement:null;return}const g=f.current;if(f.current=null,!!g){if(g.isConnected){g.focus();return}document.querySelector("[data-conversation-actions]")?.focus()}},[n]);const p=s.find(g=>g.session_id===n)?.title||e;return c.jsx(nd,{open:n!==null,title:h("ui.chat.dialogs.delete_title"),message:c.jsxs(c.Fragment,{children:[c.jsx("p",{children:htt(p,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:ftt})]}),confirmText:h("ui.chat.dialogs.delete_action"),cancelText:h("ui.chat.dialogs.cancel"),isDangerous:!0,focusCancelSignal:u,onConfirm:()=>{n&&(async()=>{const g=await i(n);g.ok||(o({candidate:n,detail:g.detail,guarded:g.guarded}),d(v=>v+1))})()},onCancel:()=>r(null)})},gtt=[],mtt=[{id:"canonical",role:"system",timestamp:new Date(0)}],vtt={},btt=(e,t=!1)=>!!(e&&qse({status:e.view.status,failure:e.view.failure,stale:e.view.stale,missing:e.view.missing||t})),Lj=(e,t=!1)=>!!(e&&D8({status:e.view.status,failure:e.view.failure,stale:e.view.stale,missing:e.view.missing||t})),Ix={openTabs:[],selectedTabId:null,files:[],mentionedFiles:[]},xtt=jx,_tt=it.memo(({activeTab:e,onTabChange:t,agentName:n,description:s,descriptionPending:r,identity:i,deviceSlot:a,deviceNotice:o,deviceHold:l,renameSessionId:u,onOpenOptions:d,onStartNewChat:f,isOptionsSidebarOpen:p,onCloseOptions:g,agentId:v,agentAvatar:b=null,agentSpeakerName:x=null,messages:_,isLoading:w,isLoadingMessages:y,isFarFromBottom:S,hasNewActivity:C=!1,messagesContainerRef:E,scrollToBottom:k,rawInfoContent:F,onSendMessage:A,currentJobId:I,onCancelJob:N,onComposerInput:P,agentData:M,messageInputRef:Y,cwd:O,sessionId:X,turnTerminal:Q,cwdWritePath:ie,cwdPending:G,cwdPendingAccepted:ne,cwdReadOnlyReason:oe,sendError:B,soundStopConfirmation:H,sessionStatus:U,onSlashCommand:z,onSlashNote:te,paneHasSession:fe,canonical:J,undelivered:Se=null,runDetails:W,mcpServers:Ce=[],mcpGrantRunning:K=!1,mcpRemedy:me,monitorControls:Ee,wakeControls:Ae,jobControls:se,wakeAida:he,childrenOpenable:xe=!1,mentionsEnabled:Je=!1,mentionsUnsupported:pe=!1,pulses:Xe})=>{Ve();const[le,Qe]=m.useState(!1),et=h8(),ue=Mt(),Le=m.useCallback(He=>ue.invalidateQueries({queryKey:No.credentials(He)}),[ue]),Ne=m.useRef(null),Ue=m.useRef(null),dt=A8(J?.view.frontend),St=Se!==null&&J.view.transcript.records.some(He=>He.kind==="user"&&He.id===Se.recordId)?Se:null,Dt=ss(),{needsProvider:sn,needsModel:Kt}=Tse(),ut=Et(Dt.data,"session_archive"),Ft=Et(Dt.data,"session_delete"),At=Et(Dt.data,"aside_adopt_queue"),cn=Hm(He=>X?He.attached[X]?.queued?.messageIds.length??-1:-1),rn=J.view.transcript.index;m.useEffect(()=>{cn<0||!X||Rse(X,He=>rn.has(He),J.turnAlive)},[cn,X,rn,J.turnAlive]);const kn=Gr(Dt.data,"code_requests"),ws=F8(),Vt=x_e({sessionId:X,state:kn,cause:ws??null,loadError:Dt.data?null:Dt.error}),cs=Fe(He=>X?(He.archiveFacts[X]?.archived??He.sessions.find(Tn=>Tn.session_id===X)?.archived)===!0:!1),Vn=Fe(He=>X?He.forgotten[X]!==void 0:!1),zr=Fe(He=>X?He.sessions.some(Tn=>Tn.session_id===X):!1),ls=He=>X?_8(He.sessions.find(Tn=>Tn.session_id===X)):null,En=Fe(He=>ls(He)?.agentId??null),Vs=Fe(He=>ls(He)?.agentName??null),un=Fe(He=>ls(He)?.sha256??null),It=Fe(He=>ls(He)?.owned??!1),dn=Vn||J?.view.missing===!0&&!zr,tr=Vn||J?.view.missing===!0,Sn=J?.stopOutcome==="pending"||J?.stopOutcome==="awaiting-end",Ie=Sn&&J?.turnAlive===!0,ge=Lj(J,dn),Pe=m.useMemo(()=>fJ(J?.view.history),[J?.view.history]),L=m.useMemo(()=>J?.stopAvailable&&!ge?{active:J.turnAlive,stopping:Ie,onStop:J.onStop,onConfirmedStop:J.onConfirmedStop}:void 0,[J?.stopAvailable,ge,J?.turnAlive,Ie,J?.onStop,J?.onConfirmedStop]),V=Fe(He=>He.setSessionArchived),j=Fe(He=>He.requestArchiveConfirm),q=m.useCallback(He=>{if(X){if(!He){V(X,!1,n);return}j({sessionId:X,fromRow:!1,fromHeader:!0,title:n})}},[X,n,V,j]),Z=Fe(He=>He.requestSessionDelete);m.useEffect(()=>{if(!Ne.current)return;const He=new ResizeObserver(Tn=>{for(const Rs of Tn)Rs.contentRect.width<550?Qe(!0):Qe(!1)});return He.observe(Ne.current),()=>{He.disconnect()}},[]);const ee=nt(He=>He.rightSlotWidth),_e=nt(He=>He.setRightSlotWidth),Re=nt(He=>He.restoreDefaultRightSlotWidth),ye=v,Te=Fe(He=>ye?He.stoppedTurns[ye]??null:null),ae=m.useMemo(()=>{if(Te===null||!J)return null;const He=J.view.transcript.records;for(let Tn=He.length-1;Tn>=0;Tn-=1){const Rs=He[Tn];if(Rs.kind==="user")return Rs.text}return null},[Te,J]),we=Fs(He=>He.conversations[ye]),De=nt(He=>He.isCanvasOpen),$e=De&&(we?.viewMode??"documents")==="files",ke=m.useMemo(()=>$e&&J?{active:!0,hasMore:J.view.transcript.hasMore,oldestId:J.view.transcript.oldestId,loadOlder:J.view.loadOlder,blocked:J.view.loadingOlder}:null,[$e,J]),tt=Fe(He=>X?hA(He.sessions,He.placementFacts,X):!1),ht=Dt.data!==void 0&&!Et(Dt.data,"session_files")&&!tt,Ot=_we({conversationId:ye,records:J?.view.transcript.records??null,cwd:J?.view.frontend?.cwd,sessionId:X,enabled:!!(J?.view.frontend&&!J.view.awaitingHydration&&v&&ht),scan:ke}),Ut=Fs(He=>He.setOpenTabs),en=Fs(He=>He.setSelectedTab),yn=Fs(He=>He.setFiles),wn=nt(He=>He.isRunPanelOpen),Ps=nt(He=>He.setRunPanelOpen),[ys,Ts]=m.useState(null),an=wn&&ys===null;m.useEffect(()=>{wn||Ts(null)},[wn]);const ba=(we??Ix).openTabs,fi=(we??Ix).selectedTabId,Ms=(we??Ix).files,Ii=QG(X,!0,Q),co=k8(X,J?.view.transcript.records??null,Q),Yi=co.items,Nl=co.verdicts,Oe=m.useMemo(()=>Ase({items:Yi,verdicts:Nl}),[Yi,Nl]),kt=n9(Ii.mode==="index"?Ii.total:(we??Ix).mentionedFiles.length,Ii.mode==="index"?Ii.rows.map(He=>He.ref.type==="artifact"?He.ref.digest:null):[],co),jt=Tb(Db,ee),pi=nt(He=>He.isBrowserPaneOpen),xa=nt(He=>He.setBrowserPaneOpen),Ws=Tb(nN,ee),Cs=nt(He=>He.isConsolePaneOpen),uo=nt(He=>He.isCodeReviewPaneOpen),hr=nt(He=>He.isAskDrawerOpen),_a=nt(He=>He.askDrawerScope),hd=hr&&_a==="session"&&!!X,gi=nt(He=>He.setAskDrawerOpen),Wo=nt(He=>He.requestAskOpen),sf=nt(pJ),wa=J.asks===void 0?J?.view.frontend??null:J.asks,mi=m.useMemo(()=>Fse(wa),[wa]),jc=m.useCallback(He=>{gi(!0,"session"),He?.focus!==!1&&Wo("session","chord")},[gi,Wo]),fd=m.useMemo(()=>{const He=mi.head;if(!Dse(mi)||He===null)return null;const Tn=Ise(He.ask);return{key:Tn.key,fillable:Tn.questionId!==null,onOpen:jc,onFill:(Rs,qr)=>Nse(He,qr,Rs,J?.onFillSecretAnswer??(async()=>({status:"unavailable"}))).then(Ji=>(Ji==="sent"&&jc({focus:!1}),Ji))}},[mi,J?.onFillSecretAnswer,jc]),Hc=Nwe({sessionId:X,composerId:ye,view:mi}),Pl=HA(),nr=!!X,ya=nr?"session":"fleet",Uc=Pse(),vi=Mse(X??null,Uc),Gc=PN(He=>He.tab),xr=PN(He=>He.setTab),_r=nr?d1(mi):Pl.outstanding,rf=nr?vi:0,pd=hr&&_a===ya,Ni=nt(He=>He.setRightSlotRoute),gd=!!X;m.useLayoutEffect(()=>{Ni({mounted:!0,session:gd})},[Ni,gd]),m.useLayoutEffect(()=>()=>Ni(gJ),[Ni]);const Ml=nt(He=>He.setConsolePaneOpen),Vc=nt(He=>He.requestConsoleOpen),$o=Tb(sN,ee),Ol=nt(He=>He.setCodeReviewPaneOpen),Wc=Tb(Db,ee),$c=nt(He=>He.consoleUnseen),Ll=m.useMemo(()=>X===null?[]:$c.filter(He=>He.sessionId===X),[$c,X]),zc=zG(Ll),zo=nt(He=>He.consoleLiveSurface),af=zo!==null&&zo.sessionId===X?zo.count:0,qc=z5(X??null,{visible:!1,sessionLive:!1}).data?.rows??[],qo=q5(qc),Kc=Ose(qc),Yc=e_e(X??null),Bl=m.useRef(null),Xi=m.useRef(null),Wn=m.useRef(null),[Xc,md]=m.useState(jt),[ho,of]=m.useState(jt);m.useLayoutEffect(()=>{if(!wn)return;const He=Bl.current;if(!He)return;const Tn=()=>{const qr=He.getBoundingClientRect().width;if(qr<=0)return;md(ka=>Math.abs(ka-qr)<1?ka:qr);const Ji=Xi.current,Jo=Wn.current;if(!Ji||!Jo)return;const xd=Number.parseFloat(getComputedStyle(Jo).minWidth)||xtt,Jc=Ji.getBoundingClientRect().width-xd;of(ka=>Math.abs(ka-Jc)<1?ka:Jc)};Tn();const Rs=new ResizeObserver(Tn);return Rs.observe(He),Xi.current&&Rs.observe(Xi.current),Wn.current&&Rs.observe(Wn.current),()=>Rs.disconnect()},[wn]);const[Hn,Qc]=m.useState(0);m.useLayoutEffect(()=>{const He=Xi.current;if(!He)return;const Tn=()=>Qc(He.getBoundingClientRect().width);Tn();const Rs=new ResizeObserver(Tn);return Rs.observe(He),()=>Rs.disconnect()},[]);const Nt=_J(Hn||Number.MAX_SAFE_INTEGER)==="docked",lf=De&&Nt||hd&&Nt||wn||pi||Cs||uo,fo=nt(He=>mJ(Hn,He)),Ca=Rb({capacity:ho,min:Db,max:Fb,drawn:Xc}),bi=m.useCallback(He=>{Ca.resizable&&_e(He)},[Ca.resizable,_e]),Ko=m.useCallback(()=>{bi(0)},[bi]),Qi=Hn>0?Math.max(0,Hn-jx):Ws,Sa=Rb({capacity:Qi,min:nN,max:Fb,drawn:Math.min(Ws,Qi)}),jl=m.useCallback(He=>{Sa.resizable&&_e(He)},[Sa.resizable,_e]),vd=m.useCallback(()=>{jl(0)},[jl]),Me=Hn>0?Math.max(0,Hn-jx):$o,mt=Rb({capacity:Me,min:sN,max:Fb,drawn:Math.min($o,Me)}),Zt=m.useCallback(He=>{mt.resizable&&_e(He)},[mt.resizable,_e]),Lt=m.useCallback(()=>{Zt(0)},[Zt]),Un=Hn>0?Math.max(0,Hn-jx):Wc,fr=Rb({capacity:Un,min:Db,max:Fb,drawn:Math.min(Wc,Un)}),Hl=m.useCallback(He=>{fr.resizable&&_e(He)},[fr.resizable,_e]),Yo=m.useCallback(()=>{Hl(0)},[Hl]),Ag=m.useCallback(He=>en(ye,He),[ye,en]),bd=m.useCallback(()=>{nt.getState().setCanvasOpen(!1)},[]),$s=m.useCallback(He=>{gi(!1,"session",He)},[gi]),Xo=m.useCallback(He=>{const Tn=ba.filter(qr=>qr.id!==He),Rs=Ms.filter(qr=>qr.id!==He);Ut(ye,Tn),yn(ye,Rs),fi===He&&en(ye,FD(Ms,He)?.id??null)},[ye,Ms,ba,fi,yn,Ut,en]),Qo=D5(),Ul=(He,Tn)=>Tn;return c.jsxs("div",{ref:Xi,"data-tour-tag":"pane-row",className:"relative flex h-full w-full flex-row overflow-clip",children:[c.jsx("output",{"data-ask-open-announcer":"",className:"sr-only","aria-live":"polite",children:Hc}),c.jsx("div",{ref:Wn,"data-tour-tag":"chat-column",className:"relative h-full w-0 min-w-[480px] flex-1",children:c.jsxs("div",{ref:Ne,"data-glass-region":"canvas",style:lf?{paddingInlineEnd:vJ}:void 0,className:"panel-top-pad flex h-full min-h-0 grow flex-col overflow-hidden rounded-none bg-canvas",children:[c.jsx(Xet,{agentName:n,agentAvatar:En&&un?{agentId:En,agentName:Vs,sha256:un,owned:It}:null,description:s,descriptionPending:r,identity:i,deviceSlot:a,renameSessionId:u,sessionId:X,onOpenOptions:d,reserveTrailingChrome:!sf,onToggleBrowser:()=>xa(!pi),onToggleAsks:()=>{if(pd){gi(!1,ya,{dismissSlot:!0});return}gi(!0,ya),Wo(ya)},asksScope:ya,asksOpen:pd,archiveEnabled:ut,archived:cs,onSetArchived:X?He=>q(He):void 0,deleteEnabled:Ft,onRequestDelete:X?()=>Z(X):void 0,onOpenConsole:X?()=>{Ml(!0),Vc(X)}:()=>Ml(!Cs),onOpenCodeReview:()=>Ol(!nt.getState().isCodeReviewPaneOpen)}),o,c.jsx(utt,{}),c.jsx(W_e,{}),c.jsx(twe,{}),Ft&&c.jsx(ptt,{title:n,hasSubagentRuns:(W?.lineage.length??0)>0}),!J&&c.jsx(att,{open:p,onClose:g,agentId:v}),Qo,Ul("chat",c.jsx(O5,{frontend:J.view.frontend,transcript:J.view.transcript,openFrame:Pe,agentAvatar:b,agentName:x,undelivered:St,gate:dt,waiting:J.turnAlive,starting:J.starting===!0,startingAfterId:J.startingAfterId??null,startingSession:J.startingSession===!0,startingSince:J.startingSince??null,stopping:Sn,onInterruptTurn:L?.onConfirmedStop,idleDisputed:J.idleDisputed===!0,loadingOlder:J.view.loadingOlder,onLoadOlder:J.view.loadOlder,onLoadOlderOutcome:J.view.loadOlderDetailed,olderFailed:J.view.olderFailed,containerRef:E,isSmallView:le,status:J.view.status,failure:J.view.failure,awaitingHydration:J.view.awaitingHydration,hydrationProven:J.view.hydrated,historyReadPending:J.view.historyReadPending,onRetryHydration:J.view.rehydrate,conversationId:ye,labelPending:J.view.labelPending,labelHoldLate:J.view.labelHoldLate,labelMarked:J.view.labelMarked,refusedAttachments:Oe,onReconnect:J.view.retry,onStartNewChat:f,stale:J.view.stale,missing:dn})),J?.view.liveUpdatesPaused&&!J.view.missing&&c.jsx("div",{className:R(p1,f1,"w-full shrink-0 pt-2"),children:c.jsx(swe,{className:h1,paused:J.view.liveUpdatesPaused,reloading:J.view.liveUpdatesReloading,reloadFailed:J.view.liveUpdatesReloadFailed,onReload:J.view.reloadFromHistory})}),dt!==null&&c.jsx("div",{className:R(p1,f1,"w-full shrink-0 pt-2"),children:c.jsx(Cge,{className:h1,gate:dt,sessionId:X,onAnswer:J.onAnswer,onAnswerSecret:J.onAnswerSecret,answering:!!J.admitting,answer:J.answer??null},dt.request_id)}),Te!==null&&!J.turnAlive&&J.stopOutcome!=="unconfirmed"&&c.jsx("div",{className:R(p1,f1,"w-full shrink-0 pt-2"),children:c.jsxs("p",{"data-stopped-turn":!0,className:R("flex items-center gap-2 text-ink-dim text-meta",h1),children:[c.jsx("span",{children:h("ui.chat.action.stopped")}),ae!==null&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",children:"·"}),c.jsx("button",{type:"button","data-stopped-retry":!0,onClick:()=>void A(ae,[]),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:h("ui.common.actions.retry")})]})]})}),(J||!(y&&_.length===0))&&c.jsx(Lse,{ref:Y,onSendMessage:A,onComposerInput:P,initialSuggestions:Bse,noProvider:sn,noModel:Kt,deviceHold:l,deliveryRemediesReachable:St!==null,onCredentialsStored:Le,recordingProbe:et,askExpanded:J?.askExpanded,onAskToggle:J?.onAskToggle,askOutcomes:J?.askOutcomes,isLoading:J?!!(J.admitting||J.starting):w,awaitingReply:!!(J&&jse(Hse({waiting:J.turnAlive,compacting:J.view.transcript.compacting===!0,compactingSince:J.view.transcript.compactingSince,starting:J.starting===!0,startingAfterId:J.startingAfterId??null,startingSession:J.startingSession===!0,startingSince:J.startingSince??null,stopping:Sn,gate:dt,unavailable:Lj(J,dn),records:J.view.transcript.records}))),conversationId:ye,messages:J?J.view.transcript.records.length>0||btt(J,dn)||J.starting?mtt:_.length>0?_:gtt:_,isHydrating:J?J.view.awaitingHydration:!1,awaitingAnswer:dt!==null,secretAnswer:tp(dt),secretAsk:fd,unavailable:tr,currentJobId:J?null:I,onCancelJob:N,canonicalStop:L,asideSessionId:X,asideStreaming:J.turnAlive,asideAdoptQueue:At,canonicalStopAvailable:J?.stopAvailable??!1,interruptNotice:J?.stopNotice??null,isFarFromBottom:S,hasNewActivity:C,scrollToBottom:k,agentData:M,cwd:O,mentionsEnabled:Je,mentionsUnsupported:pe,cwdWritePath:ie,cwdPending:G,cwdPendingAccepted:ne,cwdReadOnlyReason:oe,sendError:B,stopConfirmation:H,sessionStatus:U,onSlashCommand:z,onSlashNote:te,paneHasSession:fe,runDetails:W,isSmallView:le})]})}),De&&c.jsxs(c.Fragment,{children:[Nt&&c.jsx(vf,{sidebarWidth:fo,onSidebarWidthChange:_e,minWidth:Ab,maxWidth:Math.max(Ab,tN(Hn)),side:"left",onDoubleClick:Re,label:"Resize canvas. Double-click resets the shared pane width."}),c.jsx(bf,{ref:Ue,width:fo,tourTag:"canvas-dock","data-canvas-mode":Nt?"docked":"overlay",children:c.jsx(wet,{activeDocumentId:fi,initialDocuments:M1e(Ms),conversationId:ye,agentId:v,sessionId:X,filesSourceReady:!!(!X||J?.view.frontend)&&!J?.view.awaitingHydration,turnTerminal:Q,currentWorkingDirectory:O,fileCount:kt,fileIndex:Ii,attachments:co,scan:Ot,goalCapable:xJ(J?.view.frontend),goalPresent:bJ(J?.view.frontend),goalHistory:J?.view.frontend?.goal_history,goalHistoryTruncated:J?.view.frontend?.goal_history_truncated===!0,onChangeActiveDocument:Ag,onClose:bd,onCloseDocument:Xo})})]}),hd&&c.jsxs(c.Fragment,{children:[Nt&&c.jsx(vf,{sidebarWidth:fo,onSidebarWidthChange:_e,minWidth:Ab,maxWidth:Math.max(Ab,tN(Hn)),side:"left",onDoubleClick:Re,label:"Resize asks. Double-click resets the shared pane width."}),c.jsx(bf,{width:Nt?fo:void 0,className:Nt?void 0:"absolute inset-0",tourTag:"ask-drawer-slot","data-ask-mode":Nt?"docked":"overlay",children:c.jsx(Use,{frontend:wa,scope:"session",tabs:Uc&&X?(()=>{const He=Gc??Gse("session",d1(mi));return{strip:c.jsx($se,{tab:He,asks:d1(mi),unreadUpdates:vi,sessionless:!1,onTab:Tn=>{if(Tn==="all"){xr(null),gi(!0,"fleet");return}xr(Tn)}}),body:He==="updates"?c.jsx(Wse,{sessionId:X}):null,action:c.jsx(Vse,{tab:He})}})():void 0,onClose:He=>{xr(null),$s(He)},onAnswer:J?.onAnswerAsk,onDecline:J?.onDeclineAsk,onRevise:J?.onReviseAsk,onDismiss:J?.onDismissAsk,answering:!!J?.admitting,outcomes:J?.askOutcomes,drafts:J?.askDrafts,onDraftChange:J?.onAskDraftChange})})]}),wn&&c.jsxs(c.Fragment,{children:[c.jsx(vf,{sidebarWidth:Ca.value,onSidebarWidthChange:bi,minWidth:Ca.minWidth,maxWidth:Ca.maxWidth,side:"left",onDoubleClick:Ko,label:"Resize run details. Double-click resets the shared pane width."}),c.jsx(bf,{ref:Bl,width:jt,tourTag:"run-panel-dock",children:W?c.jsx(c0e,{details:W,mcpServers:Ce,mcpGrantRunning:K,mcpRemedy:me,monitorControls:Ee,wakeControls:Ae,jobControls:se,wakeAida:he,sessionId:X??null,pulses:Xe??vtt,childrenOpenable:xe,olderTransportDown:(J?.view.status??"live")!=="live",paneWidth:Xc,readerChildId:ys,onReaderChildChange:Ts,onClose:()=>Ps(!1)}):c.jsx(XO,{label:"Run details",closeLabel:"Close run details",onClose:()=>Ps(!1),labelInk:"dim",labelInset:!0,...p_e({sessionId:X,status:J.view.status,missing:J.view.missing,failure:J.view.failure})})})]}),pi&&c.jsxs(c.Fragment,{children:[c.jsx(vf,{sidebarWidth:Sa.value,onSidebarWidthChange:jl,minWidth:Sa.minWidth,maxWidth:Sa.maxWidth,side:"left",onDoubleClick:vd,label:"Resize browser. Double-click resets the shared pane width."}),c.jsx(bf,{width:Ws,tourTag:"browser-pane-slot",children:c.jsx(Qxe,{sessionId:X??null,onClose:()=>xa(!1)})})]}),Cs&&c.jsxs(c.Fragment,{children:[c.jsx(vf,{sidebarWidth:mt.value,onSidebarWidthChange:Zt,minWidth:mt.minWidth,maxWidth:mt.maxWidth,side:"left",onDoubleClick:Lt,label:"Resize console. Double-click resets the shared pane width."}),c.jsx(bf,{width:$o,tourTag:"console-pane-slot",children:c.jsx(U_e,{sessionId:X??null,onClose:()=>Ml(!1)})})]}),uo&&c.jsxs(c.Fragment,{children:[c.jsx(vf,{sidebarWidth:fr.value,onSidebarWidthChange:Hl,minWidth:fr.minWidth,maxWidth:fr.maxWidth,side:"left",onDoubleClick:Yo,label:"Resize code review. Double-click resets the shared pane width."}),c.jsx(bf,{width:Wc,tourTag:"code-review-pane-slot",children:Vt.notice!==null?c.jsx(XO,{label:"Code review",closeLabel:"Close code review",onClose:()=>Ol(!1),labelInk:"muted",...Vt.notice}):c.jsx(u_e,{sessionId:Vt.sessionId,sessionLive:J?.turnAlive===!0,onClose:()=>Ol(!1)})})]}),c.jsx(zse,{children:c.jsx(J_e,{sessionId:X??null,runDetails:W??null,mcpServers:Ce,listOnScreen:an,readerChildId:ys,browserAttentionCount:Yc,askCount:_r,askUpdates:rf,askScope:ya,consoleUnseenCount:Ll.length,consoleUnseenPulsing:zc,consoleLiveCount:af,fileCount:kt,codeOpened:qo.opened.length,codeMentioned:qo.mentioned.length,codeAttention:Kc})})]})});function Ok(e,t){const n=t?.find(s=>s.destination===e);return n||{name:ytt[e]??e,description:"",aliases:[],arguments:"optional",echo:!0,consumes_prompt:!1,destination:e,execution:"native"}}function Bj(e){return e==="session.fast"?{premium_pricing:!0}:{}}function wtt(e,t,n,s,r){const i=`/${e} needs an open conversation. Start one first.`,a=tre(t);if(!a)return i;if(!n)return r?.status==="pending"?`/${e} is waiting for this conversation's model to resolve. Try again in a moment.`:r?.status==="failed"?`/${e} needs this conversation's model, which was not resolved. Press Retry, then try again.`:i;switch(Gr(s,a)){case"enabled":return`/${e} takes no argument on a new chat. Type /${e} on its own to set it for the first message.`;case"below-version":return`/${e} is not available on this version of the Local Operator service. Update Local Operator, then try again.`;case"unpaired":return`/${e} is not available: this app is not paired with the backend.`;case"unknown":return`/${e} is waiting for the local service to answer. Try again in a moment.`}}const ytt={"session.model":"model","session.effort":"effort",info:"info",usage:"usage",analytics:"analytics","session.diagnostics":"session"};function Ctt(e,t){return{id:nE(),role:"system",message:e,timestamp:new Date,status:t}}function Stt(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 ktt=new Set(["session.goal","session.context"]);function jj(e,t,n){const s=Ua.getState(),r=y5(e,t);return s.inputByConversation[r]?.inFlight!==void 0?!1:(s.returnPayload(r,{text:n,attachments:[],replies:[]}),!0)}function Ett({sessionId:e,addMessage:t,canonical:n,rebind:s,focusComposer:r,draftPicker:i,draftResolution:a,focusCwdChip:o,moveSession:l,moveReady:u,clearAsideRefusal:d,noteAsideRefusal:f}){const p=oi(),g=ss(),v=Et(g.data,"commands"),b=I8(g.data),x=u??!0,_=Et(g.data,"session_archive"),w=Et(g.data,"session_delete"),y=Et(g.data,"aida",1),S=fg(y),C=y2(),E=rG(),k=Dn({queryKey:No.commands,queryFn:()=>rt({op:"commands.list"}).then(ne=>ne.commands),enabled:v,staleTime:3e5}),[F,A]=m.useState(null),I=Au(ne=>ne.claimPresenter);m.useEffect(()=>I(),[I]);const N=m.useRef(null),P=m.useCallback(()=>{A(null);const ne=N.current;N.current=null,ne&&requestAnimationFrame(()=>{ne.isConnected?ne.focus():r?.()})},[r]),M=m.useCallback((ne,oe=!1)=>{if(e&&n.status!=="unavailable"){n.addNote(ne,oe?"error":"info");return}t(Ctt(ne,oe?"error":void 0))},[t,n.addNote,n.status,e]),Y=m.useCallback(ne=>{if(!e){M(`/${ne} needs an open conversation. Start one first.`,!0);return}if(!b){M(gE,!0);return}if(!x){M(mE,!0);return}M("Choose the folder in the working directory chip above, or type /move <path> to move straight there."),o?.()},[b,o,x,M,e]),O=m.useCallback(async ne=>{const{name:oe,args:B}=ne;if(!v)return"not-a-command";const H=k.data??[],U=H.find(W=>W.name===oe)??H.find(W=>W.aliases.includes(oe));if(!U){const W=Stt(oe,H);return M(W.length>0?`Unknown command /${oe}. Did you mean ${W.join(", ")}? Type / for the full list.`:`Unknown command /${oe}. Type / for the full list.`,!0),"consumed"}const z=g1[U.destination];if(z?.kind==="aida"){if(!y)return M(`/${U.name} needs a newer backend. Update the backend and try again.`,!0),"consumed";const W=B.trim(),Ce=Kse(W);if(Ce)return C(Ce).then(me=>{const Ee=Yse(Ce,me);Ee.kind==="success"?Hs(Ee.text):da(Ee.text)}).catch(me=>nn(Lf(me))),"consumed";const K=Xse(W);return E(S.data).then(me=>{if(K){const Ee=S_(null,me,Fe.getState().drafts);Ee&&w5(Ee,{text:K,attachments:[],images:[],mode:"prompt",cwd:""},me).then(Ae=>{Ae===null&&(jj(Ee,me,K),da(h("ui.notices.chat.send_in_flight")))}).catch(Ae=>{if(wJ(Ae)){const se=jj(Ee,me,K);nn(se?Lf(Ae):`${h("ui.notices.chat.send_in_flight")} ${Lf(Ae)}`);return}nn(Lf(Ae))})}dg(p,me)}).catch(me=>nn(Lf(me))),"consumed"}if(z&&z.argsBehavior==="execute"&&B)return e?b?x?(z.runArgs?await z.runArgs({sessionId:e,cwd:B,canonical:n,note:M,moveTo:l}):M(`/${U.name} is not available in the desktop app yet. Run it in the terminal with local-operator.`,!0),"consumed"):(M(mE,!0),"consumed"):(M(gE,!0),"consumed"):(M(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed");if(z?.kind==="direct"){if(z.action==="focus-cwd-chip")return Y(U.name),"consumed";if(z.action==="compact"){if(!e)return M(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed";try{const Ce=(await rt({op:"sessions.command",sessionId:e,requestId:nE(),command:U.name,args:B})).result;if(MN(Ce))return M(`/${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(yJ(Ce.text)){const K=Date.now(),me=n.transcript.viewEpoch;CJ(()=>n.refreshTail(K,me))}else Ce.text&&M(Ce.text,Ce.kind==="error"||Ce.style==="error")}catch(W){M(`/${U.name} could not run: ${W instanceof Error?W.message:"the backend refused it"}`,!0)}return"consumed"}if(z.action==="clear")return n.clearView(),"consumed";if(z.action==="archive"||z.action==="unarchive"){const W=z.action==="archive";if(!e)return M(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed";const Ce=Fe.getState(),K=Ce.sessions.find(se=>se.session_id===e),me=Ce.archiveFacts[e]?.archived??K?.archived;if(!_)return M(SJ,!0),"consumed";if(!kJ(U.destination,me,_))return M(W?EJ:me===void 0?TJ:RJ,!0),"consumed";if(W)return Ce.requestArchiveConfirm({sessionId:e,fromRow:!1,title:K?.title||void 0}),"consumed";const Ee=K?.title??void 0;return await Ce.setSessionArchived(e,!1,Ee),"consumed"}return z.action==="request-delete"?e?w?(Fe.getState().requestSessionDelete(e),"consumed"):(M(dtt,!0),"consumed"):(M(`/${U.name} needs an open conversation. Start one first.`,!0),"consumed"):(window.api?.desktop?.closeWindow?await window.api.desktop.closeWindow():M("Close this window to quit. Conversations keep running in the background."),"consumed")}if(z?.kind==="navigate")return p(z.route(B,e??"")),"consumed";const te=(W,Ce,K)=>{N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,A({action:{kind:"native_action",destination:W.destination,session_id:K,args:Ce,fields:[],data:{}},spec:W,sessionId:K,canonical:n,commands:H,onClose:P,note:M,dispatch:me=>void O(me),rebind:s})},fe=(W,Ce)=>{const K=ON(W.destination,Ce,i,g.data);N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,A({action:{kind:"native_action",destination:W.destination,session_id:"",args:Ce,fields:[],data:Bj(W.destination)},spec:Ok(W.destination,k.data),sessionId:"",canonical:n,commands:H,onClose:P,note:M,dispatch:me=>void O(me),rebind:s,...K?{draft:K}:{}})};if(!e){const W=z?.kind==="picker"?z.draftIdentity:void 0,Ce=W==="team"&&(B==="chart"||B.startsWith("chart ")),K=ON(U.destination,B,i,g.data);if(N8(U.destination)&&!(W&&!Ce)&&!K)return M(wtt(U.name,U.destination,i,g.data,a),!0),"consumed";if(W&&!Ce){const me=B.trim(),Ee=me.split(AJ)[0]??"";if(Ee)return Fe.getState().restageDraft({kind:W,name:Ee},me.slice(Ee.length).trim()),"consumed"}return z?.kind==="picker"?(fe(U,B),"consumed"):(te(U,B,""),"consumed")}if(z?.kind==="machine-panel")return te(U,B,e),"consumed";if(z?.kind==="aside"){if(d?.(),B){const W=vE(Hm.getState(),e);if(W)return f?f(W):M(W,!0),"retained";const Ce=P8(e,B,n.subscriptionId??void 0);M8(Ce,e,K=>M(K,!0))}else Qse(e);return"consumed"}if(!B&&ktt.has(U.destination))return A({action:{kind:"native_action",destination:U.destination,session_id:e,args:"",fields:[],data:{}},spec:U,sessionId:e,canonical:n,commands:H,onClose:P,note:M,dispatch:W=>void O(W),rebind:s}),"consumed";const J=U.name==="credential"?"":B,Se=Jse(U.name,J);if(Se)return M(Se,!0),"retained";U.name==="rename"&&Zse("title-refresh",J)&&M("refreshing the title…");try{const Ce=(await rt({op:"sessions.command",sessionId:e,requestId:nE(),command:U.name,args:J})).result;if(MN(Ce)){const K=Ce,me=g1[K.destination];return me?.kind==="navigate"?(p(me.route(K.args,e)),"consumed"):me?.kind==="direct"&&me.action==="focus-cwd-chip"?(Y(U.name),"consumed"):me?(N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,A({action:K,spec:U,sessionId:e,canonical:n,commands:H,onClose:P,note:M,dispatch:Ee=>void O(Ee),rebind:s}),"consumed"):(M(`/${U.name} is not available in the desktop app yet. Run it in the terminal with local-operator.`,!0),"consumed")}if(Ce.text)M(Ce.text,Ce.kind==="error"||Ce.style==="error");else if(Ce.kind==="block"){const K=Ce.data;Array.isArray(K.items)&&M([K.title,...K.items.map(([me,Ee])=>`${me}: ${Ee}`)].filter(Boolean).join(`
686
686
  `))}return"consumed"}catch(W){return M(`/${U.name} could not run: ${W instanceof Error?W.message:"the backend refused it"}`,!0),"retained"}},[v,_,w,y,S.data,C,E,k.data,e,M,p,n,s,P,b,x,l,Y,d,f,i,g.data,a]),X=m.useCallback(async ne=>{const oe=await O(ne);return oe==="not-a-command"&&M("The backend could not complete this request. Check its connection and try again.",!0),oe},[O,M]),Q=m.useCallback(ne=>{i&&(N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,A({action:{kind:"native_action",destination:ne,session_id:"",args:"",fields:[],data:Bj(ne)},spec:Ok(ne,k.data),sessionId:"",canonical:n,commands:k.data??[],onClose:P,note:M,dispatch:oe=>void O(oe),rebind:s,draft:i}))},[n,P,k.data,O,i,M,s]),ie=Au(ne=>ne.request),G=Au(ne=>ne.consumePanel);return m.useEffect(()=>{if(!ie||(G(ie.nonce),Date.now()-ie.requestedAt>ere))return;const ne=g1[ie.destination];if(ne?.kind!=="picker"&&ne?.kind!=="machine-panel")return;N.current=ie.sessionId?ie.invoker:null;const oe=ie.sessionId??e??"";A({action:{kind:"native_action",destination:ie.destination,session_id:oe,args:"",fields:[],data:{...ie.entryId?{entryId:ie.entryId}:{},...ie.entryId&&ie.entryExcerpt?{entryExcerpt:ie.entryExcerpt}:{},...ie.subjectName?{subjectName:ie.subjectName}:{}}},spec:Ok(ie.destination,k.data),sessionId:oe,canonical:n,commands:k.data??[],onClose:P,note:M,dispatch:B=>void O(B),rebind:s})},[ie,G,e,n,k.data,P,M,O,s]),{dispatch:O,dispatchFromControl:X,picker:F,closePicker:P,openDraftPicker:Q,note:M}}const Ttt=/^[a-f0-9]{12}$/,Lk=e=>`${e.request_id}:${e.question_index}`,Rtt=" ";function Bk(e,t){const n=e.activeDraftKey?e.drafts[e.activeDraftKey]:void 0;return!!t&&Bv(e.activeDraftKey,n?.sessionId,e.activeSessionId)===t}function Att({identity:e,draftKey:t,sessionId:n,onStartNewChat:s}){const r=Fe(Me=>S_(t,n,Me.drafts)),i=Fe(Me=>r?Me.drafts[r]:void 0),a=n??i?.warmId,o=ss(),l=IJ(a,!!a,!!n,e,{openFrame:Et(o.data,"open_frame"),journalOrder:Et(o.data,"journal_order"),peerJournalSource:Et(o.data,"peer_journal_source")});A0e(a,l.subscriptionId);const u=HA(),d=m.useMemo(()=>ibe(n,l.frontend,{rows:u.rows,capability:u.capability}),[n,l.frontend,u.rows,u.capability]),f=D0e(n,o.data),p=Et(o.data,"settings");N0e(n,p),m.useEffect(()=>{Fe.getState().setDraftWarmable(Et(o.data,"session_draft_warm")),Fe.getState().setDraftFastCarries(Et(o.data,"draft_fast"))},[o.data]),I0e(i?.warmId,l.subscriptionId,o.data);const g=m.useCallback(()=>{if(n){f();return}t&&Fe.getState().ensureDraftWarm(t)},[n,f,t]),v=m.useRef(null),b=m.useRef(null),x=Fe(Me=>Me.cwd),{data:_}=og(),w=A2(_?.online===!1),y=_?.online===!0,S=m.useRef(y);m.useEffect(()=>{const Me=y&&!S.current;S.current=y,Me&&l.status==="unavailable"&&l.retry()},[y,l]);const C=Fe(Me=>Me.setCwd),E=Fe(Me=>Me.markTurnStopped),k=Fe(Me=>Me.clearTurnStopped),[F,A]=m.useState(!1),I=m.useRef(null);I.current??=nre();const N=I.current,P=m.useRef(!1),M=m.useRef(l);M.current=l;const Y=m.useRef([]),O=m.useRef(!1),[X,Q]=m.useState(null),[ie,G]=m.useState({}),ne=nt(Me=>Me.isAskDrawerOpen),oe=nt(Me=>Me.askDrawerScope),B=ne&&oe==="session",H=nt(Me=>Me.setAskDrawerOpen),[U,z]=m.useState({}),te=l.frontend?.pending_gate??null,fe=te?Lk(te):null,J=m.useRef(null),Se=m.useRef(null);m.useLayoutEffect(()=>{J.current=fe,Se.current=l.ownerEpoch});const W=te&&X?.key===fe?{sending:X.sending,refused:X.refused,retryable:X.retryable,muted:X.muted}:null,Ce=m.useRef(""),[K,me]=m.useState(null),[Ee,Ae]=m.useState(),[se,he]=m.useState(!1),[xe,Je]=m.useState(!1),[pe,Xe]=m.useState(null),[le,Qe]=m.useState(null),et=m.useRef(le);et.current=le;const ue=m.useRef(0),Le=m.useRef(null),Ne=ebe(o.data),[Ue,dt]=m.useState(!1),[St,Dt]=m.useState("chat"),{isFarFromBottom:sn,scrollToBottom:Kt}=qU(50,b,l.transcript.records.length),ut=(l.frontend??l.heldFrontend)?.streaming===!0,Ft=m.useRef(ut);Ft.current=ut;const At=NJ(e),cn=m.useRef(null),rn=m.useRef(null);At&&(rn.current?.requestId!==At.id&&(rn.current={requestId:At.id,anchor:l.frontend?.attention?.anchor_id??null}),cn.current?.requestId!==At.id&&(cn.current={requestId:At.id,submittedAt:At.submittedAt??i?.submittedAt}));const kn=sre(l.transcript.records,cn.current?.requestId),ws=rre(l.transcript.records,cn.current?.requestId)||ire(l.frontend?.attention,rn.current?.anchor??null);cn.current&&(kn||ws||i?.error||i?.undelivered!==void 0&&i.undelivered.recordId===cn.current.requestId)&&(cn.current=null);const Vt=cn.current!==null,cs=Vt&&!(i?.sessionId??n),Vn=l.frontend??l.heldFrontend,zr=m.useMemo(()=>n&&Vn?are({jobs:Vn.jobs,todos:Vn.todos,wakes:Vn.wakes,monitors:Vn.monitors}):null,[n,Vn]),{servers:ls,grantRunning:En}=m0e({sessionId:n,accelerator:l.frontend?JSON.stringify(l.frontend.mcp_servers??null):null,errors:ore(l.frontend?.mcp_servers)}),Vs=lre({sessionId:n}),un=w0e({sessionId:n}),It=ss(),dn=T0e({sessionId:n}),tr=C0e({sessionId:n}),Sn=Et(It.data,"aida",1),Ie=fg(Sn),ge=gpe(),Pe={capability:Sn,statusResolved:Ie.isSuccess,sessionId:Ie.data?.session_id??null,name:ge},L=Et(It.data,"subagent_transcript"),V=Et(It.data,"references")&&!ut,j=Et(It.data,"input_mode"),q=It.isSuccess&&!!It.data?.desktop_available&&!Et(It.data,"references"),Z=!!n&&!t&&I8(It.data),ee=cre({sessionId:n,canonical:l,capabilities:It.data}),_e=m.useMemo(()=>t&&!i?.sessionId&&!F?{kind:"stage",commit:C}:Z?{kind:"move",commit:ee.moveTo}:void 0,[t,i?.sessionId,F,Z,C,ee.moveTo]),Re=t&&(i?.sessionId||F)?mE:Z?void 0:gE,ye=oi(),Te=Me=>{dg(ye,Me)},ae=Dn({queryKey:["desktop","entities",n,"effort",""],queryFn:()=>rt({op:"commands.entities",sessionId:n,command:"effort"}),enabled:!!n,staleTime:15e3}),we=Mt(),De=PJ(l.frontend,l.heldFrontend),$e=m.useRef(void 0);m.useEffect(()=>{const Me=$e.current;$e.current={session:n??null,model:De},!(!n||!De||!(Me?.session===n)||Me?.model===De)&&we.invalidateQueries({queryKey:["desktop","entities",n,"effort",""]})},[n,De,we]);const ke=m.useRef(null),[tt,ht]=m.useState(null);m.useEffect(()=>{if(!n){ht(null);return}if(l.frontend||l.heldFrontend){ke.current=n,ht(null);return}ht(ke.current===n&&l.status==="unavailable"&&!l.missing?n:null)},[n,l.frontend,l.heldFrontend,l.status,l.missing]);const Ot={cwd:x,...i?.target?{target:i.target}:{},model:i?.model??null},Ut=!n&&x.length>0&&Et(It.data,"draft_preview"),en=Et(It.data,"draft_fast"),yn=Dn({...MJ(Ot,en),enabled:Ut}),wn=Ut?yn.data?void 0:yn.isError?{status:"failed",retry:()=>void yn.refetch()}:{status:"pending"}:void 0,Ps=!n&&i?.model?.fast_mode===!0&&Gr(It.data,"draft_fast")==="below-version";m.useEffect(()=>{Ps&&(me(OJ),Ae(LJ),he(!1),Je(!0))},[Ps]);const ys=!n&&Et(It.data,"draft_selection")&&Et(It.data,"commands")&&Et(It.data,"catalogues"),Ts=m.useCallback(()=>{me(null),Ae(void 0)},[]),an=Hm(Me=>n?vE(Me,n)!==null:!1),ba=m.useCallback(Me=>{me(Me),Ae(rN)},[]);m.useEffect(()=>{Ee===rN&&(an||Ts())},[an,Ts,Ee]);const fi=m.useCallback(Me=>l.addNote(Me.message??""),[l.addNote]),{dispatch:Ms,dispatchFromControl:Ii,picker:co,openDraftPicker:Yi,note:Nl}=Ett({sessionId:n,canonical:l,rebind:Te,addMessage:fi,focusComposer:()=>v.current?.focusInput(),focusCwdChip:()=>v.current?.openWorkingDirectoryMenu(),moveSession:ee.moveTo,moveReady:!t,clearAsideRefusal:Ts,noteAsideRefusal:ba,draftPicker:ys&&r&&yn.data?{target:Ot,select:Me=>Fe.getState().setDraftModel(r,Me)}:void 0,draftResolution:wn}),Oe=MM(Ii),kt=!!n;m.useEffect(()=>{t&&v.current?.focusInput()},[t]),m.useEffect(()=>{if(!n||!l.frontend)return;const Me=Fe.getState();Me.sessions.some(mt=>mt.session_id===n)&&Me.upsertSession({session_id:n,...L0e({liveTitle:l.frontend.conversation_title}),attention:l.frontend.attention})},[n,l.frontend]),m.useEffect(()=>{const Me=JSON.stringify([n,l.frontend?.streaming,l.frontend?.attention?.unseen,l.frontend?.active_agent,l.frontend?.active_team]);!n||Me===Ce.current||(Ce.current=Me,Fe.getState().fetchSessions())},[n,l.frontend?.streaming,l.frontend?.attention?.unseen,l.frontend?.active_agent,l.frontend?.active_team]);const jt=Me=>YJ(Me,void 0,!1),pi=(Me,mt)=>{const Zt=Fe.getState().drafts[Me],Lt=j0e({rowError:Zt?.error,rowCode:Zt?.errorCode,rowRetry:Zt?.errorRetry,fallback:()=>jt(mt)});me(Lt?.message??null),Ae(Lt?.code),he(Lt?.retry===!0),Je(Lt?.muted===!0)},xa=async(Me,mt,Zt,Lt,Un,fr)=>{const Hl=Fe.getState(),Yo=S_(t,n,Hl.drafts);if(!Yo)return!1;const Ag=Hl.drafts[Yo],bd=()=>(me(P.current?jm.queuedSend:KJ(l.frontend?.pending_gate)),Ae(void 0),he(!1),Je(!0),!1);if(Ag?.pending||!N.tryAcquire())return bd();A(!0),me(null),Ae(void 0),he(!1),Je(!1);try{if(!t&&!n)return!1;const $s=A8(l.frontend);if($s&&l.ownerEpoch&&n){if(tp($s))throw new Jk(yre,aN);if($s.kind==="approval"){const wr=Cre(Lt??Me);if(wr===null)throw new Jk(h("ui.chat.approval.reply_required"),aN);await rt({op:"sessions.answer",sessionId:n,epoch:l.ownerEpoch,requestId:$s.request_id,approved:wr})}else await rt({op:"sessions.answer",sessionId:n,epoch:l.ownerEpoch,requestId:$s.request_id,value:Sre($s,Lt,Me),questionIndex:$s.question_index});return!0}const Xo=hA(Fe.getState().sessions,Fe.getState().placementFacts,n??i?.sessionId??""),{images:Qo,files:Ul,failures:He,overflow:Tn,fileOverflow:Rs}=await kre(mt,Me,{remoteOwned:Xo}),qr=Ere(He);if(qr)return me(qr),Ae(WJ),he(!1),Je(!1),!1;const Ji=Tre(Tn);if(Ji)return me(Ji),Ae(void 0),he(!1),Je(!1),!1;const Jo=Rre(Rs);if(Jo)return me(Jo),Ae(void 0),he(!1),Je(!1),!1;const xd=Are(Me,Qo);if(xd)return me(xd),Ae(void 0),he(!1),Je(!1),!1;const Jc=n?Hm.getState().attached[n]:void 0;if(n&&Jc){if(mt.length>0)return me("An aside answers text only. Remove the attached files to ask it."),!1;const wr=vE(Hm.getState(),n);if(wr)return ba(wr),!1;me(null),Ae(void 0);const Fg=P8(n,Me,l.subscriptionId??void 0);return M8(Fg,n,HC=>{me(HC),Ae($J)}),{offRecord:Fg}}if(n&&!Bk(Fe.getState(),n))return!1;if(n&&e1(Fe.getState().validatingSessionId,n)){P.current=!0,me(jm.queuedSend),Ae(void 0),he(!1),Je(!0);let wr;try{wr=await Xi()}finally{P.current=!1}if(wr!=="ready")return wr==="failed"&&(me(M.current.failure?.statement??zJ()),Ae(iN),Je(!1)),!1}const ka=await w5(Yo,{text:Me,attachments:mt,images:Qo,...Ul.length?{files:Ul}:{},mode:ut?"steer":"prompt",cwd:x,inputMode:j?fr:void 0},n,Zt,Un);if(!ka)return!1;const cf=mt.filter(wr=>!wr.startsWith("data:")).map(wr=>So(wr));if(cf.length>0){const wr=Fs.getState();wr.addMentionedFilesBatch(e,cf),wr.addMentionedFilesBatch(ka,cf)}return t&&Fe.getState().activeSessionId===ka&&ye(`/chat/${ka}`,{replace:!0}),Hl.fetchSessions(),!0}catch($s){const Xo=Fe.getState().drafts[Yo];return qJ(gA(t,Xo?.sessionId??n),Xo?.admissionRequestId??"")?(me(null),Ae(void 0),he(!1),Je(!1)):pi(Yo,$s),!1}finally{N.release(),A(!1)}},Ws=MM(xa),Cs=(Me,mt,Zt)=>{const Lt=Fre(Me,{liveGateKey:J.current,pressedGateKey:mt,sentEpoch:l.ownerEpoch,liveEpoch:Se.current,cardOnScreen:document.querySelector('[aria-label="Answer options"], [data-ask-secret]')!==null});switch(Lt.to){case"refused":Q(null);return;case"sent":Q({key:mt,sending:!1,refused:null,retryable:!1,muted:!1}),Zt?.();return;case"card":Q({key:mt,sending:!1,refused:Lt.refused,retryable:Lt.retryable,muted:Lt.muted});return;case"composer":Q(null),me(Lt.message),Ae(Lt.code),Je(Lt.muted),he(Lt.retry);return}},uo=async Me=>{const mt=l.frontend?.pending_gate;if(!mt||!l.ownerEpoch||!n||N.held)return;const Zt=Lk(mt);document.activeElement instanceof HTMLElement&&document.activeElement.closest('[aria-label="Answer options"]')!==null&&(O.current=!0,v.current?.focusInput()),A(!0),Q({key:Zt,sending:!0,refused:null,retryable:!1,muted:!1}),me(null),Ae(void 0);let Un;try{Un=await xre({gate:mt,sessionId:n,epoch:l.ownerEpoch,label:Me,lock:N},fr=>rt(fr))}finally{A(!1)}Cs(Un,Zt,()=>{mt.kind==="approval"&&v.current?.consumeApprovalAnswerDraft()})},hr=async Me=>{const mt=l.frontend?.pending_gate;if(!mt||!l.ownerEpoch||!n||N.held)return;const Zt=Lk(mt);document.activeElement instanceof HTMLElement&&document.activeElement.closest("[data-ask-secret]")!==null&&(O.current=!0,v.current?.focusInput()),A(!0),Q({key:Zt,sending:!0,refused:null,retryable:!1,muted:!1}),me(null),Ae(void 0);let Un;try{Un=await bre({gate:mt,sessionId:n,epoch:l.ownerEpoch,value:Me,lock:N},fr=>rt(fr))}finally{A(!1)}Cs(Un,Zt)},_a=(Me,mt,Zt=!1)=>{if(mt.status==="failed"){G(Lt=>({...Lt,[Me]:{sending:!1,refused:wre(mt.error),refusedByOwner:_re(mt.error)}}));return}G(Lt=>({...Lt,[Me]:{sending:!1,refused:null,...Zt?{changed:!0}:{}}})),we.invalidateQueries({queryKey:LN})},hd=async(Me,mt)=>{if(!n)return{status:"unavailable"};if(N.held)return{status:"locked"};A(!0),G(Lt=>({...Lt,[Me]:{sending:!0,refused:null}}));let Zt;try{Zt=await pre({taskId:Me,answers:mt,sessionId:n,lock:N},Lt=>rt(Lt))}finally{A(!1)}return _a(Me,Zt),Zt},gi=async(Me,mt)=>{if(!n||N.held)return;A(!0),G(Lt=>({...Lt,[Me]:{sending:!0,refused:null}}));let Zt;try{Zt=await mre({taskId:Me,answers:mt,sessionId:n,lock:N},Lt=>rt(Lt))}finally{A(!1)}_a(Me,Zt,Zt.status==="sent"),Zt.status==="sent"&&Hs(h("ui.notices.chat.answer_changed"))},Wo=async Me=>{if(!n||N.held)return;A(!0),G(Zt=>({...Zt,[Me]:{sending:!0,refused:null}}));let mt;try{mt=await vre({taskId:Me,sessionId:n,lock:N},Zt=>rt(Zt))}finally{A(!1)}_a(Me,mt)},sf=async(Me,mt)=>{if(!n||N.held)return;A(!0),G(Lt=>({...Lt,[Me]:{sending:!0,refused:null}}));let Zt;try{Zt=await gre({taskId:Me,reason:mt,sessionId:n,lock:N},Lt=>rt(Lt))}finally{A(!1)}if(Zt.status!=="sent"){_a(Me,Zt);return}G(Lt=>({...Lt,[Me]:{sending:!1,refused:null,dismissed:mt}})),we.invalidateQueries({queryKey:LN})},wa=m.useCallback((Me,mt)=>{Me!==B&&H(Me,"session",mt)},[B,H]);m.useLayoutEffect(()=>{if(!O.current||(O.current=!1,document.activeElement!==document.body&&!ure()))return;const Me=document.querySelector('[aria-label="Answer options"] button:not([disabled]), [data-ask-secret] input:not([disabled])');Me?Me.focus():v.current?.focusInput()},[fe]);const mi=m.useCallback(()=>{const Me=Le.current;Me!==null&&(Le.current=null,me(mt=>mt===Me?null:mt))},[]),jc=m.useCallback(()=>{if(!n||!Ne)return;const Me=et.current;if(Me==="pending"||Me==="awaiting-end")return;const mt=++ue.current;Xe(null),Qe("pending");const Zt=Date.now();E(n,Zt),tbe(n,crypto.randomUUID()).then(Lt=>{if(mt!==ue.current)return;Lt.status!=="interrupted"&&k(n);const Un=Ft.current,fr=sbe(Lt,{turnClaimed:Un});Xe(fr===null?null:{text:fr,kind:Lt.status!=="idle"?"outcome":Un?"idle-disputed":"idle"}),Qe(Lt.status==="interrupted"&&Ft.current?"awaiting-end":null),mi(),Lt.status==="idle"&&Un&&l.retry()}).catch(Lt=>{if(mt!==ue.current)return;if(!Ft.current){Qe(null);return}Qe("unconfirmed");const Un=zi(Lt,"Stop could not be confirmed. The turn may still be running.");Le.current=Un,me(Un),Ae(void 0),he(!1),Je(!1)})},[n,Ne,E,k,mi,l.retry]),fd=l.transcript.records.some(Me=>Me.kind==="tool"&&Me.phase==="running"&&!Me.stopped&&(Me.toolName==="generate_voiceover"||Me.toolName==="generate_sound_effect")),Hc=m.useCallback(()=>v.current?.focusInput(),[]),{paneRef:Pl,stop:nr,confirmation:ya}=dre({sessionId:n,runningSound:fd,available:Ne,onInterrupt:jc,onRestoreFocus:Hc}),Uc=m.useRef(null);m.useEffect(()=>{const Me=Uc.current;Uc.current=ut,!Me&&ut?(ue.current+=1,Xe(null),Qe(null),mi(),n&&k(n)):Me&&!ut&&(Xe(mt=>mt?.kind==="idle"||mt?.kind==="idle-disputed"?null:mt),Qe(mt=>mt==="awaiting-end"||mt==="unconfirmed"?null:mt),mi())},[ut,n,k,mi]),m.useEffect(()=>{ue.current+=1,Qe(null)},[n]),m.useEffect(()=>{if(!B)return;const Me=mt=>{fre(mt)&&(mt.preventDefault(),wa(!1))};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[B,wa]);const vi=D8({status:l.status,failure:l.failure,missing:l.missing,stale:l.stale});Qve({sessionId:n,turnAlive:ut,available:Ne&&!vi,recording:Dre,onInterrupt:nr});const Gc=i?.target?.kind==="team"?i.target.name:null,xr=l.frontend?.active_team||null,_r=By(!!(Gc||xr)&&Et(It.data,"team_catalogue")),rf=m.useMemo(()=>{const Me=new Map((_r.data??[]).map(mt=>[mt.name,Dp(mt)]));return mt=>Me.get(mt)??mt},[_r.data]),pd=(xr?rf(xr):"")||l.frontend?.active_agent||(i?.target?i.target.kind==="team"?rf(i.target.name):i.target.name:void 0),Ni=Fe(Me=>n?Me.sessions.find(mt=>mt.session_id===n):void 0),gd=Fe(Me=>n?Me.forgotten[n]?.title:void 0),Ml=[l.frontend?.active_agent,l.frontend?.active_team].filter(Boolean).join(" · ")||[Ni?.binding?.agent,Ni?.binding?.team].filter(Boolean).join(" · "),Vc=l.frontend?.active_agent||Ni?.binding?.agent||(i?.target?.kind==="agent"?i.target.name:"")||null,Ol=w8(!!Vc&&Et(o.data,"profile_catalogue")).data?.find(Me=>Me.name===Vc)?.agent_id??null,Wc=Ly(Ol),$c=O0e({draftKey:t,draftSessionId:i?.sessionId,draftTarget:pd,liveTitle:l.frontend?.conversation_title,catalogueTitle:Ni?.title??gd}),Ll=n?l:{...l,status:"live",error:null},zc=!Ml&&!t&&Ll.status==="connecting",zo=n&&Get({hasSession:!!n,pending:zc,teamCatalogue:Et(It.data,"team_catalogue"),identityKnown:!!Ml,streamLive:Ll.status==="live"})?{sessionId:n,activeAgent:l.frontend?.active_agent??null,activeTeam:l.frontend?.active_team??null,boundAgent:Ni?.binding?.agent??null,boundTeam:Ni?.binding?.team??null,effectiveIdentity:l.frontend?.effective_identity??null,hostKey:Oet(Ni),frameEpoch:l.frontend?.epoch??null}:void 0,af=l.frontend?.active_team||l.frontend?.active_agent,qc=(Ee??i?.errorCode)==="unresolved_attachment"&&!!af;m.useEffect(()=>{qc&&(me(null),Ae(void 0),r&&Fe.getState().updateDraft(r,{error:void 0,errorCode:void 0}))},[qc,r]);const qo=Fe(Me=>e1(Me.validatingSessionId,n)),Kc=Fe(Me=>Bk(Me,n));m.useEffect(()=>{if(!n||!qo)return;const Me=Fe.getState();l.status==="live"?Me.confirmSessionLive(n):l.missing&&Me.confirmSessionMissing(n)},[n,qo,l.status,l.missing]);const Yc=Me=>{const mt=Y.current.splice(0);for(const Zt of mt)Zt(Me)},Bl=()=>{if(M.current.missing)return"gone";if(!Bk(Fe.getState(),n))return"abandoned";const Me=M.current.status;return Me==="unavailable"?"failed":e1(Fe.getState().validatingSessionId,n)?null:Me==="live"?"ready":null},Xi=()=>{const Me=Bl();return Me?Promise.resolve(Me):new Promise(mt=>{Y.current.push(mt)})};m.useEffect(()=>{if(Y.current.length===0)return;const Me=Bl();Me&&Yc(Me)},[qo,Kc,l.status,l.missing]),m.useEffect(()=>{const Me=Y.current;return()=>{for(const mt of Me.splice(0))mt("abandoned")}},[]),m.useEffect(()=>{qo||Ee!==iN||(me(null),Ae(void 0))},[qo,Ee]),m.useEffect(()=>{r&&(BJ(r,i),jJ(r,i))},[r,i]);const Wn=i?.admissionAttempted&&!i.pending?i.admissionRequestId:void 0,Xc=Fe(()=>Wn?l.transcript.index.get(Wn):void 0),md=Fe(()=>{if(!Wn)return!1;const Me=l.transcript.records[Xc??-1];return Me?.kind==="user"&&!Me.local});m.useEffect(()=>{!Wn||!md||!r||(Ua.getState().reconcileDelivered(e),me(null),Ae(void 0),he(!1),Je(!1),Fe.getState().finishDraft(r,i?.sessionId??n??""))},[Wn,md,r,i?.sessionId,n,e]);const ho=Ua(Me=>Me.inputByConversation[e]?.lateDelivered),of=Ua(Me=>Me.inputByConversation[e]?.currentInput??""),Hn=i?i.submittedText!==void 0&&(i.error!==void 0||Wn!==void 0)?{recordId:Wn??i.admissionRequestId,text:i.submittedText,attachments:i.submittedAttachments??[],message:i.error,retry:i.errorRetry??nw(i.errorCode)}:i.undelivered??null:null,Qc=Hn?HJ(Hn.text):null,Nt=Hn?Qc?.text??Hn.text:null,lf=Hn?{recordId:Hn.recordId,message:Hn.message,retry:Hn.retry,retryDisabled:of.trim().length>0&&of===Nt,onSendAgain:()=>{xa(Hn.text,[...Hn.attachments])},onEdit:()=>{Ua.getState().returnPayload(e,{text:Nt??Hn.text,attachments:[...Hn.attachments],replies:Qc?.replies??[]}),i?.admissionAttempted!==!0&&(VJ(e,Hn.recordId),r&&Fe.getState().updateDraft(r,{error:void 0,errorCode:void 0,errorRetry:void 0,undelivered:void 0})),v.current?.focusInput()}}:null,fo=i?.admissionAttempted===!0&&i.pending!==!0,Ca=m.useRef(fo);m.useEffect(()=>{Ca.current&&!fo&&(me(null),Ae(void 0),he(!1),Je(!1)),Ca.current=fo},[fo]),m.useEffect(()=>{H0e({rowPending:i?.pending===!0,admitting:F,gatePending:l.frontend?.pending_gate!=null,muted:xe,code:Ee})&&(me(null),Ae(void 0),he(!1),Je(!1))},[i?.pending,F,l.frontend?.pending_gate,xe,Ee]);const bi=UJ(e),Ko=m.useMemo(()=>B0e({error:K,code:Ee,retry:se,muted:xe,rowError:bi?void 0:i?.error,rowCode:bi?void 0:i?.errorCode,rowRetry:bi?void 0:i?.errorRetry,lateDelivered:ho}),[K,Ee,se,xe,bi,i?.error,i?.errorCode,i?.errorRetry,ho]),Qi=m.useMemo(()=>Ko&&!(w&&Ko.code===Ov.transportFailed)?{...Ko,actions:void 0,onRetry:()=>{v.current?.submitNow(),v.current?.focusInput()},onClear:()=>{e&&Ua.getState().clearComposer(e),Ts(),r&&Fe.getState().discardDraft(r),v.current?.focusInput()},onDismiss:()=>{Ts(),r&&i&&Fe.getState().updateDraft(r,{error:void 0,errorCode:void 0})}}:void 0,[Ko,w,e,r,i,Ts]),Sa=Fe(Me=>GJ(Me.sessions,n)),jl=m.useMemo(()=>n?{frontend:l.frontend??l.heldFrontend,servingLocality:Sa,asks:d,held:l.frontend===null&&l.heldFrontend!==null,contextHeld:l.contextCarried,readingsDropped:tt===n,pendingModel:l.pendingModel,onCommand:Me=>void Oe(Me),effortEntities:ae.data?.entities,costChannels:Et(It.data,"cost_channels")}:void 0,[n,l.frontend,l.heldFrontend,l.contextCarried,Sa,tt,l.pendingModel,Oe,ae.data,It.data,d]),vd=m.useMemo(()=>c.jsx(ave,{sessionId:n??void 0}),[n]);return c.jsxs("div",{ref:Pl,"data-chat-pane":"",className:"flex h-full min-h-0 flex-col",children:[Ue&&c.jsx("div",{className:R("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(Me=>c.jsx("button",{type:"button",className:R("rounded-md px-2 py-1 hover:bg-elevated"),onClick:()=>{dt(!1),Ms({name:Me,args:""})},children:Me==="agent"?"Choose agent":Me==="team"?"Choose team":Me.charAt(0).toUpperCase()+Me.slice(1)},Me))}),c.jsx("div",{className:R("min-h-0 flex-1"),children:c.jsx(_tt,{activeTab:St,onTabChange:Dt,onStartNewChat:s,deviceSlot:c.jsx(qve,{sessionId:n??void 0,draftKey:t??void 0}),deviceNotice:c.jsx(Ove,{sessionId:n??void 0}),deviceHold:vd,agentName:$c,description:Ml||(t?Vt?pd??"Starting the session":i?.sessionId?l.frontend?.cwd||x||"Canonical chat":l.frontend?.cwd||x||"":ee.cwd||Rtt),descriptionPending:zc,identity:zo,renameSessionId:n&&Et(It.data,"commands")?n:void 0,onOpenOptions:()=>dt(Me=>!Me),isOptionsSidebarOpen:!1,onCloseOptions:()=>dt(!1),agentId:e,agentAvatar:Wc,agentSpeakerName:Vc,turnTerminal:l.turnsCompleted,cwd:t?x:ee.cwd,cwdWritePath:_e,cwdReadOnlyReason:Re,sessionId:n,cwdPending:Z&&ee.busy,cwdPendingAccepted:Z&&ee.accepted,messages:[],isLoading:!1,isLoadingMessages:!1,isFarFromBottom:sn,messagesContainerRef:b,scrollToBottom:Kt,rawInfoContent:JSON.stringify(l.frontend,null,2),onSendMessage:Ws,onSlashCommand:Oe,onSlashNote:Nl,paneHasSession:kt,sendError:Qi,soundStopConfirmation:ya,undelivered:lf,sessionStatus:n?jl:yn.data?{frontend:yn.data.snapshot,draft:!0,draftResolved:!0,onOpenDraftPicker:ys?Yi:void 0,costChannels:Et(It.data,"cost_channels")}:wn?{frontend:null,draft:!0,draftResolved:!1,draftResolution:wn,costChannels:Et(It.data,"cost_channels")}:void 0,currentJobId:null,onCancelJob:nr,messageInputRef:v,runDetails:zr,onComposerInput:g,mcpServers:ls,mcpGrantRunning:En,mcpRemedy:Vs,monitorControls:un,wakeControls:dn,jobControls:tr,wakeAida:Pe,childrenOpenable:L,mentionsEnabled:V,mentionsUnsupported:q,pulses:l.subagentPulses,canonical:{view:Ll,asks:d,turnAlive:ut,stopOutcome:le,idleDisputed:pe?.kind==="idle-disputed",admitting:F,starting:Vt,startingAfterId:cn.current?.requestId??null,startingSession:cs,startingSince:i?.submittedAt??At?.submittedAt??cn.current?.submittedAt??null,onStop:nr,onConfirmedStop:jc,stopAvailable:Ne,stopNotice:pe?.text??rbe(ut,Ne),onAnswer:Me=>void uo(Me),onAnswerSecret:Me=>void hr(Me),answer:W,onAnswerAsk:(Me,mt)=>void hd(Me,mt),onFillSecretAnswer:hd,onDeclineAsk:Me=>void Wo(Me),onReviseAsk:(Me,mt)=>void gi(Me,mt),onDismissAsk:Et(It.data,"ask_dismiss")?(Me,mt)=>void sf(Me,mt):void 0,askOutcomes:ie,askExpanded:B,onAskToggle:wa,askDrafts:U,onAskDraftChange:(Me,mt)=>z(Zt=>({...Zt,[Me]:mt}))}})}),c.jsx(hre,{context:co})]})}function Hj(){Ve();const{agentId:e}=a5(),t=oi(),n=ss(),s=Gr(n.data,"session_catalogue",2),r=s==="enabled",{data:i}=og(),a=A2(i?.online===!1),o=i?.snapshot&&!i.snapshot.pairing.available?i.snapshot.pairing.cause??"unpaired":null,l=FJ(s,o),u=dA(n.data,o),d=DJ(o),f=m.useCallback(async()=>{s==="unpaired"&&await window.api?.backend?.reconnect?.(),await n.refetch()},[s,n]),p=Fe(A=>A.activeSessionId),g=Fe(A=>A.activeDraftKey),v=Fe(A=>S_(g,A.activeSessionId,A.drafts)),b=Fe(A=>v?A.drafts[v]:void 0),x=Fe(A=>A.error),[_,w]=m.useState(null);m.useEffect(()=>{if(!r||!e)return;const A=Fe.getState();if(!Ttt.test(e)){w("This legacy link has no canonical chat. Its saved history is unchanged.");return}const I=e;w(null),(A.activeSessionId!==I||A.activeDraftKey)&&A.openSession(I)},[r,e]);const y=m.useRef(g);m.useEffect(()=>{y.current!==g&&(y.current=g,g&&w(null))},[g]);const S=(A,I)=>{Fe.getState().stageDraft(A,I),w(null),t("/chat")},C=m.useCallback(()=>{w(null),t("/chat")},[t]),E=Bv(g,b?.sessionId,p),k=gA(g,E),F=_||(x&&!a&&!u?x:null);return c.jsxs("div",{className:"panel-flush flex min-h-0 flex-1 flex-col",children:[F&&c.jsx("div",{className:"panel-top-pad",children:c.jsx("p",{role:"alert",className:R("px-4 py-2 text-body-sm text-danger"),children:F})}),r?k?c.jsx("div",{className:R("min-h-0 flex-1",F&&"[--panel-top-pad:0px]"),children:c.jsx(Att,{identity:k,draftKey:g,sessionId:E,onStartNewChat:C},k)}):c.jsx("div",{className:R("p-6"),children:c.jsx("button",{type:"button",className:R("rounded-md border border-control px-3 py-2"),onClick:()=>S(void 0,!0),children:h("ui.shell.sidebar_navigation.new_chat")})}):c.jsxs("div",{className:R("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:R("text-center"),children:n.isLoading?"Connecting to the backend… Your conversation is safe.":n.error?zi(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:R("underline"),onClick:()=>void f(),children:h("ui.common.actions.retry")})]})]})}const qK=100,Ftt=4,Dtt=16,Itt=3;function KK(e,t){return t.sessionId??(e.startsWith("send:")?e.slice(5):void 0)}function Ntt(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=KK(n,s);r&&t.push({key:n,sessionId:r,submittedAt:s.submittedAt??0})}return t}function YK(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=KK(n,s);if(!i)continue;const a=t.get(i);a?a.push(r):t.set(i,[r])}return t}function Ptt(e){const t=new Map,n=Ntt(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 hm=null;function Mtt(){return hm||(hm=Ott().catch(()=>({visited:0,resolved:0,healed:0})).finally(()=>{hm=null}),hm)}async function Ott(){const e=Fe.getState().drafts,t=Ptt(e),n=YK(e),s=[...new Set([...t.keys(),...n.keys()])].slice(0,Dtt);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 Ltt(l,t.get(l)??[],n.get(l)??[]);i+=u.resolved,a+=u.healed}};return await Promise.all(Array.from({length:Math.min(Itt,s.length)},o)),{visited:r,resolved:i,healed:a}}async function Ltt(e,t,n){let s;try{s=await rt({op:"sessions.history",sessionId:e,limit:qK})}catch{return{resolved:0,healed:0}}Fe.getState().resolveHeldFromServer(e,s.entries,!1);const r=new Set(YK(Fe.getState().drafts).get(e)??[]),i=n.filter(u=>r.has(u)),a=n.length-i.length,o=i.length>0?await Btt(e,s,i):0;let l=0;for(const u of t){const d=Fe.getState().drafts[u];if(!(d!==void 0&&d.admissionAttempted===!0&&d.submittedText!==void 0)){l+=1;for(const p of[u,y5(u,e)])Ua.getState().reconcileDelivered(p)}}return{resolved:l,healed:a+o}}async function Btt(e,t,n){const s=new Set(n);let r=t.entries[0]?.id;for(let i=0;i<Ftt;i++){if(s.size===0||!r)return n.length-s.size;let a;try{a=await rt({op:"sessions.history",sessionId:e,limit:qK,beforeId:r})}catch{return n.length-s.size}for(const o of a.entries)s.delete(o.id);if(Fe.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 Uj=!1;function jtt(){m.useEffect(()=>{Uj||(Uj=!0,Mtt())},[])}const Htt="n",Utt=e=>e.defaultPrevented||e.repeat||e.isComposing||e.shiftKey||e.altKey||e.key.toLowerCase()!==Htt||!(e.metaKey||e.ctrlKey)||XJ(e.target)?!1:!pA(e.target),Gj=e=>e?"⌘+N":"Ctrl+N",Gtt=()=>{const e=Au(o=>o.request),t=Au(o=>o.consumePanel),[n,s]=m.useState(null),r=m.useRef(null),i=m.useCallback(()=>{s(null);const o=r.current;r.current=null,o&&requestAnimationFrame(()=>{o.isConnected&&o.focus()})},[]);m.useEffect(()=>{if(!e)return;const o=Ire({request:e,presentable:!!BN(e.destination),claimed:Au.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?BN(n.destination):void 0;return!n||!a?null:c.jsx(a,{action:n.action,sessionId:"",frontend:null,onClose:i},n.destination)},g_=sg()(e=>({open:!1,openLanguage:()=>e({open:!0}),closeLanguage:()=>e({open:!1})}));function Vtt(e){return!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.repeat||e.defaultPrevented?null:e.key.toLowerCase()==="k"?"chats":null}const Wtt={chats:gQe,everything:"",commands:vQe};function $tt(e,t){const n=Wtt[e],s=ey(n).scope;return t.open?ey(t.query).scope===s?{action:"close"}:{action:"switch",query:n}:{action:"open",query:n}}function ul(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 ztt(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 qtt(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 Ktt(e,t,n){return t<=0?null:n==="next"?(e+1)%t:(e-1+t)%t}function Ytt(e){return e?["Ctrl+N","Ctrl+P"]:["Ctrl+N"]}const Xtt={general:"settings-sidebar-general",radient:"settings-sidebar-radient-account",integrations:"settings-sidebar-integrations",appearance:"settings-sidebar-appearance",updates:"settings-sidebar-application-updates"},Qtt=[{get label(){return h("ui.settings.navigation.settings_sidebar.general")},ids:["general","appearance","speech","keyboard"]},{get label(){return h("ui.settings.navigation.settings_sidebar.account")},ids:["providers","integrations","radient","agent-messages"]},{get label(){return h("ui.settings.navigation.settings_sidebar.backend")},ids:["backend","imports"]},{get label(){return h("ui.settings.navigation.settings_sidebar.system")},ids:["updates"]}],Ndt=({activeSection:e,onSelectSection:t,sections:n})=>{Ve();const s=b8("(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":Xtt[i.id],className:R("relative flex h-8 w-full items-center rounded-sm bg-transparent text-start 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 start-1 top-1/2 size-1 -translate-y-1/2 rounded-full bg-accent"}),c.jsx("span",{"aria-hidden":"true",className:R("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(vt,{content:i.label,side:"right",children:o})},i.id)};return c.jsx("nav",{"aria-label":h("ui.settings.navigation.settings_sidebar.settings_sections"),"data-glass-region":"page-sidebar",className:"panel-top-pad 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:Qtt.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)})})})},Jtt=[{id:"general",get label(){return h("ui.settings.navigation.settings_sidebar.general_settings")},icon:Su},{id:"radient",get label(){return h("ui.settings.navigation.settings_sidebar.radient_account")},icon:YU},{id:"agent-messages",get label(){return h("ui.agentMessages.settings.section")},icon:u2},{id:"integrations",get label(){return h("ui.settings.navigation.settings_sidebar.integrations")},icon:yU},{id:"appearance",get label(){return h("ui.settings.navigation.settings_sidebar.appearance")},icon:wU},{id:"speech",get label(){return h("ui.settings.navigation.settings_sidebar.speech_voicing")},icon:bce},{id:"keyboard",get label(){return h("ui.settings.navigation.settings_sidebar.keyboard_shortcuts")},icon:vU},{id:"providers",get label(){return h("ui.settings.navigation.settings_sidebar.model_providers")},icon:O8},{id:"backend",get label(){return h("ui.settings.navigation.settings_sidebar.backend_settings")},icon:Lp},{id:"imports",get label(){return h("ui.settings.imports.title")},icon:Wce},{id:"updates",get label(){return h("ui.settings.navigation.settings_sidebar.application_updates")},icon:SA}],Vj=100,Ztt=["desktop","settings"],ent=[{id:"chat",get name(){return h("ui.command_palette.use_palette_sources.chat")},path:"/chat",icon:"chat",keywords:["conversations","messages","history","sessions"]},{id:"agents",get name(){return h("ui.command_palette.use_palette_sources.my_agents")},path:"/agents",icon:"agents",keywords:["bots","assistants","roster","agent list"]},{id:"projects",get name(){return h("ui.command_palette.use_palette_sources.projects")},path:"/projects",icon:"projects",keywords:["workstreams","milestones","tracking","planning"]},{id:"agent-hub",get name(){return h("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 h("ui.command_palette.use_palette_sources.schedules")},path:"/schedules",icon:"schedules",keywords:["cron","recurring","automation","jobs","timer","daily"]},{id:"browser",get name(){return h("ui.command_palette.use_palette_sources.browser")},path:"/browser",icon:"browser",keywords:["web","sites","url","internet"]},{id:"settings",get name(){return h("ui.command_palette.use_palette_sources.settings")},path:"/settings",icon:"settings",keywords:["preferences","config","options","configuration"]}],tnt={id:"mesh",get name(){return h("ui.command_palette.use_palette_sources.mesh")},path:"/mesh",icon:"network",keywords:["networks","peers","devices","relay","mesh"]};function nnt({open:e,query:t,isOnChatPage:n,hasConversation:s,isCanvasOpen:r}){Ve();const{scope:i,terms:a}=ey(t),o=i===null||i==="chat",l=i===null||i==="agent",u=i===null||i==="agent",d=i===null||i==="setting",f=ss(),p=Et(f.data,"session_search"),g=Et(f.data,"settings"),v=Et(f.data,"session_catalogue",2),b=Et(f.data,"session_archive"),x=By((o||u)&&Et(f.data,"team_catalogue")),_=m.useMemo(()=>new Map((x.data??[]).map(me=>[me.name,Dp(me)])),[x.data]),w=I2(Et(f.data,"peers")),y=Et(f.data,"projects",1),S=m.useMemo(()=>[...ent.filter(me=>me.id!=="projects"||y),...w==="member"?[tnt]:[]],[w,y]),{data:C}=og(),E=C?.snapshot?.pairing.available===!1,k=Fe(me=>me.sessions),F=Fe(me=>me.forgotten),A=Fe(me=>me.loading),I=Fe(me=>me.fetchSessions),N=m.useRef(!1);m.useEffect(()=>{if(!e){N.current=!1;return}N.current||k.length>0||A||(N.current=!0,I(fy))},[e,k.length,A,I]);const P=rK(a,e&&o&&a.length>0&&p),M=P.data&&P.data.query===a?P.data.sessions:null,Y=m.useMemo(()=>({include:!1,facts:{},forgotten:new Set(Object.keys(F))}),[F]),O=QJ(nt(me=>me.conversationRecents)),X=Fe(me=>{const Ee=me.activeDraftKey?me.drafts[me.activeDraftKey]:void 0;return Bv(me.activeDraftKey,Ee?.sessionId,me.activeSessionId)}),Q=Fe(me=>me.archiveFacts),ie=(()=>{if(!o)return[];const{rows:me}=LR(k,a,M,{},Y),Ee=new Map((M??[]).map(Ae=>[Ae.id,Ae]));return me.map((Ae,se)=>{const he=Ee.get(Ae.session_id),xe=nK(Ae,a),Je=GQe(Ae,_),pe=kae(Ae,O,X,b,Q),Xe=!!he?.body_match&&!xe;return{...Je,hint:Xe?h("ui.command_palette.use_palette_sources.in_conversation"):Je.hint,tier:xe||he?Math.min(he?.rank??Zw,xe?Zw:Number.POSITIVE_INFINITY):void 0,soft:Ae.preview??void 0,order:se,featured:a.length===0,unread:dy(Ae)!==null,recentRank:pe.recentRank,current:pe.current,archived:pe.archived}})})(),G=aT(1,Vj),ne=Eg(a,sK),oe=(G.data?.total??0)>(G.data?.agents?.length??0),B=aT(1,Vj,0,oe&&l&&ne?ne:void 0),H=(()=>{if(!l)return[];const me=new Set,Ee=[];for(const se of[G.data?.agents,B.data?.agents])for(const he of se??[])me.has(he.id)||(me.add(he.id),Ee.push(he));const Ae=[];for(const se of Ee)v&&Ae.push({id:`agent-chat-${se.id}`,kind:"agent",group:"agents",name:se.name,hint:h("ui.command_palette.use_palette_sources.agent_chat"),icon:"agents",keywords:se.tags,target:{type:"draft",kind:"agent",name:se.name},featured:a.length===0}),Ae.push({id:`agent-settings-${se.id}`,kind:"agent",group:"agents",name:se.name,hint:h("ui.command_palette.use_palette_sources.agent_settings"),icon:"settings",keywords:se.tags,target:{type:"path",path:`/agents/${se.id}`}});return Ae.map((se,he)=>({...se,order:he}))})(),U=u?v?(x.data??[]).map((me,Ee)=>({id:`team-chat-${me.name}`,kind:"team",group:"teams",name:Dp(me),hint:h("ui.command_palette.use_palette_sources.team_chat"),icon:"team",keywords:[me.name,...me.aliases??[]],target:{type:"draft",kind:"team",name:me.name},featured:a.length===0,order:Ee})):[]:[],z=Dn({queryKey:Ztt,queryFn:()=>rt({op:"settings.list"}),enabled:e&&d&&g,staleTime:1e4}),te=d?[...BQe(Jtt),...jQe((z.data?.settings??[]).map(GA))]:[],fe=Fe(me=>me.activeSessionId),J=Fe(me=>me.activeDraftKey),Se=v&&!!(fe??J),W=!!fe,Ce=!v||E?[]:UQe([{id:"info",destination:"info",name:h("ui.command_palette.use_palette_sources.info"),hint:h("ui.command_palette.use_palette_sources.app_backend_and_environment"),icon:"info",keywords:["about","version","environment","diagnostics","host","runtime"]},{id:"usage",destination:"usage",name:h("ui.command_palette.use_palette_sources.provider_usage"),hint:h("ui.command_palette.use_palette_sources.credits_limits_and_spend"),icon:"usage",keywords:["usage","credits","billing","limits","cost","spend","tokens","quota"]},...Se&&W?[{id:"session",destination:"session.diagnostics",name:h("ui.command_palette.use_palette_sources.session"),hint:h("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:h("ui.command_palette.use_palette_sources.analytics"),hint:h("ui.command_palette.use_palette_sources.usage_over_time"),icon:"analytics",keywords:["usage","charts","trends","cost","spend","tokens","reports"]}]);return{items:[...LQe(S),...HQe(snt({isOnChatPage:n,hasConversation:s,isCanvasOpen:r,canStageDraft:v})),...Ce,...te,...H,...U,...ie],chats:{awaiting:e&&o&&a.length>0&&p&&!P.refused&&!P.isError&&P.data?.query!==a,unavailable:o&&a.length>0&&!p,unreachable:f.isError,pending:f.isLoading||f.isPending,overLong:P.refused,catalogue:k.length>0?"loaded":A||!N.current?"loading":"empty"}}}function snt({isOnChatPage:e,hasConversation:t,isCanvasOpen:n,canStageDraft:s}){return[...s?[{id:"new-chat",name:h("ui.command_palette.use_palette_sources.new_chat"),icon:"new-chat",keywords:["start chat","compose","draft","new conversation"],verb:h("ui.command_palette.use_palette_sources.start"),command:"new-chat",featured:!0}]:[],{id:"connect-provider",name:h("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:h("ui.command_palette.use_palette_sources.connect"),command:"connect-provider",featured:!0},{id:"change-interface-language",name:h("ui.settings.language.palette_action"),icon:"language",keywords:["language","locale","interface language","translation","i18n"],verb:h("ui.command_palette.use_palette_sources.change"),command:"change-interface-language"},{id:"create-agent",name:h("ui.command_palette.use_palette_sources.create_agent"),icon:"plus",keywords:["new agent","add agent","make agent"],verb:h("ui.command_palette.use_palette_sources.create"),command:"create-agent",featured:!0},...e?[{id:"toggle-canvas",name:n?h("ui.command_palette.use_palette_sources.close_canvas"):h("ui.command_palette.use_palette_sources.open_canvas"),icon:n?"canvas-close":"canvas-open",keywords:["files","workspace","panel","editor","artifacts"],verb:n?h("ui.command_palette.use_palette_sources.close"):h("ui.command_palette.use_palette_sources.open"),command:"toggle-canvas",featured:!0}]:[],...e&&t?[{id:"clear-conversation",name:h("ui.command_palette.use_palette_sources.clear_conversation"),icon:"trash",keywords:["delete chat","reset","wipe","erase","clear history"],verb:h("ui.command_palette.use_palette_sources.clear"),command:"clear-conversation",destructive:!0,featured:!0}]:[]]}const rnt={chat:u2,conversation:P0,agents:yl,team:Vm,projects:mU,hub:CU,network:L8,schedules:pU,browser:Uu,settings:Su,theme:wU,integrations:yU,providers:O8,backend:Lp,updates:SA,plus:Cl,"new-chat":ode,trash:cg,"canvas-open":Nre,"canvas-close":Hu,slider:Lp,info:ig,language:bU,usage:Qce,session:fU,analytics:Rce},int=({name:e})=>{if(e==="account")return c.jsx(YU,{size:16});const t=rnt[e];return c.jsx(t,{size:16,"aria-hidden":"true"})},fm="command-palette-input",Wj="command-palette-results",ant={get page(){return h("ui.command_palette.command_palette.go")},get action(){return h("ui.command_palette.command_palette.run")},get panel(){return h("ui.command_palette.command_palette.open")},get chat(){return h("ui.command_palette.command_palette.open")},get agent(){return h("ui.command_palette.command_palette.open")},get team(){return h("ui.command_palette.command_palette.open")},get"settings-section"(){return h("ui.command_palette.command_palette.open")},get setting(){return h("ui.command_palette.command_palette.open")}},ont=200,$j=()=>{const e=Fe.getState(),t=e.activeDraftKey;return C5(t,t?e.drafts[t]?.sessionId:void 0,e.activeSessionId)},lnt=()=>{Ve();const e=oi(),t=fA(),n=nt(se=>se.isCommandPaletteOpen),s=nt(se=>se.closeCommandPalette),r=nt(se=>se.commandPaletteQuery),i=nt(se=>se.setCommandPaletteQuery),a=nt(se=>se.isCanvasOpen),o=nt(se=>se.setCanvasOpen),l=nt(se=>se.isCreateAgentDialogOpen),u=Au(se=>se.requestPanel),{agentId:d}=vfe(),f=d8(se=>se.getLastAgentId),p=zU(),[g,v]=m.useState(r),[b,x]=m.useState(0),_=m.useRef(null),[w,y]=m.useState(!1),[S,C]=m.useState(!1),E=m.useDeferredValue(g),k=Eg(g,ont);m.useEffect(()=>{i(k)},[k,i]),m.useEffect(()=>{n&&v(r)},[n,r]);const F=t.pathname.startsWith("/chat"),A=d||f("chat"),{items:I,chats:N}=nnt({open:n,query:E,isOnChatPage:F,hasConversation:!!A,isCanvasOpen:a}),P=m.useMemo(()=>MQe({items:I,raw:E}),[I,E]),M=m.useMemo(()=>P.sections.flatMap(se=>se.items),[P]),Y=M.length,O=M[b],X=P.terms.length>0,Q=Y>0,ie=P.scope===null?null:jR.find(se=>se.scope===P.scope)??null,G=hQe({scope:P.scope,hasTerms:X,terms:P.terms,awaiting:N.awaiting,catalogue:N.catalogue}),ne=m.useCallback(()=>{s(),e("/agents?create=agent")},[s,e]),oe=m.useCallback(()=>{s(),B8.getState().openConnect()},[s]),B=m.useCallback(()=>{s(),g_.getState().openLanguage()},[s]),H=m.useCallback(()=>{Fe.getState().stageDraft(void 0,!0),s(),e("/chat")},[s,e]),U=m.useCallback(()=>{o(!a),s()},[a,o,s]),z=m.useCallback(()=>{A&&C(!0)},[A]),te=m.useCallback(()=>{A&&p.mutate({agentId:A}),C(!1),s()},[A,p,s]),fe=m.useCallback(se=>{switch(se){case"create-agent":ne();return;case"connect-provider":oe();return;case"change-interface-language":B();return;case"new-chat":H();return;case"toggle-canvas":U();return;case"clear-conversation":z()}},[ne,oe,B,H,U,z]),J=m.useRef(null),Se=m.useRef(void 0),W=m.useCallback(se=>{switch(se.target.type){case"path":s(),e(se.target.path);return;case"session":{const{sessionId:he}=se.target;s(),dg(e,he);return}case"command":fe(se.target.command);return;case"draft":{const{kind:he,name:xe}=se.target;Fe.getState().stageDraft({kind:he,name:xe}),s(),e("/chat");return}case"panel":{const{destination:he}=se.target;u(he,J.current),s(),N8(he)&&!t.pathname.startsWith("/chat")&&e("/chat");return}}},[s,e,t.pathname,u,fe]);m.useEffect(()=>{if(!n)return;const se=document.activeElement;J.current=se instanceof HTMLElement?se:null,Se.current=$j()},[n]);const Ce=m.useCallback(()=>{const se=J.current,he=Pre({viewMoved:Se.current!==$j(),capturedUsable:!!(se?.isConnected&&se!==document.body),caretUntouched:Ore(se,document.activeElement,document.body)});if(!(he==="composer"&&Mre())&&he!=="leave"){if(he==="captured"&&se){se.focus();return}document.querySelector("[data-command-palette-trigger]")?.focus()}},[]);m.useEffect(()=>{n&&document.getElementById(fm)?.focus()},[n]),m.useEffect(()=>{x(0)},[E,n]);const K=m.useCallback(se=>{if(_.current?.disconnect(),!se?.parentElement)return;const he=se.parentElement,xe=()=>{const pe=getComputedStyle(he),Xe=Number.parseFloat(pe.paddingTop)+Number.parseFloat(pe.paddingBottom);y(se.offsetHeight+Xe>he.clientHeight+1)};xe();const Je=new ResizeObserver(xe);Je.observe(he),Je.observe(se),_.current=Je},[]);if(m.useEffect(()=>{x(se=>se>=Y?Math.max(Y-1,0):se)},[Y]),m.useEffect(()=>{if(!n)return;const se=he=>{if(S||l||he.target?.id!==fm)return;const xe=M.length,Je=qtt(he);if(Je!==null)he.preventDefault(),x(pe=>Ktt(pe,xe,Je)??pe);else if(he.key==="Enter"){he.preventDefault();const pe=M[b];pe&&W(pe.item)}else he.key==="Escape"&&(he.preventDefault(),s())};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[n,S,l,M,b,W,s]),m.useEffect(()=>{if(!n)return;const se=M[b]?.item.id;se&&document.getElementById(se)?.scrollIntoView({block:"nearest",behavior:"auto"})},[n,M,b]),!n)return null;const me=O?.item,Ee=!X||!Q,Ae=Ytt(navigator.platform.toUpperCase().indexOf("MAC")>=0);return c.jsxs(c.Fragment,{children:[c.jsx(Tc,{open:n,onOpenChange:se=>{se||s()},children:c.jsxs(Rc,{"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:se=>{se.preventDefault();const he=document.getElementById(fm);he instanceof HTMLInputElement&&(he.focus(),he.setSelectionRange(he.value.length,he.value.length))},onCloseAutoFocus:se=>{se.preventDefault(),Ce()},children:[c.jsx(wl,{className:"sr-only",children:h("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(_h,{size:16,"aria-hidden":"true",className:"shrink-0 text-ink-dim"}),c.jsx("input",{id:fm,type:"text",role:"combobox","aria-expanded":Q,"aria-controls":Q?Wj:void 0,"aria-activedescendant":me?.id,"aria-autocomplete":"list",autoComplete:"off",placeholder:h("ui.command_palette.command_palette.search_chats_settings_pages_and_actions"),value:g,onChange:se=>v(se.target.value),className:"min-w-0 flex-1 bg-transparent text-body text-ink outline-none! placeholder:text-ink-dim"}),ie&&c.jsxs("span",{className:"flex shrink-0 items-center gap-0 text-ink-dim text-meta",children:[c.jsx(Lr,{shortcut:ie.glyph}),ie.label]}),g&&c.jsx(ce,{variant:"ghost",size:"icon-sm","aria-label":h("ui.command_palette.command_palette.clear_search"),onClick:()=>{v(""),document.getElementById(fm)?.focus()},children:c.jsx(Xn,{"aria-hidden":"true"})})]}),Q?c.jsxs("div",{className:"relative",children:[w&&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:Wj,"aria-label":h("ui.command_palette.command_palette.results"),tabIndex:-1,className:"max-h-96 overflow-y-auto p-2",children:[c.jsx("div",{ref:K,children:P.sections.map((se,he)=>c.jsxs(m.Fragment,{children:[c.jsx("div",{role:"presentation",className:R("px-2 pb-1 text-ink-dim text-meta",he===0?"pt-1":"pt-3"),children:AQe[se.group]}),se.items.map(xe=>c.jsx(cnt,{match:xe,isActive:xe.item.id===me?.id,onHover:()=>x(M.indexOf(xe)),onRun:()=>W(xe.item)},xe.item.id))]},se.group))}),w&&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})]}),Q&&X&&N.awaiting&&c.jsx("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:h("ui.command_palette.command_palette.searching_conversations")}),X&&N.overLong&&c.jsxs("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:[h("ui.command_palette.command_palette.search_terms_are_limited_to"),py,h("ui.command_palette.command_palette.characters_so_chats_are_matched_by_name")]}),X&&!N.overLong&&N.unavailable&&!N.pending&&c.jsx("p",{className:"px-4 pt-2 text-ink-dim text-meta",children:N.unreachable?h("ui.command_palette.command_palette.conversation_search_is_unavailable_while_the_backend_is_unreachab"):h("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:Ee?c.jsxs(c.Fragment,{children:[jR.map(se=>c.jsxs("span",{className:"flex items-center gap-0",children:[c.jsx(Lr,{shortcut:se.glyph}),se.label]},se.scope)),c.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[c.jsx(Lr,{shortcut:"esc"}),h("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(Lr,{shortcut:"↑"}),c.jsx(Lr,{shortcut:"↓"}),Ae.map(se=>c.jsx(Lr,{shortcut:se,joined:!0},se)),h("ui.command_palette.command_palette.to_move")]}),c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx(Lr,{shortcut:"↵"}),h("ui.command_palette.command_palette.to_run")]}),c.jsx("span",{className:"flex items-center gap-1.5",children:P.clipped&&c.jsx("span",{children:X?h("ui.command_palette.matches.best",{countText:String(Y),total:P.total,totalText:String(P.total)}):h("ui.command_palette.matches.showing",{count:String(Y),total:String(P.total)})})}),c.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[c.jsx(Lr,{shortcut:"esc"}),h("ui.command_palette.command_palette.to_close")]})]})})]})}),c.jsx(nd,{open:S,title:h("ui.command_palette.command_palette.clear_this_conversation"),message:h("ui.command_palette.command_palette.every_message_in_it_is_deleted_from_this_computer_and_there_is_no"),confirmText:h("ui.command_palette.command_palette.clear"),cancelText:h("ui.common.actions.cancel"),isDangerous:!0,onConfirm:te,onCancel:()=>C(!1)})]})},cnt=({match:e,isActive:t,onHover:n,onRun:s})=>{const{item:r,soft:i}=e,a=r.verb??ant[r.kind];return c.jsxs("button",{id:r.id,type:"button",role:"option","aria-selected":t,tabIndex:-1,onClick:s,onMouseMove:n,className:R("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:R("flex size-4 shrink-0 items-center justify-center",r.destructive?"text-danger":"text-ink-dim"),children:c.jsx(int,{name:r.icon})}),c.jsx("span",{className:R("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(Lr,{shortcut:"↵"})]})]})},unt="toggle-command-palette",dnt="toggle-command-palette-commands";function jk(e){const t=nt.getState(),n=$tt(e,{open:t.isCommandPaletteOpen,query:t.commandPaletteQuery});n.action==="open"?t.toggleCommandPalette(n.query):n.action==="close"?t.closeCommandPalette():t.setCommandPaletteQuery(n.query)}function hnt(){m.useEffect(()=>{const e=t=>{const n=Vtt(t);n&&(t.preventDefault(),jk(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),m.useEffect(()=>{const e=window.electron.ipcRenderer.on(unt,()=>jk("everything")),t=window.electron.ipcRenderer.on(dnt,()=>jk("commands"));return()=>{e?.(),t?.()}},[])}const fnt=({enabled:e})=>{const t=I2(e),n=D2(e&&t==="member",{stamp:()=>Fe.getState().beginAnswer()}),s=Fve(e&&t==="member",{poll:!0,stamp:()=>Fe.getState().beginAnswer()}),r=Fe(o=>o.settlePeerCatalogue),i=m.useRef(0),a=m.useRef(0);return m.useEffect(()=>{!s.data||s.data.requestedAt<=i.current||(i.current=s.data.requestedAt,r(s.data.rows.map(JJ),s.data.requestedAt))},[s.data,r]),m.useEffect(()=>{if(!n.data||n.data.requestedAt<=a.current)return;a.current=n.data.requestedAt;const o=Object.fromEntries(n.data.peers.map(l=>[l.device_id,{reachable:l.reachable,last_seen_at:l.last_seen_at,reason:l.unreachable_reason,session_count:l.session_count,redial_state:l.redial?.state??null,at:n.data.requestedAt}]));r([],0,o,n.data.requestedAt)},[n.data,r]),null},pnt={single:"max-w-[min(40rem,calc(100vw-4rem))]"},gnt=({open:e,title:t,stepIndicators:n,children:s,actions:r,width:i="single",className:a,onDismiss:o})=>{const l=m.useRef(null);return c.jsx(Tc,{open:e,onOpenChange:u=>{u||o?.()},children:c.jsxs(Rc,{"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:R("max-h-[calc(100vh-4rem)] gap-0 overflow-hidden p-0",pnt[i],a),children:[(t||n)&&c.jsxs("div",{className:R("flex shrink-0 items-center justify-between gap-4 border-hairline border-b px-6 py-4",o&&"pr-14"),children:[t?c.jsx(wl,{className:"text-title",children:t}):c.jsx(wl,{className:"sr-only",children:h("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 mnt(e,t,n=!1){const s=e===Qr.DEFAULT_MODEL&&t!==null;return{blocked:s,reason:s?t:null,primaryDisabled:n||s}}const m_=({value:e,label:t,variant:n="ghost",onCopied:s})=>{Ve();const[r,i]=m.useState(!1);return m.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{nn(h("ui.common.actions.copy_failed"))}},children:[r?c.jsx(Js,{"aria-hidden":"true"}):c.jsx(ed,{"aria-hidden":"true"}),r?h("ui.common.actions.copied"):t]})},vnt=3e3,Af={all:["desktop","tunnel","setup"],local:e=>["desktop","tunnel","setup","local",e],fresh:e=>["desktop","tunnel","setup","fresh",e]};function Nx(e,t){if(e instanceof Fi){const n=e.code;if(n==="setup_in_progress")return"in-progress";if(n!==void 0&&n!=="setup_intent_corrupt"&&eZ.has(n))return{kind:"backend",message:e.message,code:n};if(t==="run"&&(e.status===null||n===Ov.transportFailed||n===f5))return"unconfirmed"}return{kind:"generic",during:t}}function bnt(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 Hk=e=>ZJ.parse(e);function xnt(){const e=Mt(),t=ss(),n=Et(t.data,"tunnel_setup"),[s,r]=m.useState(null),[i,a]=m.useState(null),[o,l]=m.useState(!1),u=m.useRef(0),d=m.useRef(!1),f=m.useRef(!1),p=m.useRef(!1),g=fn({retry:!1,mutationFn:async I=>Hk(await rt({op:"tunnel.setup.run",credentialId:I.credentialId,acceptMonthlyPrice:I.price})),onSuccess:I=>{p.current=f.current,a(null),e.setQueryData(Af.fresh(s),I)},onError:I=>{const N=Nx(I,"run");N==="unconfirmed"?(u.current=Date.now(),l(!0)):N!=="in-progress"&&a(N)},onSettled:(I,N)=>{d.current=N!==null&&Nx(N,"run")==="unconfirmed",e.invalidateQueries({queryKey:Af.local(s)})}}),v=g.isPending||o,b=Dn({queryKey:Af.local(s),queryFn:async()=>Hk(await rt({op:"tunnel.setup.read",credentialId:s??void 0})),enabled:n,retry:!1,staleTime:0,refetchOnWindowFocus:!1,refetchInterval:I=>v||I.state.data?.in_progress?vnt:!1}),x=b.data,_=x?.in_progress===!0||v,w=Dn({queryKey:Af.fresh(s),queryFn:async()=>{try{return Hk(await rt({op:"tunnel.setup.plan",credentialId:s??void 0}))}catch(I){throw Nx(I,"check")==="in-progress"&&e.invalidateQueries({queryKey:Af.local(s)}),I}},enabled:n&&b.isSuccess&&!_,retry:!1,staleTime:Number.POSITIVE_INFINITY,gcTime:0,refetchOnWindowFocus:!1,refetchOnMount:"always"}),y=m.useRef(Date.now()),S=w.data&&w.dataUpdatedAt>=y.current?w.data:void 0,C=x?.in_progress===!0;m.useEffect(()=>{f.current&&!C&&(p.current?p.current=!1:d.current||w.refetch()),f.current=C},[C,w.refetch]),m.useEffect(()=>{o&&x&&!x.in_progress&&b.dataUpdatedAt>u.current&&(l(!1),d.current=!1,e.resetQueries({queryKey:Af.fresh(s)}))},[o,x,b.dataUpdatedAt,e,s]),m.useEffect(()=>{const I=b.error??w.error;if(!I)return;const N=Nx(I,"check");N!=="in-progress"&&N!=="unconfirmed"&&a(N)},[b.error,w.error]);const E=bnt({enabled:n,local:x,fresh:S,failure:i,runPending:v,freshErrored:w.isError&&!S}),k=m.useCallback(I=>{a(null),r(I)},[]),F=m.useCallback(()=>{a(null),b.refetch(),w.refetch()},[b.refetch,w.refetch]),A=m.useCallback((I,N)=>{d.current||(d.current=!0,p.current=!1,a(null),g.mutate({credentialId:I,price:N}))},[g.mutate]);return{view:E,selectedId:s,choose:k,check:F,run:A}}const w0=({status:e})=>c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e==="connected"?c.jsx(xA,{size:20,className:"shrink-0 text-success","aria-hidden":"true"}):null,c.jsx("h4",{className:"text-heading text-ink",children:h("ui.providers.phone.heading")}),e==="checking"?c.jsxs("span",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(On,{size:"sm"}),c.jsx("output",{children:h("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(On,{size:"sm"}),c.jsx("output",{children:h("ui.providers.phone.status.applying")})]}):null,e==="connected"?c.jsx("output",{className:"text-body-sm text-success",children:h("ui.providers.phone.status.connected")}):null]}),PD=({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?h("ui.providers.phone.account",{identity:e.identity_label,id:t}):h("ui.providers.phone.account_unlabeled",{id:t})})},ny=({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))})]}),_nt=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(h(i)),a&&r.push(h(a)),o&&r.push(h("ui.providers.phone.outcome.failure_stage",{stage:h(o)})),r},wnt=({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"?h("ui.providers.phone.failure.run"):h("ui.providers.phone.failure.check")}),c.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:h("ui.providers.phone.action.check_again")})]}),ynt=({result:e})=>c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"verified","data-phone-verified":"true",children:[c.jsx(w0,{status:"connected"}),c.jsx(PD,{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:h("ui.providers.phone.address_label")}),c.jsx("code",{className:"break-all text-ink text-mono-sm",children:e.url}),c.jsx(m_,{value:e.url,label:h("ui.providers.phone.action.copy_address"),variant:"secondary"})]}):null,c.jsx("p",{className:"break-words text-body-sm text-ink-muted",children:h("ui.providers.phone.use_address")}),c.jsx(ny,{heading:h("ui.providers.phone.receipts_heading"),lines:e.receipts.map(t=>t.text)})]}),Cnt=({onDone:e})=>{const{issue:t,start:n,cancel:s}=Lre(),r=t.kind==="signing-in"||t.kind==="input-required",i=m.useRef(!1);return m.useEffect(()=>{i.current&&!r&&e(),i.current=r},[r,e]),r?c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(On,{size:"sm"}),c.jsx("output",{className:"text-body-sm text-ink-muted",children:h("ui.providers.phone.signing_in")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:s,children:h("ui.providers.phone.action.cancel")})]}):c.jsxs(ce,{variant:"primary",size:"sm",onClick:n,children:[h("ui.providers.phone.action.sign_in"),c.jsx(wu,{"aria-hidden":"true"})]})},Snt=({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:h("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:h("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:h("ui.providers.phone.action.set_up")}),d=a):s==="sign_in"&&n&&(u=c.jsx(Cnt,{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(w0,{}),c.jsx(PD,{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:h("ui.providers.phone.choose_heading")}),e.credential_choices.map(f=>c.jsx(ce,{variant:"secondary",size:"sm",onClick:()=>t.choose(f.id),children:f.identity_label?h("ui.providers.phone.action.choose",{identity:f.identity_label,id:String(f.id)}):h("ui.providers.phone.action.choose_unlabeled",{id:String(f.id)})},f.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:h("ui.providers.phone.consent",{amount:i})}):null,c.jsx(ny,{heading:h("ui.providers.phone.progress_heading"),lines:_nt(e)}),c.jsx(ny,{heading:h("ui.providers.phone.receipts_heading"),lines:e.receipts.map(f=>f.text)}),s==="choose_account"?null:c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[u,d]})]})},knt=({offerSignIn:e})=>{const t=xnt(),{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":h("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(w0,{status:"checking"})}):null,n.kind==="applying"?c.jsxs("div",{className:"flex flex-col gap-3","data-phone-state":"applying",children:[c.jsx(w0,{status:n.setup?"applying":"checking"}),n.account?c.jsx(PD,{result:n.account}):null,c.jsx(ny,{heading:h("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(w0,{}),c.jsx(wnt,{failure:n.failure,onCheck:t.check})]}):null,n.kind==="result"&&n.result.verified?c.jsx(ynt,{result:n.result}):null,n.kind==="result"&&!n.result.verified?c.jsx(Snt,{result:n.result,setup:t,offerSignIn:e}):null]})},Ent=({offerSignIn:e=!1})=>{const t=ss();return Et(t.data,"tunnel_setup")?c.jsx(knt,{offerSignIn:e}):null},y0={phase:"idle",operation:null,opened:!1,openFailed:!1,error:null};let tl=null;const Tnt=[[/^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 Uk(e){if(cu(e.state))return e;for(const[t,n]of Tnt)if(t.test(e.message))return{...e,state:n};return e.state!=="starting"&&e.expires_in<=0?{...e,state:"expired"}:e}function Rnt(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 zj(e,t){return e instanceof Error&&e.message?e.message:t}function Ant(e){let t=y0,n=null,s=null,r=0,i=!1;const a=p=>{t={...t,...p},i||e.onChange(t)},o=()=>{n?.(),n=null},l=async(p,g)=>{const v=p.auth_url;if(!v||j8(p))return;const b=`${p.id}|${v}`;if(s!==b){s=b;try{await e.open(p.id,!1),g===r&&a({opened:!0,openFailed:!1})}catch{g===r&&a({opened:!1,openFailed:!0})}}},u=(p,g)=>{if(g!==r)return;const v=Uk(p),b=s!==null&&s===`${v.id}|${v.auth_url}`;if(cu(v.state)){o(),tl?.id===v.id&&(tl=null),a({phase:"settled",operation:v,opened:b&&t.opened}),v.state==="succeeded"&&e.onSucceeded?.(v);return}a({phase:"active",operation:v,opened:b?t.opened:!1}),l(v,g)},d=(p,g)=>{u(p,g),!(cu(Uk(p).state)||g!==r)&&(o(),n=e.poll(p.id,v=>u(v,g),{onGone:()=>{g===r&&(n=null,tl?.id===p.id&&(tl=null),a({phase:"settled",operation:Rnt(p.id,p.provider)}))}}))},f=async(p,g)=>{const v=tl;if(!v)return!1;let b=null;try{b=await e.read(v.id)}catch{b=null}if(g!==r)return!0;if(b&&!cu(b.state)&&v.provider===p)return d(b,g),!0;if(b&&!cu(b.state))try{await e.cancel(v.id)}catch{}if(tl=null,g!==r)return!0;const x=await e.start(p);return tl={id:x.id,provider:p},d(x,g),!0};return{async start(p){r+=1;const g=r;o();const v=t.operation;if(s=null,a({phase:"starting",operation:null,opened:!1,openFailed:!1,error:null}),v&&!cu(v.state)){try{await e.cancel(v.id)}catch{}if(g!==r)return}try{const b=await e.start(p);tl={id:b.id,provider:p},d(b,g)}catch(b){if(g!==r)return;if(b instanceof Fi&&b.status===409)try{if(await f(p,g))return}catch(x){if(g!==r)return;a({phase:"settled",error:zj(x,h("ui.providers.sign_in_flow.sign_in_could_not_start"))});return}a({phase:"settled",error:zj(b,h("ui.providers.sign_in_flow.sign_in_could_not_start"))})}},async cancel(){const p=t.operation;if(r+=1,o(),s=null,a({...y0}),!(!p||cu(p.state))){tl?.id===p.id&&(tl=null);try{await e.cancel(p.id)}catch{}}},async reopen(){const p=t.operation;if(!p?.auth_url)return;const g=r;try{await e.open(p.id,!0),s=`${p.id}|${p.auth_url}`,g===r&&a({opened:!0,openFailed:!1})}catch{g===r&&a({openFailed:!0})}},pause(){r+=1,o()},resume(){const p=t.operation;p&&(cu(Uk(p).state)||(r+=1,d(p,r)))},reset(){r+=1,o(),s=null,a({...y0})},dispose(){i=!0,r+=1,o()},getState:()=>t}}const zR=new Map,MD=new Map;function Lm(e){return MD.get(e)??{saved:null,error:null}}function Fnt(e,t){MD.set(e,{...Lm(e),...t})}function Dnt(e){MD.delete(e)}function Int(e){return zR.get(e)?.state??y0}function qj(e,t,n,s){const i=zR.get(e)??(()=>{const a={flow:null,state:y0,listeners:new Set,deps:t};return a.flow=Ant({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)}),zR.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 Nnt(e,t){const n=m.useRef(t);n.current=t;const[s,r]=m.useState(()=>Int(e)),[i,a]=m.useState(()=>qj(e,n.current(),r)),o=m.useRef(e);return m.useEffect(()=>{if(o.current===e)return;i.detach();const l=qj(e,n.current(),r);o.current=e,a(l),r(l.getState()),l.resume()},[e,i]),m.useEffect(()=>(i.setDeps(n.current()),r(i.getState()),i.resume(),()=>i.detach()),[i]),{flow:i.flow,state:s}}const Pnt=({provider:e})=>{Ve();const[t,n]=m.useState(!1),[s,r]=m.useState(null),i=m.useCallback(async()=>{n(!0);try{r(await rt({op:"auth.probe",provider:e.id}))}catch(o){r({reachable:!1,detail:o instanceof Error?o.message:h("ui.providers.provider_detail.the_connection_could_not_be_tested")})}finally{n(!1)}},[e.id]);m.useEffect(()=>{r(null),i()},[i]);const a=ra(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(On,{size:"sm"}),h("ui.providers.provider_detail.checking_whether"),a," ",h("ui.providers.provider_detail.is_running")]}):s.reachable?c.jsxs("p",{className:"text-body-sm text-success",children:[a," ",h("ui.providers.provider_detail.is_running")]}):c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[a," ",h("ui.providers.provider_detail.isn_t_answering"),e.base_url?c.jsxs(c.Fragment,{children:[h("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?h("ui.providers.provider_detail.checking"):h("ui.providers.provider_detail.check_again")})]})},Kj=({id:e,value:t,onChange:n,label:s,invalid:r,describedBy:i})=>{Ve();const[a,o]=m.useState(!1);return c.jsxs("div",{className:"relative",children:[c.jsx(bs,{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?h("ui.providers.provider_detail.hide_key"):h("ui.providers.provider_detail.show_key"),children:a?c.jsx(Hce,{"aria-hidden":"true"}):c.jsx(Kre,{"aria-hidden":"true"})})]})},Mnt=/[.!?]$/,Ont=e=>Mnt.test(e.trim())?e:`${e}.`,Yj=({brand:e,verb:t,defaults:n,retainedNotice:s,unverified:r,onChangeModel:i,actionLabel:a,onAction:o,primaryAction:l,headline:u,tone:d="success",verdict:f})=>{Ve();const p=f?.group==="Needs sign-in",g=m.useRef(null);return m.useEffect(()=>{g.current?.focus()},[]),c.jsxs("div",{className:"flex flex-col gap-3","data-sign-in-state":"succeeded","data-verdict":p?f.tone:void 0,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[p&&f?c.jsx(Bo,{size:20,className:f.tone==="attention"?"text-warning":"text-ink-muted","aria-hidden":"true"}):c.jsx(xA,{size:20,className:d==="unchecked"?"text-ink-muted":"text-success","aria-hidden":"true"}),c.jsx("output",{className:"text-heading text-ink",children:p&&f?f.label:u??(t==="Connected"?h("ui.providers.provider_detail.connected_variant_163",{brand:e}):h("ui.providers.provider_detail.signed_in_to_variant_164",{brand:e}))})]}),p&&f?c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[Ont(f.detail??(f.tone==="attention"?h("ui.providers.provider_detail.is_no_longer_accepting_the_sign_in",{brand:e}):h("ui.providers.provider_detail.this_app_could_not_confirm_the_sign",{brand:e})))," ",h("ui.providers.provider_detail.the_sign_in_itself_finished_what_follows")]}):null,s?.trim()?c.jsx("p",{className:"min-w-0 whitespace-pre-wrap text-body-sm text-ink-muted [overflow-wrap:anywhere]","data-retained-notice":!0,children:s}):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:[h("ui.providers.provider_detail.default_model")," ",c.jsx("span",{className:"text-ink",children:n.model_name}),"."]}):null,i?c.jsxs(c.Fragment,{children:[" ",c.jsx(ce,{variant:"link",size:"sm",onClick:i,children:h("ui.providers.provider_detail.change")})]}):null]}):null,n&&!n.hosting&&n.receipt?c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("ui.providers.provider_detail.your_default_model_is_unchanged")}):null,r?c.jsxs("p",{className:d==="unchecked"?"text-body-sm text-ink-muted":"text-ink-dim text-meta",children:[h("ui.providers.provider_detail.saved_but_not_checked_yet"),r]}):null,c.jsx("div",{children:c.jsx(ce,{ref:g,variant:l?"primary":"secondary",size:"sm",onClick:o,children:a})})]})},Lnt=({provider:e,onConnected:t,onDone:n,onChangeModel:s,context:r="settings",readiness:i})=>{Ve();const a=Mt(),o=H8({retryOnMount:!1}),{accountRead:l,unavailable:u}=wy({retryOnMount:!1}),d=U8(e.id,o,{accountRead:l,unavailable:u}),f=i!==void 0?i:d===null?null:VA(e,d),[p,g]=m.useState(null),[v,b]=m.useState(""),[x,_]=m.useState(!1),[w,y]=m.useState(()=>Lm(e.id).error),[S,C]=m.useState(()=>Lm(e.id).saved),E=m.useCallback(se=>{"saved"in se&&C(se.saved??null),"error"in se&&y(se.error??null),Fnt(e.id,se)},[e.id]),[k,F]=m.useState(""),[A,I]=m.useState(null),N=ra(e),P=e.auth_methods.find(se=>se.method_id===p)??Bre(e.auth_methods),M=m.useCallback(()=>{a.invalidateQueries({queryKey:No.providers}),a.invalidateQueries({queryKey:No.catalogue}),e.id==="radient"&&jre(a),a.invalidateQueries({queryKey:["config"]}),a.invalidateQueries({queryKey:Hre}),t?.()},[a,t,e.id]),Y=KU(),O=m.useCallback(async(se,he,xe)=>{const Je=async()=>{await a.invalidateQueries({queryKey:["config"]}),await a.invalidateQueries({queryKey:["desktop","session-preview"]})};try{if(he!==void 0){await Je();return}const pe=await rt({op:"config.get"});if(await Je(),pe?.values?.hosting)return;let Xe=$R(se);if(Xe.length===0&&(await th.getState().fetchModels(Zs.baseUrl,!0),Xe=$R(se)),Xe.length===0)return;const le=(xe||"").trim()||Xe.find(Qe=>Qe.recommended)?.id||Xe[0].id;await Y.mutateAsync({hosting:se,model_name:le}),await Je()}catch{}},[a,Y]),X=m.useRef(O);X.current=O;const Q=m.useRef(M);Q.current=M;const{flow:ie,state:G}=Nnt(e.id,()=>({start:se=>rt({op:"auth.start",provider:se}),read:se=>rt({op:"auth.status",id:se}),cancel:se=>rt({op:"auth.cancel",id:se}),open:(se,he)=>tZ(se,he),poll:qre,onSucceeded:se=>{Q.current(),X.current(e.id,se.defaults_applied,e.suggested_model?.id)}})),ne=m.useRef(null);m.useEffect(()=>{const se=ne.current!==null,he=ne.current!==e.id;ne.current=e.id,se&&he&&(g(null),b(""),y(Lm(e.id).error),C(Lm(e.id).saved))},[e.id]);const oe=se=>{g(se),E({error:null}),C(null),ie.reset()},B=m.useCallback(async()=>{const se=G.operation;if(!(!se?.prompt_id||!k)){I(null);try{await rt({op:"auth.input",id:se.id,promptId:se.prompt_id,value:k}),F("")}catch(he){I(he instanceof Error?he.message:h("ui.providers.provider_detail.the_code_was_not_accepted"))}}},[G.operation,k]),H=m.useCallback(async()=>{if(!(!P||!v.trim())){_(!0),E({error:null});try{const se=await rt({op:"auth.key",provider:P.id,value:v.trim()})??{};b(""),E({saved:se}),M(),X.current(e.id,se?.defaults_applied,e.suggested_model?.id)}catch(se){E({error:se instanceof Fi||se instanceof Error?se.message:h("ui.providers.provider_detail.the_key_could_not_be_saved")})}finally{_(!1)}}},[P,v,M,E,e.id,e.suggested_model?.id]),U=r==="dialog"?h("ui.providers.provider_detail.continue"):h("ui.providers.provider_detail.done"),z=()=>{Dnt(e.id),C(null),ie.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:[h("ui.providers.provider_detail.runs_on_this_computer_and_needs_no"),N,h("ui.providers.provider_detail.then_check_the_connection")]}),c.jsx(Pnt,{provider:e})]});if(!P)return c.jsx(Rr,{variant:"warning",children:h("ui.providers.provider_detail.this_provider_has_no_supported_sign_in")});const te=e.auth_methods.find(se=>se.kind==="api_key"),fe=G.operation,J=`key-help-${e.id}`,Se=e.auth_methods.length>1&&G.phase!=="settled"?c.jsx(R5,{value:P.method_id,onValueChange:oe,children:c.jsx(A5,{"aria-label":h("ui.providers.provider_detail.how_to_connect"),children:e.auth_methods.map(se=>c.jsx(rE,{value:se.method_id,children:Ure(se)},se.method_id))})}):null;if(P.kind==="api_key")return S?c.jsxs("div",{className:"flex flex-col gap-4",children:[Se,c.jsx(Yj,{brand:N,verb:"Connected",defaults:S.defaults_applied,unverified:S.valid===!0?null:S.reason??h("ui.providers.provider_detail.this_local_operator_does_not_check_keys"),tone:S.valid===!0?"success":"unchecked",headline:S.valid===!0?void 0:h("ui.providers.provider_detail.key_saved",{brand:N}),onChangeModel:s,actionLabel:U,onAction:z,primaryAction:r==="dialog",verdict:f})]}):c.jsxs("div",{className:"flex flex-col gap-4",children:[Se,c.jsxs("div",{className:"flex flex-col gap-2","data-sign-in-state":"api-key",children:[c.jsx(dr,{htmlFor:`key-${e.id}`,children:h("ui.providers.provider_catalog.api_key")}),c.jsx(Kj,{id:`key-${e.id}`,value:v,onChange:se=>{b(se),E({error:null})},label:h("ui.providers.provider_detail.api_key_variant_215",{brand:N}),invalid:w!==null,describedBy:J}),c.jsx("p",{id:J,className:w?"text-danger text-meta":"text-ink-dim text-meta",role:w?"alert":void 0,children:w??(e.has_credential?h("ui.providers.provider_detail.a_key_is_saved_paste_a_new",{brand:N}):h("ui.providers.provider_detail.stored_encrypted_on_this_computer_billed_per",{brand:N}))}),c.jsx("div",{children:c.jsxs(ce,{variant:"primary",size:"sm",disabled:!v.trim()||x,onClick:()=>void H(),children:[x?c.jsx(On,{size:"sm"}):null,x?h("ui.providers.provider_detail.checking_key"):h("ui.providers.provider_detail.save_key")]})})]})]});const W=()=>void ie.start(P.id),Ce=Gre(fe?.auth_url),K=fe?j8(fe):null,me=fe?Vre(fe.expires_in):null,Ee=fe?.input_optional??(P.paste_fallback&&!P.requires_secret_input);let Ae;if(G.phase==="idle")Ae=c.jsxs("div",{className:"flex flex-col items-start gap-3","data-sign-in-state":"idle",children:[e.configured&&f?.group==="Needs sign-in"?c.jsxs(Rr,{variant:f.tone==="attention"?"warning":"neutral",children:[c.jsx(fN,{children:f.label}),c.jsx(pN,{children:f.detail??h("ui.providers.provider_detail.is_no_longer_accepting_the_sign_in",{brand:N})})]}):null,c.jsxs("p",{className:"text-body-sm text-ink-muted",children:[Wre(P,e)," ",P.kind==="device"?h("ui.providers.provider_detail.you_ll_get_a_code_to_enter"):h("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:W,children:[P.kind==="device"?h("ui.providers.provider_detail.get_a_sign_in_code"):h("ui.providers.provider_detail.continue_in_browser"),P.kind==="device"?null:c.jsx(wu,{"aria-hidden":"true"})]})})]});else if(G.phase==="starting"||G.phase==="active"&&fe&&!fe.auth_url&&!K&&!(fe.input_required&&!Ee))Ae=c.jsxs("div",{className:"flex items-center gap-3","data-sign-in-state":"starting",children:[c.jsx(On,{size:"sm"}),c.jsx("output",{className:"text-body-sm text-ink-muted",children:P.kind==="device"?h("ui.providers.provider_detail.getting_a_code"):h("ui.providers.provider_detail.opening_your_browser")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void ie.cancel(),children:h("ui.providers.provider_detail.cancel")})]});else if(G.phase==="active"&&fe&&K){const se=fe.auth_url;Ae=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:[h("ui.providers.provider_detail.enter_this_code"),Ce?h("ui.providers.provider_detail.at_variant_248",{host:Ce}):h("ui.providers.provider_detail.on_the_sign_in_page"),h("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:K})}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx(m_,{value:K,label:se?h("ui.providers.provider_detail.copy_code_and_open_page"):h("ui.providers.provider_detail.copy_code"),variant:"primary",onCopied:()=>{se&&ie.reopen()}}),se?c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void ie.reopen(),children:[c.jsx(wu,{"aria-hidden":"true"}),G.opened?h("ui.providers.provider_detail.open_browser_again"):h("ui.providers.provider_detail.open_sign_in_page")]}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void ie.cancel(),children:h("ui.providers.provider_detail.cancel")})]}),me?c.jsx("p",{className:"text-ink-dim text-meta",children:h("ui.providers.provider_detail.code_expiry",{minutes:me})}):null]})}else if(G.phase==="active"&&fe){const se=he=>fe.input_required?c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx(dr,{htmlFor:`prompt-${fe.id}`,children:Ce?h("ui.providers.provider_detail.code_from",{host:Ce}):h("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(Kj,{id:`prompt-${fe.id}`,value:k,onChange:xe=>{F(xe),I(null)},label:h("ui.providers.provider_detail.sign_in_code"),invalid:A!==null})}),c.jsx(ce,{variant:he?"primary":"secondary",size:"md",disabled:!k,onClick:()=>void B(),children:h("ui.providers.provider_detail.continue")})]}),A?c.jsx("p",{className:"text-danger text-meta",role:"alert",children:A}):null]}):null;fe.input_required&&!Ee?Ae=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:[h("ui.providers.provider_detail.paste_the_code"),Ce??h("ui.providers.provider_detail.the_provider")," ",h("ui.providers.provider_detail.shows_after_you_approve")]}),c.jsx("div",{className:"w-full",children:se(!0)}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>void ie.reopen(),children:[c.jsx(wu,{"aria-hidden":"true"}),G.opened?h("ui.providers.provider_detail.open_browser_again"):h("ui.providers.provider_detail.open_sign_in_page")]}),fe.auth_url?c.jsx(m_,{value:fe.auth_url,label:h("ui.providers.provider_detail.copy_link")}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void ie.cancel(),children:h("ui.providers.provider_detail.cancel")})]})]}):Ae=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(On,{size:"sm"}),c.jsx("output",{className:"text-body text-ink",children:h("ui.providers.provider_detail.finish_signing_in_with_your_browser")})]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:G.opened?h("ui.providers.provider_detail.we_opened_approve_access_there_and_this",{host:Ce??h("ui.providers.provider_detail.the_sign_in_page")}):G.openFailed?h("ui.providers.provider_detail.your_browser_didn_t_open_open_the"):h("ui.providers.provider_detail.opening_approve_access_there_and_this_page",{host:Ce??h("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 ie.reopen(),children:[c.jsx(wu,{"aria-hidden":"true"}),G.opened?h("ui.providers.provider_detail.open_browser_again"):h("ui.providers.provider_detail.open_sign_in_page")]}),fe.auth_url?c.jsx(m_,{value:fe.auth_url,label:h("ui.providers.provider_detail.copy_link")}):null,c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>void ie.cancel(),children:h("ui.providers.provider_detail.cancel")})]}),me?c.jsx("p",{className:"text-ink-dim text-meta",children:h("ui.providers.provider_detail.link_expiry",{minutes:me})}):null,fe.input_required?c.jsx(Uh,{summary:h("ui.providers.provider_detail.browser_showed_a_code_paste_it_here"),className:"w-full",children:c.jsx("div",{className:"pt-2",children:se(!1)})}):null]})}else if(G.phase==="settled"&&fe?.state==="succeeded")Ae=c.jsx(Yj,{brand:N,verb:"Signed in to",defaults:fe.defaults_applied,retainedNotice:e.id==="radient"&&fe.provider==="radient"?fe.retained_notice:void 0,onChangeModel:s,actionLabel:e.id==="radient"&&f?.group==="Needs sign-in"?"Sign in again":U,onAction:e.id==="radient"&&f?.group==="Needs sign-in"?W:z,primaryAction:r==="dialog",verdict:f});else{const se=fe?$re(fe,N):G.error??h("ui.providers.provider_detail.didn_t_confirm_the_sign_in",{brand:N});Ae=c.jsxs("div",{className:"flex flex-col gap-3","data-sign-in-state":"unfinished",children:[c.jsxs(Rr,{variant:fe?.state==="cancelled"?"neutral":"warning",children:[c.jsx(fN,{children:h("ui.providers.provider_detail.sign_in_didn_t_finish")}),c.jsx(pN,{children:se})]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs(ce,{variant:"secondary",size:"sm",onClick:W,children:[c.jsx(zre,{"aria-hidden":"true"}),h("ui.providers.provider_detail.try_again")]}),te?c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>oe(te.method_id),children:h("ui.providers.provider_detail.use_an_api_key_instead")}):null]})]})}return c.jsxs("div",{className:"flex flex-col gap-4",children:[Se,Ae,e.id==="radient"&&e.has_credential?c.jsx(Ent,{offerSignIn:!1}):null]})},Bnt=()=>h("ui.providers.provider_catalog.one_browser_sign_in_nothing_to_paste");function jnt(e){const t=e.find(n=>n.id===tie);return t===void 0?null:VA(t).group==="Needs sign-in"?t:null}function Hnt(e,t){return t!==null&&e===t}function Unt(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 Xj=({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:iie(ra(e))}),Px=({children:e,label:t})=>(Ve(),c.jsx("ul",{"aria-label":t,className:"flex flex-col divide-y divide-hairline overflow-hidden rounded-[14px] bg-surface",children:e})),XK=({onConnected:e,initialProviderId:t=null,context:n="settings",featuredOnly:s=!1,focusGroup:r=null,onDone:i,onChangeModel:a})=>{Ve();const o=Pv(!0),{hosting:l,model:u}=G8(),d=Mt(),f=H8(),{accountRead:p,unavailable:g}=wy(),[v,b]=m.useState(t),x=m.useCallback(()=>{a?.(),requestAnimationFrame(()=>{document.getElementById("model-settings")?.focus?.({preventScroll:!0})})},[a]);m.useEffect(()=>{t&&b(t)},[t]);const[_,w]=m.useState(""),[y,S]=m.useState(null),C=m.useRef(null),E=m.useRef(null),k=m.useRef(new Map),F=m.useMemo(()=>o.data??[],[o.data]),A=m.useMemo(()=>Yre(F,l),[F,l]),I=m.useMemo(()=>Xre(F,l,_),[F,l,_]),N=jnt(F)?.id??null,[P,M]=m.useState(null);m.useEffect(()=>{if(P===null)return;const W=K=>K?.isConnected?K:null,Ce=W(k.current.get(P))??W(C.current)??W(E.current);M(null),Ce?.focus()},[P]),m.useEffect(()=>{v!==null&&k.current.get(v)?.closest("li")?.scrollIntoView({block:"nearest"})},[v,A.length]);const Y=W=>{v===W?(b(null),M(W)):b(W)},O=()=>{const W=v;b(null),W&&M(W),i?.()};m.useEffect(()=>{if(v===null)return;const W=Ce=>{Ce.key!=="Escape"||Ce.defaultPrevented||Ce.target?.closest('[role="menu"], [role="dialog"], [role="listbox"]')||O()};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)});const X=()=>{d.invalidateQueries({queryKey:No.providers}),d.invalidateQueries({queryKey:oie})},Q=async W=>{const Ce=W.suggested_model;try{await aie.updateConfig("",{hosting:W.id,model_name:Ce?.id??""}),X()}catch(K){nn(K instanceof Error?K.message:h("ui.providers.provider_grid.the_default_was_not_changed"))}},ie=async W=>{S(null);try{await rt({op:"auth.logout",provider:W.id}),await d.invalidateQueries({queryKey:No.providers}),e?.()}catch(Ce){nn(Ce instanceof Error?Ce.message:h("ui.providers.provider_grid.sign_out_did_not_complete"))}finally{M(W.id)}};if(o.isLoading)return c.jsx("div",{className:"flex h-40 items-center justify-center",children:c.jsx(On,{size:"lg",label:h("ui.providers.provider_grid.loading_providers")})});if(o.isError)return c.jsx(Rr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:Qre(o.error)}),c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0",onClick:()=>void o.refetch(),disabled:o.isFetching,children:o.isFetching?h("ui.providers.provider_grid.retrying"):h("ui.providers.provider_grid.retry")})]})});const G=(W,Ce)=>v===W.id?c.jsx("div",{className:"border-hairline border-t bg-surface px-4 py-4",children:c.jsx(Lnt,{provider:W,onConnected:e,onDone:O,onChangeModel:a,context:n,readiness:Ce})}):null,ne=W=>{const Ce=Hnt(W.id,N),K=W.suggested_model?.name,me=v===W.id;return c.jsxs("li",{"data-provider-id":W.id,"data-search-row":`providers.${W.id}`,"data-search-control":!0,children:[c.jsxs("div",{className:"flex min-h-14 items-center gap-3 px-4 py-2",children:[c.jsx(Xj,{provider:W}),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:[ra(W),Ce?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:h("ui.providers.provider_grid.recommended")})]}):null]}),c.jsxs("span",{className:"text-ink-muted text-meta",children:[Ce?Bnt():rie(W),K?c.jsxs("span",{className:"text-ink-dim",children:[" ",h("ui.providers.provider_grid.suggests"),K]}):null]})]}),c.jsx(ce,{ref:Ee=>{k.current.set(W.id,Ee)},variant:Ce&&!me&&v===null&&A.length===0?"primary":"secondary",size:"sm","aria-expanded":me,"aria-label":h("ui.providers.provider_grid.row_action",{action:me?h("ui.providers.provider_grid.close"):HN(W),brand:ra(W)}),onClick:()=>Y(W.id),children:me?h("ui.providers.provider_grid.close"):HN(W)})]}),G(W)]},W.id)},oe=W=>{const Ce=W.id===l,K=Ce?V8(W,u):W.suggested_model?.name??null,me=v===W.id,Ee=U8(W.id,f,{accountRead:p,unavailable:g}),Ae=Ee===null?null:VA(W,Ee),se=nie(W,K,Ae?.label??null);return c.jsxs("li",{"data-provider-id":W.id,"data-search-row":`providers.${W.id}`,"data-search-control":!0,children:[c.jsxs("div",{className:"flex min-h-14 items-center gap-3 px-4 py-2",children:[c.jsx(Xj,{provider:W}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsx("span",{className:"text-body text-ink",children:ra(W)}),c.jsx("span",{className:`truncate text-meta ${Ae?.tone==="attention"?"text-warning":"text-ink-muted"}`,title:Ae?.detail,"data-claim":Ee===null?"withheld":void 0,"data-claim-tone":Ae?.tone,children:se??" "})]}),Ce?c.jsx("span",{className:"text-ink-muted text-meta",children:h("ui.providers.provider_grid.default")}):null,y===W.id?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("span",{className:"text-body-sm text-ink",children:[h("ui.providers.provider_grid.sign_out_of"),ra(W),"?"]}),c.jsx(ce,{variant:"danger",size:"sm",onClick:()=>void ie(W),children:h("ui.providers.provider_grid.sign_out")}),c.jsx(ce,{variant:"ghost",size:"sm",onClick:()=>{S(null),M(W.id)},children:h("ui.providers.provider_grid.keep")})]}):c.jsxs(Po,{children:[c.jsx(eo,{asChild:!0,children:c.jsx(ce,{ref:he=>{k.current.set(W.id,he)},variant:"ghost",size:"icon-sm",className:me?"bg-control text-on-accent":void 0,"aria-expanded":me,"aria-label":h("ui.providers.provider_grid.manage",{brand:ra(W)}),children:c.jsx(oc,{"aria-hidden":"true"})})}),c.jsxs(Mo,{align:"end",onCloseAutoFocus:he=>he.preventDefault(),children:[Ce?null:c.jsx(Jt,{onSelect:()=>void Q(W),children:h("ui.providers.provider_grid.make_default")}),Ce&&a?c.jsx(Jt,{onClick:()=>x(),onSelect:()=>x(),children:h("ui.providers.provider_grid.change_model")}):null,c.jsx(Jt,{onSelect:()=>Y(W.id),"data-panel-toggle":W.id,children:me?h("ui.providers.provider_grid.close"):W.local?h("ui.providers.provider_grid.check_connection"):sie(W)==="key"?h("ui.providers.provider_grid.replace_key"):h("ui.providers.provider_grid.sign_in_again")}),!W.local&&W.stored_credentials>0?c.jsxs(c.Fragment,{children:[c.jsx(Nr,{}),c.jsx(Jt,{destructive:!0,onSelect:()=>S(W.id),children:h("ui.providers.provider_grid.sign_out_variant_351")})]}):null]})]})]}),me?G(W,Ae):null]},W.id)},B=s?Jre:Zre,H=B.every(W=>I[W].length===0),U=c.jsxs("div",{className:"relative w-full sm:w-64",children:[c.jsx(_h,{size:16,className:"pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-ink-dim","aria-hidden":"true"}),c.jsx(bs,{ref:C,value:_,onChange:W=>w(W.target.value),placeholder:h("ui.providers.provider_grid.search_providers"),"aria-label":h("ui.providers.provider_grid.search_providers"),className:"pl-9"})]}),z=h("ui.providers.provider_grid.no_providers_match_this_search"),te=h("ui.providers.provider_grid.the_matching_providers_are_in_the_suggested"),fe=h("ui.providers.provider_grid.the_matching_providers_are_in_the_connected"),J=(W,Ce)=>Ce?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:Ce}),c.jsxs(ce,{variant:"secondary",size:"sm",onClick:()=>{w(""),C.current?.focus()},children:[c.jsx(Xn,{"aria-hidden":"true"}),h("ui.providers.provider_grid.clear_search")]})]}):B.map(K=>W[K].length>0?c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("h4",{className:"text-ink-dim text-meta",children:jN[K]}),c.jsx(Px,{label:jN[K],children:W[K].map(ne)})]},K):null),Se=J(I,H?z:null);if(s){const W=new Set(Unt(F,_).map(he=>he.id)),Ce=bE.map(he=>F.find(xe=>xe.id===he)).filter(he=>he!==void 0&&!A.some(xe=>xe.id===he.id)&&W.has(he.id)),K=new Set(bE.filter(he=>F.some(xe=>xe.id===he))),me={subscription:I.subscription.filter(he=>!K.has(he.id)),key:I.key.filter(he=>!K.has(he.id)),local:I.local.filter(he=>!K.has(he.id))},Ee=B.reduce((he,xe)=>he+me[xe].length,0),Ae=_.trim().length>0,se=Ae?W.size===0?z:Ee===0?Ce.length>0?te: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(Px,{label:h("ui.providers.provider_grid.connected"),children:A.map(oe)}):null,Ce.length>0?c.jsx(Px,{label:h("ui.providers.provider_grid.suggested_providers"),children:Ce.map(ne)}):null,Ae||Ee>0?c.jsx(Uh,{summary:eie(me,B),defaultOpen:r!==null||t!==null,chevron:"trailing",children:c.jsxs("div",{className:"flex flex-col gap-4 pt-3",children:[U,J(me,se)]})}):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:h("ui.providers.provider_grid.connected")}),c.jsx(Px,{children:A.map(oe)})]}):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?h("ui.providers.provider_grid.add_a_provider"):h("ui.providers.provider_grid.connect_a_provider")}),U]}),Se]})]})},Gnt=({onContinue:e})=>c.jsxs("div",{className:"flex flex-col gap-5",children:[c.jsx("p",{className:"text-body text-ink-muted",children:h("ui.onboarding.connect.intro")}),c.jsx(XK,{context:"dialog",featuredOnly:!0,onDone:e,onChangeModel:e})]});function Qj(e){for(const t of bE){const n=e.find(s=>s.id===t);if(n)return n}return e[0]??null}function Vnt(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&&lie(a,null)),s=n.filter(a=>a.suggested_model),r=Qj(s);if(r?.suggested_model)return{kind:"proposed",provider:r,model:r.suggested_model};const i=Qj(n);return i?{kind:"choose",provider:i}:{kind:"none"}}const Wnt="ui.onboarding.default_model.block.pick_a_model",$nt="ui.onboarding.default_model.block.loading_models";function znt(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?h(Wnt):r.ready?null:h($nt):null,noCatalogue:d&&r.ready&&!u,modelToWrite:l}}const qnt=({choice:e,onChange:t})=>{if(e.kind==="none")return c.jsx(Rr,{variant:"neutral",children:h("ui.onboarding.default_model.none_connected")});if(e.kind==="choose")return c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("ui.onboarding.default_model.connected_pick",{brand:ra(e.provider)})});const n=e.kind==="applied"?V8(e.provider,e.model)??h("ui.onboarding.default_model.fallback_name",{brand:e.provider?ra(e.provider):e.hosting}):e.model.name,s=e.kind==="applied"?e.provider?ra(e.provider):e.hosting:ra(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"?h("ui.onboarding.default_model.tag.applied"):h("ui.onboarding.default_model.tag.suggested")]}),c.jsx("div",{className:"pt-2",children:c.jsx(ce,{variant:"secondary",size:"sm",onClick:t,children:h("ui.onboarding.default_model.change")})})]})},Knt=({onBeforeContinue:e,onBlockReason:t})=>{const n=Pv(!0),s=G8(),r=KU(),[i,a]=m.useState(!1),o=n.isLoading||s.isLoading?null:Vnt(n.data??[],s),{refreshModels:l}=UA();m.useEffect(()=>{l()},[]);const u=th(C=>C.isInitialized),d=th(C=>C.models),f=m.useMemo(()=>{const C=new Set;for(const E of d)C.add(E.provider);return[...C]},[d]),p=m.useMemo(()=>znt({choice:o,hosting:s.hosting,model:s.model,catalogue:{ready:u,providers:f}}),[o,s.hosting,s.model,u,f]),{shownProvider:g,write:v,block:b,noCatalogue:x,modelToWrite:_}=p,w=m.useCallback(C=>{const E=th.getState().models.filter(k=>k.provider===C);return E.find(k=>k.info?.recommended)?.id??E[0]?.id},[]),y=(n.data??[]).find(C=>C.id===g)??null;if(m.useEffect(()=>(e?.(v?async()=>{await r.mutateAsync(v)}:null),()=>e?.(null)),[e,v,r.mutateAsync]),m.useEffect(()=>{if(t)return t(b),()=>t(null)},[t,b]),o===null)return c.jsxs("div",{className:"flex items-center justify-center gap-3 py-8",children:[c.jsx(On,{size:"sm"}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("ui.onboarding.default_model.loading")})]});const S=c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsx(WK,{value:g,onSave:async C=>{const E=w(C);E&&await r.mutateAsync({hosting:C,model_name:E})},filterByCredentials:!0,allowCustom:!1,allowDefault:!1,emptyHelperText:h("ui.onboarding.default_model.empty_helper")}),c.jsx($K,{value:_,hostingId:g,onSave:async C=>{await r.mutateAsync({model_name:C})},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:h("ui.onboarding.default_model.intro")}),x?c.jsx("p",{className:"text-ink-dim text-meta",children:h("ui.onboarding.default_model.nothing_saved",{brand:y?ra(y):h("ui.onboarding.default_model.provider_fallback")})}):null,i||o.kind==="choose"?S:c.jsx(qnt,{choice:o,onChange:()=>a(!0)})]})};var QK=(e=>(e.Hosting="hosting",e.Search="search",e.Oauth="oauth",e))(QK||{});const Ynt=[{key:"RADIENT_API_KEY",name:"Radient Pass",get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_openai_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_openrouter_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_deepseek_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_mistral_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_kimi_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_alibaba_cloud_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_google_ai_studio_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_google_access_token")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_google_token_expiry_timestamp")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_google_refresh_token")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_anthropic_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_serp_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_tavily_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_brave_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_exa_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_parallel_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_perplexity_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_fal_api_key")},get description(){return h("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 h("ui.settings.integrations.credential_manifest.name_xai_api_key")},get description(){return h("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"}],Xnt=Ynt.filter(e=>e.type===QK.Search),Qnt="onboarding-search-mode",Jnt="onboarding-search-mode-free",Znt="onboarding-search-mode-keys",Jj="onboarding-search-mode-label",est=e=>`onboarding-search-key-${e.toLowerCase()}`,Zj=({id:e,title:t,recommended:n=!1,checked:s,onSelect:r,children:i})=>c.jsxs("label",{htmlFor:e,className:R("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:Qnt,className:"sr-only outline-none",checked:s,onChange:r}),c.jsx("span",{"aria-hidden":"true",className:R("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:R("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:R("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:h("ui.onboarding.search.recommended")})]}):null]}),c.jsx("span",{className:"text-body-sm text-ink-muted",children:i})]})]}),tst=({credential:e,showDescription:t,isStored:n,save:s})=>{const[r,i]=m.useState(""),[a,o]=m.useState(!1),[l,u]=m.useState(!1),[d,f]=m.useState(null),[p,g]=m.useState(null),v=est(e.key),b=n||l,x=async()=>{const _=r.trim();if(!(!_||a||_===d))try{o(!0),g(null),await s(e.key,_),f(_),u(!0)}catch(w){const y=w instanceof Error&&w.message?w.message:h("ui.onboarding.search.row.save_failed");g(h("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(dr,{htmlFor:v,children:e.name}),c.jsxs("span",{className:"flex items-center gap-2",children:[a?c.jsx(On,{size:"sm",label:h("ui.onboarding.search.row.saving",{name:e.name})}):null,b?c.jsx(Lu,{variant:"success",children:h("ui.onboarding.search.row.saved")}):null]})]}),c.jsx(bs,{id:v,inputSize:"lg",type:"password",value:r,onChange:_=>{i(_.target.value),u(!1),g(null)},onBlur:x,onKeyDown:_=>{_.key==="Enter"&&r.trim()&&!a&&x()},placeholder:h("ui.onboarding.search.row.placeholder"),disabled:a}),p?c.jsx("p",{className:"text-danger text-meta",role:"alert",children:p}):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:[h("ui.onboarding.search.row.get_your",{name:e.name}),c.jsx(wu,{size:12,"aria-hidden":"true"})]})]})},nst=({showCredentialDescription:e=!0})=>{const[t,n]=m.useState("free"),{data:s}=T8(),r=_fe(),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:h("ui.onboarding.search.intro")}),c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{id:Jj,className:"sr-only",children:h("ui.onboarding.search.mode.label")}),c.jsxs("div",{role:"radiogroup","aria-labelledby":Jj,className:"flex flex-col gap-2",children:[c.jsx(Zj,{id:Jnt,title:h("ui.onboarding.search.mode.free"),recommended:!0,checked:t==="free",onSelect:()=>n("free"),children:h("ui.onboarding.search.mode.free_detail")}),c.jsx(Zj,{id:Znt,title:h("ui.onboarding.search.mode.keys"),checked:t==="keys",onSelect:()=>n("keys"),children:h("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:h("ui.onboarding.search.each_key_saved")}),Xnt.map(o=>c.jsx(tst,{credential:o,showDescription:e,isStored:i.includes(o.key),save:a},o.key))]}):null]})},sst=({aidaName:e=null,oweGreeting:t=!0})=>c.jsxs("div",{className:"flex flex-col gap-8",children:[c.jsx(nst,{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:h("ui.onboarding.extras.next_meet",{name:e})}),c.jsx("p",{className:"text-body text-ink-muted",children:t?h("ui.onboarding.extras.greeting_owed",{name:e}):h("ui.onboarding.extras.greeting_done",{name:e})})]}):null]}),rst={[Qr.CONNECT_PROVIDER]:"ui.onboarding.modal.title.connect_provider",[Qr.DEFAULT_MODEL]:"ui.onboarding.modal.title.default_model",[Qr.EXTRAS]:"ui.onboarding.modal.title.extras"};function ist(e,t){return e===Qr.EXTRAS&&t?h("ui.onboarding.modal.title.extras_with_name",{name:t}):h(rst[e])}const bo=[Qr.CONNECT_PROVIDER,Qr.DEFAULT_MODEL,Qr.EXTRAS],ast={},ost=({open:e})=>{const{currentStep:t,setCurrentStep:n,completeModalOnboarding:s}=D0(),r=oi(),i=Pv(e),a=cie(i.data??[]),o=ss(),l=Et(o.data,"aida",1),u=fg(e&&l),d=l&&u.data?.enabled===!0,f=u.data?.name?.trim()||"Aida",p=uie(u.data),g=y2(),v=m.useMemo(()=>{const B=d?f:null;return Object.fromEntries(bo.map(H=>[H,ist(H,B)]))},[d,f]),[b,x]=m.useState(!1),_=m.useRef(null),[w,y]=m.useState(null),S=m.useCallback(B=>{y(B)},[]),[C,E]=m.useState(!1),k=C||b,F=m.useCallback(B=>{_.current=B},[]);m.useEffect(()=>{bo.includes(t)||n(Qr.CONNECT_PROVIDER)},[t,n]);const[A,I]=m.useState(new Set);m.useEffect(()=>{I(B=>{if(B.has(t))return B;const H=new Set(B);return H.add(t),H})},[t]);const N=v[t]??h("ui.onboarding.modal.title.fallback"),P=m.useCallback(()=>{s(),r("/chat")},[s,r]),M=m.useCallback(async()=>{x(!0);try{const B=await g("greet");if(s(),!B.session_id){r("/chat"),nn(h("ui.onboarding.modal.error.aida_open_failed",{name:f}));return}dg(r,B.session_id);const H=die(B,f);H&&da(H)}catch(B){s(),r("/chat");const H=hie(B,f);H?.kind==="info"?da(H.text):H&&nn(H.text)}finally{x(!1)}},[g,f,s,r]),Y=m.useCallback(async()=>{const B=bo.indexOf(t);if(t===Qr.DEFAULT_MODEL&&_.current){E(!0);try{await _.current()}catch{E(!1);return}E(!1)}B>=0&&B<bo.length-1?n(bo[B+1]):d?await M():P()},[t,n,P,d,M]),O=m.useCallback(()=>{const B=bo.indexOf(t);B>0&&n(bo[B-1])},[t,n]),X=m.useMemo(()=>{switch(t){case Qr.CONNECT_PROVIDER:return c.jsx(Gnt,{onContinue:()=>n(Qr.DEFAULT_MODEL)});case Qr.DEFAULT_MODEL:return c.jsx(Knt,{onBeforeContinue:F,onBlockReason:S});case Qr.EXTRAS:return c.jsx(sst,{aidaName:d?f:null,oweGreeting:p});default:return null}},[t,n,F,S,d,f,p]),Q=t===Qr.CONNECT_PROVIDER,ie=t===Qr.EXTRAS,G=mnt(t,w,k),ne=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:Q?c.jsx(ce,{variant:"ghost",size:"lg",onClick:P,children:h("ui.onboarding.modal.action.skip_for_now")}):c.jsx(ce,{variant:"secondary",size:"lg",onClick:O,children:h("ui.onboarding.modal.action.back")})}),c.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[ie?c.jsx(ce,{variant:"ghost",size:"lg",onClick:P,disabled:b,children:d?h("ui.onboarding.modal.action.skip_to_chat"):h("ui.onboarding.modal.action.skip")}):null,!Q||a?c.jsx(ce,{variant:"primary",size:"lg",onClick:()=>void Y(),disabled:G.primaryDisabled,children:ie?d?h("ui.onboarding.modal.action.meet",{name:f}):h("ui.onboarding.modal.action.finish"):h("ui.onboarding.modal.action.continue")}):null]})]})]}),oe=m.useMemo(()=>{if(!t)return null;const B=bo.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:B>=0?h("ui.onboarding.modal.step_of",{current:B+1,total:bo.length}):h("ui.onboarding.modal.steps_total",{total:bo.length})}),c.jsx("ol",{className:"flex items-center gap-1",children:bo.map((H,U)=>{const z=t===H,fe=A.has(H)&&!z,J=U<=B;return c.jsx("li",{className:"flex",children:c.jsx(vt,{content:v[H],children:c.jsx("button",{type:"button","aria-label":v[H],"aria-current":z?"step":void 0,"aria-disabled":!fe,onClick:()=>{fe&&n(H)},className:"flex h-4 w-4 items-center",children:c.jsx("span",{className:R("h-1 w-full rounded-xs transition-colors duration-base ease-out-quart",J?"bg-accent":"bg-control")})})})},H)})})]})},[t,A,n,v]);return c.jsx(gnt,{open:e,onDismiss:P,title:N,stepIndicators:oe,actions:ne,width:ast[t]??"single",children:X})};var e6={exports:{}},pm={};/**
@@ -691,7 +691,7 @@ If you are trying to annotate ${s} with application data, use the '${s}.context'
691
691
  *
692
692
  * This source code is licensed under the MIT license found in the
693
693
  * LICENSE file in the root directory of this source tree.
694
- */var t6;function lst(){if(t6)return pm;t6=1;var e=it,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,f={},p=null,g=null;u!==void 0&&(p=""+u),l.key!==void 0&&(p=""+l.key),l.ref!==void 0&&(g=l.ref);for(d in l)s.call(l,d)&&!i.hasOwnProperty(d)&&(f[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)f[d]===void 0&&(f[d]=l[d]);return{$$typeof:t,type:o,key:p,ref:g,props:f,_owner:r.current}}return pm.Fragment=n,pm.jsx=a,pm.jsxs=a,pm}var n6;function cst(){return n6||(n6=1,e6.exports=lst()),e6.exports}var ust=cst();/*! shepherd.js 14.5.0 */function dst(e){return e instanceof Element}function Qp(e){return e instanceof HTMLElement}function Qu(e){return typeof e=="function"}function Av(e){return typeof e=="string"}function ni(e){return e===void 0}class OD{on(t,n,s,r=!1){var i;return ni(this.bindings)&&(this.bindings={}),ni(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(ni(this.bindings)||ni(this.bindings[t]))return this;if(ni(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(!ni(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 $i(){return $i=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},$i.apply(null,arguments)}function LD(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 cd={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")};cd.defaultMerge;function hst(e,t){return t}function fst(e,t){return e.filter(n=>n!==void 0)}var s6;(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"})(s6||(s6={}));function r6(e){return typeof e!="object"||e===null?0:Array.isArray(e)?2:mst(e)?1:e instanceof Set?3:e instanceof Map?4:5}function pst(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 gst(e,t){return typeof e=="object"&&Object.prototype.propertyIsEnumerable.call(e,t)}function JK(e){return{*[Symbol.iterator](){for(const t of e)for(const n of t)yield n}}}const i6=new Set(["[object Object]","[object Module]"]);function mst(e){if(!i6.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"||!i6.has(Object.prototype.toString.call(n))||!n.hasOwnProperty("isPrototypeOf"))}function vst(e,t,n){const s={};for(const r of pst(e)){const i=[];for(const l of e)gst(l,r)&&i.push(l[r]);if(i.length===0)continue;const a=t.metaDataUpdater(n,{key:r,parents:e}),o=ZK(i,t,a);o!==cd.skip&&(r==="__proto__"?Object.defineProperty(s,r,{value:o,configurable:!0,enumerable:!0,writable:!0}):s[r]=o)}return s}function bst(e){return e.flat()}function xst(e){return new Set(JK(e))}function _st(e){return new Map(JK(e))}function wst(e){return e.at(-1)}const Mx={mergeRecords:vst,mergeArrays:bst,mergeSets:xst,mergeMaps:_st,mergeOthers:wst};function BD(...e){return yst({})(...e)}function yst(e,t){const n=Cst(e,s);function s(...r){return ZK(r,n,t)}return s}function Cst(e,t){var n,s,r;return{defaultMergeFunctions:Mx,mergeFunctions:$i({},Mx,Object.fromEntries(Object.entries(e).filter(([i,a])=>Object.hasOwn(Mx,i)).map(([i,a])=>a===!1?[i,Mx.mergeOthers]:[i,a]))),metaDataUpdater:(n=e.metaDataUpdater)!=null?n:hst,deepmerge:t,useImplicitDefaultMerging:(s=e.enableImplicitDefaultMerging)!=null?s:!1,filterValues:e.filterValues===!1?void 0:(r=e.filterValues)!=null?r:fst,actions:cd}}function ZK(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 Gk(r,t,n);const i=r6(r[0]);if(i!==0&&i!==5){for(let a=1;a<r.length;a++)if(r6(r[a])!==i)return Gk(r,t,n)}switch(i){case 1:return Sst(r,t,n);case 2:return kst(r,t,n);case 3:return Est(r,t,n);case 4:return Tst(r,t,n);default:return Gk(r,t,n)}}function Sst(e,t,n){const s=t.mergeFunctions.mergeRecords(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(e,t,n):s}function kst(e,t,n){const s=t.mergeFunctions.mergeArrays(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(e):s}function Est(e,t,n){const s=t.mergeFunctions.mergeSets(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(e):s}function Tst(e,t,n){const s=t.mergeFunctions.mergeMaps(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(e):s}function Gk(e,t,n){const s=t.mergeFunctions.mergeOthers(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(e):s}function jD(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 Rst(e,t){return n=>{if(e.isOpen()){const s=e.el&&n.currentTarget===e.el;(!ni(t)&&n.currentTarget.matches(t)||s)&&e.tour.next()}}}function Ast(e){const{event:t,selector:n}=e.options.advanceOn||{};if(t){const s=Rst(e,n);let r=null;if(!ni(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 Fst{constructor(t){}}class Dst{constructor(t,n){}}function eY(e){return!Av(e)||e===""?"":e.charAt(e.length-1)!=="-"?`${e}-`:e}function Ist(e){const t=e.options.attachTo||{},n=Object.assign({},t);if(Qu(n.element)&&(n.element=n.element.call(e)),Av(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 Nst(e){return e.options.extraHighlights?e.options.extraHighlights.flatMap(t=>Array.from(document.querySelectorAll(t))):[]}function tY(e){return e==null?!0:!e.element||!e.on}function nY(){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 Pst=["top","right","bottom","left"],a6=["start","end"],o6=Pst.reduce((e,t)=>e.concat(t,t+"-"+a6[0],t+"-"+a6[1]),[]),Jp=Math.min,mh=Math.max,sy=Math.round,Ox=Math.floor,_l=e=>({x:e,y:e}),Mst={left:"right",right:"left",bottom:"top",top:"bottom"},Ost={start:"end",end:"start"};function qR(e,t,n){return mh(e,Jp(t,n))}function jh(e,t){return typeof e=="function"?e(t):e}function Sc(e){return e.split("-")[0]}function bc(e){return e.split("-")[1]}function HD(e){return e==="x"?"y":"x"}function UD(e){return e==="y"?"height":"width"}function Zp(e){return["top","bottom"].includes(Sc(e))?"y":"x"}function GD(e){return HD(Zp(e))}function sY(e,t,n){n===void 0&&(n=!1);const s=bc(e),r=GD(e),i=UD(r);let a=r==="x"?s===(n?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=iy(a)),[a,iy(a)]}function Lst(e){const t=iy(e);return[ry(e),t,ry(t)]}function ry(e){return e.replace(/start|end/g,t=>Ost[t])}function Bst(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 jst(e,t,n,s){const r=bc(e);let i=Bst(Sc(e),n==="start",s);return r&&(i=i.map(a=>a+"-"+r),t&&(i=i.concat(i.map(ry)))),i}function iy(e){return e.replace(/left|right|bottom|top/g,t=>Mst[t])}function Hst(e){return $i({top:0,right:0,bottom:0,left:0},e)}function rY(e){return typeof e!="number"?Hst(e):{top:e,right:e,bottom:e,left:e}}function ay(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 Ust=["crossAxis","alignment","allowedPlacements","autoAlignment"],Gst=["mainAxis","crossAxis","fallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment"],Vst=["mainAxis","crossAxis","limiter"];function l6(e,t,n){let{reference:s,floating:r}=e;const i=Zp(t),a=GD(t),o=UD(a),l=Sc(t),u=i==="y",d=s.x+s.width/2-r.width/2,f=s.y+s.height/2-r.height/2,p=s[o]/2-r[o]/2;let g;switch(l){case"top":g={x:d,y:s.y-r.height};break;case"bottom":g={x:d,y:s.y+s.height};break;case"right":g={x:s.x+s.width,y:f};break;case"left":g={x:s.x-r.width,y:f};break;default:g={x:s.x,y:s.y}}switch(bc(t)){case"start":g[a]-=p*(n&&u?-1:1);break;case"end":g[a]+=p*(n&&u?-1:1);break}return g}const Wst=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:f}=l6(u,s,l),p=s,g={},v=0;for(let b=0;b<o.length;b++){const{name:x,fn:_}=o[b],{x:w,y,data:S,reset:C}=await _({x:d,y:f,initialPlacement:s,placement:p,strategy:r,middlewareData:g,rects:u,platform:a,elements:{reference:e,floating:t}});d=w??d,f=y??f,g=$i({},g,{[x]:$i({},g[x],S)}),C&&v<=50&&(v++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(u=C.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):C.rects),{x:d,y:f}=l6(u,p,l)),b=-1)}return{x:d,y:f,placement:p,strategy:r,middlewareData:g}};async function VD(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:f="floating",altBoundary:p=!1,padding:g=0}=jh(t,e),v=rY(g),b=o[p?f==="floating"?"reference":"floating":f],x=ay(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:u,rootBoundary:d,strategy:l})),_=f==="floating"?{x:s,y:r,width:a.floating.width,height:a.floating.height}:a.reference,w=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),y=await(i.isElement==null?void 0:i.isElement(w))?await(i.getScale==null?void 0:i.getScale(w))||{x:1,y:1}:{x:1,y:1},S=ay(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:_,offsetParent:w,strategy:l}):_);return{top:(x.top-S.top+v.top)/y.y,bottom:(S.bottom-x.bottom+v.bottom)/y.y,left:(x.left-S.left+v.left)/y.x,right:(S.right-x.right+v.right)/y.x}}const $st=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}=jh(e,t)||{};if(u==null)return{};const f=rY(d),p={x:n,y:s},g=GD(r),v=UD(g),b=await a.getDimensions(u),x=g==="y",_=x?"top":"left",w=x?"bottom":"right",y=x?"clientHeight":"clientWidth",S=i.reference[v]+i.reference[g]-p[g]-i.floating[v],C=p[g]-i.reference[g],E=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let k=E?E[y]:0;(!k||!await(a.isElement==null?void 0:a.isElement(E)))&&(k=o.floating[y]||i.floating[v]);const F=S/2-C/2,A=k/2-b[v]/2-1,I=Jp(f[_],A),N=Jp(f[w],A),P=I,M=k-b[v]-N,Y=k/2-b[v]/2+F,O=qR(P,Y,M),X=!l.arrow&&bc(r)!=null&&Y!==O&&i.reference[v]/2-(Y<P?I:N)-b[v]/2<0,Q=X?Y<P?Y-P:Y-M:0;return{[g]:p[g]+Q,data:$i({[g]:O,centerOffset:Y-O-Q},X&&{alignmentOffset:Q}),reset:X}}});function zst(e,t,n){return(e?[...n.filter(s=>bc(s)===e),...n.filter(s=>bc(s)!==e)]:n.filter(s=>Sc(s)===s)).filter(s=>e?bc(s)===e||(t?ry(s)!==s:!1):!0)}const qst=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=jh(e,t),{crossAxis:f=!1,alignment:p,allowedPlacements:g=o6,autoAlignment:v=!0}=d,b=LD(d,Ust),x=p!==void 0||g===o6?zst(p||null,v,g):g,_=await VD(t,b),w=((n=a.autoPlacement)==null?void 0:n.index)||0,y=x[w];if(y==null)return{};const S=sY(y,i,await(l.isRTL==null?void 0:l.isRTL(u.floating)));if(o!==y)return{reset:{placement:x[0]}};const C=[_[Sc(y)],_[S[0]],_[S[1]]],E=[...((s=a.autoPlacement)==null?void 0:s.overflows)||[],{placement:y,overflows:C}],k=x[w+1];if(k)return{data:{index:w+1,overflows:E},reset:{placement:k}};const F=E.map(I=>{const N=bc(I.placement);return[I.placement,N&&f?I.overflows.slice(0,2).reduce((P,M)=>P+M,0):I.overflows[0],I.overflows]}).sort((I,N)=>I[1]-N[1]),A=((r=F.filter(I=>I[2].slice(0,bc(I[0])?2:3).every(N=>N<=0))[0])==null?void 0:r[0])||F[0][0];return A!==o?{data:{index:w+1,overflows:E},reset:{placement:A}}:{}}}},Kst=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=jh(e,t),{mainAxis:f=!0,crossAxis:p=!0,fallbackPlacements:g,fallbackStrategy:v="bestFit",fallbackAxisSideDirection:b="none",flipAlignment:x=!0}=d,_=LD(d,Gst);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const w=Sc(r),y=Zp(o),S=Sc(o)===o,C=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=g||(S||!x?[iy(o)]:Lst(o)),k=b!=="none";!g&&k&&E.push(...jst(o,x,b,C));const F=[o,...E],A=await VD(t,_),I=[];let N=((s=i.flip)==null?void 0:s.overflows)||[];if(f&&I.push(A[w]),p){const O=sY(r,a,C);I.push(A[O[0]],A[O[1]])}if(N=[...N,{placement:r,overflows:I}],!I.every(O=>O<=0)){var P,M;const O=(((P=i.flip)==null?void 0:P.index)||0)+1,X=F[O];if(X)return{data:{index:O,overflows:N},reset:{placement:X}};let Q=(M=N.filter(ie=>ie.overflows[0]<=0).sort((ie,G)=>ie.overflows[1]-G.overflows[1])[0])==null?void 0:M.placement;if(!Q)switch(v){case"bestFit":{var Y;const ie=(Y=N.filter(G=>{if(k){const ne=Zp(G.placement);return ne===y||ne==="y"}return!0}).map(G=>[G.placement,G.overflows.filter(ne=>ne>0).reduce((ne,oe)=>ne+oe,0)]).sort((G,ne)=>G[1]-ne[1])[0])==null?void 0:Y[0];ie&&(Q=ie);break}case"initialPlacement":Q=o;break}if(r!==Q)return{reset:{placement:Q}}}return{}}}},Yst=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:r}=t,i=jh(e,t),{mainAxis:a=!0,crossAxis:o=!1,limiter:l={fn:_=>{let{x:w,y}=_;return{x:w,y}}}}=i,u=LD(i,Vst),d={x:n,y:s},f=await VD(t,u),p=Zp(Sc(r)),g=HD(p);let v=d[g],b=d[p];if(a){const _=g==="y"?"top":"left",w=g==="y"?"bottom":"right",y=v+f[_],S=v-f[w];v=qR(y,v,S)}if(o){const _=p==="y"?"top":"left",w=p==="y"?"bottom":"right",y=b+f[_],S=b-f[w];b=qR(y,b,S)}const x=l.fn($i({},t,{[g]:v,[p]:b}));return $i({},x,{data:{x:x.x-n,y:x.y-s}})}}},Xst=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}=jh(e,t),d={x:n,y:s},f=Zp(r),p=HD(f);let g=d[p],v=d[f];const b=jh(o,t),x=typeof b=="number"?{mainAxis:b,crossAxis:0}:$i({mainAxis:0,crossAxis:0},b);if(l){const y=p==="y"?"height":"width",S=i.reference[p]-i.floating[y]+x.mainAxis,C=i.reference[p]+i.reference[y]-x.mainAxis;g<S?g=S:g>C&&(g=C)}if(u){var _,w;const y=p==="y"?"width":"height",S=["top","left"].includes(Sc(r)),C=i.reference[f]-i.floating[y]+(S&&((_=a.offset)==null?void 0:_[f])||0)+(S?0:x.crossAxis),E=i.reference[f]+i.reference[y]+(S?0:((w=a.offset)==null?void 0:w[f])||0)-(S?x.crossAxis:0);v<C?v=C:v>E&&(v=E)}return{[p]:g,[f]:v}}}};function IC(){return typeof window<"u"}function Tg(e){return iY(e)?(e.nodeName||"").toLowerCase():"#document"}function fa(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Il(e){var t;return(t=(iY(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function iY(e){return IC()?e instanceof Node||e instanceof fa(e).Node:!1}function Oo(e){return IC()?e instanceof Element||e instanceof fa(e).Element:!1}function El(e){return IC()?e instanceof HTMLElement||e instanceof fa(e).HTMLElement:!1}function c6(e){return!IC()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof fa(e).ShadowRoot}function pb(e){const{overflow:t,overflowX:n,overflowY:s,display:r}=Lo(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&!["inline","contents"].includes(r)}function Qst(e){return["table","td","th"].includes(Tg(e))}function NC(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function WD(e){const t=$D(),n=Oo(e)?Lo(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 Jst(e){let t=Ju(e);for(;El(t)&&!eg(t);){if(WD(t))return t;if(NC(t))return null;t=Ju(t)}return null}function $D(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function eg(e){return["html","body","#document"].includes(Tg(e))}function Lo(e){return fa(e).getComputedStyle(e)}function PC(e){return Oo(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ju(e){if(Tg(e)==="html")return e;const t=e.assignedSlot||e.parentNode||c6(e)&&e.host||Il(e);return c6(t)?t.host:t}function aY(e){const t=Ju(e);return eg(t)?e.ownerDocument?e.ownerDocument.body:e.body:El(t)&&pb(t)?t:aY(t)}function Fv(e,t,n){var s;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=aY(e),i=r===((s=e.ownerDocument)==null?void 0:s.body),a=fa(r);if(i){const o=KR(a);return t.concat(a,a.visualViewport||[],pb(r)?r:[],o&&n?Fv(o):[])}return t.concat(r,Fv(r,[],n))}function KR(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function oY(e){const t=Lo(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const r=El(e),i=r?e.offsetWidth:n,a=r?e.offsetHeight:s,o=sy(n)!==i||sy(s)!==a;return o&&(n=i,s=a),{width:n,height:s,$:o}}function zD(e){return Oo(e)?e:e.contextElement}function Tp(e){const t=zD(e);if(!El(t))return _l(1);const n=t.getBoundingClientRect(),{width:s,height:r,$:i}=oY(t);let a=(i?sy(n.width):n.width)/s,o=(i?sy(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!o||!Number.isFinite(o))&&(o=1),{x:a,y:o}}const Zst=_l(0);function lY(e){const t=fa(e);return!$D()||!t.visualViewport?Zst:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function ert(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==fa(e)?!1:t}function Hh(e,t,n,s){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=zD(e);let a=_l(1);t&&(s?Oo(s)&&(a=Tp(s)):a=Tp(e));const o=ert(i,n,s)?lY(i):_l(0);let l=(r.left+o.x)/a.x,u=(r.top+o.y)/a.y,d=r.width/a.x,f=r.height/a.y;if(i){const p=fa(i),g=s&&Oo(s)?fa(s):s;let v=p,b=KR(v);for(;b&&s&&g!==v;){const x=Tp(b),_=b.getBoundingClientRect(),w=Lo(b),y=_.left+(b.clientLeft+parseFloat(w.paddingLeft))*x.x,S=_.top+(b.clientTop+parseFloat(w.paddingTop))*x.y;l*=x.x,u*=x.y,d*=x.x,f*=x.y,l+=y,u+=S,v=fa(b),b=KR(v)}}return ay({width:d,height:f,x:l,y:u})}function qD(e,t){const n=PC(e).scrollLeft;return t?t.left+n:Hh(Il(e)).left+n}function cY(e,t,n){n===void 0&&(n=!1);const s=e.getBoundingClientRect(),r=s.left+t.scrollLeft-(n?0:qD(e,s)),i=s.top+t.scrollTop;return{x:r,y:i}}function trt(e){let{elements:t,rect:n,offsetParent:s,strategy:r}=e;const i=r==="fixed",a=Il(s),o=t?NC(t.floating):!1;if(s===a||o&&i)return n;let l={scrollLeft:0,scrollTop:0},u=_l(1);const d=_l(0),f=El(s);if((f||!f&&!i)&&((Tg(s)!=="body"||pb(a))&&(l=PC(s)),El(s))){const g=Hh(s);u=Tp(s),d.x=g.x+s.clientLeft,d.y=g.y+s.clientTop}const p=a&&!f&&!i?cY(a,l,!0):_l(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+p.x,y:n.y*u.y-l.scrollTop*u.y+d.y+p.y}}function nrt(e){return Array.from(e.getClientRects())}function srt(e){const t=Il(e),n=PC(e),s=e.ownerDocument.body,r=mh(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),i=mh(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let a=-n.scrollLeft+qD(e);const o=-n.scrollTop;return Lo(s).direction==="rtl"&&(a+=mh(t.clientWidth,s.clientWidth)-r),{width:r,height:i,x:a,y:o}}function rrt(e,t){const n=fa(e),s=Il(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=$D();(!u||u&&t==="fixed")&&(o=r.offsetLeft,l=r.offsetTop)}return{width:i,height:a,x:o,y:l}}function irt(e,t){const n=Hh(e,!0,t==="fixed"),s=n.top+e.clientTop,r=n.left+e.clientLeft,i=El(e)?Tp(e):_l(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 u6(e,t,n){let s;if(t==="viewport")s=rrt(e,n);else if(t==="document")s=srt(Il(e));else if(Oo(t))s=irt(t,n);else{const r=lY(e);s={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return ay(s)}function uY(e,t){const n=Ju(e);return n===t||!Oo(n)||eg(n)?!1:Lo(n).position==="fixed"||uY(n,t)}function art(e,t){const n=t.get(e);if(n)return n;let s=Fv(e,[],!1).filter(o=>Oo(o)&&Tg(o)!=="body"),r=null;const i=Lo(e).position==="fixed";let a=i?Ju(e):e;for(;Oo(a)&&!eg(a);){const o=Lo(a),l=WD(a);!l&&o.position==="fixed"&&(r=null),(i?!l&&!r:!l&&o.position==="static"&&r&&["absolute","fixed"].includes(r.position)||pb(a)&&!l&&uY(e,a))?s=s.filter(u=>u!==a):r=o,a=Ju(a)}return t.set(e,s),s}function ort(e){let{element:t,boundary:n,rootBoundary:s,strategy:r}=e;const i=[...n==="clippingAncestors"?NC(t)?[]:art(t,this._c):[].concat(n),s],a=i[0],o=i.reduce((l,u)=>{const d=u6(t,u,r);return l.top=mh(d.top,l.top),l.right=Jp(d.right,l.right),l.bottom=Jp(d.bottom,l.bottom),l.left=mh(d.left,l.left),l},u6(t,a,r));return{width:o.right-o.left,height:o.bottom-o.top,x:o.left,y:o.top}}function lrt(e){const{width:t,height:n}=oY(e);return{width:t,height:n}}function crt(e,t,n){const s=El(t),r=Il(t),i=n==="fixed",a=Hh(e,!0,i,t);let o={scrollLeft:0,scrollTop:0};const l=_l(0);if(s||!s&&!i)if((Tg(t)!=="body"||pb(r))&&(o=PC(t)),s){const p=Hh(t,!0,i,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else r&&(l.x=qD(r));const u=r&&!s&&!i?cY(r,o):_l(0),d=a.left+o.scrollLeft-l.x-u.x,f=a.top+o.scrollTop-l.y-u.y;return{x:d,y:f,width:a.width,height:a.height}}function Vk(e){return Lo(e).position==="static"}function d6(e,t){if(!El(e)||Lo(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Il(e)===n&&(n=n.ownerDocument.body),n}function dY(e,t){const n=fa(e);if(NC(e))return n;if(!El(e)){let r=Ju(e);for(;r&&!eg(r);){if(Oo(r)&&!Vk(r))return r;r=Ju(r)}return n}let s=d6(e,t);for(;s&&Qst(s)&&Vk(s);)s=d6(s,t);return s&&eg(s)&&Vk(s)&&!WD(s)?n:s||Jst(e)||n}const urt=async function(e){const t=this.getOffsetParent||dY,n=this.getDimensions,s=await n(e.floating);return{reference:crt(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function drt(e){return Lo(e).direction==="rtl"}const hrt={convertOffsetParentRelativeRectToViewportRelativeRect:trt,getDocumentElement:Il,getClippingRect:ort,getOffsetParent:dY,getElementRects:urt,getClientRects:nrt,getDimensions:lrt,getScale:Tp,isElement:Oo,isRTL:drt};function frt(e,t){let n=null,s;const r=Il(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:f,height:p}=e.getBoundingClientRect();if(o||t(),!f||!p)return;const g=Ox(d),v=Ox(r.clientWidth-(u+f)),b=Ox(r.clientHeight-(d+p)),x=Ox(u),_={rootMargin:-g+"px "+-v+"px "+-b+"px "+-x+"px",threshold:mh(0,Jp(1,l))||1};let w=!0;function y(S){const C=S[0].intersectionRatio;if(C!==l){if(!w)return a();C?a(!1,C):s=setTimeout(()=>{a(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(y,$i({},_,{root:r.ownerDocument}))}catch{n=new IntersectionObserver(y,_)}n.observe(e)}return a(!0),i}function prt(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=zD(e),d=r||i?[...u?Fv(u):[],...Fv(t)]:[];d.forEach(_=>{r&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const f=u&&o?frt(u,n):null;let p=-1,g=null;a&&(g=new ResizeObserver(_=>{let[w]=_;w&&w.target===u&&g&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var y;(y=g)==null||y.observe(t)})),n()}),u&&!l&&g.observe(u),g.observe(t));let v,b=l?Hh(e):null;l&&x();function x(){const _=Hh(e);b&&(_.x!==b.x||_.y!==b.y||_.width!==b.width||_.height!==b.height)&&n(),b=_,v=requestAnimationFrame(x)}return n(),()=>{var _;d.forEach(w=>{r&&w.removeEventListener("scroll",n),i&&w.removeEventListener("resize",n)}),f?.(),(_=g)==null||_.disconnect(),g=null,l&&cancelAnimationFrame(v)}}const grt=qst,mrt=Yst,vrt=Kst,brt=$st,xrt=Xst,_rt=(e,t,n)=>{const s=new Map,r=$i({platform:hrt},n),i=$i({},r.platform,{_c:s});return Wst(e,t,$i({},r,{platform:i}))};function wrt(e){e.cleanup&&e.cleanup();const t=e._getResolvedAttachToOptions();let n=t.element;const s=Trt(t,e),r=tY(t);return r&&(n=document.body,e.shepherdElementComponent.getElement().classList.add("shepherd-centered")),e.cleanup=prt(n,e.el,()=>{if(!e.el){e.cleanup==null||e.cleanup();return}Srt(n,e,s,r)}),e.target=t.element,s}function yrt(e,t){return{floatingUIOptions:BD(e.floatingUIOptions||{},t.floatingUIOptions||{})}}function Crt(e){e.cleanup&&e.cleanup(),e.cleanup=null}function Srt(e,t,n,s){return _rt(e,t.el,n).then(krt(t,s)).then(r=>new Promise(i=>{setTimeout(()=>i(r),300)})).then(r=>{r!=null&&r.el&&r.el.focus({preventScroll:!0})})}function krt(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,Ert(e.el,i)),e)}function Ert(e,t){const n=e.querySelector(".shepherd-arrow");if(Qp(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 Trt(e,t){var n,s,r;const i={strategy:"absolute"};i.middleware=[];const a=Rrt(t),o=tY(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(grt({crossAxis:!0,alignment:u?e==null||(d=e.on)==null?void 0:d.split("-").pop():null}))}else i.middleware.push(vrt());if(i.middleware.push(mrt({limiter:xrt(),crossAxis:!0})),a){const f=typeof t.options.arrow=="object"?t.options.arrow:{padding:4};i.middleware.push(brt({element:a,padding:u?f.padding:0}))}l||(i.placement=e.on)}return BD(i,t.options.floatingUIOptions||{})}function Rrt(e){return e.options.arrow&&e.el?e.el.querySelector(".shepherd-arrow"):!1}function ma(){}function Art(e,t){for(const n in t)e[n]=t[n];return e}function hY(e){return e()}function h6(){return Object.create(null)}function gb(e){e.forEach(hY)}function KD(e){return typeof e=="function"}function Oc(e,t){return e!=e?t==t:e!==t||e&&typeof e=="object"||typeof e=="function"}function Frt(e){return Object.keys(e).length===0}function tg(e,t){e.appendChild(t)}function Vo(e,t,n){e.insertBefore(t,n||null)}function oo(e){e.parentNode&&e.parentNode.removeChild(e)}function Drt(e,t){for(let n=0;n<e.length;n+=1)e[n]&&e[n].d(t)}function Tl(e){return document.createElement(e)}function f6(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function fY(e){return document.createTextNode(e)}function oy(){return fY(" ")}function Irt(){return fY("")}function MC(e,t,n,s){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}function os(e,t,n){n==null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n)}const Nrt=["width","height"];function p6(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&&Nrt.indexOf(s)===-1?e[s]=t[s]:os(e,s,t[s])}function Prt(e){return Array.from(e.childNodes)}function Ff(e,t,n){e.classList.toggle(t,!!n)}let Dv;function C0(e){Dv=e}function pY(){if(!Dv)throw new Error("Function called outside component initialization");return Dv}function Mrt(e){pY().$$.on_mount.push(e)}function YD(e){pY().$$.after_update.push(e)}const Wf=[],ng=[];let Rp=[];const g6=[],Ort=Promise.resolve();let YR=!1;function Lrt(){YR||(YR=!0,Ort.then(gY))}function XR(e){Rp.push(e)}const Wk=new Set;let Df=0;function gY(){if(Df!==0)return;const e=Dv;do{try{for(;Df<Wf.length;){const t=Wf[Df];Df++,C0(t),Brt(t.$$)}}catch(t){throw Wf.length=0,Df=0,t}for(C0(null),Wf.length=0,Df=0;ng.length;)ng.pop()();for(let t=0;t<Rp.length;t+=1){const n=Rp[t];Wk.has(n)||(Wk.add(n),n())}Rp.length=0}while(Wf.length);for(;g6.length;)g6.pop()();YR=!1,Wk.clear(),C0(e)}function Brt(e){if(e.fragment!==null){e.update(),gb(e.before_update);const t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(XR)}}function jrt(e){const t=[],n=[];Rp.forEach(s=>e.indexOf(s)===-1?t.push(s):n.push(s)),n.forEach(s=>s()),Rp=t}const v_=new Set;let Zd;function vh(){Zd={r:0,c:[],p:Zd}}function bh(){Zd.r||gb(Zd.c),Zd=Zd.p}function Kn(e,t){e&&e.i&&(v_.delete(e),e.i(t))}function Ks(e,t,n,s){if(e&&e.o){if(v_.has(e))return;v_.add(e),Zd.c.push(()=>{v_.delete(e),s&&(n&&e.d(1),s())}),e.o(t)}else s&&s()}function m6(e){return e?.length!==void 0?e:Array.from(e)}function Hrt(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 nf(e){e&&e.c()}function ud(e,t,n){const{fragment:s,after_update:r}=e.$$;s&&s.m(t,n),XR(()=>{const i=e.$$.on_mount.map(hY).filter(KD);e.$$.on_destroy?e.$$.on_destroy.push(...i):gb(i),e.$$.on_mount=[]}),r.forEach(XR)}function dd(e,t){const n=e.$$;n.fragment!==null&&(jrt(n.after_update),gb(n.on_destroy),n.fragment&&n.fragment.d(t),n.on_destroy=n.fragment=null,n.ctx=[])}function Urt(e,t){e.$$.dirty[0]===-1&&(Wf.push(e),Lrt(),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<<t%31}function Lc(e,t,n,s,r,i,a=null,o=[-1]){const l=Dv;C0(e);const u=e.$$={fragment:null,ctx:[],props:i,update:ma,not_equal:r,bound:h6(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(l?l.$$.context:[])),callbacks:h6(),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||{},(f,p,...g)=>{const v=g.length?g[0]:p;return u.ctx&&r(u.ctx[f],u.ctx[f]=v)&&(!u.skip_bound&&u.bound[f]&&u.bound[f](v),d&&Urt(e,f)),p}):[],u.update(),d=!0,gb(u.before_update),u.fragment=s?s(u.ctx):!1,t.target){if(t.hydrate){const f=Prt(t.target);u.fragment&&u.fragment.l(f),f.forEach(oo)}else u.fragment&&u.fragment.c();t.intro&&Kn(e.$$.fragment),ud(e,t.target,t.anchor),gY()}C0(l)}class Bc{constructor(){this.$$=void 0,this.$$set=void 0}$destroy(){dd(this,1),this.$destroy=ma}$on(t,n){if(!KD(n))return ma;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&&!Frt(t)&&(this.$$.skip_bound=!0,this.$$set(t),this.$$.skip_bound=!1)}}const Grt="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Grt);function Vrt(e){let t,n,s,r,i;return{c(){t=Tl("button"),os(t,"aria-label",n=e[3]?e[3]:null),os(t,"class",s=`${e[1]||""} shepherd-button ${e[4]?"shepherd-button-secondary":""}`),t.disabled=e[2],os(t,"tabindex","0"),os(t,"type","button")},m(a,o){Vo(a,t,o),t.innerHTML=e[5],r||(i=MC(t,"click",function(){KD(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)&&os(t,"aria-label",n),o&18&&s!==(s=`${e[1]||""} shepherd-button ${e[4]?"shepherd-button-secondary":""}`)&&os(t,"class",s),o&4&&(t.disabled=e[2])},i:ma,o:ma,d(a){a&&oo(t),r=!1,i()}}}function Wrt(e,t,n){let{config:s,step:r}=t,i,a,o,l,u,d;function f(p){return Qu(p)?p=p.call(r):p}return e.$$set=p=>{"config"in p&&n(6,s=p.config),"step"in p&&n(7,r=p.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?f(s.disabled):!1),n(3,l=s.label?f(s.label):null),n(4,u=s.secondary),n(5,d=s.text?f(s.text):null))},[i,a,o,l,u,d,s,r]}class $rt extends Bc{constructor(t){super(),Lc(this,t,Wrt,Vrt,Oc,{config:6,step:7})}}function v6(e,t,n){const s=e.slice();return s[2]=t[n],s}function b6(e){let t,n,s=m6(e[1]),r=[];for(let a=0;a<s.length;a+=1)r[a]=x6(v6(e,s,a));const i=a=>Ks(r[a],1,1,()=>{r[a]=null});return{c(){for(let a=0;a<r.length;a+=1)r[a].c();t=Irt()},m(a,o){for(let l=0;l<r.length;l+=1)r[l]&&r[l].m(a,o);Vo(a,t,o),n=!0},p(a,o){if(o&3){s=m6(a[1]);let l;for(l=0;l<s.length;l+=1){const u=v6(a,s,l);r[l]?(r[l].p(u,o),Kn(r[l],1)):(r[l]=x6(u),r[l].c(),Kn(r[l],1),r[l].m(t.parentNode,t))}for(vh(),l=s.length;l<r.length;l+=1)i(l);bh()}},i(a){if(!n){for(let o=0;o<s.length;o+=1)Kn(r[o]);n=!0}},o(a){r=r.filter(Boolean);for(let o=0;o<r.length;o+=1)Ks(r[o]);n=!1},d(a){a&&oo(t),Drt(r,a)}}}function x6(e){let t,n;return t=new $rt({props:{config:e[2],step:e[0]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function zrt(e){let t,n,s=e[1]&&b6(e);return{c(){t=Tl("footer"),s&&s.c(),os(t,"class","shepherd-footer")},m(r,i){Vo(r,t,i),s&&s.m(t,null),n=!0},p(r,[i]){r[1]?s?(s.p(r,i),i&2&&Kn(s,1)):(s=b6(r),s.c(),Kn(s,1),s.m(t,null)):s&&(vh(),Ks(s,1,1,()=>{s=null}),bh())},i(r){n||(Kn(s),n=!0)},o(r){Ks(s),n=!1},d(r){r&&oo(t),s&&s.d()}}}function qrt(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 Krt extends Bc{constructor(t){super(),Lc(this,t,qrt,zrt,Oc,{step:0})}}function Yrt(e){let t,n,s,r,i;return{c(){t=Tl("button"),n=Tl("span"),n.textContent="×",os(n,"aria-hidden","true"),os(t,"aria-label",s=e[0].label?e[0].label:"Close Tour"),os(t,"class","shepherd-cancel-icon"),os(t,"type","button")},m(a,o){Vo(a,t,o),tg(t,n),r||(i=MC(t,"click",e[1]),r=!0)},p(a,[o]){o&1&&s!==(s=a[0].label?a[0].label:"Close Tour")&&os(t,"aria-label",s)},i:ma,o:ma,d(a){a&&oo(t),r=!1,i()}}}function Xrt(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 Qrt extends Bc{constructor(t){super(),Lc(this,t,Xrt,Yrt,Oc,{cancelIcon:0,step:2})}}function Jrt(e){let t;return{c(){t=Tl("h3"),os(t,"id",e[1]),os(t,"class","shepherd-title")},m(n,s){Vo(n,t,s),e[3](t)},p(n,[s]){s&2&&os(t,"id",n[1])},i:ma,o:ma,d(n){n&&oo(t),e[3](null)}}}function Zrt(e,t,n){let{labelId:s,element:r,title:i}=t;YD(()=>{Qu(i)&&n(2,i=i()),n(0,r.innerHTML=i,r)});function a(o){ng[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 eit extends Bc{constructor(t){super(),Lc(this,t,Zrt,Jrt,Oc,{labelId:1,element:0,title:2})}}function _6(e){let t,n;return t=new eit({props:{labelId:e[0],title:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function w6(e){let t,n;return t=new Qrt({props:{cancelIcon:e[3],step:e[1]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function tit(e){let t,n,s,r=e[2]&&_6(e),i=e[3]&&e[3].enabled&&w6(e);return{c(){t=Tl("header"),r&&r.c(),n=oy(),i&&i.c(),os(t,"class","shepherd-header")},m(a,o){Vo(a,t,o),r&&r.m(t,null),tg(t,n),i&&i.m(t,null),s=!0},p(a,[o]){a[2]?r?(r.p(a,o),o&4&&Kn(r,1)):(r=_6(a),r.c(),Kn(r,1),r.m(t,n)):r&&(vh(),Ks(r,1,1,()=>{r=null}),bh()),a[3]&&a[3].enabled?i?(i.p(a,o),o&8&&Kn(i,1)):(i=w6(a),i.c(),Kn(i,1),i.m(t,null)):i&&(vh(),Ks(i,1,1,()=>{i=null}),bh())},i(a){s||(Kn(r),Kn(i),s=!0)},o(a){Ks(r),Ks(i),s=!1},d(a){a&&oo(t),r&&r.d(),i&&i.d()}}}function nit(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 sit extends Bc{constructor(t){super(),Lc(this,t,nit,tit,Oc,{labelId:0,step:1})}}function rit(e){let t;return{c(){t=Tl("div"),os(t,"class","shepherd-text"),os(t,"id",e[1])},m(n,s){Vo(n,t,s),e[3](t)},p(n,[s]){s&2&&os(t,"id",n[1])},i:ma,o:ma,d(n){n&&oo(t),e[3](null)}}}function iit(e,t,n){let{descriptionId:s,element:r,step:i}=t;YD(()=>{let{text:o}=i.options;Qu(o)&&(o=o.call(i)),Qp(o)?r.appendChild(o):n(0,r.innerHTML=o,r)});function a(o){ng[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 ait extends Bc{constructor(t){super(),Lc(this,t,iit,rit,Oc,{descriptionId:1,element:0,step:2})}}function y6(e){let t,n;return t=new sit({props:{labelId:e[1],step:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function C6(e){let t,n;return t=new ait({props:{descriptionId:e[0],step:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function S6(e){let t,n;return t=new Krt({props:{step:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(t,s,r),n=!0},p(s,r){const i={};r&4&&(i.step=s[2]),t.$set(i)},i(s){n||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function oit(e){let t,n=!ni(e[2].options.title)||e[2].options.cancelIcon&&e[2].options.cancelIcon.enabled,s,r=!ni(e[2].options.text),i,a=Array.isArray(e[2].options.buttons)&&e[2].options.buttons.length,o,l=n&&y6(e),u=r&&C6(e),d=a&&S6(e);return{c(){t=Tl("div"),l&&l.c(),s=oy(),u&&u.c(),i=oy(),d&&d.c(),os(t,"class","shepherd-content")},m(f,p){Vo(f,t,p),l&&l.m(t,null),tg(t,s),u&&u.m(t,null),tg(t,i),d&&d.m(t,null),o=!0},p(f,[p]){p&4&&(n=!ni(f[2].options.title)||f[2].options.cancelIcon&&f[2].options.cancelIcon.enabled),n?l?(l.p(f,p),p&4&&Kn(l,1)):(l=y6(f),l.c(),Kn(l,1),l.m(t,s)):l&&(vh(),Ks(l,1,1,()=>{l=null}),bh()),p&4&&(r=!ni(f[2].options.text)),r?u?(u.p(f,p),p&4&&Kn(u,1)):(u=C6(f),u.c(),Kn(u,1),u.m(t,i)):u&&(vh(),Ks(u,1,1,()=>{u=null}),bh()),p&4&&(a=Array.isArray(f[2].options.buttons)&&f[2].options.buttons.length),a?d?(d.p(f,p),p&4&&Kn(d,1)):(d=S6(f),d.c(),Kn(d,1),d.m(t,null)):d&&(vh(),Ks(d,1,1,()=>{d=null}),bh())},i(f){o||(Kn(l),Kn(u),Kn(d),o=!0)},o(f){Ks(l),Ks(u),Ks(d),o=!1},d(f){f&&oo(t),l&&l.d(),u&&u.d(),d&&d.d()}}}function lit(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 cit extends Bc{constructor(t){super(),Lc(this,t,lit,oit,Oc,{descriptionId:0,labelId:1,step:2})}}function k6(e){let t;return{c(){t=Tl("div"),os(t,"class","shepherd-arrow"),os(t,"data-popper-arrow","")},m(n,s){Vo(n,t,s)},d(n){n&&oo(t)}}}function uit(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&&k6();s=new cit({props:{descriptionId:e[2],labelId:e[3],step:e[4]}});let d=[{"aria-describedby":r=ni(e[4].options.text)?null:e[2]},{"aria-labelledby":i=e[4].options.title?e[3]:null},e[1],{open:"true"}],f={};for(let p=0;p<d.length;p+=1)f=Art(f,d[p]);return{c(){t=Tl("dialog"),u&&u.c(),n=oy(),nf(s.$$.fragment),p6(t,f),Ff(t,"shepherd-has-cancel-icon",e[5]),Ff(t,"shepherd-has-title",e[6]),Ff(t,"shepherd-element",!0)},m(p,g){Vo(p,t,g),u&&u.m(t,null),tg(t,n),ud(s,t,null),e[13](t),a=!0,o||(l=MC(t,"keydown",e[7]),o=!0)},p(p,[g]){p[4].options.arrow&&p[4].options.attachTo&&p[4].options.attachTo.element&&p[4].options.attachTo.on?u||(u=k6(),u.c(),u.m(t,n)):u&&(u.d(1),u=null);const v={};g&4&&(v.descriptionId=p[2]),g&8&&(v.labelId=p[3]),g&16&&(v.step=p[4]),s.$set(v),p6(t,f=Hrt(d,[(!a||g&20&&r!==(r=ni(p[4].options.text)?null:p[2]))&&{"aria-describedby":r},(!a||g&24&&i!==(i=p[4].options.title?p[3]:null))&&{"aria-labelledby":i},g&2&&p[1],{open:"true"}])),Ff(t,"shepherd-has-cancel-icon",p[5]),Ff(t,"shepherd-has-title",p[6]),Ff(t,"shepherd-element",!0)},i(p){a||(Kn(s.$$.fragment,p),a=!0)},o(p){Ks(s.$$.fragment,p),a=!1},d(p){p&&oo(t),u&&u.d(),dd(s),e[13](null),o=!1,l()}}}const dit=9,hit=27,fit=37,pit=39;function E6(e){return e.split(" ").filter(t=>!!t.length)}function git(e,t,n){let{classPrefix:s,element:r,descriptionId:i,firstFocusableElement:a,focusableElements:o,labelId:l,lastFocusableElement:u,step:d,dataStepId:f}=t,p,g,v;const b=()=>r;Mrt(()=>{n(1,f={[`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])}),YD(()=>{v!==d.options.classes&&x()});function x(){_(v),v=d.options.classes,w(v)}function _(C){if(Av(C)){const E=E6(C);E.length&&r.classList.remove(...E)}}function w(C){if(Av(C)){const E=E6(C);E.length&&r.classList.add(...E)}}const y=C=>{const{tour:E}=d;switch(C.keyCode){case dit:if(o.length===0){C.preventDefault();break}C.shiftKey?(document.activeElement===a||document.activeElement.classList.contains("shepherd-element"))&&(C.preventDefault(),u.focus()):document.activeElement===u&&(C.preventDefault(),a.focus());break;case hit:E.options.exitOnEsc&&(C.preventDefault(),C.stopPropagation(),d.cancel());break;case fit:E.options.keyboardNavigation&&(C.preventDefault(),C.stopPropagation(),E.back());break;case pit:E.options.keyboardNavigation&&(C.preventDefault(),C.stopPropagation(),E.next());break}};function S(C){ng[C?"unshift":"push"](()=>{r=C,n(0,r)})}return e.$$set=C=>{"classPrefix"in C&&n(11,s=C.classPrefix),"element"in C&&n(0,r=C.element),"descriptionId"in C&&n(2,i=C.descriptionId),"firstFocusableElement"in C&&n(8,a=C.firstFocusableElement),"focusableElements"in C&&n(9,o=C.focusableElements),"labelId"in C&&n(3,l=C.labelId),"lastFocusableElement"in C&&n(10,u=C.lastFocusableElement),"step"in C&&n(4,d=C.step),"dataStepId"in C&&n(1,f=C.dataStepId)},e.$$.update=()=>{e.$$.dirty&16&&(n(5,p=d.options&&d.options.cancelIcon&&d.options.cancelIcon.enabled),n(6,g=d.options&&d.options.title))},[r,f,i,l,d,p,g,y,a,o,u,s,b,S]}class mit extends Bc{constructor(t){super(),Lc(this,t,git,uit,Oc,{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 QR extends OD{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?eY(this.tour.options.classPrefix):"",this.styles=t.styles,this._resolvedAttachTo=null,jD(this),this._setOptions(n),this}cancel(){this.tour.cancel(),this.trigger("cancel")}complete(){this.tour.complete(),this.trigger("complete")}destroy(){Crt(this),Qp(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=Nst(this),this._resolvedExtraHighlightElements}_resolveAttachToOptions(){return this._resolvedAttachTo=Ist(this),this._resolvedAttachTo}_getResolvedAttachToOptions(){return this._resolvedAttachTo===null?this._resolveAttachToOptions():this._resolvedAttachTo}isOpen(){return!!(this.el&&!this.el.hidden)}show(){return Qu(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 mit({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();Qu(this.options.scrollToHandler)?this.options.scrollToHandler(n):dst(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=BD({},n||{}),this.options=Object.assign({arrow:!0},n,t,yrt(n,t));const{when:s}=this.options;this.options.classes=this._getClassOptions(t),this.destroy(),this.id=this.options.id||`step-${nY()}`,s&&Object.keys(s).forEach(r=>{this.on(r,s[r],this)})}_setupElements(){ni(this.el)||this.destroy(),this.el=this._createTooltipContent(),this.options.advanceOn&&Ast(this),wrt(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 vit(e){if(e){const{steps:t}=e;t.forEach(n=>{n.options&&n.options.canClickTarget===!1&&n.options.attachTo&&(Qp(n.target)&&n.target.classList.remove("shepherd-target-click-disabled"),n._resolvedExtraHighlightElements&&n._resolvedExtraHighlightElements.forEach(s=>{Qp(s)&&s.classList.remove("shepherd-target-click-disabled")}))})}}function bit(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:f=0,bottomRight:p=0,bottomLeft:g=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-g} a${g},${g},0,0,0,${g},${g} H${i+o-p} a${p},${p},0,0,0,${p}-${p} V${l+f} a${f},${f},0,0,0-${f}-${f} Z`}),`M${n},${s} H0 V0 H${n} V${s} Z ${t}`.replace(/\s/g,"")}function xit(e){let t,n,s,r,i;return{c(){t=f6("svg"),n=f6("path"),os(n,"d",e[2]),os(t,"class",s=`${e[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)},m(a,o){Vo(a,t,o),tg(t,n),e[11](t),r||(i=MC(t,"touchmove",e[3]),r=!0)},p(a,[o]){o&4&&os(n,"d",a[2]),o&2&&s!==(s=`${a[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)&&os(t,"class",s)},i:ma,o:ma,d(a){a&&oo(t),e[11](null),r=!1,i()}}}function mY(e){if(!e)return null;const t=e instanceof HTMLElement&&window.getComputedStyle(e).overflowY;return t!=="hidden"&&t!=="visible"&&e.scrollHeight>=e.clientHeight?e:mY(e.parentElement)}function _it(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 wit(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 yit(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),_()}function f(S=0,C=0,E=0,k=0,F,A,I){if(A){const N=[A,...I||[]];n(4,r=[]);for(const P of N){if(!P||N.indexOf(P)!==N.lastIndexOf(P))continue;const{y:M,height:Y}=wit(P,F),{x:O,width:X,left:Q}=P.getBoundingClientRect();N.some(ie=>{if(ie===P)return!1;const G=ie.getBoundingClientRect();return O>=G.left&&O+X<=G.right&&M>=G.top&&M+Y<=G.bottom})||r.push({width:X+S*2,height:Y+S*2,x:(O||Q)+E-S,y:M+k-S,r:C})}}else u()}function p(S){_(),S.tour.options.useModalOverlay?(w(S),g()):d()}function g(){n(1,i=!0)}const v=S=>{S.preventDefault()},b=S=>{S.stopPropagation()};function x(){window.addEventListener("touchmove",v,{passive:!1})}function _(){a&&(cancelAnimationFrame(a),a=void 0),window.removeEventListener("touchmove",v,{passive:!1})}function w(S){const{modalOverlayOpeningPadding:C,modalOverlayOpeningRadius:E,modalOverlayOpeningXOffset:k=0,modalOverlayOpeningYOffset:F=0}=S.options,A=_it(S.target),I=mY(S.target),N=()=>{a=void 0,f(C,E,k+A.left,F+A.top,I,S.target,S._resolvedExtraHighlightElements),a=requestAnimationFrame(N)};N(),x()}function y(S){ng[S?"unshift":"push"](()=>{s=S,n(0,s)})}return e.$$set=S=>{"element"in S&&n(0,s=S.element),"openingProperties"in S&&n(4,r=S.openingProperties)},e.$$.update=()=>{e.$$.dirty&16&&n(2,o=bit(r))},[s,i,o,b,r,l,u,d,f,p,g,y]}class Cit extends Bc{constructor(t){super(),Lc(this,t,yit,xit,Oc,{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 Sit extends OD{constructor(){super(),this.activeTour=void 0,jD(this)}}class kit extends OD{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,jD(this);const n={exitOnEsc:!0,keyboardNavigation:!0};return this.options=Object.assign({},n,t),this.classPrefix=eY(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,eh.trigger(r,i)})})(s)}),this._setTourID(t.id),this}addStep(t,n){let s=t;return s instanceof QR?s.tour=this:s=new QR(this,s),ni(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;Qu(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 eh.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=Av(t)?this.getById(t):this.steps[t];s&&(this._updateStateBeforeShow(),Qu(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()),vit(this),this.trigger(t,{index:n}),eh.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)}Qp(this.focusedElBeforeOpen)&&this.focusedElBeforeOpen.focus()}_setupActiveTour(){this.trigger("active",{tour:this}),eh.activeTour=this}setupModal(){this.modal=new Cit({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||nY();this.id=`${n}--${s}`}}const eh=new Sit,vY=typeof window>"u";eh.Step=vY?Fst:QR;eh.Tour=vY?Dst:kit;const OC=m.createContext(void 0);OC.Consumer;const Eit=({children:e})=>ust.jsx(OC.Provider,{value:{Shepherd:eh},children:e}),ly=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Tit=e=>ly(e).replace(/"/g,"&quot;"),at=e=>ly(h(e)),Rit=['<div class="tour-figure-rail" aria-hidden="true">','<span class="tour-figure-dot"></span>','<span class="tour-figure-dot"></span>','<span class="tour-figure-dot"></span>','<span class="tour-figure-rail-line"></span>',"</div>",'<div class="tour-figure-main" aria-hidden="true">','<span class="tour-figure-bubble tour-figure-bubble-in"></span>','<span class="tour-figure-bubble tour-figure-bubble-out"></span>','<span class="tour-figure-composer">','<span class="tour-figure-composer-line"></span>','<span class="tour-figure-send"></span>',"</span>","</div>"].join(""),Ait=['<div class="tour-figure-flow" aria-hidden="true">','<div class="tour-figure-node">','<span class="tour-figure-node-icon"></span>','<span class="tour-figure-node-bar"></span>','<span class="tour-figure-node-bar tour-figure-node-bar-short"></span>',"</div>",'<span class="tour-figure-connector"></span>','<div class="tour-figure-node">','<span class="tour-figure-node-icon tour-figure-node-icon-round"></span>','<span class="tour-figure-node-bar"></span>','<span class="tour-figure-node-bar tour-figure-node-bar-short"></span>',"</div>",'<span class="tour-figure-connector"></span>','<div class="tour-figure-node">','<span class="tour-figure-node-icon tour-figure-node-icon-end"></span>','<span class="tour-figure-node-bar"></span>','<span class="tour-figure-node-bar tour-figure-node-bar-short"></span>',"</div>","</div>"].join(""),Fit={welcome:Rit,"agent-capabilities":Ait},T6=e=>e.map(t=>"key"in t?ly(h(t.key)):`<code>${ly(t.code)}</code>`).join(""),Dit=e=>{const t="<br/>".repeat(e.breaks??0);return e.kind==="paragraph"?`${T6(e.runs)}${t}`:e.kind==="list"?`<ul>${e.items.map(s=>`<li>${T6(s)}</li>`).join("")}</ul>${t}`:`<div class="tour-figure tour-figure-${e.figure}" role="img" aria-label="${Tit(h(e.altKey))}">${Fit[e.figure]}</div>${t}`},vn=e=>e.map(Dit).join(""),bn={welcome:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.1"}],breaks:1},{kind:"figure",figure:"welcome",altKey:"ui.onboarding.tour.welcome.image.1.alt",breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.2"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.3"}],breaks:0},{kind:"list",items:[[{key:"ui.onboarding.tour.welcome.list.1.item.1"}],[{key:"ui.onboarding.tour.welcome.list.1.item.2"}],[{key:"ui.onboarding.tour.welcome.list.1.item.3"}],[{key:"ui.onboarding.tour.welcome.list.1.item.4"}],[{key:"ui.onboarding.tour.welcome.list.1.item.5"}],[{key:"ui.onboarding.tour.welcome.list.1.item.6"}],[{key:"ui.onboarding.tour.welcome.list.1.item.7"}]],breaks:0},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.4"}],breaks:0}],agent_list:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_list.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_list.body.2"}],breaks:0}],select_agent:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.select_agent.body.1"}],breaks:0}],chat_input:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.chat_input.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.chat_input.body.2"}],breaks:2},{kind:"list",items:[[{key:"ui.onboarding.tour.chat_input.list.1.item.1"}],[{key:"ui.onboarding.tour.chat_input.list.1.item.2"}],[{key:"ui.onboarding.tour.chat_input.list.1.item.3"}]],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.chat_input.body.3"}],breaks:0}],attachments:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.2"}],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.3"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.4"}],breaks:0}],agent_capabilities:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_capabilities.body.1"}],breaks:1},{kind:"figure",figure:"agent-capabilities",altKey:"ui.onboarding.tour.agent_capabilities.image.1.alt",breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_capabilities.body.2"}],breaks:0}],pre_command_palette_open_canvas:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.1"},{code:ul("everything",!0)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.connector.on_mac_and"},{code:ul("everything",!1)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.3"},{code:"#"},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.4"},{code:"@"},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.5"},{code:","},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.6"},{code:">"},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.7"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.2.1"},{code:ul("chats",!0)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.connector.on_mac_and"},{code:ul("chats",!1)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.2.3"},{code:ul("commands",!0)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.connector.on_mac_and"},{code:ul("commands",!1)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.2.5"}],breaks:0}],canvas_open_button:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_open_button.body.1"}],breaks:0}],canvas_feature:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_feature.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_feature.body.2"}],breaks:0}],canvas_documents_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.2"}],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.3"}],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.4"}],breaks:0}],canvas_files_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_files_view.body.1"}],breaks:0}],canvas_variables_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_variables_view.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_variables_view.body.2"}],breaks:0}],agent_options:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_options.body.1"}],breaks:0}],click_view_settings_from_chat:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.click_view_settings_from_chat.body.1"}],breaks:0}],view_agent_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.view_agent_settings.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.view_agent_settings.body.2"}],breaks:0}],select_provider:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.select_provider.body.1"}],breaks:0}],select_model:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.select_model.body.1"}],breaks:0}],modify_security_prompt:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.modify_security_prompt.body.1"}],breaks:0}],modify_agent_prompt:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.modify_agent_prompt.body.1"}],breaks:0}],create_new_agent:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_new_agent.body.1"}],breaks:0}],agent_naming_guidelines:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_naming_guidelines.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_naming_guidelines.body.2"}],breaks:0}],navigate_agent_hub:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.navigate_agent_hub.body.1"}],breaks:0}],agent_hub_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_hub_view.body.1"}],breaks:0}],download_agent:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.download_agent.body.1"}],breaks:0}],upload_agent_hub:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.upload_agent_hub.body.1"}],breaks:0}],upload_agent_hub_dialog:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.upload_agent_hub_dialog.body.1"}],breaks:0}],navigate_schedules:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.navigate_schedules.body.1"}],breaks:0}],schedules_overview:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.schedules_overview.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.schedules_overview.body.2"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.schedules_overview.body.3"}],breaks:0}],create_schedule:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule.body.2"}],breaks:0}],create_schedule_dialog:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule_dialog.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule_dialog.body.2"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule_dialog.body.3"}],breaks:0}],navigate_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.navigate_settings.body.1"}],breaks:0}],general_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.general_settings.body.1"}],breaks:0}],appearance_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.appearance_settings.body.1"}],breaks:0}],radient_account_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.radient_account_settings.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.radient_account_settings.body.2"}],breaks:0}],integrations_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.integrations_settings.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.integrations_settings.body.2"}],breaks:0}],application_updates_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.application_updates_settings.body.1"}],breaks:0}],tour_complete:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.tour_complete.body.1"}],breaks:0}]},Iit=e=>{const t=Array.from(document.querySelectorAll(`[data-tour-tag="${e}"]`));return t.find(n=>n.offsetParent!==null)??t[0]??null},R6=e=>{document.querySelector(`[data-tour-action="${e}"]`)?.click()},bY=1340,XD="tour-beside-palette",LC="pre-command-palette-open-canvas",xY='[data-tour-tag="command-palette-dialog"]',ds=e=>$5(Bm())!=="rtl"?e:e==="left"?"right":"left",Nit=e=>(e.getById(LC)?.options.classes??"").split(" ").includes(XD),_Y=(e,t)=>{const n=e.getById(LC);!n||Nit(e)===t||n.updateStepOptions(t?{attachTo:{element:xY,on:ds("right")},classes:XD}:{attachTo:void 0,classes:void 0})},wY=e=>{const t=window.innerWidth>=bY;return _Y(e,t),t};let QD=0;const JR=new WeakMap;nt.subscribe((e,t)=>{t.isCommandPaletteOpen&&!e.isCommandPaletteOpen&&(QD+=1)});const yY=e=>{const t=JR.get(e);return t===void 0||(JR.delete(e),t!==QD)?!1:(nt.getState().closeCommandPalette(),!0)},A6=(e,t)=>{if(!wY(e)){t();return}const n=nt.getState();n.isCommandPaletteOpen||(n.openCommandPalette(),JR.set(e,QD)),setTimeout(()=>{e.isActive()&&t()},500)},F6=(e,t)=>{if(!yY(e)){t();return}setTimeout(()=>{e.isActive()&&t()},500)},D6=e=>{const t=e?.step;if(t?.id!==LC)return;(!wY(t.tour)||document.querySelector(xY)===null)&&_Y(t.tour,!1)},Pit=()=>{const e=window.innerWidth>=bY;return{id:LC,...e?{attachTo:{element:'[data-tour-tag="command-palette-dialog"]',on:ds("right")},classes:XD}:{},title:at("ui.onboarding.tour.pre_command_palette_open_canvas.title"),text:vn(bn.pre_command_palette_open_canvas),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){F6(this,()=>this.back())}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){F6(this,()=>this.next())}}]}},CY=()=>[{id:"welcome",title:at("ui.onboarding.tour.welcome.title"),text:vn(bn.welcome),buttons:[{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"agent-list",attachTo:{element:'[data-tour-tag="agent-list-panel"]',on:ds("right")},title:at("ui.onboarding.tour.agent_list.title"),text:vn(bn.agent_list),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-agent",attachTo:{element:'[data-tour-tag="agent-list-item-button-0"]',on:ds("right")},title:at("ui.onboarding.tour.select_agent.title"),text:vn(bn.select_agent),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.chat_input.title"),text:vn(bn.chat_input),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.attachments.title"),text:vn(bn.attachments),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"agent-capabilities",attachTo:{element:'[data-tour-tag="chat-header"]',on:"top"},title:at("ui.onboarding.tour.agent_capabilities.title"),text:vn(bn.agent_capabilities),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){A6(this,()=>this.next())}}]},Pit(),{id:"canvas-open-button",attachTo:{element:'button[data-tour-tag="open-canvas-button"]',on:ds("left")},title:at("ui.onboarding.tour.canvas_open_button.title"),text:vn(bn.canvas_open_button),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){A6(this,()=>this.back())}},{text:at("ui.onboarding.tour.action.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:ds("left")},title:at("ui.onboarding.tour.canvas_feature.title"),text:vn(bn.canvas_feature),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.canvas_documents_view.title"),text:vn(bn.canvas_documents_view),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.canvas_files_view.title"),text:vn(bn.canvas_files_view),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.canvas_variables_view.title"),text:vn(bn.canvas_variables_view),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.agent_options.title"),text:vn(bn.agent_options),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.click_view_settings_from_chat.title"),text:vn(bn.click_view_settings_from_chat),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:ds("left")},title:at("ui.onboarding.tour.view_agent_settings.title"),text:vn(bn.view_agent_settings),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-provider",attachTo:{element:'[data-tour-tag="agent-settings-hosting-select"]',on:ds("left")},title:at("ui.onboarding.tour.select_provider.title"),text:vn(bn.select_provider),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-model",attachTo:{element:'[data-tour-tag="agent-settings-model-select"]',on:ds("left")},title:at("ui.onboarding.tour.select_model.title"),text:vn(bn.select_model),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"modify-security-prompt",attachTo:{element:'[data-tour-tag="agent-settings-security"]',on:ds("left")},title:at("ui.onboarding.tour.modify_security_prompt.title"),text:vn(bn.modify_security_prompt),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"modify-agent-prompt",attachTo:{element:'[data-tour-tag="agent-settings-system-prompt"]',on:ds("left")},title:at("ui.onboarding.tour.modify_agent_prompt.title"),text:vn(bn.modify_agent_prompt),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.create_new_agent.title"),text:vn(bn.create_new_agent),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.agent_naming_guidelines.title"),text:vn(bn.agent_naming_guidelines),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.navigate_agent_hub.title"),text:vn(bn.navigate_agent_hub),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.agent_hub_view.title"),text:vn(bn.agent_hub_view),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.download_agent.title"),text:vn(bn.download_agent),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:()=>Iit("upload-to-hub-header-button"),on:"bottom"},title:at("ui.onboarding.tour.upload_agent_hub.title"),text:vn(bn.upload_agent_hub),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){R6("open-upload-dialog"),setTimeout(()=>{this.next()},500)}}]},{id:"upload-agent-hub-dialog",attachTo:{element:'[data-tour-tag="upload-agent-dialog"]',on:ds("right")},title:at("ui.onboarding.tour.upload_agent_hub_dialog.title"),text:vn(bn.upload_agent_hub_dialog),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.navigate_schedules.title"),text:vn(bn.navigate_schedules),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{R6("open-upload-dialog")},500),setTimeout(()=>{this.back()},1e3)}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.schedules_overview.title"),text:vn(bn.schedules_overview),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"create-schedule",attachTo:{element:'button[data-tour-tag="create-schedule-button"]',on:"bottom"},title:at("ui.onboarding.tour.create_schedule.title"),text:vn(bn.create_schedule),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.create_schedule_dialog.title"),text:vn(bn.create_schedule_dialog),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.navigate_settings.title"),text:vn(bn.navigate_settings),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.general_settings.title"),text:vn(bn.general_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"appearance-settings",attachTo:{element:'[data-tour-tag="settings-appearance-section"]',on:ds("right")},title:at("ui.onboarding.tour.appearance_settings.title"),text:vn(bn.appearance_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"radient-account-settings",attachTo:{element:'[data-tour-tag="settings-radient-account-section"]',on:ds("right")},title:at("ui.onboarding.tour.radient_account_settings.title"),text:vn(bn.radient_account_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"integrations-settings",attachTo:{element:'[data-tour-tag="settings-integrations-section"]',on:ds("right")},title:at("ui.onboarding.tour.integrations_settings.title"),text:vn(bn.integrations_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"application-updates-settings",attachTo:{element:'[data-tour-tag="settings-app-updates-section"]',on:ds("right")},title:at("ui.onboarding.tour.application_updates_settings.title"),text:vn(bn.application_updates_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"tour-complete",title:at("ui.onboarding.tour.tour_complete.title"),text:vn(bn.tour_complete),buttons:[{text:at("ui.onboarding.tour.action.finish"),classes:"shepherd-button-primary",action:function(){this.complete()}}]}],SY=()=>({enabled:!0,label:h("ui.onboarding.tour.action.close")}),ZR=new WeakMap,Mit=(e,t)=>{ZR.set(e,t)},Oit=(e,t)=>{if(ZR.get(e)===t)return;const n=new Map(CY().filter(r=>r.id).map(r=>[r.id,r])),s=SY();for(const r of e.steps){const i=r.id?n.get(r.id):void 0;i&&r.updateStepOptions({title:i.title,text:i.text,buttons:i.buttons,cancelIcon:s})}e.options.defaultStepOptions={...e.options.defaultStepOptions,cancelIcon:s},ZR.set(e,t)},I6=new WeakMap,Lit=e=>{const t=I6.get(e);if(t)return t;const n=()=>yY(e);return I6.set(e,n),n},Bit=()=>{const e=oi(),{completeTourOnboarding:t}=D0(),n=m.useContext(OC),s=Ve(),r={cancelIcon:SY(),scrollTo:{behavior:"smooth",block:"center"}},i=!0,a=o=>{if(n?.tour?.isActive()&&!o?.forceModalCompleted){console.log("Onboarding tour is already active (from context.tour). Not starting another.");return}const l=D0.getState();if(!o?.forceModalCompleted&&!l.isModalComplete){console.log("Onboarding modal not completed (checked via store). Tour will not start.");return}if(l.isTourComplete&&!o?.forceModalCompleted){console.log("Onboarding tour already completed in store and not forced. Not starting again.");return}let u=n?.tour;const d=n?.Shepherd;if(!u&&d&&(u=d.activeTour,!u&&d.Tour&&(console.log("No active Shepherd tour found from context or global. Creating a new one."),u=new d.Tour({useModalOverlay:i,defaultStepOptions:r}))),!u){console.warn("Failed to get or create a Shepherd tour instance.",n);return}if(u.isActive()){console.log("Tour is already active. Not starting again.");return}u.options.defaultStepOptions={...u.options.defaultStepOptions||{},...r},u.options.useModalOverlay=i,o?.firstAgentId&&(u.options.firstAgentId=o.firstAgentId),u.off("complete",t),u.on("complete",t),u.off("cancel",t),u.on("cancel",t);const f=Lit(u);u.off("complete",f),u.on("complete",f),u.off("cancel",f),u.on("cancel",f),u.off("show",D6),u.on("show",D6);const p=CY();if(o?.forceModalCompleted||!u.isActive()){const g=[...u.steps];for(const v of g)v.id&&u.removeStep(v.id);u.addSteps(p)}else u.steps.length===0&&u.addSteps(p);Mit(u,Bm()),typeof u.start=="function"?(e("/"),u.start()):console.warn("Shepherd tour instance does not have a start method.",u)};return m.useEffect(()=>{const o=n?.tour??n?.Shepherd?.activeTour;o?.isActive()&&Oit(o,s)},[s,n]),{startTour:a}},jit=()=>{const{isModalComplete:e,isTourComplete:t}=D0(),{startTour:n}=Bit(),s=it.useContext(OC),{data:r}=aT(1,1);return m.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},Hit=({children:e})=>c.jsxs(Eit,{children:[e,c.jsx(jit,{})]}),Uit=()=>{Ve();const{open:e,focusGroup:t,providerId:n,closeConnect:s}=B8(),r=m.useRef(null);m.useEffect(()=>{e&&(r.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},[e]);const i=oi();return c.jsx(Tc,{open:e,onOpenChange:a=>{a||s()},children:c.jsxs(Rc,{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(wl,{className:"text-title",children:h("ui.providers.connect_provider_dialog.connect_a_model_provider")}),c.jsx(Zu,{className:"text-body-sm text-ink-muted",children:h("ui.providers.connect_provider_dialog.your_agents_need_a_model_to_think")})]}),e?c.jsx(XK,{context:"dialog",featuredOnly:!0,focusGroup:t,initialProviderId:n,onDone:s,onChangeModel:()=>{s(),i("/settings")}}):null]})})};function Git(){const{visible:e,rows:t,cursor:n,commitAt:s,hoverAt:r}=Eae();_u(e,"session-switcher");const i=n!==null&&e?t[n]??null:null,a=e&&t.length>=2;return c.jsxs(c.Fragment,{children:[c.jsx("output",{"aria-live":"polite",className:"sr-only","data-session-switcher-announcement":"",children:i!==null&&n!==null?c.jsxs(c.Fragment,{children:[kY(i),", ",n+1," / ",t.length]}):null}),a?jv.createPortal(c.jsx("div",{className:"pointer-events-none fixed inset-0 z-50 flex items-start justify-center pt-[18vh]",children:c.jsx("div",{role:"dialog","aria-modal":"false","aria-label":h("ui.command_palette.palette_search.recents"),className:"pointer-events-auto w-160 max-w-[90vw] rounded-lg border border-hairline bg-elevated p-2 shadow-overlay",children:t.map((o,l)=>c.jsx($it,{row:o,active:l===n,onCommit:()=>s(l),onHover:()=>r(l)},o.sessionId))})}),document.body):null]})}function kY(e){return e.title??h("ui.command_palette.palette_search.untitled_chat")}const Vit=1e3;function Wit(){let e=0;function t(){window.clearTimeout(e),window.removeEventListener("contextmenu",n,!0),window.removeEventListener("pointerup",t,!0)}function n(s){s.preventDefault(),s.stopPropagation(),t()}e=window.setTimeout(t,Vit),window.addEventListener("contextmenu",n,!0),window.addEventListener("pointerup",t,!0)}function $it({row:e,active:t,onCommit:n,onHover:s}){return c.jsxs("button",{type:"button",tabIndex:-1,"aria-current":t?"true":void 0,"data-session-id":e.sessionId,onPointerDown:r=>{r.button===0&&(r.preventDefault(),Wit(),n())},onMouseDown:r=>r.preventDefault(),onContextMenu:r=>r.preventDefault(),onMouseMove:s,className:R("flex h-9 w-full items-center gap-3 rounded-sm px-2 text-left",t?"bg-sunken outline-solid outline-1 -outline-offset-1 outline-control":"bg-transparent"),children:[e.row===null?c.jsx("span",{"aria-hidden":"true",className:"size-4 shrink-0"}):c.jsx(WR,{row:e.row}),c.jsx("span",{className:R("min-w-0 flex-1 truncate text-body-sm",e.title===null?"text-ink-muted":"text-ink"),children:kY(e)})]})}const EY=({title:e,description:t,icon:n,children:s,titleComponent:r,sectionRef:i,dataTourTag:a,className:o,id:l,searchSection:u,searchSectionLabel:d,searchIgnore:f})=>c.jsxs("div",{ref:i,id:l,"data-search-section":u,"data-search-section-label":d,"data-search-ignore":f,tabIndex:l?-1:void 0,"data-tour-tag":a,className:R("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})]}),Pdt=({label:e,value:t,className:n,valueClassName:s})=>c.jsxs("div",{className:R("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:R("mt-0.5 break-words text-body-sm",s??"text-ink"),children:t})]}),Mdt=({children:e,className:t})=>c.jsx("div",{className:R("grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-x-6 gap-y-4",t),children:e});function TY({id:e,rank:t,action:n,settingKey:s,help:r,hint:i,ariaLabel:a,value:o,fieldRef:l,saving:u,showReset:d,onReset:f,onKeyDown:p,onKeyUp:g,onBlur:v,notes:b,error:x,focusKey:_}){const w=m.useRef(!1);return m.useEffect(()=>{if(_!==s||w.current)return;const y=l.current;y&&(w.current=!0,y.scrollIntoView?.({block:"center"}),y.focus())},[_,s,l]),c.jsxs("div",{className:"group flex min-w-0 flex-col gap-1","data-speech-rank":t,"data-search-row":`keyboard.${s}`,"data-search-label":n,"data-search-terms":s,"data-search-control":!0,children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs("div",{className:"flex w-32 flex-col",children:[c.jsx(dr,{htmlFor:e,className:"text-body-sm text-ink",children:t==="primary"?h("ui.settings.shortcuts.speech.primary"):h("ui.settings.shortcuts.speech.secondary")}),c.jsx("span",{className:"text-meta text-ink-muted",children:n})]}),c.jsx(bs,{ref:l,id:e,"aria-label":a,"aria-describedby":`${e}-hint ${e}-notes ${e}-status`,"aria-invalid":x?!0:void 0,"aria-busy":u,"data-shortcut-action":s,className:"w-52 text-left font-mono text-body-sm",value:o,readOnly:!0,onKeyDown:p,onKeyUp:g,onBlur:v}),d&&c.jsx(ce,{variant:"secondary",size:"sm",disabled:u,"aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.reset_label_to_its_default",{label:n}),onClick:f,children:h("ui.settings.shortcuts.keyboard_shortcuts_section.reset")})]}),c.jsxs("div",{className:"ml-0 max-w-88 text-meta text-ink-muted sm:ml-34",children:[c.jsx("p",{children:r}),c.jsx("p",{id:`${e}-hint`,className:"hidden group-focus-within:block",children:i}),c.jsx("div",{id:`${e}-notes`,children:b}),c.jsx("output",{id:`${e}-status`,className:"block","aria-live":"polite",children:u?h("ui.settings.configuration.backend_setting_row.saving"):x?c.jsx("span",{className:"text-danger",children:x}):null})]})]})}function RY({settingKey:e,refetch:t,fieldRef:n,onPending:s,onSaved:r}){const[i,a]=m.useState(!1),[o,l]=m.useState(null),[u,d]=m.useState(!1);return m.useEffect(()=>{!u||i||(n.current?.focus(),d(!1))},[u,i,n]),{saving:i,error:o,setError:l,write:async(p,g)=>{if(!(e===void 0||i||p==="settings.edit"&&g===void 0)){a(!0),l(null),s?.(g);try{await rt(p==="settings.edit"?{op:p,key:e,value:g??""}:{op:p,key:e}),r?.(p,g),await t()}catch(v){let b;if(v instanceof Fi){const x=v.detail;typeof x=="object"&&x!==null&&"code"in x&&x.code==="keymap.conflict"&&"label"in x&&typeof x.label=="string"&&(b=h("ui.settings.shortcuts.capture.already_assigned",{label:x.label}))}l(b??(v instanceof Error?v.message:h(p==="settings.edit"?"ui.settings.configuration.backend_settings_section.the_setting_could_not_be_saved":"ui.settings.configuration.backend_settings_section.the_setting_could_not_be_reset")))}finally{s?.(),a(!1),d(!0)}}}}}function AY(e,t,n,s=[]){const r=/^(Alt|Meta|Control)/.exec(e)?.[1],i=o=>r==="Control"?o.includes("ctrl")||o.includes("primary"):r==="Meta"?o.includes("meta")||t==="darwin"&&o.includes("primary"):r==="Alt"&&o.includes("alt"),a=o=>o.split("+").slice(0,-1);return s.find(o=>i(a(o)))??n.find(o=>i(a(o)))??null}function zit(e,t,n){const s=e.split("+"),r=s.at(-1)??"",i=o=>o==="primary"?t==="Control"||t==="Command"?t:n==="darwin"?"Command":"Control":o==="ctrl"?"Control":o==="shift"?"Shift":o==="alt"?n==="darwin"?"Option":"Alt":o==="meta"?n==="darwin"?"Command":n==="win32"?"Windows":"Super":o,a=r.length===1?r.toUpperCase():r.charAt(0).toUpperCase()+r.slice(1);return[...s.slice(0,-1).map(i),a].join("+")}function qit(e,t,n,s){for(const r of["AltRight","ControlRight","MetaRight"]){const i=W8(r,t);if(i===null)continue;const a=Dd(i);if(!(!a||a.code===e)&&!AY(r,t,n,s))return a.label}return null}const Kit=/^(Alt|Meta|Control|Shift)(Left|Right)$/,$k=e=>e.split("-").slice(1).join("-");function Yit({setting:e,refetch:t,focusKey:n}){const s=WA(),r=nt(F=>F.shortcutBindings),i=m.useRef(null),a=m.useId(),o=m.useMemo(()=>fie(),[]),l=m.useRef(null),u=typeof e.default=="string"?e.default:UN,{saving:d,error:f,setError:p,write:g}=RY({settingKey:e.key,refetch:t,fieldRef:i,onSaved:(F,A)=>pie(F==="settings.edit"?A:u)}),v=h("ui.settings.shortcuts.speech.push_to_talk_hold"),b=typeof e.value=="string"?e.value:"",x=Dd(b)??Dd(u)??Dd(UN),_=Dd(b)?.code===Dd(u)?.code,w=gy.flatMap(F=>{const A=mA(F.id,r);return A?[A]:[]}),y=s.canonical?[s.canonical]:[],S=x===null?null:AY(x.code,o,w,y),C=S===null||x===null?null:qit(x.code,o,w,y),E=h("ui.settings.shortcuts.speech.push_to_talk_letter_pointer"),k=()=>p(h("ui.settings.shortcuts.speech.push_to_talk_refused",{platform:o}));return c.jsx(TY,{id:a,rank:"secondary",action:v,settingKey:e.key,focusKey:n,help:e.help,hint:`${h("ui.settings.shortcuts.speech.push_to_talk_hint")} ${E}`,ariaLabel:h("ui.settings.configuration.setting_control.label_press_the_key_you_want",{label:v}),value:x?.label??"",fieldRef:i,saving:d,showReset:!_,onReset:()=>void g("settings.reset"),onBlur:()=>{l.current=null,p(null)},onKeyDown:F=>{if(d)return;if(F.repeat||F.nativeEvent.isComposing){xE.has(F.key)||F.preventDefault();return}const A=l.current!==null;if(l.current&&(l.current.tainted=!0),xE.has(F.key)){A&&k();return}if(N_.has(F.key)){l.current=null,p(null),F.preventDefault();return}if(F.preventDefault(),A||!Kit.test(F.code)){A||(l.current=null),k();return}p(null),l.current={code:F.code,tainted:!1}},onKeyUp:F=>{const A=l.current;if(!A||F.code!==A.code||(l.current=null,A.tainted||d))return;const I=W8(A.code,o);if(I===null){k();return}Dd(I)?.code!==x?.code&&g("settings.edit",I)},notes:S!==null&&x!==null&&c.jsx("p",{children:h("ui.settings.shortcuts.speech.push_to_talk_overlap",{modifier:$k(x.label),example:zit(S,$k(x.label),o),alternative:C?$k(C):"none"})}),error:f})}function Xit({setting:e,refetch:t,focusKey:n}){const s=m.useRef(!1),r=WA(),i=m.useRef(null),a=m.useId(),o=m.useMemo(()=>ag(),[]),{saving:l,error:u,setError:d,write:f}=RY({settingKey:e.key,refetch:t,fieldRef:i,onPending:S=>window.api?.recordingShortcut?.markPending(S)}),p=h("ui.settings.shortcuts.speech.start_recording_press"),g=typeof e.value=="string"?e.value:r.value,v=r.problem?r.value:g,b=typeof e.default=="string"?e.default:gie,x=Pb(g)===Pb(b),_=S=>h("ui.settings.shortcuts.capture.already_assigned",{label:S}),w=h("ui.chat.composer.start_recording"),y=h("ui.settings.shortcuts.keyboard_shortcuts_section.press_the_keys_you_want_esc_cancels");return c.jsx(TY,{id:a,rank:"primary",action:p,settingKey:e.key,focusKey:n,help:e.help,hint:y,ariaLabel:h("ui.settings.shortcuts.keyboard_shortcuts_section.label_press_the_keys_you_want",{label:p}),value:S5(v,o),fieldRef:i,saving:l,showReset:!x,onReset:()=>void f("settings.reset"),onKeyUp:S=>{!xm.has(S.key)||!s.current||(s.current=!1,d(h("ui.settings.shortcuts.speech.start_recording_needs_key")))},onBlur:()=>{s.current=!1},onKeyDown:S=>{if(l)return;if(S.repeat&&xm.has(S.key)){S.preventDefault();return}if(s.current=xm.has(S.key),N_.has(S.key)||xm.has(S.key)){N_.has(S.key)&&d(null),S.preventDefault();return}const C=$A(S);if(C===null)return;if(S.preventDefault(),Pb(C)===Pb(g)){d(null);return}const E=nt.getState().shortcutBindings,k=$8(r,_(w));for(const A of gy){const I=E[A.id]??A.defaultChord;I&&k.set(I,A.label)}const F=k5(C,"panel.console",{},o,k);if(F!==null){d(F);return}f("settings.edit",C)},notes:c.jsxs(c.Fragment,{children:[r.shadowedBy&&!u&&c.jsx("output",{className:"block text-danger",children:h("ui.settings.shortcuts.recording.inactive_claimed",{label:r.shadowedBy})}),r.problem&&!u&&c.jsx("output",{className:"block text-danger",children:h("ui.settings.shortcuts.recording.invalid_stored_value")})]}),error:u})}function Qit({focusKey:e}){const{client:t,provided:n}=nZ(),s=Dn({queryKey:No.settings,queryFn:()=>rt({op:"settings.list"}),enabled:n,staleTime:1e4},t),r=l=>s.data?.settings.find(u=>u.key===l),i=r(mie),a=r(vie);if(!n)return null;const o=c.jsx("h3",{className:"pt-1 text-body-sm font-medium text-ink",children:h("ui.settings.shortcuts.category.speech_to_text")});return!i&&!a?s.isPending?c.jsx("div",{className:"min-h-24 space-y-3","aria-busy":"true",children:o}):null:c.jsxs("div",{className:"space-y-3","data-shortcut-recording":!0,children:[o,i&&c.jsx(Xit,{setting:i,refetch:s.refetch,focusKey:e}),a&&c.jsx(Yit,{setting:a,refetch:s.refetch,focusKey:e})]})}const FY=e=>{switch(e.id){case"panel.console":return h("ui.settings.shortcuts.row.console");case"panel.canvas":return h("ui.settings.shortcuts.row.canvas");case"panel.run":return h("ui.settings.shortcuts.row.execution");case"panel.ask":return h("ui.settings.shortcuts.row.asks");case"panel.browser":return h("ui.settings.shortcuts.row.browser");case"panel.code":return h("ui.settings.shortcuts.row.code_review")}},Jit=()=>h("ui.chat.composer.start_recording");function Zit(){m.useEffect(()=>{let e=0;const t=()=>{const r=nt.getState().shortcutBindings,i=new Map(sZ);for(const a of gy){const o=mA(a.id,r);if(!o)continue;const l=FY(a);for(const u of bie(o,ag()))i.set(u,l)}window.api?.recordingShortcut?.syncClaims(++e,[...i].map(([a,o])=>({chord:a,label:o})))};t();const n=nt.subscribe((r,i)=>{r.shortcutBindings!==i.shortcutBindings&&t()}),s=$X(t);return()=>{n(),s()}},[])}const eat=({action:e})=>{const t=WA(),n=$8(t,Jit());Ve();const s=m.useId(),r=m.useRef(null),i=nt(x=>x.shortcutBindings),a=i[e.id],o=nt(x=>x.setShortcutBinding),l=nt(x=>x.clearShortcutBinding),[u,d]=m.useState(!1),[f,p]=m.useState(null),g=m.useMemo(ag,[]),v=mA(e.id,i),b=FY(e);return c.jsxs("div",{"data-search-row":`keyboard.${e.id}`,"data-search-control":!0,className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx(dr,{htmlFor:s,className:"w-32 text-body-sm text-ink",children:b}),c.jsx(bs,{id:s,readOnly:!0,value:v===null?h("ui.settings.shortcuts.keyboard_shortcuts_section.no_shortcut"):S5(v,g),"aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.label_press_the_keys_you_want",{label:String(b)}),"data-shortcut-action":e.id,ref:r,className:R("w-52",v===null?"text-body-sm":"font-mono text-body-sm"),onFocus:()=>d(!0),onBlur:()=>{d(!1),p(null)},onKeyDown:x=>{if(xE.has(x.key))return;if(N_.has(x.key)){d(!1),p(null);return}if(xm.has(x.key)||x.nativeEvent.isComposing)return;const _=$A({key:x.key,code:x.code,metaKey:x.metaKey,ctrlKey:x.ctrlKey,altKey:x.altKey,shiftKey:x.shiftKey}),w=k5(_,e.id,i,g,n);if(w!==null){x.preventDefault(),d(!0),p(w);return}if(_===v){d(!0),p(null);return}x.preventDefault(),d(!0),p(null),_===e.defaultChord?o(e.id,null,n):_!==null&&o(e.id,_,n)}}),v!==null&&c.jsx(ce,{variant:"secondary",size:"sm","aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.clear_label_s_shortcut",{label:String(b)}),onClick:()=>{l(e.id),r.current?.focus()},children:h("ui.settings.shortcuts.keyboard_shortcuts_section.clear")}),a!==void 0&&c.jsx(ce,{variant:"secondary",size:"sm","aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.reset_label_to_its_default",{label:String(b)}),onClick:()=>{o(e.id,null,n),r.current?.focus()},children:h("ui.settings.shortcuts.keyboard_shortcuts_section.reset")})]}),u&&c.jsx("span",{className:"text-meta text-ink-dim",children:h("ui.settings.shortcuts.keyboard_shortcuts_section.press_the_keys_you_want_esc_cancels")}),f!==null&&c.jsx("output",{className:"text-meta text-danger",children:f})]})},Odt=({sectionRef:e,focusKey:t})=>(Ve(),c.jsx(EY,{title:h("ui.settings.shortcuts.keyboard_shortcuts_section.keyboard_shortcuts"),icon:vU,description:h("ui.settings.shortcuts.keyboard_shortcuts_section.shortcut_capture_description"),sectionRef:e,searchSection:"keyboard",searchSectionLabel:h("ui.settings.navigation.settings_sidebar.keyboard_shortcuts"),children:c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsx("p",{"data-shortcut-note":"browser-scope",className:"max-w-2xl text-body-sm text-ink-muted",children:h("ui.settings.shortcuts.keyboard_shortcuts_section.browser_shortcuts_answer_only_while_the_browser_has_focus")}),c.jsx(Qit,{focusKey:t}),c.jsx("h3",{className:"pt-1 text-body-sm font-medium text-ink",children:h("ui.settings.shortcuts.category.panels")}),c.jsx("div",{className:"flex flex-col gap-4",children:gy.map(n=>c.jsx(eat,{action:n},n.id))})]})}));async function tat(e){await rt({op:"settings.edit",key:hl,value:e.value}),wie(e.queryClient)}async function DY(e){await tat(e),e.queryClient.setQueryData(P_.all,t=>t&&{...t,settings:t.settings.map(n=>n.key===hl?{...n,value:e.value,is_default:e.value===n.default}:n)});try{return await e.queryClient.fetchQuery({queryKey:P_.all,queryFn:()=>rt({op:"settings.list"}),staleTime:0,retry:!1}),"confirmed"}catch{return"readback-unknown"}}const Ldt=({focus:e=!1,focusNonce:t})=>{Ve();const n=Mt(),s=ss(),r=Et(s.data,"settings"),i=Dn({queryKey:P_.all,queryFn:()=>rt({op:"settings.list"}),enabled:r,retry:!1,refetchOnReconnect:!0}),a=i.data?.settings.find(I=>I.key===hl),[o,l]=m.useState(!1),[u,d]=m.useState(null),[f,p]=m.useState(!1),[g,v]=m.useState(!1),b=m.useRef(!1),x=m.useRef(null),_=m.useRef(!1),w=m.useRef(t);m.useEffect(()=>{t!==w.current&&(w.current=t,_.current=!1)},[t]),m.useEffect(()=>{if(!e){_.current=!1;return}!a||_.current||(x.current?.querySelector("[role=combobox]")?.focus(),_.current=!0)},[e,t,a]),m.useEffect(()=>{i.isSuccess&&!i.isFetching&&p(!1)},[i.isFetching,i.isSuccess]);const y=async I=>{if(!(!a||b.current||f||!a.choices.some(N=>N.value===I))){b.current=!0,l(!0),d(null),v(!1);try{const N=await DY({value:I,queryClient:n});p(N==="readback-unknown"),v(N==="confirmed")}catch(N){d({value:I,message:N instanceof Error?N.message:""})}finally{b.current=!1,l(!1)}}},S=async()=>{const[I,N]=await Promise.all([i.refetch(),s.refetch()]);!I.isError&&!N.isError&&p(!1)},C=!i.data&&i.error||!s.data&&s.error,E=s.data&&(!r||i.data&&!a),k=!C&&!E&&!a,F=s.data?.features?.i18n?s.data.language:void 0,A=typeof F=="string"&&F!==""?F:void 0;return c.jsx(EY,{title:h("ui.settings.language.dialog.title"),icon:bU,description:h("ui.settings.language.general.description"),children:c.jsxs("div",{ref:x,"data-setting-key":hl,"data-search-row":"general.language","data-search-control":!0,className:"flex flex-col gap-3","aria-busy":o,children:[k&&c.jsx("output",{className:"text-meta text-ink-dim",children:h("ui.settings.language.dialog.loading")}),E&&c.jsx("p",{className:"text-meta text-ink-dim",children:h("ui.settings.language.dialog.unavailable")}),a&&c.jsx(z8,{setting:{...GA(a),label:h("ui.settings.language.dialog.title")},value:String(a.value),onValueChange:I=>{y(I)},disabled:o||f,suppressEffectiveNote:!0}),c.jsx("output",{id:xie(hl),"aria-live":"polite",className:"text-meta text-ink-dim",children:o?h("ui.settings.language.general.pending"):g?h("ui.settings.language.general.saved"):A?h(f||s.error?"ui.settings.language.general.last_known":"ui.settings.language.general.effective",{locale:_ie(A)?.name??A}):h("ui.settings.language.general.no_resolution")}),(C||u||f)&&c.jsx(Rr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:u?h("ui.settings.language.general.write_error",{message:u.message}):f?h("ui.settings.language.general.readback_error"):h("ui.settings.language.dialog.unavailable")}),c.jsx(ce,{variant:"outline",size:"sm",disabled:o||i.isFetching||s.isFetching,onClick:()=>{u?y(u.value):S()},children:h("ui.settings.language.dialog.retry")})]})})]})})},nat=()=>{Ve();const e=g_(O=>O.open),t=g_(O=>O.closeLanguage),n=Mt(),s=ss(),r=Et(s.data,"settings"),i=Dn({queryKey:P_.all,queryFn:()=>rt({op:"settings.list"}),enabled:e&&r,staleTime:1e4}),a=m.useRef(null),o=F8(),l=(i.data?.settings??[]).find(O=>O.key===hl),u=l?GA(l):void 0,[d,f]=m.useState(!1),[p,g]=m.useState(!1),[v,b]=m.useState(null),[x,_]=m.useState(!1),w=m.useRef(!1);m.useEffect(()=>{e&&(g(!1),b(null))},[e]);const y=String(u?.value??""),S=async O=>{if(!(!u||w.current||x||!u.choices.some(X=>X.value===O))){w.current=!0,f(!0),b(null),g(!1);try{const X=await DY({value:O,queryClient:n});_(X==="readback-unknown"),g(X==="confirmed")}catch(X){const Q=X instanceof Error?X.message:"";b({value:O,message:Q}),g_.getState().open||nn(h("ui.settings.language.general.write_error",{message:Q}))}finally{w.current=!1,f(!1)}}},C=async()=>{const[O,X]=await Promise.all([i.refetch(),s.refetch()]);!O.isError&&!X.isError&&_(!1)},E=!!s.data,k=E&&!r,F=s.error&&!s.data?s.error:null,A=F??(i.data?null:i.error),I=!E&&!A,{sentence:N,remedy:P}=rZ(o??null,h("ui.settings.configuration.language_dialog.your_settings_could_not_be_loaded"),A),M=s.isFetching||i.isFetching,Y=u?"combo":A?"retry":"none";return m.useEffect(()=>{!e||Y==="none"||requestAnimationFrame(()=>{a.current?.querySelector(Y==="combo"?'[role="combobox"]':"[data-language-retry]")?.focus()})},[e,Y]),c.jsx(Tc,{open:e,onOpenChange:O=>!O&&t(),children:c.jsxs(Rc,{ref:a,onOpenAutoFocus:O=>O.preventDefault(),className:"max-w-[min(28rem,calc(100vw-4rem))] gap-4",children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx(wl,{className:"text-title",children:h("ui.settings.language.dialog.title")}),c.jsx(Zu,{className:"text-body-sm text-ink-muted",children:h("ui.settings.language.dialog.description")})]}),I?c.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(On,{}),h("ui.settings.language.dialog.loading")]}):k?c.jsx(Rr,{variant:"warning",children:c.jsx("span",{children:h("ui.settings.language.dialog.unavailable")})}):A?c.jsx(Rr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:N}),P&&c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0","data-language-retry":"",onClick:()=>{F?s.refetch():i.refetch()},disabled:M,children:M?h("ui.settings.language.dialog.retrying"):h("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(On,{}),h("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:GN(hl),className:"text-meta text-ink-dim",children:u.help}),c.jsx(z8,{setting:u,value:y,disabled:d||x,helpId:GN(hl),effectiveNoteId:yie(hl,Cie),onValueChange:O=>{S(O)}})]}),v&&c.jsx(Rr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:h("ui.settings.language.general.write_error",{message:v.message})}),c.jsx(ce,{variant:"outline",size:"sm",disabled:d||i.isFetching,onClick:()=>{S(v.value)},children:h("ui.settings.language.dialog.retry")})]})}),x&&c.jsx(Rr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:h("ui.settings.language.general.readback_error")}),c.jsx(ce,{variant:"outline",size:"sm",disabled:d||i.isFetching||s.isFetching,onClick:()=>{C()},children:h("ui.settings.language.dialog.retry")})]})}),c.jsx("div",{className:"flex min-h-8 items-center justify-end",children:d?c.jsx("output",{"aria-live":"polite",className:"text-body-sm text-ink-muted",children:h("ui.settings.language.general.pending")}):p?c.jsxs("output",{"data-language-status":"","aria-live":"polite",className:"inline-flex items-center gap-1.5 text-body-sm text-ink",children:[c.jsx(Js,{"aria-hidden":"true",className:"size-3.5"}),h("ui.settings.language.dialog.saved")]}):null})]}):c.jsx(Rr,{variant:"warning",children:c.jsx("span",{children:h("ui.settings.language.dialog.unavailable")})})]})})},Iv=320,sat=360,rat=320,iat=/^[A-Za-z0-9_.:-]{1,128}$/,aat=/^[0-9a-f]{16}$/;function IY(e){const t=e.codePointAt(0)??0;return e==="<"||e===">"||t<32||t>=127&&t<=159||t===1564||t===8206||t===8207||t>=8234&&t<=8238||t>=8294&&t<=8297||t===8232||t===8233}function oat(e){return Array.from(e).some(IY)}const lat=/\s+/g,cat=new Intl.Segmenter(void 0,{granularity:"grapheme"});function NY(e,t,n="points"){let s=0,r="";for(const{segment:i}of cat.segment(e)){const a=n==="points"?Array.from(i).length:i.length;if(s+a>t)return`${r.trimEnd()}…`;r+=i,s+=a}return r}function Ap(e,t){let n="";for(const r of e)r==="<"?n+="‹":r===">"?n+="›":n+=IY(r)?" ":r;const s=n.replace(lat," ").trim();return s.length<=t?s:NY(s,Math.max(0,t-1),"units")}function uat(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(t.v!==1||t.kind!=="person"&&t.kind!=="person_agent")return;const n=dat(t.account_id),s=N6(t.display_name,Iv),r=N6(t.agent_name,Iv);if(!n||!s||t.kind==="person_agent"&&!r)return;const i=t.avatar,a=i&&typeof i=="object"&&i.account_id===n&&typeof i.hash=="string"&&aat.test(i.hash)?{account_id:n,hash:i.hash}:void 0;return{v:1,kind:t.kind,account_id:n,display_name:s,...t.kind==="person_agent"?{agent_name:r}:{},...a?{avatar:a}:{}}}function dat(e){return typeof e=="string"&&iat.test(e)?e:null}function N6(e,t){if(typeof e!="string")return null;const n=e.trim();return n.length===0||n.length>t||oat(e)?null:n}const Bdt=!0,jdt=!0;function hat(e){return`/team-bridge?${new URLSearchParams({tenant:e.tenantId,conversation:e.conversationId,...e.threadId?{thread:e.threadId}:{},...e.messageId?{message:e.messageId}:{}}).toString()}`}function P6(e){return JSON.stringify([sp(e),qA(e)])}function fat(e,t){const n=Mt(),s=m.useCallback(u=>zA(n,u),[n]),r=m.useCallback(()=>P6(n),[n]),i=m.useSyncExternalStore(s,r,r),a={...$r(n),token:i},[o,l]=m.useState(null);m.useEffect(()=>{let u=!0;const d=window.api?.desktop?.teamBridge,f=()=>{d?.pendingOpen?.().then(g=>{u&&g&&l(g)}).catch(()=>{})},p=d?.onOpen?.(f);return f(),()=>{u=!1,p?.()}},[]),m.useEffect(()=>{if(!o||qA(n)||a.token!==P6(n))return;const u=$r(n).accountId;if("unavailable"in o||!o.owner?.accountId||o.owner.accountId!==u){da(h("ui.teamBridge.notify.unavailable")),l(null);return}!e||a.accountId!==u||(t(hat(o)),l(null))},[o,e,t,n,a.accountId,a.token])}const ur=je.string().min(1).max(128),PY="team_bridge_owner_guard_unavailable",pat=je.object({account_id:ur,kind:je.enum(["human","agent"]),display_label:je.string().min(1).max(64),role:je.enum(["owner","member"]),state:je.enum(["invited","active","left","removed"]),joined_seq:je.number().int().nonnegative().optional()}).passthrough(),MY=je.enum(["all","mention","mute"]),pu=je.object({id:ur,tenant_id:ur,kind:je.enum(["dm","group","channel"]),name:je.string().optional(),topic:je.string().optional(),visibility:je.enum(["private","tenant"]),agent_capable:je.boolean(),status:je.enum(["open","archived"]),created_by:ur,last_message_at:je.string(),latest_seq:je.number().int().nonnegative(),members:je.array(pat),last_read_seq:je.number().int().nonnegative(),unread_count:je.number().int().nonnegative(),muted:je.boolean(),discoverable:je.boolean().optional(),member:je.boolean().optional(),member_count:je.number().int().nonnegative().optional(),notify:MY.optional(),last_sender_label:je.string().min(1).max(64).optional(),last_thread_root_id:ur.optional(),builtin:je.string().min(1).max(32).optional(),can_administer:je.boolean().optional(),archived_at:je.string().optional(),archived_by:ur.optional(),archived_by_label:je.string().min(1).max(64).optional()}).passthrough(),gat=je.object({conversations:je.array(pu),has_more:je.boolean().optional(),next_before:je.string().optional(),next_cursor:je.string().optional()}).passthrough(),OY=je.object({emoji:je.string().min(1),count:je.number().int().positive(),reacted_by_me:je.boolean(),sample_labels:je.array(je.string()).max(3)}).passthrough(),mat=je.object({message_id:ur,reactions:je.array(OY).max(50)}).passthrough(),vat=OY.extend({sample_labels:je.array(je.string()).transform(e=>e.slice(0,3))}),bat=je.array(vat).transform(e=>e.slice(0,50)),LY=je.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),JD=je.object({id:LY,mime:je.string().max(64),size:je.number().int().nonnegative(),width:je.number().int().nonnegative(),height:je.number().int().nonnegative(),sha256:je.string().max(128).optional(),state:je.string().max(32).optional(),expires_at:je.string().optional()}).passthrough(),xat=je.object({attachment:JD}).passthrough(),Hdt=je.object({enabled:je.boolean(),max_count:je.number().int().positive().max(16),max_bytes:je.number().int().positive(),max_pixels:je.number().int().positive().optional(),mime_types:je.array(je.string())}).passthrough(),eA=je.object({id:ur,conversation_id:ur,seq:je.number().int().nonnegative(),sender:je.object({account_id:ur,kind:je.enum(["human","agent"]),display_label:je.string().min(1).max(64)}).passthrough(),body:je.string().nullable(),body_hash:je.string().optional(),origin:je.enum(["human","agent","system"]),agent_label:je.string().optional(),created_at:je.string(),reactions:bat.optional(),thread_root_id:ur.optional(),reply_count:je.number().int().nonnegative().optional(),last_reply_at:je.string().optional(),reply_participants:je.array(je.string()).optional(),attachments:je.array(JD).max(16).optional()}).passthrough(),_at=je.object({root:eA,replies:je.array(eA),next_after_seq:je.number().int().nonnegative().optional(),has_more:je.boolean().optional()}).passthrough(),wat=["invited","joined","left","removed","consented","declined","withdrawn"],yat=["owner_invite","dm_receive_policy"];function Cat(e){return wat.includes(e)?e:null}function Sat(e){return e!==void 0&&yat.includes(e)?e:null}const M6=je.object({kind:je.enum(["human","agent"]),account_id:je.string(),endpoint_id:je.string().optional(),display_label:je.string().max(64).catch("")}).passthrough(),kat=je.object({id:ur,event_seq:je.number().int().nonnegative(),kind:je.string(),implicit:je.boolean().optional(),implicit_reason:je.string().optional(),actor:M6,targets:je.array(M6),request_id:je.string().optional(),after_seq:je.number().int().nonnegative(),at:je.string()}).passthrough(),Eat=je.array(je.unknown()).transform(e=>e.flatMap(t=>{const n=kat.safeParse(t);return n.success?[n.data]:[]})),Tat=je.object({messages:je.array(eA),next_before_seq:je.number().int().nonnegative().optional(),has_more:je.boolean().optional(),events:Eat.optional().catch(void 0),events_truncated:je.boolean().optional()}).passthrough(),Rat=je.object({tenant_id:ur,tenant_name:je.string(),unread:je.number().int().nonnegative(),eligible:je.boolean()}).passthrough(),Aat=je.object({total:je.number().int().nonnegative(),conversations:je.array(je.object({conversation_id:ur,unread_count:je.number().int().nonnegative(),last_read_seq:je.number().int().nonnegative(),latest_seq:je.number().int().nonnegative(),muted:je.boolean()}).passthrough()).optional(),organizations:je.array(Rat).optional()}).passthrough(),BY=je.enum(["active","paused","disabled","none"]),jY=je.object({endpoint_id:ur,name:je.string().max(128),state:je.string().min(1).max(32)}).passthrough(),tA=je.object({display_name:je.string().refine(e=>Array.from(e).length<=64).catch(""),title:je.string().refine(e=>Array.from(e).length<=80).catch(""),description:je.string().refine(e=>Array.from(e).length<=500).catch(""),pronouns:je.string().refine(e=>Array.from(e).length<=32).catch(""),timezone:je.string().refine(e=>Array.from(e).length<=64).catch(""),avatar:je.object({source:je.enum(["uploaded","google","microsoft","none"]),hash:je.string().regex(/^[0-9a-f]{16}$/),updated_at:je.string()}).passthrough().optional().catch(void 0)}).passthrough(),nA=je.string().max(512).regex(/^\/v1\/accounts\/(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|acc_[a-zA-Z0-9_-]{1,64})\/avatar\?v=[0-9a-f]{16}$/).optional().catch(void 0),Fat=je.object({account_id:ur,display_label:je.string(),role:je.string().min(1).max(32),bridge_enabled:je.boolean(),bridge_state:BY,agent:jY.optional().catch(void 0),profile:tA.optional().catch(void 0),avatar_url:nA}).passthrough();function Dat(e){if(e===null||typeof e!="object")return null;const t=e,n=t.account_id;if(typeof n!="string"||n.length===0)return null;const s=typeof t.display_label=="string"?t.display_label:"",r=typeof t.role=="string"&&t.role.length>0?t.role:"member",i=t.bridge_enabled===!0,a=BY.safeParse(t.bridge_state),o=jY.safeParse(t.agent);return{account_id:n,display_label:s,role:r,bridge_enabled:i,bridge_state:a.success?a.data:"none",...o.success?{agent:o.data}:{},profile:tA.safeParse(t.profile).success?tA.parse(t.profile):void 0,avatar_url:nA.safeParse(t.avatar_url).success?nA.parse(t.avatar_url):void 0}}const Iat=je.object({members:je.array(je.unknown())}).passthrough().transform(e=>{const t=[];let n=0;for(const s of e.members){const r=Fat.safeParse(s);if(r.success){t.push(r.data);continue}const i=Dat(s);i?t.push(i):n+=1}return{...e,members:t,unavailable_count:n}}),Nat=je.object({account_id:je.string().min(1).nullable().optional()}).passthrough(),O6=je.object({conversation_id:ur,last_read_seq:je.number().int().nonnegative(),unread_count:je.number().int().nonnegative(),muted:je.boolean(),notify:MY.optional()}).passthrough(),sA=je.object({id:ur,tenant_id:ur,conversation_id:ur,body:je.string(),send_at:je.string().datetime({offset:!0}),status:je.enum(["scheduled","sending"]),created_at:je.string().datetime({offset:!0}),version:je.number().int().nonnegative().nullish(),attachments:je.array(JD).max(16).optional(),attachment_ids:je.array(LY).max(16).optional()}).transform(({attachment_ids:e,...t})=>t.attachments!==void 0||!e?.length?t:{...t,attachments:e.map(n=>({id:n,mime:"",size:0,width:0,height:0,state:"reserved"}))}),Pat=je.object({scheduled:je.array(sA)});class zk extends Error{status;code;constructor(t,n){super("team bridge attachment request failed"),this.name="TeamBridgeAttachmentError",this.status=t,this.code=n}}async function Fa(e,t){if(!e||!t)throw new Error("Team Bridge write owner and tenant required");if(((await rt({op:"capabilities"})).features?.team_bridge_conversation_owner_guard??0)<1)throw Object.assign(new Error("Team Bridge runtime owner guard unavailable"),{code:PY});return{expected_account_id:e,tenant_id:t}}function Mat(e){if(!e)throw new Error("Team Bridge write account required");return e}const _s={async scheduledList(e){return Pat.parse(await rt({op:"team_bridge.scheduled.list",tenant_id:e}))},async scheduledCreate(e){return sA.parse(await rt({op:"team_bridge.scheduled.create",...e}))},async scheduledUpdate(e,t,n){return sA.parse(await rt({op:"team_bridge.scheduled.update",tenant_id:e,scheduled_id:t,...n}))},async scheduledCancel(e,t){return rt({op:"team_bridge.scheduled.cancel",tenant_id:e,scheduled_id:t})},async react(e,t,n,s,r,i){const a=await rt({op:"team_bridge.reactions.toggle",conversation_id:e,message_id:t,emoji:n,active:s,tenant_id:r,expected_account_id:i});return mat.parse(a)},async listConversations(e,t,n){const s=await rt({op:"team_bridge.conversations.list",...e==="account"?{scope:"account"}:{tenant_id:e.tenantId},...t?{status:t}:{},...n?{cursor:n}:{}}),r=gat.parse(s);return t?{...r,conversations:r.conversations.filter(i=>i.status===t)}:r},async getConversation(e,t){const n=await rt({op:"team_bridge.conversations.get",conversation_id:e,...t?{tenant_id:t}:{}});return pu.parse(n)},async startConversation(e){const t=await rt({op:"team_bridge.conversations.create",...await Fa(e.expectedAccountId,e.tenantId),kind:e.kind,...e.tenantId?{tenant_id:e.tenantId}:{},...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agentCapable===void 0?{}:{agent_capable:e.agentCapable},members:e.members});return pu.parse(t)},async addMembers(e){const t=await rt({op:"team_bridge.conversations.members.add",...await Fa(e.expectedAccountId,e.tenantId),conversation_id:e.conversationId,members:e.members});return pu.parse(t)},async removeMember(e){const t=await rt({op:"team_bridge.conversations.members.remove",...await Fa(e.expectedAccountId,e.tenantId),conversation_id:e.conversationId,account_id:e.accountId});return pu.parse(t)},async listMessages(e,t={}){const n=await rt({op:"team_bridge.messages.list",conversation_id:e,...t.tenantId?{tenant_id:t.tenantId}:{},...t.limit===void 0?{}:{limit:t.limit},...t.beforeSeq===void 0?{}:{before_seq:t.beforeSeq}});return Tat.parse(n)},async listReplies(e,t,n){const s=await rt({op:"team_bridge.messages.replies",conversation_id:e,message_id:t,tenant_id:n.tenantId,expected_account_id:n.accountId,...n.limit===void 0?{}:{limit:n.limit},...n.afterSeq===void 0?{}:{after_seq:n.afterSeq}});return _at.parse(s)},async send(e,t){return rt({op:"team_bridge.messages.send",...t.threadRootId?{}:await Fa(t.expectedAccountId,t.tenantId),conversation_id:e,client_ref:t.clientRef,body:t.body,...t.expectedAccountId?{expected_account_id:t.expectedAccountId}:{},...t.tenantId?{tenant_id:t.tenantId}:{},...t.threadRootId?{thread_root_id:t.threadRootId}:{},...t.attachmentIds?.length?{attachment_ids:[...t.attachmentIds]}:{},...t.mentions?.length?{mentions:[...t.mentions]}:{}})},async uploadAttachment(e,t,n,s){const r=await t1({op:"team_bridge.attachment.upload",tenantId:e,conversationId:t,expectedAccountId:s},n);if(r.kind!=="json")throw new zk(r.kind==="error"?r.status:null,r.kind==="error"?r.code:void 0);const i=r.body;return xat.parse(i&&typeof i=="object"&&"result"in i?i.result:i).attachment},async deleteAttachment(e,t,n,s){return rt({op:"team_bridge.attachments.delete",tenant_id:e,expected_account_id:s,conversation_id:t,attachment_id:n})},async attachmentBytes(e){const t=await t1({op:"team_bridge.attachment",...e},null);if(t.kind!=="bytes")throw new zk(t.kind==="error"?t.status:null,t.kind==="error"?t.code:void 0);return{data:t.data,mimeType:t.mimeType}},async avatarBytes(e){const t=await t1({op:"team_bridge.avatar",...e},null);if(t.kind!=="bytes")throw new zk(t.kind==="error"?t.status:null,t.kind==="error"?t.code:void 0);return{data:t.data,mimeType:t.mimeType}},async markRead(e,t){const n=await rt({op:"team_bridge.read",...await Fa(t.expectedAccountId,t.tenantId),conversation_id:e,...t.tenantId?{tenant_id:t.tenantId}:{},...t.seq===void 0?{}:{seq:t.seq},...t.muted===void 0?{}:{muted:t.muted}});return O6.parse(n)},async identity(){const e=await rt({op:"agent_messages.status",boundary:"surface_open"}),t=Nat.parse(e);return mT(gT(),t),t.account_id??null},async unread(e){const t=await rt({op:"team_bridge.unread",...e==="account"?{scope:"account"}:{tenant_id:e.tenantId}});return Aat.parse(t)},async directory(e){const t=await rt({op:"team_bridge.directory",tenant_id:e});return Iat.parse(t)},async status(e){const t=await rt({op:"team_bridge.status",...e?{boundary:e}:{}}),n=c5.parse(t);return mT(gT(),n),n},async setArchived(e,t,n,s){return rt({op:"team_bridge.conversations.lifecycle",conversation_id:e,action:t?"archive":"unarchive",...await Fa(s,n)})},async deleteConversation(e,t,n){return rt({op:"team_bridge.conversations.delete",conversation_id:e,...await Fa(n,t)})},async leave(e,t,n){return rt({op:"team_bridge.conversations.lifecycle",conversation_id:e,action:"leave",...await Fa(n,t)})},async join(e,t,n){const s=await rt({op:"team_bridge.conversations.join",...await Fa(n,t),conversation_id:e,...t?{tenant_id:t}:{}});return pu.parse(s)},async answerAgentInvitation(e){const t=await rt({op:"team_bridge.conversations.consent",...await Fa(e.accountId,e.tenantId),conversation_id:e.conversationId,account_id:e.accountId,decision:e.decision,consent_version:e.consentVersion});return pu.parse(t)},async setNotify(e,t,n,s){const r=await rt({op:"team_bridge.conversations.notify",...await Fa(s,n),conversation_id:e,...n?{tenant_id:n}:{},notify:t});return O6.parse(r)},async setAgentNotify(e){const t=await rt({op:"team_bridge.conversations.agent_notify",...await Fa(e.accountId,e.tenantId),conversation_id:e.conversationId,notify:e.notify});return pu.parse(t)}},rA=new WeakMap,Oat=64,Lat=1024*1024,Bat=3e3;function jat(e){const t=rA.get(e);if(t)return t;const n=new Map;rA.set(e,n);let s=sp(e);return zA(e,()=>{const r=sp(e);if(r===s)return;s=r;const i=[...n.values()];n.clear();for(const a of i){a.url&&I_(a.url),a.url=void 0;for(const o of a.listeners)o()}}),n}function Hat(e){if(e.size<Oat)return!0;for(const[t,n]of e)if(!(n.listeners.size||n.promise))return n.url&&I_(n.url),e.delete(t),!0;return!1}const HY=/^\/v1\/accounts\/((?:acc_[A-Za-z0-9_-]{1,64})|(?:[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}))\/avatar\?v=([0-9a-f]{16})$/;function UY(e){if(!e?.avatar_url)return null;const t=HY.exec(e.avatar_url);return!t||t[1]!==e.account_id||e.profile?.avatar&&e.profile.avatar.hash!==t[2]?null:{accountId:t[1],hash:t[2]}}const Uat=/^(?:acc_[A-Za-z0-9_-]{1,64}|[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12})$/,Gat=/^[0-9a-f]{16}$/;function Vat(e){const t=e?.id,n=e?.profile?.avatar;if(!t||!Uat.test(t)||!n||!n.hash||!Gat.test(n.hash)||n.source==="none")return null;if(e.avatar_url){const s=HY.exec(e.avatar_url);if(!s||s[1]!==t||s[2]!==n.hash)return null}return{accountId:t,hash:n.hash}}function Udt(e,t){const n=m.useMemo(()=>UY(e),[e]);return GY(n,t)}function Wat(e,t){const n=ug(),s=e?.id,r=e?.profile?.avatar?.hash,i=e?.profile?.avatar?.source,a=e?.avatar_url,o=m.useMemo(()=>Vat({id:s,avatar_url:a,profile:{avatar:{hash:r,source:i}}}),[s,r,i,a]);return GY(o&&o.accountId===n.accountId?o:null,t,{retryOnce:!0})}function GY(e,t,n={}){const s=n.retryOnce===!0,r=Mt(),i=ug(),a=e?`${i.epoch}:${i.accountId??"none"}:${e.accountId}:${e.hash}:${t}`:null,[,o]=m.useState(0),l=m.useRef(!0);if(m.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]),m.useEffect(()=>{if(!a||!e||!i.accountId)return;const u=jat(r),d=u.get(a),f=d??{failed:!1,listeners:new Set,retried:!1},p=i.epoch,g=i.accountId,v=()=>{f.failed=!1,f.promise=_s.avatarBytes({expectedAccountId:g,accountId:e.accountId,hash:e.hash,size:t}).then(({data:w,mimeType:y})=>{if(u.get(a)!==f)return;const S=$r(r);if(S.epoch!==p||S.accountId!==g){u.delete(a);return}if(!["image/png","image/jpeg"].includes(y)||w.byteLength===0||w.byteLength>Lat)throw new Error("Invalid avatar bytes");f.url=y8(new Blob([w],{type:y}),y)}).catch(()=>{f.failed=!0}).finally(()=>{if(f.promise=void 0,u.get(a)===f)for(const w of f.listeners)w()})};if(!d){if(!Hat(u))return;u.set(a,f),v()}let b=!1;const x=()=>{!s||!f.failed||f.promise||f.retried||(f.retried=!0,b=!0,f.retryTimer=setTimeout(()=>{if(f.retryTimer=void 0,b=!1,u.get(a)!==f||!f.failed)return;const w=$r(r);w.epoch!==p||w.accountId!==g||v()},Bat))};u.delete(a),u.set(a,f);const _=()=>{x(),l.current&&o(w=>w+1)};return f.listeners.add(_),x(),()=>{f.listeners.delete(_),b&&f.retryTimer&&(clearTimeout(f.retryTimer),f.retryTimer=void 0,f.retried=!1)}},[i.accountId,i.epoch,a,r,s,t,e]),!(!a||!i.accountId))return rA.get(r)?.get(a)?.url}const $at=140,zat=/^\s*(```|~~~).*$/gm,qat=/^\s{0,3}#{1,6}\s+/gm,Kat=/^\s{0,3}(>\s?)+/gm,Yat=/^\s*([-*+]|\d{1,9}[.)])\s+/gm,Xat=/^\[[ xX]\]\s+/gm,Qat=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/gm,Jat=/!\[([^\]]*)\]\([^)]*\)/g,Zat=/\[([^\]]+)\]\([^)]*\)/g,eot=/<((?:https?|mailto):[^>\s]+)>/gi,tot=/<\/?[A-Za-z][^>]*>/g,not=/`+([^`]*)`+/g,sot=/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,rot=/~~(?=\S)([\s\S]*?\S)~~/g,iot=/(^|[^\w*])\*(?=\S)([^*]*?\S)\*(?!\w)/g,aot=/(^|[^\w])_(?=\S)([^_]*?\S)_(?!\w)/g;function oot(e,t=$at){if(typeof e!="string"||e.trim().length===0)return null;const n=e.replace(zat," ").replace(Qat," ").replace(qat,"").replace(Kat,"").replace(Yat,"").replace(Xat,"").replace(Jat,"$1").replace(Zat,"$1").replace(eot,"$1").replace(tot,"").replace(not,"$1").replace(sot,"$2").replace(rot,"$1").replace(iot,"$1$2").replace(aot,"$1$2"),s=Ap(n,Number.MAX_SAFE_INTEGER);return s.length===0?null:NY(s,t)}function lot(e,t){const n=e.senderLabel?.trim()||e.conversationName?.trim()||t.untitled,s=e.place.kind==="dm"?t.directMessage:e.place.kind==="channel"?e.place.name?.trim()?t.channel(e.place.name.trim()):e.conversationName?.trim()??t.untitled:e.place.name?.trim()||e.conversationName?.trim()||t.group,r=e.organizationName?t.subtitle(s,e.organizationName):s,i=Math.max(1,Math.floor(e.unreadCount)),a=i>1?e.preview?t.countPreview(i,e.preview):t.count(i):e.preview??t.fallback;return{title:Ap(n,Iv)||t.untitled,subtitle:Ap(r,rat)||t.untitled,body:Ap(a,sat)||t.fallback}}const gm=3e4,cot=10;function uot(e,t=cot){return[...e?.organizations??[]].filter(n=>n.eligible&&n.unread>0).sort((n,s)=>s.unread-n.unread||n.tenant_id.localeCompare(s.tenant_id)).slice(0,t)}function dot(e,t){return e.member===!0?!0:e.member===!1||!t?!1:e.members.some(n=>n.kind==="human"&&n.account_id===t&&n.state==="active")}function VY(e,t){return dot(e,t)&&q8(e)==="all"&&e.builtin!=="agents"}function hot(e,t,n){return{conversationName:K8(e,t),organizationName:Sie(e,n),senderLabel:KA(e.last_sender_label??"")}}function fot(e){const t=new Map(e.cursors),n=e.rows;if(!e.seeded){for(const a of n)t.set(a.conversation_id,a.latest_seq);return{candidates:[],cursors:t,seeded:!0}}const r=new Map(e.conversations.map(a=>[a.id,a])),i=[];for(const a of n){const o=t.get(a.conversation_id);if(a.unread_count===0||a.latest_seq<=a.last_read_seq||o!==void 0&&a.latest_seq<=o){(o===void 0||a.latest_seq>o)&&t.set(a.conversation_id,a.latest_seq);continue}const l=r.get(a.conversation_id);l!==void 0&&l.latest_seq===a.latest_seq&&(t.set(a.conversation_id,a.latest_seq),VY(l,e.selfAccountId)&&(e.quiet||i.push({conversationId:l.id,...l.last_thread_root_id?{threadId:l.last_thread_root_id}:{},tenantId:a.tenant_id,seq:a.latest_seq,...hot(l,e.selfAccountId,e.organizations),kind:l.kind,name:l.name?.trim()||null,unreadCount:a.unread_count})))}return{candidates:i,cursors:t,seeded:!0}}function ZD(e,t,n,s){return e.getMutationCache().findAll({mutationKey:$t.notifyMutation(t.accountId,t.epoch),exact:!0,status:"pending"}).some(r=>{const i=r.state.variables;return i?.conversationId===n&&(i.tenantId===void 0||i.tenantId===s)})}function pot(e,t,n,s,r){return new Promise(i=>{const a=()=>{l(),r.removeEventListener("abort",a),i()},o=()=>{(r.aborted||!ZD(e,t,n,s))&&a()},l=e.getMutationCache().subscribe(o);r.addEventListener("abort",a,{once:!0}),o()})}function eI(){return wy(),ug()}function WY(e){return e?{accountId:e.account_id,state:e.state,readOnly:!!e.read_only,localEnabled:e.local.enabled}:null}function got(e,t){return!e||!t?!0:e.accountId!==t.accountId||e.state!==t.state||e.readOnly!==t.readOnly||e.localEnabled!==t.localEnabled}function $Y(e,t){const n=()=>WY(e.getQueryData($t.statusFor(t))),s=n();return()=>!got(s,n())}function kc(e,t){const n=$r(e),s=WY(e.getQueryData($t.statusFor(t)));return!!(t&&n.accountId===t&&s?.accountId===t&&s.state==="ready"&&s.localEnabled&&!s.readOnly)}function L6(e,t){const n=e.getQueryData($t.statusFor(t));if(!t||$r(e).accountId!==t||n?.account_id!==t)throw new Error("Team Bridge read owner changed")}const zY=x8;async function Ec(e,t,n){L6(e,t);const s=$Y(e,t),r=await zY(e,t,n);if(L6(e,t),!s())throw new Error("Team Bridge read authority changed");return r}function lo(e){const t=Mt(),n=$r(t),s=m.useRef({accountId:e??n.accountId,epoch:n.epoch}).current,r=m.useRef(!0);m.useLayoutEffect(()=>(r.current=!0,()=>{r.current=!1}),[]);const i=()=>{const d=$r(t);return!!s.accountId&&d.accountId===s.accountId&&d.epoch===s.epoch},a=()=>i()&&kc(t,s.accountId),o=()=>r.current&&i(),l=()=>o()&&kc(t,s.accountId),u=()=>{if(!l())throw new Error("Team Bridge write authority changed")};return{accountId:s.accountId,isCurrent:l,isReadCurrent:o,isAuthorityCurrent:a,assertCurrent:u}}function Gdt(e){const t=e.get("tenant"),n=e.get("conversation"),s=e.get("thread");return t&&n&&s?{tenantId:t,conversationId:n,rootId:s}:null}function qY(e,t){if(e.root.id!==t.rootId||e.root.conversation_id!==t.conversationId||e.root.thread_root_id||e.replies.some(n=>n.conversation_id!==t.conversationId||n.thread_root_id!==t.rootId))throw new Error("Thread response identity mismatch");return e}async function Vdt(e,t,n){return qY(await _s.listReplies(e.conversationId,e.rootId,{tenantId:e.tenantId,accountId:t,afterSeq:n}),e)}function Wdt(e,t,n){if(typeof IntersectionObserver>"u")return()=>{};const s=new Map(t.map(d=>[d.id,d.seq])),r=new Map,i=e.ownerDocument;let a=!0,o=-1;const l=()=>{if(!a||!e.isConnected||i.visibilityState!=="visible"||!i.hasFocus())return;const d=Math.max(-1,...r.values());d<=o||(o=d,n(d).catch(()=>{a&&o===d&&(o=-1)}))},u=new IntersectionObserver(d=>{if(a){for(const f of d){const p=f.target.dataset.messageId??"",g=s.get(p);g!==void 0&&f.isIntersecting&&f.intersectionRect.height>0?r.set(p,g):r.delete(p)}l()}},{root:e.querySelector("[data-radix-scroll-area-viewport]"),threshold:0});for(const d of e.querySelectorAll("[data-message-id]"))s.has(d.dataset.messageId??"")&&u.observe(d);return i.addEventListener("visibilitychange",l),i.defaultView?.addEventListener("focus",l),()=>{a=!1,u.disconnect(),i.removeEventListener("visibilitychange",l),i.defaultView?.removeEventListener("focus",l)}}const tI=(e,t)=>`${e}\0${t}`,BC=(e,t)=>e.at(-1)===t&&e.at(-2)==="account",KY={rows:new Map,byTenant:new Map,total:0};function YY(e,t){const n=e.getQueryCache(),s=r=>n.findAll({queryKey:r}).filter(i=>BC(i.queryKey,t));return{conversations:s($t.conversationsPrefix),unread:s($t.unreadPrefix)}}function mot(e,t){return t?XY(YY(e,t)):KY}function XY(e){const t=new Map,n=u=>{const d=tI(u.tenantId,u.conversationId),f=t.get(d);(!f||u.at>=f.at)&&t.set(d,u)},s=new Set;for(const u of e.conversations){if(u.queryKey.includes("archived"))continue;const d=u.state.data;for(const f of d?.conversations??[])f.status!=="archived"&&n({tenantId:f.tenant_id,conversationId:f.id,unread:f.unread_count,lastReadSeq:f.last_read_seq,latestSeq:f.latest_seq,muted:q8(f)==="mute",at:u.state.dataUpdatedAt})}let r,i=0;for(const u of e.unread){const d=u.queryKey[2],f=u.state.data;if(f){if(d===Vu){r=f,i=u.state.dataUpdatedAt;continue}if(!(typeof d!="string"||!f.conversations)){s.add(d);for(const p of f.conversations)n({tenantId:d,conversationId:p.conversation_id,unread:p.unread_count,lastReadSeq:p.last_read_seq,latestSeq:p.latest_seq,muted:p.muted,at:u.state.dataUpdatedAt})}}}const a=new Map((r?.organizations??[]).map(u=>[u.tenant_id,u.unread]));for(const[u,d]of t)!d.muted&&a.get(d.tenantId)===0&&i>d.at&&t.set(u,{...d,unread:0});const o=new Map;for(const[u,d]of a){let f=0;for(const p of t.values())p.tenantId===u&&!p.muted&&(f+=p.unread);o.set(u,s.has(u)?f:Math.max(d,f))}let l=0;for(const u of o.values())l+=u;return r&&!r.organizations?.length&&(l=r.total),{rows:t,byTenant:o,total:l}}function $dt(e,t){const n=t.rows.get(tI(e.tenant_id,e.id));return!n||n.unread===e.unread_count&&n.lastReadSeq===e.last_read_seq?e:{...e,unread_count:n.unread,last_read_seq:Math.max(n.lastReadSeq,e.last_read_seq)}}const B6=new WeakMap;let vot=1;function bot(e){if(!e||typeof e!="object")return 0;let t=B6.get(e);return t===void 0&&(t=vot++,B6.set(e,t)),t}function xot(e,t){const n=[];for(const s of[...t.conversations,...t.unread])n.push(`${s.queryHash}@${s.state.dataUpdatedAt}:${bot(s.state.data)}`);return`${e}#${n.join("|")}`}function _ot(e){const t=Mt(),n=m.useRef(null),s=m.useCallback(i=>t.getQueryCache().subscribe(i),[t]),r=m.useCallback(()=>{if(!e)return KY;const i=YY(t,e),a=xot(e,i);return n.current?.signature!==a&&(n.current={signature:a,view:XY(i)}),n.current.view},[t,e]);return m.useSyncExternalStore(s,r,r)}function b_(e,t,n){const s=e.getQueryState(t);s?.data!==void 0&&e.setQueryData(t,n(s.data),{updatedAt:s.dataUpdatedAt})}function j6(e,t){for(const n of[$t.unreadPrefix,$t.conversationsPrefix])for(const s of e.getQueryCache().findAll({queryKey:n}))BC(s.queryKey,t)&&s.state.data!==void 0&&s.state.fetchStatus!=="idle"&&s.cancel({revert:!0})}function wot(e,t,n,s){const r=new Map(s.map(i=>[i.conversation_id,i]));for(const i of e.getQueryCache().findAll({queryKey:$t.conversationsPrefix}))BC(i.queryKey,t)&&b_(e,i.queryKey,a=>{let o=!1;const l=a.conversations.map(u=>{const d=u.tenant_id===n?r.get(u.id):null;return!d||d.unread_count===u.unread_count&&d.last_read_seq===u.last_read_seq?u:(o=!0,{...u,unread_count:d.unread_count,last_read_seq:Math.max(d.last_read_seq,u.last_read_seq)})});return o?{...a,conversations:l}:a})}function yot(e,t,n){const s=mot(e,t).rows.get(tI(n.tenantId,n.conversationId));if(!(s!==void 0&&n.seq>=s.latestSeq))return[];const i=s.muted?0:s.unread,a=[],o=d=>{const f=e.getQueryState(d);a.push({key:d,data:f?.data,updatedAt:f?.dataUpdatedAt??0})};for(const d of e.getQueryCache().findAll({queryKey:$t.conversationsPrefix}))!BC(d.queryKey,t)||!d.state.data?.conversations.some(p=>p.id===n.conversationId&&p.tenant_id===n.tenantId)||(o(d.queryKey),b_(e,d.queryKey,p=>({...p,conversations:p.conversations.map(g=>g.id===n.conversationId&&g.tenant_id===n.tenantId?{...g,unread_count:0,last_read_seq:Math.max(g.last_read_seq,n.seq)}:g)})));const l=$t.unread(_E(n.tenantId),t);e.getQueryData(l)!==void 0&&(o(l),b_(e,l,d=>({...d,total:Math.max(0,d.total-i),conversations:d.conversations?.map(f=>f.conversation_id===n.conversationId?{...f,unread_count:0,last_read_seq:Math.max(f.last_read_seq,n.seq)}:f)})));const u=$t.unread(Vu,t);return i>0&&e.getQueryData(u)!==void 0&&(o(u),b_(e,u,d=>({...d,total:Math.max(0,d.total-i),organizations:d.organizations?.map(f=>f.tenant_id===n.tenantId?{...f,unread:Math.max(0,f.unread-i)}:f)}))),a}function Cot(e,t){for(const{key:n,data:s,updatedAt:r}of t)e.setQueryData(n,s,{updatedAt:r})}let x_=null;function Sot(){return x_}function zdt(e){m.useEffect(()=>{const t=e??null;return x_=t,()=>{x_===t&&(x_=null)}},[e])}const QY="bridge_agent_participation_v2",qdt=`ui.teamBridge.invitations.consent.${QY}`;function kot(e,t,n){const s=t.invited_by,[r,i]=typeof s=="string"&&s!==""?["added",s]:["created",e.created_by];if(i===n)return{role:r,self:!0};const a=Eot(e,i);return a?{role:r,name:a,self:!1}:null}function Eot(e,t){const n=e.members.find(s=>s.kind==="human"&&s.account_id===t);return n?KA(n.display_label):null}function Kdt(e,t){if(!t)return[];const n=[];for(const s of e){if(s.builtin||s.status!=="open")continue;const r=s.members.find(i=>i.kind==="agent"&&i.account_id===t&&i.state==="invited");r&&n.push({key:`${s.tenant_id}|${s.id}`,conversationId:s.id,tenantId:s.tenant_id,conversationKind:s.kind,conversationName:K8(s,t),agentName:KA(r.display_label),inviter:kot(s,r,t)})}return n}function Ydt(e,t,n){const s=new Map(t.map(a=>[a.key,a])),r=e.flatMap(a=>{const o=s.get(a.key);return o?[o]:n.has(a.key)?[a]:[]}),i=new Set(r.map(a=>a.key));return[...r,...t.filter(a=>!i.has(a.key))]}function Xdt(e,t,n){return n?e:t}function Tot(e,t,n,s){return JY(e,t,n,"invited",s==="accept"?"active":"removed")}function Rot(e,t,n,s){return JY(e,t,n,s==="accept"?"active":"removed","invited")}function JY(e,t,n,s,r){return{...e,conversations:e.conversations.map(i=>i.id===t.conversationId&&i.tenant_id===t.tenantId?{...i,members:i.members.map(a=>a.kind==="agent"&&a.account_id===n&&a.state===s?{...a,state:r}:a)}:i)}}function Qdt(e){const t=e,n=typeof t?.status=="number"?t.status:null,s=typeof t?.code=="string"?t.code:null,r=t?.detail?.details?.rule;return n===401||s==="bridge_signin_required"?"sign_in":s==="agent_not_permitted"?"agent_unavailable":s==="invalid_transition"?r==="builtin"?"gone":"already_answered":s===PY?"runtime_outdated":s==="member_not_found"||s==="conversation_not_found"?"gone":s==="consent_version_unknown"?"outdated":s==="bridge_not_available"||s==="bridge_disabled"?"not_available":n===null&&s===null&&e instanceof Error&&"status"in e?"unreachable":"unconfirmed"}function Aot(e){if(!e.has_more)return 0;let t;for(const n of e.messages)typeof n.seq=="number"&&(t===void 0||n.seq<t)&&(t=n.seq);return t??0}function Fot(e,t){const n=e?.events??[],s=t.events??[];if(n.length===0&&s.length===0)return t;const r=Aot(t),i=new Map;for(const o of n)o.after_seq>=r&&i.set(o.id,o);for(const o of s)i.set(o.id,o);const a=[...i.values()].sort((o,l)=>l.event_seq-o.event_seq);if(a.length===0){const{events:o,...l}=t;return l}return{...t,events:a}}const Ad=e=>`${e.kind}:${e.account_id}:${e.endpoint_id??""}`;function Jdt(e){const t=[...e].sort((r,i)=>r.event_seq-i.event_seq),n=[],s=new Map;for(const r of t){const a=r.targets.length>0?Cat(r.kind):null,o=a==="joined"&&r.implicit===!0&&Sat(r.implicit_reason)==="owner_invite",l=r.request_id&&a!==null?`${r.request_id}\0${a}\0${o}\0${Ad(r.actor)}`:null,u=l?s.get(l):void 0;if(u){const g=new Set(u.targets.map(Ad));for(const v of r.targets)g.has(Ad(v))||u.targets.push(v);r.at>u.at&&(u.at=r.at),u.selfOnly=!1;continue}const d=[],f=new Set;for(const g of r.targets)f.has(Ad(g))||(f.add(Ad(g)),d.push(g));const p={key:`event:${r.id}`,kind:a,ownerAddedAgent:o,actor:r.actor,targets:d,selfOnly:d.length===0||d.length===1&&Ad(d[0])===Ad(r.actor),at:r.at};n.push(p),l&&s.set(l,p)}return n}const Dot="leading";function Zdt(e,t){const n=new Map;if(!t||t.length===0)return n;const s=e.filter(i=>typeof i.seq=="number").sort((i,a)=>i.seq-a.seq),r=new Set;for(const i of t){if(r.has(i.id))continue;r.add(i.id);let a=Dot,o=0,l=s.length-1;for(;o<=l;){const d=o+l>>1;s[d].seq<=i.after_seq?(a=s[d].id,o=d+1):l=d-1}const u=n.get(a);u?u.push(i):n.set(a,[i])}return n}const eht=2,qd=new Map,Iot=32,nI=(e,t)=>`${e}\0${t.trim()}`;function tht(e,t,n){const s=nI(e,t);if(qd.delete(s),!(!n||n.length===0))for(qd.set(s,n);qd.size>Iot;){const r=qd.keys().next().value;if(r===void 0)break;qd.delete(r)}}function Not(e,t){return qd.get(nI(e,t))}function Pot(e,t){qd.delete(nI(e,t))}function Rg(e,t){const n=s=>({onSuccess:(r,i,a)=>s?.onSuccess?.(r,i.input,a),onError:(r,i,a)=>s?.onError?.(r,i.input,a),onSettled:(r,i,a,o)=>s?.onSettled?.(r,i,a.input,o)});return{...e,variables:e.variables?.input,mutate:(s,r)=>e.mutate({input:s,target:t()},n(r)),mutateAsync:(s,r)=>e.mutateAsync({input:s,target:t()},n(r))}}function jC(e){return e===Vu?"account":{tenantId:e}}const Mot=18e4,H6=6e4;function Oot(){return typeof document>"u"?H6:document.visibilityState==="visible"?Mot:H6}function nht(e,t=!0,n){const s=Mt();return Dn({queryKey:$t.conversations(e,n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.listConversations(jC(e))),enabled:t&&!!n,staleTime:15e3,refetchOnWindowFocus:!0})}function sht(e,t=!0,n){const s=Mt();return Dn({queryKey:$t.archivedConversations(e,n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.listConversations(jC(e),"archived")),enabled:t&&!!n,staleTime:15e3,refetchOnWindowFocus:!0})}function rht(e,t){const n=Mt(),s=$t.archivedConversations(e,t??"unresolved-owner");return fn({mutationFn:async()=>{const r=n.getQueryData(s),i=r?.next_cursor;if(!r||!i)return r??{conversations:[]};const a=await Ec(n,t,()=>_s.listConversations(jC(e),"archived",i));return kie(r,a)},onSuccess:r=>{n.setQueryData(s,r)}})}function sI(e,t,n,s){return{queryKey:$t.messages(t??"none",n,s??"unresolved-owner"),queryFn:async({queryKey:r})=>Fot(e.getQueryData(r),await Ec(e,s,()=>_s.listMessages(t,{tenantId:n})))}}function iht(e,t,n=!0,s){const r=Mt();return Dn({...sI(r,e,t,s),enabled:n&&!!s&&!!e,staleTime:5e3,retry:(i,a)=>!VN(a)&&i<3,refetchInterval:i=>VN(i.state.error)?!1:8e3,refetchOnWindowFocus:!0})}function Lot(e,t){return zY(e,t,async()=>{const n=await _s.status("surface_open");if(n.state==="ready"&&n.account_id!==t)throw new Error("Team Bridge status owner changed");return n})}function aht(e,t=!0,n){const s=Mt();return Dn({queryKey:$t.directory(e??"none",n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.directory(e)),enabled:t&&!!n&&!!e,staleTime:3e4,refetchOnWindowFocus:!0,retry:1})}function Bot(e,t=!0,n){const s=Mt(),r=tH({queries:e.map(i=>({queryKey:$t.directory(i,n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.directory(i)),enabled:t&&!!n,staleTime:3e4,refetchOnWindowFocus:!0,retry:1}))});return m.useMemo(()=>{const i={},a={},o={},l=new Map;return r.forEach((u,d)=>{const f=e[d];u.data&&(i[f]=u.data.members),u.isError&&(o[f]=u.error),a[f]=u.isPending?"loading":u.isError?"error":"ready",l.set(f,()=>{u.refetch()})}),{members:i,state:a,errors:o,retry:u=>{l.get(u)?.()}}},[r,e])}function ZY(e=!0){const t=Mt(),{accountId:n}=eI();return Dn({queryKey:$t.statusFor(n),queryFn:()=>Lot(t,n),enabled:e&&!!n,staleTime:6e4,refetchOnWindowFocus:!0,retry:1})}function eX(e,t=Vu,n={}){const s=Mt();return Dn({queryKey:$t.unread(t,n.accountId??"unresolved-owner"),queryFn:()=>Ec(s,n.accountId,()=>_s.unread(jC(t))),enabled:e&&!!n.accountId,staleTime:3e4,refetchInterval:n.refetchInterval??Oot(),refetchIntervalInBackground:n.refetchIntervalInBackground,refetchOnWindowFocus:!0,retry:1})}async function tX(e,t,n,s=()=>!0){s()&&(await e.invalidateQueries({queryKey:$t.messages(t,n)}),s()&&(await e.invalidateQueries({queryKey:$t.conversationsPrefix}),s()&&await e.invalidateQueries({queryKey:$t.unreadPrefix})))}function oht(e,t){const n=Mt(),s=lo(),r=fn({mutationFn:({input:i,target:a})=>(a.assertCurrent(),_s.send(a.conversationId,{...i,tenantId:a.tenantId,expectedAccountId:Mat(a.accountId),mentions:Not(a.conversationId,i.body)})),onSuccess:(i,{input:a,target:o})=>(Pot(o.conversationId,a.body),tX(n,o.conversationId,o.tenantId,o.isCurrent))});return Rg(r,()=>({...s,conversationId:e,tenantId:t}))}function lht(e,t){const n=Mt(),s=lo(),r=fn({mutationFn:({target:i})=>(i.assertCurrent(),_s.join(i.conversationId,i.tenantId,i.accountId)),onSuccess:(i,{target:a})=>tX(n,a.conversationId,a.tenantId,a.isCurrent)});return Rg(r,()=>({...s,conversationId:e,tenantId:t}))}function jot(e,t){const{accountId:n,epoch:s}=$r(e),r=()=>kc(e,n)&&(t?.()??!0),i=()=>{if(!r())throw new Error("Team Bridge write authority changed")},a={queryKey:$t.conversationsPrefix,predicate:o=>o.queryKey.at(-1)===n&&o.queryKey.at(-2)==="account"};return{mutationKey:$t.notifyMutation(n,s),mutationFn:({conversationId:o,notify:l,tenantId:u})=>(i(),_s.setNotify(o,l,u,n)),onMutate:async({conversationId:o,notify:l,tenantId:u})=>{i(),await e.cancelQueries(a),i();const d=e.getQueriesData(a);return e.setQueriesData(a,f=>f===void 0?f:Eie(f,o,l,u)),{snapshots:d}},onError:(o,l,u)=>{if(r())for(const[d,f]of u?.snapshots??[])e.setQueryData(d,f)},onSettled:async()=>{r()&&(await e.invalidateQueries(a),r()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function cht(){const e=Mt(),t=lo();return fn(jot(e,t.isCurrent))}function Hot(e,t,n){const{accountId:s}=$r(e),r=()=>kc(e,s)&&(n?.()??!0),i=()=>{if(!r()||!s)throw new Error("Team Bridge write authority changed");return s},a={queryKey:$t.conversationsPrefix,predicate:u=>u.queryKey.at(-1)===s&&u.queryKey.at(-2)==="account"},o=u=>{if(t?.conversationId!==u.conversationId||t.tenantId!==u.tenantId)throw new Error("Team Bridge agent-notify target changed")},l=["agent-notify",s??"unresolved-owner",t?.tenantId??"unknown-tenant",t?.conversationId??"no-conversation"];return{mutationKey:[...$t.all,...l],scope:{id:l.join(":")},mutationFn:({conversationId:u,tenantId:d,notify:f})=>(o({conversationId:u,tenantId:d}),_s.setAgentNotify({conversationId:u,tenantId:d,notify:f,accountId:i()})),onMutate:async u=>{o(u);const d=i();await e.cancelQueries(a),i();let f=null;for(const[,p]of e.getQueriesData(a)){const g=p?.conversations.find(b=>b.id===u.conversationId&&b.tenant_id===u.tenantId),v=g?Aie(g,d):null;if(v){f=Fie(v);break}}return e.setQueriesData(a,p=>p===void 0?p:Die(p,u,d,u.notify)),{self:d,previous:f}},onSuccess:u=>{!r()||!s||e.setQueriesData(a,d=>d===void 0?d:Rie(d,u,s))},onError:(u,d,f)=>{!r()||!f||e.setQueriesData(a,p=>p===void 0?p:Tie(p,d,f.self,d.notify,f.previous))},onSettled:async()=>{r()&&await e.invalidateQueries(a)}}}function uht(e,t){const n=Mt(),s=lo();return fn(Hot(n,e&&t?{conversationId:e,tenantId:t}:null,s.isCurrent))}function Uot(e,t){const{accountId:n}=$r(e),s=()=>kc(e,n)&&(t?.()??!0),r=()=>{if(!s()||!n)throw new Error("Team Bridge write authority changed");return n},i={queryKey:$t.conversationsPrefix,predicate:a=>a.queryKey.at(-1)===n&&a.queryKey.at(-2)==="account"};return{mutationFn:({conversationId:a,tenantId:o,decision:l})=>_s.answerAgentInvitation({conversationId:a,tenantId:o,decision:l,accountId:r(),consentVersion:QY}),onMutate:async a=>{const o=r();await e.cancelQueries(i),r(),e.setQueriesData(i,l=>l===void 0?l:Tot(l,a,o,a.decision))},onError:(a,o)=>{!s()||!n||e.setQueriesData(i,l=>l===void 0?l:Rot(l,o,n,o.decision))},onSettled:async()=>{s()&&await e.invalidateQueries(i)}}}function dht(){const e=Mt(),t=lo();return fn(Uot(e,t.isCurrent))}function hht(e,t){const n=Mt(),s=lo(),r=fn({mutationFn:({input:i,target:a})=>(a.assertCurrent(),_s.markRead(a.conversationId,{...i,tenantId:a.tenantId,expectedAccountId:a.accountId})),onMutate:({input:i,target:a})=>{if(!(!a.isCurrent()||!a.accountId||!a.tenantId))return j6(n,a.accountId),yot(n,a.accountId,{tenantId:a.tenantId,conversationId:a.conversationId,seq:i.seq})},onError:async(i,{target:a},o)=>{!a.isCurrent()||!o||(Cot(n,o),await n.invalidateQueries({queryKey:$t.conversationsPrefix}),a.isCurrent()&&await n.invalidateQueries({queryKey:$t.unreadPrefix}))},onSuccess:async(i,{target:a})=>{a.isCurrent()&&a.accountId&&(j6(n,a.accountId),await n.invalidateQueries({queryKey:$t.conversationsPrefix}),a.isCurrent()&&await n.invalidateQueries({queryKey:$t.unreadPrefix}))}});return Rg(r,()=>({...s,conversationId:e,tenantId:t}))}function fht(){const e=Mt(),t=lo(),n=fn({mutationFn:({input:s,target:r})=>(r.assertCurrent(),_s.addMembers({conversationId:s.conversationId,tenantId:s.tenantId,expectedAccountId:r.accountId,members:s.members})),onSuccess:async(s,{target:r})=>{r.isCurrent()&&(nX(e,r.accountId,s),await e.invalidateQueries({queryKey:$t.conversationsPrefix}))}});return Rg(n,()=>t)}function pht(){const e=Mt(),t=lo(),n=fn({mutationFn:({input:s,target:r})=>(r.assertCurrent(),_s.removeMember({conversationId:s.conversationId,tenantId:s.tenantId,expectedAccountId:r.accountId,accountId:s.accountId})),onSuccess:async(s,{target:r})=>{r.isCurrent()&&(nX(e,r.accountId,s),await e.invalidateQueries({queryKey:$t.conversationsPrefix}))}});return Rg(n,()=>t)}function nX(e,t,n){const s={queryKey:$t.conversationsPrefix,predicate:r=>r.queryKey.at(-1)===t&&r.queryKey.at(-2)==="account"};e.setQueriesData(s,r=>r===void 0?r:{...r,conversations:r.conversations.map(i=>i.id===n.id&&i.tenant_id===n.tenant_id?n:i)})}function ght(e,t=()=>!0){const n=Mt(),s=lo(),r=fn({mutationFn:({input:i,target:a})=>{if(a.assertCurrent(),!a.isCurrent())throw new Error("Team Bridge write authority changed");return _s.startConversation({...i,tenantId:a.tenantId,expectedAccountId:a.accountId})},onSuccess:async(i,{target:a})=>{a.isCurrent()&&await n.invalidateQueries({queryKey:$t.conversationsPrefix})}});return Rg(r,()=>({...s,conversationId:"",tenantId:e,isCurrent:()=>s.isCurrent()&&t()}))}function rI(e){return{queryKey:$t.conversationsPrefix,predicate:t=>t.queryKey.at(-1)===e&&t.queryKey.at(-2)==="account"}}function Got(e,t){const{accountId:n,epoch:s}=$r(e),r=()=>kc(e,n)&&(t?.()??!0),i=()=>{if(!r())throw new Error("Team Bridge write authority changed")},a=rI(n);return{mutationKey:[...$t.all,"archive",n,s],mutationFn:({conversationId:o,tenantId:l})=>(i(),_s.setArchived(o,!0,l,n)),onMutate:async({conversationId:o,tenantId:l})=>{i(),await e.cancelQueries(a),i();const u=e.getQueriesData(a);return e.setQueriesData(a,d=>d===void 0?d:Y8(d,o,l)),{snapshots:u}},onError:(o,l,u)=>{if(r())for(const[d,f]of u?.snapshots??[])e.setQueryData(d,f)},onSettled:async()=>{r()&&(await e.invalidateQueries(a),r()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function mht(){const e=Mt(),t=lo();return fn(Got(e,t.isCurrent))}function Vot(e,t){const{accountId:n,epoch:s}=$r(e),r=()=>kc(e,n)&&(t?.()??!0),i=()=>{if(!r())throw new Error("Team Bridge write authority changed")},a=rI(n);return{mutationKey:[...$t.all,"unarchive",n,s],mutationFn:({conversationId:o,tenantId:l})=>(i(),_s.setArchived(o,!1,l,n)),onMutate:async({conversationId:o,tenantId:l})=>{i(),await e.cancelQueries(a),i();const u=e.getQueriesData(a);return e.setQueriesData(a,d=>d===void 0?d:Iie(d,o,"open",l)),{snapshots:u}},onError:(o,l,u)=>{if(r())for(const[d,f]of u?.snapshots??[])e.setQueryData(d,f)},onSettled:async()=>{r()&&(await e.invalidateQueries(a),r()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function vht(){const e=Mt(),t=lo();return fn(Vot(e,t.isCurrent))}function Wot(e,t,n=new Set){const{accountId:s,epoch:r}=$r(e),i=()=>kc(e,s)&&(t?.()??!0),a=()=>{if(!i())throw new Error("Team Bridge write authority changed")},o=rI(s);return{mutationKey:[...$t.all,"delete",s,r],mutationFn:async({conversationId:l,tenantId:u})=>{a();try{return await _s.deleteConversation(l,u,s)}catch(d){const f=d;if(f.code==="conversation_not_found"){if(n.delete(l))return{deleted:!0};throw d}throw(f.status===null||f.status===void 0||f.status>=500)&&n.add(l),d}},onSuccess:(l,{conversationId:u,tenantId:d})=>{i()&&e.setQueriesData(o,f=>f===void 0?f:Y8(f,u,d))},onSettled:async()=>{i()&&(await e.invalidateQueries(o),i()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function bht(){const e=Mt(),t=lo(),n=m.useRef(new Set);return fn(Wot(e,t.isCurrent,n.current))}const $ot="display.notifications";function zot(){return{untitled:h("ui.teamBridge.list.untitled"),directMessage:h("ui.teamBridge.kind.dm"),group:h("ui.teamBridge.kind.group"),channel:e=>h("ui.teamBridge.notify.channel",{channel:e}),subtitle:(e,t)=>h("ui.teamBridge.notify.subtitle",{place:e,organization:t}),count:e=>h("ui.teamBridge.notify.count",{count:e}),countPreview:(e,t)=>h("ui.teamBridge.notify.count_preview",{count:e,preview:t}),fallback:h("ui.teamBridge.notify.body_fallback")}}function qot(e){return e.kind==="dm"?{kind:"dm"}:{kind:e.kind,name:e.name}}function iA(e,t){const n=e.profile?.avatar?.source==="none"?null:UY(e);return uat({v:1,kind:t,account_id:e.account_id,display_name:Ap(e.display_label,Iv),agent_name:Ap(e.agent?.name??"",Iv),...n?{avatar:{account_id:n.accountId,hash:n.hash}}:{}})}function Kot(e,t,n){return e.getQueryData($t.directory(t,n))?.members??[]}function Yot(e,t,n,s){const r=$t.replies(t.tenantId,t.conversationId,n);e.setQueryData(r,i=>{const a=i?.pages.at(-1);return!i||!a||a.has_more||i.pages.some(o=>o.replies.some(l=>l.id===s.id))?i:{...i,pages:[...i.pages.slice(0,-1),{...a,replies:[...a.replies,s].sort((o,l)=>o.seq-l.seq)}]}})}function Xot(e,t,n,s){return{...sI(e,t,n,s),staleTime:0}}async function Qot(e,t,n,s,r){if(!s())return;let i=t.senderLabel,a,o=null,l;const u=$r(e);if(u.accountId!==n)return;const d={accountId:n,epoch:u.epoch},f=t.threadId;try{let b;if(f)b=qY(await _s.listReplies(t.conversationId,f,{tenantId:t.tenantId,accountId:n,afterSeq:t.seq,limit:1}),{tenantId:t.tenantId,conversationId:t.conversationId,rootId:f}).replies.find(x=>x.seq===t.seq),b&&s()&&Yot(e,t,f,b);else{const x=()=>e.fetchQuery(Xot(e,t.conversationId,t.tenantId,n));b=(await x().catch(w=>{if(!iZ(w))throw w;return x()})).messages.reduce((w,y)=>w===void 0||y.seq>w.seq?y:w,void 0)}if(b&&b.seq>=t.seq){if(f||(l=b.id),b.sender.kind==="human"&&b.sender.account_id===n||!s())return;const x=Kot(e,t.tenantId,n);i=Mie(b.sender,x,{named:(w,y)=>h("ui.teamBridge.chief.label",{agent:w,person:y}),unnamed:w=>h("ui.teamBridge.chief.unnamed",{person:w})});const _=x.find(w=>w.account_id===b.sender.account_id);_&&(b.sender.kind==="human"||b.sender.kind==="agent")&&(a=iA(_,b.sender.kind==="human"?"person":"person_agent")),o=oot(b.body)}}catch{}const p=window.api?.desktop?.teamBridge;if(!p)return;const g=lot({senderLabel:i,conversationName:t.conversationName,place:qot(t),organizationName:t.organizationName,preview:o,unreadCount:t.unreadCount},zot());for(;ZD(e,d,t.conversationId,t.tenantId);)if(await pot(e,d,t.conversationId,t.tenantId,r),r.aborted||!s())return;if(r.aborted||!s())return;const v=e.getQueryData($t.conversations(Vu,n))?.conversations.find(b=>b.id===t.conversationId&&b.tenant_id===t.tenantId);!v||!VY(v,n)||await p.notify({owner:{accountId:n,epoch:d.epoch},conversationId:t.conversationId,...f?{threadId:f}:{},...l?{messageId:l}:{},tenantId:t.tenantId,...a?{sender:a}:{},seq:t.seq,title:g.title,subtitle:g.subtitle,body:g.body,viewing:Sot()===t.conversationId}).catch(()=>{})}function Jot(e,t,n,s,r){wot(e,t,n,s);for(const i of s){const a=`${n}\0${i.conversation_id}`,o=r.get(a);if(r.set(a,i.latest_seq),o===void 0||i.latest_seq<=o)continue;const l=sI(e,i.conversation_id,n,t);e.getQueryState(l.queryKey)?.data!==void 0&&e.fetchQuery({...l,staleTime:0}).catch(()=>{})}}function Zot(e){const t=!!window.api?.desktop?.teamBridge,n=eI(),s=ZY(e&&t),r=n.accountId,a=e&&t&&!!r&&s.data?.account_id===r&&s.data?.state==="ready"&&s.data.local.enabled&&!s.data.read_only,o=Mt(),l=Nae({filters:{mutationKey:$t.notifyMutation(r,n.epoch),exact:!0,status:"pending"},select:H=>H.mutationId});m.useLayoutEffect(()=>{const H=window.api?.desktop?.teamBridge;if(!H?.setAuthority)return;const U=()=>{H.setAuthority({...$r(o),settling:qA(o)}).catch(()=>{})},z=zA(o,U);return U(),z},[o]);const u=vK({enabled:a}),d=ss(),f=Et(d.data,"settings"),p=Dn({...U5(),enabled:a&&f}),g=f&&Nie(p.data?.settings,$ot)===!1,v=m.useRef(g);v.current=g;const b=m.useRef(r);b.current=r;const x=m.useRef(a);x.current=a;const _=m.useRef(new AbortController);m.useEffect(()=>{const H=new AbortController;return _.current=H,(!a||g||n.token!==sp(o))&&H.abort(),()=>H.abort()},[a,g,n.token,o]),m.useEffect(()=>(x.current=a,()=>{x.current=!1}),[a]);const w=u.data,y=eX(a,Vu,{accountId:r,refetchInterval:gm,refetchIntervalInBackground:!0}),S=m.useMemo(()=>uot(y.data),[y.data]),C=tH({queries:S.map(H=>{const U=_E(H.tenant_id);return{queryKey:$t.unread(U,r??"unresolved-owner"),queryFn:()=>Ec(o,r,()=>_s.unread({tenantId:U})),enabled:a,staleTime:gm,refetchInterval:gm,refetchIntervalInBackground:!0,refetchOnWindowFocus:!0,retry:1}})}),E=C.map(H=>`${H.status}:${H.dataUpdatedAt}`).join("|"),k=m.useRef(C);k.current=C;const F=m.useRef(S);F.current=S;const I=Bot(S.map(H=>_E(H.tenant_id)),a,r).members,N={};for(const[H,U]of Object.entries(I))N[H]=U.filter(z=>z.account_id!==r).flatMap(z=>[iA(z,"person"),...z.agent?.name?[iA(z,"person_agent")]:[]]).filter(z=>z!==void 0);const P=JSON.stringify(N),M=m.useRef(N);M.current=N;const Y=m.useRef(null),O=m.useRef(new Set),X=Dn({queryKey:$t.conversations(Vu,r??"unresolved-owner"),queryFn:()=>Ec(o,r,()=>_s.listConversations("account")),enabled:a,staleTime:gm,refetchInterval:gm,refetchIntervalInBackground:!0,refetchOnWindowFocus:!0,retry:1}),Q=m.useRef(new Map),ie=m.useRef(new Map),G=m.useRef(new Set),ne=m.useRef(void 0),oe=m.useRef(null),B=[a,g,l.join(","),E,y.dataUpdatedAt,X.dataUpdatedAt,(w?.memberships??[]).map(H=>`${H.tenant_id}:${H.tenant_name}`).join(","),r??""].join("#");m.useEffect(()=>{if(Y.current===P)return;Y.current=P;const H=window.api?.desktop?.teamBridge;if(!H?.syncDirectory)return;const U=M.current;for(const z of O.current)z in U||H.syncDirectory({tenantId:z,members:[]}).catch(()=>{});O.current=new Set(Object.keys(U));for(const[z,te]of Object.entries(U))H.syncDirectory({tenantId:z,members:te}).catch(()=>{})},[P]),m.useEffect(()=>{const H=ne.current;ne.current=r,H!==r&&H!==void 0&&(Q.current=new Map,ie.current=new Map,G.current=new Set,oe.current=null,o.invalidateQueries({queryKey:$t.unreadPrefix}),o.invalidateQueries({queryKey:$t.conversationsPrefix}))},[r,o]),m.useEffect(()=>{if(oe.current===B||(oe.current=B,!y.data))return;for(const fe of y.data.organizations??[])fe.unread===0&&!G.current.has(fe.tenant_id)&&G.current.add(fe.tenant_id);if(!X.data)return;const H=k.current,U=F.current,z=Pie(w?.memberships??[],y.data.organizations,y.data.organizations??null);let te=Q.current;for(let fe=0;fe<U.length;fe+=1){const J=U[fe],Se=H[fe]?.data;if(!Se)continue;const W=(Se.conversations??[]).map(xe=>({conversation_id:xe.conversation_id,tenant_id:J.tenant_id,unread_count:xe.unread_count,last_read_seq:xe.last_read_seq,latest_seq:xe.latest_seq}));r&&Jot(o,r,J.tenant_id,Se.conversations??[],ie.current);const Ce=G.current.has(J.tenant_id),K=$r(o),me=W.filter(xe=>!Ce||!x.current||v.current||!K.accountId||K.accountId!==r?!0:!ZD(o,{accountId:K.accountId,epoch:K.epoch},xe.conversation_id,xe.tenant_id)),Ee=fot({conversations:X.data.conversations,rows:me,organizations:z,selfAccountId:r,cursors:te,seeded:Ce,quiet:!a||g});if(te=Ee.cursors,Ee.seeded&&G.current.add(J.tenant_id),!a||g||!r)continue;const Ae=r,se=sp(o),he=$Y(o,Ae);for(const xe of Ee.candidates)Qot(o,xe,Ae,()=>b.current===Ae&&sp(o)===se&&he()&&x.current&&!v.current&&kc(o,Ae),_.current.signal)}Q.current=te},[B,a,g,y.data,X.data,w,r,o])}function elt(){const{data:e}=ss();m.useEffect(()=>{e&&zX(e)},[e]);const t=jA(),n=Mt(),s=m.useRef(null);m.useEffect(()=>{const r=t.configChange;if(!r)return;const i=`${r.epoch}:${r.seq}`;s.current!==i&&r.changedKeys.includes(hl)&&(s.current=i,n.invalidateQueries({queryKey:No.capabilities}),n.invalidateQueries({queryKey:No.settings}),!Oie()&&da(h("ui.settings.language.external_notice",{language:r.language}),{id:"i18n-language-external"}))},[t.configChange,n])}function tlt(e,t){if(e.defaultPrevented||e.repeat||e.isComposing||!(e.metaKey||e.ctrlKey))return null;const n=$A(e);if(n===null)return null;const s=aZ(t.bindings).get(n);return s===void 0||pA(e.target)||!u0e(sX(s),t.route)?null:s}const sX=e=>e.slice(6);function nlt(e){const t=Fe.getState(),n=t.activeDraftKey?t.drafts[t.activeDraftKey]:void 0,s=Bv(t.activeDraftKey,n?.sessionId,t.activeSessionId)??null;Gd(sX(e),{sessionId:s,askScope:s===null?"fleet":"session",via:"chord"})}function slt(){m.useEffect(()=>{const e=t=>{const n=nt.getState(),s=tlt(t,{bindings:n.shortcutBindings,route:n.rightSlotRoute});s!==null&&(t.preventDefault(),nlt(s))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}function rlt(e,t){const n=ug(),s=m.useRef(!1);m.useEffect(()=>{s.current||!e||!n.accountId||window.__loDevDriver?.armed!==!0||window.__loDevDriver.startupScene!=="team-bridge-owner-audit"||(s.current=!0,t("/team-bridge"))},[e,n.accountId,t])}const ilt=""+new URL("radient-icon-1024x1024-D_JJedvo.png",import.meta.url).href,rX=sg()(l5(e=>({hasBeenNotified:!1,setHasBeenNotified:t=>{e({hasBeenNotified:t})}}),{name:"low-credits-storage"})),alt=({open:e,onClose:t,onGoToConsole:n})=>{Ve();const{setHasBeenNotified:s}=rX(),{prices:r,isLoading:i,error:a}=Lie(),o=d=>typeof d!="number"?"$...":h("ui.common.account.low_credits_dialog.detail",{detail:String(d.toFixed(2))}),l=()=>{s(!0),t()},u=()=>{s(!0),n()};return c.jsx(Ac,{open:e,onClose:l,title:c.jsxs(c.Fragment,{children:[c.jsx("img",{src:ilt,alt:h("ui.common.account.low_credits_dialog.radient_icon"),className:"size-7"}),h("ui.common.account.low_credits_dialog.running_low_on_radient_credits")]}),maxWidth:"sm",fullWidth:!1,actions:c.jsxs(c.Fragment,{children:[c.jsx(Uv,{onClick:l,children:h("ui.common.account.low_credits_dialog.maybe_later")}),c.jsx(Gv,{onClick:u,startIcon:c.jsx(wu,{size:18}),className:"min-w-55",children:h("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:[h("ui.common.account.low_credits_dialog.unlock_the_full_power_of_local_operator_with")," ",c.jsx("span",{className:"font-bold text-accent",children:h("ui.common.account.low_credits_dialog.radient_pass")}),"."]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("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:h("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:[h("ui.common.account.low_credits_dialog.plus_get")," ",c.jsx("span",{className:"font-medium text-ink",children:i?c.jsx(On,{size:"sm",className:"me-0.5 align-middle"}):o(r?.default_registration_credits)})," ",h("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:h("ui.common.account.low_credits_dialog.could_not_load_bonus_credit_information")})]}),c.jsx("p",{className:"text-meta text-ink-dim",children:h("ui.common.account.low_credits_dialog.you_can_also_reach_the_radient_console_from_settings_at_any_time")})]})})},olt=(e,t)=>t?Yk(e.filter(n=>n.session_id===t)).length:0;function llt(e){return Fe(t=>olt(t.sessions,e))}const clt=(e,t)=>t?e.some(n=>n.session_id===t&&n.status?.code==="busy"):!1;function ult(e){return Fe(t=>clt(t.sessions,e))}const dlt=[];function hlt(){const{state:e}=Yy(),t=e?.pendingConsent??dlt,n=uG(s=>XM(t,s));return m.useEffect(()=>{t.length>0&&S2()},[t]),XM(t,n)}const iX={approvals:["desktop","mesh","approvals"]},flt=15e3,plt=new Set(["requested","approved","connecting","failed"]);function glt(e){return plt.has(e)}function mlt(e){return e==="requested"}function vlt(e){return e.filter(t=>mlt(t.state)).length}function xht(e){return e.state==="requested"&&e.canApproveHere!==!1&&(e.kind==="device"||e.kind==="machine")}function _ht(e){return glt(e)}function wht(e){switch(e){case"requested":return h("ui.mesh.mesh_approvals.waiting_for_you");case"approved":return h("ui.mesh.mesh_approvals.approved");case"connecting":return h("ui.mesh.mesh_approvals.connecting");case"connected":return h("ui.mesh.mesh_approvals.connected");case"denied":return h("ui.mesh.mesh_approvals.denied");case"expired":return h("ui.mesh.mesh_approvals.expired");case"failed":return h("ui.mesh.mesh_approvals.failed");default:return e}}function xu(e){return typeof e=="object"&&e!==null}function blt(e){const t=xu(e)?e:{};return{deviceId:qn(t.device_id),name:qn(t.name),host:qn(t.host),user:qn(t.user),transport:qn(t.transport),hostKeyFp:qn(t.host_key_fp)}}function xlt(e){const t=xu(e)?e:{};return{connect:n1(t.connect,!1),install:n1(t.install,!1),anchor:xu(t.anchor),networkId:qn(t.network_id),role:qn(t.role),unattended:n1(t.unattended,!1),grants:eE(t.grant)}}function _lt(e){const t=Array.isArray(e)?e:e?.approvals??[];if(!Array.isArray(t))return[];const n=[];for(const s of t){if(!xu(s))continue;const r=qn(s.approval_id),i=qn(s.state);if(!r||!i)continue;const a=xu(s.what)&&Object.prototype.hasOwnProperty.call(s.what,"credential_inheritance"),o=Object.prototype.hasOwnProperty.call(s,"kind")?qn(s.kind):void 0,l=a||o==="credential_inheritance"?"credential":o!==void 0&&!["device_onboard","local_authority"].includes(o)?"unknown":!xu(s.device)&&xu(s.machine)?"machine":"device",u=xu(s.requested_by)?s.requested_by:{};n.push({approvalId:r,state:i,kind:l,summary:qn(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:qn(s.approve_remedy)||void 0,where:blt(l==="machine"?s.machine:s.device),what:xlt(s.what),requestedBy:{surface:qn(u.surface),sessionId:qn(u.session_id),deviceId:qn(u.device_id)},expiresAt:oZ(s.expires_at)})}return n}function wlt(e){return e.kind==="machine"?h("ui.mesh.mesh_approvals.this_machine"):Zk({device_id:e.where.deviceId,name:e.where.name})}function yht(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 U6(e)}const n=U6(e),s=Clt(e,t).map(r=>r.clause);return s.length?h("ui.mesh.mesh_approvals.approval_title_with_clauses",{head:n,clauses:ylt(s)}):h("ui.mesh.mesh_approvals.approval_title",{head:n})}function U6(e){return e.kind==="credential"?e.summary||h("ui.mesh.approval.credential_title"):e.kind==="unknown"?e.summary||h("ui.mesh.approval.unknown_title"):e.canApproveHere===!1&&e.summary?e.summary:e.kind==="machine"?h("ui.mesh.mesh_approvals.set_up_operator_authority_on_this_machine"):h("ui.mesh.mesh_approvals.onboard_subject",{subject:wlt(e)})}function ylt(e){return e.length===1?e[0]:h("ui.mesh.mesh_approvals.join_clauses",{clauses:e.slice(0,-1).join(", "),last:e[e.length-1]})}function Cht(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?h("ui.mesh.mesh_approvals.via_transport",{transport:s}):"",r&&r!==n?`(${r})`:""].filter(Boolean);return i.length?i.join(" "):null}function Sht(e){return e.kind==="credential"||e.kind==="unknown"?null:e.where.hostKeyFp||null}function kht(e){const{surface:t,sessionId:n}=e.requestedBy,s=[t||"",n?h("ui.mesh.mesh_approvals.session_suffix",{suffix:n.slice(-6)}):""].filter(Boolean);return s.length?h("ui.mesh.mesh_approvals.asked_by",{requester:s.join(" · ")}):null}function Clt(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?h("ui.mesh.mesh_approvals.connect_over",{transport:e.where.transport}):h("ui.mesh.mesh_approvals.connect_to_it"),consequence:e.where.transport?h("ui.mesh.mesh_approvals.may_connect_over",{transport:e.where.transport}):h("ui.mesh.mesh_approvals.this_machine_may_connect_to_it")}),s&&u.push({term:"install",clause:e.kind==="machine"?h("ui.mesh.mesh_approvals.install_local_operator"):h("ui.mesh.mesh_approvals.install_local_operator_there"),consequence:e.kind==="machine"?h("ui.mesh.mesh_approvals.local_operator_is_installed_on_this_machine"):h("ui.mesh.mesh_approvals.local_operator_is_installed_on_it")}),r&&u.push({term:h("ui.mesh.mesh_approvals.install_operator_anchor"),clause:h("ui.mesh.mesh_approvals.check_approvals_signed_on_your_machines"),consequence:h("ui.mesh.mesh_approvals.that_device_can_check_approvals_signed_on")}),i){const d=t?.get(i),f=h("ui.mesh.mesh_approvals.join_network",{network:d||i,role:a||"?"});u.push({term:f,clause:f,consequence:h("ui.mesh.mesh_approvals.joins_network",{network:d||i,role:a||"?"})})}o&&u.push({term:h("ui.mesh.mesh_approvals.trust_unattended_sessions"),clause:h("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt"),consequence:h("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")});for(const d of Slt(l,o)){const f=klt()[d];u.push({term:f?.term??h("ui.mesh.mesh_approvals.grant_capability",{grant:d}),clause:Elt()[d]??h("ui.mesh.mesh_approvals.use_capability",{grant:d}),consequence:f?.gloss??h("ui.mesh.mesh_approvals.may_use_capability",{grant:d})})}return u}function Slt(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 klt=()=>({unattended:{term:h("ui.mesh.mesh_approvals.trust_unattended_sessions"),gloss:h("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")},broker_credential:{term:h("ui.mesh.mesh_approvals.borrow_logins_there"),gloss:h("ui.mesh.mesh_approvals.your_sessions_may_use_the_logins_stored")}}),Elt=()=>({list:h("ui.mesh.mesh_approvals.see_its_sessions"),view:h("ui.mesh.mesh_approvals.watch_a_session_there"),prompt:h("ui.mesh.mesh_approvals.send_prompts_to_a_session_there"),steer:h("ui.mesh.mesh_approvals.steer_a_running_turn_there"),stop:h("ui.mesh.mesh_approvals.stop_a_session_there"),slash:h("ui.mesh.mesh_approvals.run_slash_commands_there"),delete:h("ui.mesh.mesh_approvals.archive_or_delete_a_session_there"),move:h("ui.mesh.mesh_approvals.move_sessions_to_or_from_there"),broker_credential:h("ui.mesh.mesh_approvals.borrow_the_logins_stored_there"),approve:h("ui.mesh.mesh_approvals.answer_approval_prompts_there"),unattended:h("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt")});function Eht(e,t){if(e===null||e<=0)return null;const n=e-t;if(n<=0)return null;if(n<60)return h("ui.mesh.mesh_approvals.expires_in_under_a_minute");const s=Math.ceil(n/60);if(s<90)return h("ui.mesh.mesh_approvals.expires_minutes",{count:s});const r=Math.ceil(s/60);return h("ui.mesh.mesh_approvals.expires_hours",{count:r})}function Tlt(e,{poll:t=!0}={}){return Dn({queryKey:iX.approvals,enabled:e,queryFn:async()=>_lt(await rt({op:"approvals.list"})),retry:!1,staleTime:t?1e4:Number.POSITIVE_INFINITY,refetchInterval:e&&t?flt:!1,refetchOnWindowFocus:t})}function Tht(){const e=Mt();return fn({mutationFn:async t=>{const n=t.decision==="approve"?{op:"approvals.approve",approvalId:t.approvalId}:{op:"approvals.deny",approvalId:t.approvalId};await rt(n)},onSettled:()=>{e.invalidateQueries({queryKey:iX.approvals}),e.invalidateQueries({queryKey:xc.networks}),e.invalidateQueries({queryKey:xc.peers})}})}function Rht(e){const t=e?.message;return typeof t=="string"&&t.trim()?t.trim():h("ui.mesh.mesh_approvals.the_approvals_could_not_be_read")}function Aht(e){const t=e;return{code:qn(t?.code)||"approval_refused",sentence:qn(t?.message)||h("ui.mesh.mesh_approvals.decision_could_not_be_answered")}}const Rlt="/team-bridge",Alt="nav-team-bridge",Flt="nav-team-bridge-badge";function Dlt(e){const{accountId:t}=eI(),n=ZY(e),s=e&&!!t&&n.data?.account_id===t,r=eX(s,Vu,{accountId:t}),i=_ot(s?t:void 0);if(!e)return null;const a=s&&r.data?i.total:0;return{icon:P0,label:h("ui.teamBridge.nav.label"),path:Rlt,tourTag:Alt,attention:a,attentionTag:Flt,attentionName:o=>h("ui.teamBridge.nav.unread",{count:o})}}const aA={aida:"visible",notifications:"visible",library:"visible",projects:"visible",agents:"visible",schedules:"more",browser:"visible","team-bridge":"more","agent-hub":"more",mesh:"more"},cy=["aida","notifications","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh"],uy={visible:cy.filter(e=>aA[e]==="visible"),more:cy.filter(e=>aA[e]==="more")},G6=new Map(cy.map((e,t)=>[e,t])),Ilt=new Map([["notifications","notifications"]]);function Nlt(e,t){const n=s=>{const r=Ilt.get(s);return r===void 0||t(r)};return{visible:e.visible.filter(n),more:e.more.filter(n)}}const Plt=new Set(lZ);function Mlt(e){return typeof e=="string"&&Plt.has(e)}function qk(e,t){if(e===t)return!0;if(e.visible.length!==t.visible.length||e.more.length!==t.more.length)return!1;for(let n=0;n<e.visible.length;n+=1)if(e.visible[n]!==t.visible[n])return!1;for(let n=0;n<e.more.length;n+=1)if(e.more[n]!==t.more[n])return!1;return!0}function xo(e,t){return e.visible.includes(t)?"visible":"more"}function __(e,t,n){return e[t].filter(s=>n.has(s))}function Olt(e,t,n,s){if(!s.has(t))return null;const r=xo(e,t),i=__(e,r,s),a=i.indexOf(t);if(a<0)return null;const o=a+n;if(o<0||o>=i.length)return null;const l=i[o],u=e[r],d=u.indexOf(t),f=u.indexOf(l);if(d<0||f<0)return null;const p=u.slice();p[d]=l,p[f]=t;const g={visible:e.visible.slice(),more:e.more.slice()};return g[r]=p,g}function V6(e,t,n){const s={visible:e.visible.filter(r=>r!==t),more:e.more.filter(r=>r!==t)};return{...s,[n]:[...s[n],t]}}function Llt(e,t,n,s,r){if(s===t)return{visible:e.visible.slice(),more:e.more.slice()};if(s!==null&&(!r.has(s)||!e[n].includes(s)))return null;const i={visible:e.visible.filter(l=>l!==t),more:e.more.filter(l=>l!==t)},a=i[n].slice(),o=s===null?a.length:a.indexOf(s);return o<0?null:(a.splice(o,0,t),{...i,[n]:a})}function W6(e,t){for(const n of cy){if(aA[n]!==t||e.visible.includes(n)||e.more.includes(n))continue;const s=G6.get(n)??0,r=e[t];let i=-1,a=-1,o=-1,l=Number.POSITIVE_INFINITY;for(let d=0;d<r.length;d+=1){const f=G6.get(r[d])??0;f<s&&f>a&&(a=f,i=d),f>s&&f<l&&(l=f,o=d)}const u=i>=0?i+1:o>=0?o:r.length;r.splice(u,0,n)}}function oA(e){const t={visible:[],more:[]},n=new Set;if(e&&typeof e=="object"){const s=e;for(const r of["visible","more"]){const i=s[r];if(Array.isArray(i))for(const a of i)Mlt(a)&&(n.has(a)||(n.add(a),t[r].push(a)))}}return W6(t,"visible"),W6(t,"more"),t}function Blt(e){return e.reduce((t,n)=>{const s=n.attention??0;return Number.isFinite(s)&&s>0?t+s:t},0)}const If={layout:["desktop","sidebar_layout"]};async function jlt(){const e=await rt({op:"sidebar_layout.get"});return oA(e.layout)}function Hlt(e,t=()=>!1){const n=Mt(),s=Dn({queryKey:If.layout,enabled:e,queryFn:jlt,staleTime:Number.POSITIVE_INFINITY,retry:Mv}),r=m.useRef(0),i=fn({scope:{id:"sidebar-layout"},mutationFn:async d=>{const f=await rt({op:"sidebar_layout.set",layout:Nlt(d,t)});return oA(f.layout)},retry:cZ,onMutate:async d=>{const f=++r.current;await n.cancelQueries({queryKey:If.layout});const p=n.getQueryData(If.layout);return n.setQueryData(If.layout,d),{previous:p,seq:f}},onError:(d,f,p)=>{p?.seq===r.current&&p.previous&&n.setQueryData(If.layout,p.previous),nn(h("ui.shell.sidebar_navigation.save_failed"))},onSettled:(d,f,p,g)=>{g?.seq===r.current&&n.invalidateQueries({queryKey:If.layout})}}),a=e&&s.data!==void 0;return{layout:a?s.data:uy,canCustomise:a,save:d=>{a&&i.mutate(d)},reset:()=>{a&&i.mutate(oA(uy))}}}const $6=e=>{const t=Hie(e.type),n=typeof e.percent=="number"?`, ${Math.round(e.percent)}%`:"";return h("ui.common.updates.update_foot_icon.in_progress",{subject:t,percent:n})},aX=e=>jie({type:e.type,version:e.offer.version}),Ult=e=>{const t=e.map(s=>aX(s)),n=t.slice(1).reduce((s,r)=>h("ui.common.updates.update_foot_icon.subject_join",{left:s,right:`${r.charAt(0).toLowerCase()}${r.slice(1)}`}),t[0]);return h("ui.common.updates.update_foot_icon.available_show_the_update_notice",{joined:n})},Glt=({surfaces:e,inflight:t,onShow:n,onDismiss:s})=>{if(Ve(),t===null&&e.length===0)return null;if(t!==null)return c.jsx(vt,{side:"top",collisionPadding:8,content:$6(t),children:c.jsx("output",{"data-update-foot-icon":"","data-update-foot-icon-state":"inflight","aria-label":$6(t),className:"flex size-8 shrink-0 items-center justify-center text-accent",children:c.jsx(ri,{className:"size-4 shrink-0 motion-safe:animate-spin","aria-hidden":"true"})})});const r=e.find(i=>(i.offer.summary??"").trim()!=="");return c.jsx(vt,{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:[aX(i)," ",h("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:h("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":Ult(e),onClick:n,onKeyDown:i=>{i.key!=="Escape"||!s||(i.stopPropagation(),s())},className:R("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(BA,{className:"size-4 shrink-0","aria-hidden":"true"})})})},z6=()=>{const e=kr(g=>g.followed),t=kr(g=>g.running),n=kr(g=>g.offers),s=kr(g=>g.detailOpen),r=kr(g=>g.inflight),i=kr(g=>g.downloadPercent),a=kr(g=>g.openNotice),o=kr(g=>g.noticeOpen),l=kr(g=>g.dismissNotice),u=m.useMemo(()=>{const g={followed:e,running:t,offers:n,detailOpen:s};return N5.filter(v=>Bie(g,v)).map(v=>{const b=n[v];return b?{type:v,offer:b}:null}).filter(v=>v!==null)},[e,t,n,s]),d=m.useMemo(()=>r[Rn.BACKEND]?{type:Rn.BACKEND,percent:null}:r[Rn.UI]?{type:Rn.UI,percent:i[Rn.UI]}:null,[r,i]),f=m.useCallback(()=>a(),[a]),p=m.useCallback(()=>l(),[l]);return c.jsx(Glt,{surfaces:u,inflight:d,onShow:f,onDismiss:o?p:void 0})},q6=({expanded:e})=>(Ve(),c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(V5,{className:"size-6",label:e?void 0:h("ui.shell.collapsible_app_logo.local_operator")}),e&&c.jsx("span",{className:"truncate font-semibold text-body text-ink",children:h("ui.shell.collapsible_app_logo.local_operator")})]})),lA=it.memo(({expanded:e,useAuth:t=!1})=>{const n=yA(),s=oi(),{user:r,isAuthenticated:i,accountRead:a,signOut:o}=Oy(),l=a==="checking"?h("ui.shell.user_profile_sidebar.checking_account"):WN(a)?h("ui.shell.user_profile_sidebar.account_unavailable"):null,u=r?.name??l??h("ui.shell.user_profile_sidebar.user"),d=WN(a),f=r?.email??"",p=d?h("ui.shell.user_profile_sidebar.reconnect_radient"):f,g=d?"/settings?section=providers&provider=radient":"/settings",v=d?h("ui.shell.user_profile_sidebar.reconnect_radient"):h("ui.shell.user_profile_sidebar.account_settings"),b=m.useCallback(async()=>{i&&(await o(),window.location.reload())},[i,o]),x=m.useMemo(()=>{const S=r?.name;return S?S.split(" ").map(C=>C.charAt(0)).join("").toUpperCase().substring(0,2):null},[r?.name]),_=Wat(r?.radientUser.account,64),w=c.jsxs("button",{type:"button",onClick:t?void 0:()=>s(g),"aria-label":e?void 0:v,className:R("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.jsxs(F5,{className:"size-7 shrink-0 rounded-md bg-media-surface",children:[_&&c.jsx(xy,{src:_,alt:"",className:"lo-avatar-arrival"}),c.jsx(_y,{className:"rounded-md bg-media-surface text-ink-muted",children:x??c.jsx(Dde,{size:14,"aria-hidden":"true"})})]}),e&&u&&c.jsxs("span",{className:"min-w-0 text-start",children:[c.jsx("span",{className:"block truncate text-body-sm text-ink",children:u}),p&&c.jsx("span",{className:R("block truncate text-meta",d?"text-accent":"text-ink-dim"),children:p})]})]}),y=e?w:c.jsx(Ld,{content:v,side:n==="rtl"?"left":"right",children:w});return t?c.jsxs(Po,{children:[e?c.jsx(eo,{asChild:!0,children:w}):c.jsx(Ld,{content:v,side:n==="rtl"?"left":"right",children:c.jsx(eo,{asChild:!0,children:w})}),c.jsxs(Mo,{align:"end",side:"top",className:"min-w-50",children:[d?c.jsxs(Jt,{onSelect:()=>s(g),children:[c.jsx(T5,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.reconnect_radient")]}):null,c.jsxs(Jt,{onSelect:()=>s("/settings"),children:[c.jsx(Su,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.settings")]}),c.jsxs(Jt,{children:[c.jsx(Zue,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.privacy_and_security")]}),c.jsx(Nr,{}),c.jsxs(Jt,{onSelect:b,className:"text-danger focus:bg-danger-wash focus:text-danger",children:[c.jsx(Cue,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.sign_out")]})]})]}):y});lA.displayName="UserProfileSidebar";const Vlt=()=>{const e=jA(),t=ss(),n=Fe(u=>u.setCataloguePageable),s=Fe(u=>u.setCatalogueActivityHead),r=Fe(u=>u.fetchSessions),i=Et(t.data,"session_catalogue_page"),a=Et(t.data,"session_catalogue_sort");m.useEffect(()=>{n(i)},[i,n]),m.useEffect(()=>{s(a)},[a,s]);const o=Gr(t.data,"session_catalogue",2)==="enabled",l=m.useCallback(()=>r(i?x5:fy,i),[r,i]);return m.useEffect(()=>{o&&l()},[o,l,e.catalogueRevision]),null},K6="flex h-[30px] w-full items-center gap-2 rounded-md px-2 text-body-sm transition-colors duration-fast ease-out-quart",Wlt=()=>{Ve();const e=yA()==="rtl",t=oi(),n=bfe(),{expanded:s,onCollapse:r}=Uie(),i=nt(ae=>ae.openCommandPalette),a=ss(),o=Dlt(Et(a.data,"team_bridge_conversations")),l=Fe(ae=>ae.activeSessionId),u=hlt(),d=Gr(a.data,"peers")==="enabled",f=I2(d),p=Gr(a.data,"approvals")==="enabled",g=Tlt(f==="member"&&p,{poll:!0}),v=vlt(g.data??[]),b=Et(a.data,"projects",1),x=Et(a.data,"library",1),_=Et(a.data,"notifications",1),w=Gie(_),y=_?Vie(w.data):0,S=nt(ae=>ae.sidebarOverflowExpanded),C=nt(ae=>ae.setSidebarOverflowExpanded),E=Et(a.data,"aida",1),k=fg(E),F=E&&k.data?.enabled===!0,A=k.data?.name??"Aida",I=vpe(),N=llt(k.data?.session_id),P=ult(k.data?.session_id),M=()=>{I(t,k.data).catch(ae=>nn(Lf(ae)))},Y=new Map;F&&Y.set("aida",{icon:Wie,label:A,path:"/chat",isActive:n==="chat"&&!!k.data?.session_id&&l===k.data?.session_id,tourTag:"nav-item-aida",onSelect:M,attention:N,attentionTag:"nav-aida-badge",attentionName:ae=>h("ui.shell.sidebar_navigation.aida_missed",{name:A,count:ae}),working:P,workingName:h("ui.shell.sidebar_navigation.aida_working",{name:A})}),_&&Y.set("notifications",{icon:_ce,label:h("ui.notifications.nav.label"),path:"/notifications",isActive:n==="notifications",tourTag:"nav-item-notifications",attention:y,attentionTag:"nav-notifications-badge",attentionName:ae=>h("ui.notifications.nav.unread",{count:ae,countText:String(ae)})}),x&&Y.set("library",{icon:due,label:h("ui.library.page.title"),path:"/library",isActive:n==="library",tourTag:"nav-item-library"}),b&&Y.set("projects",{icon:mU,label:h("ui.shell.sidebar_navigation.projects"),path:"/projects",isActive:n==="projects",tourTag:"nav-item-projects"}),Y.set("agents",{icon:yl,label:h("ui.shell.sidebar_navigation.agents"),path:"/agents",isActive:n==="agents",tourTag:"nav-item-agents"}),Y.set("schedules",{icon:pU,label:h("ui.shell.sidebar_navigation.schedules"),path:"/schedules",isActive:n==="schedules",tourTag:"nav-item-schedules"}),Y.set("browser",{icon:Uu,label:h("ui.shell.sidebar_navigation.browser"),path:"/browser",isActive:n==="browser",tourTag:"nav-item-browser",attention:u,attentionTag:"nav-browser-badge",attentionName:ae=>h("ui.shell.sidebar_navigation.browser_waiting",{count:ae,countText:String(ae)})}),o&&Y.set("team-bridge",{...o,isActive:n==="team-bridge"}),Y.set("agent-hub",{icon:CU,label:h("ui.shell.sidebar_navigation.agent_hub"),path:"/agent-hub",isActive:n==="agent-hub",tourTag:"nav-item-agent-hub"}),f==="member"&&Y.set("mesh",{icon:L8,label:h("ui.shell.sidebar_navigation.mesh"),path:"/mesh",isActive:n==="mesh",tourTag:"nav-item-mesh",attention:v,attentionTag:"nav-mesh-badge",attentionName:ae=>h("ui.shell.sidebar_navigation.mesh_waiting",{count:ae,countText:String(ae)})});const O=new Set(Y.keys()),X=Et(a.data,"sidebar_layout",1),{layout:Q,canCustomise:ie,save:G,reset:ne}=Hlt(X,ae=>Et(a.data,ae,1)),oe=ie?Q:uy,B=__(oe,"visible",O),H=__(oe,"more",O),[U,z]=m.useState(!1),te=S||U||H.some(ae=>Y.get(ae)?.isActive),[fe,J]=m.useState(""),[Se,W]=m.useState(null),Ce=m.useRef(new Map),K=ae=>{requestAnimationFrame(()=>Ce.current.get(ae)?.focus())},[me,Ee]=m.useState(null),[Ae,se]=m.useState(null),he=m.useRef(null),xe=m.useRef(null),Je=m.useRef(null),pe=m.useRef(0),Xe=m.useRef(0),le=m.useRef(null),Qe=m.useRef(null),et=m.useRef(!1),ue=ae=>{const we=he.current;return we===null?[]:Array.from(we.querySelectorAll("[data-sidebar-row]")).filter(De=>De.dataset.sidebarRow!==ae).map(De=>{const $e=De.getBoundingClientRect();return{id:De.dataset.sidebarRow??"",top:$e.top,bottom:$e.bottom}})},Le=(ae,we)=>{const De=he.current;if(De===null)return null;const $e=De.getBoundingClientRect(),ke=ue(we),tt=Ot=>ke.filter(Ut=>xo(oe,Ut.id)===Ot);let ht=null;if(ae.kind==="more"){const Ot=tt("more").at(-1);if(Ot)ht=Ot.bottom;else{const Ut=De.querySelector("[data-sidebar-more]");ht=Ut?Ut.getBoundingClientRect().bottom:$e.top+2}}else if(ae.kind==="band"){const Ot=xo(oe,we),en=tt(Ot==="more"?"visible":"more").at(-1);if(en)ht=en.bottom;else if(Ot==="more"){const yn=De.querySelector("[data-sidebar-more]");ht=yn?yn.getBoundingClientRect().top:$e.top+2}}else{const Ot=ke[ae.slot];Ot?ht=Ot.top:ht=ke.at(-1)?.bottom??$e.top+2}return ht===null?null:Math.round(ht-$e.top+De.scrollTop)},Ne=()=>{Qe.current!==null&&(window.clearTimeout(Qe.current),Qe.current=null)},Ue=(ae,we)=>{const De=xe.current;if(De===null||!De.armed)return;const $e=document.elementFromPoint(ae,we),ke=!!$e?.closest("[data-sidebar-more]"),tt=!!$e?.closest("[data-sidebar-drop-band]");let ht;if(ke)ht={kind:"more"},xo(oe,De.id)==="visible"&&!te&&Qe.current===null&&(Qe.current=window.setTimeout(()=>{Qe.current=null,z(!0),requestAnimationFrame(()=>dt.current(pe.current,Xe.current))},400));else if(Ne(),tt)ht={kind:"band"};else{const Ot=ue(De.id),Ut=aK(Ot,De.id,we),en=Ot[Ut];let yn="visible";if(en)yn=xo(oe,en.id);else{const wn=Ot.at(-1);yn=wn?xo(oe,wn.id):"visible"}ht={kind:"slot",slot:Ut,beforeId:en?.id??null,region:yn}}Je.current=ht,se(Le(ht,De.id))},dt=m.useRef(Ue);dt.current=Ue;const St=()=>{le.current!==null&&(cancelAnimationFrame(le.current),le.current=null)},Dt=()=>{le.current=null;const ae=xe.current,we=he.current;if(ae===null||!ae.armed||we===null)return;const De=we.getBoundingClientRect(),$e=Xe.current,ke=we.scrollHeight-we.clientHeight;let tt=0;$e-De.top<24&&we.scrollTop>0?tt=-1:De.bottom-$e<24&&we.scrollTop<ke&&(tt=1),tt!==0&&(we.scrollTop+=tt*8,dt.current(pe.current,$e)),le.current=requestAnimationFrame(Dt)},sn=(ae,we)=>{if(ie&&we.button===0&&!(we.altKey||we.ctrlKey||we.metaKey||we.shiftKey)){try{we.currentTarget.setPointerCapture(we.pointerId)}catch{}xe.current={pointerId:we.pointerId,id:ae,armed:!1,startX:we.clientX,startY:we.clientY},pe.current=we.clientX,Xe.current=we.clientY}},Kt=ae=>{const we=xe.current;if(!(we===null||we.pointerId!==ae.pointerId)){if(pe.current=ae.clientX,Xe.current=ae.clientY,!we.armed){if(Math.hypot(ae.clientX-we.startX,ae.clientY-we.startY)<5)return;we.armed=!0,et.current=!0,Ee(we.id);const De=Y.get(we.id);De&&J(h("ui.shell.sidebar_navigation.drag_armed",{name:De.label})),le.current===null&&(le.current=requestAnimationFrame(Dt))}Ue(ae.clientX,ae.clientY)}},ut=(ae,we)=>{if(we.kind==="slot")return Llt(oe,ae,we.region,we.beforeId,O);const De=xo(oe,ae),$e=we.kind==="more"?"more":De==="more"?"visible":"more";return V6(oe,ae,$e)},Ft=(ae,we)=>{const De=Y.get(ae);if(De===void 0)return;const $e=ut(ae,we);if($e===null||qk($e,oe))return;const ke=xo($e,ae);if(ke==="more"&&C(!0),G($e),we.kind==="slot"){At($e,ae);return}J(ke==="more"?h("ui.shell.sidebar_navigation.move_to_more_note",{name:De.label}):h("ui.shell.sidebar_navigation.show_in_sidebar_note",{name:De.label}))},At=(ae,we)=>{const De=Y.get(we),$e=xo(ae,we),ke=__(ae,$e,O);J(h("ui.shell.sidebar_navigation.move_note",{name:De?.label??"",position:String(ke.indexOf(we)+1),total:String(ke.length)}))},cn=(ae,we=!1)=>{const De=xe.current;if(De===null)return;xe.current=null,St(),Ne();const $e=Je.current;if(Je.current=null,Ee(null),se(null),z(!1),!!De.armed){if(!ae){if(we){et.current=!1,J("");return}const ke=()=>{et.current=!1},tt=()=>{window.setTimeout(ke,0)},ht=()=>{window.removeEventListener("pointerup",Ot,!0),window.removeEventListener("pointercancel",Ut,!0),window.removeEventListener("blur",Ut,!0)},Ot=()=>{ht(),tt()},Ut=()=>{ht(),ke()};window.addEventListener("pointerup",Ot,!0),window.addEventListener("pointercancel",Ut,!0),window.addEventListener("blur",Ut,!0),J("");return}window.setTimeout(()=>{et.current=!1},0),$e!==null&&Ft(De.id,$e)}},rn=m.useRef(cn);rn.current=cn,m.useEffect(()=>{if(me===null)return;const ae=$e=>{$e.key==="Escape"&&(rn.current(!1),$e.preventDefault())},we=$e=>{xe.current?.pointerId===$e.pointerId&&rn.current(!0)},De=()=>rn.current(!1,!0);return window.addEventListener("keydown",ae),window.addEventListener("pointerup",we),window.addEventListener("pointercancel",De),window.addEventListener("blur",De),()=>{window.removeEventListener("keydown",ae),window.removeEventListener("pointerup",we),window.removeEventListener("pointercancel",De),window.removeEventListener("blur",De)}},[me]),m.useEffect(()=>()=>{le.current!==null&&cancelAnimationFrame(le.current),Qe.current!==null&&window.clearTimeout(Qe.current)},[]);const kn=(ae,we)=>{if(!ie)return;const De=Y.get(ae);if(De===void 0)return;if(we.kind==="reset"){ne(),J(h("ui.shell.sidebar_navigation.reset_note")),K(ae);return}if(we.kind==="move"){const ke=Olt(oe,ae,we.delta,O);if(ke===null)return;G(ke),At(ke,ae),K(ae);return}const $e=V6(oe,ae,we.region);qk($e,oe)||(we.region==="more"&&C(!0),G($e),J(we.region==="more"?h("ui.shell.sidebar_navigation.move_to_more_note",{name:De.label}):h("ui.shell.sidebar_navigation.show_in_sidebar_note",{name:De.label})),K(ae))},ws=c.jsx(MZe,{selectedConversation:l??void 0,onSelectConversation:ae=>void dg(t,ae),onStageDraft:(ae,we)=>{Fe.getState().stageDraft(ae,we),t("/chat")}}),Vt=ae=>{const we=ae.attention??0,De=we>0&&ae.attentionName?ae.attentionName(we):ae.label;return ae.working&&ae.workingName?ae.workingName:De},cs=ae=>{const we=Y.get(ae);if(we===void 0)return null;const De=xo(oe,ae),$e=De==="more"?H:B,ke=$e.indexOf(ae),tt=ke<=0,ht=ke===-1||ke>=$e.length-1,Ot=we.attention??0,Ut=Vt(we),en=me===ae,yn=e?"left":"right",wn=we.isActive?yo:"text-ink-muted hover:bg-row-hover hover:text-ink",Ps=c.jsx(we.icon,{size:16,"aria-hidden":"true",className:R("shrink-0",we.isActive&&"text-accent")}),ys=c.jsxs("button",{type:"button",ref:an=>{an?Ce.current.set(ae,an):Ce.current.delete(ae)},onClick:()=>{if(et.current){et.current=!1;return}we.onSelect?we.onSelect():t(we.path)},onPointerDown:ie?an=>sn(ae,an):void 0,onPointerMove:ie?Kt:void 0,onPointerUp:ie?an=>{xe.current?.pointerId===an.pointerId&&cn(!0)}:void 0,onPointerCancel:ie?()=>cn(!1,!0):void 0,onKeyDown:ie?an=>{if(an.key==="ContextMenu"||an.shiftKey&&an.key==="F10"){an.preventDefault(),W(ae);return}an.altKey&&(an.key!=="ArrowUp"&&an.key!=="ArrowDown"||(an.preventDefault(),kn(ae,{kind:"move",delta:an.key==="ArrowUp"?-1:1})))}:void 0,"data-tour-tag":we.tourTag,"aria-current":we.isActive?"page":void 0,"aria-haspopup":ie?"menu":void 0,"aria-label":s&&Ut===we.label?void 0:Ut,className:R("flex h-full min-w-0 flex-1 items-center gap-2 rounded-md",s?"px-2":"justify-center px-0"),children:[s?Ps:c.jsxs("span",{className:"relative flex size-7 shrink-0 items-center justify-center",children:[Ps,Ot>0&&c.jsx("span",{className:"pointer-events-none absolute -top-1 -end-1.5 flex",children:c.jsx(Ib,{count:Ot,placement:"corner","data-tour-tag":we.attentionTag})})]}),!s&&we.working&&c.jsx("span",{className:"inline-flex",children:c.jsx(ri,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})}),s&&c.jsx("span",{className:"truncate",children:we.label})]}),Ts=ie?c.jsxs(Po,{open:Se===ae,onOpenChange:an=>W(an?ae:null),children:[c.jsx(eo,{asChild:!0,children:s?c.jsx("button",{type:"button","data-sidebar-row-menu":"","aria-label":h("ui.shell.sidebar_navigation.row_actions",{name:we.label}),className:R("me-0.5 flex size-6 shrink-0 items-center justify-center rounded-sm","text-ink-muted opacity-0 transition-opacity duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink","group-hover/row:opacity-100 group-focus-within/row:opacity-100","focus-visible:opacity-100 data-[state=open]:opacity-100",me!==null&&"pointer-events-none opacity-0!"),children:c.jsx(oc,{size:16,"aria-hidden":"true"})}):c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-1 end-0 w-0"})}),c.jsxs(Mo,{align:"start",side:yn,sideOffset:s?6:16,className:"min-w-44",onCloseAutoFocus:an=>{an.preventDefault(),K(ae)},children:[c.jsx(Jt,{disabled:tt,onSelect:()=>kn(ae,{kind:"move",delta:-1}),children:h("ui.shell.sidebar_navigation.move_up")}),c.jsx(Jt,{disabled:ht,onSelect:()=>kn(ae,{kind:"move",delta:1}),children:h("ui.shell.sidebar_navigation.move_down")}),c.jsx(Nr,{}),De==="more"?c.jsx(Jt,{onSelect:()=>kn(ae,{kind:"region",region:"visible"}),children:h("ui.shell.sidebar_navigation.show_in_sidebar")}):c.jsx(Jt,{onSelect:()=>kn(ae,{kind:"region",region:"more"}),children:h("ui.shell.sidebar_navigation.move_to_more")}),!qk(oe,uy)&&c.jsxs(c.Fragment,{children:[c.jsx(Nr,{}),c.jsx(Jt,{onSelect:()=>kn(ae,{kind:"reset"}),children:h("ui.shell.sidebar_navigation.reset_layout")})]})]})]}):null;return c.jsxs("li",{"data-sidebar-row":ae,"data-sidebar-region":De,onContextMenu:ie?an=>{an.preventDefault(),W(ae)}:void 0,className:R("group/row relative flex h-[30px] w-full items-center rounded-md","transition-colors duration-fast ease-out-quart",wn,en&&IK,en&&NK),children:[s?ys:c.jsx(Ld,{content:Vt(we),side:yn,suppressed:me!==null,children:ys}),Ts,s&&(Ot>0||we.working)&&c.jsxs("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex shrink-0 items-center gap-1 pe-2",children:[Ot>0&&c.jsx(Ib,{count:Ot,"data-tour-tag":we.attentionTag}),we.working&&c.jsx(ri,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})]})]},we.tourTag)},Vn=Ae===null?null:c.jsx("span",{"aria-hidden":"true","data-sidebar-drop-indicator":"",className:"pointer-events-none absolute inset-x-1 z-10 h-0.5 -translate-y-px rounded-full bg-accent",style:{top:Ae}}),ls=(me===null?null:xo(oe,me))==="more"?h("ui.shell.sidebar_navigation.show_in_sidebar"):h("ui.shell.sidebar_navigation.move_to_more"),En=me===null?null:s?c.jsx("div",{"data-sidebar-drop-band":"",className:"absolute inset-x-0 top-full z-20 mt-1 flex h-7 items-center justify-center rounded-md border border-dashed border-control bg-surface text-meta text-ink-dim",children:ls}):c.jsx(Ld,{content:ls,side:e?"left":"right",children:c.jsx("div",{"data-sidebar-drop-band":"",className:"absolute inset-x-0 top-full z-20 mx-auto mt-1 flex h-6 w-8 items-center justify-center rounded-sm border border-dashed border-control bg-surface",children:c.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-4 rounded-full bg-ink-dim"})})}),Vs=c.jsx("span",{className:"sr-only","aria-live":"polite","aria-atomic":"true",children:fe}),un=s?h("ui.shell.sidebar_navigation.collapse_sidebar"):h("ui.shell.sidebar_navigation.expand_sidebar"),It=s?e?Vi:ju:e?ju:Vi,dn=navigator.platform.toUpperCase().indexOf("MAC")>=0,tr=Et(a.data,"session_catalogue",2),Sn=Fe(ae=>ae.activeDraftKey),Ie=Fe(ae=>ae.drafts),ge=!!Sn&&!(Sn?Ie[Sn]:void 0)?.target,Pe=()=>{Fe.getState().stageDraft(void 0,!0),t("/chat")},L=h("ui.shell.sidebar_navigation.new_chat_shortcut",{shortcut:Gj(dn).replace("+","")}),V=h("ui.shell.sidebar_navigation.search_accessible",{everything:ul("everything",dn),chats:ul("chats",dn)}),j=h("ui.shell.sidebar_navigation.search_tooltip",{everything:ul("everything",dn),chats:ul("chats",dn)}),q=(ae,we,De,$e)=>{const ke=ae;return c.jsxs("button",{type:"button",...$e.attrs,onClick:$e.onClick,disabled:$e.disabled,"aria-label":$e.ariaLabel,"aria-current":$e.current?"page":void 0,className:R(K6,$e.current?yo:"text-ink-muted hover:bg-row-hover hover:text-ink","disabled:text-ink-disabled disabled:hover:bg-transparent"),children:[c.jsx(ke,{size:16,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"truncate",children:we}),c.jsx("span",{"aria-hidden":"true",className:"ms-auto",children:c.jsx(Lr,{shortcut:De,joined:!0})})]})},Z=q(iT,h("ui.shell.sidebar_navigation.new_chat"),Gj(dn),{onClick:Pe,ariaLabel:L,current:ge,disabled:!tr,attrs:{"data-tour-tag":"nav-item-chat","data-new-chat-row":""}}),ee=q(_h,h("ui.shell.sidebar_navigation.search"),ztt("everything",dn),{onClick:i,ariaLabel:V,attrs:{"data-command-palette-trigger":"",title:j}}),_e=(ae,we,De)=>{const $e=ae;return c.jsx(Ld,{content:we,side:e?"left":"right",children:c.jsx("button",{type:"button",...De.attrs,onClick:De.onClick,disabled:De.disabled,"aria-label":we,className:R("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.jsxs("span",{className:"relative flex size-7 items-center justify-center",children:[c.jsx($e,{size:16,"aria-hidden":"true"}),(De.attention??0)>0&&c.jsx("span",{className:"pointer-events-none absolute -top-1 -end-1.5 flex",children:c.jsx(Ib,{count:De.attention??0,placement:"corner","data-tour-tag":De.attentionTag})}),De.working&&c.jsx("span",{className:"pointer-events-none absolute -bottom-0.5 -end-0.5 flex",children:c.jsx(ri,{size:12,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})})]})})})},Re=c.jsx("div",{className:R("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(Ld,{content:un,side:e?"left":"right",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":un,"aria-expanded":s,"aria-keyshortcuts":oN(dn),children:c.jsx(It,{"aria-hidden":"true"})})})}),ye=()=>{if(H.length===0)return null;const ae=H.map(tt=>Y.get(tt)).filter(tt=>tt!==void 0),we=Blt(ae),De=te?0:we,$e=ae.some(tt=>tt.working===!0),ke=we>0?h("ui.shell.sidebar_navigation.more_waiting",{count:we,countText:String(we)}):$e?h("ui.shell.sidebar_navigation.more_working"):h("ui.library.page.more_destinations");return c.jsxs("li",{className:R("flex flex-col",s?"gap-0.5":"items-center gap-1"),children:[s?c.jsxs("button",{type:"button","data-tour-tag":"nav-item-more","data-sidebar-more":"","aria-expanded":te,"aria-controls":"sidebar-more-destinations","aria-label":ke,onClick:()=>C(!te),className:R(K6,"text-ink-muted hover:bg-row-hover hover:text-ink"),children:[c.jsx(oc,{size:16,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-start",children:h("ui.library.page.more")}),(De>0||$e)&&c.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[De>0&&c.jsx(Ib,{count:De,"data-tour-tag":"nav-more-badge"}),$e&&c.jsx(ri,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})]}),c.jsx(Ei,{size:14,"aria-hidden":"true",className:R("shrink-0 transition-transform duration-fast",te&&"rotate-180")})]}):_e(oc,ke,{onClick:()=>C(!te),attention:De,attentionTag:"nav-more-badge",working:$e,attrs:{"aria-expanded":te,"aria-controls":"sidebar-more-destinations","data-tour-tag":"nav-item-more","data-sidebar-more":""}}),te&&c.jsx("ul",{id:"sidebar-more-destinations",className:R("flex flex-col gap-0.5",!s&&"items-center gap-1"),children:H.map(cs)})]},"nav-overflow")},Te=c.jsx(Ld,{content:h("ui.shell.sidebar_navigation.settings"),side:"top",children:c.jsx("button",{type:"button","data-tour-tag":"nav-item-settings",onClick:()=>t("/settings"),"aria-current":n==="settings"?"page":void 0,"aria-label":h("ui.shell.sidebar_navigation.settings"),className:R("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",n==="settings"&&"text-ink"),children:c.jsx(Su,{size:16,"aria-hidden":"true"})})});return s?c.jsxs("div",{"data-sidebar-shell":"","data-glass-region":"sidebar",className:"panel-top-pad 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 pe-2 ps-4",children:[c.jsx(q6,{expanded:!0}),c.jsx("span",{className:"ms-auto",children:Re})]}),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:[Z,ee]}),c.jsxs("div",{className:"relative",children:[c.jsxs("div",{ref:he,"data-sidebar-destinations-area":"","data-sidebar-dragging":me!==null?"":void 0,className:"relative min-h-0 max-h-[50dvh] overflow-y-auto select-none",children:[c.jsxs("ul",{"data-sidebar-destinations":"",className:"flex flex-col gap-0.5",children:[B.map(cs),ye()]}),Vn]}),En]}),Vs]}),c.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:ws}),c.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-1 px-2 pb-2",children:[c.jsx(lA,{expanded:!0}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(z6,{}),Te]})]})]}):c.jsxs("div",{"data-sidebar-strip":"","data-glass-region":"sidebar",className:"panel-top-pad group/sidebar flex h-full min-h-0 flex-col items-center bg-surface",children:[c.jsx(Vlt,{}),c.jsx("div",{className:"flex h-10 shrink-0 items-center justify-center",children:c.jsx(q6,{expanded:!1})}),c.jsxs("ul",{className:"flex flex-col items-center gap-1",children:[c.jsx("li",{children:_e(Vi,un,{onClick:r,attrs:{"aria-expanded":!1,"aria-keyshortcuts":oN(dn)}})}),c.jsx("li",{children:_e(iT,L,{onClick:Pe,disabled:!tr,attrs:{"data-tour-tag":"nav-item-chat"}})}),c.jsx("li",{children:_e(_h,V,{onClick:i,attrs:{"data-command-palette-trigger":""}})})]}),c.jsxs("div",{ref:he,"data-sidebar-destinations-area":"","data-sidebar-dragging":me!==null?"":void 0,className:"relative mt-4 flex flex-col items-center gap-1 select-none",children:[c.jsxs("ul",{"data-sidebar-destinations":"",className:"flex flex-col items-center gap-1",children:[B.map(cs),ye()]}),Vn,En]}),Vs,c.jsxs("div",{className:"mt-auto flex flex-col items-center gap-1 pb-2",children:[c.jsx(z6,{}),Te,c.jsx(lA,{expanded:!1})]})]})},$lt=1,zlt=()=>{const{isAuthenticated:e,user:t}=Oy(),{hasBeenNotified:n,setHasBeenNotified:s}=rX(),[r,i]=m.useState(!1),[a,o]=m.useState(null),l=m.useCallback(async()=>{if(!(!e||!t?.radientUser?.account?.tenant_id))try{const p=await $ie({operation:"credits",tenantId:t.radientUser.account.tenant_id});if(!p||typeof p.balance!="number")throw new Error(h("ui.common.errors.credit_balance_invalid"));o(p.balance)}catch(p){console.error("Failed to fetch Radient credits:",p),o(null)}},[e,t?.radientUser?.account?.tenant_id]);return m.useEffect(()=>{e&&l()},[e,l]),m.useEffect(()=>{e&&a!==null?a<$lt?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 qlt(){const e=oi();m.useEffect(()=>{const t=r=>{e(r==="back"?-1:1)},n=r=>{const i=Tae(r);i&&(r.preventDefault(),t(i))},s=r=>{const i=Rae(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 Klt(){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 Ylt(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 Xlt(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 Qlt(){m.useLayoutEffect(()=>{if(!window.api?.windowChrome)return;const t=document.documentElement.dataset.chromePlatform??"linux",n=()=>Ylt(Klt(),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)}},[]),m.useEffect(()=>{const e=window.api?.windowChrome;if(e)return e.onState(t=>{document.documentElement.dataset.chromeFullscreen=t.fullScreen?"true":"false"})},[])}const Jlt=m.lazy(()=>va(()=>import("./agent-details-page-B9WQ68z3.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]),import.meta.url).then(e=>({default:e.AgentDetailsPage}))),Zlt=m.lazy(()=>va(()=>import("./agent-hub-page-C-UV58tJ.js"),__vite__mapDeps([15,1,2,3,5,16,7,6,8,4,9,10,11,12,17,18,19,20,13,14]),import.meta.url).then(e=>({default:e.AgentHubPage}))),Y6=m.lazy(()=>va(()=>import("./agents-page-CSQOyTDS.js").then(e=>e.a),__vite__mapDeps([21,6,1,2,3,5,7,8,17,22,23]),import.meta.url).then(e=>({default:e.AgentsPage}))),ect=m.lazy(()=>va(()=>import("./schedules-page-DAwa60MB.js"),__vite__mapDeps([24,1,2,3,5,16,7,6,8,25,11,13,14]),import.meta.url).then(e=>({default:e.SchedulesPage}))),X6=m.lazy(()=>va(()=>import("./projects-page-Br5DSkr6.js"),__vite__mapDeps([26,1,2,3,6,5,7,8,16,13,14,23,27]),import.meta.url).then(e=>({default:e.ProjectsPage}))),Q6=m.lazy(()=>va(()=>import("./library-page-D-CE1ZCg.js").then(e=>e.l),__vite__mapDeps([28,1,2,3,13,5,14,16,6,7,8,12,29,27]),import.meta.url).then(e=>({default:e.LibraryPage}))),J6=m.lazy(()=>va(()=>import("./notifications-page-SK5NqB-7.js"),__vite__mapDeps([30,1,2,3,13,5,14,16,7,6,8,23]),import.meta.url).then(e=>({default:e.NotificationsPage}))),tct=m.lazy(()=>va(()=>import("./team-bridge-page-HYbbsoUb.js"),__vite__mapDeps([31,1,2,3,6,5,7,8,29,22,32,20,13,14]),import.meta.url).then(e=>({default:e.TeamBridgePage}))),nct=m.lazy(()=>va(()=>import("./browser-page-Db4cYtxn.js"),__vite__mapDeps([33,1,2,3,5,7,6,8,13,14]),import.meta.url).then(e=>({default:e.BrowserPage}))),sct=m.lazy(()=>va(()=>import("./mesh-page-CR_KErFC.js"),__vite__mapDeps([34,1,2,3,5,16,7,6,8,13,14]),import.meta.url).then(e=>({default:e.MeshPage}))),rct=m.lazy(()=>va(()=>import("./settings-page-Db00UHjC.js"),__vite__mapDeps([35,1,2,3,13,5,14,6,7,8,16,32,18,36,10,25,11]),import.meta.url).then(e=>({default:e.SettingsPage}))),ict=m.lazy(()=>va(()=>import("./browser-webauthn-prompt-CH3nbvN4.js"),__vite__mapDeps([37,1,2,3,5,7,6,8,13,14]),import.meta.url).then(e=>({default:e.BrowserWebauthnPrompt}))),act=()=>{Ve(),Zit(),Qlt(),elt(),zie();const{pathname:e}=fA(),t=e.startsWith("/chat")||e.startsWith("/browser"),{isOnboardingActive:n}=mfe(),{isLowCreditsDialogOpen:s,openRadientConsole:r,onLowCreditsDialogClose:i}=zlt(),{isCommandPaletteOpen:a,isCreateAgentDialogOpen:o,isSidebarCollapsed:l,closeCreateAgentDialog:u}=nt();_u(a,"command-palette"),_u(o,"dialog","create-agent"),_u(n,"onboarding"),_u(s,"dialog","low-credits");const d=oi(),f=ss(),p=Et(f.data,"session_catalogue",2),g=Et(f.data,"session_archive");m.useEffect(()=>{Fe.getState().requestArchiveConfirm(null)},[e]);const v=Gr(f.data,"peers"),b=Gr(f.data,"library"),x=Gr(f.data,"notifications"),_=Gr(f.data,"team_bridge_conversations");Zot(Et(f.data,"team_bridge_conversations"));const w=N=>{Fe.getState().stageDraft({kind:"agent",name:N.name}),d("/chat"),u()};hnt(),slt(),Aae(),qie(),qlt(),E_e();const y=Fe(N=>N.setActiveSession),S=ss(),C=fg(Et(S.data,"aida",1)),E=Fe(N=>{const P=N.activeDraftKey?N.drafts[N.activeDraftKey]:void 0;return Bv(N.activeDraftKey,P?.sessionId,N.activeSessionId)}),k=fpe({displayedSessionId:E,archiveEnabled:g}),F=nt(N=>N.setConsolePaneOpen),A=nt(N=>N.setBrowserPaneOpen),I=nt(N=>N.setConsoleActiveSurface);return m.useEffect(()=>{const N=window.api?.desktop?.onOpenConversation?.((P,M)=>{P!==null&&performance.mark("lop:open:requested"),y(P),M!==void 0&&P!==null&&(I(M),F(!0)),d("/chat")});return()=>N?.()},[d,y,F,I]),fat(_==="enabled",d),rlt(_==="enabled",d),m.useEffect(()=>{const N=window.api?.console?.onReveal?.(P=>{if(P.mode!=="none"&&!(P.mode==="session"&&P.session_id!==E)){if(P.mode==="open"){if(!Kie({targetSessionId:P.session_id,displayedSessionId:E,activeElement:document.activeElement,commandPaletteOpen:a}))return;y(P.session_id)}I(P.surface),F(!0)}});return()=>N?.()},[E,a,y,F,I]),jpe(),jtt(),m.useEffect(()=>{const N=window.api?.browser?.onConsentAttention?.(P=>{const M=wpe(P.requesterSessionId,Fe.getState().sessions);if(bpe(P.entryId),M.kind==="browser"){d("/browser");return}y(M.sessionId),A(!0),d("/chat")});return()=>N?.()},[d,y,A]),m.useEffect(()=>{const N=P=>{n||p&&Utt(P)&&(P.preventDefault(),Fe.getState().stageDraft(void 0,!0),d("/chat"))};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[p,n,d]),c.jsx(Hit,{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(lnt,{}),c.jsx(Git,{}),c.jsx(Gtt,{}),c.jsx(Yie,{}),c.jsx(fnt,{enabled:v==="enabled"}),c.jsx(ost,{open:n}),c.jsx(Uit,{}),c.jsx(nat,{}),g&&c.jsx(Vpe,{}),c.jsx(Wfe,{}),c.jsx(m.Suspense,{fallback:null,children:c.jsx(ict,{})}),c.jsx(ope,{blocked:n||s||a||o||k,sessionId:C.data?.session_id??null}),c.jsx(alt,{open:s,onClose:i,onGoToConsole:r}),c.jsx(wfe,{open:o,onClose:u,onAgentCreated:w}),c.jsx(Xie,{sidebar:c.jsx(Wlt,{}),content:c.jsxs("main",{"data-glass-region":"canvas-backing",className:"panel-top-pad flex grow flex-col overflow-hidden",children:[t?null:c.jsx("div",{"data-chrome-route-band":""}),c.jsx(m.Suspense,{fallback:c.jsx("div",{className:"flex grow items-center justify-center",children:c.jsx(On,{size:"lg",label:h("ui.common.loading.page")})}),children:c.jsxs(uZ,{children:[c.jsx(pr,{path:"/",element:c.jsx(lN,{to:"/chat",replace:!0})}),c.jsx(pr,{path:"/chat",element:c.jsx(Hj,{})}),c.jsx(pr,{path:"/chat/:agentId",element:c.jsx(Hj,{})}),c.jsx(pr,{path:"/agents",element:c.jsx(Y6,{})}),c.jsx(pr,{path:"/agents/:agentId",element:c.jsx(Y6,{})}),c.jsx(pr,{path:"/settings",element:c.jsx(rct,{})}),c.jsx(pr,{path:"/agent-hub",element:c.jsx(Zlt,{})}),c.jsx(pr,{path:"/agent-hub/:agentId",element:c.jsx(Jlt,{})}),c.jsx(pr,{path:"/schedules",element:c.jsx(ect,{})}),c.jsx(pr,{path:"/projects",element:c.jsx(X6,{})}),c.jsx(pr,{path:"/projects/:projectId",element:c.jsx(X6,{})}),c.jsx(pr,{path:"/browser",element:c.jsx(nct,{})}),x==="enabled"&&c.jsxs(c.Fragment,{children:[c.jsx(pr,{path:"/notifications",element:c.jsx(J6,{})}),c.jsx(pr,{path:"/notifications/:notificationId",element:c.jsx(J6,{})})]}),b==="enabled"&&c.jsxs(c.Fragment,{children:[c.jsx(pr,{path:"/library",element:c.jsx(Q6,{})}),c.jsx(pr,{path:"/library/assets/:assetId",element:c.jsx(Q6,{})})]}),_==="enabled"&&c.jsx(pr,{path:"/team-bridge",element:c.jsx(tct,{})}),v==="enabled"&&c.jsx(pr,{path:"/mesh",element:c.jsx(sct,{})}),c.jsx(pr,{path:"*",element:c.jsx(lN,{to:"/chat",replace:!0})})]})})]})})]})})})};let nl=null,Nf=null,mm=null,Pf=null,Kk=null;const oct={soundsArm:async()=>{if(xf.getState().element)throw new Error("sounds safety: element already exists");if(nl)throw new Error("sounds safety: graph already armed");return nl=new AudioContext,await nl.resume(),Jie(e=>{if(!nl)throw new Error("sounds safety: no context");const t=nl.createMediaElementSource(e);mm=nl.createGain(),mm.gain.value=0,Nf=nl.createAnalyser(),Pf=nl.createAnalyser(),t.connect(Pf),Pf.connect(mm),mm.connect(Nf),Nf.connect(nl.destination)}),{armed:!0,contextState:nl.state}},soundsFacts:()=>{const e=xf.getState(),t=new Float32Array(Nf?.fftSize??32);Nf?.getFloatTimeDomainData(t);const n=new Float32Array(Pf?.fftSize??32);return Pf?.getFloatTimeDomainData(n),{ownerId:e.ownerId,status:e.status,time:e.element?.currentTime??0,duration:e.element?.duration??0,paused:e.element?.paused??!0,gain:mm?.gain.value??null,inputRms:Pf?Math.sqrt(n.reduce((s,r)=>s+r*r,0)/n.length):null,players:Array.from(document.querySelectorAll("[data-sound-player]")).map(s=>({status:s.getAttribute("data-sound-status"),clock:s.querySelector("[data-sound-time]")?.textContent,clip:s.querySelectorAll("canvas")[1]?.style.clipPath,numeric:getComputedStyle(s.querySelector("[data-sound-time]")??s).fontVariantNumeric})),rms:Nf?Math.sqrt(t.reduce((s,r)=>s+r*r,0)/t.length):null,src:e.element?.src??null,nativeElements:document.querySelectorAll("audio").length,canvas:Object.values(Fs.getState().conversations).map(s=>({selectedTab:s.selectedTabId,files:s.files?.map(r=>({id:r.id,path:r.path,artifact:r.artifact??null}))}))}},soundsScrub:e=>{const t=e,n=document.querySelector(t.selector);if(!n)throw new Error("sounds: no slider");const s=n.getBoundingClientRect(),r=(u,d)=>n.dispatchEvent(new PointerEvent(u,{pointerId:17,pointerType:"mouse",clientX:d,clientY:s.y+s.height/2,bubbles:!0})),i=n.setPointerCapture,a=n.releasePointerCapture;n.setPointerCapture=()=>{},n.releasePointerCapture=()=>{},r("pointerdown",s.left+1),r("pointermove",s.left+s.width*t.fraction);const o=()=>n.closest("[data-sound-player]")?.getAttribute("data-sound-status"),l=performance.now()+1500;return new Promise(u=>{const d=()=>{const f=o();if(f!=="scrubbing"&&performance.now()<l){requestAnimationFrame(d);return}Kk=()=>{r("pointerup",s.left+s.width*t.fraction),n.setPointerCapture=i,n.releasePointerCapture=a},u({during:f,seconds:xf.getState().element?.currentTime})};requestAnimationFrame(d)})},soundsScrubFinish:()=>(Kk?.(),Kk=null,{committed:!0}),soundsEnd:()=>{const e=xf.getState();if(!e.ownerId||!e.element)throw new Error("sounds: no active playback");return e.seek(e.ownerId,e.element.duration-.12),{requested:!0}},soundsSpeech:async()=>{const e=xf.getState();if(!e.element?.src)throw new Error("sounds: fixture not resolved");const{fetchAttachmentBlob:t}=await va(async()=>{const{fetchAttachmentBlob:r}=await import("./conversation-input-sync-BsdkPoIA.js").then(i=>i.nj);return{fetchAttachmentBlob:r}},__vite__mapDeps([6,1,2,3,5,7,8]),import.meta.url),n=Fe.getState().activeSessionId,s=e.ownerId?.startsWith("sound:")?e.ownerId.slice(6):null;if(!n||!s)throw new Error("sounds: missing attachment identity");return await Qie.getState().speak("sounds-driver",()=>t({sessionId:n,childId:null},s)),{ownerId:xf.getState().ownerId}}};function Kd(){return new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))})}const lct=3,cct=3e3;function uct(e){return e instanceof CSSTransition&&e.playState==="running"}function dct(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 ${Nv(n)??"an element no longer in the document"} = ${i}`}async function hct(e=cct){const t=performance.now();let n=0;for(;;){await Kd();const s=Math.round(performance.now()-t),r=document.getAnimations().filter(uct);if(n=r.length===0?n+1:0,n>=lct)return{waitedMs:s,timedOut:!1,pending:[]};if(s>e)return{waitedMs:s,timedOut:!0,pending:r.map(dct)}}}const fct=/^#/;function S0(){const e=window.location.hash.replace(fct,"");return e===""?"/":e}function Nv(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 pct(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=>Nv(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:Nv(r),stack:a,disabled:e instanceof HTMLButtonElement?e.disabled:null,rect:{x:t.x,y:t.y,width:t.width,height:t.height}}}function vm(e,t){if(typeof e!="string"||e==="")throw new Error(`${t} must be a non-empty string`);return e}async function gct(e,t=1e4){const n=Date.now();for(;S0()!==e;){if(Date.now()-n>t)throw new Error(`route did not become ${e} (it is ${S0()})`);await new Promise(s=>setTimeout(s,50))}return await Kd(),S0()}const cA=["dev-driver","query-fetch-probe"];let k0=null;function mct(){if(k0)return k0;const e=[],t=cN.prototype.fetch;return cN.prototype.fetch=function(...s){return e.push({at:Date.now(),key:JSON.stringify(this.queryKey),stack:(new Error().stack??"").split(`
694
+ */var t6;function lst(){if(t6)return pm;t6=1;var e=it,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,f={},p=null,g=null;u!==void 0&&(p=""+u),l.key!==void 0&&(p=""+l.key),l.ref!==void 0&&(g=l.ref);for(d in l)s.call(l,d)&&!i.hasOwnProperty(d)&&(f[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)f[d]===void 0&&(f[d]=l[d]);return{$$typeof:t,type:o,key:p,ref:g,props:f,_owner:r.current}}return pm.Fragment=n,pm.jsx=a,pm.jsxs=a,pm}var n6;function cst(){return n6||(n6=1,e6.exports=lst()),e6.exports}var ust=cst();/*! shepherd.js 14.5.0 */function dst(e){return e instanceof Element}function Qp(e){return e instanceof HTMLElement}function Qu(e){return typeof e=="function"}function Av(e){return typeof e=="string"}function ni(e){return e===void 0}class OD{on(t,n,s,r=!1){var i;return ni(this.bindings)&&(this.bindings={}),ni(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(ni(this.bindings)||ni(this.bindings[t]))return this;if(ni(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(!ni(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 $i(){return $i=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},$i.apply(null,arguments)}function LD(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 cd={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")};cd.defaultMerge;function hst(e,t){return t}function fst(e,t){return e.filter(n=>n!==void 0)}var s6;(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"})(s6||(s6={}));function r6(e){return typeof e!="object"||e===null?0:Array.isArray(e)?2:mst(e)?1:e instanceof Set?3:e instanceof Map?4:5}function pst(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 gst(e,t){return typeof e=="object"&&Object.prototype.propertyIsEnumerable.call(e,t)}function JK(e){return{*[Symbol.iterator](){for(const t of e)for(const n of t)yield n}}}const i6=new Set(["[object Object]","[object Module]"]);function mst(e){if(!i6.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"||!i6.has(Object.prototype.toString.call(n))||!n.hasOwnProperty("isPrototypeOf"))}function vst(e,t,n){const s={};for(const r of pst(e)){const i=[];for(const l of e)gst(l,r)&&i.push(l[r]);if(i.length===0)continue;const a=t.metaDataUpdater(n,{key:r,parents:e}),o=ZK(i,t,a);o!==cd.skip&&(r==="__proto__"?Object.defineProperty(s,r,{value:o,configurable:!0,enumerable:!0,writable:!0}):s[r]=o)}return s}function bst(e){return e.flat()}function xst(e){return new Set(JK(e))}function _st(e){return new Map(JK(e))}function wst(e){return e.at(-1)}const Mx={mergeRecords:vst,mergeArrays:bst,mergeSets:xst,mergeMaps:_st,mergeOthers:wst};function BD(...e){return yst({})(...e)}function yst(e,t){const n=Cst(e,s);function s(...r){return ZK(r,n,t)}return s}function Cst(e,t){var n,s,r;return{defaultMergeFunctions:Mx,mergeFunctions:$i({},Mx,Object.fromEntries(Object.entries(e).filter(([i,a])=>Object.hasOwn(Mx,i)).map(([i,a])=>a===!1?[i,Mx.mergeOthers]:[i,a]))),metaDataUpdater:(n=e.metaDataUpdater)!=null?n:hst,deepmerge:t,useImplicitDefaultMerging:(s=e.enableImplicitDefaultMerging)!=null?s:!1,filterValues:e.filterValues===!1?void 0:(r=e.filterValues)!=null?r:fst,actions:cd}}function ZK(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 Gk(r,t,n);const i=r6(r[0]);if(i!==0&&i!==5){for(let a=1;a<r.length;a++)if(r6(r[a])!==i)return Gk(r,t,n)}switch(i){case 1:return Sst(r,t,n);case 2:return kst(r,t,n);case 3:return Est(r,t,n);case 4:return Tst(r,t,n);default:return Gk(r,t,n)}}function Sst(e,t,n){const s=t.mergeFunctions.mergeRecords(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(e,t,n):s}function kst(e,t,n){const s=t.mergeFunctions.mergeArrays(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(e):s}function Est(e,t,n){const s=t.mergeFunctions.mergeSets(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(e):s}function Tst(e,t,n){const s=t.mergeFunctions.mergeMaps(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(e):s}function Gk(e,t,n){const s=t.mergeFunctions.mergeOthers(e,t,n);return s===cd.defaultMerge||t.useImplicitDefaultMerging&&s===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(e):s}function jD(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 Rst(e,t){return n=>{if(e.isOpen()){const s=e.el&&n.currentTarget===e.el;(!ni(t)&&n.currentTarget.matches(t)||s)&&e.tour.next()}}}function Ast(e){const{event:t,selector:n}=e.options.advanceOn||{};if(t){const s=Rst(e,n);let r=null;if(!ni(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 Fst{constructor(t){}}class Dst{constructor(t,n){}}function eY(e){return!Av(e)||e===""?"":e.charAt(e.length-1)!=="-"?`${e}-`:e}function Ist(e){const t=e.options.attachTo||{},n=Object.assign({},t);if(Qu(n.element)&&(n.element=n.element.call(e)),Av(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 Nst(e){return e.options.extraHighlights?e.options.extraHighlights.flatMap(t=>Array.from(document.querySelectorAll(t))):[]}function tY(e){return e==null?!0:!e.element||!e.on}function nY(){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 Pst=["top","right","bottom","left"],a6=["start","end"],o6=Pst.reduce((e,t)=>e.concat(t,t+"-"+a6[0],t+"-"+a6[1]),[]),Jp=Math.min,mh=Math.max,sy=Math.round,Ox=Math.floor,_l=e=>({x:e,y:e}),Mst={left:"right",right:"left",bottom:"top",top:"bottom"},Ost={start:"end",end:"start"};function qR(e,t,n){return mh(e,Jp(t,n))}function jh(e,t){return typeof e=="function"?e(t):e}function Sc(e){return e.split("-")[0]}function bc(e){return e.split("-")[1]}function HD(e){return e==="x"?"y":"x"}function UD(e){return e==="y"?"height":"width"}function Zp(e){return["top","bottom"].includes(Sc(e))?"y":"x"}function GD(e){return HD(Zp(e))}function sY(e,t,n){n===void 0&&(n=!1);const s=bc(e),r=GD(e),i=UD(r);let a=r==="x"?s===(n?"end":"start")?"right":"left":s==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=iy(a)),[a,iy(a)]}function Lst(e){const t=iy(e);return[ry(e),t,ry(t)]}function ry(e){return e.replace(/start|end/g,t=>Ost[t])}function Bst(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 jst(e,t,n,s){const r=bc(e);let i=Bst(Sc(e),n==="start",s);return r&&(i=i.map(a=>a+"-"+r),t&&(i=i.concat(i.map(ry)))),i}function iy(e){return e.replace(/left|right|bottom|top/g,t=>Mst[t])}function Hst(e){return $i({top:0,right:0,bottom:0,left:0},e)}function rY(e){return typeof e!="number"?Hst(e):{top:e,right:e,bottom:e,left:e}}function ay(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 Ust=["crossAxis","alignment","allowedPlacements","autoAlignment"],Gst=["mainAxis","crossAxis","fallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment"],Vst=["mainAxis","crossAxis","limiter"];function l6(e,t,n){let{reference:s,floating:r}=e;const i=Zp(t),a=GD(t),o=UD(a),l=Sc(t),u=i==="y",d=s.x+s.width/2-r.width/2,f=s.y+s.height/2-r.height/2,p=s[o]/2-r[o]/2;let g;switch(l){case"top":g={x:d,y:s.y-r.height};break;case"bottom":g={x:d,y:s.y+s.height};break;case"right":g={x:s.x+s.width,y:f};break;case"left":g={x:s.x-r.width,y:f};break;default:g={x:s.x,y:s.y}}switch(bc(t)){case"start":g[a]-=p*(n&&u?-1:1);break;case"end":g[a]+=p*(n&&u?-1:1);break}return g}const Wst=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:f}=l6(u,s,l),p=s,g={},v=0;for(let b=0;b<o.length;b++){const{name:x,fn:_}=o[b],{x:w,y,data:S,reset:C}=await _({x:d,y:f,initialPlacement:s,placement:p,strategy:r,middlewareData:g,rects:u,platform:a,elements:{reference:e,floating:t}});d=w??d,f=y??f,g=$i({},g,{[x]:$i({},g[x],S)}),C&&v<=50&&(v++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(u=C.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:r}):C.rects),{x:d,y:f}=l6(u,p,l)),b=-1)}return{x:d,y:f,placement:p,strategy:r,middlewareData:g}};async function VD(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:f="floating",altBoundary:p=!1,padding:g=0}=jh(t,e),v=rY(g),b=o[p?f==="floating"?"reference":"floating":f],x=ay(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:u,rootBoundary:d,strategy:l})),_=f==="floating"?{x:s,y:r,width:a.floating.width,height:a.floating.height}:a.reference,w=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),y=await(i.isElement==null?void 0:i.isElement(w))?await(i.getScale==null?void 0:i.getScale(w))||{x:1,y:1}:{x:1,y:1},S=ay(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:_,offsetParent:w,strategy:l}):_);return{top:(x.top-S.top+v.top)/y.y,bottom:(S.bottom-x.bottom+v.bottom)/y.y,left:(x.left-S.left+v.left)/y.x,right:(S.right-x.right+v.right)/y.x}}const $st=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}=jh(e,t)||{};if(u==null)return{};const f=rY(d),p={x:n,y:s},g=GD(r),v=UD(g),b=await a.getDimensions(u),x=g==="y",_=x?"top":"left",w=x?"bottom":"right",y=x?"clientHeight":"clientWidth",S=i.reference[v]+i.reference[g]-p[g]-i.floating[v],C=p[g]-i.reference[g],E=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let k=E?E[y]:0;(!k||!await(a.isElement==null?void 0:a.isElement(E)))&&(k=o.floating[y]||i.floating[v]);const F=S/2-C/2,A=k/2-b[v]/2-1,I=Jp(f[_],A),N=Jp(f[w],A),P=I,M=k-b[v]-N,Y=k/2-b[v]/2+F,O=qR(P,Y,M),X=!l.arrow&&bc(r)!=null&&Y!==O&&i.reference[v]/2-(Y<P?I:N)-b[v]/2<0,Q=X?Y<P?Y-P:Y-M:0;return{[g]:p[g]+Q,data:$i({[g]:O,centerOffset:Y-O-Q},X&&{alignmentOffset:Q}),reset:X}}});function zst(e,t,n){return(e?[...n.filter(s=>bc(s)===e),...n.filter(s=>bc(s)!==e)]:n.filter(s=>Sc(s)===s)).filter(s=>e?bc(s)===e||(t?ry(s)!==s:!1):!0)}const qst=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=jh(e,t),{crossAxis:f=!1,alignment:p,allowedPlacements:g=o6,autoAlignment:v=!0}=d,b=LD(d,Ust),x=p!==void 0||g===o6?zst(p||null,v,g):g,_=await VD(t,b),w=((n=a.autoPlacement)==null?void 0:n.index)||0,y=x[w];if(y==null)return{};const S=sY(y,i,await(l.isRTL==null?void 0:l.isRTL(u.floating)));if(o!==y)return{reset:{placement:x[0]}};const C=[_[Sc(y)],_[S[0]],_[S[1]]],E=[...((s=a.autoPlacement)==null?void 0:s.overflows)||[],{placement:y,overflows:C}],k=x[w+1];if(k)return{data:{index:w+1,overflows:E},reset:{placement:k}};const F=E.map(I=>{const N=bc(I.placement);return[I.placement,N&&f?I.overflows.slice(0,2).reduce((P,M)=>P+M,0):I.overflows[0],I.overflows]}).sort((I,N)=>I[1]-N[1]),A=((r=F.filter(I=>I[2].slice(0,bc(I[0])?2:3).every(N=>N<=0))[0])==null?void 0:r[0])||F[0][0];return A!==o?{data:{index:w+1,overflows:E},reset:{placement:A}}:{}}}},Kst=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=jh(e,t),{mainAxis:f=!0,crossAxis:p=!0,fallbackPlacements:g,fallbackStrategy:v="bestFit",fallbackAxisSideDirection:b="none",flipAlignment:x=!0}=d,_=LD(d,Gst);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const w=Sc(r),y=Zp(o),S=Sc(o)===o,C=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=g||(S||!x?[iy(o)]:Lst(o)),k=b!=="none";!g&&k&&E.push(...jst(o,x,b,C));const F=[o,...E],A=await VD(t,_),I=[];let N=((s=i.flip)==null?void 0:s.overflows)||[];if(f&&I.push(A[w]),p){const O=sY(r,a,C);I.push(A[O[0]],A[O[1]])}if(N=[...N,{placement:r,overflows:I}],!I.every(O=>O<=0)){var P,M;const O=(((P=i.flip)==null?void 0:P.index)||0)+1,X=F[O];if(X)return{data:{index:O,overflows:N},reset:{placement:X}};let Q=(M=N.filter(ie=>ie.overflows[0]<=0).sort((ie,G)=>ie.overflows[1]-G.overflows[1])[0])==null?void 0:M.placement;if(!Q)switch(v){case"bestFit":{var Y;const ie=(Y=N.filter(G=>{if(k){const ne=Zp(G.placement);return ne===y||ne==="y"}return!0}).map(G=>[G.placement,G.overflows.filter(ne=>ne>0).reduce((ne,oe)=>ne+oe,0)]).sort((G,ne)=>G[1]-ne[1])[0])==null?void 0:Y[0];ie&&(Q=ie);break}case"initialPlacement":Q=o;break}if(r!==Q)return{reset:{placement:Q}}}return{}}}},Yst=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:r}=t,i=jh(e,t),{mainAxis:a=!0,crossAxis:o=!1,limiter:l={fn:_=>{let{x:w,y}=_;return{x:w,y}}}}=i,u=LD(i,Vst),d={x:n,y:s},f=await VD(t,u),p=Zp(Sc(r)),g=HD(p);let v=d[g],b=d[p];if(a){const _=g==="y"?"top":"left",w=g==="y"?"bottom":"right",y=v+f[_],S=v-f[w];v=qR(y,v,S)}if(o){const _=p==="y"?"top":"left",w=p==="y"?"bottom":"right",y=b+f[_],S=b-f[w];b=qR(y,b,S)}const x=l.fn($i({},t,{[g]:v,[p]:b}));return $i({},x,{data:{x:x.x-n,y:x.y-s}})}}},Xst=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}=jh(e,t),d={x:n,y:s},f=Zp(r),p=HD(f);let g=d[p],v=d[f];const b=jh(o,t),x=typeof b=="number"?{mainAxis:b,crossAxis:0}:$i({mainAxis:0,crossAxis:0},b);if(l){const y=p==="y"?"height":"width",S=i.reference[p]-i.floating[y]+x.mainAxis,C=i.reference[p]+i.reference[y]-x.mainAxis;g<S?g=S:g>C&&(g=C)}if(u){var _,w;const y=p==="y"?"width":"height",S=["top","left"].includes(Sc(r)),C=i.reference[f]-i.floating[y]+(S&&((_=a.offset)==null?void 0:_[f])||0)+(S?0:x.crossAxis),E=i.reference[f]+i.reference[y]+(S?0:((w=a.offset)==null?void 0:w[f])||0)-(S?x.crossAxis:0);v<C?v=C:v>E&&(v=E)}return{[p]:g,[f]:v}}}};function IC(){return typeof window<"u"}function Tg(e){return iY(e)?(e.nodeName||"").toLowerCase():"#document"}function fa(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Il(e){var t;return(t=(iY(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function iY(e){return IC()?e instanceof Node||e instanceof fa(e).Node:!1}function Oo(e){return IC()?e instanceof Element||e instanceof fa(e).Element:!1}function El(e){return IC()?e instanceof HTMLElement||e instanceof fa(e).HTMLElement:!1}function c6(e){return!IC()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof fa(e).ShadowRoot}function pb(e){const{overflow:t,overflowX:n,overflowY:s,display:r}=Lo(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&!["inline","contents"].includes(r)}function Qst(e){return["table","td","th"].includes(Tg(e))}function NC(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function WD(e){const t=$D(),n=Oo(e)?Lo(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 Jst(e){let t=Ju(e);for(;El(t)&&!eg(t);){if(WD(t))return t;if(NC(t))return null;t=Ju(t)}return null}function $D(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function eg(e){return["html","body","#document"].includes(Tg(e))}function Lo(e){return fa(e).getComputedStyle(e)}function PC(e){return Oo(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ju(e){if(Tg(e)==="html")return e;const t=e.assignedSlot||e.parentNode||c6(e)&&e.host||Il(e);return c6(t)?t.host:t}function aY(e){const t=Ju(e);return eg(t)?e.ownerDocument?e.ownerDocument.body:e.body:El(t)&&pb(t)?t:aY(t)}function Fv(e,t,n){var s;t===void 0&&(t=[]),n===void 0&&(n=!0);const r=aY(e),i=r===((s=e.ownerDocument)==null?void 0:s.body),a=fa(r);if(i){const o=KR(a);return t.concat(a,a.visualViewport||[],pb(r)?r:[],o&&n?Fv(o):[])}return t.concat(r,Fv(r,[],n))}function KR(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function oY(e){const t=Lo(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const r=El(e),i=r?e.offsetWidth:n,a=r?e.offsetHeight:s,o=sy(n)!==i||sy(s)!==a;return o&&(n=i,s=a),{width:n,height:s,$:o}}function zD(e){return Oo(e)?e:e.contextElement}function Tp(e){const t=zD(e);if(!El(t))return _l(1);const n=t.getBoundingClientRect(),{width:s,height:r,$:i}=oY(t);let a=(i?sy(n.width):n.width)/s,o=(i?sy(n.height):n.height)/r;return(!a||!Number.isFinite(a))&&(a=1),(!o||!Number.isFinite(o))&&(o=1),{x:a,y:o}}const Zst=_l(0);function lY(e){const t=fa(e);return!$D()||!t.visualViewport?Zst:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function ert(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==fa(e)?!1:t}function Hh(e,t,n,s){t===void 0&&(t=!1),n===void 0&&(n=!1);const r=e.getBoundingClientRect(),i=zD(e);let a=_l(1);t&&(s?Oo(s)&&(a=Tp(s)):a=Tp(e));const o=ert(i,n,s)?lY(i):_l(0);let l=(r.left+o.x)/a.x,u=(r.top+o.y)/a.y,d=r.width/a.x,f=r.height/a.y;if(i){const p=fa(i),g=s&&Oo(s)?fa(s):s;let v=p,b=KR(v);for(;b&&s&&g!==v;){const x=Tp(b),_=b.getBoundingClientRect(),w=Lo(b),y=_.left+(b.clientLeft+parseFloat(w.paddingLeft))*x.x,S=_.top+(b.clientTop+parseFloat(w.paddingTop))*x.y;l*=x.x,u*=x.y,d*=x.x,f*=x.y,l+=y,u+=S,v=fa(b),b=KR(v)}}return ay({width:d,height:f,x:l,y:u})}function qD(e,t){const n=PC(e).scrollLeft;return t?t.left+n:Hh(Il(e)).left+n}function cY(e,t,n){n===void 0&&(n=!1);const s=e.getBoundingClientRect(),r=s.left+t.scrollLeft-(n?0:qD(e,s)),i=s.top+t.scrollTop;return{x:r,y:i}}function trt(e){let{elements:t,rect:n,offsetParent:s,strategy:r}=e;const i=r==="fixed",a=Il(s),o=t?NC(t.floating):!1;if(s===a||o&&i)return n;let l={scrollLeft:0,scrollTop:0},u=_l(1);const d=_l(0),f=El(s);if((f||!f&&!i)&&((Tg(s)!=="body"||pb(a))&&(l=PC(s)),El(s))){const g=Hh(s);u=Tp(s),d.x=g.x+s.clientLeft,d.y=g.y+s.clientTop}const p=a&&!f&&!i?cY(a,l,!0):_l(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+d.x+p.x,y:n.y*u.y-l.scrollTop*u.y+d.y+p.y}}function nrt(e){return Array.from(e.getClientRects())}function srt(e){const t=Il(e),n=PC(e),s=e.ownerDocument.body,r=mh(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),i=mh(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let a=-n.scrollLeft+qD(e);const o=-n.scrollTop;return Lo(s).direction==="rtl"&&(a+=mh(t.clientWidth,s.clientWidth)-r),{width:r,height:i,x:a,y:o}}function rrt(e,t){const n=fa(e),s=Il(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=$D();(!u||u&&t==="fixed")&&(o=r.offsetLeft,l=r.offsetTop)}return{width:i,height:a,x:o,y:l}}function irt(e,t){const n=Hh(e,!0,t==="fixed"),s=n.top+e.clientTop,r=n.left+e.clientLeft,i=El(e)?Tp(e):_l(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 u6(e,t,n){let s;if(t==="viewport")s=rrt(e,n);else if(t==="document")s=srt(Il(e));else if(Oo(t))s=irt(t,n);else{const r=lY(e);s={x:t.x-r.x,y:t.y-r.y,width:t.width,height:t.height}}return ay(s)}function uY(e,t){const n=Ju(e);return n===t||!Oo(n)||eg(n)?!1:Lo(n).position==="fixed"||uY(n,t)}function art(e,t){const n=t.get(e);if(n)return n;let s=Fv(e,[],!1).filter(o=>Oo(o)&&Tg(o)!=="body"),r=null;const i=Lo(e).position==="fixed";let a=i?Ju(e):e;for(;Oo(a)&&!eg(a);){const o=Lo(a),l=WD(a);!l&&o.position==="fixed"&&(r=null),(i?!l&&!r:!l&&o.position==="static"&&r&&["absolute","fixed"].includes(r.position)||pb(a)&&!l&&uY(e,a))?s=s.filter(u=>u!==a):r=o,a=Ju(a)}return t.set(e,s),s}function ort(e){let{element:t,boundary:n,rootBoundary:s,strategy:r}=e;const i=[...n==="clippingAncestors"?NC(t)?[]:art(t,this._c):[].concat(n),s],a=i[0],o=i.reduce((l,u)=>{const d=u6(t,u,r);return l.top=mh(d.top,l.top),l.right=Jp(d.right,l.right),l.bottom=Jp(d.bottom,l.bottom),l.left=mh(d.left,l.left),l},u6(t,a,r));return{width:o.right-o.left,height:o.bottom-o.top,x:o.left,y:o.top}}function lrt(e){const{width:t,height:n}=oY(e);return{width:t,height:n}}function crt(e,t,n){const s=El(t),r=Il(t),i=n==="fixed",a=Hh(e,!0,i,t);let o={scrollLeft:0,scrollTop:0};const l=_l(0);if(s||!s&&!i)if((Tg(t)!=="body"||pb(r))&&(o=PC(t)),s){const p=Hh(t,!0,i,t);l.x=p.x+t.clientLeft,l.y=p.y+t.clientTop}else r&&(l.x=qD(r));const u=r&&!s&&!i?cY(r,o):_l(0),d=a.left+o.scrollLeft-l.x-u.x,f=a.top+o.scrollTop-l.y-u.y;return{x:d,y:f,width:a.width,height:a.height}}function Vk(e){return Lo(e).position==="static"}function d6(e,t){if(!El(e)||Lo(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Il(e)===n&&(n=n.ownerDocument.body),n}function dY(e,t){const n=fa(e);if(NC(e))return n;if(!El(e)){let r=Ju(e);for(;r&&!eg(r);){if(Oo(r)&&!Vk(r))return r;r=Ju(r)}return n}let s=d6(e,t);for(;s&&Qst(s)&&Vk(s);)s=d6(s,t);return s&&eg(s)&&Vk(s)&&!WD(s)?n:s||Jst(e)||n}const urt=async function(e){const t=this.getOffsetParent||dY,n=this.getDimensions,s=await n(e.floating);return{reference:crt(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}};function drt(e){return Lo(e).direction==="rtl"}const hrt={convertOffsetParentRelativeRectToViewportRelativeRect:trt,getDocumentElement:Il,getClippingRect:ort,getOffsetParent:dY,getElementRects:urt,getClientRects:nrt,getDimensions:lrt,getScale:Tp,isElement:Oo,isRTL:drt};function frt(e,t){let n=null,s;const r=Il(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:f,height:p}=e.getBoundingClientRect();if(o||t(),!f||!p)return;const g=Ox(d),v=Ox(r.clientWidth-(u+f)),b=Ox(r.clientHeight-(d+p)),x=Ox(u),_={rootMargin:-g+"px "+-v+"px "+-b+"px "+-x+"px",threshold:mh(0,Jp(1,l))||1};let w=!0;function y(S){const C=S[0].intersectionRatio;if(C!==l){if(!w)return a();C?a(!1,C):s=setTimeout(()=>{a(!1,1e-7)},1e3)}w=!1}try{n=new IntersectionObserver(y,$i({},_,{root:r.ownerDocument}))}catch{n=new IntersectionObserver(y,_)}n.observe(e)}return a(!0),i}function prt(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=zD(e),d=r||i?[...u?Fv(u):[],...Fv(t)]:[];d.forEach(_=>{r&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const f=u&&o?frt(u,n):null;let p=-1,g=null;a&&(g=new ResizeObserver(_=>{let[w]=_;w&&w.target===u&&g&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var y;(y=g)==null||y.observe(t)})),n()}),u&&!l&&g.observe(u),g.observe(t));let v,b=l?Hh(e):null;l&&x();function x(){const _=Hh(e);b&&(_.x!==b.x||_.y!==b.y||_.width!==b.width||_.height!==b.height)&&n(),b=_,v=requestAnimationFrame(x)}return n(),()=>{var _;d.forEach(w=>{r&&w.removeEventListener("scroll",n),i&&w.removeEventListener("resize",n)}),f?.(),(_=g)==null||_.disconnect(),g=null,l&&cancelAnimationFrame(v)}}const grt=qst,mrt=Yst,vrt=Kst,brt=$st,xrt=Xst,_rt=(e,t,n)=>{const s=new Map,r=$i({platform:hrt},n),i=$i({},r.platform,{_c:s});return Wst(e,t,$i({},r,{platform:i}))};function wrt(e){e.cleanup&&e.cleanup();const t=e._getResolvedAttachToOptions();let n=t.element;const s=Trt(t,e),r=tY(t);return r&&(n=document.body,e.shepherdElementComponent.getElement().classList.add("shepherd-centered")),e.cleanup=prt(n,e.el,()=>{if(!e.el){e.cleanup==null||e.cleanup();return}Srt(n,e,s,r)}),e.target=t.element,s}function yrt(e,t){return{floatingUIOptions:BD(e.floatingUIOptions||{},t.floatingUIOptions||{})}}function Crt(e){e.cleanup&&e.cleanup(),e.cleanup=null}function Srt(e,t,n,s){return _rt(e,t.el,n).then(krt(t,s)).then(r=>new Promise(i=>{setTimeout(()=>i(r),300)})).then(r=>{r!=null&&r.el&&r.el.focus({preventScroll:!0})})}function krt(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,Ert(e.el,i)),e)}function Ert(e,t){const n=e.querySelector(".shepherd-arrow");if(Qp(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 Trt(e,t){var n,s,r;const i={strategy:"absolute"};i.middleware=[];const a=Rrt(t),o=tY(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(grt({crossAxis:!0,alignment:u?e==null||(d=e.on)==null?void 0:d.split("-").pop():null}))}else i.middleware.push(vrt());if(i.middleware.push(mrt({limiter:xrt(),crossAxis:!0})),a){const f=typeof t.options.arrow=="object"?t.options.arrow:{padding:4};i.middleware.push(brt({element:a,padding:u?f.padding:0}))}l||(i.placement=e.on)}return BD(i,t.options.floatingUIOptions||{})}function Rrt(e){return e.options.arrow&&e.el?e.el.querySelector(".shepherd-arrow"):!1}function ma(){}function Art(e,t){for(const n in t)e[n]=t[n];return e}function hY(e){return e()}function h6(){return Object.create(null)}function gb(e){e.forEach(hY)}function KD(e){return typeof e=="function"}function Oc(e,t){return e!=e?t==t:e!==t||e&&typeof e=="object"||typeof e=="function"}function Frt(e){return Object.keys(e).length===0}function tg(e,t){e.appendChild(t)}function Vo(e,t,n){e.insertBefore(t,n||null)}function oo(e){e.parentNode&&e.parentNode.removeChild(e)}function Drt(e,t){for(let n=0;n<e.length;n+=1)e[n]&&e[n].d(t)}function Tl(e){return document.createElement(e)}function f6(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function fY(e){return document.createTextNode(e)}function oy(){return fY(" ")}function Irt(){return fY("")}function MC(e,t,n,s){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}function os(e,t,n){n==null?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n)}const Nrt=["width","height"];function p6(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&&Nrt.indexOf(s)===-1?e[s]=t[s]:os(e,s,t[s])}function Prt(e){return Array.from(e.childNodes)}function Ff(e,t,n){e.classList.toggle(t,!!n)}let Dv;function C0(e){Dv=e}function pY(){if(!Dv)throw new Error("Function called outside component initialization");return Dv}function Mrt(e){pY().$$.on_mount.push(e)}function YD(e){pY().$$.after_update.push(e)}const Wf=[],ng=[];let Rp=[];const g6=[],Ort=Promise.resolve();let YR=!1;function Lrt(){YR||(YR=!0,Ort.then(gY))}function XR(e){Rp.push(e)}const Wk=new Set;let Df=0;function gY(){if(Df!==0)return;const e=Dv;do{try{for(;Df<Wf.length;){const t=Wf[Df];Df++,C0(t),Brt(t.$$)}}catch(t){throw Wf.length=0,Df=0,t}for(C0(null),Wf.length=0,Df=0;ng.length;)ng.pop()();for(let t=0;t<Rp.length;t+=1){const n=Rp[t];Wk.has(n)||(Wk.add(n),n())}Rp.length=0}while(Wf.length);for(;g6.length;)g6.pop()();YR=!1,Wk.clear(),C0(e)}function Brt(e){if(e.fragment!==null){e.update(),gb(e.before_update);const t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(XR)}}function jrt(e){const t=[],n=[];Rp.forEach(s=>e.indexOf(s)===-1?t.push(s):n.push(s)),n.forEach(s=>s()),Rp=t}const v_=new Set;let Zd;function vh(){Zd={r:0,c:[],p:Zd}}function bh(){Zd.r||gb(Zd.c),Zd=Zd.p}function Kn(e,t){e&&e.i&&(v_.delete(e),e.i(t))}function Ks(e,t,n,s){if(e&&e.o){if(v_.has(e))return;v_.add(e),Zd.c.push(()=>{v_.delete(e),s&&(n&&e.d(1),s())}),e.o(t)}else s&&s()}function m6(e){return e?.length!==void 0?e:Array.from(e)}function Hrt(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 nf(e){e&&e.c()}function ud(e,t,n){const{fragment:s,after_update:r}=e.$$;s&&s.m(t,n),XR(()=>{const i=e.$$.on_mount.map(hY).filter(KD);e.$$.on_destroy?e.$$.on_destroy.push(...i):gb(i),e.$$.on_mount=[]}),r.forEach(XR)}function dd(e,t){const n=e.$$;n.fragment!==null&&(jrt(n.after_update),gb(n.on_destroy),n.fragment&&n.fragment.d(t),n.on_destroy=n.fragment=null,n.ctx=[])}function Urt(e,t){e.$$.dirty[0]===-1&&(Wf.push(e),Lrt(),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<<t%31}function Lc(e,t,n,s,r,i,a=null,o=[-1]){const l=Dv;C0(e);const u=e.$$={fragment:null,ctx:[],props:i,update:ma,not_equal:r,bound:h6(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(l?l.$$.context:[])),callbacks:h6(),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||{},(f,p,...g)=>{const v=g.length?g[0]:p;return u.ctx&&r(u.ctx[f],u.ctx[f]=v)&&(!u.skip_bound&&u.bound[f]&&u.bound[f](v),d&&Urt(e,f)),p}):[],u.update(),d=!0,gb(u.before_update),u.fragment=s?s(u.ctx):!1,t.target){if(t.hydrate){const f=Prt(t.target);u.fragment&&u.fragment.l(f),f.forEach(oo)}else u.fragment&&u.fragment.c();t.intro&&Kn(e.$$.fragment),ud(e,t.target,t.anchor),gY()}C0(l)}class Bc{constructor(){this.$$=void 0,this.$$set=void 0}$destroy(){dd(this,1),this.$destroy=ma}$on(t,n){if(!KD(n))return ma;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&&!Frt(t)&&(this.$$.skip_bound=!0,this.$$set(t),this.$$.skip_bound=!1)}}const Grt="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Grt);function Vrt(e){let t,n,s,r,i;return{c(){t=Tl("button"),os(t,"aria-label",n=e[3]?e[3]:null),os(t,"class",s=`${e[1]||""} shepherd-button ${e[4]?"shepherd-button-secondary":""}`),t.disabled=e[2],os(t,"tabindex","0"),os(t,"type","button")},m(a,o){Vo(a,t,o),t.innerHTML=e[5],r||(i=MC(t,"click",function(){KD(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)&&os(t,"aria-label",n),o&18&&s!==(s=`${e[1]||""} shepherd-button ${e[4]?"shepherd-button-secondary":""}`)&&os(t,"class",s),o&4&&(t.disabled=e[2])},i:ma,o:ma,d(a){a&&oo(t),r=!1,i()}}}function Wrt(e,t,n){let{config:s,step:r}=t,i,a,o,l,u,d;function f(p){return Qu(p)?p=p.call(r):p}return e.$$set=p=>{"config"in p&&n(6,s=p.config),"step"in p&&n(7,r=p.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?f(s.disabled):!1),n(3,l=s.label?f(s.label):null),n(4,u=s.secondary),n(5,d=s.text?f(s.text):null))},[i,a,o,l,u,d,s,r]}class $rt extends Bc{constructor(t){super(),Lc(this,t,Wrt,Vrt,Oc,{config:6,step:7})}}function v6(e,t,n){const s=e.slice();return s[2]=t[n],s}function b6(e){let t,n,s=m6(e[1]),r=[];for(let a=0;a<s.length;a+=1)r[a]=x6(v6(e,s,a));const i=a=>Ks(r[a],1,1,()=>{r[a]=null});return{c(){for(let a=0;a<r.length;a+=1)r[a].c();t=Irt()},m(a,o){for(let l=0;l<r.length;l+=1)r[l]&&r[l].m(a,o);Vo(a,t,o),n=!0},p(a,o){if(o&3){s=m6(a[1]);let l;for(l=0;l<s.length;l+=1){const u=v6(a,s,l);r[l]?(r[l].p(u,o),Kn(r[l],1)):(r[l]=x6(u),r[l].c(),Kn(r[l],1),r[l].m(t.parentNode,t))}for(vh(),l=s.length;l<r.length;l+=1)i(l);bh()}},i(a){if(!n){for(let o=0;o<s.length;o+=1)Kn(r[o]);n=!0}},o(a){r=r.filter(Boolean);for(let o=0;o<r.length;o+=1)Ks(r[o]);n=!1},d(a){a&&oo(t),Drt(r,a)}}}function x6(e){let t,n;return t=new $rt({props:{config:e[2],step:e[0]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function zrt(e){let t,n,s=e[1]&&b6(e);return{c(){t=Tl("footer"),s&&s.c(),os(t,"class","shepherd-footer")},m(r,i){Vo(r,t,i),s&&s.m(t,null),n=!0},p(r,[i]){r[1]?s?(s.p(r,i),i&2&&Kn(s,1)):(s=b6(r),s.c(),Kn(s,1),s.m(t,null)):s&&(vh(),Ks(s,1,1,()=>{s=null}),bh())},i(r){n||(Kn(s),n=!0)},o(r){Ks(s),n=!1},d(r){r&&oo(t),s&&s.d()}}}function qrt(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 Krt extends Bc{constructor(t){super(),Lc(this,t,qrt,zrt,Oc,{step:0})}}function Yrt(e){let t,n,s,r,i;return{c(){t=Tl("button"),n=Tl("span"),n.textContent="×",os(n,"aria-hidden","true"),os(t,"aria-label",s=e[0].label?e[0].label:"Close Tour"),os(t,"class","shepherd-cancel-icon"),os(t,"type","button")},m(a,o){Vo(a,t,o),tg(t,n),r||(i=MC(t,"click",e[1]),r=!0)},p(a,[o]){o&1&&s!==(s=a[0].label?a[0].label:"Close Tour")&&os(t,"aria-label",s)},i:ma,o:ma,d(a){a&&oo(t),r=!1,i()}}}function Xrt(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 Qrt extends Bc{constructor(t){super(),Lc(this,t,Xrt,Yrt,Oc,{cancelIcon:0,step:2})}}function Jrt(e){let t;return{c(){t=Tl("h3"),os(t,"id",e[1]),os(t,"class","shepherd-title")},m(n,s){Vo(n,t,s),e[3](t)},p(n,[s]){s&2&&os(t,"id",n[1])},i:ma,o:ma,d(n){n&&oo(t),e[3](null)}}}function Zrt(e,t,n){let{labelId:s,element:r,title:i}=t;YD(()=>{Qu(i)&&n(2,i=i()),n(0,r.innerHTML=i,r)});function a(o){ng[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 eit extends Bc{constructor(t){super(),Lc(this,t,Zrt,Jrt,Oc,{labelId:1,element:0,title:2})}}function _6(e){let t,n;return t=new eit({props:{labelId:e[0],title:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function w6(e){let t,n;return t=new Qrt({props:{cancelIcon:e[3],step:e[1]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function tit(e){let t,n,s,r=e[2]&&_6(e),i=e[3]&&e[3].enabled&&w6(e);return{c(){t=Tl("header"),r&&r.c(),n=oy(),i&&i.c(),os(t,"class","shepherd-header")},m(a,o){Vo(a,t,o),r&&r.m(t,null),tg(t,n),i&&i.m(t,null),s=!0},p(a,[o]){a[2]?r?(r.p(a,o),o&4&&Kn(r,1)):(r=_6(a),r.c(),Kn(r,1),r.m(t,n)):r&&(vh(),Ks(r,1,1,()=>{r=null}),bh()),a[3]&&a[3].enabled?i?(i.p(a,o),o&8&&Kn(i,1)):(i=w6(a),i.c(),Kn(i,1),i.m(t,null)):i&&(vh(),Ks(i,1,1,()=>{i=null}),bh())},i(a){s||(Kn(r),Kn(i),s=!0)},o(a){Ks(r),Ks(i),s=!1},d(a){a&&oo(t),r&&r.d(),i&&i.d()}}}function nit(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 sit extends Bc{constructor(t){super(),Lc(this,t,nit,tit,Oc,{labelId:0,step:1})}}function rit(e){let t;return{c(){t=Tl("div"),os(t,"class","shepherd-text"),os(t,"id",e[1])},m(n,s){Vo(n,t,s),e[3](t)},p(n,[s]){s&2&&os(t,"id",n[1])},i:ma,o:ma,d(n){n&&oo(t),e[3](null)}}}function iit(e,t,n){let{descriptionId:s,element:r,step:i}=t;YD(()=>{let{text:o}=i.options;Qu(o)&&(o=o.call(i)),Qp(o)?r.appendChild(o):n(0,r.innerHTML=o,r)});function a(o){ng[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 ait extends Bc{constructor(t){super(),Lc(this,t,iit,rit,Oc,{descriptionId:1,element:0,step:2})}}function y6(e){let t,n;return t=new sit({props:{labelId:e[1],step:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function C6(e){let t,n;return t=new ait({props:{descriptionId:e[0],step:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(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||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function S6(e){let t,n;return t=new Krt({props:{step:e[2]}}),{c(){nf(t.$$.fragment)},m(s,r){ud(t,s,r),n=!0},p(s,r){const i={};r&4&&(i.step=s[2]),t.$set(i)},i(s){n||(Kn(t.$$.fragment,s),n=!0)},o(s){Ks(t.$$.fragment,s),n=!1},d(s){dd(t,s)}}}function oit(e){let t,n=!ni(e[2].options.title)||e[2].options.cancelIcon&&e[2].options.cancelIcon.enabled,s,r=!ni(e[2].options.text),i,a=Array.isArray(e[2].options.buttons)&&e[2].options.buttons.length,o,l=n&&y6(e),u=r&&C6(e),d=a&&S6(e);return{c(){t=Tl("div"),l&&l.c(),s=oy(),u&&u.c(),i=oy(),d&&d.c(),os(t,"class","shepherd-content")},m(f,p){Vo(f,t,p),l&&l.m(t,null),tg(t,s),u&&u.m(t,null),tg(t,i),d&&d.m(t,null),o=!0},p(f,[p]){p&4&&(n=!ni(f[2].options.title)||f[2].options.cancelIcon&&f[2].options.cancelIcon.enabled),n?l?(l.p(f,p),p&4&&Kn(l,1)):(l=y6(f),l.c(),Kn(l,1),l.m(t,s)):l&&(vh(),Ks(l,1,1,()=>{l=null}),bh()),p&4&&(r=!ni(f[2].options.text)),r?u?(u.p(f,p),p&4&&Kn(u,1)):(u=C6(f),u.c(),Kn(u,1),u.m(t,i)):u&&(vh(),Ks(u,1,1,()=>{u=null}),bh()),p&4&&(a=Array.isArray(f[2].options.buttons)&&f[2].options.buttons.length),a?d?(d.p(f,p),p&4&&Kn(d,1)):(d=S6(f),d.c(),Kn(d,1),d.m(t,null)):d&&(vh(),Ks(d,1,1,()=>{d=null}),bh())},i(f){o||(Kn(l),Kn(u),Kn(d),o=!0)},o(f){Ks(l),Ks(u),Ks(d),o=!1},d(f){f&&oo(t),l&&l.d(),u&&u.d(),d&&d.d()}}}function lit(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 cit extends Bc{constructor(t){super(),Lc(this,t,lit,oit,Oc,{descriptionId:0,labelId:1,step:2})}}function k6(e){let t;return{c(){t=Tl("div"),os(t,"class","shepherd-arrow"),os(t,"data-popper-arrow","")},m(n,s){Vo(n,t,s)},d(n){n&&oo(t)}}}function uit(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&&k6();s=new cit({props:{descriptionId:e[2],labelId:e[3],step:e[4]}});let d=[{"aria-describedby":r=ni(e[4].options.text)?null:e[2]},{"aria-labelledby":i=e[4].options.title?e[3]:null},e[1],{open:"true"}],f={};for(let p=0;p<d.length;p+=1)f=Art(f,d[p]);return{c(){t=Tl("dialog"),u&&u.c(),n=oy(),nf(s.$$.fragment),p6(t,f),Ff(t,"shepherd-has-cancel-icon",e[5]),Ff(t,"shepherd-has-title",e[6]),Ff(t,"shepherd-element",!0)},m(p,g){Vo(p,t,g),u&&u.m(t,null),tg(t,n),ud(s,t,null),e[13](t),a=!0,o||(l=MC(t,"keydown",e[7]),o=!0)},p(p,[g]){p[4].options.arrow&&p[4].options.attachTo&&p[4].options.attachTo.element&&p[4].options.attachTo.on?u||(u=k6(),u.c(),u.m(t,n)):u&&(u.d(1),u=null);const v={};g&4&&(v.descriptionId=p[2]),g&8&&(v.labelId=p[3]),g&16&&(v.step=p[4]),s.$set(v),p6(t,f=Hrt(d,[(!a||g&20&&r!==(r=ni(p[4].options.text)?null:p[2]))&&{"aria-describedby":r},(!a||g&24&&i!==(i=p[4].options.title?p[3]:null))&&{"aria-labelledby":i},g&2&&p[1],{open:"true"}])),Ff(t,"shepherd-has-cancel-icon",p[5]),Ff(t,"shepherd-has-title",p[6]),Ff(t,"shepherd-element",!0)},i(p){a||(Kn(s.$$.fragment,p),a=!0)},o(p){Ks(s.$$.fragment,p),a=!1},d(p){p&&oo(t),u&&u.d(),dd(s),e[13](null),o=!1,l()}}}const dit=9,hit=27,fit=37,pit=39;function E6(e){return e.split(" ").filter(t=>!!t.length)}function git(e,t,n){let{classPrefix:s,element:r,descriptionId:i,firstFocusableElement:a,focusableElements:o,labelId:l,lastFocusableElement:u,step:d,dataStepId:f}=t,p,g,v;const b=()=>r;Mrt(()=>{n(1,f={[`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])}),YD(()=>{v!==d.options.classes&&x()});function x(){_(v),v=d.options.classes,w(v)}function _(C){if(Av(C)){const E=E6(C);E.length&&r.classList.remove(...E)}}function w(C){if(Av(C)){const E=E6(C);E.length&&r.classList.add(...E)}}const y=C=>{const{tour:E}=d;switch(C.keyCode){case dit:if(o.length===0){C.preventDefault();break}C.shiftKey?(document.activeElement===a||document.activeElement.classList.contains("shepherd-element"))&&(C.preventDefault(),u.focus()):document.activeElement===u&&(C.preventDefault(),a.focus());break;case hit:E.options.exitOnEsc&&(C.preventDefault(),C.stopPropagation(),d.cancel());break;case fit:E.options.keyboardNavigation&&(C.preventDefault(),C.stopPropagation(),E.back());break;case pit:E.options.keyboardNavigation&&(C.preventDefault(),C.stopPropagation(),E.next());break}};function S(C){ng[C?"unshift":"push"](()=>{r=C,n(0,r)})}return e.$$set=C=>{"classPrefix"in C&&n(11,s=C.classPrefix),"element"in C&&n(0,r=C.element),"descriptionId"in C&&n(2,i=C.descriptionId),"firstFocusableElement"in C&&n(8,a=C.firstFocusableElement),"focusableElements"in C&&n(9,o=C.focusableElements),"labelId"in C&&n(3,l=C.labelId),"lastFocusableElement"in C&&n(10,u=C.lastFocusableElement),"step"in C&&n(4,d=C.step),"dataStepId"in C&&n(1,f=C.dataStepId)},e.$$.update=()=>{e.$$.dirty&16&&(n(5,p=d.options&&d.options.cancelIcon&&d.options.cancelIcon.enabled),n(6,g=d.options&&d.options.title))},[r,f,i,l,d,p,g,y,a,o,u,s,b,S]}class mit extends Bc{constructor(t){super(),Lc(this,t,git,uit,Oc,{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 QR extends OD{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?eY(this.tour.options.classPrefix):"",this.styles=t.styles,this._resolvedAttachTo=null,jD(this),this._setOptions(n),this}cancel(){this.tour.cancel(),this.trigger("cancel")}complete(){this.tour.complete(),this.trigger("complete")}destroy(){Crt(this),Qp(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=Nst(this),this._resolvedExtraHighlightElements}_resolveAttachToOptions(){return this._resolvedAttachTo=Ist(this),this._resolvedAttachTo}_getResolvedAttachToOptions(){return this._resolvedAttachTo===null?this._resolveAttachToOptions():this._resolvedAttachTo}isOpen(){return!!(this.el&&!this.el.hidden)}show(){return Qu(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 mit({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();Qu(this.options.scrollToHandler)?this.options.scrollToHandler(n):dst(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=BD({},n||{}),this.options=Object.assign({arrow:!0},n,t,yrt(n,t));const{when:s}=this.options;this.options.classes=this._getClassOptions(t),this.destroy(),this.id=this.options.id||`step-${nY()}`,s&&Object.keys(s).forEach(r=>{this.on(r,s[r],this)})}_setupElements(){ni(this.el)||this.destroy(),this.el=this._createTooltipContent(),this.options.advanceOn&&Ast(this),wrt(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 vit(e){if(e){const{steps:t}=e;t.forEach(n=>{n.options&&n.options.canClickTarget===!1&&n.options.attachTo&&(Qp(n.target)&&n.target.classList.remove("shepherd-target-click-disabled"),n._resolvedExtraHighlightElements&&n._resolvedExtraHighlightElements.forEach(s=>{Qp(s)&&s.classList.remove("shepherd-target-click-disabled")}))})}}function bit(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:f=0,bottomRight:p=0,bottomLeft:g=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-g} a${g},${g},0,0,0,${g},${g} H${i+o-p} a${p},${p},0,0,0,${p}-${p} V${l+f} a${f},${f},0,0,0-${f}-${f} Z`}),`M${n},${s} H0 V0 H${n} V${s} Z ${t}`.replace(/\s/g,"")}function xit(e){let t,n,s,r,i;return{c(){t=f6("svg"),n=f6("path"),os(n,"d",e[2]),os(t,"class",s=`${e[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)},m(a,o){Vo(a,t,o),tg(t,n),e[11](t),r||(i=MC(t,"touchmove",e[3]),r=!0)},p(a,[o]){o&4&&os(n,"d",a[2]),o&2&&s!==(s=`${a[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)&&os(t,"class",s)},i:ma,o:ma,d(a){a&&oo(t),e[11](null),r=!1,i()}}}function mY(e){if(!e)return null;const t=e instanceof HTMLElement&&window.getComputedStyle(e).overflowY;return t!=="hidden"&&t!=="visible"&&e.scrollHeight>=e.clientHeight?e:mY(e.parentElement)}function _it(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 wit(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 yit(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),_()}function f(S=0,C=0,E=0,k=0,F,A,I){if(A){const N=[A,...I||[]];n(4,r=[]);for(const P of N){if(!P||N.indexOf(P)!==N.lastIndexOf(P))continue;const{y:M,height:Y}=wit(P,F),{x:O,width:X,left:Q}=P.getBoundingClientRect();N.some(ie=>{if(ie===P)return!1;const G=ie.getBoundingClientRect();return O>=G.left&&O+X<=G.right&&M>=G.top&&M+Y<=G.bottom})||r.push({width:X+S*2,height:Y+S*2,x:(O||Q)+E-S,y:M+k-S,r:C})}}else u()}function p(S){_(),S.tour.options.useModalOverlay?(w(S),g()):d()}function g(){n(1,i=!0)}const v=S=>{S.preventDefault()},b=S=>{S.stopPropagation()};function x(){window.addEventListener("touchmove",v,{passive:!1})}function _(){a&&(cancelAnimationFrame(a),a=void 0),window.removeEventListener("touchmove",v,{passive:!1})}function w(S){const{modalOverlayOpeningPadding:C,modalOverlayOpeningRadius:E,modalOverlayOpeningXOffset:k=0,modalOverlayOpeningYOffset:F=0}=S.options,A=_it(S.target),I=mY(S.target),N=()=>{a=void 0,f(C,E,k+A.left,F+A.top,I,S.target,S._resolvedExtraHighlightElements),a=requestAnimationFrame(N)};N(),x()}function y(S){ng[S?"unshift":"push"](()=>{s=S,n(0,s)})}return e.$$set=S=>{"element"in S&&n(0,s=S.element),"openingProperties"in S&&n(4,r=S.openingProperties)},e.$$.update=()=>{e.$$.dirty&16&&n(2,o=bit(r))},[s,i,o,b,r,l,u,d,f,p,g,y]}class Cit extends Bc{constructor(t){super(),Lc(this,t,yit,xit,Oc,{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 Sit extends OD{constructor(){super(),this.activeTour=void 0,jD(this)}}class kit extends OD{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,jD(this);const n={exitOnEsc:!0,keyboardNavigation:!0};return this.options=Object.assign({},n,t),this.classPrefix=eY(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,eh.trigger(r,i)})})(s)}),this._setTourID(t.id),this}addStep(t,n){let s=t;return s instanceof QR?s.tour=this:s=new QR(this,s),ni(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;Qu(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 eh.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=Av(t)?this.getById(t):this.steps[t];s&&(this._updateStateBeforeShow(),Qu(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()),vit(this),this.trigger(t,{index:n}),eh.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)}Qp(this.focusedElBeforeOpen)&&this.focusedElBeforeOpen.focus()}_setupActiveTour(){this.trigger("active",{tour:this}),eh.activeTour=this}setupModal(){this.modal=new Cit({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||nY();this.id=`${n}--${s}`}}const eh=new Sit,vY=typeof window>"u";eh.Step=vY?Fst:QR;eh.Tour=vY?Dst:kit;const OC=m.createContext(void 0);OC.Consumer;const Eit=({children:e})=>ust.jsx(OC.Provider,{value:{Shepherd:eh},children:e}),ly=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Tit=e=>ly(e).replace(/"/g,"&quot;"),at=e=>ly(h(e)),Rit=['<div class="tour-figure-rail" aria-hidden="true">','<span class="tour-figure-dot"></span>','<span class="tour-figure-dot"></span>','<span class="tour-figure-dot"></span>','<span class="tour-figure-rail-line"></span>',"</div>",'<div class="tour-figure-main" aria-hidden="true">','<span class="tour-figure-bubble tour-figure-bubble-in"></span>','<span class="tour-figure-bubble tour-figure-bubble-out"></span>','<span class="tour-figure-composer">','<span class="tour-figure-composer-line"></span>','<span class="tour-figure-send"></span>',"</span>","</div>"].join(""),Ait=['<div class="tour-figure-flow" aria-hidden="true">','<div class="tour-figure-node">','<span class="tour-figure-node-icon"></span>','<span class="tour-figure-node-bar"></span>','<span class="tour-figure-node-bar tour-figure-node-bar-short"></span>',"</div>",'<span class="tour-figure-connector"></span>','<div class="tour-figure-node">','<span class="tour-figure-node-icon tour-figure-node-icon-round"></span>','<span class="tour-figure-node-bar"></span>','<span class="tour-figure-node-bar tour-figure-node-bar-short"></span>',"</div>",'<span class="tour-figure-connector"></span>','<div class="tour-figure-node">','<span class="tour-figure-node-icon tour-figure-node-icon-end"></span>','<span class="tour-figure-node-bar"></span>','<span class="tour-figure-node-bar tour-figure-node-bar-short"></span>',"</div>","</div>"].join(""),Fit={welcome:Rit,"agent-capabilities":Ait},T6=e=>e.map(t=>"key"in t?ly(h(t.key)):`<code>${ly(t.code)}</code>`).join(""),Dit=e=>{const t="<br/>".repeat(e.breaks??0);return e.kind==="paragraph"?`${T6(e.runs)}${t}`:e.kind==="list"?`<ul>${e.items.map(s=>`<li>${T6(s)}</li>`).join("")}</ul>${t}`:`<div class="tour-figure tour-figure-${e.figure}" role="img" aria-label="${Tit(h(e.altKey))}">${Fit[e.figure]}</div>${t}`},vn=e=>e.map(Dit).join(""),bn={welcome:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.1"}],breaks:1},{kind:"figure",figure:"welcome",altKey:"ui.onboarding.tour.welcome.image.1.alt",breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.2"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.3"}],breaks:0},{kind:"list",items:[[{key:"ui.onboarding.tour.welcome.list.1.item.1"}],[{key:"ui.onboarding.tour.welcome.list.1.item.2"}],[{key:"ui.onboarding.tour.welcome.list.1.item.3"}],[{key:"ui.onboarding.tour.welcome.list.1.item.4"}],[{key:"ui.onboarding.tour.welcome.list.1.item.5"}],[{key:"ui.onboarding.tour.welcome.list.1.item.6"}],[{key:"ui.onboarding.tour.welcome.list.1.item.7"}]],breaks:0},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.welcome.body.4"}],breaks:0}],agent_list:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_list.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_list.body.2"}],breaks:0}],select_agent:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.select_agent.body.1"}],breaks:0}],chat_input:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.chat_input.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.chat_input.body.2"}],breaks:2},{kind:"list",items:[[{key:"ui.onboarding.tour.chat_input.list.1.item.1"}],[{key:"ui.onboarding.tour.chat_input.list.1.item.2"}],[{key:"ui.onboarding.tour.chat_input.list.1.item.3"}]],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.chat_input.body.3"}],breaks:0}],attachments:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.2"}],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.3"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.attachments.body.4"}],breaks:0}],agent_capabilities:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_capabilities.body.1"}],breaks:1},{kind:"figure",figure:"agent-capabilities",altKey:"ui.onboarding.tour.agent_capabilities.image.1.alt",breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_capabilities.body.2"}],breaks:0}],pre_command_palette_open_canvas:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.1"},{code:ul("everything",!0)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.connector.on_mac_and"},{code:ul("everything",!1)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.3"},{code:"#"},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.4"},{code:"@"},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.5"},{code:","},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.6"},{code:">"},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.1.7"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.2.1"},{code:ul("chats",!0)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.connector.on_mac_and"},{code:ul("chats",!1)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.2.3"},{code:ul("commands",!0)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.connector.on_mac_and"},{code:ul("commands",!1)},{key:"ui.onboarding.tour.pre_command_palette_open_canvas.body.2.5"}],breaks:0}],canvas_open_button:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_open_button.body.1"}],breaks:0}],canvas_feature:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_feature.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_feature.body.2"}],breaks:0}],canvas_documents_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.2"}],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.3"}],breaks:1},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_documents_view.body.4"}],breaks:0}],canvas_files_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_files_view.body.1"}],breaks:0}],canvas_variables_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_variables_view.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.canvas_variables_view.body.2"}],breaks:0}],agent_options:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_options.body.1"}],breaks:0}],click_view_settings_from_chat:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.click_view_settings_from_chat.body.1"}],breaks:0}],view_agent_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.view_agent_settings.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.view_agent_settings.body.2"}],breaks:0}],select_provider:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.select_provider.body.1"}],breaks:0}],select_model:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.select_model.body.1"}],breaks:0}],modify_security_prompt:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.modify_security_prompt.body.1"}],breaks:0}],modify_agent_prompt:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.modify_agent_prompt.body.1"}],breaks:0}],create_new_agent:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_new_agent.body.1"}],breaks:0}],agent_naming_guidelines:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_naming_guidelines.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_naming_guidelines.body.2"}],breaks:0}],navigate_agent_hub:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.navigate_agent_hub.body.1"}],breaks:0}],agent_hub_view:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.agent_hub_view.body.1"}],breaks:0}],download_agent:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.download_agent.body.1"}],breaks:0}],upload_agent_hub:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.upload_agent_hub.body.1"}],breaks:0}],upload_agent_hub_dialog:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.upload_agent_hub_dialog.body.1"}],breaks:0}],navigate_schedules:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.navigate_schedules.body.1"}],breaks:0}],schedules_overview:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.schedules_overview.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.schedules_overview.body.2"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.schedules_overview.body.3"}],breaks:0}],create_schedule:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule.body.2"}],breaks:0}],create_schedule_dialog:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule_dialog.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule_dialog.body.2"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.create_schedule_dialog.body.3"}],breaks:0}],navigate_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.navigate_settings.body.1"}],breaks:0}],general_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.general_settings.body.1"}],breaks:0}],appearance_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.appearance_settings.body.1"}],breaks:0}],radient_account_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.radient_account_settings.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.radient_account_settings.body.2"}],breaks:0}],integrations_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.integrations_settings.body.1"}],breaks:2},{kind:"paragraph",runs:[{key:"ui.onboarding.tour.integrations_settings.body.2"}],breaks:0}],application_updates_settings:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.application_updates_settings.body.1"}],breaks:0}],tour_complete:[{kind:"paragraph",runs:[{key:"ui.onboarding.tour.tour_complete.body.1"}],breaks:0}]},Iit=e=>{const t=Array.from(document.querySelectorAll(`[data-tour-tag="${e}"]`));return t.find(n=>n.offsetParent!==null)??t[0]??null},R6=e=>{document.querySelector(`[data-tour-action="${e}"]`)?.click()},bY=1340,XD="tour-beside-palette",LC="pre-command-palette-open-canvas",xY='[data-tour-tag="command-palette-dialog"]',ds=e=>$5(Bm())!=="rtl"?e:e==="left"?"right":"left",Nit=e=>(e.getById(LC)?.options.classes??"").split(" ").includes(XD),_Y=(e,t)=>{const n=e.getById(LC);!n||Nit(e)===t||n.updateStepOptions(t?{attachTo:{element:xY,on:ds("right")},classes:XD}:{attachTo:void 0,classes:void 0})},wY=e=>{const t=window.innerWidth>=bY;return _Y(e,t),t};let QD=0;const JR=new WeakMap;nt.subscribe((e,t)=>{t.isCommandPaletteOpen&&!e.isCommandPaletteOpen&&(QD+=1)});const yY=e=>{const t=JR.get(e);return t===void 0||(JR.delete(e),t!==QD)?!1:(nt.getState().closeCommandPalette(),!0)},A6=(e,t)=>{if(!wY(e)){t();return}const n=nt.getState();n.isCommandPaletteOpen||(n.openCommandPalette(),JR.set(e,QD)),setTimeout(()=>{e.isActive()&&t()},500)},F6=(e,t)=>{if(!yY(e)){t();return}setTimeout(()=>{e.isActive()&&t()},500)},D6=e=>{const t=e?.step;if(t?.id!==LC)return;(!wY(t.tour)||document.querySelector(xY)===null)&&_Y(t.tour,!1)},Pit=()=>{const e=window.innerWidth>=bY;return{id:LC,...e?{attachTo:{element:'[data-tour-tag="command-palette-dialog"]',on:ds("right")},classes:XD}:{},title:at("ui.onboarding.tour.pre_command_palette_open_canvas.title"),text:vn(bn.pre_command_palette_open_canvas),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){F6(this,()=>this.back())}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){F6(this,()=>this.next())}}]}},CY=()=>[{id:"welcome",title:at("ui.onboarding.tour.welcome.title"),text:vn(bn.welcome),buttons:[{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"agent-list",attachTo:{element:'[data-tour-tag="agent-list-panel"]',on:ds("right")},title:at("ui.onboarding.tour.agent_list.title"),text:vn(bn.agent_list),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-agent",attachTo:{element:'[data-tour-tag="agent-list-item-button-0"]',on:ds("right")},title:at("ui.onboarding.tour.select_agent.title"),text:vn(bn.select_agent),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.chat_input.title"),text:vn(bn.chat_input),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.attachments.title"),text:vn(bn.attachments),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"agent-capabilities",attachTo:{element:'[data-tour-tag="chat-header"]',on:"top"},title:at("ui.onboarding.tour.agent_capabilities.title"),text:vn(bn.agent_capabilities),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){A6(this,()=>this.next())}}]},Pit(),{id:"canvas-open-button",attachTo:{element:'button[data-tour-tag="open-canvas-button"]',on:ds("left")},title:at("ui.onboarding.tour.canvas_open_button.title"),text:vn(bn.canvas_open_button),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){A6(this,()=>this.back())}},{text:at("ui.onboarding.tour.action.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:ds("left")},title:at("ui.onboarding.tour.canvas_feature.title"),text:vn(bn.canvas_feature),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.canvas_documents_view.title"),text:vn(bn.canvas_documents_view),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.canvas_files_view.title"),text:vn(bn.canvas_files_view),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.canvas_variables_view.title"),text:vn(bn.canvas_variables_view),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.agent_options.title"),text:vn(bn.agent_options),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.click_view_settings_from_chat.title"),text:vn(bn.click_view_settings_from_chat),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:ds("left")},title:at("ui.onboarding.tour.view_agent_settings.title"),text:vn(bn.view_agent_settings),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-provider",attachTo:{element:'[data-tour-tag="agent-settings-hosting-select"]',on:ds("left")},title:at("ui.onboarding.tour.select_provider.title"),text:vn(bn.select_provider),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"select-model",attachTo:{element:'[data-tour-tag="agent-settings-model-select"]',on:ds("left")},title:at("ui.onboarding.tour.select_model.title"),text:vn(bn.select_model),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"modify-security-prompt",attachTo:{element:'[data-tour-tag="agent-settings-security"]',on:ds("left")},title:at("ui.onboarding.tour.modify_security_prompt.title"),text:vn(bn.modify_security_prompt),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"modify-agent-prompt",attachTo:{element:'[data-tour-tag="agent-settings-system-prompt"]',on:ds("left")},title:at("ui.onboarding.tour.modify_agent_prompt.title"),text:vn(bn.modify_agent_prompt),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.create_new_agent.title"),text:vn(bn.create_new_agent),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.agent_naming_guidelines.title"),text:vn(bn.agent_naming_guidelines),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.navigate_agent_hub.title"),text:vn(bn.navigate_agent_hub),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.agent_hub_view.title"),text:vn(bn.agent_hub_view),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.download_agent.title"),text:vn(bn.download_agent),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:()=>Iit("upload-to-hub-header-button"),on:"bottom"},title:at("ui.onboarding.tour.upload_agent_hub.title"),text:vn(bn.upload_agent_hub),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){R6("open-upload-dialog"),setTimeout(()=>{this.next()},500)}}]},{id:"upload-agent-hub-dialog",attachTo:{element:'[data-tour-tag="upload-agent-dialog"]',on:ds("right")},title:at("ui.onboarding.tour.upload_agent_hub_dialog.title"),text:vn(bn.upload_agent_hub_dialog),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.navigate_schedules.title"),text:vn(bn.navigate_schedules),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){const e=document.querySelector('[data-tour-tag="nav-item-agents"]');e&&e.click(),setTimeout(()=>{R6("open-upload-dialog")},500),setTimeout(()=>{this.back()},1e3)}},{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.schedules_overview.title"),text:vn(bn.schedules_overview),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"create-schedule",attachTo:{element:'button[data-tour-tag="create-schedule-button"]',on:"bottom"},title:at("ui.onboarding.tour.create_schedule.title"),text:vn(bn.create_schedule),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.create_schedule_dialog.title"),text:vn(bn.create_schedule_dialog),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.navigate_settings.title"),text:vn(bn.navigate_settings),buttons:[{text:at("ui.onboarding.tour.action.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:at("ui.onboarding.tour.action.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:ds("right")},title:at("ui.onboarding.tour.general_settings.title"),text:vn(bn.general_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"appearance-settings",attachTo:{element:'[data-tour-tag="settings-appearance-section"]',on:ds("right")},title:at("ui.onboarding.tour.appearance_settings.title"),text:vn(bn.appearance_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"radient-account-settings",attachTo:{element:'[data-tour-tag="settings-radient-account-section"]',on:ds("right")},title:at("ui.onboarding.tour.radient_account_settings.title"),text:vn(bn.radient_account_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"integrations-settings",attachTo:{element:'[data-tour-tag="settings-integrations-section"]',on:ds("right")},title:at("ui.onboarding.tour.integrations_settings.title"),text:vn(bn.integrations_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"application-updates-settings",attachTo:{element:'[data-tour-tag="settings-app-updates-section"]',on:ds("right")},title:at("ui.onboarding.tour.application_updates_settings.title"),text:vn(bn.application_updates_settings),buttons:[{text:at("ui.onboarding.tour.action.back"),classes:"shepherd-button-secondary",action:function(){this.back()}},{text:at("ui.onboarding.tour.action.next"),classes:"shepherd-button-primary",action:function(){this.next()}}]},{id:"tour-complete",title:at("ui.onboarding.tour.tour_complete.title"),text:vn(bn.tour_complete),buttons:[{text:at("ui.onboarding.tour.action.finish"),classes:"shepherd-button-primary",action:function(){this.complete()}}]}],SY=()=>({enabled:!0,label:h("ui.onboarding.tour.action.close")}),ZR=new WeakMap,Mit=(e,t)=>{ZR.set(e,t)},Oit=(e,t)=>{if(ZR.get(e)===t)return;const n=new Map(CY().filter(r=>r.id).map(r=>[r.id,r])),s=SY();for(const r of e.steps){const i=r.id?n.get(r.id):void 0;i&&r.updateStepOptions({title:i.title,text:i.text,buttons:i.buttons,cancelIcon:s})}e.options.defaultStepOptions={...e.options.defaultStepOptions,cancelIcon:s},ZR.set(e,t)},I6=new WeakMap,Lit=e=>{const t=I6.get(e);if(t)return t;const n=()=>yY(e);return I6.set(e,n),n},Bit=()=>{const e=oi(),{completeTourOnboarding:t}=D0(),n=m.useContext(OC),s=Ve(),r={cancelIcon:SY(),scrollTo:{behavior:"smooth",block:"center"}},i=!0,a=o=>{if(n?.tour?.isActive()&&!o?.forceModalCompleted){console.log("Onboarding tour is already active (from context.tour). Not starting another.");return}const l=D0.getState();if(!o?.forceModalCompleted&&!l.isModalComplete){console.log("Onboarding modal not completed (checked via store). Tour will not start.");return}if(l.isTourComplete&&!o?.forceModalCompleted){console.log("Onboarding tour already completed in store and not forced. Not starting again.");return}let u=n?.tour;const d=n?.Shepherd;if(!u&&d&&(u=d.activeTour,!u&&d.Tour&&(console.log("No active Shepherd tour found from context or global. Creating a new one."),u=new d.Tour({useModalOverlay:i,defaultStepOptions:r}))),!u){console.warn("Failed to get or create a Shepherd tour instance.",n);return}if(u.isActive()){console.log("Tour is already active. Not starting again.");return}u.options.defaultStepOptions={...u.options.defaultStepOptions||{},...r},u.options.useModalOverlay=i,o?.firstAgentId&&(u.options.firstAgentId=o.firstAgentId),u.off("complete",t),u.on("complete",t),u.off("cancel",t),u.on("cancel",t);const f=Lit(u);u.off("complete",f),u.on("complete",f),u.off("cancel",f),u.on("cancel",f),u.off("show",D6),u.on("show",D6);const p=CY();if(o?.forceModalCompleted||!u.isActive()){const g=[...u.steps];for(const v of g)v.id&&u.removeStep(v.id);u.addSteps(p)}else u.steps.length===0&&u.addSteps(p);Mit(u,Bm()),typeof u.start=="function"?(e("/"),u.start()):console.warn("Shepherd tour instance does not have a start method.",u)};return m.useEffect(()=>{const o=n?.tour??n?.Shepherd?.activeTour;o?.isActive()&&Oit(o,s)},[s,n]),{startTour:a}},jit=()=>{const{isModalComplete:e,isTourComplete:t}=D0(),{startTour:n}=Bit(),s=it.useContext(OC),{data:r}=aT(1,1);return m.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},Hit=({children:e})=>c.jsxs(Eit,{children:[e,c.jsx(jit,{})]}),Uit=()=>{Ve();const{open:e,focusGroup:t,providerId:n,closeConnect:s}=B8(),r=m.useRef(null);m.useEffect(()=>{e&&(r.current=document.activeElement instanceof HTMLElement?document.activeElement:null)},[e]);const i=oi();return c.jsx(Tc,{open:e,onOpenChange:a=>{a||s()},children:c.jsxs(Rc,{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(wl,{className:"text-title",children:h("ui.providers.connect_provider_dialog.connect_a_model_provider")}),c.jsx(Zu,{className:"text-body-sm text-ink-muted",children:h("ui.providers.connect_provider_dialog.your_agents_need_a_model_to_think")})]}),e?c.jsx(XK,{context:"dialog",featuredOnly:!0,focusGroup:t,initialProviderId:n,onDone:s,onChangeModel:()=>{s(),i("/settings")}}):null]})})};function Git(){const{visible:e,rows:t,cursor:n,commitAt:s,hoverAt:r}=Eae();_u(e,"session-switcher");const i=n!==null&&e?t[n]??null:null,a=e&&t.length>=2;return c.jsxs(c.Fragment,{children:[c.jsx("output",{"aria-live":"polite",className:"sr-only","data-session-switcher-announcement":"",children:i!==null&&n!==null?c.jsxs(c.Fragment,{children:[kY(i),", ",n+1," / ",t.length]}):null}),a?jv.createPortal(c.jsx("div",{className:"pointer-events-none fixed inset-0 z-50 flex items-start justify-center pt-[18vh]",children:c.jsx("div",{role:"dialog","aria-modal":"false","aria-label":h("ui.command_palette.palette_search.recents"),className:"pointer-events-auto w-160 max-w-[90vw] rounded-lg border border-hairline bg-elevated p-2 shadow-overlay",children:t.map((o,l)=>c.jsx($it,{row:o,active:l===n,onCommit:()=>s(l),onHover:()=>r(l)},o.sessionId))})}),document.body):null]})}function kY(e){return e.title??h("ui.command_palette.palette_search.untitled_chat")}const Vit=1e3;function Wit(){let e=0;function t(){window.clearTimeout(e),window.removeEventListener("contextmenu",n,!0),window.removeEventListener("pointerup",t,!0)}function n(s){s.preventDefault(),s.stopPropagation(),t()}e=window.setTimeout(t,Vit),window.addEventListener("contextmenu",n,!0),window.addEventListener("pointerup",t,!0)}function $it({row:e,active:t,onCommit:n,onHover:s}){return c.jsxs("button",{type:"button",tabIndex:-1,"aria-current":t?"true":void 0,"data-session-id":e.sessionId,onPointerDown:r=>{r.button===0&&(r.preventDefault(),Wit(),n())},onMouseDown:r=>r.preventDefault(),onContextMenu:r=>r.preventDefault(),onMouseMove:s,className:R("flex h-9 w-full items-center gap-3 rounded-sm px-2 text-left",t?"bg-sunken outline-solid outline-1 -outline-offset-1 outline-control":"bg-transparent"),children:[e.row===null?c.jsx("span",{"aria-hidden":"true",className:"size-4 shrink-0"}):c.jsx(WR,{row:e.row}),c.jsx("span",{className:R("min-w-0 flex-1 truncate text-body-sm",e.title===null?"text-ink-muted":"text-ink"),children:kY(e)})]})}const EY=({title:e,description:t,icon:n,children:s,titleComponent:r,sectionRef:i,dataTourTag:a,className:o,id:l,searchSection:u,searchSectionLabel:d,searchIgnore:f})=>c.jsxs("div",{ref:i,id:l,"data-search-section":u,"data-search-section-label":d,"data-search-ignore":f,tabIndex:l?-1:void 0,"data-tour-tag":a,className:R("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})]}),Pdt=({label:e,value:t,className:n,valueClassName:s})=>c.jsxs("div",{className:R("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:R("mt-0.5 break-words text-body-sm",s??"text-ink"),children:t})]}),Mdt=({children:e,className:t})=>c.jsx("div",{className:R("grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-x-6 gap-y-4",t),children:e});function TY({id:e,rank:t,action:n,settingKey:s,help:r,hint:i,ariaLabel:a,value:o,fieldRef:l,saving:u,showReset:d,onReset:f,onKeyDown:p,onKeyUp:g,onBlur:v,notes:b,error:x,focusKey:_}){const w=m.useRef(!1);return m.useEffect(()=>{if(_!==s||w.current)return;const y=l.current;y&&(w.current=!0,y.scrollIntoView?.({block:"center"}),y.focus())},[_,s,l]),c.jsxs("div",{className:"group flex min-w-0 flex-col gap-1","data-speech-rank":t,"data-search-row":`keyboard.${s}`,"data-search-label":n,"data-search-terms":s,"data-search-control":!0,children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsxs("div",{className:"flex w-32 flex-col",children:[c.jsx(dr,{htmlFor:e,className:"text-body-sm text-ink",children:t==="primary"?h("ui.settings.shortcuts.speech.primary"):h("ui.settings.shortcuts.speech.secondary")}),c.jsx("span",{className:"text-meta text-ink-muted",children:n})]}),c.jsx(bs,{ref:l,id:e,"aria-label":a,"aria-describedby":`${e}-hint ${e}-notes ${e}-status`,"aria-invalid":x?!0:void 0,"aria-busy":u,"data-shortcut-action":s,className:"w-52 text-left font-mono text-body-sm",value:o,readOnly:!0,onKeyDown:p,onKeyUp:g,onBlur:v}),d&&c.jsx(ce,{variant:"secondary",size:"sm",disabled:u,"aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.reset_label_to_its_default",{label:n}),onClick:f,children:h("ui.settings.shortcuts.keyboard_shortcuts_section.reset")})]}),c.jsxs("div",{className:"ml-0 max-w-88 text-meta text-ink-muted sm:ml-34",children:[c.jsx("p",{children:r}),c.jsx("p",{id:`${e}-hint`,className:"hidden group-focus-within:block",children:i}),c.jsx("div",{id:`${e}-notes`,children:b}),c.jsx("output",{id:`${e}-status`,className:"block","aria-live":"polite",children:u?h("ui.settings.configuration.backend_setting_row.saving"):x?c.jsx("span",{className:"text-danger",children:x}):null})]})]})}function RY({settingKey:e,refetch:t,fieldRef:n,onPending:s,onSaved:r}){const[i,a]=m.useState(!1),[o,l]=m.useState(null),[u,d]=m.useState(!1);return m.useEffect(()=>{!u||i||(n.current?.focus(),d(!1))},[u,i,n]),{saving:i,error:o,setError:l,write:async(p,g)=>{if(!(e===void 0||i||p==="settings.edit"&&g===void 0)){a(!0),l(null),s?.(g);try{await rt(p==="settings.edit"?{op:p,key:e,value:g??""}:{op:p,key:e}),r?.(p,g),await t()}catch(v){let b;if(v instanceof Fi){const x=v.detail;typeof x=="object"&&x!==null&&"code"in x&&x.code==="keymap.conflict"&&"label"in x&&typeof x.label=="string"&&(b=h("ui.settings.shortcuts.capture.already_assigned",{label:x.label}))}l(b??(v instanceof Error?v.message:h(p==="settings.edit"?"ui.settings.configuration.backend_settings_section.the_setting_could_not_be_saved":"ui.settings.configuration.backend_settings_section.the_setting_could_not_be_reset")))}finally{s?.(),a(!1),d(!0)}}}}}function AY(e,t,n,s=[]){const r=/^(Alt|Meta|Control)/.exec(e)?.[1],i=o=>r==="Control"?o.includes("ctrl")||o.includes("primary"):r==="Meta"?o.includes("meta")||t==="darwin"&&o.includes("primary"):r==="Alt"&&o.includes("alt"),a=o=>o.split("+").slice(0,-1);return s.find(o=>i(a(o)))??n.find(o=>i(a(o)))??null}function zit(e,t,n){const s=e.split("+"),r=s.at(-1)??"",i=o=>o==="primary"?t==="Control"||t==="Command"?t:n==="darwin"?"Command":"Control":o==="ctrl"?"Control":o==="shift"?"Shift":o==="alt"?n==="darwin"?"Option":"Alt":o==="meta"?n==="darwin"?"Command":n==="win32"?"Windows":"Super":o,a=r.length===1?r.toUpperCase():r.charAt(0).toUpperCase()+r.slice(1);return[...s.slice(0,-1).map(i),a].join("+")}function qit(e,t,n,s){for(const r of["AltRight","ControlRight","MetaRight"]){const i=W8(r,t);if(i===null)continue;const a=Dd(i);if(!(!a||a.code===e)&&!AY(r,t,n,s))return a.label}return null}const Kit=/^(Alt|Meta|Control|Shift)(Left|Right)$/,$k=e=>e.split("-").slice(1).join("-");function Yit({setting:e,refetch:t,focusKey:n}){const s=WA(),r=nt(F=>F.shortcutBindings),i=m.useRef(null),a=m.useId(),o=m.useMemo(()=>fie(),[]),l=m.useRef(null),u=typeof e.default=="string"?e.default:UN,{saving:d,error:f,setError:p,write:g}=RY({settingKey:e.key,refetch:t,fieldRef:i,onSaved:(F,A)=>pie(F==="settings.edit"?A:u)}),v=h("ui.settings.shortcuts.speech.push_to_talk_hold"),b=typeof e.value=="string"?e.value:"",x=Dd(b)??Dd(u)??Dd(UN),_=Dd(b)?.code===Dd(u)?.code,w=gy.flatMap(F=>{const A=mA(F.id,r);return A?[A]:[]}),y=s.canonical?[s.canonical]:[],S=x===null?null:AY(x.code,o,w,y),C=S===null||x===null?null:qit(x.code,o,w,y),E=h("ui.settings.shortcuts.speech.push_to_talk_letter_pointer"),k=()=>p(h("ui.settings.shortcuts.speech.push_to_talk_refused",{platform:o}));return c.jsx(TY,{id:a,rank:"secondary",action:v,settingKey:e.key,focusKey:n,help:e.help,hint:`${h("ui.settings.shortcuts.speech.push_to_talk_hint")} ${E}`,ariaLabel:h("ui.settings.configuration.setting_control.label_press_the_key_you_want",{label:v}),value:x?.label??"",fieldRef:i,saving:d,showReset:!_,onReset:()=>void g("settings.reset"),onBlur:()=>{l.current=null,p(null)},onKeyDown:F=>{if(d)return;if(F.repeat||F.nativeEvent.isComposing){xE.has(F.key)||F.preventDefault();return}const A=l.current!==null;if(l.current&&(l.current.tainted=!0),xE.has(F.key)){A&&k();return}if(N_.has(F.key)){l.current=null,p(null),F.preventDefault();return}if(F.preventDefault(),A||!Kit.test(F.code)){A||(l.current=null),k();return}p(null),l.current={code:F.code,tainted:!1}},onKeyUp:F=>{const A=l.current;if(!A||F.code!==A.code||(l.current=null,A.tainted||d))return;const I=W8(A.code,o);if(I===null){k();return}Dd(I)?.code!==x?.code&&g("settings.edit",I)},notes:S!==null&&x!==null&&c.jsx("p",{children:h("ui.settings.shortcuts.speech.push_to_talk_overlap",{modifier:$k(x.label),example:zit(S,$k(x.label),o),alternative:C?$k(C):"none"})}),error:f})}function Xit({setting:e,refetch:t,focusKey:n}){const s=m.useRef(!1),r=WA(),i=m.useRef(null),a=m.useId(),o=m.useMemo(()=>ag(),[]),{saving:l,error:u,setError:d,write:f}=RY({settingKey:e.key,refetch:t,fieldRef:i,onPending:S=>window.api?.recordingShortcut?.markPending(S)}),p=h("ui.settings.shortcuts.speech.start_recording_press"),g=typeof e.value=="string"?e.value:r.value,v=r.problem?r.value:g,b=typeof e.default=="string"?e.default:gie,x=Pb(g)===Pb(b),_=S=>h("ui.settings.shortcuts.capture.already_assigned",{label:S}),w=h("ui.chat.composer.start_recording"),y=h("ui.settings.shortcuts.keyboard_shortcuts_section.press_the_keys_you_want_esc_cancels");return c.jsx(TY,{id:a,rank:"primary",action:p,settingKey:e.key,focusKey:n,help:e.help,hint:y,ariaLabel:h("ui.settings.shortcuts.keyboard_shortcuts_section.label_press_the_keys_you_want",{label:p}),value:S5(v,o),fieldRef:i,saving:l,showReset:!x,onReset:()=>void f("settings.reset"),onKeyUp:S=>{!xm.has(S.key)||!s.current||(s.current=!1,d(h("ui.settings.shortcuts.speech.start_recording_needs_key")))},onBlur:()=>{s.current=!1},onKeyDown:S=>{if(l)return;if(S.repeat&&xm.has(S.key)){S.preventDefault();return}if(s.current=xm.has(S.key),N_.has(S.key)||xm.has(S.key)){N_.has(S.key)&&d(null),S.preventDefault();return}const C=$A(S);if(C===null)return;if(S.preventDefault(),Pb(C)===Pb(g)){d(null);return}const E=nt.getState().shortcutBindings,k=$8(r,_(w));for(const A of gy){const I=E[A.id]??A.defaultChord;I&&k.set(I,A.label)}const F=k5(C,"panel.console",{},o,k);if(F!==null){d(F);return}f("settings.edit",C)},notes:c.jsxs(c.Fragment,{children:[r.shadowedBy&&!u&&c.jsx("output",{className:"block text-danger",children:h("ui.settings.shortcuts.recording.inactive_claimed",{label:r.shadowedBy})}),r.problem&&!u&&c.jsx("output",{className:"block text-danger",children:h("ui.settings.shortcuts.recording.invalid_stored_value")})]}),error:u})}function Qit({focusKey:e}){const{client:t,provided:n}=nZ(),s=Dn({queryKey:No.settings,queryFn:()=>rt({op:"settings.list"}),enabled:n,staleTime:1e4},t),r=l=>s.data?.settings.find(u=>u.key===l),i=r(mie),a=r(vie);if(!n)return null;const o=c.jsx("h3",{className:"pt-1 text-body-sm font-medium text-ink",children:h("ui.settings.shortcuts.category.speech_to_text")});return!i&&!a?s.isPending?c.jsx("div",{className:"min-h-24 space-y-3","aria-busy":"true",children:o}):null:c.jsxs("div",{className:"space-y-3","data-shortcut-recording":!0,children:[o,i&&c.jsx(Xit,{setting:i,refetch:s.refetch,focusKey:e}),a&&c.jsx(Yit,{setting:a,refetch:s.refetch,focusKey:e})]})}const FY=e=>{switch(e.id){case"panel.console":return h("ui.settings.shortcuts.row.console");case"panel.canvas":return h("ui.settings.shortcuts.row.canvas");case"panel.run":return h("ui.settings.shortcuts.row.execution");case"panel.ask":return h("ui.settings.shortcuts.row.asks");case"panel.browser":return h("ui.settings.shortcuts.row.browser");case"panel.code":return h("ui.settings.shortcuts.row.code_review")}},Jit=()=>h("ui.chat.composer.start_recording");function Zit(){m.useEffect(()=>{let e=0;const t=()=>{const r=nt.getState().shortcutBindings,i=new Map(sZ);for(const a of gy){const o=mA(a.id,r);if(!o)continue;const l=FY(a);for(const u of bie(o,ag()))i.set(u,l)}window.api?.recordingShortcut?.syncClaims(++e,[...i].map(([a,o])=>({chord:a,label:o})))};t();const n=nt.subscribe((r,i)=>{r.shortcutBindings!==i.shortcutBindings&&t()}),s=$X(t);return()=>{n(),s()}},[])}const eat=({action:e})=>{const t=WA(),n=$8(t,Jit());Ve();const s=m.useId(),r=m.useRef(null),i=nt(x=>x.shortcutBindings),a=i[e.id],o=nt(x=>x.setShortcutBinding),l=nt(x=>x.clearShortcutBinding),[u,d]=m.useState(!1),[f,p]=m.useState(null),g=m.useMemo(ag,[]),v=mA(e.id,i),b=FY(e);return c.jsxs("div",{"data-search-row":`keyboard.${e.id}`,"data-search-control":!0,className:"flex flex-col gap-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx(dr,{htmlFor:s,className:"w-32 text-body-sm text-ink",children:b}),c.jsx(bs,{id:s,readOnly:!0,value:v===null?h("ui.settings.shortcuts.keyboard_shortcuts_section.no_shortcut"):S5(v,g),"aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.label_press_the_keys_you_want",{label:String(b)}),"data-shortcut-action":e.id,ref:r,className:R("w-52",v===null?"text-body-sm":"font-mono text-body-sm"),onFocus:()=>d(!0),onBlur:()=>{d(!1),p(null)},onKeyDown:x=>{if(xE.has(x.key))return;if(N_.has(x.key)){d(!1),p(null);return}if(xm.has(x.key)||x.nativeEvent.isComposing)return;const _=$A({key:x.key,code:x.code,metaKey:x.metaKey,ctrlKey:x.ctrlKey,altKey:x.altKey,shiftKey:x.shiftKey}),w=k5(_,e.id,i,g,n);if(w!==null){x.preventDefault(),d(!0),p(w);return}if(_===v){d(!0),p(null);return}x.preventDefault(),d(!0),p(null),_===e.defaultChord?o(e.id,null,n):_!==null&&o(e.id,_,n)}}),v!==null&&c.jsx(ce,{variant:"secondary",size:"sm","aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.clear_label_s_shortcut",{label:String(b)}),onClick:()=>{l(e.id),r.current?.focus()},children:h("ui.settings.shortcuts.keyboard_shortcuts_section.clear")}),a!==void 0&&c.jsx(ce,{variant:"secondary",size:"sm","aria-label":h("ui.settings.shortcuts.keyboard_shortcuts_section.reset_label_to_its_default",{label:String(b)}),onClick:()=>{o(e.id,null,n),r.current?.focus()},children:h("ui.settings.shortcuts.keyboard_shortcuts_section.reset")})]}),u&&c.jsx("span",{className:"text-meta text-ink-dim",children:h("ui.settings.shortcuts.keyboard_shortcuts_section.press_the_keys_you_want_esc_cancels")}),f!==null&&c.jsx("output",{className:"text-meta text-danger",children:f})]})},Odt=({sectionRef:e,focusKey:t})=>(Ve(),c.jsx(EY,{title:h("ui.settings.shortcuts.keyboard_shortcuts_section.keyboard_shortcuts"),icon:vU,description:h("ui.settings.shortcuts.keyboard_shortcuts_section.shortcut_capture_description"),sectionRef:e,searchSection:"keyboard",searchSectionLabel:h("ui.settings.navigation.settings_sidebar.keyboard_shortcuts"),children:c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsx("p",{"data-shortcut-note":"browser-scope",className:"max-w-2xl text-body-sm text-ink-muted",children:h("ui.settings.shortcuts.keyboard_shortcuts_section.browser_shortcuts_answer_only_while_the_browser_has_focus")}),c.jsx(Qit,{focusKey:t}),c.jsx("h3",{className:"pt-1 text-body-sm font-medium text-ink",children:h("ui.settings.shortcuts.category.panels")}),c.jsx("div",{className:"flex flex-col gap-4",children:gy.map(n=>c.jsx(eat,{action:n},n.id))})]})}));async function tat(e){await rt({op:"settings.edit",key:hl,value:e.value}),wie(e.queryClient)}async function DY(e){await tat(e),e.queryClient.setQueryData(P_.all,t=>t&&{...t,settings:t.settings.map(n=>n.key===hl?{...n,value:e.value,is_default:e.value===n.default}:n)});try{return await e.queryClient.fetchQuery({queryKey:P_.all,queryFn:()=>rt({op:"settings.list"}),staleTime:0,retry:!1}),"confirmed"}catch{return"readback-unknown"}}const Ldt=({focus:e=!1,focusNonce:t})=>{Ve();const n=Mt(),s=ss(),r=Et(s.data,"settings"),i=Dn({queryKey:P_.all,queryFn:()=>rt({op:"settings.list"}),enabled:r,retry:!1,refetchOnReconnect:!0}),a=i.data?.settings.find(I=>I.key===hl),[o,l]=m.useState(!1),[u,d]=m.useState(null),[f,p]=m.useState(!1),[g,v]=m.useState(!1),b=m.useRef(!1),x=m.useRef(null),_=m.useRef(!1),w=m.useRef(t);m.useEffect(()=>{t!==w.current&&(w.current=t,_.current=!1)},[t]),m.useEffect(()=>{if(!e){_.current=!1;return}!a||_.current||(x.current?.querySelector("[role=combobox]")?.focus(),_.current=!0)},[e,t,a]),m.useEffect(()=>{i.isSuccess&&!i.isFetching&&p(!1)},[i.isFetching,i.isSuccess]);const y=async I=>{if(!(!a||b.current||f||!a.choices.some(N=>N.value===I))){b.current=!0,l(!0),d(null),v(!1);try{const N=await DY({value:I,queryClient:n});p(N==="readback-unknown"),v(N==="confirmed")}catch(N){d({value:I,message:N instanceof Error?N.message:""})}finally{b.current=!1,l(!1)}}},S=async()=>{const[I,N]=await Promise.all([i.refetch(),s.refetch()]);!I.isError&&!N.isError&&p(!1)},C=!i.data&&i.error||!s.data&&s.error,E=s.data&&(!r||i.data&&!a),k=!C&&!E&&!a,F=s.data?.features?.i18n?s.data.language:void 0,A=typeof F=="string"&&F!==""?F:void 0;return c.jsx(EY,{title:h("ui.settings.language.dialog.title"),icon:bU,description:h("ui.settings.language.general.description"),children:c.jsxs("div",{ref:x,"data-setting-key":hl,"data-search-row":"general.language","data-search-control":!0,className:"flex flex-col gap-3","aria-busy":o,children:[k&&c.jsx("output",{className:"text-meta text-ink-dim",children:h("ui.settings.language.dialog.loading")}),E&&c.jsx("p",{className:"text-meta text-ink-dim",children:h("ui.settings.language.dialog.unavailable")}),a&&c.jsx(z8,{setting:{...GA(a),label:h("ui.settings.language.dialog.title")},value:String(a.value),onValueChange:I=>{y(I)},disabled:o||f,suppressEffectiveNote:!0}),c.jsx("output",{id:xie(hl),"aria-live":"polite",className:"text-meta text-ink-dim",children:o?h("ui.settings.language.general.pending"):g?h("ui.settings.language.general.saved"):A?h(f||s.error?"ui.settings.language.general.last_known":"ui.settings.language.general.effective",{locale:_ie(A)?.name??A}):h("ui.settings.language.general.no_resolution")}),(C||u||f)&&c.jsx(Rr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:u?h("ui.settings.language.general.write_error",{message:u.message}):f?h("ui.settings.language.general.readback_error"):h("ui.settings.language.dialog.unavailable")}),c.jsx(ce,{variant:"outline",size:"sm",disabled:o||i.isFetching||s.isFetching,onClick:()=>{u?y(u.value):S()},children:h("ui.settings.language.dialog.retry")})]})})]})})},nat=()=>{Ve();const e=g_(O=>O.open),t=g_(O=>O.closeLanguage),n=Mt(),s=ss(),r=Et(s.data,"settings"),i=Dn({queryKey:P_.all,queryFn:()=>rt({op:"settings.list"}),enabled:e&&r,staleTime:1e4}),a=m.useRef(null),o=F8(),l=(i.data?.settings??[]).find(O=>O.key===hl),u=l?GA(l):void 0,[d,f]=m.useState(!1),[p,g]=m.useState(!1),[v,b]=m.useState(null),[x,_]=m.useState(!1),w=m.useRef(!1);m.useEffect(()=>{e&&(g(!1),b(null))},[e]);const y=String(u?.value??""),S=async O=>{if(!(!u||w.current||x||!u.choices.some(X=>X.value===O))){w.current=!0,f(!0),b(null),g(!1);try{const X=await DY({value:O,queryClient:n});_(X==="readback-unknown"),g(X==="confirmed")}catch(X){const Q=X instanceof Error?X.message:"";b({value:O,message:Q}),g_.getState().open||nn(h("ui.settings.language.general.write_error",{message:Q}))}finally{w.current=!1,f(!1)}}},C=async()=>{const[O,X]=await Promise.all([i.refetch(),s.refetch()]);!O.isError&&!X.isError&&_(!1)},E=!!s.data,k=E&&!r,F=s.error&&!s.data?s.error:null,A=F??(i.data?null:i.error),I=!E&&!A,{sentence:N,remedy:P}=rZ(o??null,h("ui.settings.configuration.language_dialog.your_settings_could_not_be_loaded"),A),M=s.isFetching||i.isFetching,Y=u?"combo":A?"retry":"none";return m.useEffect(()=>{!e||Y==="none"||requestAnimationFrame(()=>{a.current?.querySelector(Y==="combo"?'[role="combobox"]':"[data-language-retry]")?.focus()})},[e,Y]),c.jsx(Tc,{open:e,onOpenChange:O=>!O&&t(),children:c.jsxs(Rc,{ref:a,onOpenAutoFocus:O=>O.preventDefault(),className:"max-w-[min(28rem,calc(100vw-4rem))] gap-4",children:[c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx(wl,{className:"text-title",children:h("ui.settings.language.dialog.title")}),c.jsx(Zu,{className:"text-body-sm text-ink-muted",children:h("ui.settings.language.dialog.description")})]}),I?c.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-ink-muted",children:[c.jsx(On,{}),h("ui.settings.language.dialog.loading")]}):k?c.jsx(Rr,{variant:"warning",children:c.jsx("span",{children:h("ui.settings.language.dialog.unavailable")})}):A?c.jsx(Rr,{variant:"warning",children:c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx("span",{children:N}),P&&c.jsx(ce,{variant:"secondary",size:"sm",className:"shrink-0","data-language-retry":"",onClick:()=>{F?s.refetch():i.refetch()},disabled:M,children:M?h("ui.settings.language.dialog.retrying"):h("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(On,{}),h("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:GN(hl),className:"text-meta text-ink-dim",children:u.help}),c.jsx(z8,{setting:u,value:y,disabled:d||x,helpId:GN(hl),effectiveNoteId:yie(hl,Cie),onValueChange:O=>{S(O)}})]}),v&&c.jsx(Rr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:h("ui.settings.language.general.write_error",{message:v.message})}),c.jsx(ce,{variant:"outline",size:"sm",disabled:d||i.isFetching,onClick:()=>{S(v.value)},children:h("ui.settings.language.dialog.retry")})]})}),x&&c.jsx(Rr,{variant:"danger",children:c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("p",{role:"alert",children:h("ui.settings.language.general.readback_error")}),c.jsx(ce,{variant:"outline",size:"sm",disabled:d||i.isFetching||s.isFetching,onClick:()=>{C()},children:h("ui.settings.language.dialog.retry")})]})}),c.jsx("div",{className:"flex min-h-8 items-center justify-end",children:d?c.jsx("output",{"aria-live":"polite",className:"text-body-sm text-ink-muted",children:h("ui.settings.language.general.pending")}):p?c.jsxs("output",{"data-language-status":"","aria-live":"polite",className:"inline-flex items-center gap-1.5 text-body-sm text-ink",children:[c.jsx(Js,{"aria-hidden":"true",className:"size-3.5"}),h("ui.settings.language.dialog.saved")]}):null})]}):c.jsx(Rr,{variant:"warning",children:c.jsx("span",{children:h("ui.settings.language.dialog.unavailable")})})]})})},Iv=320,sat=360,rat=320,iat=/^[A-Za-z0-9_.:-]{1,128}$/,aat=/^[0-9a-f]{16}$/;function IY(e){const t=e.codePointAt(0)??0;return e==="<"||e===">"||t<32||t>=127&&t<=159||t===1564||t===8206||t===8207||t>=8234&&t<=8238||t>=8294&&t<=8297||t===8232||t===8233}function oat(e){return Array.from(e).some(IY)}const lat=/\s+/g,cat=new Intl.Segmenter(void 0,{granularity:"grapheme"});function NY(e,t,n="points"){let s=0,r="";for(const{segment:i}of cat.segment(e)){const a=n==="points"?Array.from(i).length:i.length;if(s+a>t)return`${r.trimEnd()}…`;r+=i,s+=a}return r}function Ap(e,t){let n="";for(const r of e)r==="<"?n+="‹":r===">"?n+="›":n+=IY(r)?" ":r;const s=n.replace(lat," ").trim();return s.length<=t?s:NY(s,Math.max(0,t-1),"units")}function uat(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(t.v!==1||t.kind!=="person"&&t.kind!=="person_agent")return;const n=dat(t.account_id),s=N6(t.display_name,Iv),r=N6(t.agent_name,Iv);if(!n||!s||t.kind==="person_agent"&&!r)return;const i=t.avatar,a=i&&typeof i=="object"&&i.account_id===n&&typeof i.hash=="string"&&aat.test(i.hash)?{account_id:n,hash:i.hash}:void 0;return{v:1,kind:t.kind,account_id:n,display_name:s,...t.kind==="person_agent"?{agent_name:r}:{},...a?{avatar:a}:{}}}function dat(e){return typeof e=="string"&&iat.test(e)?e:null}function N6(e,t){if(typeof e!="string")return null;const n=e.trim();return n.length===0||n.length>t||oat(e)?null:n}const Bdt=!0,jdt=!0;function hat(e){return`/team-bridge?${new URLSearchParams({tenant:e.tenantId,conversation:e.conversationId,...e.threadId?{thread:e.threadId}:{},...e.messageId?{message:e.messageId}:{}}).toString()}`}function P6(e){return JSON.stringify([sp(e),qA(e)])}function fat(e,t){const n=Mt(),s=m.useCallback(u=>zA(n,u),[n]),r=m.useCallback(()=>P6(n),[n]),i=m.useSyncExternalStore(s,r,r),a={...$r(n),token:i},[o,l]=m.useState(null);m.useEffect(()=>{let u=!0;const d=window.api?.desktop?.teamBridge,f=()=>{d?.pendingOpen?.().then(g=>{u&&g&&l(g)}).catch(()=>{})},p=d?.onOpen?.(f);return f(),()=>{u=!1,p?.()}},[]),m.useEffect(()=>{if(!o||qA(n)||a.token!==P6(n))return;const u=$r(n).accountId;if("unavailable"in o||!o.owner?.accountId||o.owner.accountId!==u){da(h("ui.teamBridge.notify.unavailable")),l(null);return}!e||a.accountId!==u||(t(hat(o)),l(null))},[o,e,t,n,a.accountId,a.token])}const ur=je.string().min(1).max(128),PY="team_bridge_owner_guard_unavailable",pat=je.object({account_id:ur,kind:je.enum(["human","agent"]),display_label:je.string().min(1).max(64),role:je.enum(["owner","member"]),state:je.enum(["invited","active","left","removed"]),joined_seq:je.number().int().nonnegative().optional()}).passthrough(),MY=je.enum(["all","mention","mute"]),pu=je.object({id:ur,tenant_id:ur,kind:je.enum(["dm","group","channel"]),name:je.string().optional(),topic:je.string().optional(),visibility:je.enum(["private","tenant"]),agent_capable:je.boolean(),status:je.enum(["open","archived"]),created_by:ur,last_message_at:je.string(),latest_seq:je.number().int().nonnegative(),members:je.array(pat),last_read_seq:je.number().int().nonnegative(),unread_count:je.number().int().nonnegative(),muted:je.boolean(),discoverable:je.boolean().optional(),member:je.boolean().optional(),member_count:je.number().int().nonnegative().optional(),notify:MY.optional(),last_sender_label:je.string().min(1).max(64).optional(),last_thread_root_id:ur.optional(),builtin:je.string().min(1).max(32).optional(),can_administer:je.boolean().optional(),archived_at:je.string().optional(),archived_by:ur.optional(),archived_by_label:je.string().min(1).max(64).optional()}).passthrough(),gat=je.object({conversations:je.array(pu),has_more:je.boolean().optional(),next_before:je.string().optional(),next_cursor:je.string().optional()}).passthrough(),OY=je.object({emoji:je.string().min(1),count:je.number().int().positive(),reacted_by_me:je.boolean(),sample_labels:je.array(je.string()).max(3)}).passthrough(),mat=je.object({message_id:ur,reactions:je.array(OY).max(50)}).passthrough(),vat=OY.extend({sample_labels:je.array(je.string()).transform(e=>e.slice(0,3))}),bat=je.array(vat).transform(e=>e.slice(0,50)),LY=je.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),JD=je.object({id:LY,mime:je.string().max(64),size:je.number().int().nonnegative(),width:je.number().int().nonnegative(),height:je.number().int().nonnegative(),sha256:je.string().max(128).optional(),state:je.string().max(32).optional(),expires_at:je.string().optional()}).passthrough(),xat=je.object({attachment:JD}).passthrough(),Hdt=je.object({enabled:je.boolean(),max_count:je.number().int().positive().max(16),max_bytes:je.number().int().positive(),max_pixels:je.number().int().positive().optional(),mime_types:je.array(je.string())}).passthrough(),eA=je.object({id:ur,conversation_id:ur,seq:je.number().int().nonnegative(),sender:je.object({account_id:ur,kind:je.enum(["human","agent"]),display_label:je.string().min(1).max(64)}).passthrough(),body:je.string().nullable(),body_hash:je.string().optional(),origin:je.enum(["human","agent","system"]),agent_label:je.string().optional(),created_at:je.string(),reactions:bat.optional(),thread_root_id:ur.optional(),reply_count:je.number().int().nonnegative().optional(),last_reply_at:je.string().optional(),reply_participants:je.array(je.string()).optional(),attachments:je.array(JD).max(16).optional()}).passthrough(),_at=je.object({root:eA,replies:je.array(eA),next_after_seq:je.number().int().nonnegative().optional(),has_more:je.boolean().optional()}).passthrough(),wat=["invited","joined","left","removed","consented","declined","withdrawn"],yat=["owner_invite","dm_receive_policy"];function Cat(e){return wat.includes(e)?e:null}function Sat(e){return e!==void 0&&yat.includes(e)?e:null}const M6=je.object({kind:je.enum(["human","agent"]),account_id:je.string(),endpoint_id:je.string().optional(),display_label:je.string().max(64).catch("")}).passthrough(),kat=je.object({id:ur,event_seq:je.number().int().nonnegative(),kind:je.string(),implicit:je.boolean().optional(),implicit_reason:je.string().optional(),actor:M6,targets:je.array(M6),request_id:je.string().optional(),after_seq:je.number().int().nonnegative(),at:je.string()}).passthrough(),Eat=je.array(je.unknown()).transform(e=>e.flatMap(t=>{const n=kat.safeParse(t);return n.success?[n.data]:[]})),Tat=je.object({messages:je.array(eA),next_before_seq:je.number().int().nonnegative().optional(),has_more:je.boolean().optional(),events:Eat.optional().catch(void 0),events_truncated:je.boolean().optional()}).passthrough(),Rat=je.object({tenant_id:ur,tenant_name:je.string(),unread:je.number().int().nonnegative(),eligible:je.boolean()}).passthrough(),Aat=je.object({total:je.number().int().nonnegative(),conversations:je.array(je.object({conversation_id:ur,unread_count:je.number().int().nonnegative(),last_read_seq:je.number().int().nonnegative(),latest_seq:je.number().int().nonnegative(),muted:je.boolean()}).passthrough()).optional(),organizations:je.array(Rat).optional()}).passthrough(),BY=je.enum(["active","paused","disabled","none"]),jY=je.object({endpoint_id:ur,name:je.string().max(128),state:je.string().min(1).max(32)}).passthrough(),tA=je.object({display_name:je.string().refine(e=>Array.from(e).length<=64).catch(""),title:je.string().refine(e=>Array.from(e).length<=80).catch(""),description:je.string().refine(e=>Array.from(e).length<=500).catch(""),pronouns:je.string().refine(e=>Array.from(e).length<=32).catch(""),timezone:je.string().refine(e=>Array.from(e).length<=64).catch(""),avatar:je.object({source:je.enum(["uploaded","google","microsoft","none"]),hash:je.string().regex(/^[0-9a-f]{16}$/),updated_at:je.string()}).passthrough().optional().catch(void 0)}).passthrough(),nA=je.string().max(512).regex(/^\/v1\/accounts\/(?:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|acc_[a-zA-Z0-9_-]{1,64})\/avatar\?v=[0-9a-f]{16}$/).optional().catch(void 0),Fat=je.object({account_id:ur,display_label:je.string(),role:je.string().min(1).max(32),bridge_enabled:je.boolean(),bridge_state:BY,agent:jY.optional().catch(void 0),profile:tA.optional().catch(void 0),avatar_url:nA}).passthrough();function Dat(e){if(e===null||typeof e!="object")return null;const t=e,n=t.account_id;if(typeof n!="string"||n.length===0)return null;const s=typeof t.display_label=="string"?t.display_label:"",r=typeof t.role=="string"&&t.role.length>0?t.role:"member",i=t.bridge_enabled===!0,a=BY.safeParse(t.bridge_state),o=jY.safeParse(t.agent);return{account_id:n,display_label:s,role:r,bridge_enabled:i,bridge_state:a.success?a.data:"none",...o.success?{agent:o.data}:{},profile:tA.safeParse(t.profile).success?tA.parse(t.profile):void 0,avatar_url:nA.safeParse(t.avatar_url).success?nA.parse(t.avatar_url):void 0}}const Iat=je.object({members:je.array(je.unknown())}).passthrough().transform(e=>{const t=[];let n=0;for(const s of e.members){const r=Fat.safeParse(s);if(r.success){t.push(r.data);continue}const i=Dat(s);i?t.push(i):n+=1}return{...e,members:t,unavailable_count:n}}),Nat=je.object({account_id:je.string().min(1).nullable().optional()}).passthrough(),O6=je.object({conversation_id:ur,last_read_seq:je.number().int().nonnegative(),unread_count:je.number().int().nonnegative(),muted:je.boolean(),notify:MY.optional()}).passthrough(),sA=je.object({id:ur,tenant_id:ur,conversation_id:ur,body:je.string(),send_at:je.string().datetime({offset:!0}),status:je.enum(["scheduled","sending"]),created_at:je.string().datetime({offset:!0}),version:je.number().int().nonnegative().nullish(),attachments:je.array(JD).max(16).optional(),attachment_ids:je.array(LY).max(16).optional()}).transform(({attachment_ids:e,...t})=>t.attachments!==void 0||!e?.length?t:{...t,attachments:e.map(n=>({id:n,mime:"",size:0,width:0,height:0,state:"reserved"}))}),Pat=je.object({scheduled:je.array(sA)});class zk extends Error{status;code;constructor(t,n){super("team bridge attachment request failed"),this.name="TeamBridgeAttachmentError",this.status=t,this.code=n}}async function Fa(e,t){if(!e||!t)throw new Error("Team Bridge write owner and tenant required");if(((await rt({op:"capabilities"})).features?.team_bridge_conversation_owner_guard??0)<1)throw Object.assign(new Error("Team Bridge runtime owner guard unavailable"),{code:PY});return{expected_account_id:e,tenant_id:t}}function Mat(e){if(!e)throw new Error("Team Bridge write account required");return e}const _s={async scheduledList(e){return Pat.parse(await rt({op:"team_bridge.scheduled.list",tenant_id:e}))},async scheduledCreate(e){return sA.parse(await rt({op:"team_bridge.scheduled.create",...e}))},async scheduledUpdate(e,t,n){return sA.parse(await rt({op:"team_bridge.scheduled.update",tenant_id:e,scheduled_id:t,...n}))},async scheduledCancel(e,t){return rt({op:"team_bridge.scheduled.cancel",tenant_id:e,scheduled_id:t})},async react(e,t,n,s,r,i){const a=await rt({op:"team_bridge.reactions.toggle",conversation_id:e,message_id:t,emoji:n,active:s,tenant_id:r,expected_account_id:i});return mat.parse(a)},async listConversations(e,t,n){const s=await rt({op:"team_bridge.conversations.list",...e==="account"?{scope:"account"}:{tenant_id:e.tenantId},...t?{status:t}:{},...n?{cursor:n}:{}}),r=gat.parse(s);return t?{...r,conversations:r.conversations.filter(i=>i.status===t)}:r},async getConversation(e,t){const n=await rt({op:"team_bridge.conversations.get",conversation_id:e,...t?{tenant_id:t}:{}});return pu.parse(n)},async startConversation(e){const t=await rt({op:"team_bridge.conversations.create",...await Fa(e.expectedAccountId,e.tenantId),kind:e.kind,...e.tenantId?{tenant_id:e.tenantId}:{},...e.name?{name:e.name}:{},...e.topic?{topic:e.topic}:{},...e.visibility?{visibility:e.visibility}:{},...e.agentCapable===void 0?{}:{agent_capable:e.agentCapable},members:e.members});return pu.parse(t)},async addMembers(e){const t=await rt({op:"team_bridge.conversations.members.add",...await Fa(e.expectedAccountId,e.tenantId),conversation_id:e.conversationId,members:e.members});return pu.parse(t)},async removeMember(e){const t=await rt({op:"team_bridge.conversations.members.remove",...await Fa(e.expectedAccountId,e.tenantId),conversation_id:e.conversationId,account_id:e.accountId});return pu.parse(t)},async listMessages(e,t={}){const n=await rt({op:"team_bridge.messages.list",conversation_id:e,...t.tenantId?{tenant_id:t.tenantId}:{},...t.limit===void 0?{}:{limit:t.limit},...t.beforeSeq===void 0?{}:{before_seq:t.beforeSeq}});return Tat.parse(n)},async listReplies(e,t,n){const s=await rt({op:"team_bridge.messages.replies",conversation_id:e,message_id:t,tenant_id:n.tenantId,expected_account_id:n.accountId,...n.limit===void 0?{}:{limit:n.limit},...n.afterSeq===void 0?{}:{after_seq:n.afterSeq}});return _at.parse(s)},async send(e,t){return rt({op:"team_bridge.messages.send",...t.threadRootId?{}:await Fa(t.expectedAccountId,t.tenantId),conversation_id:e,client_ref:t.clientRef,body:t.body,...t.expectedAccountId?{expected_account_id:t.expectedAccountId}:{},...t.tenantId?{tenant_id:t.tenantId}:{},...t.threadRootId?{thread_root_id:t.threadRootId}:{},...t.attachmentIds?.length?{attachment_ids:[...t.attachmentIds]}:{},...t.mentions?.length?{mentions:[...t.mentions]}:{}})},async uploadAttachment(e,t,n,s){const r=await t1({op:"team_bridge.attachment.upload",tenantId:e,conversationId:t,expectedAccountId:s},n);if(r.kind!=="json")throw new zk(r.kind==="error"?r.status:null,r.kind==="error"?r.code:void 0);const i=r.body;return xat.parse(i&&typeof i=="object"&&"result"in i?i.result:i).attachment},async deleteAttachment(e,t,n,s){return rt({op:"team_bridge.attachments.delete",tenant_id:e,expected_account_id:s,conversation_id:t,attachment_id:n})},async attachmentBytes(e){const t=await t1({op:"team_bridge.attachment",...e},null);if(t.kind!=="bytes")throw new zk(t.kind==="error"?t.status:null,t.kind==="error"?t.code:void 0);return{data:t.data,mimeType:t.mimeType}},async avatarBytes(e){const t=await t1({op:"team_bridge.avatar",...e},null);if(t.kind!=="bytes")throw new zk(t.kind==="error"?t.status:null,t.kind==="error"?t.code:void 0);return{data:t.data,mimeType:t.mimeType}},async markRead(e,t){const n=await rt({op:"team_bridge.read",...await Fa(t.expectedAccountId,t.tenantId),conversation_id:e,...t.tenantId?{tenant_id:t.tenantId}:{},...t.seq===void 0?{}:{seq:t.seq},...t.muted===void 0?{}:{muted:t.muted}});return O6.parse(n)},async identity(){const e=await rt({op:"agent_messages.status",boundary:"surface_open"}),t=Nat.parse(e);return mT(gT(),t),t.account_id??null},async unread(e){const t=await rt({op:"team_bridge.unread",...e==="account"?{scope:"account"}:{tenant_id:e.tenantId}});return Aat.parse(t)},async directory(e){const t=await rt({op:"team_bridge.directory",tenant_id:e});return Iat.parse(t)},async status(e){const t=await rt({op:"team_bridge.status",...e?{boundary:e}:{}}),n=c5.parse(t);return mT(gT(),n),n},async setArchived(e,t,n,s){return rt({op:"team_bridge.conversations.lifecycle",conversation_id:e,action:t?"archive":"unarchive",...await Fa(s,n)})},async deleteConversation(e,t,n){return rt({op:"team_bridge.conversations.delete",conversation_id:e,...await Fa(n,t)})},async leave(e,t,n){return rt({op:"team_bridge.conversations.lifecycle",conversation_id:e,action:"leave",...await Fa(n,t)})},async join(e,t,n){const s=await rt({op:"team_bridge.conversations.join",...await Fa(n,t),conversation_id:e,...t?{tenant_id:t}:{}});return pu.parse(s)},async answerAgentInvitation(e){const t=await rt({op:"team_bridge.conversations.consent",...await Fa(e.accountId,e.tenantId),conversation_id:e.conversationId,account_id:e.accountId,decision:e.decision,consent_version:e.consentVersion});return pu.parse(t)},async setNotify(e,t,n,s){const r=await rt({op:"team_bridge.conversations.notify",...await Fa(s,n),conversation_id:e,...n?{tenant_id:n}:{},notify:t});return O6.parse(r)},async setAgentNotify(e){const t=await rt({op:"team_bridge.conversations.agent_notify",...await Fa(e.accountId,e.tenantId),conversation_id:e.conversationId,notify:e.notify});return pu.parse(t)}},rA=new WeakMap,Oat=64,Lat=1024*1024,Bat=3e3;function jat(e){const t=rA.get(e);if(t)return t;const n=new Map;rA.set(e,n);let s=sp(e);return zA(e,()=>{const r=sp(e);if(r===s)return;s=r;const i=[...n.values()];n.clear();for(const a of i){a.url&&I_(a.url),a.url=void 0;for(const o of a.listeners)o()}}),n}function Hat(e){if(e.size<Oat)return!0;for(const[t,n]of e)if(!(n.listeners.size||n.promise))return n.url&&I_(n.url),e.delete(t),!0;return!1}const HY=/^\/v1\/accounts\/((?:acc_[A-Za-z0-9_-]{1,64})|(?:[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}))\/avatar\?v=([0-9a-f]{16})$/;function UY(e){if(!e?.avatar_url)return null;const t=HY.exec(e.avatar_url);return!t||t[1]!==e.account_id||e.profile?.avatar&&e.profile.avatar.hash!==t[2]?null:{accountId:t[1],hash:t[2]}}const Uat=/^(?:acc_[A-Za-z0-9_-]{1,64}|[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12})$/,Gat=/^[0-9a-f]{16}$/;function Vat(e){const t=e?.id,n=e?.profile?.avatar;if(!t||!Uat.test(t)||!n||!n.hash||!Gat.test(n.hash)||n.source==="none")return null;if(e.avatar_url){const s=HY.exec(e.avatar_url);if(!s||s[1]!==t||s[2]!==n.hash)return null}return{accountId:t,hash:n.hash}}function Udt(e,t){const n=m.useMemo(()=>UY(e),[e]);return GY(n,t)}function Wat(e,t){const n=ug(),s=e?.id,r=e?.profile?.avatar?.hash,i=e?.profile?.avatar?.source,a=e?.avatar_url,o=m.useMemo(()=>Vat({id:s,avatar_url:a,profile:{avatar:{hash:r,source:i}}}),[s,r,i,a]);return GY(o&&o.accountId===n.accountId?o:null,t,{retryOnce:!0})}function GY(e,t,n={}){const s=n.retryOnce===!0,r=Mt(),i=ug(),a=e?`${i.epoch}:${i.accountId??"none"}:${e.accountId}:${e.hash}:${t}`:null,[,o]=m.useState(0),l=m.useRef(!0);if(m.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]),m.useEffect(()=>{if(!a||!e||!i.accountId)return;const u=jat(r),d=u.get(a),f=d??{failed:!1,listeners:new Set,retried:!1},p=i.epoch,g=i.accountId,v=()=>{f.failed=!1,f.promise=_s.avatarBytes({expectedAccountId:g,accountId:e.accountId,hash:e.hash,size:t}).then(({data:w,mimeType:y})=>{if(u.get(a)!==f)return;const S=$r(r);if(S.epoch!==p||S.accountId!==g){u.delete(a);return}if(!["image/png","image/jpeg"].includes(y)||w.byteLength===0||w.byteLength>Lat)throw new Error("Invalid avatar bytes");f.url=y8(new Blob([w],{type:y}),y)}).catch(()=>{f.failed=!0}).finally(()=>{if(f.promise=void 0,u.get(a)===f)for(const w of f.listeners)w()})};if(!d){if(!Hat(u))return;u.set(a,f),v()}let b=!1;const x=()=>{!s||!f.failed||f.promise||f.retried||(f.retried=!0,b=!0,f.retryTimer=setTimeout(()=>{if(f.retryTimer=void 0,b=!1,u.get(a)!==f||!f.failed)return;const w=$r(r);w.epoch!==p||w.accountId!==g||v()},Bat))};u.delete(a),u.set(a,f);const _=()=>{x(),l.current&&o(w=>w+1)};return f.listeners.add(_),x(),()=>{f.listeners.delete(_),b&&f.retryTimer&&(clearTimeout(f.retryTimer),f.retryTimer=void 0,f.retried=!1)}},[i.accountId,i.epoch,a,r,s,t,e]),!(!a||!i.accountId))return rA.get(r)?.get(a)?.url}const $at=140,zat=/^\s*(```|~~~).*$/gm,qat=/^\s{0,3}#{1,6}\s+/gm,Kat=/^\s{0,3}(>\s?)+/gm,Yat=/^\s*([-*+]|\d{1,9}[.)])\s+/gm,Xat=/^\[[ xX]\]\s+/gm,Qat=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/gm,Jat=/!\[([^\]]*)\]\([^)]*\)/g,Zat=/\[([^\]]+)\]\([^)]*\)/g,eot=/<((?:https?|mailto):[^>\s]+)>/gi,tot=/<\/?[A-Za-z][^>]*>/g,not=/`+([^`]*)`+/g,sot=/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,rot=/~~(?=\S)([\s\S]*?\S)~~/g,iot=/(^|[^\w*])\*(?=\S)([^*]*?\S)\*(?!\w)/g,aot=/(^|[^\w])_(?=\S)([^_]*?\S)_(?!\w)/g;function oot(e,t=$at){if(typeof e!="string"||e.trim().length===0)return null;const n=e.replace(zat," ").replace(Qat," ").replace(qat,"").replace(Kat,"").replace(Yat,"").replace(Xat,"").replace(Jat,"$1").replace(Zat,"$1").replace(eot,"$1").replace(tot,"").replace(not,"$1").replace(sot,"$2").replace(rot,"$1").replace(iot,"$1$2").replace(aot,"$1$2"),s=Ap(n,Number.MAX_SAFE_INTEGER);return s.length===0?null:NY(s,t)}function lot(e,t){const n=e.senderLabel?.trim()||e.conversationName?.trim()||t.untitled,s=e.place.kind==="dm"?t.directMessage:e.place.kind==="channel"?e.place.name?.trim()?t.channel(e.place.name.trim()):e.conversationName?.trim()??t.untitled:e.place.name?.trim()||e.conversationName?.trim()||t.group,r=e.organizationName?t.subtitle(s,e.organizationName):s,i=Math.max(1,Math.floor(e.unreadCount)),a=i>1?e.preview?t.countPreview(i,e.preview):t.count(i):e.preview??t.fallback;return{title:Ap(n,Iv)||t.untitled,subtitle:Ap(r,rat)||t.untitled,body:Ap(a,sat)||t.fallback}}const gm=3e4,cot=10;function uot(e,t=cot){return[...e?.organizations??[]].filter(n=>n.eligible&&n.unread>0).sort((n,s)=>s.unread-n.unread||n.tenant_id.localeCompare(s.tenant_id)).slice(0,t)}function dot(e,t){return e.member===!0?!0:e.member===!1||!t?!1:e.members.some(n=>n.kind==="human"&&n.account_id===t&&n.state==="active")}function VY(e,t){return dot(e,t)&&q8(e)==="all"&&e.builtin!=="agents"}function hot(e,t,n){return{conversationName:K8(e,t),organizationName:Sie(e,n),senderLabel:KA(e.last_sender_label??"")}}function fot(e){const t=new Map(e.cursors),n=e.rows;if(!e.seeded){for(const a of n)t.set(a.conversation_id,a.latest_seq);return{candidates:[],cursors:t,seeded:!0}}const r=new Map(e.conversations.map(a=>[a.id,a])),i=[];for(const a of n){const o=t.get(a.conversation_id);if(a.unread_count===0||a.latest_seq<=a.last_read_seq||o!==void 0&&a.latest_seq<=o){(o===void 0||a.latest_seq>o)&&t.set(a.conversation_id,a.latest_seq);continue}const l=r.get(a.conversation_id);l!==void 0&&l.latest_seq===a.latest_seq&&(t.set(a.conversation_id,a.latest_seq),VY(l,e.selfAccountId)&&(e.quiet||i.push({conversationId:l.id,...l.last_thread_root_id?{threadId:l.last_thread_root_id}:{},tenantId:a.tenant_id,seq:a.latest_seq,...hot(l,e.selfAccountId,e.organizations),kind:l.kind,name:l.name?.trim()||null,unreadCount:a.unread_count})))}return{candidates:i,cursors:t,seeded:!0}}function ZD(e,t,n,s){return e.getMutationCache().findAll({mutationKey:$t.notifyMutation(t.accountId,t.epoch),exact:!0,status:"pending"}).some(r=>{const i=r.state.variables;return i?.conversationId===n&&(i.tenantId===void 0||i.tenantId===s)})}function pot(e,t,n,s,r){return new Promise(i=>{const a=()=>{l(),r.removeEventListener("abort",a),i()},o=()=>{(r.aborted||!ZD(e,t,n,s))&&a()},l=e.getMutationCache().subscribe(o);r.addEventListener("abort",a,{once:!0}),o()})}function eI(){return wy(),ug()}function WY(e){return e?{accountId:e.account_id,state:e.state,readOnly:!!e.read_only,localEnabled:e.local.enabled}:null}function got(e,t){return!e||!t?!0:e.accountId!==t.accountId||e.state!==t.state||e.readOnly!==t.readOnly||e.localEnabled!==t.localEnabled}function $Y(e,t){const n=()=>WY(e.getQueryData($t.statusFor(t))),s=n();return()=>!got(s,n())}function kc(e,t){const n=$r(e),s=WY(e.getQueryData($t.statusFor(t)));return!!(t&&n.accountId===t&&s?.accountId===t&&s.state==="ready"&&s.localEnabled&&!s.readOnly)}function L6(e,t){const n=e.getQueryData($t.statusFor(t));if(!t||$r(e).accountId!==t||n?.account_id!==t)throw new Error("Team Bridge read owner changed")}const zY=x8;async function Ec(e,t,n){L6(e,t);const s=$Y(e,t),r=await zY(e,t,n);if(L6(e,t),!s())throw new Error("Team Bridge read authority changed");return r}function lo(e){const t=Mt(),n=$r(t),s=m.useRef({accountId:e??n.accountId,epoch:n.epoch}).current,r=m.useRef(!0);m.useLayoutEffect(()=>(r.current=!0,()=>{r.current=!1}),[]);const i=()=>{const d=$r(t);return!!s.accountId&&d.accountId===s.accountId&&d.epoch===s.epoch},a=()=>i()&&kc(t,s.accountId),o=()=>r.current&&i(),l=()=>o()&&kc(t,s.accountId),u=()=>{if(!l())throw new Error("Team Bridge write authority changed")};return{accountId:s.accountId,isCurrent:l,isReadCurrent:o,isAuthorityCurrent:a,assertCurrent:u}}function Gdt(e){const t=e.get("tenant"),n=e.get("conversation"),s=e.get("thread");return t&&n&&s?{tenantId:t,conversationId:n,rootId:s}:null}function qY(e,t){if(e.root.id!==t.rootId||e.root.conversation_id!==t.conversationId||e.root.thread_root_id||e.replies.some(n=>n.conversation_id!==t.conversationId||n.thread_root_id!==t.rootId))throw new Error("Thread response identity mismatch");return e}async function Vdt(e,t,n){return qY(await _s.listReplies(e.conversationId,e.rootId,{tenantId:e.tenantId,accountId:t,afterSeq:n}),e)}function Wdt(e,t,n){if(typeof IntersectionObserver>"u")return()=>{};const s=new Map(t.map(d=>[d.id,d.seq])),r=new Map,i=e.ownerDocument;let a=!0,o=-1;const l=()=>{if(!a||!e.isConnected||i.visibilityState!=="visible"||!i.hasFocus())return;const d=Math.max(-1,...r.values());d<=o||(o=d,n(d).catch(()=>{a&&o===d&&(o=-1)}))},u=new IntersectionObserver(d=>{if(a){for(const f of d){const p=f.target.dataset.messageId??"",g=s.get(p);g!==void 0&&f.isIntersecting&&f.intersectionRect.height>0?r.set(p,g):r.delete(p)}l()}},{root:e.querySelector("[data-radix-scroll-area-viewport]"),threshold:0});for(const d of e.querySelectorAll("[data-message-id]"))s.has(d.dataset.messageId??"")&&u.observe(d);return i.addEventListener("visibilitychange",l),i.defaultView?.addEventListener("focus",l),()=>{a=!1,u.disconnect(),i.removeEventListener("visibilitychange",l),i.defaultView?.removeEventListener("focus",l)}}const tI=(e,t)=>`${e}\0${t}`,BC=(e,t)=>e.at(-1)===t&&e.at(-2)==="account",KY={rows:new Map,byTenant:new Map,total:0};function YY(e,t){const n=e.getQueryCache(),s=r=>n.findAll({queryKey:r}).filter(i=>BC(i.queryKey,t));return{conversations:s($t.conversationsPrefix),unread:s($t.unreadPrefix)}}function mot(e,t){return t?XY(YY(e,t)):KY}function XY(e){const t=new Map,n=u=>{const d=tI(u.tenantId,u.conversationId),f=t.get(d);(!f||u.at>=f.at)&&t.set(d,u)},s=new Set;for(const u of e.conversations){if(u.queryKey.includes("archived"))continue;const d=u.state.data;for(const f of d?.conversations??[])f.status!=="archived"&&n({tenantId:f.tenant_id,conversationId:f.id,unread:f.unread_count,lastReadSeq:f.last_read_seq,latestSeq:f.latest_seq,muted:q8(f)==="mute",at:u.state.dataUpdatedAt})}let r,i=0;for(const u of e.unread){const d=u.queryKey[2],f=u.state.data;if(f){if(d===Vu){r=f,i=u.state.dataUpdatedAt;continue}if(!(typeof d!="string"||!f.conversations)){s.add(d);for(const p of f.conversations)n({tenantId:d,conversationId:p.conversation_id,unread:p.unread_count,lastReadSeq:p.last_read_seq,latestSeq:p.latest_seq,muted:p.muted,at:u.state.dataUpdatedAt})}}}const a=new Map((r?.organizations??[]).map(u=>[u.tenant_id,u.unread]));for(const[u,d]of t)!d.muted&&a.get(d.tenantId)===0&&i>d.at&&t.set(u,{...d,unread:0});const o=new Map;for(const[u,d]of a){let f=0;for(const p of t.values())p.tenantId===u&&!p.muted&&(f+=p.unread);o.set(u,s.has(u)?f:Math.max(d,f))}let l=0;for(const u of o.values())l+=u;return r&&!r.organizations?.length&&(l=r.total),{rows:t,byTenant:o,total:l}}function $dt(e,t){const n=t.rows.get(tI(e.tenant_id,e.id));return!n||n.unread===e.unread_count&&n.lastReadSeq===e.last_read_seq?e:{...e,unread_count:n.unread,last_read_seq:Math.max(n.lastReadSeq,e.last_read_seq)}}const B6=new WeakMap;let vot=1;function bot(e){if(!e||typeof e!="object")return 0;let t=B6.get(e);return t===void 0&&(t=vot++,B6.set(e,t)),t}function xot(e,t){const n=[];for(const s of[...t.conversations,...t.unread])n.push(`${s.queryHash}@${s.state.dataUpdatedAt}:${bot(s.state.data)}`);return`${e}#${n.join("|")}`}function _ot(e){const t=Mt(),n=m.useRef(null),s=m.useCallback(i=>t.getQueryCache().subscribe(i),[t]),r=m.useCallback(()=>{if(!e)return KY;const i=YY(t,e),a=xot(e,i);return n.current?.signature!==a&&(n.current={signature:a,view:XY(i)}),n.current.view},[t,e]);return m.useSyncExternalStore(s,r,r)}function b_(e,t,n){const s=e.getQueryState(t);s?.data!==void 0&&e.setQueryData(t,n(s.data),{updatedAt:s.dataUpdatedAt})}function j6(e,t){for(const n of[$t.unreadPrefix,$t.conversationsPrefix])for(const s of e.getQueryCache().findAll({queryKey:n}))BC(s.queryKey,t)&&s.state.data!==void 0&&s.state.fetchStatus!=="idle"&&s.cancel({revert:!0})}function wot(e,t,n,s){const r=new Map(s.map(i=>[i.conversation_id,i]));for(const i of e.getQueryCache().findAll({queryKey:$t.conversationsPrefix}))BC(i.queryKey,t)&&b_(e,i.queryKey,a=>{let o=!1;const l=a.conversations.map(u=>{const d=u.tenant_id===n?r.get(u.id):null;return!d||d.unread_count===u.unread_count&&d.last_read_seq===u.last_read_seq?u:(o=!0,{...u,unread_count:d.unread_count,last_read_seq:Math.max(d.last_read_seq,u.last_read_seq)})});return o?{...a,conversations:l}:a})}function yot(e,t,n){const s=mot(e,t).rows.get(tI(n.tenantId,n.conversationId));if(!(s!==void 0&&n.seq>=s.latestSeq))return[];const i=s.muted?0:s.unread,a=[],o=d=>{const f=e.getQueryState(d);a.push({key:d,data:f?.data,updatedAt:f?.dataUpdatedAt??0})};for(const d of e.getQueryCache().findAll({queryKey:$t.conversationsPrefix}))!BC(d.queryKey,t)||!d.state.data?.conversations.some(p=>p.id===n.conversationId&&p.tenant_id===n.tenantId)||(o(d.queryKey),b_(e,d.queryKey,p=>({...p,conversations:p.conversations.map(g=>g.id===n.conversationId&&g.tenant_id===n.tenantId?{...g,unread_count:0,last_read_seq:Math.max(g.last_read_seq,n.seq)}:g)})));const l=$t.unread(_E(n.tenantId),t);e.getQueryData(l)!==void 0&&(o(l),b_(e,l,d=>({...d,total:Math.max(0,d.total-i),conversations:d.conversations?.map(f=>f.conversation_id===n.conversationId?{...f,unread_count:0,last_read_seq:Math.max(f.last_read_seq,n.seq)}:f)})));const u=$t.unread(Vu,t);return i>0&&e.getQueryData(u)!==void 0&&(o(u),b_(e,u,d=>({...d,total:Math.max(0,d.total-i),organizations:d.organizations?.map(f=>f.tenant_id===n.tenantId?{...f,unread:Math.max(0,f.unread-i)}:f)}))),a}function Cot(e,t){for(const{key:n,data:s,updatedAt:r}of t)e.setQueryData(n,s,{updatedAt:r})}let x_=null;function Sot(){return x_}function zdt(e){m.useEffect(()=>{const t=e??null;return x_=t,()=>{x_===t&&(x_=null)}},[e])}const QY="bridge_agent_participation_v2",qdt=`ui.teamBridge.invitations.consent.${QY}`;function kot(e,t,n){const s=t.invited_by,[r,i]=typeof s=="string"&&s!==""?["added",s]:["created",e.created_by];if(i===n)return{role:r,self:!0};const a=Eot(e,i);return a?{role:r,name:a,self:!1}:null}function Eot(e,t){const n=e.members.find(s=>s.kind==="human"&&s.account_id===t);return n?KA(n.display_label):null}function Kdt(e,t){if(!t)return[];const n=[];for(const s of e){if(s.builtin||s.status!=="open")continue;const r=s.members.find(i=>i.kind==="agent"&&i.account_id===t&&i.state==="invited");r&&n.push({key:`${s.tenant_id}|${s.id}`,conversationId:s.id,tenantId:s.tenant_id,conversationKind:s.kind,conversationName:K8(s,t),agentName:KA(r.display_label),inviter:kot(s,r,t)})}return n}function Ydt(e,t,n){const s=new Map(t.map(a=>[a.key,a])),r=e.flatMap(a=>{const o=s.get(a.key);return o?[o]:n.has(a.key)?[a]:[]}),i=new Set(r.map(a=>a.key));return[...r,...t.filter(a=>!i.has(a.key))]}function Xdt(e,t,n){return n?e:t}function Tot(e,t,n,s){return JY(e,t,n,"invited",s==="accept"?"active":"removed")}function Rot(e,t,n,s){return JY(e,t,n,s==="accept"?"active":"removed","invited")}function JY(e,t,n,s,r){return{...e,conversations:e.conversations.map(i=>i.id===t.conversationId&&i.tenant_id===t.tenantId?{...i,members:i.members.map(a=>a.kind==="agent"&&a.account_id===n&&a.state===s?{...a,state:r}:a)}:i)}}function Qdt(e){const t=e,n=typeof t?.status=="number"?t.status:null,s=typeof t?.code=="string"?t.code:null,r=t?.detail?.details?.rule;return n===401||s==="bridge_signin_required"?"sign_in":s==="agent_not_permitted"?"agent_unavailable":s==="invalid_transition"?r==="builtin"?"gone":"already_answered":s===PY?"runtime_outdated":s==="member_not_found"||s==="conversation_not_found"?"gone":s==="consent_version_unknown"?"outdated":s==="bridge_not_available"||s==="bridge_disabled"?"not_available":n===null&&s===null&&e instanceof Error&&"status"in e?"unreachable":"unconfirmed"}function Aot(e){if(!e.has_more)return 0;let t;for(const n of e.messages)typeof n.seq=="number"&&(t===void 0||n.seq<t)&&(t=n.seq);return t??0}function Fot(e,t){const n=e?.events??[],s=t.events??[];if(n.length===0&&s.length===0)return t;const r=Aot(t),i=new Map;for(const o of n)o.after_seq>=r&&i.set(o.id,o);for(const o of s)i.set(o.id,o);const a=[...i.values()].sort((o,l)=>l.event_seq-o.event_seq);if(a.length===0){const{events:o,...l}=t;return l}return{...t,events:a}}const Ad=e=>`${e.kind}:${e.account_id}:${e.endpoint_id??""}`;function Jdt(e){const t=[...e].sort((r,i)=>r.event_seq-i.event_seq),n=[],s=new Map;for(const r of t){const a=r.targets.length>0?Cat(r.kind):null,o=a==="joined"&&r.implicit===!0&&Sat(r.implicit_reason)==="owner_invite",l=r.request_id&&a!==null?`${r.request_id}\0${a}\0${o}\0${Ad(r.actor)}`:null,u=l?s.get(l):void 0;if(u){const g=new Set(u.targets.map(Ad));for(const v of r.targets)g.has(Ad(v))||u.targets.push(v);r.at>u.at&&(u.at=r.at),u.selfOnly=!1;continue}const d=[],f=new Set;for(const g of r.targets)f.has(Ad(g))||(f.add(Ad(g)),d.push(g));const p={key:`event:${r.id}`,kind:a,ownerAddedAgent:o,actor:r.actor,targets:d,selfOnly:d.length===0||d.length===1&&Ad(d[0])===Ad(r.actor),at:r.at};n.push(p),l&&s.set(l,p)}return n}const Dot="leading";function Zdt(e,t){const n=new Map;if(!t||t.length===0)return n;const s=e.filter(i=>typeof i.seq=="number").sort((i,a)=>i.seq-a.seq),r=new Set;for(const i of t){if(r.has(i.id))continue;r.add(i.id);let a=Dot,o=0,l=s.length-1;for(;o<=l;){const d=o+l>>1;s[d].seq<=i.after_seq?(a=s[d].id,o=d+1):l=d-1}const u=n.get(a);u?u.push(i):n.set(a,[i])}return n}const eht=2,qd=new Map,Iot=32,nI=(e,t)=>`${e}\0${t.trim()}`;function tht(e,t,n){const s=nI(e,t);if(qd.delete(s),!(!n||n.length===0))for(qd.set(s,n);qd.size>Iot;){const r=qd.keys().next().value;if(r===void 0)break;qd.delete(r)}}function Not(e,t){return qd.get(nI(e,t))}function Pot(e,t){qd.delete(nI(e,t))}function Rg(e,t){const n=s=>({onSuccess:(r,i,a)=>s?.onSuccess?.(r,i.input,a),onError:(r,i,a)=>s?.onError?.(r,i.input,a),onSettled:(r,i,a,o)=>s?.onSettled?.(r,i,a.input,o)});return{...e,variables:e.variables?.input,mutate:(s,r)=>e.mutate({input:s,target:t()},n(r)),mutateAsync:(s,r)=>e.mutateAsync({input:s,target:t()},n(r))}}function jC(e){return e===Vu?"account":{tenantId:e}}const Mot=18e4,H6=6e4;function Oot(){return typeof document>"u"?H6:document.visibilityState==="visible"?Mot:H6}function nht(e,t=!0,n){const s=Mt();return Dn({queryKey:$t.conversations(e,n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.listConversations(jC(e))),enabled:t&&!!n,staleTime:15e3,refetchOnWindowFocus:!0})}function sht(e,t=!0,n){const s=Mt();return Dn({queryKey:$t.archivedConversations(e,n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.listConversations(jC(e),"archived")),enabled:t&&!!n,staleTime:15e3,refetchOnWindowFocus:!0})}function rht(e,t){const n=Mt(),s=$t.archivedConversations(e,t??"unresolved-owner");return fn({mutationFn:async()=>{const r=n.getQueryData(s),i=r?.next_cursor;if(!r||!i)return r??{conversations:[]};const a=await Ec(n,t,()=>_s.listConversations(jC(e),"archived",i));return kie(r,a)},onSuccess:r=>{n.setQueryData(s,r)}})}function sI(e,t,n,s){return{queryKey:$t.messages(t??"none",n,s??"unresolved-owner"),queryFn:async({queryKey:r})=>Fot(e.getQueryData(r),await Ec(e,s,()=>_s.listMessages(t,{tenantId:n})))}}function iht(e,t,n=!0,s){const r=Mt();return Dn({...sI(r,e,t,s),enabled:n&&!!s&&!!e,staleTime:5e3,retry:(i,a)=>!VN(a)&&i<3,refetchInterval:i=>VN(i.state.error)?!1:8e3,refetchOnWindowFocus:!0})}function Lot(e,t){return zY(e,t,async()=>{const n=await _s.status("surface_open");if(n.state==="ready"&&n.account_id!==t)throw new Error("Team Bridge status owner changed");return n})}function aht(e,t=!0,n){const s=Mt();return Dn({queryKey:$t.directory(e??"none",n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.directory(e)),enabled:t&&!!n&&!!e,staleTime:3e4,refetchOnWindowFocus:!0,retry:1})}function Bot(e,t=!0,n){const s=Mt(),r=tH({queries:e.map(i=>({queryKey:$t.directory(i,n??"unresolved-owner"),queryFn:()=>Ec(s,n,()=>_s.directory(i)),enabled:t&&!!n,staleTime:3e4,refetchOnWindowFocus:!0,retry:1}))});return m.useMemo(()=>{const i={},a={},o={},l=new Map;return r.forEach((u,d)=>{const f=e[d];u.data&&(i[f]=u.data.members),u.isError&&(o[f]=u.error),a[f]=u.isPending?"loading":u.isError?"error":"ready",l.set(f,()=>{u.refetch()})}),{members:i,state:a,errors:o,retry:u=>{l.get(u)?.()}}},[r,e])}function ZY(e=!0){const t=Mt(),{accountId:n}=eI();return Dn({queryKey:$t.statusFor(n),queryFn:()=>Lot(t,n),enabled:e&&!!n,staleTime:6e4,refetchOnWindowFocus:!0,retry:1})}function eX(e,t=Vu,n={}){const s=Mt();return Dn({queryKey:$t.unread(t,n.accountId??"unresolved-owner"),queryFn:()=>Ec(s,n.accountId,()=>_s.unread(jC(t))),enabled:e&&!!n.accountId,staleTime:3e4,refetchInterval:n.refetchInterval??Oot(),refetchIntervalInBackground:n.refetchIntervalInBackground,refetchOnWindowFocus:!0,retry:1})}async function tX(e,t,n,s=()=>!0){s()&&(await e.invalidateQueries({queryKey:$t.messages(t,n)}),s()&&(await e.invalidateQueries({queryKey:$t.conversationsPrefix}),s()&&await e.invalidateQueries({queryKey:$t.unreadPrefix})))}function oht(e,t){const n=Mt(),s=lo(),r=fn({mutationFn:({input:i,target:a})=>(a.assertCurrent(),_s.send(a.conversationId,{...i,tenantId:a.tenantId,expectedAccountId:Mat(a.accountId),mentions:Not(a.conversationId,i.body)})),onSuccess:(i,{input:a,target:o})=>(Pot(o.conversationId,a.body),tX(n,o.conversationId,o.tenantId,o.isCurrent))});return Rg(r,()=>({...s,conversationId:e,tenantId:t}))}function lht(e,t){const n=Mt(),s=lo(),r=fn({mutationFn:({target:i})=>(i.assertCurrent(),_s.join(i.conversationId,i.tenantId,i.accountId)),onSuccess:(i,{target:a})=>tX(n,a.conversationId,a.tenantId,a.isCurrent)});return Rg(r,()=>({...s,conversationId:e,tenantId:t}))}function jot(e,t){const{accountId:n,epoch:s}=$r(e),r=()=>kc(e,n)&&(t?.()??!0),i=()=>{if(!r())throw new Error("Team Bridge write authority changed")},a={queryKey:$t.conversationsPrefix,predicate:o=>o.queryKey.at(-1)===n&&o.queryKey.at(-2)==="account"};return{mutationKey:$t.notifyMutation(n,s),mutationFn:({conversationId:o,notify:l,tenantId:u})=>(i(),_s.setNotify(o,l,u,n)),onMutate:async({conversationId:o,notify:l,tenantId:u})=>{i(),await e.cancelQueries(a),i();const d=e.getQueriesData(a);return e.setQueriesData(a,f=>f===void 0?f:Eie(f,o,l,u)),{snapshots:d}},onError:(o,l,u)=>{if(r())for(const[d,f]of u?.snapshots??[])e.setQueryData(d,f)},onSettled:async()=>{r()&&(await e.invalidateQueries(a),r()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function cht(){const e=Mt(),t=lo();return fn(jot(e,t.isCurrent))}function Hot(e,t,n){const{accountId:s}=$r(e),r=()=>kc(e,s)&&(n?.()??!0),i=()=>{if(!r()||!s)throw new Error("Team Bridge write authority changed");return s},a={queryKey:$t.conversationsPrefix,predicate:u=>u.queryKey.at(-1)===s&&u.queryKey.at(-2)==="account"},o=u=>{if(t?.conversationId!==u.conversationId||t.tenantId!==u.tenantId)throw new Error("Team Bridge agent-notify target changed")},l=["agent-notify",s??"unresolved-owner",t?.tenantId??"unknown-tenant",t?.conversationId??"no-conversation"];return{mutationKey:[...$t.all,...l],scope:{id:l.join(":")},mutationFn:({conversationId:u,tenantId:d,notify:f})=>(o({conversationId:u,tenantId:d}),_s.setAgentNotify({conversationId:u,tenantId:d,notify:f,accountId:i()})),onMutate:async u=>{o(u);const d=i();await e.cancelQueries(a),i();let f=null;for(const[,p]of e.getQueriesData(a)){const g=p?.conversations.find(b=>b.id===u.conversationId&&b.tenant_id===u.tenantId),v=g?Aie(g,d):null;if(v){f=Fie(v);break}}return e.setQueriesData(a,p=>p===void 0?p:Die(p,u,d,u.notify)),{self:d,previous:f}},onSuccess:u=>{!r()||!s||e.setQueriesData(a,d=>d===void 0?d:Rie(d,u,s))},onError:(u,d,f)=>{!r()||!f||e.setQueriesData(a,p=>p===void 0?p:Tie(p,d,f.self,d.notify,f.previous))},onSettled:async()=>{r()&&await e.invalidateQueries(a)}}}function uht(e,t){const n=Mt(),s=lo();return fn(Hot(n,e&&t?{conversationId:e,tenantId:t}:null,s.isCurrent))}function Uot(e,t){const{accountId:n}=$r(e),s=()=>kc(e,n)&&(t?.()??!0),r=()=>{if(!s()||!n)throw new Error("Team Bridge write authority changed");return n},i={queryKey:$t.conversationsPrefix,predicate:a=>a.queryKey.at(-1)===n&&a.queryKey.at(-2)==="account"};return{mutationFn:({conversationId:a,tenantId:o,decision:l})=>_s.answerAgentInvitation({conversationId:a,tenantId:o,decision:l,accountId:r(),consentVersion:QY}),onMutate:async a=>{const o=r();await e.cancelQueries(i),r(),e.setQueriesData(i,l=>l===void 0?l:Tot(l,a,o,a.decision))},onError:(a,o)=>{!s()||!n||e.setQueriesData(i,l=>l===void 0?l:Rot(l,o,n,o.decision))},onSettled:async()=>{s()&&await e.invalidateQueries(i)}}}function dht(){const e=Mt(),t=lo();return fn(Uot(e,t.isCurrent))}function hht(e,t){const n=Mt(),s=lo(),r=fn({mutationFn:({input:i,target:a})=>(a.assertCurrent(),_s.markRead(a.conversationId,{...i,tenantId:a.tenantId,expectedAccountId:a.accountId})),onMutate:({input:i,target:a})=>{if(!(!a.isCurrent()||!a.accountId||!a.tenantId))return j6(n,a.accountId),yot(n,a.accountId,{tenantId:a.tenantId,conversationId:a.conversationId,seq:i.seq})},onError:async(i,{target:a},o)=>{!a.isCurrent()||!o||(Cot(n,o),await n.invalidateQueries({queryKey:$t.conversationsPrefix}),a.isCurrent()&&await n.invalidateQueries({queryKey:$t.unreadPrefix}))},onSuccess:async(i,{target:a})=>{a.isCurrent()&&a.accountId&&(j6(n,a.accountId),await n.invalidateQueries({queryKey:$t.conversationsPrefix}),a.isCurrent()&&await n.invalidateQueries({queryKey:$t.unreadPrefix}))}});return Rg(r,()=>({...s,conversationId:e,tenantId:t}))}function fht(){const e=Mt(),t=lo(),n=fn({mutationFn:({input:s,target:r})=>(r.assertCurrent(),_s.addMembers({conversationId:s.conversationId,tenantId:s.tenantId,expectedAccountId:r.accountId,members:s.members})),onSuccess:async(s,{target:r})=>{r.isCurrent()&&(nX(e,r.accountId,s),await e.invalidateQueries({queryKey:$t.conversationsPrefix}))}});return Rg(n,()=>t)}function pht(){const e=Mt(),t=lo(),n=fn({mutationFn:({input:s,target:r})=>(r.assertCurrent(),_s.removeMember({conversationId:s.conversationId,tenantId:s.tenantId,expectedAccountId:r.accountId,accountId:s.accountId})),onSuccess:async(s,{target:r})=>{r.isCurrent()&&(nX(e,r.accountId,s),await e.invalidateQueries({queryKey:$t.conversationsPrefix}))}});return Rg(n,()=>t)}function nX(e,t,n){const s={queryKey:$t.conversationsPrefix,predicate:r=>r.queryKey.at(-1)===t&&r.queryKey.at(-2)==="account"};e.setQueriesData(s,r=>r===void 0?r:{...r,conversations:r.conversations.map(i=>i.id===n.id&&i.tenant_id===n.tenant_id?n:i)})}function ght(e,t=()=>!0){const n=Mt(),s=lo(),r=fn({mutationFn:({input:i,target:a})=>{if(a.assertCurrent(),!a.isCurrent())throw new Error("Team Bridge write authority changed");return _s.startConversation({...i,tenantId:a.tenantId,expectedAccountId:a.accountId})},onSuccess:async(i,{target:a})=>{a.isCurrent()&&await n.invalidateQueries({queryKey:$t.conversationsPrefix})}});return Rg(r,()=>({...s,conversationId:"",tenantId:e,isCurrent:()=>s.isCurrent()&&t()}))}function rI(e){return{queryKey:$t.conversationsPrefix,predicate:t=>t.queryKey.at(-1)===e&&t.queryKey.at(-2)==="account"}}function Got(e,t){const{accountId:n,epoch:s}=$r(e),r=()=>kc(e,n)&&(t?.()??!0),i=()=>{if(!r())throw new Error("Team Bridge write authority changed")},a=rI(n);return{mutationKey:[...$t.all,"archive",n,s],mutationFn:({conversationId:o,tenantId:l})=>(i(),_s.setArchived(o,!0,l,n)),onMutate:async({conversationId:o,tenantId:l})=>{i(),await e.cancelQueries(a),i();const u=e.getQueriesData(a);return e.setQueriesData(a,d=>d===void 0?d:Y8(d,o,l)),{snapshots:u}},onError:(o,l,u)=>{if(r())for(const[d,f]of u?.snapshots??[])e.setQueryData(d,f)},onSettled:async()=>{r()&&(await e.invalidateQueries(a),r()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function mht(){const e=Mt(),t=lo();return fn(Got(e,t.isCurrent))}function Vot(e,t){const{accountId:n,epoch:s}=$r(e),r=()=>kc(e,n)&&(t?.()??!0),i=()=>{if(!r())throw new Error("Team Bridge write authority changed")},a=rI(n);return{mutationKey:[...$t.all,"unarchive",n,s],mutationFn:({conversationId:o,tenantId:l})=>(i(),_s.setArchived(o,!1,l,n)),onMutate:async({conversationId:o,tenantId:l})=>{i(),await e.cancelQueries(a),i();const u=e.getQueriesData(a);return e.setQueriesData(a,d=>d===void 0?d:Iie(d,o,"open",l)),{snapshots:u}},onError:(o,l,u)=>{if(r())for(const[d,f]of u?.snapshots??[])e.setQueryData(d,f)},onSettled:async()=>{r()&&(await e.invalidateQueries(a),r()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function vht(){const e=Mt(),t=lo();return fn(Vot(e,t.isCurrent))}function Wot(e,t,n=new Set){const{accountId:s,epoch:r}=$r(e),i=()=>kc(e,s)&&(t?.()??!0),a=()=>{if(!i())throw new Error("Team Bridge write authority changed")},o=rI(s);return{mutationKey:[...$t.all,"delete",s,r],mutationFn:async({conversationId:l,tenantId:u})=>{a();try{return await _s.deleteConversation(l,u,s)}catch(d){const f=d;if(f.code==="conversation_not_found"){if(n.delete(l))return{deleted:!0};throw d}throw(f.status===null||f.status===void 0||f.status>=500)&&n.add(l),d}},onSuccess:(l,{conversationId:u,tenantId:d})=>{i()&&e.setQueriesData(o,f=>f===void 0?f:Y8(f,u,d))},onSettled:async()=>{i()&&(await e.invalidateQueries(o),i()&&await e.invalidateQueries({queryKey:$t.unreadPrefix}))}}}function bht(){const e=Mt(),t=lo(),n=m.useRef(new Set);return fn(Wot(e,t.isCurrent,n.current))}const $ot="display.notifications";function zot(){return{untitled:h("ui.teamBridge.list.untitled"),directMessage:h("ui.teamBridge.kind.dm"),group:h("ui.teamBridge.kind.group"),channel:e=>h("ui.teamBridge.notify.channel",{channel:e}),subtitle:(e,t)=>h("ui.teamBridge.notify.subtitle",{place:e,organization:t}),count:e=>h("ui.teamBridge.notify.count",{count:e}),countPreview:(e,t)=>h("ui.teamBridge.notify.count_preview",{count:e,preview:t}),fallback:h("ui.teamBridge.notify.body_fallback")}}function qot(e){return e.kind==="dm"?{kind:"dm"}:{kind:e.kind,name:e.name}}function iA(e,t){const n=e.profile?.avatar?.source==="none"?null:UY(e);return uat({v:1,kind:t,account_id:e.account_id,display_name:Ap(e.display_label,Iv),agent_name:Ap(e.agent?.name??"",Iv),...n?{avatar:{account_id:n.accountId,hash:n.hash}}:{}})}function Kot(e,t,n){return e.getQueryData($t.directory(t,n))?.members??[]}function Yot(e,t,n,s){const r=$t.replies(t.tenantId,t.conversationId,n);e.setQueryData(r,i=>{const a=i?.pages.at(-1);return!i||!a||a.has_more||i.pages.some(o=>o.replies.some(l=>l.id===s.id))?i:{...i,pages:[...i.pages.slice(0,-1),{...a,replies:[...a.replies,s].sort((o,l)=>o.seq-l.seq)}]}})}function Xot(e,t,n,s){return{...sI(e,t,n,s),staleTime:0}}async function Qot(e,t,n,s,r){if(!s())return;let i=t.senderLabel,a,o=null,l;const u=$r(e);if(u.accountId!==n)return;const d={accountId:n,epoch:u.epoch},f=t.threadId;try{let b;if(f)b=qY(await _s.listReplies(t.conversationId,f,{tenantId:t.tenantId,accountId:n,afterSeq:t.seq,limit:1}),{tenantId:t.tenantId,conversationId:t.conversationId,rootId:f}).replies.find(x=>x.seq===t.seq),b&&s()&&Yot(e,t,f,b);else{const x=()=>e.fetchQuery(Xot(e,t.conversationId,t.tenantId,n));b=(await x().catch(w=>{if(!iZ(w))throw w;return x()})).messages.reduce((w,y)=>w===void 0||y.seq>w.seq?y:w,void 0)}if(b&&b.seq>=t.seq){if(f||(l=b.id),b.sender.kind==="human"&&b.sender.account_id===n||!s())return;const x=Kot(e,t.tenantId,n);i=Mie(b.sender,x,{named:(w,y)=>h("ui.teamBridge.chief.label",{agent:w,person:y}),unnamed:w=>h("ui.teamBridge.chief.unnamed",{person:w})});const _=x.find(w=>w.account_id===b.sender.account_id);_&&(b.sender.kind==="human"||b.sender.kind==="agent")&&(a=iA(_,b.sender.kind==="human"?"person":"person_agent")),o=oot(b.body)}}catch{}const p=window.api?.desktop?.teamBridge;if(!p)return;const g=lot({senderLabel:i,conversationName:t.conversationName,place:qot(t),organizationName:t.organizationName,preview:o,unreadCount:t.unreadCount},zot());for(;ZD(e,d,t.conversationId,t.tenantId);)if(await pot(e,d,t.conversationId,t.tenantId,r),r.aborted||!s())return;if(r.aborted||!s())return;const v=e.getQueryData($t.conversations(Vu,n))?.conversations.find(b=>b.id===t.conversationId&&b.tenant_id===t.tenantId);!v||!VY(v,n)||await p.notify({owner:{accountId:n,epoch:d.epoch},conversationId:t.conversationId,...f?{threadId:f}:{},...l?{messageId:l}:{},tenantId:t.tenantId,...a?{sender:a}:{},seq:t.seq,title:g.title,subtitle:g.subtitle,body:g.body,viewing:Sot()===t.conversationId}).catch(()=>{})}function Jot(e,t,n,s,r){wot(e,t,n,s);for(const i of s){const a=`${n}\0${i.conversation_id}`,o=r.get(a);if(r.set(a,i.latest_seq),o===void 0||i.latest_seq<=o)continue;const l=sI(e,i.conversation_id,n,t);e.getQueryState(l.queryKey)?.data!==void 0&&e.fetchQuery({...l,staleTime:0}).catch(()=>{})}}function Zot(e){const t=!!window.api?.desktop?.teamBridge,n=eI(),s=ZY(e&&t),r=n.accountId,a=e&&t&&!!r&&s.data?.account_id===r&&s.data?.state==="ready"&&s.data.local.enabled&&!s.data.read_only,o=Mt(),l=Nae({filters:{mutationKey:$t.notifyMutation(r,n.epoch),exact:!0,status:"pending"},select:H=>H.mutationId});m.useLayoutEffect(()=>{const H=window.api?.desktop?.teamBridge;if(!H?.setAuthority)return;const U=()=>{H.setAuthority({...$r(o),settling:qA(o)}).catch(()=>{})},z=zA(o,U);return U(),z},[o]);const u=vK({enabled:a}),d=ss(),f=Et(d.data,"settings"),p=Dn({...U5(),enabled:a&&f}),g=f&&Nie(p.data?.settings,$ot)===!1,v=m.useRef(g);v.current=g;const b=m.useRef(r);b.current=r;const x=m.useRef(a);x.current=a;const _=m.useRef(new AbortController);m.useEffect(()=>{const H=new AbortController;return _.current=H,(!a||g||n.token!==sp(o))&&H.abort(),()=>H.abort()},[a,g,n.token,o]),m.useEffect(()=>(x.current=a,()=>{x.current=!1}),[a]);const w=u.data,y=eX(a,Vu,{accountId:r,refetchInterval:gm,refetchIntervalInBackground:!0}),S=m.useMemo(()=>uot(y.data),[y.data]),C=tH({queries:S.map(H=>{const U=_E(H.tenant_id);return{queryKey:$t.unread(U,r??"unresolved-owner"),queryFn:()=>Ec(o,r,()=>_s.unread({tenantId:U})),enabled:a,staleTime:gm,refetchInterval:gm,refetchIntervalInBackground:!0,refetchOnWindowFocus:!0,retry:1}})}),E=C.map(H=>`${H.status}:${H.dataUpdatedAt}`).join("|"),k=m.useRef(C);k.current=C;const F=m.useRef(S);F.current=S;const I=Bot(S.map(H=>_E(H.tenant_id)),a,r).members,N={};for(const[H,U]of Object.entries(I))N[H]=U.filter(z=>z.account_id!==r).flatMap(z=>[iA(z,"person"),...z.agent?.name?[iA(z,"person_agent")]:[]]).filter(z=>z!==void 0);const P=JSON.stringify(N),M=m.useRef(N);M.current=N;const Y=m.useRef(null),O=m.useRef(new Set),X=Dn({queryKey:$t.conversations(Vu,r??"unresolved-owner"),queryFn:()=>Ec(o,r,()=>_s.listConversations("account")),enabled:a,staleTime:gm,refetchInterval:gm,refetchIntervalInBackground:!0,refetchOnWindowFocus:!0,retry:1}),Q=m.useRef(new Map),ie=m.useRef(new Map),G=m.useRef(new Set),ne=m.useRef(void 0),oe=m.useRef(null),B=[a,g,l.join(","),E,y.dataUpdatedAt,X.dataUpdatedAt,(w?.memberships??[]).map(H=>`${H.tenant_id}:${H.tenant_name}`).join(","),r??""].join("#");m.useEffect(()=>{if(Y.current===P)return;Y.current=P;const H=window.api?.desktop?.teamBridge;if(!H?.syncDirectory)return;const U=M.current;for(const z of O.current)z in U||H.syncDirectory({tenantId:z,members:[]}).catch(()=>{});O.current=new Set(Object.keys(U));for(const[z,te]of Object.entries(U))H.syncDirectory({tenantId:z,members:te}).catch(()=>{})},[P]),m.useEffect(()=>{const H=ne.current;ne.current=r,H!==r&&H!==void 0&&(Q.current=new Map,ie.current=new Map,G.current=new Set,oe.current=null,o.invalidateQueries({queryKey:$t.unreadPrefix}),o.invalidateQueries({queryKey:$t.conversationsPrefix}))},[r,o]),m.useEffect(()=>{if(oe.current===B||(oe.current=B,!y.data))return;for(const fe of y.data.organizations??[])fe.unread===0&&!G.current.has(fe.tenant_id)&&G.current.add(fe.tenant_id);if(!X.data)return;const H=k.current,U=F.current,z=Pie(w?.memberships??[],y.data.organizations,y.data.organizations??null);let te=Q.current;for(let fe=0;fe<U.length;fe+=1){const J=U[fe],Se=H[fe]?.data;if(!Se)continue;const W=(Se.conversations??[]).map(xe=>({conversation_id:xe.conversation_id,tenant_id:J.tenant_id,unread_count:xe.unread_count,last_read_seq:xe.last_read_seq,latest_seq:xe.latest_seq}));r&&Jot(o,r,J.tenant_id,Se.conversations??[],ie.current);const Ce=G.current.has(J.tenant_id),K=$r(o),me=W.filter(xe=>!Ce||!x.current||v.current||!K.accountId||K.accountId!==r?!0:!ZD(o,{accountId:K.accountId,epoch:K.epoch},xe.conversation_id,xe.tenant_id)),Ee=fot({conversations:X.data.conversations,rows:me,organizations:z,selfAccountId:r,cursors:te,seeded:Ce,quiet:!a||g});if(te=Ee.cursors,Ee.seeded&&G.current.add(J.tenant_id),!a||g||!r)continue;const Ae=r,se=sp(o),he=$Y(o,Ae);for(const xe of Ee.candidates)Qot(o,xe,Ae,()=>b.current===Ae&&sp(o)===se&&he()&&x.current&&!v.current&&kc(o,Ae),_.current.signal)}Q.current=te},[B,a,g,y.data,X.data,w,r,o])}function elt(){const{data:e}=ss();m.useEffect(()=>{e&&zX(e)},[e]);const t=jA(),n=Mt(),s=m.useRef(null);m.useEffect(()=>{const r=t.configChange;if(!r)return;const i=`${r.epoch}:${r.seq}`;s.current!==i&&r.changedKeys.includes(hl)&&(s.current=i,n.invalidateQueries({queryKey:No.capabilities}),n.invalidateQueries({queryKey:No.settings}),!Oie()&&da(h("ui.settings.language.external_notice",{language:r.language}),{id:"i18n-language-external"}))},[t.configChange,n])}function tlt(e,t){if(e.defaultPrevented||e.repeat||e.isComposing||!(e.metaKey||e.ctrlKey))return null;const n=$A(e);if(n===null)return null;const s=aZ(t.bindings).get(n);return s===void 0||pA(e.target)||!u0e(sX(s),t.route)?null:s}const sX=e=>e.slice(6);function nlt(e){const t=Fe.getState(),n=t.activeDraftKey?t.drafts[t.activeDraftKey]:void 0,s=Bv(t.activeDraftKey,n?.sessionId,t.activeSessionId)??null;Gd(sX(e),{sessionId:s,askScope:s===null?"fleet":"session",via:"chord"})}function slt(){m.useEffect(()=>{const e=t=>{const n=nt.getState(),s=tlt(t,{bindings:n.shortcutBindings,route:n.rightSlotRoute});s!==null&&(t.preventDefault(),nlt(s))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}function rlt(e,t){const n=ug(),s=m.useRef(!1);m.useEffect(()=>{s.current||!e||!n.accountId||window.__loDevDriver?.armed!==!0||window.__loDevDriver.startupScene!=="team-bridge-owner-audit"||(s.current=!0,t("/team-bridge"))},[e,n.accountId,t])}const ilt=""+new URL("radient-icon-1024x1024-D_JJedvo.png",import.meta.url).href,rX=sg()(l5(e=>({hasBeenNotified:!1,setHasBeenNotified:t=>{e({hasBeenNotified:t})}}),{name:"low-credits-storage"})),alt=({open:e,onClose:t,onGoToConsole:n})=>{Ve();const{setHasBeenNotified:s}=rX(),{prices:r,isLoading:i,error:a}=Lie(),o=d=>typeof d!="number"?"$...":h("ui.common.account.low_credits_dialog.detail",{detail:String(d.toFixed(2))}),l=()=>{s(!0),t()},u=()=>{s(!0),n()};return c.jsx(Ac,{open:e,onClose:l,title:c.jsxs(c.Fragment,{children:[c.jsx("img",{src:ilt,alt:h("ui.common.account.low_credits_dialog.radient_icon"),className:"size-7"}),h("ui.common.account.low_credits_dialog.running_low_on_radient_credits")]}),maxWidth:"sm",fullWidth:!1,actions:c.jsxs(c.Fragment,{children:[c.jsx(Uv,{onClick:l,children:h("ui.common.account.low_credits_dialog.maybe_later")}),c.jsx(Gv,{onClick:u,startIcon:c.jsx(wu,{size:18}),className:"min-w-55",children:h("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:[h("ui.common.account.low_credits_dialog.unlock_the_full_power_of_local_operator_with")," ",c.jsx("span",{className:"font-bold text-accent",children:h("ui.common.account.low_credits_dialog.radient_pass")}),"."]}),c.jsx("p",{className:"text-body-sm text-ink-muted",children:h("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:h("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:[h("ui.common.account.low_credits_dialog.plus_get")," ",c.jsx("span",{className:"font-medium text-ink",children:i?c.jsx(On,{size:"sm",className:"me-0.5 align-middle"}):o(r?.default_registration_credits)})," ",h("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:h("ui.common.account.low_credits_dialog.could_not_load_bonus_credit_information")})]}),c.jsx("p",{className:"text-meta text-ink-dim",children:h("ui.common.account.low_credits_dialog.you_can_also_reach_the_radient_console_from_settings_at_any_time")})]})})},olt=(e,t)=>t?Yk(e.filter(n=>n.session_id===t)).length:0;function llt(e){return Fe(t=>olt(t.sessions,e))}const clt=(e,t)=>t?e.some(n=>n.session_id===t&&n.status?.code==="busy"):!1;function ult(e){return Fe(t=>clt(t.sessions,e))}const dlt=[];function hlt(){const{state:e}=Yy(),t=e?.pendingConsent??dlt,n=uG(s=>XM(t,s));return m.useEffect(()=>{t.length>0&&S2()},[t]),XM(t,n)}const iX={approvals:["desktop","mesh","approvals"]},flt=15e3,plt=new Set(["requested","approved","connecting","failed"]);function glt(e){return plt.has(e)}function mlt(e){return e==="requested"}function vlt(e){return e.filter(t=>mlt(t.state)).length}function xht(e){return e.state==="requested"&&e.canApproveHere!==!1&&(e.kind==="device"||e.kind==="machine")}function _ht(e){return glt(e)}function wht(e){switch(e){case"requested":return h("ui.mesh.mesh_approvals.waiting_for_you");case"approved":return h("ui.mesh.mesh_approvals.approved");case"connecting":return h("ui.mesh.mesh_approvals.connecting");case"connected":return h("ui.mesh.mesh_approvals.connected");case"denied":return h("ui.mesh.mesh_approvals.denied");case"expired":return h("ui.mesh.mesh_approvals.expired");case"failed":return h("ui.mesh.mesh_approvals.failed");default:return e}}function xu(e){return typeof e=="object"&&e!==null}function blt(e){const t=xu(e)?e:{};return{deviceId:qn(t.device_id),name:qn(t.name),host:qn(t.host),user:qn(t.user),transport:qn(t.transport),hostKeyFp:qn(t.host_key_fp)}}function xlt(e){const t=xu(e)?e:{};return{connect:n1(t.connect,!1),install:n1(t.install,!1),anchor:xu(t.anchor),networkId:qn(t.network_id),role:qn(t.role),unattended:n1(t.unattended,!1),grants:eE(t.grant)}}function _lt(e){const t=Array.isArray(e)?e:e?.approvals??[];if(!Array.isArray(t))return[];const n=[];for(const s of t){if(!xu(s))continue;const r=qn(s.approval_id),i=qn(s.state);if(!r||!i)continue;const a=xu(s.what)&&Object.prototype.hasOwnProperty.call(s.what,"credential_inheritance"),o=Object.prototype.hasOwnProperty.call(s,"kind")?qn(s.kind):void 0,l=a||o==="credential_inheritance"?"credential":o!==void 0&&!["device_onboard","local_authority"].includes(o)?"unknown":!xu(s.device)&&xu(s.machine)?"machine":"device",u=xu(s.requested_by)?s.requested_by:{};n.push({approvalId:r,state:i,kind:l,summary:qn(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:qn(s.approve_remedy)||void 0,where:blt(l==="machine"?s.machine:s.device),what:xlt(s.what),requestedBy:{surface:qn(u.surface),sessionId:qn(u.session_id),deviceId:qn(u.device_id)},expiresAt:oZ(s.expires_at)})}return n}function wlt(e){return e.kind==="machine"?h("ui.mesh.mesh_approvals.this_machine"):Zk({device_id:e.where.deviceId,name:e.where.name})}function yht(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 U6(e)}const n=U6(e),s=Clt(e,t).map(r=>r.clause);return s.length?h("ui.mesh.mesh_approvals.approval_title_with_clauses",{head:n,clauses:ylt(s)}):h("ui.mesh.mesh_approvals.approval_title",{head:n})}function U6(e){return e.kind==="credential"?e.summary||h("ui.mesh.approval.credential_title"):e.kind==="unknown"?e.summary||h("ui.mesh.approval.unknown_title"):e.canApproveHere===!1&&e.summary?e.summary:e.kind==="machine"?h("ui.mesh.mesh_approvals.set_up_operator_authority_on_this_machine"):h("ui.mesh.mesh_approvals.onboard_subject",{subject:wlt(e)})}function ylt(e){return e.length===1?e[0]:h("ui.mesh.mesh_approvals.join_clauses",{clauses:e.slice(0,-1).join(", "),last:e[e.length-1]})}function Cht(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?h("ui.mesh.mesh_approvals.via_transport",{transport:s}):"",r&&r!==n?`(${r})`:""].filter(Boolean);return i.length?i.join(" "):null}function Sht(e){return e.kind==="credential"||e.kind==="unknown"?null:e.where.hostKeyFp||null}function kht(e){const{surface:t,sessionId:n}=e.requestedBy,s=[t||"",n?h("ui.mesh.mesh_approvals.session_suffix",{suffix:n.slice(-6)}):""].filter(Boolean);return s.length?h("ui.mesh.mesh_approvals.asked_by",{requester:s.join(" · ")}):null}function Clt(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?h("ui.mesh.mesh_approvals.connect_over",{transport:e.where.transport}):h("ui.mesh.mesh_approvals.connect_to_it"),consequence:e.where.transport?h("ui.mesh.mesh_approvals.may_connect_over",{transport:e.where.transport}):h("ui.mesh.mesh_approvals.this_machine_may_connect_to_it")}),s&&u.push({term:"install",clause:e.kind==="machine"?h("ui.mesh.mesh_approvals.install_local_operator"):h("ui.mesh.mesh_approvals.install_local_operator_there"),consequence:e.kind==="machine"?h("ui.mesh.mesh_approvals.local_operator_is_installed_on_this_machine"):h("ui.mesh.mesh_approvals.local_operator_is_installed_on_it")}),r&&u.push({term:h("ui.mesh.mesh_approvals.install_operator_anchor"),clause:h("ui.mesh.mesh_approvals.check_approvals_signed_on_your_machines"),consequence:h("ui.mesh.mesh_approvals.that_device_can_check_approvals_signed_on")}),i){const d=t?.get(i),f=h("ui.mesh.mesh_approvals.join_network",{network:d||i,role:a||"?"});u.push({term:f,clause:f,consequence:h("ui.mesh.mesh_approvals.joins_network",{network:d||i,role:a||"?"})})}o&&u.push({term:h("ui.mesh.mesh_approvals.trust_unattended_sessions"),clause:h("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt"),consequence:h("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")});for(const d of Slt(l,o)){const f=klt()[d];u.push({term:f?.term??h("ui.mesh.mesh_approvals.grant_capability",{grant:d}),clause:Elt()[d]??h("ui.mesh.mesh_approvals.use_capability",{grant:d}),consequence:f?.gloss??h("ui.mesh.mesh_approvals.may_use_capability",{grant:d})})}return u}function Slt(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 klt=()=>({unattended:{term:h("ui.mesh.mesh_approvals.trust_unattended_sessions"),gloss:h("ui.mesh.mesh_approvals.sessions_you_start_on_that_device_run")},broker_credential:{term:h("ui.mesh.mesh_approvals.borrow_logins_there"),gloss:h("ui.mesh.mesh_approvals.your_sessions_may_use_the_logins_stored")}}),Elt=()=>({list:h("ui.mesh.mesh_approvals.see_its_sessions"),view:h("ui.mesh.mesh_approvals.watch_a_session_there"),prompt:h("ui.mesh.mesh_approvals.send_prompts_to_a_session_there"),steer:h("ui.mesh.mesh_approvals.steer_a_running_turn_there"),stop:h("ui.mesh.mesh_approvals.stop_a_session_there"),slash:h("ui.mesh.mesh_approvals.run_slash_commands_there"),delete:h("ui.mesh.mesh_approvals.archive_or_delete_a_session_there"),move:h("ui.mesh.mesh_approvals.move_sessions_to_or_from_there"),broker_credential:h("ui.mesh.mesh_approvals.borrow_the_logins_stored_there"),approve:h("ui.mesh.mesh_approvals.answer_approval_prompts_there"),unattended:h("ui.mesh.mesh_approvals.run_sessions_there_without_an_approval_prompt")});function Eht(e,t){if(e===null||e<=0)return null;const n=e-t;if(n<=0)return null;if(n<60)return h("ui.mesh.mesh_approvals.expires_in_under_a_minute");const s=Math.ceil(n/60);if(s<90)return h("ui.mesh.mesh_approvals.expires_minutes",{count:s});const r=Math.ceil(s/60);return h("ui.mesh.mesh_approvals.expires_hours",{count:r})}function Tlt(e,{poll:t=!0}={}){return Dn({queryKey:iX.approvals,enabled:e,queryFn:async()=>_lt(await rt({op:"approvals.list"})),retry:!1,staleTime:t?1e4:Number.POSITIVE_INFINITY,refetchInterval:e&&t?flt:!1,refetchOnWindowFocus:t})}function Tht(){const e=Mt();return fn({mutationFn:async t=>{const n=t.decision==="approve"?{op:"approvals.approve",approvalId:t.approvalId}:{op:"approvals.deny",approvalId:t.approvalId};await rt(n)},onSettled:()=>{e.invalidateQueries({queryKey:iX.approvals}),e.invalidateQueries({queryKey:xc.networks}),e.invalidateQueries({queryKey:xc.peers})}})}function Rht(e){const t=e?.message;return typeof t=="string"&&t.trim()?t.trim():h("ui.mesh.mesh_approvals.the_approvals_could_not_be_read")}function Aht(e){const t=e;return{code:qn(t?.code)||"approval_refused",sentence:qn(t?.message)||h("ui.mesh.mesh_approvals.decision_could_not_be_answered")}}const Rlt="/team-bridge",Alt="nav-team-bridge",Flt="nav-team-bridge-badge";function Dlt(e){const{accountId:t}=eI(),n=ZY(e),s=e&&!!t&&n.data?.account_id===t,r=eX(s,Vu,{accountId:t}),i=_ot(s?t:void 0);if(!e)return null;const a=s&&r.data?i.total:0;return{icon:P0,label:h("ui.teamBridge.nav.label"),path:Rlt,tourTag:Alt,attention:a,attentionTag:Flt,attentionName:o=>h("ui.teamBridge.nav.unread",{count:o})}}const aA={aida:"visible",notifications:"visible",library:"visible",projects:"visible",agents:"visible",schedules:"more",browser:"visible","team-bridge":"more","agent-hub":"more",mesh:"more"},cy=["aida","notifications","library","projects","agents","schedules","browser","team-bridge","agent-hub","mesh"],uy={visible:cy.filter(e=>aA[e]==="visible"),more:cy.filter(e=>aA[e]==="more")},G6=new Map(cy.map((e,t)=>[e,t])),Ilt=new Map([["notifications","notifications"]]);function Nlt(e,t){const n=s=>{const r=Ilt.get(s);return r===void 0||t(r)};return{visible:e.visible.filter(n),more:e.more.filter(n)}}const Plt=new Set(lZ);function Mlt(e){return typeof e=="string"&&Plt.has(e)}function qk(e,t){if(e===t)return!0;if(e.visible.length!==t.visible.length||e.more.length!==t.more.length)return!1;for(let n=0;n<e.visible.length;n+=1)if(e.visible[n]!==t.visible[n])return!1;for(let n=0;n<e.more.length;n+=1)if(e.more[n]!==t.more[n])return!1;return!0}function xo(e,t){return e.visible.includes(t)?"visible":"more"}function __(e,t,n){return e[t].filter(s=>n.has(s))}function Olt(e,t,n,s){if(!s.has(t))return null;const r=xo(e,t),i=__(e,r,s),a=i.indexOf(t);if(a<0)return null;const o=a+n;if(o<0||o>=i.length)return null;const l=i[o],u=e[r],d=u.indexOf(t),f=u.indexOf(l);if(d<0||f<0)return null;const p=u.slice();p[d]=l,p[f]=t;const g={visible:e.visible.slice(),more:e.more.slice()};return g[r]=p,g}function V6(e,t,n){const s={visible:e.visible.filter(r=>r!==t),more:e.more.filter(r=>r!==t)};return{...s,[n]:[...s[n],t]}}function Llt(e,t,n,s,r){if(s===t)return{visible:e.visible.slice(),more:e.more.slice()};if(s!==null&&(!r.has(s)||!e[n].includes(s)))return null;const i={visible:e.visible.filter(l=>l!==t),more:e.more.filter(l=>l!==t)},a=i[n].slice(),o=s===null?a.length:a.indexOf(s);return o<0?null:(a.splice(o,0,t),{...i,[n]:a})}function W6(e,t){for(const n of cy){if(aA[n]!==t||e.visible.includes(n)||e.more.includes(n))continue;const s=G6.get(n)??0,r=e[t];let i=-1,a=-1,o=-1,l=Number.POSITIVE_INFINITY;for(let d=0;d<r.length;d+=1){const f=G6.get(r[d])??0;f<s&&f>a&&(a=f,i=d),f>s&&f<l&&(l=f,o=d)}const u=i>=0?i+1:o>=0?o:r.length;r.splice(u,0,n)}}function oA(e){const t={visible:[],more:[]},n=new Set;if(e&&typeof e=="object"){const s=e;for(const r of["visible","more"]){const i=s[r];if(Array.isArray(i))for(const a of i)Mlt(a)&&(n.has(a)||(n.add(a),t[r].push(a)))}}return W6(t,"visible"),W6(t,"more"),t}function Blt(e){return e.reduce((t,n)=>{const s=n.attention??0;return Number.isFinite(s)&&s>0?t+s:t},0)}const If={layout:["desktop","sidebar_layout"]};async function jlt(){const e=await rt({op:"sidebar_layout.get"});return oA(e.layout)}function Hlt(e,t=()=>!1){const n=Mt(),s=Dn({queryKey:If.layout,enabled:e,queryFn:jlt,staleTime:Number.POSITIVE_INFINITY,retry:Mv}),r=m.useRef(0),i=fn({scope:{id:"sidebar-layout"},mutationFn:async d=>{const f=await rt({op:"sidebar_layout.set",layout:Nlt(d,t)});return oA(f.layout)},retry:cZ,onMutate:async d=>{const f=++r.current;await n.cancelQueries({queryKey:If.layout});const p=n.getQueryData(If.layout);return n.setQueryData(If.layout,d),{previous:p,seq:f}},onError:(d,f,p)=>{p?.seq===r.current&&p.previous&&n.setQueryData(If.layout,p.previous),nn(h("ui.shell.sidebar_navigation.save_failed"))},onSettled:(d,f,p,g)=>{g?.seq===r.current&&n.invalidateQueries({queryKey:If.layout})}}),a=e&&s.data!==void 0;return{layout:a?s.data:uy,canCustomise:a,save:d=>{a&&i.mutate(d)},reset:()=>{a&&i.mutate(oA(uy))}}}const $6=e=>{const t=Hie(e.type),n=typeof e.percent=="number"?`, ${Math.round(e.percent)}%`:"";return h("ui.common.updates.update_foot_icon.in_progress",{subject:t,percent:n})},aX=e=>jie({type:e.type,version:e.offer.version}),Ult=e=>{const t=e.map(s=>aX(s)),n=t.slice(1).reduce((s,r)=>h("ui.common.updates.update_foot_icon.subject_join",{left:s,right:`${r.charAt(0).toLowerCase()}${r.slice(1)}`}),t[0]);return h("ui.common.updates.update_foot_icon.available_show_the_update_notice",{joined:n})},Glt=({surfaces:e,inflight:t,onShow:n,onDismiss:s})=>{if(Ve(),t===null&&e.length===0)return null;if(t!==null)return c.jsx(vt,{side:"top",collisionPadding:8,content:$6(t),children:c.jsx("output",{"data-update-foot-icon":"","data-update-foot-icon-state":"inflight","aria-label":$6(t),className:"flex size-8 shrink-0 items-center justify-center text-accent",children:c.jsx(ri,{className:"size-4 shrink-0 motion-safe:animate-spin","aria-hidden":"true"})})});const r=e.find(i=>(i.offer.summary??"").trim()!=="");return c.jsx(vt,{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:[aX(i)," ",h("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:h("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":Ult(e),onClick:n,onKeyDown:i=>{i.key!=="Escape"||!s||(i.stopPropagation(),s())},className:R("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(BA,{className:"size-4 shrink-0","aria-hidden":"true"})})})},z6=()=>{const e=kr(g=>g.followed),t=kr(g=>g.running),n=kr(g=>g.offers),s=kr(g=>g.detailOpen),r=kr(g=>g.inflight),i=kr(g=>g.downloadPercent),a=kr(g=>g.openNotice),o=kr(g=>g.noticeOpen),l=kr(g=>g.dismissNotice),u=m.useMemo(()=>{const g={followed:e,running:t,offers:n,detailOpen:s};return N5.filter(v=>Bie(g,v)).map(v=>{const b=n[v];return b?{type:v,offer:b}:null}).filter(v=>v!==null)},[e,t,n,s]),d=m.useMemo(()=>r[Rn.BACKEND]?{type:Rn.BACKEND,percent:null}:r[Rn.UI]?{type:Rn.UI,percent:i[Rn.UI]}:null,[r,i]),f=m.useCallback(()=>a(),[a]),p=m.useCallback(()=>l(),[l]);return c.jsx(Glt,{surfaces:u,inflight:d,onShow:f,onDismiss:o?p:void 0})},q6=({expanded:e})=>(Ve(),c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(V5,{className:"size-6",label:e?void 0:h("ui.shell.collapsible_app_logo.local_operator")}),e&&c.jsx("span",{className:"truncate font-semibold text-body text-ink",children:h("ui.shell.collapsible_app_logo.local_operator")})]})),lA=it.memo(({expanded:e,useAuth:t=!1})=>{const n=yA(),s=oi(),{user:r,isAuthenticated:i,accountRead:a,signOut:o}=Oy(),l=a==="checking"?h("ui.shell.user_profile_sidebar.checking_account"):WN(a)?h("ui.shell.user_profile_sidebar.account_unavailable"):null,u=r?.name??l??h("ui.shell.user_profile_sidebar.user"),d=WN(a),f=r?.email??"",p=d?h("ui.shell.user_profile_sidebar.reconnect_radient"):f,g=d?"/settings?section=providers&provider=radient":"/settings",v=d?h("ui.shell.user_profile_sidebar.reconnect_radient"):h("ui.shell.user_profile_sidebar.account_settings"),b=m.useCallback(async()=>{i&&(await o(),window.location.reload())},[i,o]),x=m.useMemo(()=>{const S=r?.name;return S?S.split(" ").map(C=>C.charAt(0)).join("").toUpperCase().substring(0,2):null},[r?.name]),_=Wat(r?.radientUser.account,64),w=c.jsxs("button",{type:"button",onClick:t?void 0:()=>s(g),"aria-label":e?void 0:v,className:R("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.jsxs(F5,{className:"size-7 shrink-0 rounded-md bg-media-surface",children:[_&&c.jsx(xy,{src:_,alt:"",className:"lo-avatar-arrival"}),c.jsx(_y,{className:"rounded-md bg-media-surface text-ink-muted",children:x??c.jsx(Dde,{size:14,"aria-hidden":"true"})})]}),e&&u&&c.jsxs("span",{className:"min-w-0 text-start",children:[c.jsx("span",{className:"block truncate text-body-sm text-ink",children:u}),p&&c.jsx("span",{className:R("block truncate text-meta",d?"text-accent":"text-ink-dim"),children:p})]})]}),y=e?w:c.jsx(Ld,{content:v,side:n==="rtl"?"left":"right",children:w});return t?c.jsxs(Po,{children:[e?c.jsx(eo,{asChild:!0,children:w}):c.jsx(Ld,{content:v,side:n==="rtl"?"left":"right",children:c.jsx(eo,{asChild:!0,children:w})}),c.jsxs(Mo,{align:"end",side:"top",className:"min-w-50",children:[d?c.jsxs(Jt,{onSelect:()=>s(g),children:[c.jsx(T5,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.reconnect_radient")]}):null,c.jsxs(Jt,{onSelect:()=>s("/settings"),children:[c.jsx(Su,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.settings")]}),c.jsxs(Jt,{children:[c.jsx(Zue,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.privacy_and_security")]}),c.jsx(Nr,{}),c.jsxs(Jt,{onSelect:b,className:"text-danger focus:bg-danger-wash focus:text-danger",children:[c.jsx(Cue,{size:16,"aria-hidden":"true"}),h("ui.shell.user_profile_sidebar.sign_out")]})]})]}):y});lA.displayName="UserProfileSidebar";const Vlt=()=>{const e=jA(),t=ss(),n=Fe(u=>u.setCataloguePageable),s=Fe(u=>u.setCatalogueActivityHead),r=Fe(u=>u.fetchSessions),i=Et(t.data,"session_catalogue_page"),a=Et(t.data,"session_catalogue_sort");m.useEffect(()=>{n(i)},[i,n]),m.useEffect(()=>{s(a)},[a,s]);const o=Gr(t.data,"session_catalogue",2)==="enabled",l=m.useCallback(()=>r(i?x5:fy,i),[r,i]);return m.useEffect(()=>{o&&l()},[o,l,e.catalogueRevision]),null},K6="flex h-[30px] w-full items-center gap-2 rounded-md px-2 text-body-sm transition-colors duration-fast ease-out-quart",Wlt=()=>{Ve();const e=yA()==="rtl",t=oi(),n=bfe(),{expanded:s,onCollapse:r}=Uie(),i=nt(ae=>ae.openCommandPalette),a=ss(),o=Dlt(Et(a.data,"team_bridge_conversations")),l=Fe(ae=>ae.activeSessionId),u=hlt(),d=Gr(a.data,"peers")==="enabled",f=I2(d),p=Gr(a.data,"approvals")==="enabled",g=Tlt(f==="member"&&p,{poll:!0}),v=vlt(g.data??[]),b=Et(a.data,"projects",1),x=Et(a.data,"library",1),_=Et(a.data,"notifications",1),w=Gie(_),y=_?Vie(w.data):0,S=nt(ae=>ae.sidebarOverflowExpanded),C=nt(ae=>ae.setSidebarOverflowExpanded),E=Et(a.data,"aida",1),k=fg(E),F=E&&k.data?.enabled===!0,A=k.data?.name??"Aida",I=vpe(),N=llt(k.data?.session_id),P=ult(k.data?.session_id),M=()=>{I(t,k.data).catch(ae=>nn(Lf(ae)))},Y=new Map;F&&Y.set("aida",{icon:Wie,label:A,path:"/chat",isActive:n==="chat"&&!!k.data?.session_id&&l===k.data?.session_id,tourTag:"nav-item-aida",onSelect:M,attention:N,attentionTag:"nav-aida-badge",attentionName:ae=>h("ui.shell.sidebar_navigation.aida_missed",{name:A,count:ae}),working:P,workingName:h("ui.shell.sidebar_navigation.aida_working",{name:A})}),_&&Y.set("notifications",{icon:_ce,label:h("ui.notifications.nav.label"),path:"/notifications",isActive:n==="notifications",tourTag:"nav-item-notifications",attention:y,attentionTag:"nav-notifications-badge",attentionName:ae=>h("ui.notifications.nav.unread",{count:ae,countText:String(ae)})}),x&&Y.set("library",{icon:due,label:h("ui.library.page.title"),path:"/library",isActive:n==="library",tourTag:"nav-item-library"}),b&&Y.set("projects",{icon:mU,label:h("ui.shell.sidebar_navigation.projects"),path:"/projects",isActive:n==="projects",tourTag:"nav-item-projects"}),Y.set("agents",{icon:yl,label:h("ui.shell.sidebar_navigation.agents"),path:"/agents",isActive:n==="agents",tourTag:"nav-item-agents"}),Y.set("schedules",{icon:pU,label:h("ui.shell.sidebar_navigation.schedules"),path:"/schedules",isActive:n==="schedules",tourTag:"nav-item-schedules"}),Y.set("browser",{icon:Uu,label:h("ui.shell.sidebar_navigation.browser"),path:"/browser",isActive:n==="browser",tourTag:"nav-item-browser",attention:u,attentionTag:"nav-browser-badge",attentionName:ae=>h("ui.shell.sidebar_navigation.browser_waiting",{count:ae,countText:String(ae)})}),o&&Y.set("team-bridge",{...o,isActive:n==="team-bridge"}),Y.set("agent-hub",{icon:CU,label:h("ui.shell.sidebar_navigation.agent_hub"),path:"/agent-hub",isActive:n==="agent-hub",tourTag:"nav-item-agent-hub"}),f==="member"&&Y.set("mesh",{icon:L8,label:h("ui.shell.sidebar_navigation.mesh"),path:"/mesh",isActive:n==="mesh",tourTag:"nav-item-mesh",attention:v,attentionTag:"nav-mesh-badge",attentionName:ae=>h("ui.shell.sidebar_navigation.mesh_waiting",{count:ae,countText:String(ae)})});const O=new Set(Y.keys()),X=Et(a.data,"sidebar_layout",1),{layout:Q,canCustomise:ie,save:G,reset:ne}=Hlt(X,ae=>Et(a.data,ae,1)),oe=ie?Q:uy,B=__(oe,"visible",O),H=__(oe,"more",O),[U,z]=m.useState(!1),te=S||U||H.some(ae=>Y.get(ae)?.isActive),[fe,J]=m.useState(""),[Se,W]=m.useState(null),Ce=m.useRef(new Map),K=ae=>{requestAnimationFrame(()=>Ce.current.get(ae)?.focus())},[me,Ee]=m.useState(null),[Ae,se]=m.useState(null),he=m.useRef(null),xe=m.useRef(null),Je=m.useRef(null),pe=m.useRef(0),Xe=m.useRef(0),le=m.useRef(null),Qe=m.useRef(null),et=m.useRef(!1),ue=ae=>{const we=he.current;return we===null?[]:Array.from(we.querySelectorAll("[data-sidebar-row]")).filter(De=>De.dataset.sidebarRow!==ae).map(De=>{const $e=De.getBoundingClientRect();return{id:De.dataset.sidebarRow??"",top:$e.top,bottom:$e.bottom}})},Le=(ae,we)=>{const De=he.current;if(De===null)return null;const $e=De.getBoundingClientRect(),ke=ue(we),tt=Ot=>ke.filter(Ut=>xo(oe,Ut.id)===Ot);let ht=null;if(ae.kind==="more"){const Ot=tt("more").at(-1);if(Ot)ht=Ot.bottom;else{const Ut=De.querySelector("[data-sidebar-more]");ht=Ut?Ut.getBoundingClientRect().bottom:$e.top+2}}else if(ae.kind==="band"){const Ot=xo(oe,we),en=tt(Ot==="more"?"visible":"more").at(-1);if(en)ht=en.bottom;else if(Ot==="more"){const yn=De.querySelector("[data-sidebar-more]");ht=yn?yn.getBoundingClientRect().top:$e.top+2}}else{const Ot=ke[ae.slot];Ot?ht=Ot.top:ht=ke.at(-1)?.bottom??$e.top+2}return ht===null?null:Math.round(ht-$e.top+De.scrollTop)},Ne=()=>{Qe.current!==null&&(window.clearTimeout(Qe.current),Qe.current=null)},Ue=(ae,we)=>{const De=xe.current;if(De===null||!De.armed)return;const $e=document.elementFromPoint(ae,we),ke=!!$e?.closest("[data-sidebar-more]"),tt=!!$e?.closest("[data-sidebar-drop-band]");let ht;if(ke)ht={kind:"more"},xo(oe,De.id)==="visible"&&!te&&Qe.current===null&&(Qe.current=window.setTimeout(()=>{Qe.current=null,z(!0),requestAnimationFrame(()=>dt.current(pe.current,Xe.current))},400));else if(Ne(),tt)ht={kind:"band"};else{const Ot=ue(De.id),Ut=aK(Ot,De.id,we),en=Ot[Ut];let yn="visible";if(en)yn=xo(oe,en.id);else{const wn=Ot.at(-1);yn=wn?xo(oe,wn.id):"visible"}ht={kind:"slot",slot:Ut,beforeId:en?.id??null,region:yn}}Je.current=ht,se(Le(ht,De.id))},dt=m.useRef(Ue);dt.current=Ue;const St=()=>{le.current!==null&&(cancelAnimationFrame(le.current),le.current=null)},Dt=()=>{le.current=null;const ae=xe.current,we=he.current;if(ae===null||!ae.armed||we===null)return;const De=we.getBoundingClientRect(),$e=Xe.current,ke=we.scrollHeight-we.clientHeight;let tt=0;$e-De.top<24&&we.scrollTop>0?tt=-1:De.bottom-$e<24&&we.scrollTop<ke&&(tt=1),tt!==0&&(we.scrollTop+=tt*8,dt.current(pe.current,$e)),le.current=requestAnimationFrame(Dt)},sn=(ae,we)=>{if(ie&&we.button===0&&!(we.altKey||we.ctrlKey||we.metaKey||we.shiftKey)){try{we.currentTarget.setPointerCapture(we.pointerId)}catch{}xe.current={pointerId:we.pointerId,id:ae,armed:!1,startX:we.clientX,startY:we.clientY},pe.current=we.clientX,Xe.current=we.clientY}},Kt=ae=>{const we=xe.current;if(!(we===null||we.pointerId!==ae.pointerId)){if(pe.current=ae.clientX,Xe.current=ae.clientY,!we.armed){if(Math.hypot(ae.clientX-we.startX,ae.clientY-we.startY)<5)return;we.armed=!0,et.current=!0,Ee(we.id);const De=Y.get(we.id);De&&J(h("ui.shell.sidebar_navigation.drag_armed",{name:De.label})),le.current===null&&(le.current=requestAnimationFrame(Dt))}Ue(ae.clientX,ae.clientY)}},ut=(ae,we)=>{if(we.kind==="slot")return Llt(oe,ae,we.region,we.beforeId,O);const De=xo(oe,ae),$e=we.kind==="more"?"more":De==="more"?"visible":"more";return V6(oe,ae,$e)},Ft=(ae,we)=>{const De=Y.get(ae);if(De===void 0)return;const $e=ut(ae,we);if($e===null||qk($e,oe))return;const ke=xo($e,ae);if(ke==="more"&&C(!0),G($e),we.kind==="slot"){At($e,ae);return}J(ke==="more"?h("ui.shell.sidebar_navigation.move_to_more_note",{name:De.label}):h("ui.shell.sidebar_navigation.show_in_sidebar_note",{name:De.label}))},At=(ae,we)=>{const De=Y.get(we),$e=xo(ae,we),ke=__(ae,$e,O);J(h("ui.shell.sidebar_navigation.move_note",{name:De?.label??"",position:String(ke.indexOf(we)+1),total:String(ke.length)}))},cn=(ae,we=!1)=>{const De=xe.current;if(De===null)return;xe.current=null,St(),Ne();const $e=Je.current;if(Je.current=null,Ee(null),se(null),z(!1),!!De.armed){if(!ae){if(we){et.current=!1,J("");return}const ke=()=>{et.current=!1},tt=()=>{window.setTimeout(ke,0)},ht=()=>{window.removeEventListener("pointerup",Ot,!0),window.removeEventListener("pointercancel",Ut,!0),window.removeEventListener("blur",Ut,!0)},Ot=()=>{ht(),tt()},Ut=()=>{ht(),ke()};window.addEventListener("pointerup",Ot,!0),window.addEventListener("pointercancel",Ut,!0),window.addEventListener("blur",Ut,!0),J("");return}window.setTimeout(()=>{et.current=!1},0),$e!==null&&Ft(De.id,$e)}},rn=m.useRef(cn);rn.current=cn,m.useEffect(()=>{if(me===null)return;const ae=$e=>{$e.key==="Escape"&&(rn.current(!1),$e.preventDefault())},we=$e=>{xe.current?.pointerId===$e.pointerId&&rn.current(!0)},De=()=>rn.current(!1,!0);return window.addEventListener("keydown",ae),window.addEventListener("pointerup",we),window.addEventListener("pointercancel",De),window.addEventListener("blur",De),()=>{window.removeEventListener("keydown",ae),window.removeEventListener("pointerup",we),window.removeEventListener("pointercancel",De),window.removeEventListener("blur",De)}},[me]),m.useEffect(()=>()=>{le.current!==null&&cancelAnimationFrame(le.current),Qe.current!==null&&window.clearTimeout(Qe.current)},[]);const kn=(ae,we)=>{if(!ie)return;const De=Y.get(ae);if(De===void 0)return;if(we.kind==="reset"){ne(),J(h("ui.shell.sidebar_navigation.reset_note")),K(ae);return}if(we.kind==="move"){const ke=Olt(oe,ae,we.delta,O);if(ke===null)return;G(ke),At(ke,ae),K(ae);return}const $e=V6(oe,ae,we.region);qk($e,oe)||(we.region==="more"&&C(!0),G($e),J(we.region==="more"?h("ui.shell.sidebar_navigation.move_to_more_note",{name:De.label}):h("ui.shell.sidebar_navigation.show_in_sidebar_note",{name:De.label})),K(ae))},ws=c.jsx(MZe,{selectedConversation:l??void 0,onSelectConversation:ae=>void dg(t,ae),onStageDraft:(ae,we)=>{Fe.getState().stageDraft(ae,we),t("/chat")}}),Vt=ae=>{const we=ae.attention??0,De=we>0&&ae.attentionName?ae.attentionName(we):ae.label;return ae.working&&ae.workingName?ae.workingName:De},cs=ae=>{const we=Y.get(ae);if(we===void 0)return null;const De=xo(oe,ae),$e=De==="more"?H:B,ke=$e.indexOf(ae),tt=ke<=0,ht=ke===-1||ke>=$e.length-1,Ot=we.attention??0,Ut=Vt(we),en=me===ae,yn=e?"left":"right",wn=we.isActive?yo:"text-ink-muted hover:bg-row-hover hover:text-ink",Ps=c.jsx(we.icon,{size:16,"aria-hidden":"true",className:R("shrink-0",we.isActive&&"text-accent")}),ys=c.jsxs("button",{type:"button",ref:an=>{an?Ce.current.set(ae,an):Ce.current.delete(ae)},onClick:()=>{if(et.current){et.current=!1;return}we.onSelect?we.onSelect():t(we.path)},onPointerDown:ie?an=>sn(ae,an):void 0,onPointerMove:ie?Kt:void 0,onPointerUp:ie?an=>{xe.current?.pointerId===an.pointerId&&cn(!0)}:void 0,onPointerCancel:ie?()=>cn(!1,!0):void 0,onKeyDown:ie?an=>{if(an.key==="ContextMenu"||an.shiftKey&&an.key==="F10"){an.preventDefault(),W(ae);return}an.altKey&&(an.key!=="ArrowUp"&&an.key!=="ArrowDown"||(an.preventDefault(),kn(ae,{kind:"move",delta:an.key==="ArrowUp"?-1:1})))}:void 0,"data-tour-tag":we.tourTag,"aria-current":we.isActive?"page":void 0,"aria-haspopup":ie?"menu":void 0,"aria-label":s&&Ut===we.label?void 0:Ut,className:R("flex h-full min-w-0 flex-1 items-center gap-2 rounded-md",s?"px-2":"justify-center px-0"),children:[s?Ps:c.jsxs("span",{className:"relative flex size-7 shrink-0 items-center justify-center",children:[Ps,Ot>0&&c.jsx("span",{className:"pointer-events-none absolute -top-1 -end-1.5 flex",children:c.jsx(Ib,{count:Ot,placement:"corner","data-tour-tag":we.attentionTag})})]}),!s&&we.working&&c.jsx("span",{className:"inline-flex",children:c.jsx(ri,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})}),s&&c.jsx("span",{className:"truncate",children:we.label})]}),Ts=ie?c.jsxs(Po,{open:Se===ae,onOpenChange:an=>W(an?ae:null),children:[c.jsx(eo,{asChild:!0,children:s?c.jsx("button",{type:"button","data-sidebar-row-menu":"","aria-label":h("ui.shell.sidebar_navigation.row_actions",{name:we.label}),className:R("me-0.5 flex size-6 shrink-0 items-center justify-center rounded-sm","text-ink-muted opacity-0 transition-opacity duration-fast ease-out-quart","hover:bg-row-hover hover:text-ink","group-hover/row:opacity-100 group-focus-within/row:opacity-100","focus-visible:opacity-100 data-[state=open]:opacity-100",me!==null&&"pointer-events-none opacity-0!"),children:c.jsx(oc,{size:16,"aria-hidden":"true"})}):c.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-1 end-0 w-0"})}),c.jsxs(Mo,{align:"start",side:yn,sideOffset:s?6:16,className:"min-w-44",onCloseAutoFocus:an=>{an.preventDefault(),K(ae)},children:[c.jsx(Jt,{disabled:tt,onSelect:()=>kn(ae,{kind:"move",delta:-1}),children:h("ui.shell.sidebar_navigation.move_up")}),c.jsx(Jt,{disabled:ht,onSelect:()=>kn(ae,{kind:"move",delta:1}),children:h("ui.shell.sidebar_navigation.move_down")}),c.jsx(Nr,{}),De==="more"?c.jsx(Jt,{onSelect:()=>kn(ae,{kind:"region",region:"visible"}),children:h("ui.shell.sidebar_navigation.show_in_sidebar")}):c.jsx(Jt,{onSelect:()=>kn(ae,{kind:"region",region:"more"}),children:h("ui.shell.sidebar_navigation.move_to_more")}),!qk(oe,uy)&&c.jsxs(c.Fragment,{children:[c.jsx(Nr,{}),c.jsx(Jt,{onSelect:()=>kn(ae,{kind:"reset"}),children:h("ui.shell.sidebar_navigation.reset_layout")})]})]})]}):null;return c.jsxs("li",{"data-sidebar-row":ae,"data-sidebar-region":De,onContextMenu:ie?an=>{an.preventDefault(),W(ae)}:void 0,className:R("group/row relative flex h-[30px] w-full items-center rounded-md","transition-colors duration-fast ease-out-quart",wn,en&&IK,en&&NK),children:[s?ys:c.jsx(Ld,{content:Vt(we),side:yn,suppressed:me!==null,children:ys}),Ts,s&&(Ot>0||we.working)&&c.jsxs("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex shrink-0 items-center gap-1 pe-2",children:[Ot>0&&c.jsx(Ib,{count:Ot,"data-tour-tag":we.attentionTag}),we.working&&c.jsx(ri,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})]})]},we.tourTag)},Vn=Ae===null?null:c.jsx("span",{"aria-hidden":"true","data-sidebar-drop-indicator":"",className:"pointer-events-none absolute inset-x-1 z-10 h-0.5 -translate-y-px rounded-full bg-accent",style:{top:Ae}}),ls=(me===null?null:xo(oe,me))==="more"?h("ui.shell.sidebar_navigation.show_in_sidebar"):h("ui.shell.sidebar_navigation.move_to_more"),En=me===null?null:s?c.jsx("div",{"data-sidebar-drop-band":"",className:"absolute inset-x-0 top-full z-20 mt-1 flex h-7 items-center justify-center rounded-md border border-dashed border-control bg-surface text-meta text-ink-dim",children:ls}):c.jsx(Ld,{content:ls,side:e?"left":"right",children:c.jsx("div",{"data-sidebar-drop-band":"",className:"absolute inset-x-0 top-full z-20 mx-auto mt-1 flex h-6 w-8 items-center justify-center rounded-sm border border-dashed border-control bg-surface",children:c.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-4 rounded-full bg-ink-dim"})})}),Vs=c.jsx("span",{className:"sr-only","aria-live":"polite","aria-atomic":"true",children:fe}),un=s?h("ui.shell.sidebar_navigation.collapse_sidebar"):h("ui.shell.sidebar_navigation.expand_sidebar"),It=s?e?Vi:ju:e?ju:Vi,dn=navigator.platform.toUpperCase().indexOf("MAC")>=0,tr=Et(a.data,"session_catalogue",2),Sn=Fe(ae=>ae.activeDraftKey),Ie=Fe(ae=>ae.drafts),ge=!!Sn&&!(Sn?Ie[Sn]:void 0)?.target,Pe=()=>{Fe.getState().stageDraft(void 0,!0),t("/chat")},L=h("ui.shell.sidebar_navigation.new_chat_shortcut",{shortcut:Gj(dn).replace("+","")}),V=h("ui.shell.sidebar_navigation.search_accessible",{everything:ul("everything",dn),chats:ul("chats",dn)}),j=h("ui.shell.sidebar_navigation.search_tooltip",{everything:ul("everything",dn),chats:ul("chats",dn)}),q=(ae,we,De,$e)=>{const ke=ae;return c.jsxs("button",{type:"button",...$e.attrs,onClick:$e.onClick,disabled:$e.disabled,"aria-label":$e.ariaLabel,"aria-current":$e.current?"page":void 0,className:R(K6,$e.current?yo:"text-ink-muted hover:bg-row-hover hover:text-ink","disabled:text-ink-disabled disabled:hover:bg-transparent"),children:[c.jsx(ke,{size:16,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"truncate",children:we}),c.jsx("span",{"aria-hidden":"true",className:"ms-auto",children:c.jsx(Lr,{shortcut:De,joined:!0})})]})},Z=q(iT,h("ui.shell.sidebar_navigation.new_chat"),Gj(dn),{onClick:Pe,ariaLabel:L,current:ge,disabled:!tr,attrs:{"data-tour-tag":"nav-item-chat","data-new-chat-row":""}}),ee=q(_h,h("ui.shell.sidebar_navigation.search"),ztt("everything",dn),{onClick:i,ariaLabel:V,attrs:{"data-command-palette-trigger":"",title:j}}),_e=(ae,we,De)=>{const $e=ae;return c.jsx(Ld,{content:we,side:e?"left":"right",children:c.jsx("button",{type:"button",...De.attrs,onClick:De.onClick,disabled:De.disabled,"aria-label":we,className:R("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.jsxs("span",{className:"relative flex size-7 items-center justify-center",children:[c.jsx($e,{size:16,"aria-hidden":"true"}),(De.attention??0)>0&&c.jsx("span",{className:"pointer-events-none absolute -top-1 -end-1.5 flex",children:c.jsx(Ib,{count:De.attention??0,placement:"corner","data-tour-tag":De.attentionTag})}),De.working&&c.jsx("span",{className:"pointer-events-none absolute -bottom-0.5 -end-0.5 flex",children:c.jsx(ri,{size:12,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})})]})})})},Re=c.jsx("div",{className:R("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(Ld,{content:un,side:e?"left":"right",children:c.jsx(ce,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":un,"aria-expanded":s,"aria-keyshortcuts":oN(dn),children:c.jsx(It,{"aria-hidden":"true"})})})}),ye=()=>{if(H.length===0)return null;const ae=H.map(tt=>Y.get(tt)).filter(tt=>tt!==void 0),we=Blt(ae),De=te?0:we,$e=ae.some(tt=>tt.working===!0),ke=we>0?h("ui.shell.sidebar_navigation.more_waiting",{count:we,countText:String(we)}):$e?h("ui.shell.sidebar_navigation.more_working"):h("ui.library.page.more_destinations");return c.jsxs("li",{className:R("flex flex-col",s?"gap-0.5":"items-center gap-1"),children:[s?c.jsxs("button",{type:"button","data-tour-tag":"nav-item-more","data-sidebar-more":"","aria-expanded":te,"aria-controls":"sidebar-more-destinations","aria-label":ke,onClick:()=>C(!te),className:R(K6,"text-ink-muted hover:bg-row-hover hover:text-ink"),children:[c.jsx(oc,{size:16,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"min-w-0 flex-1 truncate text-start",children:h("ui.library.page.more")}),(De>0||$e)&&c.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[De>0&&c.jsx(Ib,{count:De,"data-tour-tag":"nav-more-badge"}),$e&&c.jsx(ri,{size:16,"aria-hidden":"true",className:"text-accent motion-safe:animate-spin"})]}),c.jsx(Ei,{size:14,"aria-hidden":"true",className:R("shrink-0 transition-transform duration-fast",te&&"rotate-180")})]}):_e(oc,ke,{onClick:()=>C(!te),attention:De,attentionTag:"nav-more-badge",working:$e,attrs:{"aria-expanded":te,"aria-controls":"sidebar-more-destinations","data-tour-tag":"nav-item-more","data-sidebar-more":""}}),te&&c.jsx("ul",{id:"sidebar-more-destinations",className:R("flex flex-col gap-0.5",!s&&"items-center gap-1"),children:H.map(cs)})]},"nav-overflow")},Te=c.jsx(Ld,{content:h("ui.shell.sidebar_navigation.settings"),side:"top",children:c.jsx("button",{type:"button","data-tour-tag":"nav-item-settings",onClick:()=>t("/settings"),"aria-current":n==="settings"?"page":void 0,"aria-label":h("ui.shell.sidebar_navigation.settings"),className:R("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",n==="settings"&&"text-ink"),children:c.jsx(Su,{size:16,"aria-hidden":"true"})})});return s?c.jsxs("div",{"data-sidebar-shell":"","data-glass-region":"sidebar",className:"panel-top-pad 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 pe-2 ps-4",children:[c.jsx(q6,{expanded:!0}),c.jsx("span",{className:"ms-auto",children:Re})]}),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:[Z,ee]}),c.jsxs("div",{className:"relative",children:[c.jsxs("div",{ref:he,"data-sidebar-destinations-area":"","data-sidebar-dragging":me!==null?"":void 0,className:"relative min-h-0 max-h-[50dvh] overflow-y-auto select-none",children:[c.jsxs("ul",{"data-sidebar-destinations":"",className:"flex flex-col gap-0.5",children:[B.map(cs),ye()]}),Vn]}),En]}),Vs]}),c.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:ws}),c.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-1 px-2 pb-2",children:[c.jsx(lA,{expanded:!0}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(z6,{}),Te]})]})]}):c.jsxs("div",{"data-sidebar-strip":"","data-glass-region":"sidebar",className:"panel-top-pad group/sidebar flex h-full min-h-0 flex-col items-center bg-surface",children:[c.jsx(Vlt,{}),c.jsx("div",{className:"flex h-10 shrink-0 items-center justify-center",children:c.jsx(q6,{expanded:!1})}),c.jsxs("ul",{className:"flex flex-col items-center gap-1",children:[c.jsx("li",{children:_e(Vi,un,{onClick:r,attrs:{"aria-expanded":!1,"aria-keyshortcuts":oN(dn)}})}),c.jsx("li",{children:_e(iT,L,{onClick:Pe,disabled:!tr,attrs:{"data-tour-tag":"nav-item-chat"}})}),c.jsx("li",{children:_e(_h,V,{onClick:i,attrs:{"data-command-palette-trigger":""}})})]}),c.jsxs("div",{ref:he,"data-sidebar-destinations-area":"","data-sidebar-dragging":me!==null?"":void 0,className:"relative mt-4 flex flex-col items-center gap-1 select-none",children:[c.jsxs("ul",{"data-sidebar-destinations":"",className:"flex flex-col items-center gap-1",children:[B.map(cs),ye()]}),Vn,En]}),Vs,c.jsxs("div",{className:"mt-auto flex flex-col items-center gap-1 pb-2",children:[c.jsx(z6,{}),Te,c.jsx(lA,{expanded:!1})]})]})},$lt=1,zlt=()=>{const{isAuthenticated:e,user:t}=Oy(),{hasBeenNotified:n,setHasBeenNotified:s}=rX(),[r,i]=m.useState(!1),[a,o]=m.useState(null),l=m.useCallback(async()=>{if(!(!e||!t?.radientUser?.account?.tenant_id))try{const p=await $ie({operation:"credits",tenantId:t.radientUser.account.tenant_id});if(!p||typeof p.balance!="number")throw new Error(h("ui.common.errors.credit_balance_invalid"));o(p.balance)}catch(p){console.error("Failed to fetch Radient credits:",p),o(null)}},[e,t?.radientUser?.account?.tenant_id]);return m.useEffect(()=>{e&&l()},[e,l]),m.useEffect(()=>{e&&a!==null?a<$lt?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 qlt(){const e=oi();m.useEffect(()=>{const t=r=>{e(r==="back"?-1:1)},n=r=>{const i=Tae(r);i&&(r.preventDefault(),t(i))},s=r=>{const i=Rae(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 Klt(){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 Ylt(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 Xlt(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 Qlt(){m.useLayoutEffect(()=>{if(!window.api?.windowChrome)return;const t=document.documentElement.dataset.chromePlatform??"linux",n=()=>Ylt(Klt(),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)}},[]),m.useEffect(()=>{const e=window.api?.windowChrome;if(e)return e.onState(t=>{document.documentElement.dataset.chromeFullscreen=t.fullScreen?"true":"false"})},[])}const Jlt=m.lazy(()=>va(()=>import("./agent-details-page-2H3QKmn4.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]),import.meta.url).then(e=>({default:e.AgentDetailsPage}))),Zlt=m.lazy(()=>va(()=>import("./agent-hub-page-C9NPxFvM.js"),__vite__mapDeps([15,1,2,3,5,16,7,6,8,4,9,10,11,12,17,18,19,20,13,14]),import.meta.url).then(e=>({default:e.AgentHubPage}))),Y6=m.lazy(()=>va(()=>import("./agents-page-BQ52N82v.js").then(e=>e.a),__vite__mapDeps([21,6,1,2,3,5,7,8,17,22,23]),import.meta.url).then(e=>({default:e.AgentsPage}))),ect=m.lazy(()=>va(()=>import("./schedules-page-D1DyGowS.js"),__vite__mapDeps([24,1,2,3,5,16,7,6,8,25,11,13,14]),import.meta.url).then(e=>({default:e.SchedulesPage}))),X6=m.lazy(()=>va(()=>import("./projects-page-CAziBDff.js"),__vite__mapDeps([26,1,2,3,6,5,7,8,16,13,14,23,27]),import.meta.url).then(e=>({default:e.ProjectsPage}))),Q6=m.lazy(()=>va(()=>import("./library-page-DYuFgJMi.js").then(e=>e.l),__vite__mapDeps([28,1,2,3,13,5,14,16,6,7,8,12,29,27]),import.meta.url).then(e=>({default:e.LibraryPage}))),J6=m.lazy(()=>va(()=>import("./notifications-page-CR9hkgko.js"),__vite__mapDeps([30,1,2,3,13,5,14,16,7,6,8,23]),import.meta.url).then(e=>({default:e.NotificationsPage}))),tct=m.lazy(()=>va(()=>import("./team-bridge-page-D7gX4utS.js"),__vite__mapDeps([31,1,2,3,6,5,7,8,29,22,32,20,13,14]),import.meta.url).then(e=>({default:e.TeamBridgePage}))),nct=m.lazy(()=>va(()=>import("./browser-page-Bw_APhwi.js"),__vite__mapDeps([33,1,2,3,5,7,6,8,13,14]),import.meta.url).then(e=>({default:e.BrowserPage}))),sct=m.lazy(()=>va(()=>import("./mesh-page-CGfJy25z.js"),__vite__mapDeps([34,1,2,3,5,16,7,6,8,13,14]),import.meta.url).then(e=>({default:e.MeshPage}))),rct=m.lazy(()=>va(()=>import("./settings-page-AJ0WetEN.js"),__vite__mapDeps([35,1,2,3,13,5,14,6,7,8,16,32,18,36,10,25,11]),import.meta.url).then(e=>({default:e.SettingsPage}))),ict=m.lazy(()=>va(()=>import("./browser-webauthn-prompt-CJWzdqpH.js"),__vite__mapDeps([37,1,2,3,5,7,6,8,13,14]),import.meta.url).then(e=>({default:e.BrowserWebauthnPrompt}))),act=()=>{Ve(),Zit(),Qlt(),elt(),zie();const{pathname:e}=fA(),t=e.startsWith("/chat")||e.startsWith("/browser"),{isOnboardingActive:n}=mfe(),{isLowCreditsDialogOpen:s,openRadientConsole:r,onLowCreditsDialogClose:i}=zlt(),{isCommandPaletteOpen:a,isCreateAgentDialogOpen:o,isSidebarCollapsed:l,closeCreateAgentDialog:u}=nt();_u(a,"command-palette"),_u(o,"dialog","create-agent"),_u(n,"onboarding"),_u(s,"dialog","low-credits");const d=oi(),f=ss(),p=Et(f.data,"session_catalogue",2),g=Et(f.data,"session_archive");m.useEffect(()=>{Fe.getState().requestArchiveConfirm(null)},[e]);const v=Gr(f.data,"peers"),b=Gr(f.data,"library"),x=Gr(f.data,"notifications"),_=Gr(f.data,"team_bridge_conversations");Zot(Et(f.data,"team_bridge_conversations"));const w=N=>{Fe.getState().stageDraft({kind:"agent",name:N.name}),d("/chat"),u()};hnt(),slt(),Aae(),qie(),qlt(),E_e();const y=Fe(N=>N.setActiveSession),S=ss(),C=fg(Et(S.data,"aida",1)),E=Fe(N=>{const P=N.activeDraftKey?N.drafts[N.activeDraftKey]:void 0;return Bv(N.activeDraftKey,P?.sessionId,N.activeSessionId)}),k=fpe({displayedSessionId:E,archiveEnabled:g}),F=nt(N=>N.setConsolePaneOpen),A=nt(N=>N.setBrowserPaneOpen),I=nt(N=>N.setConsoleActiveSurface);return m.useEffect(()=>{const N=window.api?.desktop?.onOpenConversation?.((P,M)=>{P!==null&&performance.mark("lop:open:requested"),y(P),M!==void 0&&P!==null&&(I(M),F(!0)),d("/chat")});return()=>N?.()},[d,y,F,I]),fat(_==="enabled",d),rlt(_==="enabled",d),m.useEffect(()=>{const N=window.api?.console?.onReveal?.(P=>{if(P.mode!=="none"&&!(P.mode==="session"&&P.session_id!==E)){if(P.mode==="open"){if(!Kie({targetSessionId:P.session_id,displayedSessionId:E,activeElement:document.activeElement,commandPaletteOpen:a}))return;y(P.session_id)}I(P.surface),F(!0)}});return()=>N?.()},[E,a,y,F,I]),jpe(),jtt(),m.useEffect(()=>{const N=window.api?.browser?.onConsentAttention?.(P=>{const M=wpe(P.requesterSessionId,Fe.getState().sessions);if(bpe(P.entryId),M.kind==="browser"){d("/browser");return}y(M.sessionId),A(!0),d("/chat")});return()=>N?.()},[d,y,A]),m.useEffect(()=>{const N=P=>{n||p&&Utt(P)&&(P.preventDefault(),Fe.getState().stageDraft(void 0,!0),d("/chat"))};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[p,n,d]),c.jsx(Hit,{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(lnt,{}),c.jsx(Git,{}),c.jsx(Gtt,{}),c.jsx(Yie,{}),c.jsx(fnt,{enabled:v==="enabled"}),c.jsx(ost,{open:n}),c.jsx(Uit,{}),c.jsx(nat,{}),g&&c.jsx(Vpe,{}),c.jsx(Wfe,{}),c.jsx(m.Suspense,{fallback:null,children:c.jsx(ict,{})}),c.jsx(ope,{blocked:n||s||a||o||k,sessionId:C.data?.session_id??null}),c.jsx(alt,{open:s,onClose:i,onGoToConsole:r}),c.jsx(wfe,{open:o,onClose:u,onAgentCreated:w}),c.jsx(Xie,{sidebar:c.jsx(Wlt,{}),content:c.jsxs("main",{"data-glass-region":"canvas-backing",className:"panel-top-pad flex grow flex-col overflow-hidden",children:[t?null:c.jsx("div",{"data-chrome-route-band":""}),c.jsx(m.Suspense,{fallback:c.jsx("div",{className:"flex grow items-center justify-center",children:c.jsx(On,{size:"lg",label:h("ui.common.loading.page")})}),children:c.jsxs(uZ,{children:[c.jsx(pr,{path:"/",element:c.jsx(lN,{to:"/chat",replace:!0})}),c.jsx(pr,{path:"/chat",element:c.jsx(Hj,{})}),c.jsx(pr,{path:"/chat/:agentId",element:c.jsx(Hj,{})}),c.jsx(pr,{path:"/agents",element:c.jsx(Y6,{})}),c.jsx(pr,{path:"/agents/:agentId",element:c.jsx(Y6,{})}),c.jsx(pr,{path:"/settings",element:c.jsx(rct,{})}),c.jsx(pr,{path:"/agent-hub",element:c.jsx(Zlt,{})}),c.jsx(pr,{path:"/agent-hub/:agentId",element:c.jsx(Jlt,{})}),c.jsx(pr,{path:"/schedules",element:c.jsx(ect,{})}),c.jsx(pr,{path:"/projects",element:c.jsx(X6,{})}),c.jsx(pr,{path:"/projects/:projectId",element:c.jsx(X6,{})}),c.jsx(pr,{path:"/browser",element:c.jsx(nct,{})}),x==="enabled"&&c.jsxs(c.Fragment,{children:[c.jsx(pr,{path:"/notifications",element:c.jsx(J6,{})}),c.jsx(pr,{path:"/notifications/:notificationId",element:c.jsx(J6,{})})]}),b==="enabled"&&c.jsxs(c.Fragment,{children:[c.jsx(pr,{path:"/library",element:c.jsx(Q6,{})}),c.jsx(pr,{path:"/library/assets/:assetId",element:c.jsx(Q6,{})})]}),_==="enabled"&&c.jsx(pr,{path:"/team-bridge",element:c.jsx(tct,{})}),v==="enabled"&&c.jsx(pr,{path:"/mesh",element:c.jsx(sct,{})}),c.jsx(pr,{path:"*",element:c.jsx(lN,{to:"/chat",replace:!0})})]})})]})})]})})})};let nl=null,Nf=null,mm=null,Pf=null,Kk=null;const oct={soundsArm:async()=>{if(xf.getState().element)throw new Error("sounds safety: element already exists");if(nl)throw new Error("sounds safety: graph already armed");return nl=new AudioContext,await nl.resume(),Jie(e=>{if(!nl)throw new Error("sounds safety: no context");const t=nl.createMediaElementSource(e);mm=nl.createGain(),mm.gain.value=0,Nf=nl.createAnalyser(),Pf=nl.createAnalyser(),t.connect(Pf),Pf.connect(mm),mm.connect(Nf),Nf.connect(nl.destination)}),{armed:!0,contextState:nl.state}},soundsFacts:()=>{const e=xf.getState(),t=new Float32Array(Nf?.fftSize??32);Nf?.getFloatTimeDomainData(t);const n=new Float32Array(Pf?.fftSize??32);return Pf?.getFloatTimeDomainData(n),{ownerId:e.ownerId,status:e.status,time:e.element?.currentTime??0,duration:e.element?.duration??0,paused:e.element?.paused??!0,gain:mm?.gain.value??null,inputRms:Pf?Math.sqrt(n.reduce((s,r)=>s+r*r,0)/n.length):null,players:Array.from(document.querySelectorAll("[data-sound-player]")).map(s=>({status:s.getAttribute("data-sound-status"),clock:s.querySelector("[data-sound-time]")?.textContent,clip:s.querySelectorAll("canvas")[1]?.style.clipPath,numeric:getComputedStyle(s.querySelector("[data-sound-time]")??s).fontVariantNumeric})),rms:Nf?Math.sqrt(t.reduce((s,r)=>s+r*r,0)/t.length):null,src:e.element?.src??null,nativeElements:document.querySelectorAll("audio").length,canvas:Object.values(Fs.getState().conversations).map(s=>({selectedTab:s.selectedTabId,files:s.files?.map(r=>({id:r.id,path:r.path,artifact:r.artifact??null}))}))}},soundsScrub:e=>{const t=e,n=document.querySelector(t.selector);if(!n)throw new Error("sounds: no slider");const s=n.getBoundingClientRect(),r=(u,d)=>n.dispatchEvent(new PointerEvent(u,{pointerId:17,pointerType:"mouse",clientX:d,clientY:s.y+s.height/2,bubbles:!0})),i=n.setPointerCapture,a=n.releasePointerCapture;n.setPointerCapture=()=>{},n.releasePointerCapture=()=>{},r("pointerdown",s.left+1),r("pointermove",s.left+s.width*t.fraction);const o=()=>n.closest("[data-sound-player]")?.getAttribute("data-sound-status"),l=performance.now()+1500;return new Promise(u=>{const d=()=>{const f=o();if(f!=="scrubbing"&&performance.now()<l){requestAnimationFrame(d);return}Kk=()=>{r("pointerup",s.left+s.width*t.fraction),n.setPointerCapture=i,n.releasePointerCapture=a},u({during:f,seconds:xf.getState().element?.currentTime})};requestAnimationFrame(d)})},soundsScrubFinish:()=>(Kk?.(),Kk=null,{committed:!0}),soundsEnd:()=>{const e=xf.getState();if(!e.ownerId||!e.element)throw new Error("sounds: no active playback");return e.seek(e.ownerId,e.element.duration-.12),{requested:!0}},soundsSpeech:async()=>{const e=xf.getState();if(!e.element?.src)throw new Error("sounds: fixture not resolved");const{fetchAttachmentBlob:t}=await va(async()=>{const{fetchAttachmentBlob:r}=await import("./conversation-input-sync-BXe0XySA.js").then(i=>i.nj);return{fetchAttachmentBlob:r}},__vite__mapDeps([6,1,2,3,5,7,8]),import.meta.url),n=Fe.getState().activeSessionId,s=e.ownerId?.startsWith("sound:")?e.ownerId.slice(6):null;if(!n||!s)throw new Error("sounds: missing attachment identity");return await Qie.getState().speak("sounds-driver",()=>t({sessionId:n,childId:null},s)),{ownerId:xf.getState().ownerId}}};function Kd(){return new Promise(e=>{requestAnimationFrame(()=>requestAnimationFrame(()=>e()))})}const lct=3,cct=3e3;function uct(e){return e instanceof CSSTransition&&e.playState==="running"}function dct(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 ${Nv(n)??"an element no longer in the document"} = ${i}`}async function hct(e=cct){const t=performance.now();let n=0;for(;;){await Kd();const s=Math.round(performance.now()-t),r=document.getAnimations().filter(uct);if(n=r.length===0?n+1:0,n>=lct)return{waitedMs:s,timedOut:!1,pending:[]};if(s>e)return{waitedMs:s,timedOut:!0,pending:r.map(dct)}}}const fct=/^#/;function S0(){const e=window.location.hash.replace(fct,"");return e===""?"/":e}function Nv(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 pct(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=>Nv(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:Nv(r),stack:a,disabled:e instanceof HTMLButtonElement?e.disabled:null,rect:{x:t.x,y:t.y,width:t.width,height:t.height}}}function vm(e,t){if(typeof e!="string"||e==="")throw new Error(`${t} must be a non-empty string`);return e}async function gct(e,t=1e4){const n=Date.now();for(;S0()!==e;){if(Date.now()-n>t)throw new Error(`route did not become ${e} (it is ${S0()})`);await new Promise(s=>setTimeout(s,50))}return await Kd(),S0()}const cA=["dev-driver","query-fetch-probe"];let k0=null;function mct(){if(k0)return k0;const e=[],t=cN.prototype.fetch;return cN.prototype.fetch=function(...s){return e.push({at:Date.now(),key:JSON.stringify(this.queryKey),stack:(new Error().stack??"").split(`
695
695
  `).slice(2).join(" | ")}),t.apply(this,s)},k0=e,e}function vct(e){const t=k0??[],n=JSON.stringify(cA),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:k0!==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 bct(){const e=window.__loDevDriver;return e?.armed?e.install({...oct,hello:()=>({armed:!0,outDir:e.outDir,title:document.title,route:S0(),href:window.location.href,theme:nt.getState().themeName,viewport:{width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio},visibilityState:document.visibilityState,hasFocus:document.hasFocus(),apiBaseUrl:Zs.baseUrl,userAgent:navigator.userAgent}),filesFacts:()=>Zie(),state:()=>{const t=nt.getState(),n=Fe.getState();return{route:S0(),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,model:r.model??null}])),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:()=>M_.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 vct(n.key);const s=mct(),r=JSON.stringify(cA),i=s.length;return await M_.fetchQuery({queryKey:cA,queryFn:()=>null,retry:!1,staleTime:0}),{armed:!0,validated:s.slice(i).some(a=>a.key===r)}},navigate:async t=>{const n=vm(t,"navigate path");if(!n.startsWith("/"))throw new Error(`navigate path must start with "/" (got "${n}")`);return window.location.hash=`#${n}`,{route:await gct(n)}},setTheme:async t=>{const n=vm(t,"theme name");nt.getState().setTheme(n),await Kd();const s=document.documentElement.getAttribute("data-theme"),r=await hct();return{theme:nt.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=dZ(n);return nt.getState().setChatSidebarWidth(s),await Kd(),{width:nt.getState().chatSidebarWidth,clamped:s!==n}},measure:async t=>{const n=typeof t=="string"?{selector:t}:t,s=vm(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:Nv(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=vm(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=pct(a);return await Kd(),{selector:s,target:Nv(a),...o}},openCanvasDocument:async t=>{const n=t,s=vm(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=So(a,{title:r,type:Gu(a),availability:"present",sizeBytes:i.sizeBytes??void 0,lastAgentModified:i.mtimeMs??void 0,readMtimeMs:i.mtimeMs??void 0}),l=Ny[lg(a,o.type)??"code"];if(l==="utf-8"||l==="base64"){const f=await window.api.readFile(o.path,l);if(!f.success)throw new Error(`could not read ${o.path}`);o.content=f.data}const u=Fe.getState(),d=gA(u.activeDraftKey,u.activeSessionId)??u.stageDraft();return nt.getState().setCanvasOpen(!0),Fs.getState().addFileAndSelect(d,o),n?.mention===!0&&Fs.getState().addMentionedFile(d,o),await Kd(),{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 Fae({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 Kd(),{count:s}}}):[]}function xct(){const e=m.useMemo(ag,[]),t=m.useRef(null);return m.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);nn(eae(a.status,l))};n.getRegistration?.()?.then(r)?.catch(()=>{});const i=n.onRegistration(r);return()=>{s=!0,i?.()}},[e]),null}const _ct=`
696
696
  /*
697
697
  * A transition declared on ::-webkit-scrollbar-thumb does not animate in