local-operator-ui 0.34.47 → 0.34.49

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 (120) hide show
  1. package/out/main/index.js +2259 -47
  2. package/out/preload/index.js +1 -0
  3. package/out/renderer/assets/{_basePickBy-B2JiaFKi.js → _basePickBy-Coq1U1Is.js} +1 -1
  4. package/out/renderer/assets/{_baseUniq-CfpDxOYw.js → _baseUniq-CN5nbj15.js} +1 -1
  5. package/out/renderer/assets/agent-details-page-BOHG1UL8.js +6 -0
  6. package/out/renderer/assets/agent-hub-page-lDe6m3U_.js +11 -0
  7. package/out/renderer/assets/agents-page-CS2ctxLL.js +7 -0
  8. package/out/renderer/assets/{arc-K65ZzfoN.js → arc-CyEksofH.js} +1 -1
  9. package/out/renderer/assets/architectureDiagram-IEHRJDOE-o2ZHU4e3.js +36 -0
  10. package/out/renderer/assets/{blockDiagram-JOT3LUYC-DpImr7tl.js → blockDiagram-JOT3LUYC-B0Yyp4_C.js} +1 -1
  11. package/out/renderer/assets/{book-open-BEOtYKZe.js → book-open-CEakesEi.js} +1 -1
  12. package/out/renderer/assets/browser-page-CjbkyuiR.js +1 -0
  13. package/out/renderer/assets/browser-webauthn-prompt-Dq82YVua.js +1 -0
  14. package/out/renderer/assets/{c4Diagram-VJAJSXHY-CD9xVR0f.js → c4Diagram-VJAJSXHY-DLUNsMlf.js} +1 -1
  15. package/out/renderer/assets/channel-BrqzOdfK.js +1 -0
  16. package/out/renderer/assets/{chunk-4BMEZGHF-CTvc3b4C.js → chunk-4BMEZGHF-TEJuQZ1Y.js} +1 -1
  17. package/out/renderer/assets/{chunk-A2AXSNBT-ByqThlbf.js → chunk-A2AXSNBT-B_dFl8CN.js} +1 -1
  18. package/out/renderer/assets/{chunk-AEK57VVT-DD6OqDr0.js → chunk-AEK57VVT-BZoQ5TO6.js} +1 -1
  19. package/out/renderer/assets/{chunk-D6G4REZN-DyRn0cWl.js → chunk-D6G4REZN-D1bYNZJL.js} +1 -1
  20. package/out/renderer/assets/{chunk-RZ5BOZE2-CnZV3WTJ.js → chunk-RZ5BOZE2-DbkFvpUt.js} +1 -1
  21. package/out/renderer/assets/{chunk-XZIHB7SX-DolFB-S0.js → chunk-XZIHB7SX-C0c85hT-.js} +1 -1
  22. package/out/renderer/assets/classDiagram-GIVACNV2-C4Q7B2pX.js +1 -0
  23. package/out/renderer/assets/classDiagram-v2-COTLJTTW-C4Q7B2pX.js +1 -0
  24. package/out/renderer/assets/clone-T21nSsyt.js +1 -0
  25. package/out/renderer/assets/{console-mirror-DpL-JwpC.js → console-mirror-DDhXu5hQ.js} +2 -2
  26. package/out/renderer/assets/consoleCapture-DomsRGWw.js +1 -0
  27. package/out/renderer/assets/{conversation-input-sync-BX8IVirL.js → conversation-input-sync-B3FVv0Mq.js} +257 -258
  28. package/out/renderer/assets/dagre-OKDRZEBW-CAb1XIuS.js +4 -0
  29. package/out/renderer/assets/diagram-SSKATNLV-CAh7vH7L.js +43 -0
  30. package/out/renderer/assets/diagram-VNBRO52H-CU4FF4Qr.js +24 -0
  31. package/out/renderer/assets/en-US-CHJkXXr4.js +1 -0
  32. package/out/renderer/assets/{erDiagram-Q7BY3M3F-CKncNCh2.js → erDiagram-Q7BY3M3F-CbnNz_kj.js} +1 -1
  33. package/out/renderer/assets/error-boundary-etstfCzN.js +126 -0
  34. package/out/renderer/assets/{flowDiagram-4HSFHLVR-DxgK_2s-.js → flowDiagram-4HSFHLVR-BB6aJVKV.js} +1 -1
  35. package/out/renderer/assets/{format-CZUObkkr.js → format-esAOn2VS.js} +1 -1
  36. package/out/renderer/assets/{ganttDiagram-APWFNJXF-C26kU1-9.js → ganttDiagram-APWFNJXF-CtOJM4d7.js} +1 -1
  37. package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-DvrevAjH.js +65 -0
  38. package/out/renderer/assets/{graph-CnXCW8BP.js → graph-DOR9Sgwh.js} +1 -1
  39. package/out/renderer/assets/index-5vl5RXGq.js +1 -0
  40. package/out/renderer/assets/index-9_-S4Njy.js +809 -0
  41. package/out/renderer/assets/index-CZ5usiad.js +7 -0
  42. package/out/renderer/assets/index-CftawgM9.js +57 -0
  43. package/out/renderer/assets/index-VwZaZzVv.css +1 -0
  44. package/out/renderer/assets/infoDiagram-PH2N3AL5-CTd32x3B.js +2 -0
  45. package/out/renderer/assets/installer-CjbOLDvI.js +1 -0
  46. package/out/renderer/assets/{journeyDiagram-U35MCT3I-C-Aue1NR.js → journeyDiagram-U35MCT3I-2BsbTilL.js} +1 -1
  47. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-DhgXwdEM.js → kanban-definition-NDS4AKOZ-DoYAcNl0.js} +1 -1
  48. package/out/renderer/assets/{layout-Dw8q0WZh.js → layout-DSk91znb.js} +1 -1
  49. package/out/renderer/assets/legacy-agents-page-BGSPncrN.js +33 -0
  50. package/out/renderer/assets/{mermaid.core-CLdsX7Rp.js → mermaid.core-BqK7XNWH.js} +5 -5
  51. package/out/renderer/assets/mesh-page-BxEA5Aan.js +1 -0
  52. package/out/renderer/assets/mindmap-definition-ALO5MXBD-HV-ovM7g.js +95 -0
  53. package/out/renderer/assets/mini-Bco2ITLo.js +1 -0
  54. package/out/renderer/assets/{notebook-pen-B5Stfimb.js → notebook-pen-DsGb6zKu.js} +1 -1
  55. package/out/renderer/assets/org-access-B_xqEqnd.js +1 -0
  56. package/out/renderer/assets/{org-surface-gate-i_SGPHN5.js → org-surface-gate-D4SilXIt.js} +1 -1
  57. package/out/renderer/assets/{page-header-BR-fmx4f.js → page-header-DZ04Whs5.js} +1 -1
  58. package/out/renderer/assets/{parseISO-CZfAC2_J.js → parseISO-BHJWTxrA.js} +1 -1
  59. package/out/renderer/assets/{pieDiagram-IB7DONF6-DjDH1mVr.js → pieDiagram-IB7DONF6-BArx4Jik.js} +1 -1
  60. package/out/renderer/assets/{projects-page-CGRUr8ls.js → projects-page-DABVK4s_.js} +14 -14
  61. package/out/renderer/assets/publication-validation-BmkCCv-H.js +1 -0
  62. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-Ba5XUz4h.js → quadrantDiagram-7GDLP6J5-Dmmo_urD.js} +1 -1
  63. package/out/renderer/assets/{radar-MK3ICKWK-eQRm6qEE.js → radar-MK3ICKWK-D8Sc1Ajv.js} +1 -1
  64. package/out/renderer/assets/radient-auth-buttons-BmQt2D1Y.js +1 -0
  65. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-BSpyCNos.js → requirementDiagram-KVF5MWMF-BU04-wPA.js} +1 -1
  66. package/out/renderer/assets/sankeyDiagram-QLVOVGJD-CIQO7kso.js +10 -0
  67. package/out/renderer/assets/schedules-page-DllGJFS2.js +115 -0
  68. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-DdHVib_S.js → sequenceDiagram-X6HHIX6F-BN2soxj_.js} +1 -1
  69. package/out/renderer/assets/settings-page-DKzDa5P5.js +292 -0
  70. package/out/renderer/assets/stateDiagram-DGXRK772-bGNaZvy4.js +1 -0
  71. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-CNVQhmQM.js +1 -0
  72. package/out/renderer/assets/{timeline-definition-BDJGKUSR-5dsF-6I0.js → timeline-definition-BDJGKUSR-DmM_eb2d.js} +1 -1
  73. package/out/renderer/assets/ui-preferences-store-Byw1dJtt.js +1 -0
  74. package/out/renderer/assets/use-download-agent-mutation-CXv_tRQE.js +61 -0
  75. package/out/renderer/assets/{use-memberships-query-BMGVy3RO.js → use-memberships-query-C4IVeIBl.js} +1 -1
  76. package/out/renderer/assets/{use-session-snapshot-D3QghcPD.js → use-session-snapshot-CrOrWGgL.js} +1 -1
  77. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-DmEwPPnE.js → xychartDiagram-VJFVF3MP-CbbQZrKE.js} +1 -1
  78. package/out/renderer/console-capture.html +5 -5
  79. package/out/renderer/index.html +7 -7
  80. package/out/renderer/installer.html +4 -4
  81. package/out/renderer/mini.html +7 -7
  82. package/package.json +3 -5
  83. package/out/renderer/assets/agent-details-page-C0GdJMfq.js +0 -6
  84. package/out/renderer/assets/agent-hub-page-C6ze_xjQ.js +0 -11
  85. package/out/renderer/assets/agents-page-DSNLtN_J.js +0 -7
  86. package/out/renderer/assets/architectureDiagram-IEHRJDOE-CLJdV8y-.js +0 -36
  87. package/out/renderer/assets/browser-page-Hj-3V4SP.js +0 -1
  88. package/out/renderer/assets/browser-webauthn-prompt-4jHz_1RY.js +0 -1
  89. package/out/renderer/assets/channel-CjH9_X6K.js +0 -1
  90. package/out/renderer/assets/classDiagram-GIVACNV2-DNFX9Bxc.js +0 -1
  91. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DNFX9Bxc.js +0 -1
  92. package/out/renderer/assets/clone-Dh-7KwYI.js +0 -1
  93. package/out/renderer/assets/consoleCapture-DD1Sq_ph.js +0 -1
  94. package/out/renderer/assets/dagre-OKDRZEBW-CDaLTqSD.js +0 -4
  95. package/out/renderer/assets/diagram-SSKATNLV-CT01eufZ.js +0 -43
  96. package/out/renderer/assets/diagram-VNBRO52H-Dm95zJ6Z.js +0 -24
  97. package/out/renderer/assets/en-US-BcB1DWxG.js +0 -1
  98. package/out/renderer/assets/error-boundary-BDLNfQKz.js +0 -126
  99. package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-B22ejsPk.js +0 -65
  100. package/out/renderer/assets/index-Be9pTy7F.js +0 -7
  101. package/out/renderer/assets/index-CnQsclLj.js +0 -809
  102. package/out/renderer/assets/index-DF_hRerL.js +0 -55
  103. package/out/renderer/assets/index-Dk4-Px6P.css +0 -1
  104. package/out/renderer/assets/index-UE_QEAqr.js +0 -1
  105. package/out/renderer/assets/infoDiagram-PH2N3AL5-DJZU3P7J.js +0 -2
  106. package/out/renderer/assets/installer-CIu909RT.js +0 -1
  107. package/out/renderer/assets/legacy-agents-page-u84wTmRV.js +0 -33
  108. package/out/renderer/assets/mesh-page-Dys9-2sY.js +0 -1
  109. package/out/renderer/assets/messages-Yrm2FT2V.js +0 -3
  110. package/out/renderer/assets/mindmap-definition-ALO5MXBD-BjBiqabY.js +0 -95
  111. package/out/renderer/assets/mini-BXXRy4rW.js +0 -1
  112. package/out/renderer/assets/org-access-CyjYN726.js +0 -1
  113. package/out/renderer/assets/publication-validation-B4k6VAFZ.js +0 -1
  114. package/out/renderer/assets/radient-auth-buttons-BW_zi2lF.js +0 -1
  115. package/out/renderer/assets/sankeyDiagram-QLVOVGJD-C-fzkOnd.js +0 -10
  116. package/out/renderer/assets/schedules-page-CiSL5P8q.js +0 -115
  117. package/out/renderer/assets/settings-page-C11l7qyA.js +0 -292
  118. package/out/renderer/assets/stateDiagram-DGXRK772-DEwuWkNd.js +0 -1
  119. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-DRPVtafh.js +0 -1
  120. package/out/renderer/assets/use-download-agent-mutation-DGGt-uXR.js +0 -61
