@camstack/addon-admin-ui 1.2.288 → 1.2.290

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 (105) hide show
  1. package/dist/assets/{AddonCollectionPage-C7ayIMM9.js → AddonCollectionPage-D1pWGGvT.js} +1 -1
  2. package/dist/assets/Addons-BZ97Xzg1.js +1 -0
  3. package/dist/assets/{AdminTabs-CsuISePK.js → AdminTabs-DJBff_i8.js} +1 -1
  4. package/dist/assets/AiProfiles-B2ZTI_l9.js +3 -0
  5. package/dist/assets/{BrokerForm-dRYlE1mM.js → BrokerForm-qoePj2K4.js} +1 -1
  6. package/dist/assets/Build-C2d1cwHA.js +32 -0
  7. package/dist/assets/{Capabilities-hmBG5iHS.js → Capabilities-S4kRIl4K.js} +1 -1
  8. package/dist/assets/{CapabilityBadges-swlED12j.js → CapabilityBadges-DwWL_l7c.js} +1 -1
  9. package/dist/assets/Cluster-67TUhWLy.js +11 -0
  10. package/dist/assets/CompositionEditor-D1r-JisY.js +1 -0
  11. package/dist/assets/CompositionEditorPage-B9h3eUkU.js +1 -0
  12. package/dist/assets/Data-CTGdXReL.js +1 -0
  13. package/dist/assets/DetectionIntelligence-ClVstSbX.js +1 -0
  14. package/dist/assets/DeviceAggregateSection-VpXFysnh.js +1 -0
  15. package/dist/assets/DeviceDetail-BC1J_Uus.js +2 -0
  16. package/dist/assets/{Devices-BpRz1Xdn.js → Devices-ENl1rQTV.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-Lm-KdV8M.js → EmbedPlayerPage-CZv8OzxI.js} +1 -1
  18. package/dist/assets/Events-BAtHdRH_.js +1 -0
  19. package/dist/assets/{FormBuilder-C2WDUIjk.js → FormBuilder-DmVp78xs.js} +1 -1
  20. package/dist/assets/Identity-DBJbXwFL.js +1 -0
  21. package/dist/assets/IntegrationDetail-BOSgQh4k.js +1 -0
  22. package/dist/assets/Integrations-B9TIBbr7.js +1 -0
  23. package/dist/assets/Integrations-DGY8tg5o.js +1 -0
  24. package/dist/assets/Locations-Cb0oJLNi.js +3 -0
  25. package/dist/assets/{Logs-DaR2eWH8.js → Logs-BwQ51kvC.js} +1 -1
  26. package/dist/assets/{ModelLicenses-C_yuUYF0.js → ModelLicenses-URNrQt1_.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-lG9ICzYm.js → MotionZonesSettings-YQ3UaVz7.js} +1 -1
  28. package/dist/assets/{MyAccess-Dg3wNIyX.js → MyAccess-_aiNFcbi.js} +1 -1
  29. package/dist/assets/Network-GxxrMQ2A.js +1 -0
  30. package/dist/assets/{NodeAddonsSettingsPanel-nVujTUZd.js → NodeAddonsSettingsPanel-BY9z0lZa.js} +1 -1
  31. package/dist/assets/{NodeInferenceDevices-D-9wjaea.js → NodeInferenceDevices-DZ-_1qB2.js} +1 -1
  32. package/dist/assets/Notifications-BmxbDLAS.js +1 -0
  33. package/dist/assets/Pipeline-Cod6aDKO.js +1 -0
  34. package/dist/assets/{Plates-B9QC90DW.js → Plates-5zDioApI.js} +1 -1
  35. package/dist/assets/{PrivacyMaskSettings-B30owOPb.js → PrivacyMaskSettings-Bo3emiuH.js} +1 -1
  36. package/dist/assets/{ProviderIcon-Crd8UZSu.js → ProviderIcon-CnCmdk4B.js} +1 -1
  37. package/dist/assets/Recordings-s4jIucSI.js +1 -0
  38. package/dist/assets/{ScanNetworkModal-BP4y5EFU.js → ScanNetworkModal-DWiaxsCk.js} +1 -1
  39. package/dist/assets/{SceneMonitorEditor-LhHK_HEn.js → SceneMonitorEditor-CVrYjKnp.js} +1 -1
  40. package/dist/assets/{Scenes-tZH-TLIq.js → Scenes-CvM_wh49.js} +1 -1
  41. package/dist/assets/{Settings-6rkZTSqM.js → Settings-C0t6ywVO.js} +1 -1
  42. package/dist/assets/{Showroom-DWgZjcq9.js → Showroom-Dr0ztns6.js} +1 -1
  43. package/dist/assets/{StorageLocationsPanel-CGS6o7PS.js → StorageLocationsPanel-DYu23Cr2.js} +1 -1
  44. package/dist/assets/{Terminal-tVcEYJLE.js → Terminal-C3DyYl4d.js} +4 -4
  45. package/dist/assets/{Viewer-D4IO9n4B.js → Viewer-ig9o4_z0.js} +1 -1
  46. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-lPdCjOyw.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BXMJgpii.js} +1 -1
  47. package/dist/assets/{archive-BIXtiyjc.js → archive-Da1Yqakr.js} +1 -1
  48. package/dist/assets/{authed-media-qZnqtqU3.js → authed-media-BMuC_wHZ.js} +1 -1
  49. package/dist/assets/{boxes-DGsQ8Ror.js → boxes-Baa5Ogmj.js} +1 -1
  50. package/dist/assets/circle-slash-BRokabFn.js +1 -0
  51. package/dist/assets/{debounced-invalidate-ckAXYt7l.js → debounced-invalidate-BrkGpqQR.js} +1 -1
  52. package/dist/assets/{device-integration-icon-A7WLxehO.js → device-integration-icon-DMH1CC1W.js} +1 -1
  53. package/dist/assets/dist-B2jpWgNR.js +349 -0
  54. package/dist/assets/{dist-CD_CDfq5.js → dist-DnbX2Ts3.js} +1 -1
  55. package/dist/assets/{face-bbox-DAsDmJyI.js → face-bbox-CqL9Av-Z.js} +1 -1
  56. package/dist/assets/{hard-drive-download-BeXxSShB.js → hard-drive-download-BLcXiD8l.js} +1 -1
  57. package/dist/assets/{hostInit-DWQhlf0_.js → hostInit-DZGOkLOR.js} +1 -1
  58. package/dist/assets/index-DmZC8m5k.js +4 -0
  59. package/dist/assets/{index-Cz9U1hKX.css → index-Dw7R0OTh.css} +1 -1
  60. package/dist/assets/{layers-UeA2puY5.js → layers-CheyENp_.js} +1 -1
  61. package/dist/assets/{location-owned-usage-CfkxNajr.js → location-owned-usage-Cqkcqdng.js} +1 -1
  62. package/dist/assets/{mf-entry-bootstrap-0-fe41b9bb.js → mf-entry-bootstrap-0-f6e27852.js} +2 -2
  63. package/dist/assets/{player-overlays-ktPblw8g.js → player-overlays-COWJpSPo.js} +1 -1
  64. package/dist/assets/remoteEntry-4ktgOeTU.js +1 -0
  65. package/dist/assets/{send-fCs65tYo.js → send-WZjVf7tk.js} +1 -1
  66. package/dist/assets/{settings-2-DTnA9d2i.js → settings-2-CHLR6iGS.js} +1 -1
  67. package/dist/assets/{square-check-big-DBmxHLSu.js → square-check-big-x9DuWnSt.js} +1 -1
  68. package/dist/assets/src-CYsrYOj2.js +349 -0
  69. package/dist/assets/src-CxavCtUA.js +67 -0
  70. package/dist/assets/{use-scenes-feed-B7au-NxO.js → use-scenes-feed-C6zdrId0.js} +1 -1
  71. package/dist/assets/{use-stationary-objects-Dw5yZlWu.js → use-stationary-objects-CgZoUHn3.js} +1 -1
  72. package/dist/assets/{useDevice-Clhg6DiH.js → useDevice-DbxoO2nr.js} +1 -1
  73. package/dist/assets/useEventInvalidation-5ATLpxzV.js +1 -0
  74. package/dist/assets/{useNodeUrlSelection-D5mc9m1b.js → useNodeUrlSelection-CAolorcm.js} +1 -1
  75. package/dist/assets/user-round-5BSQ3oXA.js +1 -0
  76. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-XT7TEMtp.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Iofpk1rr.js} +2 -2
  77. package/dist/index.html +6 -6
  78. package/dist/server/addon.js +163 -46
  79. package/package.json +1 -1
  80. package/dist/assets/Addons-B5bJmt14.js +0 -1
  81. package/dist/assets/AiProfiles-m8NYS5Xf.js +0 -3
  82. package/dist/assets/Build-CJDVtUvY.js +0 -32
  83. package/dist/assets/Cluster-CZaH_7qk.js +0 -11
  84. package/dist/assets/Data-r8eVjOjz.js +0 -1
  85. package/dist/assets/DetectionIntelligence-C6IC_hni.js +0 -1
  86. package/dist/assets/DeviceAggregateSection-DbhqIKcA.js +0 -1
  87. package/dist/assets/DeviceDetail-CsUtnssS.js +0 -2
  88. package/dist/assets/Events-B8WC6qEf.js +0 -1
  89. package/dist/assets/Identity-B9RLqeSJ.js +0 -1
  90. package/dist/assets/IntegrationDetail-BdG1Ivd_.js +0 -1
  91. package/dist/assets/Integrations-B6lyndjU.js +0 -1
  92. package/dist/assets/Integrations-DtlGKWAz.js +0 -1
  93. package/dist/assets/Locations-vzJV0WMo.js +0 -3
  94. package/dist/assets/Network-CzchW8JE.js +0 -1
  95. package/dist/assets/Notifications-DYzExejZ.js +0 -1
  96. package/dist/assets/Pipeline-C6TlvtSX.js +0 -1
  97. package/dist/assets/Recordings-Bxw85cLZ.js +0 -1
  98. package/dist/assets/circle-slash-B5ut5l60.js +0 -1
  99. package/dist/assets/dist-BQE2PzNV.js +0 -349
  100. package/dist/assets/index-qsRpCvR5.js +0 -4
  101. package/dist/assets/remoteEntry-BZFveBpZ.js +0 -1
  102. package/dist/assets/src-CExJu3gi.js +0 -67
  103. package/dist/assets/src-DCJABiaG.js +0 -349
  104. package/dist/assets/useEventInvalidation-CNEhZXmE.js +0 -1
  105. package/dist/assets/user-round-COxdqZ7I.js +0 -1
