@camstack/addon-admin-ui 1.2.427 → 1.2.428

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 (143) hide show
  1. package/dist/assets/{AddonAssetIcon-BgXfFdy2.js → AddonAssetIcon-Cs_blBpK.js} +1 -1
  2. package/dist/assets/Addons-2xWF73cR.js +4 -0
  3. package/dist/assets/{AdminPage-C0Zxs_ot.js → AdminPage-DuuyDIsY.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-D2kYQhvu.js → AdminSectionedPage-C3VHg80L.js} +1 -1
  5. package/dist/assets/AiProfiles-DmHcVlS2.js +3 -0
  6. package/dist/assets/BrokerForm-Dqhjsi3Y.js +1 -0
  7. package/dist/assets/Build-CBYP1fT5.js +40 -0
  8. package/dist/assets/Calendars-C926x7b_.js +1 -0
  9. package/dist/assets/Cluster-OZlA14uV.js +1 -0
  10. package/dist/assets/ClusterStepModel-DHbwIGAW.js +1 -0
  11. package/dist/assets/CompositionEditor-vP3JcV2R.js +1 -0
  12. package/dist/assets/{CompositionEditorPage-CDyW_Buu.js → CompositionEditorPage-Acq7iapA.js} +1 -1
  13. package/dist/assets/Data-7BoejvKA.js +1 -0
  14. package/dist/assets/DeviceDetail-ByM0856T.js +2 -0
  15. package/dist/assets/DeviceDoActionFields-BDJsvRNX.js +1 -0
  16. package/dist/assets/{Devices-CHeb_BTk.js → Devices-PIrWjfhq.js} +1 -1
  17. package/dist/assets/EmbedPlayerPage-RXOmf2F3.js +1 -0
  18. package/dist/assets/Identity-C-tztwfa.js +1 -0
  19. package/dist/assets/IntegrationDetail-DugB7cv6.js +1 -0
  20. package/dist/assets/IntegrationHub-BePMbmC5.js +1 -0
  21. package/dist/assets/Integrations-Dj3nT9ZT.js +1 -0
  22. package/dist/assets/Integrations-OH5z-t03.js +1 -0
  23. package/dist/assets/Library-DDNti2te.js +1 -0
  24. package/dist/assets/Locations-OL9_NoSi.js +3 -0
  25. package/dist/assets/Logs-DIeXeCqI.js +1 -0
  26. package/dist/assets/{MotionZonesSettings-DjvGw8j4.js → MotionZonesSettings-CfTOerul.js} +1 -1
  27. package/dist/assets/MyAccess-iJP3JQIS.js +2 -0
  28. package/dist/assets/Network-DYssxNiN.js +1 -0
  29. package/dist/assets/NodeAddonsSettingsPanel-mmtEgDbu.js +1 -0
  30. package/dist/assets/Notifications-DEcxFWp3.js +1 -0
  31. package/dist/assets/{PrivacyMaskSettings-IK6ytyM8.js → PrivacyMaskSettings-CJUKFEIs.js} +1 -1
  32. package/dist/assets/Recordings-lygSYEJj.js +1 -0
  33. package/dist/assets/ScanNetworkModal-C2oJlLfj.js +1 -0
  34. package/dist/assets/{SceneMonitorEditor-V_pHxg3U.js → SceneMonitorEditor-D1S-D2V9.js} +1 -1
  35. package/dist/assets/SessionsList-CIN4GdSm.js +2 -0
  36. package/dist/assets/{Showroom-Cw-6ZdvC.js → Showroom-W2yJvb8s.js} +1 -1
  37. package/dist/assets/System-ChWpOOqN.js +1 -0
  38. package/dist/assets/{Terminal-D-YHBrHK.js → Terminal-CrFum1tE.js} +5 -5
  39. package/dist/assets/{Viewer-BmXiweP2.js → Viewer-YBzeS3RA.js} +1 -1
  40. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-wt87pCBz.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CE2IIKhe.js} +1 -1
  41. package/dist/assets/{addon-icons-context-CvwUgMRr.js → addon-icons-context-D6glxUQF.js} +1 -1
  42. package/dist/assets/{archive-Bwv0mNo-.js → archive-kvflMCgL.js} +1 -1
  43. package/dist/assets/{authed-media-0TPg9TTZ.js → authed-media-CSlndmzS.js} +1 -1
  44. package/dist/assets/{bell-off-D2KzCQW2.js → bell-off-BYnwGeiH.js} +1 -1
  45. package/dist/assets/{boxes-BXQUMgws.js → boxes-Dx4USyB3.js} +1 -1
  46. package/dist/assets/circle-slash-D5mo-8G0.js +1 -0
  47. package/dist/assets/client-CMlUvfoK.js +358 -0
  48. package/dist/assets/{cloud-upload-BsULjxPu.js → cloud-upload-82x5w5u8.js} +1 -1
  49. package/dist/assets/crop-Dev61hIh.js +1 -0
  50. package/dist/assets/{device-integration-icon-CCoHGEQZ.js → device-integration-icon-bTnWrYe0.js} +1 -1
  51. package/dist/assets/device-picker-model-DlnG_8P7.js +1 -0
  52. package/dist/assets/{dist-DQtBl_2T.js → dist--5X8Gy0U.js} +1 -1
  53. package/dist/assets/{dist-DWoekMi0.js → dist-Dod19ois.js} +13 -13
  54. package/dist/assets/{eraser-DB7_WMyf.js → eraser-B8Awx5Sj.js} +1 -1
  55. package/dist/assets/{file-up-DuqaeMYR.js → file-up-LqDVgVVa.js} +1 -1
  56. package/dist/assets/{hard-drive-download-CKj8xKOz.js → hard-drive-download-C24D80x2.js} +1 -1
  57. package/dist/assets/{history-V8RQKQAb.js → history-DZsORyBG.js} +1 -1
  58. package/dist/assets/{hostInit-CdxLRG1l.js → hostInit-D2EmEDvv.js} +1 -1
  59. package/dist/assets/i18n-vggiB6gm.js +1 -0
  60. package/dist/assets/{icons-CEMmjIEL.js → icons-D5RaCH1q.js} +1 -1
  61. package/dist/assets/index-BgQGn3LX.js +4 -0
  62. package/dist/assets/index-BndCgmxf.css +2 -0
  63. package/dist/assets/{key-Bj5-ZBrb.js → key-DLwSBrPM.js} +1 -1
  64. package/dist/assets/{key-round-B2I1YisX.js → key-round-CYflkUyd.js} +1 -1
  65. package/dist/assets/{layers-BARFkXZ5.js → layers-C1wzFfr1.js} +1 -1
  66. package/dist/assets/linked-devices-model-CCTQ_gka.js +1 -0
  67. package/dist/assets/{list-ordered-9lF0Gp3K.js → list-ordered-CFeS9o_w.js} +1 -1
  68. package/dist/assets/location-owned-usage-DSLiI6RY.js +1 -0
  69. package/dist/assets/{log-in-CjtrIfG3.js → log-in-Be_RcxDr.js} +1 -1
  70. package/dist/assets/{memory-stick-B26_SbtH.js → memory-stick-4BwYEagi.js} +1 -1
  71. package/dist/assets/{message-square-plus-COMrVZEZ.js → message-square-plus-D7BNG3h7.js} +1 -1
  72. package/dist/assets/{mf-entry-bootstrap-0-ec37d41a.js → mf-entry-bootstrap-0-9df0d08c.js} +2 -2
  73. package/dist/assets/{mic-off-DBIqFVjg.js → mic-off-e162Bcfu.js} +1 -1
  74. package/dist/assets/{monitor-off-CTQMySOs.js → monitor-off-CARYfHC4.js} +1 -1
  75. package/dist/assets/{monitor-smartphone-iBd_3nPv.js → monitor-smartphone-lsNgnRRZ.js} +1 -1
  76. package/dist/assets/mount-DlnG_8P7.js +1 -0
  77. package/dist/assets/notification-schedule-field-DWpT_5Vh.js +1 -0
  78. package/dist/assets/{octagon-alert-DMjnTemh.js → octagon-alert-h80nyWRM.js} +1 -1
  79. package/dist/assets/{player-overlays-DWMIy1MJ.js → player-overlays-Cda8wso6.js} +1 -1
  80. package/dist/assets/{recycle-BCVF0r6Y.js → recycle-0MLWppmT.js} +1 -1
  81. package/dist/assets/remoteEntry-V_83-NrI.js +1 -0
  82. package/dist/assets/{scan-eye-DRXP3PgB.js → scan-eye-DVK8MF3K.js} +1 -1
  83. package/dist/assets/{scissors-DUFtPb9T.js → scissors-Cz3GoeOd.js} +1 -1
  84. package/dist/assets/{search-x-B3nve3vV.js → search-x-i_A-Upbe.js} +1 -1
  85. package/dist/assets/{send-P2KlabIu.js → send-B5VKcNUH.js} +1 -1
  86. package/dist/assets/{settings-2-reEhyiKz.js → settings-2-ZQsYJ0Zb.js} +1 -1
  87. package/dist/assets/{speaker-DSNMuvS8.js → speaker-Cl8DZGk_.js} +1 -1
  88. package/dist/assets/{src-BLkInT8U.js → src-eoSUZcV-.js} +8 -8
  89. package/dist/assets/{timer-reset-CsRTbSzh.js → timer-reset-A5ofAkBW.js} +1 -1
  90. package/dist/assets/{ungroup-BLeVa8__.js → ungroup-t0yDnzVf.js} +1 -1
  91. package/dist/assets/{unlink-DeNvF8r-.js → unlink-C1ZpCxl3.js} +1 -1
  92. package/dist/assets/{usb-CFseVsQJ.js → usb-DmUPajSy.js} +1 -1
  93. package/dist/assets/{use-scenes-feed-C8frh3hQ.js → use-scenes-feed-BQlYhRMq.js} +1 -1
  94. package/dist/assets/{use-stationary-objects-DNayAuMq.js → use-stationary-objects-BWM4vE0E.js} +1 -1
  95. package/dist/assets/useEventInvalidation-DlnG_8P7.js +1 -0
  96. package/dist/assets/{useNodeUrlSelection-BsLRiUy8.js → useNodeUrlSelection-CTxv9Em7.js} +1 -1
  97. package/dist/assets/user-round-BTaID248.js +1 -0
  98. package/dist/assets/{user-x-CpaZ5HO0.js → user-x-DRcPeM9C.js} +1 -1
  99. package/dist/assets/{video--MLJeLNU.js → video-tLHyNE3q.js} +1 -1
  100. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-1Do_dc2z.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DOOXjnRq.js} +2 -2
  101. package/dist/index.html +11 -10
  102. package/dist/server/addon.js +27 -3
  103. package/package.json +1 -1
  104. package/dist/assets/Addons-BTWw53aT.js +0 -4
  105. package/dist/assets/AiProfiles-Ca7zuVMp.js +0 -3
  106. package/dist/assets/BrokerForm-6-BwPs-g.js +0 -1
  107. package/dist/assets/Build-BsduavcU.js +0 -40
  108. package/dist/assets/Calendars-DVTk_2iT.js +0 -1
  109. package/dist/assets/Cluster-BPJ4maiI.js +0 -1
  110. package/dist/assets/ClusterStepModel-CjuZ-oml.js +0 -1
  111. package/dist/assets/CompositionEditor-DJcmWU2U.js +0 -1
  112. package/dist/assets/Data-CLLvqZwG.js +0 -1
  113. package/dist/assets/DeviceDetail-BKw1gufS.js +0 -2
  114. package/dist/assets/DeviceDoActionFields-R-ZYIdMv.js +0 -1
  115. package/dist/assets/EmbedPlayerPage-B4y0Q0wO.js +0 -1
  116. package/dist/assets/Identity-NOlTR-3q.js +0 -1
  117. package/dist/assets/IntegrationDetail-CcZkPlbN.js +0 -1
  118. package/dist/assets/IntegrationHub-CuW7-WRy.js +0 -1
  119. package/dist/assets/Integrations-ACdx4iPR.js +0 -1
  120. package/dist/assets/Integrations-DjnhmLye.js +0 -1
  121. package/dist/assets/Library-B3iyoKdK.js +0 -1
  122. package/dist/assets/Locations-Cs1VwmXB.js +0 -3
  123. package/dist/assets/Logs-BMc6WXCH.js +0 -1
  124. package/dist/assets/MyAccess-BfUfTXrv.js +0 -2
  125. package/dist/assets/Network-F2lAIcbT.js +0 -1
  126. package/dist/assets/NodeAddonsSettingsPanel-D3ux_JIo.js +0 -1
  127. package/dist/assets/Notifications-Cp3qo_EC.js +0 -1
  128. package/dist/assets/Recordings-D91q74Ga.js +0 -1
  129. package/dist/assets/ScanNetworkModal-DjU-xM4X.js +0 -1
  130. package/dist/assets/SessionsList-DQ7kj8fX.js +0 -2
  131. package/dist/assets/System-DLLa4weE.js +0 -1
  132. package/dist/assets/circle-slash-DpUtlEnB.js +0 -1
  133. package/dist/assets/client-CjyKfSu1.js +0 -358
  134. package/dist/assets/crop-BtQBZ9jm.js +0 -1
  135. package/dist/assets/device-picker-model-1Z6p3UkP.js +0 -1
  136. package/dist/assets/index-D66JvELZ.js +0 -4
  137. package/dist/assets/index-dmZ34NAY.css +0 -2
  138. package/dist/assets/location-owned-usage-CNXQ-Obv.js +0 -1
  139. package/dist/assets/mount-1Z6p3UkP.js +0 -1
  140. package/dist/assets/notification-schedule-field-D8dd67dT.js +0 -1
  141. package/dist/assets/remoteEntry-RwWzzVu_.js +0 -1
  142. package/dist/assets/useEventInvalidation-1Z6p3UkP.js +0 -1
  143. package/dist/assets/user-round-BB0VDRnJ.js +0 -1
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,V as i,W as a,b as o,o as s,q as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{D as d,It as f,Jr as p,Nt as m,Oi as h,On as g,Pn as _,Rn as v,Rr as y,Sn as b,Yi as x,_i as S,_n as C,ai as w,ar as T,bi as E,bn as D,di as O,dn as k,dt as A,fn as j,on as M,ot as N,pi as ee,un as te,yi as ne,yn as P}from"./player-overlays-DWMIy1MJ.js";import{t as re}from"./hard-drive-download-CKj8xKOz.js";import{t as ie}from"./memory-stick-B26_SbtH.js";import{$r as ae,Qr as oe,Zr as se,ni as ce}from"./client-CjyKfSu1.js";import{$o as le,An as ue,Bn as F,Dn as de,En as fe,Fc as pe,G as I,Go as me,Ht as L,Ic as he,Lc as ge,Ln as R,M as _e,Ns as ve,On as ye,Pc as be,Qo as xe,Rn as Se,Tn as Ce,Tt as we,U as Te,Ut as Ee,Vs as De,Vt as Oe,Wo as ke,Wt as Ae,Xl as z,Xs as je,Xt as Me,Zn as B,Zo as Ne,ar as Pe,cr as Fe,dr as Ie,es as Le,fu as Re,gu as V,il as ze,jn as Be,kn as Ve,lr as He,ma as Ue,pu as H,rc as We,ur as Ge,wt as Ke}from"./src-BLkInT8U.js";import{t as U}from"./useTranslation-Bc5yH9V9.js";import{Z as qe}from"./index-D66JvELZ.js";import{t as Je}from"./AdminPage-C0Zxs_ot.js";import{t as Ye}from"./NodeAddonsSettingsPanel-D3ux_JIo.js";import{f as Xe,l as Ze,m as Qe,u as $e}from"./board-model-Bmts6hrg.js";import{t as W}from"./format-size-DIxKXxtj.js";import{n as et,t as tt}from"./useNodeUrlSelection-BsLRiUy8.js";n();var nt={unpaired:`Not paired`,pending:`Pairing…`,paired:`Paired`},rt=new Set([`paired`,`rejected`,`failed`,`expired`]);function G(e){return rt.has(e)}function it(e){return e.replace(/\D/g,``).slice(0,6)}function at(e){return e.length===6}function ot(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3)),r=Math.floor(n/60),i=n%60;return`${r}:${String(i).padStart(2,`0`)}`}function st(e,t){return e.includes(`:`)?`[${e}]:${t}`:`${e}:${t}`}function ct(e){return e.length<=23?e:`${e.slice(0,20)}…`}function lt({view:e,beginError:t}){if(e===null)return t===null?`sending`:`send-failed`;switch(e.state){case`paired`:return`paired`;case`rejected`:return`rejected`;case`failed`:return`failed`;case`expired`:return`expired`;case`completing`:return`completing`;case`awaiting-confirmation`:return e.hubConfirmed&&!e.agentConfirmed?`awaiting-agent`:e.agentConfirmed&&!e.hubConfirmed?`awaiting-hub`:`awaiting-both`}}function ut(e){return e===`awaiting-both`||e===`awaiting-hub`}var dt={sending:`Sending the pairing offer to the agent…`,"send-failed":`The agent could not be reached`,"awaiting-both":`Waiting for both confirmations`,"awaiting-agent":`Confirmed here — waiting for the agent`,"awaiting-hub":`The agent is confirmed — now confirm here`,completing:`Issuing the node certificate…`,paired:`Paired`,rejected:`Pairing was rejected`,failed:`Pairing failed`,expired:`The pairing expired`},ft=2e3,pt=1e3;function mt(e){return e.message.length>0?e.message:`Request failed`}function ht(e){return e.length===6?`${e.slice(0,3)} ${e.slice(3)}`:e}function gt(e){let[t,n]=c(()=>Date.now());return u(()=>{if(!e)return;let t=setInterval(()=>n(Date.now()),pt);return()=>clearInterval(t)},[e]),t}function _t({target:e,onClose:n,onSettled:i,onOpenNode:a}){let[s,d]=c(null),[f,p]=c(null),[m,h]=c(``),[g,_]=c(null),v=t(null),y=V.agentPairing.beginPairing.useMutation(),b=V.agentPairing.confirmPairing.useMutation(),x=V.agentPairing.rejectPairing.useMutation();u(()=>{if(e===null){v.current=null,d(null),p(null),h(``),_(null);return}v.current!==e&&(v.current=e,y.mutateAsync({host:e.host,port:e.port}).then(t=>{v.current===e&&d(t.pairingId)}).catch(t=>{v.current===e&&p(mt(t))}))},[e]);let S=V.agentPairing.getPairing.useQuery({pairingId:s??``},{enabled:s!==null,refetchInterval:e=>{let t=e.state.data?.state;return t!==void 0&&G(t)?!1:ft}}),C=vt(b.data??x.data??null,S.data??null),w=lt({view:C,beginError:f}),E=C!==null&&G(C.state),D=t(!1);u(()=>{if(!E){D.current=!1;return}D.current||(D.current=!0,i())},[E,i]);let O=gt(C!==null&&!E),k=()=>{s===null||!at(m)||(_(null),b.mutate({pairingId:s,code:m},{onError:e=>{_(mt(e)),h(``)}}))};return l(Ce,{open:e!==null,onOpenChange:e=>!e&&n(),children:r(de,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[r(ue,{children:[r(Be,{children:[`Pair agent `,e?.nodeId??``]}),l(ye,{children:e===null?``:`Each screen shows a code; you type the code from the OTHER screen. Agent at ${st(e.host,e.port)}`})]}),r(fe,{className:`space-y-4`,children:[l(yt,{phase:w}),w===`send-failed`&&f!==null&&l(R,{title:`Could not start the pairing`,message:f}),C!==null&&!E&&l(bt,{view:C,phase:w,now:O,typed:m,onType:e=>h(it(e)),onSubmit:k,confirmError:g,busy:b.isPending}),w===`paired`&&C!==null&&l(xt,{nodeId:C.nodeId,onOpenNode:a,onClose:n}),E&&w!==`paired`&&C?.failure!=null&&l(R,{message:C.failure})]}),l(Ve,{children:E||w===`send-failed`?l(F,{type:`button`,variant:`outline`,onClick:n,children:`Close`}):r(o,{children:[l(F,{type:`button`,variant:`outline`,disabled:x.isPending,onClick:()=>{if(s===null){n();return}x.mutate({pairingId:s},{onSettled:n})},children:`Reject`}),ut(w)&&r(F,{type:`button`,disabled:!at(m)||b.isPending,onClick:k,children:[b.isPending&&l(T,{className:`h-4 w-4 animate-spin`}),`Confirm`]})]})})]})})}function vt(e,t){if(t===null)return e;if(e===null)return t;let n=e=>(G(e.state)?10:e.state===`completing`?5:0)+ +!!e.hubConfirmed+ +!!e.agentConfirmed;return n(e)>n(t)?e:t}function yt({phase:e}){let t=e===`sending`||e===`completing`,n=e===`paired`,i=e===`rejected`||e===`failed`||e===`expired`||e===`send-failed`;return r(`p`,{role:`status`,className:`flex items-center gap-2 text-sm font-medium ${n?`text-success`:i?`text-danger`:`text-foreground`}`,children:[t&&l(T,{className:`h-4 w-4 animate-spin`}),n&&l(O,{className:`h-4 w-4`}),i&&l(w,{className:`h-4 w-4`}),dt[e]]})}function bt({view:e,phase:t,now:n,typed:i,onType:a,onSubmit:o,confirmError:s,busy:c}){return r(`div`,{className:`space-y-4`,children:[r(`section`,{"aria-label":`Code on this hub`,className:`rounded-md border border-border bg-surface p-3`,children:[l(`p`,{className:`text-xs text-foreground-muted`,children:`Code on this hub — read it out to the agent`}),l(`p`,{"data-testid":`hub-code`,className:`mt-1 font-mono text-3xl font-semibold tracking-widest text-foreground`,children:ht(e.code)}),l(`p`,{className:`mt-2 text-xs text-foreground-muted`,children:`On the agent, enter this code and the agent’s local PIN (shown on the agent’s console or log, or on its own screen).`})]}),ut(t)?l(`form`,{className:`space-y-2`,onSubmit:e=>{e.preventDefault(),o()},children:l(I,{label:`Code shown on the agent`,description:`Type the six digits the agent displays. Do not copy the code above.`,...s===null?{}:{error:s},children:l(z,{value:i,onChange:e=>a(e.target.value),inputMode:`numeric`,autoComplete:`off`,spellCheck:!1,placeholder:`000000`,maxLength:6,disabled:c,"aria-label":`Code shown on the agent`,className:`font-mono tracking-widest`})})}):l(`p`,{className:`text-xs text-foreground-muted`,children:t===`awaiting-agent`?`You confirmed here. The agent still has to enter the hub code and its PIN.`:`Working…`}),r(`ul`,{className:`flex flex-wrap gap-x-4 gap-y-1 text-xs text-foreground-muted`,children:[l(`li`,{children:e.hubConfirmed?`Hub: confirmed`:`Hub: not confirmed`}),l(`li`,{children:e.agentConfirmed?`Agent: confirmed`:`Agent: not confirmed`}),r(`li`,{"data-testid":`countdown`,children:[`Expires in `,ot(e.expiresAt,n)]})]})]})}function xt({nodeId:e,onOpenNode:t,onClose:n}){let{nodes:i}=Re(),a=i?.some(t=>t.id===e&&t.isOnline)===!0;return r(`div`,{className:`space-y-2 rounded-md border border-success/40 bg-success/10 p-3 text-sm`,children:[r(`p`,{className:`flex items-center gap-2 text-success`,children:[l(M,{className:`h-4 w-4`}),a?`${e} joined and registered its capabilities.`:`${e} holds its certificate. Waiting for it to connect and register its capabilities…`]}),l(F,{type:`button`,size:`sm`,variant:`outline`,disabled:!a,onClick:()=>{n(),t(e)},children:`Open node`})]})}var St={paired:`success`,pending:`warning`,unpaired:`default`};function Ct({state:e,connected:t}){return r(`span`,{className:`inline-flex items-center gap-1.5`,children:[l(Pe,{variant:St[e],className:`text-[10px]`,children:nt[e]}),e===`paired`&&l(`span`,{className:`text-[10px] text-foreground-muted`,children:t?`connected`:`not connected`})]})}n();var K={pending:0,unpaired:1,paired:2};function wt(e){if(e.trim().length===0)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:null}function Tt({onOpenNode:e}){let t=B(),n=V.useUtils(),i=V.agentPairing.listDiscoveredAgents.useQuery(void 0,{refetchInterval:15e3}),[s,u]=c(null),[f,p]=c(null),[m,h]=c(!1),[_,v]=c(``),[y,x]=c(``),[S,C]=c(null),[w,E]=c(!1),D=()=>void n.agentPairing.listDiscoveredAgents.invalidate(),O=V.agentPairing.addAgentByAddress.useMutation({onSuccess:()=>{h(!1),v(``),x(``),C(null),D()},onError:e=>C(e.message)}),k=V.agentPairing.unpairAgent.useMutation({onSuccess:e=>{p({tone:`success`,message:`${e.nodeId}: ${e.next}${e.agentNotified?``:` The agent could not be told; forget the hub on its own page.`}`}),D()},onError:e=>p({tone:`danger`,message:`Unpair failed: ${e.message}`})}),A=a(()=>(i.data?.agents??[]).toSorted((e,t)=>K[e.state]-K[t.state]),[i.data]),j=async()=>{E(!0);try{await n.agentPairing.listDiscoveredAgents.fetch({refresh:!0}),D()}finally{E(!1)}},M=()=>{let e=wt(y);if(e===null){C(`The port must be a whole number between 1 and 65535.`);return}C(null),O.mutate({host:_.trim(),...e===void 0?{}:{port:e}})},N=async e=>{await t({title:`Unpair ${e.nodeId}`,message:`${e.nodeId}'s certificates are revoked at once and it is disconnected from the mesh. It must be paired again before it can rejoin.`,confirmLabel:`Unpair`,variant:`danger`})&&(p(null),k.mutate({nodeId:e.nodeId}))},ee=a(()=>[{key:`node`,header:`Node`,render:e=>l(`span`,{className:`font-medium text-foreground`,children:e.nodeId}),sortValue:e=>e.nodeId},{key:`address`,header:`Address`,render:e=>l(`span`,{className:`font-mono text-xs`,children:st(e.host,e.port)}),sortValue:e=>e.host},{key:`version`,header:`Version`,render:e=>e.version??`—`,sortValue:e=>e.version},{key:`state`,header:`State`,render:e=>l(Ct,{state:e.state,connected:e.connected}),sortValue:e=>K[e.state]},{key:`fingerprint`,header:`Certificate`,render:e=>e.fingerprint===null?`—`:l(`span`,{className:`font-mono text-xs`,title:e.fingerprint,children:ct(e.fingerprint)}),sortValue:e=>e.fingerprint},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>e.state===`unpaired`?l(F,{type:`button`,size:`sm`,onClick:()=>u({nodeId:e.nodeId,host:e.host,port:e.port}),children:`Pair`}):e.state===`paired`?l(F,{type:`button`,size:`sm`,variant:`outline`,disabled:k.isPending,onClick:()=>void N(e),children:`Unpair`}):null}],[k.isPending]);return r(Oe,{headingId:`agents-found`,title:`Agents found on the network`,icon:b,testId:`agents-found`,actions:r(o,{children:[r(F,{type:`button`,size:`sm`,variant:`outline`,disabled:w,onClick:()=>void j(),children:[w?l(T,{className:`h-3.5 w-3.5 animate-spin`}):l(P,{className:`h-3.5 w-3.5`}),`Scan`]}),r(F,{type:`button`,size:`sm`,onClick:()=>h(e=>!e),children:[l(g,{className:`h-3.5 w-3.5`}),`Add by address`]})]}),children:[r(`div`,{className:`${d} space-y-3`,children:[l(`p`,{className:`text-[11px] leading-relaxed text-foreground-muted`,children:`An agent holds no secret: pairing issues it a certificate after you confirm the same six digits on this page and on the agent. Discovery needs the agent on its own IP or host networking; a Docker bridge hides it — add it by address.`}),m&&r(`form`,{"aria-label":`Add agent by address`,className:`flex flex-wrap items-start gap-2`,onSubmit:e=>{e.preventDefault(),_.trim().length>0&&!O.isPending&&M()},children:[l(I,{label:`Address`,description:`A private or local address only.`,...S===null?{}:{error:S},children:l(z,{value:_,onChange:e=>v(e.target.value),placeholder:`192.168.1.50`,"aria-label":`Agent address`,autoComplete:`off`})}),l(I,{label:`Port`,description:`Optional.`,children:l(z,{value:y,onChange:e=>x(e.target.value),placeholder:`4444`,inputMode:`numeric`,"aria-label":`Agent port`,className:`w-24`})}),r(F,{type:`submit`,size:`sm`,className:`mt-5`,disabled:_.trim().length===0||O.isPending,children:[O.isPending&&l(T,{className:`h-3.5 w-3.5 animate-spin`}),`Add`]})]}),f!==null&&l(`p`,{role:`status`,className:`rounded border px-3 py-2 text-xs ${f.tone===`success`?`border-success/30 text-foreground`:`border-danger/40 text-danger`}`,children:f.message}),i.isError?l(R,{title:`Could not list agents`,message:i.error?.message??`Request failed`,onRetry:D}):i.isLoading?l(`p`,{className:`py-4 text-center text-xs text-foreground-muted`,children:`Looking for agents…`}):A.length===0?l(Se,{icon:b,title:`No agents found`,description:`Nothing is advertising on this network. Start the agent on its own IP (or host networking), or add it by address.`}):l(L,{columns:ee,rows:A,rowKey:e=>e.nodeId,minWidthPx:720,mobileMode:`cards`,defaultSort:{columnKey:`state`,dir:`asc`}})]}),l(_t,{target:s,onClose:()=>u(null),onSettled:D,onOpenNode:e})]})}function Et(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dt(e){if(!Et(e))return null;let t=e.ticket;if(typeof t!=`string`||t.length===0)return null;let n=e.dashboardUrl;return typeof n==`string`&&n.length>0?{ticket:t,dashboardUrl:n}:{ticket:t}}function Ot(e){let t=e.trim();return!(t.length===0||t.includes(`/`)||t.includes(`?`)||t.includes(`#`)||t.includes(`@`)||t.includes(`:`))}function kt(e){return e.startsWith(`172.17.`)}function At(e){let t=/^100\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=64&&n<=127}function jt(e){if(e.startsWith(`10.`)||e.startsWith(`192.168.`))return!0;let t=/^172\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=16&&n<=31&&!kt(e)}function Mt(e,t){if(typeof t==`string`&&Ot(t))return t.trim();let n=e.filter(e=>!e.includes(`:`)),r=n.find(e=>!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!kt(e)&&!At(e)&&jt(e));if(r!==void 0)return r;for(let e of n)if(!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!kt(e))return e;return null}function Nt(e){return`http://${e}:4444/`}function Pt(e,t){let n=new URL(Nt(e));return n.searchParams.set(`ticket`,t),n.toString()}function Ft(){return window.open(`about:blank`,`_blank`)}function It(e,t){return e===null||e.closed?!1:(e.location.href=t,!0)}n();function Lt(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}function Rt(e){return e===`running`?`running`:e===`crashed`||e===`failed`?`error`:`stopped`}var zt=[`trace`,`debug`,`info`,`warn`,`error`];function Bt({proc:e,nodeId:t,defaultExpanded:n,activePanel:i,onTogglePanel:a}){let o=e.services??[],s=o.length===1,[u,d]=c(s||n),[f,p]=c(null),[m,g]=c(`info`),_=e.name.includes(`(core)`),v=xe(),y=le(),b=Le(),x=async e=>{p(e);try{await v.mutateAsync({nodeId:t,addonId:e})}catch(e){console.error(`Failed to restart addon:`,e)}finally{p(null)}},w=async()=>{p(e.name);try{await y.mutateAsync({nodeId:t,processName:e.name})}catch(e){console.error(`Failed to restart process:`,e)}finally{p(null)}},T=async n=>{let r=`${t}/${e.name}`;try{await b.mutateAsync({nodeId:r,level:n}),g(n)}catch(e){console.error(`Failed to set log level:`,e)}};return r(`div`,{className:`border border-border/50 rounded-lg overflow-hidden`,children:[r(`div`,{role:s?void 0:`button`,tabIndex:s?void 0:0,onClick:s?void 0:()=>d(!u),onKeyDown:s?void 0:e=>{(e.key===`Enter`||e.key===` `)&&d(!u)},className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 w-full px-3 py-2 bg-muted/20 transition-colors text-left select-none ${s?``:`hover:bg-muted/40 cursor-pointer`}`,children:[s?l(`span`,{className:`h-3 w-3 shrink-0`}):l(u?ne:S,{className:`h-3 w-3 text-muted-foreground shrink-0`}),_?l(te,{className:`h-3.5 w-3.5 text-primary shrink-0`}):l(h,{className:`h-3.5 w-3.5 text-warning shrink-0`}),l(`span`,{className:`text-xs font-semibold min-w-0 flex-1 basis-full truncate sm:basis-auto`,children:e.name}),r(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:[`PID `,e.pid]}),l(_e,{status:Rt(e.state),label:e.state}),r(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:[e.cpuPercent,`% CPU`]}),l(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:W(e.memoryRss)}),l(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:Lt(e.uptimeSeconds)}),!_&&r(`div`,{className:`flex items-center gap-1`,onClick:e=>e.stopPropagation(),children:[r(Fe,{children:[l(Ie,{className:`text-[9px] px-1.5 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors font-mono`,title:`Set log level`,children:m}),l(He,{align:`end`,className:`min-w-[70px] py-0.5`,children:zt.map(e=>l(Ge,{onClick:()=>T(e),className:`h-auto px-2 py-1 text-[10px] font-mono ${e===m?`text-primary font-semibold`:``}`,children:e},e))})]}),l(`button`,{onClick:w,disabled:f===e.name,className:`p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:`Restart process`,children:l(C,{className:`h-3 w-3 ${f===e.name?`animate-spin`:``}`})})]})]}),u&&o.length>0&&l(`div`,{className:`divide-y divide-border/30`,children:o.map(e=>r(`div`,{children:[r(`div`,{className:`flex items-center gap-2 px-3 py-1.5 pl-9 hover:bg-muted/10 transition-colors`,children:[l(`div`,{className:`h-1.5 w-1.5 rounded-full shrink-0 ${e.status===`running`?`bg-success`:`bg-muted-foreground/30`}`}),l(`span`,{className:`text-xs font-medium flex-1 min-w-0 truncate`,children:e.addonId}),e.capabilities.length>0&&r(`div`,{className:`flex gap-1 flex-shrink-0`,children:[e.capabilities.slice(0,3).map(e=>l(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-info/10 text-info truncate max-w-[80px]`,children:e},e)),e.capabilities.length>3&&r(`span`,{className:`text-[9px] text-muted-foreground`,children:[`+`,e.capabilities.length-3]})]}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[l(`button`,{onClick:()=>a(e.addonId,`logs`),className:`p-0.5 rounded transition-colors ${i?.addonId===e.addonId&&i.type===`logs`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:`Show logs for ${e.addonId}`,children:l(j,{className:`h-3 w-3`})}),l(`button`,{onClick:()=>a(e.addonId,`events`),className:`p-0.5 rounded transition-colors ${i?.addonId===e.addonId&&i.type===`events`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:`Show events for ${e.addonId}`,children:l(D,{className:`h-3 w-3`})}),l(`button`,{onClick:()=>x(e.addonId),disabled:f===e.addonId,className:`p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:`Restart ${e.addonId}`,children:l(C,{className:`h-3 w-3 ${f===e.addonId?`animate-spin`:``}`})})]})]}),i?.addonId===e.addonId&&i.type===`logs`&&l(`div`,{className:`border-t border-border/40 bg-muted/5`,children:l(we,{addonId:e.addonId,agentId:t,maxHeight:`max-h-48`,showFilters:!1,onClose:()=>a(e.addonId,`logs`)})}),i?.addonId===e.addonId&&i.type===`events`&&l(`div`,{className:`border-t border-border/40 bg-muted/5`,children:l(Ke,{addonId:e.addonId,category:`addon.*`,maxHeight:`max-h-48`,onClose:()=>a(e.addonId,`events`)})})]},e.addonId))}),u&&o.length===0&&l(`div`,{className:`px-3 py-2 pl-9 text-[10px] text-muted-foreground`,children:`No services`})]})}function Vt({nodeId:e,processes:t}){let[n,r]=c(null),i=(e,t)=>{r(n=>n?.addonId===e&&n.type===t?null:{addonId:e,type:t})};return t.length===0?l(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:`No processes on this node`}):l(`div`,{className:`space-y-2 py-1`,children:t.map((t,r)=>l(Bt,{proc:t,nodeId:e,defaultExpanded:r===0,activePanel:n,onTogglePanel:i},t.name))})}var Ht={system:0,managed:1,root:2};n();function Ut(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`}function Wt(e,t=80){return e.length<=t?e:`…${e.slice(e.length-t+1)}`}function Gt({nodeId:e}){let t=s(),n=H(`metrics.node-processes-snapshot`,t=>t.nodeId===e),{data:i}=me({nodeId:e}),o=n?.processes??i,c=a(()=>o?[...o]:[],[o]),u=a(()=>[{key:`classification`,header:`Class`,sortValue:e=>Ht[e.classification],render:e=>l(`span`,{className:`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium ${e.classification===`root`?`bg-info/20 text-info`:e.classification===`system`?`bg-foreground-subtle/20 text-foreground-subtle`:`bg-success/20 text-success`}`,children:e.classification})},{key:`pid`,header:`PID`,align:`right`,sortValue:e=>e.pid,render:e=>l(`span`,{className:`font-mono`,children:e.pid})},{key:`ppid`,header:`PPID`,align:`right`,sortValue:e=>e.ppid,render:e=>l(`span`,{className:`font-mono text-foreground-subtle`,children:e.ppid})},{key:`addonId`,header:`Addon`,sortValue:e=>e.addonId,render:e=>l(`span`,{className:`text-foreground-subtle text-[11px]`,children:e.addonId??`—`})},{key:`command`,header:`Command`,nowrap:!1,render:e=>l(`span`,{className:`font-mono text-[10px] text-foreground-subtle break-all`,children:Wt(e.command)})},{key:`cpuPercent`,header:`CPU%`,align:`right`,sortValue:e=>e.cpuPercent,render:e=>e.cpuPercent.toFixed(1)},{key:`memoryRssBytes`,header:`RSS`,align:`right`,sortValue:e=>e.memoryRssBytes,render:e=>W(e.memoryRssBytes)},{key:`uptimeSec`,header:`Uptime`,align:`right`,sortValue:e=>e.uptimeSec,render:e=>l(`span`,{className:`text-foreground-subtle`,children:Ut(e.uptimeSec)})}],[]);return r(`div`,{className:`space-y-4`,children:[l(`div`,{className:`flex items-start justify-end gap-4`,children:r(`button`,{type:`button`,onClick:()=>t.invalidateQueries({queryKey:[[`metricsProvider`,`listNodeProcesses`]]}),className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:[l(P,{className:`h-3 w-3`}),` Refresh`]})}),l(L,{columns:u,rows:c,rowKey:e=>e.pid,minWidthPx:880,mobileMode:`cards`,maxBodyHeight:Ee,emptyMessage:`Scanning…`})]})}var q={width:320,height:64},Kt=.8,J=Math.ceil(8*Kt-3)+1,Y=q.width+34,qt=q.height+J+1+11,Jt=J+q.height+1+3+Math.ceil(8*Kt),Yt=[1,2,5,10],Xt=[1,2,4,8,16,32,64,128,256,512,1024],Zt=[1,1.5,2,2.5,3,4,5],Qt=[4,3,5,2],$t=1e-9;function en(e,t){if(!Number.isFinite(e)||e<=0)return!1;if(t===`bytes`){if(!Number.isInteger(e))return!1;let t=e/1024**Math.floor(Math.log(e)/Math.log(1024));return Zt.some(e=>Math.abs(t-e)<$t)}let n=e/10**Math.floor(Math.log10(e));return Zt.some(e=>Math.abs(n-e)<$t)}function tn(e,t,n){let r=0;for(let t of e)t!==null&&t>r&&(r=t);if(r<=t)return t;if(n===`bytes`){let e=1024**Math.floor(Math.log(r)/Math.log(1024));for(let t of Xt){let n=t*e;if(n>=r)return n}return 1024*e}let i=10**Math.floor(Math.log10(r));for(let e of Yt){let t=e*i;if(t>=r)return t}return 10*i}function nn(e,t){if(!Number.isFinite(e)||e<=0)return[];let n=Qt.find(n=>en(e/n,t))??Qt[Qt.length-1],r=e/n,i=[];for(let e=1;e<=n;e++)i.push(r*e);return i}var rn=2.5;function an(e){return e*rn}function on(e,t,n,r){if(e.length===0)return[];let i=e[0].atMs,a=e.at(-1).atMs-i,o=n<=0?1:n,s=r!==void 0&&r>0?r:null;return e.map((r,c)=>{let l=a>0?(r.atMs-i)/a*t.width:c/Math.max(1,e.length-1)*t.width,u=c>0?e[c-1]:void 0;return{x:l,y:r.value===null?null:t.height-Math.min(r.value,n)/o*t.height,gapBefore:s!==null&&u!==void 0&&r.atMs-u.atMs>s}})}function sn(e){let t=[],n=!1;for(let r of e){if(r.y===null){n=!1;continue}r.gapBefore&&(n=!1),t.push(`${n?`L`:`M`}${r.x.toFixed(1)},${r.y.toFixed(1)}`),n=!0}return t.join(` `)}function cn(e,t){let n=[],r=[],i=()=>{if(r.length<2){r=[];return}let e=r.map((e,t)=>`${t===0?`M`:`L`}${e.x.toFixed(1)},${e.top.toFixed(1)}`),t=[...r].reverse().map(e=>`L${e.x.toFixed(1)},${e.bottom.toFixed(1)}`);n.push(`${e.join(` `)} ${t.join(` `)} Z`),r=[]};for(let n=0;n<e.length;n++){let a=e[n],o=t[n];if(!a||!o||a.y===null||o.y===null){i();continue}(a.gapBefore||o.gapBefore)&&i(),r.push({x:a.x,top:a.y,bottom:o.y})}return i(),n.join(` `)}function ln(e,t,n=3){if(e.length<2||n<2)return[];let r=e[0].atMs,i=e.at(-1).atMs-r;if(i<=0)return[];let a=[];for(let e=0;e<n;e++){let o=e/(n-1);a.push({atMs:r+i*o,x:o*t.width,anchor:e===0?`start`:e===n-1?`end`:`middle`})}return a}function un(e){return e.length<2?0:Math.max(0,e.at(-1).atMs-e[0].atMs)}function dn(e){let t=[];for(let n=1;n<e.length;n++){let r=e[n];r.gapBefore&&t.push({fromX:e[n-1].x,toX:r.x})}return t}function fn(e,t){if(e.length===0)return null;let n=0,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].x-t);a<r&&(r=a,n=i)}return n}n();var X={main:`var(--color-chart-series-a)`,gc:`var(--color-chart-series-b)`},Z=q,pn={height:qt};function mn({title:e,points:n,mainLabel:s,gcLabel:u,formatValue:d,emptyMessage:f,gapMs:p}){let m=i(),h=t(null),[g,_]=c(null),v=a(()=>{let e=n.map(e=>({atMs:e.atMs,value:e.main===null||e.gc===null?null:e.main+e.gc})),t=n.map(e=>({atMs:e.atMs,value:e.main})),r=tn(e.map(e=>e.value),25,`linear`),i=on(e,Z,r,p),a=on(t,Z,r,p),o=a.map(e=>({x:e.x,y:e.y===null?null:Z.height,gapBefore:e.gapBefore}));return{max:r,ticks:nn(r,`linear`),upper:i,middle:a,base:o,gaps:dn(i),times:ln(e,Z),spanMs:un(e)}},[n,p]),y=n.at(-1),b=g===null?void 0:n[g.index],x=b??y;return n.length===0||v.upper.every(e=>e.y===null)?l(Q,{title:e,children:l(En,{message:f})}):l(Q,{title:e,legend:r(o,{children:[l(wn,{color:X.main,label:s}),l(wn,{color:X.gc,label:u})]}),readout:x&&x.main!==null&&x.gc!==null?r(o,{children:[b!==void 0&&l(Cn,{atMs:b.atMs,spanMs:v.spanMs}),l(Tn,{color:X.main,text:d(x.main)}),l(Tn,{color:X.gc,text:d(x.gc)})]}):null,children:r(`svg`,{ref:h,viewBox:`0 0 ${Y} ${qt}`,preserveAspectRatio:`none`,className:`w-full`,style:pn,role:`img`,"aria-label":`${e}: ${s} and ${u} over time`,onMouseLeave:()=>_(null),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width===0)return;let n=(e.clientX-t.left)/t.width*Y-34,r=fn(v.upper,n);r!==null&&_({index:r,xPx:v.upper[r].x})},children:[l(gn,{ticks:v.ticks,max:v.max,formatValue:d}),l(Sn,{ticks:v.times,spanMs:v.spanMs}),r(`g`,{transform:`translate(34,${J})`,clipPath:`url(#${m})`,children:[l(`clipPath`,{id:m,children:l(`rect`,{x:0,y:0,width:Z.width,height:Z.height})}),l(_n,{spans:v.gaps}),l(`path`,{d:cn(v.middle,v.base),fill:X.main,fillOpacity:.85}),l(`path`,{d:cn(v.upper,v.middle),fill:X.gc,fillOpacity:.85,stroke:`var(--color-surface, transparent)`,strokeWidth:2}),l(`path`,{d:sn(v.upper),fill:`none`,stroke:X.gc,strokeWidth:2}),g!==null&&l(`line`,{x1:g.xPx,x2:g.xPx,y1:0,y2:Z.height,stroke:`currentColor`,strokeWidth:1,className:`text-foreground-subtle`})]})]})})}function hn({title:e,points:n,formatValue:i,emptyMessage:s,axisFloor:u,axisScale:d=`linear`,gapMs:f}){let p=t(null),[m,h]=c(null),g=a(()=>{let e=tn(n.map(e=>e.value),u,d),t=on(n,Z,e,f);return{max:e,ticks:nn(e,d),projected:t,gaps:dn(t),times:ln(n,Z),spanMs:un(n)}},[n,u,d,f]),_=m===null?void 0:n[m.index],v=_??n.at(-1)??void 0;return n.length===0||g.projected.every(e=>e.y===null)?l(Q,{title:e,children:l(En,{message:s})}):l(Q,{title:e,readout:v&&v.value!==null?r(o,{children:[_!==void 0&&l(Cn,{atMs:_.atMs,spanMs:g.spanMs}),l(Tn,{color:X.main,text:i(v.value)})]}):null,children:r(`svg`,{ref:p,viewBox:`0 0 ${Y} ${qt}`,preserveAspectRatio:`none`,className:`w-full`,style:pn,role:`img`,"aria-label":e,onMouseLeave:()=>h(null),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width===0)return;let n=(e.clientX-t.left)/t.width*Y-34,r=fn(g.projected,n);r!==null&&h({index:r,xPx:g.projected[r].x})},children:[l(gn,{ticks:g.ticks,max:g.max,formatValue:i}),l(Sn,{ticks:g.times,spanMs:g.spanMs}),r(`g`,{transform:`translate(34,${J})`,children:[l(_n,{spans:g.gaps}),l(`path`,{d:sn(g.projected),fill:`none`,stroke:X.main,strokeWidth:2}),m!==null&&l(`line`,{x1:m.xPx,x2:m.xPx,y1:0,y2:Z.height,stroke:`currentColor`,strokeWidth:1,className:`text-foreground-subtle`})]})]})})}function gn({ticks:e,max:t,formatValue:n}){let i=t<=0?1:t;return l(`g`,{className:`text-foreground-subtle`,children:e.map(e=>{let t=J+Z.height-e/i*Z.height;return r(`g`,{children:[l(`line`,{x1:34,x2:34+Z.width,y1:t,y2:t,stroke:`currentColor`,strokeWidth:.5,strokeOpacity:.3}),l(`text`,{x:0,y:t+3,fontSize:8,fill:`currentColor`,children:n(e)})]},e)})})}function _n({spans:e}){return e.length===0?null:l(`g`,{className:`text-foreground-subtle`,children:e.map(e=>l(`rect`,{x:e.fromX,y:0,width:Math.max(1,e.toX-e.fromX),height:Z.height,fill:`currentColor`,fillOpacity:.12,children:l(`title`,{children:`No samples in this interval — nothing was measured, nothing is drawn.`})},`${e.fromX}-${e.toX}`))})}var vn=10*6e4,yn={hour:`2-digit`,minute:`2-digit`},bn={hour:`2-digit`,minute:`2-digit`,second:`2-digit`};function xn(e,t){return new Date(e).toLocaleTimeString(void 0,t<vn?bn:yn)}function Sn({ticks:e,spanMs:t}){return e.length===0?null:l(`g`,{className:`text-foreground-subtle`,children:e.map(e=>l(`text`,{x:34+e.x,y:Jt,fontSize:8,textAnchor:e.anchor,fill:`currentColor`,children:xn(e.atMs,t)},e.atMs))})}function Cn({atMs:e,spanMs:t}){return l(`span`,{className:`text-[10px] tabular-nums text-foreground-subtle`,children:xn(e,t)})}function Q({title:e,legend:t,readout:n,children:i}){return r(`div`,{className:`min-w-0`,children:[r(`div`,{className:`flex items-baseline justify-between gap-2 mb-1`,children:[l(`span`,{className:`text-[10px] uppercase tracking-wider text-foreground-subtle`,children:e}),l(`div`,{className:`flex items-center gap-2`,children:n})]}),i,t&&l(`div`,{className:`flex items-center gap-3 mt-1`,children:t})]})}function wn({color:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1 text-[9px] text-foreground-subtle`,children:[l(`span`,{className:`inline-block h-2 w-2 rounded-[2px]`,style:{backgroundColor:e}}),t]})}function Tn({color:e,text:t}){return r(`span`,{className:`inline-flex items-center gap-1 text-[11px] tabular-nums text-foreground`,children:[l(`span`,{className:`inline-block h-2 w-2 rounded-[2px]`,style:{backgroundColor:e}}),t]})}function En({message:e}){return l(`div`,{className:`h-16 flex items-center justify-center rounded border border-dashed border-border text-[10px] text-foreground-subtle text-center px-2`,children:e})}function Dn(e,t){let n=e.at(-1);return n===void 0?[t]:t.atMs>n.atMs?[...e,t]:e.some(e=>e.atMs===t.atMs)?e:[...e,t].toSorted((e,t)=>e.atMs-t.atMs)}function On(e,t,n,r){let i=e.get(t),a=Dn(i?.points??[],r);if(i!==void 0&&a===i.points)return e;let o=new Map(e);return o.set(t,{key:t,kind:n,points:a.slice(Math.max(0,a.length-720))}),o}function kn(e,t,n){let r=e;for(let e of ce(t,n))r=On(r,e.key,e.kind,e.point);return r}function An(e,t){let n=e;for(let e of t)for(let t of e.points)n=On(n,e.key,e.kind,t);return n}function jn(e){let t=null;for(let n of e.values()){let e=n.points.at(-1);e!==void 0&&(t===null||e.atMs>t)&&(t=e.atMs)}return t}var Mn=12e4;function Nn(e,t){return e===null?!1:t-e>Mn}function Pn(e){let t=e=>{let t=e.points.at(-1);return t===void 0?-1:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.key.localeCompare(n.key):r})}function Fn(e){for(let t of e.values()){let e=t.points.at(-1);if(e&&e.cpuMainPercent!==null)return!0}return!1}var In={key:`cpu`,dir:`desc`};function Ln(e){let t=e.points.at(-1);return t===void 0?null:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent}function Rn(e){return e.points.at(-1)?.memoryRssBytes??null}function zn(e,t,n){let r=n.trim().toLowerCase();return r===``?!0:e.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function Bn(e,t){return t===`memory`?Rn(e):Ln(e)}function Vn(e,t,n){let r=e.filter(e=>t.selectedKeys.size>0&&!t.selectedKeys.has(e.key)?!1:zn(n(e),e.key,t.search)),i=(e,t)=>e.key.localeCompare(t.key);return[...r].toSorted((e,r)=>{if(t.sort.key===`name`){let a=n(e).localeCompare(n(r)),o=t.sort.dir===`asc`?a:-a;return o===0?i(e,r):o}let a=Bn(e,t.sort.key),o=Bn(r,t.sort.key);if(a===null&&o===null)return i(e,r);if(a===null)return 1;if(o===null)return-1;let s=t.sort.dir===`desc`?o-a:a-o;return s===0?i(e,r):s})}n();function Hn(e,n=720){let r=H(`metrics.node-processes-snapshot`,t=>t.nodeId===e),[i,a]=c(new Map),[o,s]=c(void 0),l=t(null),{data:d,isPending:f}=ke({forNodeId:e,sinceMs:o,maxPoints:n});u(()=>{d!==void 0&&a(e=>{let t=An(e,d.series);return l.current=jn(t),t})},[d]);let p=r?.timestamp;u(()=>{r==null||p===void 0||(Nn(l.current,p)&&s(l.current??0),a(e=>{let t=kn(e,r.processes,p);return l.current=jn(t),t}))},[p]),u(()=>{a(new Map),s(void 0),l.current=null},[e]);let m=0;for(let e of i.values())m=Math.max(m,e.points.length);return{series:Pn(i),sampleCount:m,threadSplitAvailable:Fn(i),loadingRetained:f,durable:d?.durable??null,bucketMs:d?.bucketMs??null,cadenceMs:d?.cadenceMs??null,retainedSamples:d?.retainedSamples??null}}var Un=`__unclaimed__`;function Wn(e,t){return{kind:e,deviceId:t,cpu:0,cpuKnown:!0,rss:0,rssKnown:!0,count:0,roles:new Set}}function Gn(e,t){return{key:e,kind:t.kind,deviceId:t.deviceId,cpuSeconds:t.cpuKnown?Math.round(t.cpu*100)/100:null,rssBytes:t.rssKnown?t.rss:null,unitCount:t.count,roles:[...t.roles].sort()}}function Kn(e,t){let n=new Map,r=new Set;for(let t of e){t.pid!==void 0&&r.add(t.pid);let e=t.deviceId!==null&&t.attribution!==`unattributable`,i=e?`device:${t.deviceId}`:`shared:${t.role}`,a=n.get(i)??Wn(e?`camera`:`shared`,e?t.deviceId:null);a.count+=1,a.roles.add(t.role),t.cpuSeconds===void 0?a.cpuKnown=!1:a.cpu+=t.cpuSeconds,t.rssBytes===void 0?a.rssKnown=!1:a.rss+=t.rssBytes,n.set(i,a)}let i=[...n.entries()].map(([e,t])=>Gn(e,t));if(t===void 0)return i;let a=t.filter(e=>!r.has(e.pid));if(a.length===0)return i;let o=Wn(`unclaimed`,null);for(let e of a)o.count+=1,o.rss+=e.memoryRssBytes;return o.cpuKnown=!1,[...i,Gn(Un,o)]}var qn=[{family:`decode`,attribution:`measured`,unit:`one forked decode-worker child per decode SESSION`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:118`,`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:131`,`packages/addon-pipeline/src/pipeline-runner/index.ts:2765`,`packages/types/src/process/child-cost-registry.ts:188`]},{family:`transcode`,attribution:`measured`,unit:`one ffmpeg child per (camera, encode plan)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/egress-transcode-manager.ts:960`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:282`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:324`,`packages/types/src/ffmpeg/sharing-key.ts:139`]},{family:`recording`,attribution:`measured`,unit:`one passthrough ffmpeg per (camera, profile)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:33`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:217`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:279`,`packages/addon-pipeline/src/recorder/addon/recording-controller.ts:1710`]},{family:`detection`,attribution:`accounted`,unit:`a SHARED inference pool per (node, runtime, device) — no per-camera process`,perCamera:!1,wiredToday:!0,missingLink:"Nothing is missing for COUNTING — per-camera inference milliseconds, processed/shed frames and bytes-to-pool are already accumulated. What is missing is any basis for CPU seconds: `deviceId` reaches the pool as a diagnostic label and selects nothing, so cost can only ever be apportioned, never measured. Since 2026-08-27 the pool DECLARES this itself, contributing `deviceId: null` + `attribution: unattributable` rather than leaving an observer to infer it — the renunciation is data, and it is still refused by the chart gate.",evidence:[`packages/addon-pipeline/src/detection-pipeline/provider.ts:540`,`packages/addon-pipeline/src/detection-pipeline/engine/shared-inference-pool.ts:413`,`packages/types/src/interfaces/inference-engine.ts:24`,`packages/addon-pipeline/src/pipeline-runner/timing-sampler.ts:63`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:353`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:849`,`packages/addon-pipeline/src/pipeline-runner/frame-lazy-metrics.ts:100`]},{family:`streaming`,attribution:`measured`,unit:"one StreamBroker per `${deviceId}/${camStreamId}`, with an exact RTP ring byte counter",perCamera:!0,wiredToday:!1,missingLink:"The ffmpeg-backed ingest is now reported per camera, but that is the minority path. `rtpRingBytes` — the exact figure for the in-process case — is maintained on every push and drop and is still private and absent from `getStats()`. The three `EncodedRingBuffer`s track packets and duration and have no byte accumulator at all; the only byte figure they offer is `preRollBudgetBytes`, which is a BUDGET, not an occupancy.",evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2895`,`packages/addon-pipeline/src/stream-broker/rtsp/ffmpeg-push-reader.ts:189`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:494`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:498`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2505`,`packages/addon-pipeline/src/stream-broker/stream-broker/pre-roll.ts:269`]}];function Jn(e){return e.attribution===`measured`&&e.wiredToday}function Yn(){let e=new Set;for(let t of qn)Jn(t)&&e.add(t.family);return e}var Xn=Yn();function Zn(e){return!Xn.has(e.role)||e.deviceId===null?!1:e.attribution===`measured`}function Qn(e){return`${e.addonId}${e.role}${e.unit}${e.pid??`-`}`}function $n(){return{cpuSeconds:0,cpuKnown:!0,rssBytes:0,rssKnown:!0,unitCount:0,roles:new Set}}function er(e,t,n){if(t.cpuSeconds===void 0)return null;if(e===void 0)return t.startedAtMs===void 0||t.startedAtMs<n?null:t.cpuSeconds;if(e.cpuSeconds===void 0||e.startedAtMs===void 0||t.startedAtMs===void 0||e.startedAtMs!==t.startedAtMs)return null;let r=t.cpuSeconds-e.cpuSeconds;return r<0?null:r}function tr(e){return Math.round(e*10)/10}function nr(e,t){let n=t.atMs-e.atMs;if(n<=0)return[];let r=n/1e3,i=new Map;for(let t of e.entries)Zn(t)&&i.set(Qn(t),t);let a=new Map,o=new Set;for(let n of t.entries){if(!Zn(n)||n.deviceId===null)continue;let t=Qn(n);o.add(t);let r=a.get(n.deviceId)??$n();r.unitCount+=1,r.roles.add(n.role);let s=er(i.get(t),n,e.atMs);s===null?r.cpuKnown=!1:r.cpuSeconds+=s,n.rssBytes===void 0?r.rssKnown=!1:r.rssBytes+=n.rssBytes,a.set(n.deviceId,r)}for(let[e,t]of i){if(o.has(e)||t.deviceId===null)continue;let n=a.get(t.deviceId);n!==void 0&&(n.cpuKnown=!1)}return[...a.entries()].map(([e,n])=>({deviceId:e,point:{atMs:t.atMs,cpuPercent:n.cpuKnown?tr(n.cpuSeconds/r*100):null,rssBytes:n.rssKnown?n.rssBytes:null,unitCount:n.unitCount,roles:[...n.roles].toSorted()}}))}function rr(e,t){if(t.length===0)return e;let n=new Map(e);for(let e of t){let t=n.get(e.deviceId),r=t?.points.at(-1);if(r!==void 0&&e.point.atMs<=r.atMs)continue;let i=[...t?.points??[],e.point];n.set(e.deviceId,{deviceId:e.deviceId,points:i.slice(Math.max(0,i.length-720))})}return n}function ir(e){let t=e=>{for(let t=e.points.length-1;t>=0;t--){let n=e.points[t]?.cpuPercent;if(n!=null)return n}return-1};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.deviceId-n.deviceId:r})}function ar(e){let t=e.indexOf(`@`);return t===-1?{addonId:e,nodeId:null}:{addonId:e.slice(0,t),nodeId:e.slice(t+1)}}function or(e,t){let n=ar(e);return n.nodeId===null?t.isHub:n.nodeId===t.nodeId}function sr(e,t){return e.filter(e=>or(e.addonId,t))}n();function cr(e){let n=H(`metrics.node-processes-snapshot`,t=>t.nodeId===e.nodeId),r=ze(void 0,{staleTime:1/0,refetchOnWindowFocus:!1}),[i,a]=c(new Map),o=t(null),s=t(r.refetch);s.current=r.refetch;let l=n?.timestamp;u(()=>{l!==void 0&&s.current()},[l]),u(()=>{a(new Map),o.current=null},[e.nodeId,e.isHub]);let d=r.data,f=r.dataUpdatedAt;u(()=>{if(d===void 0||f===0)return;let t={atMs:f,entries:sr(d,e)},n=o.current;if(o.current=t,n===null)return;let r=nr(n,t);r.length!==0&&a(e=>rr(e,r))},[d,f,e.nodeId,e.isHub]);let p=d===void 0?[]:sr(d,e),m=n?.processes,h=Kn(p,m);return{series:ir(i),unclaimed:h.find(e=>e.kind===`unclaimed`)??null,loading:r.isPending,error:r.error===null?null:r.error.message}}function lr(e){let t=new Map;for(let n of e){let e=n.name?.trim();e===void 0||e===``||t.set(n.id,e)}return t}var ur=25,dr=64*1024*1024,fr=1e4;function pr({scope:e,cadenceMs:t}){let{t:n}=U(),i=cr(e),{data:a=[]}=Ue({isCamera:!0,projection:`slim`}),o=lr(a),s=an(t??fr);return r(`section`,{className:`space-y-3`,children:[i.error!==null&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-[11px] text-destructive`,children:[l(m,{className:`h-3 w-3 mt-0.5 shrink-0`}),l(`span`,{children:n(`cameraLoad.readFailed`,`Could not read the load contributions: {{error}}. This is a failed read, NOT an idle cluster.`,{error:i.error})})]}),l(hr,{unclaimed:i.unclaimed}),i.series.length===0&&i.error===null&&l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:i.loading?n(`cameraLoad.loading`,`Reading what the addons report…`):n(`cameraLoad.waitingWindow`,`No per-camera window yet.`)}),l(`div`,{className:`space-y-3`,children:i.series.map(e=>r(`div`,{className:`rounded-lg border border-border p-3`,children:[r(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[l(mr,{deviceId:e.deviceId,name:o.get(e.deviceId)}),l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`cameraLoad.unitCount`,`{{count}} unit(s): {{roles}}`,{count:e.points.at(-1)?.unitCount??0,roles:(e.points.at(-1)?.roles??[]).join(`, `)})})]}),r(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[l(hn,{title:n(`cameraLoad.cpuTitle`,`CPU % of one core (delta)`),points:e.points.map(e=>({atMs:e.atMs,value:e.cpuPercent})),formatValue:e=>`${e.toFixed(1)}%`,axisFloor:ur,gapMs:s,emptyMessage:n(`cameraLoad.cpuUnavailable`,`No measurable window yet.`)}),l(hn,{title:n(`cameraLoad.memoryTitle`,`Memory RSS`),points:e.points.map(e=>({atMs:e.atMs,value:e.rssBytes})),formatValue:W,axisFloor:dr,axisScale:`bytes`,gapMs:s,emptyMessage:n(`cameraLoad.memoryUnavailable`,`No memory reported.`)})]})]},e.deviceId))})]})}function mr({deviceId:e,name:t}){let{t:n}=U();return t===void 0?l(`span`,{className:`text-xs font-medium text-foreground`,children:n(`cameraLoad.deviceLabel`,`Camera {{deviceId}}`,{deviceId:e})}):r(`span`,{className:`flex items-baseline gap-1.5 min-w-0`,children:[l(`span`,{className:`text-xs font-medium text-foreground truncate`,children:t}),r(`span`,{className:`shrink-0 text-[10px] font-mono text-foreground-subtle`,children:[`#`,e]})]})}function hr({unclaimed:e}){let{t}=U();return e===null||e.unitCount===0?null:l(`div`,{className:`flex items-center gap-2`,children:l(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-warning/10 text-warning font-medium tabular-nums`,children:t(`cameraLoad.unclaimedBadge`,`{{count}} unclaimed · {{rss}}`,{count:e.unitCount,rss:e.rssBytes===null?`—`:W(e.rssBytes)})})})}n();var gr=256*1024*1024,_r=1e4;function vr({nodeId:e,isHub:t}){let{t:n}=U(),{series:i,sampleCount:o,threadSplitAvailable:s,loadingRetained:u,bucketMs:d,cadenceMs:f}=Hn(e),[p,h]=c(``),[g,_]=c(new Set),[v,y]=c(In),b=e=>e.key===`__root__`?n(`clusterLoad.bucketRoot`,`Node supervisor`):e.key===`__unattributed__`?n(`clusterLoad.bucketUnattributed`,`Unattributed processes`):e.key,x=an(d??f??_r),S=a(()=>Vn(i,{search:p,selectedKeys:g,sort:v},b),[i,p,g,v]),C=e=>{_(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return r(`div`,{className:`space-y-4`,children:[l(yr,{bucketMs:d,cadenceMs:f}),!s&&o>0&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/5 px-3 py-2 text-[11px] text-warning`,children:[l(m,{className:`h-3 w-3 mt-0.5 shrink-0`}),l(`span`,{children:n(`clusterLoad.noThreadSplit`,`No thread-level CPU split on this node — /proc/<pid>/task is Linux-only, and the first sample after a restart has no window to measure. CPU below falls back to the ps lifetime AVERAGE, which is not a rate.`)})]}),o===0&&l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:u?n(`clusterLoad.loadingRetained`,`Reading the retained series from this node…`):n(`clusterLoad.waitingFirstSample`,`No retained samples for this node — waiting for the next snapshot (up to 20s). The chart needs two to draw a rate.`)}),i.length>0&&r(`div`,{className:`space-y-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`label`,{className:`relative flex-1 min-w-[160px]`,children:[l(k,{className:`pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-foreground-subtle`}),l(`input`,{type:`search`,value:p,onChange:e=>h(e.target.value),placeholder:n(`clusterLoad.searchPlaceholder`,`Find a runner…`),"aria-label":n(`clusterLoad.searchLabel`,`Find a runner`),className:`w-full rounded border border-border bg-background py-1 pl-7 pr-2 text-[11px] text-foreground placeholder:text-foreground-subtle`})]}),l(br,{sort:v,onChange:y})]}),r(`div`,{className:`flex flex-wrap items-center gap-1`,children:[i.map(e=>{let t=g.has(e.key);return l(`button`,{type:`button`,"aria-pressed":t,onClick:()=>C(e.key),className:`rounded-full border px-2 py-0.5 text-[10px] transition-colors ${t?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:b(e)},e.key)}),g.size>0&&r(`button`,{type:`button`,onClick:()=>_(new Set),className:`inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground`,children:[l(A,{className:`h-2.5 w-2.5`}),n(`clusterLoad.clearFilter`,`All runners`)]})]})]}),i.length>0&&S.length===0&&l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:n(`clusterLoad.noMatches`,`No runner matches this search on {{count}} present. The node is reporting — the filter is hiding them.`,{count:i.length})}),l(`div`,{className:`space-y-3`,children:S.map(e=>r(`div`,{className:`rounded-lg border border-border p-3`,children:[r(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[l(`span`,{className:`text-xs font-medium text-foreground`,children:b(e)}),l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`clusterLoad.processCount`,`{{count}} process(es)`,{count:e.points.at(-1)?.processCount??0})})]}),r(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[l(mn,{title:s?n(`clusterLoad.cpuTitle`,`CPU % of one core`):n(`clusterLoad.cpuTitleLifetime`,`CPU % (ps lifetime average)`),mainLabel:n(`clusterLoad.seriesMain`,`Main threads`),gcLabel:n(`clusterLoad.seriesGc`,`GC / V8 helpers`),points:e.points.map(e=>({atMs:e.atMs,main:e.cpuMainPercent,gc:e.cpuGcPercent})),formatValue:e=>`${e.toFixed(0)}%`,gapMs:x,emptyMessage:n(`clusterLoad.cpuUnavailable`,`No thread split on this node. Lifetime average: {{avg}}%`,{avg:(e.points.at(-1)?.cpuLifetimePercent??0).toFixed(1)})}),l(hn,{title:n(`clusterLoad.memoryTitle`,`Memory RSS`),points:e.points.map(e=>({atMs:e.atMs,value:e.memoryRssBytes})),formatValue:W,axisFloor:gr,axisScale:`bytes`,gapMs:x,emptyMessage:n(`clusterLoad.memoryUnavailable`,`No memory samples yet.`)})]})]},e.key))}),l(pr,{scope:{nodeId:e,isHub:t},cadenceMs:f})]})}function yr({bucketMs:e,cadenceMs:t}){let{t:n}=U();return e===null?null:l(`p`,{className:`text-[10px] text-foreground-subtle`,children:t!==null&&e>t?n(`clusterLoad.captionBucket`,`1 point = {{bucket}}s (bucket MAXIMUM, not a mean)`,{bucket:Math.round(e/1e3)}):n(`clusterLoad.captionRaw`,`1 point = 1 snapshot`)})}function br({sort:e,onChange:t}){let{t:n}=U(),i=[{key:`cpu`,label:n(`clusterLoad.sortCpu`,`CPU`)},{key:`memory`,label:n(`clusterLoad.sortMemory`,`Memory`)},{key:`name`,label:n(`clusterLoad.sortName`,`Name`)}];return r(`div`,{className:`flex items-center gap-1`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`clusterLoad.sortBy`,`Sort by`)}),i.map(n=>{let i=e.key===n.key;return r(`button`,{type:`button`,"aria-pressed":i,onClick:()=>t(i?{key:n.key,dir:e.dir===`desc`?`asc`:`desc`}:{key:n.key,dir:n.key===`name`?`asc`:`desc`}),className:`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${i?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:[n.label,i&&(e.dir===`desc`?` ↓`:` ↑`)]},n.key)})]})}var xr=`No per-node settings on this node. Every other setting these addons expose is one value for the whole cluster — edit those in System → Settings, not here.`;function Sr({nodeId:e,addonIds:t}){return t.length===0?l(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:`No addons on this node`}):l(`div`,{className:`w-full py-2`,children:l(Ye,{nodeId:e,addonIds:t,level:`global`,fieldScope:`perNode`,emptyMessage:xr,selfTabbed:!0})})}n();function Cr({nodeId:e,addons:t}){let n=s(),{data:r,isLoading:i}=ve({nodeId:e}),o=a(()=>{let e=new Map;for(let n of t)for(let t of n.capabilities){let r=e.get(t)??[];r.push(n.id),e.set(t,r)}return[...e.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({capName:e,providers:t}))},[t]),c=We({onSuccess:()=>{n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCapabilityBindings`]]})}});return o.length===0?l(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:`No capabilities on this node`}):l(L,{columns:[{key:`capName`,header:`Capability`,width:`w-1/2`,sortValue:e=>e.capName,render:e=>l(`span`,{className:`font-medium`,children:e.capName})},{key:`provider`,header:`Bound provider`,render:t=>{let n=r?.[t.capName]??t.providers[0]??``,a=t.providers.length===1;return l(`select`,{value:n,onChange:n=>c.mutate({nodeId:e,capName:t.capName,addonId:n.target.value}),disabled:a||c.isPending||i,className:`w-full rounded-md border border-border bg-surface px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-60`,title:a?`Only one provider installed — choice becomes available once a second addon registers this capability`:void 0,children:t.providers.map(e=>l(`option`,{value:e,children:e},e))})}}],rows:o,rowKey:e=>e.capName,minWidthPx:520,mobileMode:`cards`,maxBodyHeight:Ee})}n();function wr(e){if(e==null)return`—`;let t=Math.floor(e/1e3),n=Math.floor(t/86400),r=Math.floor(t%86400/3600),i=Math.floor(t%3600/60);return n>0?`${n}d ${r}h ${i}m`:r>0?`${r}h ${i}m`:`${i}m`}function Tr(e){let[t,n]=c(!1),[i,a]=c(e.name),o=s(),u=Ne({onSuccess:()=>{o.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}}),d=(e.localIps??[]).filter(e=>!e.includes(`:`)),f=(e.localIps??[]).filter(e=>e.includes(`:`)),p=async()=>{if(!i.trim()||i===e.name){n(!1);return}try{await u.mutateAsync({nodeId:e.nodeId,name:i.trim()}),n(!1)}catch(e){console.error(`Rename failed:`,e)}},m=[[`Node ID`,l(`span`,{className:`font-mono text-xs`,children:e.nodeId})],[`Display Name`,t?r(`div`,{className:`flex items-center gap-1.5`,children:[l(`input`,{type:`text`,className:`flex-1 px-2 py-0.5 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&p(),e.key===`Escape`&&n(!1)},disabled:u.isPending,autoFocus:!0}),l(`button`,{onClick:()=>void p(),disabled:u.isPending,className:`p-0.5 text-success hover:bg-success/10 rounded`,title:`Save`,children:l(E,{className:`h-3.5 w-3.5`})}),l(`button`,{onClick:()=>n(!1),className:`p-0.5 text-muted-foreground hover:bg-muted rounded`,title:`Cancel`,children:l(A,{className:`h-3.5 w-3.5`})})]}):r(`div`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-xs`,children:e.name}),!e.isHub&&l(`button`,{onClick:()=>{a(e.name),n(!0)},className:`p-0.5 text-muted-foreground hover:text-primary rounded`,title:`Rename`,children:l(_,{className:`h-3 w-3`})})]})],[`Hostname`,l(`span`,{className:`text-xs`,children:e.hostname})],[`Role`,e.isHub?l(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium`,children:`Hub`}):l(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-medium`,children:`Agent`})],[`Root Package`,e.rootPackage?r(`span`,{className:`font-mono text-xs`,children:[e.rootPackage.name,`@`,e.rootPackage.version]}):l(`span`,{className:`text-xs text-muted-foreground`,children:`—`})],[`Platform`,r(`span`,{className:`text-xs`,children:[e.platform,` / `,e.arch]})],[`CPU`,r(`span`,{className:`text-xs`,children:[e.cpuModel??`—`,` (`,e.cpuCores,` cores)`]})],[`Memory`,l(`span`,{className:`text-xs`,children:e.memoryMB>0?`${(e.memoryMB/1024).toFixed(1)} GB`:`—`})],[`Uptime`,l(`span`,{className:`text-xs`,children:wr(e.uptime)})],[`Engines`,e.engines.length>0?l(`div`,{className:`flex flex-wrap gap-1`,children:e.engines.map(e=>l(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e))}):l(`span`,{className:`text-xs text-muted-foreground`,children:`—`})]];return d.length>0&&m.push([`IPv4`,l(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map((e,t)=>l(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted`,children:e},`${e}-${t}`))})]),f.length>0&&m.push([`IPv6`,l(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map((e,t)=>l(`span`,{className:`font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[280px]`,title:e,children:e},`${e}-${t}`))})]),l(`div`,{className:`py-2`,children:l(`table`,{className:`w-full text-sm`,children:l(`tbody`,{children:m.map(([e,t],n)=>r(`tr`,{className:n%2==0?`bg-muted/20`:``,children:[l(`td`,{className:`py-1.5 px-2 text-xs font-medium text-muted-foreground w-28 align-top whitespace-nowrap`,children:e}),l(`td`,{className:`py-1.5 px-2`,children:t})]},e))})})})}n();function Er({nodeId:e,value:t,detectedHosts:n,status:i,errorMessage:a,onCommit:o}){let[s,d]=c(t??``);u(()=>{d(t??``)},[t]);let f=n[0],p=f===void 0?`auto-detect`:`auto: ${f}`,m=i===`pending`,h=s.trim(),g=h!==(t??``),_=g&&!m,v=()=>{_&&o(e,h.length>0?h:null)};return r(`div`,{className:`flex items-center gap-1.5`,children:[l(z,{"aria-label":`Reachable host for ${e}`,type:`text`,inputMode:`url`,autoComplete:`off`,spellCheck:!1,placeholder:p,value:s,disabled:m,onChange:e=>d(e.target.value),onBlur:v,onKeyDown:e=>{e.key===`Enter`&&v(),e.key===`Escape`&&d(t??``)},className:`w-36`}),r(F,{variant:`outline`,size:`sm`,onClick:v,disabled:!_,"aria-label":`Save reachable host for ${e}`,title:`Save reachable host`,children:[m?l(T,{className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):l(E,{className:`h-3 w-3`,"aria-hidden":`true`}),`Save`]}),!g&&!m&&i===`success`&&l(E,{className:`h-3.5 w-3.5 shrink-0 text-success`,"aria-label":`Saved`,role:`img`}),i===`error`&&l(`span`,{title:a??`Failed to save reachable host`,children:l(ee,{className:`h-3.5 w-3.5 shrink-0 text-danger`,"aria-label":a??`Failed to save reachable host`,role:`img`})})]})}n();function Dr(e){let t=oe.safeParse(Xe(e,`color`));return t.success?t.data:null}function Or(e,t){return t.variables?.agentNodeId===e?t.isPending?`pending`:t.isError?`error`:t.isSuccess?`success`:`idle`:`idle`}function kr({nodeId:e,detectedHosts:t}){let{t:n}=U(),i=s(),o=De(void 0),c=je({onSuccess:()=>Ze(i)}),u=je({onSuccess:()=>Ze(i)}),d=a(()=>o.data?.find(t=>t.nodeId===e)?.settings,[o.data,e]),f=Dr(d)??(o.isLoading?null:ae(e)),p=Qe(d,`reachableHost`),m=Or(e,c),h=m===`error`?$e(c.error):null,g=t.filter(e=>!e.includes(`:`)),_=t=>{t!==f&&u.mutate({agentNodeId:e,color:t})};return r(`div`,{className:`rounded-lg border border-border bg-surface/40 divide-y divide-border px-3`,children:[l(Ae,{label:n(`nodes.general.nodeColour`,`Node colour`),children:l(`div`,{role:`group`,"aria-label":n(`nodes.general.nodeColourGroup`,`Node colour`),className:`flex flex-wrap gap-2`,children:se.map(e=>{let t=f===e;return l(F,{type:`button`,role:`radio`,"aria-checked":t,"aria-label":e,variant:`outline`,size:`sm`,disabled:o.isLoading||u.isPending,title:e,onClick:()=>_(e),className:`h-6 w-6 min-w-6 shrink-0 rounded-full border-0 p-0 ${Me(e)} ${t?`ring-2 ring-primary ring-offset-2 ring-offset-background`:`opacity-80 hover:opacity-100`}`,children:l(`span`,{className:`sr-only`,children:e})},e)})})}),l(Ae,{label:n(`nodes.general.reachableHost`,`Reachable host`),children:l(Er,{nodeId:e,value:p,detectedHosts:g,status:m,errorMessage:h,onCommit:(e,t)=>{c.mutate({agentNodeId:e,reachableHost:t})}})})]})}n();var Ar=[[`serverManagement`,`getServerPackageStatus`]];function jr({label:e,tone:t}){return l(`span`,{className:`inline-flex items-center rounded px-2 py-0.5 text-[11px] font-medium ${{neutral:`bg-surface-muted text-foreground-subtle`,ok:`bg-success/15 text-success`,info:`bg-info/15 text-info`,warn:`bg-warning/15 text-warning`,error:`bg-danger/15 text-danger`}[t]}`,children:e})}function $({label:e,value:t}){return r(`div`,{className:`flex items-center justify-between gap-4 text-sm`,children:[l(`span`,{className:`text-foreground-subtle`,children:e}),l(`span`,{className:`font-mono text-foreground`,children:t??`—`})]})}function Mr({runningVersion:e,latestVersion:t,seedVersion:n,nodeRuntimeVersion:i,labelRunning:a,labelLatest:o,labelSeed:s,labelRuntime:c}){return l(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-sm`,children:[{key:`running`,label:a,value:e},{key:`latest`,label:o,value:t},{key:`seed`,label:s,value:n},{key:`runtime`,label:c,value:i}].map(({key:e,label:t,value:n})=>r(`span`,{className:`inline-flex items-baseline gap-1`,children:[l(`span`,{className:`text-foreground-subtle`,children:t}),l(`span`,{className:`font-mono text-foreground`,children:n??`—`})]},e))})}var Nr={ok:`border-success/40 bg-success/10 text-success`,warn:`border-warning/40 bg-warning/10 text-warning`,error:`border-danger/40 bg-danger/10 text-danger`};function Pr(e){return e.outcome===`failed`?`error`:(e.outcome,e.accepted?`ok`:`warn`)}function Fr(e,t){let n=t instanceof Error?t.message:String(t);return`${e(`serverManagement.outcomeDropped`,`The connection dropped and the result could not be confirmed. The node may be restarting — re-check the version above.`)} — ${n}`}function Ir({node:t}){let{t:n}=U(),i=s(),a=B(),[o,u]=c(!1),[d,f]=c(null),p=t.isHub?void 0:{nodeId:t.id},m=he(p,{refetchInterval:1e4,enabled:t.isOnline,retry:1}),h=m.data??null,g=e(()=>{i.invalidateQueries({queryKey:Ar})},[i]),_=pe({onSettled:g}),v=be({onSettled:g}),y=ge({onSettled:g}),b=e(async()=>{if(h?.latestVersion==null){f({tone:`warn`,text:n(`serverManagement.outcomeNoTarget`,`No target version is known for this node — run "Check for update" first.`)});return}if(await a({title:n(`serverManagement.confirmUpdateTitle`,`Update node root package`),message:n(`serverManagement.confirmUpdateBody`,`Install {{pkg}}@{{version}} on "{{node}}" and restart to apply.`,{pkg:h.packageName,version:h.latestVersion,node:t.name}),confirmLabel:n(`serverManagement.confirmUpdateAction`,`Update & restart`)})){f(null);try{let e=await v.mutateAsync({version:h.latestVersion,...p});f({tone:Pr(e),text:e.message}),e.restarting&&u(!0)}catch(e){f({tone:`warn`,text:Fr(n,e)})}}},[v,a,t.name,p,h,n]),S=e(async()=>{if(await a({title:n(`serverManagement.confirmRestartTitle`,`Restart node`),message:n(`serverManagement.confirmRestartBody`,`Restart "{{node}}"? In-flight requests to this node are dropped.`,{node:t.name}),confirmLabel:n(`serverManagement.confirmRestartAction`,`Restart`),variant:`warning`})){f(null);try{let e=await y.mutateAsync(p);f({tone:Pr(e),text:e.message}),e.restarting&&u(!0)}catch(e){f({tone:`warn`,text:Fr(n,e)})}}},[a,t.name,y,p,n]),w=()=>{switch(h?.bootMode){case`data-root`:return{label:n(`serverManagement.bootDataRoot`,`runtime-updatable`),tone:`ok`};case`workspace`:return{label:n(`serverManagement.bootWorkspace`,`dev workspace`),tone:`info`};default:return{label:n(`serverManagement.bootBaked`,`baked image seed`),tone:`neutral`}}},E=()=>{if(h==null)return null;switch(h.updateState){case`checking`:return{label:n(`serverManagement.stateChecking`,`checking…`),tone:`info`};case`staging`:return{label:n(`serverManagement.stateStaging`,`updating…`),tone:`info`};case`pending-restart`:return{label:n(`serverManagement.statePending`,`restart pending`),tone:`warn`};default:return h.restartRequired===!0?{label:n(`serverManagement.stateRestartRequired`,`restart required`),tone:`warn`}:h.updateAvailable?{label:n(`serverManagement.stateUpdateAvailable`,`update available`),tone:`warn`}:{label:n(`serverManagement.stateUpToDate`,`up to date`),tone:`ok`}}},D=h?.bootMode===`workspace`,O=t.isOnline&&h!=null&&!D&&h.updateAvailable&&h.updateState===`idle`&&!v.isPending,k=t.isOnline&&h!=null&&h.updateState===`idle`&&!y.isPending,A=t.isOnline?E():null;return r(`div`,{className:`space-y-4 py-2`,children:[r(`div`,{className:`flex items-center justify-between gap-3`,children:[r(`div`,{className:`flex items-center gap-2 min-w-0`,children:[l(`span`,{className:`font-mono text-xs text-foreground-subtle truncate`,children:h?.packageName??t.rootPackage?.name??`@camstack/server`}),t.isOnline&&h!=null&&l(jr,{...w()})]}),A!=null&&l(jr,{...A})]}),!t.isOnline&&l($,{label:n(`serverManagement.lastReportedVersion`,`Last reported version`),value:t.rootPackage?.version??null}),t.isOnline&&m.isLoading&&r(`div`,{className:`flex items-center gap-2 text-sm text-foreground-subtle`,children:[l(T,{className:`h-4 w-4 animate-spin`}),n(`common.loading`,`Loading…`)]}),t.isOnline&&m.isError&&r(`div`,{className:`space-y-1.5`,children:[l(`p`,{className:`text-sm text-danger`,children:n(`serverManagement.loadError`,`Could not load the node root-package status.`)}),t.rootPackage!=null&&l($,{label:n(`serverManagement.lastReportedVersion`,`Last reported version`),value:t.rootPackage.version})]}),t.isOnline&&h!=null&&r(`div`,{className:`space-y-1.5`,children:[l(Mr,{runningVersion:h.runningVersion,latestVersion:h.latestVersion,seedVersion:h.seedVersion,nodeRuntimeVersion:h.nodeRuntimeVersion,labelRunning:n(`serverManagement.runningVersionShort`,`Running`),labelLatest:n(`serverManagement.latestVersionShort`,`Latest`),labelSeed:n(`serverManagement.imageSeedShort`,`Seed`),labelRuntime:n(`serverManagement.nodeRuntimeVersionShort`,`Node.js`)}),h.pendingVersion!=null&&l($,{label:n(`serverManagement.pendingVersion`,`Staged (applies on restart)`),value:h.pendingVersion}),h.installedVersion!=null&&h.installedVersion!==h.runningVersion&&l($,{label:n(`serverManagement.installedVersion`,`Installed on disk (runs after restart)`),value:h.installedVersion})]}),t.isOnline&&h?.imageContract?.state===`behind-series`&&r(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs leading-relaxed text-danger`,children:[l(`p`,{className:`mb-0.5 font-semibold`,children:n(`serverManagement.imageContractDiverged`,`Container image diverges from the deployment contract`)}),l(`p`,{children:h.imageContract.message})]}),t.isOnline&&D&&l(`p`,{className:`text-xs text-foreground-subtle`,children:n(`serverManagement.workspaceNote`,`Development workspace detected — runtime updates are disabled (the dev loop resolves code from the workspace).`)}),d!=null&&l(`p`,{role:`status`,className:`rounded border px-2 py-1.5 text-xs leading-relaxed ${Nr[d.tone]}`,children:d.text}),o&&r(`div`,{className:`flex items-center gap-2 text-sm text-warning`,children:[l(T,{className:`h-4 w-4 animate-spin`}),n(`serverManagement.nodeRestarting`,`The node is restarting to apply the change…`)]}),t.isOnline&&r(`div`,{className:`flex flex-wrap items-center gap-2 pt-1`,children:[r(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:_.isPending||h?.updateState===`staging`,onClick:()=>_.mutate(p),children:[_.isPending?l(T,{className:`h-3.5 w-3.5 animate-spin`}):l(P,{className:`h-3.5 w-3.5`}),n(`serverManagement.checkForUpdate`,`Check for update`)]}),O&&r(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50`,onClick:()=>void b(),children:[v.isPending?l(T,{className:`h-3.5 w-3.5 animate-spin`}):l(x,{className:`h-3.5 w-3.5`}),n(`serverManagement.updateTo`,`Update to {{version}}`,{version:h?.latestVersion??``})]}),r(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:!k,onClick:()=>void S(),children:[y.isPending?l(T,{className:`h-3.5 w-3.5 animate-spin`}):l(C,{className:`h-3.5 w-3.5`}),n(`serverManagement.restart`,`Restart`)]})]}),t.isOnline&&h?.lastCheckedAtMs!=null&&r(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(re,{className:`h-3 w-3`}),n(`serverManagement.lastChecked`,`Last checked: {{when}}`,{when:new Date(h.lastCheckedAtMs).toLocaleString()})]})]})}n();function Lr(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`reachableHost`);return typeof t==`string`&&t.length>0?t:null}function Rr({node:t}){let n=N(),i=s(),[u,d]=c(`info`),[m,h]=c(!1),[g,_]=c(null),v=t.processes??[],b=t.addons.map(e=>e.id),x=De(void 0),S=a(()=>{let e=x.data?.find(e=>e.nodeId===t.id);return Lr(e?.settings)},[x.data,t.id]),[C,w]=c(!1),[T,E]=c(null),[D,O]=c(null),k=e(async()=>{if(C||t.isHub)return;let e=Mt(t.localIps??[],S);if(e===null){E(`No LAN IPv4 on this node — open its :4444 URL by hand.`),O(null);return}let r=Ft();w(!0),E(null),O(null);try{let i=Dt(await n.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:t.id,dashboardBaseUrl:Nt(e)}})),a=i===null?null:i.dashboardUrl??Pt(e,i.ticket);if(a===null){r?.close(),E(`Hub did not return an unlock ticket.`);return}It(r,a)||(O(a),E(`Browser blocked the new tab — click the link below (or allow popups for this site).`))}catch(e){r?.close(),E(e instanceof Error?e.message:String(e))}finally{w(!1)}},[t.id,t.isHub,t.localIps,C,S,n.trpcClient]),A=async()=>{if(!m){h(!0),_(null);try{await n.trpcClient.pipelineOrchestrator.removeAgentSettings.mutate({agentNodeId:t.id}).catch(()=>void 0);let e=await n.trpcClient.clusterNodes.forgetNode.mutate({nodeId:t.id});_({tone:e.stillListed?`warn`:`ok`,text:e.message}),e.stillListed||i.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}catch(e){_({tone:`warn`,text:`Forget failed: ${e instanceof Error?e.message:String(e)}`})}finally{h(!1)}}};return t.isOnline?r(`div`,{className:`border border-border rounded-xl`,children:[r(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30 border-b border-border rounded-t-xl`,children:[r(`div`,{className:`flex min-w-0 flex-1 basis-full items-center gap-x-2 gap-y-1 sm:basis-auto sm:flex-initial`,children:[l(`div`,{className:`w-2.5 h-2.5 rounded-full bg-success shrink-0`}),l(`span`,{className:`text-sm font-semibold shrink-0`,children:t.name}),r(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[t.cpuModel??t.platform,` ·`,` `,t.memoryMB>0?`${Math.round(t.memoryMB/1024)}GB`:``,` · `,t.arch]})]}),t.engines.map(e=>l(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium shrink-0`,children:e},e)),r(`div`,{className:`flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-1 text-xs text-muted-foreground w-full sm:ml-auto sm:w-auto`,children:[!t.isHub&&r(`button`,{type:`button`,onClick:()=>void k(),disabled:C,title:`Open this agent's status dashboard (unlocks with a short-lived hub ticket)`,className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-xs text-foreground hover:bg-surface-hover disabled:opacity-50`,children:[l(y,{className:`h-3 w-3`}),C?`Opening…`:`Open dashboard`]}),r(`span`,{className:`flex items-center gap-1`,children:[l(p,{className:`h-3 w-3`}),` `,t.cpuPercent,`%`]}),r(`span`,{className:`flex items-center gap-1`,children:[l(ie,{className:`h-3 w-3`}),` `,t.memoryPercent,`%`]})]})]}),(T!==null||D!==null)&&r(`p`,{role:`status`,className:`px-4 pt-2 text-xs text-warning`,children:[T,D!==null&&r(o,{children:[` `,l(`a`,{href:D,target:`_blank`,rel:`noreferrer`,className:`underline text-foreground`,children:`Open dashboard`})]})]}),l(`div`,{className:`sticky top-0 z-20 flex border-b border-border px-4 bg-background overflow-x-auto`,children:[`info`,`forks`,`processes`,`load`,`settings`,`capabilities`].map(e=>l(`button`,{onClick:()=>d(e),className:`shrink-0 whitespace-nowrap px-3 py-2 text-xs font-medium border-b-2 transition-colors ${u===e?`border-primary text-primary`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:e===`info`?`General`:e===`forks`?`Forks (${v.length})`:e===`processes`?`Processes`:e===`load`?`Load`:e===`settings`?`Settings`:`Capabilities`},e))}),r(`div`,{className:`px-4 py-2`,children:[u===`info`&&r(`div`,{className:`space-y-3`,children:[l(Tr,{nodeId:t.id,name:t.name,hostname:t.hostname,platform:t.platform,arch:t.arch,cpuModel:t.cpuModel,cpuCores:t.cpuCores,memoryMB:t.memoryMB,engines:t.engines,isHub:t.isHub,uptime:t.uptime,localIps:t.localIps,rootPackage:t.rootPackage}),l(kr,{nodeId:t.id,detectedHosts:t.localIps??[]}),l(`div`,{className:`border-t border-border pt-1`,children:l(Ir,{node:{id:t.id,name:t.name,isHub:t.isHub,isOnline:t.isOnline,rootPackage:t.rootPackage??null}})})]}),u===`forks`&&l(Vt,{nodeId:t.id,processes:v}),u===`processes`&&l(Gt,{nodeId:t.id}),u===`load`&&l(vr,{nodeId:t.id,isHub:t.isHub}),u===`settings`&&l(Sr,{nodeId:t.id,addonIds:b}),u===`capabilities`&&l(Cr,{nodeId:t.id,addons:t.addons})]})]}):r(`div`,{className:`border border-border rounded-xl overflow-hidden opacity-60`,children:[r(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30`,children:[l(`div`,{className:`w-2.5 h-2.5 rounded-full bg-destructive shrink-0`}),l(`span`,{className:`text-sm font-semibold shrink-0`,children:t.name}),r(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[t.cpuModel??t.platform,` ·`,` `,t.memoryMB>0?`${Math.round(t.memoryMB/1024)}GB`:``,` · `,t.arch]}),t.engines.map(e=>l(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e)),t.rootPackage&&r(`span`,{className:`text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:[t.rootPackage.name,`@`,t.rootPackage.version]}),l(`span`,{className:`ml-auto text-xs px-2 py-0.5 rounded-full bg-destructive/10 text-destructive`,children:`offline`})]}),r(`div`,{className:`flex items-center justify-between gap-3 px-4 py-3`,children:[r(`span`,{className:`text-xs text-muted-foreground`,children:[t.lastSeen?`Last seen ${new Date(t.lastSeen).toLocaleString()} — `:``,t.addons.length,` addon`,t.addons.length===1?``:`s`,` assigned; will resume when node reconnects`]}),r(`button`,{type:`button`,onClick:()=>void A(),disabled:m,title:`Forget this node — removes its saved history and pipeline assignments`,className:`flex items-center gap-1 text-xs px-2 py-1 rounded-md border border-border text-muted-foreground hover:text-destructive hover:border-destructive/50 disabled:opacity-50 transition-colors`,children:[l(f,{className:`h-3 w-3`}),m?`Forgetting…`:`Forget node`]})]}),g!=null&&l(`p`,{role:`status`,className:`px-4 pb-3 text-xs leading-relaxed ${g.tone===`ok`?`text-success`:`text-warning`}`,children:g.text})]})}var zr=3,Br=7e3;function Vr(e){return[...e].sort((e,t)=>e.isHub===t.isHub?0:e.isHub?1:-1)}function Hr(e){return e.isHub?{}:{nodeId:e.id}}function Ur(e){return e.updateState===`staging`||e.updateState===`pending-restart`||e.pendingVersion!==null?!0:!e.updateAvailable}async function Wr(e,t){let n=Hr(e),r=`no answer`;for(let i=1;i<=zr;i+=1)try{let r=await t.readStatus(n);return Ur(r)?{nodeId:e.id,nodeName:e.name,outcome:`applied`,detail:`Connection dropped, and the node confirms the update landed (state ${r.updateState}, running ${r.runningVersion??`unknown`}).`}:{nodeId:e.id,nodeName:e.name,outcome:`failed`,detail:`Connection dropped and the node came back unchanged (still ${r.runningVersion??`unknown`}, update still available). Nothing was staged.`}}catch(e){r=e instanceof Error?e.message:String(e),i<zr&&await t.wait(Br)}return{nodeId:e.id,nodeName:e.name,outcome:`unconfirmed`,detail:`Connection dropped and the node could not be confirmed after ${zr} attempts (${r}). It may be restarting — re-check this node.`}}function Gr(e){return e.accepted?`applied`:e.outcome===`failed`?`failed`:`refused`}async function Kr(e,t){let n=[];for(let r of Vr(e))try{let e=await t.apply(Hr(r));n.push({nodeId:r.id,nodeName:r.name,outcome:Gr(e),detail:e.message})}catch{n.push(await Wr(r,t))}return n}n();function qr(){let{nodes:e,isLoading:t}=Re(),n=a(()=>e??[],[e]);return{nodes:n,isLoading:t&&n.length===0}}var Jr={applied:`border-success/40 bg-success/10 text-success`,refused:`border-warning/40 bg-warning/10 text-warning`,failed:`border-danger/40 bg-danger/10 text-danger`,unconfirmed:`border-warning/40 bg-warning/10 text-warning`};function Yr(){let{t}=U(),n=B(),{nodes:i,isLoading:s}=qr(),[d,f]=qe(),{selection:p,selectNode:m}=tt(i),h=p.node,g=a(()=>i.filter(e=>e.isOnline),[i]),_=g.length,y=i.filter(e=>!e.isOnline).length,b=be(),S=N(),[C,w]=c(!1),[E,D]=c([]),O=d.get(`unlockNode`),k=d.get(`returnTo`),[A,j]=c(null);u(()=>{if(O===null||k===null)return;let e=!1;return(async()=>{try{let t=await S.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:O,dashboardBaseUrl:k}});if(e)return;let n=Dt(t),r=n===null?null:n.dashboardUrl??(()=>{let e=new URL(k);return e.searchParams.set(`ticket`,n.ticket),e.toString()})();if(r===null){j(`Could not mint an unlock ticket.`);return}let i=new URLSearchParams(d);i.delete(`unlockNode`),i.delete(`returnTo`),f(i,{replace:!0}),window.location.assign(r)}catch(t){e||j(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[O,k,d,f,S.trpcClient]);let M=e(async()=>{let e=g.map(e=>({id:e.id,name:e.name,isHub:e.isHub}));if(await n({title:t(`serverManagement.confirmUpdateAllTitle`,`Update all nodes`),message:t(`serverManagement.confirmUpdateAllBody`,`Update and restart every online node, agents first, hub last. Up-to-date nodes are skipped; this page reconnects when the hub comes back.`),confirmLabel:t(`serverManagement.confirmUpdateAllAction`,`Update all & restart`),variant:`warning`})){w(!0),D([]);try{D(await Kr(e,{apply:e=>b.mutateAsync(e),readStatus:e=>S.trpcClient.serverManagement.getServerPackageStatus.query(e),wait:e=>new Promise(t=>setTimeout(t,e))}))}finally{w(!1)}}},[b,n,g,S,t]);return r(Je,{icon:v,title:t(`nav.nodes`,`Nodes`),subtitle:t(`cluster.subtitle`,`One node at a time — topology and packages. Agents join by pairing (certificate, no shared secret).`),actions:r(o,{children:[_>0&&r(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-xs text-success`,children:[_,` online`]}),y>0&&r(`span`,{className:`rounded-full bg-destructive/10 px-2 py-0.5 text-xs text-destructive`,children:[y,` offline`]}),_>1&&r(F,{type:`button`,size:`sm`,disabled:C,title:t(`serverManagement.updateAllHint`,`Sequenced agents-first, hub-last — up-to-date nodes are skipped.`),onClick:()=>void M(),children:[C?l(T,{className:`h-3.5 w-3.5 animate-spin`}):l(x,{className:`h-3.5 w-3.5`}),t(`serverManagement.updateAll`,`Update all nodes`)]})]}),children:[E.length>0&&l(`ul`,{"aria-label":`update-all-report`,className:`flex flex-col gap-1 text-xs`,children:E.map(e=>r(`li`,{"data-outcome":e.outcome,className:`rounded border px-2 py-1 ${Jr[e.outcome]}`,children:[l(`span`,{className:`font-medium`,children:e.nodeName}),l(`span`,{className:`mx-1 uppercase tracking-wide`,children:e.outcome}),l(`span`,{className:`opacity-80`,children:e.detail})]},e.nodeId))}),A!==null&&r(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,children:[`Unlock from agent failed: `,A]}),l(Tt,{onOpenNode:m}),s?l(`div`,{className:`flex items-center justify-center py-12 text-muted-foreground`,children:`Loading cluster topology...`}):h===null?l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-foreground-subtle`,children:t(`cluster.noNodes`,`No nodes in this cluster yet.`)}):r(`div`,{className:`flex flex-col gap-3`,children:[l(et,{staleNodeId:p.staleNodeId,shownNodeName:h.name}),l(Te,{selectedNodeId:h.id,onSelect:m,allowOffline:!0,alwaysShow:!0}),l(Rr,{node:h})]})]})}export{Yr as ClusterPage};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Cyuzqnbw.js";import{I as t,K as n,Q as r,S as i,W as a,b as o,i as s,o as c,p as l,q as u,x as d,z as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{A as p,D as m,It as h,Jr as g,Mn as _,N as v,Nr as y,Nt as b,O as x,Qi as S,T as C,Tr as w,V as T,Xt as E,Yn as D,_i as O,_t as k,ar as A,b as j,bn as M,dt as N,j as P,k as F,lr as I,nr as ee,ot as te,pn as ne,rr as L,sn as R,un as z,ut as re,v as ie,y as ae,yi as oe,yn as se,z as B}from"./player-overlays-DWMIy1MJ.js";import{c as ce,l as le,t as ue}from"./video--MLJeLNU.js";import{a as de,i as fe,n as pe,r as me,t as he}from"./usb-CFseVsQJ.js";import{t as ge}from"./crop-BtQBZ9jm.js";import{t as _e}from"./layers-BARFkXZ5.js";import{An as ve,Cn as ye,Dn as be,En as xe,Gr as Se,On as Ce,Tn as we,Wr as Te,_i as Ee,c as De,jn as Oe,kn as ke,l as Ae,m as je,wi as Me,wn as Ne}from"./client-CjyKfSu1.js";import{n as Pe}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-DX7sYWrs.js";import{An as Fe,As as Ie,Bn as V,C as Le,Cs as Re,Dn as ze,E as Be,En as Ve,Es as He,F as Ue,Fs as We,Gl as H,Gs as Ge,H as Ke,Hs as qe,Ht as Je,J as Ye,Js as Xe,Jt as Ze,Ks as Qe,Ln as $e,Ls as et,Mt as tt,O as nt,On as rt,Ps as it,Rn as at,Rs as ot,S as st,Ss as ct,T as lt,Tn as ut,Ts as dt,Tt as ft,Us as pt,Ut as mt,Vs as ht,Vt as U,W as gt,Xl as _t,Y as vt,Ys as yt,Yt as bt,Zl as xt,Zn as St,_n as W,_r as Ct,ac as wt,an as Tt,ar as G,bs as Et,cc as Dt,cn as Ot,dc as kt,dn as At,du as K,fu as jt,gu as Mt,hn as Nt,hu as Pt,ic as Ft,in as It,iu as Lt,jn as Rt,kn as zt,lc as Bt,ln as Vt,ma as Ht,mn as Ut,mr as Wt,mu as Gt,oc as Kt,pn as qt,pr as Jt,pu as Yt,qs as Xt,qt as Zt,r as Qt,ru as $t,sc as en,sn as tn,un as nn,vn as rn,vs as an,vt as on,w as sn,wn as cn,ws as ln,xs as un,ys as dn,zs as fn}from"./src-BLkInT8U.js";import{V as pn,Z as mn,q as hn}from"./index-D66JvELZ.js";import"./useEventInvalidation-1Z6p3UkP.js";import{t as gn}from"./NodeAddonsSettingsPanel-D3ux_JIo.js";import{a as _n,c as vn,d as yn,g as bn,h as xn,i as Sn,l as Cn,n as wn,o as Tn,p as En,r as Dn,s as On,t as kn}from"./board-model-Bmts6hrg.js";var An=`step`,jn=[An,`acc`];function Mn(e,t){return`${e}/${t}`}function Nn(e,t,n){let r=n.step!==null&&e.includes(n.step),i=n.acc!==null&&t.includes(n.acc);return{stepId:r?n.step:null,acceleratorId:i?n.acc:null,staleStepId:n.step!==null&&n.step!==``&&!r&&e.length>0?n.step:null}}function Pn(e){if(e==null)return null;if(typeof e==`number`)return e>0?e:null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Fn(e){return e}function In(e,t){for(let[n,r]of Object.entries(e??{}))if(n===t)return r}function Ln(e,t){return typeof e==`boolean`?e:Fn(t)}function Rn(e,t){return{pipeline:Ln(In(e,`detect`),t),audio:Ln(In(e,`audio`),t),ingest:Ln(In(e,`ingest`),t)}}function zn(e,t,n){let r=e?.find(e=>e.nodeId===t);return Rn(r?.settings,n)}function Bn({selectedNodeId:e,onSelect:t,refreshToken:n}){let{nodes:r}=jt(),{data:a}=et(void 0),{data:s}=ht(void 0),c=new Map;for(let e of a??[])c.set(e.agentNodeId,(c.get(e.agentNodeId)??0)+1);let l=r??[],u=l.filter(e=>e.isOnline).length,f=l.filter(e=>!e.isOnline).length;return i(`div`,{className:`flex flex-col h-full`,children:[i(`button`,{type:`button`,onClick:()=>t(Oo),className:`flex items-center gap-3 px-4 py-3 border-b border-border text-left transition-colors ${e===`__cluster__`?`bg-primary/10 text-primary`:`text-foreground hover:bg-surface-hover`}`,children:[d(ce,{className:`h-4 w-4 flex-shrink-0`}),i(`div`,{className:`min-w-0 flex-1`,children:[d(`div`,{className:`text-xs font-semibold truncate`,children:`Cluster`}),d(`div`,{className:`text-[10px] text-foreground-subtle`,children:`Assignments, load balancing, roles`})]})]}),d(`div`,{className:`flex-1 overflow-y-auto`,children:l.map(n=>{let r=e===n.id,a=c.get(n.id)??0,l=n.isHub?z:g,u=zn(s,n.id,n.isHub),f=n.isOnline?null:on(Pn(n.lastSeen));return i(`button`,{type:`button`,onClick:()=>t(n.id),className:`flex items-center gap-3 w-full px-4 py-3 border-b border-border text-left transition-colors ${r?`bg-primary/10 text-primary`:`text-foreground hover:bg-surface-hover`}${n.isOnline?``:` opacity-60`}`,children:[d(l,{className:`h-4 w-4 flex-shrink-0`}),i(`div`,{className:`min-w-0 flex-1`,children:[i(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-xs font-semibold truncate`,children:n.name}),n.isHub&&d(`span`,{className:`text-[9px] uppercase tracking-wider text-foreground-subtle border border-border rounded px-1 py-0.5`,children:`hub`}),!n.isOnline&&d(`span`,{className:`h-1.5 w-1.5 rounded-full bg-danger flex-shrink-0`}),n.isOnline&&d(`span`,{className:`h-1.5 w-1.5 rounded-full bg-success flex-shrink-0`})]}),i(`div`,{className:`text-[10px] text-foreground-subtle flex items-center gap-2 mt-0.5`,children:[i(`span`,{children:[n.cpuCores,` cores`]}),d(`span`,{children:`•`}),i(`span`,{children:[Math.round(n.memoryMB/1024),` GB`]}),a>0&&i(o,{children:[d(`span`,{children:`•`}),i(`span`,{className:`inline-flex items-center gap-0.5 text-foreground`,children:[d(ue,{className:`h-2.5 w-2.5`}),a]})]}),!n.isOnline&&i(o,{children:[d(`span`,{children:`•`}),i(`span`,{className:`text-danger`,children:[`offline`,f===null?``:` · ${f}`]})]})]}),i(`div`,{className:`mt-0.5 flex items-center gap-1`,children:[d(G,{variant:u.pipeline?`success`:`danger`,className:`px-1 py-0 text-[9px] leading-3`,title:u.pipeline?`Pipeline: enabled`:`Pipeline: not enabled (agent capability)`,children:`Pipe`}),d(G,{variant:u.audio?`success`:`danger`,className:`px-1 py-0 text-[9px] leading-3`,title:u.audio?`Audio: enabled`:`Audio: not enabled (agent capability)`,children:`Aud`})]})]})]},n.id)})}),i(`div`,{className:`px-4 py-2 border-t border-border text-[10px] text-foreground-subtle flex items-center justify-between`,children:[i(`span`,{children:[u,` online`]}),f>0&&i(`span`,{className:`text-danger`,children:[f,` offline`]})]})]})}function Vn({nodeId:e,refreshToken:t}){let{nodes:n}=jt(),r=n?.find(t=>t.id===e),a=Yt(`pipeline.runner-load-snapshot`,t=>t.nodeId===e)?.load??null;return r?i(`div`,{className:`px-6 py-4 border-b border-border`,children:[i(`div`,{className:`flex items-center gap-2 mb-1`,children:[d(`h2`,{className:`text-base font-semibold text-foreground`,children:r.name}),r.isOnline?d(`span`,{className:`text-[10px] px-2 py-0.5 rounded-full bg-success/10 text-success`,children:`online`}):d(`span`,{className:`text-[10px] px-2 py-0.5 rounded-full bg-danger/10 text-danger`,children:`offline`}),r.isHub&&d(`span`,{className:`text-[9px] uppercase tracking-wider text-foreground-subtle border border-border rounded px-1 py-0.5`,children:`hub`})]}),i(`div`,{className:`text-[11px] text-foreground-subtle flex items-center gap-2 flex-wrap`,children:[d(`span`,{children:r.cpuModel??`CPU`}),d(`span`,{children:`•`}),i(`span`,{children:[r.cpuCores,` cores`]}),d(`span`,{children:`•`}),i(`span`,{children:[Math.round(r.memoryMB/1024),` GB`]}),a&&i(o,{children:[d(`span`,{children:`•`}),i(`span`,{children:[a.attachedCameras,` cameras (`,a.activeCameras,` active)`]}),d(`span`,{children:`•`}),i(`span`,{children:[a.avgInferenceTimeMs.toFixed(0),`ms avg inference`]}),d(`span`,{children:`•`}),i(`span`,{children:[`queue `,a.queueDepthTotal]}),a.hardware.hasGpu&&i(o,{children:[d(`span`,{children:`•`}),d(`span`,{className:`text-success`,children:`GPU`})]})]})]})]}):d(`div`,{className:`px-6 py-4 border-b border-border`,children:i(`div`,{className:`text-xs text-foreground-subtle`,children:[`Node not found: `,e]})})}var Hn=[`assignments`,`tree`,`engines`,`logs`];r();function Un({refreshToken:e,nodeId:t}){let[n,r]=u(new Map),{nodes:o}=K();Pt(`pipeline.camera-metrics-snapshot`,e=>{let t=e.data;typeof t?.deviceId==`number`&&r(e=>{let n=new Map(e);return n.set(t.deviceId,t),n})});let{data:s}=He(void 0),c=a(()=>{let e=new Map;for(let t of s??[])e.set(t.nodeId,t.deviceCount);return e},[s]),l=a(()=>{let e=new Map,t=Date.now()-3e4;for(let r of n.values()){if(r.timestamp<t)continue;let n=r.nodeId??`hub`,i=e.get(n)??{attachedCameras:0,activeCameras:0,totalFps:0,totalInferenceWeighted:0,queueDepth:0};i.attachedCameras++,r.metrics.phase===`active`&&i.activeCameras++,i.totalFps+=r.metrics.actualFps,i.totalInferenceWeighted+=r.metrics.avgInferenceTimeMs,i.queueDepth+=r.metrics.queueDepth,e.set(n,i)}return e},[n]),f=a(()=>{let e=new Map;for(let t of o)e.set(t.id,t.shortName);return e},[o]),p=a(()=>{let e=0,t=0,n=0,r=0,i=0;for(let a of l.values())e+=a.attachedCameras,t+=a.activeCameras,n+=a.totalFps,r+=a.totalInferenceWeighted,i+=a.queueDepth;let a=e>0?r/e:0;return{totalAgents:o.length,onlineAgents:o.filter(e=>e.isOnline).length,attachedCameras:e,activeCameras:t,avgInferenceTimeMs:a,queueDepth:i,totalFps:n}},[l,o]);if(t){let e=l.get(t);return i(`div`,{className:`@container/liveload`,children:[d(`h3`,{className:`text-sm font-semibold text-foreground mb-2`,children:`Live load`}),i(`div`,{className:`grid grid-cols-2 @md/liveload:grid-cols-3 @3xl/liveload:grid-cols-5 gap-2 mb-3`,children:[d(q,{label:`FPS`,value:e?e.totalFps.toFixed(1):`—`}),d(q,{label:`Active / Attached`,value:e?`${e.activeCameras}/${e.attachedCameras}`:`—`}),d(q,{label:`Avg infer ms`,value:e&&e.attachedCameras>0?(e.totalInferenceWeighted/e.attachedCameras).toFixed(0):`—`}),d(q,{label:`Queue`,value:e?String(e.queueDepth):`—`}),d(q,{label:`Audio`,value:String(c.get(t)??`—`)})]})]})}let m=[...l.entries()].toSorted(([e],[t])=>e===`hub`?-1:t===`hub`?1:e.localeCompare(t));return i(`div`,{className:`@container/liveload`,children:[d(`h3`,{className:`text-sm font-semibold text-foreground mb-2`,children:`Live load`}),i(`div`,{className:`grid grid-cols-2 @md/liveload:grid-cols-3 @3xl/liveload:grid-cols-5 gap-2 sm:gap-3 mb-3`,children:[d(q,{label:`Total agents`,value:`${p.onlineAgents}/${p.totalAgents}`}),d(q,{label:`Active / Attached`,value:`${p.activeCameras}/${p.attachedCameras}`}),d(q,{label:`Total FPS`,value:p.totalFps.toFixed(1)}),d(q,{label:`Avg inference ms`,value:p.avgInferenceTimeMs.toFixed(0)}),d(q,{label:`Queue depth`,value:String(p.queueDepth)})]}),d(`div`,{className:`rounded-lg border border-border overflow-x-auto`,children:i(`table`,{className:`w-full text-xs min-w-[480px]`,children:[d(`thead`,{className:`bg-surface`,children:i(`tr`,{className:`text-foreground-subtle text-[10px] uppercase tracking-wider`,children:[d(`th`,{className:`text-left px-3 py-2`,children:`Agent`}),d(`th`,{className:`text-right px-3 py-2`,children:`FPS`}),d(`th`,{className:`text-right px-3 py-2`,children:`Cameras`}),d(`th`,{className:`text-right px-3 py-2`,children:`Inference ms`}),d(`th`,{className:`text-right px-3 py-2`,children:`Queue`}),d(`th`,{className:`text-right px-3 py-2`,children:`Audio`})]})}),i(`tbody`,{children:[m.map(([e,t])=>i(`tr`,{className:`border-t border-border`,children:[d(`td`,{className:`px-3 py-2 text-foreground font-medium`,children:f.get(e)??e}),d(`td`,{className:`px-3 py-2 text-right text-foreground`,children:t.totalFps.toFixed(1)}),d(`td`,{className:`px-3 py-2 text-right text-foreground`,children:t.attachedCameras}),d(`td`,{className:`px-3 py-2 text-right text-foreground`,children:t.attachedCameras>0?(t.totalInferenceWeighted/t.attachedCameras).toFixed(0):`—`}),d(`td`,{className:`px-3 py-2 text-right text-foreground`,children:t.queueDepth}),d(`td`,{className:`px-3 py-2 text-right text-foreground`,children:c.get(e)??`—`})]},e)),m.length===0&&d(`tr`,{children:d(`td`,{colSpan:6,className:`px-3 py-4 text-center text-foreground-subtle text-[11px]`,children:`No camera metrics received yet`})})]})]})})]})}function q({label:e,value:t}){return i(`div`,{className:`rounded-lg border border-border bg-surface/60 p-3`,children:[d(`div`,{className:`text-[10px] uppercase tracking-wider text-foreground-subtle mb-1`,children:e}),d(`div`,{className:`text-lg font-semibold text-foreground`,children:t})]})}var Wn={active:!1,pinned:!1,nodeId:null,reason:``};function Gn(e,t){return e.deviceName.localeCompare(t.deviceName)||e.deviceId-t.deviceId}function Kn(e,t,n){let r=new Map(t.map(e=>[e.deviceId,e])),i=new Map(n.map(e=>[e.deviceId,e]));return e.map(e=>{let t=r.get(e.id),n=i.get(e.id),a=t?{active:!0,pinned:t.pinned,nodeId:t.agentNodeId,reason:t.reason??``}:Wn,o=n?{active:!0,pinned:n.pinned,nodeId:n.nodeId,reason:``}:Wn;return{deviceId:e.id,deviceName:e.name,disabled:e.disabled===!0,pipeline:a,detection:a,decoder:Wn,audio:o}}).toSorted(Gn)}function qn(e,t,n){return{active:e!==null,pinned:t,nodeId:e,reason:n??``}}function Jn(e,t){let n=new Map(t.map(e=>[e.deviceId,e.assignment]));return e.map(e=>{let t=n.get(e.deviceId);return t===void 0?e:{...e,detection:qn(t.detectionNodeId,t.pinned.detection,t.reasons.detection),decoder:qn(t.decoderNodeId,t.pinned.decoder,t.reasons.decoder),audio:qn(t.audioNodeId,t.pinned.audio,t.reasons.audio)}})}function Yn(e,t,n){let r=(t,n,r)=>({active:t!==null&&t===e,pinned:n,nodeId:t,reason:r??``});return t.map(({deviceId:e,assignment:t})=>({deviceId:e,deviceName:n(e),detection:r(t.detectionNodeId,t.pinned.detection,t.reasons.detection),decoder:r(t.decoderNodeId,t.pinned.decoder,t.reasons.decoder),audio:r(t.audioNodeId,t.pinned.audio,t.reasons.audio)})).filter(e=>e.detection.active||e.decoder.active||e.audio.active).toSorted(Gn)}function Xn(e){let t=new Map(e.map(e=>[e.id,e.name]));return e=>{let n=t.get(e);return n!==void 0&&n!==``?n:e}}function Zn(e){let t=new Map(e.map(e=>[e.id,e.name]));return e=>t.get(e)??`Camera ${e}`}function Qn(e,t,n){return[{value:`auto`,label:`Auto`},...[...new Set([...e.nodeId===null?[]:[e.nodeId],...t.map(e=>e.id)])].map(e=>({value:e,label:`Pin → ${n(e)}`}))]}function $n({roleId:e,roleLabel:t,state:n,nameOf:r,colorByNodeId:i,emphasizeOnNodeId:a}){if(n.nodeId===null)return null;let o=n.nodeId,s=a===void 0?!1:n.active&&o===a;return d(Zt,{roleId:e,roleLabel:t,nodeName:r(o),colorId:bt(i,o),emphasized:s,pinned:n.pinned})}function er({detection:e,decoder:t,audio:n,nameOf:r,colorByNodeId:a,emphasizeOnNodeId:o}){let s=(e,t,n)=>d($n,{roleId:e,roleLabel:t,state:n,nameOf:r,colorByNodeId:a,emphasizeOnNodeId:o},e);return i(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1.5`,children:[s(`detection`,`Detection`,e),s(`decode`,`Decode`,t),s(`audio`,`Audio`,n)]})}function tr({snap:e}){if(e===void 0)return d(`div`,{className:`flex h-8 items-center text-[11px] text-foreground-subtle`,title:`No metrics in the last 10 s — the camera has no session running`,children:`no live data`});let{phase:t,actualFps:n,avgInferenceTimeMs:r,queueDepth:a,configuredFps:o,droppedFrames:s}=e.metrics,c=tt(t);return i(`div`,{className:`flex h-8 min-w-0 flex-col justify-center font-mono text-[10px] leading-tight tabular-nums`,children:[i(`span`,{className:`inline-flex min-w-0 items-center gap-1 ${c.textColor}`,children:[d(Ue,{phase:t,className:`h-2.5 w-2.5 shrink-0`}),d(`span`,{className:`truncate font-semibold uppercase tracking-wider`,children:c.label}),d(`span`,{className:`text-foreground`,children:n.toFixed(1)}),i(`span`,{className:`text-foreground-subtle`,children:[`/`,o.toFixed(0),` fps`]})]}),i(`span`,{className:`truncate text-foreground-subtle`,children:[d(`span`,{className:`text-foreground`,children:r.toFixed(0)}),` ms`,a>0&&i(`span`,{className:`ml-1 text-warning`,children:[`q`,a]}),i(`span`,{className:s>0?`ml-1 text-warning`:`ml-1`,children:[`drops `,s]})]})]})}r();var nr=1e4,rr=5e3;function ir(e){let[t,n]=u(new Map);return Pt(`pipeline.camera-metrics-snapshot`,t=>{let r=t.data;typeof r.deviceId==`number`&&(e!==void 0&&r.nodeId!==e||n(e=>new Map(e).set(r.deviceId,r)))}),f(()=>{if(t.size===0)return;let e=setInterval(()=>{n(e=>{let t=Date.now()-nr,n=[...e].filter(([,e])=>e.timestamp>=t);return n.length===e.size?e:new Map(n)})},rr);return()=>clearInterval(e)},[t.size]),t}var ar=3e5;function or({state:e,onlineNodes:t,nameOf:n,pending:r,onChange:i}){return d(H,{"aria-label":`Node pin`,title:`Auto lets each session pick its node; a pin keeps the camera on one node.`,value:e.pinned&&e.nodeId!==null?e.nodeId:`auto`,disabled:r,options:[...Qn(e,t,n)],onChange:e=>i(e.target.value)})}function sr({deviceId:e,nodeId:t}){let n=c(),{data:r}=ot({deviceId:e},{refetchOnMount:`always`}),{data:i}=We({nodeId:t},{staleTime:ar}),a=wt({onSuccess:()=>{n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getPipelineDevicePin`]]})}});if(r===void 0||i===void 0)return d(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:`accelerator: …`});let o=i.devices??[],s=o.filter(e=>e.enabled),l=r?.deviceKey??`auto`,u=l!==`auto`&&!s.some(e=>e.key===l),f=o.find(e=>e.key===l),p=[{value:`auto`,label:`Any accelerator`},...u?[{value:l,label:`${f?`${W(f)} (${l})`:l} (not enabled)`}]:[],...s.map(e=>({value:e.key,label:`${W(e)} · ${e.format}`}))];return d(H,{"aria-label":`Inference device pin`,title:`Pin detection to one accelerator of the node, or let each session pick.`,value:l,disabled:a.isPending,options:p,onChange:t=>a.mutate({deviceId:e,deviceKey:t.target.value})})}r();function cr(e){let t=n(null);return e.nodeId!==null&&(t.current=e),t.current}function lr({deviceId:e,state:t,...n}){let r=cr(t);return i(`div`,{className:`grid w-80 grid-cols-2 gap-1.5`,children:[d(or,{state:t,...n}),r?.nodeId==null?d(H,{"aria-label":`Inference device pin (no node yet)`,title:`An accelerator is pinned on the camera's node; this camera has not run on one yet.`,disabled:!0,defaultValue:`auto`,options:[{value:`auto`,label:`Any accelerator`}]}):d(sr,{deviceId:e,nodeId:r.nodeId})]})}function ur({state:e,nameOf:t}){let n=cr(e);if(n?.nodeId==null)return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:`— no session yet`});let r=e.active&&e.nodeId!==null,a=n.pinned?`pinned`:`auto · ${n.reason||`capacity`}`;return i(`div`,{"data-testid":`resolved-placement`,className:`flex w-40 min-w-0 flex-col leading-tight`,title:n.pinned?void 0:`An unpinned camera is placed again at every session start, so this can change between sessions.`,children:[i(`span`,{className:`flex min-w-0 items-center gap-1.5 text-xs`,children:[d(`span`,{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${r?`bg-success`:`bg-foreground-subtle/40`}`}),d(`span`,{"data-testid":`resolved-placement-node`,className:`truncate font-medium ${r?`text-foreground`:`text-foreground-muted`}`,children:t(n.nodeId)})]}),d(`span`,{className:`truncate pl-3 text-[10px] ${n.pinned?`text-warning`:`text-foreground-subtle`}`,children:r?a:`${a} · idle, last session`})]})}function dr({deviceId:e,deviceName:t}){let[n,r]=u(!1);return i(o,{children:[d(xt,{icon:M,variant:`ghost`,size:`sm`,"aria-label":`Stream brokers of ${t}`,title:`Stream brokers & clients`,onClick:()=>r(!0)}),d(ut,{open:n,onOpenChange:r,children:i(ze,{width:`lg`,scroll:`body`,placement:`sheet-on-mobile`,children:[d(Fe,{children:i(Rt,{children:[t,` — stream brokers & clients`]})}),d(Ve,{children:n&&d(cn,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:e,instanceId:`pipeline-row/${e}`,config:{variant:`compact`}})})]})})]})}function fr(e){return e.hasFreshMetrics?`active`:e.hasPipelineAssignment?`recently-active`:`inactive`}function pr(e,t){return t.size===0?!0:t.has(e)}var mr=[{value:`active`,label:`Active`},{value:`recently-active`,label:`Recently active`},{value:`inactive`,label:`Inactive`}];r();var hr=[`pipeline.camera-assigned`,`pipeline.camera-unassigned`,`pipeline.camera-updated`,`agent.online`,`agent.offline`];function gr(e){for(let t of[`getPipelineAssignments`,`getAudioAssignments`,`getCameraStatuses`])e.invalidateQueries({queryKey:[[`pipelineOrchestrator`,t]]})}function _r(){let e=c();Qt([`pipelineOrchestrator`,`getPipelineAssignments`],hr),Qt([`pipelineOrchestrator`,`getAudioAssignments`],hr),Qt([`pipelineOrchestrator`,`getCameraStatuses`],hr);let{data:t}=Ht({isCamera:!0,projection:`slim`}),{data:n}=et(void 0),{data:r}=dt(void 0),{data:o}=Ie({}),{data:s}=ht(void 0),{nodes:l}=K(),f=ir(),p=a(()=>Xn(l),[l]),m=a(()=>Ze(s),[s]),h=a(()=>l.filter(e=>e.isOnline).map(e=>({id:e.id,name:e.name})),[l]),g=a(()=>Jn(Kn((t??[]).map(e=>({id:e.id,name:e.name,disabled:e.disabled})),n??[],r??[]),o??[]),[t,n,r,o]),[_,v]=u(()=>new Set),y=a(()=>g.filter(e=>pr(fr({hasPipelineAssignment:e.pipeline.active,hasFreshMetrics:f.has(e.deviceId)}),_)),[g,f,_]),b=e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},x=()=>gr(e),S=Re({onSuccess:x}),C=Bt({onSuccess:x}),w=S.isPending||C.isPending,T=[{key:`camera`,header:`Camera`,width:`w-44`,sortValue:e=>e.deviceName,render:e=>i(`div`,{className:`flex w-44 min-w-0 items-center gap-1.5`,children:[d(hn,{to:`/devices/${String(e.deviceId)}`,className:`min-w-0 truncate text-xs font-medium text-primary hover:underline`,title:e.deviceName,children:e.deviceName}),e.disabled&&d(G,{variant:`default`,children:`off`})]})},{key:`placement`,header:`Placement`,width:`w-80`,notSortableReason:`A pair of controls — editing one would move the row under the cursor.`,render:e=>d(lr,{deviceId:e.deviceId,state:e.pipeline,onlineNodes:h,nameOf:p,pending:w,onChange:t=>t===`auto`?C.mutate({deviceId:e.deviceId}):S.mutate({deviceId:e.deviceId,agentNodeId:t})})},{key:`roles`,header:`Roles here`,notSortableReason:`A set of roles has no single order.`,render:e=>d(er,{detection:e.detection,decoder:e.decoder,audio:e.audio,nameOf:p,colorByNodeId:m})},{key:`resolved`,header:`Running on`,width:`w-40`,sortValue:e=>e.pipeline.nodeId===null?null:p(e.pipeline.nodeId),render:e=>d(ur,{state:e.pipeline,nameOf:p})},{key:`status`,header:`Status`,width:`w-40`,sortValue:e=>f.get(e.deviceId)?.metrics.actualFps??null,render:e=>d(tr,{snap:f.get(e.deviceId)})},{key:`brokers`,header:``,align:`right`,width:`w-10`,notSortableReason:`An action`,render:e=>d(dr,{deviceId:e.deviceId,deviceName:e.deviceName})}],E=t===void 0?`Loading cameras…`:g.length===0?`No cameras`:`No cameras match this activity filter.`;return i(`div`,{className:`flex flex-col gap-2`,children:[d(`nav`,{"aria-label":`Filter by camera activity`,"data-testid":`assignments-activity-filter`,children:d(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1.5`,children:mr.map(e=>{let t=_.has(e.value);return d(`button`,{type:`button`,"aria-pressed":t,"data-testid":`assignments-activity-${e.value}`,className:Lt(ae,t?ie:j),onClick:()=>b(e.value),children:e.label},e.value)})})}),d(Je,{columns:T,rows:y,rowKey:e=>e.deviceId,minWidthPx:920,mobileMode:`scroll`,maxBodyHeight:mt,emptyMessage:E})]})}r();function vr({nodeId:e}){let t=c();Qt([`pipelineOrchestrator`,`getCameraStatuses`],hr);let{data:n}=Ie({}),{data:r}=ht(void 0),{data:i}=Ht({isCamera:!0,projection:`slim`}),{nodes:o}=K(),s=ir(),l=a(()=>Xn(o),[o]),u=a(()=>Ze(r),[r]),f=a(()=>Yn(e,n??[],Zn((i??[]).map(e=>({id:e.id,name:e.name})))),[e,n,i]),p=o.filter(t=>t.isOnline&&t.id!==e),m=()=>gr(t),h=Re({onSuccess:m}),g=Bt({onSuccess:m}),_=ct({onSuccess:m}),v=Dt({onSuccess:m}),y=e=>[...e.detection.active?p.map(t=>({id:`detect-${t.id}`,label:`Move detection to ${t.name}`,onClick:()=>h.mutate({deviceId:e.deviceId,agentNodeId:t.id})})):[],...e.audio.active?p.map(t=>({id:`audio-${t.id}`,label:`Move audio to ${t.name}`,onClick:()=>_.mutate({deviceId:e.deviceId,nodeId:t.id})})):[],{id:`unpin-detect`,label:`Unpin detection`,hidden:!(e.detection.active&&e.detection.pinned),separatorBefore:!0,onClick:()=>g.mutate({deviceId:e.deviceId})},{id:`unpin-audio`,label:`Unpin audio`,hidden:!(e.audio.active&&e.audio.pinned),onClick:()=>v.mutate({deviceId:e.deviceId})}];return d(Je,{columns:[{key:`camera`,header:`Camera`,width:`w-44`,sortValue:e=>e.deviceName,render:e=>d(hn,{to:`/devices/${String(e.deviceId)}`,className:`block w-44 truncate text-xs font-medium text-primary hover:underline`,title:e.deviceName,children:e.deviceName})},{key:`roles`,header:`Roles here`,notSortableReason:`A set of roles has no single order.`,render:t=>d(er,{detection:t.detection,decoder:t.decoder,audio:t.audio,nameOf:l,colorByNodeId:u,emphasizeOnNodeId:e})},{key:`status`,header:`Status`,width:`w-40`,sortValue:e=>s.get(e.deviceId)?.metrics.actualFps??null,render:e=>d(tr,{snap:s.get(e.deviceId)})},{key:`actions`,header:``,align:`right`,width:`w-10`,notSortableReason:`Actions`,render:e=>d(gt,{items:y(e),title:`Move ${e.deviceName}`})}],rows:f,rowKey:e=>e.deviceId,minWidthPx:560,mobileMode:`scroll`,maxBodyHeight:mt,emptyMessage:n===void 0?`Loading cameras…`:`No camera runs on this node right now`})}function yr({nodeId:e,refreshToken:t}){let{nodes:n}=K(),r=n.find(t=>t.id===e)?.name??e;return i(`div`,{className:`space-y-3 sm:space-y-4`,children:[d(Un,{refreshToken:t,nodeId:e}),i(`div`,{className:`space-y-2`,children:[i(`div`,{children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:[`Cameras on `,r]}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`The roles each camera runs here right now. Move a role or unpin it from the row menu; pins for every camera are on Cluster → Assignments.`})]}),d(vr,{nodeId:e})]})]})}r();function br(e,t){let n=Math.max(0,t-e);return`${Math.floor(e/1e3)}s idle · ${Math.floor(n/1e3)}s left`}function xr({nodeId:e,refreshToken:t}){let n=c(),r=St(),o=dn({onSettled:()=>{n.invalidateQueries({queryKey:[`pipelineExecutor`,`listLoadedEngines`]})}}),{data:s}=Et({nodeId:e}),l=Yt(`pipeline.engine-metrics-snapshot`,t=>t.nodeId===e)?.engines??s??null,u=l===null;Qt([`pipelineRunner`,`getLocalCameras`],[`pipeline.camera-assigned`,`pipeline.camera-unassigned`]);let{data:f}=kt({nodeId:e}),{values:p}=Gt(`pipeline.camera-metrics-snapshot`,e=>e.deviceId,t=>t.nodeId===e),m=a(()=>p.filter(e=>e.metrics.phase===`active`).length,[p]),_=t=>{let n=f??[];if(n.length===0){o.mutate({nodeId:e,engine:t,force:!1});return}(async()=>{await r({title:`Kill engine`,message:`${String(n.length)} camera(s) are dispatching through this engine. Killing it drops their in-flight work and forces a respawn on the next frame.`,confirmLabel:`Kill engine`,variant:`danger`})&&o.mutate({nodeId:e,engine:t,force:!0})})()};return i(`div`,{className:`space-y-6`,children:[i(`div`,{children:[d(`h3`,{className:`text-sm font-semibold text-foreground mb-1`,children:`Inference engines on this node`}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:[(l??[]).length,` engine(s) resident in RAM. `,(f??[]).length,` `,`camera(s) attached, `,m,` actively dispatching frames. Refreshes every 5s.`]})]}),d(`div`,{className:`rounded-lg border border-border overflow-x-auto`,children:i(`table`,{className:`w-full text-xs min-w-[640px]`,children:[d(`thead`,{className:`bg-surface`,children:i(`tr`,{className:`text-foreground-subtle text-[10px] uppercase tracking-wider`,children:[d(`th`,{className:`text-left px-3 py-2 whitespace-nowrap`,children:`Kind`}),d(`th`,{className:`text-left px-3 py-2 whitespace-nowrap`,children:`Runtime / Backend / Device`}),d(`th`,{className:`text-left px-3 py-2`,children:`Models`}),d(`th`,{className:`text-right px-3 py-2 whitespace-nowrap`,children:`Pool PID`}),d(`th`,{className:`text-right px-3 py-2 whitespace-nowrap`,children:`Auto-kill`}),d(`th`,{className:`text-right px-3 py-2 whitespace-nowrap`,children:`In use`}),d(`th`,{className:`w-20`})]})}),i(`tbody`,{children:[u&&d(`tr`,{children:d(`td`,{colSpan:7,className:`px-3 py-4 text-center text-foreground-subtle text-[11px]`,children:`Loading…`})}),!u&&(l??[]).map(e=>{let t=e.kind===`device-pool`;return i(`tr`,{className:`border-t border-border ${t?`bg-primary/[0.05]`:``}`,children:[d(`td`,{className:`px-3 py-2`,children:i(`span`,{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${t?`bg-primary/15 text-primary`:`bg-success/15 text-success`}`,children:[d(t?_e:g,{className:`h-3 w-3`}),t?`pool`:`runtime`]})}),d(`td`,{className:`px-3 py-2`,children:i(`span`,{className:`inline-flex items-center gap-1 text-[11px] text-sky-400`,children:[d(re,{className:`h-3 w-3`}),e.engine.runtime,`/`,e.engine.backend,e.engine.device?`/${e.engine.device}`:``,e.engine.format?` · ${e.engine.format}`:``]})}),d(`td`,{className:`px-3 py-2`,children:e.modelsLoaded.length===0?d(`span`,{className:`text-foreground-subtle text-[11px]`,children:`—`}):d(`div`,{className:`flex flex-wrap gap-1`,children:e.modelsLoaded.map(e=>d(`span`,{className:`inline-block rounded bg-surface px-1.5 py-0.5 text-[10px] font-mono text-foreground-subtle`,children:e},e))})}),d(`td`,{className:`px-3 py-2 text-right font-mono text-foreground`,children:e.poolPid??`—`}),d(`td`,{className:`px-3 py-2 text-right text-[11px]`,children:e.idleMs!==null&&e.idleTtlMs!==null?d(`span`,{className:`text-foreground-subtle`,children:br(e.idleMs,e.idleTtlMs)}):d(`span`,{className:`text-foreground-subtle/50`,children:`never`})}),d(`td`,{className:`px-3 py-2 text-right text-foreground`,children:(f??[]).length}),d(`td`,{className:`px-3 py-2 text-right`,children:t?d(`span`,{className:`text-[11px] text-foreground-subtle`,children:`auto`}):i(V,{variant:`ghost`,size:`sm`,disabled:o.isPending,onClick:()=>_(e.engine),className:`text-danger hover:bg-danger/10 hover:text-danger`,children:[d(h,{className:`h-3.5 w-3.5`}),`Kill`]})})]},e.engineKey)}),!u&&(l??[]).length===0&&d(`tr`,{children:d(`td`,{colSpan:7,className:`px-3 py-4 text-center text-foreground-subtle text-[11px]`,children:`No engines resident — the factory spins up on the first pipeline run.`})})]})]})}),i(`div`,{className:`text-[10px] text-foreground-subtle leading-relaxed`,children:[d(`strong`,{className:`text-foreground`,children:`runtime`}),`: main camera-serving engine; never auto-killed while cameras attached. `,d(`strong`,{className:`text-foreground`,children:`warm`}),`: benchmark/test override held in cache for fast re-use; auto-disposed after the idle TTL.`,` `,d(`strong`,{className:`text-foreground`,children:`pool`}),`: a per-device balanced inference pool (one per enabled accelerator, running concurrently); reaper-managed on its own idle TTL.`]}),o.isError&&d($e,{message:`Kill failed: ${o.error instanceof Error?o.error.message:`unknown error`}`})]})}var Sr=`pipeline-runner`,Cr=200;function wr({nodeId:e}){return i(`div`,{className:`flex flex-col gap-3`,children:[i(`div`,{children:[d(`h3`,{className:`text-sm font-semibold text-foreground mb-1`,children:`Runner logs`}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`pipeline-runner activity on `,e,` — camera attach/detach, engine phases and pipeline errors. Streaming live; the device chip on a line tells which camera it refers to.`]})]}),d(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:d(ft,{agentId:e,addonId:Sr,limit:Cr,maxHeight:`max-h-[calc(100vh-360px)]`,showScope:!0,showDeviceChip:!0,showFilters:!1})})]})}r();function Tr({nodeId:e,title:t}){let{data:n}=pn(),{data:r}=et(void 0),o=a(()=>{let e=new Map;for(let t of n??[])e.set(t.id,t.name);return e},[n]),s=a(()=>{if(!e)return null;let t=new Set;for(let n of r??[])n.agentNodeId===e&&t.add(n.deviceId);return t},[e,r]),c=ir(e),l=a(()=>{let e=[];for(let t of c.values())s&&!s.has(t.deviceId)||e.push(t);return e.sort((e,t)=>e.deviceId-t.deviceId),e},[c,s]);return l.length===0?i(`div`,{className:`rounded-md border border-border bg-surface px-3 py-2 text-[11px] text-foreground-subtle italic`,children:[t??`Cameras`,`: no live snapshots yet`]}):i(`div`,{className:`rounded-md border border-border bg-surface px-3 py-2`,children:[i(`div`,{className:`flex items-center gap-2 mb-1.5`,children:[d(`span`,{className:`text-[10px] uppercase tracking-wider text-foreground-subtle`,children:t??`Cameras`}),d(`span`,{className:`text-[10px] text-foreground-subtle`,children:l.length})]}),d(`div`,{className:`flex flex-wrap gap-1.5`,children:l.map(e=>{let t=o.get(e.deviceId)??`#${e.deviceId}`,n=tt(e.metrics.phase);return i(`div`,{title:`${t} · ${n.label} · ${e.metrics.actualFps.toFixed(1)} fps · ${e.metrics.avgInferenceTimeMs.toFixed(0)}ms infer · q=${e.metrics.queueDepth}`,className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${n.badgeClass}`,children:[d(Ue,{phase:e.metrics.phase,className:`h-2.5 w-2.5`}),d(`span`,{className:`font-medium text-foreground/90 max-w-[220px] truncate`,children:t}),d(`span`,{className:`font-mono tabular-nums`,children:e.metrics.actualFps.toFixed(1)}),d(`span`,{className:`opacity-60`,children:`fps`})]},e.deviceId)})})]})}function Er(e,t,n){return e.map(e=>{if(e.key===t)return e;let r=e.steps[n];if(!r||r.settings===void 0)return e;let{settings:i,...a}=r,o={...e.steps};return Object.keys(a).length>0?o[n]=a:delete o[n],{...e,steps:o}})}function Dr(e,t,n){let r=e.filter(e=>e.key!==t).toSorted((e,t)=>e.key.localeCompare(t.key)),i=[...r.filter(e=>!e.enabled),...r.filter(e=>e.enabled),...e.filter(e=>e.key===t)],a;for(let e of i){let t=e.steps?.[n]?.settings;!t||Object.keys(t).length===0||(a={...a,...t})}return a}function Or(e){let t={};for(let n of e){let e=Object.keys(n.steps).length>0;t[n.key]={enabled:n.enabled,weight:Math.max(1,n.weight),...n.maxSessions!==null&&n.maxSessions>0?{maxSessions:n.maxSessions}:{},...e?{steps:n.steps}:{}}}return t}var kr=`pipeline-orchestrator`;function Ar({addonId:e,highlightLabel:t}){let n=be(e),{data:r}=Wt({addonId:kr});if(n.length===0)return null;let a=ve(r??null)[e]??{};return i(`section`,{className:`space-y-1.5 border-t border-border/60 pt-3`,"aria-label":`Cluster-wide settings`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`h3`,{className:T,children:`Cluster-wide settings`}),d(hn,{to:Fo(e),className:`ml-auto text-[11px] text-primary hover:underline`,children:`Edit in Cluster → Settings ›`})]}),n.map(e=>i(`div`,{className:`${p} rounded px-2 ${t===e.label?`bg-primary/5 ring-1 ring-primary/40`:``}`,children:[d(`span`,{className:P,children:e.label}),d(`span`,{className:v,children:d(`span`,{className:`font-mono text-xs text-foreground`,children:String(a[e.key]??e.default)})})]},e.key)),d(`p`,{className:B,children:`One value for every node and camera — this step writes into a shared index.`})]})}function jr({rows:e}){return i(`div`,{className:`space-y-1.5`,"data-testid":`effective-models`,children:[d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.map(e=>i(`li`,{className:`${C} flex flex-wrap items-baseline gap-x-2 text-xs`,children:[d(`span`,{className:`min-w-0 flex-1 truncate text-foreground-muted`,children:e.label}),d(`span`,{className:`font-mono text-foreground`,children:e.modelId??`—`}),d(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.sourceLabel})]},e.id))}),d(`p`,{className:B,children:`To change a model, open that accelerator's cell in the table.`})]})}r();function Mr(e,n){let[r,i]=mn(),o=r.get(An),s=r.get(`acc`),c=a(()=>Nn(e,n,{step:o,acc:s}),[e,n,o,s]),l=t(e=>{i(t=>{let n=new URLSearchParams(t);return e(n),n},{replace:!0})},[i]);return{selection:c,open:t(e=>l(t=>{t.set(An,e.stepId),e.acceleratorId===void 0?t.delete(`acc`):t.set(`acc`,e.acceleratorId)}),[l]),close:t(()=>l(e=>{e.delete(An),e.delete(`acc`)}),[l])}}function Nr(e,t){for(let n of e?.slots??[])for(let e of n.addons)if(e.id===t)return e;return null}function Pr(e){return e.split(`.`)[0]??e}function Fr(e,t,n){return{id:Mn(e,n.key),nodeId:e,deviceKey:n.key,device:n,label:`${Pr(t)} · ${W(n)}`,shortLabel:`${Pr(t)} · ${rn(n)}`,nodeLabel:Pr(t),disabled:!n.enabled}}function Ir(e,t,n,r=!1){return n.filter(e=>r||e.enabled).map(n=>Fr(e,t,n))}function Lr(e,t,n=!1){return e.flatMap(e=>{let r=t[e.id]??[];if(n)return r.map(t=>Fr(e.id,e.name,t));let i=r.filter(e=>e.enabled&&e.available);if(i.length>0)return i.map(t=>Fr(e.id,e.name,t));let a=r.find(e=>e.available)??r[0];return a===void 0?[]:[Fr(e.id,e.name,a)]})}function Rr(e,t,n){return{modelId:qt({catalog:e,device:t.device,base:n.nodePin,override:n.cameraPin}),source:n.cameraPin===void 0?n.nodePin===void 0?`default`:`node`:`camera`}}function zr(e,t,n){let r=Nr(e,`object-detection`);if(r===null)return;let i=qt({catalog:r,device:t.device,base:t.device.steps?.[`object-detection`]?.modelId,override:n});if(i===void 0)return;let a=r.models.find(e=>e.id===i);return{modelId:i,name:a?.name??i,supplies:a?.suppliesSteps??[]}}function Br(e,t,n){return!Te(e)||n===void 0?!1:Se(e,t,n.supplies).effective}function Vr(e,t){return e!==null&&Ut(e.models,t.device.format)}function Hr(e){return Vr(e.addon,e.acc)?e.clusterModelId===void 0?{kind:`enabled`,modelId:e.model.modelId??`Auto`,overridden:e.model.source===`camera`,...e.rootName===void 0?{}:{suppliedByRoot:e.rootName},...e.jumpTo===void 0?{}:{jumpTo:e.jumpTo}}:{kind:`enabled`,modelId:e.clusterModelId,clusterWide:!0}:e.gatedOn?e.jumpTo===void 0?{kind:`skip`}:{kind:`skip`,jumpTo:e.jumpTo}:{kind:`na`}}function Ur(e){return Object.values(e).reduce((e,t)=>e+t.filter(e=>!e.enabled).length,0)}function Wr(e){if(e===null)return[];let t=(e.configSchema??[]).flatMap(e=>`label`in e&&typeof e.label==`string`?[e.label]:[]),n=be(e.id).map(e=>e.label);return[...new Set([...t,...n])]}function Gr(e){return e.flatMap(e=>[{node:e,depth:0},...Gr(e.children).map(e=>({node:e.node,depth:e.depth+1}))])}function Kr(e,t){return e.flatMap(e=>{let n=Kr(e.children,t);return t.has(e.addonId)||n.length>0?[{...e,children:n}]:[]})}r();function qr(e){return{agentNodeId:e.nodeId,nodeLabel:e.nodeLabel,engineLabel:e.device.format,deviceKey:e.deviceKey,deviceLabel:W(e.device),detail:e.device.defaultModelId,disabled:e.disabled}}function Jr({tree:e,searchRows:r,accelerators:o,cellState:s,stepBadge:c,disabledCount:l,showDisabled:f,onShowDisabledChange:p,dirty:m,onDiscard:h,summary:g,toolbar:_,label:v,renderDetail:y}){let b=St(),x=$t(),{selection:S,open:C,close:w}=Mr(a(()=>Gr(e).map(e=>e.node.addonId),[e]),a(()=>o.map(e=>e.id),[o])),[T,E]=u(``),[D,O]=u(null),[k,A]=u(null),j=n(null),M=n(null),P=n(null),F=n(null),I=a(()=>Le(r,T),[r,T]),ee=a(()=>T.trim()===``?e:Kr(e,new Set(I.map(e=>e.addonId))),[e,I,T]),te=e=>I.find(t=>t.addonId===e)?.matchedField??null,ne=a(()=>o.map(qr),[o]),L=e=>o.find(t=>t.nodeId===e.agentNodeId&&t.deviceKey===e.deviceKey),R=o.find(e=>e.id===S.acceleratorId)??null,z=S.stepId!==null,re=t(async e=>{if(m){if(!await b({title:`Discard unsaved changes?`,message:`This step has changes that are not saved yet.`,confirmLabel:`Discard`,variant:`danger`}))return;h()}e()},[b,m,h]),ie=()=>{requestAnimationFrame(()=>F.current?.focus())},ae=(e,t,n=!1)=>{if(e===S.stepId&&(t?.id??null)===S.acceleratorId){n&&ie();return}let r=()=>{O(te(e)),C({stepId:e,...t===void 0?{}:{acceleratorId:t.id}}),n&&ie()};e===S.stepId?r():re(r)},oe=()=>{let e=S.stepId;re(()=>{if(w(),e!==null){let t=R===null?null:vt({agentNodeId:R.nodeId,deviceKey:R.deviceKey});requestAnimationFrame(()=>j.current?.focusCell(e,t))}})},se=e=>{if(e.key===`Enter`){let t=I[0];if(t===void 0)return;e.preventDefault(),ae(t.addonId,void 0,!0)}else e.key===`Escape`&&E(``)},ce=x?d(Be,{onClick:oe}):d(xt,{icon:N,variant:`ghost`,size:`sm`,"aria-label":`Close`,onClick:oe});return i(`div`,{ref:M,className:`space-y-2`,onKeyDown:e=>{let t=e.target instanceof HTMLElement&&e.target.dataset.r!==void 0;e.key===`/`&&t&&(e.preventDefault(),P.current?.focus()),e.key===`Escape`&&t&&z&&(e.preventDefault(),oe())},children:[i(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[d(`div`,{className:`min-w-0 basis-full sm:basis-auto`,children:g}),d(`input`,{ref:P,type:`search`,value:T,onChange:e=>E(e.target.value),onKeyDown:se,placeholder:`Filter steps or settings /`,"aria-label":`Filter steps or settings`,className:`h-9 w-56 rounded-md border border-border bg-background px-2 text-xs text-foreground outline-none focus:border-primary focus:ring-1 focus:ring-primary/30 md:h-7`}),l>0&&i(`label`,{className:`inline-flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[d(Tt,{checked:f,onChange:e=>p(e.target.checked)}),`Show disabled accelerators (`,l,`)`]}),_]}),S.staleStepId!==null&&i(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-1.5 text-[11px] text-warning`,children:[`The link names a step this pipeline does not have (`,S.staleStepId,`).`]}),ee.length===0?i(`p`,{className:`${B} rounded-md border border-dashed border-border px-3 py-4 text-center`,children:[`No step matches “`,T,`”.`]}):d(Ye,{ref:j,tree:ee,agents:ne,label:v,getCellState:(e,t)=>{let n=L(t);return n===void 0?{kind:`na`}:s(e,n)},onCellClick:(e,t,n)=>ae(e,L(t),n),onStepClick:(e,t)=>ae(e,void 0,t),...c===void 0?{}:{stepBadge:c},selectedCell:z&&S.stepId!==null&&R!==null?{addonId:S.stepId,agentNodeId:R.nodeId,deviceKey:R.deviceKey}:null,fallbackNodeId:k,onFallbackNodeChange:A,reserveRightPx:z&&!x?432:0}),d(nt,{open:z,anchor:M,onClose:oe,label:`Step settings`,children:S.stepId!==null&&y({stepId:S.stepId,accelerator:R,matchedField:D,closeButton:ce,onEscape:oe,headingRef:e=>{F.current=e}})})]})}r();function Yr(e){f(()=>{if(e===null)return;let t=document.getElementById(e);t===null||typeof t.scrollIntoView!=`function`||t.scrollIntoView({block:`center`,behavior:`smooth`})},[e])}r();function Xr(e,t){let n=e.filter(e=>e.steps?.[t]?.settings!==void 0),r=e=>e.toSorted((e,t)=>e.key.localeCompare(t.key));return r(n.filter(e=>e.enabled))[0]?.key??r(n)[0]?.key??r(e.filter(e=>e.enabled))[0]?.key??e[0]?.key}function Zr(e,t){let n=t.settings===void 0?void 0:Xr(e,t.stepId),r=e.map(e=>{let r={...e.steps},i=r[t.stepId]??{},a=t.models[e.key],o=t.jumps[e.key],s=e.key===n&&t.settings!==void 0?Object.keys(t.settings).length>0?t.settings:void 0:i.settings,c=a===void 0?i.modelId:a??void 0,l=o===void 0?i.jumpDeviceKey:o||void 0,u={...c===void 0?{}:{modelId:c},...s===void 0?{}:{settings:s},...l===void 0?{}:{jumpDeviceKey:l}};return Object.keys(u).length>0?r[t.stepId]=u:delete r[t.stepId],{key:e.key,enabled:e.enabled,weight:e.weight,maxSessions:e.maxSessions,steps:r}});return n===void 0?r:Er(r,n,t.stepId)}function Qr(e,t,n){if(t===null)return 0;let r=Object.entries(t.models).filter(([n,r])=>(r??void 0)!==e.find(e=>e.key===n)?.steps?.[t.stepId]?.modelId).length,i=Object.entries(t.jumps).filter(([n,r])=>(r||void 0)!==e.find(e=>e.key===n)?.steps?.[t.stepId]?.jumpDeviceKey).length,a=new Set([...Object.keys(n),...Object.keys(t.settings??{})]),o=t.settings===void 0?0:[...a].filter(e=>!je(n[e],t.settings?.[e])).length;return r+i+o}function $r({nodeId:e,nodeName:t,toolbar:n}){let r=c(),s=We({nodeId:e},{refetchOnMount:`always`}),l=an({nodeId:e},{refetchOnMount:`always`}),f=ke(Wt({addonId:`pipeline-orchestrator`}).data??null),p=s.data?.devices??[],m=l.data??null,[h,g]=u(null),[_,v]=u(null),[y,b]=u(null),x=Xe({onSuccess:()=>{r.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`]]})}}),S=a(()=>m?st(m):[],[m]),C=a(()=>Gr(S),[S]),[w,E]=u(!1),D=a(()=>Ir(e,t,p,w),[e,t,p,w]),O=a(()=>Ir(e,t,p),[e,t,p]),k=O.length>=2,A=(e,t)=>(t===void 0?void 0:Dr(p,t.deviceKey,e))??{},j=(e,t,n)=>{let r=n??t.device.steps?.[e?.id??``]?.jumpDeviceKey;if(r!==void 0&&r!==``)return O.find(e=>e.deviceKey===r);if(!Vr(e,t))return O.filter(n=>n.id!==t.id&&Vr(e,n)).toSorted((e,t)=>e.deviceKey.localeCompare(t.deviceKey))[0]},M=(e,t)=>{let n=Nr(m,e),r=Ro(e),i=zr(m,t),a=A(e,t),o=j(n,t);return Hr({addon:n,acc:t,gatedOn:n?.enabledByDefault??!0,model:n?Rr(n,t,{nodePin:t.device.steps?.[e]?.modelId}):{modelId:void 0,source:`default`},...Br(e,a,i)&&i?{rootName:i.name}:{},...r?{clusterModelId:f[e]??r.defaultModelId}:{},...o?{jumpTo:rn(o.device)}:{}})},N=C.map(({node:e})=>({addonId:e.addonId,name:e.addonName,fieldLabels:Wr(Nr(m,e.addonId))}));if(s.isLoading||l.isLoading)return d(`div`,{className:`animate-pulse p-4 text-xs text-foreground-subtle`,children:`Loading pipeline…`});if(m===null)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`Catalog unavailable.`});let P=i(`span`,{className:B,children:[`Accelerators:`,` `,d(`span`,{className:`text-foreground`,children:O.length>0?O.map(e=>rn(e.device)).join(` · `):`none enabled`}),p.some(e=>!e.enabled)&&i(o,{children:[` `,`— off:`,` `,p.filter(e=>!e.enabled).map(rn).join(`, `)]}),` `,`·`,` `,d(hn,{to:Io(),className:`text-primary hover:underline`,children:`Cluster → Load balancing ›`})]});return d(Jr,{tree:S,searchRows:N,accelerators:D,cellState:M,disabledCount:p.filter(e=>!e.enabled).length,showDisabled:w,onShowDisabledChange:E,dirty:h!==null&&Qr(p,h,A(h.stepId,D[0]))>0,onDiscard:()=>g(null),summary:P,...n===void 0?{}:{toolbar:n},label:`Detection steps`,renderDetail:({stepId:n,accelerator:r,matchedField:a,closeButton:s,onEscape:c,headingRef:l})=>{let u=Nr(m,n);if(u===null)return d(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`No step selected.`});let f=h?.stepId===n?h:null,S=r??O[0]??D[0],C=A(n,S),w=f?.settings??C,E=Qr(p,f,C),M=e=>{b(null),g(t=>({...t?.stepId===n?t:{stepId:n,models:{},jumps:{}},...e}))},N=Ro(n),P=Vt(u),F=S===void 0?void 0:zr(m,S),I=e=>{let t=f?.models[e.deviceKey];return t===void 0?e.device.steps?.[n]?.modelId:t??void 0},ee=S===void 0?void 0:Rr(u,S,{nodePin:I(S)}).modelId,te=D.length>1&&D.some(e=>!je(A(n,e),C)),ne=e=>{let t=I(e),r=Rr(u,e,{nodePin:t}),a=zr(m,e),s=Br(n,f?.settings??A(n,e),a),c=f?.jumps[e.deviceKey],l=j(u,e,c),p=Vr(u,e)?s&&a?d(tn,{rootModel:a,stepModelId:r.modelId}):void 0:i(o,{children:[`No `,e.device.format,` build of this step.`,` `,l?`It runs on ${l.shortLabel} instead.`:`It does not run here.`]}),h=k?i(`label`,{className:`block space-y-1`,children:[d(`span`,{className:`text-[11px] font-medium text-foreground`,children:`Run on`}),d(H,{"aria-label":`Run on`,value:c??e.device.steps?.[n]?.jumpDeviceKey??``,options:[{value:``,label:`Auto (this accelerator, or the next one that can run it)`},...O.filter(t=>t.id!==e.id).map(e=>({value:e.deviceKey,label:`${e.label} · ${e.device.format}`}))],onChange:t=>M({jumps:{...f?.jumps,[e.deviceKey]:t.target.value}})}),d(`span`,{className:B,children:`Routes this step (and its child steps) to another accelerator of this node.`})]}):void 0;return{label:e.label,format:e.device.format,modelId:r.modelId,source:r.source===`node`?`node`:`default`,sourceLabel:r.source===`node`?`node pin`:`hardware default`,models:Nt(u.models??[],e.device.format),defaultModelId:u.defaultModelIdByFormat?.[e.device.format]??u.defaultModelId,expanded:_===e.id,onToggle:()=>v(t=>t===e.id?null:e.id),onChangeModel:t=>M({models:{...f?.models,[e.deviceKey]:t}}),...t===void 0?{}:{onReset:()=>M({models:{...f?.models,[e.deviceKey]:null}}),resetLabel:`Reset to hardware default`},...p===void 0?{}:{note:p},...h===void 0?{}:{extra:h},changed:f?.models[e.deviceKey]!==void 0||c!==void 0}},L=()=>{f!==null&&x.mutate({agentNodeId:e,inferenceDevices:Or(Zr(p,f))},{onSuccess:()=>{g(null),b({kind:`saved`})},onError:e=>b({kind:`error`,error:e.message})})};return d(lt,{ref:l,title:r===null?`${u.name} · ${t}`:`${u.name} · ${r.label}`,subtitle:r===null?`${u.slot} · every accelerator of ${t}`:`${u.slot} · ${r.device.format} · base for every camera that lands here`,leading:s,onEscape:c,saveBar:{dirtyCount:E,saving:x.isPending,status:y?.kind??null,...y?.error===void 0?{}:{error:y.error},onSave:L,onDiscard:()=>g(null)},children:i(`div`,{className:`space-y-3`,children:[i(`section`,{className:`space-y-2`,"aria-label":`Model`,children:[d(`h3`,{className:T,children:`Model`}),N!==null&&S!==void 0?d(zo,{step:N,engineFormat:S.device.format,runnableModelIds:Nt(u.models??[],S.device.format).map(e=>e.id)}):D.length===0?i(`p`,{className:B,children:[`No accelerator is enabled on this node —`,` `,d(hn,{to:Io(),className:`text-primary hover:underline`,children:`enable one in Cluster → Load balancing`}),`.`]}):r===null?d(jr,{rows:D.map(e=>{let t=Rr(u,e,{nodePin:I(e)});return{id:e.id,label:e.label,modelId:t.modelId,sourceLabel:t.source===`node`?`node pin`:`hardware default`}})}):d(sn,{...ne(r)},r.id)]}),(P.length>0||F!==void 0)&&N===null&&i(`section`,{"aria-label":`Settings`,className:`space-y-2 border-t border-border/60 pt-2`,children:[i(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`settings-scope`,children:[`Node-wide: these settings apply on every accelerator of `,t,`.`]}),te&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2 py-1 text-[11px] text-warning`,children:`This step's settings differ between this node's accelerators. Saving makes the values shown here node-wide.`}),d(ei,{addon:u,fields:P,settings:w,modelId:Ot(u,ee,w,F),root:F,highlight:a,onChange:e=>M({settings:e})})]}),d(Ar,{addonId:n,highlightLabel:a})]})})}})}function ei({addon:e,fields:t,settings:n,modelId:r,root:i,highlight:a,onChange:o}){let s=t.find(e=>`label`in e&&e.label===a)?.key??null;return Yr(s===null?null:At(s)),d(nn,{addon:e,fields:t,layers:{node:n},target:`node`,labels:{node:`Node`},modelId:r,...i===void 0?{}:{rootModel:i},highlightKey:s,onChangeLayer:o})}r();function ti({nodeId:e,refreshToken:t}){let n=St(),[r,a]=u(null),{nodes:s}=K(),c=s.find(t=>t.id===e)?.name??e,l=Ge({onSuccess:e=>{a(e.effectiveModelId===null?`Reset done — model config cleared (node offline: effective model resolves on reconnect)`:`Reset done — effective detection model: ${e.effectiveModelId} (Auto)`)}}),f=async()=>{await n({title:`Reset ${c} to hardware-aware defaults?`,message:`This clears every per-device model default on this node (back to the format default) and every per-camera step override scoped to it. Existing per-camera customisations on this node are lost.`,confirmLabel:`Reset`,variant:`danger`})&&(a(null),l.mutate({agentNodeId:e}))};return i(`div`,{className:`space-y-2`,children:[d(Tr,{nodeId:e}),d($r,{nodeId:e,nodeName:c,toolbar:i(o,{children:[r&&d(`span`,{className:`text-[11px] text-success`,children:r}),l.isError&&d(`span`,{className:`text-[11px] text-danger`,children:l.error instanceof Error?l.error.message:`Reset failed`}),d(V,{variant:`outline`,size:`sm`,onClick:()=>{f()},disabled:l.isPending,title:`Clear this node's per-device model defaults + per-camera overrides scoped to this node`,children:l.isPending?`Resetting…`:`Reset to default`})]})})]})}var ni=[`detection-pipeline`,`audio-analyzer`,`pipeline-runner`],ri=`decoder-nodeav`,ii=`ntab`,ai={decoder:`engine`},oi={engine:`Engine & decoder`},si=`Nothing here is set per node. Cluster-wide values are on Cluster → Settings.`;function ci({nodeId:e,refreshToken:t}){let[n,r]=mn(),{nodes:a}=K(),o=a.find(t=>t.id===e)?.addons.find(e=>e.capabilities.includes(`decoder`))?.addonId??ri,s=[...ni,o],c=n.get(ii),l={assignments:{id:`assignments`,label:`Assignments`,order:-10,content:d(yr,{nodeId:e,refreshToken:t})},tree:{id:`tree`,label:`Pipeline`,order:39,content:d(ti,{nodeId:e,refreshToken:t})},engines:{id:`engines`,label:`Warm instances`,order:180,content:d(xr,{nodeId:e,refreshToken:t})},logs:{id:`logs`,label:`Logs`,order:300,content:d(wr,{nodeId:e})}},u=Hn.map(e=>l[e]);return i(`div`,{className:`flex flex-col h-full`,children:[d(Vn,{nodeId:e,refreshToken:t}),d(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 sm:p-6`,children:d(gn,{nodeId:e,addonIds:s,level:`global`,fieldScope:`perNode`,emptyMessage:si,tabAliases:ai,tabLabelOverrides:oi,extraTabs:u,activeTab:c===null?null:ai[c]??c,onActiveTabChange:e=>r(t=>{let n=new URLSearchParams(t);n.set(ii,e);for(let e of jn)n.delete(e);return n},{replace:!0})})})]})}function li(){return i(`div`,{className:`space-y-2`,children:[i(`div`,{className:`min-w-0`,children:[d(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Camera placement`}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Pin a camera to a node, or to one accelerator of its node; Auto lets each session pick. Decode always runs with detection. Load, shares and caps are on Load balancing.`})]}),d(_r,{})]})}function ui(e){return`${Math.round(e*100)}%`}function di(e){return`${e} session${e===1?``:`s`}`}var fi={"intel-npu":`Intel NPU`,"intel-igpu":`Intel iGPU`,"amd-igpu":`AMD iGPU (WebGPU)`,"amd-npu":`AMD XDNA NPU`,"x86-cpu":`CPU`,"arm-cpu":`CPU`,"apple-ane":`Apple Neural Engine`,coral:`Coral Edge TPU`},pi={"intel-core-ultra":`Intel Core Ultra`,"intel-n-series":`Intel N-series`,"apple-m-base":`Apple M (base)`,"apple-m-pro":`Apple M Pro / Max / Ultra`,"amd-phoenix":`AMD Ryzen Phoenix / Hawk Point`,unknown:`Not measured`};function mi(e){return e===null?`—`:fi[e]??e}function hi(e){return e===null?`—`:pi[e]??e}function gi(e){switch(e.kind){case`capacity`:return`Capacity ${di(e.sessions)} ≥ min ${e.minSessions}.`;case`tie-faster`:return`As accurate as ${e.over} (within ${ui(e.recallDelta)} recall) and faster.`;case`stepped-down`:return`${e.from} would not fit the load on ${e.limitedBy}; ${e.to} is the most accurate that does.`;case`no-fit-lightest`:return`No model reaches ${di(e.minSessions)} per device; the one with the most capacity (${di(e.sessions)}) is used.`;case`derived-latency`:return`${e.modelId}: latency estimated from a similar chip, not measured on this one.`;case`cpu-device`:return`CPU fallback device: picked on its own.`;case`coral-untouched`:return`Coral: left as is (no YOLOv9 build exists for it).`;case`device-disabled`:return`Disabled: not changed.`;case`device-unavailable`:return`Not available on the node right now: not changed.`;case`node-offline`:return`Node offline: nothing on it will change.`;case`no-hardware-facts`:return`Hardware could not be read: nothing on this node will change.`;case`no-measured-data`:return`This hardware has no measured data: nothing on this node will change.`;case`no-family-build`:return`No YOLOv9 build for the ${e.format} format: not changed.`;case`kept-custom-pin`:return`Custom model ${e.modelId} is pinned on ${e.deviceKey}: Auto tune skips this device.`}}function _i(e,t){switch(e.kind){case`detector-store-cluster-wide`:return`Per-camera detector thresholds are not tied to a node, so they are cleared for every camera — including cameras that run on skipped nodes (${e.skippedNodes.map(t).join(`, `)}).`;case`detector-store-unreadable`:return`Per-camera detector thresholds could not be read (${e.error}); those will not be cleared.`;case`coral-enabled`:return`${t(e.nodeId)}: the Coral (${e.deviceKey}) is enabled and keeps running its SSD model, which finds far fewer people than YOLOv9. Consider disabling it.`;case`custom-pin-kept`:return e.deviceId===null?`${t(e.nodeId)}: custom model ${e.modelId} pinned on ${e.deviceKey??`—`} — Auto tune skips this node device.`:`Camera ${e.deviceId} pins custom model ${e.modelId} on ${t(e.nodeId)} — Auto tune keeps that override and its thresholds.`;case`custom-registry-unreadable`:return`The custom-model registry could not be read (${e.error}): every pin to a model outside the measured catalog is kept.`}}function vi(e){let t=e.nodeChanges.reduce((e,t)=>e+t.modelPins.length,0),n=e.nodeChanges.reduce((e,t)=>e+t.thresholds.length,0),r=new Set([...e.cameraClears.map(e=>e.deviceId),...e.detectorStoreClears.map(e=>e.deviceId)]);return{modelChanges:t,thresholdClears:n,cameraOverrideClears:e.cameraClears.length,detectorStoreClears:e.detectorStoreClears.length,camerasTouched:r.size}}function yi(e){let t=vi(e);return t.modelChanges+t.thresholdClears+t.cameraOverrideClears+t.detectorStoreClears===0}function bi(e,t,n){let r=e.nodeChanges.find(e=>e.nodeId===t&&e.deviceKey===n)?.modelPins.find(e=>e.stepId===`object-detection`);return r===void 0?null:{before:r.before,after:r.after}}function xi(e,t){return e?.kind===`node-benchmark`?`measured on this node, ${new Date(e.measuredAtMs).toLocaleDateString(t,{day:`numeric`,month:`short`})}`:`from the latency table — benchmark this node to measure it`}r();var Si=[.3,.4,.5];function Ci(e){return Si.some(t=>t===e)}var wi=[1,2,3,4,6,8];function Ti({plan:e,node:t,nodeName:n}){return i(`section`,{className:x,"data-testid":`auto-tune-node-${t.nodeId}`,children:[i(`header`,{className:`${F} flex flex-wrap items-center gap-2`,children:[d(g,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`,"aria-hidden":!0}),d(`h3`,{className:`${T} min-w-0 flex-1`,children:n(t.nodeId)}),i(`span`,{className:`text-[11px] text-foreground-subtle`,children:[hi(t.hardwareClass),t.cpuModel===null?``:` · ${t.cpuModel}`]}),t.skipped?d(G,{variant:`warning`,children:`Not changed`}):t.acceleratorModelId!==null&&d(G,{variant:`info`,children:t.acceleratorModelId})]}),t.reasons.length>0&&d(`ul`,{className:`px-3 pt-2 text-[11px] text-foreground-muted`,children:t.reasons.map((e,t)=>d(`li`,{children:gi(e)},t))}),d(`div`,{className:`overflow-x-auto`,children:i(`table`,{className:`w-full text-xs`,children:[d(`thead`,{children:i(`tr`,{className:`text-left text-[11px] text-foreground-subtle`,children:[d(`th`,{className:`px-3 py-1.5 font-medium`,children:`Device`}),d(`th`,{className:`px-3 py-1.5 font-medium`,children:`Capacity`}),d(`th`,{className:`px-3 py-1.5 font-medium`,children:`Detector`}),d(`th`,{className:`px-3 py-1.5 font-medium`,children:`Why`})]})}),d(`tbody`,{children:t.devices.map(n=>{let r=bi(e,t.nodeId,n.deviceKey);return i(`tr`,{className:`border-t border-border align-top`,children:[i(`td`,{className:`px-3 py-1.5`,children:[d(`div`,{className:`font-mono text-foreground`,children:n.deviceKey}),d(`div`,{className:`text-[11px] text-foreground-subtle`,children:mi(n.accelerator)})]}),i(`td`,{className:`px-3 py-1.5 text-foreground-muted`,children:[n.chosen===null?`—`:`${n.chosen.capacitySessions} session${n.chosen.capacitySessions===1?``:`s`} at ${e.cameraFps} fps`,n.chosen!==null&&i(`div`,{className:`text-[11px] text-foreground-subtle`,children:[n.chosen.fps,` fps, `,Math.round(e.headroom*100),`% kept free`,d(`div`,{children:xi(n.chosen.source)})]})]}),d(`td`,{className:`px-3 py-1.5`,children:n.chosen===null?d(`span`,{className:`text-foreground-subtle`,children:`unchanged`}):r!==null&&r.before!==r.after?i(`span`,{children:[d(`span`,{className:`text-foreground-subtle`,children:r.before??`default`}),` → `,d(`span`,{className:`font-medium text-foreground`,children:r.after})]}):d(`span`,{className:`text-foreground`,children:n.chosen.modelId})}),d(`td`,{className:`px-3 py-1.5 text-[11px] text-foreground-muted`,children:n.reasons.map((e,t)=>d(`div`,{children:gi(e)},t))})]},n.deviceKey)})})]})})]})}function Ei({plan:e,nameOf:t,nodeName:n}){return i(`div`,{className:`flex flex-col gap-3 text-xs`,"data-testid":`auto-tune-change-list`,children:[i(`div`,{children:[d(`div`,{className:T,children:`Node settings`}),e.nodeChanges.length===0?d(`div`,{className:`text-foreground-subtle`,children:`No change.`}):d(`ul`,{className:`mt-1 flex flex-col gap-0.5`,children:e.nodeChanges.flatMap(e=>[...e.modelPins.map(t=>i(`li`,{children:[i(`span`,{className:`font-mono`,children:[n(e.nodeId),` · `,e.deviceKey]}),` `,`— `,t.stepId,`: `,t.before??`default`,` → `,t.after??`step default`]},`${e.nodeId}/${e.deviceKey}/${t.stepId}/pin`)),...e.thresholds.map(t=>i(`li`,{children:[i(`span`,{className:`font-mono`,children:[n(e.nodeId),` · `,e.deviceKey]}),` `,`— `,t.stepId,`: reset `,t.keys.join(`, `),` to the model default`]},`${e.nodeId}/${e.deviceKey}/${t.stepId}/thr`))])})]}),i(`div`,{children:[d(`div`,{className:T,children:`Camera overrides cleared`}),e.cameraClears.length===0&&e.detectorStoreClears.length===0?d(`div`,{className:`text-foreground-subtle`,children:`None.`}):i(`ul`,{className:`mt-1 flex flex-col gap-0.5`,children:[e.cameraClears.map((e,r)=>i(`li`,{children:[t(e.deviceId),` — `,n(e.nodeId),e.deviceKey===null?` (whole pipeline)`:` · ${e.deviceKey}`,` — `,e.stepId,e.modelIdBefore===null?``:`: model ${e.modelIdBefore} removed`,e.keys.length>0?`; ${e.keys.join(`, `)} reset`:``]},`c${r}`)),e.detectorStoreClears.map(e=>i(`li`,{children:[t(e.deviceId),` — detector thresholds: `,e.keys.join(`, `),` reset`]},`d${e.deviceId}`))]})]})]})}function Di({result:e}){return e.kind===`refused`?d(`div`,{className:`text-xs text-warning`,children:`Another apply is already running.`}):e.kind===`stale`?d(`div`,{className:`text-xs text-warning`,children:`The configuration changed since the plan was shown. Review the updated plan below and apply again.`}):i(`ul`,{className:`text-xs`,"data-testid":`auto-tune-result`,children:[e.kind===`aborted`&&d(`li`,{className:`text-danger`,children:`A model could not be downloaded: nothing was changed.`}),e.phases.map(e=>i(`li`,{className:e.ok?`text-foreground-muted`:`text-danger`,children:[e.ok?`✓`:`✗`,` `,e.phase,`: `,e.detail]},e.phase))]})}function Oi(){let e=c(),[t,n]=u(.4),[r,o]=u(2),[s,l]=u(!1),[f,p]=u(!1),[m,h]=u(null),{data:g}=pn(),_=a(()=>new Map((g??[]).map(e=>[e.id,e.name])),[g]),v=e=>_.get(e)??`Camera ${e}`,{nodes:y}=K(),b=a(()=>Xn(y),[y]),S=qe({headroom:t,minSessionsPerDevice:r},{enabled:s,refetchOnWindowFocus:!1}),C=un({onSuccess:t=>{h(t),p(!1),e.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`]]}),e.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]}),e.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),t.kind===`applied`&&S.refetch()}}),w=m?.kind===`stale`?m.plan:S.data,D=w===void 0?null:vi(w);return i(`div`,{className:`flex flex-col gap-3`,"data-testid":`cluster-auto-tune`,children:[i(`section`,{className:x,children:[i(`header`,{className:`${F} flex flex-wrap items-center gap-2`,children:[d(E,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`,"aria-hidden":!0}),d(`h3`,{className:`${T} min-w-0 flex-1`,children:`Auto tune`})]}),i(`div`,{className:`flex flex-col gap-2 px-3 py-2 text-xs text-foreground-muted`,children:[d(`p`,{children:`Picks, for every accelerator, the most accurate YOLOv9 detector that still carries at least the chosen number of cameras at once, from the node's hardware and measured speeds. Nothing is measured or estimated about your cameras' activity. Applying it sets those models and clears every model and threshold override — node level and per camera — so each model runs its own default thresholds. Enabled steps, devices, pins, recording, notifications, zones and rules are not touched. There is no undo.`}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(`label`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`whitespace-nowrap`,children:`Keep free`}),d(H,{"aria-label":`Share of each accelerator kept free`,value:String(t),options:Si.map(e=>({value:String(e),label:`${Math.round(e*100)}% of each accelerator`})),onChange:e=>{let t=Number(e.target.value);Ci(t)&&n(t)}})]}),i(`label`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`whitespace-nowrap`,children:`At least`}),d(H,{"aria-label":`Minimum parallel sessions per device`,value:String(r),options:wi.map(e=>({value:String(e),label:`${e} camera${e===1?``:`s`} at once per accelerator`})),onChange:e=>{let t=Number(e.target.value);wi.some(e=>e===t)&&o(t)}})]}),d(V,{size:`sm`,variant:`secondary`,onClick:()=>{h(null),l(!0),s&&S.refetch()},children:S.isFetching?`Computing…`:w===void 0?`Compute plan`:`Recompute`}),w!==void 0&&d(V,{size:`sm`,disabled:yi(w),onClick:()=>p(!0),children:`Apply…`})]}),S.error!==null&&d(`div`,{className:`text-danger`,children:S.error.message}),m!==null&&d(Di,{result:m}),D!==null&&i(`div`,{className:`text-[11px] text-foreground-subtle`,children:[D.modelChanges,` model change(s), `,D.thresholdClears,` node threshold reset(s), `,D.cameraOverrideClears+D.detectorStoreClears,` camera override(s) on `,D.camerasTouched,` camera(s).`]})]})]}),w?.warnings.map((e,t)=>d(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,children:_i(e,b)},t)),w?.nodes.map(e=>d(Ti,{plan:w,node:e,nodeName:b},e.nodeId)),w!==void 0&&d(ut,{open:f,onOpenChange:p,children:i(ze,{width:`lg`,scroll:`body`,children:[i(Fe,{children:[d(Rt,{children:`Apply auto tune?`}),d(rt,{children:`These are all the changes. Every override listed is removed and cannot be restored.`})]}),d(Ve,{children:d(Ei,{plan:w,nameOf:v,nodeName:b})}),i(zt,{children:[d(V,{variant:`ghost`,onClick:()=>p(!1),children:`Cancel`}),d(V,{variant:`danger`,disabled:C.isPending,onClick:()=>C.mutate({planHash:w.planHash,headroom:t,minSessionsPerDevice:r}),children:C.isPending?`Applying…`:`Apply`})]})]})})]})}var ki={disabled:`switched off — not a dispatch target`,unavailable:`the node probe does not see it (unplugged or still provisioning)`,"cannot-host-camera-root":`its engine format has no object-detection root model`,"accelerator-preferred":`CPU fallback — it never competes while an accelerator is serving`};function Ai(e,t){return t<=0?0:Math.round(e/t*1e3)/10}function ji(e){return e===void 0?!1:e.load.devices.reduce((e,t)=>e+t.attachedCameras,0)>=e.load.attachedCameras}function Mi(e,t,n){let r=e.filter(e=>e.exclusion===null).reduce((e,t)=>e+(t.weight>0?t.weight:1),0);return e.map(e=>{let i=t.get(e.key)??(n?0:null),a=e.weight>0?e.weight:1;return{key:e.key,label:W(e),format:e.format,sessions:i,weight:a,weightSharePct:e.exclusion===null?Ai(a,r):null,maxSessions:e.maxSessions,atCap:e.maxSessions!==null&&i!==null&&i>=e.maxSessions,available:e.available,enabled:e.enabled,exclusion:e.exclusion}}).toSorted((e,t)=>e.exclusion===null==(t.exclusion===null)?e.key.localeCompare(t.key):e.exclusion===null?-1:1)}function Ni(e){let t=new Map(e.loads.map(e=>[e.nodeId,e])),n=e.nodes.filter(e=>e.isOnline&&e.detectEnabled).reduce((e,t)=>e+(t.weight>0?t.weight:1),0);return e.nodes.map(r=>{let i=t.get(r.id),a=Mi(e.devicesByNode[r.id]??[],new Map((i?.load.devices??[]).map(e=>[e.deviceKey,e.attachedCameras])),ji(i)),o=r.isOnline&&r.detectEnabled,s=r.weight>0?r.weight:1,c=i?.load.attachedCameras??null;return{nodeId:r.id,name:r.name,isOnline:r.isOnline,detectEnabled:r.detectEnabled,reported:i!==void 0,attachedCameras:c,activeCameras:i?.load.activeCameras??null,maxCameras:r.maxCameras,capacityPct:c!==null&&r.maxCameras!==null&&r.maxCameras>0?Ai(c,r.maxCameras):null,queueDepthTotal:i?.load.queueDepthTotal??null,avgInferenceTimeMs:i?.load.avgInferenceTimeMs??null,score:i?.score??null,weight:s,weightSharePct:o?Ai(s,n):null,decodeHwaccel:i?.decodeHwaccel??null,devices:a,eligibleDeviceCount:a.filter(e=>e.exclusion===null).length}})}r();var Pi=2e4,Fi=3e5;function Ii({stats:e,targetWeights:t}){let{nodes:n}=K(),r=te().trpcClient,o=ln(void 0,{placeholderData:l,staleTime:Pi,refetchInterval:Pi,refetchOnWindowFocus:!0}),c=ht(void 0,{staleTime:Fi}),u=a(()=>n.map(e=>e.id),[n]),f=s({queries:u.map(e=>({queryKey:Pe(Mt.pipelineOrchestrator.getNodeInferenceDevices,{nodeId:e},`query`),queryFn:()=>r.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:e}),staleTime:Fi,refetchOnWindowFocus:!1,placeholderData:l}))}),p=a(()=>{let e={};return u.forEach((t,n)=>{let r=f[n]?.data;r&&(e[t]=r.devices)}),e},[u,f.map(e=>e.dataUpdatedAt).join(`|`)]),h=a(()=>{let e=new Map;for(let t of c.data??[])e.set(t.nodeId,t.settings);return e},[c.data]),g=a(()=>n.map(e=>{let n=h.get(e.id);return{id:e.id,name:e.name,isOnline:e.isOnline,detectEnabled:Rn(n,e.isHub).pipeline,weight:t?.[e.id]??yn(n,`detectWeight`)??1,maxCameras:yn(n,`maxCameras`)}}),[n,h,t]),_=o.data??[],v=a(()=>Ni({nodes:g,loads:_,devicesByNode:p}),[g,_,p]),y=v.reduce((e,t)=>e+(t.attachedCameras??0),0),b=v.reduce((e,t)=>e+(t.activeCameras??0),0),x=o.dataUpdatedAt>0?Date.now()-o.dataUpdatedAt:null,C=new Map((e?.nodes??[]).map(e=>[e.nodeId,e]));return d(U,{headingId:`load-balancing-node-load`,title:`Node load`,icon:S,actions:i(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums`,children:[b,` running · `,y,` attached ·`,` `,o.data===void 0?`reading…`:`${x===null?`—`:`${Math.round(x/1e3)}s`} old`]}),children:d(`div`,{className:m,children:v.length===0?d(`p`,{className:`text-[11px] italic text-foreground-subtle`,children:`No cluster nodes reported yet.`}):d(`div`,{className:`grid gap-2 @2xl/clustertab:grid-cols-2 @5xl/clustertab:grid-cols-3`,children:v.map(e=>d(Li,{row:e,placed:C.get(e.nodeId)},e.nodeId))})})})}function Li({row:e,placed:t}){let n=e.attachedCameras===null?`—`:`${e.activeCameras??0} / ${e.attachedCameras}${e.maxCameras===null?``:` of ${e.maxCameras}`}`;return i(`div`,{className:`rounded-lg border border-border bg-surface/60 p-2.5 min-w-0`,children:[i(`div`,{className:`flex items-center gap-1.5 min-w-0`,children:[d(`span`,{className:`h-1.5 w-1.5 shrink-0 rounded-full ${e.isOnline?`bg-emerald-400`:`bg-foreground-subtle/40`}`}),d(`span`,{className:`truncate text-xs font-medium text-foreground`,title:e.nodeId,children:e.name}),!e.detectEnabled&&d(`span`,{className:`shrink-0 rounded bg-surface-hover px-1 text-[9px] uppercase tracking-wide text-foreground-subtle`,children:`no detect`}),!e.reported&&e.isOnline&&i(`span`,{className:`ml-auto inline-flex shrink-0 items-center gap-1 text-[9px] text-amber-400`,title:`Online, but it did not answer the last load read — its numbers below are unknown, not zero.`,children:[d(b,{className:`h-2.5 w-2.5`}),` no reading`]}),!e.isOnline&&i(`span`,{className:`ml-auto inline-flex shrink-0 items-center gap-1 text-[9px] text-foreground-subtle`,children:[d(k,{className:`h-2.5 w-2.5`}),` offline`]})]}),i(`dl`,{className:`mt-1.5 grid grid-cols-2 gap-x-2 gap-y-0.5 text-[10px]`,children:[d(J,{label:`Running / attached`,value:n,title:`Sessions in inference now / cameras attached to this runner (the balancer's committed load) / operator cap.`}),d(J,{label:`Target share`,value:e.weightSharePct===null?`out of play`:`${e.weightSharePct}%`,title:`The node share (automatic or manual) normalised over the nodes the balancer actually ranks (online AND detect-enabled).`}),d(J,{label:`Actual share (1 h)`,value:t?.observedShare===null||t===void 0?`—`:`${Math.round(t.observedShare*100)}%`,title:`Time-weighted share of the cluster's PARALLEL detection sessions this node carried over the last hour — the quantity a share holds. '—' = no session ran here in the window.`}),d(J,{label:`Peak · yields`,value:t===void 0?`—`:`${t.peakSessions} · ${t.yieldsAway}`,title:`Most sessions this node ran at once in the last hour, and how many share turns it handed to another node because it was full or drowning.`}),d(J,{label:`Score · queue`,value:e.score===null?`—`:`${e.score} · ${e.queueDepthTotal??0}`,title:`The capacity score balance() minimises (attached + queue depth), and the raw queue depth.`}),e.capacityPct!==null&&d(J,{label:`Cap fill`,value:`${e.capacityPct}%`,title:`attached / maxCameras.`}),e.avgInferenceTimeMs!==null&&d(J,{label:`Avg infer`,value:`${Math.round(e.avgInferenceTimeMs)} ms`,title:`Mean inference time across this node's attached cameras.`}),e.decodeHwaccel!==null&&d(J,{label:`Decode`,value:e.decodeHwaccel,title:`This node's probed decode hwaccel.`})]}),d(Ri,{row:e})]})}function Ri({row:e}){return e.devices.length===0?d(`p`,{className:`mt-2 text-[10px] italic text-foreground-subtle`,children:`Accelerators not read yet.`}):i(`div`,{className:`mt-2 border-t border-border pt-1.5`,children:[i(`div`,{className:`flex items-center gap-1 text-[9px] uppercase tracking-wider text-foreground-subtle`,children:[d(w,{className:`h-2.5 w-2.5`}),`Accelerators`,e.eligibleDeviceCount===0&&d(`span`,{className:`ml-1 normal-case tracking-normal text-amber-400`,title:`No device is a camera-root candidate on this node — sessions run on the runner's default (CPU) pool.`,children:`none in play · runner default pool`})]}),d(`ul`,{className:`mt-1 space-y-0.5`,children:e.devices.map(e=>d(zi,{device:e},e.key))})]})}function zi({device:e}){let t=e.exclusion;return i(`li`,{className:`flex items-baseline gap-1.5 text-[10px] min-w-0`,children:[d(g,{className:`h-2.5 w-2.5 shrink-0 ${t===null?`text-foreground-subtle`:`text-foreground-subtle/50`}`}),d(`span`,{className:`shrink-0 font-medium ${t===null?`text-foreground`:`text-foreground-subtle`}`,title:`${e.key} · ${e.format}`,children:e.label}),t===null?i(o,{children:[i(`span`,{className:`shrink-0 tabular-nums text-foreground-subtle`,children:[e.weightSharePct,`% share`]}),i(`span`,{className:`shrink-0 tabular-nums text-foreground-subtle`,title:e.sessions===null?`Not known: the node did not report, or runs a session no device accounts for.`:void 0,children:[`· `,e.sessions??`—`,` session`,e.sessions===1?``:`s`,e.maxSessions===null?``:`/${e.maxSessions}`]}),e.atCap&&d(`span`,{className:`shrink-0 text-amber-400`,title:`At its maxSessions cap — the balancer skips it until a session ends.`,children:`· at cap`})]}):i(`span`,{className:`truncate text-foreground-subtle/80`,title:ki[t],children:[`excluded — `,ki[t]]})]})}function J({label:e,value:t,title:n}){return i(`div`,{className:`min-w-0`,title:n,children:[d(`dt`,{className:`text-[9px] uppercase tracking-wide text-foreground-subtle`,children:e}),d(`dd`,{className:`truncate font-medium tabular-nums text-foreground`,children:t})]})}function Bi(e){return{nodes:Object.fromEntries(e.map(e=>[e.nodeId,Math.max(1,e.weight)])),devices:{}}}function Vi(e){let t={},n={};for(let r of e.nodes){if(r.share===null||r.share<=0)continue;t[r.nodeId]=r.share;let e=Object.fromEntries(r.devices.filter(e=>e.share>0).map(e=>[e.deviceKey,e.share]));Object.keys(e).length>0&&(n[r.nodeId]=e)}return{nodes:t,devices:n}}function Hi(e){return Object.fromEntries(e.nodes.map(e=>[e.nodeId,Object.fromEntries(e.devices.map(e=>[e.deviceKey,e.suggestedMaxSessions]))]))}function Ui(e){return e.reason===`disabled`?`${e.deviceKey} is not enabled on any node — sessions ignore this pin`:`no node offers ${e.deviceKey} — sessions ignore this pin`}function Wi(e,t){if(t===void 0||t.source===`manual`||t.autoPending)return{nodes:e,readOnly:t!==void 0&&t.source!==`manual`};let n=new Map(t.nodes.map(e=>[e.nodeId,e.configuredPct]));return{nodes:e.map(e=>({...e,weight:Math.round(n.get(e.id)??e.weight)})),readOnly:!0}}function Gi(e,t){let n=e.nodes.filter(e=>!e.eligible);if(n.length===0)return null;let r=e.nodes.filter(e=>e.eligible).map(e=>`${t(e.nodeId)} ${Math.round(e.effectivePct)}%`).join(`, `);return`${n.map(e=>t(e.nodeId)).join(`, `)} cannot take sessions — ${n.length===1?`its share goes`:`their shares go`} to the others: ${r}`}var Ki=[{value:`hardware`,label:`Hardware`,hint:`Each node’s share follows what its accelerators can carry at their Auto tune models, from the measured speed of its hardware. No load is measured or estimated.`},{value:`benchmark`,label:`Benchmark`,hint:`Each node’s share follows its own node-benchmark results. A node without results uses its hardware capacity instead, and says so.`},{value:`manual`,label:`Manual`,hint:`The sliders below, as you set them.`}];function qi(e){return e===`no-benchmark-results`?`no benchmark results yet — sized from hardware`:e===`partial-benchmark-results`?`benchmark results miss some of its accelerators — sized from hardware`:null}function Ji(e,t){if(e.source!==`benchmark`)return null;let n=e.nodes.filter(e=>e.capacityFallback!==null);return n.length===0?null:n.map(e=>`${t(e.nodeId)}: ${qi(e.capacityFallback)??``}`).join(` · `)}r();function Yi(e,t,n){return Math.min(Math.max(e,t),n)}function Xi(e){let t=e.reduce((e,t)=>e+Math.max(t.weight,0),0);if(t<=0){let t=e.length>0?100/e.length:0;return Object.fromEntries(e.map(e=>[e.id,t]))}return Object.fromEntries(e.map(e=>[e.id,Math.max(e.weight,0)/t*100]))}function Zi(e,t,n,r,i){let a=i.filter(e=>e!==t&&r.has(e)).reduce((t,n)=>t+Math.max(e[n]??0,0),0),o=Math.max(0,100-a),s=i.filter(e=>e!==t&&!r.has(e)),c=s.length===0?o:Yi(n,0,o),l={...e,[t]:c};if(s.length>0){let e=Math.max(0,o-c)/s.length;for(let t of s)l[t]=e}return l}function Qi(e,t,n){let r={},i=0,a=[];for(let o of t){let t=Math.max(e[o]??0,0);if(n.has(o)){let e=Math.round(t);r[o]=e,i+=e}else{let e=Math.floor(t);r[o]=e,a.push({id:o,floor:e,frac:t-e})}}let o=Math.max(0,100-i)-a.reduce((e,t)=>e+t.floor,0),s=[...a].sort((e,t)=>t.frac-e.frac);for(let e=0;o>0&&s.length>0;e+=1)r[s[e%s.length].id]+=1,--o;let c=[...a].sort((e,t)=>e.frac-t.frac);for(let e=0;o<0&&c.length>0;e+=1){let t=c[e%c.length].id;r[t]>0&&(--r[t],o+=1)}return r}function $i({nodes:e,pending:t,onCommitWeights:n,weightLabel:r=`Detection weight`,emptyHint:a,footnote:s,readOnly:c=!1}){let[l,p]=u(()=>Xi(e)),[m,h]=u(new Set);f(()=>{p(Xi(e)),h(t=>new Set([...t].filter(t=>e.some(e=>e.id===t))))},[e.map(e=>`${e.id}:${e.weight}`).join(`|`)]);let g=e.map(e=>e.id),_=e=>{h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},v=(e,t)=>{p(n=>Zi(n,e,t,m,g))},y=()=>{let t=Qi(l,g,m),r=e.filter(e=>(t[e.id]??0)!==e.weight).map(e=>e.id);if(r.length===0)return;let i=new Set([...r,...m]);n(e.filter(e=>i.has(e.id)).map(e=>({nodeId:e.id,weight:t[e.id]??0})))};if(e.length===0)return d(`p`,{className:`rounded-lg border border-dashed border-border bg-background px-4 py-6 text-center text-xs text-foreground-subtle`,children:a??`No detect-enabled nodes. Enable “Detect” on a node above to distribute detection weight.`});let b=e.length===1;return i(`div`,{className:`space-y-3`,children:[e.map(e=>{let n=l[e.id]??0,a=m.has(e.id);return i(`div`,{className:`flex items-center gap-3`,children:[d(`span`,{className:`w-28 shrink-0 truncate text-xs font-medium text-foreground`,title:e.name,children:e.name}),d(`input`,{"aria-label":`${r} for ${e.name}`,type:`range`,min:0,max:100,step:1,value:Math.round(n),disabled:c||t||a||b,onChange:t=>v(e.id,Number(t.target.value)),onPointerUp:()=>y(),onKeyUp:()=>y(),className:`h-1.5 flex-1 cursor-pointer accent-primary disabled:cursor-not-allowed disabled:opacity-50`}),i(`span`,{className:`w-10 shrink-0 text-right font-mono text-xs tabular-nums text-foreground`,children:[Math.round(n),`%`]}),!c&&d(`button`,{type:`button`,onClick:()=>_(e.id),disabled:t||b,"aria-pressed":a,title:a?`Unlock — allow rebalancing`:`Lock this share when others change`,className:`shrink-0 rounded p-1 hover:bg-surface-hover disabled:opacity-40 ${a?`text-amber-400`:`text-foreground-subtle`}`,children:d(a?ee:L,{className:`h-3.5 w-3.5`})})]},e.id)}),d(`p`,{className:`text-[10px] leading-tight text-foreground-subtle`,children:s??d(o,{children:`Dragging one slider splits the rest equally across the unlocked nodes; lock a node to pin its share — locked nodes never move and the total always stays at 100%, so a drag is bounded by the room the unlocked nodes leave. Detection only distributes across nodes that can source a camera’s frames.`})})]})}function ea(e){let t=e.steps?.[`object-detection`]?.modelId;return typeof t==`string`&&t.length>0?t:typeof e.defaultModelId==`string`&&e.defaultModelId.length>0?e.defaultModelId:null}r();function ta(e){let t=W(e),n=e.backend.toLowerCase(),r=e.device.toLowerCase();return e.key===`cpu`||r===`cpu`?{label:t,Icon:g,hue:`slate`}:r===`npu`?{label:t,Icon:re,hue:`sky`}:r===`gpu`||r===`igpu`?{label:t,Icon:de,hue:`violet`}:n===`edgetpu`?{label:t,Icon:he,hue:`emerald`}:{label:t,Icon:g,hue:`slate`}}var na={sky:`bg-sky-500/12 text-sky-400 ring-sky-500/25`,violet:`bg-violet-500/12 text-violet-400 ring-violet-500/25`,emerald:`bg-emerald-500/12 text-emerald-400 ring-emerald-500/25`,slate:`bg-surface-hover text-foreground-subtle ring-border`};function ra({nodeId:e,nodeName:t,isOnline:n,suggestedMaxSessions:r,autoDeviceShares:s}){let l=c(),{data:p,isLoading:m}=We({nodeId:e},{refetchInterval:15e3}),h=Xe({onSettled:()=>{l.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`]]})}}),g=p?.devices??[],_=p?.reachable??n,[v,y]=u({});f(()=>{y(Object.fromEntries(g.map(e=>[e.key,{enabled:e.enabled,weight:e.weight,maxSessions:e.maxSessions,steps:e.steps??{}}])))},[g.map(e=>`${e.key}:${e.enabled}:${e.weight}:${e.maxSessions}:${JSON.stringify(e.steps??{})}`).join(`|`)]);let b=a(()=>g.filter(e=>v[e.key]?.enabled??e.enabled).length,[g,v]),[x,S]=u(null),C=x??b>0,w=t=>{let n=g.map(e=>{let n=t[e.key]??T(e);return{key:e.key,enabled:n.enabled,weight:n.weight,maxSessions:n.maxSessions,steps:n.steps}});h.mutate({agentNodeId:e,inferenceDevices:Or(n)})},T=e=>({enabled:e.enabled,weight:e.weight,maxSessions:e.maxSessions,steps:e.steps??{}}),E=e=>{if(!e.available)return;let t=v[e.key]??T(e),n={...v,[e.key]:{...t,enabled:!t.enabled}};y(n),w(n)},D=(e,t)=>{let n=v[e.key]??T(e),r={...v,[e.key]:{...n,maxSessions:t}};y(r),w(r)},A=a(()=>g.filter(e=>(v[e.key]?.enabled??e.enabled)&&e.available),[g,v]),j=a(()=>A.map(e=>({id:e.key,name:ta(e).label,weight:s===void 0?v[e.key]?.weight??e.weight:Math.round(s[e.key]??0)})),[A,v,s]);return i(`div`,{className:`rounded-lg border border-border bg-surface/60`,children:[i(`button`,{type:`button`,onClick:()=>S(!C),className:`flex w-full items-center gap-2.5 px-3.5 py-2.5 text-left`,"aria-expanded":C,children:[d(O,{className:`h-4 w-4 shrink-0 text-foreground-subtle transition-transform ${C?`rotate-90`:``}`}),d(`span`,{className:`truncate text-[13px] font-medium text-foreground`,children:t}),d(`span`,{className:`ml-auto flex items-center gap-2 text-[11px]`,children:_?b>=2?i(`span`,{className:`inline-flex items-center gap-1 text-emerald-400`,children:[d(_e,{className:`h-3.5 w-3.5`}),b,` accelerators`]}):b===1?d(`span`,{className:`text-foreground-subtle`,children:`single default`}):d(`span`,{className:`text-foreground-subtle/70`,children:`auto default`}):i(`span`,{className:`inline-flex items-center gap-1 text-foreground-subtle`,children:[d(k,{className:`h-3.5 w-3.5`}),` unreachable`]})})]}),C&&i(`div`,{className:`space-y-3 border-t border-border px-3.5 py-3`,children:[_?m&&g.length===0?d(`p`,{className:`rounded-lg border border-dashed border-border bg-background px-4 py-6 text-center text-xs text-foreground-subtle`,children:`Probing accelerators…`}):g.length===0?d(`p`,{className:`rounded-lg border border-dashed border-border bg-background px-4 py-6 text-center text-xs text-foreground-subtle`,children:`No inference devices reported by this node's platform probe.`}):d(`ul`,{className:`space-y-2`,children:g.map(e=>{let t=ta(e),n=v[e.key]??T(e),a=n.enabled&&e.available,s=ea({defaultModelId:e.defaultModelId,steps:n.steps});return i(`li`,{className:`flex items-center gap-3 rounded-lg border px-3 py-2.5 transition-colors ${e.available?a?`border-primary/40 bg-primary/[0.04] ring-1 ring-inset ring-primary/20`:`border-border bg-surface`:`border-border/60 bg-background opacity-55`}`,children:[d(`span`,{className:`grid h-9 w-9 shrink-0 place-items-center rounded-md ring-1 ring-inset ${na[t.hue]}`,children:d(t.Icon,{className:`h-4.5 w-4.5`})}),i(`div`,{className:`min-w-0 flex-1`,children:[i(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`truncate text-[13px] font-medium text-foreground`,children:t.label}),d(G,{variant:`default`,style:`outline`,className:`font-mono text-[9px]`,children:e.format}),!e.available&&d(G,{variant:`warning`,className:`text-[9px]`,children:`unavailable`})]}),i(`div`,{className:`mt-0.5 flex items-center gap-1.5 text-[10px] text-foreground-subtle`,children:[d(`span`,{className:`font-mono`,children:e.key}),s!==null&&i(o,{children:[d(`span`,{"aria-hidden":!0,children:`·`}),i(`span`,{children:[`root model`,` `,d(`span`,{className:`font-mono text-foreground/80`,children:s})]})]})]})]}),a&&i(`label`,{className:`flex shrink-0 items-center gap-1 text-[10px] text-foreground-subtle`,children:[d(`span`,{className:`hidden @sm/clustertab:inline`,children:`cap`}),d(`input`,{type:`number`,min:1,placeholder:`∞`,value:n.maxSessions??``,onChange:t=>{let n=t.target.value.trim(),r=n===``?null:Number.parseInt(n,10);D(e,r!=null&&r>0?r:null)},disabled:h.isPending,"aria-label":`Max concurrent sessions for ${t.label}`,className:`w-14 rounded border border-border bg-background px-1.5 py-1 text-right font-mono text-[11px] text-foreground focus:border-primary focus:outline-none`})]}),a&&d(ia,{suggested:r?.[e.key]??null,current:n.maxSessions,pending:h.isPending,onApply:t=>D(e,t)}),d(It,{checked:a,onCheckedChange:()=>E(e),disabled:!e.available||h.isPending,"aria-label":`Enable ${t.label}`,className:e.available?``:`cursor-not-allowed opacity-50`})]},e.key)})}):d(aa,{}),_&&A.length>=2&&i(`div`,{className:`space-y-3 rounded-lg border border-border bg-background/60 p-3.5`,children:[i(`h4`,{className:`flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-foreground-subtle`,children:[d(pe,{className:`h-3.5 w-3.5`}),`Accelerator share`]}),d($i,{nodes:j,pending:h.isPending,onCommitWeights:e=>{let t={...v};for(let n of e){let e=t[n.nodeId];e&&(t[n.nodeId]={...e,weight:n.weight})}y(t),w(t)},weightLabel:`Accelerator share`,readOnly:s!==void 0,footnote:s===void 0?d(o,{children:`Drag to shift the share of detection sessions each accelerator handles; lock one to pin its share while the others rebalance. Shares always sum to 100%.`}):d(o,{children:`Automatic: each accelerator's share follows its measured throughput at its model. Switch the node shares to manual to set them yourself.`})})]}),h.isError&&i(`div`,{className:`rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-[11px] text-danger`,children:[`Failed to save inference devices:`,` `,h.error instanceof Error?h.error.message:`unknown error`]})]})]})}function ia({suggested:e,current:t,pending:n,onApply:r}){return e===null||e<1||e===t?null:i(V,{variant:`ghost`,size:`sm`,onClick:()=>r(e),disabled:n,title:`Advisory cap from the measured throughput at the suggested model, with the headroom kept free. Applying it writes this device's cap.`,children:[`use `,e]})}function aa(){return i(`div`,{className:`flex flex-col items-center gap-2 rounded-lg border border-dashed border-border bg-background px-4 py-8 text-center`,children:[d(k,{className:`h-6 w-6 text-foreground-subtle/60`}),d(`p`,{className:`text-xs font-medium text-foreground`,children:`Node unreachable`}),d(`p`,{className:`max-w-sm text-[11px] text-foreground-subtle`,children:`The platform probe couldn't be reached, so its live accelerator set is unavailable. Settings resume once the node reconnects.`})]})}r();var oa=3600*1e3,sa=2e4,ca=.4;function la({refreshToken:e,onOpenAutoTune:t}){let n=c(),{nodes:r}=K(),s=ht(void 0),f=Ht({isCamera:!0,projection:`slim`}),p=fn({windowMs:oa},{refetchInterval:sa,placeholderData:l}).data,h=it(void 0,{refetchInterval:sa,placeholderData:l}).data,_=()=>{Cn(n),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`]]})},v=Ft({onSuccess:_}),y=Kt({onSuccess:()=>{_(),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getEffectiveShares`]]})}}),b=yt({onSuccess:_}),x=pt(),[S,w]=u(!1),T=h?.source,D=T===`benchmark`?`benchmark`:`hardware`,O=en({headroom:ca,source:D},{enabled:S,staleTime:1/0}),k=O.data,A=a(()=>{let e=new Map((s.data??[]).map(e=>[e.nodeId,e.settings]));return r.filter(t=>Rn(e.get(t.id),t.isHub).pipeline).map(t=>{let n=e.get(t.id);return{id:t.id,name:t.name,isOnline:t.isOnline,weight:yn(n,`detectWeight`)??1,maxCameras:yn(n,`maxCameras`)}})},[r,s.data]),j=e=>r.find(t=>t.id===e)?.name??e,M=Zn((f.data??[]).map(e=>({id:e.id,name:e.name}))),N=k?Hi(k):void 0,P=Wi(A,h),F=T!==`manual`,ee=e=>{if(h===void 0||h.source===`manual`||h.autoPending)return;let t=h.nodes.find(t=>t.nodeId===e);return t===void 0?void 0:Object.fromEntries(t.devices.map(e=>[e.deviceKey,e.configuredPct]))},te=h?Gi(h,j):null,ne=h?Ji(h,j):null,L=Ki.find(e=>e.value===T)?.hint;return i(`div`,{className:`space-y-3 sm:space-y-4`,children:[d(gn,{nodeId:`hub`,addonIds:[Dn],level:`global`,sectionIds:[`load`],title:`Placement policy`,description:`How a new detection session picks its node and device, and what happens when a node falls behind. 'Honour shares' (default) holds the shares below for PARALLEL sessions.`}),d(Un,{refreshToken:e}),d(Ii,{stats:p,...h!==void 0&&h.source!==`manual`&&!h.autoPending?{targetWeights:Object.fromEntries(h.nodes.map(e=>[e.nodeId,e.configuredPct]))}:{}}),d(U,{headingId:`load-balancing-node-shares`,title:`Node shares`,icon:pe,actions:i(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[d(`div`,{role:`radiogroup`,"aria-label":`Share source`,className:`flex items-center gap-1`,children:Ki.map(e=>d(V,{role:`radio`,"aria-checked":T===e.value,variant:T===e.value?`primary`:`outline`,size:`sm`,title:e.hint,disabled:y.isPending||h===void 0,onClick:()=>{T!==e.value&&y.mutate({source:e.value})},children:e.label},e.value))}),i(V,{variant:`outline`,size:`sm`,onClick:()=>{w(!0),S&&O.refetch()},disabled:O.isFetching,children:[d(I,{className:`h-3.5 w-3.5`}),O.isFetching?`Suggesting…`:D===`benchmark`?`Suggest from benchmark`:`Suggest from hardware`]}),i(V,{variant:`ghost`,size:`sm`,onClick:t,children:[d(E,{className:`h-3.5 w-3.5`}),`Auto tune`]}),i(V,{variant:`outline`,size:`sm`,onClick:()=>x.mutate(void 0),disabled:x.isPending,title:`Move standing (always-on) cameras that are no longer on their best node. Pinned cameras never move; on-motion sessions are placed per session anyway.`,children:[d(re,{className:`h-3.5 w-3.5`}),x.isPending?`Rebalancing…`:`Rebalance`]})]}),children:i(`div`,{className:`${m} space-y-3`,children:[L!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:L}),p&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Policy:`,` `,d(G,{variant:p.policy===`share`?`info`:`default`,children:p.policy===`share`?`honour shares`:`least-loaded`}),` `,`· cluster peak `,p.clusterPeakSessions,` parallel sessions in the last hour`,p.policy===`least-loaded`&&` · under least-loaded an idle node always wins, so shares only bite once nodes are busy`]}),d($i,{nodes:P.nodes,pending:v.isPending,readOnly:P.readOnly,onCommitWeights:e=>v.mutate(Bi(e)),weightLabel:`Node share`,...P.readOnly?{footnote:h?.autoPending?d(o,{children:`Automatic shares are being computed from the cluster's measured capacity; the stored values are used meanwhile.`}):i(o,{children:[T===`benchmark`?`Benchmark: each node's share follows its measured capacity from node benchmark results (hardware capacity where it has none)`:`Hardware: each node's share follows its capacity at its Auto tune model, from the measured speed of its hardware`,`, recomputed whenever a node or accelerator is added, removed, switched on or off, or changes model`,h?.computedAt==null?``:` — last at ${new Date(h.computedAt).toLocaleTimeString()}${h.trigger===null?``:` (${h.trigger})`}`,`.`]})}:{}}),te!==null&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:te}),ne!==null&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`benchmark-fallback-note`,children:ne}),y.isError&&d($e,{message:`Failed to switch shares: ${y.error instanceof Error?y.error.message:`unknown error`}`}),v.isError&&d($e,{message:`Failed to save shares: ${v.error instanceof Error?v.error.message:`unknown error`}`}),i(`details`,{className:`rounded-md border border-border`,children:[d(`summary`,{className:`${C} cursor-pointer text-xs text-foreground`,children:`Max concurrent sessions (advanced)`}),d(`ul`,{className:`divide-y divide-border border-t border-border`,children:A.map(e=>i(`li`,{className:`${C} flex items-center gap-2`,children:[d(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.name}),d(_t,{type:`number`,min:1,placeholder:`∞`,defaultValue:e.maxCameras??``,"aria-label":`Max concurrent sessions for ${e.name}`,className:`w-20 text-right`,disabled:b.isPending,onBlur:t=>{let n=t.target.value.trim(),r=n===``?null:Number.parseInt(n,10),i=r!==null&&r>0?r:null;i!==e.maxCameras&&b.mutate({agentNodeId:e.id,maxCameras:i})}})]},e.id))}),d(`p`,{className:`${C} ${B} border-t border-border`,children:`A hard cap on the sessions a node runs at once (always-on cameras count too). A node at its cap is never chosen; under shares its turn goes to a free node. Empty = unlimited.`})]})]})}),O.isError&&d($e,{message:`Suggestion failed: ${O.error instanceof Error?O.error.message:`unknown error`}`}),k&&d(ua,{suggestion:k,nameOf:j,pending:v.isPending,...F?{}:{onApply:()=>v.mutate(Vi(k))}}),d(U,{headingId:`load-balancing-accelerators`,title:`Accelerators`,icon:g,children:d(`div`,{className:`${m} space-y-2`,children:A.length===0?d(at,{title:`No detect-capable nodes`,description:`Enable detection on a node in Roles & nodes to configure its accelerators.`}):A.map(e=>d(ra,{nodeId:e.id,nodeName:e.name,isOnline:e.isOnline,...N?.[e.id]===void 0?{}:{suggestedMaxSessions:N[e.id]},...ee(e.id)===void 0?{}:{autoDeviceShares:ee(e.id)}},e.id))})}),p!==void 0&&p.stalePins.length>0&&d(da,{stats:p,cameraName:M})]})}function ua({suggestion:e,nameOf:t,pending:n,onApply:r}){return i(U,{headingId:`load-balancing-suggestion`,title:e.source===`benchmark`?`Suggested from benchmark`:`Suggested from hardware`,icon:I,...r===void 0?{}:{actions:d(V,{size:`sm`,onClick:r,disabled:n,children:`Apply suggested shares`})},children:[d(`ul`,{className:`divide-y divide-border`,children:e.nodes.map(e=>i(`li`,{className:`${C} space-y-0.5`,children:[i(`div`,{className:`flex items-baseline gap-2 text-xs`,children:[d(`span`,{className:`min-w-0 flex-1 truncate font-medium text-foreground`,children:t(e.nodeId)}),d(`span`,{className:`tabular-nums text-foreground`,children:e.share===null?`skipped`:`${e.share}%`})]}),i(`p`,{className:B,children:[qi(e.capacityFallback)===null?``:`${qi(e.capacityFallback)} · `,e.skippedReason===null?`≈ ${e.capacitySessions} parallel sessions · ${e.devices.map(e=>`${e.deviceKey} ${e.share}% (${e.modelId??`—`}${e.measured?``:`, estimated`}, cap ${e.suggestedMaxSessions??`—`})`).join(` · `)}`:`not part of the suggestion — ${e.skippedReason}`]})]},e.nodeId))}),i(`p`,{className:`${C} ${B} border-t border-border`,children:[`Shares in proportion to each node's capacity in parallel sessions —`,` `,e.source===`benchmark`?`measured by node benchmarks, or from the hardware table where a node has no results`:`at the models Auto tune picks (at least ${e.minSessionsPerDevice} per accelerator), from the measured speed of each node's hardware`,`, counted in `,e.cameraFps,` fps sessions with`,` `,Math.round(e.headroom*100),`% kept free. No load is measured or estimated.`,r===void 0?`Automatic shares already follow this; the caps are advisory — apply each from its accelerator row.`:`Applying writes the node and accelerator shares; the caps are advisory — apply each from its accelerator row.`]})]})}function da({stats:e,cameraName:t}){let n=c(),r=wt({onSuccess:()=>{n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getPlacementStats`]]}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getPipelineDevicePin`]]})}});return d(U,{headingId:`load-balancing-stale-pins`,title:`Stale device pins`,icon:me,children:d(`ul`,{className:`divide-y divide-border`,children:e.stalePins.map(e=>i(`li`,{className:`${C} flex items-center gap-2`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[d(`p`,{className:`truncate text-xs text-foreground`,title:t(e.deviceId),children:t(e.deviceId)}),d(`p`,{className:B,children:Ui(e)})]}),d(V,{variant:`outline`,size:`sm`,disabled:r.isPending,onClick:()=>r.mutate({deviceId:e.deviceId,deviceKey:`auto`}),children:`Clear pin`})]},e.deviceId))})})}function fa({node:e,emphasis:t=!1}){let n=e.isHub?z:g;return i(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[d(`span`,{className:`h-2 w-2 shrink-0 rounded-full ${e.isOnline?`bg-success`:`bg-danger`}`,"aria-hidden":`true`}),d(n,{className:`h-4 w-4 shrink-0 text-foreground-subtle`,"aria-hidden":`true`}),i(`div`,{className:`min-w-0`,children:[i(`div`,{className:`flex items-center gap-1.5 ${t?`text-sm`:`text-xs`} font-semibold text-foreground`,children:[d(`span`,{className:`truncate`,children:e.name}),e.isHub&&d(G,{variant:`info`,className:`px-1.5 py-0 text-[9px] uppercase tracking-wider`,children:`hub`}),!e.isOnline&&d(G,{variant:`danger`,className:`px-1.5 py-0 text-[9px] uppercase tracking-wider`,children:`offline`})]}),d(`div`,{className:`font-mono text-[10px] text-foreground-subtle truncate`,children:e.id})]})]})}function pa({nodes:e,actions:t}){return d(Je,{columns:[{key:`node`,header:`Node`,sortValue:e=>e.name,render:e=>d(fa,{node:e})},...wn.map(e=>({key:e.key,header:e.label,align:`center`,notSortableReason:`A switch — sorting would move the row while it is being changed.`,render:n=>d(It,{"aria-label":`${e.label} on ${n.name}`,title:e.hint,checked:vn(n.effective,e.key),disabled:t.capabilityPending,onCheckedChange:r=>t.onToggleCapability(n.id,e.key,r)})}))],rows:e,rowKey:e=>e.id,bordered:!1,minWidthPx:720,mobileMode:`scroll`,rowClassName:e=>e.isOnline?void 0:`opacity-60`,emptyMessage:`No cluster nodes reporting yet.`})}function ma({roleValues:e,options:t,pending:n,onRoleChange:r}){let a=t.map(e=>({value:e.id,label:e.id===`hub`?`${e.name} (default)`:e.name}));return d(`ul`,{className:`divide-y divide-border`,children:On.map(t=>i(`li`,{className:`${C} flex flex-wrap items-center gap-x-3 gap-y-1.5`,children:[i(`div`,{className:`min-w-0 flex-1 basis-56`,children:[d(`div`,{className:`text-xs font-medium text-foreground`,children:bn(t)}),d(`p`,{className:B,children:xn(t)})]}),d(`div`,{className:`w-full sm:w-48`,children:d(H,{"aria-label":`${bn(t)} node`,value:e[t],disabled:n,options:a,onChange:e=>r(t,e.target.value)})})]},t))})}r();function ha(){let e=c(),{nodes:t}=K(),n=ht(void 0),r=Wt({addonId:Dn}),o=Wt({addonId:_n}),s=Wt({addonId:kn}),l=()=>Cn(e),u=Xt({onSuccess:l}),f=Ct({onSuccess:l}),p=a(()=>{let e=new Map;for(let t of n.data??[])e.set(t.nodeId,t.settings);return e},[n.data]),m=a(()=>t.map(e=>{let t=p.get(e.id),n=Rn(t,e.isHub);return{id:e.id,name:e.name,isHub:e.isHub,isOnline:e.isOnline,settings:t,effective:n}}),[t,p]),h={ingestNode:En(r.data,`ingestNode`,`hub`),recordingNode:En(o.data,Tn,`hub`),audioNode:En(r.data,`audioNode`,`hub`),motionNode:En(r.data,`motionNode`,`hub`),postProcessingNode:En(s.data,Sn,`hub`)},g=a(()=>{let e=t.filter(e=>e.isOnline).map(e=>e.id),n=e=>t.find(t=>t.id===e)?.name||e;return[...new Set([`hub`,...On.map(e=>h[e]),...e])].filter(e=>e.length>0).map(e=>({id:e,name:n(e)}))},[t,h]),_=n.isLoading||r.isLoading||o.isLoading||s.isLoading,v=(e,t,n)=>{u.mutate({agentNodeId:e,[t]:n})},y=(e,t)=>{if(e===`recordingNode`){f.mutate({addonId:_n,patch:{[Tn]:t}});return}if(e===`postProcessingNode`){f.mutate({addonId:kn,patch:{[Sn]:t}});return}f.mutate({addonId:Dn,patch:{[e]:t}})},b={capabilityPending:u.isPending,onToggleCapability:v};return i(`div`,{className:`space-y-3 sm:space-y-4`,children:[i(U,{headingId:`roles-nodes-cluster-roles`,title:`Cluster roles`,icon:fe,actions:_?d(A,{className:`h-3.5 w-3.5 animate-spin text-foreground-subtle`,"aria-label":`Loading`}):null,children:[d(`p`,{className:`${B} border-b border-border px-3 py-1.5 sm:px-4`,children:`One node holds each role for every camera. Detection shares and caps are on Load balancing.`}),d(ma,{roleValues:h,options:g,pending:f.isPending,onRoleChange:y})]}),d(U,{headingId:`roles-nodes-node-capabilities`,title:`Node capabilities`,icon:z,children:d(pa,{nodes:m,actions:b})})]})}var ga=`pipeline-analytics`,_a=`face-gallery`,va=`pipeline-orchestrator`,ya=`pipeline-runner`,ba=`audio-analyzer`;function xa(e){return[...Ne.filter(t=>t.stepId===e).map(e=>xe(e.stepId)),...we.filter(t=>t.stepId===e).map(e=>Ce(e.stepId,e.key))]}var Sa=`faces`,Ca=`semantic-search`,wa=[{id:Sa,title:`Faces & recognition`,hint:`The face encoder for every node, the smallest faces worth embedding, keeping and auto-assigning, and how a face is matched to a person.`,panels:[{addonId:va,fieldKeys:xa(`face-embedding`)},{addonId:ga,capability:_a}]},{id:Ca,title:`Semantic search`,hint:`The image encoder behind "search by description". One for the whole cluster: changing it hides existing results until the index is rebuilt.`,panels:[{addonId:va,fieldKeys:xa(`clip-embedding`)}]},{id:Ae,title:`Enrichment crop`,hint:`How the crop handed to face, plate and search models is cut from the frame.`,panels:[{addonId:va,sectionIds:[Ae]}]},{id:De,title:`Full-resolution crops`,hint:`How long each camera keeps full-resolution pixels so a late crop (snapshot, face, plate) is sharp instead of cut from the small detection frame.`,panels:[{addonId:va,sectionIds:[De]}]},{id:`runner-defaults`,title:`Runner defaults`,hint:`Values every node's detection runner and audio analyzer use. A node's own decode limits (Engine & decoder) take precedence.`,panels:[{addonId:ya,fieldScope:`cluster`},{addonId:ba,fieldScope:`cluster`}]},{id:`failover`,title:`Failover`,hint:`What happens to cameras when a node disconnects and comes back.`,panels:[{addonId:va,sectionIds:[`failover`]}]}],Ta={"cluster-step-models":Sa};function Ea(e){return e===`clip-embedding`?Ca:Sa}r();var Da=2500,Oa={faces:ne,"semantic-search":E,"detail-crop":ge,"native-lease":_e,"runner-defaults":g,failover:R};function ka(e){f(()=>{if(e===null)return;let t=Ta[e]??e,n=`[data-cluster-settings-card="${CSS.escape(t)}"]`,r=()=>{let e=document.querySelector(n);return e===null?!1:(e.scrollIntoView({block:`start`,behavior:`smooth`}),e.classList.add(`ring-2`,`ring-primary/60`),setTimeout(()=>e.classList.remove(`ring-2`,`ring-primary/60`),Da),!0)};if(r())return;let i=new MutationObserver(()=>{r()&&i.disconnect()});return i.observe(document.body,{childList:!0,subtree:!0}),()=>i.disconnect()},[e])}function Aa({section:e}){return d(`div`,{"data-cluster-settings-card":e.id,className:`rounded-lg`,children:d(U,{headingId:`cluster-settings-${e.id}`,title:e.title,...Oa[e.id]===void 0?{}:{icon:Oa[e.id]},children:i(`div`,{className:`${m} space-y-3`,children:[d(`p`,{className:B,children:e.hint}),e.panels.map(e=>d(gn,{nodeId:`hub`,addonIds:[e.addonId],level:`global`,hideSectionChrome:!0,omitSectionIds:[`cluster`,`load`],emptyMessage:`Not available — the addon that owns these settings did not answer.`,...e.capability===void 0?{}:{capability:e.capability},...e.sectionIds===void 0?{}:{sectionIds:e.sectionIds},...e.fieldKeys===void 0?{}:{fieldKeys:e.fieldKeys},...e.fieldScope===void 0?{}:{fieldScope:e.fieldScope}},`${e.addonId}:${e.capability??``}`))]})})})}function ja({refreshToken:e}){let[t]=mn();return ka(t.get(No)),d(`div`,{className:`space-y-3 sm:space-y-4`,children:wa.map(e=>d(Aa,{section:e},e.id))})}var Ma=`pipeline-orchestrator`,Na=200;function Pa(){return i(`div`,{className:`flex flex-col gap-3`,children:[i(`div`,{children:[d(`h3`,{className:`text-sm font-semibold text-foreground mb-1`,children:`Orchestrator logs`}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Dispatch decisions, balancer moves and failover events from the pipeline orchestrator. Streaming live; the device chip on a line tells which camera it refers to.`})]}),d(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:d(ft,{addonId:Ma,limit:Na,maxHeight:`max-h-[calc(100vh-360px)]`,showScope:!0,showDeviceChip:!0,showFilters:!1})})]})}var Fa=[{id:`assignments`,label:`Assignments`},{id:`load-balancing`,label:`Load balancing`},{id:`auto-tune`,label:`Auto tune`},{id:`roles-nodes`,label:`Roles`},{id:`settings`,label:`Settings`},{id:`logs`,label:`Logs`}];function Ia(e){return Fa.some(t=>t.id===e)}function La({refreshToken:e}){let[t,n]=mn(),r=t.get(Mo),a=Ia(r)?r:`assignments`,o=e=>{n(t=>{let n=new URLSearchParams(t);return n.set(Mo,e),n.delete(No),n},{replace:!0})};return i(`div`,{className:`flex flex-col h-full`,children:[i(`div`,{className:`px-4 sm:px-6 py-4 border-b border-border`,children:[d(`h2`,{className:`text-base font-semibold text-foreground`,children:`Cluster Orchestration`}),d(`div`,{className:`text-[11px] text-foreground-subtle mt-1`,children:`Camera assignments, load balancing, the detector recommendation, cluster roles and settings.`})]}),d(`div`,{className:`flex items-center gap-1 px-4 sm:px-6 border-b border-border overflow-x-auto`,children:Fa.map(e=>d(`button`,{type:`button`,onClick:()=>o(e.id),className:`shrink-0 whitespace-nowrap px-3 py-2 text-xs font-medium border-b-2 transition-colors ${a===e.id?`border-primary text-primary`:`border-transparent text-foreground-subtle hover:text-foreground`}`,children:e.label},e.id))}),i(`div`,{className:`flex-1 min-h-0 overflow-y-auto p-4 sm:p-6 @container/clustertab`,children:[a===`assignments`&&d(li,{}),a===`load-balancing`&&d(la,{refreshToken:e,onOpenAutoTune:()=>o(`auto-tune`)}),a===`auto-tune`&&d(Oi,{}),a===`roles-nodes`&&d(ha,{}),a===`settings`&&d(ja,{refreshToken:e}),a===`logs`&&d(Pa,{})]})]})}var Ra=`armed:`;function za(e){return e.assignment.reasons.detection?.startsWith(Ra)===!0}function Ba(e){let{assignment:t,detection:n}=e;return n!==null&&n.provisioning.state===`failed`||t.detectionNodeId===null&&n===null&&!za(e)?`error`:n!==null&&n.phase===`active`?`healthy`:`idle`}function Va(e){let t=[],n=[],{assignment:r,detection:i,broker:a}=e;i!==null&&i.provisioning.state===`failed`&&t.push({code:`provisioning-failed`,severity:`error`,message:i.provisioning.error!==void 0&&i.provisioning.error.length>0?`Engine provisioning failed: ${i.provisioning.error}`:`Engine provisioning failed on the detection node`}),i!==null&&i.phase===`active`&&i.actualFps===0&&t.push({code:`detection-black-hole`,severity:`error`,message:`Detection phase is ACTIVE but 0 fps are being processed — frames are not reaching the detector (cross-node black-hole signature)`}),r.detectionNodeId===null&&i===null&&!za(e)&&n.push({code:`unassigned`,severity:`warning`,message:`Not placed on any detection node — no pipeline is running for this camera`});let o=e.degraded??[];if(o.length>0){let e=[...new Set(o.map(e=>e.stage))].join(`, `);n.push({code:`status-unreadable`,severity:`warning`,message:`Could not read ${e} for this camera — those blocks are unknown, not empty (a switch read that failed does NOT mean nothing is switched off)`})}n.push(...Wa(e.cameraSensors));for(let e of a?.profiles??[])e.status===`streaming`&&e.inFps===0&&n.push({code:`broker-stalled`,severity:`warning`,message:`Broker profile "${e.profile}" reports streaming but 0 in-fps — the source pull may be stalled`});return[...t,...n]}function Ha(e){return e.state===`unreadable`&&Oe.state===`unreadable`&&e.reason===Oe.reason}function Ua(e){switch(e.state){case`ready`:return null;case`missing`:return{code:`camera-sensor-missing`,severity:`warning`,message:`Camera sensor ${e.addonId}/${e.stableId} is missing`};case`offline`:return{code:`camera-sensor-offline`,severity:`warning`,message:`Camera sensor ${e.name} (#${e.deviceId}) is ${e.reason}`};case`unsupported`:return{code:`camera-sensor-unsupported`,severity:`warning`,message:`Camera sensor ${e.name} (#${e.deviceId}) cannot drive motion: ${e.reason}`};case`unreadable`:return{code:`camera-sensor-unreadable`,severity:`warning`,message:`Camera sensor ${e.addonId}/${e.stableId} is unreadable: ${e.reason}`}}}function Wa(e){if(e===void 0||e.state===`not-configured`)return[];if(e.state===`unreadable`)return Ha(e)?[]:[{code:`camera-sensors-unreadable`,severity:`warning`,message:`Camera sensors unreadable: ${e.reason}`}];let t=e.sensors.flatMap(e=>{let t=Ua(e);return t===null?[]:[t]}),n=e.notForwarded===void 0?t:[Ga(e.notForwarded),...t];return e.notEnforced===void 0?n:[{code:`camera-sensors-not-enforced`,severity:`warning`,message:`Confirm / Replace cannot suppress this camera's own motion until its provider is updated`},...n]}function Ga(e){return{code:`camera-sensors-not-forwarded`,severity:`warning`,message:e===`onboard-not-listed`?`Camera sensors are attached but never fire: add "Camera sensors" (onboard) to this camera's motion sources`:`Camera sensors are attached but never fire: this camera has no active detection`}}function Ka(e){return e===void 0?`status unavailable from this node`:e.state===`not-configured`?`none attached`:e.state===`unreadable`?`unknown — ${e.reason}`:e.sensors.map(Ja).join(`, `)}function qa(e){return e.mode===`in-addition`?``:` · ${e.mode}`}function Ja(e){return`${Ya(e)}${qa(e)}`}function Ya(e){switch(e.state){case`ready`:return`${e.name} (#${e.deviceId})`;case`offline`:return`${e.name} (#${e.deviceId}) — ${e.reason}`;case`unsupported`:return`${e.name} (#${e.deviceId}) — unsupported`;case`missing`:case`unreadable`:return`${e.addonId}/${e.stableId} — ${e.state}`}}function Xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Y(e){return typeof e==`string`&&e.length>0?e:null}function Za(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Qa(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function $a(e,t){return e==null?!1:JSON.stringify(e)!==JSON.stringify(t??null)}var eo={detectionMode:null,detectionStreamProfile:null,detectionFps:null,motionSources:[],motionFps:null,motionCooldownMs:null,motionStreamProfile:null,audioMode:null,pipelineNodeId:null,decoderNodeId:null,audioNodeId:null,overriddenKeys:new Set};function to(e){if(!Xa(e)||!Array.isArray(e.sections))return eo;let t=Ee(e),n=e=>{let n=t.get(e);if(n!==void 0)return n.value??n.default},r=new Set;for(let[e,n]of t)$a(n.value,n.default)&&r.add(e);return{detectionMode:Y(n(`detectionMode`)),detectionStreamProfile:Y(n(`detectionStreamProfile`)),detectionFps:Za(n(`detectionFps`)),motionSources:Qa(n(`motionSources`)),motionFps:Za(n(`motionFps`)),motionCooldownMs:Za(n(`motionCooldownMs`)),motionStreamProfile:Y(n(`motionStreamProfile`)),audioMode:Y(n(`audioMode`)),pipelineNodeId:Y(n(`pipelineNodeId`)),decoderNodeId:Y(n(`decoderNodeId`)),audioNodeId:Y(n(`audioNodeId`)),overriddenKeys:r}}function no(e,t=0){let n=[];for(let r of e)n.push({addonId:r.addonId,modelId:r.modelId??null,enabled:r.enabled,depth:t}),r.children!==void 0&&r.children.length>0&&n.push(...no(r.children,t+1));return n}function X({title:e,children:t}){return i(`div`,{className:`bg-background px-3.5 py-3 min-w-0`,children:[d(`div`,{className:`text-[9px] font-semibold uppercase tracking-[0.14em] text-foreground-subtle mb-2`,children:e}),d(`div`,{className:`flex flex-col gap-1 min-w-0`,children:t})]})}function Z({label:e,children:t,overridden:n=!1}){return i(`div`,{className:`flex items-baseline gap-2 text-[11px] leading-snug min-w-0`,children:[d(`span`,{className:`text-foreground-subtle shrink-0 w-24 truncate`,title:e,children:e}),d(`span`,{className:`font-mono tabular-nums text-foreground min-w-0 truncate flex-1`,children:t}),n&&d(ro,{})]})}function ro(){return d(`span`,{className:`inline-block h-1.5 w-1.5 rounded-full bg-warning shrink-0 self-center`,title:`Device-level override active`,"aria-label":`Device-level override active`,role:`img`})}var io={neutral:`border-border text-foreground-muted`,success:`border-success/40 text-success`,warning:`border-warning/40 text-warning`,danger:`border-danger/40 text-danger`,info:`border-info/40 text-info`};function Q({tone:e=`neutral`,children:t,title:n}){return d(`span`,{title:n,className:`inline-flex items-center gap-1 rounded border px-1.5 py-px text-[10px] font-medium leading-tight whitespace-nowrap ${io[e]}`,children:t})}function $({children:e}){return d(`div`,{className:`text-[11px] text-foreground-subtle italic`,children:e})}function ao({icon:e,label:t,nodeId:n,pinned:r,reason:a,overridden:s}){return i(`div`,{className:`flex items-center gap-2 text-[11px] leading-snug min-w-0`,children:[d(e,{className:`h-3 w-3 text-foreground-subtle shrink-0`}),d(`span`,{className:`text-foreground-subtle w-[4.5rem] shrink-0`,children:t}),n===null?d(`span`,{className:`text-foreground-subtle italic`,children:`unassigned`}):i(o,{children:[d(`span`,{className:`font-mono text-foreground truncate`,title:n,children:n}),r?i(`span`,{className:`inline-flex items-center gap-0.5 text-[10px] text-warning shrink-0`,title:`Manually pinned`,children:[d(_,{className:`h-2.5 w-2.5`}),` manual`]}):i(`span`,{className:`text-[10px] text-foreground-subtle shrink-0 truncate`,children:[`auto · `,a!==void 0&&a.length>0?a:`capacity`]}),s&&d(`span`,{className:`inline-block h-1.5 w-1.5 rounded-full bg-warning shrink-0`,title:`Persisted settings pin for this role`})]})]})}function oo({assignment:e,settings:t,onlineNodes:n,pinPending:r,onDetectionPinChange:a}){let o=e.pinned.detection&&e.detectionNodeId!==null?e.detectionNodeId:`auto`,s=[...new Set([...e.detectionNodeId===null?[]:[e.detectionNodeId],...n.map(e=>e.id)])];return i(X,{title:`Where it runs`,children:[d(ao,{icon:g,label:`Detection`,nodeId:e.detectionNodeId,pinned:e.pinned.detection,reason:e.reasons.detection,overridden:t.overriddenKeys.has(`pipelineNodeId`)}),d(ao,{icon:y,label:`Decoder`,nodeId:e.decoderNodeId,pinned:e.pinned.decoder,reason:e.reasons.decoder,overridden:t.overriddenKeys.has(`decoderNodeId`)}),d(ao,{icon:D,label:`Audio`,nodeId:e.audioNodeId,pinned:e.pinned.audio,reason:e.reasons.audio,overridden:t.overriddenKeys.has(`audioNodeId`)}),d(ao,{icon:M,label:`Source`,nodeId:e.sourceNodeId,pinned:!1,reason:`ingest owner`,overridden:!1}),d(`div`,{className:`mt-1.5`,children:i(`select`,{value:o,disabled:r,"aria-label":`Detection placement pin`,onChange:e=>a(e.target.value),className:`w-full min-w-0 rounded-md border border-border bg-background px-2 py-1 text-[11px] text-foreground disabled:opacity-50`,children:[d(`option`,{value:`auto`,children:`Auto (load balanced)`}),s.map(e=>i(`option`,{value:e,children:[`Pin detection → `,n.find(t=>t.id===e)?.name??e]},e))]})})]})}function so(e){return`${e.width}×${e.height} ${e.codec} @${e.fps}fps`}function co(e,t){if(!(t===null||e===void 0))return e.find(e=>e.profile===t)}function lo(e){return e===null?`default`:e===0?`native (no throttle)`:`${e} fps`}function uo({streams:e,brokerProfiles:t,settings:n,motionEnabled:r,motionFpsLive:a,cameraSensors:s}){let c=co(t,n.detectionStreamProfile),l=co(t,n.motionStreamProfile),u=n.motionSources.includes(`analyzer`);return i(X,{title:`Streams & motion`,children:[i(Z,{label:`Detect stream`,overridden:n.overriddenKeys.has(`detectionStreamProfile`),children:[n.detectionStreamProfile??`—`,c!==void 0&&` · ${c.width}×${c.height} ${c.codec}`]}),d(Z,{label:`Detect FPS`,overridden:n.overriddenKeys.has(`detectionFps`),children:lo(n.detectionFps)}),i(Z,{label:`Motion src`,overridden:n.overriddenKeys.has(`motionSources`),children:[n.motionSources.length>0?n.motionSources.map(ye).join(` + `):`none`,r===!1&&` · inactive`]}),d(Z,{label:`Camera sensors`,children:Ka(s)}),u&&i(o,{children:[i(Z,{label:`Motion stream`,overridden:n.overriddenKeys.has(`motionStreamProfile`),children:[n.motionStreamProfile??`—`,l!==void 0&&` · ${l.width}×${l.height} ${l.codec}`]}),i(Z,{label:`Motion FPS`,overridden:n.overriddenKeys.has(`motionFps`),children:[lo(n.motionFps),a!==null&&` · live ${a.toFixed(1)}`]})]}),d(Z,{label:`Cooldown`,overridden:n.overriddenKeys.has(`motionCooldownMs`),children:n.motionCooldownMs===null?`default`:`${n.motionCooldownMs/1e3}s`}),d(`div`,{className:`mt-1.5 flex flex-col gap-0.5`,children:e.length===0?d($,{children:`No streams registered`}):e.map(e=>i(`div`,{className:`text-[10px] font-mono text-foreground-subtle truncate`,title:e.camStreamId,children:[d(`span`,{className:`text-foreground-muted`,children:e.kind}),` `,so(e)]},e.camStreamId))})]})}function fo({steps:e,audioModelId:t,audioEnabled:n,audioMode:r}){return i(X,{title:`Pipeline steps`,children:[e===void 0?d($,{children:`Resolving…`}):e.length===0?d($,{children:`No steps configured`}):d(`div`,{className:`flex flex-wrap gap-1`,children:e.map((e,t)=>d(Q,{tone:e.enabled&&e.depth===0?`info`:`neutral`,title:e.modelId??e.addonId,children:i(`span`,{className:e.enabled?``:`line-through opacity-60`,children:[e.depth>0&&d(`span`,{className:`opacity-50`,children:`↳ `}),e.addonId,e.modelId!==null&&i(`span`,{className:`font-mono opacity-75`,children:[` · `,e.modelId]})]})},`${e.addonId}-${t}`))}),d(`div`,{className:`mt-1`,children:i(Z,{label:`Audio class.`,children:[r??`—`,n!==null&&(n?` · running`:` · off`),t!==null&&` · ${t}`]})})]})}var po={ready:`success`,installing:`info`,verifying:`info`,idle:`neutral`,failed:`danger`};function mo({detection:e,live:t,detectionMode:n,modeOverridden:r}){if(e===null)return i(X,{title:`Detection runtime`,children:[d(Z,{label:`Mode`,overridden:r,children:n??`—`}),d($,{children:`Detection stage inactive or unreachable`})]});let a=t?.phase??e.phase,o=t?.actualFps??e.actualFps,s=t?.configuredFps??e.configuredFps,c=t?.avgInferenceTimeMs??e.avgInferenceMs,l=t?.queueDepth??e.queueDepth,u=tt(a),f=a===`active`&&o===0;return i(X,{title:`Detection runtime`,children:[i(`div`,{className:`flex items-center gap-1.5 mb-0.5`,children:[i(`span`,{className:`inline-flex items-center gap-1 rounded border px-1.5 py-px text-[10px] font-semibold uppercase tracking-wider ${u.badgeClass}`,children:[d(Ue,{phase:a,className:`h-2.5 w-2.5`}),u.label]}),t!==void 0&&d(`span`,{className:`text-[9px] text-foreground-subtle uppercase tracking-wider`,children:`live`})]}),d(Z,{label:`Mode`,overridden:r,children:n??`—`}),i(Z,{label:`FPS`,children:[d(`span`,{className:f?`text-danger font-semibold`:``,children:o.toFixed(1)}),i(`span`,{className:`text-foreground-subtle`,children:[` / `,s.toFixed(0),` configured`]})]}),i(Z,{label:`Inference`,children:[c.toFixed(0),` ms`,l>0&&i(`span`,{className:`text-warning`,children:[` · queue `,l]}),t!==void 0&&t.droppedFrames>0&&i(`span`,{className:`text-warning`,children:[` · drops `,t.droppedFrames]})]}),i(Z,{label:`Engine`,children:[e.engine.backend,` · `,e.engine.device]}),i(Z,{label:`Provisioning`,children:[d(Q,{tone:po[e.provisioning.state]??`neutral`,children:e.provisioning.state}),e.provisioning.error!==void 0&&i(`span`,{className:`text-danger text-[10px]`,children:[` `,e.provisioning.error]})]})]})}function ho({broker:e}){return e===null?d(X,{title:`Stream broker`,children:d($,{children:`Broker stage inactive or unreachable`})}):i(X,{title:`Stream broker`,children:[e.profiles.length===0?d($,{children:`No broker profiles`}):d(`div`,{className:`flex flex-col gap-1`,children:e.profiles.map(e=>{let t=e.status===`streaming`,n=t&&e.inFps===0;return i(`div`,{className:`flex items-center gap-2 text-[11px] font-mono tabular-nums min-w-0`,children:[d(`span`,{className:`inline-block h-1.5 w-1.5 rounded-full shrink-0 ${n?`bg-danger`:t?`bg-success animate-pulse`:`bg-border`}`,title:e.status}),d(`span`,{className:`text-foreground w-10 shrink-0 truncate`,title:e.profile,children:e.profile}),i(`span`,{className:`text-foreground-subtle truncate`,children:[e.width,`×`,e.height,` `,e.codec]}),i(`span`,{className:`ml-auto shrink-0 ${n?`text-danger`:`text-foreground`}`,children:[e.inFps===null?`—`:e.inFps.toFixed(0),`fps`]}),i(`span`,{className:`text-foreground-subtle shrink-0`,title:`Subscribers`,children:[`×`,e.subscribers]})]},e.profile)})}),i(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:[i(Q,{tone:e.webrtcSessions>0?`info`:`neutral`,children:[`WebRTC `,e.webrtcSessions]}),i(Q,{tone:e.rtspRestream?`success`:`neutral`,children:[`restream `,e.rtspRestream?`on`:`off`]})]})]})}function go({decoder:e}){return e===null?d(X,{title:`Decoder`,children:d($,{children:`Decoder stage inactive or unreachable`})}):d(X,{title:`Decoder`,children:d(Z,{label:`Node`,children:e.nodeId})})}r();var _o=`pipeline-orchestrator`,vo={healthy:`bg-success`,idle:`bg-warning`,error:`bg-danger`},yo={healthy:`Healthy`,idle:`Idle`,error:`Error`};function bo({problems:e}){return d(`div`,{role:`alert`,className:`flex flex-col border-b border-border`,children:e.map(e=>i(`div`,{className:`flex items-start gap-2 px-4 py-1.5 text-[11px] font-medium ${e.severity===`error`?`bg-danger/10 text-danger`:`bg-warning/10 text-warning`}`,children:[d(b,{className:`h-3.5 w-3.5 shrink-0 mt-px`}),d(`span`,{className:`min-w-0`,children:e.message})]},e.code))})}function xo({deviceId:e,name:t,online:n,status:r,live:o,onlineNodes:s}){let l=c(),{data:u}=Jt({addonId:_o,deviceId:e,nodeId:`hub`},{staleTime:3e4}),{data:f}=Qe({deviceId:e},{staleTime:3e4}),p=a(()=>to(u),[u]),m=a(()=>f===void 0?void 0:no(f.steps),[f]),h=a(()=>r===void 0?[]:Va(r),[r]),g=()=>{l.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStatuses`]]}),l.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getPipelineAssignments`]]})},_=Re({onSuccess:g}),v=Bt({onSuccess:g}),y=t=>{t===`auto`?v.mutate({deviceId:e}):_.mutate({deviceId:e,agentNodeId:t})},b=r===void 0?`idle`:Ba(r),x=h.some(e=>e.severity===`error`),S=h.length>0,C=x?`border-danger/50`:S?`border-warning/40`:`border-border`;return i(`article`,{"aria-label":`${t} pipeline status`,className:`rounded-lg border ${C} bg-background overflow-hidden`,children:[i(`header`,{className:`flex items-center gap-2.5 px-4 py-2.5 border-b border-border bg-surface/50 min-w-0`,children:[d(`span`,{className:`inline-block h-2 w-2 rounded-full shrink-0 ${x?`bg-danger`:vo[b]}`,title:x?`Error`:yo[b],"aria-label":x?`Error`:yo[b],role:`img`}),d(`h3`,{className:`text-[13px] font-semibold text-foreground truncate`,title:t,children:t}),i(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:[`#`,e]}),!n&&d(Q,{tone:`danger`,children:`offline`}),i(`span`,{className:`ml-auto flex items-center gap-1.5 shrink-0`,children:[p.detectionMode!==null&&d(Q,{tone:p.detectionMode===`disabled`?`warning`:p.detectionMode===`always-on`?`info`:`neutral`,title:`Object detection mode`,children:p.detectionMode===`disabled`?`detection off`:p.detectionMode}),r?.recording!=null&&(r.recording.active?i(Q,{tone:`danger`,title:`Recording (${r.recording.mode})`,children:[d(`span`,{className:`inline-block h-1.5 w-1.5 rounded-full bg-danger animate-pulse`}),`REC`]}):r.recording.mode!==`off`&&i(Q,{tone:`neutral`,title:`Recording mode`,children:[`rec `,r.recording.mode]}))]})]}),h.length>0&&d(bo,{problems:h}),r===void 0?d(`div`,{className:`px-4 py-5 text-[11px] text-foreground-subtle italic`,children:`No pipeline status yet — the orchestrator has not composed a snapshot for this camera.`}):i(`div`,{className:`grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-px bg-border`,children:[d(oo,{assignment:r.assignment,settings:p,onlineNodes:s,pinPending:_.isPending||v.isPending,onDetectionPinChange:y}),d(mo,{detection:r.detection,live:o,detectionMode:p.detectionMode,modeOverridden:p.overriddenKeys.has(`detectionMode`)}),d(fo,{steps:m,audioModelId:f?.audio?.modelId??null,audioEnabled:r.audio?.enabled??f?.audio?.enabled??null,audioMode:p.audioMode}),d(uo,{streams:r.source.streams,brokerProfiles:r.broker?.profiles,settings:p,motionEnabled:r.motion?.enabled??null,motionFpsLive:r.motion?.fps??null,cameraSensors:r.cameraSensors}),d(ho,{broker:r.broker}),d(go,{decoder:r.decoder})]})]})}r();var So=5e3,Co=1e4,wo=5e3;function To(e){let t=c(),{data:n,isLoading:r}=pn(),{data:i,isLoading:o}=Ie({},{refetchInterval:So}),{nodes:s}=K();f(()=>{e!==0&&t.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStatuses`]]})},[e,t]);let[l,d]=u(new Map);Pt(Me.PipelineCameraMetricsSnapshot,e=>{let t=e.data;typeof t.deviceId==`number`&&d(e=>{let n=new Map(e);return n.set(t.deviceId,{phase:t.metrics.phase,configuredFps:t.metrics.configuredFps,actualFps:t.metrics.actualFps,queueDepth:t.metrics.queueDepth,avgInferenceTimeMs:t.metrics.avgInferenceTimeMs,droppedFrames:t.metrics.droppedFrames,timestamp:t.timestamp}),n})}),f(()=>{if(l.size===0)return;let e=setInterval(()=>{d(e=>{let t=Date.now()-Co,n=!1,r=new Map(e);for(let[i,a]of e)a.timestamp<t&&(r.delete(i),n=!0);return n?r:e})},wo);return()=>clearInterval(e)},[l.size]);let p=a(()=>{let e=new Map;for(let t of i??[])e.set(t.deviceId,t);return e},[i]);return{rows:a(()=>(n??[]).filter(e=>e.isCamera).map(e=>({deviceId:e.id,name:e.name,online:e.online,status:p.get(e.id)})).sort((e,t)=>e.name.localeCompare(t.name)),[n,p]),liveMetrics:l,onlineNodes:a(()=>(s??[]).filter(e=>e.isOnline).map(e=>({id:e.id,name:e.name})),[s]),isLoading:r||o}}r();function Eo({refreshToken:e}){let{rows:t,liveMetrics:n,onlineNodes:r,isLoading:o}=To(e),s=a(()=>[...t.map(e=>{let t=e.status===void 0?[]:Va(e.status);return{row:e,errorCount:t.filter(e=>e.severity===`error`).length,warningCount:t.filter(e=>e.severity===`warning`).length}})].sort((e,t)=>e.errorCount===t.errorCount?e.warningCount===t.warningCount?0:t.warningCount-e.warningCount:t.errorCount-e.errorCount),[t]),c=a(()=>{let e=0,t=0;for(let r of s)(r.errorCount>0||r.warningCount>0)&&(t+=1),(n.get(r.row.deviceId)?.phase??r.row.status?.detection?.phase)===`active`&&(e+=1);return{total:s.length,active:e,issues:t}},[s,n]);return o&&t.length===0?d(`div`,{className:`flex items-center justify-center h-full text-sm text-foreground-subtle`,children:`Loading camera pipelines…`}):t.length===0?d(`div`,{className:`flex items-center justify-center h-full text-sm text-foreground-subtle`,children:`No cameras found`}):d(`div`,{className:`h-full overflow-y-auto`,children:i(`div`,{className:`max-w-6xl mx-auto flex flex-col gap-3 px-4 py-4`,children:[i(`div`,{className:`flex items-center gap-4 text-[11px] text-foreground-subtle px-1`,children:[i(`span`,{children:[d(`span`,{className:`font-semibold text-foreground`,children:c.total}),` cameras`]}),i(`span`,{children:[d(`span`,{className:`font-semibold text-success`,children:c.active}),` actively inferring`]}),i(`span`,{children:[d(`span`,{className:`font-semibold ${c.issues>0?`text-danger`:`text-foreground`}`,children:c.issues}),` `,`with issues`]}),d(`span`,{className:`ml-auto hidden sm:inline text-[10px]`,children:`polled every 5 s · detection metrics live at 1 Hz`})]}),s.map(({row:e})=>d(xo,{deviceId:e.deviceId,name:e.name,online:e.online,status:e.status,live:n.get(e.deviceId),onlineNodes:r},e.deviceId))]})})}var Do=e({CLUSTER_NODE_ID:()=>Oo,PipelinePage:()=>jo});r();var Oo=`__cluster__`;function ko(e){return e===`cameras`?`cameras`:`nodes`}function Ao({viewMode:e,onNodes:t,onCameras:n}){return i(`div`,{className:`flex items-center gap-1 rounded-lg border border-border bg-surface p-0.5`,role:`tablist`,"aria-label":`Pipeline view`,children:[d(`button`,{type:`button`,role:`tab`,"aria-selected":e===`nodes`,onClick:t,className:[`rounded-md px-3 py-1 text-[11px] font-medium transition-colors`,e===`nodes`?`bg-background text-foreground shadow-sm`:`text-foreground-subtle hover:text-foreground`].join(` `),children:`Nodes`}),d(`button`,{type:`button`,role:`tab`,"aria-selected":e===`cameras`,onClick:n,className:[`rounded-md px-3 py-1 text-[11px] font-medium transition-colors`,e===`cameras`?`bg-background text-foreground shadow-sm`:`text-foreground-subtle hover:text-foreground`].join(` `),children:`Cameras`})]})}function jo(){let[e,t]=mn(),n=ko(e.get(`view`)),r=e.get(`node`)??`__cluster__`,[a,s]=u(0),[c,l]=u(!1);return f(()=>{n===`nodes`&&!e.get(`node`)&&t({view:`nodes`,node:Oo},{replace:!0})},[n,e,t]),i(Ke,{icon:le,title:`Pipeline`,subtitle:`Detection placement, load and per-camera runtime across the cluster.`,actions:i(V,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>s(e=>e+1),title:`Refresh`,children:[d(se,{className:`h-3.5 w-3.5`}),`Refresh`]}),nav:d(Ao,{viewMode:n,onNodes:()=>{t({view:`nodes`,node:r},{replace:!0})},onCameras:()=>{t({view:`cameras`},{replace:!0})}}),className:`flex h-full min-h-0 flex-col overflow-hidden`,children:[n===`nodes`&&i(V,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>l(e=>!e),"aria-expanded":c,className:`flex w-full shrink-0 justify-between border-b border-border md:hidden`,children:[i(`span`,{children:[c?`Hide`:`Show`,` node list`]}),d(oe,{className:[`h-4 w-4 transition-transform`,c?`rotate-180`:``].join(` `)})]}),d(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden md:flex-row`,children:n===`nodes`?i(o,{children:[d(`aside`,{className:[c?`block`:`hidden`,`md:block w-full md:w-72 shrink-0 border-b border-border md:border-b-0 md:border-r`,`max-h-[60vh] overflow-y-auto md:max-h-none`].join(` `),children:d(Bn,{selectedNodeId:r,onSelect:e=>{t({view:`nodes`,node:e},{replace:!0}),l(!1)},refreshToken:a})}),d(`section`,{className:`min-h-0 flex-1 overflow-hidden`,children:r===`__cluster__`?d(La,{refreshToken:a}):d(ci,{nodeId:r,refreshToken:a})})]}):d(`section`,{className:`min-h-0 flex-1 overflow-hidden`,children:d(Eo,{refreshToken:a})})})]})}var Mo=`ctab`,No=`section`;function Po(e,t){let n=new URLSearchParams({view:`nodes`,node:Oo,[Mo]:e});return t!==void 0&&n.set(No,t),`/system/pipeline?${n.toString()}`}function Fo(e){return Po(`settings`,Ea(e))}function Io(){return Po(`load-balancing`)}var Lo=`pipeline-orchestrator`;function Ro(e){return Ne.find(t=>t.stepId===e)??null}function zo({step:e,engineFormat:t,runnableModelIds:n}){let{data:r}=Wt({addonId:Lo}),a=ke(r??null)[e.stepId]??e.defaultModelId,o=e.options.find(e=>e.id===a)?.label??a,s=n.length>0&&!n.includes(a);return i(`div`,{className:`space-y-2 rounded-md border border-primary/30 bg-primary/5 px-3 py-2`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[d(`span`,{className:`font-medium text-foreground`,children:e.label}),d(`span`,{className:`font-mono text-foreground`,children:o}),d(`span`,{title:`One value for the whole cluster — this step writes into a shared vector index, where two encoders make similarity scores meaningless.`,className:`rounded border border-primary/40 bg-primary/10 px-1 py-px text-[9px] font-medium uppercase tracking-wide text-primary`,children:`cluster-wide`}),d(hn,{to:Fo(e.stepId),className:`ml-auto text-[11px] text-primary hover:underline`,children:`Change in Cluster → Settings ›`})]}),i(`p`,{className:B,children:[`One model for every node and camera: `,e.indexName,` only matches vectors from the model that made them.`]}),s&&i(`p`,{className:`rounded border border-warning/40 bg-warning/10 px-2 py-1 text-[10px] leading-snug text-warning`,children:[`This accelerator's engine (`,t,`) ships no build of `,d(`b`,{children:a}),`. It refuses this step rather than run a different encoder — a substitute would put a second feature space into `,e.indexName,`.`]})]})}export{Ar as _,Jr as a,Nr as c,zr as d,Vr as f,jr as g,Br as h,Yr as i,Gr as l,Rr as m,Ro as n,Lr as o,Wr as p,Do as r,Hr as s,zo as t,Ur as u,Dr as v,jn as y};
@@ -1 +0,0 @@
1
- import{G as e,I as t,K as n,Q as r,S as i,b as a,q as o,x as s,z as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{D as l,O as u,V as d,ot as f}from"./player-overlays-DWMIy1MJ.js";import{Ar as p,Cr as m,Dr as h,Er as g,Lr as _,Rr as v,Sr as y,Tr as b,_n as x,an as S,br as C,cn as w,hr as T,jr as E,ln as ee,on as te,sn as ne,vr as re,wr as ie,yr as ae}from"./client-CjyKfSu1.js";import{Bn as D,Li as oe,Ln as O,Ua as se,Xl as ce,Zn as le,ar as ue,cu as de,ji as fe,ma as k,pa as pe,s as me,uu as he}from"./src-BLkInT8U.js";import{t as A}from"./useTranslation-Bc5yH9V9.js";r();function ge(e){return{target:{kind:`new`,type:e},name:``,features:[]}}function _e(e){return{target:{kind:`existing`,device:e},name:``,features:[]}}function j(e,t){return{target:e.target,name:t,features:e.features.flatMap(e=>e.kind===`fields`?[e]:[])}}function M(e,t,n){return{...e,features:e.features.map(e=>e.cap===t?n(e):e)}}function N(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ve(e,t){switch(t.type){case`set-new-type`:return e.target.kind===`new`?{...e,target:{...e.target,type:t.deviceType}}:e;case`set-new-role`:{if(e.target.kind!==`new`)return e;let{role:n,...r}=e.target;return{...e,target:t.role===null?r:{...r,role:t.role}}}case`set-name`:return{...e,name:t.name};case`add-feature`:return e.features.some(e=>e.cap===t.cap)?e:{...e,features:[...e.features,{kind:`fields`,cap:t.cap,fields:{}}]};case`remove-feature`:return{...e,features:e.features.filter(e=>e.cap!==t.cap)};case`set-field`:return M(e,t.cap,e=>({...e,fields:{...e.fields,[t.path]:t.source}}));case`clear-field`:return M(e,t.cap,e=>({...e,fields:N(e.fields,t.path)}));case`remove-binding`:return M(e,t.cap,e=>{let n=e.fields[t.path];return n?.kind===`expression`?{...e,fields:{...e.fields,[t.path]:{...n,bindings:N(n.bindings,t.bindingName)}}}:e});case`copy-feature`:return M(e,t.cap,e=>({...e,fields:{...e.fields,...Object.fromEntries(t.paths.map(e=>[e,{kind:`from`,source:t.from,cap:t.sourceCap,fieldPath:e}]))}}))}}function ye(e){let t=C.safeParse({target:e.target,features:e.features});return t.success?{ok:!0,composition:t.data}:{ok:!1,problems:t.error.issues.map(e=>`${e.path.join(`.`)||`composition`}: ${e.message}`)}}function be(e,t){return JSON.stringify(e)!==JSON.stringify(t)}function xe(e){for(let t=1;;t++){let n=`s${t}`;if(!e.includes(n))return n}}var Se=[`room`,`converted-sensor`,`derived-binary`],P={addonId:`provider-homeassistant`,stableId:`sensor.template_source`};function Ce(){return j(w({temperatureSources:te,motionSources:S,occupancyWindowMs:ne}),`Room`)}function we(){return j({target:{kind:`new`,type:E.Sensor},features:[{kind:`fields`,cap:`numeric-sensor`,fields:{value:{kind:`expression`,expr:`convert(v, "°C", "°F")`,bindings:{v:{kind:`from`,source:P,cap:`numeric-sensor`,fieldPath:`value`}}},unit:{kind:`expression`,expr:`"°F"`,bindings:{}},lastFetchedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Converted sensor`)}function Te(){return j({target:{kind:`new`,type:E.Sensor},features:[{kind:`fields`,cap:`binary`,fields:{on:{kind:`expression`,expr:`v > 20`,bindings:{v:{kind:`from`,source:P,cap:`temperature-sensor`,fieldPath:`celsius`}}},lastChangedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Derived binary`)}function Ee(e){switch(e){case`room`:return Ce();case`converted-sensor`:return we();case`derived-binary`:return Te()}}function De(e,t){return typeof t==`number`&&Number.isFinite(t)&&t>0?{kind:`device`,path:`/devices/${t}`}:{kind:`editor`,path:`/build/compositions/${encodeURIComponent(e)}`}}var F=`rounded-lg border border-border bg-surface p-4`,Oe=F;function ke(e){return{addonId:e.addonId,stableId:e.stableId}}function I(e){return new Map(e.map(e=>[g(ke(e)),e]))}function Ae(e,t,n){let r=e?.features??[],i=r.findIndex(e=>e.cap===n.cap);return{target:e?.target??{kind:`existing`,device:t},features:i===-1?[...r,n]:r.map((e,t)=>t===i?n:e)}}function je(e,t){let n=e.features.filter(e=>e.cap!==t);return n.length===0?null:{target:e.target,features:n}}function Me(e,t){let n=e?.features.find(e=>e.cap===t);return n!==void 0&&n.kind===`fields`?n:null}function L(e){return Array.isArray(e)?e.map(L):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,L(t)]))}function R(e){return JSON.stringify(L(e))}function Ne(e,t){return R(e)===R(t)}function z(e,t){return R(e)===R(t)}function Pe(e,t){switch(e.kind){case`pending`:return{kind:`refused`,reason:`the customization has not been read yet — try again`};case`unknown`:return{kind:`refused`,reason:`the customization could not be read: ${e.reason}`};case`not-loaded`:return{kind:`refused`,reason:`the customizations are not loaded yet: ${e.reason}`};case`none`:return t===null?{kind:`noop`}:{kind:`create`,input:{enabled:!0,composition:t}};case`present`:{let n=e.view.block.id;return t===null?{kind:`delete`,blockId:n}:R(t)===R(e.composition)?{kind:`noop`}:{kind:`update`,blockId:n,expectedUpdatedAt:e.view.block.updatedAt,composition:t}}}}function B(e,t){let n=e===`enum`?`string`:e,r=t.kind===`enum`?`string`:t.kind,i={source:t.source,cap:t.cap,fieldPath:t.fieldPath};return r===n?{kind:`from`,...i}:n===`number`&&r===`string`?{kind:`expression`,expr:`number(x)`,bindings:{x:{kind:`from`,...i}}}:null}function V(e){return{kind:`expression`,expr:e,bindings:{}}}function H(e){let t=B(`number`,e.percentage);return t===null?null:{kind:`fields`,cap:`battery`,fields:e.mode===`replace`?{percentage:t}:{percentage:t,charging:V(`"unknown"`),sleeping:V(`false`),lastUpdated:V(`now`)}}}var Fe=[`percent`,...x.options];function U(e,t){return t===`percent`?{level:e}:{"remaining.value":e,"remaining.unit":V(JSON.stringify(t))}}function Ie(e,t){let n=B(`number`,t.remaining);if(n===null||!ae.test(t.key)||t.label.trim()===``)return null;let r={label:t.label.trim(),fields:U(n,t.unit)};return{kind:`fields`,cap:`consumables`,...e?.enabled===void 0?{}:{enabled:e.enabled},fields:e?.fields??{lastChangedAt:V(`now`),lastFetchedAt:V(`now`)},items:{...e?.items,[t.key]:r}}}function Le(e){if(e.level!==void 0)return`percent`;let t=e[`remaining.unit`];if(t===void 0||t.kind!==`expression`)return null;try{let e=x.safeParse(JSON.parse(t.expr));return e.success?e.data:null}catch{return null}}function Re(e){return Object.entries(e?.items??{}).map(([e,t])=>{let n=Le(t.fields),r=W(t.fields.level??t.fields[`remaining.value`]),i=r===null?null:B(`number`,r);return n!==null&&i!==null&&Ne(U(i,n),t.fields)?{key:e,label:t.label,unit:n,source:r}:{key:e,label:t.label,unit:null,source:null}})}function ze(e,t){let n=Object.fromEntries(Object.entries(e.items??{}).filter(([e])=>e!==t));return Object.keys(n).length===0?null:{...e,items:n}}function Be(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48)}function Ve(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=Object.entries(t.bindings).filter(([e])=>e.startsWith(`active`)).flatMap(([,e])=>e.kind===`from`?[e.source]:[]);return[...new Map(n.map(e=>[g(e),e])).values()]}function He(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=t.bindings;return Object.entries(n).flatMap(([e,t])=>{if(!e.startsWith(`active`)||t.kind!==`from`)return[];let r=n[`changed${e.slice(6)}`];return r===void 0||r.kind!==`from`?[]:[{source:t.source,cap:t.cap,activeField:t.fieldPath,changedAtField:r.fieldPath}]})}function W(e){if(e===void 0)return null;if(e.kind===`from`){let{kind:t,...n}=e;return{...n,kind:`number`}}if(e.kind!==`expression`||e.expr!==`number(x)`)return null;let t=e.bindings.x;if(t===void 0||t.kind!==`from`||Object.keys(e.bindings).length!==1)return null;let{kind:n,...r}=t;return{...r,kind:`string`}}function Ue(e,t){let n=W(e.fields.percentage);if(n===null)return!1;let r=H({percentage:n,mode:t}),{enabled:i,...a}=e;return r!==null&&z(a,r)}function G(e){return e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,location:e.location,type:e.type}))}function We(e,t,n){let r=t.trim().toLowerCase();return r===``?[]:e.filter(e=>!n.includes(e.id)&&[e.name,e.stableId,e.location??``].some(e=>e.toLowerCase().includes(r))).toSorted((e,t)=>e.name.localeCompare(t.name)).slice(0,20)}function K(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=Object.getOwnPropertyDescriptor(n,e)?.value}return n}function Ge(e,t,n,r){return r===null?{kind:`from`,source:e,cap:t,fieldPath:n.path}:B(r,{source:e,cap:t,fieldPath:n.path,kind:n.kind})}function Ke(e,t,n,r){let i={addonId:e.addonId,stableId:e.stableId};return t.caps.flatMap(e=>e.fields.filter(e=>e.item!==!0).map(t=>({cap:e.cap,path:t.path,kind:t.kind,value:n===null?void 0:K(n[e.cap],t.path),source:Ge(i,e.cap,t,r)})))}function q(e,t){return t?e===void 0?`—`:e===null?`null`:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e):`…`}var qe=[];function J({title:e,targetKind:t,excludeDeviceIds:n=qe,onPick:r,onCancel:a}){let{t:c}=A(),[f,p]=o(null);return i(`aside`,{"aria-label":e,className:`${u} ${l} flex flex-col gap-2`,children:[s(`h3`,{className:d,children:e}),f===null?s(Je,{excludeDeviceIds:n,onSelect:p}):s(Y,{device:f,targetKind:t,onPick:r,onBack:()=>p(null)}),s(`div`,{children:s(D,{variant:`ghost`,size:`sm`,onClick:a,children:c(`customize.picker.cancel`)})})]})}function Je({excludeDeviceIds:e,onSelect:t}){let{t:n}=A(),[r,c]=o(``),l=k({projection:`slim`});return i(a,{children:[i(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground-subtle`,children:[n(`customize.picker.search`),s(ce,{type:`search`,"aria-label":n(`customize.picker.search`),value:r,onChange:e=>c(e.target.value)})]}),l.status===`pending`&&s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:n(`customize.picker.loadingDevices`)}),l.status===`error`&&s(O,{title:n(`customize.picker.devicesFailed`),message:l.error?.message??``}),l.status===`success`&&s(`ul`,{className:`flex flex-col gap-1`,children:We(G(l.data),r,e).map(e=>s(`li`,{children:i(`button`,{type:`button`,className:`text-left text-[11px] hover:underline`,onClick:()=>t(e),children:[e.name,` `,i(`span`,{className:`text-foreground-subtle`,children:[`· `,e.stableId]})]})},e.id))})]})}function Y({device:e,targetKind:t,selected:n,onPick:r,onBack:a}){let{t:o}=A(),c=pe({deviceId:e.id}),l=se({deviceId:e.id});if(c.status===`pending`)return s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.picker.loadingFields`)});if(c.status===`error`)return s(O,{title:o(`customize.picker.fieldsFailed`),message:c.error?.message??``});let u=Ke(e,c.data,l.status===`success`?l.data:null,t),d=u.filter(e=>e.source===null).length,f={addonId:e.addonId,stableId:e.stableId};return i(`div`,{className:`flex flex-col gap-1`,children:[i(`button`,{type:`button`,className:`text-left text-[11px] text-primary`,onClick:a,children:[`← `,e.name]}),l.status===`error`&&s(`p`,{role:`alert`,className:`text-[10px] text-warning`,children:o(`customize.picker.valuesFailed`,{reason:l.error?.message??``})}),s(`ul`,{role:`listbox`,"aria-label":o(`customize.picker.fields`),className:`flex flex-col gap-1`,children:u.map(t=>{let a=t.source;if(a===null)return null;let o=()=>r({device:e,ref:f,cap:t.cap,path:t.path,kind:t.kind,source:a,value:t.value});return i(`li`,{role:`option`,"aria-selected":n?.cap===t.cap&&n.path===t.path,tabIndex:0,className:`flex justify-between gap-2 text-[11px] cursor-pointer hover:bg-surface-hover rounded px-1`,onClick:o,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&o()},children:[i(`span`,{className:`font-mono`,children:[t.cap,`.`,t.path]}),s(`span`,{children:q(t.value,l.status===`success`)})]},`${t.cap}.${t.path}`)})}),d>0&&t!==null&&s(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`customize.picker.hidden`,{count:d,kind:o(`customize.kinds.${t}`)})})]})}var Ye=`integration`;function X(e,t){switch(e.kind){case`from`:{let n=g(e.source);return`${t.get(n)??n} · ${e.cap}.${e.fieldPath}`}case`expression`:return e.expr;case`code`:return`code`}}function Xe(e,t){if(e.kind===`unreachable`)return{kind:`unknown`,reason:e.error};if(e.state===null)return{kind:`unknown`,reason:`the composer has not reported this customization yet`};let n=e.state.fields.find(t);return n===void 0?{kind:`unknown`,reason:`the composer reports no value for this field`}:n.state===`unavailable`?{kind:`unavailable`,reason:n.reason??`unavailable`}:{kind:`value`,value:n.value,staleReason:n.state===`stale`?n.reason??`stale`:null}}function Ze(e,t,n,r){return{key:`${e.feature.cap}.${t}`,cap:e.feature.cap,field:t,origin:`composed`,mode:e.mode,from:X(n,e.input.sourceNames),value:e.enabled?Xe(e.input.state,r):{kind:`off`}}}function Qe(e){let t=e.feature.cap;return Object.entries(e.feature.fields).map(([n,r])=>Ze(e,n,r,e=>e.cap===t&&e.path===n&&e.item===void 0))}function $e(e){let t=e.feature.cap;return Object.entries(e.feature.items??{}).flatMap(([n,r])=>Object.entries(r.fields).map(([r,i])=>Ze(e,m(re,n,r),i,e=>e.cap===t&&e.path===r&&e.item?.arrayPath===`items`&&e.item.key===n)))}function et(e,t,n){if(e===null)return{kind:`unknown`,reason:`the device state could not be read`};let r=K(e[t],n),i=r===void 0?void 0:_(r);return i===void 0?{kind:`unknown`,reason:`not reported`}:{kind:`value`,value:i,staleReason:null}}function tt(e){if(e.mode!==`replace`)return[];let t=e.feature.cap,n=new Set(Object.keys(e.feature.fields));return(e.input.nativeFields.get(t)??[]).filter(e=>!n.has(e)).map(n=>({key:`${t}.${n}`,cap:t,field:n,origin:`native`,mode:e.mode,from:Ye,value:et(e.input.snapshot,t,n)}))}function nt(e){return e.composition.features.flatMap(t=>{if(t.kind!==`fields`)return[];let n={feature:t,mode:e.nativeCaps.has(t.cap)?`replace`:`add`,enabled:y(t),input:e};return[...Qe(n),...$e(n),...tt(n)]})}var rt={min:`min(a, b, …)`,max:`max(a, b, …)`,abs:`abs(x)`,floor:`floor(x)`,ceil:`ceil(x)`,sqrt:`sqrt(x)`,round:`round(x, digits?)`,pow:`pow(x, y)`,clamp:`clamp(x, lo, hi)`,avg:`avg(a, b, …)`,sum:`sum(a, b, …)`,coalesce:`coalesce(a, b, …)`,age:`age(now, ts)`,convert:`convert(x, "from", "to")`,any:`any(a, b, …)`,all:`all(a, b, …)`,within:`within(ts, ms)`,number:`number(x)`,latest:`latest(ts, …)`,rose:`rose(level, changedAt, debounceMs?)`,count:`count(x)`},Z=/[A-Za-z_][A-Za-z0-9_]*$/;function it(e,t,n){let r=Z.exec(e.slice(0,t))?.[0]??``;if(r===``)return[];let i=n.filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`binding`,label:e,insert:e,hintKey:null})),a=`now`.startsWith(r)?[{kind:`now`,label:`now`,insert:`now`,hintKey:`compositionEditor.now`}]:[],o=[...v].filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`builtin`,label:rt[e]??e,insert:`${e}(`,hintKey:`compositionEditor.builtins.${e}`}));return[...i,...a,...o].slice(0,8)}function at(e,t,n){let r=t-(Z.exec(e.slice(0,t))?.[0]??``).length;return{text:`${e.slice(0,r)}${n.insert}${e.slice(t)}`,cursor:r+n.insert.length}}r();function ot({label:e,value:t,bindings:r,onChange:a}){let{t:c}=A(),l=n(null),[u,d]=o(t.length),f=it(t,u,r);return i(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[e,s(`input`,{ref:l,className:`font-mono px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`,value:t,onChange:e=>{a(e.target.value),d(e.target.selectionStart??e.target.value.length)},onSelect:e=>d(e.currentTarget.selectionStart??t.length)})]}),f.length>0&&s(`ul`,{role:`listbox`,"aria-label":c(`compositionEditor.suggestions`),className:`rounded border border-border bg-surface text-[11px]`,children:f.map(e=>i(`li`,{role:`option`,"aria-selected":!1,tabIndex:0,className:`flex justify-between gap-2 px-1 cursor-pointer hover:bg-surface-hover`,onClick:()=>{let n=at(t,u,e);a(n.text),d(n.cursor),l.current?.focus()},children:[s(`span`,{className:`font-mono`,children:e.label}),e.hintKey!==null&&s(`span`,{className:`text-foreground-subtle`,children:c(e.hintKey)})]},`${e.kind}:${e.label}`))})]})}function st(e,t,n){if(e.kind===`code`)return{kind:`unavailable`,reason:`code fields arrive in slice 4`};if(e.kind===`expression`&&(T(e.expr,`rose`)||T(e.expr,`count`)))return{kind:`runtime-only`};let r=h(e).filter(e=>t.get(b(e.source,e.cap))?.kind!==`value`).map(ie);if(r.length>0)return{kind:`waiting`,missing:r};let i=ee({source:e,now:n,read:e=>{let n=t.get(b(e.source,e.cap)),r=n?.kind===`value`?K(n.slice,e.fieldPath):void 0,i=r===void 0?void 0:_(r);return i===void 0?{state:`unavailable`,reason:`${e.cap}.${e.fieldPath} is not reported`,fatal:!1}:{state:`fresh`,value:i}}});return i.state===`unavailable`?{kind:`unavailable`,reason:i.reason}:{kind:`value`,value:i.value,stale:i.reason}}r();function ct({sliceKey:e,deviceId:t,capName:n,onReading:r}){let i=me(f().trpcClient,t,n);return c(()=>{r(e,i===void 0?{kind:`pending`}:{kind:`value`,slice:i})},[e,i,r]),null}function lt(e,t){return[...new Map(h(e).map(e=>[b(e.source,e.cap),e]))].map(([e,n])=>({key:e,read:n,device:t.get(g(n.source))}))}function ut({source:e}){let{t:n}=A(),r=k({projection:`slim`}),[a,c]=o(new Map),l=t((e,t)=>{c(n=>new Map([...n,[e,t]]))},[]),u=lt(e,I(r.status===`success`?G(r.data):[])),d=r.status===`success`?u.filter(e=>e.device===void 0).map(e=>g(e.read.source)):[];return i(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px]`,children:[u.map(e=>e.device===void 0?null:s(ct,{sliceKey:e.key,deviceId:e.device.id,capName:e.read.cap,onReading:l},e.key)),s(`span`,{className:`text-foreground-subtle`,children:n(`compositionEditor.preview.label`)}),r.status===`error`?s(`span`,{className:`text-warning`,children:n(`compositionEditor.preview.devicesFailed`,{reason:r.error?.message??``})}):d.length>0?s(`span`,{className:`text-warning`,children:n(`compositionEditor.preview.unknownDevice`,{sources:d.join(`, `)})}):s(dt,{preview:st(e,a,Date.now())})]})}function dt({preview:e}){let{t}=A();switch(e.kind){case`value`:return i(`strong`,{children:[`→ `,q(e.value,!0),e.stale===null?``:` (${e.stale})`]});case`unavailable`:return s(`span`,{className:`text-warning`,children:e.reason});case`waiting`:return s(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.waiting`,{sources:e.missing.join(`, `)})});case`runtime-only`:return s(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.runtimeOnly`)})}}r();function ft({path:e,kind:t,required:n,source:r,onSet:c,onClear:l,onRemoveBinding:u,sourceNames:d}){let{t:f}=A(),[p,m]=o(`idle`),h=r?.kind===`expression`?r:null;return i(`div`,{className:`flex flex-col gap-1 rounded border border-border p-2`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`font-mono text-[11px]`,children:e}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:[f(`customize.kinds.${t}`),n?` · ${f(`compositionEditor.required`)}`:``]}),s(D,{size:`sm`,variant:`outline`,onClick:()=>m(`take`),children:f(`compositionEditor.takeFrom`)}),s(D,{size:`sm`,variant:`outline`,"aria-pressed":h!==null,onClick:()=>c(h??{kind:`expression`,expr:`null`,bindings:{}}),children:f(`compositionEditor.formula`)}),r!==void 0&&s(D,{size:`sm`,variant:`ghost`,onClick:l,children:f(`compositionEditor.clear`)})]}),r?.kind===`from`&&s(`span`,{className:`text-[11px]`,children:X(r,d)}),h!==null&&i(a,{children:[s(ot,{label:f(`compositionEditor.formulaFor`,{path:e}),value:h.expr,bindings:Object.keys(h.bindings),onChange:e=>c({...h,expr:e})}),s(`ul`,{className:`text-[11px] flex flex-col gap-0.5`,children:Object.entries(h.bindings).map(([e,t])=>i(`li`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`font-mono`,children:e}),s(`span`,{children:t.kind===`from`?X(t,d):JSON.stringify(t.value)}),s(D,{size:`sm`,variant:`ghost`,"aria-label":f(`compositionEditor.removeBinding`,{name:e}),onClick:()=>u(e),children:`×`})]},e))}),s(D,{size:`sm`,variant:`ghost`,onClick:()=>m(`add-binding`),children:f(`compositionEditor.addSource`)})]}),p!==`idle`&&s(J,{title:f(p===`take`?`compositionEditor.takeFrom`:`compositionEditor.addSource`),targetKind:p===`take`?t:null,onCancel:()=>m(`idle`),onPick:e=>{if(p===`take`)c(e.source);else if(h!==null){let t=xe(Object.keys(h.bindings));c({...h,bindings:{...h.bindings,[t]:{kind:`from`,source:e.ref,cap:e.cap,fieldPath:e.path}}})}m(`idle`)}}),r!==void 0&&s(ut,{source:r})]})}r();function Q(e){return e===null||e.kind===`known`?null:e}function pt({draft:e,deviceType:t,nativeCaps:n,targetFields:r,dispatch:c}){let{t:l}=A(),u=fe({deviceType:t}),d=k({projection:`slim`}),f=new Map([...I(d.status===`success`?G(d.data):[])].map(([e,t])=>[e,t.name])),[p,m]=o(null),h=Q(n)??Q(r),g=n?.kind===`known`?n.value:new Set,_=new Set(e.features.map(e=>e.cap)),v=u.status===`success`?u.data.caps.filter(e=>!_.has(e.cap)&&!g.has(e.cap)):[],y=[...g].filter(e=>!_.has(e)),b=e=>g.has(e)?((r?.kind===`known`?r.value.caps.find(t=>t.cap===e):void 0)?.fields??[]).filter(e=>e.item!==!0&&!e.path.includes(`.`)).map(e=>({path:e.path,kind:e.kind,required:!1})):((u.status===`success`?u.data.caps.find(t=>t.cap===e):void 0)?.fields??[]).map(e=>({path:e.path,kind:e.kind,required:e.required}));return h===null?i(a,{children:[i(`section`,{"aria-labelledby":`editor-features`,className:`${F} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),u.status===`pending`&&s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.checking`)}),u.status===`error`&&s(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.unknown`,{reason:u.error?.message??``})}),i(`div`,{className:`flex flex-wrap gap-1`,children:[e.features.map(e=>i(`span`,{className:`flex items-center gap-1 rounded border border-border px-1.5 text-[11px]`,children:[e.cap,s(ue,{variant:g.has(e.cap)?`default`:`info`,children:g.has(e.cap)?l(`compositionEditor.replaces`):l(`compositionEditor.added`)}),s(`button`,{type:`button`,"aria-label":l(`compositionEditor.removeFeature`,{cap:e.cap}),onClick:()=>c({type:`remove-feature`,cap:e.cap}),children:`×`})]},e.cap)),v.map(e=>i(D,{size:`sm`,variant:`outline`,onClick:()=>c({type:`add-feature`,cap:e.cap}),children:[`+ `,e.cap]},e.cap)),y.map(e=>s(D,{size:`sm`,variant:`ghost`,onClick:()=>c({type:`add-feature`,cap:e}),children:l(`compositionEditor.replaceIn`,{cap:e})},e))]})]}),e.features.map(e=>i(`section`,{"aria-label":l(`compositionEditor.steps.fieldsOf`,{cap:e.cap}),className:`${F} flex flex-col gap-2`,children:[i(`div`,{className:`flex items-center justify-between`,children:[s(`h2`,{className:`text-sm font-semibold`,children:l(`compositionEditor.steps.fieldsOf`,{cap:e.cap})}),s(D,{size:`sm`,variant:`outline`,onClick:()=>m(e.cap),children:l(`compositionEditor.copyFeature`)})]}),p===e.cap&&s(J,{title:l(`compositionEditor.copyFeature`),targetKind:null,onCancel:()=>m(null),onPick:t=>{c({type:`copy-feature`,cap:e.cap,from:t.ref,sourceCap:t.cap,paths:b(e.cap).map(e=>e.path)}),m(null)}}),b(e.cap).map(t=>s(ft,{path:t.path,kind:t.kind,required:t.required,source:e.fields[t.path],onSet:n=>c({type:`set-field`,cap:e.cap,path:t.path,source:n}),onClear:()=>c({type:`clear-field`,cap:e.cap,path:t.path}),onRemoveBinding:n=>c({type:`remove-binding`,cap:e.cap,path:t.path,bindingName:n}),sourceNames:f},t.path))]},e.cap))]}):i(`section`,{"aria-labelledby":`editor-features`,className:`${F} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:h.kind===`unknown`?h.reason:l(`compositionEditor.reading`)})]})}var $=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function mt({draft:e,targetName:t,dispatch:n}){let{t:r}=A(),a=e.target;return i(`section`,{"aria-labelledby":`editor-target`,className:`${F} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-target`,className:`text-sm font-semibold`,children:r(`compositionEditor.steps.target`)}),a.kind===`existing`?s(`p`,{className:`text-[11px]`,children:r(`compositionEditor.existingTarget`,{name:t??`${a.device.addonId}/${a.device.stableId}`})}):i(`div`,{className:`grid grid-cols-3 gap-2`,children:[i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[r(`compositionEditor.targetType`),s(`select`,{className:$,value:a.type,onChange:e=>{let t=Object.values(E).find(t=>t===e.target.value);t!==void 0&&n({type:`set-new-type`,deviceType:t})},children:Object.values(E).map(e=>s(`option`,{value:e,children:he(e).label},e))})]}),i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[r(`customize.identity.role`),i(`select`,{className:$,value:a.role??``,onChange:e=>n({type:`set-new-role`,role:Object.values(p).find(t=>t===e.target.value)??null}),children:[s(`option`,{value:``,children:r(`customize.identity.noRole`)}),Object.values(p).map(e=>s(`option`,{value:e,children:de(e).label},e))]})]}),i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[r(`compositionEditor.name`),s(`input`,{className:$,value:e.name,onChange:e=>n({type:`set-name`,name:e.target.value})})]})]})]})}r();function ht({draft:e,blockId:t,saving:n,onSave:r,onCancel:a}){let{t:l}=A(),u=oe(),d=ye(e),f=d.ok?JSON.stringify(d.composition):``,[p,m]=o({key:``,state:{kind:`checking`}});c(()=>{if(!d.ok)return;let e=d.composition,n=setTimeout(()=>{u.mutateAsync({composition:e,...t===null?{}:{blockId:t}}).then(e=>m({key:f,state:e.ok?{kind:`ok`}:{kind:`refused`,problems:e.problems}})).catch(e=>m({key:f,state:{kind:`unknown`,reason:e instanceof Error?e.message:String(e)}}))},500);return()=>clearTimeout(n)},[f,t]);let h=d.ok?p.key===f?p.state:{kind:`checking`}:{kind:`invalid-draft`,problems:d.problems};return i(`section`,{"aria-labelledby":`editor-verify`,className:`${F} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-verify`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.verify`)}),h.kind===`checking`&&s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.verify.checking`)}),h.kind===`ok`&&s(`p`,{className:`text-[11px] text-success`,children:l(`compositionEditor.verify.ok`)}),h.kind===`unknown`&&s(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.verify.unknown`,{reason:h.reason})}),(h.kind===`invalid-draft`||h.kind===`refused`)&&s(`ul`,{role:`alert`,className:`flex flex-col gap-1 text-[11px] text-danger`,children:h.kind===`invalid-draft`?h.problems.map(e=>s(`li`,{children:e},e)):h.problems.map(e=>i(`li`,{children:[s(`span`,{className:`font-mono`,children:e.path}),` — `,e.message]},`${e.path}:${e.code}`))}),i(`div`,{className:`flex gap-2`,children:[s(D,{variant:`ghost`,onClick:a,children:l(`compositionEditor.cancel`)}),s(D,{disabled:h.kind!==`ok`||n||!d.ok,onClick:()=>d.ok&&r(d.composition),children:l(`compositionEditor.save`)})]})]})}r();function gt({initial:e,blockId:t,deviceType:n,targetName:r=null,nativeCaps:i,targetFields:a,save:c,onCancel:l,showTemplates:u=!1}){let[d,f]=o(e),p=`${d.name}:${d.features.map(e=>e.cap).join(`,`)}:${d.target.kind===`new`?d.target.type:`existing`}`;return s(_t,{seed:d,blockId:t,deviceType:n,targetName:r,nativeCaps:i,targetFields:a,showTemplates:u,onApplyTemplate:e=>{f(Ee(e))},save:c,onCancel:l},p)}function _t({seed:t,blockId:n,deviceType:r,targetName:a,nativeCaps:c,targetFields:l,showTemplates:u,onApplyTemplate:d,save:f,onCancel:p}){let{t:m}=A(),h=le(),[g,_]=e(ve,t),[v,y]=o(!1),[b,x]=o(null),S=async e=>{be(t,g)&&!await h({title:m(`compositionEditor.templates.confirmTitle`),message:m(`compositionEditor.templates.confirmMessage`),confirmLabel:m(`compositionEditor.templates.confirmApply`),variant:`danger`})||d(e)},C=g.target.kind===`new`?g.target.type:r,w=async e=>{y(!0);let t=await f(e,g.name);y(!1),x(t.kind===`refused`?t.reason:null)};return i(`div`,{className:`flex flex-col gap-4`,children:[u&&g.target.kind===`new`&&i(`div`,{className:`rounded-lg border border-border bg-surface p-4 flex flex-wrap gap-2`,"data-testid":`composition-templates`,children:[s(`span`,{className:`text-[11px] text-foreground-subtle self-center`,children:m(`compositionEditor.templates.label`)}),Se.map(e=>s(D,{size:`sm`,variant:`outline`,onClick:()=>void S(e),children:m(`compositionEditor.templates.${e}`)},e))]}),s(mt,{draft:g,targetName:a,dispatch:_}),s(pt,{draft:g,deviceType:C,nativeCaps:c,targetFields:l,dispatch:_}),s(ht,{draft:g,blockId:n,saving:v,onSave:e=>void w(e),onCancel:p}),b!==null&&s(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:b})]})}export{je as C,_e as D,j as E,ge as O,Ae as S,De as T,W as _,Y as a,Pe as b,G as c,Ie as d,Re as f,Be as g,Ue as h,nt as i,Fe as l,He as m,st as n,q as o,Ve as p,ot as r,K as s,gt as t,H as u,ze as v,Oe as w,z as x,Me as y};