@@ -1,33 +0,0 @@
1
- import{r as o,j as e,c as z}from"./index-DF_hRerL.js";import{bL as Je,aJ as Ct,bB as _t,bM as St,C as Xe,u as et,ag as Oe,ah as Z,aH as tt,aI as It,bN as Pt,aG as ce,bq as Dt,bO as Lt,aF as at,aO as se,aP as be,bz as Tt,bP as Et,aN as Ot,bE as Le,aK as Re,Z as Rt,a as Ut,c as zt,bH as qt,aU as $t,bu as Mt,a1 as At,a0 as Ht,B as st,aq as nt,bt as Bt,aT as Wt}from"./conversation-input-sync-BX8IVirL.js";import{P as Vt}from"./page-header-BR-fmx4f.js";import{c as ie,q as it,r as ot,B as D,s as rt,v as Q,x as lt,S as ct,l as A,I as dt,w as Kt,$ as je,L as le,y as ut,X as mt,a0 as Gt,a1 as Qt,a2 as Ft,A as ye,m as _e,n as re,z as Yt,F as Zt,G as Jt,H as Xt,J as Se,C as ea,a3 as ta,i as aa,j as sa}from"./error-boundary-BDLNfQKz.js";import{aI as na,aJ as ht,aK as Te,aL as Ee,aM as ia,aN as Ke,aO as oa,aP as ra,az as pt,aQ as ae,aR as ne,aS as la,aT as ca,aU as da,aV as ua,aW as Ie,aX as ma,aG as ha,aY as pa,b as Ue,aZ as xt,ay as xa,ag as ga,ai as fa,am as ba,a_ as gt,a$ as ya,b0 as ft,aC as ja,b1 as ka,b2 as Ge}from"./index-CnQsclLj.js";import{N as va}from"./notebook-pen-B5Stfimb.js";import{e as wa,g as Na,i as Ca,t as K,u as _a}from"./messages-Yrm2FT2V.js";import{f as Sa}from"./use-memberships-query-BMGVy3RO.js";import{n as Pe,u as Ia,a as Pa,H as Da,p as La}from"./org-access-CyjYN726.js";import{o as Ta,a as Ea}from"./org-surface-gate-i_SGPHN5.js";import{R as Qe}from"./radient-auth-buttons-BW_zi2lF.js";import{c as Oa,i as Ra,d as Ua,e as za,t as qa,p as Fe,P as Ye}from"./publication-validation-B4k6VAFZ.js";import"./console-mirror-DpL-JwpC.js";/**
2
- * @license lucide-react v0.507.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const $a=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Ma=ie("ellipsis-vertical",$a);/**
7
- * @license lucide-react v0.507.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const Aa=[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]],Ze=ie("file-input",Aa);/**
12
- * @license lucide-react v0.507.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const Ha=[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],Ba=ie("file-output",Ha);/**
17
- * @license lucide-react v0.507.0 - ISC
18
- *
19
- * This source code is licensed under the ISC license.
20
- * See the LICENSE file in the root directory of this source tree.
21
- */const Wa=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],Va=ie("git-branch",Wa);/**
22
- * @license lucide-react v0.507.0 - ISC
23
- *
24
- * This source code is licensed under the ISC license.
25
- * See the LICENSE file in the root directory of this source tree.
26
- */const Ka=[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]],Ga=ie("id-card",Ka);/**
27
- * @license lucide-react v0.507.0 - ISC
28
- *
29
- * This source code is licensed under the ISC license.
30
- * See the LICENSE file in the root directory of this source tree.
31
- */const Qa=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]],Fa=ie("import",Qa),Ya=({agentId:t,agentName:s,onAgentDeleted:a,buttonSx:i={},isAgentsPage:n=!1,onViewAgentSettings:r,onChatWithAgent:c,onExportAgent:g,onClearConversation:m,onUploadAgentToHub:k})=>{const[y,f]=o.useState(!1),[l,d]=o.useState(!1),[u,b]=o.useState(!1),v=o.useRef(!1),_=na(),{clearAgentFromAllPages:S}=Je(),I=async()=>{try{await _.mutateAsync(t),S(t),a?.(t)}catch(C){console.error("Failed to delete agent:",C)}finally{d(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(it,{open:y,onOpenChange:f,modal:!1,children:[e.jsx(ot,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"icon-sm","aria-label":"agent options","data-tour-tag":"agent-options-button",onClick:C=>{C.stopPropagation(),C.detail===0&&f(L=>!L)},style:i,children:e.jsx(Ma,{"aria-hidden":"true"})})}),e.jsxs(rt,{align:"end",className:"min-w-45",onClick:C=>C.stopPropagation(),onInteractOutside:C=>{const L=C.detail.originalEvent.target;L instanceof Element&&L.closest(".shepherd-element")&&C.preventDefault()},onCloseAutoFocus:C=>{v.current&&(v.current=!1,C.preventDefault())},children:[n&&c&&e.jsxs(Q,{onSelect:c,children:[e.jsx(ht,{"aria-hidden":"true"}),e.jsx("span",{children:"Chat with agent"})]}),!n&&r&&e.jsxs(Q,{"data-tour-tag":"view-agent-settings-menu-item",onSelect:r,children:[e.jsx(Te,{"aria-hidden":"true"}),e.jsx("span",{children:"View agent settings"})]}),g&&e.jsxs(Q,{onSelect:g,children:[e.jsx(Ba,{"aria-hidden":"true"}),e.jsx("span",{children:"Export agent"})]}),k&&e.jsxs(Q,{"data-tour-tag":"upload-to-hub-menu-item",onSelect:k,children:[e.jsx(Ee,{"aria-hidden":"true"}),e.jsx("span",{children:"Upload to hub"})]}),m&&e.jsxs(Q,{className:"text-warning data-[highlighted]:bg-warning-wash",onSelect:()=>{v.current=!0,b(!0)},children:[e.jsx(ia,{"aria-hidden":"true"}),e.jsx("span",{children:"Clear conversation"})]}),e.jsxs(Q,{destructive:!0,onSelect:()=>{v.current=!0,d(!0)},children:[e.jsx(Ct,{"aria-hidden":"true"}),e.jsx("span",{children:"Delete agent"})]})]})]}),e.jsx(Ke,{open:l,title:"Delete agent",message:e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-body text-ink",children:['Are you sure you want to delete the agent "',s,'"?']}),e.jsx("p",{className:"mt-2 text-body-sm text-ink-muted",children:"This action cannot be undone. All conversations with this agent will be permanently deleted."})]}),confirmText:"Delete",cancelText:"Cancel",isDangerous:!0,onConfirm:I,onCancel:()=>d(!1)}),e.jsx(Ke,{open:u,title:"Clear this conversation?",message:"Every message in it is deleted from this computer, and there is no undo. The agent itself is not affected.",confirmText:"Clear",cancelText:"Cancel",isDangerous:!0,onConfirm:()=>{m?.(),b(!1)},onCancel:()=>b(!1)})]})},Za=({page:t,count:s,onChange:a})=>{const i=()=>{t>1&&a(t-1)},n=()=>{t<s&&a(t+1)};return s<=1?null:e.jsxs("div",{className:"sticky bottom-0 left-0 right-0 z-10 flex min-h-13 items-center justify-between border-t border-hairline bg-surface px-4 py-2",children:[e.jsx(D,{variant:"ghost",size:"icon-sm",onClick:i,disabled:t<=1,"aria-label":"Previous page",children:e.jsx(_t,{})}),e.jsxs("span",{className:"select-none text-meta text-ink-dim",children:["Page ",t," of ",s]}),e.jsx(D,{variant:"ghost",size:"icon-sm",onClick:n,disabled:t>=s,"aria-label":"Next page",children:e.jsx(lt,{})})]})},bt=t=>["agent-system-prompt",t],yt=t=>{const{shouldEnableQuery:s}=St();return Xe({enabled:s({bypassInternetCheck:!0})&&!!t,queryKey:bt(t),queryFn:async()=>{try{const i=await Oe(Z.baseUrl).agents.getAgentSystemPrompt(t);if(i.status>=400)throw new Error(i.message||"Failed to fetch agent system prompt");return i.result?.system_prompt||""}catch(a){const i=a instanceof Error?a.message:"An unknown error occurred while fetching agent system prompt";throw ce(i),a}},refetchOnWindowFocus:!1,staleTime:5e3})},Ja=t=>{const s=et(),a=Oe(Z.baseUrl);return tt({mutationFn:async i=>{const n=Pt(i);if(n)throw ce(n),new Error(n);try{const r=await a.agents.updateAgentSystemPrompt(t,i);if(r.status>=400)throw new Error(r.message||"Failed to update agent system prompt");return r}catch(r){const c=r instanceof Error?r.message:"An unknown error occurred while updating agent system prompt";throw ce(c),r}},onSuccess:async()=>{await s.invalidateQueries({queryKey:bt(t)}),It("Agent system prompt updated")},onError:i=>{console.error("Error updating agent system prompt:",i)}})},Xa=()=>{const[t,s]=Dt(),a=Lt(),i=()=>{const r=t.get("page");return r?Number.parseInt(r,10):1},n=r=>{const c=new URLSearchParams(t);r===1?c.delete("page"):c.set("page",r.toString()),s(c)};return{page:i(),setPage:n,isView:r=>a.pathname.startsWith(`/${r}`)}},es=({open:t,onClose:s,onAgentImported:a})=>{const[i,n]=o.useState(null),[r,c]=o.useState(!1),[g,m]=o.useState(null),k=o.useRef(null),y=oa(),f=o.useCallback(j=>{j.preventDefault(),j.stopPropagation(),c(!0)},[]),l=o.useCallback(j=>{j.preventDefault(),j.stopPropagation(),c(!1)},[]),d=o.useCallback(j=>{j.preventDefault(),j.stopPropagation()},[]),u=o.useCallback(j=>j.name.toLowerCase().endsWith(".zip")?(m(null),!0):(m("Only ZIP files are supported"),!1),[]),b=o.useCallback(j=>{if(j.preventDefault(),j.stopPropagation(),c(!1),j.dataTransfer.files&&j.dataTransfer.files.length>0){const T=j.dataTransfer.files[0];u(T)&&n(T)}},[u]),v=o.useCallback(j=>{if(j.target.files&&j.target.files.length>0){const T=j.target.files[0];u(T)&&n(T)}},[u]),_=o.useCallback(()=>{k.current?.click()},[]),S=async()=>{if(i)try{const j=await y.mutateAsync(i);n(null),m(null),a&&j&&a(j.id),s()}catch(j){console.error("Failed to import agent:",j)}},I=()=>{n(null),m(null),s()},C=y.isPending,L=C||!i,x=e.jsxs(e.Fragment,{children:[e.jsx(Ze,{size:19,className:"text-accent","aria-hidden":"true"}),"Import agent"]}),w=e.jsxs(e.Fragment,{children:[e.jsx(se,{onClick:I,disabled:C,children:"Cancel"}),e.jsx(be,{onClick:S,disabled:L,startIcon:C?e.jsx(ct,{}):null,children:"Import agent"})]});return e.jsxs(at,{open:t,onClose:I,title:x,actions:w,maxWidth:"sm",children:[e.jsx("p",{className:"mb-4 text-body-sm text-ink-muted",children:"Import an agent from a ZIP file exported from Local Operator. The file should contain an agent.yml file."}),e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsx("input",{ref:k,type:"file",accept:".zip",onChange:v,disabled:C,className:"hidden"}),e.jsx("button",{type:"button",onClick:_,onDragEnter:f,onDragLeave:l,onDragOver:d,onDrop:b,disabled:C,className:z("cursor-pointer rounded-lg border-2 border-control border-dashed bg-surface p-4 text-center","transition-colors duration-base ease-out-quart","hover:bg-accent-wash","disabled:border-hairline disabled:bg-sunken disabled:text-ink-disabled",r&&"border-accent bg-accent-wash"),children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{size:32,className:"mx-auto mb-2 text-ink-muted","aria-hidden":"true"}),e.jsx("p",{className:"text-body text-ink",children:i.name}),e.jsx("p",{className:"text-body-sm text-ink-muted",children:"Click or drag to replace"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ra,{size:32,className:"mx-auto mb-2 text-ink-muted","aria-hidden":"true"}),e.jsx("p",{className:"text-body text-ink",children:"Drag and drop a ZIP file here"}),e.jsx("p",{className:"text-body-sm text-ink-muted",children:"or click to select a file"})]})}),g&&e.jsx("p",{role:"alert",className:"text-body-sm text-danger",children:g})]})]})},ts=({title:t,searchQuery:s,onSearchChange:a,onNewAgentClick:i,searchPlaceholder:n="Search agents",newAgentTooltip:r="Create a new agent",onImportAgentClick:c,importAgentTooltip:g="Import an agent from a ZIP file"})=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"truncate text-heading text-ink",children:t}),e.jsxs("div",{className:"flex shrink-0 gap-1",children:[c&&e.jsx(A,{content:g,children:e.jsx(D,{variant:"ghost",size:"icon",onClick:c,"aria-label":"Import agent",children:e.jsx(Fa,{"aria-hidden":"true"})})}),e.jsx(A,{content:r,children:e.jsx(D,{variant:"primary",size:"icon",onClick:i,"aria-label":"New agent","data-tour-tag":"create-new-agent-button",children:e.jsx(pt,{"aria-hidden":"true"})})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Tt,{size:16,"aria-hidden":"true",className:"pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-ink-dim"}),e.jsx(dt,{type:"search",inputSize:"lg",placeholder:n,value:s,onChange:m=>a(m.target.value),"aria-label":n,className:"pl-9"})]})]}),N={temperature:.2,top_p:.9,top_k:40,max_tokens:4096,frequency_penalty:0,presence_penalty:0,seed:42},G=({label:t,description:s,defaultLabel:a,onSet:i})=>e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-body-sm text-ink",children:t}),e.jsx("span",{className:"text-meta text-ink-dim",children:"Not set yet"})]}),e.jsx("p",{className:"mt-1 text-meta text-ink-dim",children:s})]}),e.jsxs(D,{variant:"secondary",size:"sm",className:"shrink-0",onClick:i,children:["Set to default (",a,")"]})]}),De=({title:t,children:s})=>e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("h3",{className:"text-body-sm font-semibold text-ink-muted",children:t}),s]}),as=({selectedAgent:t,savingField:s,setSavingField:a,updateAgentMutation:i,refetchAgent:n,initialSelectedAgentId:r})=>{const[c,g]=o.useState(t);o.useEffect(()=>{g(t)},[t]);const[m,k]=o.useState(!1),y=o.useId(),f=m?Kt:lt;return e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(!m),"aria-expanded":m,"aria-controls":y,className:"group flex items-center gap-2 py-1 text-left text-heading text-ink",children:[e.jsx(f,{size:14,"aria-hidden":"true",className:"shrink-0 text-ink-dim transition-colors duration-fast ease-out-quart group-hover:text-ink"}),"Advanced chat settings"]}),e.jsx(A,{content:"Advanced settings to change how the agent generates responses",children:e.jsx(D,{variant:"ghost",size:"icon-sm","aria-label":"About advanced chat settings",children:e.jsx(je,{})})})]}),m&&e.jsxs("div",{id:y,className:"mt-3",children:[e.jsx("p",{className:"max-w-2xl text-body-sm text-ink-muted",children:"Set custom values for any of these options. Anything left unset uses a default optimized from user testing."}),e.jsxs("div",{className:"mt-6 flex flex-col gap-8",children:[e.jsxs(De,{title:"Sampling",children:[c.temperature===null?e.jsx(G,{label:"Temperature",description:"Controls randomness in responses (0.0-1.0). Higher values make output more random.",defaultLabel:N.temperature,onSet:async()=>{a("temperature");try{const l={temperature:N.temperature};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,temperature:N.temperature})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ae,{value:c.temperature??N.temperature,label:"Temperature",description:"Controls randomness in responses (0.0-1.0). Higher values make output more random.",min:0,max:1,step:.01,isSaving:s==="temperature",onChange:async l=>{a("temperature");try{const d={temperature:l};await i.mutateAsync({agentId:t.id,update:d}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),c.top_p===null?e.jsx(G,{label:"Top P",description:"Controls cumulative probability of tokens to sample from (0.0-1.0).",defaultLabel:N.top_p,onSet:async()=>{a("top_p");try{const l={top_p:N.top_p};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,top_p:N.top_p})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ae,{value:c.top_p??N.top_p,label:"Top P",description:"Controls cumulative probability of tokens to sample from (0.0-1.0).",min:0,max:1,step:.01,isSaving:s==="top_p",onChange:async l=>{a("top_p");try{const d={top_p:l};await i.mutateAsync({agentId:t.id,update:d}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),c.top_k===null?e.jsx(G,{label:"Top K",description:"Limits tokens to sample from at each step.",defaultLabel:N.top_k,onSet:async()=>{a("top_k");try{const l={top_k:N.top_k};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,top_k:N.top_k})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ae,{value:c.top_k??N.top_k,label:"Top K",description:"Limits tokens to sample from at each step.",min:1,max:100,step:1,isSaving:s==="top_k",onChange:async l=>{a("top_k");try{const d={top_k:l};await i.mutateAsync({agentId:t.id,update:d}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),c.seed===null?e.jsx(G,{label:"Seed",description:"Random number seed for deterministic generation.",defaultLabel:N.seed,onSet:async()=>{a("seed");try{const l={seed:N.seed};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,seed:N.seed})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ne,{value:c.seed?.toString()||"",label:"Seed",placeholder:"Random number seed for deterministic generation",icon:e.jsx(Te,{size:16}),isSaving:s==="seed",onSave:async l=>{a("seed");try{const d=l.trim()?Number.parseInt(l,10):void 0;if(l.trim()&&Number.isNaN(d)){ce("Seed must be a valid number");return}const u={seed:d};await i.mutateAsync({agentId:t.id,update:u}),t.id===r&&n&&await n()}catch{}finally{a(null)}}})]}),e.jsxs(De,{title:"Repetition",children:[c.frequency_penalty===null?e.jsx(G,{label:"Frequency penalty",description:"Reduces repetition by lowering likelihood of repeated tokens (-2.0 to 2.0).",defaultLabel:N.frequency_penalty,onSet:async()=>{a("frequency_penalty");try{const l={frequency_penalty:N.frequency_penalty};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,frequency_penalty:N.frequency_penalty})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ae,{value:c.frequency_penalty??N.frequency_penalty,label:"Frequency penalty",description:"Reduces repetition by lowering likelihood of repeated tokens (-2.0 to 2.0).",min:-2,max:2,step:.01,isSaving:s==="frequency_penalty",onChange:async l=>{a("frequency_penalty");try{const d={frequency_penalty:l};await i.mutateAsync({agentId:t.id,update:d}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),c.presence_penalty===null?e.jsx(G,{label:"Presence penalty",description:"Increases diversity by lowering likelihood of prompt tokens (-2.0 to 2.0).",defaultLabel:N.presence_penalty,onSet:async()=>{a("presence_penalty");try{const l={presence_penalty:N.presence_penalty};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,presence_penalty:N.presence_penalty})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ae,{value:c.presence_penalty??N.presence_penalty,label:"Presence penalty",description:"Increases diversity by lowering likelihood of prompt tokens (-2.0 to 2.0).",min:-2,max:2,step:.01,isSaving:s==="presence_penalty",onChange:async l=>{a("presence_penalty");try{const d={presence_penalty:l};await i.mutateAsync({agentId:t.id,update:d}),t.id===r&&n&&await n()}catch{}finally{a(null)}}})]}),e.jsxs(De,{title:"Length and stopping",children:[c.max_tokens===null?e.jsx(G,{label:"Max tokens",description:"Maximum tokens to generate in response.",defaultLabel:N.max_tokens,onSet:async()=>{a("max_tokens");try{const l={max_tokens:N.max_tokens};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,max_tokens:N.max_tokens})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ae,{value:c.max_tokens??N.max_tokens,label:"Max tokens",description:"Maximum tokens to generate in response.",min:1,max:8192,step:1,isSaving:s==="max_tokens",onChange:async l=>{a("max_tokens");try{const d={max_tokens:l};await i.mutateAsync({agentId:t.id,update:d}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),c.stop===null?e.jsx(G,{label:"Stop sequences",description:"Sequences that will cause the model to stop generating text.",defaultLabel:"empty",onSet:async()=>{a("stop");try{const l={stop:[]};await i.mutateAsync({agentId:t.id,update:l}),g(d=>({...d,stop:[]})),t.id===r&&n&&await n()}catch{}finally{a(null)}}}):e.jsx(ne,{value:c.stop?.join(`
32
- `)||"",label:"Stop sequences",placeholder:"Enter stop sequences (one per line)...",icon:e.jsx(Te,{size:16}),multiline:!0,rows:3,isSaving:s==="stop",onSave:async l=>{a("stop");try{const d=l.split(`
33
- `).map(b=>b.trim()).filter(b=>b.length>0),u={stop:d.length>0?d:void 0};await i.mutateAsync({agentId:t.id,update:u}),t.id===r&&n&&await n()}catch{}finally{a(null)}}})]})]})]})]})},jt=["investment","accounting","healthcare","legal","software","security","role_play","personal_assistance","education","marketing","sales","research","analysis","management","social_media","other"],ge=Object.fromEntries(jt.map(t=>[t,t.split("_").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")])),ss=({value:t,label:s,onChange:a,placeholder:i="Add category...",disabled:n=!1,icon:r})=>{const[c,g]=o.useState(""),[m,k]=o.useState(!1),[y,f]=o.useState(0),l=o.useRef(null),d=o.useRef([]),u=o.useId(),b=o.useId(),v=o.useMemo(()=>{const x=c.trim().toLowerCase();return jt.filter(w=>!t.includes(w)&&(!x||ge[w].toLowerCase().includes(x)))},[t,c]);o.useEffect(()=>{m&&d.current[y]?.scrollIntoView({block:"nearest"})},[y,m]);const _=x=>{t.includes(x)||a([...t,x]),g(""),k(!1),f(0),l.current?.focus()},S=x=>{g(x.target.value),f(0),k(!0)},I=x=>{const w=v.length;switch(x.key){case"ArrowDown":if(x.preventDefault(),w===0)break;m?f((y+1)%w):(f(0),k(!0));break;case"ArrowUp":if(x.preventDefault(),w===0)break;m?f((y-1+w)%w):(f(w-1),k(!0));break;case"Enter":m&&v[y]&&(x.preventDefault(),_(v[y]));break;case"Escape":m&&(x.preventDefault(),k(!1));break;case"Home":m&&(x.preventDefault(),f(0));break;case"End":m&&(x.preventDefault(),f(v.length-1));break}},C=x=>{a(t.filter(w=>w!==x)),f(0)},L=m&&v[y]?`${b}-option-${y}`:void 0;return e.jsxs("div",{children:[e.jsxs(le,{htmlFor:u,className:"mb-1.5 flex items-center gap-2 text-ink-muted",children:[r,s]}),e.jsxs("div",{className:z("flex min-h-11 flex-wrap items-center gap-2 rounded-sm border border-control bg-surface p-2","has-[input:focus-visible]:outline-solid has-[input:focus-visible]:outline-2","has-[input:focus-visible]:outline-accent has-[input:focus-visible]:outline-offset-2",n&&"border-hairline bg-sunken"),children:[t.map(x=>e.jsxs(ut,{className:"gap-1 pr-1 text-ink",children:[ge[x]||x,e.jsx("button",{type:"button","aria-label":`Remove category ${ge[x]||x}`,disabled:n,onClick:()=>C(x),className:z("rounded-xs text-ink-dim","transition-colors duration-fast ease-out-quart","hover:text-danger disabled:text-ink-disabled"),children:e.jsx(mt,{})})]},x)),e.jsxs(Gt,{open:m,onOpenChange:k,children:[e.jsx(Qt,{asChild:!0,children:e.jsx("input",{id:u,ref:l,type:"text",role:"combobox","aria-expanded":m,"aria-controls":b,"aria-autocomplete":"list","aria-activedescendant":L,autoComplete:"off",value:c,placeholder:i,disabled:n,"aria-label":s,onChange:S,onKeyDown:I,onClick:()=>{v.length>0&&k(!0)},className:z("min-w-20 flex-1 bg-transparent px-1 py-0.5 outline-none","text-body-sm text-ink placeholder:text-ink-dim","disabled:text-ink-disabled disabled:placeholder:text-ink-disabled")})}),e.jsx(Ft,{align:"start",sideOffset:4,onOpenAutoFocus:x=>x.preventDefault(),className:"max-h-60 w-(--radix-popover-trigger-width) overflow-y-auto p-1",children:e.jsx("div",{id:b,role:"listbox","aria-label":s,children:v.map((x,w)=>e.jsx("div",{id:`${b}-option-${w}`,ref:j=>{d.current[w]=j},role:"option","aria-selected":w===y,onMouseDown:j=>{j.preventDefault()},onMouseEnter:()=>f(w),onClick:()=>_(x),className:z("cursor-pointer rounded-sm px-3 py-1.5 font-medium text-body-sm",w===y?"bg-accent-wash":void 0,"text-ink"),children:ge[x]||x},x))})})]})]}),t.length===0&&e.jsx("span",{className:"mt-1 ml-1 block text-ink-dim text-meta",children:"No categories selected"})]})},ns=({value:t,label:s,onChange:a,placeholder:i="Add tag...",disabled:n=!1,icon:r})=>{const[c,g]=o.useState(""),m=o.useRef(null),k=o.useId(),y=u=>{g(u.target.value)},f=()=>{const u=c.trim().toLowerCase();u&&!t.includes(u)&&a([...t,u]),g("")},l=u=>{u.key==="Enter"&&c.trim()?(u.preventDefault(),f()):u.key==="Backspace"&&!c&&t.length>0&&a(t.slice(0,-1))},d=u=>{a(t.filter(b=>b!==u))};return e.jsxs("div",{children:[e.jsxs(le,{htmlFor:k,className:"mb-1.5 flex items-center gap-2 text-ink-muted",children:[r,s]}),e.jsxs("div",{className:z("flex min-h-11 flex-wrap items-center gap-2 rounded-sm border border-control bg-surface p-2","has-[input:focus-visible]:outline-solid has-[input:focus-visible]:outline-2","has-[input:focus-visible]:outline-accent has-[input:focus-visible]:outline-offset-2",n&&"border-hairline bg-sunken"),children:[t.map(u=>e.jsxs(ut,{className:"gap-1 pr-1 text-ink",children:[u,e.jsx("button",{type:"button","aria-label":`Remove tag ${u}`,disabled:n,onClick:()=>d(u),className:z("rounded-xs text-ink-dim","transition-colors duration-fast ease-out-quart","hover:text-danger disabled:text-ink-disabled"),children:e.jsx(mt,{})})]},u)),e.jsx("input",{id:k,ref:m,type:"text",value:c,onChange:y,onKeyDown:l,placeholder:i,disabled:n,"aria-label":s,className:z("min-w-20 flex-1 bg-transparent px-1 py-0.5 outline-none","text-body-sm text-ink placeholder:text-ink-dim","disabled:text-ink-disabled disabled:placeholder:text-ink-disabled")}),c.trim()&&e.jsx(D,{variant:"ghost",size:"icon-sm","aria-label":"Add tag",disabled:n,onClick:()=>{f(),m.current?.focus()},className:"text-accent hover:text-accent",children:e.jsx(pt,{})})]}),t.length===0&&!c&&e.jsx("span",{className:"mt-1 ml-1 block text-ink-dim text-meta",children:"No tags added"})]})},is=({selectedAgent:t,savingField:s,setSavingField:a,updateAgentMutation:i,refetchAgent:n,initialSelectedAgentId:r})=>{const{data:c,isLoading:g}=Et(),[m,k]=o.useState("");o.useEffect(()=>{!g&&c?.values?k(t.hosting||c.values.hosting||""):g||k(t.hosting||"")},[t,c,g]);const[y,f]=o.useState(!1),[l,d]=o.useState(!1);return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(ne,{value:t.name,label:"Agent name",placeholder:"Enter agent name...",isSaving:s==="name",onSave:async u=>{if(!u.trim()){ce("Agent name cannot be empty");return}a("name");try{const b={name:u};await i.mutateAsync({agentId:t.id,update:b}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx("div",{"data-tour-tag":"agent-settings-hosting-select",children:e.jsx(la,{value:t.hosting||(c?.values.hosting??""),isSaving:s==="hosting",onSave:async u=>{a("hosting"),k(u);try{const b={hosting:u,model:""};await i.mutateAsync({agentId:t.id,update:b}),t.id===r&&n&&await n()}catch{k(t.hosting||"")}finally{a(null)}},filterByCredentials:!0,allowDefault:!0},`hosting-select-${t.id}-${t.hosting||(c?.values.hosting??"default")}`)}),e.jsx("div",{"data-tour-tag":"agent-settings-model-select",children:m?e.jsx(ca,{value:t.hosting?t.model||"":t.model||(c?.values.model_name??""),hostingId:m,isSaving:s==="model",allowDefault:!0,onSave:async u=>{a("model");try{const b={model:u};await i.mutateAsync({agentId:t.id,update:b}),t.id===r&&n&&await n()}catch{}finally{a(null)}}},`model-select-${t.id}-${m}-${t.model||(!t.hosting&&c?.values.model_name?c.values.model_name:"default")}`):e.jsxs("div",{className:"relative",children:[e.jsx(A,{content:"Select a hosting provider first, and then select the AI model that you want to use. Each model has different capabilities and costs. Recommended: Automatic",children:e.jsxs("div",{className:"mb-1.5 flex w-fit items-center gap-2 text-body-sm text-ink-muted",children:[e.jsx(da,{size:16,"aria-hidden":"true"}),"Model"]})}),e.jsx("div",{className:"flex h-8 w-full items-center rounded-sm border border-control bg-surface px-3",children:e.jsx("span",{className:"truncate text-body-sm text-ink-disabled",children:"Select a hosting provider first..."})})]})})]}),e.jsxs("h2",{className:"mt-4 flex items-center gap-2 text-heading text-ink",children:[e.jsx(je,{size:16,className:"shrink-0 text-ink-dim"}),"Agent information"]}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(ne,{value:t.description||"",label:"Description",placeholder:"Enter agent description...",multiline:!0,rows:3,isSaving:s==="description",onSave:async u=>{a("description");try{const b={description:u};await i.mutateAsync({agentId:t.id,update:b}),t.id===r&&n&&await n()}catch{}finally{a(null)}}}),e.jsx(ns,{value:t.tags||[],label:"Tags",placeholder:"Add tag...",disabled:y,onChange:async u=>{if(!(Array.isArray(t.tags)&&u.length===t.tags.length&&u.every((b,v)=>b===t.tags?.[v]))){f(!0);try{const b={tags:u};await i.mutateAsync({agentId:t.id,update:b}),t.id===r&&n&&await n()}catch{}finally{f(!1)}}}}),e.jsx(ss,{value:t.categories||[],label:"Categories",placeholder:"Add category...",disabled:l,onChange:async u=>{if(!(Array.isArray(t.categories)&&u.length===t.categories.length&&u.every((b,v)=>b===t.categories?.[v]))){d(!0);try{const b={categories:u};await i.mutateAsync({agentId:t.id,update:b}),t.id===r&&n&&await n()}catch{}finally{d(!1)}}}}),e.jsxs(ua,{children:[e.jsx(Ie,{label:e.jsxs(e.Fragment,{children:[e.jsx(Ga,{size:12,"aria-hidden":"true"}),"ID"]}),value:e.jsx("span",{className:"font-mono text-mono-sm",children:t.id})}),e.jsx(Ie,{label:e.jsxs(e.Fragment,{children:[e.jsx(ma,{size:12,"aria-hidden":"true"}),"Created"]}),value:Ot(t.created_date)}),e.jsx(Ie,{label:e.jsxs(e.Fragment,{children:[e.jsx(Va,{size:12,"aria-hidden":"true"}),"Version"]}),value:t.version})]})]})]})},os=({selectedAgent:t,savingField:s,setSavingField:a,updateAgentMutation:i,refetchAgent:n,initialSelectedAgentId:r})=>e.jsxs("div",{"data-tour-tag":"agent-settings-security",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-heading text-ink",children:[e.jsx(ha,{size:16,className:"shrink-0 text-ink-dim"}),"Security instructions",e.jsx(A,{content:`Security instructions that guide the agent's behavior and limitations. This is the "system prompt" for the security agent.`,children:e.jsx(D,{variant:"ghost",size:"icon-sm","aria-label":"About security instructions",children:e.jsx(je,{})})})]}),e.jsx("p",{className:"mt-1 max-w-2xl text-body-sm text-ink-muted",children:`This prompt is directed to the AI security reviewer. It helps the reviewer decide whether to block or allow actions based on safety. Write as if talking to another agent that is watching this agent (eg. "Allow all git operations", "Don't let the agent access drive files in the restricted folder"). Update this to allow the agent to perform actions if you are getting frequent security blocks.`}),e.jsx("div",{className:"mt-4",children:e.jsx(ne,{value:t.security_prompt||"",label:"",placeholder:"Enter instructions for the security agent...",multiline:!0,rows:6,isSaving:s==="security_prompt",onSave:async c=>{a("security_prompt");try{const g={security_prompt:c};await i.mutateAsync({agentId:t.id,update:g}),t.id===r&&n&&await n()}catch{}finally{a(null)}}})})]}),rs=({selectedAgent:t,savingField:s,setSavingField:a,refetchAgent:i,initialSelectedAgentId:n})=>{const{data:r,isLoading:c}=yt(t.id),g=Ja(t.id),[m,k]=o.useState("");return o.useEffect(()=>{r!==void 0&&k(r)},[r]),e.jsxs("div",{"data-tour-tag":"agent-settings-system-prompt",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-heading text-ink",children:[e.jsx(va,{size:16,className:"shrink-0 text-ink-dim"}),"Agent instructions",e.jsx(A,{content:`System instructions that define the agent's behavior and capabilities. This is the agent's "system prompt".`,children:e.jsx(D,{variant:"ghost",size:"icon-sm","aria-label":"About agent instructions",children:e.jsx(je,{})})})]}),e.jsx("p",{className:"mt-1 max-w-2xl text-body-sm text-ink-muted",children:`Define the agent's role, personality, or provide context. Write as if talking to the agent (e.g., "You are an expert researcher") and/or about yourself (e.g., "My name is John").`}),e.jsx("div",{className:"mt-4",children:e.jsx(ne,{value:m,label:"",placeholder:c?"Loading system prompt...":"Enter instructions for the agent...",multiline:!0,rows:6,isSaving:s==="system_prompt",onSave:async y=>{a("system_prompt");try{await g.mutateAsync(y),t.id===n&&i&&await i()}finally{a(null)}}})})]})},ls=({selectedAgent:t,refetchAgent:s,initialSelectedAgentId:a})=>{const[i,n]=o.useState(null),r=pa();return e.jsx("div",{"data-tour-tag":"agent-settings-details-paper",className:"h-full overflow-hidden",children:t?e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsxs("div",{className:"mx-auto flex w-full max-w-4xl flex-col gap-8 pb-8",children:[e.jsx(is,{selectedAgent:t,savingField:i,setSavingField:n,updateAgentMutation:r,refetchAgent:s,initialSelectedAgentId:a}),e.jsx(rs,{selectedAgent:t,savingField:i,setSavingField:n,refetchAgent:s,initialSelectedAgentId:a}),e.jsx(os,{selectedAgent:t,savingField:i,setSavingField:n,updateAgentMutation:r,refetchAgent:s,initialSelectedAgentId:a}),e.jsx(as,{selectedAgent:t,savingField:i,setSavingField:n,updateAgentMutation:r,refetchAgent:s,initialSelectedAgentId:a})]})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-8 text-center",children:[e.jsx(Ue,{size:48,className:"text-ink-dim","aria-hidden":"true"}),e.jsx("h2",{className:"text-heading text-ink",children:"No agent selected"}),e.jsx("p",{className:"max-w-md text-body-sm text-ink-muted",children:"Select an agent from the list on the left to view its configuration and details."})]})})},ze=wa()(Na(t=>({listings:{},remember:(s,a)=>{t(i=>({listings:{...i.listings,[s]:a}}))},forget:s=>{t(a=>{if(!(s in a.listings))return a;const i={...a.listings};return delete i[s],{listings:i}})}}),{name:"published-listings-storage"})),cs=t=>ze(s=>t?s.listings[t]??null:null),ds=400,us=2,ms=t=>[...t].length>=us;function hs(t){if(!t)return{state:"unknown",builtinName:null};if(t.available)return{state:"available",builtinName:null};const s=t.details?.builtin_name??null;return t.code==="name_taken"?{state:"taken",builtinName:null}:t.code==="name_reserved_builtin"?{state:"reserved",builtinName:s}:{state:"unknown",builtinName:null}}const ps=(t,s)=>{const a=t.trim(),i=xt(a,ds),n=s&&i===a&&ms(i)&&Ca(i),r=Xe({queryKey:["agent-name-availability",i],enabled:n,queryFn:async()=>(await Le.getAgentNameAvailability(Z.baseUrl,i)).result,retry:!1,staleTime:15e3,refetchOnWindowFocus:!1});return!n||r.isPending?{state:n?"checking":"idle",builtinName:null}:r.isError?{state:"unknown",builtinName:null}:hs(r.data)},xs=()=>{const t=et();return tt({mutationFn:async({agentId:s,document:a,hubAgentId:i,target:n,policy:r})=>{if(!Z.baseUrl)throw new Error("Local Operator API URL is not configured.");return i?Le.republishAgentInstructionSet(Z.baseUrl,s,i,a,n,r):Le.publishAgentInstructionSet(Z.baseUrl,s,a,n,r)},onSuccess:(s,a)=>{const i=s.result;i?.agent_id&&!a.target&&ze.getState().remember(a.agentId,{hubAgentId:i.agent_id,name:i.name,publishedAt:new Date().toISOString()}),i?.local_link_receipt&&t.invalidateQueries({queryKey:xa}),a.target?Oa(t,a.target.tenantId):Ra(t)},onError:s=>{console.error("Publishing an agent to the hub failed:",s)}})},fe="public",kt=({open:t,onClose:s,agent:a,isAuthenticated:i,onSignInSuccess:n,onPublished:r})=>{const[c,g]=o.useState(!1),[m,k]=o.useState(""),[y,f]=o.useState(null),[l,d]=o.useState(null),[u,b]=o.useState(!1),v=o.useRef(null),_=o.useRef(null),S=Re(),I=xs();Rt();const[C,L]=o.useState(Pe),x=o.useRef(null),w=o.useRef({open:!1,id:null}),j=cs(a?.id??null),T=Ut(),O=zt(T.data,"hub_links"),H=ga(t&&O),ke=qt(),de=$t(T.data,"radient_org"),ve=Ea(de),ue=i?Ta(de,ke??null):null,{memberships:F,isError:we}=Sa({enabled:t&&i&&ve}),J=o.useMemo(()=>Ia(F),[F]),Y=o.useMemo(()=>Pa(F),[F]),[q,me]=o.useState(fe),p=q!==fe,E=(H.data?.links??[]).filter(h=>h.kind==="agent"&&h.local_id===a?.id),P=E.find(h=>h.visibility===(p?"org":"public")&&h.tenant_id===(p?q:null)),$=E.find(h=>h.link_id!==P?.link_id),W=H.data?.unresolved.some(h=>h.kind==="agent"&&h.local_id===a?.id),M=J.find(h=>h.tenant_id===q),he=p?M?.tenant_name?K("ui.hub.links.source_private",{organization:M.tenant_name}):K("ui.hub.links.source_unavailable"):K("ui.hub.links.source_public"),oe=J.find(h=>h.tenant_id===q)?.tenant_name||"this organization",pe=o.useId(),xe=o.useId(),{data:qe}=yt(t&&a?a.id:""),{data:$e}=Mt(t);o.useEffect(()=>{t&&(!w.current.open||w.current.id!==(a?.id??null))&&k(a?.name??""),w.current={open:t,id:a?.id??null}},[t,a?.id,a?.name]),o.useEffect(()=>{t||(g(!1),f(null),d(null),b(!1),me(fe),L(Pe()),x.current=null)},[t]);const vt=o.useMemo(()=>($e??[]).filter(h=>h.source==="builtin").map(h=>h.name),[$e]),Me=Ua(m,vt),Ae=ps(m,t&&i),X=o.useMemo(()=>{const h=za({name:m,description:a?.description??"",instructions:qe??null,tools:qa(a?.tags)});return Me&&h.unshift({field:"name",message:Fe({code:"name_reserved_builtin",message:""},{name:m,hubAgentId:null}).body}),h},[m,a?.description,a?.tags,qe,Me]),R=y?Fe(y,{name:m,hubAgentId:j?.hubAgentId??null}):null,ee=I.isPending,Ne=async h=>{if(!a||ee||X.length>0||p&&!M)return;f(null);const U=h?.asNewListing?null:P?.hub_id??(p?null:j?.hubAgentId??null),Be=!!U;if(!(O&&(!H.isSuccess||$||W)))try{const V={name:m.trim()},We=JSON.stringify({agent:a.id,document:V,hubAgentId:U,target:q,policy:P?null:C}),Ce=x.current?.tuple===We?x.current:{tuple:We,id:crypto.randomUUID()};x.current=Ce;const te=(await I.mutateAsync({agentId:a.id,document:V,hubAgentId:U,...O?{policy:P?{requestId:Ce.id,...P.remote_revision&&Be?{expectedRemoteRevision:P.remote_revision}:{}}:{requestId:Ce.id,...C}}:{},target:p?{visibility:"org",tenantId:q}:void 0})).result,Ve={name:te?.name??m.trim(),hubAgentId:te?.agent_id??null,republished:Be,orgName:p?oe:null,localPolicies:te?.local_link_receipt?La(te)?"complete":"pending":O?"pending":null};d(Ve),te&&r?.(te,Ve.republished)}catch(V){f(Ht(V)?{code:V.code,message:V.message,details:V.details}:{message:At(V,"The agent could not be published. Try again.")})}},He=h=>{switch(h){case"focus-name":f(null),requestAnimationFrame(()=>{v.current?.focus(),v.current?.select()});break;case"update-listing":{const U=y?.details?.existing_agent_id??j?.hubAgentId;U&&(s(),S(`/agent-hub/${U}`));break}case"install-builtin":{const U=y?.details?.builtin_name??Ae.builtinName;U&&(s(),S(`/agents?kind=agent&name=${encodeURIComponent(U)}`));break}case"edit-instructions":case"edit-agent":a&&(s(),S(`/agents/${a.id}`));break;case"publish-as-new":a&&ze.getState().forget(a.id),Ne({asNewListing:!0});break;case"sign-in":b(!0);break;case"refresh-hub":s(),S("/agent-hub");break;case"retry":Ne();break}},B=a?.name??"",wt=l?l.orgName?`Published "${B}" to ${l.orgName}`:l.republished?`Updated the Agent hub listing for "${B}"`:`Published "${B}" to the Agent hub`:p?`Publish "${B}" to ${oe}?`:j?`Update the Agent hub listing for "${B}"?`:`Publish "${B}" to the Agent hub?`;o.useLayoutEffect(()=>{!y&&!l||_.current?.focus()},[y,l]);const Nt=l?e.jsxs(e.Fragment,{children:[e.jsx(se,{onClick:s,"data-tour-tag":"upload-agent-dialog-cancel-button",children:"Close"}),l.hubAgentId&&e.jsx(be,{onClick:()=>{s(),S(`/agent-hub/${l.hubAgentId}`)},children:"Open the listing"})]}):R?e.jsxs(e.Fragment,{children:[e.jsx(se,{onClick:s,"data-tour-tag":"upload-agent-dialog-cancel-button",children:"Close"}),R.actions.map((h,U)=>U===0?e.jsx(be,{onClick:()=>He(h),disabled:ee,children:Ye[h]},h):e.jsx(se,{onClick:()=>He(h),disabled:ee,children:Ye[h]},h))]}):e.jsxs(e.Fragment,{children:[e.jsx(se,{onClick:s,"data-tour-tag":"upload-agent-dialog-cancel-button",children:"Cancel"}),X.some(h=>h.field!=="name")&&e.jsx(se,{onClick:()=>{a&&(s(),S(`/agents/${a.id}`))},children:"Edit the agent"}),i&&e.jsx(be,{"data-testid":"publish-submit",onClick:()=>void Ne(),disabled:p&&!M||!c||X.length>0||!m.trim()||ee||O&&(!H.isSuccess||!!$||!!W),children:ee?"Publishing…":j&&!p?"Update listing":"Publish"})]});return e.jsx(at,{open:t,onClose:s,title:wt,maxWidth:"sm",fullWidth:!0,actions:Nt,dataTourTag:"upload-agent-dialog",dialogProps:{className:"outline-none"},children:e.jsxs("div",{ref:_,tabIndex:y||l?-1:void 0,className:z("flex flex-col gap-4",(y||l)&&"outline-none"),children:[i?l?e.jsxs(ye,{variant:"success","aria-live":"polite",children:[e.jsx(_e,{children:l.orgName?`Published to ${l.orgName}`:l.republished?"Listing updated":"Published to the hub"}),e.jsx(re,{children:l.orgName?`"${l.name}" is in ${l.orgName}'s shared agents as an instruction set. Its members can read and install it; nobody outside the organization can.`:l.republished?`The hub now holds the current instruction set of "${l.name}".`:`"${l.name}" is on the hub as an instruction set. Anyone can read and install it.`}),e.jsx(re,{className:"text-ink-muted",children:"Nothing else left this machine: no conversation, no execution history, no memory, no plan and no machine-specific configuration."})]}):R&&y?e.jsxs(ye,{variant:R.variant,role:"alert",children:[e.jsx(_e,{children:R.headline}),e.jsx(re,{children:R.body}),R.note&&e.jsx(re,{className:"text-ink-muted",children:R.note})]}):null:e.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[e.jsx("p",{className:"text-body text-ink",children:"You need to be signed in to Radient to publish agents to the Agent hub."}),e.jsx(Qe,{titleText:"Sign in to continue",descriptionText:"",onSignInSuccess:n})]}),R&&u&&e.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[e.jsx("p",{className:"text-body text-ink",children:"Sign in to Radient again to replace the credential the hub refused."}),e.jsx(Qe,{titleText:"Sign in again",descriptionText:"",onSignInSuccess:()=>{b(!1),f(null),n?.()}})]}),l?.localPolicies==="pending"&&e.jsx("p",{role:"alert",className:"text-body-sm text-warning",children:K("ui.hub.skills.policy_pending")}),!l&&O&&e.jsx("div",{className:"flex flex-col gap-3",children:H.isLoading?e.jsx("p",{className:"text-meta text-ink-muted",children:K("ui.hub.links.loading")}):H.error?e.jsx("p",{role:"alert",className:"text-body-sm text-warning",children:K("ui.hub.links.load_failed")}):$?e.jsx("p",{className:"text-body-sm text-warning",children:K("ui.hub.subscriptions.source_separation",{currentSource:fa($),newSource:he})}):W?e.jsx("p",{className:"text-body-sm text-warning",children:K("ui.hub.links.source_unavailable")}):P?e.jsx(ba,{link:P}):e.jsx(Da,{value:C,onChange:L,source:he,item:m||B,visibility:p?"org":"public",organization:p?oe:null,destinationKey:`${q}:${a?.id??""}`,canEnableAutoPush:!1,disabled:ee||!H.isSuccess})}),!l&&!R&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-body text-ink",children:p?`You are about to publish this agent's instruction set into ${oe}, where only its members can read and install it. What is published is what describes the agent:`:"You are about to publish this agent's instruction set to the public Agent hub. What is published is what describes the agent:"}),e.jsxs("ul",{className:"list-disc space-y-1 pl-5 text-body text-ink-muted",children:[e.jsx("li",{children:"Its name and description"}),e.jsx("li",{children:"Its instructions"}),e.jsx("li",{children:"Its tool surface, effort and delegation, when it has them"})]}),e.jsx("p",{className:"text-body text-ink",children:p?`Nothing else leaves this machine: no conversation, no execution history, no memory or learnings, no plan, and no machine-specific configuration. ${oe}'s members can read and install what you publish; nobody outside it can.`:"Nothing else leaves this machine: no conversation, no execution history, no memory or learnings, no plan, and no machine-specific configuration. Anyone can read and install what you publish."}),J.length>0||Y.length>0?e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(le,{htmlFor:`${pe}-target`,children:"Publish to"}),e.jsxs(Yt,{value:q,onValueChange:h=>{me(h),L(Pe()),x.current=null},children:[e.jsx(Zt,{id:`${pe}-target`,className:"w-full","data-testid":"publish-target",children:e.jsx(Jt,{})}),e.jsxs(Xt,{children:[e.jsx(Se,{value:fe,children:"Public hub"}),J.map(h=>e.jsx(Se,{value:h.tenant_id,children:h.tenant_name||"Organization"},h.tenant_id)),Y.map(h=>e.jsxs(Se,{value:h.tenant_id,disabled:!0,children:[h.tenant_name||"Organization"," (upgrade needed)"]},h.tenant_id))]})]}),e.jsx("p",{className:"text-meta text-ink-muted","data-testid":"publish-target-hint",children:Y.length>0?`Sharing agents inside an organization is part of the Team plan. An owner of ${Y.length===1?Y[0].tenant_name||"this organization":"any of the organizations marked above"} can activate it in the Radient console.`:"Public hub publications are readable by anyone. An organization's agents are readable by its members only."})]}):ue?e.jsx("p",{className:"text-meta text-ink-muted","data-testid":"publish-target-unavailable",children:ue}):we?e.jsx("p",{className:"text-meta text-ink-muted","data-testid":"publish-target-failed",children:"Your organizations could not be read, so this publishes to the public hub. Try again in a moment to publish into an organization."}):null,X.length>0&&e.jsxs(ye,{variant:"danger",children:[e.jsx(_e,{children:"This agent cannot be published yet"}),e.jsx("ul",{className:"list-disc space-y-1 pl-5",children:X.map(h=>e.jsx("li",{children:h.message},`${h.field}:${h.message}`))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(le,{htmlFor:xe,children:"Name on the hub"}),e.jsx(dt,{id:xe,ref:v,value:m,onChange:h=>k(h.target.value),autoComplete:"off",spellCheck:!1,"aria-invalid":X.some(h=>h.field==="name"),"aria-describedby":`${xe}-hint`}),e.jsx("p",{id:`${xe}-hint`,className:"text-meta text-ink-muted",children:'No "/", "\\" or ":". Up to 128 characters.'}),!p&&gs(Ae)]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-5 shrink-0 items-center",children:e.jsx(ea,{id:pe,name:"termsAgreement","data-testid":"publish-consent",checked:c,onCheckedChange:h=>g(h===!0)})}),e.jsxs(le,{htmlFor:pe,className:"block font-normal text-body text-ink",children:["I confirm that I have read and agree to the"," ",e.jsx("a",{href:"https://radienthq.com/terms",target:"_blank",rel:"noopener noreferrer",className:"text-accent underline-offset-4 hover:text-accent-hover hover:underline",children:"terms and conditions"})," ","and that this agent does not contain malicious content or violate usage policies."]})]})]}),(l||R)&&B&&e.jsxs("p",{className:"text-meta text-ink-muted",children:["Agent: ",B]})]})})},gs=t=>{switch(t.state){case"checking":return e.jsx("p",{className:"text-meta text-ink-muted",children:"Checking whether this name is free…"});case"available":return e.jsx("p",{className:"text-meta text-ink-muted",children:"This name looks free."});case"taken":return e.jsx("p",{className:"text-meta text-ink",children:"This name is already published on the hub."});case"reserved":return e.jsx("p",{className:"text-meta text-ink-muted",children:t.builtinName?`The hub reserves "${t.builtinName}" for one of its built-in agents.`:"The hub reserves this name for one of its built-in agents."});default:return null}},fs=1200,bs=({agent:t,isSelected:s,onSelectAgent:a,onChatWithAgent:i,onExportAgent:n,onAgentDeleted:r,onUploadAgentToHub:c})=>{const g=t.description||"No description";return e.jsxs("li",{className:"group relative",children:[e.jsxs("button",{type:"button",onClick:()=>a(t),"aria-current":s?"true":void 0,"data-tour-tag":"agent-list-item-button",className:z("flex w-full items-center gap-2 rounded-sm py-1.5 pr-9 pl-2 text-left","transition-colors duration-fast ease-out-quart",s?ja:"hover:bg-row-hover"),children:[e.jsx(aa,{className:"size-8 shrink-0",children:e.jsx(sa,{className:"border border-control bg-sunken",children:e.jsx(Ue,{size:16,"aria-hidden":!0})})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx(A,{content:t.name,side:"top",align:"start",children:e.jsx("span",{className:"block truncate font-medium text-body-sm text-ink",children:t.name})}),e.jsx(A,{content:g,side:"bottom",align:"start",children:e.jsx("span",{className:"block truncate text-meta text-ink-dim",children:g})})]})]}),e.jsx("div",{className:z("pointer-events-none absolute top-0 right-1 flex h-full items-center","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"),children:e.jsx(A,{content:"Agent options",children:e.jsx("span",{children:e.jsx(Ya,{agentId:t.id,agentName:t.name,isAgentsPage:!0,onAgentDeleted:()=>r(t.id),onChatWithAgent:()=>i(t),onExportAgent:()=>n(t.id),onUploadAgentToHub:()=>c(t),buttonSx:{width:24,height:24,borderRadius:"6px",display:"flex",justifyContent:"center",alignItems:"center"}})})})})]})},ys=(t,s)=>t.isSelected===s.isSelected&&t.agent.id===s.agent.id&&t.agent.name===s.agent.name&&t.agent.description===s.agent.description&&t.onSelectAgent===s.onSelectAgent&&t.onChatWithAgent===s.onChatWithAgent&&t.onExportAgent===s.onExportAgent&&t.onAgentDeleted===s.onAgentDeleted&&t.onUploadAgentToHub===s.onUploadAgentToHub,js=o.memo(bs,ys),ks=({selectedAgentId:t,onSelectAgent:s})=>{const a=Re(),[i,n]=o.useState(""),r=_a(p=>p.openCreateAgentDialog),c=xt(i.trim(),250),[g,m]=o.useState(!1),k=50,[y,f]=o.useState(!1),[l,d]=o.useState(null),{isAuthenticated:u}=st(),b=o.useMemo(()=>Oe(Z.baseUrl),[]),v=gt(),{page:_,setPage:S}=Xa(),{data:I,isLoading:C,isError:L,refetch:x}=ya(_,k,0,c||void 0,"created_date","desc"),w=I?.agents||[],j=I?.total||0,{data:T}=ft(t&&!w.find(p=>p.id===t)?t:void 0),O=o.useMemo(()=>{const p=[...w];return T&&!p.find(E=>E.id===T.id)&&p.push(T),p.sort((E,P)=>new Date(P.created_date).getTime()-new Date(E.created_date).getTime()),p},[w,T]),H=o.useCallback(p=>{S(p)},[S]),ke=o.useCallback(p=>{s(p)},[s]),de=o.useCallback(()=>{m(!0)},[]),ve=o.useCallback(()=>{m(!1)},[]),ue=o.useCallback(async p=>{try{const E=await v.mutateAsync(p),P=O.find(he=>he.id===p),$=P?P.name.replace(/\s+/g,"-").toLowerCase():p,W=URL.createObjectURL(E),M=document.createElement("a");M.href=W,M.download=`${$}-export.zip`,document.body.appendChild(M),M.click(),URL.revokeObjectURL(W),document.body.removeChild(M)}catch(E){console.error("Failed to export agent:",E)}},[O,v]),F=o.useCallback(p=>{d(p),f(!0)},[]),we=o.useCallback(()=>{f(!1),d(null)},[]),J=o.useCallback(async p=>{try{const P=((await x()).data?.agents||[]).find(W=>W.id===p);if(P){s(P);return}const $=await b.agents.getAgent(p);$.status<400&&$.result&&s($.result)}catch(E){console.error("Error selecting newly created agent:",E)}},[s,x,b]),Y=o.useCallback(p=>{nt.getState().stageDraft({kind:"agent",name:p.name}),a("/chat")},[a]),q=o.useCallback(p=>{x(),a("/agents")},[t,x,a]),me=o.useCallback(p=>{F(p)},[F]);return e.jsxs("div",{className:"flex h-full w-full flex-col overflow-hidden bg-surface",children:[e.jsx(ts,{title:"Agents",searchQuery:i,onSearchChange:p=>n(p),onNewAgentClick:r,onImportAgentClick:de,importAgentTooltip:"Import an agent from a ZIP file"}),C?e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsx(ct,{size:"lg",label:"Loading agents"})}):L?e.jsxs(ye,{variant:"danger",role:"alert",className:"m-4 w-auto",children:[e.jsx(re,{children:"Failed to load agents. Please try again."}),e.jsx(D,{variant:"ghost",size:"sm",className:"self-start",onClick:()=>x(),children:"Retry"})]}):O.length===0&&!C?e.jsx("p",{className:"p-6 text-center text-body-sm text-ink-muted",children:i?"No agents match your search":"No agents found"}):e.jsx(ta,{delayDuration:fs,skipDelayDuration:0,children:e.jsx("ul",{className:"flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2",children:O.map(p=>e.jsx(js,{agent:p,isSelected:t===p.id||T?.id===p.id,onSelectAgent:ke,onChatWithAgent:Y,onExportAgent:ue,onAgentDeleted:q,onUploadAgentToHub:me},p.id))})}),e.jsx(es,{open:g,onClose:ve,onAgentImported:J}),j>0&&e.jsx(Za,{page:_,count:Math.max(1,Math.ceil(j/k)),onChange:H}),e.jsx(kt,{open:y,onClose:we,agent:l,isAuthenticated:u})]})},vs=o.memo(ks),zs=()=>{const t=Bt("surface"),{agentId:s,navigateToAgent:a}=ka(),i=Re(),{isAuthenticated:n}=st(),[r,c]=o.useState(!1),g=gt(),{setLastAgentsPageAgentId:m,getLastAgentId:k}=Je(),y=s||k("agents"),{data:f,refetch:l}=ft(y||void 0);o.useEffect(()=>{s&&m(s)},[s,m]);const d=async()=>{if(f)try{const _=await g.mutateAsync(f.id),S=URL.createObjectURL(_),I=document.createElement("a");I.href=S,I.download=`${f.name.replace(/\s+/g,"-").toLowerCase()}-lo-agent.zip`,document.body.appendChild(I),I.click(),URL.revokeObjectURL(S),document.body.removeChild(I)}catch(_){console.error("Failed to export agent:",_)}},u=()=>{c(!0)},b=()=>{c(!1)},v=_=>{m(_.id),a(_.id,"agents")};return e.jsxs("div",{className:"flex h-full w-full overflow-hidden",children:[e.jsx("div",{ref:t,className:"h-full w-70 shrink-0",children:e.jsx(vs,{selectedAgentId:f?.id,onSelectAgent:v})}),e.jsx("div",{className:"h-full grow overflow-hidden",children:e.jsxs("div",{className:"flex h-full flex-col gap-8 p-4 sm:p-6 lg:p-8",children:[e.jsx("div",{className:"mx-auto w-full max-w-4xl",children:e.jsx(Vt,{title:"Agent management",icon:Ue,subtitle:"View, configure and manage your agents",children:f&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(it,{children:[e.jsx(ot,{asChild:!0,children:e.jsx(D,{"data-tour-tag":"upload-to-hub-header-button",variant:"secondary",size:"icon","aria-label":"More agent actions",className:"@min-[400px]:hidden",children:e.jsx(Wt,{"aria-hidden":"true"})})}),e.jsxs(rt,{align:"end",className:"min-w-45",children:[e.jsxs(Q,{disabled:g.isPending,onSelect:d,children:[e.jsx(Ge,{"aria-hidden":"true"}),e.jsx("span",{children:"Export"})]}),e.jsxs(Q,{onSelect:u,children:[e.jsx(Ee,{"aria-hidden":"true"}),e.jsx("span",{children:"Upload to hub"})]})]})]}),e.jsxs(D,{variant:"secondary",onClick:d,disabled:g.isPending,className:"hidden @min-[400px]:inline-flex",children:[e.jsx(Ge,{"aria-hidden":"true"}),"Export"]}),e.jsxs(D,{"data-tour-tag":"upload-to-hub-header-button","data-tour-action":"open-upload-dialog",variant:"secondary",onClick:u,className:"hidden @min-[400px]:inline-flex",children:[e.jsx(Ee,{"aria-hidden":"true"}),"Upload to hub"]}),e.jsx(A,{content:`Chat with ${f.name||"this agent"}`,children:e.jsxs(D,{variant:"primary",onClick:()=>{nt.getState().stageDraft({kind:"agent",name:f.name}),i("/chat")},children:[e.jsx(ht,{"aria-hidden":"true"}),"Chat"]})})]})})}),e.jsx("div",{className:"min-h-0 grow overflow-hidden",children:e.jsx(ls,{selectedAgent:f??null,refetchAgent:l,initialSelectedAgentId:s})})]})}),f&&e.jsx(kt,{open:r,onClose:b,agent:f,isAuthenticated:n})]})};export{zs as LegacyAgentsPage};
@@ -1 +0,0 @@
1
- import{r as x,j as t,c as _}from"./index-DF_hRerL.js";import{aQ as ze,aR as je,aS as Qe,aT as He,a as Je,aU as ge,aq as Ce,aV as et}from"./conversation-input-sync-BX8IVirL.js";import{P as tt}from"./page-header-BR-fmx4f.js";import{B as U,A as pe,p as st,h as ae,q as nt,r as at,s as it,t as rt,u as Se,v as Me,k as De}from"./error-boundary-BDLNfQKz.js";import{i as oe,d as lt,e as ot,f as dt,g as ct,h as ut,j as mt,k as ht,l as pt,m as xt,n as ft,o as gt,p as bt,N as vt,q as Ne,r as kt,s as de,D as wt,t as jt,u as Nt,v as ye,w as we,R as yt,x as ce,y as Be,z as Fe,C as It,E as he,F as be,G as Ct,H as St,I as xe,J as Ae,K as Mt,L as Dt,M as ve,O as At,Q as qe,T as Et,U as Ue,V as _t,W as Rt,X as $t,Y as Lt,Z as Pt,_ as Tt,$ as Ot,a0 as Wt,a1 as zt,a2 as Ht,a3 as Bt,a4 as Ft,a5 as qt,a6 as Ut,a7 as Yt,a8 as Gt,a9 as Vt,aa as Kt,ab as Xt,ac as le,ad as Zt}from"./index-CnQsclLj.js";import"./messages-Yrm2FT2V.js";import"./console-mirror-DpL-JwpC.js";function Qt(e){return e==="failed"?"text-danger":oe(e)?"text-ink-muted":"text-ink-dim"}function Jt(e){return e==="failed"?"Abandon":"Stop"}function es(e){switch(e){case"requested":return[{term:"Signing",text:"Approving signs with this machine's operator key; the system may ask for it."}];case"approved":return[{term:"Next",text:"An agent runs the install and connect."},{term:"Stop",text:"Stopping now denies the request; nothing has run yet."}];case"connecting":return[{term:"Stop",text:"Stopping now denies the request; the runner stops at its next step."}];case"failed":return[{term:"After a stop",text:"The runner stopped before it finished. Abandoning denies the request; a retry re-enters the same record instead."}];default:return[]}}const ts=({rows:e,error:s,pending:i,refusal:a,onDecide:o,onRetry:c,nowSeconds:h,networkNames:r})=>{const g=i!==null,v=x.useMemo(()=>e.filter(f=>oe(f.state)),[e]),N=x.useMemo(()=>e.filter(f=>!oe(f.state)),[e]),[y,I]=x.useState(!1),l=N.some(f=>f.state==="failed"),d=N.filter(f=>f.state==="failed").length,p=a!==null&&e.some(f=>f.approvalId===a.approvalId&&(oe(f.state)||y));return v.length===0&&N.length===0&&!s&&!a?null:t.jsxs("section",{"aria-label":"Approvals","data-tour-tag":"mesh-approvals-tray",className:"flex flex-col gap-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(lt,{"aria-hidden":"true",className:"size-4 text-ink-muted"}),t.jsx("h2",{className:"text-body-sm text-ink",children:"Approvals"}),v.length>0&&t.jsx("span",{className:"text-meta text-ink-dim",children:v.length===1?"1 waiting":`${v.length} waiting`})]}),s&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("p",{className:"min-w-0 flex-1 text-meta text-ink-muted",children:s}),t.jsx(U,{variant:"secondary",size:"sm",onClick:c,children:"Ask again"})]}),v.length>0&&t.jsx("ul",{className:"flex flex-col divide-y divide-hairline",children:v.map(f=>t.jsx(Ee,{row:f,pending:i?.approvalId===f.approvalId?i:null,busy:g,refusal:a?.approvalId===f.approvalId?a:null,onDecide:o,nowSeconds:h,networkNames:r},f.approvalId))}),a&&!p&&t.jsx(Ye,{refusal:a}),N.length>0&&t.jsx(ze,{open:y,onOpenChange:I,chevronClassName:"text-ink-dim",className:_(v.length>0&&"border-hairline border-t pt-3"),summary:t.jsxs("span",{className:"flex items-center gap-1.5 text-meta text-ink-muted",children:["Settled approvals",t.jsxs("span",{className:"text-ink-dim",children:["(",N.length,")"]}),l&&t.jsx("span",{"aria-hidden":"true",className:"size-1.5 rounded-full bg-danger"}),d>0&&t.jsxs("span",{className:"text-danger",children:[d," failed"]})]}),children:t.jsx("ul",{className:"flex flex-col divide-y divide-hairline","data-tour-tag":"mesh-approvals-records",children:N.map(f=>t.jsx(Ee,{row:f,pending:i?.approvalId===f.approvalId?i:null,busy:g,refusal:a?.approvalId===f.approvalId?a:null,onDecide:o,nowSeconds:h,networkNames:r},f.approvalId))})})]})},Ee=({row:e,pending:s,busy:i,refusal:a,onDecide:o,nowSeconds:c,networkNames:h})=>{const r=oe(e.state),g=ot(e),v=dt(e,h),N=ct(e,h),y=ut(e),I=mt(e),l=ht(e),d=pt(e.expiresAt,c),p=es(e.state),f=xt(e.state),w=ft(e.state);return t.jsxs("li",{className:"flex flex-col gap-2 py-3 first:pt-0 last:pb-0","data-tour-tag":"mesh-approval-card",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:_("text-meta",Qt(e.state)),children:gt(e.state)}),t.jsx("div",{className:"grow"}),r&&d&&t.jsx("span",{className:"text-meta text-ink-dim",children:d})]}),t.jsx("p",{className:"text-body-sm text-ink","data-tour-tag":"mesh-approval-summary",children:r?v:g}),e.state==="failed"&&t.jsx("p",{className:"text-meta text-ink-muted","data-tour-tag":"mesh-approval-stopped-note",children:"The runner stopped before it finished. It stays retryable until its window closes; Abandon denies the request."}),(f||w)&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f&&t.jsx(U,{variant:"primary",size:"sm",disabled:i,onClick:()=>o(e.approvalId,"approve"),"data-tour-tag":"mesh-approval-approve",children:"Approve"}),w&&t.jsx(U,{variant:"ghost",size:"sm",disabled:i,onClick:()=>o(e.approvalId,"deny"),"data-tour-tag":r?"mesh-approval-deny":"mesh-approval-stop",children:r?"Deny":Jt(e.state)}),s&&t.jsx("span",{className:"text-meta text-ink-dim",children:s.decision==="approve"?"Waiting for the signing prompt…":"Writing the decision…"})]}),t.jsxs(ze,{chevronClassName:"text-ink-dim",summary:t.jsx("span",{className:"text-meta",children:"Details"}),children:[N.length>0&&t.jsx("dl",{className:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-0.5 text-meta text-ink-dim","data-tour-tag":"mesh-approval-consequences",children:N.map(m=>t.jsxs(x.Fragment,{children:[t.jsx("dt",{className:"text-ink-muted",children:m.term}),t.jsx("dd",{children:m.consequence})]},m.term))}),(y||I)&&t.jsxs("p",{className:"text-meta text-ink-muted",children:[y&&t.jsx("span",{children:y}),y&&I&&t.jsx("span",{children:" · "}),I&&t.jsx("span",{className:"font-mono",children:I})]}),l&&t.jsx("p",{className:"text-meta text-ink-dim",children:l}),p.length>0&&t.jsx("dl",{className:"grid grid-cols-[max-content_1fr] gap-x-4 gap-y-0.5 text-meta","data-tour-tag":"mesh-approval-consequence",children:p.map(m=>t.jsxs(x.Fragment,{children:[t.jsx("dt",{className:"text-ink-muted",children:m.term}),t.jsx("dd",{className:"text-ink-muted",children:m.text})]},m.term))})]}),a&&t.jsx(Ye,{refusal:a})]})},Ye=({refusal:e})=>t.jsx(pe,{variant:"warning",className:"text-meta","data-tour-tag":"mesh-approval-refusal",children:t.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[t.jsx("span",{className:"min-w-0 flex-1",children:e.sentence}),t.jsx("span",{className:"shrink-0 font-mono text-ink-dim",children:e.code})]})}),ss=4,fe={kind:"idle"};function ns(e){switch(e.kind){case"dragging":case"settling":return e.payload.session.id;case"pressing":return null;default:return null}}function J(e,s){switch(s.kind){case"press":return e.kind!=="idle"?e:{kind:"pressing",payload:s.payload,originX:s.x,originY:s.y,pointerId:s.pointerId};case"move":return e.kind==="pressing"?Math.max(Math.abs(s.x-e.originX),Math.abs(s.y-e.originY))<ss?e:{kind:"dragging",payload:e.payload,x:s.x,y:s.y,target:s.target,pointerId:e.pointerId}:e.kind==="dragging"?{...e,x:s.x,y:s.y,target:s.target}:e;case"release":return e.kind==="dragging"?{kind:"settling",payload:e.payload,target:e.target}:e.kind==="pressing"?fe:e;case"cancel":case"settled":return fe;default:return e}}const as=({edges:e,geometry:s,selectedDeviceId:i})=>t.jsx("svg",{"aria-hidden":"true",className:"pointer-events-none absolute top-0 left-0 overflow-visible",width:s.bounds.width,height:s.bounds.height,children:e.map(a=>{const o=s.networks.get(a.networkId),c=s.devices.get(a.deviceId);if(!o||!c)return null;const h=i!==null&&a.deviceId===i;return t.jsx("path",{"data-mesh-edge":a.key,d:bt(o,c),fill:"none",strokeWidth:h?2:1.5,strokeDasharray:a.active?void 0:"4 4",className:h?"stroke-ink":"stroke-ink-dim"},a.key)})}),is={self:"border-l-hairline",reached:"border-l-hairline",unanswered:"border-l-warning","not-attempted":"border-l-hairline",unknown:"border-l-hairline"};function rs(e){return e.suspect?"border-l-danger":is[de(e)]}const ls={self:"ring-2 ring-accent",reachable:null,unreachable:null,suspect:null},os={accept:"border-accent bg-accent-wash",refuse:"border-warning"};function ds(e,s,i){return[e.label,Fe(e,s),i].filter(Boolean).join(", ")}function ee(e){return e.name.trim()||e.id.slice(-6)}function Ge(e,s,i){if(i!=="reached"&&i!=="self"){const a=ce(i);return e.unreachable_reason?`${a} (${e.unreachable_reason})`:a}return e.live_state.trim()?e.live_state.trim():e.locality==="local"?"on this device":`on ${s}`}const cs={resting:"border-l-2 border-l-hairline",attention:"border-l-2 border-l-warning"},us=({network:e,x:s,y:i,refused:a})=>t.jsxs("li",{"data-mesh-network":e.id,"data-mesh-network-refused":a?"true":void 0,className:_("absolute flex items-center gap-2 rounded-md border bg-elevated px-3",a?"border-warning":"border-hairline"),style:{left:s,top:i,width:Ne,height:vt},children:[t.jsx(je,{"aria-hidden":"true",className:"size-4 shrink-0 text-ink-muted"}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block truncate text-body-sm text-ink",children:e.label}),t.jsxs("span",{title:`epoch ${e.epoch}`,className:"block truncate text-meta text-ink-dim",children:[e.memberCount," ",e.memberCount===1?"device":"devices",e.revokedCount>0?` · ${e.revokedCount} revoked`:""]})]})]}),ms=({device:e,x:s,y:i,nowSeconds:a,selected:o,sessions:c,sessionTotal:h,dropState:r,movingSessionId:g,draggedSessionId:v,onOpen:N,onChipPointerDown:y,onChipClick:I,onShowAllSessions:l})=>{const{activity:d}=kt(e,c.rows),p=d==="working",f=ds(e,a,p?"working":null),w=de(e);return t.jsxs("li",{"data-mesh-device":e.id,"data-mesh-state":e.state,"data-mesh-drop":r??void 0,"aria-current":o?"true":void 0,className:_("absolute flex flex-col rounded-md border border-l-4 border-control bg-elevated","hover:bg-row-hover",o&&"border-y-ink border-r-ink bg-row-selected",rs(e),ls[e.state],r&&os[r]),style:{left:s,top:i,width:Ne,height:wt},children:[t.jsxs("button",{type:"button","data-mesh-device-open":e.id,"data-mesh-reach":w,"aria-label":f,title:Nt(e),onClick:()=>N(e.id),className:_("flex w-full flex-col justify-between rounded-t-[5px] px-3 pt-2 pb-2 text-left","cursor-pointer","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-[-2px]"),style:{height:jt},children:[t.jsxs("span",{className:"flex w-full min-w-0 items-center gap-2",children:[t.jsx(Qe,{"aria-hidden":"true",className:"size-4 shrink-0 text-ink-muted"}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-body-sm text-ink",children:e.label}),e.suspect&&t.jsx(ye,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-danger"})]}),t.jsxs("span",{className:"flex w-full min-w-0 items-baseline gap-1",children:[t.jsx("span",{className:"w-3 shrink-0 font-mono text-body-sm text-ink tabular-nums",children:e.sessionCount??"–"}),t.jsx("span",{className:_("min-w-0 truncate text-meta",e.sessionCount===null?"text-ink-dim":"text-ink-muted"),children:we(e.sessionCount)})]}),t.jsxs("span",{"data-mesh-state-line":"",className:"flex w-full min-w-0 items-baseline gap-1.5 text-meta",children:[t.jsx("span",{"aria-hidden":"true",className:"shrink-0 text-ink-dim",children:yt[w]}),t.jsx("span",{className:_("shrink-0",Be[w]),children:ce(w)}),p&&t.jsx("span",{"data-mesh-working":"",className:"shrink-0 text-info",children:"working"}),e.memberships.length>1&&t.jsxs("span",{className:"min-w-0 truncate text-ink-dim",children:["· ",e.memberships.length," networks"]})]})]}),t.jsxs("ul",{"aria-label":`Conversations on ${e.label}`,className:_("m-0 flex h-6 list-none items-center gap-1 overflow-hidden px-3",r==="accept"&&"opacity-40"),children:[c.shown.map(m=>t.jsx(hs,{session:m,ownerLabel:e.label,ownerReach:w,ownerReachable:e.reachable,moving:g===m.id,dragging:v===m.id,onPointerDown:y,onClick:()=>I(m)},m.id)),c.hidden>0&&t.jsx("li",{className:"shrink-0",children:t.jsxs("button",{type:"button","data-mesh-more":e.id,onClick:()=>l(e.id),className:_("flex min-h-6 items-center rounded-sm px-1.5 text-meta text-ink-dim","hover:bg-row-hover hover:text-ink","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2"),title:`Showing ${c.shown.length} of ${h} conversations`,"aria-label":`Show all ${h} conversations`,children:["+",c.hidden]})})]})]})},hs=({session:e,ownerLabel:s,ownerReach:i,ownerReachable:a,moving:o,dragging:c,onPointerDown:h,onClick:r})=>{const g=Ge(e,s,i);return o?t.jsx("li",{role:"status","data-mesh-session":e.id,"data-mesh-moving":"true",children:t.jsx("span",{className:"flex min-h-6 items-center rounded-sm bg-sunken px-1.5 text-meta text-ink-muted",children:"moving…"})}):t.jsx("li",{className:"min-w-0 flex-1","data-mesh-session-item":e.id,"data-mesh-dragging":c?"true":void 0,children:t.jsx("button",{type:"button","data-mesh-session":e.id,style:{touchAction:"none"},title:`${ee(e)} · ${g}`,"aria-label":`${ee(e)}, ${g}. Opens ${s}.`,onPointerDown:v=>h(v,e),onClick:()=>r(e),className:_("flex min-h-6 w-full max-w-32 items-center rounded-sm border border-hairline bg-surface px-1.5 text-left text-meta text-ink-muted","cursor-grab active:cursor-grabbing","hover:text-ink",cs[It(e,a)],c&&"opacity-60","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2"),children:t.jsx("span",{className:"min-w-0 flex-1 truncate",children:ee(e)})})})};function _e(e){const s=e.trim();if(!s)return null;if(s.startsWith("[")){const a=s.indexOf("]");if(a<=1)return null;const o=s.slice(1,a),c=s.slice(a+1);if(!c)return{host:o,port:null};if(!c.startsWith(":"))return null;const h=Number(c.slice(1));return{host:o,port:Number.isInteger(h)?h:null}}const i=s.lastIndexOf(":");if(i>0){const a=s.slice(i+1);if(/^\d+$/.test(a))return{host:s.slice(0,i),port:Number(a)}}return{host:s,port:null}}function Re(e){const s=e.trim().split(".");if(s.length!==4)return null;for(const i of s)if(!/^\d{1,3}$/.test(i)||Number(i)>255)return null;return`${s[0]}.${s[1]}.${s[2]}`}function ps(e){return`${e}.x`}function xs(e){const s=new Map;for(const a of e.values())for(const o of a)s.set(o,(s.get(o)??0)+1);const i=new Set;for(const[a,o]of s)o>1&&i.add(a);return i}function ke(e){return new Set(e.endpoints.map(s=>s.trim()).filter(Boolean))}function fs(e,s){const i=e.filter(l=>l.id!==s),a=e.find(l=>l.id===s)??null,o=new Map;for(const l of e)o.set(l.id,ke(l));const c=xs(o),h=new Set;for(const l of a?ke(a):[]){if(c.has(l))continue;const d=_e(l),p=d?Re(d.host):null;p&&h.add(p)}const r=l=>{const d=new Set;for(const p of ke(l)){if(c.has(p))continue;const f=_e(p),w=f?Re(f.host):null;w&&d.add(w)}return d},g=new Map,v=new Map;for(const l of i){const d=gs(l);if(d){g.set(d,[...g.get(d)??[],l.id]);continue}for(const p of r(l))v.set(p,[...v.get(p)??[],l.id])}const N=new Map(e.map((l,d)=>[l.id,d])),y=l=>[...l].sort((d,p)=>(N.get(d)??0)-(N.get(p)??0)),I=[];for(const[l,d]of g)I.push({prefix:l,tier:"declared",deviceIds:y(d),words:"declared"});for(const[l,d]of v)h.has(l)?I.push({prefix:l,tier:"shared",deviceIds:y(d),words:"shared with this device"}):d.length>1&&I.push({prefix:l,tier:"probable",deviceIds:y(d),words:"same prefix"});return I.sort((l,d)=>l.tier.localeCompare(d.tier)||l.prefix.localeCompare(d.prefix))}function gs(e){for(const s of e.memberships){const i=s.scope.trim();if(i)return i}return""}const $e={declared:0,shared:1,probable:2};function bs(e,s){const i=new Map;for(const o of e){let c=null;for(const r of o.deviceIds){const g=s.get(r);g!==void 0&&(c===null||g<c.slot)&&(c={id:r,slot:g})}if(c===null)continue;const h=i.get(c.id);h===void 0?i.set(c.id,{slot:c.slot,groups:[o]}):h.groups.push(o)}const a=o=>{let c=-1;for(const h of o.deviceIds){const r=s.get(h);r!==void 0&&r>c&&(c=r)}return c};return[...i.entries()].sort((o,c)=>o[1].slot-c[1].slot).map(([o,c])=>({deviceId:o,groups:c.groups.sort((h,r)=>a(r)-a(h)||$e[h.tier]-$e[r.tier]||h.prefix.localeCompare(r.prefix))}))}function vs(e){return new Map(e.map(s=>[s.deviceId,s.groups.length]))}function ks(e){return`${e.tier==="declared"?e.prefix:ps(e.prefix)} · ${e.words}`}const Le=(e,s)=>e.deviceIds.map(i=>s.devices.get(i)).filter(i=>i!==void 0),ws=({stacks:e,geometry:s})=>t.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute top-0 left-0",children:e.map(i=>{const a=i.groups.length,o=new Array(a).fill(0);let c=null;for(let r=a-1;r>=0;r-=1){const g=Le(i.groups[r],s),v=(g.length===0?0:Math.max(...g.map(N=>N.y+N.height)))+he;c=c===null?v:Math.max(v,c+be),o[r]=c}const h=s.devices.get(i.deviceId);return i.groups.map((r,g)=>{const v=Le(r,s);if(v.length===0)return null;const N=a-1-g,y=Math.min(...v.map(w=>w.x)),I=Math.max(...v.map(w=>w.x)),d=(h?.y??Math.min(...v.map(w=>w.y)))-he-Ct*N,p=r.tier==="declared",f=ks(r);return t.jsx("div",{"data-mesh-scope":`${r.tier}:${r.prefix}`,"data-mesh-scope-level":g,className:_("absolute rounded-lg",r.tier==="probable"?"border border-dashed border-hairline-strong":"border border-control"),style:{left:y-he-be*N,top:d,width:I+Ne-y+(he+be*N)*2,height:o[g]-d},children:t.jsx("span",{"data-mesh-scope-label":"",className:_("absolute bottom-full left-1 mb-0.5 whitespace-nowrap text-meta",r.tier==="probable"?"text-ink-dim":"text-ink-muted",p&&"font-medium"),children:f})},`${r.tier}:${r.prefix}`)})})}),Pe=48,Te=1.25,js=.0015,Ns=({graph:e,slots:s,nowSeconds:i,selectedDeviceId:a,sessions:o,sessionTotals:c,movingSessionId:h,canMove:r,onOpenDevice:g,onAskMove:v,onDropRefused:N,onShowAllSessions:y,summaryId:I})=>{const l=x.useRef(null),[d,p]=x.useState({width:0,height:0,clipWidth:0,clipHeight:0,left:0,top:0}),[f,w]=x.useState({k:1,tx:0,ty:0}),m=x.useRef(!1),S=x.useRef(!1),D=x.useRef(null),P=x.useMemo(()=>fs(e.devices,e.selfDeviceId),[e.devices,e.selfDeviceId]),C=x.useMemo(()=>bs(P,s.devices),[P,s]),M=x.useMemo(()=>St(s,vs(C)),[s,C]),B=x.useMemo(()=>({selfDeviceId:e.selfDeviceId,devices:new Map(e.devices.map(n=>[n.id,n])),networks:new Map(e.networks.map(n=>[n.id,n]))}),[e]),[j,W]=x.useState(fe),te=x.useRef({kind:"ground"}),z=x.useCallback((n,u)=>{const b=document.elementFromPoint(n,u),E=b?.closest("[data-mesh-device]");if(E){const G=E.getAttribute("data-mesh-device");if(G)return{kind:"device",deviceId:G}}const O=b?.closest("[data-mesh-network]");if(O){const G=O.getAttribute("data-mesh-network");if(G)return{kind:"network",networkId:G}}return{kind:"ground"}},[]),L=x.useMemo(()=>j.kind!=="dragging"&&j.kind!=="settling"?null:xe(j.payload,j.target,B),[j,B]),se=x.useCallback(n=>{if(!L)return null;if(L.kind==="plan"){const u=j.kind==="dragging"||j.kind==="settling"?j.target:null;return u&&u.kind==="device"&&u.deviceId===n?"accept":null}if(L.kind==="refused"){const u=j.kind==="dragging"||j.kind==="settling"?j.target:null;return u&&u.kind==="device"&&u.deviceId===n?"refuse":null}return null},[L,j]),ne=x.useCallback((n,u)=>{if(!r||n.button!==0)return;S.current=!1;const b=u.locality==="local"?e.selfDeviceId??"":u.owner_device,E=B.devices.get(b),O={session:u,ownerDeviceId:b,ownerLabel:E?.label??u.owner_device_name};try{n.currentTarget.setPointerCapture(n.pointerId)}catch{}W(G=>J(G,{kind:"press",payload:O,x:n.clientX,y:n.clientY,pointerId:n.pointerId}))},[r,B,e.selfDeviceId]),ie=n=>{if(j.kind==="pressing"||j.kind==="dragging"){const u=z(n.clientX,n.clientY);te.current=u,W(b=>J(b,{kind:"move",x:n.clientX,y:n.clientY,target:u}));return}ue(n)},re=n=>{if(Q(n),j.kind!=="pressing"&&j.kind!=="dragging")return;if(j.kind==="pressing"){W(b=>J(b,{kind:"cancel"}));return}const u=xe(j.payload,j.target,B);S.current=!0,W(b=>J(b,{kind:"release"})),u.kind==="plan"?v({plan:u.plan,alternatives:u.alternatives,risky:u.risky}):u.kind==="refused"&&N({code:u.code,sentence:u.sentence,remedy:u.remedy,plan:u.plan??null}),W(b=>J(b,{kind:"settled"}))};x.useEffect(()=>()=>W(fe),[]);const Z=x.useCallback(()=>{w(Ae(M.bounds,d))},[M.bounds,d]);x.useEffect(()=>{const n=l.current;if(!n)return;const u=()=>{const E=n.getBoundingClientRect();p({width:E.width,height:E.height,clipWidth:n.clientWidth,clipHeight:n.clientHeight,left:E.left,top:E.top})};u();const b=new ResizeObserver(u);return b.observe(n),()=>b.disconnect()},[]),x.useEffect(()=>{m.current||d.width<=0||d.height<=0||(m.current=!0,w(Ae(M.bounds,d)))},[d,M.bounds]),x.useEffect(()=>{const n=D.current;if(D.current={width:d.width,height:d.height},!n||!m.current||d.width<=0||d.height<=0||d.width>=n.width&&d.height>=n.height||!a)return;const u=M.devices.get(a);u&&w(b=>{const E={width:d.clipWidth,height:d.clipHeight},O=Math.max(0,Math.min(E.width-M.bounds.width*b.k,E.height-M.bounds.height*b.k));return Mt(b,u,E,Math.min(At,O))})},[d,a,M]);const F=j.kind==="dragging"?{x:j.x-d.left+12,y:j.y-d.top+12}:{x:0,y:0},K=L?Dt(L):null,k=x.useRef(null),A=x.useRef(null),$=x.useRef(null),T=x.useRef(null),R=x.useCallback(()=>{$.current=null;const n=k.current,u=A.current;if(k.current=null,A.current=null,n){const b=T.current;if(!b)return;w({k:b.transform.k,tx:b.transform.tx+(n.x-b.x),ty:b.transform.ty+(n.y-b.y)});return}u&&w(b=>ve(b,{x:u.x,y:u.y},b.k*Math.exp(-u.deltaY*js)))},[]),q=x.useCallback(()=>{$.current===null&&($.current=requestAnimationFrame(R))},[R]);x.useEffect(()=>()=>{$.current!==null&&cancelAnimationFrame($.current)},[]);const Y=n=>{!(n.target===n.currentTarget)&&n.button!==1||n.button!==0&&n.button!==1||(T.current={x:n.clientX,y:n.clientY,transform:f},n.currentTarget.setPointerCapture(n.pointerId),n.preventDefault())},ue=n=>{T.current&&(k.current={x:n.clientX,y:n.clientY},q())},Q=n=>{T.current&&(T.current=null,k.current=null,n.currentTarget.hasPointerCapture(n.pointerId)&&n.currentTarget.releasePointerCapture(n.pointerId))},X=x.useCallback(n=>{if(n.deltaY===0)return;n.preventDefault();const u=n.currentTarget.getBoundingClientRect();A.current={x:n.clientX-u.left,y:n.clientY-u.top,deltaY:n.deltaY},q()},[q]);x.useEffect(()=>{const n=l.current;if(n)return n.addEventListener("wheel",X,{passive:!1}),()=>n.removeEventListener("wheel",X)},[X]);const me=n=>{const u=n.shiftKey?Pe*4:Pe;switch(n.key){case"Escape":if(j.kind!=="pressing"&&j.kind!=="dragging")return;n.preventDefault(),j.kind==="dragging"&&(S.current=!0),W(b=>J(b,{kind:"cancel"}));return;case"0":n.preventDefault(),Z();return;case"+":case"=":n.preventDefault(),w(b=>ve(b,{x:d.width/2,y:d.height/2},b.k*Te));return;case"-":case"_":n.preventDefault(),w(b=>ve(b,{x:d.width/2,y:d.height/2},b.k/Te));return;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{n.preventDefault();const b=n.key==="ArrowLeft"?u:n.key==="ArrowRight"?-u:0,E=n.key==="ArrowUp"?u:n.key==="ArrowDown"?-u:0;w(O=>({...O,tx:O.tx+b,ty:O.ty+E}));return}}};return t.jsxs("div",{ref:l,"data-mesh-canvas":"",role:"group","aria-labelledby":I,tabIndex:0,onPointerDown:Y,onPointerMove:ie,onPointerUp:re,onPointerCancel:n=>{j.kind==="dragging"&&(S.current=!0),W(u=>J(u,{kind:"cancel"})),Q(n)},"data-mesh-gesture":j.kind,onKeyDown:me,onDoubleClick:n=>{n.target===n.currentTarget&&Z()},className:_("relative min-h-0 flex-1 overflow-hidden rounded-lg border border-hairline bg-sunken","[touch-action:none]","cursor-grab active:cursor-grabbing","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-[-2px]"),children:[t.jsx("div",{"data-mesh-ground":"","aria-hidden":"true",className:"mesh-ground pointer-events-none absolute inset-0",style:{backgroundPosition:`${f.tx}px ${f.ty}px`}}),t.jsxs("div",{"data-mesh-world":"",className:"absolute top-0 left-0",style:{transform:`translate3d(${f.tx}px, ${f.ty}px, 0) scale(${f.k})`,transformOrigin:"0 0",width:M.bounds.width,height:M.bounds.height},children:[t.jsx(ws,{stacks:C,geometry:M}),t.jsx(as,{edges:e.edges,geometry:M,selectedDeviceId:a}),t.jsx("ul",{"aria-label":"Networks",className:"m-0 list-none p-0",children:e.networks.map(n=>{const u=M.networks.get(n.id);return u?t.jsx(us,{network:n,x:u.x,y:u.y,refused:L?.kind==="refused"&&j.kind==="dragging"&&j.target.kind==="network"&&j.target.networkId===n.id},n.id):null})}),t.jsx("ul",{"aria-label":"Devices",className:"m-0 list-none p-0",children:e.devices.map(n=>{const u=M.devices.get(n.id);return u?t.jsx(ms,{device:n,x:u.x,y:u.y,nowSeconds:i,selected:n.id===a,sessions:o.get(n.id)??{rows:[],shown:[],hidden:0},sessionTotal:c.get(n.id)??n.sessionCount??0,dropState:se(n.id),movingSessionId:h,draggedSessionId:ns(j),onOpen:g,onChipPointerDown:ne,onChipClick:()=>{if(S.current){S.current=!1;return}g(n.id)},onShowAllSessions:y},n.id):null})})]}),j.kind==="dragging"&&t.jsx("div",{"data-mesh-ghost":"","aria-hidden":"true",className:"pointer-events-none absolute z-10 max-w-40 truncate rounded-sm border border-ink-dim bg-surface px-1.5 py-0.5 text-meta text-ink",style:{left:F.x,top:F.y},children:j.payload.session.name||"untitled"}),j.kind==="dragging"&&K&&t.jsx("div",{"data-mesh-indicator":"",className:_("pointer-events-none absolute z-10 rounded-sm border bg-surface px-2 py-1 text-meta",L?.kind==="refused"?"border-warning text-warning":"border-control text-ink"),style:{left:F.x,maxWidth:Math.max(160,d.width-F.x-12),...F.y>d.height*.6?{bottom:Math.max(12,d.height-F.y+8)}:{top:F.y+24}},children:K})]})};function ys(e,s,i,a){const o=i.locality==="local"?s:i.owner_device,c=[];for(const h of e)if(h.id!==o){if(h.id===s){c.push({deviceId:h.id,label:a,verb:"Recall to this device",keepVerb:"Copy here, leave it there"});continue}c.push({deviceId:h.id,label:h.label,verb:`Move to ${h.label}`,keepVerb:`Copy to ${h.label}`})}return c}function Is(e,s,i){return ys(e.devices,e.selfDeviceId,s,i)}function Ve(e,s,i){const a=Is(e,s,i),o={selfDeviceId:e.selfDeviceId,devices:new Map(e.devices.map(r=>[r.id,r])),networks:new Map(e.networks.map(r=>[r.id,r]))},c=s.locality==="local"?e.selfDeviceId??"":s.owner_device,h=o.devices.get(c);return a.map(r=>{const g=xe({session:s,ownerDeviceId:c,ownerLabel:h?.label??s.owner_device_name},{kind:"device",deviceId:r.deviceId},o);return{...r,refused:g.kind==="refused"&&g.code!=="busy"?g.sentence:null}})}const Ke=({session:e,destinations:s,disabled:i,onChoose:a,onOpenChange:o,trigger:c,triggerLabel:h})=>t.jsxs(nt,{onOpenChange:o,children:[t.jsx(at,{asChild:!0,children:t.jsx("button",{type:"button","aria-label":h,"data-mesh-session-menu":e.id,disabled:i||s.length===0,className:"rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2 disabled:text-ink-disabled",children:c})}),t.jsxs(it,{align:"start",className:"min-w-56",children:[t.jsx(rt,{children:ee(e)}),t.jsx(Se,{}),s.map(r=>t.jsx(Me,{"data-mesh-move-to":r.deviceId,disabled:!!r.refused,title:r.refused??void 0,onSelect:()=>a(r,!1),children:r.verb},r.deviceId)),t.jsx(Se,{}),s.map(r=>t.jsx(Me,{"data-mesh-copy-to":r.deviceId,disabled:!!r.refused,title:r.refused??void 0,onSelect:()=>a(r,!0),children:r.keepVerb},`keep-${r.deviceId}`))]})]}),Cs=({device:e,sessions:s,sessionTotal:i,nowSeconds:a,destinationsFor:o,movingSessionId:c,canMove:h,canInvite:r,onClose:g,onMove:v,onShowInList:N,onInvite:y,onRemoveMember:I})=>{const l=de(e);x.useEffect(()=>{const m=S=>{S.key!=="Escape"||S.defaultPrevented||S.target?.closest('[role="menu"],[role="dialog"]')||(document.querySelector(`[data-mesh-device-open="${e.id}"]`)?.focus(),g())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e.id,g]);const d=e.memberships.every(m=>!m.active),p=e.sessionCount===null?we(null):`${e.sessionCount} ${we(e.sessionCount)}`,f=e.suspect?qe:[d?"revoked membership":p,ce(l)].filter(Boolean).join(" · "),w=i>s.rows.length?`${s.rows.length} of ${i}`:`${s.rows.length}`;return t.jsxs("aside",{"aria-label":`${e.label} details`,"data-mesh-panel":e.id,className:"flex w-80 shrink-0 flex-col gap-3 overflow-y-auto rounded-md border border-hairline bg-surface p-4",children:[t.jsxs("header",{className:"flex flex-col gap-1",children:[t.jsx(U,{size:"sm",variant:"ghost",className:"w-fit self-end","data-mesh-panel-close":"",onClick:g,children:"Close"}),t.jsx("h2",{className:"text-body-sm text-ink",children:e.label}),t.jsxs("p",{className:"flex items-center gap-1.5 text-meta text-ink-muted",children:[e.suspect&&t.jsx(ye,{"aria-hidden":"true",className:"size-3.5 text-danger"}),!e.suspect&&l==="unanswered"&&t.jsx(st,{"aria-hidden":"true",className:"size-3.5 text-warning"}),f]})]}),t.jsx(ae,{}),t.jsxs("section",{className:"flex flex-col gap-2",children:[t.jsx("h3",{className:"text-meta text-ink-dim",children:"Memberships"}),t.jsx("ul",{className:"m-0 flex list-none flex-col gap-2 p-0",children:e.memberships.map(m=>t.jsxs("li",{className:"flex flex-col gap-1",children:[t.jsxs("span",{className:"flex items-center gap-2 text-body-sm text-ink",children:[t.jsx(je,{"aria-hidden":"true",className:"size-3.5 text-ink-muted"}),m.networkName]}),t.jsxs("span",{className:"text-meta text-ink-dim",children:[m.role||"member",m.capabilities.length>0?` · ${m.capabilities.join(", ")}`:"",m.active?"":" · revoked"]}),r&&m.active&&t.jsxs(U,{size:"sm",variant:"ghost",className:"w-fit","data-mesh-remove-member":`${m.networkId}:${e.id}`,onClick:()=>I(e,m.networkId),children:["Remove from ",m.networkName,"…"]})]},m.networkId))}),r&&t.jsx(U,{size:"sm",variant:"secondary",className:"w-fit","data-mesh-invite":e.id,onClick:()=>y(e),children:"Invite to a network…"})]}),t.jsx(ae,{}),t.jsxs("section",{className:"flex shrink-0 flex-col gap-2",children:[t.jsxs("h3",{className:"text-meta text-ink-dim",children:["Conversations ",t.jsxs("span",{className:"text-ink-disabled",children:["(",w,")"]})]}),s.rows.length===0?t.jsx("p",{className:"text-meta text-ink-dim",children:e.sessionCount===null?"This device did not report its conversations.":"No conversations here."}):t.jsx("ul",{className:"m-0 flex list-none flex-col gap-1 p-0",children:s.rows.map(m=>t.jsxs("li",{"data-mesh-panel-session":m.id,className:_("flex items-center gap-2 rounded-sm px-2 py-1","border border-hairline bg-elevated",c===m.id&&"border-control"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-body-sm text-ink",title:ee(m),children:ee(m)}),t.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:Ge(m,e.label,de(e))}),c===m.id?t.jsx("span",{className:"shrink-0 text-meta text-ink-muted",children:"moving…"}):t.jsx(Ke,{session:m,destinations:o(m),disabled:!h,onChoose:(S,D)=>v(m,S,D),trigger:t.jsx(He,{"aria-hidden":"true",className:"size-4"}),triggerLabel:`Move ${ee(m)}`})]},m.id))})]}),t.jsx(ae,{}),t.jsxs("section",{className:"flex flex-col gap-2",children:[t.jsx("h3",{className:"text-meta text-ink-dim",children:"Network addresses"}),e.endpoints.length===0?t.jsx("p",{className:"text-meta text-ink-dim",children:"No address published."}):t.jsx("ul",{className:"m-0 flex list-none flex-col gap-1 p-0",children:e.endpoints.map(m=>t.jsxs("li",{className:"flex items-baseline justify-between gap-2",children:[t.jsx("span",{className:"min-w-0 truncate font-mono text-body-sm text-ink",children:m}),t.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:"advertised"})]},m))})]}),t.jsx(ae,{}),t.jsxs("section",{className:"flex flex-col gap-2",children:[t.jsx("h3",{className:"text-meta text-ink-dim",children:"Status"}),t.jsxs("dl",{className:"m-0 flex flex-col gap-1",children:[t.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[t.jsx("dt",{className:"text-meta text-ink-dim",children:"Reach"}),t.jsx("dd",{className:"m-0 text-body-sm text-ink",children:ce(l)})]}),t.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[t.jsx("dt",{className:"text-meta text-ink-dim",children:"Last status frame"}),t.jsx("dd",{className:"m-0 text-body-sm text-ink",children:e.lastSeenAt===null?"never":Et(a-e.lastSeenAt)})]})]}),e.reason&&t.jsx("p",{className:"text-meta text-warning",children:e.reason})]}),t.jsx(ae,{}),t.jsx(U,{size:"sm",variant:"ghost",className:"w-fit","data-mesh-show-in-list":e.id,onClick:()=>N(e.id),children:"Show in list"})]})},Ss=["name","chats","state"],Ms={name:"Name",chats:"Conversations",state:"State"},Oe={suspect:0,unreachable:1,self:2,reachable:3};function Ds(e,s){const i=[...e];switch(s){case"chats":return i.sort((a,o)=>(o.sessionCount??-1)-(a.sessionCount??-1)||a.label.localeCompare(o.label)),i;case"state":return i.sort((a,o)=>Oe[a.state]-Oe[o.state]||a.label.localeCompare(o.label)),i;default:return i.sort((a,o)=>a.label.localeCompare(o.label))}}const We=8;function As(e,s){if(e.locality==="local")return e.live_state||"here";const i=e.owner_device_name||s,a=e.live_state?` · ${e.live_state}`:"";return e.reachable?`on ${i}${a}`:`on ${i} (not answering)`}const Es=({graph:e,nowSeconds:s,selectedDeviceId:i,sessions:a,selfLabel:o,canMove:c,onSelect:h,onMove:r,onInvite:g,onRemove:v})=>{const[N,y]=x.useState("name"),I=x.useMemo(()=>e.networks.map(l=>({network:l,members:Ds(e.devices.filter(d=>d.memberships.some(p=>p.networkId===l.id)),N)})),[e,N]);return t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto pr-1",children:[t.jsxs("fieldset",{className:"m-0 w-fit border-0 p-0",children:[t.jsx("legend",{className:"sr-only",children:"Sort devices by"}),t.jsx("div",{className:"flex gap-0.5 rounded-md bg-sunken p-0.5",children:Ss.map(l=>t.jsx("button",{type:"button","aria-pressed":N===l,onClick:()=>y(l),className:_("h-6 rounded-sm px-3 text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart","hover:text-ink","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2",N===l&&"bg-surface text-ink"),children:Ms[l]},l))})]}),I.map(({network:l,members:d})=>t.jsxs("section",{"data-mesh-network-group":l.id,className:"flex flex-col gap-2",children:[t.jsxs("h2",{className:"flex flex-wrap items-baseline gap-2 text-body-sm text-ink",title:`epoch ${l.epoch}`,children:[l.label,t.jsxs("span",{className:"text-meta text-ink-dim",children:[l.trust," · ",l.memberCount," ",l.memberCount===1?"device":"devices",l.revokedCount>0?` · ${l.revokedCount} revoked`:""]})]}),t.jsx("ul",{className:"m-0 flex list-none flex-col gap-1 p-0",children:d.map(p=>{const f=p.memberships.find(C=>C.networkId===l.id),w=p.id===i,m=a.get(p.id),S=m?.rows??[],D=m?Ue(m,p.sessionCount):p.sessionCount??0,P=de(p);return t.jsxs("li",{"data-mesh-device-row":p.id,"data-mesh-state":p.state,"aria-current":w?"true":void 0,className:_("flex flex-col gap-1 rounded-md px-3 py-2","border border-hairline bg-surface",w&&"border-ink bg-row-selected"),children:[t.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[t.jsx("button",{type:"button","data-mesh-device-open":p.id,onClick:()=>h(p.id),className:_("min-w-0 flex-1 truncate text-left text-body-sm text-ink","hover:text-ink-muted","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2"),children:p.label}),t.jsxs("span",{className:_("flex shrink-0 items-center gap-1 text-meta",Be[P]),"data-mesh-reach":P,children:[p.suspect&&t.jsx(ye,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-danger"}),p.suspect?ce(P):Fe(p,s),p.suspect&&t.jsx("span",{className:"shrink-0 rounded-sm border border-danger px-1 text-danger",children:qe})]}),t.jsxs("span",{className:"shrink-0 text-meta text-ink-dim",children:[f?.role?`${f.role} · `:"",f&&!f.active?"revoked":"member"]})]}),S.length>0?t.jsxs(t.Fragment,{children:[t.jsx(ae,{className:"my-1"}),t.jsx("ul",{className:"m-0 flex list-none flex-col gap-0.5 p-0",children:S.slice(0,We).map(C=>t.jsxs("li",{"data-mesh-row-session":C.id,className:"flex items-center gap-2 py-0.5",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-meta text-ink-muted",children:C.name||C.id}),t.jsx("span",{className:"shrink-0 text-meta text-ink-dim",children:As(C,o)}),t.jsx(Ke,{session:C,destinations:Ve(e,C,o),disabled:!c,onChoose:(M,B)=>r(C,M,B),trigger:t.jsx(He,{"aria-hidden":"true",className:"size-3.5"}),triggerLabel:`Move ${C.name||C.id}`})]},C.id))}),D>S.slice(0,We).length&&t.jsx("button",{type:"button",onClick:()=>h(p.id),className:"w-fit text-meta text-ink-dim hover:text-ink",children:`show all ${D} in the panel`})]}):t.jsx("span",{className:"text-meta text-ink-dim",children:D===0?"no conversations":D===1?"1 conversation":`${D} conversations`}),(f?.active||p.state!=="self")&&t.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[t.jsx(U,{size:"sm",variant:"ghost","data-mesh-invite":p.id,onClick:()=>g({deviceId:p.id,deviceLabel:p.label}),children:"Invite to a network…"}),f?.active&&t.jsxs(U,{size:"sm",variant:"ghost","data-mesh-remove-member":`${l.id}:${p.id}`,onClick:()=>v({networkId:l.id,networkLabel:l.label,deviceId:p.id,deviceLabel:p.label}),children:["Remove from ",l.label,"…"]})]})]},p.id)})})]},l.id)),e.unmatchedPeers.length>0&&t.jsxs("p",{className:"text-meta text-warning",children:[e.unmatchedPeers.length," ",e.unmatchedPeers.length===1?"device":"devices"," answered the peer read but is in no network this app can name."]})]})},_s=["canvas","list"],Rs={canvas:"Canvas",list:"List"},$s=({state:e,graph:s,nowSeconds:i,checking:a,staleError:o,onRetry:c,approvals:h,sessions:r,sessionError:g,selfLabel:v,movingSessionId:N,canMove:y,pendingMove:I,onAskMove:l,onDropRefused:d,onChooseMove:p,onCancelMove:f,moveBusy:w,moveReport:m,onDismissReport:S,onWaitForIdle:D,onUndoCopy:P,invite:C,onOpenInvite:M,onInvite:B,onCloseInvite:j,inviteBusy:W,inviteReceipt:te,inviteRefusal:z,remove:L,onOpenRemove:se,onRemove:ne,onCloseRemove:ie,removeBusy:re,removeRefusal:Z,removed:F})=>{const[K,k]=x.useState("canvas"),[A,$]=x.useState(null),T=s?_t(s):"",R="mesh-summary",q=Rt(s),Y=$t(s,r,s?.selfDeviceId??null),ue=x.useMemo(()=>{const n=new Map;for(const u of s?.devices??[]){const b=Y.byDevice.get(u.id);n.set(u.id,b?Ue(b,u.sessionCount):u.sessionCount??0)}return n},[s,Y]),Q=x.useCallback(n=>{$(n)},[]),X=s?s.devices.find(n=>n.id===A)??null:null,me=x.useCallback((n,u,b)=>{if(!s)return null;const E={selfDeviceId:s.selfDeviceId,devices:new Map(s.devices.map(V=>[V.id,V])),networks:new Map(s.networks.map(V=>[V.id,V]))},O=n.locality==="local"?s.selfDeviceId??"":n.owner_device,G=E.devices.get(O),H=xe({session:n,ownerDeviceId:O,ownerLabel:G?.label??n.owner_device_name},{kind:"device",deviceId:u.deviceId},E);if(H.kind==="refused")return d({code:H.code,sentence:H.sentence,remedy:H.remedy,plan:H.plan??null}),null;if(H.kind==="none")return null;const Ie=b?H.alternatives.find(V=>V.keep)??H.plan:H.plan,Xe=[H.plan,...H.alternatives].filter(V=>V.keep!==Ie.keep),Ze={plan:Ie,alternatives:Xe,risky:H.risky};l(Ze)},[s,l,d]);return t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-6 overflow-y-auto p-6",children:[t.jsx(tt,{title:"Mesh",icon:je,subtitle:"Devices this app is paired with, and the networks that hold them.",children:t.jsxs("div",{className:"flex items-center gap-4",children:[a&&t.jsx("output",{className:"text-meta text-ink-dim",children:"checking…"}),(e.kind==="ready"||e.kind==="loading")&&t.jsxs("fieldset",{className:"m-0 w-fit border-0 p-0",children:[t.jsx("legend",{className:"sr-only",children:"Presentation"}),t.jsx("div",{className:"flex gap-0.5 rounded-md bg-sunken p-0.5",children:_s.map(n=>t.jsx("button",{type:"button","aria-pressed":K===n,disabled:e.kind!=="ready",onClick:()=>k(n),className:_("h-6 rounded-sm px-3 text-body-sm text-ink-muted transition-colors duration-fast ease-out-quart","hover:text-ink","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2","disabled:text-ink-dim disabled:hover:text-ink-dim",K===n&&"bg-surface text-ink"),children:Rs[n]},n))})]})]})}),t.jsx(ts,{rows:h.rows,error:h.error,pending:h.pending,refusal:h.decisionRefusal,onDecide:h.onDecide,onRetry:h.onRetry,nowSeconds:h.nowSeconds,networkNames:new Map((s?.networks??[]).map(n=>[n.id,n.label]))}),e.kind==="loading"&&t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[t.jsx(De,{className:"h-4 w-64"}),t.jsx(De,{className:"min-h-40 w-full flex-1"})]}),e.kind==="error"&&t.jsxs(pe,{variant:"warning",className:"flex-col items-start gap-2",children:[t.jsx("p",{children:e.message}),t.jsx(U,{variant:"secondary",size:"sm",onClick:c,className:"w-fit",children:"Ask again"})]}),e.kind==="empty"&&t.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center rounded-lg border border-hairline bg-surface p-6",children:t.jsxs("div",{className:"flex flex-col items-start gap-3",children:[t.jsx("h2",{className:"text-heading text-ink",children:"No network on this device"}),t.jsx("p",{className:"max-w-140 text-body-sm text-ink-muted",children:"This device is not in any network, so there is no mesh to draw. Create one on this machine:"}),t.jsx("code",{className:"rounded-sm bg-sunken px-2 py-1 font-mono text-meta text-ink",children:"lop network init <name>"}),t.jsx("p",{className:"text-meta text-ink-dim",children:"A network appears here once this device has joined one."})]})}),e.kind==="ready"&&s&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"flex min-h-[22rem] flex-1 gap-4",children:[t.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-3",children:[t.jsx("p",{id:R,className:"text-meta text-ink-muted","data-mesh-summary":"",children:T}),o&&t.jsx(pe,{variant:"warning",children:t.jsx("p",{children:o})}),g&&t.jsx(pe,{variant:"warning",children:t.jsx("p",{children:g})}),m&&t.jsx(Lt,{receipt:m.kind==="moved"?{verb:m.verb,detail:m.detail,undo:m.undo}:null,refusal:m.kind==="refused"?m.refusal:null,canWait:m.kind==="refused"&&m.plan!==null,onWait:D,onRecheck:c,onUndo:P,onDismiss:S,pending:w}),K==="canvas"?t.jsx(Ns,{graph:s,slots:q,nowSeconds:i,selectedDeviceId:A,sessions:Y.byDevice,sessionTotals:ue,movingSessionId:N,canMove:y,onOpenDevice:Q,onAskMove:l,onDropRefused:d,onShowAllSessions:Q,summaryId:R}):t.jsx(Es,{graph:s,nowSeconds:i,selectedDeviceId:A,sessions:Y.byDevice,selfLabel:v,canMove:y,onSelect:Q,onMove:me,onInvite:M,onRemove:se})]}),X&&t.jsx(Cs,{device:X,sessions:Y.byDevice.get(X.id)??{rows:[],shown:[],hidden:0},sessionTotal:ue.get(X.id)??0,nowSeconds:i,canMove:y,canInvite:e.kind==="ready",movingSessionId:N,destinationsFor:n=>Ve(s,n,v),onClose:()=>$(null),onMove:me,onInvite:n=>M({deviceId:n.id,deviceLabel:n.label}),onRemoveMember:(n,u)=>{const b=s.networks.find(E=>E.id===u);se({networkId:u,networkLabel:b?.label??u,deviceId:n.id,deviceLabel:n.label})},onShowInList:n=>{Q(n),k("list")}})]})}),t.jsx(Pt,{open:I!==null,plan:I?.plan??Ls,alternatives:I?.alternatives??[],risky:I?.risky??!1,busy:w,onCancel:f,onChoose:p}),C&&t.jsx(Tt,{open:C.open,options:C.options,deviceId:C.deviceId,deviceLabel:C.deviceLabel,onClose:j,onInvite:B,pending:W,receipt:te,refusal:z}),L&&t.jsx(Ot,{open:L.open,networkLabel:L.networkLabel,deviceLabel:L.deviceLabel,onClose:ie,onConfirm:ne,pending:re,refusal:Z,removed:F})]})},Ls={sessionId:"",to:"",keep:!1,verb:"",waitS:0,lost:null},qs=()=>{const e=Je(),s=ge(e.data,"peers")==="enabled",i=ge(e.data,"session_transfer")==="enabled",a=Wt(s),o=zt(s),c=Ht(s,{poll:!1,stamp:()=>Ce.getState().beginAnswer()}),h=x.useMemo(()=>({peers:a,networks:o}),[a,o]),r=Bt(h),g=Ft(h),v=qt(),N=ge(e.data,"approvals")==="enabled",y=Ut(s&&N,{poll:!1}),I=Yt(),l=I.isError?{approvalId:I.variables?.approvalId??null,...Gt(I.error)}:null,d=x.useMemo(()=>Math.floor((y.dataUpdatedAt||Date.now())/1e3),[y.dataUpdatedAt]),p=Ce(k=>k.settlePlacement),f=Vt(),w=Kt(),[m,S]=x.useState(null),[D,P]=x.useState(null),[C,M]=x.useState(null),[B,j]=x.useState(null),[W,te]=x.useState(null),[z,L]=x.useState(null),[se,ne]=x.useState(null),ie=x.useMemo(()=>{const k=Math.max(a.dataUpdatedAt,o.dataUpdatedAt);return Math.floor((k||Date.now())/1e3)},[a.dataUpdatedAt,o.dataUpdatedAt]),re=x.useCallback(()=>{a.refetch(),o.refetch(),c.refetch()},[a,o,c]),Z=x.useCallback((k,A)=>{S(null);const $={sessionId:k.sessionId,to:k.to,keep:k.keep,waitS:A??k.waitS};v.mutate($,{onSuccess:T=>{if(T.kind==="moved"){const{receipt:R}=T;p(k.sessionId,R);const q=R.locality==="local"?"this device":g?.devices.find(Y=>Y.id===R.owner_device)?.label??R.owner_device;P({kind:"moved",verb:R.mode==="keep"?"Copied":"Moved",detail:R.mode==="keep"?`${q} holds a copy as ${R.new_session_id.slice(-6)}; the original is still here.`:`${q} holds it now${R.source_retired?"; the copy here is gone":""}.`,undo:R.mode==="keep"?{sessionId:R.new_session_id,to:"local",keep:!1,verb:`Bring the copy back from ${q}`,waitS:0,lost:Xt(q,"this device")}:null});return}P({kind:"refused",refusal:T.refusal,plan:k})},onError:()=>{P({kind:"refused",refusal:{code:"move_failed",sentence:"The move could not be sent. Nothing here changed; the list has been read again.",status:null,unconfirmed:!1},plan:k})}})},[g,v,p]),F=x.useMemo(()=>{if(!g)return[];const k=C?.deviceId,A=k?g.devices.find($=>$.id===k):void 0;return g.networks.filter($=>{if(!A)return!0;const T=A.memberships.find(R=>R.networkId===$.id);return!T||!T.active}).map($=>({id:$.id,label:$.label}))},[g,C]);if(!s)return t.jsx(et,{to:"/chat",replace:!0});const K=r.kind==="ready"?a.error?le(a.error):o.error?le(o.error):null:null;return t.jsx($s,{state:r,graph:g,nowSeconds:ie,checking:a.isFetching||o.isFetching,staleError:K,onRetry:re,approvals:{rows:y.data??[],error:y.isError?Zt(y.error):null,pending:I.isPending?I.variables??null:null,decisionRefusal:l,onDecide:(k,A)=>I.mutate({approvalId:k,decision:A}),onRetry:()=>void y.refetch(),nowSeconds:d},sessions:c.data?.rows??[],movingSessionId:v.isPending?v.variables?.sessionId??null:null,sessionError:c.isError?le(c.error):null,selfLabel:g?.devices.find(k=>k.state==="self")?.label??"this device",canMove:i,pendingMove:m,onAskMove:S,onDropRefused:k=>P({kind:"refused",refusal:{code:k.code,sentence:k.sentence,status:null,unconfirmed:!1},plan:k.plan}),onChooseMove:k=>Z(k),onCancelMove:()=>S(null),moveBusy:v.isPending,moveReport:D,onDismissReport:()=>P(null),onWaitForIdle:()=>{D?.kind!=="refused"||!D.plan||Z(D.plan,Ps)},onUndoCopy:()=>{D?.kind!=="moved"||!D.undo||S({plan:D.undo,alternatives:[],risky:!1})},invite:C===null?null:{open:!0,deviceId:C.deviceId,deviceLabel:C.deviceLabel,options:F},onOpenInvite:k=>{j(null),te(null),M(k)},onInvite:k=>{f.mutate(k,{onSuccess:A=>j(A),onError:A=>te({code:"invite_refused",sentence:le(A),status:null,unconfirmed:!1})})},onCloseInvite:()=>M(null),inviteBusy:f.isPending,inviteReceipt:B,inviteRefusal:W,remove:z===null?null:{open:!0,networkId:z.networkId,networkLabel:z.networkLabel,deviceId:z.deviceId,deviceLabel:z.deviceLabel},onOpenRemove:k=>{ne(null),L(k)},onRemove:k=>{z&&w.mutate({networkId:z.networkId,deviceId:z.deviceId,confirm:k},{onSuccess:A=>ne(A)})},onCloseRemove:()=>L(null),removeBusy:w.isPending,removeRefusal:w.isError?{code:"remove_refused",sentence:le(w.error),status:null,unconfirmed:!1}:null,removed:se})},Ps=300;export{qs as MeshPage,$s as MeshSurface,qs as default};