@@ -1,2 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,a,b as o,o as s,q as c,t as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{G as f,U as p,W as m,X as h,_ as g,at as _,ht as v,lt as y,mt as b,q as x,r as S,st as C,t as w,ut as T,vt as E,yt as D}from"./player-overlays-ktPblw8g.js";import{$ as O,$r as k,A,Ai as j,Al as M,B as N,Bl as P,Cl as F,Co as I,Ct as L,Da as R,Di as z,Dl as B,Dt as V,Ei as ee,Fc as H,Fl as U,Fo as W,Fr as G,G as K,Gr as te,Gu as ne,H as q,Ht as re,I as ie,Io as ae,Jl as oe,Jr as se,K as ce,L as J,Lo as le,M as ue,Mc as de,Mu as fe,N as pe,Na as me,Nl as he,Nu as ge,O as _e,Oc as ve,Oi as ye,P as be,Pa as Y,Pr as xe,Q as Se,Qt as Ce,Si as we,St as Te,Tt as Ee,U as De,Uo as Oe,Ut as ke,Vt as Ae,W as je,Wt as Me,X as Ne,Y as Pe,Z as Fe,Zi as Ie,Zt as Le,_n as Re,_t as ze,a as Be,ai as Ve,b as He,bl as Ue,bt as We,c as Ge,cu as Ke,d as qe,dl as Je,ei as Ye,et as Xe,f as Ze,fi as Qe,fn as $e,go as et,gt as tt,gu as nt,hi as rt,ho as it,ht as at,i as ot,ii as st,is as ct,j as lt,jc as ut,jl as dt,ju as ft,kl as pt,l as mt,lr as ht,lu as gt,mn as _t,na as vt,nl as yt,nn as bt,o as xt,oi as St,pl as Ct,pn as wt,po as Tt,q as Et,qn as Dt,r as Ot,ra as kt,ri as At,s as jt,si as Mt,st as Nt,ta as Pt,tn as Ft,tt as It,u as Lt,ui as Rt,ut as zt,v as Bt,vl as Vt,w as Ht,wt as Ut,wu as Wt,x as Gt,xc as Kt,xi as qt,xt as Jt,y as Yt,yl as Xt,yo as Zt,yt as Qt,yu as $t,zl as en}from"./src-CExJu3gi.js";import{t as tn}from"./archive-BIXtiyjc.js";import{t as nn}from"./boxes-DGsQ8Ror.js";import{t as rn}from"./ProviderIcon-Crd8UZSu.js";import{t as an}from"./circle-slash-B5ut5l60.js";import{n as on}from"./NodeInferenceDevices-D-9wjaea.js";import{t as sn}from"./layers-UeA2puY5.js";import{t as cn}from"./CapabilityBadges-swlED12j.js";import{Nn as ln,Pn as un,a as dn,an as X,i as fn,rn as pn}from"./src-DCJABiaG.js";import{a as mn,c as hn,n as gn,o as _n,s as vn,u as yn}from"./index-qsRpCvR5.js";import{n as bn,t as xn}from"./useDevice-Clhg6DiH.js";import{t as Sn}from"./authed-media-qZnqtqU3.js";import"./useEventInvalidation-CNEhZXmE.js";import{t as Cn}from"./StatusBadge-CeptlsPG.js";import{t as wn}from"./use-stationary-objects-Dw5yZlWu.js";import{i as Tn,n as En,r as Dn,t as On}from"./DeviceAggregateSection-DbhqIKcA.js";var kn=D(`arrow-left-right`,[[`path`,{d:`M8 3 4 7l4 4`,key:`9rb6wj`}],[`path`,{d:`M4 7h16`,key:`6tx8e3`}],[`path`,{d:`m16 21 4-4-4-4`,key:`siv7j2`}],[`path`,{d:`M20 17H4`,key:`h6l3hr`}]]),An=D(`disc`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),jn=D(`ear`,[[`path`,{d:`M6 8.5a6.5 6.5 0 1 1 13 0c0 6-6 6-6 10a3.5 3.5 0 1 1-7 0`,key:`1dfaln`}],[`path`,{d:`M15 8.5a2.5 2.5 0 0 0-5 0v1a2 2 0 1 1 0 4`,key:`1qnva7`}]]);n();function Mn(e){if(typeof e!=`object`||!e)return null;let t=e,n=t.id,r=t.label;if(typeof n!=`string`||typeof r!=`string`)return null;let i=t.available===!0,a=t.enabled,o=t.unavailableReason;return{id:n,label:r,costWhenOff:typeof t.costWhenOff==`string`?t.costWhenOff:``,on:i&&typeof a==`boolean`?a:null,available:i,unavailableReason:typeof o==`string`?o:null}}function Nn(e){if(typeof e!=`object`||!e)return null;let t=e.switches;if(!Array.isArray(t))return null;let n=t.map(Mn).filter(e=>e!==null);return n.length===0?null:n}var Pn=[[/privacy|mask/i,`privacy`],[/microphone|mic\b/i,`microphone`],[/speaker|broker audio|stream audio/i,`speaker`],[/audio/i,`listening`],[/object|detect/i,`detection`],[/event/i,`archive`],[/record/i,`recording`],[/notif/i,`notifications`],[/stream|broker/i,`stream`]];function Fn(e){for(let[t,n]of Pn)if(t.test(e))return n;return`generic`}function In(e){let t=e.filter(e=>e.on===!1).map(e=>e.id),n=e.filter(e=>e.on===null).map(e=>e.id),r=t=>t.map(t=>e.find(e=>e.id===t)?.label??t).join(`, `),i=[];return t.length>0&&i.push(`Off: ${r(t)}`),n.length>0&&i.push(`Unknown: ${r(n)}`),{offIds:t,unknownIds:n,summary:i.length===0?`All camera functions on`:i.join(` · `)}}var Ln={stream:Ue,detection:yn,privacy:b,microphone:T,speaker:H,listening:jn,archive:tn,recording:An,notifications:ft,generic:yt};function Rn({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(!1),f=et({deviceId:t},{enabled:i});Ot([`pipelineOrchestrator`,`getCameraSwitches`],[`capability.binding-changed`]);let p=Nn(f.data),m=le({onError:(e,r)=>{console.error(`[CameraFunctionSwitches] switch write failed — reverting`,{tags:{deviceId:t},meta:{switchId:r.switchId,error:e instanceof Error?e.message:String(e)}}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSwitches`]]}),o({id:r.switchId,message:e instanceof Error?e.message:String(e)})},onSuccess:()=>{o(null),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`]]}),n.invalidateQueries({queryKey:[[`deviceManager`]]}),n.invalidateQueries({queryKey:[[`recording`]]})}}),h=e(e=>{!e.available||e.on===null||m.mutate({deviceId:t,switchId:e.id,enabled:!e.on})},[t,m]);if(p===null)return null;let g=In(p),_=e=>a?.id===e.id?a.message:null;return r(L,{open:l,onOpenChange:d,children:[r(Ee,{"aria-label":`Camera functions`,title:g.summary,className:`inline-flex items-center gap-1 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors ${a===null?g.offIds.length>0?`border-warning/40 text-warning hover:bg-warning/10`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(yt,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden lg:inline`,children:`Functions`}),g.offIds.length>0&&r(`span`,{className:`rounded bg-warning/20 px-1 text-[9px] font-semibold uppercase tracking-wide`,children:[g.offIds.length,` off`]})]}),r(Ut,{className:`left-auto right-0 mt-1 min-w-[240px] max-h-[60vh] overflow-y-auto p-1`,children:[u(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:`Camera functions`}),u(`ul`,{className:`space-y-0.5`,children:p.map(e=>u(`li`,{children:u(zn,{row:e,failure:_(e),onToggle:()=>h(e)})},e.id))})]})]})}function zn({row:e,failure:t,onToggle:n}){let i=Ln[Fn(e.label)],a=e.on===null,o=e.on===!1,s=t===null?a?e.unavailableReason??`The source that owns this did not answer.`:e.costWhenOff:`Write failed: ${t}`,c=t===null?a?e.unavailableReason??`unknown`:null:`write failed`;return r(`button`,{type:`button`,role:`switch`,"aria-label":e.label,"aria-checked":e.on===!0,disabled:!e.available,onClick:n,title:s,className:`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-[12px] text-foreground transition-colors hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed`,children:[u(i,{className:`h-3.5 w-3.5 shrink-0 ${t===null?a?`text-foreground-subtle/50`:o?`text-warning`:`text-success`:`text-danger`}`}),r(`span`,{className:`flex-1 min-w-0 truncate`,children:[e.label,c!==null&&r(`span`,{className:`ml-1 text-[10px] text-foreground-subtle`,children:[`· `,c]})]}),u(`span`,{className:`shrink-0 rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide ${a?`bg-surface-hover text-foreground-subtle/60`:o?`bg-warning/20 text-warning`:`bg-success/20 text-success`}`,children:a?`—`:o?`off`:`on`})]})}function Bn({deviceId:e}){let t=ie(_().trpcClient,e);return t===null?null:r(`a`,{href:t.url,target:`_blank`,rel:`noopener noreferrer`,title:`${t.label} — ${t.host}`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[u(v,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:t.label})]})}function Vn({parentDeviceId:e}){let{t}=gn(),n=mn(),i=_(),{data:a,isLoading:o,isError:s}=bn(e),{data:c}=At({deviceId:e},{enabled:Number.isFinite(e)});if(o)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-foreground-subtle`,children:t(`common.loading`,{defaultValue:`Loading…`})})});if(s)return u(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:u(`p`,{className:`text-[10px] text-warning`,children:t(`integrations.childrenLoadError`,{defaultValue:`Failed to load children`})})});let l=(a??[]).filter(e=>e.display?.hidden!==!0);if(l.length===0)return null;let d=ue(c?.stableId??``,l,c?.childLayout),f=d.ungrouped,p=e=>n(`/devices/${String(e)}`),m=c?.name??``,h=(e,t)=>u(A,{trpc:i.trpcClient,device:{...t,name:J(t,m)},variant:`minimal`,onNavigate:p},e),g=f.some(e=>!!e.role),v=f.some(e=>!e.role),y=g&&!v?t(`device.accessories`,{defaultValue:`Accessories`}):!g&&v?t(`device.adoptedDevices`,{defaultValue:`Adopted devices`}):t(`device.children`,{defaultValue:`Children`}),b=f.length>0?r(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5`,children:y}),u(`div`,{className:`space-y-1`,children:f.map(e=>h(e.id,e))})]}):null,x=d.disabledSection===void 0?null:u(lt,{title:t(`device.disabledSection`,{defaultValue:`Disabled`}),count:d.disabledSection.children.length,defaultOpen:!1,children:u(`div`,{className:`opacity-60 space-y-1`,children:d.disabledSection.children.map(e=>h(e.id,e))})},d.disabledSection.title);if(d.sections.length===0)return x===null?b:r(`div`,{className:`space-y-2`,children:[b,x]});let S=v&&!g;return r(`div`,{className:`space-y-2`,children:[S?b:null,d.sections.map(e=>u(lt,{title:e.title,count:e.children.length,defaultOpen:e.defaultOpen,children:e.children.map(e=>h(e.id,e))},e.title)),S?null:b,x]})}function Hn({deviceId:e}){let t=_(),{data:n,isLoading:r}=xn(e),{data:i,isLoading:a}=bn(e),o=r||a,s=(i??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,features:e.features,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),c=typeof n?.linkDeviceId==`number`?n.linkDeviceId:null,l=typeof n?.primaryChildEntityId==`string`?n.primaryChildEntityId:null;return o?u(`div`,{className:`h-full min-h-32 w-full animate-pulse rounded-lg bg-surface`,"aria-hidden":`true`}):u(`div`,{className:`flex h-full w-full flex-col`,children:u(K,{trpc:t.trpcClient,children:s,linkDeviceId:c,primaryChildEntityId:l})})}n();function Un({dev:e,busy:t,setBusy:n}){let i=e?.motionTrigger,a=x(e?.state.motionTrigger),[o,s]=c(!1);if(!i)return null;let l=a?.enabled===!0,d=a!==void 0,f=async()=>{if(t||!d)return;let e=!l;n(!0),s(!0);try{await i.setMotionTrigger({enabled:e})}finally{n(!1),s(!1)}};return r(`button`,{type:`button`,onClick:()=>{f()},disabled:t||!d,title:d?l?`Disable trigger on motion`:`Enable trigger on motion`:`Awaiting state…`,"aria-pressed":l,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${l?`border-primary/50 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground`}`,children:[u(ne,{className:`h-3 w-3`}),u(`span`,{children:o?l?`Disabling…`:`Enabling…`:d?l?`On motion: on`:`On motion: off`:`On motion: …`})]})}n();function Z({deviceId:e,deviceType:t,features:n}){let i=_(),a=Pe(t)?.HeroCard??Ne,o=f(i.trpcClient,e),s=x(o?.state.deviceStatus),[l,d]=c(!1),p=s!==void 0&&s.online===!1,m=p?s.lastChangedAt:null;return r(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[p?u(`div`,{className:`flex justify-center`,children:u(Et,{lastChangedAt:m})}):null,u(a,{trpc:i.trpcClient,deviceId:e,features:n}),u(`div`,{className:`flex justify-center`,children:u(Un,{dev:o,busy:l,setBusy:d})})]})}function Wn({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:u(Fe,{trpc:_().trpcClient,deviceId:e,features:t})})}function Gn({deviceId:e,features:t}){return u(`div`,{className:`flex h-full w-full flex-col items-stretch p-3 sm:p-4`,children:u(Ne,{trpc:_().trpcClient,deviceId:e,features:t})})}function Kn(e){if(!e)return null;let t=e.channel;return typeof t!=`number`||!Number.isInteger(t)||t<0?null:t}function qn(e){if(!e)return null;let t=Kn(e.data);return t===null?e.eventType:`Button ${String(t)} · ${e.eventType}`}var Jn=1e3,Yn=60*Jn,Xn=60*Yn,Zn=24*Xn;function Qn(e,t){if(e==null||e<=0)return`—`;let n=t-e;return n<Jn?`just now`:n<Yn?`${String(Math.floor(n/Jn))}s ago`:n<Xn?`${String(Math.floor(n/Yn))}m ago`:n<Zn?`${String(Math.floor(n/Xn))}h ago`:`${String(Math.floor(n/Zn))}d ago`}n();var $n=1500,er=15e3,tr=1e3;function nr({deviceId:e}){let n=f(_().trpcClient,e)?.state.eventEmitter,i=x(n);d(()=>{if(!n)return;n.refresh();let e=setInterval(()=>{n.refresh()},er);return()=>{clearInterval(e)}},[n]);let a=i?.lastEvent??null,o=a?.seq??null,s=t(null),[l,p]=c(!1);d(()=>{if(o===null)return;let e=s.current;if(s.current=o,e===null||e===o)return;p(!0);let t=setTimeout(()=>{p(!1)},$n);return()=>{clearTimeout(t)}},[o]);let[m,h]=c(()=>Date.now());d(()=>{let e=setInterval(()=>{h(Date.now())},tr);return()=>{clearInterval(e)}},[]);let g=qn(a),v=i?.eventTypes??[],y=i?.eventCountSinceStart??0,b=i!==void 0,S=Kn(a?.data);return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 p-4`,children:[u(`div`,{"data-testid":`event-emitter-indicator`,"data-flashing":String(l),className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${l?`border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 scale-105`:`border-border bg-surface text-foreground-subtle`}`,"aria-live":`polite`,title:g??`No press recorded`,children:u(l?M:oe,{className:`h-10 w-10`})}),r(`div`,{className:`text-center`,children:[S!==null&&u(`div`,{className:`text-xs font-semibold uppercase tracking-wide text-primary`,children:`Button ${String(S)}`}),u(`div`,{"data-testid":`event-emitter-headline`,className:`text-sm font-semibold ${g?`text-foreground`:`text-foreground-subtle`}`,children:g??(b?`No press recorded`:`Awaiting state…`)}),u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:a?Qn(a.timestamp,m):`Waiting for the first event`})]}),v.length>0&&u(`div`,{className:`flex max-w-full flex-wrap justify-center gap-1`,children:v.map(e=>u(`span`,{"data-testid":`event-emitter-chip`,className:`rounded-full border px-2 py-0.5 text-[10px] font-medium ${e===a?.eventType?`border-primary bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle`}`,children:e},e))}),u(`div`,{className:`text-[10px] text-foreground-subtle`,children:`${String(y)} ${y===1?`event`:`events`} since start`})]})}function rr({deviceName:e,deviceType:t,provider:n,isOnline:i,features:a}){return r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center`,children:[u(rn,{type:n,size:`lg`}),r(`div`,{children:[u(`div`,{className:`text-sm font-semibold text-foreground`,children:e}),u(`div`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5`,children:t})]}),r(`div`,{className:`flex items-center gap-2 flex-wrap justify-center`,children:[u(Cn,{status:i?`online`:`offline`}),a.length>0&&u(cn,{capabilities:a})]}),u(`div`,{className:`text-[10px] text-foreground-subtle italic max-w-xs mt-1`,children:`No live view for this device type. Use the Config tab or the shortcut row to interact.`})]})}n();function ir({deviceId:e}){let t=s(),n=xe({deviceId:e},{refetchInterval:1e4,retry:!1}),a=G({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceDiscovery`,`listDiscovered`]]}),t.invalidateQueries({queryKey:[[`deviceDiscovery`,`getStatus`]]})}}),o=i(()=>ar(n.data??[]),[n.data]);return r(`div`,{className:`flex h-full w-full flex-col gap-3 p-3 sm:p-4`,children:[r(`div`,{className:`flex flex-wrap items-stretch gap-2 sm:gap-3`,children:[u(or,{label:`Discovered`,value:o.total,icon:u(pt,{className:`h-3.5 w-3.5`})}),u(or,{label:`Adopted`,value:o.adopted,accent:`success`}),u(or,{label:`Available`,value:o.available,accent:o.available>0?`primary`:void 0}),r(`button`,{type:`button`,onClick:()=>{a.mutateAsync({deviceId:e}).catch(()=>{})},disabled:a.isPending,className:`inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0`,children:[a.isPending?u(en,{className:`h-3.5 w-3.5 animate-spin`}):u(Xt,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:`Discover`})]})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2`,children:[u(sr,{icon:u(ut,{className:`h-3 w-3 text-emerald-500`}),label:`${o.online} online`}),u(sr,{icon:u(dt,{className:`h-3 w-3 text-amber-500`}),label:`${o.sleeping} sleeping`}),u(sr,{icon:u(de,{className:`h-3 w-3 text-destructive`}),label:`${o.offline} offline`}),o.unknown>0?u(sr,{icon:u(nt,{className:`h-3 w-3 text-foreground-subtle`}),label:`${o.unknown} unknown`}):null]})]})}function ar(e){let t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(let n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function or({label:e,value:t,icon:n,accent:i}){return r(`div`,{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${i===`success`?`bg-emerald-500/10 border-emerald-500/30 text-emerald-500`:i===`primary`?`bg-primary/10 border-primary/30 text-primary`:`bg-surface-hover border-border text-foreground`}`,children:[r(`div`,{className:`flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate`,children:[n,u(`span`,{className:`truncate`,children:e})]}),u(`div`,{className:`text-xl sm:text-2xl font-semibold tabular-nums leading-none`,children:t})]})}function sr({icon:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1`,children:[e,u(`span`,{children:t})]})}var cr={[X.Switch]:Z,[X.Siren]:Z,[X.Light]:Z,[X.Sensor]:Z,[X.Button]:Z,[X.Hub]:ir,[X.Cover]:Wn,[X.Valve]:Z,[X.Humidifier]:Z,[X.WaterHeater]:Z,[X.Container]:Hn,[X.Lock]:Z,[X.Fan]:Z,[X.Thermostat]:Z,[X.Climate]:Z,[X.MediaPlayer]:Z,[X.Control]:Z,[X.AlarmPanel]:Z,[X.EventEmitter]:nr,[X.Notifier]:Gn,[X.Script]:Z,[X.Automation]:Z,[X.Presence]:Z,[X.Update]:Z,[X.Vacuum]:Z,[X.LawnMower]:Z,[X.Weather]:Z,[X.Image]:Z,[X.PetFeeder]:Z};function lr(e){return cr[e]??rr}function ur(e){return u(lr(e.deviceType),{...e})}function dr(e){return jt(_().trpcClient,e)}n();function fr(n){let[r,i]=c(`idle`),[a,o]=c(null),s=t(null),l=t(null),u=t(null),f=t(!0),p=vt(),m=Pt(),h=kt(),g=e(()=>{if(s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null},[]),_=e(async()=>{if(r===`idle`)return;i(`stopping`);let e=u.current;if(e&&n!==null)try{await Promise.race([h.mutateAsync({deviceId:n,sessionId:e}),new Promise((e,t)=>setTimeout(()=>t(Error(`server stopSession timeout`)),2e3))])}catch(e){console.warn(`[intercom] server stopSession failed (continuing teardown)`,e)}g(),f.current&&(i(`idle`),o(null))},[r,n,h,g]),v=e(async()=>{if(n===null||r!==`idle`&&r!==`error`)return;o(null);let e=null,t=null,a=null;try{i(`requesting-mic`),e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),l.current=e,i(`starting`);let r=await p.mutateAsync({deviceId:n});a=r.sessionId,u.current=a,i(`connecting`),t=new RTCPeerConnection,s.current=t,t.oniceconnectionstatechange=()=>{if(!f.current)return;let e=t.iceConnectionState;e===`connected`||e===`completed`?i(`talking`):(e===`failed`||e===`closed`||e===`disconnected`)&&f.current&&(o(e===`failed`?`WebRTC connection failed`:null),_())};for(let n of e.getAudioTracks())t.addTrack(n,e);await t.setRemoteDescription({type:`offer`,sdp:r.sdpOffer});let c=await t.createAnswer();await t.setLocalDescription(c);let d=t.localDescription?.sdp??c.sdp??``;await m.mutateAsync({deviceId:n,sessionId:a,sdpAnswer:d})}catch(r){let c=r instanceof Error?r.message:String(r);if(console.warn(`[intercom] start failed`,r),t)try{t.close()}catch{}if(e)for(let t of e.getTracks())try{t.stop()}catch{}if(s.current=null,l.current=null,a!==null)try{await h.mutateAsync({deviceId:n,sessionId:a})}catch{}u.current=null,f.current&&(o(c),i(`error`))}},[n,r,p,m,h,_]);return d(()=>(f.current=!0,()=>{f.current=!1;let e=u.current;if(e!==null&&n!==null&&h.mutate({deviceId:n,sessionId:e}),s.current){try{s.current.close()}catch{}s.current=null}if(l.current){for(let e of l.current.getTracks())try{e.stop()}catch{}l.current=null}u.current=null}),[n]),{state:r,error:a,start:v,stop:_,isTalking:r===`talking`}}n();var pr=0;function Q(){return++pr}function mr(e){switch(e.type){case`system`:return`system`;case`device`:return`#${e.deviceId}`;case`provider`:return e.providerId;case`addon`:return e.addonId}}function hr(e){return[``,`Commands`,` help Show this help`,` examples Show usage examples for the current scope`,` context Show every available variable + full API surface`,` clear Clear terminal (also Ctrl+L)`,``,`Shortcuts`,` Enter Execute expression`,` Arrow Up/Down Navigate command history`,` Ctrl+L Clear terminal`,``,`Try: ${{system:` sm.summary() // fleet overview`,device:` device.state.battery.value?.sleeping // sync read`,provider:` devices.map(d => d.name)`,addon:` manifest.version`}[e.type]}`,``,`Top-level objects: sm (SystemMirror), DeviceType, Math, JSON, Date, …`]}function gr(e){switch(e.type){case`device`:return[``,`── State (sync, zero round-trip) ─────────────────────────`,` device.state.battery.value`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,``,`── Actions (async, through wrapper chain) ────────────────`,` await device.snapshot.getSnapshot({})`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.switch.setState({ on: true })`,``,`── Wait for condition ───────────────────────────────────`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`── Subscribe to changes ─────────────────────────────────`,` const off = device.state.battery.subscribe(s => console.log(s))`,``,`── Quick info ───────────────────────────────────────────`,` info.name device name`,` info.addonId owning addon`,` sm.dump(deviceId) full debug dump`];case`system`:return[``,`── Lookups ──────────────────────────────────────────────`,` sm.getDeviceById(8)`,` sm.getDeviceByName('Sala da pranzo')`,` sm.getDevicesByAddon('reolink')`,` sm.getDevicesByType(DeviceType.Camera)`,``,`── Filters (typed query) ────────────────────────────────`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] })`,` sm.query({ name: /^Cam-/ })`,``,`── Cross-device ─────────────────────────────────────────`,` sm.whereState('battery', s => s.percentage < 20).length`,` sm.mapState('battery', s => s.percentage)`,` sm.countByCap('snapshot')`,``,`── Batch action ─────────────────────────────────────────`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,``,`── Listen ───────────────────────────────────────────────`,` sm.listenCap('motion', (id, s) => console.log(id, s))`,` sm.onDeviceAdded((id, info) => console.log('+', info.name))`,``,`── Diagnostics ──────────────────────────────────────────`,` sm.summary()`,` sm.dump(8)`];case`provider`:return[``,` devices.map(d => d.name)`,` await getIntegration()`,` sm.getDevicesByAddon('<this-addon-id>').length`];case`addon`:return[``,` manifest.name`,` manifest.version`,` declaration`]}}function _r(e){let t=[``,`Scope: ${e.type}`,``];switch(e.type){case`system`:return[...t,`Primary API — sm (SystemMirror):`,` sm.getDeviceById(id) DeviceProxy | null (sync)`,` sm.getDeviceByName(name) DeviceProxy | null`,` sm.getDeviceByStableId(sid) DeviceProxy | null`,` sm.getAllDevices() readonly DeviceProxy[]`,` sm.getDeviceInfo(id) DeviceInfo | null`,` sm.summary() fleet stats`,``,`Filters — sm.query({...}):`,` sm.query({ addonId: 'reolink', online: true })`,` sm.query({ caps: ['battery', 'snapshot'] }) // ALL caps required`,` sm.query({ anyCap: ['ptz', 'motion'] }) // ANY cap`,` sm.query({ name: { contains: 'sala' } }) // case-insensitive`,` sm.query({ name: /^Cam-\\d+$/ })`,` sm.query({ type: DeviceType.Camera })`,` sm.query({ parentDeviceId: 8 }) // accessories of cam 8`,` sm.query({ where: (info, dev) => dev.state.battery.value?.sleeping })`,``,`State queries:`,` sm.whereState('battery', s => s.percentage < 20)`,` sm.mapState('battery', s => s.percentage)`,` sm.findState('motion', s => s.detected)`,` sm.countByCap('snapshot')`,``,`Listeners (return unsubscribe fn):`,` sm.listen((id, cap, slice) => …) // every state change`,` sm.listenCap('motion', (id, slice) => …)`,` sm.listenDevice(8, (id, cap, slice) => …)`,` sm.onDeviceAdded((id, info) => …)`,` sm.onDeviceRemoved((id, info) => …)`,``,`Wait primitives:`,` await sm.waitForState(8, 'battery', s => !s.sleeping, 30_000)`,` await sm.waitForDevice(99, 30_000)`,``,`Batch:`,` await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })`,` await sm.forEachCap('reboot', d => d.reboot.reboot({}))`,``,`Diagnostics:`,` sm.dump(8) debug dump (one device)`,` sm.dump() full fleet dump`,` sm.summary() breakdown by cap/addon/type`,``,`Legacy: deviceRegistry, addonRegistry, eventBus, devices(), addons()`];case`device`:return[...t,`Pre-bound variables:`,` device DeviceProxy for this device (sync state + async methods)`,` deviceId number`,` info DeviceInfo metadata (name, addonId, type, online, …)`,` sm SystemMirror (full cluster view)`,` rawDevice legacy IDevice instance (escape hatch)`,``,`Reactive state (sync, zero round-trip):`,` device.state.battery.value BatteryStatus | undefined`,` device.state.battery.value?.sleeping`,` device.state.battery.value?.percentage`,` device.state.motion.value?.detected`,` device.state.switch.value?.on`,` device.state.brightness.value?.percentage`,` device.state.doorbell.value?.lastPressedAt`,``,`Cap actions (async, through wrapper chain):`,` await device.snapshot.getSnapshot({})`,` await device.snapshot.getSnapshot({ streamId: 'high' })`,` await device.ptz.move({ direction: 'left', steps: 1 })`,` await device.ptz.goToPreset({ presetId: 'home' })`,` await device.switch.setState({ on: true })`,` await device.brightness.setBrightness({ percentage: 60 })`,` await device.reboot.reboot({})`,``,`Subscribe to slice changes:`,` const off = device.state.battery.subscribe(s => console.log(s))`,` // off() to unsubscribe`,``,`Wait for a state condition:`,` await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)`,``,`Diagnostics:`,` info.name device name`,` info.addonId which addon owns it`,` info.online transport health`,` sm.dump(deviceId) full debug dump (binding + state + info)`];case`provider`:return[...t,`Pre-bound variables:`,` devices Devices belonging to this provider (raw IDevice[])`,` getIntegration() Integration metadata`,``,`For typed device access use the SystemMirror:`,` await getSystemMirror()`,` sm.getDevicesByAddon('this-addon-id')`];case`addon`:return[...t,`Pre-bound variables:`,` manifest { name, version, ... }`,` declaration addon declaration`,` source addon source location`,``,`Examples:`,` manifest.name`,` manifest.version`]}}function vr({scope:n,greeting:i,className:a}){let o=_(),[s,f]=c(()=>{let e=[];return i&&e.push({id:Q(),kind:`info`,text:i}),e.push({id:Q(),kind:`info`,text:`scope: ${mr(n)} — type help or context for available commands`}),e}),[p,m]=c(``),[h,g]=c([]),[v,y]=c(-1),b=t(null),x=t(null);d(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[s]);let S=e(()=>{b.current?.focus()},[]),C=l({mutationFn:e=>o.trpcClient.repl.execute.mutate({code:e,scope:n}),onSuccess:e=>{let t=e??{},n=typeof t.output==`string`?t.output:e==null?`undefined`:typeof e==`string`?e:JSON.stringify(e,null,2),r=t.type===`error`;f(e=>[...e,{id:Q(),kind:r?`error`:`result`,text:n}])},onError:e=>{let t=e instanceof Error?e.message:String(e);f(e=>[...e,{id:Q(),kind:`error`,text:t}])}});function w(e){let t=e.trim();if(t){if(t===`clear`){f([{id:Q(),kind:`info`,text:`scope: ${mr(n)}`}]),m(``);return}if(t===`help`){f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`},...hr(n).map(e=>({id:Q(),kind:`info`,text:e}))]),m(``);return}if(t===`context`){f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`},..._r(n).map(e=>({id:Q(),kind:`info`,text:e}))]),m(``);return}if(t===`examples`){f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`},...gr(n).map(e=>({id:Q(),kind:`info`,text:e}))]),m(``);return}g(e=>[...e,t]),y(-1),f(e=>[...e,{id:Q(),kind:`input`,text:`> ${t}`}]),m(``),C.mutate(t)}}function T(e){if(e.key===`Enter`){e.preventDefault(),w(p);return}if(e.key===`ArrowUp`){if(e.preventDefault(),h.length===0)return;let t=v===-1?h.length-1:Math.max(0,v-1);y(t),m(h[t]??``);return}if(e.key===`ArrowDown`){if(e.preventDefault(),v===-1)return;let t=v+1;t>=h.length?(y(-1),m(``)):(y(t),m(h[t]??``));return}e.ctrlKey&&e.key===`l`&&(e.preventDefault(),f([{id:Q(),kind:`info`,text:`scope: ${mr(n)}`}]))}let E={input:`text-zinc-300`,result:`text-emerald-300`,error:`text-red-300`,info:`text-zinc-400`};return r(`div`,{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${a??``}`,onClick:S,children:[r(`div`,{ref:x,className:`flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]`,children:[s.map(e=>u(`pre`,{className:`whitespace-pre-wrap break-words leading-relaxed ${E[e.kind]}`,children:e.text},e.id)),C.isPending&&u(`span`,{className:`text-zinc-500 animate-pulse`,children:`…thinking`})]}),r(`div`,{className:`flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]`,children:[u(`span`,{className:`text-emerald-400 flex-shrink-0 select-none font-bold`,children:`>`}),u(`input`,{ref:b,value:p,onChange:e=>m(e.target.value),onKeyDown:T,disabled:C.isPending,placeholder:`device.state.battery.value`,autoFocus:!0,className:`flex-1 bg-transparent text-zinc-100 placeholder:text-zinc-600 focus:outline-none caret-emerald-400 disabled:opacity-50`,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`})]})]})}function yr(e,t){return e===null?null:{playbackUrl:e.url,...e.format===void 0?{}:{playbackFormat:e.format},playbackAuthToken:t,...e.label===void 0?{}:{playbackLabel:e.label}}}n();function br({deviceId:e,intercomAvailable:t=!1}){let n=_(),r=typeof window<`u`?h():``,a=Number.isFinite(e),s=dr(a?e:null),c=wn(a?[e]:[]),l=i(()=>{if(!a)return;let e=[];for(let t of c.rows){let n=xt(t);n!==null&&e.push(n)}return e},[a,c.rows]),{streams:d,pipelineMetrics:f,createSession:p,sendAnswer:g,handleOffer:v,getIceServers:y,addIceCandidate:b,getIceCandidates:x,closeSession:C,getSessionState:w}=Be(n.trpcClient,a?e:null),T=m(a?e:null,{width:Tr}),E=fr(a&&t?e:null),D=E.state===`requesting-mic`||E.state===`starting`||E.state===`connecting`||E.state===`stopping`,O=E.isTalking||D,k=()=>{E.state===`idle`||E.state===`error`?E.start():E.state!==`stopping`&&E.stop()},A=S(),j=bt(),M=typeof window<`u`?window.localStorage.getItem(`camstack_admin_token`):null,N=yr(j.request,M),P=A.length>0?u(o,{children:A.map(e=>u(`div`,{className:`absolute inset-0`,children:e.node},e.id))}):null;return u(Lt,{serverUrl:r,createSession:p,sendAnswer:g,handleOffer:v,getIceServers:y,addIceCandidate:b,getIceCandidates:x,closeSession:C,getSessionState:w,...N===null?{}:{...N,onExitPlayback:()=>j.clear()},streams:d,pipelineMetrics:f,phase:s.phase,detections:s,...l===void 0?{}:{stationaryObjects:l},defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:T.src,...T.src?{posterUrl:T.src}:{},snapshotLoading:T.loading,onRefreshSnapshot:T.refresh,intercomAvailable:t,intercomShown:O,onIntercomToggle:k,extraOverlay:P,chromeless:!0,className:`h-full`})}function xr({deviceId:e,containerDeviceId:t}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full`,children:u(It,{...t===void 0?{deviceId:e}:{containerDeviceId:t},limit:50,maxHeight:`max-h-full`,showScope:!1,showFilters:!1})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function Sr({deviceId:e}){if(!Number.isFinite(e))return r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]});let t=[`CamStack REPL — device #${e}`,``,` device.state.battery.value sync state read`,` await device.snapshot.getSnapshot({}) cap action`,``,` type 'examples' for more, 'context' for the full API`].join(`
2
- `);return u(vr,{scope:{type:`device`,deviceId:e},greeting:t,className:`h-full border-0 rounded-none`})}function Cr({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(Xe,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}function wr({deviceId:e}){return Number.isFinite(e)?u(`div`,{className:`flex flex-col h-full overflow-y-auto`,children:u(O,{deviceId:e,limit:50,maxHeight:`max-h-full`})}):r(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]})}var Tr=960,Er=`overview`;function Dr(e,t){return e.some(e=>e.id===t)?t:Er}function Or({deviceId:e}){let t=s(),n=Number.isFinite(e),{data:i}=At({deviceId:e},{enabled:n}),a=typeof i?.type==`string`?i.type:`camera`;Ot([`deviceManager`,`getBindings`],[`capability.binding-changed`]);let{data:o,isLoading:c,isError:l,error:d}=Ye({deviceId:e},{enabled:n}),{data:f}=Mt({deviceType:a},{enabled:!!a}),p=j({onSuccess:()=>{t.invalidateQueries({queryKey:[[`deviceManager`,`getBindings`]]})}});if(c)return u(`div`,{className:`p-4`,children:u(`div`,{className:`h-20 rounded-lg border border-border bg-surface animate-pulse`})});if(l)return r(`div`,{className:`p-4 text-xs text-red-400`,children:[`Failed to load bindings: `,d instanceof Error?d.message:String(d)]});let m=new Map,h={};for(let e of f??[])h[e.capName]=e.wrappers;for(let e of o?.entries??[])m.set(e.capName,{...e,wrappers:h[e.capName]??[]});for(let e of f??[])m.has(e.capName)||m.set(e.capName,{capName:e.capName,kind:`unbound`,providerAddonId:``,providerNodeId:``,nativeAddonId:``,wrappers:e.wrappers});let g=[...m.values()].toSorted((e,t)=>e.capName.localeCompare(t.capName));if(g.length===0)return r(`div`,{className:`flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle`,children:[u(nn,{className:`h-8 w-8 opacity-40`}),u(`p`,{className:`text-xs`,children:`No capability providers applicable to this device yet.`}),u(`p`,{className:`text-[10px] opacity-60`,children:`Native providers show up here as soon as the owning addon registers them.`})]});let _=g.filter(e=>e.kind!==`unbound`).length;return r(`div`,{className:`flex flex-col gap-3 p-1`,children:[r(`div`,{className:`text-[11px] text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-foreground`,children:_}),` of `,g.length,` capabilit`,g.length===1?`y`:`ies`,` bound — rows marked `,u(`em`,{children:`unbound`}),` have a wrapper available you can activate.`]}),u(zt,{columns:[{key:`capability`,header:`Capability`,render:e=>u(`span`,{className:`font-mono text-foreground`,children:e.capName})},{key:`kind`,header:`Kind`,render:e=>u(kr,{kind:e.kind})},{key:`provider`,header:`Active Provider`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.providerAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`node`,header:`Node`,render:e=>e.providerNodeId?u(Ar,{nodeId:e.providerNodeId}):u(`span`,{className:`text-[10px] opacity-40`,children:`—`})},{key:`native`,header:`Native`,render:e=>u(`span`,{className:`font-mono text-foreground-subtle`,children:e.nativeAddonId||u(`span`,{className:`opacity-40`,children:`—`})})},{key:`wrapper`,header:`Wrapper`,render:t=>{let n=t.kind===`wrapped`?t.providerAddonId:null;return u(jr,{wrappers:t.wrappers,activeWrapperId:n,disabled:p.isPending,onPick:r=>{let i=n===r;p.mutate({deviceId:e,capName:t.capName,wrapperAddonId:r,active:!i})}})}}],rows:g,rowKey:e=>e.capName,minWidthPx:720})]})}function kr({kind:e}){return e===`native`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(Je,{className:`h-3 w-3`}),`native`]}):e===`wrapped`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(sn,{className:`h-3 w-3`}),`wrapped`]}):e===`linked`?r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-warning/30 text-warning bg-warning/5 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(P,{className:`h-3 w-3`}),`linked`]}):r(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium`,children:[u(he,{className:`h-3 w-3`}),`unbound`]})}function Ar({nodeId:e}){return u(`span`,{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e===`hub`?`text-foreground-subtle`:`text-foreground`}`,children:e})}function jr({wrappers:e,activeWrapperId:t,disabled:n,onPick:i}){return e.length===0?u(`span`,{className:`text-[10px] opacity-40`,children:`none available`}):u(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>{let a=e===t;return r(`button`,{disabled:n,onClick:()=>i(e),title:a?`Click to deactivate (revert to native)`:`Activate wrapper ${e}`,className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${a?`border-primary/40 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(a?Wt:y,{className:`h-3 w-3`}),e]},e)})})}function Mr({deviceId:e,activeSubTab:t,onSubTabChange:n}){return u(`div`,{className:`flex flex-col gap-3`,children:u(On,{deviceId:e,activeSubTab:t,onSubTabChange:n})})}n();var Nr=new Set([`package-detection`]);function Pr(e,t){if(!e)return null;for(let n of e.slots)for(let e of n.addons)if(e.id===t)return e;return null}function Fr(e){return e?e.modelId!==void 0||e.settings!==void 0:!1}function Ir({deviceId:e,refreshToken:t}){let n=s(),l=_().trpcClient,[d,f]=c(null),[p,m]=c(null),[h,g]=c(null),v=Tt({deviceId:e},{refetchOnMount:`always`}),y=it({deviceId:e},{refetchOnMount:`always`}),b=I(void 0,{refetchOnMount:`always`});Ot([`nodes`,`topology`],[`agent.online`,`agent.offline`,`agent.unregistered`,`addon.installed`,`addon.uninstalled`]);let{nodes:x}=Kt(),S=i(()=>{let e=new Set;for(let t of x)t.isOnline&&e.add(t.id);return e},[x]),C=i(()=>(b.data??[]).filter(e=>S.has(e.nodeId)).map(e=>e.nodeId),[b.data,S]),w=a({enabled:C.length>0,queryKey:[[`pipelineExecutor`,`getSchema`],`device-step-schemas`,C.join(`,`),t],queryFn:async()=>{let e={};for(let t of C)try{e[t]=await l.pipelineExecutor.getSchema.query({nodeId:t})}catch{}return e}}),T=e=>w.data?.[e]??null,E=i(()=>{let e=C[0];if(e!==void 0){let t=w.data?.[e];if(t)return t}return Object.values(w.data??{})[0]??null},[C,w.data]),D=a({enabled:C.length>0,queryKey:[[`pipelineOrchestrator`,`getNodeInferenceDevices`],`device-step`,C.join(`,`),t],queryFn:async()=>{let e={};for(let t of C)try{e[t]=(await l.pipelineOrchestrator.getNodeInferenceDevices.query({nodeId:t})).devices}catch{e[t]=[]}return e}}),O=()=>{n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraSettings`]]}),n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCameraStepOverrides`]]})},k=W({onSuccess:O}),A=ae({onSuccess:O}),j=i(()=>E?qe(E):[],[E]),M=i(()=>{let e=b.data??[],t=S.size===0?[]:e.filter(e=>S.has(e.nodeId)),n=[];for(let e of t){let t=(D.data?.[e.nodeId]??[]).filter(e=>e.enabled&&e.available);if(t.length>=2)for(let r of t)n.push({agentNodeId:e.nodeId,engineLabel:r.format,deviceKey:r.key,deviceLabel:on(r).label});else n.push({agentNodeId:e.nodeId,engineLabel:t[0]?.format??`(engine unknown)`})}return n},[b.data,D.data,S]),N=(e,t)=>D.data?.[e]?.find(e=>e.key===t)??null,P=e=>{if(e.deviceKey!==void 0)return e.deviceKey;let t=D.data?.[e.agentNodeId]??[],n=t.filter(e=>e.enabled&&e.available);return n.length>=1?n[0].key:t.find(e=>e.available)?.key??t[0]?.key??null},F=(e,t,n)=>y.data?.[e]?.[t]?.[n]??null,L=e=>{if(Nr.has(e))return{kind:`zone-driven`};let t=Pr(E,e)?.enabledByDefault??!0,n=v.data?.stepToggles?.[e];return{kind:`gate`,effectiveOn:n??t,defaultOn:t,explicit:n!==void 0}},R=(e,t,n)=>{let r=Pr(T(n),e);if(r)return re(r,t)},z=(e,t)=>{let n=L(e),r=n.kind===`gate`?n.effectiveOn:!1,i=Pr(T(t.agentNodeId),e),a=P(t),o=a===null?null:N(t.agentNodeId,a);if(!Me(i?.models??[],o?.format))return r?{kind:`skip`}:{kind:`na`};let s=a===null?null:F(t.agentNodeId,a,e),c=o?.steps?.[e];return{kind:`enabled`,modelId:(i?ke({catalog:i,device:o,override:s?.modelId,base:c?.modelId}):void 0)??`Auto`,overridden:Fr(s)}},B=d===null?null:Pr(T(d.agentNodeId),d.addonId),V=d?N(d.agentNodeId,d.deviceKey):null,ee=V?.format??`coreml`,H=d?Fr(F(d.agentNodeId,d.deviceKey,d.addonId)):!1,U=d?R(d.addonId,V,d.agentNodeId):void 0,G=i(()=>{if(!d||!V)return null;let e=V.steps?.[d.addonId];return{enabled:!0,...e?.modelId===void 0?{}:{modelId:e.modelId},settings:e?.settings??{}}},[d,V]),K=()=>{f(null),m(null)},te=(e,t)=>{let n=P(t);n!==null&&(f({addonId:e,agentNodeId:t.agentNodeId,deviceKey:n}),m(F(t.agentNodeId,n,e)))},ne=(t,n)=>{A.mutate({deviceId:e,addonId:t,enabled:n})},q=()=>{d&&k.mutate({deviceId:e,agentNodeId:d.agentNodeId,deviceKey:d.deviceKey,addonId:d.addonId,patch:p},{onSuccess:K})},ie=()=>{d&&k.mutate({deviceId:e,agentNodeId:d.agentNodeId,deviceKey:d.deviceKey,addonId:d.addonId,patch:null},{onSuccess:K})};if(b.isLoading||C.length>0&&w.isLoading)return u(`div`,{className:`text-xs text-foreground-subtle animate-pulse p-4`,children:`Loading pipeline…`});if(M.length===0)return u(`div`,{className:`text-xs text-foreground-subtle p-4`,children:`No online agents.`});if(!E)return u(`div`,{className:`text-xs text-foreground-subtle p-4`,children:`Catalog unavailable.`});let oe=d!==null&&B!==null&&V!==null;return r(`div`,{className:`relative h-full w-full space-y-3`,children:[r(`div`,{className:`rounded-md border border-border bg-muted/20 px-3 py-2 text-[11px] leading-relaxed text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-foreground`,children:`Gate`}),` (col 1) decides whether this camera runs a step — independent of nodes. Each`,` `,u(`span`,{className:`font-medium text-foreground`,children:`node column`}),` shows the model that node runs; click a cell to pin a per-camera model override for that accelerator. A gated-on step with no model on a device shows a clickable `,u(`span`,{className:`text-amber-500`,children:`⚠ skip`}),` `,`and won't run there.`]}),r(`div`,{className:`rounded-md border border-sky-500/25 bg-sky-500/[0.06] px-3 py-2 text-[11px] leading-relaxed text-foreground-subtle`,children:[u(`span`,{className:`font-medium text-sky-400`,children:`Placement is dynamic.`}),` When a node has multiple inference accelerators, each session is balanced across them per-session at dispatch time — these device columns show each accelerator's effective model (override ?? device default), not a fixed assignment.`]}),u(`div`,{className:oe?`md:pr-[360px]`:``,children:j.length>0?u(Gt,{tree:j,agents:M,gateFor:L,getCellState:z,onCellClick:te,selectedCell:d,onSetGate:ne,gateBusy:A.isPending,fallbackNodeId:h,onFallbackNodeChange:g}):u(`div`,{className:`text-xs text-foreground-subtle`,children:`Catalog empty.`})}),u(Ze,{open:oe,onClose:K,title:B?.name??``,subtitle:d&&V?`${d.agentNodeId} · ${on(V).label} · ${V.format}`:``,footer:r(o,{children:[u(`button`,{type:`button`,className:`px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted text-foreground-subtle disabled:opacity-50`,disabled:!H||k.isPending,onClick:ie,children:`Clear override`}),u(`div`,{className:`flex-1`}),u(`button`,{type:`button`,className:`px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted`,onClick:K,children:`Cancel`}),u(`button`,{type:`button`,disabled:!d||!G||k.isPending,className:`px-3 py-1 text-xs bg-primary text-primary-foreground rounded disabled:opacity-50`,onClick:q,children:k.isPending?`Saving…`:`Save`})]}),children:B&&d&&G?u(Ae,{mode:`device`,addon:B,agentDefault:G,agentNodeId:d.agentNodeId,currentPatch:p,engineFormat:ee,effectiveModelId:U,onChangePatch:m}):u(`div`,{className:`rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-300`,children:`This accelerator is no longer reported by the node, so there is nothing to provision here.`})})]})}var Lr=[{id:`object-detection`,label:`Object detection`,icon:`scan-search`},{id:`tracking`,label:`Tracking`,icon:`route`},{id:`motion`,label:`Motion`,icon:`activity`},{id:`stationary`,label:`Stationary`,icon:`square-parking`},{id:`zones`,label:`Zones`,icon:`shapes`},{id:`audio`,label:`Audio`,icon:`volume-2`},{id:`cluster`,label:`Cluster`,icon:`server`}],Rr={"pipeline-object-detection":`object-detection`,"detection-sensitivity":`object-detection`,"onboard-object-detection":`object-detection`,tracking:`tracking`,"tracking-core":`tracking`,"motion-tuning":`motion`,"stationary-objects":`stationary`,occupancy:`stationary`,zones:`zones`,"pipeline-audio":`audio`,"cluster-assignment":`cluster`,"orchestrator-live":`cluster`};function zr(e){return Rr[e]??`object-detection`}n();var Br=`steps`,Vr=`settings`,Hr=new Set([Br,Vr]);function Ur(e){return e.location===`top-tab`&&(e.tab===`detection-pipeline`||e.tab===`zones`)}function Wr({deviceId:t,activeSubTab:n,onSubTabChange:i}){return r(Qt,{value:n&&Hr.has(n)?n:Br,onValueChange:e(e=>{i?.(e)},[i]),className:`flex flex-col`,children:[r(Jt,{className:`flex-shrink-0`,children:[u(Te,{value:Br,children:`Steps`}),u(Te,{value:Vr,children:`Settings`})]}),u(We,{value:Br,children:u(Ir,{deviceId:t,refreshToken:0})}),u(We,{value:Vr,children:u(On,{deviceId:t,sectionFilter:Ur,subTabGrouping:{groupOf:e=>zr(e.id),tabs:Lr}})})]})}function $({label:e,value:t}){return r(`div`,{className:`${g} flex items-start gap-2 sm:gap-3`,children:[u(`span`,{className:`w-20 sm:w-28 flex-shrink-0 text-[11px] text-foreground-subtle`,children:e}),u(`div`,{className:`flex-1 min-w-0 text-[11px] text-foreground`,children:t})]})}n();function Gr({deviceId:e,initialName:n}){let i=s(),[a,o]=c(!1),[l,f]=c(n),[p,m]=c(!1),h=t(null);d(()=>{a||f(n)},[n,a]),d(()=>{a&&h.current?.focus()},[a]);let g=ee({onSuccess:()=>{i.invalidateQueries({queryKey:[[`deviceManager`,`getDevice`]]}),i.invalidateQueries({queryKey:[[`deviceManager`,`listAll`]]}),i.invalidateQueries({queryKey:[[`deviceManager`,`getDeviceAggregate`]]})}}),_=async()=>{let t=l.trim();if(t.length===0||t===n){o(!1),f(n);return}m(!0);try{await g.mutateAsync({deviceId:e,name:t}),o(!1)}catch{}finally{m(!1)}},v=()=>{f(n),o(!1)};return a?u($,{label:`Name`,value:r(`div`,{className:`flex items-center gap-1`,children:[u(`input`,{ref:h,type:`text`,value:l,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`?_():e.key===`Escape`&&v()},disabled:p,className:`flex-1 min-w-0 px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary`}),u(`button`,{type:`button`,onClick:()=>void _(),disabled:p,className:`p-0.5 rounded hover:bg-success/10 text-success disabled:opacity-50`,"aria-label":`Save`,children:u(Wt,{className:`h-3 w-3`})}),u(`button`,{type:`button`,onClick:v,disabled:p,className:`p-0.5 rounded hover:bg-danger/10 text-danger disabled:opacity-50`,"aria-label":`Cancel`,children:u(ve,{className:`h-3 w-3`})})]})}):u($,{label:`Name`,value:r(`div`,{className:`flex items-center gap-2 group`,children:[u(`span`,{className:`truncate`,children:n}),u(`button`,{type:`button`,onClick:()=>o(!0),className:`p-0.5 rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Edit name`,children:u(B,{className:`h-3.5 w-3.5`})})]})})}n();function Kr({deviceId:e,initialLocation:n}){let a=s(),[o,l]=c(!1),[f,p]=c(n??``),[m,h]=c(!1),g=t(null),{data:_}=Rt(void 0,{enabled:o}),v=_??[];d(()=>{o||p(n??``)},[n,o]),d(()=>{o&&g.current?.focus()},[o]);let y=we({onSuccess:()=>{a.invalidateQueries({queryKey:[[`deviceManager`,`getDevice`]]}),a.invalidateQueries({queryKey:[[`deviceManager`,`listAll`]]}),a.invalidateQueries({queryKey:[[`deviceManager`,`getDeviceAggregate`]]}),a.invalidateQueries({queryKey:[[`deviceManager`,`listLocations`]]})}}),b=i(()=>{let e=f.trim().toLowerCase();return e.length===0?v:v.filter(t=>t.toLowerCase()!==e&&t.toLowerCase().includes(e))},[v,f]),x=f.trim().length>0&&!v.some(e=>e.toLowerCase()===f.trim().toLowerCase()),S=async t=>{let r=(t??f).trim(),i=r.length===0?null:r;if(i===(n??null)){l(!1);return}h(!0);try{await y.mutateAsync({deviceId:e,location:i}),l(!1)}catch{}finally{h(!1)}},C=()=>{p(n??``),l(!1)};return o?u($,{label:`Location`,value:r(`div`,{className:`relative`,children:[r(`div`,{className:`flex items-center gap-1`,children:[u(`input`,{ref:g,type:`text`,value:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`?S():e.key===`Escape`&&C()},disabled:m,placeholder:`Room / area (or leave empty to clear)`,className:`flex-1 min-w-0 px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary`}),u(`button`,{type:`button`,onClick:()=>void S(),disabled:m,className:`p-0.5 rounded hover:bg-success/10 text-success disabled:opacity-50`,"aria-label":`Save`,children:u(Wt,{className:`h-3 w-3`})}),u(`button`,{type:`button`,onClick:C,disabled:m,className:`p-0.5 rounded hover:bg-danger/10 text-danger disabled:opacity-50`,"aria-label":`Cancel`,children:u(ve,{className:`h-3 w-3`})})]}),(b.length>0||x)&&r(`div`,{className:`absolute z-10 left-0 right-0 mt-0.5 max-h-40 overflow-y-auto rounded-md border border-border bg-surface shadow-md`,children:[b.map(e=>r(`button`,{type:`button`,onClick:()=>{p(e),S(e)},className:`w-full flex items-center gap-2 px-2 py-1 text-left text-[11px] hover:bg-surface-hover`,children:[u(U,{className:`h-3 w-3 text-foreground-subtle flex-shrink-0`}),u(`span`,{className:`truncate`,children:e})]},e)),x&&r(`button`,{type:`button`,onClick:()=>void S(),className:`w-full flex items-center gap-2 px-2 py-1 text-left text-[11px] hover:bg-surface-hover border-t border-border`,children:[u(`span`,{className:`text-foreground-subtle`,children:`Create`}),r(`span`,{className:`font-medium truncate`,children:[`"`,f.trim(),`"`]})]})]})]})}):u($,{label:`Location`,value:r(`div`,{className:`flex items-center gap-2 group`,children:[n?u(`span`,{className:`truncate`,children:n}):u(`span`,{className:`italic text-foreground-subtle`,children:`unset`}),u(`button`,{type:`button`,onClick:()=>l(!0),className:`p-0.5 rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Edit location`,children:u(B,{className:`h-3.5 w-3.5`})})]})})}n();function qr({deviceId:e}){let t=s(),{data:n}=xn(e),{data:i}=bn(e),[a,l]=c(null),d=z({onSuccess:()=>{l(null),t.invalidateQueries({queryKey:[[`deviceManager`]]})},onError:e=>{l(`Could not change primary child: ${e.message}`)}});if(n==null||String(n.type??``)!==X.Container)return null;let f=(i??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,name:e.name,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}}));if(f.length<=1)return null;let p=ce(f,typeof n.linkDeviceId==`number`?n.linkDeviceId:null,typeof n.primaryChildEntityId==`string`?n.primaryChildEntityId:null);return r(o,{children:[u($,{label:`Primary child`,value:u(je,{childrenList:f,selectedId:p===null?f[0].id:p.id,onSetPrimary:t=>d.mutate({deviceId:e,primaryChildEntityId:t}),disabled:d.isPending})}),a!==null&&u(`p`,{role:`alert`,className:`px-3 sm:px-4 py-1.5 text-[11px] text-danger`,children:a})]})}n();var Jr=[`manufacturer`,`model`,`hardware`,`firmware`,`serialNumber`,`uid`,`mac`,`itemNo`];function Yr(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}function Xr(e){return e==null?`—`:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function Zr(){let e=wt(),t=_t(),{data:n}=At({deviceId:e??0},{enabled:e!==null}),{data:i}=Ye({deviceId:e??0},{enabled:e!==null}),a=n??t??null,[o,s]=c(`identity`);if(e===null||!a)return null;let l=String(a.stableId??``),d=String(a.name??``),f=String(a.type??``),p=String(a.addonId??``),m=a.features??[],h=new Set([`device-status`,`feature-probe`,`device-ops`]),g=(i?.entries??[]).filter(e=>e.kind===`native`&&!h.has(e.capName)).map(e=>e.capName),_=m.length>0?m:g,v=a.location??null,y=a.metadata??null,b=y!==null&&Object.keys(y).length>0;return r(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`border-b border-border px-3 sm:px-4 py-2 flex items-center justify-between gap-3`,children:[u(`h2`,{className:`text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:`Device Info`}),b&&r(`div`,{className:`flex items-center gap-1 rounded-md bg-surface-hover p-0.5`,children:[u(Qr,{active:o===`identity`,onClick:()=>s(`identity`),label:`Identity`}),u(Qr,{active:o===`hardware`,onClick:()=>s(`hardware`),label:`Hardware`})]})]}),(!b||o===`identity`)&&r(`div`,{className:`divide-y divide-border`,children:[u($,{label:`ID`,value:r(`span`,{className:`font-mono text-[11px] text-foreground`,children:[`#${e}`,r(`span`,{className:`ml-1.5 text-foreground-subtle`,children:[`(`,l,`)`]})]})}),u(Gr,{deviceId:e,initialName:d}),u(Kr,{deviceId:e,initialLocation:v}),u(qr,{deviceId:e}),u($,{label:`Type`,value:f}),u($,{label:`Provider`,value:u(rn,{type:p,size:`sm`,showLabel:!0})}),u($,{label:`Capabilities`,value:_.length>0?u(cn,{capabilities:_,showLabels:!0}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`None`})})]}),b&&o===`hardware`&&u($r,{metadata:y})]})}function Qr({active:e,onClick:t,label:n}){return u(`button`,{type:`button`,onClick:t,className:`px-2 py-0.5 rounded text-[10px] font-medium transition-colors ${e?`bg-surface text-foreground shadow-sm`:`text-foreground-subtle hover:text-foreground`}`,children:n})}function $r({metadata:e}){let t=Jr.filter(t=>t in e),n=Object.keys(e).filter(e=>!Jr.includes(e)).toSorted(),i=[...t,...n];return r(`div`,{children:[u(`div`,{className:`px-3 sm:px-4 py-1.5 text-[10px] text-foreground-subtle border-b border-border bg-surface-subtle/40`,children:`Auto-populated by the driver on every connect. Read-only.`}),u(`div`,{className:`divide-y divide-border`,children:i.map(t=>u($,{label:Yr(t),value:u(`span`,{className:`font-mono text-[11px] text-foreground break-all`,children:Xr(e[t])})},t))})]})}var ei=`Notifications`,ti=`This camera never notifies — no rule, no target, no alarm. Existing events, tracks and recordings are unaffected.`;function ni(e){let{mutedDeviceIds:t,deviceId:n}=e,r=t===null?null:!t.includes(n),i=e.pendingOn??null;return{label:ei,on:r===null?null:i??r,available:r!==null,costWhenOff:ti}}function ri(e,t){return!e.available||e.on===null?null:{deviceId:t,muted:e.on}}n();function ii(e){if(typeof e!=`object`||!e)return null;let t={...e}.mutedDeviceIds;return Array.isArray(t)?t.filter(e=>typeof e==`number`):null}function ai({deviceId:t}){let n=s(),i=Number.isFinite(t),[a,o]=c(null),[l,d]=c(null),f=ni({mutedDeviceIds:ii(me({},{enabled:i}).data),deviceId:t,pendingOn:l}),p=Y({onError:e=>{console.error(`[DeviceNotificationMute] mute write failed — reverting`,{tags:{deviceId:t},meta:{error:e instanceof Error?e.message:String(e)}}),d(null),o(e instanceof Error?e.message:String(e)),n.invalidateQueries({queryKey:[[`notificationRules`,`listDeviceMutes`]]})},onSuccess:()=>{o(null),d(null),n.invalidateQueries({queryKey:[[`notificationRules`]]})}}),m=e(()=>{let e=ri(f,t);e!==null&&(d(!e.muted),p.mutate(e))},[t,p,f]),h=f.on===null,g=f.on===!1,_=g?ge:fe;return r(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`border-b border-border px-4 py-2 flex items-center justify-between gap-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Notifications`}),g&&u(`span`,{className:`rounded bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-warning`,children:`muted`})]}),r(`div`,{className:`px-4 py-3 flex items-start gap-3`,children:[r(`button`,{type:`button`,role:`switch`,"aria-label":f.label,"aria-checked":f.on===!0,disabled:!f.available||p.isPending,onClick:m,title:h?`Notification mute — state unknown; the notification centre did not answer.`:g?`Muted. ${f.costWhenOff}`:`Notifying. Muting it: ${f.costWhenOff}`,className:`inline-flex items-center gap-1.5 rounded-lg border px-2 py-1.5 text-[11px] font-medium transition-colors disabled:cursor-not-allowed ${a===null?h?`border-dashed border-border text-foreground-subtle/50`:g?`border-warning/40 text-warning hover:bg-warning/10`:`border-success/30 text-success hover:bg-success/10`:`border-danger/50 text-danger bg-danger/5`}`,children:[u(_,{className:`h-3.5 w-3.5`}),u(`span`,{children:h?`Unknown`:g?`Muted`:`Notifying`})]}),u(`p`,{className:`flex-1 text-[11px] leading-relaxed text-foreground-subtle`,children:a===null?h?`The notification centre did not answer, so this device’s mute state is unknown.`:f.costWhenOff:`Write failed: ${a}`})]})]})}function oi(e,t){return{switchId:e,label:ln[e].label,detail:t===void 0||t.length===0?null:t}}function si(e){let t=new Map;for(let n of e.switches)n.deviceId===e.sourceId&&(t.has(n.switchId)||t.set(n.switchId,n));return t}function ci(e){let t=si(e),n=new Set(e.sourceStillLive),r=e.sourceStillLive.map(e=>oi(e,t.get(e)?.detail)),i=[...t.values()].filter(e=>e.outcome===`not-offered`&&!n.has(e.switchId)).map(e=>oi(e.switchId,e.detail));return{inheritedId:e.sourceId,retiredId:e.targetId,swapped:e.swapped,verdict:r.length===0?`quiet`:`still-live`,stillLive:r,neverOffered:i}}n();function li(e,t){return e.filter(e=>e.isCamera&&e.id!==t).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name))}function ui({deviceId:e,deviceName:t}){let{t:n}=gn(),a=Re(),[o,s]=c(null),l=St({isCamera:!0,projection:`slim`}),d=Qe(),f=l.data!==void 0,p=i(()=>l.data===void 0?[]:li(l.data,e),[l.data,e]),m=p.find(e=>e.id===o)??null,h=d.data===void 0?null:ci(d.data),g=d.error===null?null:d.error.message,_=async()=>{m===null||m.id===e||await a({title:n(`deviceMigrate.confirmTitle`,`Replace “{{source}}” with “{{target}}”?`,{source:t,target:m.name}),message:n(`deviceMigrate.confirmMessage`,`“{{target}}” takes over number {{sourceId}}. That number is what every recording, event, rule, zone and home-automation export of “{{source}}” is filed under, so all of it follows the number to the new hardware and keeps working. “{{source}}” is switched off and handed number {{targetId}} in exchange. This swaps two device identities and cannot be undone from here.`,{source:t,target:m.name,sourceId:e,targetId:m.id}),confirmLabel:n(`deviceMigrate.confirmAction`,`Migrate`),variant:`danger`})&&d.mutate({sourceId:e,targetId:m.id})};return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`min-w-0`,children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:n(`deviceMigrate.title`,`Migrate to…`)}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.subtitle`,`Replace this camera with other hardware you have already adopted. The new camera inherits number {{deviceId}}, so recordings, rules and integrations follow it.`,{deviceId:e})})]}),r(`div`,{className:`flex shrink-0 items-center gap-2`,children:[r(`select`,{"aria-label":n(`deviceMigrate.pickerLabel`,`Replacement camera`),className:`rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground disabled:opacity-50`,disabled:!f||p.length===0||d.isPending,value:o===null?``:String(o),onChange:e=>{let t=e.target.value;s(t===``?null:Number(t))},children:[u(`option`,{value:``,children:f?n(`deviceMigrate.pickerPlaceholder`,`Select a camera…`):n(`deviceMigrate.pickerPending`,`Reading the fleet…`)}),p.map(e=>r(`option`,{value:String(e.id),children:[e.name,` (#`,e.id,`)`]},e.id))]}),r(`button`,{type:`button`,disabled:m===null||d.isPending,onClick:()=>{_()},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(kn,{className:`h-3 w-3`}),d.isPending?n(`deviceMigrate.running`,`Migrating…`):n(`deviceMigrate.action`,`Migrate`)]})]})]}),f&&p.length===0&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:n(`deviceMigrate.noTargets`,`No other camera is adopted, so there is nothing to migrate to.`)}),g!==null&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:n(`deviceMigrate.failed`,`Migration failed: {{error}}`,{error:g})}),h!==null&&u(di,{report:h})]})}function di({report:e}){let{t}=gn(),n=e.verdict===`quiet`;return r(`div`,{className:`mt-3 space-y-2 border-t border-border pt-3`,children:[u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`deviceMigrate.swapped`,`The replacement now answers on number {{inheritedId}}; the old camera was handed number {{retiredId}}.`,{inheritedId:e.inheritedId,retiredId:e.retiredId})}),n?r(`div`,{className:`flex items-start gap-2 rounded-md border border-success/30 bg-success/5 px-3 py-2`,children:[u($t,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-success`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.quiet`,`Every function on the replaced camera was switched off — the old hardware is quiet.`)})]}):r(`div`,{className:`rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(Ue,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground`,children:t(`deviceMigrate.stillLive`,`The replaced camera could not be reached, so these functions are STILL RUNNING on the old hardware. Nothing here failed to migrate — but until you unplug it or reach it physically, it can still produce data.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.stillLive.map(e=>r(`li`,{className:`text-[11px] text-foreground`,children:[u(`span`,{className:`font-medium`,children:e.label}),e.detail!==null&&r(`span`,{className:`text-foreground-subtle`,children:[` — `,e.detail]})]},e.switchId))})]}),e.neverOffered.length>0&&r(`div`,{className:`rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`flex items-start gap-2`,children:[u(an,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`p`,{className:`text-[11px] leading-relaxed text-foreground-subtle`,children:t(`deviceMigrate.neverOffered`,`The replaced camera never offered these, so there was nothing to switch off. They are not running.`)})]}),u(`ul`,{className:`mt-2 space-y-1 pl-5`,children:e.neverOffered.map(e=>u(`li`,{className:`text-[11px] text-foreground-subtle`,children:e.label},e.switchId))})]})]})}n();function fi({deviceId:e}){let[t,n]=c(null),i=te({onSuccess:e=>{n(e.changed?`Re-aligned with source — ${e.rebuiltChildren} child${e.rebuiltChildren===1?``:`ren`} rebuilt.`:`Already up to date.`)},onError:e=>n(`Re-sync failed: ${e.message}`)});return r(`div`,{className:`rounded-lg border border-border bg-surface px-4 py-3`,children:[r(`div`,{className:`flex items-center justify-between gap-3`,children:[r(`div`,{children:[u(`h2`,{className:`text-xs font-semibold uppercase tracking-wider text-foreground`,children:`Re-sync`}),u(`p`,{className:`mt-0.5 text-[11px] text-foreground-subtle`,children:`Re-align this device's type, role, capabilities and units with its source.`})]}),r(`button`,{type:`button`,disabled:i.isPending,onClick:()=>{n(null),i.mutate({camDeviceId:e})},className:`inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground hover:bg-surface disabled:opacity-50`,children:[u(Xt,{className:`h-3 w-3 ${i.isPending?`animate-spin`:``}`}),i.isPending?`Re-syncing…`:`Re-sync`]})]}),t!==null&&u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:t})]})}function pi({deviceName:e,value:t,inheritedIcon:n,inheritedLabel:i,disabled:a,onChange:o}){let{t:s}=gn(),c={trigger:s(`deviceDisplay.pickIcon`,{name:e}),panel:s(`deviceDisplay.iconFor`,{name:e}),close:s(`deviceDisplay.closePicker`),searchPlaceholder:s(`deviceDisplay.iconSearchPlaceholder`),clear:i,noMatches:s(`deviceDisplay.iconNoMatches`),groups:{device:s(`deviceDisplay.iconGroupDevice`),lighting:s(`deviceDisplay.iconGroupLighting`),sensing:s(`deviceDisplay.iconGroupSensing`),place:s(`deviceDisplay.iconGroupPlace`),life:s(`deviceDisplay.iconGroupLife`)}};return r(`div`,{className:`flex items-center gap-2`,children:[u(Ht,{value:t===``?null:t,onPick:e=>o(e??``),resolveGlyph:De,fallbackGlyph:n,labels:c,disabled:a}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:t===``?i:t})]})}n();var mi=`w-full min-w-0 px-1.5 py-0.5 text-[11px] bg-background border border-border rounded focus:outline-none focus:border-primary disabled:opacity-50`,hi={icon:``,label:``,unit:``,precision:``,hidden:!1};function gi(e){return{icon:e?.icon??``,label:e?.label??``,unit:e?.unit??``,precision:e?.precision===void 0?``:String(e.precision),hidden:e?.hidden===!0}}function _i(e){if(typeof e!=`object`||!e)return;let t=e.unit;return typeof t==`string`?t:void 0}function vi(e){if(e.trim()===``)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function yi(e,t){let n=vi(e.precision),r={...e.icon===``?{}:{icon:e.icon},...e.label.trim()===``?{}:{label:e.label.trim()},...e.unit===``?{}:{unit:e.unit},...n===void 0?{}:{precision:n},...e.hidden?{hidden:!0}:{},...t?.perCap===void 0?{}:{perCap:t.perCap}};return Object.keys(r).length===0?null:r}function bi({deviceId:e}){let{t}=gn(),n=_(),a=s(),{data:l}=At({deviceId:e},{enabled:e>0}),d=typeof l?.role==`string`&&l.role.length>0?l.role:null,f=d===null?void 0:Se[d],p=f?.kind===`numeric`,m=String(l?.type??``),h=d!==null||l?.parentDeviceId!==null&&l?.parentDeviceId!==void 0,g=Ge(n.trpcClient,e,d??``),v=f?.kind===`numeric`?f.canonicalUnit:void 0,y=_i(g)??v,b=y===void 0?void 0:fn(y),x=i(()=>b===void 0?[]:dn(b),[b]),[S,C]=c(null),w=S??gi(l?.display),T=qt({onSuccess:()=>{a.invalidateQueries({queryKey:[[`deviceManager`]]})}}),{data:E}=Ve({},{staleTime:6e4,enabled:d!==null}),D=ye({onSuccess:()=>{a.invalidateQueries({queryKey:[[`deviceManager`]]})}});if(l==null)return null;let O=e=>{C({...w,...e})},k=()=>{T.mutate({deviceId:e,display:yi(w,l.display)})},A=()=>{C(hi),T.mutate({deviceId:e,display:null})},j=()=>{if(d===null)return;let e=vi(w.precision),t={...w.icon===``?{}:{icon:w.icon},...w.unit===``?{}:{unit:w.unit},...e===void 0?{}:{precision:e}},n={...E?.defaults,[d]:t};D.mutate({defaults:n})},M=d===null?void 0:E?.defaults[d]?.icon,P=M===void 0?void 0:De(M),F=d===null?q(m):N(d),I={icon:P??F.icon,label:P===void 0?F.label:String(M)},L=d===null&&m===X.Container?t(`deviceDisplay.inheritedContainer`):P===void 0?t(`deviceDisplay.inherited`,{name:I.label}):t(`deviceDisplay.inheritedRoleDefault`,{icon:I.label,role:F.label}),R=typeof l.name==`string`?l.name:`#${String(e)}`,z=d===null?``:N(d).label;return r(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[u(`div`,{className:`border-b border-border px-3 sm:px-4 py-2`,children:u(`h2`,{className:`text-[11px] font-semibold text-foreground uppercase tracking-wider`,children:t(`deviceDisplay.title`)})}),r(`div`,{className:`divide-y divide-border`,children:[u($,{label:t(`deviceDisplay.icon`),value:u(pi,{deviceName:R,value:w.icon,inheritedIcon:I.icon,inheritedLabel:L,disabled:T.isPending,onChange:e=>O({icon:e})})}),h&&u($,{label:t(`deviceDisplay.label`),value:u(`input`,{type:`text`,className:mi,"aria-label":t(`deviceDisplay.label`),placeholder:d===null?R:z,value:w.label,onChange:e=>O({label:e.target.value})})}),p&&r(o,{children:[u($,{label:t(`deviceDisplay.unit`),value:r(`select`,{className:mi,"aria-label":t(`deviceDisplay.unit`),value:w.unit,onChange:e=>O({unit:e.target.value}),disabled:x.length===0,children:[u(`option`,{value:``,children:t(`deviceDisplay.unitSource`,{unit:y===void 0?``:` (${y})`})}),x.map(e=>u(`option`,{value:e,children:e},e))]})}),u($,{label:t(`deviceDisplay.precision`),value:u(`input`,{type:`number`,min:0,max:10,step:1,className:mi,"aria-label":t(`deviceDisplay.precision`),placeholder:t(`deviceDisplay.precisionInherit`),value:w.precision,onChange:e=>O({precision:e.target.value})})})]}),u($,{label:t(`deviceDisplay.hidden`),value:r(`label`,{className:`flex items-center gap-2`,children:[u(`input`,{type:`checkbox`,checked:w.hidden,onChange:e=>O({hidden:e.target.checked})}),u(`span`,{className:`text-[11px] text-foreground`,children:t(`deviceDisplay.hideFromLists`)})]})})]}),r(`div`,{className:`border-t border-border px-3 sm:px-4 py-2 flex flex-wrap items-center gap-2`,children:[u(`button`,{type:`button`,className:`rounded bg-primary px-3 py-1 text-[11px] font-medium text-primary-foreground disabled:opacity-50`,onClick:k,disabled:T.isPending,children:t(`common.save`)}),u(`button`,{type:`button`,className:`rounded border border-border px-3 py-1 text-[11px] text-foreground-subtle`,onClick:A,disabled:T.isPending,children:t(`common.reset`)}),d!==null&&u(`button`,{type:`button`,className:`rounded border border-border px-3 py-1 text-[11px] text-foreground-subtle`,onClick:j,disabled:D.isPending,title:t(`deviceDisplay.setRoleDefaultTitle`,{role:z}),children:t(`deviceDisplay.setRoleDefault`,{role:z})})]})]})}function xi(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function Si({device:e}){let t=mn(),n=typeof e.id==`number`?e.id:null,i=String(e.type??``),a=i===X.Camera,o=i===X.Hub,s=e.features??[],c=s.includes(pn.Resyncable),{data:l}=R({deviceId:n??0},{enabled:n!==null&&a,refetchInterval:5e3}),d=l?.streams??{},f=Object.entries(d),p=s.includes(pn.DoorbellButton),m=ot(p?{deviceId:n??void 0,historyLimit:10}:void 0),h=m.latest?Date.now()-m.latest.timestamp<3e4:!1;return r(`div`,{className:`space-y-5`,children:[o&&n!==null&&u(He,{deviceId:n,onOpenChild:e=>t(`/devices/${e}`)}),c&&n!==null&&u(fi,{deviceId:n}),a&&n!==null&&u(ui,{deviceId:n,deviceName:String(e.name??``)}),n!==null&&u(ai,{deviceId:n}),a&&n!==null&&u(Le,{widgetId:`pipeline-orchestrator/pipeline-quick-stats`,host:`device-tab`,deviceId:n}),p&&u(Yt,{history:m.history,latestIsFresh:h}),a&&n!==null&&u(Le,{widgetId:`stream-broker/stream-broker-panel`,host:`device-tab`,deviceId:n}),a&&f.length>0&&r(`div`,{className:`@container rounded-lg border border-border bg-surface overflow-hidden`,style:{containerType:`inline-size`},children:[u(`div`,{className:`border-b border-border px-4 py-2`,children:u(`h2`,{className:`text-xs font-semibold text-foreground uppercase tracking-wider`,children:`Stream Network`})}),u(`div`,{className:`divide-y divide-border`,children:f.map(([e,t])=>r(`div`,{className:`px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 mb-2`,children:[u(ut,{className:`h-3 w-3 text-foreground-subtle`}),u(`span`,{className:`text-[11px] font-medium text-foreground`,children:e})]}),r(`div`,{className:`grid grid-cols-2 @[640px]:grid-cols-4 gap-2`,children:[u(Ci,{label:`Nominal`,value:xi(t.nominalBitrateKbps??0)}),u(Ci,{label:`Observed`,value:xi(t.observedBitrateKbps??0)}),u(Ci,{label:`Peak`,value:xi(t.peakBitrateKbps??0)}),u(Ci,{label:`Packet Loss`,value:`${(t.packetLossPercent??0).toFixed(2)}%`,warning:(t.packetLossPercent??0)>1})]})]},e))})]}),u(Zr,{}),n!==null&&u(bi,{deviceId:n})]})}function Ci({label:e,value:t,warning:n}){return r(`div`,{children:[u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e}),u(`p`,{className:`text-xs font-medium ${n?`text-warning`:`text-foreground`}`,children:t})]})}function wi({provider:e,integrationId:t,name:n}){let r=mn(),i=t===null?`/integrations`:`/integrations/${t}`,a=n===null?`Open integrations`:`Open integration ${n}`;return u(`button`,{type:`button`,onClick:()=>r(i),className:`shrink-0 rounded-md transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/50`,title:a,"aria-label":a,children:u(rn,{type:e,size:`lg`})})}n();var Ti=[{id:`overview`,label:`Overview`,cameraOnly:!1},{id:`config`,label:`Config`,cameraOnly:!1},{id:`detection-pipeline`,label:`Detection pipeline`,cameraOnly:!0},{id:`bindings`,label:`Bindings`,cameraOnly:!0}];function Ei(e){let t=e===X.Camera;return Ti.filter(e=>t||!e.cameraOnly).map(({id:e,label:t})=>({id:e,label:t}))}var Di=[{id:`logs`,icon:Ct,label:`Logs`},{id:`repl`,icon:hn,label:`REPL`},{id:`events`,icon:ft,label:`Events`},{id:`state`,icon:Ke,label:`State`}];function Oi(){let n=_n(),a=Number(n.deviceId),l=Number.isFinite(a),d=mn(),f=s(),m=Re(),h=_(),[g,v]=vn(),y=g.get(`tab`)??`overview`,b=g.get(`sub`),[x,S]=c(`logs`),T=`device-detail.left-col-width-px`,[D,O]=c(()=>{if(typeof window>`u`)return null;let e=window.localStorage.getItem(T),t=e?Number(e):NaN;return Number.isFinite(t)&&t>0?t:null}),A=t(D);A.current=D;function j(e){e.preventDefault();let t=e.clientX,n=e.currentTarget.previousElementSibling?.getBoundingClientRect().width??D??0,r=Math.max(330,Math.floor(window.innerWidth*.7)),i=e=>{O(Math.max(280,Math.min(r,n+(e.clientX-t))))},a=()=>{document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a);let e=A.current;if(e!==null)try{window.localStorage.setItem(T,String(Math.round(e)))}catch{}document.body.style.userSelect=``,document.body.style.cursor=``};document.body.style.userSelect=`none`,document.body.style.cursor=`col-resize`,document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)}let{data:M,isLoading:N,isError:P}=At({deviceId:a},{enabled:l,refetchInterval:5e3,retry:1}),{data:I}=st({deviceId:a},{enabled:l}),L=i(()=>{let e=I?.settings?.sections??[],t=I?.live?.sections??[],n=[...e,...t],r=new Set;for(let e of n)e.location===`top-tab`&&e.tab&&r.add(e.tab===`zones`?`detection-pipeline`:e.tab);return n.some(Tn)&&r.add(En),[...r].map(e=>e===`export`?{id:e,label:Dn,isAddonContrib:!0}:{id:e,label:un[e]?.label??e,isAddonContrib:!0})},[I]),R=M,z=String(R?.name??n.deviceId??`Device`),B=R?.online===!0,ee=B?`online`:`offline`,H=String(R?.addonId??`rtsp`),U=R?.features??[],W=R?.type,G=W===X.Camera,{data:K}=bn(l?a:0),te=W===X.Container,ne=i(()=>(K??[]).map(e=>({id:e.id,stableId:e.stableId,type:e.type,...e.sourceInfo?{sourceInfo:{id:e.sourceInfo.id}}:{}})),[K]),q=i(()=>te?ce(ne,typeof R?.linkDeviceId==`number`?R.linkDeviceId:null,typeof R?.primaryChildEntityId==`string`?R.primaryChildEntityId:null)?.id??null:null,[te,ne,R?.linkDeviceId,R?.primaryChildEntityId]),{data:re}=st({deviceId:q??0},{enabled:q!==null}),ie=i(()=>{if(q===null)return[];let e=re?.settings?.sections??[],t=re?.live?.sections??[],n=new Set;for(let r of[...e,...t])r.location===`top-tab`&&r.tab&&n.add(r.tab);return[...n].map(e=>({id:e,label:un[e]?.label??e,isAddonContrib:!0,childDeviceId:q}))},[q,re]),ae=typeof R?.parentDeviceId==`number`?R.parentDeviceId:null,{data:oe}=At({deviceId:ae??0},{enabled:ae!==null}),J=V(),le=R?.disabled!==!0,ue=i(()=>{let e=new Set,t=[];for(let n of[...Ei(W),...L,...ie])e.has(n.id)||(e.add(n.id),t.push(n));return t},[W,L,ie]),de=i(()=>Dr(ue,y),[ue,y]),fe=e(e=>{v(t=>{let n=new URLSearchParams(t);return e===`overview`?n.delete(`tab`):n.set(`tab`,e),n.delete(`sub`),n},{replace:!0})},[v]),me=e(e=>{v(t=>{let n=new URLSearchParams(t);return n.set(`sub`,e),n},{replace:!0})},[v]),he=(K??[]).length>0,ge=i(()=>Di.filter(({featureGate:e})=>!e||U.includes(e)),[U]),{data:ve}=Ie(void 0),ye=i(()=>R?_e(R,ve):null,[R,ve]),Y=ye?.kind===`resolved`?ye.integration:null,xe=Y===null?ye?.kind===`unknown`?`Loading integration…`:ye?.kind===`orphan`?`Missing integration`:`No integration`:Y.name,Se=Y!==null&&Y.addonId===H?Y.name:H,we=rt({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]}),d(Y?.id?`/integrations/${Y.id}`:`/integrations`)}}),Te=k({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ee=se({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),De=ct(),ke=Dt({onSuccess:()=>{f.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ae=U.includes(pn.Rebootable),je=U.includes(pn.BatteryOperated),Me=be(h.trpcClient,je&&l?a:null),Ne=pe(h.trpcClient,l?a:null),[Pe,Fe]=c(!1),Le=async()=>{if(!Pe){Fe(!0);try{let e=z.replace(/[^a-zA-Z0-9_.-]+/g,`_`),t=new Date().toISOString().replace(/[:.]/g,`-`);await Sn(`${p}/${String(a)}.jpg?force=1`,`${e}-${t}.jpg`)}finally{Fe(!1)}}},Be=Te.isPending||Ee.isPending,{data:Ve}=Zt({deviceId:a},{enabled:l,refetchInterval:1e4}),He=Ve?.agentNodeId??null,Ue=typeof He==`string`&&He.length>0&&!He.startsWith(`addon:`)?He:void 0,{data:We}=Oe({deviceId:a,...Ue?{nodeId:Ue}:{}},{enabled:l,refetchInterval:3e3,retry:!1}),{data:Ge}=ht({deviceId:a},{enabled:l,refetchInterval:3e3,retry:!1}),Ke=Ge?.level?.dbfs??null;function qe(){if(!l)return null;switch(de){case`overview`:return u(Si,{device:R??{}});case`config`:return u(Mr,{deviceId:a,activeSubTab:b,onSubTabChange:me});case`detection-pipeline`:return u(Wr,{deviceId:a,activeSubTab:b,onSubTabChange:me});case`bindings`:return u(Or,{deviceId:a});default:{let e=de,t=L.some(t=>t.id===e),n=ie.find(t=>t.id===e);if(!t&&n===void 0)return null;let r=n?.childDeviceId??a;if(e===`export`)return u(On,{deviceId:a,sectionFilter:Tn,activeSubTab:b,onSubTabChange:me});let i=u(On,{deviceId:r,sectionFilter:t=>t.location===`top-tab`&&(t.tab===e||e===`detection-pipeline`&&t.tab===`zones`),flattenSubTabs:e===`detection-pipeline`,activeSubTab:b,onSubTabChange:me});return n!==void 0&&r!==a?u($e,{deviceId:r,children:i}):i}}}return l?N?r(`div`,{className:`flex flex-col h-full`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-4`,children:[u(`div`,{className:`h-4 w-48 rounded bg-surface-hover animate-pulse mb-3`}),u(`div`,{className:`h-8 w-64 rounded bg-surface-hover animate-pulse`})]}),u(`div`,{className:`flex-1 p-6`,children:u(`div`,{className:`h-40 rounded-lg border border-border bg-surface animate-pulse`})})]}):P||!M?r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Device not found`}),r(`p`,{className:`text-xs`,children:[`No device with ID`,` `,r(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:[`#`,a]})]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]}):r(`div`,{className:`absolute inset-0 flex flex-col overflow-clip`,children:[r(`div`,{className:`border-b border-border bg-surface px-6 py-3 flex-shrink-0`,children:[u(`div`,{className:`mb-2`,children:u(at,{items:[{label:`Integrations`,onClick:()=>d(`/integrations`)},Y===null?{label:xe}:{label:xe,onClick:()=>d(`/integrations/${Y.id}`)},{label:z}]})}),r(`div`,{className:`flex items-center gap-2 sm:gap-3`,children:[Y!==null&&u(wi,{provider:Y.addonId,integrationId:Y.id,name:Y.name}),r(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`h1`,{className:`text-sm sm:text-base font-semibold text-foreground truncate`,children:z}),u(Cn,{status:ee}),je&&u(ze,{status:Me,variant:`full`}),u(tt,{status:Ne})]}),ae!==null&&oe&&r(`button`,{type:`button`,onClick:()=>d(`/devices/${ae}`),className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1`,title:`Open parent device ${oe.name}`,children:[u(`span`,{children:`↑`}),u(`span`,{className:`truncate`,children:String(oe.name??`Device #${ae}`)})]}),u(`div`,{className:`hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle`,children:U.length>0&&u(cn,{capabilities:U})})]}),We&&u(`div`,{className:`hidden lg:flex`,children:u(ki,{metrics:We,dbfs:Ke})}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[r(`button`,{onClick:async()=>{le?await m({title:`Disable "${z}"?`,message:`The device will stop processing streams and events. You can re-enable it later.`,confirmLabel:`Disable`,variant:`danger`})&&Ee.mutate({deviceId:a}):Te.mutate({deviceId:a})},disabled:Be,title:le?`Disable device`:`Enable device`,className:`inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 ${le?`border-success/30 text-success hover:bg-success/10`:`border-border text-foreground-subtle/50 hover:text-foreground hover:bg-surface-hover`}`,children:[u(F,{className:`h-3.5 w-3.5`}),u(`span`,{className:`hidden sm:inline`,children:Be?`Updating…`:le?`Enabled`:`Disabled`})]}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`}),G&&r(o,{children:[u(Rn,{deviceId:a}),u(`div`,{className:`hidden sm:block h-5 w-px bg-border mx-1`})]}),u(Bn,{deviceId:a}),u(Bt,{triggerClassName:`ml-1`,items:[{id:`snapshot`,label:`Take snapshot`,description:`Fetch a fresh frame and download it.`,icon:E,disabled:Pe,onClick:()=>{Le()}},{id:`reboot`,label:`Reboot device`,description:`Camera goes offline for ~30 seconds.`,icon:Vt,hidden:!Ae,disabled:De.isPending,danger:!0,onClick:async()=>{await m({title:`Reboot "${z}"?`,message:`The camera will go offline for around 30 seconds while the firmware reboots.`,confirmLabel:`Reboot`,variant:`danger`})&&De.mutate({deviceId:a})}},{id:`restart-addon`,label:`Restart addon`,description:`Bounces every device served by ${Se}.`,icon:Xt,disabled:ke.isPending,danger:!0,onClick:async()=>{await m({title:`Restart "${Se}"?`,message:`Restarting the addon will briefly disconnect every device served by it (not just "${z}"). Streams will reconnect automatically.`,confirmLabel:`Restart`,variant:`danger`})&&ke.mutate({addonId:H})}},{id:`delete`,label:`Delete device`,description:`Remove the device and all its settings.`,icon:C,separatorBefore:!0,disabled:we.isPending,danger:!0,onClick:async()=>{await m({title:`Delete "${z}"?`,message:`This will remove the device and all its settings. This action cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&we.mutate({deviceId:a})}}]})]})]})]}),u($e,{deviceId:a,device:R??void 0,children:u(Ft,{children:u(Ce,{children:u(w,{children:u(mt,{children:r(`main`,{className:J?`flex-1 overflow-y-auto flex flex-col`:`flex-1 min-h-0 overflow-hidden flex flex-row`,children:[r(`div`,{className:J?`flex flex-col bg-surface`:`${D===null?`w-1/2 lg:w-1/3`:``} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!J&&D!==null?{width:`${String(D)}px`}:void 0,children:[u(`div`,{className:G?`flex-shrink-0 border-b border-border-subtle bg-black`:J?`flex-shrink-0 border-b border-border-subtle bg-surface`:`max-h-[55%] shrink-0 overflow-y-auto border-b border-border-subtle bg-surface`,children:G?u(br,{deviceId:a,intercomAvailable:U.includes(pn.TwoWayAudio)}):u(ur,{deviceId:a,deviceName:z,deviceType:W??`unknown`,provider:H,isOnline:B,features:U})}),r(`div`,{className:J?`flex flex-col border-b border-border`:`flex-1 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border-subtle px-2 py-1.5`,children:u(`div`,{className:`flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5`,children:ge.map(({id:e,label:t,icon:n})=>r(`button`,{onClick:()=>S(e),title:t,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${x===e?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[u(n,{className:`h-3 w-3`}),t]},e))})}),r(`div`,{className:J?`h-72 overflow-hidden`:`flex-1 min-h-0 overflow-hidden`,children:[x===`logs`&&u(xr,{deviceId:a,containerDeviceId:W===`container`?a:void 0}),x===`repl`&&u(Sr,{deviceId:a}),x===`events`&&u(Cr,{deviceId:a}),x===`state`&&u(wr,{deviceId:a})]})]})]}),!J&&u(`div`,{role:`separator`,"aria-orientation":`vertical`,title:`Drag to resize`,onMouseDown:j,className:`flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10`,children:u(`span`,{className:`absolute inset-y-0 -left-1 -right-1`})}),r(`div`,{className:J?`flex flex-col`:`flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden`,children:[u(`div`,{className:`flex-shrink-0 border-b border-border bg-surface px-4`,children:u(`div`,{className:`flex flex-nowrap overflow-x-auto md:flex-wrap md:overflow-x-visible items-center gap-0`,children:ue.map(e=>{let t=de===e.id;return r(`button`,{onClick:()=>fe(e.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${t?`text-primary`:`text-foreground-subtle hover:text-foreground`}`,children:[e.label,t&&u(`span`,{className:`absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary`})]},e.id)})})}),r(`div`,{className:J?`p-3 flex flex-col gap-3`:`flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3`,children:[de===`overview`&&he&&u(Vn,{parentDeviceId:a}),qe()]})]})]})})})})})})]}):r(`div`,{className:`flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle`,children:[u(`p`,{className:`text-lg font-semibold text-foreground`,children:`Invalid device id`}),r(`p`,{className:`text-xs`,children:[`The URL segment`,` `,u(`code`,{className:`font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]`,children:n.deviceId}),` `,`is not a number.`]}),u(`button`,{onClick:()=>d(`/integrations`),className:`mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors`,children:`Back to Integrations`})]})}function ki({metrics:e,dbfs:t}){let n=Nt(e.phase??`idle`);return r(`div`,{className:`flex items-center gap-3 flex-shrink-0`,children:[r(`div`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`h-1.5 w-1.5 rounded-full ${n.dotClass}`}),u(`span`,{className:`text-[10px] font-medium ${n.textColor}`,children:n.label})]}),u(`div`,{className:`h-3 w-px bg-border`}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(ne,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.actualFps??0).toFixed(1)}),u(`span`,{children:`fps`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[u(gt,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:(e.avgInferenceTimeMs??0).toFixed(0)}),u(`span`,{children:`ms`})]}),r(`div`,{className:`flex items-center gap-1 text-[10px] text-foreground-subtle`,title:`Current audio level (dBFS)`,children:[u(H,{className:`h-3 w-3`}),u(`span`,{className:`text-foreground tabular-nums`,children:t==null?`—`:t.toFixed(0)}),u(`span`,{children:`dB`})]}),(e.queueDepth??0)>0&&r(`span`,{className:`text-[10px] text-warning tabular-nums`,children:[`q:`,e.queueDepth]})]})}export{Oi as DeviceDetailPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,U as i,W as a,a as o,b as s,o as c,q as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{X as f,Z as p,_t as m,at as h,ct as g,ft as _,gt as v,st as y,yt as b}from"./player-overlays-ktPblw8g.js";import{$l as x,$t as S,Ba as C,Bt as w,Eu as T,Fa as E,Ga as D,Gu as O,Ha as k,Ja as A,Jc as j,Ka as M,La as N,Nt as P,Oc as F,Oo as ee,Qa as te,Qc as ne,R as I,Ra as re,Tc as L,Ua as R,Un as ie,Ut as z,Va as B,Vc as V,Wa as H,Xa as ae,Ya as oe,Za as se,Zc as ce,_n as le,an as U,bc as ue,bn as W,du as de,en as fe,eo as pe,fl as me,gn as he,io as ge,jt as _e,mo as ve,mu as ye,no as be,oi as xe,on as G,ou as Se,rn as Ce,ro as we,to as Te,uu as Ee,vn as De,vo as Oe,wa as ke,wu as Ae,xn as je,yc as Me,yl as Ne,yu as Pe,zl as K}from"./src-CExJu3gi.js";import{t as Fe}from"./square-check-big-DBmxHLSu.js";import{Gt as Ie,In as Le}from"./src-DCJABiaG.js";import{n as Re}from"./index-qsRpCvR5.js";import{t as ze}from"./AdminPage-CiKtOLQm.js";import{a as Be,i as Ve,r as He,t as Ue}from"./authed-media-qZnqtqU3.js";import{a as We,c as Ge,d as Ke,f as qe,i as Je,n as Ye,o as Xe,p as Ze,r as Qe,s as $e,t as et}from"./debounced-invalidate-ckAXYt7l.js";import{t as tt}from"./use-stationary-objects-Dw5yZlWu.js";import{t as nt}from"./AdminTabs-CsuISePK.js";import{t as rt}from"./format-size-DIxKXxtj.js";var it=b(`arrow-down-wide-narrow`,[[`path`,{d:`m3 16 4 4 4-4`,key:`1co6wj`}],[`path`,{d:`M7 20V4`,key:`1yoxec`}],[`path`,{d:`M11 4h10`,key:`1w87gc`}],[`path`,{d:`M11 8h7`,key:`djye34`}],[`path`,{d:`M11 12h4`,key:`q8tih4`}]]),at=b(`circle-dashed`,[[`path`,{d:`M10.1 2.182a10 10 0 0 1 3.8 0`,key:`5ilxe3`}],[`path`,{d:`M13.9 21.818a10 10 0 0 1-3.8 0`,key:`11zvb9`}],[`path`,{d:`M17.609 3.721a10 10 0 0 1 2.69 2.7`,key:`1iw5b2`}],[`path`,{d:`M2.182 13.9a10 10 0 0 1 0-3.8`,key:`c0bmvh`}],[`path`,{d:`M20.279 17.609a10 10 0 0 1-2.7 2.69`,key:`1ruxm7`}],[`path`,{d:`M21.818 10.1a10 10 0 0 1 0 3.8`,key:`qkgqxc`}],[`path`,{d:`M3.721 6.391a10 10 0 0 1 2.7-2.69`,key:`1mcia2`}],[`path`,{d:`M6.391 20.279a10 10 0 0 1-2.69-2.7`,key:`1fvljs`}]]),ot=b(`circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),st=b(`graduation-cap`,[[`path`,{d:`M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z`,key:`j76jl0`}],[`path`,{d:`M22 10v6`,key:`1lu8f3`}],[`path`,{d:`M6 12.5V16a6 3 0 0 0 12 0v-3.5`,key:`1r8lef`}]]),ct=b(`square-parking`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 17V7h4a3 3 0 0 1 0 6H9`,key:`1dfk2c`}]]);n();function lt(e){return e.subLabel??e.label}var ut=720*60*60*1e3;function dt(e){let t=[];for(let n of e)t.push(...n);return t}function ft(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function pt(e,t){return e.filter(e=>!(e.importance<t.minImportance||t.cameras.size>0&&!t.cameras.has(e.deviceId)||t.classes.size>0&&!t.classes.has(e.className)))}function mt(e,t){return`${String(e)}:${t}`}function ht(e,t){let n=new Map,r=new Set;for(let i of e){let e=mt(i.deviceId,i.trackId);if(!t.has(e)||r.has(e))continue;r.add(e);let a=n.get(i.deviceId);a?a.push(i.trackId):n.set(i.deviceId,[i.trackId])}return n}function gt(e,t){return{since:e.fromMs??t-ut,until:e.toMs??t}}var _t=[`native`,`raster`,`standin`];function vt(e){return _t.some(t=>t===e)}var yt={standin:{label:`stand-in`,title:`Stand-in: this tile is a face or plate detail crop copied in because no frame of the subject was captured. It is not a best shot.`,tone:`warning`},raster:{label:`low-res`,title:`Raster crop: a sub-native cut of the subject, not a native capture. Honest, but lower resolution than a best shot.`,tone:`info`}};function bt(e){return e===`standin`?yt.standin:e===`raster`?yt.raster:null}var xt={"no-key-frame":`No key frame existed at close, so no native tile could be cut.`,"no-best-seen-bbox":`No subject box was ever recorded, so there was nothing to cut around.`,"derive-returned-null":`The close-time crop was attempted and produced nothing.`,"derive-threw":`The close-time crop failed with an error.`,"derive-not-wired":`No close-time crop was wired on this node.`,"no-media-store":`The node was shutting down mid-close.`,"no-thumbnail":`The track closed with no tile of any kind.`,"standin-tile":`The track closed with a detail crop standing in for the subject.`,"raster-tile":`The track closed with a sub-native raster crop of the subject.`,"native-tile":`The track closed with a native tile.`};function St(e){if(e===void 0)return null;let t=e.trim();if(t.length===0)return null;let n=t.split(/\s+/),r=n[0]??t,i=[];for(let e of n.slice(1)){let t=e.indexOf(`=`);t===-1?i.push({key:e,value:null}):i.push({key:e.slice(0,t),value:e.slice(t+1)})}return{sentence:xt[r]??r,detail:i,raw:t}}function Ct(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${String(n)}m ${String(r).padStart(2,`0`)}s`}function wt({row:e,cameraName:t,nowMs:n,onOpenDetail:i,selected:a=!1,onToggleSelect:o,score:s,provenance:c,footer:l}){let d=Be(e.mediaId===void 0?Ve(`track`,e.trackId):He(e.mediaId)),f=Math.round(e.importance*100),p=s===void 0?void 0:Math.round(s*100),m=Ct(e.windowMs),h=()=>i(e),v=bt(c);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${a?`border-primary ring-1 ring-primary`:`border-border`}`,children:[r(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[d.src?u(`img`,{src:d.src,alt:`Event from ${t}`,onClick:h,className:`h-full w-full cursor-zoom-in object-cover`}):u(`button`,{type:`button`,onClick:h,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:d.failed?`Key-event media unavailable`:`No key-event media`,children:u(_,{className:`h-6 w-6 opacity-60`})}),o&&u(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),o(mt(e.deviceId,e.trackId))},className:`absolute left-0 top-0 z-10 rounded-br-md bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":a?`Deselect`:`Select`,children:a?u(Fe,{className:`h-4 w-4 text-primary`}):u(g,{className:`h-4 w-4`})}),p!==void 0&&r(`span`,{className:`absolute left-1 top-1 z-10 rounded bg-primary/85 px-1.5 py-0.5 text-[10px] font-semibold text-white tabular-nums`,title:`CLIP semantic-match score`,children:[String(p),`%`]}),f>0&&u(`span`,{className:`absolute right-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white`,children:String(f)}),v!==null&&u(`span`,{className:`absolute bottom-1 right-1 z-10 rounded px-1.5 py-0.5 text-[10px] font-semibold text-white ${v.tone===`warning`?`bg-warning/90`:`bg-black/70`}`,title:v.title,children:v.label}),(e.markForTrain===!0||e.debug===!0||e.favourited===!0)&&r(`span`,{className:`absolute bottom-1 left-1 z-10 flex gap-1`,children:[e.markForTrain===!0&&u(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Marked for training`,"aria-label":`Marked for training`,children:u(st,{className:`h-3 w-3`})}),e.debug===!0&&u(`span`,{className:`rounded bg-black/70 p-0.5 text-white`,title:`Flagged for debug`,"aria-label":`Flagged for debug`,children:u(T,{className:`h-3 w-3`})}),e.favourited===!0&&u(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Favourited`,"aria-label":`Favourited`,children:u(ce,{className:`h-3 w-3`})})]})]}),r(`button`,{type:`button`,onClick:h,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[r(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:e.className,children:[e.className,lt(e)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,lt(e)]}):null]}),u(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:t,children:t}),r(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:qe(e.timestamp,n)}),m&&u(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:m})]})]}),l!==void 0&&u(`div`,{className:`px-2 pb-1.5`,children:l})]})}var Tt=1400,Et=`Admin-gated URL — opens only inside an authenticated session`;function Dt({label:t,value:n,title:i}){let[a,o]=l(!1),s=De();return d(()=>{if(!a)return;let e=setTimeout(()=>o(!1),Tt);return()=>clearTimeout(e)},[a]),r(`button`,{type:`button`,onClick:e(()=>{(async()=>{try{await navigator.clipboard.writeText(n),o(!0)}catch{await s({title:`Copy the media URL`,message:`Clipboard access was refused. Select the URL below and copy it manually.`,label:`${t} URL`,defaultValue:n,readOnly:!0,cancelLabel:`Close`})}})()},[n,t,s]),title:i,"aria-label":`Copy ${t} URL`,className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${a?`border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[u(a?Ae:Ee,{className:`h-2.5 w-2.5 shrink-0`}),u(`span`,{className:`truncate`,children:a?`Copied`:t})]})}function Ot({localUrl:e,publicUrl:t}){return r(`div`,{className:`flex flex-wrap gap-1`,children:[u(Dt,{label:`Local`,value:e,title:`Copy LAN URL — ${Et}`}),t&&u(Dt,{label:`Public`,value:t,title:`Copy public URL — ${Et}`})]})}var kt={firstFrame:`First frame (track start)`,lastFrame:`Last frame (track end)`,thumbnail:`Best detection`,thumbnailSmall:`Best detection (480)`,snapshot:`Snapshot`,keyFrame:`Key frame (native-res)`,keyFrameSmall:`Key frame (960)`,crop:`Object crop`,fullFrame:`Full frame`,fullFrameBoxed:`Full frame (boxed)`,faceCrop:`Face crop`,plateCrop:`Plate crop`,confirmationCrop:`Confirmation crop (what the gate saw)`,debugCrop:`Debug crop (why this decision)`,sceneFrame:`Scene frame (clean)`,lastSceneFrame:`Last frame (clean)`};function At(e){return e in kt}function jt(e){return At(e)?kt[e]:e}function Mt(e,t){return`${e}${t}`}n();var Nt=3e4;function Pt(t){let[n,r]=l(null),i=e(e=>{r(t=>t??e)},[]);return d(()=>{t||r(null)},[t]),{publicOrigin:n,probes:t?u(Ft,{onOrigin:i}):null}}function Ft({onOrigin:e}){let{data:t}=ie({capName:`network-access`});return u(s,{children:(t??[]).map(t=>u(It,{addonId:t.addonId,onOrigin:e},t.addonId))})}function It({addonId:e,onOrigin:t}){let{data:n}=ke({addonId:e},{refetchInterval:Nt,retry:!1});return d(()=>{let e=n?Ie.safeParse(n):null,r=e?.success?e.data.endpoint?.url:void 0;if(r)try{t(new URL(r).origin)}catch{}},[n,t]),null}var q=typeof we==`function`,Lt=`Track flags arrive with the next server update`;function Rt(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var zt=q?we:Rt;function Bt(e){if(typeof e!=`object`||!e||!(`trackId`in e)||!(`markForTrain`in e)||!(`debug`in e)||!(`favourited`in e))return null;let{trackId:t,markForTrain:n,debug:r,favourited:i}=e;return typeof t!=`string`||typeof n!=`boolean`||typeof r!=`boolean`||typeof i!=`boolean`?null:{trackId:t,markForTrain:n,debug:r,favourited:i}}n();function Vt({label:e,hint:t,checked:n,disabled:i,title:a,icon:o,onToggle:s}){return r(`button`,{type:`button`,role:`switch`,"aria-checked":n,"aria-label":e,disabled:i,title:a,onClick:s,className:`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left transition-colors disabled:opacity-50 ${n?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[u(`span`,{className:n?`text-primary`:`text-foreground-subtle`,children:o}),r(`span`,{className:`min-w-0 flex-1`,children:[u(`span`,{className:`block text-[11px] font-medium text-foreground`,children:e}),u(`span`,{className:`block text-[10px] text-foreground-subtle`,children:t})]}),u(`span`,{"aria-hidden":`true`,className:`h-4 w-7 shrink-0 rounded-full p-0.5 transition-colors ${n?`bg-primary`:`bg-border`}`,children:u(`span`,{className:`block h-3 w-3 rounded-full bg-white transition-transform ${n?`translate-x-3`:``}`})})]})}function Ht({deviceId:e,trackId:t,markForTrain:n,debug:i,favourited:a,onChange:o}){let s=zt(),c=he(),[d,f]=l(null),p=d?.markForTrain??n===!0,m=d?.debug??i===!0,h=d?.favourited??a===!0,g=!q||s.isPending,_=q?void 0:Lt,v=n=>{g||(async()=>{try{let r=Bt(await s.mutateAsync({deviceId:e,trackId:t,flags:n}));if(!r)return;f(r),o?.(r)}catch(e){let t=e instanceof Error?e.message:``;await c({title:`Could not update this track`,message:t===``?`Could not update this track. Check the server logs.`:t,variant:`danger`})}})()};return r(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[u(Vt,{label:`Mark for training`,hint:`Keeps this track and its media past retention`,checked:p,disabled:g,..._===void 0?{}:{title:_},icon:u(st,{className:`h-4 w-4`}),onToggle:()=>v({markForTrain:!p})}),u(Vt,{label:`Debug`,hint:`Flag this track for diagnostic attention`,checked:m,disabled:g,..._===void 0?{}:{title:_},icon:u(T,{className:`h-4 w-4`}),onToggle:()=>v({debug:!m})}),u(Vt,{label:`Favourited`,hint:`Keeps this track and its media past retention`,checked:h,disabled:g,..._===void 0?{}:{title:_},icon:u(ce,{className:`h-4 w-4`}),onToggle:()=>v({favourited:!h})})]})}var J=100,Ut=120,Wt={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},Y=e=>e<0?0:e>1?1:e,X=e=>Math.round(e*100)/100;function Gt(e,t){if(e.length<=t)return[...e];let n=(e.length-1)/(t-1),r=[];for(let i=0;i<t;i++)r.push(e[Math.round(i*n)]);return r[r.length-1]=e[e.length-1],r}function Kt(e,t,n){if(e.length===0||t===null)return Wt;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return Wt;let a=Gt(e,n?.maxPoints??Ut).map(e=>({x:X(Y(e.x/r)*J),y:X(Y(e.y/i)*J)})),o=a[0]??null,s=a[a.length-1]??null,c=a.length>=2?a.map(e=>`${e.x},${e.y}`).join(` `):``,l=(n?.snapshots??[]).map(e=>({x:X(Y(e.x/r)*J),y:X(Y(e.y/i)*J),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=Y(t.bbox.w/r)*Y(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:X(Y(u.bbox.x/r)*J),y:X(Y(u.bbox.y/i)*J),w:X(Y(u.bbox.w/r)*J),h:X(Y(u.bbox.h/i)*J)}:null}}var qt=typeof N==`function`,Jt=`Track deletion arrives with the next server update`;function Yt(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var Xt=qt?N:Yt;n();var Zt=15e3,Qt=f();function $t({url:e,label:t}){let{src:n,failed:r}=Be(e);return n===null?u(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?u(_,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):u(K,{className:`h-4 w-4 animate-spin text-foreground-subtle opacity-70`})}):u(`img`,{src:n,alt:t,className:`h-full w-full object-cover`})}var en=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),tn=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function nn(e){let[t,n]=l(null);return d(()=>{if(n(null),!e)return;let t=!1,r=new Image;return r.onload=()=>{t||n({width:r.naturalWidth,height:r.naturalHeight})},r.src=e,()=>{t=!0,r.onload=null}},[e]),t}function rn({overlay:e,onPickSnapshot:t}){return!e.polyline&&!e.peakBox&&e.snapshots.length===0?null:r(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[e.peakBox&&u(`rect`,{x:e.peakBox.x,y:e.peakBox.y,width:e.peakBox.w,height:e.peakBox.h,fill:`none`,stroke:`#f59e0b`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&u(`polyline`,{points:e.polyline,fill:`none`,stroke:`#38bdf8`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),e.points.map((e,t)=>u(`circle`,{cx:e.x,cy:e.y,r:1,fill:`#38bdf8`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),e.snapshots.map((e,n)=>u(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`#0ea5e9`,fillOpacity:.95,stroke:`#082f49`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:t?`pointer-events-auto cursor-pointer`:void 0,onClick:t?n=>{n.stopPropagation(),t(e.mediaId)}:void 0,children:u(`title`,{children:`Snapshot checkpoint — click to view this frame`})},`snap-${String(e.mediaId)}-${String(n)}`)),e.start&&u(`circle`,{cx:e.start.x,cy:e.start.y,r:2.4,fill:`#22c55e`,stroke:`#052e16`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&u(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`#ef4444`,stroke:`#450a0a`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function Z({label:e,value:t,mono:n}){return r(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[u(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),u(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground ${n?`font-mono text-[11px]`:``}`,title:t,children:t})]})}function an({row:t,cameraName:n,deleteAvailable:i,onClose:o,onDeleted:c,onFlagsChanged:f}){let p=h(),m=he(),g=le(),v=Xt(),b=t!==null,S=t?.deviceId??0,C=t?.trackId??``,w=t?.timestamp??0,T=t?.windowMs??0,{data:E}=k({deviceId:S,trackId:C},{enabled:b}),{data:D}=se({trackId:C,deviceId:S},{enabled:b}),O=E?.bestEventId===void 0?void 0:Number(E.bestEventId),{data:A}=M({ownerType:`object`,eventId:O??0,deviceId:S},{enabled:b&&O!==void 0&&Number.isFinite(O)}),{data:j}=ue({deviceId:S},{enabled:b}),N=(j??[]).find(e=>e.addonId!==void 0)?.addonId,{data:ee}=Me({deviceId:S,since:w-Zt,until:w+T+Zt,provider:N??``},{enabled:b&&N!==void 0}),[te,ne]=l(null),[I,re]=l(!1),{publicOrigin:L,probes:R}=Pt(b);d(()=>{ne(null)},[S,C]);let ie=a(()=>{let e=D??[],t=A??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[D,A]),z=te??ie,B=Be(z?z.url:void 0),V=a(()=>{let e=new Set,t=[];for(let n of[...A??[],...D??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[A,D]),H=a(()=>V.find(e=>en.has(e.kind))??null,[V]),ae=nn(Be(H?H.url:void 0).src),oe=a(()=>Kt(E?.positions??[],ae,{snapshots:(E?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[E?.positions,E?.snapshots,ae]),ce=e(e=>{let t=V.find(t=>t.mediaId===e);t&&ne(t)},[V]);if(t===null)return null;let U=B.src,W=z?.kind,de=W!==void 0&&tn.has(W)&&ae!==null&&(E?.positions.length??0)>=2,fe=ee&&ee.length>0?ee[0]:null,pe=()=>{fe&&(re(!0),(async()=>{try{let e=await p.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:fe.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{m({title:`Clip unavailable`,message:`Could not resolve clip playback. Check the server logs.`,variant:`warning`})}finally{re(!1)}})())},me=()=>{!i||v.isPending||(async()=>{if(await g({title:`Delete track`,message:`Delete this track and every image and clip captured for it? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`}))try{await v.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),c()}catch{await m({title:`Delete failed`,message:`Failed to delete this track. Check the server logs.`,variant:`danger`})}})()},ge=Math.round(t.importance*100),ve=E?.importanceReason?`${String(ge)}% · ${E.importanceReason}`:`${String(ge)}%`,ye=E?.zonesVisited&&E.zonesVisited.length>0?E.zonesVisited.join(`, `):`—`,be=E?.audioLabels&&E.audioLabels.length>0?E.audioLabels.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `):`—`,xe=E?E.totalDistance.toFixed(2):`—`,Se=St(E?.previewMissReason),Ce=Ze(E?E.firstSeen:w),we=E?Ze(E.lastSeen):`—`;return u(_e,{open:!0,onOpenChange:e=>!e&&o(),children:r(P,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Event detail`,className:`flex h-[92dvh] flex-col gap-0 overflow-hidden p-0 bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none md:bottom-auto md:left-1/2 md:right-auto md:top-1/2 md:h-auto md:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[r(`header`,{className:`flex shrink-0 items-start justify-between gap-2 border-b border-border px-4 py-3`,children:[r(`div`,{className:`min-w-0`,children:[r(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,lt(t)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,lt(t)]}):null]}),u(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:n})]}),u(`button`,{type:`button`,onClick:o,className:`rounded p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Close`,children:u(F,{className:`h-4 w-4`})})]}),r(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[U?u(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:u(Ye,{src:U,alt:`Key frame from ${n}`,fit:`natural`,className:`w-full`,overlay:de?u(rn,{overlay:oe,onPickSnapshot:ce}):void 0})}):u(`div`,{className:`flex aspect-video w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-surface-hover text-foreground-subtle`,children:B.failed?r(s,{children:[u(_,{className:`h-8 w-8 opacity-60`}),u(`span`,{className:`text-[11px]`,children:`Key-frame media unavailable`})]}):u(K,{className:`h-6 w-6 animate-spin opacity-70`})}),V.length>0&&u(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:V.map(e=>{let t=jt(e.kind),n=Mt(Qt,e.url),i=L?Mt(L,e.url):null;return r(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[u(`button`,{type:`button`,onClick:()=>ne(e),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${t} · ${Ze(e.timestamp)}`,children:u($t,{url:e.url,label:t})}),r(`figcaption`,{className:`min-w-0 px-0.5`,children:[u(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:t,children:t}),u(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:Ze(e.timestamp),children:Ke(e.timestamp)})]}),u(Ot,{localUrl:n,publicUrl:i})]},e.mediaId)})}),R,fe&&r(G,{variant:`secondary`,onClick:pe,disabled:I,children:[I?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(x,{className:`h-3.5 w-3.5`}),` `,`View clip`]}),u(Ht,{deviceId:t.deviceId,trackId:t.trackId,...(E?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:E?.markForTrain??t.markForTrain},...(E?.debug??t.debug)===void 0?{}:{debug:E?.debug??t.debug},...(E?.favourited??t.favourited)===void 0?{}:{favourited:E?.favourited??t.favourited},onChange:f}),Se!==null&&r(`div`,{className:`rounded-lg border border-warning/40 bg-warning/8 px-3 py-2`,children:[u(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`Best shot`}),u(`p`,{className:`mt-0.5 text-xs text-foreground`,children:Se.sentence}),u(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:Se.raw})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[u(Z,{label:`Camera`,value:n}),u(Z,{label:`Class`,value:t.className}),u(Z,{label:`Label`,value:t.label??`—`}),u(Z,{label:`Sub-label`,value:t.subLabel??`—`}),u(Z,{label:`Importance`,value:ve}),u(Z,{label:`Zones visited`,value:ye}),u(Z,{label:`Audio heard`,value:be}),u(Z,{label:`Total distance`,value:xe}),u(Z,{label:`First seen`,value:Ce}),u(Z,{label:`Last seen`,value:we}),u(Z,{label:`Track`,value:t.trackId,mono:!0})]})]}),u(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:u(`span`,{title:i?void 0:Jt,children:r(G,{variant:`secondary`,onClick:me,disabled:!i||v.isPending,children:[v.isPending?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete track`]})})})]})})}var on=`pipeline-analytics`,sn=`debug.listTracks`,cn=`debug.analyze`,ln=p(`/addon/pipeline-analytics/debug-export`);function un(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`string`?n:null}function $(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function dn(e,t){let n=e[t];return typeof n==`boolean`?n:null}function fn(e){return e===`error`||e===`warn`||e===`info`}function pn(e){if(!un(e))return null;let t=Q(e,`code`),n=Q(e,`detail`),r=e.severity;return t===null||n===null||!fn(r)?null:{code:t,severity:r,detail:n}}function mn(e){if(!un(e))return null;let t=Q(e,`trackId`),n=$(e,`deviceId`),r=Q(e,`className`),i=$(e,`firstSeen`),a=$(e,`lastSeen`),o=$(e,`durationMs`),s=dn(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=Q(e,`label`),l=Q(e,`subLabel`),u=Q(e,`previewMissReason`),d=dn(e,`markForTrain`),f=dn(e,`favourited`);return{trackId:t,deviceId:n,className:r,...c===null?{}:{label:c},...l===null?{}:{subLabel:l},firstSeen:i,lastSeen:a,durationMs:o,active:s,timestamp:i,windowMs:o,importance:$(e,`importance`)??0,bestEventId:Q(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function hn(e){let t=mn(e);if(t===null||!un(e))return null;let n=$(e,`mediaCount`),r=$(e,`eventCount`),i=$(e,`positionCount`);if(n===null||r===null||i===null)return null;let a=e.mediaKinds,o=e.findings;if(!Array.isArray(a)||!Array.isArray(o))return null;let s=a.filter(e=>typeof e==`string`),c=[];for(let e of o){let t=pn(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...vt(l)?{thumbnailProvenance:l}:{}}}function gn(e){if(!un(e))return null;let t=dn(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=mn(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function _n(e){if(!un(e))return null;let t=e.reports,n=e.vanished;if(!Array.isArray(t)||!Array.isArray(n))return null;let r=[];for(let e of t){let t=hn(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var vn={MEDIA_EVICTED_OR_NEVER:`no media`,MISSING_KEYFRAME:`no keyframe`,MISSING_FIRSTFRAME:`no first frame`,MISSING_LASTFRAME:`no last frame`,MISSING_THUMBNAIL:`no thumbnail`,MISSING_BEST_CROP:`no crop`,SHORT_TRACK:`very short`,ZERO_EVENTS:`no events`,ZERO_POSITIONS:`no trajectory`,NO_PERIODIC_SNAPSHOTS:`no snapshots`,LASTFRAME_STALE:`stale last frame`,MEDIA_STOPPED_EARLY:`media stopped early`,NO_BEST_EVENT:`no best event`,LOW_BEST_SCORE:`low score`,UNSCORED_LABEL:`unscored label`,BEST_SHOT_STANDIN:`stand-in best shot`,BEST_SHOT_RASTER:`low-res best shot`};function yn(e){return vn[e]??e}var bn={error:0,warn:1,info:2};function xn(e){return e.toSorted((e,t)=>bn[e.severity]-bn[t.severity]||e.code.localeCompare(t.code))}function Sn(e){return e.length===0?ln:`${ln}?deviceIds=${e.join(`,`)}`}function Cn(e,t){return`${String(e)}:${t}`}function wn(e,t){let n=[],r=new Set;for(let i of e){let e=Cn(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}n();var Tn=`all`,En=`The server answered in a shape this build does not understand.`,Dn={error:`danger`,warn:`warning`,info:`info`};function On({findings:e}){return e.length===0?u(S,{variant:`success`,children:`no anomaly found`}):u(`div`,{className:`flex flex-wrap gap-1`,children:xn(e).map(e=>u(S,{variant:Dn[e.severity],title:e.detail,children:yn(e.code)},e.code))})}function kn({track:e,report:t,analyzing:n}){let i=St(t?.previewMissReason??e.previewMissReason);return r(`div`,{className:`space-y-1 border-t border-border pt-1.5`,children:[t===void 0?u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n?`analysing…`:`not analysed`}):r(s,{children:[u(On,{findings:t.findings}),r(`p`,{className:`text-[10px] text-foreground-subtle`,title:t.mediaKinds.length>0?t.mediaKinds.join(`, `):`no media of any kind`,children:[String(t.mediaCount),` media · `,String(t.eventCount),` events ·`,` `,String(t.positionCount),` positions`]})]}),i!==null&&u(`p`,{className:`text-[10px] text-foreground-subtle`,title:i.raw,children:i.sentence})]})}function An(){let e=h(),[t,n]=l(Tn),[i,s]=l(!1),[c,d]=l(null),[f,p]=l(new Set),[m,g]=l(null),[_,v]=l(null),[y,b]=l(null),[x,S]=l([]),C=zt(),w=xe({isCamera:!0,projection:`slim`}),E=a(()=>[{value:Tn,label:`All cameras`},...(w.data??[]).map(e=>({value:String(e.id),label:e.name}))],[w.data]),D=a(()=>{let e=new Map;for(let t of w.data??[])e.set(t.id,t.name);return e},[w.data]),O=e=>D.get(e)??`Camera ${String(e)}`,k=a(()=>t===Tn?[]:[Number.parseInt(t,10)],[t]),A=o({queryKey:[`events-debug`,`list`,k],queryFn:async()=>gn(await e.trpcClient.addons.custom.mutate({addonId:on,action:sn,input:k.length===0?{}:{deviceIds:k}}))}),j=a(()=>(A.data?.tracks??[]).map(e=>e.trackId),[A.data]),M=o({queryKey:[`events-debug`,`analyze`,j],enabled:j.length>0,queryFn:async()=>_n(await e.trpcClient.addons.custom.mutate({addonId:on,action:cn,input:{trackIds:j}}))}),N=a(()=>{let e=new Map;for(let t of M.data?.reports??[])e.set(t.trackId,t);return e},[M.data]),P=A.data?.tracks??[],ee=A.data===null||M.data===null,te=()=>{A.refetch(),M.refetch()},ne=e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},I=()=>{p(new Set(P.map(e=>Cn(e.deviceId,e.trackId))))},re=()=>p(new Set),L=async(e,t)=>{let n=e===`analyzed`?{debug:!1}:{favourited:!0},r=0,i=[];for(let e of t)try{await C.mutateAsync({deviceId:e.deviceId,trackId:e.trackId,flags:n}),r+=1}catch{i.push(e.trackId)}return{applied:r,refused:i}},R=e=>{if(!q||_!==null)return;let t=wn(P,f);t.length!==0&&(v(e),b(null),(async()=>{let n=await L(e,t);v(null);let r=new Set(n.refused);p(new Set(t.filter(e=>r.has(e.trackId)).map(e=>Cn(e.deviceId,e.trackId)))),e===`analyzed`&&S(t.filter(e=>!r.has(e.trackId))),n.refused.length>0&&b(`${String(n.refused.length)} of ${String(t.length)} were refused by the server and are still selected. Check the hub log.`),A.refetch()})())},ie=()=>{let e=x;e.length===0||_!==null||(v(`analyzed`),b(null),(async()=>{for(let t of e)try{await C.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{b(`Some tracks could not be re-marked. Refresh and try again.`)}v(null),S([]),A.refetch()})())},z=async()=>{s(!0),d(null);try{await Ue(Sn(k),`camstack-debug.zip`)}catch(e){d(e instanceof Error?e.message:`Export failed.`)}finally{s(!1)}},B=_!==null;return u(ze,{children:r(`section`,{className:`space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`div`,{className:`w-44`,children:u(U,{value:t,options:E,onChange:e=>n(e.target.value)})}),r(G,{variant:`secondary`,onClick:te,disabled:A.isFetching,children:[A.isFetching?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),`Refresh`]}),r(G,{onClick:()=>void z(),disabled:i||P.length===0,children:[i?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Se,{className:`h-3.5 w-3.5`}),`Export all (`,String(P.length),`)`]}),P.length>0&&f.size<P.length&&u(G,{variant:`ghost`,onClick:I,children:`Select all`})]}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A `,u(`code`,{children:`debug`}),` mark does not pin retention — this lists the marked tracks that still exist. A track whose media was evicted shows as missing media. Use `,u(`strong`,{children:`Keep`}),` `,`to hold a selection against pruning while you investigate, and `,u(`strong`,{children:`Analyzed`}),` `,`to un-mark the ones you are finished with.`]}),A.isError&&u(Ce,{message:`Could not load the marked tracks.`}),ee&&!A.isError&&u(Ce,{message:En}),c!==null&&u(Ce,{message:c}),y!==null&&u(Ce,{message:y}),A.data?.truncated===!0&&u(Ce,{message:`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`}),(M.data?.vanished.length??0)>0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:[String(M.data?.vanished.length),` marked track(s) were evicted between the list and the analysis.`]}),f.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[String(f.size),` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[u(`span`,{title:q?void 0:`Track flags arrive with the next server update`,children:r(G,{variant:`secondary`,onClick:()=>R(`keep`),disabled:!q||B,children:[_===`keep`?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(ce,{className:`h-3.5 w-3.5`}),` `,`Keep`]})}),u(`span`,{title:q?void 0:`Track flags arrive with the next server update`,children:r(G,{onClick:()=>R(`analyzed`),disabled:!q||B,children:[_===`analyzed`?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(Ae,{className:`h-3.5 w-3.5`}),` `,`Analyzed`]})}),u(G,{variant:`ghost`,onClick:re,disabled:B,children:u(F,{className:`h-3.5 w-3.5`})})]})]}),x.length>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border bg-surface px-3 py-2`,children:[r(`span`,{className:`text-xs text-foreground`,children:[String(x.length),` track(s) marked analyzed and removed from this list.`]}),r(G,{variant:`ghost`,onClick:ie,disabled:B,children:[u(V,{className:`h-3.5 w-3.5`}),` Undo`]}),u(G,{variant:`ghost`,onClick:()=>S([]),disabled:B,children:u(F,{className:`h-3.5 w-3.5`})})]}),A.isLoading?u(fe,{children:u(`div`,{className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`Loading…`})}):P.length===0?u(fe,{children:r(`div`,{className:`flex flex-col items-center gap-2 px-3 py-8 text-center`,children:[u(T,{className:`h-5 w-5 text-foreground-subtle`}),u(`p`,{className:`text-xs text-foreground-subtle`,children:`No track is marked for debug. Mark one from a track's actions to see it here.`})]})}):u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:P.map(e=>{let t=N.get(e.trackId);return u(wt,{row:e,cameraName:O(e.deviceId),nowMs:e.lastSeen,selected:f.has(Cn(e.deviceId,e.trackId)),onToggleSelect:ne,onOpenDetail:g,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:u(kn,{track:e,report:t,analyzing:M.isFetching})},Cn(e.deviceId,e.trackId))})}),m&&u(an,{row:m,cameraName:O(m.deviceId),deleteAvailable:qt,onClose:()=>g(null),onDeleted:()=>{g(null),A.refetch()},onFlagsChanged:e=>{e.debug||(g(null),A.refetch())}})]})})}var jn=200,Mn=3e4,Nn=[];function Pn(e){let t=h(),n=e.deviceIds.length>0,r=[...e.deviceIds].sort((e,t)=>e-t),{data:i,isLoading:a}=o({queryKey:[`events-feed`,r,e.since,e.until,e.minImportance??null,e.classFilter??null],enabled:n,staleTime:Mn,refetchInterval:Mn,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:r,since:e.since,until:e.until,limit:jn,...e.minImportance===void 0?{}:{minImportance:e.minImportance},...e.classFilter===void 0?{}:{classFilter:e.classFilter}})).map(e=>e.events.map(t=>({...t,deviceId:e.deviceId})))});return{rows:ft(dt(i??Nn),`importance`),isLoading:n&&a}}n();var Fn=[`events-feed`],In=2e3;function Ln(n){let r=c(),i=n?.paused===!0,a=t(r);a.current=r;let o=t(i);o.current=i;let[s,u]=l(!1),f=e(()=>{a.current.invalidateQueries({queryKey:Fn})},[]),p=t(void 0);p.current||=et({delayMs:In,invalidate:()=>{o.current?u(!0):f()}}),d(()=>()=>p.current?.cancel(),[]),d(()=>{i||!s||(u(!1),f())},[i,s,f]);let m=e(()=>{u(!1),f()},[f]);return L(Le.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),L(Le.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:s,refreshNow:m}}n();function Rn({groups:e,selected:t,onChange:n,loading:i=!1}){let{t:o}=Re(),[s,c]=l(!1),[d,f]=l(``),[p,h]=l(new Set),g=d.trim().toLowerCase(),_=e=>g.length===0||W(e,o).toLowerCase().includes(g),y=a(()=>e.map(e=>({macro:e.macro,subs:e.subs.filter(t=>_(t)||_(e.macro))})).filter(e=>_(e.macro)||e.subs.length>0),[e,g]),b=e=>h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),x=e=>{let r=new Set(t),i=t.has(e.macro.kind)&&e.subs.every(e=>t.has(e.kind)),a=[e.macro.kind,...e.subs.map(e=>e.kind)];if(i)for(let e of a)r.delete(e);else for(let e of a)r.add(e);n(r)},S=e=>{let r=new Set(t);r.has(e)?r.delete(e):r.add(e),n(r)},C=()=>n(new Set),w=t.size;return r(`div`,{className:`relative`,children:[r(`button`,{type:`button`,onClick:()=>c(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${w>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[u(j,{className:`h-3.5 w-3.5`}),w>0?`Kinds (${String(w)})`:`Kinds`,u(m,{className:`h-3 w-3`})]}),s&&r(`div`,{className:`absolute z-20 mt-1 max-h-80 w-64 overflow-auto rounded-md border border-border bg-surface p-2 shadow-lg`,children:[r(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[u(me,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:`Search kinds…`,className:`w-full bg-transparent py-1 text-xs outline-none`}),w>0&&u(`button`,{type:`button`,onClick:C,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:`Clear`})]}),y.length===0&&u(`div`,{className:`px-1 py-2 text-[11px] text-foreground-subtle`,children:i?`Loading kinds…`:g.length>0?`No kind matches that search.`:`These cameras advertise no event kinds.`}),y.map(e=>{let n=je(e.macro.iconId),i=p.has(e.macro.kind)||g.length>0,a=t.has(e.macro.kind);return r(`div`,{className:`mb-0.5`,children:[r(`div`,{className:`flex items-center gap-1`,children:[e.subs.length>0?u(`button`,{type:`button`,onClick:()=>b(e.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Expand`,children:u(i?m:v,{className:`h-3 w-3`})}):u(`span`,{className:`w-3`}),r(`label`,{className:`flex flex-1 cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[u(`input`,{type:`checkbox`,checked:a,onChange:()=>x(e),className:`accent-primary`}),u(n,{className:`h-3.5 w-3.5`,style:{color:e.macro.color}}),u(`span`,{className:`font-medium`,children:W(e.macro,o)})]})]}),i&&e.subs.map(e=>{let n=je(e.iconId);return r(`label`,{className:`ml-5 flex cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[u(`input`,{type:`checkbox`,checked:t.has(e.kind),onChange:()=>S(e.kind),className:`accent-primary`}),u(n,{className:`h-3.5 w-3.5`,style:{color:e.color}}),u(`span`,{children:W(e,o)})]},e.kind)})]},e.macro.kind)})]})]})}function zn(e,t){let n=new Map;for(let r of e)if(!(t.size>0&&!t.has(r.deviceId)))for(let e of r.kinds)n.has(e.kind)||n.set(e.kind,e);return n}function Bn(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var Vn=new Set([`detection`,`package`]);function Hn(e,t){return[...zn(e,t).values()].filter(e=>e.parentKind===null&&Vn.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function Un(e,t){let n=zn(e,t),r=new Map,i=new Map;for(let e of n.values()){if(e.parentKind===null){i.set(e.kind,e);continue}let t=r.get(e.parentKind);t===void 0?r.set(e.parentKind,[e]):t.push(e)}for(let[e,t]of r){if(i.has(e))continue;let n=t[0];n!==void 0&&i.set(e,Bn(e,n))}return[...i.values()].map(e=>({macro:e,subs:[...r.get(e.kind)??[]].sort((e,t)=>e.label.localeCompare(t.label))})).sort((e,t)=>e.macro.label.localeCompare(t.macro.label))}n();function Wn(){let[n,r]=l(!1),i=t(null),[a,o]=l(0),s=e(e=>{i.current!==e&&(i.current=e,o(e=>e+1))},[]);return d(()=>{let e=i.current;if(!e||typeof IntersectionObserver>`u`){r(!1);return}let t=new IntersectionObserver(e=>{let t=e[e.length-1];t&&r(!t.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[a]),{ref:s,scrolledPast:n}}n();var Gn=[`events-feed`],Kn=60,qn=[{value:`importance`,label:`Importance`,icon:it},{value:`time`,label:`Recent`,icon:ye}];function Jn(){let e=c(),t=he(),n=le(),[i,o]=l($e),[f,p]=l(new Set),[m,h]=l(new Set),[g,_]=l(0),[v,b]=l(`time`),[x,S]=l(new Set),[C,w]=l(null),[T,E]=l(()=>Date.now());d(()=>{let e=setInterval(()=>E(Date.now()),6e4);return()=>clearInterval(e)},[]);let{since:O,until:k}=a(()=>gt({fromMs:i.fromMs,toMs:i.toMs},T),[i.fromMs,i.toMs,T]),A=Wn(),{pending:j,refreshNow:M}=Ln({paused:C!==null||x.size>0||A.scrolledPast}),{data:N=[]}=xe({isCamera:!0,projection:`slim`}),P=a(()=>N.map(e=>e.id),[N]),{data:ee,isLoading:te}=D({deviceIds:P},{enabled:P.length>0,staleTime:5*6e4}),ne=a(()=>Un(ee??[],f),[ee,f]),I=Xt(),re=I.isPending,{rows:L,isLoading:R}=Pn({deviceIds:P,since:O,until:k,minImportance:g>0?g:void 0,classFilter:m.size===1?[...m][0]:void 0}),ie=a(()=>{let e=new Map;for(let t of N??[])e.set(t.id,t.name);return e},[N]),z=e=>ie.get(e)??`Camera #${String(e)}`,B=a(()=>Ge(L).map(e=>({id:e,name:z(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[L,ie]),V=a(()=>ft(pt(L,{cameras:f,classes:m,minImportance:g}),v),[L,f,m,g,v]),H=Xe(V,Kn,a(()=>JSON.stringify([[...f].sort((e,t)=>e-t),[...m].sort(),g,v,O,k]),[f,m,g,v,O,k])),ae=()=>{e.invalidateQueries({queryKey:Gn})},oe=()=>S(new Set);function se(e){S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function ce(){if(x.size===0||!qt)return;let e=ht(L,x),t=[...e.values()].reduce((e,t)=>e+t.length,0);t!==0&&(async()=>{await n({title:`Delete ${String(t)} track${t===1?``:`s`}`,message:`Delete ${String(t)} track${t===1?``:`s`} and every image and clip captured for ${t===1?`it`:`them`}? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&U(e)})()}function U(e){let n=[...e];Promise.allSettled(n.map(([e,t])=>I.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{ae();let r=[],i=new Set;e.forEach((e,t)=>{let a=n[t];if(!a)return;let[o,s]=a;if(e.status===`fulfilled`)for(let e of s)i.add(mt(o,e));else r.push(o)}),S(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t}),r.length>0&&t({title:`Some tracks were not deleted`,message:`Failed to delete tracks on: ${r.map(e=>z(e)).join(`, `)}. They remain selected — retry, or check the server logs.`,variant:`danger`})})}let ue=V.length!==L.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(Qe,{onChange:o}),u(Je,{cameras:B,selected:f,onChange:p}),u(Rn,{groups:ne,selected:m,onChange:h,loading:te}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(`span`,{children:`Min score`}),u(`input`,{type:`range`,min:0,max:1,step:.05,value:g,onChange:e=>_(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":`Minimum importance`}),u(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(g*100)})]}),u(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:qn.map(e=>{let t=e.icon;return r(`button`,{type:`button`,onClick:()=>b(e.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${v===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[u(t,{className:`h-3.5 w-3.5`}),` `,e.label]},e.value)})}),!R&&u(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:ue?`${String(V.length)} of ${String(L.length)} events`:`${String(V.length)} event${V.length===1?``:`s`}`})]}),x.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[x.size,` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[u(`span`,{title:qt?void 0:`Track deletion arrives with the next server update`,children:r(G,{variant:`secondary`,onClick:ce,disabled:!qt||re,children:[re?u(K,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),u(G,{variant:`ghost`,onClick:oe,disabled:re,children:u(F,{className:`h-3.5 w-3.5`})})]})]}),R&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(K,{className:`h-4 w-4 animate-spin`}),` Loading events…`]}),!R&&V.length===0&&u(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:`No key events in this window.`}),j&&u(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:u(`button`,{type:`button`,onClick:M,className:`rounded-full border border-primary/40 bg-surface px-3 py-1 text-[11px] font-medium text-primary shadow-sm hover:bg-primary/10`,children:`New events — refresh`})}),!R&&V.length>0&&r(s,{children:[u(`div`,{ref:A.ref,"aria-hidden":!0,className:`h-0`}),u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:H.pageItems.map(e=>u(wt,{row:e,cameraName:z(e.deviceId),nowMs:T,selected:x.has(mt(e.deviceId,e.trackId)),onToggleSelect:se,onOpenDetail:w},mt(e.deviceId,e.trackId)))}),u(We,{currentPage:H.page,totalItems:H.totalItems,pageSize:H.pageSize,onPageChange:H.setPage,itemNoun:`events`})]}),C&&u(an,{row:C,cameraName:z(C.deviceId),deleteAvailable:qt,onClose:()=>w(null),onDeleted:()=>{ae(),w(null)},onFlagsChanged:e=>{w(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}n();var Yn=50,Xn=350,Zn=[{value:`loose`,label:`Loose`,title:`The search model's own floor`},{value:`balanced`,label:`Balanced`,title:`1.25× the search model's floor`},{value:`strict`,label:`Strict`,title:`1.5× the search model's floor`}];function Qn(e){let t=String(e.id);return{id:t,trackId:e.trackId??t,deviceId:e.deviceId,timestamp:e.timestamp,className:e.className,label:e.label,subLabel:e.subLabel,importance:e.importance??0,bestEventId:t,mediaId:e.keyFrameMediaId??e.mediaId,windowMs:void 0}}function $n({onActiveChange:e}){let[t,n]=l(``),[i,o]=l(`loose`),[s,c]=l(null),[f,p]=l(null),[m,h]=l(null),g=I(t,Xn).trim(),_=g.length>0;d(()=>{e(_)},[_,e]);let[v,y]=l(()=>Date.now());d(()=>{let e=setInterval(()=>y(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:b=[]}=xe({isCamera:!0,projection:`slim`}),x=a(()=>{let e=new Map;for(let t of b)e.set(t.id,t.name);return e},[b]),S=e=>x.get(e)??`Camera #${String(e)}`,C=a(()=>b.map(e=>e.id),[b]),{data:w}=D({deviceIds:C},{enabled:C.length>0,staleTime:5*6e4}),T=a(()=>Hn(w??[],new Set(f===null?[]:[f])),[w,f]);d(()=>{s!==null&&(T.some(e=>e.kind===s)||c(null))},[T,s]);let{data:E,isFetching:O,isError:k,error:A}=Te({text:g,strictness:i,limit:Yn,classFilter:s??void 0,deviceId:f??void 0},{enabled:_}),j=a(()=>[...E??[]].sort((e,t)=>t.score-e.score).map(e=>({...Qn(e),score:e.score})),[E]);function M(e){c(t=>t===e?null:e)}return r(`div`,{className:`space-y-3`,children:[r(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`div`,{className:`relative min-w-[16rem] flex-1`,children:[u(me,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),u(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Semantic search — describe what you're looking for…`,className:`h-9 w-full rounded-md border border-border bg-background pl-8 pr-8 text-sm text-foreground placeholder:text-foreground-subtle focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":`Semantic event search`}),t&&u(`button`,{type:`button`,onClick:()=>n(``),className:`absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Clear search`,children:u(F,{className:`h-3.5 w-3.5`})})]}),O&&_&&u(K,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[u(`div`,{className:`flex items-center gap-1`,children:T.map(e=>u(`button`,{type:`button`,onClick:()=>M(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${s===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:W(e)},e.kind))}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(`span`,{children:`Camera`}),r(`select`,{value:f===null?``:String(f),onChange:e=>p(e.target.value===``?null:Number(e.target.value)),className:`h-7 rounded-md border border-border bg-background px-1.5 text-xs text-foreground focus:border-primary focus:outline-none`,"aria-label":`Filter by camera`,children:[u(`option`,{value:``,children:`All`}),b.map(e=>u(`option`,{value:String(e.id),children:e.name},e.id))]})]}),r(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(`span`,{children:`Match`}),u(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Zn.map(e=>u(`button`,{type:`button`,onClick:()=>o(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${i===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:e.title,children:e.label},e.value))})]}),_&&!O&&!k&&r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[j.length,` match`,j.length===1?``:`es`]})]})]}),_&&r(`div`,{className:`space-y-3`,children:[k&&r(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,A instanceof Error?A.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!k&&O&&j.length===0&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(K,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!k&&!O&&j.length===0&&r(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:[`No semantic matches for “`,g,`”. Try a looser match threshold or a different phrasing.`]}),!k&&j.length>0&&u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:j.map(e=>u(wt,{row:e,cameraName:S(e.deviceId),nowMs:v,score:e.score,onOpenDetail:h},e.id))})]}),m&&u(an,{row:m,cameraName:S(m.deviceId),deleteAvailable:qt,onClose:()=>h(null),onDeleted:()=>h(null)})]})}n();function er(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return`just now`;if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function tr({row:e,cameraName:t,nowMs:n}){let i=Be(e.keyFrameMediaId===void 0?void 0:He(e.keyFrameMediaId));return r(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[r(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[i.src?u(`img`,{src:i.src,alt:`Parked ${e.className} on ${t}`,className:`h-full w-full object-cover`}):u(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:u(ct,{className:`h-6 w-6`})}),u(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium capitalize text-white`,children:e.label??e.className})]}),r(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[u(`span`,{className:`truncate text-[11px] text-foreground`,children:t}),r(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`parked `,er(n,e.becameStationaryAt)]})]})]})}function nr(){let[e,t]=l(!1),n=Date.now(),{data:i=[]}=xe({isCamera:!0,projection:`slim`}),o=a(()=>i.map(e=>e.id),[i]),s=a(()=>{let e=new Map;for(let t of i)e.set(t.id,t.name);return e},[i]),{rows:c,unreadableCount:d}=tt(o);return c.length===0&&d===0?null:r(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[r(`button`,{type:`button`,onClick:()=>t(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[u(e?m:v,{className:`h-4 w-4 text-foreground-subtle`}),u(ct,{className:`h-4 w-4 text-foreground-subtle`}),u(`span`,{className:`text-sm font-semibold text-foreground`,children:`Stationary`}),u(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:c.length}),u(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:`Parked objects — kept out of the event feed`}),d>0?r(`span`,{className:`ml-2 text-[11px] text-warning`,children:[d,` camera`,d===1?``:`s`,` could not be read`]}):null]}),e&&u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:c.map(e=>u(tr,{row:e,cameraName:s.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:n},e.id))})]})}n();function rr(){let[e,t]=l(!1);return u(ze,{children:r(`section`,{className:`space-y-3`,children:[u($n,{onActiveChange:t}),!e&&u(nr,{}),!e&&u(Jn,{})]})})}var ir=[`person`,`vehicle`,`animal`,`package`,`face`,`plate`],ar=new Set(ir);function or(e){let t=e?.trim().toLowerCase();return t===void 0||t===``?null:ar.has(t)?`"${t}" is a macro class, not a label — person / postman / Marco are three different tiers`:null}function sr({annotations:e,selectedIndex:t,onSelect:n,onChange:i,onDelete:a}){return e.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle p-3`,children:[`No subject on this frame yet. Drag on the image to draw one, or ask the pipeline for a proposal. Annotate `,u(`strong`,{children:`every`}),` subject — a frame with one box and three unlabelled people teaches the model that two thirds of the people in it are background.`]}):u(`ul`,{className:`divide-y divide-border`,children:e.map((e,o)=>{let s=o===t,c=or(e.label),l=or(e.subLabel);return r(`li`,{className:`p-2.5 space-y-1.5 ${s?`bg-surface-hover`:``}`,onFocus:()=>{n(o)},children:[r(`div`,{className:`flex items-center gap-2`,children:[u(U,{className:`w-28`,value:e.macroClass,options:ir.map(e=>({value:e,label:e})),onChange:e=>{let t=ir.find(t=>t===e.target.value);t!==void 0&&i(o,{macroClass:t})}}),u(U,{className:`w-32`,value:e.kind,options:[{value:`subject`,label:`subject`},{value:`model_error`,label:`model error`}],onChange:e=>{i(o,{kind:e.target.value===`model_error`?`model_error`:`subject`})}}),e.source===`assist`&&r(S,{variant:`info`,children:[e.assistModelId??`assist`,e.assistScore===void 0?``:` ${e.assistScore.toFixed(2)}`]}),u(G,{variant:`ghost`,size:`sm`,"aria-label":`Delete this subject`,onClick:()=>{a(o)},children:u(y,{className:`h-3 w-3`})})]}),r(`div`,{className:`flex items-center gap-2`,children:[u(w,{className:`flex-1`,placeholder:`label (postman, van, cat…)`,value:e.label??``,onChange:e=>{i(o,{label:e.target.value})}}),u(w,{className:`flex-1`,placeholder:`sub-label (a name, a plate…)`,value:e.subLabel??``,onChange:e=>{i(o,{subLabel:e.target.value})}})]}),c!==null&&u(`p`,{className:`text-[11px] text-danger`,children:c}),l!==null&&u(`p`,{className:`text-[11px] text-danger`,children:l})]},`${String(o)}-${String(e.bbox.x)}`)})})}function cr(e){return e.every(e=>or(e.label)===null&&or(e.subLabel)===null&&ar.has(e.macroClass))}function lr(e){return e<0?0:e>1?1:e}function ur(e,t,n,r){if(!(e>0)||!(t>0)||!(n>0)||!(r>0))return null;let i=Math.min(e/n,t/r),a=n*i,o=r*i;return{left:(e-a)/2,top:(t-o)/2,width:a,height:o}}function dr(e,t,n){return{x:lr((e-n.left)/n.width),y:lr((t-n.top)/n.height)}}function fr(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),w:Math.abs(t.x-e.x),h:Math.abs(t.y-e.y)}}function pr(e){return e.w>=.01&&e.h>=.01}function mr(e,t){return{left:t.left+e.x*t.width,top:t.top+e.y*t.height,width:e.w*t.width,height:e.h*t.height}}function hr(e,t){let n=-1,r=1/0;return e.forEach((e,i)=>{if(!(t.x>=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h))return;let a=e.w*e.h;a<r&&(n=i,r=a)}),n}n();function gr({imageSrc:n,imageWidth:a,imageHeight:o,boxes:s,selectedIndex:c,onSelect:d,onDraw:f}){let p=t(null),[m,h]=l({w:0,h:0}),[g,_]=l(null);i(()=>{let e=p.current;if(e===null)return;let t=new ResizeObserver(()=>{h({w:e.clientWidth,h:e.clientHeight})});return t.observe(e),h({w:e.clientWidth,h:e.clientHeight}),()=>{t.disconnect()}},[]);let v=ur(m.w,m.h,a,o),y=e(e=>{let t=p.current;if(t===null||v===null)return null;let n=t.getBoundingClientRect();return dr(e.clientX-n.left,e.clientY-n.top,v)},[v]);return r(`div`,{ref:p,className:`relative w-full h-full min-h-[280px] bg-surface-sunken select-none touch-none`,onPointerDown:e=>{let t=y(e);t!==null&&(e.currentTarget.setPointerCapture(e.pointerId),_({start:t,current:fr(t,t)}))},onPointerMove:e=>{if(g===null)return;let t=y(e);t!==null&&_({start:g.start,current:fr(g.start,t)})},onPointerUp:()=>{if(g===null)return;let e=g.current;_(null),pr(e)?f(e):d(hr(s.map(e=>e.bbox),g.start))},children:[u(`img`,{src:n,alt:`Frame being annotated`,className:`absolute inset-0 w-full h-full object-contain pointer-events-none`}),v!==null&&s.map((e,t)=>{let n=mr(e.bbox,v),i=e.kind===`model_error`,a=t===c,o=i?`#ef4444`:a?`#22c55e`:`#3b82f6`;return u(`div`,{className:`absolute pointer-events-none`,style:{left:n.left,top:n.top,width:n.width,height:n.height,border:`${a?`2px`:`1px`} ${i?`dashed`:`solid`} ${o}`,opacity:e.source===`assist`&&!a?.65:1},children:r(`span`,{className:`absolute -top-4 left-0 text-[10px] px-1 rounded`,style:{background:o,color:`#08121f`},children:[e.label??e.macroClass,i?` ✕`:``]})},`${String(t)}-${String(e.bbox.x)}-${String(e.bbox.y)}`)}),g!==null&&v!==null&&u(`div`,{className:`absolute border border-dashed border-primary pointer-events-none`,style:mr(g.current,v)})]})}n();function _r(){let e=R({}),t=C({}),n=H({}),[i,a]=l(null),[o,s]=l(null),c=async(e,t,n)=>{a(e),s(null);try{await Ue(p(t),n)}catch(e){s(e instanceof Error?e.message:String(e))}finally{a(null)}},d=e.data,f=d!==void 0&&d.trackCount===0;return r(`div`,{className:`rounded-md border border-border bg-surface p-3 space-y-2`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground flex-1`,children:`Export dataset`}),r(G,{variant:`secondary`,size:`sm`,disabled:t.data===void 0||i!==null,onClick:()=>{t.data!==void 0&&c(`annotated`,t.data.url,`camstack-retrain-export.tar`)},children:[i===`annotated`?u(K,{className:`h-3 w-3 animate-spin`}):u(Se,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Annotated dataset`})]}),r(G,{variant:`secondary`,size:`sm`,disabled:n.data===void 0||f||i!==null,onClick:()=>{n.data!==void 0&&c(`marked`,n.data.url,`camstack-training-export.tar`)},children:[i===`marked`?u(K,{className:`h-3 w-3 animate-spin`}):u(Se,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Marked media`})]})]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.isError?`The export summary could not be read, so the size of the marked set is unknown — not zero.`:d===void 0?`Measuring the marked set…`:f?`No track is marked for training: the marked-media archive would be empty. The annotated dataset can still hold frames from tracks already completed — this count does not measure those.`:`${String(d.trackCount)} marked track${d.trackCount===1?``:`s`} · ${String(d.fileCount)} file${d.fileCount===1?``:`s`} · ${rt(d.byteCount)}${d.truncated?` · more marked tracks exist than one pass carries`:``}`}),(t.isError||n.isError)&&u(`p`,{className:`text-[11px] text-danger`,children:`An export data plane is not available on the node that answered — no archive can be streamed from here.`}),o!==null&&r(`p`,{className:`text-[11px] text-danger`,children:[`Download failed: `,o]})]})}function vr(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.round(e/1e3)} KB`}function yr({candidates:e,copies:t,activeFrameId:n,refusals:i,isSelecting:a,onSelectCandidate:o,onOpenCopy:s,onRemoveCopy:c}){let l=new Set(t.map(e=>e.sourceMediaId)),d=e.filter(e=>!l.has(e.mediaId));return r(`div`,{className:`space-y-3`,children:[r(`section`,{children:[r(`h3`,{className:`text-xs font-semibold text-foreground mb-1.5`,children:[`In the dataset (`,t.length,`)`]}),t.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No frame copied yet. Selecting a frame copies it into retrain storage immediately — the dataset stops depending on the track's own media from that moment.`}):u(`ul`,{className:`flex flex-wrap gap-2`,children:t.map(e=>u(`li`,{children:r(`div`,{className:`rounded-md border px-2 py-1.5 text-[11px] ${e.frameId===n?`border-primary bg-surface-hover`:`border-border`}`,children:[r(`button`,{type:`button`,className:`flex items-center gap-1.5 text-left`,onClick:()=>{s(e.frameId)},children:[u(Ae,{className:`h-3 w-3 text-success`}),u(`span`,{className:`font-medium text-foreground`,children:e.sourceKind}),r(`span`,{className:`text-foreground-subtle`,children:[e.width,`×`,e.height,` · `,vr(e.sizeBytes)]})]}),r(`button`,{type:`button`,"aria-label":`Remove this frame from the dataset`,className:`mt-1 flex items-center gap-1 text-foreground-muted hover:text-danger`,onClick:()=>{c(e.frameId)},children:[u(y,{className:`h-3 w-3`}),`remove`]})]})},e.frameId))})]}),r(`section`,{children:[r(`h3`,{className:`text-xs font-semibold text-foreground mb-1.5`,children:[`Available frames (`,d.length,`)`]}),d.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.length===0?`This track has no whole, unannotated frame left — its media aged out before it was marked. Anything already copied above is still usable.`:`Every available frame is already in the dataset.`}):u(`ul`,{className:`flex flex-wrap gap-2`,children:d.map(e=>{let t=i.get(e.mediaId);return r(`li`,{children:[r(G,{variant:`secondary`,size:`sm`,disabled:a||t!==void 0,onClick:()=>{o(e.mediaId)},children:[a?u(K,{className:`h-3 w-3 animate-spin`}):u(t===void 0?de:_,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:e.kind}),u(`span`,{className:`ml-1 text-foreground-subtle`,children:vr(e.sizeBytes)})]}),t!==void 0&&u(S,{variant:`danger`,className:`ml-1`,children:t})]},e.mediaId)})})]})]})}function br(e){return e.frameCount===0?`untouched`:e.annotationCount===0?`started`:`ready`}var xr={untouched:{icon:ot,label:`to do`,variant:`default`},started:{icon:at,label:`frames only`,variant:`info`},ready:{icon:Pe,label:`annotated`,variant:`success`}};function Sr(e){return new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}function Cr({tracks:e,isLoading:t,selectedTrackId:n,deviceNames:i,onSelect:a}){return t?r(`div`,{className:`flex items-center gap-2 p-4 text-xs text-foreground-subtle`,children:[u(K,{className:`h-3.5 w-3.5 animate-spin`}),`Loading staging tracks…`]}):e.length===0?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`Nothing in staging. Mark a track for training from the viewer or the Events grid and it appears here.`}):u(`ul`,{className:`divide-y divide-border`,children:e.map(e=>{let t=xr[br(e)],o=t.icon;return u(`li`,{children:r(`button`,{type:`button`,onClick:()=>{a(e)},className:`w-full text-left px-3 py-2 flex items-start gap-2 hover:bg-surface-hover ${e.trackId===n?`bg-surface-hover`:``}`,children:[u(o,{className:`h-3.5 w-3.5 mt-0.5 shrink-0 text-foreground-subtle`}),r(`span`,{className:`min-w-0 flex-1`,children:[r(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-xs font-medium text-foreground truncate`,children:e.label??e.className}),u(S,{variant:t.variant,children:t.label})]}),r(`span`,{className:`block text-[11px] text-foreground-subtle truncate`,children:[i.get(e.deviceId)??`Camera ${String(e.deviceId)}`,` ·`,` `,Sr(e.lastSeen)]}),r(`span`,{className:`block text-[11px] text-foreground-muted`,children:[e.frameCount,` frame`,e.frameCount===1?``:`s`,` ·`,` `,e.annotationCount,` subject`,e.annotationCount===1?``:`s`]})]})]})},e.trackId)})})}var wr=`object-detection`;function Tr(e,t){for(let n of e){if(n.addonId===t)return n;let e=n.children===void 0?void 0:Tr(n.children,t);if(e!==void 0)return e}}function Er(e,t){for(let n of e.slots){let e=n.addons.find(e=>e.id===t);if(e!==void 0)return e}}function Dr(e){let{status:t,nodeDevices:n,schema:r,resolvedSteps:i}=e;if(t===void 0)return{kind:`unknown`,gap:`pending`};if(t.detection===null)return{kind:`unknown`,gap:t.degraded.some(e=>e.stage===`detection`)?`placement-unreadable`:`detection-off`};let a=t.detection;if(n===void 0||r===void 0||i===void 0)return{kind:`unknown`,gap:`pending`};if(!n.reachable)return{kind:`unknown`,gap:`node-unreachable`};let o=n.devices.find(e=>e.backend===a.engine.backend&&e.device===a.engine.device);if(o===void 0)return{kind:`unknown`,gap:`device-unknown`};let s=Er(r,wr);if(s===void 0)return{kind:`unknown`,gap:`step-unknown`};let c=z({catalog:s,device:o,override:Tr(i,wr)?.modelId,base:o.steps?.[wr]?.modelId});return c===void 0?{kind:`unknown`,gap:`no-model`}:{kind:`resolved`,nodeId:a.nodeId,modelId:c,minScore:s.models.find(e=>e.id===c)?.defaultConfidence??s.defaultConfidence}}n();var Or=`person`,kr={pending:`Reading which detector this camera runs…`,"placement-unreadable":`The detection stage of this camera could not be read, so the model it runs is unknown — not absent.`,"detection-off":`This camera runs no object detector, so there is no proposal to mirror.`,"node-unreachable":`The node that detects for this camera did not answer about its accelerators.`,"device-unknown":`The node does not list the accelerator this camera detects on — asking another one would propose with a different model.`,"step-unknown":`That node carries no object-detection step in its catalog.`,"no-model":`No object-detection model on that accelerator can be resolved for this camera.`};function Ar(){let[t,n]=l(null),[i,o]=l(null),[c,f]=l([]),[p,m]=l(-1),[h,g]=l(new Map),[_,v]=l(null),y=xe({projection:`slim`,isCamera:!0}),b=a(()=>{let e=new Map;for(let t of y.data??[])e.set(t.id,t.name);return e},[y.data]),x=ae({}),C=oe({trackId:t?.trackId??``},{enabled:t!==null}),w=A({trackId:t?.trackId??``},{enabled:t!==null}),T=B({frameId:i??``},{enabled:i!==null}),D=be(),O=re(),k=te(),j=pe(),M=E(),N=ve({deviceIds:t===null?[]:[t.deviceId]},{enabled:t!==null,staleTime:3e4}),P=N.data?.[0]?.detection?.nodeId??null,F=Oe({nodeId:P??``},{enabled:P!==null,staleTime:3e4}),I=ge({nodeId:P??``},{enabled:P!==null,staleTime:3e4}),L=ee({deviceId:t?.deviceId??0},{enabled:t!==null,staleTime:3e4}),R=a(()=>Dr({status:N.data?.[0],nodeDevices:F.data,schema:I.data,resolvedSteps:L.data?.steps}),[N.data,F.data,I.data,L.data]);d(()=>{if(i===null){f([]);return}f((w.data??[]).filter(e=>e.mediaKey===i).map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},...e.subLabel===void 0?{}:{subLabel:e.subLabel},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}))),m(-1)},[i,w.data]),d(()=>{let e=C.data?.copies??[];i===null&&e.length>0&&o(e[0].frameId)},[C.data,i]);let ie=e(e=>{n(e),o(null),f([]),g(new Map),v(null)},[]),z=e(async e=>{if(t===null)return;let n=await D.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,mediaIds:[e]});if(n.refused.length>0){let e=new Map(h);for(let t of n.refused)e.set(t.sourceMediaId,t.reason);g(e)}n.copied.length>0&&o(n.copied[0].frameId),await C.refetch(),await x.refetch()},[t,D,h,C,x]),V=e(async e=>{t!==null&&(await O.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,frameId:e}),i===e&&o(null),await C.refetch(),await w.refetch(),await x.refetch())},[t,O,i,C,w,x]),H=e(async e=>{if(t===null||i===null)return;if(v(null),R.kind!==`resolved`){v(kr[R.gap]);return}let n=await k.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,frameId:i,subject:e===`package`?{kind:`package`}:{kind:`objects`,modelId:R.modelId,minScore:R.minScore},nodeId:R.nodeId});if(n.kind===`refused`){v(n.reason===`no-zone`?`A package proposal runs on the zone crop only — this camera has no zone, and running the detector on the whole frame at 0.35 proposes furniture.`:`The pipeline refused: ${n.reason}${n.detail===void 0?``:` — ${n.detail}`}`);return}f(e=>[...e,...n.proposals.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}))]),v(`${n.proposals.length} proposal${n.proposals.length===1?``:`s`} from ${n.modelId}`+(n.belowThreshold>0?` — ${n.belowThreshold} more were below ${n.minScore.toFixed(2)}`:``))},[t,i,k,R]),se=e(e=>{f(t=>[...t,{bbox:e,macroClass:Or,kind:`subject`,source:`operator`}]),m(c.length)},[c.length]),ce=e((e,t)=>{f(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),le=e(e=>{f(t=>t.filter((t,n)=>n!==e)),m(-1)},[]),U=e(async()=>{t===null||i===null||(await j.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,frameId:i,annotations:c.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label!==void 0&&e.label!==``?{label:e.label}:{},...e.subLabel!==void 0&&e.subLabel!==``?{subLabel:e.subLabel}:{},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}))}),await w.refetch(),await x.refetch(),v(`Annotations saved.`))},[t,i,c,j,w,x]),ue=e(async()=>{if(t===null)return;let e=await M.mutateAsync({deviceId:t.deviceId,trackId:t.trackId});v(e.changed?`Track completed — it is now trained, and its own media is evictable again.`:e.reason===`no-frames-copied`?`Refused: no frame was ever copied into the dataset. Completing would let retention delete material nothing was extracted from.`:`Refused: ${e.reason??`unknown`}`),await x.refetch(),e.changed&&n(null)},[t,M,x]),W=T.data,de=cr(c)&&i!==null;return r(ze,{subtitle:`Turn the tracks you marked for training into an annotated dataset. Selecting a frame copies it — the dataset never depends on media that can be swept.`,actions:t===null?null:r(G,{size:`sm`,onClick:()=>void ue(),children:[u(st,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Complete track`})]}),children:[_!==null&&u(`div`,{className:`rounded-md border border-border bg-surface px-3 py-2 text-xs text-foreground`,children:_}),u(_r,{}),r(`div`,{className:`grid grid-cols-1 lg:grid-cols-[minmax(0,260px)_minmax(0,1fr)] gap-4`,children:[r(`aside`,{className:`rounded-md border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`px-3 py-2 border-b border-border flex items-center justify-between`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground`,children:`Staging`}),u(S,{children:x.data?.length??0})]}),u(Cr,{tracks:x.data??[],isLoading:x.isLoading,selectedTrackId:t?.trackId??null,deviceNames:b,onSelect:ie})]}),u(`section`,{className:`space-y-3 min-w-0`,children:t===null?u(`p`,{className:`text-xs text-foreground-subtle`,children:`Pick a track from the staging list to start annotating it.`}):r(s,{children:[u(`div`,{className:`rounded-md border border-border bg-surface p-3`,children:u(yr,{candidates:C.data?.candidates??[],copies:C.data?.copies??[],activeFrameId:i,refusals:h,isSelecting:D.isPending,onSelectCandidate:e=>void z(e),onOpenCopy:o,onRemoveCopy:e=>void V(e)})}),i!==null&&r(`div`,{className:`grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(0,380px)] gap-3`,children:[u(`div`,{className:`rounded-md border border-border overflow-hidden`,children:W===void 0?r(`div`,{className:`flex items-center gap-2 p-6 text-xs text-foreground-subtle`,children:[u(K,{className:`h-3.5 w-3.5 animate-spin`}),`Loading the frame…`]}):u(gr,{imageSrc:`data:image/jpeg;base64,${W.base64}`,imageWidth:W.width,imageHeight:W.height,boxes:c,selectedIndex:p,onSelect:m,onDraw:se})}),r(`div`,{className:`rounded-md border border-border bg-surface flex flex-col min-h-0`,children:[r(`div`,{className:`px-3 py-2 border-b border-border flex items-center gap-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground flex-1`,children:`Subjects`}),r(G,{variant:`secondary`,size:`sm`,disabled:k.isPending||R.kind!==`resolved`,onClick:()=>void H(`objects`),children:[u(ne,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Propose`})]}),r(G,{variant:`secondary`,size:`sm`,disabled:k.isPending||R.kind!==`resolved`,onClick:()=>void H(`package`),children:[u(ne,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Packages`})]})]}),u(`div`,{className:`px-3 py-1 border-b border-border text-[11px] text-foreground-subtle`,children:R.kind===`resolved`?`Proposals come from ${R.modelId} at ${R.minScore.toFixed(2)}, on ${R.nodeId} — what this camera really runs.`:kr[R.gap]}),u(`div`,{className:`flex-1 overflow-y-auto`,children:u(sr,{annotations:c,selectedIndex:p,onSelect:m,onChange:ce,onDelete:le})}),r(`div`,{className:`px-3 py-2 border-t border-border flex items-center justify-between`,children:[r(`span`,{className:`text-[11px] text-foreground-subtle`,children:[c.filter(e=>e.kind===`model_error`).length,` marked as model errors`]}),u(G,{size:`sm`,disabled:!de||j.isPending,onClick:()=>void U(),children:`Save frame`})]})]})]})]})})]})]})}function jr(){return u(`div`,{className:`flex flex-col p-4`,children:u(nt,{tabs:[{id:`feed`,label:`Feed`,icon:O,content:u(rr,{})},{id:`retrain`,label:`Retrain`,icon:st,content:u(Ar,{})},{id:`debug`,label:`Debug`,icon:T,content:u(An,{})}]})})}export{jr as EventsPage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,a as r,b as i,o as a,q as o,x as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{_t as c,at as l,gt as u,st as d,yt as f}from"./player-overlays-ktPblw8g.js";import{C as p,Dl as m,Hl as h,Hn as g,Oc as _,Rc as v,S as y,Tl as b,Ul as x,Un as S,Wl as C,_c as ee,_n as w,ac as te,bu as T,cc as E,cl as D,dc as O,fc as ne,gc as k,hc as A,ic as j,lc as M,m as N,mc as P,nu as F,oc as re,oi as I,on as ie,p as L,pc as ae,sc as R,sl as z,tl as B,uc as V,ut as oe,uu as se,vc as ce,vn as le,wu as ue,zl as H}from"./src-CExJu3gi.js";import{c as de,d as fe,l as pe,u as U}from"./src-DCJABiaG.js";import{p as W,r as G}from"./index-qsRpCvR5.js";import{t as K}from"./AdminPage-CiKtOLQm.js";import{t as me}from"./AdminTabs-CsuISePK.js";import{t as he}from"./AddonCollectionPage-C7ayIMM9.js";import{t as ge}from"./addon-display-names-DvSEQty-.js";var _e=f(`book-open`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z`,key:`ruj8y`}]]),ve=f(`key-square`,[[`path`,{d:`M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z`,key:`165ttr`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814`,key:`1ubxi2`}]]),ye=f(`link`,[[`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`,key:`1cjeqo`}],[`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`,key:`19qd67`}]]);e();function be({userId:e,username:n,onClose:r}){let o=a(),c=w(),l=E({userId:e}),u=l.data,d=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=R({onSuccess:()=>{d(),r()}}),p=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return s(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4`,children:t(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl overflow-hidden`,children:[t(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-border`,children:[t(`div`,{className:`flex items-center gap-2`,children:[s(B,{className:`h-4 w-4 text-primary`}),t(`div`,{children:[s(`div`,{className:`text-sm font-medium text-foreground`,children:`Two-factor authentication`}),t(`div`,{className:`text-[11px] text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]}),s(`button`,{onClick:r,className:`p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle`,children:s(_,{className:`h-4 w-4`})})]}),t(`div`,{className:`p-4 space-y-4`,children:[p===`loading`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(H,{className:`h-3.5 w-3.5 animate-spin`}),`Checking status…`]}),p===`not_enrolled`&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/30 px-3 py-2.5 flex items-start gap-2.5 text-xs text-foreground-subtle`,children:[s(C,{className:`h-4 w-4 mt-0.5 shrink-0`}),t(`div`,{children:[s(`div`,{className:`font-medium text-foreground`,children:`2FA not enrolled`}),s(`p`,{className:`mt-0.5`,children:`Only the user themselves can enable 2FA, from their own profile page.`})]})]}),p===`enrolled`&&u&&t(i,{children:[t(`div`,{className:`rounded-md border border-emerald-500/30 bg-emerald-500/5 px-3 py-2.5 flex items-start gap-2.5`,children:[s(T,{className:`h-4 w-4 mt-0.5 text-emerald-500 shrink-0`}),t(`div`,{className:`text-xs text-foreground space-y-0.5`,children:[s(`div`,{className:`font-medium`,children:`2FA is active`}),t(`div`,{className:`text-foreground-subtle`,children:[`Enrolled on`,` `,u.confirmedAt?new Date(u.confirmedAt).toLocaleString():`—`]})]})]}),s(`div`,{className:`text-[11px] text-foreground-subtle`,children:`Removing here clears the server-side secret. Use this only when the user has lost access — they'll have to re-enroll from their profile page afterwards.`}),t(`div`,{className:`flex justify-end gap-2`,children:[s(ie,{onClick:r,variant:`secondary`,children:`Close`}),t(`button`,{onClick:async()=>{await c({title:`Remove 2FA`,message:`Remove two-factor authentication for "${n}"? They'll be able to log in with just their password until they re-enroll from their own profile page.`,confirmLabel:`Remove`,variant:`danger`})&&f.mutate({userId:e})},disabled:f.isPending,className:`rounded bg-danger px-3 py-1.5 text-xs font-medium text-white hover:bg-danger/90 disabled:opacity-50 inline-flex items-center gap-1`,children:[f.isPending?s(H,{className:`h-3 w-3 animate-spin`}):s(_,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}function q({icon:e,label:n,count:r,all:i,total:a}){return t(`div`,{className:`flex items-center gap-2 text-[11px]`,children:[s(e,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(`span`,{className:`min-w-0 flex-1 text-foreground-subtle`,children:n}),s(`span`,{className:r===0?`text-foreground-subtle`:`font-medium text-foreground`,children:r===0?`none`:i?`all ${a}`:`${r} of ${a}`})]})}function xe({scopes:e,isAdmin:n,invalidReason:a}){let o=l(),c=r({queryKey:[`auth`,`previewScope`,e,n],enabled:a===null,queryFn:()=>o.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:n})}),{data:u}=I({projection:`slim`}),f=u?.length??0;if(a!==null)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:t(`p`,{className:`flex items-center gap-1.5 text-[11px] text-warning`,children:[s(D,{className:`h-3 w-3 shrink-0`}),a]})});if(c.isLoading)return t(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface p-3 text-[11px] text-foreground-subtle`,children:[s(H,{className:`h-3 w-3 animate-spin`}),`Resolving…`]});if(c.isError||!c.data)return s(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:s(`p`,{className:`text-[11px] text-danger`,children:`Could not resolve this grant set. Saving is still allowed — the server enforces the same rules either way.`})});let p=c.data;return s(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:p.isAdmin?t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`Administrator`}),` — unrestricted. Grants are ignored for an admin.`]}):t(i,{children:[s(q,{icon:F,label:`Devices they can see`,count:p.device.view.deviceCount,all:p.device.view.all,total:f}),s(q,{icon:m,label:`Devices they can operate`,count:p.device.create.deviceCount,all:p.device.create.all,total:f}),s(q,{icon:d,label:`Devices they can delete`,count:p.device.delete.deviceCount,all:p.device.delete.all,total:f}),t(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[`System access: `,p.system.length===0?`none`:p.system.join(`, `),p.capabilities.length>0&&t(i,{children:[` · Extra capabilities: `,p.capabilities.map(e=>e.name).join(`, `)]}),p.addons.length>0&&t(i,{children:[` · Addons: `,p.addons.map(e=>e.name).join(`, `)]})]}),p.device.view.deviceCount===0&&s(`p`,{className:`text-[10px] text-warning`,children:`This user will not be able to see any device.`})]})})}function Se(e){let t=U(e);return t===null?{mode:e.length===0?`role`:`advanced`,roleId:null,selector:{kind:`all`},includeLinked:!0,advancedScopes:e}:{mode:`role`,roleId:t.roleId,selector:t.selector,includeLinked:t.includeLinked,advancedScopes:e}}function Ce(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:pe({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function we({user:e,onClose:r,onSubmit:a,submitting:l,callerScopes:d}){let f=n(()=>Se(e.scopes??[]),[e.scopes]),[p,m]=o(f),[h,g]=o(f.mode===`advanced`),v=n(()=>Ce(p),[p]),b=!e.isAdmin&&p.mode===`role`&&p.roleId===null,x=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?`Pick what this user can do to see the result.`:N(v),[e.isAdmin,p.mode,p.roleId,v]),S=e=>m({...p,...e});return s(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 pt-[calc(1rem+env(safe-area-inset-top))] pb-[calc(1rem+env(safe-area-inset-bottom))]`,children:t(`div`,{className:`flex max-h-full w-full max-w-2xl flex-col rounded-lg border border-border bg-surface shadow-xl`,children:[t(`div`,{className:`flex shrink-0 items-start justify-between border-b border-border px-4 py-3`,children:[t(`div`,{className:`min-w-0`,children:[t(`div`,{className:`text-sm font-semibold text-foreground`,children:[`Access — `,e.username]}),s(`div`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?`This user is an administrator — they can do everything, and the settings below are ignored.`:`Choose what they can do, then which devices it applies to.`})]}),s(`button`,{onClick:r,className:`shrink-0 text-foreground-subtle hover:text-foreground`,title:`Close`,children:s(_,{className:`h-4 w-4`})})]}),t(`div`,{className:`min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4`,children:[b&&t(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[s(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),t(`p`,{className:`text-[11px] text-foreground`,children:[s(`span`,{className:`font-medium`,children:`No access.`}),` `,t(`span`,{className:`text-foreground-subtle`,children:[e.username,` cannot see or do anything yet. Configure it below.`]})]})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`1 · What can they do`}),s(`div`,{className:`space-y-1.5`,children:de.map(e=>{let n=p.mode===`role`&&p.roleId===e.id;return t(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[s(`input`,{type:`radio`,name:`access-role`,checked:n,onChange:()=>S({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),t(`span`,{className:`min-w-0`,children:[s(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),s(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),t(`button`,{type:`button`,onClick:()=>{if(!h){m({...p,mode:`advanced`,advancedScopes:v}),g(!0);return}g(!1),m(Se(p.advancedScopes))},className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-foreground-subtle transition-colors hover:bg-foreground-subtle/10 hover:text-foreground`,children:[s(h?c:u,{className:`h-3 w-3`}),`Advanced — edit raw grants`]}),h&&t(`div`,{className:`rounded-lg border border-border p-2`,children:[s(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`One row per grant. Anything expressible here overrides the three roles above; close this section to go back to them.`}),s(L,{value:p.advancedScopes,onChange:e=>S({mode:`advanced`,advancedScopes:e}),clampToParent:d,emptyHint:t(i,{children:[`No grants.`,` `,s(`span`,{className:`font-medium text-foreground`,children:e.username}),` cannot call any protected endpoint until one is added.`]})})]})]}),p.mode===`role`&&t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`2 · On which devices`}),s(y,{value:p.selector,onChange:e=>S({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>S({includeLinked:e}),clampToDeviceIds:null})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p.mode===`role`?`3 · Result`:`2 · Result`}),s(xe,{scopes:v,isAdmin:e.isAdmin,invalidReason:x})]})]}),t(`div`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3`,children:[s(`button`,{onClick:r,className:`rounded border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground`,children:`Cancel`}),s(`button`,{onClick:()=>a([...v]),disabled:l||x!==null,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:l?s(H,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}e();var Te=8;function Ee(){let e=a(),{user:n}=G(),[r,i]=o(!1),[c,l]=o(``),[u,f]=o(``),[p,m]=o(!1),[g,v]=o(null),{data:y,isLoading:x,isError:S}=ne(),C=w(),T=le(),E=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),D=te({onSuccess:()=>{E(),i(!1),l(``),f(``),m(!1),v(null)},onError:e=>{v(e instanceof Error?e.message:`Failed to create user`)}}),O=re({onSuccess:E}),k=ce({onSuccess:E}),A=ae({onSuccess:E}),j=ee({onSuccess:()=>{E(),N(null)}}),[M,N]=o(null),[P,F]=o(null),I=y??[];async function ie(e){await C({title:`Delete user`,message:`Permanently delete user "${e.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:`Delete`,variant:`danger`})&&O.mutate({id:e.id})}async function L(e){let t=await T({title:`Reset password`,message:`Set a new password for "${e.username}".`,label:`New password`,inputType:`password`,placeholder:`At least 8 characters`,confirmLabel:`Continue`,validate:e=>e.length<Te?`Password must be at least ${String(Te)} characters.`:null});t===null||t.length===0||await C({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&A.mutate({id:e.id,newPassword:t})}function R(e,t){t!==e.isAdmin&&k.mutate({id:e.id,isAdmin:t})}function V(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}return t(K,{children:[s(`div`,{className:`flex items-center justify-end`,children:t(`button`,{onClick:()=>i(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm hover:bg-primary/90`,children:[s(b,{className:`h-3.5 w-3.5`}),`Create User`]})}),r&&t(`div`,{className:`rounded-lg border border-border bg-surface p-4 space-y-3`,children:[t(`div`,{className:`flex items-center justify-between`,children:[s(`span`,{className:`text-xs font-medium text-foreground`,children:`New User`}),s(`button`,{onClick:()=>i(!1),className:`text-foreground-subtle hover:text-foreground`,children:s(_,{className:`h-4 w-4`})})]}),t(`div`,{className:`grid grid-cols-3 gap-3`,children:[t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Username`}),s(`input`,{type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`john`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Password`}),s(`input`,{type:`password`,value:u,onChange:e=>f(e.target.value),placeholder:`••••••••`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Admin`}),t(`label`,{className:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked),className:`rounded border-border focus:ring-primary`}),s(`span`,{className:`text-foreground-subtle`,children:`Unrestricted access`})]})]})]}),g&&s(`p`,{className:`text-[10px] text-danger`,children:g}),t(`div`,{className:`flex justify-end gap-2`,children:[s(`button`,{onClick:()=>i(!1),className:`rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground`,children:`Cancel`}),s(`button`,{onClick:()=>D.mutate({username:c,password:u,isAdmin:p}),disabled:D.isPending||!c||!u,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:D.isPending?`Creating...`:`Create`})]})]}),x&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading...`}),S&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load`}),!x&&!S&&I.length===0&&s(`div`,{className:`text-xs text-foreground-subtle`,children:`No data`}),(()=>{let e=e=>O.isPending&&O.variables?.id===e.id||k.isPending&&k.variables?.id===e.id||A.isPending&&A.variables?.id===e.id;return s(oe,{columns:[{key:`username`,header:`Username`,render:e=>e.username},{key:`isAdmin`,header:`Admin`,render:n=>t(`label`,{className:`inline-flex items-center gap-1.5 text-xs cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:n.isAdmin,onChange:e=>R(n,e.target.checked),disabled:e(n),className:`rounded border-border focus:ring-primary disabled:opacity-50`}),s(`span`,{className:n.isAdmin?`text-primary font-medium`:`text-foreground-subtle`,children:n.isAdmin?`Admin`:`Regular`})]})},{key:`scopes`,header:`Access`,render:e=>e.isAdmin?s(`span`,{className:`text-[10px] italic text-foreground-subtle`,children:`everything (admin)`}):t(`button`,{onClick:()=>N(e),className:`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] hover:bg-foreground-subtle/10`,title:`Configure access`,children:[s(z,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(De,{scopes:e.scopes??[]})]})},{key:`createdAt`,header:`Created`,render:e=>s(`span`,{className:`text-foreground-subtle`,children:V(e.createdAt)})},{key:`actions`,header:`Actions`,align:`right`,render:r=>{let i=e(r);return t(`div`,{className:`flex items-center justify-end gap-1`,children:[r.id!==n?.id&&r.totpEnabled&&t(`button`,{onClick:()=>F(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Remove two-factor authentication`,children:[s(B,{className:`h-3 w-3`}),`Remove 2FA`]}),t(`button`,{onClick:()=>L(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Reset password`,children:[s(h,{className:`h-3 w-3`}),`Reset password`]}),t(`button`,{onClick:()=>ie(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Delete user`,children:[i?s(H,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:I,rowKey:e=>e.id,minWidthPx:560})})(),P&&s(be,{userId:P.id,username:P.username,onClose:()=>F(null)}),M&&s(Oe,{user:M,onClose:()=>N(null),onSubmit:e=>j.mutate({userId:M.id,scopes:e}),submitting:j.isPending})]})}function De({scopes:e}){if(e.length===0)return s(`span`,{className:`font-medium text-warning`,children:`No access`});let n=U(e);return n===null?t(`span`,{className:`text-foreground-subtle`,children:[`Custom · `,e.length,` grant`,e.length===1?``:`s`]}):t(`span`,{className:`text-foreground-subtle`,children:[s(`span`,{className:`font-medium text-foreground`,children:fe(n.roleId).label}),` ·`,` `,p(n.selector)]})}function Oe(e){let{user:t}=G(),n=t?.isAdmin===!0;return s(we,{...e,callerScopes:n?null:t?.scopes??[]})}e();var ke=`bg-primary/10 text-primary`,Ae=`bg-foreground-subtle/10 text-foreground-subtle`;function J(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toLocaleString()}function je(e){return e?e===`*`?`*`:e.join(`, `):``}function Me(){let e=a(),r=w(),{data:i,isLoading:c}=M(),{data:l}=ne(),u=n(()=>i??[],[i]),f=n(()=>l??[],[l]),p=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),m=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),[h,g]=o(!1),[_,v]=o(null),y=P({onSuccess:p}),b=j({onSuccess:({token:e,record:t})=>{m(),g(!1),v({token:e,label:t.name})}}),x=k({onSuccess:m}),S=async(e,t)=>{await r({title:`Revoke "${t}"?`,message:`Any client using this token will lose access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&y.mutate({id:e})},C=async(e,t)=>{await r({title:`Revoke "${t}"?`,message:`The scoped token will be invalid on its next use.`,confirmLabel:`Revoke`,variant:`danger`})&&x.mutate({id:e})};return t(K,{children:[t(`div`,{className:`flex items-center justify-between gap-3 flex-wrap`,children:[s(`p`,{className:`text-xs text-foreground-subtle max-w-2xl`,children:`Issue scoped tokens to grant a user a narrow surface — a specific addon, integration, or capability. Every token MUST be scoped: revoking it has predictable blast radius.`}),t(`button`,{onClick:()=>g(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,disabled:f.length===0,title:f.length===0?`Create a user first`:`Issue a scoped token`,children:[s(z,{className:`h-3.5 w-3.5`}),`New token`]})]}),t(Ne,{title:`Scoped tokens`,subtitle:`Grouped per user`,children:[f.length===0&&s(Fe,{text:`No users yet — scoped tokens are issued on behalf of an existing user.`}),f.map(e=>s(Le,{userId:e.id,username:e.username,onRevoke:(e,t)=>{C(e,t)},revokePending:x.isPending,revokeId:x.variables?.id},e.id))]}),u.length>0&&s(Ne,{title:`Legacy API keys`,subtitle:`${u.length} pre-existing — revoke only`,children:s(Ie,{headers:[`Label`,`Admin`,`Prefix`,`Allowed providers`,`Created`,`Last used`,``],rows:u.map(e=>{let n=!!e.isAdmin,r=y.isPending&&y.variables?.id===e.id;return t(`tr`,{className:`hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-medium`,children:e.label}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:s(`span`,{className:`inline-block rounded px-2 py-0.5 text-[10px] uppercase tracking-wide ${n?ke:Ae}`,children:n?`admin`:`regular`})}),t(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-mono text-[11px]`,children:[e.tokenPrefix,`…`]}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border text-foreground-subtle`,children:je(e.allowedProviders)||`all`}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:J(e.createdAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:J(e.lastUsedAt)}),s(`td`,{className:`px-3 py-2 border-b border-border text-right`,children:t(`button`,{onClick:()=>{S(e.id,e.label)},disabled:r,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Revoke`,children:[r?s(H,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Revoke`]})})]},e.id)})})}),c&&s(Pe,{}),h&&s(Re,{users:f.map(e=>({id:e.id,username:e.username})),onClose:()=>g(!1),onSubmit:e=>b.mutate({userId:e.userId,name:e.name,scopes:e.scopes,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}}),submitting:b.isPending}),_&&s(ze,{token:_.token,label:_.label,onClose:()=>v(null)})]})}function Ne({title:e,subtitle:n,children:r}){return t(`div`,{className:`space-y-2`,children:[t(`div`,{className:`flex items-baseline justify-between`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:e}),n&&s(`span`,{className:`text-[10px] text-foreground-subtle`,children:n})]}),r]})}function Pe(){return s(`div`,{className:`space-y-2`,children:[1,2].map(e=>s(`div`,{className:`h-10 rounded border border-border bg-surface animate-pulse`},e))})}function Fe({text:e}){return s(`div`,{className:`rounded border border-dashed border-border bg-surface px-3 py-4 text-xs text-foreground-subtle text-center`,children:e})}function Ie({headers:e,rows:n}){return s(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:t(`table`,{className:`w-full text-xs min-w-[640px]`,children:[s(`thead`,{children:s(`tr`,{children:e.map((t,n)=>s(`th`,{className:`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border whitespace-nowrap ${n===e.length-1?`text-right`:`text-left`}`,children:t},n))})}),s(`tbody`,{children:n})]})})}function Le({userId:e,username:n,onRevoke:r,revokePending:i,revokeId:a}){let{data:o,isLoading:c}=O({userId:e}),l=o??[];return c||l.length===0?null:t(`div`,{className:`space-y-1.5`,children:[s(`div`,{className:`text-[11px] font-medium text-foreground`,children:n}),s(Ie,{headers:[`Name`,`Prefix`,`Scopes`,`Expires`,`Last used`,`Created`,``],rows:l.map(e=>{let n=i&&a===e.id;return t(`tr`,{className:`hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-medium`,children:e.name}),t(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-mono text-[11px]`,children:[e.tokenPrefix,`…`]}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:s(`div`,{className:`flex flex-wrap gap-1`,children:e.scopes.map((e,n)=>t(`span`,{className:`inline-block rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-mono`,children:[e.type,`:`,e.type===`device`?`[${p(e.selector)}]`:e.target]},n))})}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:J(e.expiresAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:J(e.lastUsedAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:J(e.createdAt)}),s(`td`,{className:`px-3 py-2 border-b border-border text-right`,children:t(`button`,{onClick:()=>r(e.id,e.name),disabled:n,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[n?s(H,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Revoke`]})})]},e.id)})})]})}function Re({users:e,onClose:n,onSubmit:r,submitting:i}){let{user:a}=G(),c=a?.isAdmin===!0?null:a?.scopes??[],[l,u]=o(e[0]?.id??``),[d,f]=o(``),[p,m]=o([{type:`capability`,target:``,access:[`view`,`create`]}]),[h,g]=o(``),_=N(p),v=l!==``&&d.trim().length>0&&p.length>0&&_===null&&!i;return t(Be,{title:`Create scoped token`,onClose:n,children:[t(`div`,{className:`space-y-3`,children:[s(Y,{label:`On behalf of user`,children:s(`select`,{value:l,onChange:e=>u(e.target.value),className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary`,children:e.map(e=>s(`option`,{value:e.id,children:e.username},e.id))})}),s(Y,{label:`Name`,children:s(`input`,{value:d,onChange:e=>f(e.target.value),placeholder:`cloudflare-tunnel-route`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary`})}),t(Y,{label:`Scopes`,hint:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`,children:[s(L,{value:p,onChange:m,clampToParent:c}),_&&s(`p`,{className:`mt-1 text-[10px] text-danger`,children:_})]}),s(Y,{label:`Expires in (days)`,hint:`Leave blank for non-expiring.`,children:s(`input`,{type:`number`,min:1,value:h,onChange:e=>g(e.target.value),placeholder:`30`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary`})})]}),t(Ve,{children:[s(`button`,{onClick:n,className:`rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground`,children:`Cancel`}),t(`button`,{onClick:()=>{let e=parseInt(h,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;r({userId:l,name:d.trim(),scopes:p,expiresAt:t})},disabled:!v,className:`inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:[i?s(H,{className:`h-3.5 w-3.5 animate-spin`}):s(z,{className:`h-3.5 w-3.5`}),`Issue token`]})]})]})}function ze({token:e,label:n,onClose:r}){let[i,a]=o(!1),c=async()=>{try{await navigator.clipboard.writeText(e),a(!0)}catch{}};return t(Be,{title:`Token: ${n}`,onClose:r,children:[t(`div`,{className:`space-y-3`,children:[s(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:`Copy this token now. Once you close this dialog the secret cannot be displayed again.`}),s(`div`,{className:`rounded border border-border bg-background p-2 font-mono text-[11px] break-all select-all`,children:e})]}),t(Ve,{children:[t(`button`,{onClick:()=>{c()},className:`inline-flex items-center gap-1.5 rounded bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30`,children:[i?s(ue,{className:`h-3.5 w-3.5 text-primary`}):s(se,{className:`h-3.5 w-3.5`}),i?`Copied`:`Copy`]}),s(`button`,{onClick:r,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:`Done`})]})]})}function Be({title:e,onClose:n,children:r}){return s(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm`,onClick:n,children:t(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl`,onClick:e=>e.stopPropagation(),children:[t(`div`,{className:`flex items-start justify-between border-b border-border px-4 py-3`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:e}),s(`button`,{onClick:n,className:`text-foreground-subtle hover:text-foreground`,children:s(_,{className:`h-4 w-4`})})]}),s(`div`,{className:`p-4`,children:r})]})})}function Ve({children:e}){return s(`div`,{className:`flex justify-end gap-2 border-t border-border px-4 py-3`,children:e})}function Y({label:e,hint:n,children:r}){return t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:e}),r,n&&s(`p`,{className:`text-[10px] text-foreground-subtle`,children:n})]})}e();function X(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toLocaleString()}function He(e){if(e.type===`category`){let t=e.target??``;return t===`device`?`all devices`:`all ${t}`}if(e.type===`device`)return`device:[${(e.targets??[]).join(`,`)}]`;let t=e;return`${t.type}:${t.target??``}`}function Ue(){return s(`div`,{className:`space-y-2`,children:[1,2].map(e=>s(`div`,{className:`h-10 rounded border border-border bg-surface animate-pulse`},e))})}function We({text:e}){return s(`div`,{className:`rounded border border-dashed border-border bg-surface px-3 py-4 text-xs text-foreground-subtle text-center`,children:e})}function Ge({headers:e,rows:n}){return s(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:t(`table`,{className:`w-full text-xs min-w-[640px]`,children:[s(`thead`,{children:s(`tr`,{children:e.map((t,n)=>s(`th`,{className:`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border whitespace-nowrap ${n===e.length-1?`text-right`:`text-left`}`,children:t},n))})}),s(`tbody`,{children:n})]})})}function Ke(){let e=a(),r=w(),{data:i,isLoading:o}=V(),c=n(()=>i??[],[i]),l=A({onSuccess:()=>e.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]})}),u=async(e,t)=>{await r({title:`Revoke "${t}" session?`,message:`This integration will lose access immediately on its next API call. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&l.mutate({id:e})};return t(K,{icon:ye,title:`Linked Sessions`,subtitle:`External integrations (Alexa, …) linked to this hub via OAuth. Revoke a session to immediately invalidate that integration's access.`,children:[o&&s(Ue,{}),!o&&c.length===0&&s(We,{text:`No linked sessions — once an external integration completes the OAuth flow its session will appear here.`}),!o&&c.length>0&&s(Ge,{headers:[`Integration`,`User`,`Scopes`,`Created`,`Last used`,`Status`,``],rows:c.map(e=>{let n=e.revokedAt!==null,r=(l.isPending?l.variables?.id:void 0)===e.id;return t(`tr`,{className:`hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-medium`,children:e.integrationId}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:e.username}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:s(`div`,{className:`flex flex-wrap gap-1`,children:e.scopes.map((e,t)=>s(`span`,{className:`inline-block rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-mono`,children:He(e)},t))})}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:X(e.createdAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:X(e.lastUsedAt)}),s(`td`,{className:`px-3 py-2 border-b border-border`,children:n?t(`span`,{className:`inline-block rounded bg-foreground-subtle/10 px-2 py-0.5 text-[10px] text-foreground-subtle`,children:[`Revoked `,X(e.revokedAt)]}):s(`span`,{className:`inline-block rounded bg-emerald-500/15 px-2 py-0.5 text-[10px] text-emerald-700 dark:text-emerald-300`,children:`Active`})}),s(`td`,{className:`px-3 py-2 border-b border-border text-right`,children:!n&&t(`button`,{onClick:()=>{u(e.id,e.integrationId)},disabled:r,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Revoke`,children:[r?s(H,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Revoke`]})})]},e.id)})})]})}e();var Z=3e4,Q=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],$={title:`Authentication providers`,subtitle:`Every registered authentication surface in one list: login providers (local password, OIDC, SAML, magic-link) and second-factor providers (passkeys / WebAuthn — configure the relying-party RP ID + origin inline; users enroll from My access → Passkeys). Multiple providers run in parallel — enable/disable each independently. Disabling one only removes that method; local password login is unaffected.`,emptyTitle:`No authentication providers registered`,emptyDescription:`Local auth should always be available — if this list is empty the local-auth builtin failed to register. Check the Addons page for load errors.`,installLabel:`Add provider`};function qe(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ve,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`API keys + scoped tokens are managed from the API Keys page.`],setupSteps:[`Add users from Users → New user (or seed via CAMSTACK_ADMIN_USER / CAMSTACK_ADMIN_PASS).`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:W,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`First-time sign-ins are auto-provisioned with the configured Default Role.`],setupSteps:[`Register a web app at your IdP and copy the client_id + client_secret.`,"Set the redirect URI to `https://<this-hub>/addon/<addon-id>/callback`.",`Paste issuer + credentials in the Settings panel below — saves on every change.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:W,bullets:[`Heavier handshake than OIDC — exchange metadata XML with your IdP.`,`Group → role mapping via SAML assertions.`]}:e.startsWith(`auth-webauthn`)||e.startsWith(`auth-passkey`)?{headline:`Passkeys / WebAuthn — passwordless second factor.`,icon:B,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)||e.startsWith(`auth-magic-link`)?{headline:`TOTP / magic-link — second factor or passwordless sign-in.`,icon:B,bullets:[`Codes / links delivered out-of-band (RFC 6238 for TOTP).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:z,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Je(){let e=S({capName:Q[0].capName},{refetchInterval:Z}),t=S({capName:Q[1].capName},{refetchInterval:Z}),r=g(void 0,{refetchInterval:Z}),i=n(()=>ge(r.data??[]),[r.data]),a=n(()=>{let n=[],r=[e.data??[],t.data??[]];for(let[e,t]of Q.entries())for(let a of r[e]??[])n.push({addonId:a.addonId,displayName:i.get(a.addonId)??a.addonId,isActive:a.isActive,capName:t.capName,stageBadge:t.stageBadge});return n},[e.data,t.data,i]);return s(he,{title:$.title,subtitle:$.subtitle,pageIcon:z,itemIcon:z,capability:Q[0].capName,installButtonLabel:$.installLabel,items:a,isLoading:e.isLoading||t.isLoading,emptyTitle:$.emptyTitle,emptyDescription:$.emptyDescription,renderStatusBadges:e=>e.stageBadge===null?null:s(`span`,{className:`inline-flex items-center rounded-full border border-primary/30 bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary`,children:e.stageBadge}),renderExpandedPanel:e=>s(Ye,{addonId:e.addonId})})}function Ye({addonId:e}){let n=qe(e),r=n.icon;return t(`div`,{className:`rounded-lg border border-border bg-surface p-4 space-y-3`,children:[t(`div`,{className:`flex items-start gap-2.5`,children:[s(r,{className:`h-4 w-4 mt-0.5 text-primary shrink-0`}),s(`div`,{className:`text-xs text-foreground font-medium`,children:n.headline})]}),s(`ul`,{className:`text-xs text-foreground-subtle space-y-1.5 pl-6 list-disc`,children:n.bullets.map((e,t)=>s(`li`,{children:e},t))}),n.setupSteps&&n.setupSteps.length>0&&t(`div`,{className:`rounded-md border border-border bg-surface-hover/40 px-3 py-2.5 space-y-1.5`,children:[t(`div`,{className:`flex items-center gap-1.5 text-[10px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:[s(_e,{className:`h-3 w-3`}),`Setup steps`]}),s(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>s(`li`,{children:e},t))})]}),e===`local-auth`&&t(`div`,{className:`rounded-md border border-blue-500/30 bg-blue-500/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[s(C,{className:`h-3.5 w-3.5 mt-0.5 text-blue-500 shrink-0`}),t(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,s(`a`,{href:`/system/my-access`,className:`underline text-primary`,children:`My access`}),` `,`→ “Two-factor authentication” → Enable 2FA. Admins can only remove a user’s active enrollment (lost device) from the`,` `,s(`a`,{href:`/system/users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function Xe(){return s(`div`,{className:`flex flex-col p-4`,children:s(me,{tabs:[{id:`users`,label:`Users`,icon:v,content:s(Ee,{})},{id:`api-keys`,label:`Tokens`,icon:x,content:s(Me,{})},{id:`linked-sessions`,label:`Linked Sessions`,icon:ye,content:s(Ke,{})},{id:`authentication`,label:`Authentication`,icon:z,content:s(Je,{})}]})})}export{Xe as IdentityPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,b as a,o,q as s,x as c,z as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Z as u,_t as d,at as f,gt as p,mt as m,st as h,yt as g}from"./player-overlays-ktPblw8g.js";import{$r as _,An as v,Br as y,Bu as b,D as x,E as S,H as C,Hr as w,Ji as T,Jr as ee,Kr as E,Oc as te,Qi as D,Qr as O,Rt as k,Tl as ne,Uc as A,Ur as j,Vr as re,Wr as ie,Xi as M,Yi as ae,Zi as N,ea as P,ft as F,hi as oe,ht as se,hu as I,jc as L,ji as R,jn as z,k as ce,ni as B,nu as V,oi as le,pi as H,pl as ue,qi as de,qn as fe,qr as U,qt as W,tt as pe,ul as me,vl as he,wu as ge,xl as G,yl as K,yu as q,z as _e,zl as J}from"./src-CExJu3gi.js";import{an as ve}from"./src-DCJABiaG.js";import{a as ye,n as be,o as xe,s as Se}from"./index-qsRpCvR5.js";import{t as Ce}from"./FormBuilder-C2WDUIjk.js";import{t as we}from"./device-integration-icon-A7WLxehO.js";import{n as Te,r as Y,t as Ee}from"./ScanNetworkModal-BP4y5EFU.js";import{t as De}from"./NodeAddonsSettingsPanel-nVujTUZd.js";var Oe=g(`search-x`,[[`path`,{d:`m13.5 8.5-5 5`,key:`1cs55j`}],[`path`,{d:`m8.5 8.5 5 5`,key:`a8mexj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`path`,{d:`m21 21-4.3-4.3`,key:`1qie3q`}]]);n();function ke(e){let t=[];for(let n of e)n.type===`probe`&&t.push(n.key),n.type===`group`&&`fields`in n&&t.push(...ke(n.fields));return t}function Ae(t,n,r){let[a,o]=s(`idle`),[c,l]=s({}),u=i(()=>{let e=[];for(let n of t.sections)e.push(...ke(n.fields));return e},[t]),d=u.length>0&&r!==void 0,f=e(e=>{l(t=>{if(!t[e])return t;let n={...t};return delete n[e],n})},[]);return{testAllStatus:a,hasProbeFields:d,probeResults:c,handleTestAll:e(async()=>{if(!r)return;let e=u.filter(e=>{let t=n[e];return t!=null&&String(t).trim()!==``});if(e.length===0)return;o(`testing`);let t={};for(let n of e)t[n]={status:`probing`};l(t);let i=await Promise.allSettled(e.map(async e=>{try{return{key:e,result:await r(e,n[e])}}catch(t){return{key:e,result:{status:`error`,error:t instanceof Error?t.message:String(t)}}}})),a={};for(let e of i)if(e.status===`fulfilled`){let{key:t,result:n}=e.value;a[t]={status:n.status===`ok`?`ok`:`error`,result:n}}l(a),o(`idle`)},[r,u,n]),clearProbeResult:f}}n();function je(e){let t=[];for(let n of e)`required`in n&&n.required===!0&&`key`in n&&n.key&&t.push(n.key),n.type===`group`&&`fields`in n&&t.push(...je(n.fields));return t}function Me(e){return e==null?!0:typeof e==`string`?e.trim()===``:!1}function Ne(e,t={}){for(let n of e){if(n.type===`group`&&`fields`in n){Ne(n.fields,t);continue}`key`in n&&n.key&&`default`in n&&n.default!==void 0&&(t[n.key]=n.default)}return t}function X(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`probe-${crypto.randomUUID()}`:`probe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Pe({open:t,integrationId:n,addonId:a,onClose:u}){let{t:f}=be(),p=o(),[m,h]=s({}),[g,_]=s(!1),[v,y]=s(null),[b,x]=s(X),S=H({addonId:a},{enabled:t}),C=S.data?.deviceType??null,w=B({addonId:a,type:C??ve.Camera},{enabled:t&&S.isSuccess&&C!==null}),T=w.data??null;l(()=>{t&&(h(T?Ne(T.sections.flatMap(e=>e.fields)):{}),x(X()),_(!1),y(null))},[t,n,T]);let ee=i(()=>({...m,_probeRequestId:b}),[m,b]),E=U({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),D=R(),O=e(async(e,t)=>{_(!0);let n=await D.mutateAsync({addonId:a,type:C??ve.Camera,key:e,value:t,formValues:ee});return n.status===`ok`&&n.suggestedValues&&h(e=>{let t=!1,r={...e};for(let[i,a]of Object.entries(n.suggestedValues??{}))Me(e[i])&&!Me(a)&&(r[i]=a,t=!0);return t?r:e}),n},[D,a,ee,C]),{testAllStatus:k,hasProbeFields:ne,probeResults:j,handleTestAll:re,clearProbeResult:ie}=Ae(T??{sections:[]},m,O);async function M(e){y(null);try{await E.mutateAsync({addonId:a,type:C??ve.Camera,config:m,integrationId:n}),e?h(T?Ne(T.sections.flatMap(e=>e.fields)):{}):u()}catch(e){y(e instanceof Error?e.message:String(e))}}if(!t)return null;let ae=je((T?.sections??[]).flatMap(e=>e.fields)).filter(e=>Me(m[e])),N=ae.length===0,P=S.isLoading||C!==null&&w.isLoading,F=S.isError||S.isSuccess&&C===null||w.isError||w.isSuccess&&T===null;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[c(`div`,{className:`absolute inset-0 bg-black/60`,onClick:u}),r(`div`,{className:`relative z-10 flex w-full max-w-2xl flex-col max-h-[calc(90dvh-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] rounded-xl border border-border bg-background shadow-2xl`,children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-5 py-4 shrink-0`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:f(`integrations.addDevice`)}),c(`button`,{onClick:u,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:c(te,{className:`h-4 w-4`})})]}),c(`div`,{className:`flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-3`,children:P?c(`div`,{className:`flex items-center justify-center py-8`,children:c(J,{className:`h-5 w-5 animate-spin text-primary`})}):F?r(`div`,{className:`flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3`,children:[c(A,{className:`h-4 w-4 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`space-y-1`,children:[c(`p`,{className:`text-xs font-medium text-destructive`,children:`Provider unavailable`}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`The addon `,c(`span`,{className:`font-mono`,children:a}),` is not ready or does not support manual device creation. Check that the integration is online and try again.`]})]})]}):c(Ce,{schema:T,values:m,onChange:h,onTestField:O,probeResults:j,onClearProbe:ie})}),!F&&!P&&r(`div`,{className:`border-t border-border bg-surface/50 shrink-0`,children:[r(`button`,{type:`button`,onClick:()=>_(e=>!e),className:`flex w-full items-center justify-between px-5 py-2 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[r(`span`,{className:`flex items-center gap-2`,children:[c(ue,{className:`h-3.5 w-3.5`}),`Test logs`,c(`span`,{className:`font-mono text-[9px] opacity-60`,children:b.slice(0,14)})]}),c(d,{className:`h-3.5 w-3.5 transition-transform ${g?`rotate-180`:``}`})]}),g&&c(`div`,{className:`border-t border-border max-h-64 overflow-hidden`,children:c(pe,{addonId:a,requestId:b,limit:50,maxHeight:`max-h-64`,showFilters:!1,showScope:!1,className:`border-0 rounded-none`})})]}),!F&&!P&&(v||ae.length>0)&&c(`div`,{className:`border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[c(A,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),c(`p`,{className:`text-[11px] text-destructive`,children:v||`Required: ${ae.join(`, `)}`})]})}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[r(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{onClick:u,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors`,children:f(`integrations.cancel`)}),!F&&ne&&r(`button`,{type:`button`,onClick:re,disabled:k===`testing`,className:`inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`,children:[k===`testing`?c(J,{className:`h-3.5 w-3.5 animate-spin`}):c(L,{className:`h-3.5 w-3.5`}),`Test All`]})]}),r(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{onClick:()=>M(!0),disabled:F||!N||E.isPending,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`,children:f(`integrations.saveAndNew`)}),c(`button`,{onClick:()=>M(!1),disabled:F||!N||E.isPending,className:`rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50`,children:E.isPending?f(`integrations.saving`):f(`integrations.save`)})]})]})]})]})}var Fe=1500;function Z({addonId:e,integrationId:t,jobId:n,onFinished:i}){let{t:a}=be(),o=y(),s=(j({addonId:e,integrationId:t},{refetchInterval:e=>(e.state.data??[]).some(e=>e.state===`running`)?Fe:!1}).data??[]).find(e=>e.jobId===n);if(!s)return null;let l=s.state===`running`,u=s.processed,d=s.total>0?Math.round(u/s.total*100):0;!l&&s.finishedAt!==null&&i();let f=[`${u}/${s.total} ${a(`integrations.adoptJobProcessed`,{defaultValue:`processed`})}`];s.adopted>0&&f.push(`${s.adopted} ${a(`integrations.adoptJobAdded`,{defaultValue:`added`})}`),s.alreadyAdopted>0&&f.push(`${s.alreadyAdopted} ${a(`integrations.adoptJobSkipped`,{defaultValue:`already there`})}`),s.failed>0&&f.push(`${s.failed} ${a(`integrations.adoptJobFailed`,{defaultValue:`failed`})}`);let p=f.join(` · `);return r(`div`,{className:`border-t border-border px-5 py-3 shrink-0 space-y-2`,children:[r(`div`,{className:`flex items-center gap-2`,children:[l?c(J,{className:`h-3.5 w-3.5 animate-spin text-primary shrink-0`}):s.failed>0?c(A,{className:`h-3.5 w-3.5 text-destructive shrink-0`}):s.state===`cancelled`?c(I,{className:`h-3.5 w-3.5 text-foreground-subtle shrink-0`}):c(q,{className:`h-3.5 w-3.5 text-primary shrink-0`}),c(`p`,{className:`text-[11px] text-foreground`,children:p}),l&&c(`button`,{onClick:()=>o.mutate({jobId:n}),className:`ml-auto rounded-lg border border-border px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:a(`integrations.adoptJobCancel`,{defaultValue:`Stop`})})]}),c(`div`,{className:`h-1 w-full rounded-full bg-border overflow-hidden`,children:c(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${d}%`},role:`progressbar`,"aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100})}),s.results.filter(e=>e.outcome===`failed`).slice(0,5).map(e=>r(`p`,{className:`text-[11px] text-destructive`,children:[e.childNativeId,`: `,e.error]},e.childNativeId))]})}function Ie(e){let t=e.metadata;return[e.name,e.childNativeId,t.model,t.manufacturer,t.integration,t.externalLocation].filter(e=>typeof e==`string`&&e.length>0).join(` `)}n();var Q=`devices`,Le={id:Q,label:`Devices`,isDefault:!0},Re=2e4,$=100;function ze({addonId:n,integrationId:i,onClose:a}){let{t:u}=be(),d=o(),[f,p]=s(new Set),[m,h]=s(new Set),[g,_]=s(new Map),[v,y]=s(null),{data:b}=ae(),x=(b??[]).find(e=>e.addonId===n)?.supportsLocationImport??!1,[T,ee]=s(!0),D=re({addonId:n,integrationId:i}).data?.filters,O=D&&D.length>0?D:[Le],[k,ne]=s(O.find(e=>e.isDefault)?.id??(O.some(e=>e.id===Q)?Q:O[0].id)),j=k!==Q,M=ie(),N=w({addonId:n,integrationId:i,page:1,pageSize:Re,filter:k}),P=N.refetch,F=M.mutate,oe=e(()=>{F({addonId:n,integrationId:i},{onSettled:()=>{P()}})},[F,n,i,P]),se=t(null);l(()=>{let e=`${n}::${i}`;se.current===e||N.isLoading||(se.current=e,(N.data?.candidates.length??0)===0&&oe())},[n,i,N.isLoading,N.data,oe]);let I=M.isPending,L=M.isError?M.error instanceof Error?M.error.message:String(M.error):null,R=typeof M.data?.lastError==`string`&&M.data.lastError.length>0?M.data.lastError:null,z=N.data?.candidates??[],ce=N.isError?N.error instanceof Error?N.error.message:String(N.error):null,B=E(),[V,le]=s(null),H=e(e=>{e.alreadyAdopted||p(t=>{let n=new Set(t);return n.has(e.childNativeId)?n.delete(e.childNativeId):n.add(e.childNativeId),n})},[]),ue=e(e=>{h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),de=e((e,t)=>{_(n=>{let r=new Map(n),i=r.get(e)?.hiddenChildIds??new Set,a=new Set(i);return a.has(t)?a.delete(t):a.add(t),a.size===0?r.delete(e):r.set(e,{hiddenChildIds:a}),r})},[]),fe=e(e=>{let t={};for(let n of e){let e=g.get(n);e&&e.hiddenChildIds.size>0&&(t[n]={hiddenChildIds:[...e.hiddenChildIds]})}return Object.keys(t).length>0?t:void 0},[g]),U=e(async()=>{y(null);let e=[...f];if(e.length!==0)try{let t=fe(e),{jobId:r}=await B.mutateAsync({addonId:n,integrationId:i,filter:k,childNativeIds:e,...t?{perCandidate:t}:{},...x?{importLocations:T}:{}});le(r),p(new Set),_(new Map)}catch(e){y(e instanceof Error?e.message:String(e))}},[f,fe,B,n,i,k,x,T]),W=t(null),pe=e(()=>{V===null||W.current===V||(W.current=V,P(),d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]}))},[V,P,d]),me=e(e=>{ne(e),p(new Set),h(new Set),_(new Map),y(null)},[]),G=f.size,K=V!==null&&G===0&&!B.isPending;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[c(`div`,{className:`absolute inset-0 bg-black/60`,onClick:a}),r(`div`,{className:`relative z-10 flex w-full max-w-3xl flex-col h-[85vh] rounded-xl border border-border bg-background shadow-2xl`,children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-5 py-4 shrink-0`,children:[r(`div`,{className:`min-w-0`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:u(`integrations.adoptDevices`,{defaultValue:`Adopt devices`})}),c(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5`,children:u(`integrations.adoptDevicesHint`,{defaultValue:`Preview the candidate devices and add the ones you want.`})})]}),r(`div`,{className:`flex items-center gap-3 shrink-0`,children:[x&&r(`label`,{className:`flex items-center gap-1.5 cursor-pointer text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:[c(`input`,{type:`checkbox`,checked:T,onChange:e=>ee(e.target.checked),className:`accent-primary`}),u(`integrations.importLocations`,{defaultValue:`Import locations from the integration`})]}),c(`button`,{onClick:a,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Close`,children:c(te,{className:`h-4 w-4`})})]})]}),r(`div`,{className:`flex-1 min-h-0 px-5 py-3 flex flex-col gap-2 overflow-hidden`,children:[(L??ce??R)&&z.length===0&&c(`div`,{className:`rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[c(A,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`min-w-0`,children:[c(`p`,{className:`text-xs font-medium text-destructive`,children:u(`integrations.adoptRefreshFailed`,{defaultValue:`Could not discover devices.`})}),c(`p`,{className:`text-[11px] text-destructive/90 mt-0.5`,children:L??ce??R})]})]})}),O.length>1&&c(Be,{filters:O,activeFilter:k,onSelect:me}),c(`div`,{className:`flex-1 min-h-0`,children:c(S,{mode:`generic`,items:z,pageSize:$,getKey:e=>e.childNativeId,getSearchText:Ie,getFilterType:e=>e.type,filterOptions:_e(),filterLabel:u(`integrations.adoptColType`,{defaultValue:`Type`}),isLoading:N.isLoading||I&&z.length===0,searchPlaceholder:u(`integrations.adoptSearch`,{defaultValue:`Search candidates…`}),emptyLabel:(L??ce??R)&&z.length===0?``:u(`integrations.adoptNoCandidates`,{defaultValue:`No candidate devices found.`}),toolbar:r(`button`,{type:`button`,onClick:oe,disabled:I,title:u(`integrations.adoptRefreshTitle`,{defaultValue:`Re-scan Home Assistant for devices`}),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-60 shrink-0`,children:[c(he,{className:`h-3.5 w-3.5 ${I?`animate-spin`:``}`}),u(`integrations.adoptRefresh`,{defaultValue:`Refresh`})]}),columns:[{key:`name`,header:u(`integrations.adoptColName`,{defaultValue:`Name`}),headerClassName:`w-[55%]`,cell:e=>c(Ve,{candidate:e,expandable:!j,expanded:m.has(e.childNativeId),onToggleExpand:()=>ue(e.childNativeId),adoptedLabel:u(`integrations.adoptAlready`,{defaultValue:`Adopted`})})},{key:`type`,header:u(`integrations.adoptColType`,{defaultValue:`Type`}),headerClassName:`w-[30%] hidden sm:table-cell`,cellClassName:`hidden sm:table-cell`,cell:e=>{let t=C(e.type),n=t.icon;return r(`span`,{className:`inline-flex items-center gap-1.5 text-[10px] text-foreground-subtle`,children:[c(n,{className:`h-3.5 w-3.5 shrink-0`}),t.label]})}},{key:`select`,header:``,headerClassName:`w-[15%] text-right`,cellClassName:`text-right`,cell:e=>c(`div`,{className:`flex items-center justify-end`,children:c(`button`,{onClick:()=>H(e),disabled:e.alreadyAdopted,"aria-label":f.has(e.childNativeId)?`Deselect`:`Select`,className:`inline-flex h-5 w-5 items-center justify-center rounded border ${f.has(e.childNativeId)?`border-primary bg-primary`:`border-border`} ${e.alreadyAdopted?`cursor-not-allowed opacity-50`:``}`,children:f.has(e.childNativeId)&&c(ge,{className:`h-3 w-3 text-primary-foreground`})})})}],isExpanded:e=>!j&&m.has(e.childNativeId),renderExpanded:j?void 0:e=>c(He,{candidate:e,hiddenChildIds:g.get(e.childNativeId)?.hiddenChildIds??new Set,onToggleChildHidden:t=>de(e.childNativeId,t)}),rowClassName:e=>e.alreadyAdopted?`opacity-60`:f.has(e.childNativeId)?`bg-primary/5`:``})})]}),v&&c(`div`,{className:`border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[c(A,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),c(`p`,{className:`text-[11px] text-destructive`,children:v})]})}),V!==null&&c(Z,{addonId:n,integrationId:i,jobId:V,onFinished:pe}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[c(`div`,{}),r(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{onClick:a,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors`,children:u(`integrations.cancel`,{defaultValue:`Cancel`})}),r(`button`,{onClick:K?a:U,disabled:!K&&(G===0||B.isPending),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50 disabled:cursor-not-allowed`,children:[B.isPending&&c(J,{className:`h-3.5 w-3.5 animate-spin`}),K?u(`integrations.close`,{defaultValue:`Close`}):u(`integrations.addSelected`,{defaultValue:`Add selected`}),!K&&G>0?` (${G})`:``]})]})]})]})]})}function Be({filters:e,activeFilter:t,onSelect:n}){return c(`div`,{role:`tablist`,"aria-label":`Discovery granularity`,className:`inline-flex shrink-0 self-start rounded-lg border border-border bg-surface p-0.5`,children:e.map(e=>{let r=e.id===t;return c(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>n(e.id),className:`rounded-md px-3 py-1 text-xs font-medium transition-colors ${r?`bg-primary text-primary-foreground shadow-sm`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:e.label},e.id)})})}function Ve({candidate:e,expandable:t,expanded:n,onToggleExpand:i,adoptedLabel:a}){let o=(e.children??[]).length;return r(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[t&&o>0?r(`button`,{type:`button`,onClick:i,"aria-label":n?`Collapse`:`Expand`,"aria-expanded":n,className:`flex h-5 flex-shrink-0 items-center justify-center gap-0.5 rounded px-0.5 text-[10px] text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground`,children:[c(n?d:p,{className:`h-3.5 w-3.5`}),o]}):c(`span`,{className:`flex h-5 w-5 flex-shrink-0 items-center justify-center text-foreground-subtle/40`,children:`—`}),c(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),e.alreadyAdopted&&c(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-[9px] font-medium text-success shrink-0`,children:a})]})}function He({candidate:e,hiddenChildIds:t,onToggleChildHidden:n}){let i=e.children??[];return i.length===0?null:c(`div`,{className:`space-y-1 py-1`,children:i.map(e=>{let i=t.has(e.childNativeId),a=e.capabilities??[];return r(`div`,{className:`flex items-center gap-2 rounded px-2 py-1 ${i?`opacity-50`:``}`,children:[c(`span`,{className:`text-[11px] text-foreground truncate flex-1 min-w-0`,children:e.name}),a.length>0&&c(`span`,{className:`text-[9px] text-foreground-subtle truncate`,children:a.join(`, `)}),c(`button`,{onClick:()=>n(e.childNativeId),"aria-label":i?`Show child`:`Hide child`,title:i?`Show after adopt`:`Hide after adopt`,className:`flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0`,children:c(i?m:V,{className:`h-3 w-3`})})]},e.childNativeId)})})}n();function Ue(e){let t=[];for(let n of e){if(n.type===`group`){t.push(...Ue(n.fields));continue}`key`in n&&typeof n.key==`string`&&t.push(n.key)}return t}function We(e,t){if(!e)return{};let n=new Set(e.sections.flatMap(e=>Ue(e.fields))),r={};for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=t[e]);return r}function Ge(e){return{...e.tabs?{tabs:e.tabs}:{},sections:e.sections.map(e=>({...e,fields:e.fields.map(e=>{if(`value`in e){let{value:t,...n}=e;return n}return e})}))}}function Ke({integrationId:e,addonId:t,name:n,kind:a,mode:s,brokerKind:l,canTest:u=!1,trpc:d,onClose:f}){let{t:p}=be(),m=o(),{data:h,isLoading:g}=M({id:e},{enabled:s===`account`||s===`broker`}),_=i(()=>{let e=h?.brokerId;return typeof e==`string`?e:null},[h]),{data:y,isLoading:b}=v({addonId:t,nodeId:`hub`},{enabled:s===`account`}),x=i(()=>y?Ge(y):null,[y]),S=D(),C=t=>{S.mutate({id:e,settings:t},{onSuccess:()=>{m.invalidateQueries(),f()}})};return c(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4`,onClick:f,children:r(`div`,{className:`max-h-[85vh] w-full max-w-lg overflow-y-auto rounded-xl border border-border bg-surface p-5 shadow-xl`,onClick:e=>e.stopPropagation(),children:[r(`div`,{className:`mb-3 flex items-center justify-between`,children:[r(`h2`,{className:`text-sm font-semibold text-foreground`,children:[p(`integrations.editConfig`,{defaultValue:`Edit configuration`}),` — `,n]}),c(`button`,{onClick:f,className:`rounded-md p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":p(`common.close`,{defaultValue:`Close`}),children:c(te,{className:`h-4 w-4`})})]}),s===`broker`?l?r(`div`,{className:`space-y-3`,children:[c(`p`,{className:`text-[11px] text-foreground-subtle`,children:p(`integrations.relinkBrokerHelp`,{defaultValue:`Choose the broker this integration connects through. Picking a different broker re-points it and restarts the addon.`})}),_&&r(`p`,{className:`text-[11px] text-foreground`,children:[p(`integrations.currentBroker`,{defaultValue:`Current broker`}),`:`,` `,c(`span`,{className:`font-mono text-foreground-subtle`,children:_})]}),S.isPending?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[c(J,{className:`h-3 w-3 animate-spin`}),p(`integrations.saving`,{defaultValue:`Saving…`})]}):c(Y,{kind:l,onResolved:e=>{C({brokerId:e})},onBack:f}),S.isError&&c(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.relinkFailed`,{defaultValue:`Failed to update broker link.`})})]}):c(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.noBrokerKind`,{defaultValue:`This integration declares device-adoption but its addon manifest has no brokerKind.`})}):s===`account`?g||b?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[c(J,{className:`h-3 w-3 animate-spin`}),p(`integrations.loading`,{defaultValue:`Loading…`})]}):c(Te,{addonId:t,configSchema:x,canTest:u,initialName:n,initialConfig:We(x,h??{}),submitLabel:p(`integrations.save`,{defaultValue:`Save`}),hideName:!0,onSave:({config:e})=>C(e),onBack:f}):c(W,{trpc:d,addonId:t,nodeId:`hub`,title:n})]})})}function qe(e){return e==null?!1:e.sections.some(e=>e.fields.length>0)}n();function Je(){let{t}=be(),{integrationId:n}=xe(),d=o(),p=ye(),[m,g]=Se(),y=f(),[C,w]=s(!1),[E,D]=s(!1),[j,re]=s(!1),[ie,M]=s(!1),[I,L]=s(!1),{data:R,isLoading:B}=T({id:n??``},{enabled:!!n}),{data:V}=v({addonId:R?.addonId??``,nodeId:`hub`},{enabled:!!R?.addonId}),{data:H,isSuccess:U}=ae(),W=i(()=>{let e=R?.addonId;return!e||!U?null:(H??[]).find(t=>t.addonId===e)?.kind===`device-adoption`?`device-adoption`:`device-provider`},[H,R?.addonId,U]),{data:he}=O({}),ge=i(()=>(he?.providers??[]).some(e=>e.addonId===R?.addonId),[he,R?.addonId]),q=W!==null,_e=R?.info?.fixed===!0,ve=q?W===`device-adoption`?t(`integrations.adoptDevices`,{defaultValue:`Adopt devices`}):t(`integrations.addDevice`):t(`integrations.addDeviceLoading`,{defaultValue:`Loading…`}),Ce=i(()=>{let e=R?.addonId;return!e||!U?null:(H??[]).find(t=>t.addonId===e)?.brokerKind??null},[H,R?.addonId,U]),Te=i(()=>{let e=R?.addonId;return!e||!U?!1:(H??[]).find(t=>t.addonId===e)?.canTest===!0},[H,R?.addonId,U]),Y=i(()=>{let e=R?.addonId;return!e||!U?null:(H??[]).find(t=>t.addonId===e)?.mode??null},[H,R?.addonId,U]);l(()=>{m.get(`add`)===`1`&&q&&(w(!0),g(e=>{let t=new URLSearchParams(e);return t.delete(`add`),t},{replace:!0}))},[m,q,g]);let ke=V!=null&&Array.isArray(V.sections)&&V.sections.some(e=>e.fields.length>0),{data:Ae}=z({addonId:R?.addonId??``,nodeId:`hub`},{enabled:!!R?.addonId&&Y!==`account`}),je=Y!==null&&Y!==`account`&&qe(Ae),Me=i(()=>R?.addonId?[R.addonId]:[],[R?.addonId]),{data:Ne}=le({projection:`slim`},{refetchInterval:3e4}),X=[[`integrations`,`get`],{input:{id:n??``},type:`query`}],Fe=P({onMutate:async e=>{await d.cancelQueries({queryKey:X});let t=d.getQueryData(X);return t!=null&&d.setQueryData(X,{...t,enabled:e.enabled}),{previous:t}},onError:(e,t,n)=>{let r=n;r?.previous!=null&&d.setQueryData(X,r.previous)},onSettled:()=>{d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Z=de({onSuccess:()=>{d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]}),M(!1),p(`/integrations`)}}),Ie=fe({onSuccess:()=>{d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Q=oe({onSuccess:()=>{d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Le=ee({onSuccess:()=>{d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Re=_({onSuccess:()=>{d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),$=i(()=>Ne??[],[Ne]),Be=i(()=>{let e=new Map;for(let t of $)e.set(t.id,{id:t.id,name:t.name??t.stableId??`#${String(t.id)}`});return e},[$]),Ve=e(e=>Be.get(e)??null,[Be]),{data:He}=N(void 0),Ue=i(()=>x(He),[He]),We=e(e=>p(`/devices/${String(e)}`),[p]),Ge=i(()=>{let e=R?.id;return e?$.filter(t=>{let n=Ue(t);return n.kind===`resolved`&&n.integration.id===e}):[]},[$,R?.id,Ue]),Je=i(()=>He===void 0?null:ce(Ge).length,[He,Ge])??`…`;return B?r(`div`,{className:`p-4`,children:[c(`div`,{className:`h-16 rounded-lg bg-surface animate-pulse mb-4`}),c(`div`,{className:`h-40 rounded-lg bg-surface animate-pulse`})]}):R?r(`div`,{className:`p-4 space-y-4 overflow-x-hidden`,children:[c(se,{items:[{label:`Integrations`,onClick:()=>p(`/integrations`)},{label:R.name}]}),r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`flex items-center gap-3 min-w-0`,children:[c(`img`,{src:u(`/api/addon-assets/${R.addonId}/assets/icon.svg`),alt:``,className:`h-8 w-8 rounded-lg shrink-0`,onError:e=>{e.target.style.display=`none`}}),r(`div`,{className:`min-w-0`,children:[c(`h1`,{className:`text-lg font-semibold text-foreground truncate`,children:R.name}),r(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5 truncate`,children:[R.addonId,` · `,Je,` `,t(`integrations.devices`)]})]})]}),r(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[ge&&r(`button`,{onClick:()=>D(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:`Scan the network for devices (incl. a different subnet)`,children:[c(G,{className:`h-3.5 w-3.5`}),`Scan network`]}),!_e&&r(`button`,{onClick:()=>w(!0),disabled:!q,className:`flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50 disabled:cursor-not-allowed`,title:ve,children:[c(ne,{className:`h-3.5 w-3.5`}),ve]}),r(`div`,{className:`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 transition-colors ${Fe.isPending?`opacity-60`:``} ${R.enabled?`border-success/30 bg-success/5`:`border-border bg-surface`}`,title:t(`integrations.toggleHint`,{defaultValue:`Click to toggle`}),children:[c(k,{checked:R.enabled,onCheckedChange:e=>Fe.mutate({id:n,enabled:e}),disabled:Fe.isPending,"aria-label":R.enabled?`Disable integration`:`Enable integration`}),c(`span`,{className:`text-[11px] font-medium ${R.enabled?`text-success`:`text-foreground-subtle`}`,children:R.enabled?`Enabled`:`Disabled`}),Fe.isPending&&c(J,{className:`h-3 w-3 animate-spin text-foreground-subtle`})]}),Y!==`standalone`&&(ke||W===`device-adoption`)&&r(`button`,{onClick:()=>re(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[c(me,{className:`h-3 w-3`}),t(`integrations.config`)]}),r(`button`,{onClick:()=>L(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:t(`integrations.logs`,{defaultValue:`View logs`}),children:[c(ue,{className:`h-3 w-3`}),t(`integrations.logs`,{defaultValue:`Logs`})]}),c(F,{label:`Restart`,icon:K,title:`Restart "${R.name}"?`,description:`Restarting the addon will briefly disconnect every device backed by it (${Je} active). Streams will reconnect automatically.`,confirmLabel:`Restart`,triggerVariant:`outline`,confirmVariant:`danger`,disabled:Ie.isPending,action:()=>Ie.mutateAsync({addonId:R.addonId})}),!_e&&r(`button`,{onClick:()=>M(!0),className:`flex items-center gap-1.5 rounded-lg border border-danger bg-danger/10 px-3 py-1.5 text-[11px] font-medium text-danger hover:bg-danger hover:text-background transition-colors`,title:t(`integrations.delete`,{defaultValue:`Delete integration`}),children:[c(h,{className:`h-3 w-3`}),t(`integrations.delete`,{defaultValue:`Delete`})]})]})]}),je&&c(De,{nodeId:null,addonIds:Me,level:`global`,surface:`integration`,title:t(`integrations.settings`,{defaultValue:`Settings`})}),c(S,{context:`integration-detail`,devices:$,trpc:y.trpcClient,integrationOf:Ue,forceIntegrationId:R.id,urlScope:`root`,lsKey:`integration-detail:${R.addonId}`,resolveIntegrationIcon:we,resolveParent:Ve,onNavigate:We,batchActions:{remove:Q.mutate,disable:Le.mutate,enable:Re.mutate},..._e?{}:{onDeleteDevice:e=>Q.mutate({deviceId:e.id})}}),C&&n&&W===`device-adoption`&&c(ze,{addonId:R.addonId,integrationId:n,onClose:()=>w(!1)}),C&&n&&W===`device-provider`&&c(Pe,{open:C,integrationId:n,addonId:R.addonId,onClose:()=>w(!1)}),E&&R&&c(Ee,{open:E,scope:{addonId:R.addonId,label:R.name},onClose:()=>D(!1)}),j&&n&&W!==null&&Y!==null&&c(Ke,{integrationId:n,addonId:R.addonId,name:R.name,kind:W,mode:Y,brokerKind:Ce,canTest:Te,trpc:y.trpcClient,onClose:()=>re(!1)}),I&&c(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6`,onClick:()=>L(!1),children:r(`div`,{className:`flex flex-col rounded-xl border border-border bg-surface shadow-xl w-full max-w-5xl h-[80vh]`,onClick:e=>e.stopPropagation(),children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 min-w-0`,children:[c(ue,{className:`h-4 w-4 text-primary shrink-0`}),c(`h2`,{className:`text-sm font-semibold text-foreground truncate`,children:R.name}),r(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate`,children:[R.addonId,n?` · ${n}`:``]})]}),c(`button`,{onClick:()=>L(!1),className:`flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Close logs`,children:c(te,{className:`h-4 w-4`})})]}),c(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:c(pe,{addonId:R.addonId,limit:200,maxHeight:`max-h-full`,showScope:!1,className:`h-full border-0 rounded-none`})})]})}),ie&&c(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60`,onClick:()=>!Z.isPending&&M(!1),children:r(`div`,{className:`rounded-xl border border-border bg-background p-5 shadow-2xl w-96 space-y-3`,onClick:e=>e.stopPropagation(),children:[r(`div`,{className:`flex items-start gap-3`,children:[c(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-lg bg-danger/10 shrink-0`,children:c(A,{className:`h-4 w-4 text-danger`})}),r(`div`,{className:`min-w-0`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`integrations.deleteTitle`,{defaultValue:`Delete integration?`})}),c(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:t(`integrations.deleteWarning`,{defaultValue:`This removes the integration "{{name}}" and its {{count}} device(s). The addon will restart. This cannot be undone.`,name:R.name,count:Je})})]})]}),Z.error&&c(`div`,{className:`rounded-lg border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:Z.error instanceof Error?Z.error.message:String(Z.error)}),r(`div`,{className:`flex items-center justify-end gap-2 pt-1`,children:[c(`button`,{onClick:()=>M(!1),disabled:Z.isPending,className:`rounded-lg border border-border px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed`,children:t(`integrations.cancel`,{defaultValue:`Cancel`})}),c(`button`,{onClick:()=>Z.mutate({id:n}),disabled:Z.isPending,className:`inline-flex items-center gap-1.5 rounded-lg bg-danger px-3 py-1.5 text-[11px] font-medium text-background hover:bg-danger/90 transition-colors disabled:opacity-60 disabled:cursor-not-allowed`,children:Z.isPending?r(a,{children:[c(J,{className:`h-3 w-3 animate-spin`}),t(`integrations.deleting`,{defaultValue:`Deleting…`})]}):r(a,{children:[c(h,{className:`h-3 w-3`}),t(`integrations.confirmDelete`,{defaultValue:`Delete integration`})]})})]})]})})]}):r(`div`,{className:`flex flex-col items-center justify-center py-20 px-6 text-center gap-4`,children:[c(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-foreground-subtle/10`,children:c(Oe,{className:`h-6 w-6 text-foreground-subtle`})}),r(`div`,{className:`space-y-1 max-w-sm`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`integrations.integrationNotFound`,{defaultValue:`Integration not found`})}),c(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`integrations.integrationNotFoundHint`,{defaultValue:`The integration "{{id}}" does not exist. It may have been deleted, or the URL may be wrong.`,id:n??``})})]}),r(`button`,{onClick:()=>p(`/integrations`),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors`,children:[c(b,{className:`h-3 w-3`}),t(`integrations.backToList`,{defaultValue:`Back to integrations`})]})]})}export{Je as IntegrationDetailPage};