@camstack/addon-admin-ui 1.2.358 → 1.2.360

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 (118) hide show
  1. package/dist/assets/AddonAssetIcon-YfrTWCUl.js +1 -0
  2. package/dist/assets/Addons-CBnmHNZd.js +4 -0
  3. package/dist/assets/{AdminTabs-CjafoxvK.js → AdminTabs-FluZSCkZ.js} +1 -1
  4. package/dist/assets/AiProfiles-C55fwqpv.js +3 -0
  5. package/dist/assets/{BrokerForm-vK7o_-sd.js → BrokerForm-DNKfcMGY.js} +1 -1
  6. package/dist/assets/Build-B-W3MTQ_.js +40 -0
  7. package/dist/assets/{Calendars-py7REb8I.js → Calendars-C6AaPr2m.js} +1 -1
  8. package/dist/assets/Cluster-CcgeafgM.js +11 -0
  9. package/dist/assets/ClusterStepModel-Dt5sbcMn.js +1 -0
  10. package/dist/assets/CompositionEditor-BvxzNcTs.js +1 -0
  11. package/dist/assets/{CompositionEditorPage-DXiq4mMC.js → CompositionEditorPage-DWnecyHu.js} +1 -1
  12. package/dist/assets/Data-1Pmkjzqu.js +1 -0
  13. package/dist/assets/DetectionIntelligence-BAjtF-QJ.js +1 -0
  14. package/dist/assets/DeviceDetail-jUxcl2dt.js +2 -0
  15. package/dist/assets/{DeviceDoActionFields-4wfCnUDo.js → DeviceDoActionFields-DEzN9bNr.js} +1 -1
  16. package/dist/assets/{Devices-Zuh3Gb1y.js → Devices-Fd7nZ5MC.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-Cfayr0_2.js → EmbedPlayerPage-mgkKggkq.js} +1 -1
  18. package/dist/assets/Events-Cf6mlR2q.js +1 -0
  19. package/dist/assets/Identity-6bcQFaXB.js +1 -0
  20. package/dist/assets/IntegrationDetail-ua-c941Y.js +1 -0
  21. package/dist/assets/IntegrationHub-Blksb596.js +1 -0
  22. package/dist/assets/Integrations-C2jeLxC2.js +1 -0
  23. package/dist/assets/{Integrations-B3NL6Bhn.js → Integrations-DHz0PMI_.js} +1 -1
  24. package/dist/assets/Locations-Bz7z6CMI.js +3 -0
  25. package/dist/assets/{Logs-BYKgLvH-.js → Logs-D4FH_1l6.js} +1 -1
  26. package/dist/assets/{MotionZonesSettings-40HbSg1J.js → MotionZonesSettings-CM4WOcjH.js} +1 -1
  27. package/dist/assets/MyAccess-CrOZJPf0.js +2 -0
  28. package/dist/assets/Network-Dv-UU8In.js +1 -0
  29. package/dist/assets/NodeAddonsSettingsPanel-CB1W9PlU.js +1 -0
  30. package/dist/assets/Notifications-ho1y5DBh.js +1 -0
  31. package/dist/assets/{Plates-BW_rdxX6.js → Plates-bNeRAg3c.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-9mlw-Sg2.js → PrivacyMaskSettings-KIOBPGgQ.js} +1 -1
  33. package/dist/assets/ReauthDialog-DSMlzJbr.js +1 -0
  34. package/dist/assets/Recordings-BDpqJ0d4.js +1 -0
  35. package/dist/assets/{ScanNetworkModal-mYvbo8Uo.js → ScanNetworkModal-aJXdvOqO.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-DNVt27Re.js → SceneMonitorEditor-GovIClCv.js} +1 -1
  37. package/dist/assets/Scenes-DloxAJU0.js +1 -0
  38. package/dist/assets/{Showroom-CVxQH10K.js → Showroom-q5YYwjHY.js} +1 -1
  39. package/dist/assets/System-kbKQ9CVD.js +1 -0
  40. package/dist/assets/{Terminal-5aXU64zN.js → Terminal-DKuH4tew.js} +2 -2
  41. package/dist/assets/{Viewer-CSSu8htq.js → Viewer-BrFwktMa.js} +1 -1
  42. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DxPQ0X7S.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CvwQbyB5.js} +1 -1
  43. package/dist/assets/{archive-DeR3e4g-.js → archive-Bxuu4XK_.js} +1 -1
  44. package/dist/assets/{authed-media-DKCCsaRv.js → authed-media-D6c7tYnN.js} +1 -1
  45. package/dist/assets/{boxes-DxeTkSiW.js → boxes-C8EKsJcH.js} +1 -1
  46. package/dist/assets/circle-slash-D2xNyylo.js +1 -0
  47. package/dist/assets/client-CwOJLD7X.js +357 -0
  48. package/dist/assets/crop-B560YMk7.js +1 -0
  49. package/dist/assets/{debounced-invalidate-7E55pOhB.js → debounced-invalidate-DK6oGBoA.js} +1 -1
  50. package/dist/assets/{device-integration-icon-CPFH1cD5.js → device-integration-icon-WPgnLRa8.js} +1 -1
  51. package/dist/assets/device-picker-model-nn4N-kW_.js +1 -0
  52. package/dist/assets/dist-Ch_VwWyv.js +357 -0
  53. package/dist/assets/dist-DdkYqeyJ.js +1 -0
  54. package/dist/assets/{face-bbox-BLwRunnv.js → face-bbox-CYI0m13N.js} +1 -1
  55. package/dist/assets/{hard-drive-download-BT7-6QED.js → hard-drive-download-CHmTG4FF.js} +1 -1
  56. package/dist/assets/{hostInit-DAWBqgef.js → hostInit-DtbkNESn.js} +1 -1
  57. package/dist/assets/index-CArA6N_R.js +4 -0
  58. package/dist/assets/index-wxcbK3CM.css +2 -0
  59. package/dist/assets/{layers-D1ITEDh9.js → layers-DUTpUvYV.js} +1 -1
  60. package/dist/assets/{location-owned-usage-CFYIPCzN.js → location-owned-usage-wj2Taghd.js} +1 -1
  61. package/dist/assets/{mf-entry-bootstrap-0-127f685c.js → mf-entry-bootstrap-0-e3bab662.js} +2 -2
  62. package/dist/assets/monitor-smartphone-BcbZNX7w.js +1 -0
  63. package/dist/assets/mount-nn4N-kW_.js +1 -0
  64. package/dist/assets/notification-schedule-field-BTiUXVHy.js +1 -0
  65. package/dist/assets/octagon-alert-CMJcW8DR.js +1 -0
  66. package/dist/assets/{player-overlays-D4lg_avJ.js → player-overlays-rpfoGg2b.js} +1 -1
  67. package/dist/assets/remoteEntry-DgvAVxEY.js +1 -0
  68. package/dist/assets/{send-CYTiWXyC.js → send-DhJPA58A.js} +1 -1
  69. package/dist/assets/{settings-2-DVqttbaa.js → settings-2-BrRBQaWp.js} +1 -1
  70. package/dist/assets/src-BQ0U3gDQ.js +67 -0
  71. package/dist/assets/{use-scenes-feed-BUMM_vS8.js → use-scenes-feed-BDMkIMNT.js} +1 -1
  72. package/dist/assets/{use-stationary-objects-F6FJkq-t.js → use-stationary-objects-CxogUU2-.js} +1 -1
  73. package/dist/assets/useEventInvalidation-nn4N-kW_.js +1 -0
  74. package/dist/assets/{useNodeUrlSelection-CWDgf9EZ.js → useNodeUrlSelection-B4wkx7sG.js} +1 -1
  75. package/dist/assets/user-round-CsrOPzWq.js +1 -0
  76. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D0bzMnfx.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BLSzSrXB.js} +2 -2
  77. package/dist/index.html +8 -8
  78. package/dist/server/addon.js +1623 -131
  79. package/package.json +1 -1
  80. package/dist/assets/Addons-BpNMAC8g.js +0 -4
  81. package/dist/assets/AiProfiles-BeZSyNFd.js +0 -3
  82. package/dist/assets/Build-CHPyiOzb.js +0 -40
  83. package/dist/assets/Capabilities-CTyuV2mU.js +0 -1
  84. package/dist/assets/Cluster-Dvmv3-5C.js +0 -11
  85. package/dist/assets/ClusterStepModel-BCXM90oM.js +0 -1
  86. package/dist/assets/CompositionEditor-Bktdwhnn.js +0 -1
  87. package/dist/assets/Data-DtUlsreq.js +0 -1
  88. package/dist/assets/DetectionIntelligence-BHcjDiGb.js +0 -1
  89. package/dist/assets/DeviceDetail-TJQ3r5Wf.js +0 -2
  90. package/dist/assets/Events-C8rtJF0X.js +0 -1
  91. package/dist/assets/Identity-BHqbF-VQ.js +0 -1
  92. package/dist/assets/IntegrationDetail-DDZBkRYs.js +0 -1
  93. package/dist/assets/IntegrationHub-C_kwGzUm.js +0 -1
  94. package/dist/assets/Integrations-D3H9rujI.js +0 -1
  95. package/dist/assets/Locations-BIetkfhV.js +0 -3
  96. package/dist/assets/MyAccess-B8HF1nGo.js +0 -2
  97. package/dist/assets/Network-m6TRq9hZ.js +0 -1
  98. package/dist/assets/NodeAddonsSettingsPanel-DhbzB3yG.js +0 -1
  99. package/dist/assets/Notifications-DWpao1R2.js +0 -1
  100. package/dist/assets/Recordings-DJmbAZFE.js +0 -1
  101. package/dist/assets/Scenes-CyjlxaOP.js +0 -1
  102. package/dist/assets/Secrets-DgQr5Kxc.js +0 -1
  103. package/dist/assets/Settings-cSyoiNRe.js +0 -1
  104. package/dist/assets/circle-slash-CttzF2br.js +0 -1
  105. package/dist/assets/client-BqN2lVYf.js +0 -357
  106. package/dist/assets/crop-BEmkkd3b.js +0 -1
  107. package/dist/assets/device-picker-model-DDC4ATOt.js +0 -1
  108. package/dist/assets/dist-9DPeVlno.js +0 -1
  109. package/dist/assets/dist-CxwXQGCF.js +0 -357
  110. package/dist/assets/index-B-nNtYMr.css +0 -2
  111. package/dist/assets/index-CpGfiJoj.js +0 -4
  112. package/dist/assets/mount-DDC4ATOt.js +0 -1
  113. package/dist/assets/notification-schedule-field-CrLB-wdt.js +0 -1
  114. package/dist/assets/remoteEntry-Cpe5-iTU.js +0 -1
  115. package/dist/assets/src-DzkLcOyh.js +0 -67
  116. package/dist/assets/unlink-ZWAv-UAl.js +0 -1
  117. package/dist/assets/useEventInvalidation-DDC4ATOt.js +0 -1
  118. package/dist/assets/user-round-D1OVtUFE.js +0 -1
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,U as i,W as a,a as o,b as s,o as c,q as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{X as f,Z as p,at as m,ct as h,ft as g,gt as _,ht as v,st as y,vt as b}from"./player-overlays-D4lg_avJ.js";import{$n as x,$o as S,$t as C,An as w,As as T,Bt as E,Cd as D,Cn as O,Cs as k,Dn as A,Dt as j,En as M,Es as N,Fd as P,Fn as F,Fs as I,Gd as L,Gt as R,Ht as z,If as B,In as V,Is as ee,Jn as te,Ju as H,Kn as U,Kt as W,Lo as G,Lu as K,Ms as ne,Nn as q,Ns as re,Nt as ie,Os as ae,Pd as oe,Ps as se,Qo as ce,Qs as le,Ss as ue,Su as de,Tn as fe,Ts as pe,Ut as me,Vd as he,Wf as ge,Wt as _e,Wu as ve,Xt as ye,Yt as be,Zd as xe,Zt as Se,_s as Ce,as as we,at as Te,au as Ee,bn as J,bs as De,cd as Oe,cf as ke,cs as Ae,df as je,ds as Me,er as Ne,es as Pe,fs as Fe,gf as Ie,gs as Le,hd as Re,if as ze,is as Be,js as Ve,ks as He,lc as Ue,ls as We,ms as Ge,on as Ke,os as qe,ou as Je,ps as Ye,qd as Xe,qn as Ze,qs as Qe,qu as $e,rd as et,rs as tt,sa as nt,sn as rt,tr as Y,ts as it,us as at,vs as ot,wf as st,wn as ct,wr as lt,ws as ut,wu as dt,xf as ft,xn as pt,xs as mt,xu as ht,yn as gt,ys as _t,yu as vt}from"./src-DzkLcOyh.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-7E55pOhB.js";import{Un as jt,pi as Mt}from"./client-BqN2lVYf.js";import{t as Nt}from"./useTranslation-Bc5yH9V9.js";import"./mount-DDC4ATOt.js";import{tt as Pt}from"./index-CpGfiJoj.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-DKCCsaRv.js";import{t as Bt}from"./use-stationary-objects-F6FJkq-t.js";import{t as Vt}from"./AdminTabs-CjafoxvK.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.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(Xe,{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(st,{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($e,{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=te();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-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[u(a?ft:ke,{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}=lt({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}=G({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 se==`function`,jn=`Track flags arrive with the next server update`;function Mn(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var Nn=An?se: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=U(),[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(Xe,{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(st,{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($e,{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 we==`function`,Gn=`Track deletion arrives with the next server update`;function Kn(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var qn=Wn?we: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:`#f59e0b`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&u(`polyline`,{points:e.polyline,fill:`none`,stroke:`#38bdf8`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),e.points.map((e,t)=>u(`circle`,{cx:e.x,cy:e.y,r:1,fill:`#38bdf8`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),e.snapshots.map((e,n)=>u(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`#0ea5e9`,fillOpacity:.95,stroke:`#082f49`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:t?`pointer-events-auto cursor-pointer`:void 0,onClick:t?n=>{n.stopPropagation(),t(e.mediaId)}:void 0,children:u(`title`,{children:`Snapshot checkpoint — click to view this frame`})},`snap-${String(e.mediaId)}-${String(n)}`)),e.start&&u(`circle`,{cx:e.start.x,cy:e.start.y,r:2.4,fill:`#22c55e`,stroke:`#052e16`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&u(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`#ef4444`,stroke:`#450a0a`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function 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=U(),_=Ze(),v=qn(),b=t!==null,x=t?.deviceId??0,S=t?.trackId??``,C=t?.timestamp??0,w=t?.windowMs??0,{data:T}=at({deviceId:x,trackId:S},{enabled:b}),{data:E}=k({trackId:S,deviceId:x},{enabled:b}),D=T?.bestEventId===void 0?void 0:Number(T.bestEventId),{data:A}=Ge({ownerType:`object`,eventId:D??0,deviceId:x},{enabled:b&&D!==void 0&&Number.isFinite(D)}),{data:j}=Je({deviceId:x},{enabled:b}),M=(j??[]).find(e=>e.addonId!==void 0)?.addonId,{data:N}=Ee({deviceId:x,since:C-Jn,until:C+w+Jn,provider:M??``},{enabled:b&&M!==void 0}),[F,I]=l(null),[L,R]=l(!1),{publicOrigin:z,probes:B}=Dn(b);d(()=>{I(null)},[x,S]);let ee=a(()=>{let e=E??[],t=A??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[E,A]),te=F??ee,H=It(te?te.url:void 0),W=a(()=>{let e=new Set,t=[];for(let n of[...A??[],...E??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[A,E]),G=a(()=>W.find(e=>Zn.has(e.kind))??null,[W]),K=$n(It(G?G.url:void 0).src),ne=a(()=>Un(T?.positions??[],K,{snapshots:(T?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[T?.positions,T?.snapshots,K]),q=e(e=>{let t=W.find(t=>t.mediaId===e);t&&I(t)},[W]);if(t===null)return null;let re=H.src,ie=te?.kind,ae=ie!==void 0&&Qn.has(ie)&&K!==null&&(T?.positions.length??0)>=2,oe=N&&N.length>0?N[0]:null,se=()=>{oe&&(R(!0),(async()=>{try{let e=await p.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:oe.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{R(!1)}})())},ce=()=>{!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`})}})()},le=Math.round(t.importance*100),ue=T?.importanceReason?`${String(le)}% · ${T.importanceReason}`:`${String(le)}%`,de=T?.zonesVisited&&T.zonesVisited.length>0?T.zonesVisited.join(`, `):`—`,fe=T?.audioLabels&&T.audioLabels.length>0?T.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,pe=fe===void 0?`—`:fe.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),me=T?T.totalDistance.toFixed(2):`—`,he=hn(T?.previewMissReason),ge=Dt(T?T.firstSeen:C),_e=T?Dt(T.lastSeen):`—`;return u(pt,{open:!0,onOpenChange:e=>!e&&o(),children:r(O,{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(dt,{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:[re?u(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:u(Tt,{src:re,alt:`Key frame from ${n}`,fit:`natural`,className:`w-full`,overlay:ae?u(er,{overlay:ne,onPickSnapshot:q}):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:H.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`})}),W.length>0&&u(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:W.map(e=>{let t=wn(e.kind),n=Tn(Yn,e.url),i=z?Tn(z,e.url):null;return r(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[u(`button`,{type:`button`,onClick:()=>I(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)})}),B,oe&&r(V,{variant:`secondary`,onClick:se,disabled:L,children:[L?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(xe,{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:ue}),u(X,{label:`Zones visited`,value:de}),u(X,{label:`Audio heard`,value:pe}),u(X,{label:`Total distance`,value:me}),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(V,{variant:`secondary`,onClick:ce,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(F,{value:i,options:[...e],onChange:e=>a(e.target.value),"aria-label":`Camera`})}),u(J,{type:`datetime-local`,"aria-label":`From`,value:o,onChange:e=>s(e.target.value),className:`w-48`}),u(J,{type:`datetime-local`,"aria-label":`To`,value:c,onChange:e=>d(e.target.value),className:`w-48`}),u(J,{"aria-label":`Scenario`,placeholder:`615-door-groups`,value:f,onChange:e=>p(e.target.value),className:`w-44`}),u(J,{"aria-label":`Note`,placeholder:`optional note`,value:m,onChange:e=>h(e.target.value),className:`w-52`}),u(`div`,{className:`w-28`,children:u(F,{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(V,{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(q,{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(V,{disabled:d.length<2,onClick:()=>void b(Or(d),`same-subject`),children:`Same subject`}),u(V,{variant:`secondary`,disabled:d.length<2,onClick:()=>void b(kr(d),`different-subjects`),children:`Different subjects`}),u(J,{"aria-label":`Changed at (s from tape start)`,placeholder:`changed at s`,value:p,onChange:e=>m(e.target.value),className:`w-28`}),u(V,{variant:`secondary`,disabled:d.length!==1,onClick:()=>void x(`mixed`),children:`Mixed`}),u(V,{variant:`secondary`,disabled:d.length===0,onClick:()=>void x(`not-a-subject`),children:`Not a subject`}),u(V,{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(V,{variant:`ghost`,onClick:n,children:`Close`})]}),h!==null&&u(q,{message:h}),S!==null&&u(q,{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(Y,{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(Ke,{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=nt({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(q,{message:f}),i.isLoading&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading camera status…`}),i.data===null&&u(q,{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(Y,{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(q,{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(Y,{variant:e.state===`complete`?`success`:`warning`,children:e.state}),` `,e.reviewed&&u(Y,{variant:`info`,children:`reviewed`}),` `,e.released&&u(Y,{children:`released`})]}),r(`td`,{children:[String(e.tracksStillStored),`/`,String(e.tracks.length),` stored`]}),r(`td`,{className:`space-x-1 text-right`,children:[u(V,{variant:`secondary`,"aria-label":`Review ${e.scenario}`,onClick:()=>d(e.id),children:`Review`}),u(V,{variant:`ghost`,"aria-label":`Download ${e.scenario}`,onClick:()=>void m(e),children:u(ze,{className:`h-3.5 w-3.5`})}),u(j,{label:`Release`,icon:oe,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(j,{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(Y,{variant:`success`,children:`no anomaly found`}):u(`div`,{className:`flex flex-wrap gap-1`,children:ri(e).map(e=>u(Y,{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(),T=nt({isCamera:!0,projection:`slim`}),E=a(()=>[{value:hi,label:`All cameras`},...(T.data??[]).map(e=>({value:String(e.id),label:e.name}))],[T.data]),D=a(()=>{let e=new Map;for(let t of T.data??[])e.set(t.id,t.name);return e},[T.data]),O=e=>D.get(e)??`Camera ${String(e)}`,k=a(()=>t===hi?[]:[Number.parseInt(t,10)],[t]),A=o({queryKey:[`events-debug`,`list`,k],queryFn:async()=>Qr(await e.trpcClient.addons.custom.mutate({addonId:Br,action:Vr,input:k.length===0?{}:{deviceIds:k}}))}),j=a(()=>(A.data?.tracks??[]).map(e=>e.trackId),[A.data]),M=o({queryKey:[`events-debug`,`analyze`,j],enabled:j.length>0,queryFn:async()=>$r(await e.trpcClient.addons.custom.mutate({addonId:Br,action:Hr,input:{trackIds:j}}))}),N=a(()=>{let e=new Map;for(let t of M.data?.reports??[])e.set(t.trackId,t);return e},[M.data]),I=A.data?.tracks??[],L=A.data===null||M.data===null,R=()=>{A.refetch(),M.refetch()},z=e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},B=()=>{p(new Set(I.map(e=>oi(e.deviceId,e.trackId))))},ee=()=>p(new Set),te=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}},H=e=>{if(!An||_!==null)return;let t=si(I,f);t.length!==0&&(v(e),b(null),(async()=>{let n=await te(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.`),A.refetch()})())},U=()=>{let e=x;e.length===0||_!==null||(v(`analyzed`),b(null),(async()=>{for(let t of e)try{await C.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{b(`Some tracks could not be re-marked. Refresh and try again.`)}v(null),S([]),A.refetch()})())},W=async()=>{s(!0),d(null);try{await zt(ii(k),`camstack-debug.zip`)}catch(e){d(e instanceof Error?e.message:`Export failed.`)}finally{s(!1)}},G=_!==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(F,{value:t,options:E,onChange:e=>n(e.target.value)})}),r(V,{variant:`secondary`,onClick:R,disabled:A.isFetching,children:[A.isFetching?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(Re,{className:`h-3.5 w-3.5`}),`Refresh`]}),r(V,{onClick:()=>void W(),disabled:i||I.length===0,children:[i?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(ze,{className:`h-3.5 w-3.5`}),`Export all (`,String(I.length),`)`]}),I.length>0&&f.size<I.length&&u(V,{variant:`ghost`,onClick:B,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,{}),A.isError&&u(q,{message:`Could not load the marked tracks.`}),L&&!A.isError&&u(q,{message:gi}),c!==null&&u(q,{message:c}),y!==null&&u(q,{message:y}),A.data?.truncated===!0&&u(q,{message:`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`}),(M.data?.vanished.length??0)>0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:[String(M.data?.vanished.length),` marked track(s) were evicted between the list and the analysis.`]}),f.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[String(f.size),` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[u(`span`,{title:An?void 0:`Track flags arrive with the next server update`,children:r(V,{variant:`secondary`,onClick:()=>H(`keep`),disabled:!An||G,children:[_===`keep`?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u($e,{className:`h-3.5 w-3.5`}),` `,`Keep`]})}),u(`span`,{title:An?void 0:`Track flags arrive with the next server update`,children:r(V,{onClick:()=>H(`analyzed`),disabled:!An||G,children:[_===`analyzed`?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(ft,{className:`h-3.5 w-3.5`}),` `,`Analyzed`]})}),u(V,{variant:`ghost`,onClick:ee,disabled:G,children:u(dt,{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(V,{variant:`ghost`,onClick:U,disabled:G,children:[u(K,{className:`h-3.5 w-3.5`}),` Undo`]}),u(V,{variant:`ghost`,onClick:()=>S([]),disabled:G,children:u(dt,{className:`h-3.5 w-3.5`})})]}),A.isLoading?u(w,{children:u(`div`,{className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`Loading…`})}):I.length===0?u(w,{children:r(`div`,{className:`flex flex-col items-center gap-2 px-3 py-8 text-center`,children:[u(st,{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:I.map(e=>{let t=N.get(e.trackId);return u(_n,{row:e,cameraName:O(e.deviceId),nowMs:e.lastSeen,selected:f.has(oi(e.deviceId,e.trackId)),onToggleSelect:z,onOpenDetail:g,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:u(yi,{track:e,report:t,analyzing:M.isFetching})},oi(e.deviceId,e.trackId))})}),h&&u(tr,{row:h,cameraName:O(h.deviceId),deleteAvailable:Wn,onClose:()=>g(null),onDeleted:()=>{g(null),A.refetch()},onFlagsChanged:e=>{e.debug||(g(null),A.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 vt(Mt.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),vt(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||x(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}),S=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)},C=e=>{let r=new Set(t);r.has(e)?r.delete(e):r.add(e),n(r)},w=()=>n(new Set),T=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 ${T>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[u(ve,{className:`h-3.5 w-3.5`}),T>0?`Kinds (${String(T)})`:`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(Oe,{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`}),T>0&&u(`button`,{type:`button`,onClick:w,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=Ne(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:()=>S(e),className:`accent-primary`}),u(n,{className:`h-3.5 w-3.5`,style:{color:e.macro.color}}),u(`span`,{className:`font-medium`,children:x(e.macro,o)})]})]}),i&&e.subs.map(e=>{let n=Ne(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:()=>C(e.kind),className:`accent-primary`}),u(n,{className:`h-3.5 w-3.5`,style:{color:e.color}}),u(`span`,{children:x(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:je}];function Ri(){let e=c(),t=U(),n=Ze(),[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:M=[]}=nt({isCamera:!0,projection:`slim`}),N=a(()=>M.map(e=>e.id),[M]),{data:F,isLoading:I}=Ye({deviceIds:N},{enabled:N.length>0,staleTime:5*6e4}),L=a(()=>Ni(F??[],f),[F,f]),R=qn(),z=R.isPending,{rows:B,isLoading:ee}=wi({deviceIds:N,since:D,until:O,minImportance:g>0?g:void 0,classFilter:m.size===1?[...m][0]:void 0}),te=a(()=>{let e=new Map;for(let t of M??[])e.set(t.id,t.name);return e},[M]),H=e=>te.get(e)??`Camera #${String(e)}`,W=a(()=>bt(B).map(e=>({id:e,name:H(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[B,te]),G=a(()=>an(on(B,{cameras:f,classes:m,minImportance:g}),v),[B,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])),ne=()=>{e.invalidateQueries({queryKey:Fi})},q=()=>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(B,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])=>R.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{ne();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=>H(e)).join(`, `)}. They remain selected — retry, or check the server logs.`,variant:`danger`})})}let oe=G.length!==B.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:L,selected:m,onChange:h,loading:I}),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(B.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(V,{variant:`secondary`,onClick:ie,disabled:!Wn||z,children:[z?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),u(V,{variant:`ghost`,onClick:q,disabled:z,children:u(dt,{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:H(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:H(C.deviceId),deleteAvailable:Wn,onClose:()=>w(null),onDeleted:()=>{ne(),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=Te(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=[]}=nt({isCamera:!0,projection:`slim`}),S=a(()=>{let e=new Map;for(let t of b)e.set(t.id,t.name);return e},[b]),C=e=>S.get(e)??`Camera #${String(e)}`,w=a(()=>b.map(e=>e.id),[b]),{data:T}=Ye({deviceIds:w},{enabled:w.length>0,staleTime:5*6e4}),E=a(()=>Mi(T??[],new Set(f===null?[]:[f])),[T,f]);d(()=>{s!==null&&(E.some(e=>e.kind===s)||c(null))},[E,s]);let{data:D,isFetching:O,isError:k,error:A}=Ve({text:g,strictness:i,limit:zi,classFilter:s??void 0,deviceId:f??void 0},{enabled:_}),j=a(()=>[...D??[]].sort((e,t)=>t.score-e.score).map(e=>({...Hi(e),score:e.score})),[D]);function M(e){c(t=>t===e?null:e)}return r(`div`,{className:`space-y-3`,children:[r(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`div`,{className:`relative min-w-[16rem] flex-1`,children:[u(Oe,{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(dt,{className:`h-3.5 w-3.5`})})]}),O&&_&&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:E.map(e=>u(`button`,{type:`button`,onClick:()=>M(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${s===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:x(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))})]}),_&&!O&&!k&&r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[j.length,` match`,j.length===1?``:`es`]})]})]}),_&&r(`div`,{className:`space-y-3`,children:[k&&r(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,A instanceof Error?A.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!k&&O&&j.length===0&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(P,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!k&&!O&&j.length===0&&r(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:[`No semantic matches for “`,g,`”. Try a looser match threshold or a different phrasing.`]}),!k&&j.length>0&&u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:j.map(e=>u(_n,{row:e,cameraName:C(e.deviceId),nowMs:v,score:e.score,onOpenDetail:h},e.id))})]}),m&&u(tr,{row:m,cameraName:C(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=[]}=nt({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=ce(),[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(_e,{children:[r(W,{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(R,{className:`w-72 space-y-2 p-3`,children:[u(gt,{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(V,{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(xe,{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(Y,{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(dt,{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(J,{className:`flex-1`,"aria-label":`New collection name`,placeholder:`New collection`,value:d,onChange:e=>{f(e.target.value)}}),u(V,{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(J,{className:`flex-1`,"aria-label":`Collection name`,value:h.name,onChange:t=>{g({id:e.id,name:t.target.value})}}),u(V,{variant:`ghost`,size:`sm`,"aria-label":`Save the name`,onClick:()=>void v(),children:u(ft,{className:`h-3 w-3`})}),u(V,{variant:`ghost`,size:`sm`,"aria-label":`Cancel renaming`,onClick:()=>{g(null)},children:u(dt,{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(Y,{children:e.frameCount}),u(V,{variant:`ghost`,size:`sm`,"aria-label":`Rename ${e.name}`,onClick:()=>{g({id:e.id,name:e.name})},children:u(D,{className:`h-3 w-3`})}),u(j,{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(Y,{children:[e.frames,` frames`]}),r(Y,{variant:e.completeness>=.9?`success`:`warning`,children:[$i(e.completeness),` complete (`,e.completeFrames,`)`]}),r(Y,{children:[e.subjects,` boxes`]}),r(Y,{variant:`danger`,children:[e.modelErrors,` model errors`]}),r(Y,{variant:`info`,children:[e.hardNegatives,` hard negatives`]}),e.cameras.map(e=>r(Y,{children:[n(e.deviceId),`: `,e.frames,` ·`,` `,$i(e.frames>0?e.completeFrames/e.frames:0),` complete`]},e.deviceId))]}),u(ie,{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=I({id:e},{enabled:t});return t?i.data===void 0?u(P,{className:`h-3 w-3 animate-spin`}):i.data.matches?u(Y,{variant:`success`,children:`unchanged`}):r(Y,{variant:`warning`,children:[`changed`,i.data.missingFrames>0?` · ${String(i.data.missingFrames)} missing`:``]}):r(V,{variant:`ghost`,size:`sm`,onClick:()=>n(!0),children:[u(et,{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),[x,S]=l(`frames`),[w,T]=l(``),[E,D]=l(null),[O,k]=l(null),A={...s.length>0?{deviceIds:[...s]}:{},...f.length>0?{collectionIds:[...f]}:{},...g&&n.length>0?{frameIds:[...n]}:{}},M=ut({selection:A,completeOnly:v}),N=De({}),I=it(),L=Be(),R=async()=>{D(null);let e=await I.mutateAsync({name:w,selection:A,layout:x,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 N.refetch()},z=async e=>{k(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{k(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(Y,{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(Y,{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(C,{"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(V,{variant:`ghost`,size:`sm`,onClick:i,children:`Clear picks`}),r(`label`,{className:`flex items-center gap-1.5`,children:[u(C,{"aria-label":`Only complete frames`,checked:v,onChange:e=>b(e.target.checked)}),`Only frames marked "all subjects boxed"`]}),u(F,{className:`w-36`,"aria-label":`Layout`,value:x,options:[{value:`frames`,label:`Frames (detector)`},{value:`crops`,label:`Frames + crops (classifier)`}],onChange:e=>S(e.target.value===`crops`?`crops`:`frames`)})]}),M.data===void 0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:M.isError?`The selection could not be counted.`:`Counting the selection…`}):u(na,{stats:M.data,deviceNames:e}),r(`div`,{className:`flex items-center gap-2`,children:[u(J,{className:`flex-1`,"aria-label":`Version name`,placeholder:`Version name (e.g. night person v1)`,value:w,onChange:e=>T(e.target.value)}),u(V,{size:`sm`,disabled:w.trim()===``||I.isPending||(M.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(ie,{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(V,{variant:`ghost`,size:`sm`,"aria-label":`Download ${e.name}`,disabled:O!==null,onClick:()=>void z(e),children:O===e.id?u(P,{className:`h-3 w-3 animate-spin`}):u(ze,{className:`h-3 w-3`})}),u(j,{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:N.data??[],rowKey:e=>e.id,emptyMessage:N.isLoading?`Reading the versions…`:`No version frozen yet.`,minWidthPx:640})]})]})}n();function aa(){let e=Me({}),t=_t({}),[n,i]=l([]),a=Ae(n.length>0?{collectionIds:[...n]}:{}),o=Fe({}),[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(V,{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(ze,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Annotated dataset`})]}),r(V,{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(ze,{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(Y,{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(ft,{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(Y,{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(V,{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(Y,{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:Ie,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(Y,{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=rt({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(F,{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(Y,{variant:`warning`,children:`draft`}),e.kind===`model_error`&&u(Y,{variant:`danger`,children:`model error`}),f!==null&&u(Y,{variant:`info`,children:f}),(e.note!==void 0||e.flag!==void 0)&&r(be,{children:[u(Se,{children:u(he,{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(ye,{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(V,{variant:`secondary`,size:`sm`,"aria-label":`Accept this proposal`,onClick:()=>{a(e.key)},children:u(ft,{className:`h-3 w-3`})}),u(V,{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(B,{className:`h-3 w-3`})}),u(V,{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(J,{className:`flex-1`,placeholder:`label (postman, van, cat…)`,value:e.label??``,onChange:t=>{i(e.key,{label:t.target.value})}}),u(J,{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=Ce({},{retry:!1}),d=pe(),f=N(),[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,T]=l(qa),[E,D]=l(!1),[k,j]=l(!1),I=t(n.editor);I.current=n.editor;let L=p!==`llm`,R=p!==`teacher`,z=i.kind===`resolved`&&v!==void 0,B=C!==void 0&&w.length>0,ee=(!L||z)&&(!R||B),te=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(I.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}.`})));I.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`:``}.`},H=async t=>{if(C===void 0)return``;let r=I.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(I.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`:``}.`},U=async e=>{D(!1),j(!0),s(null);try{let t=[];L&&t.push(await te()),R&&t.push(await H(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(F,{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(V,{size:`sm`,variant:`secondary`,disabled:!ee||k,onClick:()=>{if(R&&C?.leavesHouse===!0){D(!0);return}U(!1)},children:[k?u(P,{className:`h-3 w-3 animate-spin`}):u(en,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Run`})]})]}),L&&(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(F,{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(J,{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]})]})),R&&((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(F,{"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:()=>{T(n=>t?n.filter(t=>t!==e):[...n,e])},children:e},e)})]})]})),u(pt,{open:E,onOpenChange:D,children:r(O,{children:[r(M,{children:[u(A,{children:`Send this frame outside your home?`}),u(ct,{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(fe,{children:[u(V,{variant:`ghost`,size:`sm`,onClick:()=>{D(!1)},children:`Cancel`}),u(V,{size:`sm`,onClick:()=>void U(!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(V,{variant:`ghost`,size:`sm`,"aria-label":`Zoom out`,onClick:e.zoomOut,children:u(ht,{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(V,{variant:`ghost`,size:`sm`,"aria-label":`Zoom in`,onClick:e.zoomIn,children:u(de,{className:`h-3.5 w-3.5`})}),u(V,{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(V,{variant:e.panMode?`secondary`:`ghost`,size:`sm`,"aria-label":`Pan tool`,"aria-pressed":e.panMode,onClick:e.togglePan,children:u(L,{className:`h-3.5 w-3.5`})}),u(`span`,{className:`flex-1`}),u(V,{variant:`ghost`,size:`sm`,"aria-label":`Undo`,disabled:!t,onClick:i,children:u(K,{className:`h-3.5 w-3.5`})}),u(V,{variant:`ghost`,size:`sm`,"aria-label":`Redo`,disabled:!n,onClick:a,children:u(Qt,{className:`h-3.5 w-3.5`})}),r(_e,{children:[u(W,{"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(R,{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:x}=_,S=Ao(),w=Le({frameIds:[i]}),E=We({frameId:i}),D=pe(),O=T(),k=re(),A=Qe({deviceIds:g===null?[]:[g]},{enabled:g!==null,staleTime:3e4}),j=A.data?.[0]?.detection?.nodeId??null,M=le({nodeId:j??``},{enabled:j!==null,staleTime:3e4}),N=ee({nodeId:j??``},{enabled:j!==null,staleTime:3e4}),F=Ue({deviceId:g??0},{enabled:g!==null,staleTime:3e4}),I=a(()=>ga({status:A.data?.[0],nodeDevices:M.data,schema:N.data,resolvedSteps:F.data?.steps}),[A.data,M.data,N.data,F.data]),L=t({stored:w.data,copy:h});L.current={stored:w.data,copy:h};let R=h!==void 0;d(()=>{S.fit();let{stored:e,copy:t}=L.current;b(Sa((e??[]).filter(e=>e.mediaKey===i),t?.pipelineBoxes??[]))},[i,w.dataUpdatedAt,R,b,S.fit]);let z=e(async e=>{h!==void 0&&(await k.mutateAsync({...fa(h),complete:e}),await s())},[h,k,s]),B=e(async e=>{if(h===void 0)return;if(f(null),I.kind!==`resolved`){f(Yo[I.gap]);return}let t=await D.mutateAsync({...fa(h),subject:e===`package`?{kind:`package`}:{kind:`objects`,modelId:I.modelId,minScore:I.minScore},nodeId:I.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,D,I,v,y,f]),te=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=E.data,ne=Ua(v.boxes)&&h!==void 0,q=Pa(v),ie=n.map(e=>e.frameId),ae=e=>{let t=ie.indexOf(i),n=ie[t+e];return t<0||n===void 0?!1:(o(n),!0)};return qo(!U,{history:_,onNextFrame:()=>ae(1),onPrevFrame:()=>ae(-1),onToggleComplete:()=>h===void 0||k.isPending?!1:(z(!h.complete),!0),onSave:()=>!ne||U?!1:(G(),!0),onZoomIn:S.zoomIn,onZoomOut:S.zoomOut,onZoomFit:S.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:S,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:S.viewport,onViewportChange:S.setViewport,panMode:S.panMode,onSelect:e=>{x(t=>ja(t,e))},onDraw:te,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(Y,{variant:`info`,children:`from the recording`}),m!==void 0&&r(V,{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(V,{variant:`secondary`,size:`sm`,disabled:D.isPending||I.kind!==`resolved`,onClick:()=>void B(`objects`),children:[u(H,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Propose`})]}),r(V,{variant:`secondary`,size:`sm`,disabled:D.isPending||I.kind!==`resolved`,onClick:()=>void B(`package`),children:[u(H,{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:I.kind===`resolved`?`Proposals come from ${I.modelId} at ${I.minScore.toFixed(2)}, on ${I.nodeId} — what this camera really runs.`:Yo[I.gap]}),h!==void 0&&u(Xa,{frame:h,history:_,detector:I,schema:N.data,setNotice:f}),u(`div`,{className:`flex-1 overflow-y-auto`,children:u(Ha,{boxes:v.boxes,selectedKey:v.selectedKey,onSelect:e=>{x(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(C,{"aria-label":`All subjects in this frame are boxed`,checked:h?.complete===!0,disabled:h===void 0||k.isPending,onChange:e=>void z(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.`})]})]}),q>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:[q,` draft`,q===1?``:`s`,` not confirmed — a draft is never saved. Accept, correct or delete each one.`]}),r(V,{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(V,{size:`sm`,disabled:!ne||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([]),x=nt({projection:`slim`,isCamera:!0}),C=a(()=>{let e=new Map;for(let t of x.data??[])e.set(t.id,t.name);return e},[x.data]),w=ue({}),T=mt({trackId:i?.trackId??``},{enabled:t===`tracks`&&i!==null}),D=ne(),O=qe(),k=S(),A=_t({}),j=ot({collectionId:c?.id??``},{enabled:t===`collections`&&c!==null}),M=Pe(),N=He(),P=tt(),F=ae(),I=t===`tracks`?T.data?.copies??[]:j.data??[],L=e(()=>t===`tracks`?T.refetch():j.refetch(),[t,T,j]);d(()=>{p===null&&I.length>0&&m(I[0].frameId)},[I,p]);let R=e(()=>{m(null),g(new Map),v(null)},[]),B=e(e=>{o(e),R()},[R]),ee=e(e=>{f(e),R()},[R]),te=e(async e=>{if(i===null)return;let t=await D.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 T.refetch(),await w.refetch()},[i,D,h,T,w]),H=e(async e=>{let t=(T.data?.copies??[]).find(t=>t.frameId===e);t!==void 0&&(await O.mutateAsync(fa(t)),p===e&&m(null),await T.refetch(),await w.refetch(),await A.refetch())},[T,O,p,w,A]),U=e(async()=>{if(i===null)return;let e=await k.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 w.refetch(),e.changed&&o(null)},[i,k,w]),W=e(async e=>{let t=await M.mutateAsync({name:e});return await A.refetch(),t.kind===`refused`?Zo[t.reason]??t.reason:(f(t.collection),R(),null)},[M,A,R]),G=e(async(e,t)=>{let n=await N.mutateAsync({id:e,name:t});return await A.refetch(),n.kind===`refused`?Zo[n.reason]??n.reason:(c?.id===e&&f(n.collection),null)},[N,A,c]),K=e(async e=>{let t=await P.mutateAsync({id:e});c?.id===e&&(f(null),R()),await A.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.`)},[P,c,A,R]),q=e(async e=>{if(c===null)return;let t=await F.mutateAsync({collectionId:c.id,frameId:e.frameId});p===e.frameId&&m(null),await j.refetch(),await A.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,F,p,j,A]),re=e(async()=>{await w.refetch()},[w]),ie=t===`tracks`?i!==null:c!==null,oe=I.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(V,{size:`sm`,onClick:()=>void U(),children:[u(Xe,{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(E,{value:t,onValueChange:e=>{n(e===`collections`||e===`datasets`?e:`tracks`),R()},children:r(z,{className:`px-2 pt-2`,children:[r(me,{value:`tracks`,children:[`Tracks `,u(Y,{className:`ml-1`,children:w.data?.length??0})]}),r(me,{value:`collections`,children:[`Collections `,u(Y,{className:`ml-1`,children:A.data?.length??0})]}),u(me,{value:`datasets`,children:`Datasets`})]})}),t===`tracks`?u(da,{tracks:w.data??[],isLoading:w.isLoading,selectedTrackId:i?.trackId??null,deviceNames:C,onSelect:B}):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:A.data??[],isLoading:A.isLoading,selectedId:c?.id??null,onSelect:ee,onCreate:W,onRename:G,onDelete:K})]}),u(`section`,{className:`space-y-3 min-w-0`,children:t===`datasets`?u(ia,{deviceNames:C,collections:A.data??[],pickedFrameIds:y,onClearPicked:()=>{b([])}}):ie?r(s,{children:[u(`div`,{className:`rounded-md border border-border bg-surface p-3`,children:t===`tracks`?u(sa,{candidates:T.data?.candidates??[],copies:T.data?.copies??[],activeFrameId:p,refusals:h,isSelecting:D.isPending,onSelectCandidate:e=>void te(e),onOpenCopy:m,onRemoveCopy:e=>void H(e),renderCopyActions:e=>u(Ji,{frameId:e.frameId,onAdded:()=>A.refetch()})}):u(Xi,{frames:j.data??[],isLoading:j.isLoading,activeFrameId:p,deviceNames:C,onOpen:m,onRemove:e=>void q(e)})}),p!==null&&oe&&u(Xo,{frames:I,activeFrameId:p,onActiveFrame:m,onFramesChanged:L,onSaved:re,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:ge,content:u(qi,{})},{id:`retrain`,label:`Retrain`,icon:Xe,content:u(Qo,{})},{id:`debug`,label:`Debug`,icon:st,content:u(bi,{})}]})})}export{$o as EventsPage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,a as r,b as i,o as a,q as o,x as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as c,gt as l,ht as u,st as d,vt as f}from"./player-overlays-D4lg_avJ.js";import{$l as p,Bd as m,Cd as h,Cr as g,Fd as _,Gl as v,H as y,Hl as b,In as x,Jl as S,Jn as C,Kl as w,Ld as T,M as E,N as D,Nt as ee,Pu as O,Ql as te,U as k,Ul as ne,Vd as A,Wl as re,Xl as j,Yl as M,Zl as ie,Zu as N,_f as P,bu as F,cf as I,ef as L,eu as R,id as z,iu as ae,nu as oe,ql as se,qn as B,rd as V,ru as ce,sa as le,tr as ue,tu as de,wr as H,wu as U,xd as fe,xf as pe,zd as me}from"./src-DzkLcOyh.js";import{t as he}from"./unlink-ZWAv-UAl.js";import{a as ge,i as _e,o as ve,s as ye}from"./client-BqN2lVYf.js";import{F as W,K as be,et as xe,o as Se,s as Ce}from"./index-CpGfiJoj.js";import{t as G}from"./AdminPage-BSFohA3i.js";import{t as we}from"./AdminTabs-CjafoxvK.js";import{n as Te,r as Ee,t as De}from"./IntegrationHub-C_kwGzUm.js";import{n as Oe,t as ke}from"./addon-display-names-BkwMrExv.js";var Ae=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`}]]),je=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`}]]),Me=f(`link`,[[`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`,key:`1cjeqo`}],[`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`,key:`19qd67`}]]);e();function Ne({userId:e,username:n,onClose:r}){let i=B(),a=F.useUtils(),o=S({userId:e}),c=F.auth.listLoginMethods.useQuery(),l=ce({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(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4`,children:t(`div`,{"data-testid":`external-identities-modal`,className:`w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl overflow-hidden`,children:[t(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-border`,children:[t(`div`,{className:`flex items-center gap-2`,children:[s(T,{className:`h-4 w-4 text-primary`}),t(`div`,{children:[s(`div`,{className:`text-sm font-medium text-foreground`,children:`Linked sign-in accounts`}),t(`div`,{className:`text-[11px] text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]}),s(`button`,{onClick:r,"aria-label":`Close`,className:`p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle`,children:s(U,{className:`h-4 w-4`})})]}),t(`div`,{className:`p-4 space-y-3`,children:[o.isLoading?t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[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(he,{className:`h-3 w-3`}),`Remove`]})]},`${e.provider}|${e.subject}`)})}),s(`div`,{className:`flex justify-end`,children:s(x,{onClick:r,variant:`secondary`,children:`Close`})})]})]})})}function Pe({userId:e,username:n,onClose:r}){let o=a(),c=B(),l=w({userId:e}),u=l.data,d=()=>o.invalidateQueries({queryKey:[[`userManagement`,`getTotpStatus`]]}),f=v({onSuccess:()=>{d(),r()}}),p=l.isLoading?`loading`:u?.enabled?`enrolled`:`not_enrolled`;return s(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4`,children:t(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl overflow-hidden`,children:[t(`div`,{className:`flex items-center justify-between px-4 py-3 border-b border-border`,children:[t(`div`,{className:`flex items-center gap-2`,children:[s(N,{className:`h-4 w-4 text-primary`}),t(`div`,{children:[s(`div`,{className:`text-sm font-medium text-foreground`,children:`Two-factor authentication`}),t(`div`,{className:`text-[11px] text-foreground-subtle`,children:[`User: `,s(`span`,{className:`font-mono`,children:n})]})]})]}),s(`button`,{onClick:r,className:`p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle`,children:s(U,{className:`h-4 w-4`})})]}),t(`div`,{className:`p-4 space-y-4`,children:[p===`loading`&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[s(_,{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(A,{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(P,{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(x,{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(_,{className:`h-3 w-3 animate-spin`}):s(U,{className:`h-3 w-3`}),`Remove 2FA`]})]})]})]})]})})}function K({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 Fe({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}=le({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(z,{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(_,{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(K,{icon:L,label:`Devices they can see`,count:p.device.view.deviceCount,all:p.device.view.all,total:f}),s(K,{icon:h,label:`Devices they can operate`,count:p.device.create.deviceCount,all:p.device.create.all,total:f}),s(K,{icon:d,label:`Devices they can delete`,count:p.device.delete.deviceCount,all:p.device.delete.all,total:f}),t(`div`,{className:`border-t border-border pt-2 text-[10px] text-foreground-subtle`,children:[`System access: `,p.system.length===0?`none`:p.system.join(`, `),p.capabilities.length>0&&t(i,{children:[` · Extra capabilities: `,p.capabilities.map(e=>e.name).join(`, `)]}),p.addons.length>0&&t(i,{children:[` · Addons: `,p.addons.map(e=>e.name).join(`, `)]})]}),p.device.view.deviceCount===0&&s(`p`,{className:`text-[10px] text-warning`,children:`This user will not be able to see any device.`})]})})}function Ie(e){let t=ve(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 Le(e){return e.mode===`advanced`?e.advancedScopes:e.roleId===null?[]:ge({roleId:e.roleId,selector:e.selector,includeLinked:e.includeLinked})}function Re({user:e,onClose:r,onSubmit:a,submitting:c,callerScopes:d}){let f=n(()=>Ie(e.scopes??[]),[e.scopes]),[p,m]=o(f),[h,g]=o(f.mode===`advanced`),v=n(()=>Le(p),[p]),b=!e.isAdmin&&p.mode===`role`&&p.roleId===null,x=n(()=>e.isAdmin?null:p.mode===`role`&&p.roleId===null?`Pick what this user can do to see the result.`:D(v),[e.isAdmin,p.mode,p.roleId,v]),S=e=>m({...p,...e});return s(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 pt-[calc(1rem+env(safe-area-inset-top))] pb-[calc(1rem+env(safe-area-inset-bottom))]`,children:t(`div`,{className:`flex max-h-full w-full max-w-2xl flex-col rounded-lg border border-border bg-surface shadow-xl`,children:[t(`div`,{className:`flex shrink-0 items-start justify-between border-b border-border px-4 py-3`,children:[t(`div`,{className:`min-w-0`,children:[t(`div`,{className:`text-sm font-semibold text-foreground`,children:[`Access — `,e.username]}),s(`div`,{className:`text-[10px] text-foreground-subtle`,children:e.isAdmin?`This user is an administrator — they can do everything, and the settings below are ignored.`:`Choose what they can do, then which devices it applies to.`})]}),s(`button`,{onClick:r,className:`shrink-0 text-foreground-subtle hover:text-foreground`,title:`Close`,children:s(U,{className:`h-4 w-4`})})]}),t(`div`,{className:`min-h-0 flex-1 space-y-4 overflow-y-auto px-4 py-4`,children:[b&&t(`div`,{className:`flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/10 p-3`,children:[s(z,{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:_e.map(e=>{let n=p.mode===`role`&&p.roleId===e.id;return t(`label`,{className:`flex cursor-pointer items-start gap-2 rounded-lg border p-2.5 transition-colors ${n?`border-primary bg-primary/5`:`border-border hover:bg-foreground-subtle/5`}`,children:[s(`input`,{type:`radio`,name:`access-role`,checked:n,onChange:()=>S({mode:`role`,roleId:e.id}),className:`mt-0.5 border-border focus:ring-primary`}),t(`span`,{className:`min-w-0`,children:[s(`span`,{className:`block text-[12px] font-medium text-foreground`,children:e.label}),s(`span`,{className:`mt-0.5 block text-[10px] text-foreground-subtle`,children:e.description})]})]},e.id)})}),t(`button`,{type:`button`,onClick:()=>{if(!h){m({...p,mode:`advanced`,advancedScopes:v}),g(!0);return}g(!1),m(Ie(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(E,{value:p.advancedScopes,onChange:e=>S({mode:`advanced`,advancedScopes:e}),clampToParent:d,emptyHint:t(i,{children:[`No grants.`,` `,s(`span`,{className:`font-medium text-foreground`,children:e.username}),` cannot call any protected endpoint until one is added.`]})})]})]}),p.mode===`role`&&t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`2 · On which devices`}),s(y,{value:p.selector,onChange:e=>S({selector:e}),includeLinked:p.includeLinked,onIncludeLinkedChange:e=>S({includeLinked:e}),clampToDeviceIds:null})]}),t(`section`,{className:`space-y-2`,children:[s(`h3`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p.mode===`role`?`3 · Result`:`2 · Result`}),s(Fe,{scopes:v,isAdmin:e.isAdmin,invalidReason:x})]})]}),t(`div`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3`,children:[s(`button`,{onClick:r,className:`rounded border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground`,children:`Cancel`}),s(`button`,{onClick:()=>a([...v]),disabled:c||x!==null,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:c?s(_,{className:`h-3 w-3 animate-spin`}):`Save access`})]})]})})}e();var ze=8;function Be(){let e=a(),{user:n}=W(),[r,i]=o(!1),[c,l]=o(``),[u,f]=o(``),[p,m]=o(!1),[h,g]=o(null),{data:v,isLoading:y,isError:b}=ie(),x=B(),S=C(),w=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listUsers`]]}),E=ne({onSuccess:()=>{w(),i(!1),l(``),f(``),m(!1),g(null)},onError:e=>{g(e instanceof Error?e.message:`Failed to create user`)}}),D=re({onSuccess:w}),O=ae({onSuccess:w}),k=te({onSuccess:w}),A=oe({onSuccess:()=>{w(),M(null)}}),[j,M]=o(null),[P,F]=o(null),[I,L]=o(null),R=v??[];async function z(e){await x({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`})&&D.mutate({id:e.id})}async function se(e){let t=await S({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<ze?`Password must be at least ${String(ze)} characters.`:null});t===null||t.length===0||await x({title:`Reset password`,message:`Reset the password for "${e.username}"? They will need to use the new password on their next login.`,confirmLabel:`Reset`})&&k.mutate({id:e.id,newPassword:t})}function ce(e,t){t!==e.isAdmin&&O.mutate({id:e.id,isAdmin:t})}function le(e){return e?new Date(typeof e==`number`?e:String(e)).toLocaleDateString(`en-GB`,{day:`2-digit`,month:`short`,year:`numeric`}):`—`}return t(G,{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(fe,{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(U,{className:`h-4 w-4`})})]}),t(`div`,{className:`grid grid-cols-3 gap-3`,children:[t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Username`}),s(`input`,{type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`john`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Password`}),s(`input`,{type:`password`,value:u,onChange:e=>f(e.target.value),placeholder:`••••••••`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:`Admin`}),t(`label`,{className:`flex items-center gap-2 rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground cursor-pointer`,children:[s(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked),className:`rounded border-border focus:ring-primary`}),s(`span`,{className:`text-foreground-subtle`,children:`Unrestricted access`})]})]})]}),h&&s(`p`,{className:`text-[10px] text-danger`,children:h}),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:()=>E.mutate({username:c,password:u,isAdmin:p}),disabled:E.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:E.isPending?`Creating...`:`Create`})]})]}),y&&s(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:`Loading...`}),b&&s(`div`,{className:`text-xs text-danger`,children:`Failed to load`}),!y&&!b&&R.length===0&&s(`div`,{className:`text-xs text-foreground-subtle`,children:`No data`}),(()=>{let e=e=>D.isPending&&D.variables?.id===e.id||O.isPending&&O.variables?.id===e.id||k.isPending&&k.variables?.id===e.id;return s(ee,{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=>ce(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:()=>M(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(V,{className:`h-3 w-3 shrink-0 text-foreground-subtle`}),s(Ve,{scopes:e.scopes??[]})]})},{key:`createdAt`,header:`Created`,render:e=>s(`span`,{className:`text-foreground-subtle`,children:le(e.createdAt)})},{key:`actions`,header:`Actions`,align:`right`,render:r=>{let i=e(r);return t(`div`,{className:`flex items-center justify-end gap-1`,children:[r.id!==n?.id&&r.totpEnabled&&t(`button`,{onClick:()=>F(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Remove two-factor authentication`,children:[s(N,{className:`h-3 w-3`}),`Remove 2FA`]}),t(`button`,{onClick:()=>L(r),disabled:i,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50`,title:`Linked sign-in accounts`,children:[s(T,{className:`h-3 w-3`}),`Sign-in links`]}),t(`button`,{onClick:()=>se(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(me,{className:`h-3 w-3`}),`Reset password`]}),t(`button`,{onClick:()=>z(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(_,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Delete`]})]})}}],rows:R,rowKey:e=>e.id,minWidthPx:560})})(),P&&s(Pe,{userId:P.id,username:P.username,onClose:()=>F(null)}),I&&s(Ne,{userId:I.id,username:I.username,onClose:()=>L(null)}),j&&s(He,{user:j,onClose:()=>M(null),onSubmit:e=>A.mutate({userId:j.id,scopes:e}),submitting:A.isPending})]})}function Ve({scopes:e}){if(e.length===0)return s(`span`,{className:`font-medium text-warning`,children:`No access`});let n=ve(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:ye(n.roleId).label}),` ·`,` `,k(n.selector)]})}function He(e){let{user:t}=W(),n=t?.isAdmin===!0;return s(Re,{...e,callerScopes:n?null:t?.scopes??[]})}e();var Ue=`bg-primary/10 text-primary`,We=`bg-foreground-subtle/10 text-foreground-subtle`;function q(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toLocaleString()}function Ge(e){return e?e===`*`?`*`:e.join(`, `):``}function Ke(){let e=a(),r=B(),{data:i,isLoading:c}=se(),{data:l}=ie(),u=n(()=>i??[],[i]),f=n(()=>l??[],[l]),m=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listApiKeys`]]}),h=()=>e.invalidateQueries({queryKey:[[`userManagement`,`listScopedTokens`]]}),[g,v]=o(!1),[y,x]=o(null),S=p({onSuccess:m}),C=b({onSuccess:({token:e,record:t})=>{h(),v(!1),x({token:e,label:t.name})}}),w=de({onSuccess:h}),T=async(e,t)=>{await r({title:`Revoke "${t}"?`,message:`Any client using this token will lose access immediately. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&S.mutate({id:e})},E=async(e,t)=>{await r({title:`Revoke "${t}"?`,message:`The scoped token will be invalid on its next use.`,confirmLabel:`Revoke`,variant:`danger`})&&w.mutate({id:e})};return t(G,{children:[t(`div`,{className:`flex items-center justify-between gap-3 flex-wrap`,children:[s(`p`,{className:`text-xs text-foreground-subtle max-w-2xl`,children:`Issue scoped tokens to grant a user a narrow surface — a specific addon, integration, or capability. Every token MUST be scoped: revoking it has predictable blast radius.`}),t(`button`,{onClick:()=>v(!0),className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,disabled:f.length===0,title:f.length===0?`Create a user first`:`Issue a scoped token`,children:[s(V,{className:`h-3.5 w-3.5`}),`New token`]})]}),t(qe,{title:`Scoped tokens`,subtitle:`Grouped per user`,children:[f.length===0&&s(Ye,{text:`No users yet — scoped tokens are issued on behalf of an existing user.`}),f.map(e=>s(Ze,{userId:e.id,username:e.username,onRevoke:(e,t)=>{E(e,t)},revokePending:w.isPending,revokeId:w.variables?.id},e.id))]}),u.length>0&&s(qe,{title:`Legacy API keys`,subtitle:`${u.length} pre-existing — revoke only`,children:s(Xe,{headers:[`Label`,`Admin`,`Prefix`,`Allowed providers`,`Created`,`Last used`,``],rows:u.map(e=>{let n=!!e.isAdmin,r=S.isPending&&S.variables?.id===e.id;return t(`tr`,{className:`hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-medium`,children:e.label}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:s(`span`,{className:`inline-block rounded px-2 py-0.5 text-[10px] uppercase tracking-wide ${n?Ue:We}`,children:n?`admin`:`regular`})}),t(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-mono text-[11px]`,children:[e.tokenPrefix,`…`]}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border text-foreground-subtle`,children:Ge(e.allowedProviders)||`all`}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:q(e.createdAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:q(e.lastUsedAt)}),s(`td`,{className:`px-3 py-2 border-b border-border text-right`,children:t(`button`,{onClick:()=>{T(e.id,e.label)},disabled:r,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Revoke`,children:[r?s(_,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Revoke`]})})]},e.id)})})}),c&&s(Je,{}),g&&s(Qe,{users:f.map(e=>({id:e.id,username:e.username})),onClose:()=>v(!1),onSubmit:e=>C.mutate({userId:e.userId,name:e.name,scopes:e.scopes,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}}),submitting:C.isPending}),y&&s($e,{token:y.token,label:y.label,onClose:()=>x(null)})]})}function qe({title:e,subtitle:n,children:r}){return t(`div`,{className:`space-y-2`,children:[t(`div`,{className:`flex items-baseline justify-between`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:e}),n&&s(`span`,{className:`text-[10px] text-foreground-subtle`,children:n})]}),r]})}function Je(){return s(`div`,{className:`space-y-2`,children:[1,2].map(e=>s(`div`,{className:`h-10 rounded border border-border bg-surface animate-pulse`},e))})}function Ye({text:e}){return s(`div`,{className:`rounded border border-dashed border-border bg-surface px-3 py-4 text-xs text-foreground-subtle text-center`,children:e})}function Xe({headers:e,rows:n}){return s(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:t(`table`,{className:`w-full text-xs min-w-[640px]`,children:[s(`thead`,{children:s(`tr`,{children:e.map((t,n)=>s(`th`,{className:`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border whitespace-nowrap ${n===e.length-1?`text-right`:`text-left`}`,children:t},n))})}),s(`tbody`,{children:n})]})})}function Ze({userId:e,username:n,onRevoke:r,revokePending:i,revokeId:a}){let{data:o,isLoading:c}=j({userId:e}),l=o??[];return c||l.length===0?null:t(`div`,{className:`space-y-1.5`,children:[s(`div`,{className:`text-[11px] font-medium text-foreground`,children:n}),s(Xe,{headers:[`Name`,`Prefix`,`Scopes`,`Expires`,`Last used`,`Created`,``],rows:l.map(e=>{let n=i&&a===e.id;return t(`tr`,{className:`hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-medium`,children:e.name}),t(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-mono text-[11px]`,children:[e.tokenPrefix,`…`]}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:s(`div`,{className:`flex flex-wrap gap-1`,children:e.scopes.map((e,n)=>t(`span`,{className:`inline-block rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-mono`,children:[e.type,`:`,e.type===`device`?`[${k(e.selector)}]`:e.target]},n))})}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:q(e.expiresAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:q(e.lastUsedAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:q(e.createdAt)}),s(`td`,{className:`px-3 py-2 border-b border-border text-right`,children:t(`button`,{onClick:()=>r(e.id,e.name),disabled:n,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,children:[n?s(_,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Revoke`]})})]},e.id)})})]})}function Qe({users:e,onClose:n,onSubmit:r,submitting:i}){let{user:a}=W(),c=a?.isAdmin===!0?null:a?.scopes??[],[l,u]=o(e[0]?.id??``),[d,f]=o(``),[p,m]=o([{type:`capability`,target:``,access:[`view`,`create`]}]),[h,g]=o(``),v=D(p),y=l!==``&&d.trim().length>0&&p.length>0&&v===null&&!i;return t(J,{title:`Create scoped token`,onClose:n,children:[t(`div`,{className:`space-y-3`,children:[s(Y,{label:`On behalf of user`,children:s(`select`,{value:l,onChange:e=>u(e.target.value),className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary`,children:e.map(e=>s(`option`,{value:e.id,children:e.username},e.id))})}),s(Y,{label:`Name`,children:s(`input`,{value:d,onChange:e=>f(e.target.value),placeholder:`cloudflare-tunnel-route`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary`})}),t(Y,{label:`Scopes`,hint:`Each scope picks a (cap or addon) target + one or more access flavours. The token can access ONLY what's listed.`,children:[s(E,{value:p,onChange:m,clampToParent:c}),v&&s(`p`,{className:`mt-1 text-[10px] text-danger`,children:v})]}),s(Y,{label:`Expires in (days)`,hint:`Leave blank for non-expiring.`,children:s(`input`,{type:`number`,min:1,value:h,onChange:e=>g(e.target.value),placeholder:`30`,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary`})})]}),t(et,{children:[s(`button`,{onClick:n,className:`rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground`,children:`Cancel`}),t(`button`,{onClick:()=>{let e=parseInt(h,10),t=Number.isFinite(e)&&e>0?Date.now()+e*864e5:void 0;r({userId:l,name:d.trim(),scopes:p,expiresAt:t})},disabled:!y,className:`inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50`,children:[i?s(_,{className:`h-3.5 w-3.5 animate-spin`}):s(V,{className:`h-3.5 w-3.5`}),`Issue token`]})]})]})}function $e({token:e,label:n,onClose:r}){let[i,a]=o(!1),c=async()=>{try{await navigator.clipboard.writeText(e),a(!0)}catch{}};return t(J,{title:`Token: ${n}`,onClose:r,children:[t(`div`,{className:`space-y-3`,children:[s(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:`Copy this token now. Once you close this dialog the secret cannot be displayed again.`}),s(`div`,{className:`rounded border border-border bg-background p-2 font-mono text-[11px] break-all select-all`,children:e})]}),t(et,{children:[t(`button`,{onClick:()=>{c()},className:`inline-flex items-center gap-1.5 rounded bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30`,children:[i?s(pe,{className:`h-3.5 w-3.5 text-primary`}):s(I,{className:`h-3.5 w-3.5`}),i?`Copied`:`Copy`]}),s(`button`,{onClick:r,className:`rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90`,children:`Done`})]})]})}function J({title:e,onClose:n,children:r}){return s(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm`,onClick:n,children:t(`div`,{className:`w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl`,onClick:e=>e.stopPropagation(),children:[t(`div`,{className:`flex items-start justify-between border-b border-border px-4 py-3`,children:[s(`h2`,{className:`text-sm font-semibold text-foreground`,children:e}),s(`button`,{onClick:n,className:`text-foreground-subtle hover:text-foreground`,children:s(U,{className:`h-4 w-4`})})]}),s(`div`,{className:`p-4`,children:r})]})})}function et({children:e}){return s(`div`,{className:`flex justify-end gap-2 border-t border-border px-4 py-3`,children:e})}function Y({label:e,hint:n,children:r}){return t(`div`,{className:`space-y-1`,children:[s(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:e}),r,n&&s(`p`,{className:`text-[10px] text-foreground-subtle`,children:n})]})}e();function X(e){if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?`—`:t.toLocaleString()}function tt(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 nt(){return s(`div`,{className:`space-y-2`,children:[1,2].map(e=>s(`div`,{className:`h-10 rounded border border-border bg-surface animate-pulse`},e))})}function rt({text:e}){return s(`div`,{className:`rounded border border-dashed border-border bg-surface px-3 py-4 text-xs text-foreground-subtle text-center`,children:e})}function it({headers:e,rows:n}){return s(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:t(`table`,{className:`w-full text-xs min-w-[640px]`,children:[s(`thead`,{children:s(`tr`,{children:e.map((t,n)=>s(`th`,{className:`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border whitespace-nowrap ${n===e.length-1?`text-right`:`text-left`}`,children:t},n))})}),s(`tbody`,{children:n})]})})}function at(){let e=a(),r=B(),{data:i,isLoading:o}=M(),c=n(()=>i??[],[i]),l=R({onSuccess:()=>e.invalidateQueries({queryKey:[[`userManagement`,`listOauthSessions`]]})}),u=async(e,t)=>{await r({title:`Revoke "${t}" session?`,message:`This integration will lose access immediately on its next API call. This cannot be undone.`,confirmLabel:`Revoke`,variant:`danger`})&&l.mutate({id:e})};return t(G,{icon:Me,title:`Linked Sessions`,subtitle:`External integrations (Alexa, …) linked to this hub via OAuth. Revoke a session to immediately invalidate that integration's access.`,children:[o&&s(nt,{}),!o&&c.length===0&&s(rt,{text:`No linked sessions — once an external integration completes the OAuth flow its session will appear here.`}),!o&&c.length>0&&s(it,{headers:[`Integration`,`User`,`Scopes`,`Created`,`Last used`,`Status`,``],rows:c.map(e=>{let n=e.revokedAt!==null,r=(l.isPending?l.variables?.id:void 0)===e.id;return t(`tr`,{className:`hover:bg-primary/5`,children:[s(`td`,{className:`px-3 py-2 text-foreground border-b border-border font-medium`,children:e.integrationId}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:e.username}),s(`td`,{className:`px-3 py-2 text-foreground border-b border-border`,children:s(`div`,{className:`flex flex-wrap gap-1`,children:e.scopes.map((e,t)=>s(`span`,{className:`inline-block rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-mono`,children:tt(e)},t))})}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:X(e.createdAt)}),s(`td`,{className:`px-3 py-2 text-foreground-subtle border-b border-border`,children:X(e.lastUsedAt)}),s(`td`,{className:`px-3 py-2 border-b border-border`,children:n?t(`span`,{className:`inline-block rounded bg-foreground-subtle/10 px-2 py-0.5 text-[10px] text-foreground-subtle`,children:[`Revoked `,X(e.revokedAt)]}):s(`span`,{className:`inline-block rounded bg-emerald-500/15 px-2 py-0.5 text-[10px] text-emerald-700 dark:text-emerald-300`,children:`Active`})}),s(`td`,{className:`px-3 py-2 border-b border-border text-right`,children:!n&&t(`button`,{onClick:()=>{u(e.id,e.integrationId)},disabled:r,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50`,title:`Revoke`,children:[r?s(_,{className:`h-3 w-3 animate-spin`}):s(d,{className:`h-3 w-3`}),`Revoke`]})})]},e.id)})})]})}e();var Z=3e4,Q=[{capName:`auth-provider`,stageBadge:null},{capName:`user-passkeys`,stageBadge:`Second factor`}],$={title:`Authentication`,subtitle:`Login providers (local password, OIDC, SAML, magic-link) 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 ot(e){return e===`local-auth`?{headline:`Username + password (local).`,icon:je,bullets:[`Users live in the hub’s SQLite database — no IdP roundtrip.`,`TOTP / 2FA is self-enrolled: each user enables it from their own profile page (My access → Two-factor authentication).`,`API keys + scoped tokens are managed from the API Keys page.`],setupSteps:[`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:N,bullets:[`Enroll a YubiKey, Touch ID, or platform passkey per user.`,`Resistant to phishing — the browser binds the credential to your hub origin.`]}:e.startsWith(`auth-totp`)||e.startsWith(`auth-magic-link`)?{headline:`TOTP / magic-link — second factor or passwordless sign-in.`,icon:N,bullets:[`Codes / links delivered out-of-band (RFC 6238 for TOTP).`,`Compatible with Google Authenticator, Aegis, 1Password, Bitwarden, etc.`]}:{headline:`Authentication provider.`,icon:V,bullets:[`Generic authentication provider. No additional hints registered.`]}}function st(){let e=H({capName:Q[0].capName},{refetchInterval:Z}),t=H({capName:Q[1].capName},{refetchInterval:Z}),r=g(void 0,{refetchInterval:Z}),i=n(()=>ke(r.data??[]),[r.data]),a=n(()=>{let n=[],r=[e.data??[],t.data??[]];for(let[e,t]of Q.entries())for(let a of r[e]??[])n.push({addonId:a.addonId,displayName:i.get(a.addonId)??a.addonId,isActive:a.isActive,capName:t.capName,stageBadge:t.stageBadge});return n},[e.data,t.data,i]),o=[{id:`authentication`,label:`Authentication providers`,install:{capability:Q[0].capName,label:$.installLabel},entries:a.map(e=>({id:e.addonId,name:e.displayName,fallbackIcon:V,...Oe(e.isActive),render:()=>s(Te,{addonId:e.addonId,displayName:e.displayName,capName:e.capName,isActive:e.isActive,badges:e.stageBadge===null?null:s(ue,{variant:`info`,className:Ee,children:e.stageBadge}),panels:[{id:`about`,title:`About`,icon:ot(e.addonId).icon,content:s(ct,{addonId:e.addonId})}]})}))}];return s(De,{icon:V,title:$.title,subtitle:$.subtitle,groups:o,isLoading:e.isLoading||t.isLoading,emptyTitle:$.emptyTitle,emptyDescription:$.emptyDescription})}function ct({addonId:e}){let n=ot(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(Ae,{className:`h-3 w-3`}),`Setup steps`]}),s(`ol`,{className:`text-xs text-foreground space-y-0.5 pl-4 list-decimal`,children:n.setupSteps.map((e,t)=>s(`li`,{children:e},t))})]}),e===`local-auth`&&t(`div`,{className:`rounded-md border border-blue-500/30 bg-blue-500/5 px-3 py-2 flex items-start gap-2 text-[11px] text-foreground`,children:[s(A,{className:`h-3.5 w-3.5 mt-0.5 text-blue-500 shrink-0`}),t(`span`,{children:[`TOTP / 2FA is self-service: each user enrols from their own profile page —`,` `,s(be,{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(be,{to:`/system/identity?tab=users`,className:`underline text-primary`,children:`Users`}),` `,`page via Actions → “Remove 2FA”.`]})]})]})}function lt(){return s(`div`,{className:`flex flex-col p-4`,children:s(we,{tabs:[{id:`users`,label:`Users`,icon:O,content:s(Be,{})},{id:`api-keys`,label:`Tokens`,icon:m,content:s(Ke,{})},{id:`linked-sessions`,label:`Linked Sessions`,icon:Me,content:s(at,{})},{id:Ce.authentication.tab,label:`Authentication`,icon:V,content:s(st,{}),ownedParams:Se}]})})}export{lt as IdentityPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,b as a,o,q as s,x as c,z as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as u,gt as d,ht as f,mt as p,st as m,vt as h}from"./player-overlays-D4lg_avJ.js";import{$a as g,$i as _,Bi as v,Dt as y,Du as b,Fd as x,Hi as S,It as C,Ji as w,K as T,Ki as E,Na as D,Qa as O,Qi as k,Qt as A,Ui as j,Vi as ee,Wi as te,Y as ne,Za as re,_d as M,_t as N,dr as P,ef as F,eo as I,ff as L,fr as R,ga as z,gf as B,hd as ie,io as ae,kr as V,ld as H,ma as oe,md as se,na as U,no as W,od as ce,pn as G,pu as le,q as ue,qi as de,sa as fe,to as pe,uu as K,wu as me,xd as he,xf as ge,zf as _e,zu as q}from"./src-DzkLcOyh.js";import{Tr as ve}from"./client-BqN2lVYf.js";import{t as ye}from"./useTranslation-Bc5yH9V9.js";import{J as be,N as xe,W as Se,Y as Ce,q as we}from"./index-CpGfiJoj.js";import{t as Te}from"./NodeAddonsSettingsPanel-DhbzB3yG.js";import{t as Ee}from"./device-integration-icon-CPFH1cD5.js";import{n as J,r as De,t as Oe}from"./ScanNetworkModal-mYvbo8Uo.js";var ke=h(`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 Ae(e){let t=[];for(let n of e)n.type===`probe`&&t.push(n.key),n.type===`group`&&`fields`in n&&t.push(...Ae(n.fields));return t}function je(t,n,r){let[a,o]=s(`idle`),[c,l]=s({}),u=i(()=>{let e=[];for(let n of t.sections)e.push(...Ae(n.fields));return e},[t]),d=u.length>0&&r!==void 0,f=e(e=>{l(t=>{if(!t[e])return t;let n={...t};return delete n[e],n})},[]);return{testAllStatus:a,hasProbeFields:d,probeResults:c,handleTestAll:e(async()=>{if(!r)return;let e=u.filter(e=>{let t=n[e];return t!=null&&String(t).trim()!==``});if(e.length===0)return;o(`testing`);let t={};for(let n of e)t[n]={status:`probing`};l(t);let i=await Promise.allSettled(e.map(async e=>{try{return{key:e,result:await r(e,n[e])}}catch(t){return{key:e,result:{status:`error`,error:t instanceof Error?t.message:String(t)}}}})),a={};for(let e of i)if(e.status===`fulfilled`){let{key:t,result:n}=e.value;a[t]={status:n.status===`ok`?`ok`:`error`,result:n}}l(a),o(`idle`)},[r,u,n]),clearProbeResult:f}}n();function 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 Y(e,t={}){for(let n of e){if(n.type===`group`&&`fields`in n){Y(n.fields,t);continue}`key`in n&&n.key&&`default`in n&&n.default!==void 0&&(t[n.key]=n.default)}return t}function X(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`probe-${crypto.randomUUID()}`:`probe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Pe({open:t,integrationId:n,addonId:a,onClose:u}){let{t:f}=ye(),p=o(),[m,h]=s({}),[g,_]=s(!1),[v,y]=s(null),[S,C]=s(X),w=oe({addonId:a},{enabled:t}),T=w.data?.deviceType??null,E=U({addonId:a,type:T??ve.Camera},{enabled:t&&w.isSuccess&&T!==null}),O=E.data??null;l(()=>{t&&(h(O?Y(O.sections.flatMap(e=>e.fields)):{}),C(X()),_(!1),y(null))},[t,n,O]);let k=i(()=>({...m,_probeRequestId:S}),[m,S]),A=de({onSuccess:()=>{p.invalidateQueries({queryKey:[[`deviceManager`]]})}}),j=D(),ee=e(async(e,t)=>{_(!0);let n=await j.mutateAsync({addonId:a,type:T??ve.Camera,key:e,value:t,formValues:k});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,a,k,T]),{testAllStatus:te,hasProbeFields:ne,probeResults:re,handleTestAll:M,clearProbeResult:P}=je(O??{sections:[]},m,ee);async function F(e){y(null);try{await A.mutateAsync({addonId:a,type:T??ve.Camera,config:m,integrationId:n}),e?h(O?Y(O.sections.flatMap(e=>e.fields)):{}):u()}catch(e){y(e instanceof Error?e.message:String(e))}}if(!t)return null;let I=Me((O?.sections??[]).flatMap(e=>e.fields)).filter(e=>Ne(m[e])),L=I.length===0,R=w.isLoading||T!==null&&E.isLoading,z=w.isError||w.isSuccess&&T===null||E.isError||E.isSuccess&&O===null;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[c(`div`,{className:`absolute inset-0 bg-black/60`,onClick:u}),r(`div`,{className:`relative z-10 flex w-full max-w-2xl flex-col max-h-[calc(90dvh-2*max(env(safe-area-inset-top),env(safe-area-inset-bottom)))] rounded-xl border border-border bg-background shadow-2xl`,children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-5 py-4 shrink-0`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:f(`integrations.addDevice`)}),c(`button`,{onClick:u,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:c(me,{className:`h-4 w-4`})})]}),c(`div`,{className:`flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-3`,children:R?c(`div`,{className:`flex items-center justify-center py-8`,children:c(x,{className:`h-5 w-5 animate-spin text-primary`})}):z?r(`div`,{className:`flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3`,children:[c(q,{className:`h-4 w-4 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`space-y-1`,children:[c(`p`,{className:`text-xs font-medium text-destructive`,children:`Provider unavailable`}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`The addon `,c(`span`,{className:`font-mono`,children:a}),` is not ready or does not support manual device creation. Check that the integration is online and try again.`]})]})]}):c(xe,{schema:O,values:m,onChange:h,onTestField:ee,probeResults:re,onClearProbe:P})}),!z&&!R&&r(`div`,{className:`border-t border-border bg-surface/50 shrink-0`,children:[r(`button`,{type:`button`,onClick:()=>_(e=>!e),className:`flex w-full items-center justify-between px-5 py-2 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[r(`span`,{className:`flex items-center gap-2`,children:[c(H,{className:`h-3.5 w-3.5`}),`Test logs`,c(`span`,{className:`font-mono text-[9px] opacity-60`,children:S.slice(0,14)})]}),c(d,{className:`h-3.5 w-3.5 transition-transform ${g?`rotate-180`:``}`})]}),g&&c(`div`,{className:`border-t border-border max-h-64 overflow-hidden`,children:c(N,{addonId:a,requestId:S,limit:50,maxHeight:`max-h-64`,showFilters:!1,showScope:!1,className:`border-0 rounded-none`})})]}),!z&&!R&&(v||I.length>0)&&c(`div`,{className:`border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[c(q,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),c(`p`,{className:`text-[11px] text-destructive`,children:v||`Required: ${I.join(`, `)}`})]})}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[r(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{onClick:u,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors`,children:f(`integrations.cancel`)}),!z&&ne&&r(`button`,{type:`button`,onClick:M,disabled:te===`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:[te===`testing`?c(x,{className:`h-3.5 w-3.5 animate-spin`}):c(b,{className:`h-3.5 w-3.5`}),`Test All`]})]}),r(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{onClick:()=>F(!0),disabled:z||!L||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`)}),c(`button`,{onClick:()=>F(!1),disabled:z||!L||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 Z=1500;function Fe({addonId:e,integrationId:t,jobId:n,onFinished:i}){let{t:a}=ye(),o=v(),s=(j({addonId:e,integrationId:t},{refetchInterval:e=>(e.state.data??[]).some(e=>e.state===`running`)?Z:!1}).data??[]).find(e=>e.jobId===n);if(!s)return null;let l=s.state===`running`,u=s.processed,d=s.total>0?Math.round(u/s.total*100):0;!l&&s.finishedAt!==null&&i();let f=[`${u}/${s.total} ${a(`integrations.adoptJobProcessed`,{defaultValue:`processed`})}`];s.adopted>0&&f.push(`${s.adopted} ${a(`integrations.adoptJobAdded`,{defaultValue:`added`})}`),s.alreadyAdopted>0&&f.push(`${s.alreadyAdopted} ${a(`integrations.adoptJobSkipped`,{defaultValue:`already there`})}`),s.failed>0&&f.push(`${s.failed} ${a(`integrations.adoptJobFailed`,{defaultValue:`failed`})}`);let p=f.join(` · `);return r(`div`,{className:`border-t border-border px-5 py-3 shrink-0 space-y-2`,children:[r(`div`,{className:`flex items-center gap-2`,children:[l?c(x,{className:`h-3.5 w-3.5 animate-spin text-primary shrink-0`}):s.failed>0?c(q,{className:`h-3.5 w-3.5 text-destructive shrink-0`}):s.state===`cancelled`?c(L,{className:`h-3.5 w-3.5 text-foreground-subtle shrink-0`}):c(B,{className:`h-3.5 w-3.5 text-primary shrink-0`}),c(`p`,{className:`text-[11px] text-foreground`,children:p}),l&&c(`button`,{onClick:()=>o.mutate({jobId:n}),className:`ml-auto rounded-lg border border-border px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:a(`integrations.adoptJobCancel`,{defaultValue:`Stop`})})]}),c(`div`,{className:`h-1 w-full rounded-full bg-border overflow-hidden`,children:c(`div`,{className:`h-full bg-primary transition-all`,style:{width:`${d}%`},role:`progressbar`,"aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100})}),s.results.filter(e=>e.outcome===`failed`).slice(0,5).map(e=>r(`p`,{className:`text-[11px] text-destructive`,children:[e.childNativeId,`: `,e.error]},e.childNativeId))]})}function Ie(e){let t=e.metadata;return[e.name,e.childNativeId,t.model,t.manufacturer,t.integration,t.externalLocation].filter(e=>typeof e==`string`&&e.length>0).join(` `)}n();var Le=`devices`,Re={id:Le,label:`Devices`,isDefault:!0},Q=2e4,ze=100;function Be({addonId:n,integrationId:i,onClose:a}){let{t:u}=ye(),d=o(),[f,p]=s(new Set),[m,h]=s(new Set),[_,v]=s(new Map),[y,b]=s(null),{data:C}=g(),w=(C??[]).find(e=>e.addonId===n)?.supportsLocationImport??!1,[D,O]=s(!0),k=ee({addonId:n,integrationId:i}).data?.filters,A=k&&k.length>0?k:[Re],[j,ne]=s(A.find(e=>e.isDefault)?.id??(A.some(e=>e.id===Le)?Le:A[0].id)),re=j!==Le,M=te(),N=S({addonId:n,integrationId:i,page:1,pageSize:Q,filter:j}),P=N.refetch,F=M.mutate,I=e(()=>{F({addonId:n,integrationId:i},{onSettled:()=>{P()}})},[F,n,i,P]),L=t(null);l(()=>{let e=`${n}::${i}`;L.current===e||N.isLoading||(L.current=e,(N.data?.candidates.length??0)===0&&I())},[n,i,N.isLoading,N.data,I]);let R=M.isPending,z=M.isError?M.error instanceof Error?M.error.message:String(M.error):null,B=typeof M.data?.lastError==`string`&&M.data.lastError.length>0?M.data.lastError:null,ie=N.data?.candidates??[],ae=N.isError?N.error instanceof Error?N.error.message:String(N.error):null,V=E(),[H,oe]=s(null),U=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})},[]),W=e(e=>{h(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ce=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})},[]),G=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},[_]),ue=e(async()=>{b(null);let e=[...f];if(e.length!==0)try{let t=G(e),{jobId:r}=await V.mutateAsync({addonId:n,integrationId:i,filter:j,childNativeIds:e,...t?{perCandidate:t}:{},...w?{importLocations:D}:{}});oe(r),p(new Set),v(new Map)}catch(e){b(e instanceof Error?e.message:String(e))}},[f,G,V,n,i,j,w,D]),de=t(null),fe=e(()=>{H===null||de.current===H||(de.current=H,P(),d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]}))},[H,P,d]),pe=e(e=>{ne(e),p(new Set),h(new Set),v(new Map),b(null)},[]),he=f.size,_e=H!==null&&he===0&&!V.isPending;return r(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[c(`div`,{className:`absolute inset-0 bg-black/60`,onClick:a}),r(`div`,{className:`relative z-10 flex w-full max-w-3xl flex-col h-[85vh] rounded-xl border border-border bg-background shadow-2xl`,children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-5 py-4 shrink-0`,children:[r(`div`,{className:`min-w-0`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:u(`integrations.adoptDevices`,{defaultValue:`Adopt devices`})}),c(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5`,children:u(`integrations.adoptDevicesHint`,{defaultValue:`Preview the candidate devices and add the ones you want.`})})]}),r(`div`,{className:`flex items-center gap-3 shrink-0`,children:[w&&r(`label`,{className:`flex items-center gap-1.5 cursor-pointer text-[11px] text-foreground-subtle hover:text-foreground transition-colors`,children:[c(`input`,{type:`checkbox`,checked:D,onChange:e=>O(e.target.checked),className:`accent-primary`}),u(`integrations.importLocations`,{defaultValue:`Import locations from the integration`})]}),c(`button`,{onClick:a,className:`rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Close`,children:c(me,{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:[(z??ae??B)&&ie.length===0&&c(`div`,{className:`rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[c(q,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),r(`div`,{className:`min-w-0`,children:[c(`p`,{className:`text-xs font-medium text-destructive`,children:u(`integrations.adoptRefreshFailed`,{defaultValue:`Could not discover devices.`})}),c(`p`,{className:`text-[11px] text-destructive/90 mt-0.5`,children:z??ae??B})]})]})}),A.length>1&&c(Ve,{filters:A,activeFilter:j,onSelect:pe}),c(`div`,{className:`flex-1 min-h-0`,children:c(T,{mode:`generic`,items:ie,pageSize:ze,getKey:e=>e.childNativeId,getSearchText:Ie,getFilterType:e=>e.type,filterOptions:K(),filterLabel:u(`integrations.adoptColType`,{defaultValue:`Type`}),isLoading:N.isLoading||R&&ie.length===0,searchPlaceholder:u(`integrations.adoptSearch`,{defaultValue:`Search candidates…`}),emptyLabel:(z??ae??B)&&ie.length===0?``:u(`integrations.adoptNoCandidates`,{defaultValue:`No candidate devices found.`}),toolbar:r(`button`,{type:`button`,onClick:I,disabled:R,title:u(`integrations.adoptRefreshTitle`,{defaultValue:`Re-scan Home Assistant for devices`}),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-60 shrink-0`,children:[c(se,{className:`h-3.5 w-3.5 ${R?`animate-spin`:``}`}),u(`integrations.adoptRefresh`,{defaultValue:`Refresh`})]}),columns:[{key:`name`,header:u(`integrations.adoptColName`,{defaultValue:`Name`}),headerClassName:`w-[55%]`,cell:e=>c($,{candidate:e,expandable:!re,expanded:m.has(e.childNativeId),onToggleExpand:()=>W(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=le(e.type),n=t.icon;return r(`span`,{className:`inline-flex items-center gap-1.5 text-[10px] text-foreground-subtle`,children:[c(n,{className:`h-3.5 w-3.5 shrink-0`}),t.label]})}},{key:`select`,header:``,headerClassName:`w-[15%] text-right`,cellClassName:`text-right`,cell:e=>c(`div`,{className:`flex items-center justify-end`,children:c(`button`,{onClick:()=>U(e),disabled:e.alreadyAdopted,"aria-label":f.has(e.childNativeId)?`Deselect`:`Select`,className:`inline-flex h-5 w-5 items-center justify-center rounded border ${f.has(e.childNativeId)?`border-primary bg-primary`:`border-border`} ${e.alreadyAdopted?`cursor-not-allowed opacity-50`:``}`,children:f.has(e.childNativeId)&&c(ge,{className:`h-3 w-3 text-primary-foreground`})})})}],isExpanded:e=>!re&&m.has(e.childNativeId),renderExpanded:re?void 0:e=>c(He,{candidate:e,hiddenChildIds:_.get(e.childNativeId)?.hiddenChildIds??new Set,onToggleChildHidden:t=>ce(e.childNativeId,t)}),rowClassName:e=>e.alreadyAdopted?`opacity-60`:f.has(e.childNativeId)?`bg-primary/5`:``})})]}),y&&c(`div`,{className:`border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0`,children:r(`div`,{className:`flex items-start gap-2`,children:[c(q,{className:`h-3.5 w-3.5 text-destructive mt-0.5 shrink-0`}),c(`p`,{className:`text-[11px] text-destructive`,children:y})]})}),H!==null&&c(Fe,{addonId:n,integrationId:i,jobId:H,onFinished:fe}),r(`div`,{className:`flex items-center justify-between border-t border-border px-5 py-3 shrink-0`,children:[c(`div`,{}),r(`div`,{className:`flex items-center gap-2`,children:[c(`button`,{onClick:a,className:`rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors`,children:u(`integrations.cancel`,{defaultValue:`Cancel`})}),r(`button`,{onClick:_e?a:ue,disabled:!_e&&(he===0||V.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:[V.isPending&&c(x,{className:`h-3.5 w-3.5 animate-spin`}),_e?u(`integrations.close`,{defaultValue:`Close`}):u(`integrations.addSelected`,{defaultValue:`Add selected`}),!_e&&he>0?` (${he})`:``]})]})]})]})]})}function Ve({filters:e,activeFilter:t,onSelect:n}){return c(`div`,{role:`tablist`,"aria-label":`Discovery granularity`,className:`inline-flex shrink-0 self-start rounded-lg border border-border bg-surface p-0.5`,children:e.map(e=>{let r=e.id===t;return c(`button`,{type:`button`,role:`tab`,"aria-selected":r,onClick:()=>n(e.id),className:`rounded-md px-3 py-1 text-xs font-medium transition-colors ${r?`bg-primary text-primary-foreground shadow-sm`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:e.label},e.id)})})}function $({candidate:e,expandable:t,expanded:n,onToggleExpand:i,adoptedLabel:a}){let o=(e.children??[]).length;return r(`div`,{className:`flex items-center gap-2.5 min-w-0`,children:[t&&o>0?r(`button`,{type:`button`,onClick:i,"aria-label":n?`Collapse`:`Expand`,"aria-expanded":n,className:`flex h-5 flex-shrink-0 items-center justify-center gap-0.5 rounded px-0.5 text-[10px] text-foreground-subtle transition-colors hover:bg-surface-hover hover:text-foreground`,children:[c(n?d:f,{className:`h-3.5 w-3.5`}),o]}):c(`span`,{className:`flex h-5 w-5 flex-shrink-0 items-center justify-center text-foreground-subtle/40`,children:`—`}),c(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),e.alreadyAdopted&&c(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-[9px] font-medium text-success shrink-0`,children:a})]})}function He({candidate:e,hiddenChildIds:t,onToggleChildHidden:n}){let i=e.children??[];return i.length===0?null:c(`div`,{className:`space-y-1 py-1`,children:i.map(e=>{let i=t.has(e.childNativeId),a=e.capabilities??[];return r(`div`,{className:`flex items-center gap-2 rounded px-2 py-1 ${i?`opacity-50`:``}`,children:[c(`span`,{className:`text-[11px] text-foreground truncate flex-1 min-w-0`,children:e.name}),a.length>0&&c(`span`,{className:`text-[9px] text-foreground-subtle truncate`,children:a.join(`, `)}),c(`button`,{onClick:()=>n(e.childNativeId),"aria-label":i?`Show child`:`Hide child`,title:i?`Show after adopt`:`Hide after adopt`,className:`flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0`,children:c(i?p:F,{className:`h-3 w-3`})})]},e.childNativeId)})})}n();function Ue(e){let t=[];for(let n of e){if(n.type===`group`){t.push(...Ue(n.fields));continue}`key`in n&&typeof n.key==`string`&&t.push(n.key)}return t}function We(e,t){if(!e)return{};let n=new Set(e.sections.flatMap(e=>Ue(e.fields))),r={};for(let e of n)Object.prototype.hasOwnProperty.call(t,e)&&(r[e]=t[e]);return r}function Ge(e){return{...e.tabs?{tabs:e.tabs}:{},sections:e.sections.map(e=>({...e,fields:e.fields.map(e=>{if(`value`in e){let{value:t,...n}=e;return n}return e})}))}}function Ke({integrationId:e,addonId:t,name:n,kind:a,mode:s,brokerKind:l,canTest:u=!1,trpc:d,onClose:f}){let{t:p}=ye(),m=o(),{data:h,isLoading:g}=I({id:e},{enabled:s===`account`||s===`broker`}),_=i(()=>{let e=h?.brokerId;return typeof e==`string`?e:null},[h]),{data:v,isLoading:y}=P({addonId:t,nodeId:`hub`},{enabled:s===`account`}),b=i(()=>v?Ge(v):null,[v]),S=W(),C=(t,n)=>{S.mutate({id:e,settings:t,...n?{secretKeys:[...n]}:{}},{onSuccess:()=>{m.invalidateQueries(),f()}})};return c(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4`,onClick:f,children:r(`div`,{className:`max-h-[85vh] w-full max-w-lg overflow-y-auto rounded-xl border border-border bg-surface p-5 shadow-xl`,onClick:e=>e.stopPropagation(),children:[r(`div`,{className:`mb-3 flex items-center justify-between`,children:[r(`h2`,{className:`text-sm font-semibold text-foreground`,children:[p(`integrations.editConfig`,{defaultValue:`Edit configuration`}),` — `,n]}),c(`button`,{onClick:f,className:`rounded-md p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":p(`common.close`,{defaultValue:`Close`}),children:c(me,{className:`h-4 w-4`})})]}),s===`broker`?l?r(`div`,{className:`space-y-3`,children:[c(`p`,{className:`text-[11px] text-foreground-subtle`,children:p(`integrations.relinkBrokerHelp`,{defaultValue:`Choose the broker this integration connects through. Picking a different broker re-points it and restarts the addon.`})}),_&&r(`p`,{className:`text-[11px] text-foreground`,children:[p(`integrations.currentBroker`,{defaultValue:`Current broker`}),`:`,` `,c(`span`,{className:`font-mono text-foreground-subtle`,children:_})]}),S.isPending?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[c(x,{className:`h-3 w-3 animate-spin`}),p(`integrations.saving`,{defaultValue:`Saving…`})]}):c(De,{kind:l,onResolved:e=>{C({brokerId:e})},onBack:f}),S.isError&&c(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.relinkFailed`,{defaultValue:`Failed to update broker link.`})})]}):c(`p`,{className:`text-[11px] text-danger`,children:p(`integrations.noBrokerKind`,{defaultValue:`This integration declares device-adoption but its addon manifest has no brokerKind.`})}):s===`account`?g||y?r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[c(x,{className:`h-3 w-3 animate-spin`}),p(`integrations.loading`,{defaultValue:`Loading…`})]}):c(J,{addonId:t,configSchema:b,canTest:u,initialName:n,initialConfig:We(b,h??{}),submitLabel:p(`integrations.save`,{defaultValue:`Save`}),hideName:!0,onSave:({config:e,secretKeys:t})=>C(e,t),onBack:f}):c(G,{trpc:d,addonId:t,nodeId:`hub`,title:n})]})})}function qe(e){return e==null?!1:e.sections.some(e=>e.fields.length>0)}n();function Je(){let{t}=ye(),{integrationId:n}=be(),d=o(),f=we(),[p,h]=Ce(),v=u(),[b,S]=s(!1),[E,D]=s(!1),[j,ee]=s(!1),[te,F]=s(!1),[I,L]=s(!1),{data:B,isLoading:oe}=O({id:n??``},{enabled:!!n}),{data:se}=P({addonId:B?.addonId??``,nodeId:`hub`},{enabled:!!B?.addonId}),{data:U,isSuccess:W}=g(),G=i(()=>{let e=B?.addonId;return!e||!W?null:(U??[]).find(t=>t.addonId===e)?.kind===`device-adoption`?`device-adoption`:`device-provider`},[U,B?.addonId,W]),{data:le}=k({}),de=i(()=>(le?.providers??[]).some(e=>e.addonId===B?.addonId),[le,B?.addonId]),K=G!==null,ge=B?.info?.fixed===!0,ve=K?G===`device-adoption`?t(`integrations.adoptDevices`,{defaultValue:`Adopt devices`}):t(`integrations.addDevice`):t(`integrations.addDeviceLoading`,{defaultValue:`Loading…`}),xe=i(()=>{let e=B?.addonId;return!e||!W?null:(U??[]).find(t=>t.addonId===e)?.brokerKind??null},[U,B?.addonId,W]),Se=i(()=>{let e=B?.addonId;return!e||!W?!1:(U??[]).find(t=>t.addonId===e)?.canTest===!0},[U,B?.addonId,W]),J=i(()=>{let e=B?.addonId;return!e||!W?null:(U??[]).find(t=>t.addonId===e)?.mode??null},[U,B?.addonId,W]);l(()=>{p.get(`add`)===`1`&&K&&(S(!0),h(e=>{let t=new URLSearchParams(e);return t.delete(`add`),t},{replace:!0}))},[p,K,h]);let De=se!=null&&Array.isArray(se.sections)&&se.sections.some(e=>e.fields.length>0),{data:Ae}=R({addonId:B?.addonId??``,nodeId:`hub`},{enabled:!!B?.addonId&&J!==`account`}),je=J!==null&&J!==`account`&&qe(Ae),Me=i(()=>B?.addonId?[B.addonId]:[],[B?.addonId]),{data:Ne}=fe({projection:`slim`},{refetchInterval:3e4}),Y=[[`integrations`,`get`],{input:{id:n??``},type:`query`}],X=ae({onMutate:async e=>{await d.cancelQueries({queryKey:Y});let t=d.getQueryData(Y);return t!=null&&d.setQueryData(Y,{...t,enabled:e.enabled}),{previous:t}},onError:(e,t,n)=>{let r=n;r?.previous!=null&&d.setQueryData(Y,r.previous)},onSettled:()=>{d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Z=re({onSuccess:()=>{d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]}),F(!1),f(`/integrations`)}}),Fe=V({onSuccess:()=>{d.invalidateQueries({queryKey:[[`integrations`]]}),d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Ie=z({onSuccess:()=>{d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Le=w({onSuccess:()=>{d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Re=_({onSuccess:()=>{d.invalidateQueries({queryKey:[[`deviceManager`]]})}}),Q=i(()=>Ne??[],[Ne]),ze=i(()=>{let e=new Map;for(let t of Q)e.set(t.id,{id:t.id,name:t.name??t.stableId??`#${String(t.id)}`});return e},[Q]),Ve=e(e=>ze.get(e)??null,[ze]),{data:$}=pe(void 0),He=i(()=>ue($),[$]),Ue=e(e=>f(`/devices/${String(e)}`),[f]),We=i(()=>{let e=B?.id;return e?Q.filter(t=>{let n=He(t);return n.kind===`resolved`&&n.integration.id===e}):[]},[Q,B?.id,He]),Ge=i(()=>$===void 0?null:ne(We).length,[$,We])??`…`;return oe?r(`div`,{className:`p-4`,children:[c(`div`,{className:`h-16 rounded-lg bg-surface animate-pulse mb-4`}),c(`div`,{className:`h-40 rounded-lg bg-surface animate-pulse`})]}):B?r(`div`,{className:`p-4 space-y-4 overflow-x-hidden`,children:[c(C,{items:[{label:`Integrations`,onClick:()=>f(`/integrations`)},{label:B.name}]}),r(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[r(`div`,{className:`flex items-center gap-3 min-w-0`,children:[c(Ye,{addonId:B.addonId}),r(`div`,{className:`min-w-0`,children:[c(`h1`,{className:`text-lg font-semibold text-foreground truncate`,children:B.name}),r(`p`,{className:`text-[11px] text-foreground-subtle mt-0.5 truncate`,children:[B.addonId,` · `,Ge,` `,t(`integrations.devices`)]})]})]}),r(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[de&&r(`button`,{onClick:()=>D(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:`Scan the network for devices (incl. a different subnet)`,children:[c(M,{className:`h-3.5 w-3.5`}),`Scan network`]}),!ge&&r(`button`,{onClick:()=>S(!0),disabled:!K,className:`flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50 disabled:cursor-not-allowed`,title:ve,children:[c(he,{className:`h-3.5 w-3.5`}),ve]}),r(`div`,{className:`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 transition-colors ${X.isPending?`opacity-60`:``} ${B.enabled?`border-success/30 bg-success/5`:`border-border bg-surface`}`,title:t(`integrations.toggleHint`,{defaultValue:`Click to toggle`}),children:[c(A,{checked:B.enabled,onCheckedChange:e=>X.mutate({id:n,enabled:e}),disabled:X.isPending,"aria-label":B.enabled?`Disable integration`:`Enable integration`}),c(`span`,{className:`text-[11px] font-medium ${B.enabled?`text-success`:`text-foreground-subtle`}`,children:B.enabled?`Enabled`:`Disabled`}),X.isPending&&c(x,{className:`h-3 w-3 animate-spin text-foreground-subtle`})]}),J!==`standalone`&&(De||G===`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:[c(ce,{className:`h-3 w-3`}),t(`integrations.config`)]}),r(`button`,{onClick:()=>L(!0),className:`flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:t(`integrations.logs`,{defaultValue:`View logs`}),children:[c(H,{className:`h-3 w-3`}),t(`integrations.logs`,{defaultValue:`Logs`})]}),c(y,{label:`Restart`,icon:ie,title:`Restart "${B.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:Fe.isPending,action:()=>Fe.mutateAsync({addonId:B.addonId})}),!ge&&r(`button`,{onClick:()=>F(!0),className:`flex items-center gap-1.5 rounded-lg border border-danger bg-danger/10 px-3 py-1.5 text-[11px] font-medium text-danger hover:bg-danger hover:text-background transition-colors`,title:t(`integrations.delete`,{defaultValue:`Delete integration`}),children:[c(m,{className:`h-3 w-3`}),t(`integrations.delete`,{defaultValue:`Delete`})]})]})]}),je&&c(Te,{nodeId:null,addonIds:Me,level:`global`,surface:`integration`,title:t(`integrations.settings`,{defaultValue:`Settings`})}),c(T,{context:`integration-detail`,devices:Q,trpc:v.trpcClient,integrationOf:He,forceIntegrationId:B.id,urlScope:`root`,lsKey:`integration-detail:${B.addonId}`,resolveIntegrationIcon:Ee,resolveParent:Ve,onNavigate:Ue,batchActions:{remove:Ie.mutate,disable:Le.mutate,enable:Re.mutate},...ge?{}:{onDeleteDevice:e=>Ie.mutate({deviceId:e.id})}}),b&&n&&G===`device-adoption`&&c(Be,{addonId:B.addonId,integrationId:n,onClose:()=>S(!1)}),b&&n&&G===`device-provider`&&c(Pe,{open:b,integrationId:n,addonId:B.addonId,onClose:()=>S(!1)}),E&&B&&c(Oe,{open:E,scope:{addonId:B.addonId,label:B.name},onClose:()=>D(!1)}),j&&n&&G!==null&&J!==null&&c(Ke,{integrationId:n,addonId:B.addonId,name:B.name,kind:G,mode:J,brokerKind:xe,canTest:Se,trpc:v.trpcClient,onClose:()=>ee(!1)}),I&&c(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6`,onClick:()=>L(!1),children:r(`div`,{className:`flex flex-col rounded-xl border border-border bg-surface shadow-xl w-full max-w-5xl h-[80vh]`,onClick:e=>e.stopPropagation(),children:[r(`div`,{className:`flex items-center justify-between border-b border-border px-4 py-2.5`,children:[r(`div`,{className:`flex items-center gap-2 min-w-0`,children:[c(H,{className:`h-4 w-4 text-primary shrink-0`}),c(`h2`,{className:`text-sm font-semibold text-foreground truncate`,children:B.name}),r(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate`,children:[B.addonId,n?` · ${n}`:``]})]}),c(`button`,{onClick:()=>L(!1),className:`flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,"aria-label":`Close logs`,children:c(me,{className:`h-4 w-4`})})]}),c(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:c(N,{addonId:B.addonId,limit:200,maxHeight:`max-h-full`,showScope:!1,className:`h-full border-0 rounded-none`})})]})}),te&&c(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60`,onClick:()=>!Z.isPending&&F(!1),children:r(`div`,{className:`rounded-xl border border-border bg-background p-5 shadow-2xl w-96 space-y-3`,onClick:e=>e.stopPropagation(),children:[r(`div`,{className:`flex items-start gap-3`,children:[c(`div`,{className:`flex h-9 w-9 items-center justify-center rounded-lg bg-danger/10 shrink-0`,children:c(q,{className:`h-4 w-4 text-danger`})}),r(`div`,{className:`min-w-0`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`integrations.deleteTitle`,{defaultValue:`Delete integration?`})}),c(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:t(`integrations.deleteWarning`,{defaultValue:`This removes the integration "{{name}}" and its {{count}} device(s). The addon will restart. This cannot be undone.`,name:B.name,count:Ge})})]})]}),Z.error&&c(`div`,{className:`rounded-lg border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:Z.error instanceof Error?Z.error.message:String(Z.error)}),r(`div`,{className:`flex items-center justify-end gap-2 pt-1`,children:[c(`button`,{onClick:()=>F(!1),disabled:Z.isPending,className:`rounded-lg border border-border px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed`,children:t(`integrations.cancel`,{defaultValue:`Cancel`})}),c(`button`,{onClick:()=>Z.mutate({id:n}),disabled:Z.isPending,className:`inline-flex items-center gap-1.5 rounded-lg bg-danger px-3 py-1.5 text-[11px] font-medium text-background hover:bg-danger/90 transition-colors disabled:opacity-60 disabled:cursor-not-allowed`,children:Z.isPending?r(a,{children:[c(x,{className:`h-3 w-3 animate-spin`}),t(`integrations.deleting`,{defaultValue:`Deleting…`})]}):r(a,{children:[c(m,{className:`h-3 w-3`}),t(`integrations.confirmDelete`,{defaultValue:`Delete integration`})]})})]})]})})]}):r(`div`,{className:`flex flex-col items-center justify-center py-20 px-6 text-center gap-4`,children:[c(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-full bg-foreground-subtle/10`,children:c(ke,{className:`h-6 w-6 text-foreground-subtle`})}),r(`div`,{className:`space-y-1 max-w-sm`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`integrations.integrationNotFound`,{defaultValue:`Integration not found`})}),c(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`integrations.integrationNotFoundHint`,{defaultValue:`The integration "{{id}}" does not exist. It may have been deleted, or the URL may be wrong.`,id:n??``})})]}),r(`button`,{onClick:()=>f(`/integrations`),className:`inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors`,children:[c(_e,{className:`h-3 w-3`}),t(`integrations.backToList`,{defaultValue:`Back to integrations`})]})]})}function Ye({addonId:e}){let t=Se(e),[n,r]=s(!1);return!t||n?null:c(`img`,{src:t,alt:``,className:`h-8 w-8 rounded-lg shrink-0`,onError:()=>r(!0)})}export{Je as IntegrationDetailPage};
@@ -1 +0,0 @@
1
- import{D as e,K as t,L as n,Q as r,S as i,W as a,b as o,o as s,q as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{B as d,ct as f}from"./player-overlays-D4lg_avJ.js";import{An as p,Dt as m,Fd as h,Fr as g,In as _,Ld as v,Mt as y,Nn as ee,Pn as b,Sd as x,_t as S,gt as C,hd as te,kf as w,kr as T,ld as ne,tr as re,xd as E,zu as D}from"./src-DzkLcOyh.js";import{t as O}from"./settings-2-DVqttbaa.js";import{K as k,W as A,Y as j,a as M,c as N,d as P,f as F,l as I,p as L,u as R}from"./index-CpGfiJoj.js";import{t as z}from"./AdminPage-BSFohA3i.js";import{t as B}from"./NodeAddonsSettingsPanel-DhbzB3yG.js";r();var V=[[[`addons`,`listCapabilityProviders`]],[[`addons`,`list`]]],H=`text-[10px]`;function U({isActive:e}){return l(re,{variant:e?`success`:`default`,className:H,children:e?`Enabled`:`Disabled`})}function W({capName:e,addonId:t,isActive:n}){let r=s(),a=g({onSuccess:()=>{for(let e of V)r.invalidateQueries({queryKey:e})}}),o=a.isPending;return i(_,{size:`sm`,variant:n?`secondary`:`primary`,disabled:o,onClick:()=>a.mutate({capName:e,addonId:t,enabled:!n}),children:[o?l(h,{className:`h-3 w-3 animate-spin`}):l(n?f:x,{className:`h-3 w-3`}),n?`Disable`:`Enable`]})}function G({addonId:e,displayName:t}){let n=s(),r=T({onSuccess:()=>{for(let e of V)n.invalidateQueries({queryKey:e})}});return l(m,{label:`Restart`,icon:te,size:`sm`,title:`Restart "${t}"?`,description:`Restarting the addon bounces its subprocess — the provider will briefly drop and reconnect automatically.`,confirmLabel:`Restart`,triggerVariant:`ghost`,confirmVariant:`danger`,disabled:r.isPending,action:()=>r.mutateAsync({addonId:e})})}var K=600,q=e(null);function J({id:e,title:r,icon:a,actions:s,framed:c=!1,children:u}){let f=n(q),p=t(null),m=`integration-section-${e}`;Y(p,f,e);let h=i(o,{children:[f===null?null:l(k,{to:f.sectionHref(e),"aria-label":`Link to ${r}`,title:`Link to ${r}`,className:`rounded p-0.5 text-foreground-subtle/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`,children:l(v,{className:`h-3 w-3`,"aria-hidden":!0})}),s]});return c?l(`div`,{ref:p,className:`scroll-mt-4`,children:l(y,{headingId:m,title:r,icon:a,actions:h,children:u})}):i(`section`,{ref:p,"aria-labelledby":m,className:`scroll-mt-4 space-y-2`,children:[i(`header`,{className:`flex min-h-7 flex-wrap items-center gap-2 px-0.5`,children:[a!==void 0&&l(a,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`,"aria-hidden":!0}),l(`h2`,{id:m,className:`${d} min-w-0 flex-1`,children:r}),h]}),u]})}function Y(e,t,n){let r=t?.requestedSection===n,i=t?.integrationId;u(()=>{if(!r)return;let t=()=>e.current?.scrollIntoView?.({block:`start`});t();let n=!1,i=()=>{n=!0},a=[`wheel`,`touchmove`,`keydown`];for(let e of a)window.addEventListener(e,i,{once:!0,passive:!0});let o=window.setTimeout(()=>{n||t()},K);return()=>{window.clearTimeout(o);for(let e of a)window.removeEventListener(e,i)}},[r,i,e])}r();var X=`max-h-72`;function ie({addonId:e,displayName:t,capName:n,isActive:r,badges:a,primaryAction:o,error:s=null,lead:c,panels:u=[]}){let d=u.filter(e=>e.placement!==`end`),f=u.filter(e=>e.placement===`end`);return i(`div`,{className:`flex flex-col gap-4`,children:[l(ae,{addonId:e,displayName:t,capName:n,isActive:r,badges:a,primaryAction:o}),s!==null&&l(ee,{message:s}),c,l(Z,{panels:d}),l(J,{id:R,title:`Settings`,icon:O,children:l(B,{nodeId:`hub`,addonIds:[e],level:`global`,capability:n})}),l(se,{addonId:e}),l(Z,{panels:f})]})}function Z({panels:e}){return l(o,{children:e.map(e=>l(J,{id:e.id,title:e.title,icon:e.icon,children:e.content},e.id))})}function ae({addonId:e,displayName:t,capName:n,isActive:r,badges:a,primaryAction:o}){return i(`div`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border bg-surface px-2 py-1.5 sm:px-3`,"data-testid":`integration-status-strip`,children:[i(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1.5`,children:[l(U,{isActive:r}),a,l(`span`,{className:`break-all font-mono text-[11px] text-foreground-subtle`,children:e})]}),i(`div`,{className:`flex flex-wrap items-center justify-end gap-1`,children:[o,l(W,{capName:n,addonId:e,isActive:r}),l(G,{addonId:e,displayName:t})]})]})}var oe=[{kind:`logs`,label:`Logs`,icon:ne},{kind:`events`,label:`Events`,icon:w}];function se({addonId:e}){let[t,n]=c(`logs`);return l(J,{id:M,title:`Activity`,framed:!0,actions:l(`div`,{role:`group`,"aria-label":`Activity stream`,className:`flex items-center gap-1`,children:oe.map(({kind:e,label:r,icon:a})=>i(`button`,{type:`button`,"aria-pressed":t===e,onClick:()=>n(e),className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors ${t===e?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[l(a,{className:`h-3 w-3`,"aria-hidden":!0}),r]},e))}),children:t===`logs`?l(S,{addonId:e,maxHeight:X,showFilters:!1}):l(C,{addonId:e,category:`addon.*`,maxHeight:X})})}r();function ce(e){let{ids:t,answered:n,legacyGroupParam:r=null,groupFirst:i}=e,[o]=j(),s=o.get(N),c=r===null?null:o.get(r),l=o.get(I),u=a(()=>F({ids:t,requested:s,answered:n,legacyGroup:c,...i===void 0?{}:{groupFirst:i}}),[t,s,n,c,i]),d=a(()=>(e,t)=>`?${L(o,e,r,t??null).toString()}`,[o,r]);return{...u,requestedSection:l,hrefFor:d}}r();var le={md:{tile:`h-10 w-10 rounded-lg`,img:`h-7 w-7 rounded-md p-1`,fallback:`h-5 w-5`},sm:{tile:`h-5 w-5 rounded`,img:`h-5 w-5 rounded p-0.5`,fallback:`h-3.5 w-3.5`}};function ue({addonId:e,fallback:t,tileClassName:n,size:r=`md`}){let[i,a]=c(!1),o=A(e),s=le[r];return l(`div`,{className:`${s.tile} flex items-center justify-center shrink-0 ${n}`,children:i||!o?l(t,{className:s.fallback,"aria-hidden":!0}):l(`img`,{src:o,alt:``,className:`${s.img} bg-white ring-1 ring-black/5`,onError:()=>a(!0)})})}var Q=`inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-full border py-1 pl-1 pr-2.5 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`,de=`border-primary bg-primary/10 text-primary font-medium`,fe=`border-border bg-surface text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,pe={ok:`bg-success`,off:`bg-foreground-subtle/60`,error:`bg-danger`,unknown:`border border-foreground-subtle bg-transparent`};function me({label:e,groups:t,selectedId:n,hrefFor:r}){let a=t.length>1;return l(`nav`,{"aria-label":e,className:a?`flex flex-col gap-2 sm:grid sm:grid-cols-[max-content_minmax(0,1fr)] sm:items-start sm:gap-x-3`:`flex flex-col`,children:t.map(e=>i(`div`,{role:`group`,"aria-label":e.label,className:a?`flex min-w-0 flex-col gap-1 sm:col-span-2 sm:grid sm:grid-cols-subgrid sm:items-start`:`min-w-0`,children:[a&&l(`span`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle sm:pt-2`,children:e.label}),i(`div`,{className:`flex min-w-0 flex-wrap items-center gap-1.5`,children:[e.entries.map(e=>l(he,{entry:e,current:e.id===n,href:r(e.id)},e.id)),e.install&&i(k,{to:P(e.install.capability),className:`${Q} border-dashed border-border pl-2 text-foreground-subtle hover:border-primary/50 hover:text-foreground`,children:[l(E,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":!0}),l(`span`,{className:`truncate`,children:e.install.label})]})]})]},e.id))})}function he({entry:e,current:t,href:n}){let r=e.state===`ok`;return i(k,{to:n,"aria-current":t?`true`:void 0,className:`${Q} ${t?de:fe}`,"data-testid":`integration-pill-${e.id}`,children:[l(ue,{addonId:e.id,fallback:e.fallbackIcon,tileClassName:``,size:`sm`}),l(`span`,{className:`truncate`,children:e.name}),l(`span`,{className:`h-1.5 w-1.5 shrink-0 rounded-full ${pe[e.state]}`,"aria-hidden":!0}),l(`span`,{className:r?`sr-only`:`shrink-0 text-[10px] font-normal text-foreground-subtle`,children:e.stateLabel})]})}r();function ge({icon:e,title:t,subtitle:n,groups:r,isLoading:s,emptyTitle:c,emptyDescription:u,legacyGroupParam:d,trailing:f}){let m=a(()=>r.flatMap(e=>e.entries),[r]),h=a(()=>m.map(e=>e.id),[m]),g=a(()=>{let e={};for(let t of r){let n=t.entries[0];n!==void 0&&(e[t.id]=n.id)}return e},[r]),_=ce({ids:h,answered:!s,legacyGroupParam:d??null,groupFirst:g}),v=m.find(e=>e.id===_.selectedId)??null,y=a(()=>v===null?null:{integrationId:v.id,requestedSection:_.requestedSection,sectionHref:e=>_.hrefFor(v.id,e)},[v,_]);return l(z,{icon:e,title:t,subtitle:n,nav:s?null:l(me,{label:`${t} integrations`,groups:r,selectedId:_.selectedId,hrefFor:e=>_.hrefFor(e)}),children:s?l(p,{children:l(`div`,{className:`p-6 text-sm text-foreground-subtle`,children:`Loading…`})}):i(o,{children:[_.staleId!==null&&l(_e,{staleId:_.staleId,shownName:v?.name??null}),v!==null&&y!==null?l(q.Provider,{value:y,children:l(`div`,{role:`region`,"aria-label":v.name,"data-testid":`integration-body`,children:v.render()},v.id)}):l($,{groups:r,title:c,description:u}),f]})})}function $({groups:e,title:t,description:n}){let r=e.find(e=>e.install!==void 0)?.install;return l(p,{children:l(b,{title:t,description:n,action:r?l(k,{to:P(r.capability),children:i(_,{variant:`primary`,size:`sm`,children:[l(E,{className:`mr-1 h-3.5 w-3.5`}),r.label]})}):void 0})})}function _e({staleId:e,shownName:t}){return i(`div`,{role:`status`,className:`flex items-start gap-2 rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-[11px] text-foreground-subtle`,children:[l(D,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`,"aria-hidden":!0}),i(`span`,{children:[`This link named `,l(`span`,{className:`font-mono text-foreground`,children:e}),`, which is not installed here.`,t!==null&&i(o,{children:[` `,`Showing `,l(`span`,{className:`font-medium text-foreground`,children:t}),` instead.`]})]})]})}export{ie as n,H as r,ge as t};
@@ -1 +0,0 @@
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,vt as c}from"./player-overlays-D4lg_avJ.js";import{Cd as l,Cn as u,Cr as d,Dn as f,Du as p,En as m,Fd as h,G as g,In as _,Md as v,Nn as y,Pi as ee,Sn as b,W as x,ad as S,ai as C,bd as w,ci as T,di as E,fi as te,gd as D,ii as ne,li as re,qn as ie,si as ae,tr as O,ui as k,wn as A,xd as j,xn as M}from"./src-DzkLcOyh.js";import{Nt as N,Sr as P,tr as F}from"./client-BqN2lVYf.js";import{N as I,q as L}from"./index-CpGfiJoj.js";import{t as R}from"./BrokerForm-vK7o_-sd.js";import{n as z,r as B,t as V}from"./IntegrationHub-C_kwGzUm.js";var H=c(`monitor-smartphone`,[[`path`,{d:`M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8`,key:`10dyio`}],[`path`,{d:`M10 19v-3.96 3.15`,key:`1irgej`}],[`path`,{d:`M7 19h5`,key:`qswx4l`}],[`rect`,{width:`6`,height:`10`,x:`16`,y:`12`,rx:`2`,key:`1egngj`}]]);e();var U=`kind`,W=`name`,G=`restore`,K=`restoreId`;function q(e){return{sections:[{id:`broker-identity`,title:`Broker`,columns:1,fields:[{type:`select`,key:U,label:`Kind`,options:e.map(e=>({value:e.key,label:e.label})),disabled:e.length<=1},{type:`text`,key:W,label:`Name`,placeholder:`My Home Assistant`,required:!0},{type:`boolean`,key:G,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:K,label:`Original broker id`,placeholder:`ha_004`,required:!0,showWhen:{field:G,equals:!0}}]}]}}function oe(e){let t=t=>{let n=e[t];return typeof n==`string`?n.trim():``},n=t(U);if(n===``)return{ok:!1,problem:`Pick a kind.`};let r=t(W);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(K);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 se={"home-assistant":`Home Assistant`,mqtt:`MQTT`};function J(e){return se[e]??e}function ce(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.addonId==`string`&&Array.isArray(e.kinds)):[]}var le={connected:`success`,connecting:`warning`,disconnected:`default`,"auth-failed":`danger`,unreachable:`danger`,error:`danger`};function ue({status:e}){return o(O,{variant:le[e],className:`text-[10px]`,children:e})}function de(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(M,{open:!0,onOpenChange:e=>!e&&r(),children:t(u,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[t(m,{children:[o(f,{children:e}),n&&o(A,{children:n})]}),o(b,{className:`space-y-3 pr-1`,children:i})]})})}function fe({kinds:e,onClose:r,onDone:s}){let c=i(),l=n(()=>q(e.map(e=>({key:X(e),label:e.label}))),[e]),[u,d]=a(()=>({[U]:X(e[0]),[W]:``,[G]:!1,[K]:``})),[f,p]=a(null),m=e.find(e=>X(e)===u.kind)??e[0],h=m?.kind??``,g=m?.addonId,_=ne({onSuccess:()=>{c.invalidateQueries({queryKey:[[`broker`,`list`]]}),s()}}),v=e=>{let t=oe(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(y,{message:f}),_.isError&&o(y,{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 pe({broker:e,onClose:r,onDone:a}){let s=i(),c=C({id:e.id,addonId:e.addonId}),l=E({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(h,{className:`h-3.5 w-3.5 animate-spin`}),` Loading settings…`]}):c.isError?t(`div`,{className:`space-y-3`,children:[o(y,{message:`Failed to load settings: ${c.error instanceof Error?c.error.message:`Unknown error`}`}),o(`div`,{className:`flex justify-end`,children:o(_,{variant:`outline`,size:`sm`,onClick:r,children:`Close`})})]}):t(`div`,{className:`space-y-3`,children:[l.isError&&o(y,{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 me({broker:e,onEdit:n}){let r=i(),c=ie(),[u,d]=a(null),f=te({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)})}),m=k({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`})&&m.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(ue,{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(_,{variant:`outline`,size:`sm`,onClick:()=>f.mutate({id:e.id,addonId:e.addonId}),disabled:f.isPending,title:`Test connection`,children:[f.isPending?o(h,{className:`h-3 w-3 animate-spin`}):o(p,{className:`h-3 w-3`}),`Test`]}),t(_,{variant:`outline`,size:`sm`,onClick:()=>n(e),title:`Edit`,children:[o(l,{className:`h-3 w-3`}),` Edit`]}),t(_,{variant:`outline`,size:`sm`,className:`border-danger/40 text-danger hover:bg-danger/10`,onClick:()=>{g()},disabled:m.isPending,title:`Delete`,children:[m.isPending?o(h,{className:`h-3 w-3 animate-spin`}):o(s,{className:`h-3 w-3`}),`Delete`]})]})})]})}function he({addonId:e}={}){let r=T({}),i=re(),s=n(()=>de(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 ce(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(_,{variant:`primary`,size:`sm`,onClick:()=>l(!0),disabled:f.length===0,title:f.length===0?`No broker providers available`:void 0,children:[o(j,{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(h,{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(me,{broker:e,onEdit:d},e.id))]})]})}),c&&o(fe,{kinds:f,onClose:()=>l(!1),onDone:()=>l(!1)}),u&&o(pe,{broker:u,onClose:()=>d(null),onDone:()=>d(null)})]})}function ge(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 _e(e){let t=e,n=t?.manifest;if(n?.id===void 0)return null;let r=(n.capabilities??[]).map(ge).filter(e=>e!==null);return{addonId:n.id,displayName:n.packageDisplayName??n.name??n.id,capNames:r,processState:t?.process?.state??null}}function ve(e,t){return Object.entries(e).filter(([,e])=>e===t).map(([e])=>e)}function ye(e,t){return t.find(t=>e.capNames.includes(t))??null}function Z(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 Q=1e4,be=[{kind:`device-export`,label:`Device export`,icon:S,installLabel:`Add export`},{kind:`email`,label:`Email`,icon:v,installLabel:`Add email provider`},{kind:`broker`,label:`Message brokers`,icon:D,installLabel:`Add broker addon`}];function $(){let e=d(void 0,{refetchInterval:Q}),i=L();return o(V,{icon:w,title:`Connectivity`,subtitle:`External systems this hub talks to — device exporters, email relays and message brokers.`,groups:n(()=>{let n=(e.data??[]).map(_e).filter(e=>e!==null);return be.map(e=>{let a=ve(N,e.kind),s=n.flatMap(n=>{let s=ye(n,a);if(s===null)return[];let c=Z(n.processState);return[{id:n.addonId,name:n.displayName,fallbackIcon:e.icon,state:c.state,stateLabel:c.label,render:()=>o(z,{addonId:n.addonId,displayName:n.displayName,capName:s,isActive:n.processState===`running`,badges:t(r,{children:[o(Se,{processState:n.processState}),o(Ce,{kind:e.kind,addonId:n.addonId})]}),lead:e.kind===`device-export`?o(g,{addonId:n.addonId}):void 0,panels:xe(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 xe(e,t,n){return e===`device-export`?[{id:`devices`,title:`Devices`,icon:H,placement:`end`,content:o(x,{addonId:t,onOpenDevice:n,showSetup:!1})}]:e===`broker`?[{id:`connections`,title:`Connections`,icon:D,content:o(he,{addonId:t})}]:[]}function Se({processState:e}){let{state:t,label:n}=Z(e);return o(O,{variant:t===`ok`?`success`:t===`error`?`danger`:`default`,className:`${B} capitalize`,children:n})}function Ce({kind:e,addonId:t}){return e===`broker`?o(we,{addonId:t}):e===`device-export`?o(Te,{addonId:t}):null}function we({addonId:e}){let{data:t}=ae({addonId:e},{refetchInterval:Q,retry:!1}),n=P.safeParse(t);if(!n.success)return null;let{brokerCount:r,connectedCount:i}=n.data;return o(O,{variant:`info`,className:B,children:`${r} connection${r===1?``:`s`}${i>0?` · ${i} connected`:``}`})}function Te({addonId:e}){let{data:t}=ee({addonId:e},{refetchInterval:Q,retry:!1}),n=F.safeParse(t);if(!n.success)return null;let{linkState:r,exposedDeviceCount:i}=n.data;return o(O,{variant:r===`linked`?`success`:r===`error`?`danger`:`default`,className:B,children:`${r} · ${i} exposed`})}export{$ as IntegrationsPage};