@camstack/addon-admin-ui 1.2.366 → 1.2.368

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 (121) hide show
  1. package/dist/assets/{AddonAssetIcon-17hwoRMt.js → AddonAssetIcon-DFj-ju1T.js} +1 -1
  2. package/dist/assets/AddonIntegrationBody-FGAYdPUA.js +1 -0
  3. package/dist/assets/Addons-WwpkTbDd.js +4 -0
  4. package/dist/assets/{AdminTabs-B04_5psq.js → AdminTabs-DTp_qwRF.js} +1 -1
  5. package/dist/assets/AiProfiles-CBco5ewR.js +3 -0
  6. package/dist/assets/{BrokerForm-DKV4MjEe.js → BrokerForm-C1gCAO_i.js} +1 -1
  7. package/dist/assets/Build-DurNKP8T.js +40 -0
  8. package/dist/assets/{Calendars-P_nkJSu5.js → Calendars-CgpSaf57.js} +1 -1
  9. package/dist/assets/Cluster-DvhjeS7K.js +1 -0
  10. package/dist/assets/ClusterStepModel-B6r5CyPs.js +1 -0
  11. package/dist/assets/CompositionEditor-B72RWTAg.js +1 -0
  12. package/dist/assets/{CompositionEditorPage-CsrR0pua.js → CompositionEditorPage-Czh4hLXm.js} +1 -1
  13. package/dist/assets/Data-DXof6DOP.js +1 -0
  14. package/dist/assets/DetectionIntelligence-DOHtIjr_.js +1 -0
  15. package/dist/assets/DeviceDetail-DJTOlefk.js +2 -0
  16. package/dist/assets/{DeviceDoActionFields-CNVytrZx.js → DeviceDoActionFields-CgcW2y34.js} +1 -1
  17. package/dist/assets/{Devices-C0kon5K1.js → Devices-Dxdfsu2U.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-L5iL7zMk.js → EmbedPlayerPage-DBDO4iGl.js} +1 -1
  19. package/dist/assets/Events-BfvAxlZU.js +1 -0
  20. package/dist/assets/Identity-CdNS5Nbo.js +1 -0
  21. package/dist/assets/IntegrationDetail-v37t7dlu.js +1 -0
  22. package/dist/assets/Integrations-B46b2Fdt.js +1 -0
  23. package/dist/assets/Integrations-BhXxxG3u.js +1 -0
  24. package/dist/assets/Locations-DS7U1LC0.js +3 -0
  25. package/dist/assets/{Logs-BnqR8ZxJ.js → Logs-CEo_ltyB.js} +1 -1
  26. package/dist/assets/{MotionZonesSettings-CftAgxWi.js → MotionZonesSettings-CEgwXQs4.js} +1 -1
  27. package/dist/assets/MyAccess-BPfDF0OL.js +2 -0
  28. package/dist/assets/Network-CsE6aS-2.js +1 -0
  29. package/dist/assets/{NodeAddonsSettingsPanel-CyC3dNNW.js → NodeAddonsSettingsPanel-ud5IAMLM.js} +1 -1
  30. package/dist/assets/Notifications-Dq9lhOuh.js +1 -0
  31. package/dist/assets/Plates-DY7gAqtN.js +1 -0
  32. package/dist/assets/{PrivacyMaskSettings-CUbD6k0L.js → PrivacyMaskSettings-3Qj6iJyr.js} +1 -1
  33. package/dist/assets/Recordings-Cu6I48Ge.js +1 -0
  34. package/dist/assets/ScanNetworkModal-DeQVAhiv.js +1 -0
  35. package/dist/assets/{SceneMonitorEditor-nRqgGlp2.js → SceneMonitorEditor-DLTybD7E.js} +1 -1
  36. package/dist/assets/{Scenes-BE0Mn8dr.js → Scenes-yXnX2BEQ.js} +1 -1
  37. package/dist/assets/SessionsList-DTYAg11v.js +2 -0
  38. package/dist/assets/Showroom-DWPBOwhC.js +1 -0
  39. package/dist/assets/System-B2dJPzzY.js +1 -0
  40. package/dist/assets/{Terminal-CFsSZcwd.js → Terminal-Dw2mDFS9.js} +5 -5
  41. package/dist/assets/{Viewer-DGwYXGL8.js → Viewer-BOmPgDRl.js} +1 -1
  42. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Cb0asOHw.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DtaIXYDp.js} +1 -1
  43. package/dist/assets/{archive-C_-iEHhW.js → archive-6pzbE4zL.js} +1 -1
  44. package/dist/assets/{authed-media-Bl_kQSZp.js → authed-media-dlxPHLGt.js} +1 -1
  45. package/dist/assets/{boxes-Cj3enrG0.js → boxes-B9mRSNXT.js} +1 -1
  46. package/dist/assets/circle-slash-D3OU4sq-.js +1 -0
  47. package/dist/assets/client-DdTCFotl.js +357 -0
  48. package/dist/assets/crop-C4_qNtVc.js +1 -0
  49. package/dist/assets/{debounced-invalidate-BBjgoUp1.js → debounced-invalidate-CjvnQ6zt.js} +1 -1
  50. package/dist/assets/{device-integration-icon-DztESV66.js → device-integration-icon-BRBO6DaZ.js} +1 -1
  51. package/dist/assets/device-picker-model-DOwpVM5h.js +1 -0
  52. package/dist/assets/dist-BPTn9PvV.js +1 -0
  53. package/dist/assets/dist-CJxcey0N.js +357 -0
  54. package/dist/assets/{face-bbox-Dc7-3tNi.js → face-bbox-CPsQ49nP.js} +1 -1
  55. package/dist/assets/{hard-drive-download-B1qrAMQ7.js → hard-drive-download-CUKF7GIe.js} +1 -1
  56. package/dist/assets/{history-Ixgo2o2a.js → history-BR0cgtxK.js} +1 -1
  57. package/dist/assets/{hostInit-Di1v3zcF.js → hostInit-D7PExcI5.js} +1 -1
  58. package/dist/assets/index-BhXNFlQG.js +4 -0
  59. package/dist/assets/index-BrFFHBMJ.css +2 -0
  60. package/dist/assets/{layers-JboEX-t3.js → layers-BEphtFOD.js} +1 -1
  61. package/dist/assets/location-owned-usage-BHS4BUrZ.js +1 -0
  62. package/dist/assets/{mf-entry-bootstrap-0-3214e58d.js → mf-entry-bootstrap-0-f35db814.js} +2 -2
  63. package/dist/assets/{monitor-smartphone-DEvaCEpt.js → monitor-smartphone-DbkPiYT_.js} +1 -1
  64. package/dist/assets/mount-DOwpVM5h.js +1 -0
  65. package/dist/assets/notification-schedule-field-DQOVzLdk.js +1 -0
  66. package/dist/assets/{octagon-alert-CQuofVwc.js → octagon-alert-DI2r29y1.js} +1 -1
  67. package/dist/assets/{player-overlays-OREckyXS.js → player-overlays-CVsVEZkx.js} +1 -1
  68. package/dist/assets/remoteEntry-8sPAjus8.js +1 -0
  69. package/dist/assets/{send-CuHij6pJ.js → send-CsS0XJlB.js} +1 -1
  70. package/dist/assets/{settings-2-BQZcFYTR.js → settings-2-CyVUMXY7.js} +1 -1
  71. package/dist/assets/src-DBOD88Il.js +67 -0
  72. package/dist/assets/{use-scenes-feed-ClbcxKnd.js → use-scenes-feed-B3khNWlP.js} +1 -1
  73. package/dist/assets/{use-stationary-objects-CoYzEK7V.js → use-stationary-objects-DONRHYCH.js} +1 -1
  74. package/dist/assets/useEventInvalidation-DOwpVM5h.js +1 -0
  75. package/dist/assets/{useNodeUrlSelection-DcWoCZcT.js → useNodeUrlSelection-CqbePEmt.js} +1 -1
  76. package/dist/assets/user-round-DIYdKGlH.js +1 -0
  77. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D7L4TG5K.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Cns_eCdr.js} +2 -2
  78. package/dist/index.html +8 -8
  79. package/dist/server/addon.js +13 -2
  80. package/package.json +9 -2
  81. package/dist/assets/AddonIntegrationBody-BeqtM34S.js +0 -1
  82. package/dist/assets/Addons-CtHmFFDu.js +0 -4
  83. package/dist/assets/AiProfiles-DH4OfiK8.js +0 -3
  84. package/dist/assets/Build-wVpnzyi-.js +0 -40
  85. package/dist/assets/Cluster-DcppV--F.js +0 -11
  86. package/dist/assets/ClusterStepModel-CuLU_n7Y.js +0 -1
  87. package/dist/assets/CompositionEditor-ChdRH3T6.js +0 -1
  88. package/dist/assets/Data-BI1pocFD.js +0 -1
  89. package/dist/assets/DetectionIntelligence-rgev34M5.js +0 -1
  90. package/dist/assets/DeviceDetail-Dmuqi8se.js +0 -2
  91. package/dist/assets/Events-DYXOT0Hq.js +0 -1
  92. package/dist/assets/Identity-qjHDXMR1.js +0 -1
  93. package/dist/assets/IntegrationDetail-B4r4qCRS.js +0 -1
  94. package/dist/assets/Integrations-p4SuJxJd.js +0 -1
  95. package/dist/assets/Integrations-wz7gp4PG.js +0 -1
  96. package/dist/assets/Locations-DZvyVw8M.js +0 -3
  97. package/dist/assets/MyAccess-BEllFcGI.js +0 -2
  98. package/dist/assets/Network-Bveif_QG.js +0 -1
  99. package/dist/assets/Notifications-B_aD9Cji.js +0 -1
  100. package/dist/assets/Plates-Dme6vW0C.js +0 -1
  101. package/dist/assets/Recordings-BxcuwHlj.js +0 -1
  102. package/dist/assets/ScanNetworkModal-C3DrcAg4.js +0 -1
  103. package/dist/assets/SessionsList-DUnoP2AA.js +0 -2
  104. package/dist/assets/Showroom-CbsvZXd8.js +0 -1
  105. package/dist/assets/StatusBadge-CeptlsPG.js +0 -1
  106. package/dist/assets/System-DHYlbOzD.js +0 -1
  107. package/dist/assets/circle-slash-B9leNw8c.js +0 -1
  108. package/dist/assets/client-1c3e-nOc.js +0 -357
  109. package/dist/assets/crop-Cz85GIsX.js +0 -1
  110. package/dist/assets/device-picker-model-_qZjX1i6.js +0 -1
  111. package/dist/assets/dist-DnUHR24y.js +0 -1
  112. package/dist/assets/dist-Dp0Vbww8.js +0 -357
  113. package/dist/assets/index-BS0xLTFQ.js +0 -4
  114. package/dist/assets/index-DfattF0g.css +0 -2
  115. package/dist/assets/location-owned-usage-CDli6ZEZ.js +0 -1
  116. package/dist/assets/mount-_qZjX1i6.js +0 -1
  117. package/dist/assets/notification-schedule-field-UMCuGywf.js +0 -1
  118. package/dist/assets/remoteEntry-CNuq86OS.js +0 -1
  119. package/dist/assets/src-C1q5pTPr.js +0 -67
  120. package/dist/assets/useEventInvalidation-_qZjX1i6.js +0 -1
  121. package/dist/assets/user-round-BmFyUIzE.js +0 -1
@@ -1 +1 @@
1
- import{I as e,Q as t,S as n,W as r,o as i,x as a}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 o,at as s}from"./player-overlays-OREckyXS.js";import{Gu as c,K as l,Qi as u,eo as d,ha as f,oa as p,q as m,qi as h,r as g}from"./src-C1q5pTPr.js";import{t as _}from"./useTranslation-Bc5yH9V9.js";import{K as v,Z as y}from"./index-BS0xLTFQ.js";import{t as b}from"./AdminPage-BSFohA3i.js";import"./useEventInvalidation-_qZjX1i6.js";import{t as x}from"./device-integration-icon-DztESV66.js";t();var S=32;function C(e,t){let n=e=>t(e).kind===`orphan`,r=new Set;for(let t of e)n(t)&&r.add(t.id);let i=new Map;for(let t of e)i.set(t.id,t);let a=(e,t=0)=>{if(t>S)return!1;if(r.has(e.id))return!0;if(e.parentDeviceId==null)return!1;let n=i.get(e.parentDeviceId);return n?a(n,t+1):!1},o=[],s=[];for(let t of e)a(t)?s.push(t):o.push(t);return{activeDevices:o,orphanDevices:s}}function w(){let{t}=_(),S=y(),w=s(),T=i();g([`deviceManager`],[`device.registered`,`device.unregistered`,`device.online`,`device.offline`,`device.disabled`,`device.enabled`]),g([`integrations`],[`integration.enabled`,`integration.disabled`,`integration.deleted`,`provider.started`,`provider.stopped`,`addon.installed`,`addon.uninstalled`,`addon.started`,`addon.stopped`]);let{data:E}=p({projection:`slim`}),{data:D}=d(void 0),O=f({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),k=h({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),A=u({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),j=r(()=>E??[],[E]),M=r(()=>m(D),[D]),{activeDevices:N,orphanDevices:P}=r(()=>C(j,M),[j,M]),F=r(()=>{let e=new Map;for(let t of j)e.set(t.id,{id:t.id,name:t.name??t.stableId??`#${String(t.id)}`});return e},[j]),I=e(e=>F.get(e)??null,[F]),L=r(()=>(D??[]).map(e=>({id:e.id,name:e.name??e.addonId,icon:a(v,{type:e.addonId,size:`sm`})})),[D]),R=e(e=>S(`/devices/${String(e)}`),[S]);return n(b,{icon:o,title:t(`nav.devices`,`Devices`),children:[a(l,{context:`devices`,devices:N,trpc:w.trpcClient,filters:{integrations:L},integrationOf:M,resolveIntegrationIcon:x,resolveParent:I,onNavigate:R,batchActions:{remove:O.mutate,disable:k.mutate,enable:A.mutate}}),P.length>0&&n(`div`,{className:`mt-6 space-y-2`,children:[n(`div`,{className:`flex items-baseline gap-2`,children:[a(c,{className:`h-3.5 w-3.5 text-warning shrink-0`}),a(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Orphan devices`}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[P.length,` device`,P.length===1?``:`s`,` pointing at integrations no longer registered`]})]}),n(`div`,{className:`rounded-lg border border-warning/30 bg-warning/5 p-2`,children:[a(`p`,{className:`text-[11px] text-foreground-subtle px-2 pb-2`,children:"These devices reference an integration that is no longer registered (their `integrationId`, or — for older devices without one — their `addonId`). Delete them, or re-install the missing integration to bring them back online. The provider badge beside each row is the addon that serves it."}),a(l,{context:`devices`,devices:P,trpc:w.trpcClient,integrationOf:M,urlScope:`nested`,lsKey:`devices:orphan`,resolveIntegrationIcon:x,resolveParent:I,onNavigate:R})]})]})]})}export{w as DevicesPage};
1
+ import{I as e,Q as t,S as n,W as r,o as i,x as a}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 o,at as s}from"./player-overlays-CVsVEZkx.js";import{$i as c,J as l,Ji as u,Ku as d,ga as f,q as p,r as m,sa as h,to as g}from"./src-DBOD88Il.js";import{t as _}from"./useTranslation-Bc5yH9V9.js";import{K as v,Z as y}from"./index-BhXNFlQG.js";import{t as b}from"./AdminPage-BSFohA3i.js";import"./useEventInvalidation-DOwpVM5h.js";import{t as x}from"./device-integration-icon-BRBO6DaZ.js";t();var S=32;function C(e,t){let n=e=>t(e).kind===`orphan`,r=new Set;for(let t of e)n(t)&&r.add(t.id);let i=new Map;for(let t of e)i.set(t.id,t);let a=(e,t=0)=>{if(t>S)return!1;if(r.has(e.id))return!0;if(e.parentDeviceId==null)return!1;let n=i.get(e.parentDeviceId);return n?a(n,t+1):!1},o=[],s=[];for(let t of e)a(t)?s.push(t):o.push(t);return{activeDevices:o,orphanDevices:s}}function w(){let{t}=_(),S=y(),w=s(),T=i();m([`deviceManager`],[`device.registered`,`device.unregistered`,`device.online`,`device.offline`,`device.disabled`,`device.enabled`]),m([`integrations`],[`integration.enabled`,`integration.disabled`,`integration.deleted`,`provider.started`,`provider.stopped`,`addon.installed`,`addon.uninstalled`,`addon.started`,`addon.stopped`]);let{data:E}=h({projection:`slim`}),{data:D}=g(void 0),O=f({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),k=u({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),A=c({onSuccess:()=>{T.invalidateQueries({queryKey:[[`deviceManager`]]})}}),j=r(()=>E??[],[E]),M=r(()=>l(D),[D]),{activeDevices:N,orphanDevices:P}=r(()=>C(j,M),[j,M]),F=r(()=>{let e=new Map;for(let t of j)e.set(t.id,{id:t.id,name:t.name??t.stableId??`#${String(t.id)}`});return e},[j]),I=e(e=>F.get(e)??null,[F]),L=r(()=>(D??[]).map(e=>({id:e.id,name:e.name??e.addonId,icon:a(v,{type:e.addonId,size:`sm`})})),[D]),R=e(e=>S(`/devices/${String(e)}`),[S]);return n(b,{icon:o,title:t(`nav.devices`,`Devices`),children:[a(p,{context:`devices`,devices:N,trpc:w.trpcClient,filters:{integrations:L},integrationOf:M,resolveIntegrationIcon:x,resolveParent:I,onNavigate:R,batchActions:{remove:O.mutate,disable:k.mutate,enable:A.mutate}}),P.length>0&&n(`div`,{className:`mt-6 space-y-2`,children:[n(`div`,{className:`flex items-baseline gap-2`,children:[a(d,{className:`h-3.5 w-3.5 text-warning shrink-0`}),a(`h2`,{className:`text-sm font-semibold text-foreground`,children:`Orphan devices`}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[P.length,` device`,P.length===1?``:`s`,` pointing at integrations no longer registered`]})]}),n(`div`,{className:`rounded-lg border border-warning/30 bg-warning/5 p-2`,children:[a(`p`,{className:`text-[11px] text-foreground-subtle px-2 pb-2`,children:"These devices reference an integration that is no longer registered (their `integrationId`, or — for older devices without one — their `addonId`). Delete them, or re-install the missing integration to bring them back online. The provider badge beside each row is the addon that serves it."}),a(p,{context:`devices`,devices:P,trpc:w.trpcClient,integrationOf:M,urlScope:`nested`,lsKey:`devices:orphan`,resolveIntegrationIcon:x,resolveParent:I,onNavigate:R})]})]})]})}export{w as DevicesPage};
@@ -1 +1 @@
1
- import{Q as e,S as t,W as n,d as r,q as i,u as a,x as o,z 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{rt as c}from"./player-overlays-OREckyXS.js";import{Ct as l,Eu as u,It as d,jt as f,vt as p}from"./src-C1q5pTPr.js";import{ii as m}from"./client-1c3e-nOc.js";import{D as h,M as g,O as _,P as v,T as y,y as b}from"./__vite-browser-external-DF8Eb0aa.js";e();var x=v([_({kind:y(`adaptive`)}),_({kind:y(`profile`),profile:m})]),S=_({serverUrl:g().min(1),token:g().min(1),deviceId:h().int().nonnegative(),target:x,muted:b()});function C(e,t){let n=t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t};window.ReactNativeWebView?.postMessage(JSON.stringify(n))}function w(e){switch(e){case`playing`:return`playing`;case`error`:return`error`;case`connecting`:case`disconnected`:case`idle`:return`connecting`}}function T(e){return e.kind===`adaptive`?{kind:`adaptive`}:{kind:`profile`,profile:e.profile}}function E(e){return e.kind===`adaptive`?`embed:adaptive`:`embed:profile:${e.profile}`}function D(){let e=window.__CAMSTACK_EMBED__;if(e==null)return{ok:!1,error:`window.__CAMSTACK_EMBED__ is not set`};let t=S.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function O({message:e}){return s(()=>{C(`error`,e)},[e]),t(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Embed config error: `,e]})}function k({system:e,deviceId:t,initialTarget:r,initialMuted:a}){let[c,l]=i(r),[u,p]=i(a),{handleOffer:m,getIceServers:h,addIceCandidate:g,getIceCandidates:_,closeSession:v,getSessionState:y,getSessionDebug:b,applyDownlinkProbe:S}=f(e.trpcClient,t),D=n(()=>T(c),[c]),O=n(()=>(e,t)=>m(D,e,t),[m,D]),k=n(()=>(e,t,n)=>m(n,t,e),[m]);s(()=>(window.__camstackEmbed={setMuted:e=>p(e),setTarget:e=>{let t=x.safeParse(e);t.success&&l(t.data)}},()=>{window.__camstackEmbed&&delete window.__camstackEmbed}),[]);let A=E(c);return o(`div`,{style:{position:`fixed`,inset:0,width:`100vw`,height:`100vh`,background:`#000`},children:o(d,{serverUrl:e.serverUrl,streamKey:A,autoPlay:!0,muted:u,showControls:!1,className:`w-full h-full`,getSessionDebug:b,applyDownlinkProbe:S,handleOffer:O,reoffer:k,getSessionState:y,getIceServers:h,addIceCandidate:g,getIceCandidates:_,closeSession:v,onStateChange:e=>C(w(e)),onError:e=>C(`error`,e)},A)})}function A(){let e=n(()=>D(),[]),t=n(()=>{if(!e.ok)return null;let t=l({serverUrl:e.config.serverUrl,token:e.config.token}),n=new r({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return p(n),{system:t,queryClient:n}},[e]);return s(()=>{if(t)return()=>{t.system.close()}},[t]),e.ok?t?o(c,{system:t.system,children:o(a,{client:t.queryClient,children:o(u.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:o(k,{system:t.system,deviceId:e.config.deviceId,initialTarget:e.config.target,initialMuted:e.config.muted})})})}):o(O,{message:`Failed to initialise the embed player`}):o(O,{message:e.error})}export{A as EmbedPlayerPage};
1
+ import{Q as e,S as t,W as n,d as r,q as i,u as a,x as o,z 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{rt as c}from"./player-overlays-CVsVEZkx.js";import{Du as l,Lt as u,Mt as d,wt as f,yt as p}from"./src-DBOD88Il.js";import{ii as m}from"./client-DdTCFotl.js";import{D as h,M as g,O as _,P as v,T as y,y as b}from"./__vite-browser-external-DF8Eb0aa.js";e();var x=v([_({kind:y(`adaptive`)}),_({kind:y(`profile`),profile:m})]),S=_({serverUrl:g().min(1),token:g().min(1),deviceId:h().int().nonnegative(),target:x,muted:b()});function C(e,t){let n=t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t};window.ReactNativeWebView?.postMessage(JSON.stringify(n))}function w(e){switch(e){case`playing`:return`playing`;case`error`:return`error`;case`connecting`:case`disconnected`:case`idle`:return`connecting`}}function T(e){return e.kind===`adaptive`?{kind:`adaptive`}:{kind:`profile`,profile:e.profile}}function E(e){return e.kind===`adaptive`?`embed:adaptive`:`embed:profile:${e.profile}`}function D(){let e=window.__CAMSTACK_EMBED__;if(e==null)return{ok:!1,error:`window.__CAMSTACK_EMBED__ is not set`};let t=S.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function O({message:e}){return s(()=>{C(`error`,e)},[e]),t(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Embed config error: `,e]})}function k({system:e,deviceId:t,initialTarget:r,initialMuted:a}){let[c,l]=i(r),[f,p]=i(a),{handleOffer:m,getIceServers:h,addIceCandidate:g,getIceCandidates:_,closeSession:v,getSessionState:y,getSessionDebug:b,applyDownlinkProbe:S}=d(e.trpcClient,t),D=n(()=>T(c),[c]),O=n(()=>(e,t)=>m(D,e,t),[m,D]),k=n(()=>(e,t,n)=>m(n,t,e),[m]);s(()=>(window.__camstackEmbed={setMuted:e=>p(e),setTarget:e=>{let t=x.safeParse(e);t.success&&l(t.data)}},()=>{window.__camstackEmbed&&delete window.__camstackEmbed}),[]);let A=E(c);return o(`div`,{style:{position:`fixed`,inset:0,width:`100vw`,height:`100vh`,background:`#000`},children:o(u,{serverUrl:e.serverUrl,streamKey:A,autoPlay:!0,muted:f,showControls:!1,className:`w-full h-full`,getSessionDebug:b,applyDownlinkProbe:S,handleOffer:O,reoffer:k,getSessionState:y,getIceServers:h,addIceCandidate:g,getIceCandidates:_,closeSession:v,onStateChange:e=>C(w(e)),onError:e=>C(`error`,e)},A)})}function A(){let e=n(()=>D(),[]),t=n(()=>{if(!e.ok)return null;let t=f({serverUrl:e.config.serverUrl,token:e.config.token}),n=new r({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return p(n),{system:t,queryClient:n}},[e]);return s(()=>{if(t)return()=>{t.system.close()}},[t]),e.ok?t?o(c,{system:t.system,children:o(a,{client:t.queryClient,children:o(l.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:o(k,{system:t.system,deviceId:e.config.deviceId,initialTarget:e.config.target,initialMuted:e.config.muted})})})}):o(O,{message:`Failed to initialise the embed player`}):o(O,{message:e.error})}export{A as EmbedPlayerPage};
@@ -0,0 +1 @@
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,at as m,ct as h,ft as g,gt as _,ht as v,st as y,vt as b}from"./player-overlays-CVsVEZkx.js";import{$n as x,Ad as S,As as C,Cf as w,Cn as T,Cs as E,Ds as D,Es as O,Eu as k,Fs as A,Ft as j,Gn as M,Gt as N,Hd as P,Ht as F,Is as I,Jd as L,Jt as R,Kn as z,Kt as B,Ls as V,Ms as ee,Nn as H,Ns as U,Of as W,On as G,Os as K,Ou as te,Pn as q,Ps as ne,Qd as re,Qn as ie,Qt as ae,Rs as oe,Sd as se,Sn as ce,Ss as le,Tn as ue,Ts as de,Uf as fe,Vd as pe,Wn as me,Wt as he,Wu as ge,Ys as _e,Zf as ve,Zn as ye,Zu as be,an as xe,as as Se,bs as Ce,cs as we,dc as Te,df as Ee,ds as De,du as Oe,ec as ke,ed as Ae,ef as je,es as Me,fs as Ne,fu as Pe,gs as Fe,hd as Ie,hf as Le,hs as Re,if as ze,jf as Be,jn as J,js as Ve,ju as He,kt as Ue,ku as We,ms as Ge,ns as Ke,on as qe,os as Je,ot as Ye,ou as Xe,ps as Ze,pu as Y,qt as Qe,rs as $e,sa as et,ss as tt,su as nt,td as rt,ts as it,ud as at,us as ot,uu as st,vf as ct,vn as lt,vs as ut,wn as dt,ws as ft,xn as pt,xr as mt,xs as ht,yn as gt,ys as _t,zo as vt}from"./src-DBOD88Il.js";import{a as yt,c as bt,d as xt,f as St,i as Ct,m as wt,n as Tt,o as Et,p as Dt,r as Ot,s as kt,t as At}from"./debounced-invalidate-CjvnQ6zt.js";import{Un as jt,hi as Mt}from"./client-DdTCFotl.js";import{t as Nt}from"./useTranslation-Bc5yH9V9.js";import"./mount-DOwpVM5h.js";import{ot as Pt}from"./index-BhXNFlQG.js";import{t as Ft}from"./AdminPage-BSFohA3i.js";import{a as It,i as Lt,r as Rt,t as zt}from"./authed-media-dlxPHLGt.js";import{t as Bt}from"./use-stationary-objects-DONRHYCH.js";import{t as Vt}from"./AdminTabs-DTp_qwRF.js";import{t as Ht}from"./format-size-DIxKXxtj.js";var Ut=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`}]]),Wt=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`}]]),Gt=b(`circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),Kt=b(`copy-plus`,[[`line`,{x1:`15`,x2:`15`,y1:`12`,y2:`18`,key:`1p7wdc`}],[`line`,{x1:`12`,x2:`18`,y1:`15`,y2:`15`,key:`1nscbv`}],[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),qt=b(`folder-plus`,[[`path`,{d:`M12 10v6`,key:`1bos4e`}],[`path`,{d:`M9 13h6`,key:`1uhe8q`}],[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),Jt=b(`keyboard`,[[`path`,{d:`M10 8h.01`,key:`1r9ogq`}],[`path`,{d:`M12 12h.01`,key:`1mp3jc`}],[`path`,{d:`M14 8h.01`,key:`1primd`}],[`path`,{d:`M16 12h.01`,key:`1l6xoz`}],[`path`,{d:`M18 8h.01`,key:`emo2bl`}],[`path`,{d:`M6 8h.01`,key:`x9i8wu`}],[`path`,{d:`M7 16h10`,key:`wp8him`}],[`path`,{d:`M8 12h.01`,key:`czm47f`}],[`rect`,{width:`20`,height:`16`,x:`2`,y:`4`,rx:`2`,key:`18n3k1`}]]),Yt=b(`list-video`,[[`path`,{d:`M21 5H3`,key:`1fi0y6`}],[`path`,{d:`M10 12H3`,key:`1ulcyk`}],[`path`,{d:`M10 19H3`,key:`108z41`}],[`path`,{d:`M15 12.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997a1 1 0 0 1-1.517-.86z`,key:`ms4nik`}]]),Xt=b(`maximize`,[[`path`,{d:`M8 3H5a2 2 0 0 0-2 2v3`,key:`1dcmit`}],[`path`,{d:`M21 8V5a2 2 0 0 0-2-2h-3`,key:`1e4gt3`}],[`path`,{d:`M3 16v3a2 2 0 0 0 2 2h3`,key:`wsl5sc`}],[`path`,{d:`M16 21h3a2 2 0 0 0 2-2v-3`,key:`18trek`}]]),Zt=b(`package-plus`,[[`path`,{d:`M12 22V12`,key:`d0xqtd`}],[`path`,{d:`M16 17h6`,key:`1ook5g`}],[`path`,{d:`M19 14v6`,key:`1ckrd5`}],[`path`,{d:`M21 10.535V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.729l7 4a2 2 0 0 0 2 .001l1.675-.955`,key:`28k6lz`}],[`path`,{d:`M3.29 7 12 12l8.71-5`,key:`19ckod`}],[`path`,{d:`m7.5 4.27 8.997 5.148`,key:`9yrvtv`}]]),Qt=b(`redo-2`,[[`path`,{d:`m15 14 5-5-5-5`,key:`12vg1m`}],[`path`,{d:`M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13`,key:`6uklza`}]]),$t=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`}]]),en=b(`wand-sparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]);n();function tn(e){let t=e.subLabel??e.label;if(t!==void 0)return t;let n=e.audioLabels?.[0]?.label;return n!==void 0&&n.length>0?n:void 0}var nn=720*60*60*1e3;function rn(e){let t=[];for(let n of e)t.push(...n);return t}function an(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function on(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 sn(e,t){return`${String(e)}:${t}`}function cn(e,t){let n=new Map,r=new Set;for(let i of e){let e=sn(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 ln(e,t){return{since:e.fromMs??t-nn,until:e.toMs??t}}var un=[`native`,`raster`,`standin`];function dn(e){return un.some(t=>t===e)}var fn={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 pn(e){return e===`standin`?fn.standin:e===`raster`?fn.raster:null}var mn={"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 hn(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:mn[r]??r,detail:i,raw:t}}function gn(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 _n({row:e,cameraName:t,nowMs:n,onOpenDetail:i,selected:a=!1,onToggleSelect:o,score:s,provenance:c,footer:l}){let d=It(e.mediaId===void 0?Lt(`track`,e.trackId):Rt(e.mediaId)),f=Math.round(e.importance*100),p=s===void 0?void 0:Math.round(s*100),m=gn(e.windowMs),_=()=>i(e),v=pn(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:_,className:`h-full w-full cursor-zoom-in object-cover`}):u(`button`,{type:`button`,onClick:_,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(g,{className:`h-6 w-6 opacity-60`})}),o&&u(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),o(sn(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(wt,{className:`h-4 w-4 text-primary`}):u(h,{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.retrainStatus===`trained`||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(je,{className:`h-3 w-3`})}),e.retrainStatus===`trained`&&e.markForTrain!==!0&&u(`span`,{className:`rounded bg-success/85 p-0.5 text-white`,title:`Training complete`,"aria-label":`Training complete`,"data-testid":`retrain-status-trained`,children:u(W,{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(Be,{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(Ae,{className:`h-3 w-3`})})]})]}),r(`button`,{type:`button`,onClick:_,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,tn(e)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,tn(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:St(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 vn=1400,yn=`Admin-gated URL — opens only inside an authenticated session`;function bn({label:t,value:n,title:i}){let[a,o]=l(!1),s=z();return d(()=>{if(!a)return;let e=setTimeout(()=>o(!1),vn);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-success/40 bg-success/10 text-success`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[u(a?W:Le,{className:`h-2.5 w-2.5 shrink-0`}),u(`span`,{className:`truncate`,children:a?`Copied`:t})]})}function xn({localUrl:e,publicUrl:t}){return r(`div`,{className:`flex flex-wrap gap-1`,children:[u(bn,{label:`Local`,value:e,title:`Copy LAN URL — ${yn}`}),t&&u(bn,{label:`Public`,value:t,title:`Copy public URL — ${yn}`})]})}var Sn={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 Cn(e){return e in Sn}function wn(e){return Cn(e)?Sn[e]:e}function Tn(e,t){return`${e}${t}`}n();var En=3e4;function Dn(t){let[n,r]=l(null),i=e(e=>{r(t=>t??e)},[]);return d(()=>{t||r(null)},[t]),{publicOrigin:n,probes:t?u(On,{onOrigin:i}):null}}function On({onOrigin:e}){let{data:t}=mt({capName:`network-access`});return u(s,{children:(t??[]).map(t=>u(kn,{addonId:t.addonId,onOrigin:e},t.addonId))})}function kn({addonId:e,onOrigin:t}){let{data:n}=vt({addonId:e},{refetchInterval:En,retry:!1});return d(()=>{let e=n?jt.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 An=typeof I==`function`,jn=`Track flags arrive with the next server update`;function Mn(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var Nn=An?I:Mn;function Pn(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 Fn({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 In({deviceId:e,trackId:t,markForTrain:n,debug:i,favourited:a,onChange:o}){let s=Nn(),c=me(),[d,f]=l(null),p=d?.markForTrain??n===!0,m=d?.debug??i===!0,h=d?.favourited??a===!0,g=!An||s.isPending,_=An?void 0:jn,v=n=>{g||(async()=>{try{let r=Pn(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(Fn,{label:`Mark for training`,hint:`Keeps this track and its media past retention`,checked:p,disabled:g,..._===void 0?{}:{title:_},icon:u(je,{className:`h-4 w-4`}),onToggle:()=>v({markForTrain:!p})}),u(Fn,{label:`Debug`,hint:`Flag this track for diagnostic attention`,checked:m,disabled:g,..._===void 0?{}:{title:_},icon:u(Be,{className:`h-4 w-4`}),onToggle:()=>v({debug:!m})}),u(Fn,{label:`Favourited`,hint:`Keeps this track and its media past retention`,checked:h,disabled:g,..._===void 0?{}:{title:_},icon:u(Ae,{className:`h-4 w-4`}),onToggle:()=>v({favourited:!h})})]})}var Ln=100,Rn=120,zn={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},Bn=e=>e<0?0:e>1?1:e,Vn=e=>Math.round(e*100)/100;function Hn(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 Un(e,t,n){if(e.length===0||t===null)return zn;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return zn;let a=Hn(e,n?.maxPoints??Rn).map(e=>({x:Vn(Bn(e.x/r)*Ln),y:Vn(Bn(e.y/i)*Ln)})),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:Vn(Bn(e.x/r)*Ln),y:Vn(Bn(e.y/i)*Ln),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=Bn(t.bbox.w/r)*Bn(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:Vn(Bn(u.bbox.x/r)*Ln),y:Vn(Bn(u.bbox.y/i)*Ln),w:Vn(Bn(u.bbox.w/r)*Ln),h:Vn(Bn(u.bbox.h/i)*Ln)}:null}}var Wn=typeof tt==`function`,Gn=`Track deletion arrives with the next server update`;function Kn(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var qn=Wn?tt:Kn;n();var Jn=15e3,Yn=f();function Xn({url:e,label:t}){let{src:n,failed:r}=It(e);return n===null?u(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?u(g,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):u(P,{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 Zn=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),Qn=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function $n(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 er({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:`var(--color-warning)`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&u(`polyline`,{points:e.polyline,fill:`none`,stroke:`var(--color-info)`,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:`var(--color-info)`,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:`var(--color-info)`,fillOpacity:.95,stroke:`var(--color-background)`,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:`var(--color-success)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&u(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`var(--color-danger)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function X({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 tr({row:t,cameraName:n,deleteAvailable:i,onClose:o,onDeleted:c,onFlagsChanged:f}){let p=m(),h=me(),_=M(),v=qn(),b=t!==null,x=t?.deviceId??0,S=t?.trackId??``,C=t?.timestamp??0,w=t?.windowMs??0,{data:T}=Ne({deviceId:x,trackId:S},{enabled:b}),{data:E}=de({trackId:S,deviceId:x},{enabled:b}),D=T?.bestEventId===void 0?void 0:Number(T.bestEventId),{data:O}=Fe({ownerType:`object`,eventId:D??0,deviceId:x},{enabled:b&&D!==void 0&&Number.isFinite(D)}),{data:k}=nt({deviceId:x},{enabled:b}),A=(k??[]).find(e=>e.addonId!==void 0)?.addonId,{data:j}=Xe({deviceId:x,since:C-Jn,until:C+w+Jn,provider:A??``},{enabled:b&&A!==void 0}),[N,F]=l(null),[I,L]=l(!1),{publicOrigin:R,probes:z}=Dn(b);d(()=>{F(null)},[x,S]);let B=a(()=>{let e=E??[],t=O??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[E,O]),V=N??B,ee=It(V?V.url:void 0),H=a(()=>{let e=new Set,t=[];for(let n of[...O??[],...E??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[O,E]),U=a(()=>H.find(e=>Zn.has(e.kind))??null,[H]),W=$n(It(U?U.url:void 0).src),G=a(()=>Un(T?.positions??[],W,{snapshots:(T?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[T?.positions,T?.snapshots,W]),K=e(e=>{let t=H.find(t=>t.mediaId===e);t&&F(t)},[H]);if(t===null)return null;let te=ee.src,ne=V?.kind,re=ne!==void 0&&Qn.has(ne)&&W!==null&&(T?.positions.length??0)>=2,ie=j&&j.length>0?j[0]:null,ae=()=>{ie&&(L(!0),(async()=>{try{let e=await p.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:ie.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{h({title:`Clip unavailable`,message:`Could not resolve clip playback. Check the server logs.`,variant:`warning`})}finally{L(!1)}})())},oe=()=>{!i||v.isPending||(async()=>{if(await _({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 h({title:`Delete failed`,message:`Failed to delete this track. Check the server logs.`,variant:`danger`})}})()},se=Math.round(t.importance*100),ce=T?.importanceReason?`${String(se)}% · ${T.importanceReason}`:`${String(se)}%`,le=T?.zonesVisited&&T.zonesVisited.length>0?T.zonesVisited.join(`, `):`—`,ue=T?.audioLabels&&T.audioLabels.length>0?T.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,fe=ue===void 0?`—`:ue.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),pe=T?T.totalDistance.toFixed(2):`—`,he=hn(T?.previewMissReason),ge=Dt(T?T.firstSeen:C),_e=T?Dt(T.lastSeen):`—`;return u(gt,{open:!0,onOpenChange:e=>!e&&o(),children:r(pt,{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,tn(t)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,tn(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(He,{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:[te?u(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:u(Tt,{src:te,alt:`Key frame from ${n}`,fit:`natural`,className:`w-full`,overlay:re?u(er,{overlay:G,onPickSnapshot:K}):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:ee.failed?r(s,{children:[u(g,{className:`h-8 w-8 opacity-60`}),u(`span`,{className:`text-[11px]`,children:`Key-frame media unavailable`})]}):u(P,{className:`h-6 w-6 animate-spin opacity-70`})}),H.length>0&&u(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:H.map(e=>{let t=wn(e.kind),n=Tn(Yn,e.url),i=R?Tn(R,e.url):null;return r(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[u(`button`,{type:`button`,onClick:()=>F(e),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${t} · ${Dt(e.timestamp)}`,children:u(Xn,{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:Dt(e.timestamp),children:xt(e.timestamp)})]}),u(xn,{localUrl:n,publicUrl:i})]},e.mediaId)})}),z,ie&&r(q,{variant:`secondary`,onClick:ae,disabled:I,children:[I?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(ze,{className:`h-3.5 w-3.5`}),` `,`View clip`]}),u(In,{deviceId:t.deviceId,trackId:t.trackId,...(T?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:T?.markForTrain??t.markForTrain},...(T?.debug??t.debug)===void 0?{}:{debug:T?.debug??t.debug},...(T?.favourited??t.favourited)===void 0?{}:{favourited:T?.favourited??t.favourited},onChange:f}),he!==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:he.sentence}),u(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:he.raw})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[u(X,{label:`Camera`,value:n}),u(X,{label:`Class`,value:t.className}),u(X,{label:`Label`,value:t.label??`—`}),u(X,{label:`Sub-label`,value:t.subLabel??`—`}),u(X,{label:`Importance`,value:ce}),u(X,{label:`Zones visited`,value:le}),u(X,{label:`Audio heard`,value:fe}),u(X,{label:`Total distance`,value:pe}),u(X,{label:`First seen`,value:ge}),u(X,{label:`Last seen`,value:_e}),u(X,{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:Gn,children:r(q,{variant:`secondary`,onClick:oe,disabled:!i||v.isPending,children:[v.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete track`]})})})]})})}var nr={status:`debug.tape.status`,promote:`debug.tape.promote`,list:`debug.tape.list`,tracks:`debug.tape.tracks`,review:`debug.tape.review`,release:`debug.tape.release`,remove:`debug.tape.delete`},rr={setRelation:`debug.gt.setRelation`,setPurity:`debug.gt.setPurity`,list:`debug.gt.list`},ir=p(`/addon/pipeline-analytics/tape-export`),ar=10*6e4;function or(e){return`${ir}?tapeId=${encodeURIComponent(e)}`}var sr=`The server answered in a shape this build does not understand.`;function cr(e){return e instanceof Error?e.message:`The action failed.`}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function lr(e,t){if(!(t in e))return;let n=e[t];return n===null?null:typeof n==`number`&&Number.isFinite(n)?n:void 0}function $(e,t){let n=e[t];return typeof n==`string`?n:null}function ur(e,t){let n=e[t];return typeof n==`boolean`?n:null}function dr(e,t){if(!Array.isArray(e))return null;let n=[];for(let r of e){let e=t(r);if(e===null)return null;n.push(e)}return n}function fr(e){return e===`off`||e===`recording`||e===`refused`||e===`failing`||e===`unknown`}function pr(e){if(!Z(e))return null;let t=Q(e,`deviceId`),n=e.state,r=Q(e,`gapsSinceArmed`),i=lr(e,`segmentsHeld`),a=lr(e,`bytesLastHour`),o=lr(e,`bytesHeld`);if(t===null||!fr(n)||r===null||i===void 0||a===void 0||o===void 0)return null;let s=$(e,`reason`),c=Q(e,`segmentOriginMs`),l=Q(e,`framesPerMin`),u=Q(e,`heldFromMs`),d=Q(e,`heldToMs`),f=$(e,`shelfError`);return{deviceId:t,state:n,gapsSinceArmed:r,segmentsHeld:i,bytesLastHour:a,bytesHeld:o,...s===null?{}:{reason:s},...c===null?{}:{segmentOriginMs:c},...l===null?{}:{framesPerMin:l},...u===null?{}:{heldFromMs:u},...d===null?{}:{heldToMs:d},...f===null?{}:{shelfError:f}}}function mr(e){return Z(e)?dr(e.cameras,pr):null}function hr(e){if(!Z(e))return null;let t=$(e,`id`),n=Q(e,`deviceId`),r=$(e,`scenario`),i=e.lighting,a=Q(e,`fromMs`),o=Q(e,`toMs`),s=e.state,c=Q(e,`frames`),l=Q(e,`gaps`),u=Q(e,`bytes`),d=ur(e,`reviewed`),f=ur(e,`released`),p=dr(e.tracks,e=>typeof e==`string`?e:null),m=Q(e,`tracksStillStored`);return t===null||n===null||r===null||i!==`day`&&i!==`ir`||a===null||o===null||s!==`complete`&&s!==`incomplete`||c===null||l===null||u===null||d===null||f===null||p===null||m===null?null:{id:t,deviceId:n,scenario:r,note:$(e,`note`),lighting:i,fromMs:a,toMs:o,state:s,frames:c,gaps:l,bytes:u,reviewed:d,released:f,tracks:p,tracksStillStored:m}}function gr(e){return Z(e)?dr(e.tapes,hr):null}function _r(e){if(!Z(e))return null;let t=$(e,`trackId`),n=Q(e,`firstT`),r=Q(e,`lastT`),i=Q(e,`boundFrames`),a=$(e,`cls`),o=ur(e,`stillStored`);return t===null||n===null||r===null||i===null||a===null||o===null?null:{trackId:t,firstT:n,lastT:r,boundFrames:i,cls:a,stillStored:o}}function vr(e){if(!Z(e))return null;let t=$(e,`tapeId`),n=Q(e,`deviceId`),r=Q(e,`fromMs`),i=Q(e,`toMs`),a=ur(e,`reviewed`),o=dr(e.lanes,_r);return t===null||n===null||r===null||i===null||a===null||o===null?null:{tapeId:t,deviceId:n,fromMs:r,toMs:i,reviewed:a,lanes:o}}function yr(e){if(!Z(e))return null;if(e.ok===!1){let t=$(e,`reason`),n=$(e,`detail`);return t===null||n===null?null:{ok:!1,reason:t,detail:n}}if(e.ok!==!0)return null;let t=$(e,`tapeId`),n=e.state,r=Q(e,`frames`),i=Q(e,`gaps`),a=Q(e,`pinnedTracks`),o=Q(e,`bytes`);return t===null||n!==`complete`&&n!==`incomplete`||r===null||i===null||a===null||o===null?null:{ok:!0,tapeId:t,state:n,frames:r,gaps:i,pinnedTracks:a,bytes:o}}function br(e){if(!Z(e))return null;let t=e.status;if(t===`released`){let n=Q(e,`unpinned`),r=ur(e,`pinsSettled`);return n===null||r===null?null:{status:t,unpinned:n,pinsSettled:r}}if(t===`already-released`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=$(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function xr(e){if(!Z(e))return null;let t=e.status;if(t===`deleted`||t===`pins-owed`||t===`not-found`)return{status:t};if(t===`unavailable`){let n=$(e,`reason`);return n===null?null:{status:t,reason:n}}return null}function Sr(e){switch(e.status){case`released`:case`deleted`:return null;case`already-released`:return`This tape was already released.`;case`not-found`:return`That tape no longer exists — it may have been released or deleted elsewhere.`;case`pins-owed`:return`Refused: this tape still names pins not yet taken back. Try again shortly — the ledger settles them automatically.`;case`unavailable`:return`Unavailable on this node: ${e.reason}`}}function Cr(e){if(!Z(e))return null;let t=$(e,`leftTrackId`),n=$(e,`rightTrackId`),r=e.relation,i=e.presence;return t===null||n===null||r!==`same-subject`&&r!==`different-subjects`?null:{leftTrackId:t,rightTrackId:n,relation:r,presence:i===`continuous`?`continuous`:null}}function wr(e){if(!Z(e))return null;let t=$(e,`sourceTrackId`),n=e.purity;return t===null||n!==`mixed`&&n!==`not-a-subject`?null:{sourceTrackId:t,purity:n,switchAtMs:Q(e,`switchAtMs`)}}function Tr(e){if(!Z(e))return null;let t=dr(e.relations,Cr),n=dr(e.purities,wr),r=ur(e,`truncated`);return t===null||n===null||r===null?null:{relations:t,purities:n,truncated:r}}function Er(e){if(!e.truncated)return null;let t=e.relations.length+e.purities.length;return`Showing the first ${String(t)} marks — more exist for this window.`}function Dr(e){return e.filter(e=>e.segmentsHeld===null||e.segmentsHeld>0).map(e=>({deviceId:e.deviceId,segmentsUnknown:e.segmentsHeld===null}))}function Or(e){return e.slice(1).map((t,n)=>({trackId:e[n]??t,otherTrackId:t}))}function kr(e){return e.flatMap((t,n)=>e.slice(n+1).map(e=>({trackId:t,otherTrackId:e})))}function Ar(e,t){let n=[];for(let r of t.relations){let t=r.leftTrackId===e?r.rightTrackId:r.rightTrackId===e?r.leftTrackId:null;if(t===null)continue;let i=r.relation===`same-subject`?`same as`:`different from`;n.push(`${i} ${t}${r.presence===`continuous`?` (continuous)`:``}`)}for(let r of t.purities)r.sourceTrackId===e&&n.push(r.purity===`not-a-subject`?`not a subject`:r.switchAtMs===null?`mixed`:`mixed at switch`);return n}function jr(e){switch(e.state){case`off`:return`Off`;case`recording`:return`Recording`;case`refused`:return`Refused: ${e.reason??`unknown reason`}`;case`failing`:return`Failing: ${e.reason??`unknown reason`}`;case`unknown`:return`Unknown: ${e.reason??`unknown reason`}`}}var Mr={"window-too-long":`A promoted window is at most 30 minutes.`,"window-in-future":`The window ends in the future.`,"window-not-recorded":`No segment covers that window — the camera was not recording then, or it is older than 24 h.`,"invalid-scenario":`The scenario must be a slug: lowercase letters, digits and dashes, 3–64 characters.`,"promotion-budget":`A promotion budget is full (60 tapes, 1 GiB, 3 000 pinned tracks). Release or delete a tape already committed as a case first.`,"empty-window":`No frame was recorded in that window.`,"shelf-unreadable":`The camera's recorded segments could not be listed, so the window cannot be proven whole.`,"not-post-processing-node":`This node does not post-process frames, so it records no tracking tapes.`,"artifacts-elsewhere":`The artifacts storage location is on another node; tapes are recorded only where it lives.`,"tapes-not-started":`The tape recorder has not started on this node (or failed to).`};function Nr(e,t){let n=Mr[e]??`Refused (${e}).`;return t.length>0?`${n} ${t}`:n}function Pr(e){if(e.length===0)return null;let t=new Date(e).getTime();return Number.isFinite(t)?t:null}function Fr(e){return e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function Ir(e){return e===null?`unknown`:Fr(e)}function Lr(e){return e===null?`unknown`:String(e)}function Rr(e,t){let n=t.trim();return e===404?`This tape no longer exists on this node (unknown tape).`:e===503?n.length>0?n:`Tapes are unavailable on this node.`:e===500?n.length>0?n:`The export could not be read (the tape may have just been released or deleted).`:`Download failed (${String(e)}).`}n();function zr({cameras:e,call:t,onPromoted:n}){let[i,a]=l(``),[o,s]=l(``),[c,d]=l(``),[f,p]=l(``),[m,h]=l(``),[g,_]=l(`auto`),[v,y]=l(!1),[b,x]=l(null),S=async()=>{let r=Number.parseInt(i===``?e[0]?.value??``:i,10),a=Pr(o),s=Pr(c);if(!Number.isFinite(r)||a===null||s===null){x(`Pick a camera and both ends of the window.`);return}y(!0),x(null);try{let e=yr(await t(nr.promote,{deviceId:r,fromMs:a,toMs:s,scenario:f,...m.trim().length>0?{note:m.trim()}:{},...g===`day`||g===`ir`?{lighting:g}:{}}));e===null?x(sr):e.ok?(x(`Promoted ${e.tapeId}: ${String(e.frames)} frames, ${Fr(e.bytes)}, ${String(e.pinnedTracks)} tracks pinned`+(e.state===`incomplete`?` — incomplete (it has gaps) and cannot become a case.`:`.`)),n()):x(Nr(e.reason,e.detail))}catch(e){x(cr(e))}finally{y(!1)}};return r(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`w-40`,children:u(H,{value:i,options:[...e],onChange:e=>a(e.target.value),"aria-label":`Camera`})}),u(Y,{type:`datetime-local`,"aria-label":`From`,value:o,onChange:e=>s(e.target.value),className:`w-48`}),u(Y,{type:`datetime-local`,"aria-label":`To`,value:c,onChange:e=>d(e.target.value),className:`w-48`}),u(Y,{"aria-label":`Scenario`,placeholder:`615-door-groups`,value:f,onChange:e=>p(e.target.value),className:`w-44`}),u(Y,{"aria-label":`Note`,placeholder:`optional note`,value:m,onChange:e=>h(e.target.value),className:`w-52`}),u(`div`,{className:`w-28`,children:u(H,{value:g,"aria-label":`Lighting`,options:[{value:`auto`,label:`Lighting: auto`},{value:`day`,label:`day`},{value:`ir`,label:`ir`}],onChange:e=>_(e.target.value)})}),r(q,{onClick:()=>void S(),disabled:v||e.length===0,children:[v?u(P,{className:`h-3.5 w-3.5 animate-spin`}):null,` Promote window`]}),u(`p`,{className:`w-full text-xs text-foreground-subtle`,children:`A promoted tape may be shared as a test case — keep the scenario slug and note free of names or other personal data.`}),b!==null&&u(`p`,{className:`w-full text-xs text-foreground`,children:b})]})}var Br=`pipeline-analytics`,Vr=`debug.listTracks`,Hr=`debug.analyze`,Ur=p(`/addon/pipeline-analytics/debug-export`);function Wr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Gr(e,t){let n=e[t];return typeof n==`string`?n:null}function Kr(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function qr(e,t){let n=e[t];return typeof n==`boolean`?n:null}function Jr(e){return e===`error`||e===`warn`||e===`info`}function Yr(e){if(!Wr(e))return null;let t=Gr(e,`code`),n=Gr(e,`detail`),r=e.severity;return t===null||n===null||!Jr(r)?null:{code:t,severity:r,detail:n}}function Xr(e){if(!Wr(e))return null;let t=Gr(e,`trackId`),n=Kr(e,`deviceId`),r=Gr(e,`className`),i=Kr(e,`firstSeen`),a=Kr(e,`lastSeen`),o=Kr(e,`durationMs`),s=qr(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=Gr(e,`label`),l=Gr(e,`subLabel`),u=Gr(e,`previewMissReason`),d=qr(e,`markForTrain`),f=qr(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:Kr(e,`importance`)??0,bestEventId:Gr(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function Zr(e){let t=Xr(e);if(t===null||!Wr(e))return null;let n=Kr(e,`mediaCount`),r=Kr(e,`eventCount`),i=Kr(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=Yr(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...dn(l)?{thumbnailProvenance:l}:{}}}function Qr(e){if(!Wr(e))return null;let t=qr(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=Xr(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function $r(e){if(!Wr(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=Zr(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var ei={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 ti(e){return ei[e]??e}var ni={error:0,warn:1,info:2};function ri(e){return e.toSorted((e,t)=>ni[e.severity]-ni[t.severity]||e.code.localeCompare(t.code))}function ii(e){return e.length===0?Ur:`${Ur}?deviceIds=${e.join(`,`)}`}function ai(e){if(e<1e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.round(e/1e3);if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return`${String(n)}m ${String(t%60).padStart(2,`0`)}s`}function oi(e,t){return`${String(e)}:${t}`}function si(e,t){let n=[],r=new Set;for(let i of e){let e=oi(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}n();function ci({tapeId:e,call:t,onClose:n,onChanged:i}){let a=o({queryKey:[`events-debug`,`tapes`,`tracks`,e],queryFn:async()=>vr(await t(nr.tracks,{tapeId:e}))}),s=a.data??null,c=o({queryKey:[`events-debug`,`tapes`,`marks`,e],enabled:s!==null,queryFn:async()=>s===null?null:Tr(await t(rr.list,{deviceId:s.deviceId,since:s.fromMs-ar,until:s.toMs+ar,limit:5e3}))}),[d,f]=l([]),[p,m]=l(``),[h,g]=l(null),_=e=>f(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),v=async e=>{g(null);try{for(let[n,r]of e)await t(n,r);f([]),await c.refetch(),i()}catch(e){g(cr(e))}};if(s===null)return a.isLoading?u(`p`,{className:`text-xs`,children:`Loading the tape…`}):u(J,{message:sr});let y=s.deviceId,b=(e,t)=>v(e.map(e=>[rr.setRelation,{deviceId:y,...e,relation:t}])),x=e=>{let t=Number.parseFloat(p),n=e===`mixed`&&Number.isFinite(t)?s.fromMs+t*1e3:void 0;return v(d.map(t=>[rr.setPurity,{deviceId:y,trackId:t,purity:e,...n===void 0?{}:{switchAtMs:Math.round(n)}}]))},S=c.data==null?null:Er(c.data);return r(`div`,{className:`space-y-2 rounded-md border border-primary/40 px-3 py-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[r(`span`,{className:`text-xs font-medium`,children:[s.tapeId,` — `,String(s.lanes.length),` tracks`]}),u(q,{disabled:d.length<2,onClick:()=>void b(Or(d),`same-subject`),children:`Same subject`}),u(q,{variant:`secondary`,disabled:d.length<2,onClick:()=>void b(kr(d),`different-subjects`),children:`Different subjects`}),u(Y,{"aria-label":`Changed at (s from tape start)`,placeholder:`changed at s`,value:p,onChange:e=>m(e.target.value),className:`w-28`}),u(q,{variant:`secondary`,disabled:d.length!==1,onClick:()=>void x(`mixed`),children:`Mixed`}),u(q,{variant:`secondary`,disabled:d.length===0,onClick:()=>void x(`not-a-subject`),children:`Not a subject`}),u(q,{variant:s.reviewed?`secondary`:`primary`,onClick:()=>void v([[nr.review,{tapeId:s.tapeId,reviewed:!s.reviewed}]]).then(()=>a.refetch()),children:s.reviewed?`Mark not reviewed`:`Mark reviewed`}),u(q,{variant:`ghost`,onClick:n,children:`Close`})]}),h!==null&&u(J,{message:h}),S!==null&&u(J,{variant:`warning`,message:S}),u(`ul`,{className:`space-y-1`,children:s.lanes.toSorted((e,t)=>e.firstT-t.firstT).map(e=>u(li,{lane:e,marks:c.data===null||c.data===void 0?[]:Ar(e.trackId,c.data),selected:d.includes(e.trackId),onToggle:()=>_(e.trackId)},e.trackId))})]})}function li({lane:e,marks:t,selected:n,onToggle:i}){let{src:a}=It(e.stillStored?Lt(`track`,e.trackId):void 0);return r(`li`,{className:`flex items-center gap-2 text-xs`,children:[u(`input`,{type:`checkbox`,"aria-label":`select ${e.trackId}`,checked:n,onChange:i}),a===null?u(`div`,{className:`h-10 w-10 rounded bg-surface-hover`}):u(`img`,{src:a,alt:e.trackId,className:`h-10 w-10 rounded object-cover`}),u(`span`,{className:`font-mono`,children:e.trackId}),u(`span`,{children:e.cls}),r(`span`,{className:`text-foreground-subtle`,children:[ai(e.firstT),` → `,ai(e.lastT),` · `,String(e.boundFrames),` `,`frames`]}),!e.stillStored&&u(`span`,{className:`text-foreground-subtle`,children:`not stored — marked through the tape`}),t.map(e=>u(x,{variant:`info`,children:e},e))]})}n();var ui=`camstack_admin_token`;function di(){let e=m();return(t,n)=>e.trpcClient.addons.custom.mutate({addonId:Br,action:t,input:n})}async function fi(e,t){let n=localStorage.getItem(ui),r={};n!==null&&(r.Authorization=`Bearer ${n}`);let i=await fetch(or(e),{headers:r});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(Rr(i.status,e))}let a=await i.blob(),o=i.headers.get(`content-disposition`),s=(o===null?null:/filename="?([^";]+)"?/i.exec(o))?.[1]?.trim()??t,c=URL.createObjectURL(a),l=document.createElement(`a`);l.href=c,l.download=s,l.click(),setTimeout(()=>URL.revokeObjectURL(c),6e4)}function pi(){let[e,t]=l(!1);return u(xe,{expanded:e,onExpandedChange:t,header:u(`span`,{className:`text-sm font-medium text-foreground`,children:`Tracking tapes`}),children:u(mi,{})})}function mi(){let e=di(),t=et({isCamera:!0,projection:`slim`}),n=a(()=>{let e=new Map;for(let n of t.data??[])e.set(n.id,n.name);return t=>e.get(t)??`Camera ${String(t)}`},[t.data]),i=o({queryKey:[`events-debug`,`tapes`,`status`],queryFn:async()=>mr(await e(nr.status,{}))}),s=o({queryKey:[`events-debug`,`tapes`,`list`],queryFn:async()=>gr(await e(nr.list,{}))}),[c,d]=l(null),[f,p]=l(null),m=async e=>{p(null);try{await fi(e.id,`${e.scenario}.tape-bundle.json.gz`)}catch(e){p(cr(e))}},h=async t=>{let n=br(await e(nr.release,{tapeId:t.id}));if(n===null)throw Error(sr);let r=Sr(n);if(r!==null)throw Error(r);await s.refetch()},g=async t=>{let n=xr(await e(nr.remove,{tapeId:t.id}));if(n===null)throw Error(sr);let r=Sr(n);if(r!==null)throw Error(r);await s.refetch()};return r(`div`,{className:`space-y-3`,children:[r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A camera records while its `,u(`strong`,{children:`Record the track history`}),` switch (camera settings → Tracking) is on; segments are kept 24 h. Promote a window worth keeping, label it in the review, mark it reviewed, download it and turn it into a test case with`,` `,u(`code`,{children:`npm run tracking-bench -- case`}),`.`]}),f!==null&&u(J,{message:f}),i.isLoading&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading camera status…`}),i.data===null&&u(J,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[u(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[u(`th`,{children:`Camera`}),u(`th`,{children:`State`}),u(`th`,{children:`Frames/min`}),u(`th`,{children:`Last hour`}),u(`th`,{children:`Held`}),u(`th`,{children:`Gaps`})]})}),u(`tbody`,{children:(i.data??[]).map(e=>r(`tr`,{children:[u(`td`,{children:n(e.deviceId)}),u(`td`,{children:u(x,{variant:e.state===`recording`?`success`:e.state===`off`?`default`:e.state===`unknown`?`warning`:`danger`,children:jr(e)})}),u(`td`,{children:e.framesPerMin===void 0?`—`:String(Math.round(e.framesPerMin))}),u(`td`,{title:e.shelfError,children:Ir(e.bytesLastHour)}),r(`td`,{title:e.shelfError,children:[Lr(e.segmentsHeld),` seg · `,Ir(e.bytesHeld)]}),u(`td`,{children:String(e.gapsSinceArmed)})]},e.deviceId))})]}),u(zr,{cameras:Dr(i.data??[]).map(e=>({value:String(e.deviceId),label:e.segmentsUnknown?`${n(e.deviceId)} (segments unknown)`:n(e.deviceId)})),call:e,onPromoted:()=>void s.refetch()}),s.isLoading&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading promoted tapes…`}),s.data===null&&u(J,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[u(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[u(`th`,{children:`Scenario`}),u(`th`,{children:`Camera`}),u(`th`,{children:`Window`}),u(`th`,{children:`State`}),u(`th`,{children:`Tracks`}),u(`th`,{})]})}),u(`tbody`,{children:(s.data??[]).map(e=>r(`tr`,{children:[u(`td`,{children:e.scenario}),u(`td`,{children:n(e.deviceId)}),r(`td`,{children:[new Date(e.fromMs).toLocaleString(),` · `,ai(e.toMs-e.fromMs),` `,`· `,e.lighting]}),r(`td`,{children:[u(x,{variant:e.state===`complete`?`success`:`warning`,children:e.state}),` `,e.reviewed&&u(x,{variant:`info`,children:`reviewed`}),` `,e.released&&u(x,{children:`released`})]}),r(`td`,{children:[String(e.tracksStillStored),`/`,String(e.tracks.length),` stored`]}),r(`td`,{className:`space-x-1 text-right`,children:[u(q,{variant:`secondary`,"aria-label":`Review ${e.scenario}`,onClick:()=>d(e.id),children:`Review`}),u(q,{variant:`ghost`,"aria-label":`Download ${e.scenario}`,onClick:()=>void m(e),children:u(Ee,{className:`h-3.5 w-3.5`})}),u(Ue,{label:`Release`,icon:pe,title:`Release ${e.scenario}?`,description:`Releasing returns this tape's pinned tracks to ordinary retention — they can be pruned from then on. The promoted bundle itself is kept until deleted.`,confirmLabel:`Release`,triggerVariant:`ghost`,confirmVariant:`danger`,disabled:e.released,action:()=>h(e)}),u(Ue,{label:`Delete`,icon:y,title:`Delete ${e.scenario}?`,description:`Deleting removes the promoted bundle and its index row for good. Its tracks' pins are released first — this cannot be undone.`,confirmLabel:`Delete`,triggerVariant:`ghost`,confirmVariant:`danger`,action:()=>g(e)})]})]},e.id))})]}),c!==null&&u(ci,{tapeId:c,call:e,onClose:()=>d(null),onChanged:()=>void s.refetch()})]})}n();var hi=`all`,gi=`The server answered in a shape this build does not understand.`,_i={error:`danger`,warn:`warning`,info:`info`};function vi({findings:e}){return e.length===0?u(x,{variant:`success`,children:`no anomaly found`}):u(`div`,{className:`flex flex-wrap gap-1`,children:ri(e).map(e=>u(x,{variant:_i[e.severity],title:e.detail,children:ti(e.code)},e.code))})}function yi({track:e,report:t,analyzing:n}){let i=hn(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(vi,{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 bi(){let e=m(),[t,n]=l(hi),[i,s]=l(!1),[c,d]=l(null),[f,p]=l(new Set),[h,g]=l(null),[_,v]=l(null),[y,b]=l(null),[x,S]=l([]),C=Nn(),w=et({isCamera:!0,projection:`slim`}),T=a(()=>[{value:hi,label:`All cameras`},...(w.data??[]).map(e=>({value:String(e.id),label:e.name}))],[w.data]),E=a(()=>{let e=new Map;for(let t of w.data??[])e.set(t.id,t.name);return e},[w.data]),D=e=>E.get(e)??`Camera ${String(e)}`,O=a(()=>t===hi?[]:[Number.parseInt(t,10)],[t]),k=o({queryKey:[`events-debug`,`list`,O],queryFn:async()=>Qr(await e.trpcClient.addons.custom.mutate({addonId:Br,action:Vr,input:O.length===0?{}:{deviceIds:O}}))}),A=a(()=>(k.data?.tracks??[]).map(e=>e.trackId),[k.data]),j=o({queryKey:[`events-debug`,`analyze`,A],enabled:A.length>0,queryFn:async()=>$r(await e.trpcClient.addons.custom.mutate({addonId:Br,action:Hr,input:{trackIds:A}}))}),M=a(()=>{let e=new Map;for(let t of j.data?.reports??[])e.set(t.trackId,t);return e},[j.data]),N=k.data?.tracks??[],F=k.data===null||j.data===null,I=()=>{k.refetch(),j.refetch()},L=e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},R=()=>{p(new Set(N.map(e=>oi(e.deviceId,e.trackId))))},z=()=>p(new Set),B=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}},V=e=>{if(!An||_!==null)return;let t=si(N,f);t.length!==0&&(v(e),b(null),(async()=>{let n=await B(e,t);v(null);let r=new Set(n.refused);p(new Set(t.filter(e=>r.has(e.trackId)).map(e=>oi(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.`),k.refetch()})())},ee=()=>{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([]),k.refetch()})())},U=async()=>{s(!0),d(null);try{await zt(ii(O),`camstack-debug.zip`)}catch(e){d(e instanceof Error?e.message:`Export failed.`)}finally{s(!1)}},K=_!==null;return u(Ft,{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(H,{value:t,options:T,onChange:e=>n(e.target.value)})}),r(q,{variant:`secondary`,onClick:I,disabled:k.isFetching,children:[k.isFetching?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(se,{className:`h-3.5 w-3.5`}),`Refresh`]}),r(q,{onClick:()=>void U(),disabled:i||N.length===0,children:[i?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(Ee,{className:`h-3.5 w-3.5`}),`Export all (`,String(N.length),`)`]}),N.length>0&&f.size<N.length&&u(q,{variant:`ghost`,onClick:R,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.`]}),u(pi,{}),k.isError&&u(J,{message:`Could not load the marked tracks.`}),F&&!k.isError&&u(J,{message:gi}),c!==null&&u(J,{message:c}),y!==null&&u(J,{message:y}),k.data?.truncated===!0&&u(J,{message:`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`}),(j.data?.vanished.length??0)>0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:[String(j.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:An?void 0:`Track flags arrive with the next server update`,children:r(q,{variant:`secondary`,onClick:()=>V(`keep`),disabled:!An||K,children:[_===`keep`?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(Ae,{className:`h-3.5 w-3.5`}),` `,`Keep`]})}),u(`span`,{title:An?void 0:`Track flags arrive with the next server update`,children:r(q,{onClick:()=>V(`analyzed`),disabled:!An||K,children:[_===`analyzed`?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(W,{className:`h-3.5 w-3.5`}),` `,`Analyzed`]})}),u(q,{variant:`ghost`,onClick:z,disabled:K,children:u(He,{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(q,{variant:`ghost`,onClick:ee,disabled:K,children:[u(ge,{className:`h-3.5 w-3.5`}),` Undo`]}),u(q,{variant:`ghost`,onClick:()=>S([]),disabled:K,children:u(He,{className:`h-3.5 w-3.5`})})]}),k.isLoading?u(G,{children:u(`div`,{className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`Loading…`})}):N.length===0?u(G,{children:r(`div`,{className:`flex flex-col items-center gap-2 px-3 py-8 text-center`,children:[u(Be,{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:N.map(e=>{let t=M.get(e.trackId);return u(_n,{row:e,cameraName:D(e.deviceId),nowMs:e.lastSeen,selected:f.has(oi(e.deviceId,e.trackId)),onToggleSelect:L,onOpenDetail:g,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:u(yi,{track:e,report:t,analyzing:j.isFetching})},oi(e.deviceId,e.trackId))})}),h&&u(tr,{row:h,cameraName:D(h.deviceId),deleteAvailable:Wn,onClose:()=>g(null),onDeleted:()=>{g(null),k.refetch()},onFlagsChanged:e=>{e.debug||(g(null),k.refetch())}})]})})}var xi=200,Si=3e4,Ci=[];function wi(e){let t=m(),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:Si,refetchInterval:Si,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:r,since:e.since,until:e.until,limit:xi,...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:an(rn(i??Ci),`importance`),isLoading:n&&a}}n();var Ti=[`events-feed`],Ei=2e3;function Di(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:Ti})},[]),p=t(void 0);p.current||=At({delayMs:Ei,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 k(Mt.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),k(Mt.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:s,refreshNow:m}}n();function Oi({groups:e,selected:t,onChange:n,loading:i=!1}){let{t:o}=Nt(),[s,c]=l(!1),[d,f]=l(``),[p,m]=l(new Set),h=d.trim().toLowerCase(),g=e=>h.length===0||ye(e,o).toLowerCase().includes(h),y=a(()=>e.map(e=>({macro:e.macro,subs:e.subs.filter(t=>g(t)||g(e.macro))})).filter(e=>g(e.macro)||e.subs.length>0),[e,h]),b=e=>m(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(be,{className:`h-3.5 w-3.5`}),w>0?`Kinds (${String(w)})`:`Kinds`,u(_,{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(Ie,{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…`:h.length>0?`No kind matches that search.`:`These cameras advertise no event kinds.`}),y.map(e=>{let n=ie(e.macro.iconId),i=p.has(e.macro.kind)||h.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?_: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:ye(e.macro,o)})]})]}),i&&e.subs.map(e=>{let n=ie(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:ye(e,o)})]},e.kind)})]},e.macro.kind)})]})]})}function ki(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 Ai(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var ji=new Set([`detection`,`package`]);function Mi(e,t){return[...ki(e,t).values()].filter(e=>e.parentKind===null&&ji.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function Ni(e,t){let n=ki(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,Ai(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 Pi(){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 Fi=[`events-feed`],Ii=60,Li=[{value:`importance`,label:`Importance`,icon:Ut},{value:`time`,label:`Recent`,icon:ct}];function Ri(){let e=c(),t=me(),n=M(),[i,o]=l(kt),[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:D,until:O}=a(()=>ln({fromMs:i.fromMs,toMs:i.toMs},T),[i.fromMs,i.toMs,T]),k=Pi(),{pending:A,refreshNow:j}=Di({paused:C!==null||x.size>0||k.scrolledPast}),{data:N=[]}=et({isCamera:!0,projection:`slim`}),F=a(()=>N.map(e=>e.id),[N]),{data:I,isLoading:L}=Re({deviceIds:F},{enabled:F.length>0,staleTime:5*6e4}),R=a(()=>Ni(I??[],f),[I,f]),z=qn(),B=z.isPending,{rows:V,isLoading:ee}=wi({deviceIds:F,since:D,until:O,minImportance:g>0?g:void 0,classFilter:m.size===1?[...m][0]:void 0}),H=a(()=>{let e=new Map;for(let t of N??[])e.set(t.id,t.name);return e},[N]),U=e=>H.get(e)??`Camera #${String(e)}`,W=a(()=>bt(V).map(e=>({id:e,name:U(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[V,H]),G=a(()=>an(on(V,{cameras:f,classes:m,minImportance:g}),v),[V,f,m,g,v]),K=Et(G,Ii,a(()=>JSON.stringify([[...f].sort((e,t)=>e-t),[...m].sort(),g,v,D,O]),[f,m,g,v,D,O])),te=()=>{e.invalidateQueries({queryKey:Fi})},ne=()=>S(new Set);function re(e){S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function ie(){if(x.size===0||!Wn)return;let e=cn(V,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`})&&ae(e)})()}function ae(e){let n=[...e];Promise.allSettled(n.map(([e,t])=>z.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{te();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(sn(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=>U(e)).join(`, `)}. They remain selected — retry, or check the server logs.`,variant:`danger`})})}let oe=G.length!==V.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(Ot,{onChange:o}),u(Ct,{cameras:W,selected:f,onChange:p}),u(Oi,{groups:R,selected:m,onChange:h,loading:L}),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:Li.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)})}),!ee&&u(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:oe?`${String(G.length)} of ${String(V.length)} events`:`${String(G.length)} event${G.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:Wn?void 0:`Track deletion arrives with the next server update`,children:r(q,{variant:`secondary`,onClick:ie,disabled:!Wn||B,children:[B?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),u(q,{variant:`ghost`,onClick:ne,disabled:B,children:u(He,{className:`h-3.5 w-3.5`})})]})]}),ee&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(P,{className:`h-4 w-4 animate-spin`}),` Loading events…`]}),!ee&&G.length===0&&u(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:`No key events in this window.`}),A&&u(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:u(`button`,{type:`button`,onClick:j,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`})}),!ee&&G.length>0&&r(s,{children:[u(`div`,{ref:k.ref,"aria-hidden":!0,className:`h-0`}),u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:K.pageItems.map(e=>u(_n,{row:e,cameraName:U(e.deviceId),nowMs:T,selected:x.has(sn(e.deviceId,e.trackId)),onToggleSelect:re,onOpenDetail:w},sn(e.deviceId,e.trackId)))}),u(yt,{currentPage:K.page,totalItems:K.totalItems,pageSize:K.pageSize,onPageChange:K.setPage,itemNoun:`events`})]}),C&&u(tr,{row:C,cameraName:U(C.deviceId),deleteAvailable:Wn,onClose:()=>w(null),onDeleted:()=>{te(),w(null)},onFlagsChanged:e=>{w(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}n();var zi=50,Bi=350,Vi=[{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 Hi(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 Ui({onActiveChange:e}){let[t,n]=l(``),[i,o]=l(`loose`),[s,c]=l(null),[f,p]=l(null),[m,h]=l(null),g=Ye(t,Bi).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=[]}=et({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}=Re({deviceIds:C},{enabled:C.length>0,staleTime:5*6e4}),T=a(()=>Mi(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:D,isError:O,error:k}=U({text:g,strictness:i,limit:zi,classFilter:s??void 0,deviceId:f??void 0},{enabled:_}),A=a(()=>[...E??[]].sort((e,t)=>t.score-e.score).map(e=>({...Hi(e),score:e.score})),[E]);function j(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(Ie,{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(He,{className:`h-3.5 w-3.5`})})]}),D&&_&&u(P,{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:()=>j(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:ye(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:Vi.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))})]}),_&&!D&&!O&&r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[A.length,` match`,A.length===1?``:`es`]})]})]}),_&&r(`div`,{className:`space-y-3`,children:[O&&r(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,k instanceof Error?k.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!O&&D&&A.length===0&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(P,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!O&&!D&&A.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.`]}),!O&&A.length>0&&u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:A.map(e=>u(_n,{row:e,cameraName:S(e.deviceId),nowMs:v,score:e.score,onOpenDetail:h},e.id))})]}),m&&u(tr,{row:m,cameraName:S(m.deviceId),deleteAvailable:Wn,onClose:()=>h(null),onDeleted:()=>h(null)})]})}n();function Wi(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 Gi({row:e,cameraName:t,nowMs:n}){let i=It(e.keyFrameMediaId===void 0?void 0:Rt(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($t,{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 `,Wi(n,e.becameStationaryAt)]})]})]})}function Ki(){let[e,t]=l(!1),n=Date.now(),{data:i=[]}=et({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}=Bt(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?_:v,{className:`h-4 w-4 text-foreground-subtle`}),u($t,{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(Gi,{row:e,cameraName:s.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:n},e.id))})]})}n();function qi(){let[e,t]=l(!1);return u(Ft,{children:r(`section`,{className:`space-y-3`,children:[u(Ui,{onActiveChange:t}),!e&&u(Ki,{}),!e&&u(Ri,{})]})})}n();function Ji({frameId:e,onAdded:t}){let n=Me(),[i,a]=l(null),[o,s]=l(null),c=async()=>{if(i===null)return;let r=await n.mutateAsync({collectionId:i,frameIds:[e]});s(r.added>0?`Added.`:r.alreadyMember>0?`Already in that collection.`:`That frame or collection no longer exists.`),await t()};return r(B,{children:[r(R,{className:`mt-1 flex items-center gap-1 text-foreground-muted hover:text-foreground`,"aria-label":`Add this frame to a collection`,children:[u(qt,{className:`h-3 w-3`}),`collection`]}),r(Qe,{className:`w-72 space-y-2 p-3`,children:[u(lt,{value:i,onChange:a}),r(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:o}),u(q,{size:`sm`,disabled:i===null||n.isPending,onClick:()=>void c(),children:`Add`})]})]})]})}function Yi(e){let t=e.capturedAt??e.copiedAt;return new Date(t).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Xi({frames:e,isLoading:t,activeFrameId:n,deviceNames:i,onOpen:a,onRemove:o}){return e.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t?`Reading the collection…`:`This collection is empty. Add frames with "Send frame to training" on a camera’s recording timeline, or "Add to collection" on a track’s copied frame.`}):u(`ul`,{className:`flex flex-wrap gap-2`,children:e.map(e=>u(`li`,{children:r(`div`,{className:`rounded-md border px-2 py-1.5 text-[11px] flex items-start gap-1.5 ${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:()=>{a(e.frameId)},children:[e.origin===`recording`?u(ze,{className:`h-3 w-3 text-info`,"aria-label":`From the recording`}):u(Yt,{className:`h-3 w-3 text-success`,"aria-label":`From a track`}),u(`span`,{className:`font-medium text-foreground`,children:i.get(e.deviceId)??`Camera ${String(e.deviceId)}`}),u(`span`,{className:`text-foreground-subtle`,children:Yi(e)}),e.complete&&u(x,{variant:`success`,children:`complete`})]}),u(`button`,{type:`button`,"aria-label":`Remove from this collection`,title:e.origin===`recording`?`Remove from this collection. If no other collection holds it, the frame and its boxes leave the dataset.`:`Remove from this collection. The frame stays in the dataset with its track.`,className:`text-foreground-muted hover:text-danger`,onClick:()=>{o(e)},children:u(He,{className:`h-3 w-3`})})]})},e.frameId))})}n();function Zi({collections:e,isLoading:t,selectedId:n,onSelect:i,onCreate:a,onRename:o,onDelete:c}){let[d,f]=l(``),[p,m]=l(null),[h,g]=l(null),_=async()=>{let e=await a(d);m(e),e===null&&f(``)},v=async()=>{if(h===null)return;let e=await o(h.id,h.name);m(e),e===null&&g(null)};return r(`div`,{className:`divide-y divide-border`,children:[r(`div`,{className:`p-2 space-y-1.5`,children:[r(`div`,{className:`flex items-center gap-1.5`,children:[u(Y,{className:`flex-1`,"aria-label":`New collection name`,placeholder:`New collection`,value:d,onChange:e=>{f(e.target.value)}}),u(q,{size:`sm`,disabled:d.trim()===``,onClick:()=>void _(),children:`Create`})]}),p!==null&&u(`p`,{className:`text-[11px] text-danger`,children:p})]}),e.length===0?u(`p`,{className:`p-3 text-[11px] text-foreground-subtle`,children:t?`Reading the collections…`:`No collection yet. Create one here, or use "Send frame to training" on a camera’s recording timeline.`}):u(`ul`,{className:`divide-y divide-border`,children:e.map(e=>u(`li`,{className:`px-3 py-2 flex items-center gap-2 text-xs ${e.id===n?`bg-surface-hover`:``}`,children:h?.id===e.id?r(s,{children:[u(Y,{className:`flex-1`,"aria-label":`Collection name`,value:h.name,onChange:t=>{g({id:e.id,name:t.target.value})}}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Save the name`,onClick:()=>void v(),children:u(W,{className:`h-3 w-3`})}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Cancel renaming`,onClick:()=>{g(null)},children:u(He,{className:`h-3 w-3`})})]}):r(s,{children:[u(`button`,{type:`button`,className:`flex-1 min-w-0 text-left truncate text-foreground`,onClick:()=>{i(e)},children:e.name}),u(x,{children:e.frameCount}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Rename ${e.name}`,onClick:()=>{g({id:e.id,name:e.name})},children:u(S,{className:`h-3 w-3`})}),u(Ue,{label:`Delete`,icon:y,triggerVariant:`ghost`,size:`sm`,title:`Delete "${e.name}"?`,description:`Frames taken from the recording that are in no other collection are deleted with their boxes. Frames copied from tracks stay in the dataset.`,confirmLabel:`Delete`,confirmVariant:`danger`,action:()=>c(e.id)})]})},e.id))})]})}n();var Qi={"empty-name":`Give the version a name.`,"duplicate-name":`A version with that name already exists.`,"no-frames":`This selection holds no annotated or complete frame — nothing to freeze.`},$i=e=>`${String(Math.round(e*100))}%`;function ea(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function ta({on:e,label:t,onClick:n}){return u(`button`,{type:`button`,"aria-pressed":e,className:`rounded-full border px-2 py-0.5 text-[11px] ${e?`border-primary text-primary`:`border-border text-foreground-muted hover:text-foreground`}`,onClick:n,children:t})}function na({stats:e,deviceNames:t}){let n=e=>t.get(e)??`Camera ${String(e)}`;return r(`div`,{className:`space-y-2`,"data-testid":`retrain-dataset-stats`,children:[r(`div`,{className:`flex flex-wrap gap-1.5 text-[11px]`,children:[r(x,{children:[e.frames,` frames`]}),r(x,{variant:e.completeness>=.9?`success`:`warning`,children:[$i(e.completeness),` complete (`,e.completeFrames,`)`]}),r(x,{children:[e.subjects,` boxes`]}),r(x,{variant:`danger`,children:[e.modelErrors,` model errors`]}),r(x,{variant:`info`,children:[e.hardNegatives,` hard negatives`]}),e.cameras.map(e=>r(x,{children:[n(e.deviceId),`: `,e.frames,` ·`,` `,$i(e.frames>0?e.completeFrames/e.frames:0),` complete`]},e.deviceId))]}),u(j,{columns:[{key:`class`,header:`Class`,render:e=>e.macroClass,sortValue:e=>e.macroClass},{key:`camera`,header:`Camera`,render:e=>n(e.deviceId),sortValue:e=>n(e.deviceId)},{key:`light`,header:`Light`,render:e=>e.lighting,sortValue:e=>e.lighting},{key:`subjects`,header:`Boxes`,align:`right`,render:e=>e.subjects,sortValue:e=>e.subjects},{key:`frames`,header:`Frames`,align:`right`,render:e=>e.frames,sortValue:e=>e.frames}],rows:e.cells,rowKey:e=>`${e.macroClass}-${String(e.deviceId)}-${e.lighting}`,emptyMessage:`No box in this selection.`,minWidthPx:360})]})}function ra({id:e}){let[t,n]=l(!1),i=V({id:e},{enabled:t});return t?i.data===void 0?u(P,{className:`h-3 w-3 animate-spin`}):i.data.matches?u(x,{variant:`success`,children:`unchanged`}):r(x,{variant:`warning`,children:[`changed`,i.data.missingFrames>0?` · ${String(i.data.missingFrames)} missing`:``]}):r(q,{variant:`ghost`,size:`sm`,onClick:()=>n(!0),children:[u(at,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Verify`})]})}function ia({deviceNames:e,collections:t,pickedFrameIds:n,onClearPicked:i}){let a=c(),o=m(),[s,d]=l([]),[f,h]=l([]),[g,_]=l(!1),[v,b]=l(!1),[S,C]=l(`frames`),[w,T]=l(``),[E,D]=l(null),[k,A]=l(null),M={...s.length>0?{deviceIds:[...s]}:{},...f.length>0?{collectionIds:[...f]}:{},...g&&n.length>0?{frameIds:[...n]}:{}},N=O({selection:M,completeOnly:v}),F=le({}),I=$e(),L=Je(),R=async()=>{D(null);let e=await I.mutateAsync({name:w,selection:M,layout:S,completeOnly:v});if(e.kind===`refused`){D(Qi[e.reason]??e.reason);return}T(``),D(`Version "${e.version.name}" frozen: ${String(e.version.frameCount)} frames.`),await F.refetch()},z=async e=>{A(e.id);try{let{url:t}=await o.trpcClient.pipelineAnalytics.getRetrainExportUrl.query({datasetVersionId:e.id,layout:e.layout});await zt(p(t),`camstack-dataset-${e.name.replace(/[^a-z0-9_-]+/gi,`-`)}.tar`)}catch(e){D(`Download failed: ${e instanceof Error?e.message:String(e)}`)}finally{A(null)}},B=[...e.keys()].toSorted((e,t)=>e-t);return r(`div`,{className:`space-y-3`,children:[r(`div`,{className:`rounded-md border border-border bg-surface p-3 space-y-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground`,children:`New dataset version`}),r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle w-20`,children:`Cameras`}),s.length===0&&u(x,{children:`all`}),B.map(t=>u(ta,{on:s.includes(t),label:e.get(t)??String(t),onClick:()=>d(e=>ea(e,t))},t))]}),r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle w-20`,children:`Collections`}),f.length===0&&u(x,{children:`any frame`}),t.map(e=>u(ta,{on:f.includes(e.id),label:`${e.name} · ${String(e.frameCount)}`,onClick:()=>h(t=>ea(t,e.id))},e.id))]}),r(`div`,{className:`flex flex-wrap items-center gap-3 text-[11px]`,children:[r(`label`,{className:`flex items-center gap-1.5`,children:[u(ae,{"aria-label":`Only the frames picked in the workbench`,checked:g,disabled:n.length===0,onChange:e=>_(e.target.checked)}),`Only the `,n.length,` picked frame`,n.length===1?``:`s`]}),n.length>0&&u(q,{variant:`ghost`,size:`sm`,onClick:i,children:`Clear picks`}),r(`label`,{className:`flex items-center gap-1.5`,children:[u(ae,{"aria-label":`Only complete frames`,checked:v,onChange:e=>b(e.target.checked)}),`Only frames marked "all subjects boxed"`]}),u(H,{className:`w-36`,"aria-label":`Layout`,value:S,options:[{value:`frames`,label:`Frames (detector)`},{value:`crops`,label:`Frames + crops (classifier)`}],onChange:e=>C(e.target.value===`crops`?`crops`:`frames`)})]}),N.data===void 0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:N.isError?`The selection could not be counted.`:`Counting the selection…`}):u(na,{stats:N.data,deviceNames:e}),r(`div`,{className:`flex items-center gap-2`,children:[u(Y,{className:`flex-1`,"aria-label":`Version name`,placeholder:`Version name (e.g. night person v1)`,value:w,onChange:e=>T(e.target.value)}),u(q,{size:`sm`,disabled:w.trim()===``||I.isPending||(N.data?.frames??0)===0,onClick:()=>void R(),children:`Freeze version`})]}),E!==null&&u(`p`,{className:`text-[11px] text-foreground`,children:E})]}),r(`div`,{className:`rounded-md border border-border bg-surface p-3 space-y-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground`,children:`Versions`}),u(j,{columns:[{key:`name`,header:`Version`,render:e=>e.name,sortValue:e=>e.name},{key:`created`,header:`Frozen`,render:e=>new Date(e.createdAt).toLocaleString(),sortValue:e=>e.createdAt},{key:`frames`,header:`Frames`,align:`right`,render:e=>e.frameCount,sortValue:e=>e.frameCount},{key:`boxes`,header:`Boxes`,align:`right`,render:e=>e.stats.subjects,sortValue:e=>e.stats.subjects},{key:`complete`,header:`Complete`,align:`right`,render:e=>$i(e.stats.completeness),sortValue:e=>e.stats.completeness},{key:`layout`,header:`Layout`,render:e=>e.layout},{key:`hash`,header:`Hash`,render:e=>u(`code`,{title:e.annotationHash,children:e.annotationHash.slice(0,10)})},{key:`actions`,header:``,render:e=>r(`div`,{className:`flex items-center gap-1 justify-end`,children:[u(ra,{id:e.id}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Download ${e.name}`,disabled:k!==null,onClick:()=>void z(e),children:k===e.id?u(P,{className:`h-3 w-3 animate-spin`}):u(Ee,{className:`h-3 w-3`})}),u(Ue,{label:`Delete`,icon:y,triggerVariant:`ghost`,size:`sm`,title:`Delete version "${e.name}"?`,description:`The version's record goes. Its frames stay in the dataset.`,confirmLabel:`Delete`,action:async()=>{await L.mutateAsync({id:e.id}),await a.invalidateQueries()}})]})}],rows:F.data??[],rowKey:e=>e.id,emptyMessage:F.isLoading?`Reading the versions…`:`No version frozen yet.`,minWidthPx:640})]})]})}n();function aa(){let e=Ze({}),t=ht({}),[n,i]=l([]),a=ot(n.length>0?{collectionIds:[...n]}:{}),o=Ge({}),[s,c]=l(null),[d,f]=l(null),m=async(e,t,n)=>{c(e),f(null);try{await zt(p(t),n)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(null)}},h=e.data,g=h!==void 0&&h.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(q,{variant:`secondary`,size:`sm`,disabled:a.data===void 0||s!==null,onClick:()=>{a.data!==void 0&&m(`annotated`,a.data.url,`camstack-retrain-export.tar`)},children:[s===`annotated`?u(P,{className:`h-3 w-3 animate-spin`}):u(Ee,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Annotated dataset`})]}),r(q,{variant:`secondary`,size:`sm`,disabled:o.data===void 0||g||s!==null,onClick:()=>{o.data!==void 0&&m(`marked`,o.data.url,`camstack-training-export.tar`)},children:[s===`marked`?u(P,{className:`h-3 w-3 animate-spin`}):u(Ee,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Marked media`})]})]}),(t.data??[]).length>0&&r(`div`,{className:`flex items-center gap-1.5 flex-wrap text-[11px]`,children:[u(`span`,{className:`text-foreground-subtle`,children:`Annotated dataset from:`}),n.length===0&&u(x,{children:`every collection and track`}),(t.data??[]).map(e=>{let t=n.includes(e.id);return r(`button`,{type:`button`,"aria-pressed":t,className:`rounded-full border px-2 py-0.5 ${t?`border-primary text-primary`:`border-border text-foreground-muted hover:text-foreground`}`,onClick:()=>{i(n=>t?n.filter(t=>t!==e.id):[...n,e.id])},children:[e.name,` · `,e.frameCount]},e.id)})]}),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.`:h===void 0?`Measuring the marked set…`:g?`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(h.trackCount)} marked track${h.trackCount===1?``:`s`} · ${String(h.fileCount)} file${h.fileCount===1?``:`s`} · ${Ht(h.byteCount)}${h.truncated?` · more marked tracks exist than one pass carries`:``}`}),(a.isError||o.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.`}),d!==null&&r(`p`,{className:`text-[11px] text-danger`,children:[`Download failed: `,d]})]})}function oa(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.round(e/1e3)} KB`}function sa({candidates:e,copies:t,activeFrameId:n,refusals:i,isSelecting:a,onSelectCandidate:o,onOpenCopy:s,onRemoveCopy:c,renderCopyActions:l}){let d=new Set(t.map(e=>e.sourceMediaId)),f=e.filter(e=>!d.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(W,{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,` · `,oa(e.sizeBytes)]}),e.complete&&u(x,{variant:`success`,children:`complete`})]}),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`]}),l?.(e)]})},e.frameId))})]}),r(`section`,{children:[r(`h3`,{className:`text-xs font-semibold text-foreground mb-1.5`,children:[`Available frames (`,f.length,`)`]}),f.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:f.map(e=>{let t=i.get(e.mediaId);return r(`li`,{children:[r(q,{variant:`secondary`,size:`sm`,disabled:a||t!==void 0,onClick:()=>{o(e.mediaId)},children:[a?u(P,{className:`h-3 w-3 animate-spin`}):u(t===void 0?Kt:g,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:e.kind}),u(`span`,{className:`ml-1 text-foreground-subtle`,children:oa(e.sizeBytes)})]}),t!==void 0&&u(x,{variant:`danger`,className:`ml-1`,children:t})]},e.mediaId)})})]})]})}function ca(e){return e.frameCount===0?`untouched`:e.annotationCount===0?`started`:`ready`}var la={untouched:{icon:Gt,label:`to do`,variant:`default`},started:{icon:Wt,label:`frames only`,variant:`info`},ready:{icon:w,label:`annotated`,variant:`success`}};function ua(e){return new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}function da({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(P,{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=la[ca(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(x,{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)}`,` ·`,` `,ua(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)})})}function fa(e){return{deviceId:e.deviceId,...e.trackId===void 0?{}:{trackId:e.trackId},frameId:e.frameId}}var pa=`object-detection`;function ma(e,t){for(let n of e){if(n.addonId===t)return n;let e=n.children===void 0?void 0:ma(n.children,t);if(e!==void 0)return e}}function ha(e,t){for(let n of e.slots){let e=n.addons.find(e=>e.id===t);if(e!==void 0)return e}}function ga(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=ha(r,pa);if(s===void 0)return{kind:`unknown`,gap:`step-unknown`};let c=qe({catalog:s,device:o,override:ma(i,pa)?.modelId,base:o.steps?.[pa]?.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}}function _a(e,t){let n=Math.max(0,Math.min(e.x+e.w,t.x+t.w)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.h,t.y+t.h)-Math.max(e.y,t.y)),r=e.w*e.h+t.w*t.h-n;return r>0?n/r:0}function va(e,t){let n=e.nextKey;return{boxes:t.map(e=>{let t=`b${String(n)}`;return n+=1,{...e,key:t}}),nextKey:n}}function ya(e){return{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},draft:!1}}function ba(e){return e.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},...e.subLabel===void 0?{}:{subLabel:e.subLabel},kind:`subject`,source:`pipeline`,...e.modelId===void 0?{}:{assistModelId:e.modelId},...e.score===void 0?{}:{assistScore:e.score},draft:!0,note:e.basis===`subject-box`?`The box the pipeline recorded on this very frame.`:`The pipeline's track position ${String(Math.round(e.deltaMs))} ms from this frame.`}))}var xa={boxes:[],selectedKey:null,nextKey:0};function Sa(e,t){let n=va(xa,e.map(ya));return Ca({boxes:n.boxes,selectedKey:null,nextKey:n.nextKey},ba(t)).state}function Ca(e,t){let n=[],r=0;for(let i of t){if([...e.boxes,...n].some(e=>_a(e.bbox,i.bbox)>=.8)){r+=1;continue}n.push({...i,draft:!0})}let i=va(e,n);return{state:{...e,boxes:[...e.boxes,...i.boxes],nextKey:i.nextKey},skipped:r}}function wa(e,t,n){let r=va(e,[{bbox:t,macroClass:n,kind:`subject`,source:`operator`,draft:!1}]),i=r.boxes[0];return i===void 0?e:{boxes:[...e.boxes,i],selectedKey:i.key,nextKey:r.nextKey}}function Ta(e,t,n){return{...e,boxes:e.boxes.map(e=>e.key===t?n(e):e)}}function Ea(e,t,n){return Ta(e,t,e=>({...e,...n,draft:!1}))}function Da(e,t){return Ta(e,t,e=>({...e,draft:!1}))}function Oa(e){return{...e,boxes:e.boxes.map(e=>e.draft?{...e,draft:!1}:e)}}function ka(e,t){return Ta(e,t,e=>({...e,kind:e.kind===`model_error`?`subject`:`model_error`,draft:!1}))}function Aa(e,t){return{...e,boxes:e.boxes.filter(e=>e.key!==t),selectedKey:e.selectedKey===t?null:e.selectedKey}}function ja(e,t){return{...e,selectedKey:t}}function Ma(e,t){return{...e,boxes:e.boxes.map(e=>{let n=t.get(e.key);return n===void 0?e:{...e,flag:n}})}}function Na(e,t){return new Map(e.map(e=>[e.ref,{verdict:e.verdict,reason:e.reason,by:t,...e.suggestedClass===void 0?{}:{suggestedClass:e.suggestedClass}}]))}function Pa(e){return e.boxes.filter(e=>e.draft).length}function Fa(e){let t=e?.trim();return t===void 0||t===``?void 0:t}function Ia(e){return e.boxes.filter(e=>!e.draft).map(e=>{let t=Fa(e.label),n=Fa(e.subLabel);return{bbox:e.bbox,macroClass:e.macroClass,...t===void 0?{}:{label:t},...n===void 0?{}:{subLabel:n},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}})}var La=[`person`,`vehicle`,`animal`,`package`,`face`,`plate`],Ra=new Set(La),za={operator:`drawn`,pipeline:`pipeline`,assist:`detector`,llm:`AI vision`};function Ba(e){let t=e?.trim().toLowerCase();return t===void 0||t===``?null:Ra.has(t)?`"${t}" is a macro class, not a label — person / postman / Marco are three different tiers`:null}function Va(e){if(e.source===`operator`)return null;let t=[za[e.source]];return e.assistModelId!==void 0&&t.push(e.assistModelId),e.assistScore!==void 0&&t.push(e.assistScore.toFixed(2)),t.join(` · `)}function Ha({boxes:e,selectedKey:t,onSelect:n,onChange:i,onAccept:a,onToggleModelError:o,onDelete:s}){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 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=>{let c=e.key===t,l=Ba(e.label),d=Ba(e.subLabel),f=Va(e);return r(`li`,{"data-testid":`retrain-row-${e.key}`,className:`p-2.5 space-y-1.5 ${c?`bg-surface-hover`:``}`,onFocus:()=>{n(e.key)},onClick:()=>{n(e.key)},children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(H,{className:`w-28`,"aria-label":`Class`,value:e.macroClass,options:La.map(e=>({value:e,label:e})),onChange:t=>{let n=La.find(e=>e===t.target.value);n!==void 0&&i(e.key,{macroClass:n})}}),e.draft&&u(x,{variant:`warning`,children:`draft`}),e.kind===`model_error`&&u(x,{variant:`danger`,children:`model error`}),f!==null&&u(x,{variant:`info`,children:f}),(e.note!==void 0||e.flag!==void 0)&&r(st,{children:[u(Pe,{children:u(L,{className:`h-3.5 w-3.5 ${e.flag!==void 0&&e.flag.verdict!==`confirmed`?`text-warning`:`text-foreground-subtle`}`,"aria-label":`Why this box is here`})}),r(Oe,{className:`whitespace-normal w-64 text-left`,children:[e.note!==void 0&&u(`p`,{children:e.note}),e.flag!==void 0&&r(`p`,{children:[e.flag.by,`: `,e.flag.verdict,e.flag.suggestedClass===void 0?``:` (suggests ${e.flag.suggestedClass})`,` `,`— `,e.flag.reason]})]})]}),u(`span`,{className:`flex-1`}),e.draft&&u(q,{variant:`secondary`,size:`sm`,"aria-label":`Accept this proposal`,onClick:()=>{a(e.key)},children:u(W,{className:`h-3 w-3`})}),u(q,{variant:`ghost`,size:`sm`,"aria-label":e.kind===`model_error`?`This is a real subject`:`Mark as model error`,onClick:()=>{o(e.key)},children:u(fe,{className:`h-3 w-3`})}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Delete this subject`,onClick:()=>{s(e.key)},children:u(y,{className:`h-3 w-3`})})]}),r(`div`,{className:`flex items-center gap-2`,children:[u(Y,{className:`flex-1`,placeholder:`label (postman, van, cat…)`,value:e.label??``,onChange:t=>{i(e.key,{label:t.target.value})}}),u(Y,{className:`flex-1`,placeholder:`sub-label (a name, a plate…)`,value:e.subLabel??``,onChange:t=>{i(e.key,{subLabel:t.target.value})}})]}),l!==null&&u(`p`,{className:`text-[11px] text-danger`,children:l}),d!==null&&u(`p`,{className:`text-[11px] text-danger`,children:d})]},e.key)})})}function Ua(e){return e.filter(e=>!e.draft).every(e=>Ba(e.label)===null&&Ba(e.subLabel)===null&&Ra.has(e.macroClass))}var Wa=.25;function Ga(e,t){if(e===void 0)return[];let n=e.selectedEngine.format,r=e.slots.flatMap(e=>e.addons).find(e=>e.id===pa);if(r===void 0)return[];let i=r.models.filter(e=>e.legacy!==!0&&e.provider===void 0).flatMap(e=>{let t=e.formats[n];return t===void 0?[]:[{modelId:e.id,name:e.name,sizeMB:t.sizeMB??0}]}),a=i.find(e=>e.modelId===t);return i.filter(e=>e.modelId!==t&&(a===void 0||e.sizeMB>a.sizeMB)).toSorted((e,t)=>t.sizeMB-e.sizeMB)}n();var Ka=[{value:`teacher`,label:`Bigger detector`},{value:`llm`,label:`AI vision`},{value:`both`,label:`Both`}],qa=[`person`,`vehicle`,`animal`,`package`],Ja=[`person`,`vehicle`,`animal`,`package`,`face`,`plate`],Ya={"unknown-frame":`The frame is no longer in the dataset.`,"unreadable-frame":`The frame copy could not be read.`,"unknown-profile":`That AI profile no longer exists.`,"profile-disabled":`That AI profile is disabled.`,"no-vision":`That AI profile cannot read images.`,"cloud-not-confirmed":`The frame was not sent: sending it outside the house needs your confirmation.`,"llm-error":`The AI model call failed.`,"malformed-answer":`The AI answered in a shape that cannot be trusted, so nothing was drawn.`};function Xa({frame:e,history:n,detector:i,schema:o,setNotice:s}){let c=_t({},{retry:!1}),d=D(),f=K(),[p,m]=l(`teacher`),h=a(()=>Ga(o,i.kind===`resolved`?i.modelId:void 0),[o,i]),[g,_]=l(null),v=h.find(e=>e.modelId===g)??h[0],[y,b]=l(Wa),[x,S]=l(null),C=(c.data??[]).find(e=>e.id===x)??c.data?.[0],[w,E]=l(qa),[O,k]=l(!1),[A,j]=l(!1),M=t(n.editor);M.current=n.editor;let N=p!==`llm`,F=p!==`teacher`,I=i.kind===`resolved`&&v!==void 0,L=C!==void 0&&w.length>0,R=(!N||I)&&(!F||L),z=async()=>{if(i.kind!==`resolved`||v===void 0)return``;let t=await d.mutateAsync({...fa(e),subject:{kind:`objects`,modelId:v.modelId,minScore:y},nodeId:i.nodeId});if(t.kind===`refused`)return`${v.name} refused: ${t.reason}${t.detail===void 0?``:` — ${t.detail}`}.`;let r=Ca(M.current,t.proposals.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},kind:e.kind,source:`assist`,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore},draft:!0,note:`Proposed by the larger detector ${t.modelId} on ${i.nodeId}.`})));M.current=r.state,n.setEditor(r.state);let a=t.proposals.length-r.skipped;return`${v.name}: ${String(a)} new draft${a===1?``:`s`}${r.skipped>0?`, ${String(r.skipped)} already on the frame`:``}.`},B=async t=>{if(C===void 0)return``;let r=M.current,i=await f.mutateAsync({...fa(e),profileId:C.id,classes:[...w],boxes:r.boxes.slice(0,50).map(e=>({ref:e.key,bbox:e.bbox,macroClass:e.macroClass,...e.label!==void 0&&e.label!==``?{label:e.label}:{}})),allowCloud:t});if(i.kind===`refused`)return`${Ya[i.reason]??i.reason}${i.detail===void 0?``:` (${i.detail})`}`;let a=i.proposals.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},kind:`subject`,source:`llm`,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore},draft:!0,note:`${i.model}: ${e.reason}`})),o=Na(i.reviews,i.model),s=Ca(M.current,a);n.setEditor(e=>Ma(Ca(e,a).state,o));let c=i.proposals.length-s.skipped,l=i.reviews.filter(e=>e.verdict!==`confirmed`).length;return`${C.name}: ${String(c)} new draft${c===1?``:`s`}, ${String(l)} box${l===1?``:`es`} questioned${i.rejected>0?`, ${String(i.rejected)} unusable item${i.rejected===1?``:`s`} dropped`:``}.`},V=async e=>{k(!1),j(!0),s(null);try{let t=[];N&&t.push(await z()),F&&t.push(await B(e)),s(`${t.filter(e=>e!==``).join(` `)} Drafts are not saved until you accept or correct them.`)}catch(e){s(`The assist failed: ${e instanceof Error?e.message:String(e)}`)}finally{j(!1)}};return r(`div`,{className:`px-3 py-2 border-b border-border space-y-2 text-[11px]`,"data-testid":`retrain-assist`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`span`,{className:`font-semibold text-foreground`,children:`Assist`}),u(H,{className:`w-36`,"aria-label":`Assist engine`,value:p,options:Ka.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Ka.find(t=>t.value===e.target.value);t!==void 0&&m(t.value)}}),u(`span`,{className:`flex-1`}),r(q,{size:`sm`,variant:`secondary`,disabled:!R||A,onClick:()=>{if(F&&C?.leavesHouse===!0){k(!0);return}V(!1)},children:[A?u(P,{className:`h-3 w-3 animate-spin`}):u(en,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Run`})]})]}),N&&(h.length===0||i.kind!==`resolved`?u(`p`,{className:`text-foreground-subtle`,children:i.kind===`resolved`?`The detection node’s catalog has no detector larger than this camera’s for its format.`:`The camera’s detection node is not known, so no larger detector can be run there.`}):r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(H,{className:`flex-1 min-w-40`,"aria-label":`Larger detector`,value:v?.modelId??``,options:h.map(e=>({value:e.modelId,label:`${e.name} (${String(Math.round(e.sizeMB))} MB)`})),onChange:e=>{_(e.target.value)}}),u(Y,{className:`w-20`,"aria-label":`Minimum score`,type:`number`,min:.05,max:.95,step:.05,value:y,onChange:e=>{let t=Number.parseFloat(e.target.value);Number.isFinite(t)&&b(Math.min(.95,Math.max(.05,t)))}}),r(`span`,{className:`text-foreground-subtle`,children:[`on `,i.nodeId]})]})),F&&((c.data??[]).length===0?u(`p`,{className:`text-foreground-subtle`,children:c.isError?`The AI profiles could not be read.`:`No enabled AI profile can read images. Add one under AI settings.`}):r(`div`,{className:`space-y-1.5`,children:[u(H,{"aria-label":`AI profile`,value:C?.id??``,options:(c.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.leavesHouse?` · cloud`:` · local`}`})),onChange:e=>{S(e.target.value)}}),C?.leavesHouse===!0&&u(`p`,{className:`text-warning`,children:`This profile sends the frame outside your home, to a cloud service. Each run asks first.`}),r(`div`,{className:`flex items-center gap-1 flex-wrap`,children:[u(`span`,{className:`text-foreground-subtle`,children:`Look for:`}),Ja.map(e=>{let t=w.includes(e);return u(`button`,{type:`button`,"aria-pressed":t,className:`rounded-full border px-2 py-0.5 ${t?`border-primary text-primary`:`border-border text-foreground-muted`}`,onClick:()=>{E(n=>t?n.filter(t=>t!==e):[...n,e])},children:e},e)})]})]})),u(gt,{open:O,onOpenChange:k,children:r(pt,{children:[r(dt,{children:[u(ue,{children:`Send this frame outside your home?`}),u(ce,{children:`The frame from ${e.origin===`recording`?`the recording`:`this track`} will be sent to ${C?.name??`the AI profile`} (${C?.kind??`cloud`}, model ${C?.model??``}), a service outside your network, to be analysed. Only this frame, for this run.`})]}),r(T,{children:[u(q,{variant:`ghost`,size:`sm`,onClick:()=>{k(!1)},children:`Cancel`}),u(q,{size:`sm`,onClick:()=>void V(!0),children:`Send this frame`})]})]})})]})}function Za(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 Qa(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)}}var $a=.01;function eo(e){return e.w>=.01&&e.h>=.01}function to(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}var no=[`nw`,`n`,`ne`,`e`,`se`,`s`,`sw`,`w`];function ro(e,t,n){return{x:Math.min(Math.max(0,e.x+t),Math.max(0,1-e.w)),y:Math.min(Math.max(0,e.y+n),Math.max(0,1-e.h)),w:e.w,h:e.h}}function io(e,t,n,r){if(n){let e=Math.min(Math.max(0,r),t-$a);return{start:e,size:t-e}}return{start:e,size:Math.max(Math.min(1,r),e+$a)-e}}function ao(e,t,n){let r=t.includes(`w`)||t.includes(`e`)?io(e.x,e.x+e.w,t.includes(`w`),n.x):{start:e.x,size:e.w},i=t.includes(`n`)||t.includes(`s`)?io(e.y,e.y+e.h,t.includes(`n`),n.y):{start:e.y,size:e.h};return{x:r.start,y:i.start,w:r.size,h:i.size}}function oo(e,t){return{x:t.includes(`w`)?e.x:t.includes(`e`)?e.x+e.w:e.x+e.w/2,y:t.includes(`n`)?e.y:t.includes(`s`)?e.y+e.h:e.y+e.h/2}}function so(e,t,n){let r=(e,t,n)=>Math.abs(e-t)<=n,i=r(t.x,e.x,n.x),a=r(t.x,e.x+e.w,n.x),o=r(t.y,e.y,n.y),s=r(t.y,e.y+e.h,n.y),c=t.x>=e.x-n.x&&t.x<=e.x+e.w+n.x,l=t.y>=e.y-n.y&&t.y<=e.y+e.h+n.y;return!c||!l?null:o&&i?`nw`:o&&a?`ne`:s&&i?`sw`:s&&a?`se`:o?`n`:s?`s`:i?`w`:a?`e`:t.x>=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h?`body`:null}var co={x:0,y:0,w:1,h:1},lo=1.5;function uo(e,t,n){return e<t?t:e>n?n:e}function fo(e){return 1/e.w}function po(e,t,n,r){return{x:uo(r.x+(e-n.left)/n.width*r.w,0,1),y:uo(r.y+(t-n.top)/n.height*r.h,0,1)}}function mo(e,t,n){return{x:t.left+(e.x-n.x)/n.w*t.width,y:t.top+(e.y-n.y)/n.h*t.height}}function ho(e,t,n){let r=mo(e,t,n);return{left:r.x,top:r.y,width:e.w/n.w*t.width,height:e.h/n.h*t.height}}function go(e,t){return{left:e.left-t.x/t.w*e.width,top:e.top-t.y/t.h*e.height,width:e.width/t.w,height:e.height/t.h}}function _o(e,t,n){let r=uo(e.w/n,1/16,1),i=r/e.w;return{x:uo(t.x-(t.x-e.x)*i,0,1-r),y:uo(t.y-(t.y-e.y)*i,0,1-r),w:r,h:r}}function vo(e,t,n){return{x:uo(e.x+t,0,1-e.w),y:uo(e.y+n,0,1-e.h),w:e.w,h:e.h}}function yo(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var bo=[`person`,`vehicle`,`animal`,`package`,`face`,`plate`];function xo(e){if(typeof e!=`object`||!e||!(`tagName`in e))return!1;let t=String(e.tagName).toUpperCase();return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`?!0:`isContentEditable`in e&&e.isContentEditable===!0}function So(e){let t=e.ctrlKey||e.metaKey,n=e.key.toLowerCase();if(t&&!e.altKey)return n===`s`&&!e.shiftKey?{kind:`save`}:e.typing?null:n===`z`?e.shiftKey?{kind:`redo`}:{kind:`undo`}:n===`y`&&!e.shiftKey?{kind:`redo`}:null;if(e.typing||t||e.altKey)return null;switch(e.key){case`ArrowRight`:return{kind:`next-frame`};case`ArrowLeft`:return{kind:`prev-frame`};case`Delete`:case`Backspace`:return{kind:`delete`};case`Escape`:return{kind:`deselect`};case`Tab`:return e.shiftKey?{kind:`select-prev`}:{kind:`select-next`};case`+`:case`=`:return{kind:`zoom-in`};case`-`:case`_`:return{kind:`zoom-out`};case`0`:return{kind:`zoom-fit`};default:break}let r=Number.parseInt(e.key,10);if(Number.isInteger(r)&&r>=1&&r<=bo.length){let e=bo[r-1];return e===void 0?null:{kind:`set-class`,macroClass:e}}return n===`a`?e.shiftKey?{kind:`accept-all`}:{kind:`accept`}:n===`e`&&!e.shiftKey?{kind:`toggle-model-error`}:n===`c`&&!e.shiftKey?{kind:`toggle-complete`}:null}var Co=[{keys:`← / →`,does:`Previous / next frame`},{keys:`Drag on empty frame`,does:`Draw a box`},{keys:`Drag a box / its handles`,does:`Move / resize it`},{keys:`Delete, Backspace`,does:`Delete the selected box`},{keys:`1 – 6`,does:`Class: person, vehicle, animal, package, face, plate`},{keys:`A`,does:`Accept the selected draft`},{keys:`Shift + A`,does:`Accept every draft`},{keys:`E`,does:`Mark / unmark the selected box as a model error`},{keys:`C`,does:`Toggle "all subjects boxed"`},{keys:`Tab / Shift + Tab`,does:`Select the next / previous box`},{keys:`Esc`,does:`Deselect`},{keys:`Ctrl/⌘ + Z`,does:`Undo`},{keys:`Ctrl/⌘ + Shift + Z, Ctrl/⌘ + Y`,does:`Redo`},{keys:`Ctrl/⌘ + S`,does:`Save the frame`},{keys:`+ / − / 0, wheel, pinch`,does:`Zoom in / out / fit`},{keys:`Space + drag, middle drag, two fingers`,does:`Pan`}];n();var wo=.0015,To={pipeline:`var(--color-foreground-muted)`,assist:`var(--color-info)`,llm:`var(--color-warning)`,operator:`var(--color-success)`};function Eo(e,t){return e.kind===`model_error`?{color:`var(--color-danger)`,dashed:!0,opacity:1}:t?{color:`var(--color-primary)`,dashed:e.draft,opacity:1}:e.draft?{color:To[e.source],dashed:!0,opacity:.8}:{color:`var(--color-success)`,dashed:!1,opacity:1}}function Do(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function Oo(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}}function ko({imageSrc:n,imageWidth:a,imageHeight:o,boxes:s,selectedKey:c,viewport:f,onViewportChange:p,panMode:m,onSelect:h,onDraw:g,onGestureStart:_,onGestureBox:v,onGestureEnd:y}){let b=t(null),[x,S]=l({w:0,h:0}),[C,w]=l(null),[T,E]=l(!1),D=t(new Map),O=t({mode:`none`});i(()=>{let e=b.current;if(e===null)return;let t=()=>S({w:e.clientWidth,h:e.clientHeight});if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);return n.observe(e),()=>{n.disconnect()}},[]);let k=Za(x.w,x.h,a,o);d(()=>{let e=e=>{e.key!==` `||xo(e.target)||(e.preventDefault(),E(!0))},t=e=>{e.key===` `&&E(!1)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,t)}},[]);let A=t({image:k,viewport:f,onViewportChange:p});A.current={image:k,viewport:f,onViewportChange:p},d(()=>{let e=b.current;if(e===null)return;let t=t=>{let{image:n,viewport:r,onViewportChange:i}=A.current;if(n===null)return;t.preventDefault();let a=e.getBoundingClientRect();i(_o(r,po(t.clientX-a.left,t.clientY-a.top,n,r),Math.exp(-t.deltaY*wo)))};return e.addEventListener(`wheel`,t,{passive:!1}),()=>{e.removeEventListener(`wheel`,t)}},[]);let j=e(e=>{let t=b.current?.getBoundingClientRect();return{x:e.clientX-(t?.left??0),y:e.clientY-(t?.top??0)}},[]),M=e(e=>k===null?null:po(e.x,e.y,k,f),[k,f]),N=e(()=>{let e=O.current;(e.mode===`move`||e.mode===`resize`)&&y(),e.mode===`draw`&&w(null),O.current={mode:`none`}},[y]),P=e=>{if(k===null)return;let t=j(e);if(D.current.set(e.pointerId,t),e.currentTarget.setPointerCapture?.(e.pointerId),D.current.size===2){N();let[e,t]=[...D.current.values()];if(e===void 0||t===void 0)return;let n=Oo(e,t);O.current={mode:`pinch`,startDistance:Math.max(1,Do(e,t)),anchor:po(n.x,n.y,k,f),from:f};return}if(D.current.size>2)return;if(e.button===1||T||m){e.preventDefault(),O.current={mode:`pan`,startPx:t,from:f};return}if(e.button!==0)return;let n=po(t.x,t.y,k,f),r={x:12/k.width*f.w,y:12/k.height*f.h},i=s.find(e=>e.key===c);if(i!==void 0){let e=so(i.bbox,n,r);if(e!==null&&e!==`body`){_(),O.current={mode:`resize`,key:i.key,handle:e,from:i.bbox};return}}let a=s[to(s.map(e=>e.bbox),n)];if(a!==void 0){a.key!==c&&h(a.key),_(),O.current={mode:`move`,key:a.key,start:n,from:a.bbox};return}O.current={mode:`draw`,start:n},w(Qa(n,n))},F=e=>{if(!D.current.has(e.pointerId)||k===null)return;let t=j(e);D.current.set(e.pointerId,t);let n=O.current;switch(n.mode){case`pinch`:{let[e,t]=[...D.current.values()];if(e===void 0||t===void 0)return;let r=_o(n.from,n.anchor,Do(e,t)/n.startDistance),i=Oo(e,t),a=po(i.x,i.y,k,r);p(vo(r,n.anchor.x-a.x,n.anchor.y-a.y));return}case`pan`:{let e=(t.x-n.startPx.x)/k.width*n.from.w,r=(t.y-n.startPx.y)/k.height*n.from.h;p(vo(n.from,-e,-r));return}case`move`:{let e=po(t.x,t.y,k,f);v(n.key,ro(n.from,e.x-n.start.x,e.y-n.start.y));return}case`resize`:{let e=po(t.x,t.y,k,f);v(n.key,ao(n.from,n.handle,e));return}case`draw`:{let e=po(t.x,t.y,k,f);w(Qa(n.start,e));return}default:return}},I=e=>{if(!D.current.has(e.pointerId))return;D.current.delete(e.pointerId);let t=O.current;if(t.mode===`pinch`){D.current.size<2&&(O.current={mode:`none`});return}if(t.mode===`draw`){let n=M(j(e)),r=n===null?null:Qa(t.start,n);w(null),O.current={mode:`none`},r!==null&&eo(r)?g(r):h(null);return}N()},L=s.find(e=>e.key===c),R=T||m,z=k===null?null:go(k,f);return r(`div`,{ref:b,"data-testid":`retrain-canvas`,className:`relative w-full h-full min-h-[280px] bg-surface-sunken select-none touch-none overflow-hidden`,style:{cursor:R?`grab`:`crosshair`},onPointerDown:P,onPointerMove:F,onPointerUp:I,onPointerCancel:I,children:[z!==null&&u(`img`,{src:n,alt:`Frame being annotated`,draggable:!1,className:`absolute max-w-none pointer-events-none`,style:z}),k!==null&&s.map(e=>{let t=ho(e.bbox,k,f),n=e.key===c,i=Eo(e,n);return u(`div`,{"data-testid":`retrain-box-${e.key}`,"data-draft":e.draft?`true`:`false`,"data-source":e.source,className:`absolute pointer-events-none`,style:{left:t.left,top:t.top,width:t.width,height:t.height,border:`${n?`2px`:`1px`} ${i.dashed?`dashed`:`solid`} ${i.color}`,opacity:i.opacity},children:r(`span`,{className:`absolute -top-4 left-0 text-[10px] px-1 rounded whitespace-nowrap text-background`,style:{background:i.color},children:[e.label??e.macroClass,e.kind===`model_error`?` ✕`:``,e.draft?` ?`:``,e.flag!==void 0&&e.flag.verdict!==`confirmed`?` !`:``]})},e.key)}),k!==null&&L!==void 0&&no.map(e=>{let t=mo(oo(L.bbox,e),k,f);return u(`div`,{"data-testid":`retrain-handle-${e}`,className:`absolute h-2.5 w-2.5 -translate-x-1/2 -translate-y-1/2 rounded-sm border border-background bg-primary pointer-events-none`,style:{left:t.x,top:t.y}},e)}),C!==null&&k!==null&&u(`div`,{className:`absolute border border-dashed border-primary pointer-events-none`,style:ho(C,k,f)})]})}n();function Ao(){let[t,n]=l(co),[r,i]=l(!1);return{viewport:t,setViewport:n,zoomIn:e(()=>{n(e=>_o(e,yo(e),lo))},[]),zoomOut:e(()=>{n(e=>_o(e,yo(e),1/lo))},[]),fit:e(()=>{n(co)},[]),panMode:r,togglePan:e(()=>{i(e=>!e)},[])}}function jo({view:e,canUndo:t,canRedo:n,onUndo:i,onRedo:a}){let o=fo(e.viewport);return r(`div`,{className:`flex items-center gap-1 px-2 py-1 border-b border-border bg-surface`,children:[u(q,{variant:`ghost`,size:`sm`,"aria-label":`Zoom out`,onClick:e.zoomOut,children:u(te,{className:`h-3.5 w-3.5`})}),r(`span`,{className:`w-12 text-center text-[11px] tabular-nums text-foreground-subtle`,children:[Math.round(o*100),`%`]}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Zoom in`,onClick:e.zoomIn,children:u(We,{className:`h-3.5 w-3.5`})}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Fit the whole frame`,disabled:o<=1,onClick:e.fit,children:u(Xt,{className:`h-3.5 w-3.5`})}),u(q,{variant:e.panMode?`secondary`:`ghost`,size:`sm`,"aria-label":`Pan tool`,"aria-pressed":e.panMode,onClick:e.togglePan,children:u(re,{className:`h-3.5 w-3.5`})}),u(`span`,{className:`flex-1`}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Undo`,disabled:!t,onClick:i,children:u(ge,{className:`h-3.5 w-3.5`})}),u(q,{variant:`ghost`,size:`sm`,"aria-label":`Redo`,disabled:!n,onClick:a,children:u(Qt,{className:`h-3.5 w-3.5`})}),r(B,{children:[u(R,{"aria-label":`Keyboard shortcuts`,className:`inline-flex h-7 items-center rounded-md px-2 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:u(Jt,{className:`h-3.5 w-3.5`})}),r(Qe,{className:`w-80`,children:[u(`h3`,{className:`mb-2 text-xs font-semibold text-foreground`,children:`Keyboard and gestures`}),u(`table`,{className:`w-full text-[11px]`,children:u(`tbody`,{children:Co.map(e=>r(`tr`,{className:`align-top`,children:[u(`td`,{className:`py-0.5 pr-2 font-mono whitespace-nowrap text-foreground`,children:e.keys}),u(`td`,{className:`py-0.5 text-foreground-subtle`,children:e.does})]},e.keys))})})]})]})]})}function Mo(e){return{past:[],present:e,future:[],gestureBase:null}}function No(e,t){let n=[...e,t];return n.length>100?n.slice(n.length-100):n}function Po(e,t){return t===e.present?e:{past:No(e.past,e.present),present:t,future:[],gestureBase:null}}function Fo(e,t){return{...e,present:t}}function Io(e){let t=e.past[e.past.length-1];return t===void 0?e:{past:e.past.slice(0,-1),present:t,future:[e.present,...e.future],gestureBase:null}}function Lo(e){let[t,...n]=e.future;return t===void 0?e:{past:No(e.past,e.present),present:t,future:n,gestureBase:null}}function Ro(e){return{...e,gestureBase:e.present}}function zo(e,t){return{...e,present:t}}function Bo(e){let t=e.gestureBase;return t===null?e:t===e.present?{...e,gestureBase:null}:{past:No(e.past,t),present:e.present,future:[],gestureBase:null}}function Vo(e){return e.past.length>0}function Ho(e){return e.future.length>0}n();function Uo(e,t){return typeof e==`function`?e(t):e}function Wo(t){let[n,r]=l(()=>Mo(t())),i=e(e=>{r(t=>Po(t,Uo(e,t.present)))},[]),a=e(e=>{r(Mo(e))},[]),o=e(e=>{r(t=>Fo(t,Uo(e,t.present)))},[]),s=e(()=>{r(e=>Ro(e))},[]),c=e(e=>{r(t=>zo(t,Uo(e,t.present)))},[]),u=e(()=>{r(e=>Bo(e))},[]),d=e(()=>{r(e=>Io(e))},[]),f=e(()=>{r(e=>Lo(e))},[]);return{editor:n.present,setEditor:i,resetEditor:a,selectOnly:o,beginGesture:s,updateGesture:c,endGesture:u,undo:d,redo:f,canUndo:Vo(n),canRedo:Ho(n)}}n();function Go(e,t){let n=e.boxes.length;if(n===0)return null;let r=e.boxes.findIndex(t=>t.key===e.selectedKey),i=r<0?t===1?0:n-1:(r+t+n)%n;return e.boxes[i]?.key??null}function Ko(e,t){let{history:n}=t,r=n.editor.selectedKey;switch(e.kind){case`next-frame`:return t.onNextFrame();case`prev-frame`:return t.onPrevFrame();case`toggle-complete`:return t.onToggleComplete();case`save`:return t.onSave();case`undo`:return n.canUndo?(n.undo(),!0):!1;case`redo`:return n.canRedo?(n.redo(),!0):!1;case`zoom-in`:return t.onZoomIn(),!0;case`zoom-out`:return t.onZoomOut(),!0;case`zoom-fit`:return t.onZoomFit(),!0;case`accept-all`:return n.setEditor(e=>Oa(e)),!0;case`select-next`:case`select-prev`:{let t=Go(n.editor,e.kind===`select-next`?1:-1);return t===null?!1:(n.selectOnly(e=>ja(e,t)),!0)}case`deselect`:return r===null?!1:(n.selectOnly(e=>ja(e,null)),!0);default:break}if(r===null)return!1;switch(e.kind){case`delete`:return n.setEditor(e=>Aa(e,r)),!0;case`set-class`:return n.setEditor(t=>Ea(t,r,{macroClass:e.macroClass})),!0;case`accept`:return n.setEditor(e=>Da(e,r)),!0;case`toggle-model-error`:return n.setEditor(e=>ka(e,r)),!0;default:return!1}}function qo(e,n){let r=t(n);r.current=n,d(()=>{if(!e)return;let t=e=>{if(e.defaultPrevented||e.isComposing)return;let t=So({key:e.key,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey,altKey:e.altKey,typing:xo(e.target)});t!==null&&Ko(t,r.current)&&e.preventDefault()};return window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`keydown`,t)}},[e])}n();var Jo=`person`,Yo={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 Xo({frames:n,activeFrameId:i,onActiveFrame:o,onFramesChanged:s,onSaved:c,setNotice:f,picked:p=!1,onTogglePick:m}){let h=n.find(e=>e.frameId===i),g=h?.deviceId??null,_=Wo(()=>Sa([],[])),{editor:v,setEditor:y,resetEditor:b,selectOnly:S}=_,C=Ao(),w=ut({frameIds:[i]}),T=De({frameId:i}),E=D(),O=ee(),k=A(),j=_e({deviceIds:g===null?[]:[g]},{enabled:g!==null,staleTime:3e4}),M=j.data?.[0]?.detection?.nodeId??null,N=ke({nodeId:M??``},{enabled:M!==null,staleTime:3e4}),F=oe({nodeId:M??``},{enabled:M!==null,staleTime:3e4}),I=Te({deviceId:g??0},{enabled:g!==null,staleTime:3e4}),L=a(()=>ga({status:j.data?.[0],nodeDevices:N.data,schema:F.data,resolvedSteps:I.data?.steps}),[j.data,N.data,F.data,I.data]),R=t({stored:w.data,copy:h});R.current={stored:w.data,copy:h};let z=h!==void 0;d(()=>{C.fit();let{stored:e,copy:t}=R.current;b(Sa((e??[]).filter(e=>e.mediaKey===i),t?.pipelineBoxes??[]))},[i,w.dataUpdatedAt,z,b,C.fit]);let B=e(async e=>{h!==void 0&&(await k.mutateAsync({...fa(h),complete:e}),await s())},[h,k,s]),V=e(async e=>{if(h===void 0)return;if(f(null),L.kind!==`resolved`){f(Yo[L.gap]);return}let t=await E.mutateAsync({...fa(h),subject:e===`package`?{kind:`package`}:{kind:`objects`,modelId:L.modelId,minScore:L.minScore},nodeId:L.nodeId});if(t.kind===`refused`){f(t.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: ${t.reason}${t.detail===void 0?``:` — ${t.detail}`}`);return}let n=Ca(v,t.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},draft:!0})));y(n.state),f(`${t.proposals.length} proposal${t.proposals.length===1?``:`s`} from ${t.modelId}`+(n.skipped>0?` — ${n.skipped} already on the frame`:``)+(t.belowThreshold>0?` — ${t.belowThreshold} more were below ${t.minScore.toFixed(2)}`:``)+`. Accept or correct each one; drafts are not saved.`)},[h,E,L,v,y,f]),H=e(e=>{y(t=>wa(t,e,Jo))},[y]),[U,W]=l(!1),G=e(async()=>{if(h===void 0)return;let e=Pa(v);W(!0);try{await O.mutateAsync({...fa(h),annotations:[...Ia(v)]}),await w.refetch()}finally{W(!1)}await c?.(),f(e>0?`Annotations saved. ${String(e)} unconfirmed draft${e===1?` was`:`s were`} not saved.`:`Annotations saved.`)},[h,v,O,w,c,f]),K=T.data,te=Ua(v.boxes)&&h!==void 0,ne=Pa(v),re=n.map(e=>e.frameId),ie=e=>{let t=re.indexOf(i),n=re[t+e];return t<0||n===void 0?!1:(o(n),!0)};return qo(!U,{history:_,onNextFrame:()=>ie(1),onPrevFrame:()=>ie(-1),onToggleComplete:()=>h===void 0||k.isPending?!1:(B(!h.complete),!0),onSave:()=>!te||U?!1:(G(),!0),onZoomIn:C.zoomIn,onZoomOut:C.zoomOut,onZoomFit:C.fit}),r(`div`,{className:`grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(0,380px)] gap-3 ${U?`pointer-events-none opacity-70`:``}`,"aria-busy":U,children:[r(`div`,{className:`rounded-md border border-border overflow-hidden flex flex-col`,children:[u(jo,{view:C,canUndo:_.canUndo,canRedo:_.canRedo,onUndo:_.undo,onRedo:_.redo}),K===void 0?r(`div`,{className:`flex items-center gap-2 p-6 text-xs text-foreground-subtle`,children:[u(P,{className:`h-3.5 w-3.5 animate-spin`}),`Loading the frame…`]}):u(ko,{imageSrc:`data:image/jpeg;base64,${K.base64}`,imageWidth:K.width,imageHeight:K.height,boxes:v.boxes,selectedKey:v.selectedKey,viewport:C.viewport,onViewportChange:C.setViewport,panMode:C.panMode,onSelect:e=>{S(t=>ja(t,e))},onDraw:H,onGestureStart:_.beginGesture,onGestureBox:(e,t)=>{_.updateGesture(n=>Ea(n,e,{bbox:t}))},onGestureEnd:_.endGesture})]}),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 flex-wrap`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground flex-1`,children:`Subjects`}),h?.origin===`recording`&&u(x,{variant:`info`,children:`from the recording`}),m!==void 0&&r(q,{variant:p?`primary`:`ghost`,size:`sm`,"aria-pressed":p,title:`Pick this frame for a dataset version (Datasets tab)`,onClick:m,children:[u(Zt,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:p?`Picked`:`Pick for dataset`})]}),r(q,{variant:`secondary`,size:`sm`,disabled:E.isPending||L.kind!==`resolved`,onClick:()=>void V(`objects`),children:[u(rt,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Propose`})]}),r(q,{variant:`secondary`,size:`sm`,disabled:E.isPending||L.kind!==`resolved`,onClick:()=>void V(`package`),children:[u(rt,{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:L.kind===`resolved`?`Proposals come from ${L.modelId} at ${L.minScore.toFixed(2)}, on ${L.nodeId} — what this camera really runs.`:Yo[L.gap]}),h!==void 0&&u(Xa,{frame:h,history:_,detector:L,schema:F.data,setNotice:f}),u(`div`,{className:`flex-1 overflow-y-auto`,children:u(Ha,{boxes:v.boxes,selectedKey:v.selectedKey,onSelect:e=>{S(t=>ja(t,e))},onChange:(e,t)=>{y(n=>Ea(n,e,t))},onAccept:e=>{y(t=>Da(t,e))},onToggleModelError:e=>{y(t=>ka(t,e))},onDelete:e=>{y(t=>Aa(t,e))}})}),r(`label`,{className:`px-3 py-2 border-t border-border flex items-center gap-2 text-[11px] text-foreground`,children:[u(ae,{"aria-label":`All subjects in this frame are boxed`,checked:h?.complete===!0,disabled:h===void 0||k.isPending,onChange:e=>void B(e.target.checked)}),r(`span`,{className:`flex-1`,children:[`All subjects boxed`,u(`span`,{className:`block text-foreground-subtle`,children:`Detector evaluation uses only these frames — an unboxed person counts as a false alarm. A frame with nothing in it, ticked, is a negative example.`})]})]}),ne>0&&r(`div`,{className:`px-3 py-2 border-t border-border flex items-center gap-2 text-[11px] text-warning`,children:[r(`span`,{className:`flex-1`,children:[ne,` draft`,ne===1?``:`s`,` not confirmed — a draft is never saved. Accept, correct or delete each one.`]}),r(q,{variant:`secondary`,size:`sm`,onClick:()=>{y(e=>Oa(e))},children:[u(Pt,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Accept all`})]})]}),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:[v.boxes.filter(e=>e.kind===`model_error`).length,` marked as model errors`]}),u(q,{size:`sm`,disabled:!te||U,onClick:()=>void G(),children:`Save frame`})]})]})]})}n();var Zo={"empty-name":`Give the collection a name.`,"duplicate-name":`A collection with that name already exists.`,"unknown-collection":`That collection no longer exists.`};function Qo(){let[t,n]=l(`tracks`),[i,o]=l(null),[c,f]=l(null),[p,m]=l(null),[h,g]=l(new Map),[_,v]=l(null),[y,b]=l([]),S=et({projection:`slim`,isCamera:!0}),w=a(()=>{let e=new Map;for(let t of S.data??[])e.set(t.id,t.name);return e},[S.data]),T=ft({}),D=E({trackId:i?.trackId??``},{enabled:t===`tracks`&&i!==null}),O=ne(),k=we(),A=it(),j=ht({}),M=Ce({collectionId:c?.id??``},{enabled:t===`collections`&&c!==null}),P=Ke(),I=Ve(),L=Se(),R=C(),z=t===`tracks`?D.data?.copies??[]:M.data??[],B=e(()=>t===`tracks`?D.refetch():M.refetch(),[t,D,M]);d(()=>{p===null&&z.length>0&&m(z[0].frameId)},[z,p]);let V=e(()=>{m(null),g(new Map),v(null)},[]),ee=e(e=>{o(e),V()},[V]),H=e(e=>{f(e),V()},[V]),U=e(async e=>{if(i===null)return;let t=await O.mutateAsync({deviceId:i.deviceId,trackId:i.trackId,mediaIds:[e]});if(t.refused.length>0){let e=new Map(h);for(let n of t.refused)e.set(n.sourceMediaId,n.reason);g(e)}t.copied.length>0&&m(t.copied[0].frameId),await D.refetch(),await T.refetch()},[i,O,h,D,T]),W=e(async e=>{let t=(D.data?.copies??[]).find(t=>t.frameId===e);t!==void 0&&(await k.mutateAsync(fa(t)),p===e&&m(null),await D.refetch(),await T.refetch(),await j.refetch())},[D,k,p,T,j]),G=e(async()=>{if(i===null)return;let e=await A.mutateAsync({deviceId:i.deviceId,trackId:i.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 T.refetch(),e.changed&&o(null)},[i,A,T]),K=e(async e=>{let t=await P.mutateAsync({name:e});return await j.refetch(),t.kind===`refused`?Zo[t.reason]??t.reason:(f(t.collection),V(),null)},[P,j,V]),te=e(async(e,t)=>{let n=await I.mutateAsync({id:e,name:t});return await j.refetch(),n.kind===`refused`?Zo[n.reason]??n.reason:(c?.id===e&&f(n.collection),null)},[I,j,c]),re=e(async e=>{let t=await L.mutateAsync({id:e});c?.id===e&&(f(null),V()),await j.refetch(),v(t.deleted?`Collection deleted${t.removedFrames>0?` — ${String(t.removedFrames)} recording frame${t.removedFrames===1?``:`s`} no other collection held left the dataset`:``}.`:`That collection no longer existed.`)},[L,c,j,V]),ie=e(async e=>{if(c===null)return;let t=await R.mutateAsync({collectionId:c.id,frameId:e.frameId});p===e.frameId&&m(null),await M.refetch(),await j.refetch(),v(t.deletedFrame?`Removed — it was a recording frame no other collection held, so it left the dataset with its boxes.`:`Removed from the collection.`)},[c,R,p,M,j]),ae=e(async()=>{await T.refetch()},[T]),oe=t===`tracks`?i!==null:c!==null,se=z.some(e=>e.frameId===p);return r(Ft,{subtitle:`Turn marked tracks and frames sent from recordings into an annotated dataset. Every frame is a copy the dataset owns — it never depends on media that can be swept.`,actions:t===`tracks`&&i!==null?r(q,{size:`sm`,onClick:()=>void G(),children:[u(je,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Complete track`})]}):null,children:[_!==null&&u(`div`,{className:`rounded-md border border-border bg-surface px-3 py-2 text-xs text-foreground`,children:_}),u(aa,{}),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:[u(F,{value:t,onValueChange:e=>{n(e===`collections`||e===`datasets`?e:`tracks`),V()},children:r(he,{className:`px-2 pt-2`,children:[r(N,{value:`tracks`,children:[`Tracks `,u(x,{className:`ml-1`,children:T.data?.length??0})]}),r(N,{value:`collections`,children:[`Collections `,u(x,{className:`ml-1`,children:j.data?.length??0})]}),u(N,{value:`datasets`,children:`Datasets`})]})}),t===`tracks`?u(da,{tracks:T.data??[],isLoading:T.isLoading,selectedTrackId:i?.trackId??null,deviceNames:w,onSelect:ee}):t===`datasets`?u(`p`,{className:`p-3 text-[11px] text-foreground-subtle`,children:`A dataset version freezes the frames a selection of cameras, collections and picked frames yields, with the hash of their boxes, so a training run can name exactly what it learned from. Pick frames with "Pick for dataset" in the frame workbench.`}):u(Zi,{collections:j.data??[],isLoading:j.isLoading,selectedId:c?.id??null,onSelect:H,onCreate:K,onRename:te,onDelete:re})]}),u(`section`,{className:`space-y-3 min-w-0`,children:t===`datasets`?u(ia,{deviceNames:w,collections:j.data??[],pickedFrameIds:y,onClearPicked:()=>{b([])}}):oe?r(s,{children:[u(`div`,{className:`rounded-md border border-border bg-surface p-3`,children:t===`tracks`?u(sa,{candidates:D.data?.candidates??[],copies:D.data?.copies??[],activeFrameId:p,refusals:h,isSelecting:O.isPending,onSelectCandidate:e=>void U(e),onOpenCopy:m,onRemoveCopy:e=>void W(e),renderCopyActions:e=>u(Ji,{frameId:e.frameId,onAdded:()=>j.refetch()})}):u(Xi,{frames:M.data??[],isLoading:M.isLoading,activeFrameId:p,deviceNames:w,onOpen:m,onRemove:e=>void ie(e)})}),p!==null&&se&&u(Xo,{frames:z,activeFrameId:p,onActiveFrame:m,onFramesChanged:B,onSaved:ae,setNotice:v,picked:y.includes(p),onTogglePick:()=>{b(e=>e.includes(p)?e.filter(e=>e!==p):[...e,p])}})]}):u(`p`,{className:`text-xs text-foreground-subtle`,children:t===`tracks`?`Pick a track from the staging list to start annotating it.`:`Pick or create a collection.`})})]})]})}function $o(){return u(`div`,{className:`flex flex-col p-4`,children:u(Vt,{tabs:[{id:`feed`,label:`Feed`,icon:ve,content:u(qi,{})},{id:`retrain`,label:`Retrain`,icon:je,content:u(Qo,{})},{id:`debug`,label:`Debug`,icon:Be,content:u(bi,{})}]})})}export{$o as EventsPage};
@@ -0,0 +1 @@
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{at as c,gt as l,ht as u,st as d,vt as f}from"./player-overlays-CVsVEZkx.js";import{$l as p,$n as m,$t as h,Ad as g,Cn as _,Du as v,Ft as y,Gl as b,Gn as x,Hd as S,Jd as C,Jl as w,Kd as T,Kl as E,Kn as D,N as O,Nn as ee,Od as te,Ot as k,P as A,Pn as j,Ql as M,Tn as N,U as P,Vu as ne,W as F,Wd as re,Wl as ie,Xl as ae,Yl as oe,Zl as se,au as ce,bn as I,br as le,dd as L,eu as ue,fd as de,gd as fe,id as R,iu as pe,ju as me,nu as he,pu as z,qd as ge,ql as _e,ru as ve,sa as ye,sf as be,tu as xe,ud as B,wf as Se,wn as V,xn as H,xr as Ce,yn as U}from"./src-DBOD88Il.js";import{t as we}from"./history-BR0cgtxK.js";import{t as Te}from"./monitor-smartphone-DbkPiYT_.js";import{_ as W,a as Ee,b as De,c as Oe,d as ke,f as Ae,g as je,h as G,i as Me,l as Ne,m as Pe,n as Fe,o as Ie,p as Le,s as Re,t as ze,u as Be,v as K,y as q}from"./SessionsList-DTYAg11v.js";import{a as Ve,i as He,o as Ue,s as We}from"./client-DdTCFotl.js";import{$ as Ge,R as J,X as Ke,Y as qe,at as Je,c as Ye,it as Xe,p as Ze,rt as Qe,s as $e}from"./index-BhXNFlQG.js";import{t as et}from"./AdminPage-BSFohA3i.js";import{t as tt}from"./AdminTabs-DTp_qwRF.js";import{n as nt,r as rt,t as it}from"./AddonIntegrationBody-FGAYdPUA.js";import{n as at,t as ot}from"./addon-display-names-BkwMrExv.js";var st=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`}]]),ct=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`}]]);e();function lt(){let e=x(),t=v.useUtils(),r=q(),{data:i,isLoading:a}=M(),c=n(()=>i??[],[i]),l=v.useQueries(e=>c.map(t=>e.userManagement.listExternalIdentities({userId:t.id}))),u=v.auth.listLoginMethods.useQuery(),[d,f]=o(null),p=pe({onSuccess:()=>void t.userManagement.listExternalIdentities.invalidate(),onError:e=>f(`Remove failed: ${e.message}`)}),m=n(()=>new Map((u.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),[u.data]),h=c.flatMap((e,t)=>l[t]?.data??[]),g=h.map(e=>({...ke(e,r),kind:m.get(e.provider)??e.provider})),_=async t=>{let n=h.find(e=>Be(e)===t.id);n!==void 0&&await e({title:`Remove sign-in link`,message:`"${t.ownerName}" will no longer be able to sign in with this ${t.kind} account.`,confirmLabel:`Remove`,variant:`danger`})&&(f(null),p.mutate({userId:n.userId,provider:n.provider,subject:n.subject}))};return s(W,{notice:K(d),onDismissNotice:()=>{f(null)},id:`external-identities`,title:`Sign-in links`,icon:Je,description:`External accounts (single sign-on) each user linked to their CamStack account. Only the owner can link one, from their profile; an admin can remove it.`,children:s(G,{rows:g,label:`sign-in links`,isLoading:a||l.some(e=>e.isLoading),loadError:l.find(e=>e.isError)?.error?.message??null,emptyText:`No user has linked a sign-in account.`,expiresNone:`—`,action:{label:`Remove`,icon:De,isAvailable:()=>!0,onRun:e=>void _(e),busyId:null,disabled:p.isPending}})})}e();function ut(){let e=x(),t=a(),r=q(),i=oe(),[c,l]=o(null),u=ue({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),onError:e=>l(`Revoke failed: ${e.message}`)}),f=n(()=>(i.data??[]).map(e=>Ne(e,r)),[i.data,r]),p=async t=>{await e({title:`Revoke "${t.name}"?`,message:`Any client using this key loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(l(null),u.mutate({id:t.id}))};return s(W,{notice:K(c),onDismissNotice:()=>{l(null)},id:`legacy-api-keys`,title:`Legacy API keys`,icon:we,description:`Keys from before scoped tokens. Nothing creates them any more; revoke them and issue a scoped token instead.`,children:s(G,{rows:f,label:`legacy API keys`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No legacy API keys.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void p(e),busyId:u.isPending?u.variables?.id??null:null,disabled:u.isPending}})})}e();function dt(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 ft(){let e=x(),t=a(),r=se(),[i,c]=o(null),l=xe({onSuccess:()=>void t.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]}),onError:e=>c(`Revoke failed: ${e.message}`)}),u=n(()=>(r.data??[]).map(e=>Ae(e,e.scopes.map(dt).join(`, `))),[r.data]),f=async t=>{await e({title:`Revoke the "${t.name}" link?`,message:`${t.name} loses access for ${t.ownerName} on its next call. Linking it again needs the account-link flow from the start.`,confirmLabel:`Revoke`,variant:`danger`})&&(c(null),l.mutate({id:t.id}))},p=l.isPending?l.variables?.id??null:null;return s(W,{notice:K(i),onDismissNotice:()=>{c(null)},id:`linked-apps`,title:`Linked apps`,icon:re,description:`External integrations (Alexa, …) linked to this hub through OAuth. Revoking one stops that integration on its next call.`,children:s(G,{rows:u,label:`linked apps`,isLoading:r.isLoading,loadError:r.isError?r.error?.message??`Request failed`:null,emptyText:`No linked apps — an integration appears here once it completes the account-link flow.`,expiresNone:`—`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void f(e),busyId:p,disabled:l.isPending}})})}e();var pt={one:`session`,many:`sessions`};function mt(){let e=x(),t=v.useUtils(),r=q(),i=v.auth.listSessions.useQuery(),[a,c]=o(null),l=()=>void t.auth.listSessions.invalidate(),u=v.auth.revokeSessions.useMutation({onSuccess:l,onError:e=>c(`Sign out failed: ${e.message}`)}),d=je(`login-session`,pt,l),f=n(()=>(i.data??[]).map(e=>Le(e,r,{client:e=>Ee(e).label,method:Ie})),[i.data,r]),p=async t=>{await e({title:`Sign out this session`,message:`${t.ownerName} on ${t.name} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(c(null),u.mutate({id:t.id}))};return s(W,{notice:K(a,d.outcome),onDismissNotice:()=>{c(null),d.dismiss()},id:`login-sessions`,title:`Login sessions`,icon:Te,description:`Every browser and app signed in to this hub, for every user. Signing one out ends it at once; it has to sign in again. Your own current session is marked and never included in a bulk sign-out.`,children:s(G,{rows:f,label:`sessions`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No active sessions.`,action:{label:`Sign out`,icon:Qe,isAvailable:e=>e.status===`active`,onRun:e=>void p(e),busyId:u.isPending&&u.variables!==void 0&&`id`in u.variables?u.variables.id:null,disabled:u.isPending||d.busy},bulk:{revoke:d,noun:pt,isSelectable:e=>e.status===`active`}})})}e();function ht({users:e,onClose:n,onSubmit:r,submitting:i}){let{user:a}=J(),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`]}]),[g,v]=o(``),y=A(p),b=l!==``&&d.trim().length>0&&p.length>0&&y===null&&!i;return s(U,{open:!0,onOpenChange:e=>!e&&n(),children:t(H,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(V,{children:s(N,{children:`Create scoped token`})}),t(I,{className:`space-y-3`,children:[t(`div`,{className:`space-y-1`,children:[s(h,{htmlFor:`scoped-token-user`,children:`On behalf of user`}),s(ee,{id:`scoped-token-user`,value:l,onChange:e=>u(e.target.value),options:e.map(e=>({value:e.id,label:e.username}))})]}),t(`div`,{className:`space-y-1`,children:[s(h,{htmlFor:`scoped-token-name`,children:`Name`}),s(z,{id:`scoped-token-name`,value:d,onChange:e=>f(e.target.value),placeholder:`cloudflare-tunnel-route`})]}),t(`div`,{className:`space-y-1`,children:[s(h,{children:`Scopes`}),s(O,{value:p,onChange:m,clampToParent:c}),y&&s(`p`,{className:`text-[10px] text-danger`,children:y}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`})]}),t(`div`,{className:`space-y-1`,children:[s(h,{htmlFor:`scoped-token-days`,children:`Expires in (days)`}),s(z,{id:`scoped-token-days`,type:`number`,min:1,value:g,onChange:e=>v(e.target.value),placeholder:`30`}),s(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave blank for non-expiring.`})]})]}),t(_,{children:[s(j,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Cancel`}),t(j,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>{let e=parseInt(g,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;r({userId:l,name:d.trim(),scopes:p,expiresAt:t})},disabled:!b,children:[i?s(S,{className:`h-3.5 w-3.5 animate-spin`,"aria-hidden":!0}):s(B,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`Issue token`]})]})]})})}function gt({token:e,label:n,onClose:r}){return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(H,{width:`md`,scroll:`body`,children:[s(V,{children:s(N,{children:`Token: ${n}`})}),t(I,{className:`space-y-3`,children:[s(`div`,{className:`rounded-md 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:`select-all break-all rounded-md border border-border bg-background p-2 font-mono text-[11px] text-foreground`,children:e})]}),t(_,{children:[s(k,{value:e,label:`Copy`,srLabel:`token`}),s(j,{type:`button`,variant:`primary`,size:`sm`,onClick:r,children:`Done`})]})]})})}e();function _t(e){return e.type===`device`?`device:[${F(e.selector)}]`:`${e.type}:${e.target??``}`}function vt(){let e=x(),r=a(),i=q(),{data:c,isLoading:l}=M(),u=n(()=>c??[],[c]),f=v.useQueries(e=>u.map(t=>e.userManagement.listScopedTokens({userId:t.id}))),[p,m]=o(null),[h,g]=o(!1),[_,y]=o(null),b=()=>void r.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),S=ie({onSuccess:({token:e,record:t})=>{b(),g(!1),y({token:e,label:t.name})},onError:e=>m(`Create failed: ${e.message}`)}),C=he({onSuccess:b,onError:e=>m(`Revoke failed: ${e.message}`)}),w=Date.now(),T=u.flatMap((e,t)=>(f[t]?.data??[]).map(t=>Pe(t,e.id,i,t.scopes.map(_t).join(`, `),w))),E=f.find(e=>e.isError)?.error?.message??null,D=async t=>{await e({title:`Revoke "${t.name}"?`,message:`${t.ownerName}'s scoped token stops working on its next use. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(m(null),C.mutate({id:t.id}))};return t(W,{notice:K(p),onDismissNotice:()=>{m(null)},id:`scoped-tokens`,title:`Scoped tokens`,icon:ge,description:`Tokens issued on behalf of a user for one narrow surface — an addon, an integration, a capability or some devices. Every token must be scoped, so revoking one has a predictable blast radius.`,actions:t(j,{type:`button`,variant:`primary`,size:`sm`,onClick:()=>g(!0),disabled:u.length===0,title:u.length===0?`Create a user first`:`Issue a scoped token`,children:[s(B,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),`New token`]}),children:[s(G,{rows:T,label:`scoped tokens`,isLoading:l||f.some(e=>e.isLoading),loadError:E,emptyText:`No scoped tokens.`,action:{label:`Revoke`,icon:d,isAvailable:()=>!0,onRun:e=>void D(e),busyId:C.isPending?C.variables?.id??null:null,disabled:C.isPending}}),h&&s(ht,{users:u.map(e=>({id:e.id,username:e.username})),onClose:()=>g(!1),onSubmit:e=>S.mutate({userId:e.userId,name:e.name,scopes:e.scopes,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}}),submitting:S.isPending}),_!==null&&s(gt,{token:_.token,label:_.label,onClose:()=>y(null)})]})}e();var yt={one:`admin token`,many:`admin tokens`},bt=7,xt=90,St=80;function Ct(e){let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=xt?t:null}function wt(){let{user:e}=J();return e?.isAdmin?s(Tt,{}):null}function Tt(){let e=x(),r=v.useUtils(),i=v.auth.listAdminTokens.useQuery(),a=q(),{requestProof:c,dialog:l}=Me(`Creating an admin token`),[u,f]=o(``),[p,m]=o(String(bt)),[g,_]=o(null),[y,b]=o(!1),[C,w]=o(null),T=()=>{r.auth.listAdminTokens.invalidate(),r.auth.listAuthAudit.invalidate()},E=v.auth.createAdminToken.useMutation({onSuccess:({token:e,record:t})=>{T(),f(``),m(String(bt)),w({token:e,label:t.name})},onError:e=>_(`Create failed: ${e.message}`)}),D=v.auth.revokeAdminToken.useMutation({onSuccess:T,onError:e=>_(`Revoke failed: ${e.message}`)}),O=je(`admin-token`,yt,T),ee=Date.now(),te=n(()=>(i.data??[]).map(e=>Oe(e,a,ee)),[i.data,a]),k=u.trim(),A=Ct(p),M=k.length>0&&k.length<=St&&A!==null&&!E.isPending&&!y,N=async()=>{if(!M||A===null)return;_(null),b(!0);let e=await c();b(!1),e!==null&&E.mutate({name:k,expiresInDays:A,reauthToken:e})},P=async t=>{await e({title:`Revoke admin token "${t.name}"?`,message:`Every script using it loses access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&(_(null),D.mutate({id:t.id}))};return t(`div`,{"data-testid":`admin-tokens`,children:[l,t(W,{id:`admin-tokens`,title:`Admin tokens`,icon:L,tone:`danger`,notice:K(g,O.outcome),onDismissNotice:()=>{_(null),O.dismiss()},description:t(`div`,{className:`space-y-1`,children:[t(`p`,{children:[`An admin token acts as a `,s(`strong`,{children:`full administrator`}),` for scripts, e.g.`,` `,s(`code`,{className:`font-mono`,children:`node scripts/hub/hub.mjs --token-file <file> …`}),`. Anyone holding it can do anything an admin can.`]}),s(`p`,{children:`It expires in at most 90 days and every use is audited. Creating one asks you to confirm it is you.`})]}),children:[t(`form`,{className:`grid grid-cols-1 items-end gap-2 sm:grid-cols-[1fr_120px_auto]`,onSubmit:e=>{e.preventDefault(),N()},children:[t(`div`,{className:`space-y-1`,children:[s(h,{htmlFor:`admin-token-name`,children:`Token name`}),s(z,{id:`admin-token-name`,value:u,maxLength:St,onChange:e=>f(e.target.value),placeholder:`nightly-backup`})]}),t(`div`,{className:`space-y-1`,children:[s(h,{htmlFor:`admin-token-days`,children:`Expires in (days)`}),s(z,{id:`admin-token-days`,type:`number`,min:1,max:xt,value:p,onChange:e=>m(e.target.value),state:A===null?`error`:`default`})]}),t(j,{type:`submit`,variant:`danger`,size:`sm`,disabled:!M,children:[E.isPending||y?s(S,{className:`h-3.5 w-3.5 animate-spin`}):s(L,{className:`h-3.5 w-3.5`}),`Create admin token`]})]}),A===null&&t(`div`,{className:`text-[11px] text-danger`,children:[`Expiry must be a whole number of days, 1 to `,xt,`.`]}),s(G,{rows:te,label:`admin tokens`,isLoading:i.isLoading,loadError:i.isError?i.error?.message??`Request failed`:null,emptyText:`No admin tokens.`,action:{label:`Revoke`,icon:d,isAvailable:e=>e.status===`active`,onRun:e=>void P(e),busyId:D.isPending?D.variables?.id??null:null,disabled:D.isPending||O.busy},bulk:{revoke:O,noun:yt,isSelectable:e=>e.status===`active`}})]}),C&&s(gt,{token:C.token,label:C.label,onClose:()=>w(null)})]})}var Et={"share-link":`share links`,"admin-token":`admin tokens`,"login-session":`login sessions`};function Y(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Dt(e,t){let n=Y(e,`tokenId`);return Y(e,`name`)??(n===null?void 0:t.get(n))??n??`?`}function X(e){return e.filter(e=>e!==null)}function Ot(e){let t=Y(e,`prefix`);return t===null?null:`Prefix ${t}…`}function kt(e,t){let n=e.detail??{};switch(e.action){case`admin-token-created`:{let e=n.expiresAt;return{title:`Admin token "${Dt(n,t)}" created`,details:X([Ot(n),typeof e==`number`?`Expires ${Re(e)}`:null])}}case`admin-token-used`:{let e=Y(n,`path`);return{title:`Admin token "${Dt(n,t)}" used`,details:X([Ot(n),e===null?null:`Call ${e}`])}}case`admin-token-revoked`:return{title:`Admin token "${Dt(n,t)}" revoked`,details:X([Ot(n)])};case`credentials-revoked`:{let e=Y(n,`kind`)??`credential`,t=n.revoked,r=n.skipped,i=Et[e]??`${e}s`;return{title:`${typeof t==`number`?String(t):`?`} ${i} revoked in bulk`,details:X([typeof r==`number`&&r>0?`${String(r)} skipped`:null,Y(n,`ids`)===null?null:`Ids ${Y(n,`ids`)??``}`])}}case`second-factor-skipped`:{let e=Y(n,`method`),t=Y(n,`factors`);return{title:`Second factor skipped on a trusted network`,details:X([e===null?null:`Signed in with ${Ie(e)}`,t===null?null:`Skipped: ${t.split(`,`).join(`, `)}`])}}default:return{title:e.action,details:Object.entries(n).map(([e,t])=>`${e}: ${String(t)}`)}}}e();var At=100;function jt(){let{user:e}=J();return e?.isAdmin?s(Nt,{}):null}function Mt(){let{data:e}=M(),{data:t}=v.auth.listAdminTokens.useQuery();return n(()=>{let n=new Map;for(let t of e??[])n.set(t.id,t.username);let r=new Map;for(let e of t??[])r.set(e.id,e.name);return{userNameById:n,tokenNameById:r}},[e,t])}function Nt(){let e=v.auth.listAuthAudit.useQuery({limit:At}),{userNameById:n,tokenNameById:r}=Mt(),i=e.data??[];return t(`div`,{"data-testid":`auth-audit`,className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[t(`div`,{className:`px-4 py-2.5 border-b border-border flex items-center gap-2`,children:[s(fe,{className:`h-3.5 w-3.5 text-foreground-subtle`}),s(`div`,{className:`text-xs font-semibold text-foreground`,children:`Authentication audit`}),t(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[`Latest `,At,`, newest first`]})]}),s(`div`,{className:`p-4`,children:e.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(S,{className:`h-3.5 w-3.5 animate-spin`}),`Loading audit trail…`]}):e.isError?t(`div`,{className:`text-[11px] text-danger`,children:[`Could not load the audit trail: `,e.error?.message??`Request failed`]}):i.length===0?s(`div`,{className:`rounded border border-dashed border-border px-3 py-4 text-xs text-foreground-subtle text-center`,children:`No authentication events recorded yet.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border max-h-[420px] overflow-y-auto`,children:i.map(e=>s(Pt,{record:e,userName:e.userId===void 0?null:n.get(e.userId)??e.userId,tokenNameById:r},e.id))})})]})}function Pt({record:e,userName:n,tokenNameById:r}){let i=kt(e,r);return t(`li`,{"data-testid":`auth-audit-row`,className:`px-3 py-2 text-xs space-y-0.5`,children:[t(`div`,{className:`flex flex-wrap items-baseline gap-x-2`,children:[s(`span`,{className:`font-medium text-foreground`,children:i.title}),s(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Re(e.at)})]}),t(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[n!==null&&s(`span`,{className:`text-foreground`,children:n}),e.ip!==void 0&&s(`span`,{className:`font-mono`,children:e.ip}),i.details.map(e=>s(`span`,{className:`font-mono`,children:e},e))]})]})}var Z={loginSessions:`login-sessions`,linkedApps:`linked-apps`,scopedTokens:`scoped-tokens`,adminTokens:`admin-tokens`,shareLinks:`share-links`,legacyApiKeys:`legacy-api-keys`,externalIdentities:`external-identities`,audit:`auth-audit`},Ft={state:`ok`,stateLabel:`available`,showState:!1};function Q(e,t,n,r){return{id:e,name:t,fallbackIcon:n,...Ft,render:r}}function It(){let e=oe(),t=(e.data??[]).length>0;return s(rt,{icon:ct,title:`Tokens & sessions`,subtitle:`Every credential this hub honours — who holds it, what it can reach, when it was last used and when it expires. Pick a kind; revoke one, or select several and revoke them after typing the count.`,groups:[{id:`sessions`,label:`Sessions`,entries:[Q(Z.loginSessions,`Login sessions`,Te,()=>s(mt,{})),Q(Z.linkedApps,`Linked apps`,re,()=>s(ft,{}))]},{id:`tokens`,label:`Tokens`,entries:[Q(Z.scopedTokens,`Scoped tokens`,ge,()=>s(vt,{})),Q(Z.adminTokens,`Admin tokens`,L,()=>s(wt,{})),Q(Z.shareLinks,`Share links`,de,()=>s(Fe,{})),...t?[Q(Z.legacyApiKeys,`Legacy API keys`,we,()=>s(ut,{}))]:[]]},{id:`identity`,label:`Identity`,entries:[Q(Z.externalIdentities,`Sign-in links`,Je,()=>s(lt,{})),Q(Z.audit,`Audit`,fe,()=>s(jt,{}))]}],isLoading:e.isLoading,emptyTitle:`No credential kinds`,emptyDescription:`This hub offers no credential kinds.`})}e();var Lt=3e4,Rt=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],$={title:`Authentication`,subtitle:`Login providers (local password, OIDC, SAML) and second-factor providers (passkeys / WebAuthn). They run in parallel — enable or 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 zt(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:ct,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).`,`Scoped tokens, admin tokens and sessions are managed from Identity → Tokens & sessions.`],setupSteps:[`A fresh hub has one account, admin / changeme — the first sign-in asks for a new password. Add users from Users → New user.`,`Hand out either passwords or scoped tokens — both validate through this provider.`]}:e.startsWith(`auth-oidc`)?{headline:`OpenID Connect (Google, Microsoft, Okta, Keycloak, …).`,icon:Xe,bullets:[`Three-leg redirect flow with PKCE S256 + nonce.`,`id_token is signature-verified against the IdP’s JWKS — no implicit trust.`,`Explicit linking only: an IdP account signs in only the CamStack user who linked it from their profile (My access → Linked sign-in accounts). No auto-created users, no email matching.`,`The linked user’s role, scopes and two-factor authentication apply.`],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.`,`Each user then links their IdP account from My access → Linked sign-in accounts.`]}:e.startsWith(`auth-saml`)?{headline:`SAML 2.0 — enterprise SSO (Azure AD, Okta, OneLogin).`,icon:Xe,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:R,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`)?{headline:`TOTP — second factor.`,icon:R,bullets:[`Time-based codes from an authenticator app (RFC 6238).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:B,bullets:[`Generic authentication provider. No additional hints registered.`]}}function Bt(){let e=Ce({capName:Rt[0].capName},{refetchInterval:Lt}),t=Ce({capName:Rt[1].capName},{refetchInterval:Lt}),r=le(void 0,{refetchInterval:Lt}),i=n(()=>ot(r.data??[]),[r.data]),a=n(()=>{let n=[],r=[e.data??[],t.data??[]];for(let[e,t]of Rt.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]),o=[{id:`authentication`,label:`Authentication providers`,install:{capability:Rt[0].capName,label:$.installLabel},entries:a.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:B,...at(e.isActive),render:()=>s(it,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:s(m,{variant:`info`,className:nt,children:e.stageBadge}),panels:[{id:`about`,title:`About`,icon:zt(e.addonId).icon,content:s(Vt,{addonId:e.addonId})}]})}))}];return s(rt,{icon:B,title:$.title,subtitle:$.subtitle,groups:o,isLoading:e.isLoading||t.isLoading,emptyTitle:$.emptyTitle,emptyDescription:$.emptyDescription})}function Vt({addonId:e}){let n=zt(e),r=n.icon;return t(`div`,{className:`space-y-3 rounded-lg border border-border bg-surface p-2 sm:p-4`,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(st,{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-info/30 bg-info/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-info shrink-0`}),t(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,s(qe,{to:`/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(qe,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function Ht({userId:e,username:n,onClose:r}){let i=x(),a=v.useUtils(),o=ae({userId:e}),c=v.auth.listLoginMethods.useQuery(),l=pe({onSuccess:()=>void a.userManagement.listExternalIdentities.invalidate()}),u=new Map((c.data??[]).flatMap(e=>e.kind===`redirect`?[[e.id,e.label]]:[])),d=o.data??[],f=async(t,r)=>{await i({title:`Remove sign-in link`,message:`"${n}" will no longer be able to sign in with this ${r} account.`,confirmLabel:`Remove`,variant:`danger`})&&l.mutate({userId:e,provider:t.provider,subject:t.subject})};return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(H,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`external-identities-modal`,children:[s(V,{children:t(N,{className:`flex items-center gap-2`,children:[s(re,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Linked sign-in accounts`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),s(I,{className:`space-y-3`,children:o.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(S,{className:`h-3.5 w-3.5 animate-spin`}),`Loading…`]}):d.length===0?s(`p`,{className:`text-xs text-foreground-subtle`,children:`No linked accounts. Only the user can link one, from their own profile page.`}):s(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:d.map(e=>{let n=u.get(e.provider),r=n??e.provider;return t(`li`,{className:`flex items-center gap-3 px-3 py-2 text-xs`,children:[t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`font-medium text-foreground truncate`,children:[r,n===void 0&&s(`span`,{className:`ml-2 rounded bg-foreground-subtle/15 px-1.5 py-0.5 text-[10px] font-normal text-foreground-subtle`,children:`provider unavailable`})]}),t(`div`,{className:`text-[11px] text-foreground-subtle truncate`,children:[e.label??e.subject,` ·`,` `,new Date(e.linkedAt).toLocaleDateString()]})]}),t(`button`,{onClick:()=>void f(e,r),disabled:l.isPending,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[s(De,{className:`h-3 w-3`}),`Remove`]})]},`${e.provider}|${e.subject}`)})})}),s(_,{children:s(j,{onClick:r,variant:`secondary`,children:`Close`})})]})})}function Ut({userId:e,username:n,onClose:r}){let o=a(),c=x(),l=w({userId:e}),u=l.data,d=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=_e({onSuccess:()=>{d(),r()}}),p=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(H,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(V,{children:t(N,{className:`flex items-center gap-2`,children:[s(R,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Two-factor authentication`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(I,{className:`space-y-4`,children:[p===`loading`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(S,{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(Se,{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(j,{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(S,{className:`h-3 w-3 animate-spin`}):s(me,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}e();function Wt({userId:e,username:n,onClose:r}){let{user:i,logout:a}=J(),c=i?.id===e,l=x(),u=v.useUtils(),d=v.auth.listSessions.useQuery({userId:e}),[f,p]=o(null),m=v.auth.revokeSessions.useMutation({onSuccess:(e,t)=>{if(c&&`userId`in t){a();return}u.auth.listSessions.invalidate()},onError:e=>p(`Sign out failed: ${e.message}`)}),h=async e=>{await l({title:`Sign out this session`,message:`"${n}" on ${Ee(e.client).label} will have to sign in again.`,confirmLabel:`Sign out`,variant:`danger`})&&(p(null),m.mutate({id:e.id}))},g=async()=>{await l({title:`Sign out everywhere`,message:c?`Every session of your own account ends, this browser included: you will be signed out here too.`:`Every session of "${n}" ends at once; each device has to sign in again.`,confirmLabel:`Sign out everywhere`,variant:`danger`})&&(p(null),m.mutate({userId:e}))},y=m.isPending&&m.variables!==void 0&&`id`in m.variables?m.variables.id:null;return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(H,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`user-sessions-modal`,children:[s(V,{children:t(N,{className:`flex items-center gap-2`,children:[s(Te,{className:`h-4 w-4 text-primary`}),t(`span`,{children:[`Active sessions`,t(`span`,{className:`mt-0.5 block text-[11px] font-normal text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]})}),t(I,{className:`space-y-3`,children:[f!==null&&s(`div`,{className:`text-[11px] text-danger`,children:f}),s(ze,{sessions:d.data??[],isLoading:d.isLoading,loadError:d.isError?d.error?.message??`Request failed`:null,emptyText:`No active sessions.`,onRevoke:e=>void h(e),revokingId:y})]}),t(_,{className:`justify-between`,children:[t(`button`,{onClick:()=>void g(),disabled:m.isPending||(d.data??[]).length===0,className:`inline-flex items-center gap-1.5 rounded border border-danger/40 px-2.5 py-1 text-[11px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,children:[m.isPending&&y===null?s(S,{className:`h-3 w-3 animate-spin`}):s(Qe,{className:`h-3 w-3`}),`Sign out everywhere`]}),s(j,{onClick:r,variant:`secondary`,children:`Close`})]})]})})}function Gt({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 Kt({scopes:e,isAdmin:n,invalidReason:a}){let o=c(),l=r({queryKey:[`auth`,`previewScope`,e,n],enabled:a===null,queryFn:()=>o.trpcClient.auth.previewScope.query({scopes:[...e],isAdmin:n})}),{data:u}=ye({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(L,{className:`h-3 w-3 shrink-0`}),a]})});if(l.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(S,{className:`h-3 w-3 animate-spin`}),`Resolving…`]});if(l.isError||!l.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=l.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(Gt,{icon:be,label:`Devices they can see`,count:p.device.view.deviceCount,all:p.device.view.all,total:f}),s(Gt,{icon:g,label:`Devices they can operate`,count:p.device.create.deviceCount,all:p.device.create.all,total:f}),s(Gt,{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.`})]})})}e();function qt(e){let t=Ue(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 Jt(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:Ve({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Yt({user:e,onClose:r,onSubmit:a,submitting:c,callerScopes:d}){let f=n(()=>qt(e.scopes??[]),[e.scopes]),[p,m]=o(f),[h,g]=o(f.mode===`advanced`),v=n(()=>Jt(p),[p]),y=!e.isAdmin&&p.mode===`role`&&p.roleId===null,b=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?`Pick what this user can do to see the result.`:A(v),[e.isAdmin,p.mode,p.roleId,v]),x=e=>m({...p,...e});return s(U,{open:!0,onOpenChange:e=>!e&&r(),children:t(H,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-2xl`,children:[t(V,{children:[t(N,{children:[`Access — `,e.username]}),s(`p`,{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.`})]}),t(I,{className:`space-y-4`,children:[y&&t(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[s(L,{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:He.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:()=>x({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(qt(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?l: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(O,{value:p.advancedScopes,onChange:e=>x({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(P,{value:p.selector,onChange:e=>x({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>x({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(Kt,{scopes:v,isAdmin:e.isAdmin,invalidReason:b})]})]}),t(_,{children:[s(j,{variant:`outline`,size:`sm`,onClick:r,children:`Cancel`}),s(j,{size:`sm`,onClick:()=>a([...v]),disabled:c||b!==null,children:c?s(S,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}e();var Xt=8;function Zt(){let e=a(),{user:n}=J(),[r,i]=o(!1),[c,l]=o(``),[u,f]=o(``),[m,h]=o(!1),[g,_]=o(null),{data:v,isLoading:C,isError:w}=M(),O=x(),ee=D(),k=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),A=b({onSuccess:()=>{k(),i(!1),l(``),f(``),h(!1),_(null)},onError:e=>{_(e instanceof Error?e.message:`Failed to create user`)}}),j=E({onSuccess:k}),N=ce({onSuccess:k}),P=p({onSuccess:k}),ne=ve({onSuccess:()=>{k(),ie(null)}}),[F,ie]=o(null),[ae,oe]=o(null),[se,I]=o(null),[le,L]=o(null),ue=v??[];async function de(e){await O({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`})&&j.mutate({id:e.id})}async function fe(e){let t=await ee({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<Xt?`Password must be at least ${String(Xt)} characters.`:null});t===null||t.length===0||await O({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&P.mutate({id:e.id,newPassword:t})}function pe(e,t){t!==e.isAdmin&&N.mutate({id:e.id,isAdmin:t})}function he(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}return t(et,{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(te,{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(me,{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:m,onChange:e=>h(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:()=>A.mutate({username:c,password:u,isAdmin:m}),disabled:A.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:A.isPending?`Creating...`:`Create`})]})]}),C&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading...`}),w&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load`}),!C&&!w&&ue.length===0&&s(`div`,{className:`text-xs text-foreground-subtle`,children:`No data`}),(()=>{let e=e=>j.isPending&&j.variables?.id===e.id||N.isPending&&N.variables?.id===e.id||P.isPending&&P.variables?.id===e.id;return s(y,{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=>pe(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:()=>ie(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(B,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(Qt,{scopes:e.scopes??[]})]})},{key:`createdAt`,header:`Created`,render:e=>s(`span`,{className:`text-foreground-subtle`,children:he(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:()=>oe(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(R,{className:`h-3 w-3`}),`Remove 2FA`]}),t(`button`,{onClick:()=>I(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:`Linked sign-in accounts`,children:[s(re,{className:`h-3 w-3`}),`Sign-in links`]}),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:`Active sessions`,children:[s(Te,{className:`h-3 w-3`}),`Sessions`]}),t(`button`,{onClick:()=>fe(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(T,{className:`h-3 w-3`}),`Reset password`]}),t(`button`,{onClick:()=>de(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(S,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:ue,rowKey:e=>e.id,minWidthPx:560})})(),ae&&s(Ut,{userId:ae.id,username:ae.username,onClose:()=>oe(null)}),se&&s(Ht,{userId:se.id,username:se.username,onClose:()=>I(null)}),le&&s(Wt,{userId:le.id,username:le.username,onClose:()=>L(null)}),F&&s($t,{user:F,onClose:()=>ie(null),onSubmit:e=>ne.mutate({userId:F.id,scopes:e}),submitting:ne.isPending})]})}function Qt({scopes:e}){if(e.length===0)return s(`span`,{className:`font-medium text-warning`,children:`No access`});let n=Ue(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:We(n.roleId).label}),` ·`,` `,F(n.selector)]})}function $t(e){let{user:t}=J(),n=t?.isAdmin===!0;return s(Yt,{...e,callerScopes:n?null:t?.scopes??[]})}var en={"api-keys":Z.scopedTokens,"linked-sessions":Z.linkedApps};function tn(){let[e]=Ge(),t=en[e.get(`tab`)??``];return t===void 0?s(`div`,{className:`flex flex-col p-4`,children:s(tt,{tabs:[{id:`users`,label:`Users`,icon:ne,content:s(Zt,{})},{id:Ye.access.tab,label:`Tokens & sessions`,icon:ge,content:s(It,{}),ownedParams:$e},{id:Ye.authentication.tab,label:`Authentication`,icon:B,content:s(Bt,{}),ownedParams:$e}]})}):s(Ke,{to:Ze(`access`,{integration:t}),replace:!0})}export{tn as IdentityPage};
@@ -0,0 +1 @@
1
+ import{I as e,K as t,Q as n,S as r,W as i,o as a,q as o,x as s,z as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as l,gt as u,ht as d,mt as f,st as p,vt as m}from"./player-overlays-CVsVEZkx.js";import{$a as h,$i as g,Bi as _,Cf as v,Er as y,Hd as b,Hi as x,J as S,Ji as C,Kf as w,Ki as T,Ku as E,Na as D,Od as O,Of as ee,Pu as k,Qa as A,Qi as j,Rt as te,Sd as M,Tn as N,Ui as P,Vi as F,Wi as ne,X as I,Za as L,Zt as R,_u as z,bn as B,bu as V,cr as H,eo as U,fn as W,ga as re,gd as G,io as K,ju as ie,kt as q,lr as ae,ma as oe,na as J,no as Y,pd as se,q as ce,qi as le,sa as ue,sf as de,to as fe,vt as X,wd as pe,wn as me,xd as he,xn as ge,yf as Z,yn as _e}from"./src-DBOD88Il.js";import{Er as ve}from"./client-DdTCFotl.js";import{t as ye}from"./useTranslation-Bc5yH9V9.js";import{$ as be,I as xe,Q as Se,Z as Ce,q as we}from"./index-BhXNFlQG.js";import{t as Te}from"./NodeAddonsSettingsPanel-ud5IAMLM.js";import{t as Ee}from"./device-integration-icon-BRBO6DaZ.js";import{n as De,r as Oe,t as ke}from"./ScanNetworkModal-DeQVAhiv.js";var Ae=m(`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 Q(e){let t=[];for(let n of e)n.type===`probe`&&t.push(n.key),n.type===`group`&&`fields`in n&&t.push(...Q(n.fields));return t}function je(t,n,r){let[a,s]=o(`idle`),[c,l]=o({}),u=i(()=>{let e=[];for(let n of t.sections)e.push(...Q(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;s(`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),s(`idle`)},[r,u,n]),clearProbeResult:f}}n();function Me(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(...Me(n.fields));return t}function Ne(e){return e==null?!0:typeof e==`string`?e.trim()===``:!1}function Pe(e,t={}){for(let n of e){if(n.type===`group`&&`fields`in n){Pe(n.fields,t);continue}`key`in n&&n.key&&`default`in n&&n.default!==void 0&&(t[n.key]=n.default)}return t}function Fe(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`probe-${crypto.randomUUID()}`:`probe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ie({open:t,integrationId:n,addonId:l,onClose:d}){let{t:f}=ye(),p=a(),[m,h]=o({}),[g,_]=o(!1),[v,y]=o(null),[x,S]=o(Fe),C=oe({addonId:l},{enabled:t}),w=C.data?.deviceType??null,T=J({addonId:l,type:w??ve.Camera},{enabled:t&&C.isSuccess&&w!==null}),O=T.data??null;c(()=>{t&&(h(O?Pe(O.sections.flatMap(e=>e.fields)):{}),S(Fe()),_(!1),y(null))},[t,n,O]);let ee=i(()=>({...m,_probeRequestId:x}),[m,x]),A=le({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),j=D(),te=e(async(e,t)=>{_(!0);let n=await j.mutateAsync({addonId:l,type:w??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??{}))Ne(e[i])&&!Ne(a)&&(r[i]=a,t=!0);return t?r:e}),n},[j,l,ee,w]),{testAllStatus:M,hasProbeFields:N,probeResults:P,handleTestAll:F,clearProbeResult:ne}=je(O??{sections:[]},m,te);async function I(e){y(null);try{await A.mutateAsync({addonId:l,type:w??ve.Camera,config:m,integrationId:n}),e?h(O?Pe(O.sections.flatMap(e=>e.fields)):{}):d()}catch(e){y(e instanceof Error?e.message:String(e))}}if(!t)return null;let L=Me((O?.sections??[]).flatMap(e=>e.fields)).filter(e=>Ne(m[e])),R=L.length===0,z=C.isLoading||w!==null&&T.isLoading,B=C.isError||C.isSuccess&&w===null||T.isError||T.isSuccess&&O===null;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[s(`div`,{className:`absolute inset-0 bg-black/60`,onClick:d}),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:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:f(`integrations.addDevice`)}),s(`button`,{onClick:d,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:s(ie,{className:`h-4 w-4`})})]}),s(`div`,{className:`flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-3`,children:z?s(`div`,{className:`flex items-center justify-center py-8`,children:s(b,{className:`h-5 w-5 animate-spin text-primary`})}):B?r(`div`,{className:`flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3`,children:[s(E,{className:`h-4 w-4 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`space-y-1`,children:[s(`p`,{className:`text-xs font-medium text-destructive`,children:`Provider unavailable`}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`The addon `,s(`span`,{className:`font-mono`,children:l}),` is not ready or does not support manual device creation. Check that the integration is online and try again.`]})]})]}):s(xe,{schema:O,values:m,onChange:h,onTestField:te,probeResults:P,onClearProbe:ne})}),!B&&!z&&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:[s(G,{className:`h-3.5 w-3.5`}),`Test logs`,s(`span`,{className:`font-mono text-[9px] opacity-60`,children:x.slice(0,14)})]}),s(u,{className:`h-3.5 w-3.5 transition-transform ${g?`rotate-180`:``}`})]}),g&&s(`div`,{className:`border-t border-border max-h-64 overflow-hidden`,children:s(X,{addonId:l,requestId:x,limit:50,maxHeight:`max-h-64`,showFilters:!1,showScope:!1,className:`border-0 rounded-none`})})]}),!B&&!z&&(v||L.length>0)&&s(`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:[s(E,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),s(`p`,{className:`text-[11px] text-destructive`,children:v||`Required: ${L.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:[s(`button`,{onClick:d,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`)}),!B&&N&&r(`button`,{type:`button`,onClick:F,disabled:M===`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:[M===`testing`?s(b,{className:`h-3.5 w-3.5 animate-spin`}):s(k,{className:`h-3.5 w-3.5`}),`Test All`]})]}),r(`div`,{className:`flex items-center gap-2`,children:[s(`button`,{onClick:()=>I(!0),disabled:B||!R||A.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`)}),s(`button`,{onClick:()=>I(!1),disabled:B||!R||A.isPending,className:`rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50`,children:A.isPending?f(`integrations.saving`):f(`integrations.save`)})]})]})]})]})}var Le=1500;function $({addonId:e,integrationId:t,jobId:n,onFinished:i}){let{t:a}=ye(),o=_(),c=(P({addonId:e,integrationId:t},{refetchInterval:e=>(e.state.data??[]).some(e=>e.state===`running`)?Le:!1}).data??[]).find(e=>e.jobId===n);if(!c)return null;let l=c.state===`running`,u=c.processed,d=c.total>0?Math.round(u/c.total*100):0;!l&&c.finishedAt!==null&&i();let f=[`${u}/${c.total} ${a(`integrations.adoptJobProcessed`,{defaultValue:`processed`})}`];c.adopted>0&&f.push(`${c.adopted} ${a(`integrations.adoptJobAdded`,{defaultValue:`added`})}`),c.alreadyAdopted>0&&f.push(`${c.alreadyAdopted} ${a(`integrations.adoptJobSkipped`,{defaultValue:`already there`})}`),c.failed>0&&f.push(`${c.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?s(b,{className:`h-3.5 w-3.5 animate-spin text-primary shrink-0`}):c.failed>0?s(E,{className:`h-3.5 w-3.5 text-destructive shrink-0`}):c.state===`cancelled`?s(Z,{className:`h-3.5 w-3.5 text-foreground-subtle shrink-0`}):s(v,{className:`h-3.5 w-3.5 text-primary shrink-0`}),s(`p`,{className:`text-[11px] text-foreground`,children:p}),l&&s(`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`})})]}),s(`div`,{className:`h-1 w-full rounded-full bg-border overflow-hidden`,children:s(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${d}%`},role:`progressbar`,"aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100})}),c.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 Re(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 ze=`devices`,Be={id:ze,label:`Devices`,isDefault:!0},Ve=2e4,He=100;function Ue({addonId:n,integrationId:i,onClose:l}){let{t:u}=ye(),d=a(),[f,p]=o(new Set),[m,g]=o(new Set),[_,v]=o(new Map),[y,S]=o(null),{data:C}=h(),w=(C??[]).find(e=>e.addonId===n)?.supportsLocationImport??!1,[D,O]=o(!0),k=F({addonId:n,integrationId:i}).data?.filters,A=k&&k.length>0?k:[Be],[j,te]=o(A.find(e=>e.isDefault)?.id??(A.some(e=>e.id===ze)?ze:A[0].id)),M=j!==ze,N=ne(),P=x({addonId:n,integrationId:i,page:1,pageSize:Ve,filter:j}),I=P.refetch,L=N.mutate,R=e(()=>{L({addonId:n,integrationId:i},{onSettled:()=>{I()}})},[L,n,i,I]),B=t(null);c(()=>{let e=`${n}::${i}`;B.current===e||P.isLoading||(B.current=e,(P.data?.candidates.length??0)===0&&R())},[n,i,P.isLoading,P.data,R]);let H=N.isPending,U=N.isError?N.error instanceof Error?N.error.message:String(N.error):null,W=typeof N.data?.lastError==`string`&&N.data.lastError.length>0?N.data.lastError:null,re=P.data?.candidates??[],G=P.isError?P.error instanceof Error?P.error.message:String(P.error):null,K=T(),[q,ae]=o(null),oe=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})},[]),J=e(e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Y=e((e,t)=>{v(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})},[]),se=e(e=>{let t={};for(let n of e){let e=_.get(n);e&&e.hiddenChildIds.size>0&&(t[n]={hiddenChildIds:[...e.hiddenChildIds]})}return Object.keys(t).length>0?t:void 0},[_]),le=e(async()=>{S(null);let e=[...f];if(e.length!==0)try{let t=se(e),{jobId:r}=await K.mutateAsync({addonId:n,integrationId:i,filter:j,childNativeIds:e,...t?{perCandidate:t}:{},...w?{importLocations:D}:{}});ae(r),p(new Set),v(new Map)}catch(e){S(e instanceof Error?e.message:String(e))}},[f,se,K,n,i,j,w,D]),ue=t(null),de=e(()=>{q===null||ue.current===q||(ue.current=q,I(),d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]}))},[q,I,d]),fe=e(e=>{te(e),p(new Set),g(new Set),v(new Map),S(null)},[]),X=f.size,pe=q!==null&&X===0&&!K.isPending;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[s(`div`,{className:`absolute inset-0 bg-black/60`,onClick:l}),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:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:u(`integrations.adoptDevices`,{defaultValue:`Adopt devices`})}),s(`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:[w&&r(`label`,{className:`flex items-center gap-1.5 cursor-pointer text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:[s(`input`,{type:`checkbox`,checked:D,onChange:e=>O(e.target.checked),className:`accent-primary`}),u(`integrations.importLocations`,{defaultValue:`Import locations from the integration`})]}),s(`button`,{onClick:l,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Close`,children:s(ie,{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:[(U??G??W)&&re.length===0&&s(`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:[s(E,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`min-w-0`,children:[s(`p`,{className:`text-xs font-medium text-destructive`,children:u(`integrations.adoptRefreshFailed`,{defaultValue:`Could not discover devices.`})}),s(`p`,{className:`text-[11px] text-destructive/90 mt-0.5`,children:U??G??W})]})]})}),A.length>1&&s(We,{filters:A,activeFilter:j,onSelect:fe}),s(`div`,{className:`flex-1 min-h-0`,children:s(ce,{mode:`generic`,items:re,pageSize:He,getKey:e=>e.childNativeId,getSearchText:Re,getFilterType:e=>e.type,filterOptions:z(),filterLabel:u(`integrations.adoptColType`,{defaultValue:`Type`}),isLoading:P.isLoading||H&&re.length===0,searchPlaceholder:u(`integrations.adoptSearch`,{defaultValue:`Search candidates…`}),emptyLabel:(U??G??W)&&re.length===0?``:u(`integrations.adoptNoCandidates`,{defaultValue:`No candidate devices found.`}),toolbar:r(`button`,{type:`button`,onClick:R,disabled:H,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:[s(he,{className:`h-3.5 w-3.5 ${H?`animate-spin`:``}`}),u(`integrations.adoptRefresh`,{defaultValue:`Refresh`})]}),columns:[{key:`name`,header:u(`integrations.adoptColName`,{defaultValue:`Name`}),headerClassName:`w-[55%]`,cell:e=>s(Ge,{candidate:e,expandable:!M,expanded:m.has(e.childNativeId),onToggleExpand:()=>J(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=V(e.type),n=t.icon;return r(`span`,{className:`inline-flex items-center gap-1.5 text-[10px] text-foreground-subtle`,children:[s(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=>s(`div`,{className:`flex items-center justify-end`,children:s(`button`,{onClick:()=>oe(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)&&s(ee,{className:`h-3 w-3 text-primary-foreground`})})})}],isExpanded:e=>!M&&m.has(e.childNativeId),renderExpanded:M?void 0:e=>s(Ke,{candidate:e,hiddenChildIds:_.get(e.childNativeId)?.hiddenChildIds??new Set,onToggleChildHidden:t=>Y(e.childNativeId,t)}),rowClassName:e=>e.alreadyAdopted?`opacity-60`:f.has(e.childNativeId)?`bg-primary/5`:``})})]}),y&&s(`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:[s(E,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),s(`p`,{className:`text-[11px] text-destructive`,children:y})]})}),q!==null&&s($,{addonId:n,integrationId:i,jobId:q,onFinished:de}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[s(`div`,{}),r(`div`,{className:`flex items-center gap-2`,children:[s(`button`,{onClick:l,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:pe?l:le,disabled:!pe&&(X===0||K.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:[K.isPending&&s(b,{className:`h-3.5 w-3.5 animate-spin`}),pe?u(`integrations.close`,{defaultValue:`Close`}):u(`integrations.addSelected`,{defaultValue:`Add selected`}),!pe&&X>0?` (${X})`:``]})]})]})]})]})}function We({filters:e,activeFilter:t,onSelect:n}){return s(`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 s(`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 Ge({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:[s(n?u:d,{className:`h-3.5 w-3.5`}),o]}):s(`span`,{className:`flex h-5 w-5 flex-shrink-0 items-center justify-center text-foreground-subtle/40`,children:`—`}),s(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),e.alreadyAdopted&&s(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-[9px] font-medium text-success shrink-0`,children:a})]})}function Ke({candidate:e,hiddenChildIds:t,onToggleChildHidden:n}){let i=e.children??[];return i.length===0?null:s(`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:[s(`span`,{className:`text-[11px] text-foreground truncate flex-1 min-w-0`,children:e.name}),a.length>0&&s(`span`,{className:`text-[9px] text-foreground-subtle truncate`,children:a.join(`, `)}),s(`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:s(i?f:de,{className:`h-3 w-3`})})]},e.childNativeId)})})}n();function qe(e){let t=[];for(let n of e){if(n.type===`group`){t.push(...qe(n.fields));continue}`key`in n&&typeof n.key==`string`&&t.push(n.key)}return t}function Je(e,t){if(!e)return{};let n=new Set(e.sections.flatMap(e=>qe(e.fields))),r={};for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=t[e]);return r}function Ye(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 Xe({integrationId:e,addonId:t,name:n,kind:o,mode:c,brokerKind:l,canTest:u=!1,trpc:d,onClose:f}){let{t:p}=ye(),m=a(),{data:h,isLoading:g}=U({id:e},{enabled:c===`account`||c===`broker`}),_=i(()=>{let e=h?.brokerId;return typeof e==`string`?e:null},[h]),{data:v,isLoading:y}=H({addonId:t,nodeId:`hub`},{enabled:c===`account`}),x=i(()=>v?Ye(v):null,[v]),S=Y(),C=(t,n)=>{S.mutate({id:e,settings:t,...n?{secretKeys:[...n]}:{}},{onSuccess:()=>{m.invalidateQueries(),f()}})};return s(_e,{open:!0,onOpenChange:e=>!e&&f(),children:r(ge,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[s(me,{children:r(N,{children:[p(`integrations.editConfig`,{defaultValue:`Edit configuration`}),` — `,n]})}),s(B,{children:c===`broker`?l?r(`div`,{className:`space-y-3`,children:[s(`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`}),`:`,` `,s(`span`,{className:`font-mono text-foreground-subtle`,children:_})]}),S.isPending?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[s(b,{className:`h-3 w-3 animate-spin`}),p(`integrations.saving`,{defaultValue:`Saving…`})]}):s(Oe,{kind:l,onResolved:e=>{C({brokerId:e})},onBack:f}),S.isError&&s(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.relinkFailed`,{defaultValue:`Failed to update broker link.`})})]}):s(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.noBrokerKind`,{defaultValue:`This integration declares device-adoption but its addon manifest has no brokerKind.`})}):c===`account`?g||y?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[s(b,{className:`h-3 w-3 animate-spin`}),p(`integrations.loading`,{defaultValue:`Loading…`})]}):s(De,{addonId:t,configSchema:x,canTest:u,initialName:n,initialConfig:Je(x,h??{}),submitLabel:p(`integrations.save`,{defaultValue:`Save`}),hideName:!0,onSave:({config:e,secretKeys:t})=>C(e,t),onBack:f}):s(W,{trpc:d,addonId:t,nodeId:`hub`,title:n})})]})})}function Ze(e){return e==null?!1:e.sections.some(e=>e.fields.length>0)}n();function Qe(){let{t}=ye(),{integrationId:n}=Se(),u=a(),d=Ce(),[f,m]=be(),_=l(),[v,x]=o(!1),[T,E]=o(!1),[D,ee]=o(!1),[k,P]=o(!1),{data:F,isLoading:ne}=A({id:n??``},{enabled:!!n}),{data:z}=H({addonId:F?.addonId??``,nodeId:`hub`},{enabled:!!F?.addonId}),{data:V,isSuccess:U}=h(),W=i(()=>{let e=F?.addonId;return!e||!U?null:(V??[]).find(t=>t.addonId===e)?.kind===`device-adoption`?`device-adoption`:`device-provider`},[V,F?.addonId,U]),{data:ie}=j({}),oe=i(()=>(ie?.providers??[]).some(e=>e.addonId===F?.addonId),[ie,F?.addonId]),J=W!==null,Y=F?.info?.fixed===!0,le=J?W===`device-adoption`?t(`integrations.adoptDevices`,{defaultValue:`Adopt devices`}):t(`integrations.addDevice`):t(`integrations.addDeviceLoading`,{defaultValue:`Loading…`}),de=i(()=>{let e=F?.addonId;return!e||!U?null:(V??[]).find(t=>t.addonId===e)?.brokerKind??null},[V,F?.addonId,U]),he=i(()=>{let e=F?.addonId;return!e||!U?!1:(V??[]).find(t=>t.addonId===e)?.canTest===!0},[V,F?.addonId,U]),Z=i(()=>{let e=F?.addonId;return!e||!U?null:(V??[]).find(t=>t.addonId===e)?.mode??null},[V,F?.addonId,U]);c(()=>{f.get(`add`)===`1`&&J&&(x(!0),m(e=>{let t=new URLSearchParams(e);return t.delete(`add`),t},{replace:!0}))},[f,J,m]);let ve=z!=null&&Array.isArray(z.sections)&&z.sections.some(e=>e.fields.length>0),{data:xe}=ae({addonId:F?.addonId??``,nodeId:`hub`},{enabled:!!F?.addonId&&Z!==`account`}),we=Z!==null&&Z!==`account`&&Ze(xe),De=i(()=>F?.addonId?[F.addonId]:[],[F?.addonId]),{data:Oe}=ue({projection:`slim`},{refetchInterval:3e4}),Q=[[`integrations`,`get`],{input:{id:n??``},type:`query`}],je=K({onMutate:async e=>{await u.cancelQueries({queryKey:Q});let t=u.getQueryData(Q);return t!=null&&u.setQueryData(Q,{...t,enabled:e.enabled}),{previous:t}},onError:(e,t,n)=>{let r=n;r?.previous!=null&&u.setQueryData(Q,r.previous)},onSettled:()=>{u.invalidateQueries({queryKey:[[`integrations`]]}),u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Me=L({onSuccess:()=>{u.invalidateQueries({queryKey:[[`integrations`]]}),u.invalidateQueries({queryKey:[[`deviceManager`]]}),d(`/integrations`)}}),Ne=y({onSuccess:()=>{u.invalidateQueries({queryKey:[[`integrations`]]}),u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Pe=re({onSuccess:()=>{u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Fe=C({onSuccess:()=>{u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Le=g({onSuccess:()=>{u.invalidateQueries({queryKey:[[`deviceManager`]]})}}),$=i(()=>Oe??[],[Oe]),Re=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},[$]),ze=e(e=>Re.get(e)??null,[Re]),{data:Be}=fe(void 0),Ve=i(()=>S(Be),[Be]),He=e(e=>d(`/devices/${String(e)}`),[d]),We=i(()=>{let e=F?.id;return e?$.filter(t=>{let n=Ve(t);return n.kind===`resolved`&&n.integration.id===e}):[]},[$,F?.id,Ve]),Ge=i(()=>Be===void 0?null:I(We).length,[Be,We])??`…`;return ne?r(`div`,{className:`p-4`,children:[s(`div`,{className:`h-16 rounded-lg bg-surface animate-pulse mb-4`}),s(`div`,{className:`h-40 rounded-lg bg-surface animate-pulse`})]}):F?r(`div`,{className:`p-4 space-y-4 overflow-x-hidden`,children:[s(te,{items:[{label:`Integrations`,onClick:()=>d(`/integrations`)},{label:F.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:[s($e,{addonId:F.addonId}),r(`div`,{className:`min-w-0`,children:[s(`h1`,{className:`text-lg font-semibold text-foreground truncate`,children:F.name}),r(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5 truncate`,children:[F.addonId,` · `,Ge,` `,t(`integrations.devices`)]})]})]}),r(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[oe&&r(`button`,{onClick:()=>E(!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:[s(pe,{className:`h-3.5 w-3.5`}),`Scan network`]}),!Y&&r(`button`,{onClick:()=>x(!0),disabled:!J,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:le,children:[s(O,{className:`h-3.5 w-3.5`}),le]}),r(`div`,{className:`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 transition-colors ${je.isPending?`opacity-60`:``} ${F.enabled?`border-success/30 bg-success/5`:`border-border bg-surface`}`,title:t(`integrations.toggleHint`,{defaultValue:`Click to toggle`}),children:[s(R,{checked:F.enabled,onCheckedChange:e=>je.mutate({id:n,enabled:e}),disabled:je.isPending,"aria-label":F.enabled?`Disable integration`:`Enable integration`}),s(`span`,{className:`text-[11px] font-medium ${F.enabled?`text-success`:`text-foreground-subtle`}`,children:F.enabled?`Enabled`:`Disabled`}),je.isPending&&s(b,{className:`h-3 w-3 animate-spin text-foreground-subtle`})]}),Z!==`standalone`&&(ve||W===`device-adoption`)&&r(`button`,{onClick:()=>ee(!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:[s(se,{className:`h-3 w-3`}),t(`integrations.config`)]}),r(`button`,{onClick:()=>P(!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:[s(G,{className:`h-3 w-3`}),t(`integrations.logs`,{defaultValue:`Logs`})]}),s(q,{label:`Restart`,icon:M,title:`Restart "${F.name}"?`,description:`Restarting the addon will briefly disconnect every device backed by it (${Ge} active). Streams will reconnect automatically.`,confirmLabel:`Restart`,triggerVariant:`outline`,confirmVariant:`danger`,disabled:Ne.isPending,action:()=>Ne.mutateAsync({addonId:F.addonId})}),!Y&&n&&s(q,{label:t(`integrations.delete`,{defaultValue:`Delete`}),icon:p,title:t(`integrations.deleteTitle`,{defaultValue:`Delete integration?`}),description:t(`integrations.deleteWarning`,{defaultValue:`This removes the integration "{{name}}" and its {{count}} device(s). The addon will restart. This cannot be undone.`,name:F.name,count:Ge}),confirmLabel:t(`integrations.confirmDelete`,{defaultValue:`Delete integration`}),triggerVariant:`outline`,confirmVariant:`danger`,className:`border-danger bg-danger/10 text-danger hover:bg-danger hover:text-background`,disabled:Me.isPending,action:()=>Me.mutateAsync({id:n})})]})]}),we&&s(Te,{nodeId:null,addonIds:De,level:`global`,surface:`integration`,title:t(`integrations.settings`,{defaultValue:`Settings`})}),s(ce,{context:`integration-detail`,devices:$,trpc:_.trpcClient,integrationOf:Ve,forceIntegrationId:F.id,urlScope:`root`,lsKey:`integration-detail:${F.addonId}`,resolveIntegrationIcon:Ee,resolveParent:ze,onNavigate:He,batchActions:{remove:Pe.mutate,disable:Fe.mutate,enable:Le.mutate},...Y?{}:{onDeleteDevice:e=>Pe.mutate({deviceId:e.id})}}),v&&n&&W===`device-adoption`&&s(Ue,{addonId:F.addonId,integrationId:n,onClose:()=>x(!1)}),v&&n&&W===`device-provider`&&s(Ie,{open:v,integrationId:n,addonId:F.addonId,onClose:()=>x(!1)}),T&&F&&s(ke,{open:T,scope:{addonId:F.addonId,label:F.name},onClose:()=>E(!1)}),D&&n&&W!==null&&Z!==null&&s(Xe,{integrationId:n,addonId:F.addonId,name:F.name,kind:W,mode:Z,brokerKind:de,canTest:he,trpc:_.trpcClient,onClose:()=>ee(!1)}),k&&s(_e,{open:!0,onOpenChange:e=>!e&&P(!1),children:r(ge,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`md:max-w-5xl md:h-[80vh]`,children:[s(me,{children:r(N,{className:`flex items-center gap-2 min-w-0`,children:[s(G,{className:`h-4 w-4 text-primary shrink-0`}),s(`span`,{className:`truncate`,children:F.name}),r(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate font-normal`,children:[F.addonId,n?` · ${n}`:``]})]})}),s(B,{className:`min-h-0 overflow-hidden p-0`,children:s(X,{addonId:F.addonId,limit:200,maxHeight:`max-h-full`,showScope:!1,className:`h-full border-0 rounded-none`})})]})})]}):r(`div`,{className:`flex flex-col items-center justify-center py-20 px-6 text-center gap-4`,children:[s(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-foreground-subtle/10`,children:s(Ae,{className:`h-6 w-6 text-foreground-subtle`})}),r(`div`,{className:`space-y-1 max-w-sm`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`integrations.integrationNotFound`,{defaultValue:`Integration not found`})}),s(`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:()=>d(`/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:[s(w,{className:`h-3 w-3`}),t(`integrations.backToList`,{defaultValue:`Back to integrations`})]})]})}function $e({addonId:e}){let t=we(e),[n,r]=o(!1);return!t||n?null:s(`img`,{src:t,alt:``,className:`h-8 w-8 rounded-lg shrink-0`,onError:()=>r(!0)})}export{Qe as IntegrationDetailPage};
@@ -0,0 +1 @@
1
+ import{Q as e,S as t,W as n,b as r,o as i,q as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{st as s}from"./player-overlays-CVsVEZkx.js";import{$n as c,Ad as l,Cd as u,Dd as d,G as f,Gn as p,Hd as m,K as h,Od as g,Pi as _,Pn as v,Pu as ee,Sn as y,Tn as b,ai as x,bn as S,br as C,ci as w,di as te,fd as ne,fi as re,ii as ie,jn as T,li as ae,si as E,ui as D,wn as O,xn as k,yn as A,zd as j}from"./src-DBOD88Il.js";import{t as M}from"./monitor-smartphone-DbkPiYT_.js";import{Cr as N,Nt as P,tr as F}from"./client-DdTCFotl.js";import{I,Z as L}from"./index-BhXNFlQG.js";import{t as R}from"./BrokerForm-C1gCAO_i.js";import{n as z,r as B,t as V}from"./AddonIntegrationBody-FGAYdPUA.js";e();var H=`kind`,U=`name`,W=`restore`,G=`restoreId`;function oe(e){return{sections:[{id:`broker-identity`,title:`Broker`,columns:1,fields:[{type:`select`,key:H,label:`Kind`,options:e.map(e=>({value:e.key,label:e.label})),disabled:e.length<=1},{type:`text`,key:U,label:`Name`,placeholder:`My Home Assistant`,required:!0},{type:`boolean`,key:W,label:`Restore a broker that was removed, under its original id`,description:`Devices remember the broker id they were discovered under, so restoring the original id reconnects them instead of needing re-discovery. An id that is still in use is refused.`},{type:`text`,key:G,label:`Original broker id`,placeholder:`ha_004`,required:!0,showWhen:{field:W,equals:!0}}]}]}}function K(e){let t=t=>{let n=e[t];return typeof n==`string`?n.trim():``},n=t(H);if(n===``)return{ok:!1,problem:`Pick a kind.`};let r=t(U);if(r===``)return{ok:!1,problem:`Enter a name before saving.`};if(e.restore!==!0)return{ok:!0,identity:{kindKey:n,name:r,restoreId:null}};let i=t(G);return i===``?{ok:!1,problem:`Enter the original id, or turn restore off to create a new broker.`}:{ok:!0,identity:{kindKey:n,name:r,restoreId:i}}}var q={"home-assistant":`Home Assistant`,mqtt:`MQTT`};function J(e){return q[e]??e}function se(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.addonId==`string`&&Array.isArray(e.kinds)):[]}var ce={connected:`success`,connecting:`warning`,disconnected:`default`,"auth-failed":`danger`,unreachable:`danger`,error:`danger`};function le({status:e}){return o(c,{variant:ce[e],className:`text-[10px]`,children:e})}function ue(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`):[]}function Y({title:e,subtitle:n,onClose:r,children:i}){return o(A,{open:!0,onOpenChange:e=>!e&&r(),children:t(k,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[t(O,{children:[o(b,{children:e}),n&&o(y,{children:n})]}),o(S,{className:`space-y-3 pr-1`,children:i})]})})}function de({kinds:e,onClose:r,onDone:s}){let c=i(),l=n(()=>oe(e.map(e=>({key:X(e),label:e.label}))),[e]),[u,d]=a(()=>({[H]:X(e[0]),[U]:``,[W]:!1,[G]:``})),[f,p]=a(null),m=e.find(e=>X(e)===u.kind)??e[0],h=m?.kind??``,g=m?.addonId,_=ie({onSuccess:()=>{c.invalidateQueries({queryKey:[[`broker`,`list`]]}),s()}}),v=e=>{let t=K(u);if(!t.ok){p(t.problem);return}p(null);let{name:n,restoreId:r}=t.identity;_.mutate({kind:h,name:n,settings:e,...r===null?{}:{id:r},...g===void 0?{}:{addonId:g}})};return t(Y,{title:`Add broker`,subtitle:`Register a message broker for exporters and automations.`,onClose:_.isPending?()=>{}:r,children:[o(I,{schema:l,values:u,onChange:d}),f!==null&&o(T,{message:f}),_.isError&&o(T,{message:_.error instanceof Error?_.error.message:String(_.error)}),h&&o(R,{kind:h,...g===void 0?{}:{addonId:g},onSubmit:v,onCancel:r,submitLabel:_.isPending?`Adding…`:`Add broker`,disabled:_.isPending},X(m))]})}function X(e){return e===void 0?``:`${e.addonId??``}::${e.kind}`}function fe({broker:e,onClose:r,onDone:a}){let s=i(),c=x({id:e.id,addonId:e.addonId}),l=te({onSuccess:()=>{s.invalidateQueries({queryKey:[[`broker`,`list`]]}),s.invalidateQueries({queryKey:[[`broker`,`getSettings`],{input:{id:e.id,addonId:e.addonId}}]}),a()}}),u=n(()=>{let e=c.data;return e&&typeof e==`object`?{...e}:{}},[c.data]);return o(Y,{title:`Edit ${e.name}`,subtitle:`${J(e.kind)} · ${e.id}`,onClose:l.isPending?()=>{}:r,children:c.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(m,{className:`h-3.5 w-3.5 animate-spin`}),` Loading settings…`]}):c.isError?t(`div`,{className:`space-y-3`,children:[o(T,{message:`Failed to load settings: ${c.error instanceof Error?c.error.message:`Unknown error`}`}),o(`div`,{className:`flex justify-end`,children:o(v,{variant:`outline`,size:`sm`,onClick:r,children:`Close`})})]}):t(`div`,{className:`space-y-3`,children:[l.isError&&o(T,{message:l.error instanceof Error?l.error.message:String(l.error)}),o(R,{kind:e.kind,addonId:e.addonId,initialValues:u,onSubmit:t=>{l.mutate({id:e.id,settings:t,addonId:e.addonId})},onCancel:r,submitLabel:l.isPending?`Saving…`:`Save`,disabled:l.isPending})]})})}function pe({broker:e,onEdit:n}){let r=i(),c=p(),[u,d]=a(null),f=re({onSuccess:e=>d(e.ok?{ok:!0}:{ok:!1,error:e.error}),onError:e=>d({ok:!1,error:e instanceof Error?e.message:String(e)})}),h=D({onSuccess:()=>{r.invalidateQueries({queryKey:[[`broker`,`list`]]})}}),g=async()=>{await c({title:`Delete broker`,message:`Delete broker "${e.name}"? Integrations that depend on it will stop working.`,confirmLabel:`Delete`,variant:`danger`})&&h.mutate({id:e.id,addonId:e.addonId})};return t(`tr`,{className:`border-b border-border last:border-0`,children:[o(`td`,{className:`px-3 py-2 text-xs text-foreground font-medium`,children:e.name}),o(`td`,{className:`px-3 py-2 text-xs text-foreground-subtle`,children:J(e.kind)}),t(`td`,{className:`px-3 py-2`,children:[o(le,{status:e.status}),u&&o(`span`,{className:`ml-2 text-[10px] ${u.ok?`text-success`:`text-danger`}`,children:u.ok?`OK`:u.error??`failed`})]}),o(`td`,{className:`px-3 py-2`,children:t(`div`,{className:`flex items-center justify-end gap-1.5`,children:[t(v,{variant:`outline`,size:`sm`,onClick:()=>f.mutate({id:e.id,addonId:e.addonId}),disabled:f.isPending,title:`Test connection`,children:[f.isPending?o(m,{className:`h-3 w-3 animate-spin`}):o(ee,{className:`h-3 w-3`}),`Test`]}),t(v,{variant:`outline`,size:`sm`,onClick:()=>n(e),title:`Edit`,children:[o(l,{className:`h-3 w-3`}),` Edit`]}),t(v,{variant:`outline`,size:`sm`,className:`border-danger/40 text-danger hover:bg-danger/10`,onClick:()=>{g()},disabled:h.isPending,title:`Delete`,children:[h.isPending?o(m,{className:`h-3 w-3 animate-spin`}):o(s,{className:`h-3 w-3`}),`Delete`]})]})})]})}function me({addonId:e}={}){let r=w({}),i=ae(),s=n(()=>ue(r.data).filter(t=>e===void 0||t.addonId===e),[r.data,e]),[c,l]=a(!1),[u,d]=a(null),f=n(()=>{let t=new Map;for(let n of se(i.data))if(!(e!==void 0&&n.addonId!==e))for(let e of n.kinds)t.set(`${n.addonId}::${e.kind}`,{addonId:n.addonId,kind:e.kind,label:e.label});for(let e of s)[...t.values()].some(t=>t.kind===e.kind)||t.set(`::${e.kind}`,{kind:e.kind,label:J(e.kind)});return[...t.values()]},[s,i.data,e]);return t(`div`,{className:`space-y-3`,children:[o(`div`,{className:`flex items-center justify-end`,children:t(v,{variant:`primary`,size:`sm`,onClick:()=>l(!0),disabled:f.length===0,title:f.length===0?`No broker providers available`:void 0,children:[o(g,{className:`h-3.5 w-3.5`}),` Add broker`]})}),o(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:t(`table`,{className:`w-full min-w-[36rem] border-collapse`,children:[o(`thead`,{children:t(`tr`,{className:`border-b border-border bg-background/50`,children:[o(`th`,{className:`px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Name`}),o(`th`,{className:`px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Kind`}),o(`th`,{className:`px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Status`}),o(`th`,{className:`px-3 py-2 text-right text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Actions`})]})}),t(`tbody`,{children:[r.isLoading&&o(`tr`,{children:t(`td`,{colSpan:4,className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:[o(m,{className:`inline h-4 w-4 animate-spin`}),` Loading brokers…`]})}),r.isError&&o(`tr`,{children:t(`td`,{colSpan:4,className:`px-3 py-4 text-center text-xs text-danger`,children:[`Failed to load brokers:`,` `,r.error instanceof Error?r.error.message:`Unknown error`]})}),!r.isLoading&&!r.isError&&s.length===0&&o(`tr`,{children:o(`td`,{colSpan:4,className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`No brokers registered yet. Add one to publish device events for downstream automations.`})}),s.map(e=>o(pe,{broker:e,onEdit:d},e.id))]})]})}),c&&o(de,{kinds:f,onClose:()=>l(!1),onDone:()=>l(!1)}),u&&o(fe,{broker:u,onClose:()=>d(null),onDone:()=>d(null)})]})}function he(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let t=e.name;if(typeof t==`string`)return t}return null}function Z(e){let t=e,n=t?.manifest;if(n?.id===void 0)return null;let r=(n.capabilities??[]).map(he).filter(e=>e!==null);return{addonId:n.id,displayName:n.packageDisplayName??n.name??n.id,capNames:r,processState:t?.process?.state??null}}function ge(e,t){return Object.entries(e).filter(([,e])=>e===t).map(([e])=>e)}function _e(e,t){return t.find(t=>e.capNames.includes(t))??null}function Q(e){switch(e){case`running`:return{state:`ok`,label:`running`};case`crashed`:case`failed`:return{state:`error`,label:e};case`stopped`:case`disabled`:return{state:`off`,label:`stopped`};default:return{state:`unknown`,label:e??`unknown`}}}e();var $=1e4,ve=[{kind:`device-export`,label:`Device export`,icon:ne,installLabel:`Add export`},{kind:`email`,label:`Email`,icon:j,installLabel:`Add email provider`},{kind:`broker`,label:`Message brokers`,icon:u,installLabel:`Add broker addon`}];function ye(){let e=C(void 0,{refetchInterval:$}),i=L();return o(B,{icon:d,title:`Connectivity`,subtitle:`External systems this hub talks to — device exporters, email relays and message brokers.`,groups:n(()=>{let n=(e.data??[]).map(Z).filter(e=>e!==null);return ve.map(e=>{let a=ge(P,e.kind),s=n.flatMap(n=>{let s=_e(n,a);if(s===null)return[];let c=Q(n.processState);return[{id:n.addonId,name:n.displayName,fallbackIcon:e.icon,state:c.state,stateLabel:c.label,render:()=>o(V,{addonId:n.addonId,displayName:n.displayName,capName:s,isActive:n.processState===`running`,badges:t(r,{children:[o(xe,{processState:n.processState}),o(Se,{kind:e.kind,addonId:n.addonId})]}),lead:e.kind===`device-export`?o(h,{addonId:n.addonId}):void 0,panels:be(e.kind,n.addonId,e=>i(`/devices/${e}`))})}]});return{id:e.kind,label:e.label,entries:s,install:{capability:a[0]??e.kind,label:e.installLabel}}})},[e.data,i]),isLoading:e.isLoading,emptyTitle:`No external systems installed`,emptyDescription:`Install an export, email or broker addon to connect this hub to another system.`,legacyGroupParam:`tab`})}function be(e,t,n){return e===`device-export`?[{id:`devices`,title:`Devices`,icon:M,placement:`end`,content:o(f,{addonId:t,onOpenDevice:n,showSetup:!1})}]:e===`broker`?[{id:`connections`,title:`Connections`,icon:u,content:o(me,{addonId:t})}]:[]}function xe({processState:e}){let{state:t,label:n}=Q(e);return o(c,{variant:t===`ok`?`success`:t===`error`?`danger`:`default`,className:`${z} capitalize`,children:n})}function Se({kind:e,addonId:t}){return e===`broker`?o(Ce,{addonId:t}):e===`device-export`?o(we,{addonId:t}):null}function Ce({addonId:e}){let{data:t}=E({addonId:e},{refetchInterval:$,retry:!1}),n=N.safeParse(t);if(!n.success)return null;let{brokerCount:r,connectedCount:i}=n.data;return o(c,{variant:`info`,className:z,children:`${r} connection${r===1?``:`s`}${i>0?` · ${i} connected`:``}`})}function we({addonId:e}){let{data:t}=_({addonId:e},{refetchInterval:$,retry:!1}),n=F.safeParse(t);if(!n.success)return null;let{linkState:r,exposedDeviceCount:i}=n.data;return o(c,{variant:r===`linked`?`success`:r===`error`?`danger`:`default`,className:z,children:`${r} · ${i} exposed`})}export{ye as IntegrationsPage};