@camstack/addon-admin-ui 1.2.697 → 1.2.699

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 (108) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/assets/{AccessSection-DdGWzCNU.js → AccessSection-Cg9rzCY6.js} +1 -1
  3. package/dist/assets/Addons-qxSwlXcz.js +5 -0
  4. package/dist/assets/{AdminPage-CdTTxNI2.js → AdminPage-BrYobKfu.js} +1 -1
  5. package/dist/assets/{AdminSectionedPage-naipwiRu.js → AdminSectionedPage-DMt3db7_.js} +1 -1
  6. package/dist/assets/AiProfiles-DOg54XLu.js +3 -0
  7. package/dist/assets/Archive-CVAb7ii-.js +1 -0
  8. package/dist/assets/{BootstrapSettingsForm-DFMtetlU.js → BootstrapSettingsForm-X9cZi_Nt.js} +1 -1
  9. package/dist/assets/{Build-DxY2TX10.js → Build-DxgTHExF.js} +4 -4
  10. package/dist/assets/{Calendars-CP8C8VtZ.js → Calendars-D6WsgvTf.js} +1 -1
  11. package/dist/assets/Cluster-RtxW2bKJ.js +1 -0
  12. package/dist/assets/{CompositionBlockEditor-MQKfvO2_.js → CompositionBlockEditor-Cg3OItJ7.js} +2 -2
  13. package/dist/assets/CompositionEditorPage-Ber-Qx5p.js +1 -0
  14. package/dist/assets/Data-Cwpzr7cR.js +2 -0
  15. package/dist/assets/DeviceDetail-Folb0FGW.js +1 -0
  16. package/dist/assets/{Devices-utVd78jI.js → Devices-DMIjJ196.js} +1 -1
  17. package/dist/assets/{EmbedDevicePage-CB8RtuTi.js → EmbedDevicePage-Caafl7ZH.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-BR-eSBu0.js → EmbedPlayerPage-Bi76rC5b.js} +1 -1
  19. package/dist/assets/{History-tKHh0cHS.js → History-CP79jWzy.js} +1 -1
  20. package/dist/assets/Identity-HvzyOfT2.js +1 -0
  21. package/dist/assets/InstancesTable-fl42p6i3.js +1 -0
  22. package/dist/assets/IntegrationDetail-CMMEdEjA.js +1 -0
  23. package/dist/assets/{Integrations-BFnupnaS.js → Integrations-CYaklItX.js} +2 -2
  24. package/dist/assets/Integrations-hvwXjb_k.js +1 -0
  25. package/dist/assets/Library-Opn5-0Wj.js +1 -0
  26. package/dist/assets/Locations-Db8-OTso.js +3 -0
  27. package/dist/assets/{Logs-D72884eX.js → Logs-B9zTepXX.js} +1 -1
  28. package/dist/assets/{MaskShapeCanvas-FsP-Pqfm.js → MaskShapeCanvas-CeHsVkFB.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-DWnvsLfI.js → MotionZonesSettings-adkc7eLP.js} +1 -1
  30. package/dist/assets/{MyAccess-CaeqS22Q.js → MyAccess-BPDq5d45.js} +1 -1
  31. package/dist/assets/{Network-IA4ekRza.js → Network-jSuufX_m.js} +1 -1
  32. package/dist/assets/{NewExportModal-5HfHutIX.js → NewExportModal-BwmdfSbv.js} +1 -1
  33. package/dist/assets/NodeAddonsSettingsPanel-BcvIFJ-x.js +1 -0
  34. package/dist/assets/{Notifications-ClpQwHYS.js → Notifications-DUibmZHJ.js} +1 -1
  35. package/dist/assets/{PanelContent-CvEORG5m.js → PanelContent-BCIeD6_U.js} +2 -2
  36. package/dist/assets/{Pipeline-BsG-C_sg.js → Pipeline-BvgwYZ8u.js} +1 -1
  37. package/dist/assets/{PrivacyMaskSettings-DCyzjqzQ.js → PrivacyMaskSettings-zs9fc3hQ.js} +1 -1
  38. package/dist/assets/{SceneMonitorEditor-CV82fzoU.js → SceneMonitorEditor-C3LeCTYJ.js} +1 -1
  39. package/dist/assets/{SessionsList-PTKo0Lkj.js → SessionsList-CLCT23El.js} +2 -2
  40. package/dist/assets/{Showroom-BQd-Ik5x.js → Showroom-DrLRL9I1.js} +1 -1
  41. package/dist/assets/StorageLocationsTable-Bz9GAV5K.js +1 -0
  42. package/dist/assets/{System-mDTNPf2A.js → System-BbRrxjUU.js} +2 -2
  43. package/dist/assets/{TemplateEditorDialog-CEGwmxkN.js → TemplateEditorDialog-22h0K3yb.js} +1 -1
  44. package/dist/assets/{Terminal-f3U9kOJ9.js → Terminal-BTsnnLaP.js} +5 -5
  45. package/dist/assets/{TrainingProviders-RkzNtyQH.js → TrainingProviders-YTsR5lC5.js} +1 -1
  46. package/dist/assets/{Viewer-5BTY7nR7.js → Viewer-wJAA7rtL.js} +1 -1
  47. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bjw5Y-ao.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C29DsQaz.js} +1 -1
  48. package/dist/assets/{action-draft-ClaKheRp.js → action-draft-LMoJNqJ2.js} +1 -1
  49. package/dist/assets/{ai-page.helpers-UE-kLqk-.js → ai-page.helpers-MSr4oAOr.js} +1 -1
  50. package/dist/assets/{assignment-candidates-4DJypkPw.js → assignment-candidates-lemE0qmp.js} +1 -1
  51. package/dist/assets/{authed-media-HuCfJg8e.js → authed-media-CJkTsStS.js} +1 -1
  52. package/dist/assets/{board-model-BiC_AOnT.js → board-model-BjTxORes.js} +1 -1
  53. package/dist/assets/{camera-block-model-g3cq_EI_.js → camera-block-model-D98qHpXa.js} +1 -1
  54. package/dist/assets/client-DVowZZ0s.js +1122 -0
  55. package/dist/assets/{command-vocab-9mWzh5PF.js → command-vocab-BecctZqm.js} +1 -1
  56. package/dist/assets/{device-detail-YfGCWj8t.js → device-detail-D7Mllu4s.js} +1 -1
  57. package/dist/assets/{device-integration-icon-DM6LkNcP.js → device-integration-icon-BR10V6ne.js} +1 -1
  58. package/dist/assets/device-picker-model-DccEEZ6A.js +1 -0
  59. package/dist/assets/{dist-CVN4KkB9.js → dist-DO0_AccE.js} +1 -1
  60. package/dist/assets/dist-DhsssUoX.js +1122 -0
  61. package/dist/assets/{format-BFqaqsZF.js → format-D6kgFpER.js} +1 -1
  62. package/dist/assets/{hostInit-D0OCyJdS.js → hostInit-CdUb3qyd.js} +1 -1
  63. package/dist/assets/i18n-CQiAPXio.js +1 -0
  64. package/dist/assets/{icons-DWGskgV4.js → icons-S17PAUwl.js} +1 -1
  65. package/dist/assets/index-BFLHRK9f.js +6 -0
  66. package/dist/assets/index-CgTEWhcQ.css +2 -0
  67. package/dist/assets/{linked-devices-model-BzrCMmaN.js → linked-devices-model-E6YzvEnL.js} +1 -1
  68. package/dist/assets/{mf-entry-bootstrap-0-fadd666d.js → mf-entry-bootstrap-0-26099898.js} +2 -2
  69. package/dist/assets/mount-DccEEZ6A.js +1 -0
  70. package/dist/assets/{notification-rule-status-DUgKlnjE.js → notification-rule-status-Rco24I6e.js} +1 -1
  71. package/dist/assets/{player-overlays-BwkSi_4-.js → player-overlays-DNV0OF87.js} +1 -1
  72. package/dist/assets/remoteEntry-CLeDuWWL.js +1 -0
  73. package/dist/assets/src-Dv0B4lHJ.js +279 -0
  74. package/dist/assets/{sso-popup-Dgqs_a8a.js → sso-popup-F-KRTc0f.js} +1 -1
  75. package/dist/assets/{step-inspector-model-D61dFKRl.js → step-inspector-model-drjYN2J-.js} +1 -1
  76. package/dist/assets/{use-scenes-feed-BhsIhVzS.js → use-scenes-feed-jdmupAkZ.js} +1 -1
  77. package/dist/assets/{useAdminDeviceRemoval-5dMFC-df.js → useAdminDeviceRemoval-CB-W9jkR.js} +1 -1
  78. package/dist/assets/useEventInvalidation-DccEEZ6A.js +1 -0
  79. package/dist/assets/{useNodeUrlSelection-DOGBUYEz.js → useNodeUrlSelection-BfsFEu9Z.js} +1 -1
  80. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-IXviF-_2.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CSeKpPd2.js} +2 -2
  81. package/dist/index.html +9 -9
  82. package/dist/server/addon.js +300 -7
  83. package/package.json +2 -2
  84. package/dist/assets/Addons-B0bqL6tU.js +0 -5
  85. package/dist/assets/AiProfiles-DNb_fYYp.js +0 -3
  86. package/dist/assets/Archive-7CE6jZjq.js +0 -1
  87. package/dist/assets/Cluster-C4FhspzG.js +0 -1
  88. package/dist/assets/CompositionEditorPage-BTZJ1SGJ.js +0 -1
  89. package/dist/assets/Data-C6KNxbbA.js +0 -2
  90. package/dist/assets/DeviceDetail-Osm-Rh6F.js +0 -1
  91. package/dist/assets/Identity-6rJA2fNv.js +0 -1
  92. package/dist/assets/InstancesTable-Gj2icd8R.js +0 -1
  93. package/dist/assets/IntegrationDetail-C5mkMk4l.js +0 -1
  94. package/dist/assets/Integrations-DWhc4Sc8.js +0 -1
  95. package/dist/assets/Library-FLyCVVDD.js +0 -1
  96. package/dist/assets/Locations-D-ZRoAVT.js +0 -3
  97. package/dist/assets/NodeAddonsSettingsPanel-DEfnyzvR.js +0 -1
  98. package/dist/assets/StorageLocationsTable-CQpdu3Aj.js +0 -1
  99. package/dist/assets/client-jwdAAPeF.js +0 -1122
  100. package/dist/assets/device-picker-model-CS9GUXwM.js +0 -1
  101. package/dist/assets/dist-DkjIIXcA.js +0 -1122
  102. package/dist/assets/i18n-CZf--AlM.js +0 -1
  103. package/dist/assets/index-BAoWvnYw.js +0 -6
  104. package/dist/assets/index-Cdqk-EuE.css +0 -2
  105. package/dist/assets/mount-CS9GUXwM.js +0 -1
  106. package/dist/assets/remoteEntry-DmNGDfRG.js +0 -1
  107. package/dist/assets/src-CTVIVqdZ.js +0 -279
  108. package/dist/assets/useEventInvalidation-CS9GUXwM.js +0 -1
@@ -1,3 +0,0 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,t as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Bn as d,D as f,G as p,L as m,Q as h,Rn as g,Tt as _,ba as v,ci as y,fa as b,ft as x,mn as S,tn as C,wi as w,yn as T,yt as E,zn as D,zr as O}from"./player-overlays-BwkSi_4-.js";import{Ei as k}from"./client-jwdAAPeF.js";import{t as A}from"./flask-conical-D7tbJQpj.js";import{t as j}from"./message-square-plus-_aGccjyj.js";import{Aa as M,Br as N,Ca as ee,Da as P,Ia as F,Ir as I,Sa as te,Vp as ne,Ys as L,_p as re,gi as ie,ka as R,la as z,lp as B,q as ae,ut as V,vp as oe,zr as H}from"./src-CTVIVqdZ.js";import{t as U}from"./i18n-CZf--AlM.js";import{t as W}from"./useTranslation-BJr-n0es.js";import"./mount-CS9GUXwM.js";import{D as G,Si as K,bt as q}from"./index-BAoWvnYw.js";import{t as J}from"./AdminSectionedPage-naipwiRu.js";import{t as se}from"./InstancesTable-Gj2icd8R.js";import{t as ce}from"./AdminPage-CdTTxNI2.js";import{a as le,c as ue,d as de,f as fe,i as pe,l as Y,n as me,o as he,p as ge,r as _e,s as X,t as ve,u as ye}from"./ai-page.helpers-UE-kLqk-.js";c();function be(){let{t}=W(),n=E(),r=ee({functionCap:`llm`}).data??[],a=s({queryKey:me,queryFn:()=>n.trpcClient.llm.getDefaults.query({})}),o=u({mutationFn:e=>n.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,l=e=>e===`vision`?t(`ai.defaultVision`,`Default vision profile`):t(`ai.defaultText`,`Default text profile`);return i(I,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:_e.map(({purpose:n,visionOnly:a})=>{let s=a?r.filter(Y):r,u=c(n),d=r.find(e=>e.id===u);return e(`div`,{children:[i(ie,{className:`mb-1 block`,htmlFor:`llm-default-${n}`,children:l(n)}),i(x,{id:`llm-default-${n}`,"aria-label":l(n),value:u,onChange:e=>o.mutate({purpose:n,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:t(`ai.none`,`None`)},...u!==``&&!s.some(e=>e.id===u)?[{value:u,label:d?.name??u}]:[],...s.map(e=>({value:e.id,label:X(e)===``?e.name:`${e.name} · ${X(e)}`}))]}),u!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:t(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:t(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},n)})})})}var xe=2e3;function Z(e){return U.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function Se(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Ce({nodeId:t,value:r,onChange:a}){let{t:c}=W(),l=E(),[f,p]=o(``),[m,h]=o(null),[g,_]=o(!1),v=s({queryKey:ve,queryFn:()=>l.trpcClient.llm.listModelCatalog.query({})}),y=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>l.trpcClient.llm.listNodeModels.query({nodeId:t})}),b=u({mutationFn:e=>l.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),_(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),S=u({mutationFn:e=>l.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{_(!0),y.refetch()}}),C=s({queryKey:pe,enabled:S.isPending,refetchInterval:S.isPending?xe:!1,queryFn:()=>l.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,T=n(()=>{let e=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${Z(e.sizeBytes)}`})),n=(y.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:Z(e.sizeBytes),node:t})})),r=m?.ok===!0?[{value:`custom`,label:`${m.label} · ${Z(m.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[v.data,y.data,m,t,c]),D=e=>{if(e===``){a(null);return}if(e===`custom`){if(m?.ok!==!0)return;a({model:m.model,modelId:m.label,supportsVision:m.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=v.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=y.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},k=e=>{f.trim()!==``&&b.mutate({ref:f.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(V,{label:c(`ai.model`,`Model`),required:!0,children:i(x,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:Se(r),options:T,onChange:e=>D(e.target.value)})}),i(V,{label:c(`ai.hfTitle`,`Add a model from Hugging Face`),description:c(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`),children:e(`div`,{className:`flex gap-2`,children:[i(re,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:f,onChange:e=>p(e.target.value),placeholder:c(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),k())}}),e(B,{size:`sm`,variant:`secondary`,type:`button`,disabled:f.trim()===``||b.isPending,onClick:()=>k(),children:[b.isPending?i(O,{className:`h-3.5 w-3.5 animate-spin`}):i(d,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),b.isError&&i(P,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)}),m?.ok===!1&&i(P,{message:m.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(m.candidates??[]).map(e=>i(B,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${f.trim().split(`:`)[0]??``}:${e}`;p(t),b.mutate({ref:t})},children:e},e)),m.requiredBytes!==void 0&&i(B,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>k(m.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:Z(m.requiredBytes)})})]})}),m?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:m.label}),i(R,{variant:m.purpose===`vision`?`info`:`default`,children:m.purpose}),i(R,{variant:`default`,children:Z(m.totalBytes)})]}),m.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:m.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(B,{size:`sm`,type:`button`,disabled:S.isPending||g,onClick:()=>S.mutate(m.model),children:[S.isPending?i(O,{className:`h-3.5 w-3.5 animate-spin`}):i(w,{className:`h-3.5 w-3.5`}),g?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),C!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:C.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:C.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:C.file,index:C.fileIndex,count:C.fileCount,done:Z(C.downloadedBytes),total:C.totalBytes===void 0?``:` / ${Z(C.totalBytes)}`})})]}),S.isError&&i(P,{message:S.error instanceof Error?S.error.message:c(`common.error`,`Error`)})]})]})}function we({value:t,onChange:n}){let{t:r}=W(),a=E(),o=s({queryKey:pe,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(O,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=he(a),s=o.nodeId===t;return e(B,{variant:`unstyled`,type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(R,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function Te(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Ee({providerConfig:e,onProviderConfigChange:t}){return i(we,{value:Te(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function De({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=k.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(Ce,{nodeId:Te(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var Oe=new Map([[`ai/apple-node`,Ee],[`ai/managed-model`,De]]);function ke(e){return Oe.get(e)??null}c();function Q(e,t){let n=e[t];return typeof n==`string`?n:``}function Ae({row:a}){let{t:c}=W(),d=E(),f=l(),p=s({queryKey:n(()=>[q,a.addonId,`ai-lead`,a.id],[a]),queryFn:async()=>{let e=d.trpcClient.integrationInstances,[t,n]=await Promise.all([e.describe.query({addonId:a.addonId}),e.getInstance.query({addonId:a.addonId,id:a.id})]);return{description:t,instance:n}}}),[m,h]=o({}),g=t({}),_=t(!1),v=u({mutationFn:e=>d.trpcClient.integrationInstances.updateInstance.mutate({addonId:a.addonId,id:a.id,values:e}),onSuccess:async()=>{await f.invalidateQueries({queryKey:[q]}),await f.invalidateQueries({queryKey:[te]}),h({})}}),y=r(e=>{g.current={...g.current,...e},h(t=>({...t,...e})),!_.current&&(_.current=!0,queueMicrotask(()=>{let e=g.current;g.current={},_.current=!1,v.mutate(e)}))},[v]),b=p.data?.description.kinds?.find(e=>e.id===a.kindId),S=p.data?.instance?.formValues,C=n(()=>({...S,...m}),[S,m]),w=b?.widgets??[],T=w.some(e=>e.placement===`model`),D=n(()=>({...Q(C,`nodeId`)===``?{}:{nodeId:Q(C,`nodeId`)},...typeof C.modelRef==`object`&&C.modelRef!==null?{model:C.modelRef}:{}}),[C]),k={id:Q(C,`model`),supportsVision:C.supportsVision===!0},A=u({mutationFn:()=>d.trpcClient.llm.listModels.mutate({addonId:a.addonId,kind:a.kindId??``,profileId:a.id})});if(p.isPending)return null;if(p.isError)return i(P,{variant:`warning`,message:p.error.message});let j=A.data?.ok===!0?A.data.models:[],M=A.data?.ok===!1?A.data:null,N=e=>{let t=j.find(t=>t.id===e);y({model:e,...t?.features?.vision===void 0?{}:{supportsVision:t.features.vision}})};return e(`div`,{className:`space-y-3`,"data-testid":`ai-profile-lead`,children:[w.map(({id:e})=>{let t=ke(e);return t===null?i(P,{variant:`warning`,message:c(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})},e):i(t,{providerConfig:D,onProviderConfigChange:e=>y({...Q(e,`nodeId`)===Q(D,`nodeId`)?{}:{nodeId:Q(e,`nodeId`)},...e.model!==void 0&&e.model!==D.model?{modelRef:e.model}:{}}),model:k,onModelChange:e=>y({model:e.id,supportsVision:e.supportsVision})},e)}),!T&&e(V,{label:c(`ai.model`,`Model`),children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(B,{size:`sm`,variant:`secondary`,type:`button`,disabled:A.isPending,onClick:()=>A.mutate(),children:[A.isPending?i(O,{className:`h-3.5 w-3.5 animate-spin`}):null,c(`ai.loadModels`,`Load models`)]}),j.length>0&&i(x,{"aria-label":c(`ai.model`,`Model`),value:k.id,onChange:e=>N(e.target.value),options:[...j.some(e=>e.id===k.id)||k.id===``?[]:[{value:k.id,label:k.id}],...j.map(e=>({value:e.id,label:e.label??e.id}))]})]}),M!==null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:M.message}),A.isError&&i(`p`,{className:`mt-1 text-xs text-danger`,children:A.error.message})]}),v.isError&&i(P,{variant:`warning`,message:v.error.message})]})}c();var je=5e3;function Me(e){return U.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function Ne(){let{t}=W(),r=E(),a=s({queryKey:pe,refetchInterval:je,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(R,{variant:ge(n),children:t(fe(n))}),n.status?.downloadProgress!==void 0&&i(R,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:Me(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeature`,`Feature`),render:n=>{let r=de(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(R,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(I,{headingId:`ai-runtimes-list`,title:t(`ai.runtimesList`,`Nodes`),children:a.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[i(M,{className:`h-8 w-full`}),i(M,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:f,children:i(P,{title:t(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:a.error instanceof Error?a.error.message:t(`common.error`,`Error`),onRetry:()=>void a.refetch()})}):c.length===0?i(z,{icon:g,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(H,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:N})})}var Pe=h(`/addon/ai/test-chat`),Fe=h(`/addon/ai/test-chat/chats`),Ie=6e5;function Le(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),Ie)}function Re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ze(e){if(!Re(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Be=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Ve(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Re(t))return null;switch(t.kind){case`status`:{let e=Be.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:ze(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:U.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*He(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
- `);for(;a>=0;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length>0){let t=Ve(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=Ve(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Ue(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function We(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Ge(e){return e.messages.map((t,n)=>{let r=t.mediaSent??void 0;return{id:`${e.id}-${String(n)}`,role:t.role,content:t.content,...t.attachment===void 0?{}:{attachmentRef:t.attachment,attachmentKind:t.attachment.kind},...r===void 0?{}:{attachment:r}}})}function Ke(e){let t=e.sizeBytes<1024*1024?`${(e.sizeBytes/1024).toFixed(0)} KB`:`${(e.sizeBytes/(1024*1024)).toFixed(1)} MB`,n=[e.kind===`snapshot`?`camera snapshot`:`track best-shot`,t];return e.mediaKind!==void 0&&n.push(e.mediaKind),e.capturedAt!==void 0&&n.push(new Date(e.capturedAt).toLocaleTimeString()),n.join(` · `)}function qe(e,t){switch(e){case`resolving-image`:return U.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return U.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?U.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):U.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return U.t(`helpers.aiTestChat.phaseAnswering`)}}c();var Je=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],Ye=360*60*1e3,Xe=40,Ze=160,$={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Qe(){let{t:s}=W();E();let[c,l]=o(``),[u,d]=o(``),[p,h]=o(``),[g,y]=o([]),[w,T]=o(null),[O,k]=o(`none`),[A,M]=o(`throwaway`),[N,F]=o(null),[te,ne]=o([]),[L,R]=o(null),[z,V]=o(null),H=t(null);a(()=>()=>H.current?.abort(),[]);let U=r(async()=>{let e=await fetch(Fe,{credentials:`same-origin`});e.ok&&ne((await e.json()).chats??[])},[]);a(()=>{A===`persistent`&&U()},[A,U]);let G=ee({functionCap:`llm`}),K=n(()=>(G.data??[]).filter(e=>e.enabled),[G.data]),q=K.find(e=>e.id===c)??null,J=z!==null,se=r(async(e,t)=>{let n=new AbortController;H.current=n,R(null);let r=Le(q===null?{}:ye(q));V({...$,firstTokenTimeoutMs:r??0});let i=``,a=null,o,l=null,d=null,f;try{let s=await fetch(Pe,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:n.signal,body:JSON.stringify({profileId:c,messages:e,...u.trim()===``?{}:{system:u.trim()},...t===void 0?{}:{attachment:t},...r===void 0?{}:{firstTokenTimeoutMs:r},...A===`persistent`?{persist:!0,...N===null?{}:{conversationId:N}}:{}})});if(!s.ok||s.body===null){let e=await s.text().catch(()=>``);throw Error(e.length>0?e:`HTTP ${String(s.status)}`)}for await(let e of He(s.body))switch(e.kind){case`status`:V(t=>({...t??$,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,V(t=>({...t??$,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,V(e=>({...e??$,text:i}));break;case`done`:d={outputTokens:e.outputTokens,latencyMs:e.latencyMs},f=e.conversationId;break;case`error`:l=`${e.code}: ${e.message}`;break}}catch(e){n.signal.aborted||R(e instanceof Error?e.message:s(`common.error`,`Error`))}finally{H.current=null,V(null)}f!==void 0&&(F(f),U());let p=n.signal.aborted&&i.length>0;l===null&&i.length===0&&!p||y(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:l??i,...l===null?{}:{failed:!0},...a===null?{}:{attachment:a},...o!==void 0&&l===null?{model:o}:{},...d===null?{}:d}])},[A,N,q,c,U,u,s]),ce=r(()=>{let e=p.trim();if(e===``||c===``||J)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...w===null?{}:{attachmentLabel:w.label,attachmentKind:w.ref.kind}},n=[...g,t];y(n),h(``);let r=w?.ref;T(null),k(`none`),se(A===`persistent`&&N!==null?[{role:`user`,content:e}]:Ue(n),r)},[A,N,p,w,c,se,J,g]),le=()=>H.current?.abort(),ue=()=>{H.current?.abort(),y([]),T(null),h(``),R(null),V(null),F(null)},de=async e=>{H.current?.abort();let t=await fetch(`${Fe}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();F(e),y(Ge(n)),V(null),R(null)};return e(`div`,{className:m,children:[i(I,{headingId:`ai-test-setup`,title:s(`ai.testSetup`,`Setup`),children:e(`div`,{className:`${f} space-y-3`,children:[e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(ie,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:s(`ai.profile`,`Profile`)}),i(x,{id:`ai-test-profile`,value:c,onChange:e=>l(e.target.value),options:[{value:``,label:s(`ai.selectProfile`,`Select a profile…`)},...K.map(e=>({value:e.id,label:`${e.name} · ${X(e)}${Y(e)?` · vision`:``}`}))]}),K.length===0&&!G.isLoading&&i(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:s(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),e(`div`,{children:[i(ie,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:s(`ai.systemPrompt`,`System prompt (optional)`)}),i(re,{id:`ai-test-system`,value:u,onChange:e=>d(e.target.value),placeholder:s(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(ae,{label:s(`ai.chatMode`,`Conversation mode`),value:A,options:[{value:`throwaway`,label:s(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:s(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{M(e),e===`throwaway`&&F(null)}}),A===`persistent`&&e(`div`,{className:`space-y-2`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:s(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),e(B,{size:`sm`,variant:`secondary`,type:`button`,onClick:ue,children:[i(j,{className:`h-3.5 w-3.5`}),s(`ai.newChat`,`New chat`)]}),te.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:te.map(e=>i(`button`,{type:`button`,onClick:()=>void de(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-xs hover:bg-surface-hover ${e.id===N?`bg-primary/10`:``}`,children:i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:s(`ai.streamNote`,`The answer streams as the model produces it. A cold model can take a while to load — the status line says which phase it is in.`)}),q!==null&&!Y(q)&&i(`p`,{className:`text-xs text-warning`,children:s(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]})}),L!==null&&i(P,{title:s(`ai.chatFailed`,`The test call failed`),message:L}),e(I,{headingId:`ai-test-conversation`,title:s(`ai.testConversation`,`Conversation`),actions:e(B,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.length===0&&w===null,onClick:ue,children:[i(C,{className:`h-3.5 w-3.5`}),s(`ai.clearChat`,`Clear`)]}),children:[i($e,{turns:g,live:z}),e(`div`,{className:`${f} space-y-2 border-t border-border`,children:[w!==null&&e(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[w.ref.kind===`snapshot`?i(b,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(v,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:w.label}),i(oe,{size:`sm`,variant:`ghost`,type:`button`,icon:_,"aria-label":s(`ai.removeAttachment`,`Remove attachment`),onClick:()=>T(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(B,{size:`sm`,variant:O===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>k(O===`snapshot`?`none`:`snapshot`),children:[i(b,{className:`h-3.5 w-3.5`}),s(`ai.attachSnapshot`,`Camera snapshot`)]}),e(B,{size:`sm`,variant:O===`track`?`primary`:`outline`,type:`button`,onClick:()=>k(O===`track`?`none`:`track`),children:[i(v,{className:`h-3.5 w-3.5`}),s(`ai.attachTrack`,`Recent track`)]})]}),O===`snapshot`&&i(nt,{onPick:(e,t)=>{T({ref:{kind:`snapshot`,deviceId:e.id},label:s(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t})}),k(`none`)}}),O===`track`&&i(it,{onPick:(e,t)=>{T({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:s(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),k(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(re,{value:p,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ce())},placeholder:s(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":s(`ai.message`,`Message`)}),J?e(B,{size:`sm`,variant:`secondary`,type:`button`,onClick:le,children:[i(S,{className:`h-3.5 w-3.5`}),s(`ai.stop`,`Stop`)]}):e(B,{size:`sm`,type:`button`,disabled:p.trim()===``||c===``,onClick:ce,children:[i(D,{className:`h-3.5 w-3.5`}),s(`ai.send`,`Send`)]})]})]})]})]})}function $e({turns:t,live:n}){let{t:r}=W();return t.length===0&&n===null?i(z,{icon:A,title:r(`ai.chatEmptyTitle`,`No messages yet`),description:r(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):e(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto ${f}`,children:[t.map(e=>i(et,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(tt,{attachment:n.mediaSent}),n.text.length>0&&i(et,{turn:{id:`live`,role:`assistant`,content:n.text},streaming:!0}),e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(O,{className:`h-3.5 w-3.5 animate-spin`}),qe(n.phase,n.firstTokenTimeoutMs)]})]})]})}function et({turn:t,streaming:n=!1}){let{t:r}=W(),a=t.role===`user`,o=t.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return i(`div`,{className:`flex ${a?`justify-end`:`justify-start`}`,children:e(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${a?`border-primary/40 bg-primary/10`:o}`,children:[e(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[t.content,n&&i(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),t.attachment!==void 0&&i(tt,{attachment:t.attachment}),t.attachmentLabel!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachmentKind===`track`?i(v,{className:`h-3 w-3`}):i(b,{className:`h-3 w-3`}),t.attachmentLabel]}),t.attachment!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachment.kind===`snapshot`?i(b,{className:`h-3 w-3`}):i(v,{className:`h-3 w-3`}),Ke(t.attachment)]}),t.model!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:t.model,value2:String(t.outputTokens??0),value3:String(t.latencyMs??0)})})]})})}function tt({attachment:e}){let{t}=W(),n=We(e);return n===null?null:i(`img`,{src:n,alt:t(`system.aiTestChat.sentToTheModel`,`sent to the model`),className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function nt({onPick:e}){let{t}=W(),n=L({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(O,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):i(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>i(rt,{device:t,onPick:e},t.id))})}function rt({device:t,onPick:n}){let{t:r}=W(),a=F(t,`compact`),{src:o}=p(t.id,{width:Ze});return e(`button`,{type:`button`,onClick:()=>n(t,a),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[i(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:o!==null&&i(`img`,{src:o,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),e(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!t.online&&i(R,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function it({onPick:t}){let{t:r}=W(),a=E(),o=L({isCamera:!0,projection:`slim`}),c=n(()=>(o.data??[]).map(e=>e.id),[o.data]),l=n(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),u=s({queryKey:[...Je,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-Ye,limit:Xe,projection:`slim`})});if(o.isLoading||u.isLoading)return i(O,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=u.data?.tracks??[];return d.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noTracks`,`No track in the last 6 hours.`)}):i(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(n=>e(`button`,{type:`button`,onClick:()=>t(n,l.get(n.deviceId)??String(n.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[i(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:n.label??n.className}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:l.get(n.deviceId)??n.deviceId}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(n.lastSeen).toLocaleTimeString()})]},n.trackId))})}c();var at=1440*60*1e3,ot=[1,7,30,90];function st(){let{t}=W(),r=E(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*at},[a]),u=ee({functionCap:`llm`}),d=s({queryKey:[...le,a],queryFn:()=>r.trpcClient.llm.getUsage.query({since:l})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),m=n(()=>[{key:`day`,header:t(`ai.colDay`,`Day`),nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:t(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:t(`ai.colProfile`,`Profile`),render:e=>i(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:t(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:t(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:t(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:t(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,t]),h=d.data??[],g=i(`div`,{className:`w-36`,children:i(x,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:ot.map(e=>({value:String(e),label:t(`ai.lastDays`,`Last {{days}} days`,{days:e})})),onChange:e=>c(Number(e.target.value))})});return i(I,{headingId:`ai-usage-list`,title:t(`ai.usageList`,`Rollup`),actions:g,children:d.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-usage-loading`,children:[i(M,{className:`h-8 w-full`}),i(M,{className:`h-8 w-full`}),i(M,{className:`h-8 w-full`})]}):d.isError?i(`div`,{className:f,children:i(P,{title:t(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:t(`common.error`,`Error`),onRetry:()=>void d.refetch()})}):h.length===0?i(z,{icon:y,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(H,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:N})})}c();var ct=`llm`,lt=[`profiles`,`runtimes`,`usage`,`test`],ut=[`instance`,`instance-new`];function dt(e){return lt.some(t=>t===e)}function ft(){let{t:e}=W(),t=ne(ct),[n]=K(),r=G(`/system/ai`,{t:e,isAdmin:!0})??{icon:T,title:e(`system.ai`,`AI`)};if(t!==`present`)return i(ce,{icon:r.icon,title:r.title,children:i(gt,{presence:t})});let a=n.get(`tab`),o=dt(a)?a:`profiles`,s={profiles:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),runtimes:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),usage:e(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),test:e(`ai.testSubtitle`,`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`)};return i(J,{icon:r.icon,title:r.title,subtitle:s[o],defaultSection:`profiles`,sectionsLabel:`${r.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:i(ht,{}),ownedParams:ut},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:i(Ne,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:i(st,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:i(Qe,{})}]})}function pt(e,t,n){let r=e.kind===`instance`?t.get(e.id):void 0;return r===void 0?void 0:n(r)}function mt(e,t){let n=t=>pt(t,e,X)??``,r=t=>pt(t,e,Y)??!1,a=t=>pt(t,e,ue)??``;return[{key:`model`,header:t(`ai.colModel`,`Model`),sortValue:n,render:e=>i(`span`,{className:`font-mono text-xs text-foreground-muted`,children:n(e)||`—`})},{key:`vision`,header:t(`ai.colVision`,`Vision`),sortValue:e=>+!!r(e),render:e=>r(e)?i(R,{variant:`info`,children:t(`ai.vision`,`vision`)}):null},{key:`node`,header:t(`ai.colNode`,`Node`),sortValue:a,render:e=>i(`span`,{className:`text-xs text-foreground-muted`,children:a(e)||`—`})}]}function ht(){let{t}=W(),r=ee({functionCap:ct}),a=n(()=>new Map((r.data??[]).map(e=>[e.id,e])),[r.data]),o=n(()=>mt(a,t),[a,t]);return e(`div`,{className:m,children:[i(be,{}),i(se,{functionCap:ct,icon:T,title:t(`ai.profilesList`,`Profiles`),subtitle:t(`ai.profilesTableSubtitle`,`Each profile is one model endpoint; switch one off to keep it without using it.`),emptyTitle:t(`ai.noProfilesTitle`,`No AI profiles yet`),emptyDescription:t(`ai.noProfilesDescription`,`Add a profile to give features a model to talk to.`),addLabel:t(`ai.addProfile`,`Add profile`),extraColumns:o,lead:e=>i(Ae,{row:e})})]})}function gt({presence:t}){let{t:n}=W();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(M,{className:`h-8 w-64`}),i(M,{className:`h-40 w-full`})]}):t===`unknown`?i(P,{title:n(`ai.presenceUnknownTitle`,`Could not check whether AI is installed`),message:n(`ai.presenceUnknown`,`The hub did not answer the capability check. Reload the page to try again.`)}):i(z,{icon:T,title:n(`ai.absentTitle`,`AI is not installed`),description:n(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{ft as AiProfilesPage,ft as default};
@@ -1 +0,0 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,o as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$t as d,Bn as f,Et as p,Hi as m,Lr as h,Mi as g,Q as _,Qa as v,Tt as y,Va as b,Xa as x,Xr as S,Y as C,Yn as w,Yr as T,Z as E,Za as D,Zt as O,_a as k,aa as A,ar as j,ct as M,fa as N,ft as P,hi as F,hn as I,ki as L,ln as ee,mn as R,ot as te,pn as z,qr as ne,qt as B,sa as re,si as ie,t as ae,ti as oe,tn as se,ut as ce,wi as le,yt as ue,z as de,zr as V}from"./player-overlays-BwkSi_4-.js";import{Oc as fe,cl as H,gt as pe,kc as me,ui as he}from"./client-jwdAAPeF.js";import{t as ge}from"./chevron-down-CBb-F8DT.js";import{_ as _e}from"./terminal-DZ5OZpgC.js";import{n as ve,r as ye,t as U}from"./scissors-DpiKUioV.js";import{t as be}from"./square-check-big-DAcFGNUN.js";import{Br as xe,Cr as Se,Da as W,Ep as Ce,Er as we,Ft as Te,Fu as Ee,Gi as De,Gu as Oe,Hi as ke,Ir as Ae,Ji as je,Kp as Me,Li as Ne,Md as Pe,Mr as Fe,Nd as Ie,Pd as Le,Ui as Re,Vp as ze,Vu as Be,Wi as Ve,Xi as He,Yi as Ue,Ys as We,_f as Ge,_p as Ke,aa as qe,ai as Je,au as Ye,cf as Xe,ci as Ze,cp as Qe,cu as $e,d as et,df as tt,du as nt,ea as rt,ff as it,fo as at,fu as ot,ga as st,gf as ct,gp as lt,hf as ut,hp as dt,hu as ft,ia as pt,iu as mt,jd as ht,jr as gt,ju as _t,ka as G,kr as vt,la as yt,lf as bt,lp as K,lu as xt,mf as St,mp as Ct,mr as wt,mu as Tt,na as Et,np as Dt,oi as Ot,ou as kt,pf as At,pu as jt,ql as Mt,ra as Nt,rp as Pt,si as Ft,sp as It,su as Lt,ta as Rt,tt as zt,uf as Bt,uu as Vt,vf as Ht,vp as Ut,wi as Wt,yf as Gt,zr as Kt}from"./src-CTVIVqdZ.js";import{r as qt,t as Jt}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-BPba2g2p.js";import{t as q}from"./i18n-CZf--AlM.js";import{t as J}from"./useTranslation-BJr-n0es.js";import"./mount-CS9GUXwM.js";import{Ci as Yt,Di as Xt,Ei as Zt,N as Qt,Si as $t,Ti as en,_i as tn,bi as nn,gi as rn,wi as an,yi as on}from"./index-BAoWvnYw.js";import{t as sn}from"./AdminSectionedPage-naipwiRu.js";import{a as cn,d as ln,f as un,i as dn,m as fn,n as pn,o as mn,p as hn,r as gn,s as _n,t as vn,u as yn}from"./NewExportModal-5HfHutIX.js";import{a as bn,i as xn,r as Sn,t as Cn}from"./authed-media-HuCfJg8e.js";import{a as wn,o as Tn}from"./PanelContent-CvEORG5m.js";import{t as Y}from"./format-size-DIxKXxtj.js";import{a as En,i as Dn,n as On,o as kn,r as An,s as jn,t as Mn}from"./StorageLocationsTable-CQpdu3Aj.js";c();var Nn={info:0,warning:1,critical:2},Pn={"motion-without-detections":`motion`,"detections-under-floor":`detection`,"inference-too-slow":`detection`,"frames-shed":`detection`,"inference-device-unusable":`detection`};function Fn(e){return{id:`op:${e.id}`,at:e.at,source:`operation`,severity:`info`,fn:e.domain===`recording`?`recording`:`events`,deviceId:e.deviceId,title:`${e.op} · ${e.reason}`,detail:e.detail}}function In(e,t){return{id:`finding:${e.id}`,at:t,source:`finding`,severity:e.severity,fn:Pn[e.kind],deviceId:e.subject.type===`camera`?e.subject.deviceId:null,title:e.what,detail:e.action}}function Ln(e,t){return e.filter(e=>t.deviceId===null||e.deviceId===t.deviceId).filter(e=>t.fn===null||e.fn===t.fn).filter(e=>t.minSeverity===null||Nn[e.severity]>=Nn[t.minSeverity]).toSorted((e,t)=>t.at-e.at)}var Rn=``,zn=[`recording`,`events`,`detection`,`motion`],Bn=[`info`,`warning`,`critical`];function Vn({data:t,deviceId:r}){let{t:a}=J(),s=Ie({},{refetchOnWindowFocus:!1}),c=Vt({},{refetchOnWindowFocus:!1}),[l,u]=o(Rn),[d,f]=o(Rn),[p,m]=o(Rn),h=n(()=>{let e=[...s.data??[],...c.data??[]].map(Fn),n=t.digestAtMs??0,r=(t.findings??[]).map(e=>In(e,n));return[...e,...r]},[s.data,c.data,t.findings,t.digestAtMs]),g=n(()=>({deviceId:r??(l===Rn?null:Number(l)),fn:zn.find(e=>e===d)??null,minSeverity:Bn.find(e=>e===p)??null}),[r,l,d,p]),_=n(()=>Ln(h,g),[h,g]),v=n(()=>new Map(t.cameras.map(e=>[e.id,e.name])),[t.cameras]),y=[];s.isError&&y.push(a(`archive.activity.footageLog`,`footage`)),c.isError&&y.push(a(`archive.activity.eventLog`,`event`));let b=n(()=>[{key:`at`,header:a(`archive.activity.when`,`When`),nowrap:!0,sortValue:e=>e.at,render:e=>i(`span`,{className:`tabular-nums text-foreground-subtle`,children:e.at===0?`—`:new Date(e.at).toLocaleString()})},{key:`severity`,header:a(`archive.activity.severity`,`Severity`),nowrap:!0,sortValue:e=>e.severity,render:e=>i(`span`,{className:Hn[e.severity],children:a(`archive.severity.${e.severity}`,e.severity)})},{key:`camera`,header:a(`archive.activity.camera`,`Camera`),sortValue:e=>e.deviceId===null?``:v.get(e.deviceId)??`#${String(e.deviceId)}`,render:e=>i(`span`,{className:`text-foreground`,children:e.deviceId===null?a(`archive.activity.cluster`,`Cluster`):v.get(e.deviceId)??`#${String(e.deviceId)}`})},{key:`what`,header:a(`archive.activity.what`,`What`),render:t=>e(`div`,{className:`flex flex-col`,children:[i(`span`,{className:`text-foreground`,children:t.title}),t.detail!==null&&i(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.detail})]})}],[a,v]);return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`archive-activity`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0&&e(P,{wrapperClassName:`inline-block w-auto`,value:l,onChange:e=>u(e.target.value),"aria-label":a(`archive.activity.filterCamera`,`Camera`),children:[i(`option`,{value:Rn,children:a(`archive.activity.allCameras`,`All cameras`)}),t.cameras.map(e=>i(`option`,{value:String(e.id),children:e.name},e.id))]}),e(P,{wrapperClassName:`inline-block w-auto`,value:d,onChange:e=>f(e.target.value),"aria-label":a(`archive.activity.filterFunction`,`Function`),children:[i(`option`,{value:Rn,children:a(`archive.activity.allFunctions`,`All functions`)}),zn.map(e=>i(`option`,{value:e,children:a(`archive.function.${e}`,e)},e))]}),e(P,{wrapperClassName:`inline-block w-auto`,value:p,onChange:e=>m(e.target.value),"aria-label":a(`archive.activity.filterSeverity`,`Severity`),children:[i(`option`,{value:Rn,children:a(`archive.activity.allSeverities`,`Any severity`)}),Bn.map(e=>i(`option`,{value:e,children:a(`archive.activity.atLeast`,`At least {{severity}}`,{severity:a(`archive.severity.${e}`,e)})},e))]})]}),y.length>0&&i(W,{variant:`warning`,message:a(`archive.activity.logUnread`,`The {{names}} log did not answer. This is not "nothing happened".`,{names:y.join(` / `)})}),_.length===0&&y.length===0?i(yt,{icon:x,title:a(`archive.activity.none`,`No activity`),description:a(`archive.activity.noneHint`,`Pruning, deletion and health findings show up here.`)}):i(Kt,{columns:b,rows:_,rowKey:e=>e.id,minWidthPx:640,maxBodyHeight:xe,pageSize:25})]})}var Hn={info:`text-foreground-subtle`,warning:`text-warning`,critical:`text-danger`},Un={recording:`recording`,motion:null,detection:`object-detection`,"event-media":`event-saving`},Wn={"motion-without-detections":`motion`,"detections-under-floor":`detection`,"inference-too-slow":`detection`,"frames-shed":`detection`,"inference-device-unusable":null},Gn={recording:`recording`,motion:null,detection:`detection`,"event-media":null},Kn=[`recording`,`motion`,`detection`,`event-media`];function qn(e,t){switch(e){case`recording`:return t.recording===null?null:t.recording.active?`ok`:`warning`;case`motion`:return t.motion===null?null:t.motion.enabled?`ok`:`off`;case`detection`:return t.detection===null?null:`ok`;case`event-media`:return`ok`}}function Jn(e){return e.some(e=>e.severity===`critical`)?`critical`:e.some(e=>e.severity===`warning`)?`warning`:`ok`}function Yn(e,t){return Kn.map(n=>{let r=t.filter(e=>Wn[e.kind]===n);if(e===void 0)return{fn:n,state:r.length>0?Jn(r):`unknown`,findings:r};let i=Un[n];if(i!==null&&e.switchedOff.includes(i))return{fn:n,state:`off`,findings:r};let a=Gn[n];return a!==null&&e.degraded.some(e=>e.stage===a)?{fn:n,state:r.length>0?Jn(r):`unknown`,findings:r}:r.length>0?{fn:n,state:Jn(r),findings:r}:n===`recording`&&e.recording?.mode===`off`?{fn:n,state:`off`,findings:r}:{fn:n,state:qn(n,e)??`unknown`,findings:r}})}var Xn=`recording`;function Zn(e,t){return(e??[]).filter(e=>e.subject.type===`camera`&&e.subject.deviceId===t)}function Qn(e){return e.filter(e=>e.severity!==`info`).length}function $n(e,t){return e===void 0?`unknown`:e.switchedOff.includes(Xn)||e.recording?.mode===`off`?`off`:e.degraded.some(e=>e.stage===`recording`||e.stage===`switches`)||e.recording===null?`unknown`:t>0||!e.recording.active?`degraded`:`recording`}function er(e){let t=new Map((e.footage??[]).map(e=>[e.deviceId,e])),n=new Map((e.events??[]).map(e=>[e.deviceId,e])),r=new Map((e.statuses??[]).map(e=>[e.deviceId,e]));return e.cameras.map(i=>{let a=Qn(Zn(e.findings,i.id)),o=r.get(i.id),s=t.get(i.id),c=n.get(i.id);return{deviceId:i.id,name:i.name,mode:o?.recording?.mode??null,state:$n(o,a),warnings:a,footageBytes:e.footage===null?null:s?.usedBytes??0,oldestMs:s?.oldestMs??null,eventRows:e.events===null?null:c?.rows??0,eventBytes:e.events===null?null:c?.bytes??0}})}function tr(e){let t=t=>e.filter(e=>e.state===t).length;return{recording:t(`recording`),degraded:t(`degraded`),off:t(`off`),unknown:t(`unknown`),warnings:e.reduce((e,t)=>e+t.warnings,0)}}var nr={ok:`success`,off:`default`,warning:`warning`,critical:`danger`,unknown:`default`};function rr(e,t){return e.statuses?.find(e=>e.deviceId===t)}function ir({data:t,deviceId:n}){let{t:r}=J(),a=Yn(rr(t,n),Zn(t.findings,n));return e(`div`,{className:`flex flex-col gap-4`,"data-testid":`archive-health`,children:[t.findings===null&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`archive.health.noDigest`,`The health digest has not run yet — findings are not available.`)}),i(`ul`,{className:`flex flex-col divide-y divide-border rounded-lg border border-border bg-surface`,children:a.map(t=>e(`li`,{className:`flex flex-col gap-1 p-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`span`,{className:`text-sm font-medium text-foreground`,children:r(`archive.function.${t.fn}`,t.fn)}),i(G,{variant:nr[t.state],children:r(`archive.functionState.${t.state}`,t.state)})]}),t.findings.map(t=>e(`div`,{className:`text-[11px] text-foreground-subtle`,children:[i(`span`,{className:`text-foreground`,children:t.what}),` — `,t.action]},t.id))]},t.fn))}),e(`div`,{className:`flex flex-col gap-2`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:r(`archive.health.logs`,`Camera log`)}),i(tn,{className:`text-xs text-primary hover:underline`,to:`/system/logs?deviceId=${String(n)}`,children:r(`archive.health.openLogs`,`Open in Logs`)})]}),i(`div`,{className:`overflow-hidden rounded-lg border border-border bg-surface`,children:i(wt,{deviceId:n,limit:100,maxHeight:`max-h-80`,showFilters:!0})})]})]})}qt();function ar(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 or=720*60*60*1e3;function sr(e){let t=[];for(let n of e)t.push(...n);return t}function cr(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function lr(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 ur(e,t){return`${String(e)}:${t}`}function dr(e,t){let n=new Map,r=new Set;for(let i of e){let e=ur(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 fr(e,t){return{since:e.fromMs??t-or,until:e.toMs??t}}var pr=typeof Ye==`function`,mr=`Track deletion arrives with the next server update`;function hr(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var gr=pr?Ye:hr;c();var _r=3e4,vr=[];function yr(e){let t=ue(),r=e.deviceIds.length>0,i=[...e.deviceIds].sort((e,t)=>e-t),{data:a,isLoading:o}=s({queryKey:[`events-feed`,i,e.since,e.until,e.minImportance??null,e.classFilter??null],enabled:r,staleTime:_r,refetchInterval:_r,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:i,since:e.since,until:e.until,limit:200,...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:n(()=>cr(sr(a??vr),`importance`),[a]),isLoading:r&&o}}c();var br=[`events-feed`],xr=2e3;function Sr(e){let n=l(),i=e?.paused===!0,s=t(n);s.current=n;let c=t(i);c.current=i;let[u,d]=o(!1),f=r(()=>{s.current.invalidateQueries({queryKey:br})},[]),p=t(void 0);p.current||=fn({delayMs:xr,invalidate:()=>{c.current?d(!0):f()}}),a(()=>()=>p.current?.cancel(),[]),a(()=>{i||!u||(d(!1),f())},[i,u,f]);let m=r(()=>{d(!1),f()},[f]);return Me(H.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),Me(H.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:u,refreshNow:m}}c();function Cr(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e])=>e)}function wr({classes:e,hidden:t,onChange:r}){let{t:a}=J(),o=n(()=>Cr(e).map(e=>({id:e,label:e})),[e]);return o.length<2?null:i(we,{chips:o,off:t,onChange:r,allLabel:a(`detectionIntelligence.eventClassChips.all`,`All classes`),ariaLabel:a(`detectionIntelligence.eventClassChips.label`,`Classes`),testId:`event-class-chips`})}var Tr=[0,1,2],Er=`camstack.archive.eventRowSize`,Dr={0:`w-[72px]`,1:`w-28`,2:`w-40`};function Or(e){return e===1||e===2?e:0}c();function kr({groups:t,selected:r,onChange:a,loading:s=!1}){let{t:c}=J(),l=Se(),[u,d]=o(!1),[p,m]=o(``),[h,g]=o(new Set),_=p.trim().toLowerCase(),v=e=>_.length===0||It(e,c).toLowerCase().includes(_),y=n(()=>t.map(e=>({macro:e.macro,subs:e.subs.filter(t=>v(t)||v(e.macro))})).filter(e=>v(e.macro)||e.subs.length>0),[t,_]),b=e=>g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),x=e=>{let t=new Set(r),n=r.has(e.macro.kind)&&e.subs.every(e=>r.has(e.kind)),i=[e.macro.kind,...e.subs.map(e=>e.kind)];if(n)for(let e of i)t.delete(e);else for(let e of i)t.add(e);a(t)},S=e=>{let t=new Set(r);t.has(e)?t.delete(e):t.add(e),a(t)},C=()=>a(new Set),w=r.size;return e(`div`,{className:`relative`,children:[e(K,{variant:`unstyled`,type:`button`,onClick:()=>d(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${w>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[i(ee,{className:`h-3.5 w-3.5`}),w>0?c(`detectionIntelligence.eventKindFilter.kinds`,`Kinds ({{value1}})`,{value1:String(w)}):c(`detectionIntelligence.eventKindFilter.kinds2`,`Kinds`),i(ge,{className:`h-3 w-3`})]}),u&&e(`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:[e(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[i(f,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(Ke,{type:`text`,value:p,onChange:e=>m(e.target.value),placeholder:c(`detectionIntelligence.eventKindFilter.searchKinds`,`Search kinds…`),className:`w-full bg-transparent py-1 text-xs outline-none`}),w>0&&i(K,{variant:`unstyled`,type:`button`,onClick:C,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:c(`detectionIntelligence.eventKindFilter.clear`,`Clear`)})]}),y.length===0&&i(`div`,{className:`px-1 py-2 text-[11px] text-foreground-subtle`,children:s?c(`detectionIntelligence.eventKindFilter.loadingKinds`,`Loading kinds…`):_.length>0?c(`detectionIntelligence.eventKindFilter.noKindMatchesThatSearch`,`No kind matches that search.`):c(`detectionIntelligence.eventKindFilter.theseCamerasAdvertiseNoEvent`,`These cameras advertise no event kinds.`)}),y.map(t=>{let n=Qe(t.macro.iconId),a=h.has(t.macro.kind)||_.length>0,o=r.has(t.macro.kind);return e(`div`,{className:`mb-0.5`,children:[e(`div`,{className:`flex items-center gap-1`,children:[t.subs.length>0?i(K,{variant:`unstyled`,type:`button`,onClick:()=>b(t.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":c(`detectionIntelligence.eventKindFilter.expand`,`Expand`),children:i(a?ge:A,{className:`h-3 w-3`})}):i(`span`,{className:`w-3`}),e(`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:[i(D,{checked:o,onChange:()=>x(t),className:`accent-primary`}),i(n,{className:`h-3.5 w-3.5`,style:{color:l(t.macro.kind)}}),i(`span`,{className:`font-medium`,children:It(t.macro,c)})]})]}),a&&t.subs.map(t=>{let n=Qe(t.iconId);return e(`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:[i(D,{checked:r.has(t.kind),onChange:()=>S(t.kind),className:`accent-primary`}),i(n,{className:`h-3.5 w-3.5`,style:{color:l(t.kind)}}),i(`span`,{children:It(t,c)})]},t.kind)})]},t.macro.kind)})]})]})}function Ar(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 jr(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var Mr=new Set([`detection`,`package`]);function Nr(e,t){return[...Ar(e,t).values()].filter(e=>e.parentKind===null&&Mr.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function Pr(e,t){let n=Ar(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,jr(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))}c();var Fr=1400,Ir=`Admin-gated URL — opens only inside an authenticated session`;function Lr({label:t,value:n,title:s}){let{t:c}=J(),[l,u]=o(!1),d=ce();return a(()=>{if(!l)return;let e=setTimeout(()=>u(!1),Fr);return()=>clearTimeout(e)},[l]),e(K,{variant:`unstyled`,type:`button`,onClick:r(()=>{(async()=>{try{await navigator.clipboard.writeText(n),u(!0)}catch{await d({title:c(`detectionIntelligence.copyUrlChips.copyTheMediaUrl`,`Copy the media URL`),message:c(`detectionIntelligence.copyUrlChips.clipboardAccessWasRefusedSelect`,`Clipboard access was refused. Select the URL below and copy it manually.`),label:c(`detectionIntelligence.copyUrlChips.url`,`{{label}} URL`,{label:t}),defaultValue:n,readOnly:!0,cancelLabel:c(`common.close`,`Close`)})}})()},[n,t,d,c]),title:s,"aria-label":c(`detectionIntelligence.copyUrlChips.copyUrl`,`Copy {{label}} URL`,{label:t}),className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${l?`border-success/40 bg-success/10 text-success`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[i(l?re:g,{className:`h-2.5 w-2.5 shrink-0`}),i(`span`,{className:`truncate`,children:l?c(`detectionIntelligence.copyUrlChips.copied`,`Copied`):t})]})}function Rr({localUrl:t,publicUrl:n}){let{t:r}=J();return e(`div`,{className:`flex flex-wrap gap-1`,children:[i(Lr,{label:r(`detectionIntelligence.copyUrlChips.local`,`Local`),value:t,title:r(`detectionIntelligence.copyUrlChips.copyLanUrl`,`Copy LAN URL — {{AUTH_HINT}}`,{AUTH_HINT:Ir})}),n&&i(Lr,{label:r(`detectionIntelligence.copyUrlChips.public`,`Public`),value:n,title:r(`detectionIntelligence.copyUrlChips.copyPublicUrl`,`Copy public URL — {{AUTH_HINT}}`,{AUTH_HINT:Ir})})]})}var zr={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 Br(e){return e in zr}function Vr(e){return Br(e)?zr[e]:e}function Hr(e,t){return`${e}${t}`}var Ur=[`native`,`raster`,`standin`];function Wr(e){return Ur.some(t=>t===e)}function Gr(e){return e===`standin`?{label:q.t(`helpers.mediaProvenance.standin.label`),title:q.t(`helpers.mediaProvenance.standin.title`),tone:`warning`}:{label:q.t(`helpers.mediaProvenance.raster.label`),title:q.t(`helpers.mediaProvenance.raster.title`),tone:`info`}}function Kr(e){return e===`standin`?Gr(`standin`):e===`raster`?Gr(`raster`):null}var qr={"no-key-frame":`helpers.mediaProvenance.miss.noKeyFrame`,"no-best-seen-bbox":`helpers.mediaProvenance.miss.noBestSeenBbox`,"derive-returned-null":`helpers.mediaProvenance.miss.deriveReturnedNull`,"derive-threw":`helpers.mediaProvenance.miss.deriveThrew`,"derive-not-wired":`helpers.mediaProvenance.miss.deriveNotWired`,"no-media-store":`helpers.mediaProvenance.miss.noMediaStore`,"no-thumbnail":`helpers.mediaProvenance.miss.noThumbnail`,"standin-tile":`helpers.mediaProvenance.miss.standinTile`,"raster-tile":`helpers.mediaProvenance.miss.rasterTile`,"native-tile":`helpers.mediaProvenance.miss.nativeTile`};function Jr(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)})}let a=qr[r];return{sentence:a===void 0?r:q.t(a),detail:i,raw:t}}c();var Yr=3e4;function Xr(e){let[t,n]=o(null),s=r(e=>{n(t=>t??e)},[]);return a(()=>{e||n(null)},[e]),{publicOrigin:t,probes:e?i(Zr,{onOrigin:s}):null}}function Zr({onOrigin:e}){let{data:t}=at({capName:`network-access`});return i(u,{children:(t??[]).map(t=>i(Qr,{addonId:t.addonId,onOrigin:e},t.addonId))})}function Qr({addonId:e,onOrigin:t}){let{data:n}=Mt({addonId:e},{refetchInterval:Yr,retry:!1});return a(()=>{let e=n?he.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 $r=typeof ft==`function`,ei=`Track flags arrive with the next server update`;function ti(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var ni=$r?ft:ti;function ri(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}}c();function ii({label:t,hint:n,checked:r,disabled:a,title:o,icon:s,onToggle:c}){return e(K,{variant:`unstyled`,type:`button`,role:`switch`,"aria-checked":r,"aria-label":t,disabled:a,title:o,onClick:c,className:`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left transition-colors disabled:opacity-50 ${r?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[i(`span`,{className:r?`text-primary`:`text-foreground-subtle`,children:s}),e(`span`,{className:`min-w-0 flex-1`,children:[i(`span`,{className:`block text-[11px] font-medium text-foreground`,children:t}),i(`span`,{className:`block text-[10px] text-foreground-subtle`,children:n})]}),i(`span`,{"aria-hidden":`true`,className:`h-4 w-7 shrink-0 rounded-full p-0.5 transition-colors ${r?`bg-primary`:`bg-border`}`,children:i(`span`,{className:`block h-3 w-3 rounded-full bg-white transition-transform ${r?`translate-x-3`:``}`})})]})}function ai({deviceId:t,trackId:n,markForTrain:r,debug:a,favourited:s,onChange:c}){let{t:l}=J(),u=ni(),d=te(),[f,p]=o(null),m=f?.markForTrain??r===!0,h=f?.debug??a===!0,g=f?.favourited??s===!0,_=!$r||u.isPending,v=$r?void 0:ei,y=e=>{_||(async()=>{try{let r=ri(await u.mutateAsync({deviceId:t,trackId:n,flags:e}));if(!r)return;p(r),c?.(r)}catch(e){let t=e instanceof Error?e.message:``;await d({title:l(`detectionIntelligence.trackFlagToggles.couldNotUpdateThisTrack`,`Could not update this track`),message:t===``?l(`detectionIntelligence.trackFlagToggles.couldNotUpdateThisTrack2`,`Could not update this track. Check the server logs.`):t,variant:`danger`})}})()};return e(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[i(ii,{label:l(`detectionIntelligence.trackFlagToggles.markForTraining`,`Mark for training`),hint:l(`detectionIntelligence.trackFlagToggles.keepsThisTrackAndIts`,`Keeps this track and its media past retention`),checked:m,disabled:_,...v===void 0?{}:{title:v},icon:i(ie,{className:`h-4 w-4`}),onToggle:()=>y({markForTrain:!m})}),i(ii,{label:l(`detectionIntelligence.trackFlagToggles.debug`,`Debug`),hint:l(`detectionIntelligence.trackFlagToggles.flagThisTrackForDiagnostic`,`Flag this track for diagnostic attention`),checked:h,disabled:_,...v===void 0?{}:{title:v},icon:i(k,{className:`h-4 w-4`}),onToggle:()=>y({debug:!h})}),i(ii,{label:l(`detectionIntelligence.trackFlagToggles.favourited`,`Favourited`),hint:l(`detectionIntelligence.trackFlagToggles.keepsThisTrackAndIts`,`Keeps this track and its media past retention`),checked:g,disabled:_,...v===void 0?{}:{title:v},icon:i(z,{className:`h-4 w-4`}),onToggle:()=>y({favourited:!g})})]})}function oi(e){let t=e.deviceKey===void 0?e.nodeId:`${e.nodeId} · ${e.deviceKey}`;return e.modelId===void 0?t:`${t} (${e.modelId})`}function si(e){let t=e?.openedPlacement,n=e?.closedPlacement;if(t!==void 0&&n!==void 0){let e=oi(t),r=oi(n);return e===r?[{kind:`detected`,value:e}]:[{kind:`opened`,value:e},{kind:`closed`,value:r}]}return t===void 0?n===void 0?[]:[{kind:`closed`,value:oi(n)}]:[{kind:`opened`,value:oi(t)}]}var ci=100,li={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},ui=e=>e<0?0:e>1?1:e,di=e=>Math.round(e*100)/100;function fi(e,t,n){if(e.length===0||t===null)return li;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return li;let a=pe(e.map(e=>({x:e.x/r,y:e.y/i,w:e.bbox.w/r,h:e.bbox.h/i})),n?.maxPoints===void 0?void 0:{maxPoints:n.maxPoints}).nodes.map(e=>({x:di(e.x*ci),y:di(e.y*ci)})),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:di(ui(e.x/r)*ci),y:di(ui(e.y/i)*ci),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=ui(t.bbox.w/r)*ui(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:di(ui(u.bbox.x/r)*ci),y:di(ui(u.bbox.y/i)*ci),w:di(ui(u.bbox.w/r)*ci),h:di(ui(u.bbox.h/i)*ci)}:null}}c();var pi=15e3,mi=E();function hi({url:e,label:t}){let{src:n,failed:r}=bn(e);return n===null?i(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?i(S,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):i(V,{className:`h-4 w-4 animate-spin text-foreground-subtle opacity-70`})}):i(`img`,{src:n,alt:t,className:`h-full w-full object-cover`})}var gi=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),_i=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function vi(e){let[t,n]=o(null);return a(()=>{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 yi({overlay:t,onPickSnapshot:n}){let{t:r}=J();return!t.polyline&&!t.peakBox&&t.snapshots.length===0?null:e(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[t.peakBox&&i(`rect`,{x:t.peakBox.x,y:t.peakBox.y,width:t.peakBox.w,height:t.peakBox.h,fill:`none`,stroke:`var(--color-warning)`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),t.polyline&&i(`polyline`,{points:t.polyline,fill:`none`,stroke:`var(--color-info)`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),t.points.map((e,t)=>i(`circle`,{cx:e.x,cy:e.y,r:1,fill:`var(--color-info)`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),t.snapshots.map((e,t)=>i(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`var(--color-info)`,fillOpacity:.95,stroke:`var(--color-background)`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:n?`pointer-events-auto cursor-pointer`:void 0,onClick:n?t=>{t.stopPropagation(),n(e.mediaId)}:void 0,children:i(`title`,{children:r(`detectionIntelligence.eventDetailPanel.snapshotCheckpointClickToView`,`Snapshot checkpoint — click to view this frame`)})},`snap-${String(e.mediaId)}-${String(t)}`)),t.start&&i(`circle`,{cx:t.start.x,cy:t.start.y,r:2.4,fill:`var(--color-success)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),t.end&&i(`circle`,{cx:t.end.x,cy:t.end.y,r:2.4,fill:`var(--color-danger)`,stroke:`var(--color-background)`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function X({label:t,value:n,mono:r,wrap:a}){return e(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[i(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:t}),i(`span`,{className:`min-w-0 ${a?`break-words`:`truncate`} text-right text-xs font-medium text-foreground ${r?`font-mono text-[11px]`:``}`,title:n,children:n})]})}function bi({row:t,cameraName:s,deleteAvailable:c,onClose:l,onDeleted:d,onFlagsChanged:f}){let{t:p}=J(),m=ue(),h=te(),g=M(),_=gr(),v=t!==null,y=t?.deviceId??0,b=t?.trackId??``,x=t?.timestamp??0,C=t?.windowMs??0,{data:w}=Lt({deviceId:y,trackId:b},{enabled:v}),{data:T}=nt({trackId:b,deviceId:y},{enabled:v}),E=w?.bestEventId===void 0?void 0:Number(w.bestEventId),{data:D}=xt({ownerType:`object`,eventId:E??0,deviceId:y},{enabled:v&&E!==void 0&&Number.isFinite(E)}),{data:O}=Pt({deviceId:y},{enabled:v}),k=(O??[]).find(e=>e.addonId!==void 0)?.addonId,{data:A}=Dt({deviceId:y,since:x-pi,until:x+C+pi,provider:k??``},{enabled:v&&k!==void 0}),[j,N]=o(null),[P,I]=o(!1),{publicOrigin:L,probes:ee}=Xr(v);a(()=>{N(null)},[y,b]);let R=n(()=>{let e=T??[],t=D??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[T,D]),z=j??R,ne=bn(z?z.url:void 0),B=n(()=>{let e=new Set,t=[];for(let n of[...D??[],...T??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[D,T]),re=n(()=>B.find(e=>gi.has(e.kind))??null,[B]),ie=vi(bn(re?re.url:void 0).src),ae=n(()=>fi(w?.positions??[],ie,{snapshots:(w?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[w?.positions,w?.snapshots,ie]),oe=r(e=>{let t=B.find(t=>t.mediaId===e);t&&N(t)},[B]);if(t===null)return null;let ce=ne.src,le=z?.kind,de=le!==void 0&&_i.has(le)&&ie!==null&&(w?.positions.length??0)>=2,fe=A&&A.length>0?A[0]:null,H=()=>{fe&&(I(!0),(async()=>{try{let e=await m.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:fe.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{h({title:p(`detectionIntelligence.eventDetailPanel.clipUnavailable`,`Clip unavailable`),message:p(`detectionIntelligence.eventDetailPanel.couldNotResolveClipPlayback`,`Could not resolve clip playback. Check the server logs.`),variant:`warning`})}finally{I(!1)}})())},pe=()=>{!c||_.isPending||(async()=>{if(await g({title:p(`detectionIntelligence.eventDetailPanel.deleteTrack`,`Delete track`),message:p(`detectionIntelligence.eventDetailPanel.deleteThisTrackAndEvery`,`Delete this track and every image and clip captured for it? This cannot be undone.`),confirmLabel:p(`common.delete`,`Delete`),variant:`danger`}))try{await _.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),d()}catch{await h({title:p(`detectionIntelligence.eventDetailPanel.deleteFailed`,`Delete failed`),message:p(`detectionIntelligence.eventDetailPanel.failedToDeleteThisTrack`,`Failed to delete this track. Check the server logs.`),variant:`danger`})}})()},me=Math.round(t.importance*100),he=w?.importanceReason?`${String(me)}% · ${w.importanceReason}`:`${String(me)}%`,ge=w?.zonesVisited&&w.zonesVisited.length>0?w.zonesVisited.join(`, `):`—`,_e=w?.audioLabels&&w.audioLabels.length>0?w.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,ve=_e===void 0?`—`:_e.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),ye=w?w.totalDistance.toFixed(2):`—`,U=Jr(w?.previewMissReason),be=un(w?w.firstSeen:x),xe=w?un(w.lastSeen):`—`,Se=si(w),W={detected:p(`detectionIntelligence.eventDetailPanel.detectedOn`,`Detected on`),opened:p(`detectionIntelligence.eventDetailPanel.openedOn`,`Opened on`),closed:p(`detectionIntelligence.eventDetailPanel.closedOn`,`Closed on`)};return i(Re,{open:!0,onOpenChange:e=>!e&&l(),children:e(De,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":p(`detectionIntelligence.eventDetailPanel.eventDetail`,`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:[i(`header`,{className:`flex shrink-0 items-start gap-2 border-b border-border py-3 pl-4 pr-10`,children:e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,ar(t)?e(`span`,{className:`text-foreground-subtle`,children:[` · `,ar(t)]}):null]}),i(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:s})]})}),e(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[ce?i(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:i(dn,{src:ce,alt:p(`detectionIntelligence.eventDetailPanel.keyFrameFrom`,`Key frame from {{cameraName}}`,{cameraName:s}),fit:`natural`,className:`w-full`,overlay:de?i(yi,{overlay:ae,onPickSnapshot:oe}):void 0})}):i(`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:ne.failed?e(u,{children:[i(S,{className:`h-8 w-8 opacity-60`}),i(`span`,{className:`text-[11px]`,children:p(`detectionIntelligence.eventDetailPanel.keyFrameMediaUnavailable`,`Key-frame media unavailable`)})]}):i(V,{className:`h-6 w-6 animate-spin opacity-70`})}),B.length>0&&i(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:B.map(t=>{let n=Vr(t.kind),r=Hr(mi,t.url),a=L?Hr(L,t.url):null;return e(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[i(K,{variant:`unstyled`,type:`button`,onClick:()=>N(t),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${n} · ${un(t.timestamp)}`,children:i(hi,{url:t.url,label:n})}),e(`figcaption`,{className:`min-w-0 px-0.5`,children:[i(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:n,children:n}),i(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:un(t.timestamp),children:yn(t.timestamp)})]}),i(Rr,{localUrl:r,publicUrl:a})]},t.mediaId)})}),ee,fe&&e(K,{variant:`secondary`,onClick:H,disabled:P,children:[P?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(F,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.eventDetailPanel.viewClip`,`View clip`)]}),i(ai,{deviceId:t.deviceId,trackId:t.trackId,...(w?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:w?.markForTrain??t.markForTrain},...(w?.debug??t.debug)===void 0?{}:{debug:w?.debug??t.debug},...(w?.favourited??t.favourited)===void 0?{}:{favourited:w?.favourited??t.favourited},onChange:f}),U!==null&&e(`div`,{className:`rounded-lg border border-warning/40 bg-warning/8 px-3 py-2`,children:[i(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:p(`detectionIntelligence.eventDetailPanel.bestShot`,`Best shot`)}),i(`p`,{className:`mt-0.5 text-xs text-foreground`,children:U.sentence}),i(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:U.raw})]}),e(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[i(X,{label:p(`detectionIntelligence.eventDetailPanel.camera`,`Camera`),value:s}),Se.map(e=>i(X,{label:W[e.kind],value:e.value,mono:!0,wrap:!0},e.kind)),i(X,{label:p(`detectionIntelligence.eventDetailPanel.class`,`Class`),value:t.className}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.label`,`Label`),value:t.label??`—`}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.subLabel`,`Sub-label`),value:t.subLabel??`—`}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.importance`,`Importance`),value:he}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.zonesVisited`,`Zones visited`),value:ge}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.audioHeard`,`Audio heard`),value:ve}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.totalDistance`,`Total distance`),value:ye}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.firstSeen`,`First seen`),value:be}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.lastSeen`,`Last seen`),value:xe}),i(X,{label:p(`detectionIntelligence.eventDetailPanel.track`,`Track`),value:t.trackId,mono:!0})]})]}),i(`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:i(`span`,{title:c?void 0:mr,children:e(K,{variant:`secondary`,onClick:pe,disabled:!c||_.isPending,children:[_.isPending?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(se,{className:`h-3.5 w-3.5`}),` `,p(`detectionIntelligence.eventDetailPanel.deleteTrack`,`Delete track`)]})})})]})})}function xi(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 Si({row:t,cameraName:n,nowMs:r,onOpenDetail:a,selected:o=!1,onToggleSelect:s,score:c,provenance:l,footer:u}){let{t:d}=J(),f=bn(t.mediaId===void 0?xn(`track`,t.trackId):Sn(t.mediaId)),p=Math.round(t.importance*100),m=c===void 0?void 0:Math.round(c*100),h=xi(t.windowMs),g=()=>a(t),_=Kr(l);return e(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${o?`border-primary ring-1 ring-primary`:`border-border`}`,children:[e(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[f.src?i(`img`,{src:f.src,alt:d(`detectionIntelligence.eventCard.eventFrom`,`Event from {{cameraName}}`,{cameraName:n}),onClick:g,className:`h-full w-full cursor-zoom-in object-cover`}):i(K,{variant:`unstyled`,type:`button`,onClick:g,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:f.failed?d(`detectionIntelligence.eventCard.keyEventMediaUnavailable`,`Key-event media unavailable`):d(`detectionIntelligence.eventCard.noKeyEventMedia`,`No key-event media`),children:i(S,{className:`h-6 w-6 opacity-60`})}),s&&i(K,{variant:`unstyled`,type:`button`,onClick:e=>{e.stopPropagation(),s(ur(t.deviceId,t.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":o?d(`detectionIntelligence.eventCard.deselect`,`Deselect`):d(`detectionIntelligence.eventCard.select`,`Select`),children:o?i(be,{className:`h-4 w-4 text-primary`}):i(R,{className:`h-4 w-4`})}),m!==void 0&&e(`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:d(`detectionIntelligence.eventCard.clipSemanticMatchScore`,`CLIP semantic-match score`),children:[String(m),`%`]}),p>0&&i(`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(p)}),_!==null&&i(`span`,{className:`absolute bottom-1 right-1 z-10 rounded px-1.5 py-0.5 text-[10px] font-semibold text-white ${_.tone===`warning`?`bg-warning/90`:`bg-black/70`}`,title:_.title,children:_.label}),(t.markForTrain===!0||t.retrainStatus===`trained`||t.debug===!0||t.favourited===!0)&&e(`span`,{className:`absolute bottom-1 left-1 z-10 flex gap-1`,children:[t.markForTrain===!0&&i(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.markedForTraining`,`Marked for training`),"aria-label":d(`detectionIntelligence.eventCard.markedForTraining`,`Marked for training`),children:i(ie,{className:`h-3 w-3`})}),t.retrainStatus===`trained`&&t.markForTrain!==!0&&i(`span`,{className:`rounded bg-success/85 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.trainingComplete`,`Training complete`),"aria-label":d(`detectionIntelligence.eventCard.trainingComplete`,`Training complete`),"data-testid":`retrain-status-trained`,children:i(re,{className:`h-3 w-3`})}),t.debug===!0&&i(`span`,{className:`rounded bg-black/70 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.flaggedForDebug`,`Flagged for debug`),"aria-label":d(`detectionIntelligence.eventCard.flaggedForDebug`,`Flagged for debug`),children:i(k,{className:`h-3 w-3`})}),t.favourited===!0&&i(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:d(`detectionIntelligence.eventCard.favourited`,`Favourited`),"aria-label":d(`detectionIntelligence.eventCard.favourited`,`Favourited`),children:i(z,{className:`h-3 w-3`})})]})]}),e(K,{variant:`unstyled`,type:`button`,onClick:g,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[e(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:t.className,children:[t.className,ar(t)?e(`span`,{className:`text-foreground-subtle`,children:[` · `,ar(t)]}):null]}),i(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:n,children:n}),e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:ln(t.timestamp,r)}),h&&i(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:h})]})]}),u!==void 0&&i(`div`,{className:`px-2 pb-1.5`,children:u})]})}function Ci({row:t,onSeek:n,onOpenDetail:r,size:a=0,onToggleSelect:o,selected:s=!1}){let{t:c}=J(),l=bn(t.mediaId===void 0?xn(`track`,t.trackId):Sn(t.mediaId)),u=Math.round(t.importance*100),d=ar(t),f=new Date(t.timestamp).toLocaleTimeString();return e(`div`,{className:`flex w-full items-center gap-2 rounded-md border bg-surface hover:bg-surface-hover ${s?`border-primary ring-1 ring-primary`:`border-border`}`,"data-testid":`event-row`,children:[o&&i(D,{className:`ml-2 shrink-0`,checked:s,onChange:()=>o(ur(t.deviceId,t.trackId)),"aria-label":c(`detectionIntelligence.eventRow.select`,`Select {{className}} at {{time}}`,{className:t.className,time:f})}),i(K,{variant:`unstyled`,type:`button`,onClick:()=>r(t),className:`aspect-video ${Dr[a]} shrink-0 overflow-hidden rounded-l-md bg-surface-hover`,"aria-label":c(`detectionIntelligence.eventRow.openDetail`,`Open event details`),children:l.src?i(`img`,{src:l.src,alt:``,className:`h-full w-full object-cover`}):i(`span`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:i(S,{className:`h-4 w-4 opacity-60`})})}),e(K,{variant:`unstyled`,type:`button`,onClick:()=>n(t.timestamp),className:`flex min-w-0 flex-1 items-center gap-2 py-1 pr-2 text-left`,"aria-label":c(`detectionIntelligence.eventRow.seek`,`Play {{className}} at {{time}}`,{className:t.className,time:f}),children:[e(`span`,{className:`min-w-0 flex-1`,children:[e(`span`,{className:`block truncate text-[12px] font-medium text-foreground`,children:[t.className,d?e(`span`,{className:`text-foreground-subtle`,children:[` · `,d]}):null]}),i(`span`,{className:`block text-[11px] tabular-nums text-foreground-subtle`,children:f})]}),u>0&&i(`span`,{className:`shrink-0 rounded bg-surface-hover px-1.5 py-0.5 text-[10px] font-semibold tabular-nums text-foreground-muted`,children:String(u)})]}),e(`div`,{className:`flex shrink-0 items-center gap-0.5 pr-1`,children:[i(wi,{icon:ne,label:c(`detectionIntelligence.eventRow.details`,`Details`),onClick:()=>r(t)}),i(wi,{icon:j,label:c(`detectionIntelligence.eventRow.play`,`Play`),onClick:()=>n(t.timestamp)})]})]})}function wi({icon:t,label:n,onClick:r}){return e(Ct,{children:[i(lt,{children:i(Ut,{variant:`ghost`,size:`sm`,icon:t,"aria-label":n,onClick:r})}),i(dt,{children:n})]})}var Ti=120*1e3;function Ei(e,t,n=Ti){let r=[...e].sort((e,n)=>t(n)-t(e)),i=[];for(let e of r){let r=i[i.length-1],a=t(e);r!==void 0&&r.fromMs-a<=n?(r.events.push(e),r.fromMs=a):i.push({fromMs:a,toMs:a,events:[e]})}return i}c();function Di(){let[e,n]=o(!1),i=t(null),[s,c]=o(0),l=r(e=>{i.current!==e&&(i.current=e,c(e=>e+1))},[]);return a(()=>{let e=i.current;if(!e||typeof IntersectionObserver>`u`){n(!1);return}let t=new IntersectionObserver(e=>{let t=e[e.length-1];t&&n(!t.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[s]),{ref:l,scrolledPast:e}}c();var Oi=[`events-feed`],ki=60,Ai=[{value:`importance`,labelKey:`detectionIntelligence.eventsSection.sortImportance`,icon:ye},{value:`time`,labelKey:`detectionIntelligence.eventsSection.sortRecent`,icon:m}];function ji({deviceId:t,onSeek:r,window:s,rowFilter:c,onListChange:d,layout:f=`cards`,toolbarTarget:p}={}){let{t:m}=J(),h=l(),g=te(),_=M(),[b,S]=o(mn),[C,w]=o(new Set),[E,O]=o(new Set),[k,A]=o(new Set),[j,N]=Te({storageKey:Er,options:Tr,defaultSize:0}),P=Or(j),[F,I]=o(0),[L,ee]=o(`time`),[R,z]=o(new Set),[ne,B]=o(null),[re,ie]=o(()=>Date.now());a(()=>{let e=setInterval(()=>ie(Date.now()),6e4);return()=>clearInterval(e)},[]);let ae=n(()=>fr({fromMs:b.fromMs,toMs:b.toMs},re),[b.fromMs,b.toMs,re]),oe=s?.since??ae.since,ce=s?.until??ae.until,le=Di(),{pending:ue,refreshNow:de}=Sr({paused:ne!==null||R.size>0||le.scrolledPast}),{data:fe=[]}=We({isCamera:!0,projection:`slim`}),H=n(()=>t===void 0?fe:fe.filter(e=>e.id===t),[fe,t]),pe=n(()=>H.map(e=>e.id),[H]),{data:me,isLoading:he}=$e({deviceIds:pe},{enabled:pe.length>0,staleTime:5*6e4}),ge=n(()=>Pr(me??[],C),[me,C]),_e=gr(),ye=_e.isPending,{rows:U,isLoading:be}=yr({deviceIds:pe,since:oe,until:ce,minImportance:F>0?F:void 0,classFilter:E.size===1?[...E][0]:void 0}),xe=n(()=>{let e=new Map;for(let t of H??[])e.set(t.id,t.name);return e},[H]),Se=e=>xe.get(e)??m(`detectionIntelligence.cameraFallback`,{id:String(e)}),W=n(()=>_n(U).map(e=>({id:e,name:Se(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[U,xe]),Ce=n(()=>cr(lr(U,{cameras:C,classes:E,minImportance:F}).filter(e=>!k.has(e.className)&&(c===void 0||c(e))),L),[U,C,E,k,F,L,c]),we=n(()=>U.map(e=>e.className),[U]),Ee=E.size>0||k.size>0||F>0;a(()=>{d?.({rows:Ce,narrowed:Ee})},[Ce,Ee,d]);let De=pn(Ce,ki,n(()=>JSON.stringify([[...C].sort((e,t)=>e-t),[...E].sort(),[...k].sort(),F,L,oe,ce]),[C,E,k,F,L,oe,ce])),Oe=()=>{h.invalidateQueries({queryKey:Oi})},ke=()=>z(new Set),Ae=Ce.map(e=>ur(e.deviceId,e.trackId)),je=Ae.length>0&&Ae.every(e=>R.has(e)),Me=()=>z(je?new Set:new Set(Ae));function Ne(e){z(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function Pe(){if(R.size===0||!pr)return;let e=dr(U,R),t=[...e.values()].reduce((e,t)=>e+t.length,0);t!==0&&(async()=>{await _({title:m(`detectionIntelligence.eventsSection.deleteTitle`,{count:t}),message:m(`detectionIntelligence.eventsSection.deleteMessage`,{count:t}),confirmLabel:m(`common.delete`,`Delete`),variant:`danger`})&&Fe(e)})()}function Fe(e){let t=[...e];Promise.allSettled(t.map(([e,t])=>_e.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{Oe();let n=[],r=new Set;if(e.forEach((e,i)=>{let a=t[i];if(!a)return;let[o,s]=a;if(e.status===`fulfilled`)for(let e of s)r.add(ur(o,e));else n.push(o)}),z(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),n.length>0){let e=n.map(e=>Se(e)).join(`, `);g({title:m(`detectionIntelligence.eventsSection.someTracksWereNotDeleted`,`Some tracks were not deleted`),message:m(`detectionIntelligence.eventsSection.failedToDeleteTracksOn`,`Failed to delete tracks on: {{names}}. They remain selected — retry, or check the server logs.`,{names:e}),variant:`danger`})}})}let Ie=n(()=>Ei(De.pageItems,e=>e.timestamp),[De.pageItems]),Le=Ce.length!==U.length,Re=t=>i(Si,{row:t,cameraName:Se(t.deviceId),nowMs:re,selected:R.has(ur(t.deviceId,t.trackId)),onToggleSelect:Ne,onOpenDetail:B,footer:r===void 0?void 0:e(K,{variant:`ghost`,onClick:()=>r(t.timestamp),children:[i(ve,{className:`h-3.5 w-3.5`}),m(`detectionIntelligence.eventsSection.showInReview`,`Show in Review`)]})},ur(t.deviceId,t.trackId)),ze=f===`rows`&&r!==void 0,Be=e=>ze?i(Ci,{row:e,onSeek:r,onOpenDetail:B,size:P,selected:R.has(ur(e.deviceId,e.trackId)),onToggleSelect:Ne},ur(e.deviceId,e.trackId)):Re(e),Ve=e=>ze?i(`div`,{className:`flex flex-col gap-1`,"data-testid":`events-grid`,children:e.map(Be)}):i(zt,{status:`ready`,testId:`events-grid`,children:e.map(Be)}),He=e(`div`,{className:p===void 0?`flex flex-wrap items-center gap-1.5`:`contents`,children:[s===void 0&&i(cn,{onChange:S}),t===void 0&&i(hn,{cameras:W,selected:C,onChange:w}),i(kr,{groups:ge,selected:E,onChange:O,loading:he}),ze&&i(wr,{classes:we,hidden:k,onChange:A}),e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(`span`,{children:m(`detectionIntelligence.eventsSection.minScore`,`Min score`)}),i(v,{min:0,max:1,step:.05,value:F,onChange:e=>I(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":m(`detectionIntelligence.eventsSection.minimumImportance`,`Minimum importance`)}),i(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(F*100)})]}),i(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Ai.map(t=>{let n=t.icon;return e(`button`,{type:`button`,onClick:()=>ee(t.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${L===t.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[i(n,{className:`h-3.5 w-3.5`}),` `,m(t.labelKey)]},t.value)})}),!be&&i(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:Le?m(`detectionIntelligence.eventsSection.ofEvents`,`{{value1}} of {{value2}} events`,{value1:String(Ce.length),value2:String(U.length)}):m(`detectionIntelligence.eventsSection.eventCount`,{count:Ce.length})})]});return e(`div`,{className:`relative space-y-3`,children:[p===void 0?He:p!==null&&Jt(He,p),R.size>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[i(`span`,{className:`text-xs font-medium text-foreground`,children:m(`common.selectedCount`,{count:R.size})}),e(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[i(`span`,{title:pr?void 0:`Track deletion arrives with the next server update`,children:e(K,{variant:`secondary`,onClick:Pe,disabled:!pr||ye,children:[ye?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(se,{className:`h-3.5 w-3.5`}),` `,m(`common.delete`,`Delete`)]})}),i(K,{variant:`ghost`,onClick:ke,disabled:ye,children:i(y,{className:`h-3.5 w-3.5`})})]})]}),ue&&i(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:i(`button`,{type:`button`,onClick:de,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:m(`detectionIntelligence.eventsSection.newEventsRefresh`,`New events — refresh`)})}),be?i(zt,{status:`pending`,pendingMessage:`Loading events…`,testId:`events-grid`}):Ce.length===0?i(yt,{icon:x,title:Le?m(`detectionIntelligence.eventsSection.nothingMatchesTheFilter`,`Nothing matches the filter`):m(`detectionIntelligence.eventsSection.noKeyEventsInThis`,`No key events in this window`),description:Le?m(`detectionIntelligence.eventsSection.widenTheDateRangeClear`,`Widen the date range, clear cameras or kinds, or lower the min score.`):m(`detectionIntelligence.eventsSection.capturedTracksAppearHereWhen`,`Captured tracks appear here when the pipeline scores a key event.`)}):e(u,{children:[i(`div`,{ref:le.ref,"aria-hidden":!0,className:`h-0`}),ze&&e(`div`,{className:`flex flex-wrap items-center gap-3`,children:[e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(D,{checked:je,onChange:Me,"data-testid":`event-rows-select-all`}),i(`span`,{children:m(`detectionIntelligence.eventsSection.selectAll`,`Select all ({{count}})`,{count:Ce.length})})]}),e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(T,{className:`h-3.5 w-3.5`}),i(`span`,{children:m(`detectionIntelligence.eventsSection.rowSize`,`Size`)}),i(v,{min:0,max:Tr.length-1,step:1,value:P,onChange:e=>N(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"data-testid":`event-row-size`,"aria-label":m(`detectionIntelligence.eventsSection.rowSizeLabel`,`Event row size`)})]})]}),!ze&&t!==void 0&&L===`time`?Ie.map(t=>e(`div`,{className:`space-y-1.5`,children:[i(`div`,{className:`text-[11px] font-medium text-foreground-subtle`,children:m(`detectionIntelligence.eventsSection.clusterHeading`,{count:t.events.length,time:new Date(t.toMs).toLocaleString()})}),Ve(t.events)]},t.toMs)):Ve(De.pageItems),i(gn,{currentPage:De.page,totalItems:De.totalItems,pageSize:De.pageSize,onPageChange:De.setPage,itemNoun:`events`})]}),ne&&i(bi,{row:ne,cameraName:Se(ne.deviceId),deleteAvailable:pr,onClose:()=>B(null),onDeleted:()=>{Oe(),B(null)},onFlagsChanged:e=>{B(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}var Mi={zone:null,identity:`any`,debug:!1};function Ni(e){return new Map(e.map(e=>[e.trackId,e]))}function Pi(e){let t=new Set;for(let n of e)for(let e of n.zoneNames??[])t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function Fi(e,t){if(t===`any`)return!0;let n=e.classes??[];return t===`face`?e.hasFace===!0||n.includes(`face`):n.includes(`plate`)}function Ii(e,t){return n=>{if(e.debug&&n.debug!==!0)return!1;if(e.zone===null&&e.identity===`any`)return!0;let r=t.get(n.trackId);return r===void 0?!0:e.zone!==null&&!(r.zoneNames??[]).includes(e.zone)?!1:Fi(r,e.identity)}}function Li(e){return e.zone!==null||e.identity!==`any`}function Ri(e,t,n){return Li(t)?e.filter(e=>!n.has(e.trackId)).length:0}function zi(e){return e.map(e=>({atMs:e.timestamp,kind:e.className===`audio`?`audio`:`object`}))}var Bi=`/addon/training`;function Vi(){let{t}=J(),n=nn();return e(pt,{className:`flex flex-col gap-3 border-border bg-surface p-3 sm:flex-row sm:items-center sm:gap-4`,"data-testid":`events-feed-retrain-cta`,children:[e(`div`,{className:`flex min-w-0 flex-1 items-start gap-2.5`,children:[i(ie,{className:`mt-0.5 h-4 w-4 shrink-0 text-primary`,"aria-hidden":!0}),e(`div`,{className:`min-w-0 space-y-0.5`,children:[i(`p`,{className:`text-xs font-medium text-foreground`,children:t(`detectionIntelligence.retrainTabCallout.trainingFromThisFeed`,`Training from this feed`)}),i(`p`,{className:`${de} leading-relaxed`,children:t(`detectionIntelligence.retrainTabCallout.markATrackWithThe`,`Mark a track with the graduation-cap control on its card. On Training you correct frames, build collections, and start cloud fine-tunes.`)})]})]}),i(K,{variant:`outline`,size:`sm`,className:`shrink-0 self-start sm:self-center`,onClick:()=>n(Bi),children:t(`detectionIntelligence.retrainTabCallout.openTraining`,`Open Training`)})]})}c();var Hi=50,Ui=350,Wi=[{value:`loose`,labelKey:`detectionIntelligence.semanticEventSearch.looseLabel`,titleKey:`detectionIntelligence.semanticEventSearch.looseTitle`},{value:`balanced`,labelKey:`detectionIntelligence.semanticEventSearch.balancedLabel`,titleKey:`detectionIntelligence.semanticEventSearch.balancedTitle`},{value:`strict`,labelKey:`detectionIntelligence.semanticEventSearch.strictLabel`,titleKey:`detectionIntelligence.semanticEventSearch.strictTitle`}];function Gi(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 Ki({deviceId:r}){let s=t(null);Ce(s);let{t:c}=J(),[l,u]=o(``),[d,p]=o(`loose`),[m,h]=o(null),[g,_]=o(null),v=r??g,[b,x]=o(null),S=Ne(l,Ui).trim(),C=S.length>0,[w,T]=o(()=>Date.now());a(()=>{let e=setInterval(()=>T(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:E=[]}=We({isCamera:!0,projection:`slim`}),D=n(()=>{let e=new Map;for(let t of E)e.set(t.id,t.name);return e},[E]),O=e=>D.get(e)??c(`detectionIntelligence.cameraFallback`,{id:String(e)}),k=n(()=>E.map(e=>e.id),[E]),{data:A}=$e({deviceIds:k},{enabled:k.length>0,staleTime:5*6e4}),j=n(()=>Nr(A??[],new Set(v===null?[]:[v])),[A,v]);a(()=>{m!==null&&(j.some(e=>e.kind===m)||h(null))},[j,m]);let{data:M,isFetching:N,isError:F,error:I}=Tt({text:S,strictness:d,limit:Hi,classFilter:m??void 0,deviceId:v??void 0},{enabled:C}),L=n(()=>[...M??[]].sort((e,t)=>t.score-e.score).map(e=>({...Gi(e),score:e.score})),[M]);function ee(e){h(t=>t===e?null:e)}return e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(`div`,{className:`relative min-w-[16rem] flex-1`,children:[i(f,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),i(Ke,{ref:s,type:`text`,value:l,onChange:e=>u(e.target.value),placeholder:c(`detectionIntelligence.semanticEventSearch.semanticSearchDescribeWhatYou`,`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":c(`detectionIntelligence.semanticEventSearch.semanticEventSearch`,`Semantic event search`)}),l&&i(`button`,{type:`button`,onClick:()=>u(``),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":c(`detectionIntelligence.semanticEventSearch.clearSearch`,`Clear search`),children:i(y,{className:`h-3.5 w-3.5`})})]}),N&&C&&i(V,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),e(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[i(`div`,{className:`flex items-center gap-1`,children:j.map(e=>i(`button`,{type:`button`,onClick:()=>ee(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${m===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:It(e)},e.kind))}),r===void 0&&e(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(`span`,{children:c(`detectionIntelligence.semanticEventSearch.camera`,`Camera`)}),i(P,{value:v===null?``:String(v),onChange:e=>_(e.target.value===``?null:Number(e.target.value)),className:`h-7 text-xs`,"aria-label":c(`detectionIntelligence.semanticEventSearch.filterByCamera`,`Filter by camera`),options:[{value:``,label:c(`detectionIntelligence.semanticEventSearch.all`,`All`)},...E.map(e=>({value:String(e.id),label:e.name}))]})]}),e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(`span`,{children:c(`detectionIntelligence.semanticEventSearch.match`,`Match`)}),i(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Wi.map(e=>i(`button`,{type:`button`,onClick:()=>p(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${d===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:c(e.titleKey),children:c(e.labelKey)},e.value))})]}),C&&!N&&!F&&i(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:c(`common.matches`,{count:L.length})})]})]}),C&&e(`div`,{className:`space-y-3`,children:[F&&e(`p`,{className:`py-4 text-xs text-danger`,children:[c(`detectionIntelligence.semanticEventSearch.searchFailed`,`Search failed:`),` `,I instanceof Error?I.message:c(`detectionIntelligence.semanticEventSearch.unknownError`,`unknown error`),`. Check that the CLIP embedding step is enabled.`]}),!F&&N&&L.length===0&&i(zt,{status:`pending`,pendingMessage:`Searching…`,testId:`semantic-events-grid`}),!F&&!N&&L.length===0&&i(zt,{status:`empty`,emptyMessage:c(`detectionIntelligence.semanticEventSearch.noSemanticMatchesForTry`,`No semantic matches for “{{debounced}}”. Try a looser match threshold or a different phrasing.`,{debounced:S}),testId:`semantic-events-grid`}),!F&&L.length>0&&i(zt,{status:`ready`,testId:`semantic-events-grid`,children:L.map(e=>i(Si,{row:e,cameraName:O(e.deviceId),nowMs:w,score:e.score,onOpenDetail:x},e.id))})]}),b&&i(bi,{row:b,cameraName:O(b.deviceId),deleteAvailable:pr,onClose:()=>x(null),onDeleted:()=>x(null)})]})}c();function qi(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return q.t(`helpers.relativeTime.justNow`);if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function Ji({row:t,cameraName:n,nowMs:r}){let{t:a}=J(),o=bn(t.keyFrameMediaId===void 0?void 0:Sn(t.keyFrameMediaId));return e(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[e(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[o.src?i(`img`,{src:o.src,alt:a(`detectionIntelligence.stationarySection.parkedOn`,`Parked {{className}} on {{cameraName}}`,{className:t.className,cameraName:n}),className:`h-full w-full object-cover`}):i(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:i(I,{className:`h-6 w-6`})}),i(`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:t.label??t.className})]}),e(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[i(`span`,{className:`truncate text-[11px] text-foreground`,children:n}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:a(`common.parkedSince`,{since:qi(r,t.becameStationaryAt)})})]})]})}function Yi({deviceId:t}={}){let{t:r}=J(),[a,s]=o(!1),c=Date.now(),{data:l=[]}=We({isCamera:!0,projection:`slim`}),u=n(()=>t===void 0?l.map(e=>e.id):[t],[l,t]),d=n(()=>{let e=new Map;for(let t of l)e.set(t.id,t.name);return e},[l]),{rows:f,unreadableCount:p}=Tn(u);return f.length===0&&p===0?null:e(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[e(K,{variant:`unstyled`,type:`button`,onClick:()=>s(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[i(a?ge:A,{className:`h-4 w-4 text-foreground-subtle`}),i(I,{className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-sm font-semibold text-foreground`,children:r(`detectionIntelligence.stationarySection.stationary`,`Stationary`)}),i(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:f.length}),i(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:r(`detectionIntelligence.stationarySection.parkedObjectsKeptOutOf`,`Parked objects — kept out of the event feed`)}),p>0?i(`span`,{className:`ml-2 text-[11px] text-warning`,children:r(`detectionIntelligence.stationarySection.unreadable`,{count:p})}):null]}),a&&i(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:f.map(e=>i(Ji,{row:e,cameraName:d.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:c},e.id))})]})}var Xi={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`},Zi={setRelation:`debug.gt.setRelation`,setPurity:`debug.gt.setPurity`,list:`debug.gt.list`},Qi=_(`/addon/pipeline-analytics/tape-export`),$i=10*6e4;function ea(e){return`${Qi}?tapeId=${encodeURIComponent(e)}`}var ta=`The server answered in a shape this build does not understand.`;function na(e){return e instanceof Error?e.message:q.t(`helpers.eventsDebugTapes.actionFailed`)}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 ra(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 ia(e,t){let n=e[t];return typeof n==`boolean`?n:null}function aa(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 oa(e){return e===`off`||e===`recording`||e===`refused`||e===`failing`||e===`unknown`}function sa(e){if(!Z(e))return null;let t=Q(e,`deviceId`),n=e.state,r=Q(e,`gapsSinceArmed`),i=ra(e,`segmentsHeld`),a=ra(e,`bytesLastHour`),o=ra(e,`bytesHeld`);if(t===null||!oa(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 ca(e){return Z(e)?aa(e.cameras,sa):null}function la(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=ia(e,`reviewed`),f=ia(e,`released`),p=aa(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 ua(e){return Z(e)?aa(e.tapes,la):null}function da(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=ia(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 fa(e){if(!Z(e))return null;let t=$(e,`tapeId`),n=Q(e,`deviceId`),r=Q(e,`fromMs`),i=Q(e,`toMs`),a=ia(e,`reviewed`),o=aa(e.lanes,da);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 pa(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 ma(e){if(!Z(e))return null;let t=e.status;if(t===`released`){let n=Q(e,`unpinned`),r=ia(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 ha(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 ga(e){switch(e.status){case`released`:case`deleted`:return null;case`already-released`:return q.t(`helpers.eventsDebugTapes.alreadyReleased`);case`not-found`:return q.t(`helpers.eventsDebugTapes.notFound`);case`pins-owed`:return q.t(`helpers.eventsDebugTapes.pinsOwed`);case`unavailable`:return q.t(`helpers.eventsDebugTapes.unavailable`,{reason:e.reason})}}function _a(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 va(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 ya(e){if(!Z(e))return null;let t=aa(e.relations,_a),n=aa(e.purities,va),r=ia(e,`truncated`);return t===null||n===null||r===null?null:{relations:t,purities:n,truncated:r}}function ba(e){if(!e.truncated)return null;let t=e.relations.length+e.purities.length;return q.t(`helpers.eventsDebugTapes.truncatedMarks`,{count:t})}function xa(e){return e.filter(e=>e.segmentsHeld===null||e.segmentsHeld>0).map(e=>({deviceId:e.deviceId,segmentsUnknown:e.segmentsHeld===null}))}function Sa(e){return e.slice(1).map((t,n)=>({trackId:e[n]??t,otherTrackId:t}))}function Ca(e){return e.flatMap((t,n)=>e.slice(n+1).map(e=>({trackId:t,otherTrackId:e})))}function wa(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 Ta(e){switch(e.state){case`off`:return q.t(`helpers.eventsDebugTapes.statusOff`);case`recording`:return q.t(`helpers.eventsDebugTapes.statusRecording`);case`refused`:return q.t(`helpers.eventsDebugTapes.statusRefused`,{reason:e.reason??q.t(`helpers.eventsDebugTapes.unknownReason`)});case`failing`:return q.t(`helpers.eventsDebugTapes.statusFailing`,{reason:e.reason??q.t(`helpers.eventsDebugTapes.unknownReason`)});case`unknown`:return q.t(`helpers.eventsDebugTapes.statusUnknown`,{reason:e.reason??q.t(`helpers.eventsDebugTapes.unknownReason`)})}}var Ea={"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 Da(e,t){let n=Ea[e]??`Refused (${e}).`;return t.length>0?`${n} ${t}`:n}function Oa(e){if(e.length===0)return null;let t=new Date(e).getTime();return Number.isFinite(t)?t:null}function ka(e){return e<1024*1024?q.t(`helpers.eventsDebugTapes.sizeKb`,{value:(e/1024).toFixed(0)}):q.t(`helpers.eventsDebugTapes.sizeMb`,{value:(e/1024/1024).toFixed(1)})}function Aa(e){return e===null?`unknown`:ka(e)}function ja(e){return e===null?`unknown`:String(e)}function Ma(e,t){let n=t.trim();return e===404?q.t(`helpers.eventsDebugTapes.exportUnknown`):e===503?n.length>0?n:q.t(`helpers.eventsDebugTapes.tapesUnavailable`):e===500?n.length>0?n:q.t(`helpers.eventsDebugTapes.exportUnreadable`):q.t(`helpers.eventsDebugTapes.downloadFailed`,{status:e})}c();function Na({cameras:t,call:n,onPromoted:r}){let{t:a}=J(),[s,c]=o(``),[l,u]=o(``),[d,f]=o(``),[p,m]=o(``),[h,g]=o(``),[_,v]=o(`auto`),[y,b]=o(!1),[x,S]=o(null),C=async()=>{let e=Number.parseInt(s===``?t[0]?.value??``:s,10),i=Oa(l),a=Oa(d);if(!Number.isFinite(e)||i===null||a===null){S(`Pick a camera and both ends of the window.`);return}b(!0),S(null);try{let t=pa(await n(Xi.promote,{deviceId:e,fromMs:i,toMs:a,scenario:p,...h.trim().length>0?{note:h.trim()}:{},..._===`day`||_===`ir`?{lighting:_}:{}}));t===null?S(ta):t.ok?(S(`Promoted ${t.tapeId}: ${String(t.frames)} frames, ${ka(t.bytes)}, ${String(t.pinnedTracks)} tracks pinned`+(t.state===`incomplete`?` — incomplete (it has gaps) and cannot become a case.`:`.`)),r()):S(Da(t.reason,t.detail))}catch(e){S(na(e))}finally{b(!1)}};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border px-3 py-2`,children:[i(`div`,{className:`w-40`,children:i(P,{value:s,options:[...t],onChange:e=>c(e.target.value),"aria-label":a(`eventsDebugTapesPromoteForm.camera`,`Camera`)})}),i(Ke,{type:`datetime-local`,"aria-label":a(`eventsDebugTapesPromoteForm.from`,`From`),value:l,onChange:e=>u(e.target.value),className:`w-48`}),i(Ke,{type:`datetime-local`,"aria-label":a(`eventsDebugTapesPromoteForm.to`,`To`),value:d,onChange:e=>f(e.target.value),className:`w-48`}),i(Ke,{"aria-label":a(`eventsDebugTapesPromoteForm.scenario`,`Scenario`),placeholder:`101-door-groups`,value:p,onChange:e=>m(e.target.value),className:`w-44`}),i(Ke,{"aria-label":a(`eventsDebugTapesPromoteForm.note`,`Note`),placeholder:a(`eventsDebugTapesPromoteForm.optionalNote`,`optional note`),value:h,onChange:e=>g(e.target.value),className:`w-52`}),i(`div`,{className:`w-28`,children:i(P,{value:_,"aria-label":a(`eventsDebugTapesPromoteForm.lighting`,`Lighting`),options:[{value:`auto`,label:a(`eventsDebugTapesPromoteForm.lightingAuto`,`Lighting: auto`)},{value:`day`,label:a(`eventsDebugTapes.dayMode`)},{value:`ir`,label:`IR`}],onChange:e=>v(e.target.value)})}),e(K,{onClick:()=>void C(),disabled:y||t.length===0,children:[y?i(V,{className:`h-3.5 w-3.5 animate-spin`}):null,` `,a(`eventsDebugTapes.promoteWindow`)]}),i(`p`,{className:`w-full text-xs text-foreground-subtle`,children:a(`eventsDebugTapesPromoteForm.aPromotedTapeMayBe`,`A promoted tape may be shared as a test case — keep the scenario slug and note free of names or other personal data.`)}),x!==null&&i(`p`,{className:`w-full text-xs text-foreground`,children:x})]})}var Pa=`pipeline-analytics`,Fa=`debug.listTracks`,Ia=`debug.analyze`,La=_(`/addon/pipeline-analytics/debug-export`);function Ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function za(e,t){let n=e[t];return typeof n==`string`?n:null}function Ba(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Va(e,t){let n=e[t];return typeof n==`boolean`?n:null}function Ha(e){return e===`error`||e===`warn`||e===`info`}function Ua(e){if(!Ra(e))return null;let t=za(e,`code`),n=za(e,`detail`),r=e.severity;return t===null||n===null||!Ha(r)?null:{code:t,severity:r,detail:n}}function Wa(e){if(!Ra(e))return null;let t=za(e,`trackId`),n=Ba(e,`deviceId`),r=za(e,`className`),i=Ba(e,`firstSeen`),a=Ba(e,`lastSeen`),o=Ba(e,`durationMs`),s=Va(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=za(e,`label`),l=za(e,`subLabel`),u=za(e,`previewMissReason`),d=Va(e,`markForTrain`),f=Va(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:Ba(e,`importance`)??0,bestEventId:za(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function Ga(e){let t=Wa(e);if(t===null||!Ra(e))return null;let n=Ba(e,`mediaCount`),r=Ba(e,`eventCount`),i=Ba(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=Ua(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...Wr(l)?{thumbnailProvenance:l}:{}}}function Ka(e){if(!Ra(e))return null;let t=Va(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=Wa(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function qa(e){if(!Ra(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=Ga(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var Ja={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 Ya(e){return Ja[e]??e}var Xa={error:0,warn:1,info:2};function Za(e){return e.toSorted((e,t)=>Xa[e.severity]-Xa[t.severity]||e.code.localeCompare(t.code))}function Qa(e){return e.length===0?La:`${La}?deviceIds=${e.join(`,`)}`}function $a(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 eo(e,t){return`${String(e)}:${t}`}function to(e,t){let n=[],r=new Set;for(let i of e){let e=eo(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}c();function no({tapeId:t,call:n,onClose:r,onChanged:a}){let{t:c}=J(),l=s({queryKey:[`events-debug`,`tapes`,`tracks`,t],queryFn:async()=>fa(await n(Xi.tracks,{tapeId:t}))}),u=l.data??null,d=s({queryKey:[`events-debug`,`tapes`,`marks`,t],enabled:u!==null,queryFn:async()=>u===null?null:ya(await n(Zi.list,{deviceId:u.deviceId,since:u.fromMs-$i,until:u.toMs+$i,limit:5e3}))}),[f,p]=o([]),[m,h]=o(``),[g,_]=o(null),v=e=>p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),y=async e=>{_(null);try{for(let[t,r]of e)await n(t,r);p([]),await d.refetch(),a()}catch(e){_(na(e))}};if(u===null)return l.isLoading?i(`p`,{className:`text-xs`,children:c(`eventsDebugTapesReview.loadingTheTape`,`Loading the tape…`)}):i(W,{message:ta});let b=u.deviceId,x=(e,t)=>y(e.map(e=>[Zi.setRelation,{deviceId:b,...e,relation:t}])),S=e=>{let t=Number.parseFloat(m),n=e===`mixed`&&Number.isFinite(t)?u.fromMs+t*1e3:void 0;return y(f.map(t=>[Zi.setPurity,{deviceId:b,trackId:t,purity:e,...n===void 0?{}:{switchAtMs:Math.round(n)}}]))},C=d.data==null?null:ba(d.data);return e(`div`,{className:`space-y-2 rounded-md border border-primary/40 px-3 py-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-xs font-medium`,children:c(`eventsDebugTapes.reviewLanes`,{id:u.tapeId,count:u.lanes.length})}),i(K,{disabled:f.length<2,onClick:()=>void x(Sa(f),`same-subject`),children:c(`eventsDebugTapesReview.sameSubject`,`Same subject`)}),i(K,{variant:`secondary`,disabled:f.length<2,onClick:()=>void x(Ca(f),`different-subjects`),children:c(`eventsDebugTapesReview.differentSubjects`,`Different subjects`)}),i(Ke,{"aria-label":c(`eventsDebugTapesReview.changedAtSFromTape`,`Changed at (s from tape start)`),placeholder:c(`eventsDebugTapesReview.changedAtS`,`changed at s`),value:m,onChange:e=>h(e.target.value),className:`w-28`}),i(K,{variant:`secondary`,disabled:f.length!==1,onClick:()=>void S(`mixed`),children:c(`eventsDebugTapesReview.mixed`,`Mixed`)}),i(K,{variant:`secondary`,disabled:f.length===0,onClick:()=>void S(`not-a-subject`),children:c(`eventsDebugTapesReview.notASubject`,`Not a subject`)}),i(K,{variant:u.reviewed?`secondary`:`primary`,onClick:()=>void y([[Xi.review,{tapeId:u.tapeId,reviewed:!u.reviewed}]]).then(()=>l.refetch()),children:u.reviewed?c(`eventsDebugTapesReview.markNotReviewed`,`Mark not reviewed`):c(`eventsDebugTapesReview.markReviewed`,`Mark reviewed`)}),i(K,{variant:`ghost`,onClick:r,children:c(`common.close`,`Close`)})]}),g!==null&&i(W,{message:g}),C!==null&&i(W,{variant:`warning`,message:C}),i(`ul`,{className:`space-y-1`,children:u.lanes.toSorted((e,t)=>e.firstT-t.firstT).map(e=>i(ro,{lane:e,marks:d.data===null||d.data===void 0?[]:wa(e.trackId,d.data),selected:f.includes(e.trackId),onToggle:()=>v(e.trackId)},e.trackId))})]})}function ro({lane:t,marks:n,selected:r,onToggle:a}){let{t:o}=J(),{src:s}=bn(t.stillStored?xn(`track`,t.trackId):void 0);return e(`li`,{className:`flex items-center gap-2 text-xs`,children:[i(D,{"aria-label":o(`eventsDebugTapesReview.select`,`select {{trackId}}`,{trackId:t.trackId}),checked:r,onChange:a}),s===null?i(`div`,{className:`h-10 w-10 rounded bg-surface-hover`}):i(`img`,{src:s,alt:t.trackId,className:`h-10 w-10 rounded object-cover`}),i(`span`,{className:`font-mono`,children:t.trackId}),i(`span`,{children:t.cls}),i(`span`,{className:`text-foreground-subtle`,children:o(`eventsDebugTapes.laneFrames`,{range:`${$a(t.firstT)} → ${$a(t.lastT)}`,count:t.boundFrames})}),!t.stillStored&&i(`span`,{className:`text-foreground-subtle`,children:o(`eventsDebugTapesReview.notStoredMarkedThroughThe`,`not stored — marked through the tape`)}),n.map(e=>i(G,{variant:`info`,children:e},e))]})}c();var io=`camstack_admin_token`;function ao(){let e=ue();return(t,n)=>e.trpcClient.addons.custom.mutate({addonId:Pa,action:t,input:n})}async function oo(e,t){let n=localStorage.getItem(io),r={};n!==null&&(r.Authorization=`Bearer ${n}`);let i=await fetch(ea(e),{headers:r});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(Ma(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 so(){let{t:e}=J(),[t,n]=o(!1);return i(Wt,{expanded:t,onExpandedChange:n,header:i(`span`,{className:`text-sm font-medium text-foreground`,children:e(`eventsDebugTapes.trackingTapes`,`Tracking tapes`)}),children:i(co,{})})}function co(){let{t}=J(),r=ao(),a=We({isCamera:!0,projection:`slim`}),c=n(()=>{let e=new Map;for(let t of a.data??[])e.set(t.id,t.name);return n=>e.get(n)??t(`cameraLoad.deviceLabel`,{deviceId:n})},[a.data,t]),l=s({queryKey:[`events-debug`,`tapes`,`status`],queryFn:async()=>ca(await r(Xi.status,{}))}),u=s({queryKey:[`events-debug`,`tapes`,`list`],queryFn:async()=>ua(await r(Xi.list,{}))}),[d,f]=o(null),[p,m]=o(null),g=async e=>{m(null);try{await oo(e.id,`${e.scenario}.tape-bundle.json.gz`)}catch(e){m(na(e))}},_=async e=>{let t=ma(await r(Xi.release,{tapeId:e.id}));if(t===null)throw Error(ta);let n=ga(t);if(n!==null)throw Error(n);await u.refetch()},v=async e=>{let t=ha(await r(Xi.remove,{tapeId:e.id}));if(t===null)throw Error(ta);let n=ga(t);if(n!==null)throw Error(n);await u.refetch()};return e(`div`,{className:`space-y-3`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:i(rn,{i18nKey:`eventsDebugTapes.intro`,components:{b:i(`strong`,{}),code:i(`code`,{})}})}),p!==null&&i(W,{message:p}),l.isLoading&&i(`p`,{className:`text-xs text-foreground-subtle`,children:t(`eventsDebugTapes.loadingCameraStatus`,`Loading camera status…`)}),l.data===null&&i(W,{message:`The server answered in a shape this build does not understand.`}),e(`table`,{className:`w-full text-xs`,children:[i(`thead`,{children:e(`tr`,{className:`text-left text-foreground-subtle`,children:[i(`th`,{children:t(`eventsDebugTapes.camera`,`Camera`)}),i(`th`,{children:t(`eventsDebugTapes.state`,`State`)}),i(`th`,{children:t(`eventsDebugTapes.framesMin`,`Frames/min`)}),i(`th`,{children:t(`eventsDebugTapes.lastHour`,`Last hour`)}),i(`th`,{children:t(`eventsDebugTapes.held`,`Held`)}),i(`th`,{children:t(`eventsDebugTapes.gaps`,`Gaps`)})]})}),i(`tbody`,{children:(l.data??[]).map(n=>e(`tr`,{children:[i(`td`,{children:c(n.deviceId)}),i(`td`,{children:i(G,{variant:n.state===`recording`?`success`:n.state===`off`?`default`:n.state===`unknown`?`warning`:`danger`,children:Ta(n)})}),i(`td`,{children:n.framesPerMin===void 0?`—`:String(Math.round(n.framesPerMin))}),i(`td`,{title:n.shelfError,children:Aa(n.bytesLastHour)}),i(`td`,{title:n.shelfError,children:t(`eventsDebugTapes.segsHeld`,{count:ja(n.segmentsHeld),size:Aa(n.bytesHeld)})}),i(`td`,{children:String(n.gapsSinceArmed)})]},n.deviceId))})]}),i(Na,{cameras:xa(l.data??[]).map(e=>({value:String(e.deviceId),label:e.segmentsUnknown?t(`eventsDebugTapes.segmentsUnknown`,`{{value1}} (segments unknown)`,{value1:c(e.deviceId)}):c(e.deviceId)})),call:r,onPromoted:()=>void u.refetch()}),u.isLoading&&i(`p`,{className:`text-xs text-foreground-subtle`,children:t(`eventsDebugTapes.loadingPromotedTapes`,`Loading promoted tapes…`)}),u.data===null&&i(W,{message:`The server answered in a shape this build does not understand.`}),e(`table`,{className:`w-full text-xs`,children:[i(`thead`,{children:e(`tr`,{className:`text-left text-foreground-subtle`,children:[i(`th`,{children:t(`eventsDebugTapes.scenario`,`Scenario`)}),i(`th`,{children:t(`eventsDebugTapes.camera`,`Camera`)}),i(`th`,{children:t(`eventsDebugTapes.window`,`Window`)}),i(`th`,{children:t(`eventsDebugTapes.state`,`State`)}),i(`th`,{children:t(`eventsDebugTapes.tracks`,`Tracks`)}),i(`th`,{})]})}),i(`tbody`,{children:(u.data??[]).map(n=>e(`tr`,{children:[i(`td`,{children:n.scenario}),i(`td`,{children:c(n.deviceId)}),e(`td`,{children:[new Date(n.fromMs).toLocaleString(),` · `,$a(n.toMs-n.fromMs),` `,`· `,n.lighting]}),e(`td`,{children:[i(G,{variant:n.state===`complete`?`success`:`warning`,children:n.state}),` `,n.reviewed&&i(G,{variant:`info`,children:t(`eventsDebugTapes.reviewed`)}),` `,n.released&&i(G,{children:t(`eventsDebugTapes.released`)})]}),i(`td`,{children:t(`eventsDebugTapes.storedOf`,{stored:String(n.tracksStillStored),total:String(n.tracks.length)})}),e(`td`,{className:`space-x-1 text-right`,children:[i(K,{variant:`secondary`,"aria-label":t(`eventsDebugTapes.review`,`Review {{scenario}}`,{scenario:n.scenario}),onClick:()=>f(n.id),children:t(`eventsDebugTapes.review2`,`Review`)}),i(K,{variant:`ghost`,"aria-label":t(`eventsDebugTapes.download`,`Download {{scenario}}`,{scenario:n.scenario}),onClick:()=>void g(n),children:i(le,{className:`h-3.5 w-3.5`})}),i(vt,{label:t(`eventsDebugTapes.release`,`Release`),icon:h,title:t(`eventsDebugTapes.release2`,`Release {{scenario}}?`,{scenario:n.scenario}),description:t(`eventsDebugTapes.releasingReturnsThisTapeS`,`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:t(`eventsDebugTapes.release`,`Release`),triggerVariant:`ghost`,confirmVariant:`danger`,disabled:n.released,action:()=>_(n)}),i(vt,{label:t(`common.delete`,`Delete`),icon:se,title:t(`eventsDebugTapes.delete`,`Delete {{scenario}}?`,{scenario:n.scenario}),description:t(`eventsDebugTapes.deletingRemovesThePromotedBundle`,`Deleting removes the promoted bundle and its index row for good. Its tracks' pins are released first — this cannot be undone.`),confirmLabel:t(`common.delete`,`Delete`),triggerVariant:`ghost`,confirmVariant:`danger`,action:()=>v(n)})]})]},n.id))})]}),d!==null&&i(no,{tapeId:d,call:r,onClose:()=>f(null),onChanged:()=>void u.refetch()})]})}c();var lo=`all`,uo=`The server answered in a shape this build does not understand.`,fo={error:`danger`,warn:`warning`,info:`info`};function po({findings:e}){let{t}=J();return e.length===0?i(G,{variant:`success`,children:t(`eventsDebug.noAnomalyFound`,`no anomaly found`)}):i(`div`,{className:`flex flex-wrap gap-1`,children:Za(e).map(e=>i(G,{variant:fo[e.severity],title:e.detail,children:Ya(e.code)},e.code))})}function mo({track:t,report:n,analyzing:r}){let{t:a}=J(),o=Jr(n?.previewMissReason??t.previewMissReason);return e(`div`,{className:`space-y-1 border-t border-border pt-1.5`,children:[n===void 0?i(`span`,{className:`text-[10px] text-foreground-subtle`,children:r?a(`eventsDebug.analysing`,`analysing…`):a(`eventsDebug.notAnalysed`,`not analysed`)}):e(u,{children:[i(po,{findings:n.findings}),i(`p`,{className:`text-[10px] text-foreground-subtle`,title:n.mediaKinds.length>0?n.mediaKinds.join(`, `):a(`eventsDebug.noMediaOfAnyKind`,`no media of any kind`),children:a(`eventsDebug.reportCounts`,{media:String(n.mediaCount),events:String(n.eventCount),positions:String(n.positionCount)})})]}),o!==null&&i(`p`,{className:`text-[10px] text-foreground-subtle`,title:o.raw,children:o.sentence})]})}function ho({deviceId:t}={}){let{t:r}=J(),a=ue(),[c,l]=o(lo),u=t===void 0?c:String(t),[d,f]=o(!1),[p,m]=o(null),[h,g]=o(new Set),[_,v]=o(null),[b,x]=o(null),[S,C]=o(null),[T,E]=o([]),D=ni(),O=We({isCamera:!0,projection:`slim`}),A=n(()=>[{value:lo,label:r(`eventsDebug.allCameras`,`All cameras`)},...(O.data??[]).map(e=>({value:String(e.id),label:e.name}))],[O.data,r]),j=n(()=>{let e=new Map;for(let t of O.data??[])e.set(t.id,t.name);return e},[O.data]),M=e=>j.get(e)??r(`eventsDebug.cameraFallback`,{deviceId:e}),N=n(()=>u===lo?[]:[Number.parseInt(u,10)],[u]),F=s({queryKey:[`events-debug`,`list`,N],queryFn:async()=>Ka(await a.trpcClient.addons.custom.mutate({addonId:Pa,action:Fa,input:N.length===0?{}:{deviceIds:N}}))}),I=n(()=>(F.data?.tracks??[]).map(e=>e.trackId),[F.data]),L=s({queryKey:[`events-debug`,`analyze`,I],enabled:I.length>0,queryFn:async()=>qa(await a.trpcClient.addons.custom.mutate({addonId:Pa,action:Ia,input:{trackIds:I}}))}),ee=n(()=>{let e=new Map;for(let t of L.data?.reports??[])e.set(t.trackId,t);return e},[L.data]),R=F.data?.tracks??[],te=F.data===null||L.data===null,ne=()=>{F.refetch(),L.refetch()},ie=e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},ae=()=>{g(new Set(R.map(e=>eo(e.deviceId,e.trackId))))},oe=()=>g(new Set),se=async(e,t)=>{let n=e===`analyzed`?{debug:!1}:{favourited:!0},r=0,i=[];for(let e of t)try{await D.mutateAsync({deviceId:e.deviceId,trackId:e.trackId,flags:n}),r+=1}catch{i.push(e.trackId)}return{applied:r,refused:i}},ce=e=>{if(!$r||b!==null)return;let t=to(R,h);t.length!==0&&(x(e),C(null),(async()=>{let n=await se(e,t);x(null);let r=new Set(n.refused);g(new Set(t.filter(e=>r.has(e.trackId)).map(e=>eo(e.deviceId,e.trackId)))),e===`analyzed`&&E(t.filter(e=>!r.has(e.trackId))),n.refused.length>0&&C(`${String(n.refused.length)} of ${String(t.length)} were refused by the server and are still selected. Check the hub log.`),F.refetch()})())},de=()=>{let e=T;e.length===0||b!==null||(x(`analyzed`),C(null),(async()=>{for(let t of e)try{await D.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{C(`Some tracks could not be re-marked. Refresh and try again.`)}x(null),E([]),F.refetch()})())},fe=async()=>{f(!0),m(null);try{await Cn(Qa(N),`camstack-debug.zip`)}catch(e){m(e instanceof Error?e.message:`Export failed.`)}finally{f(!1)}},H=b!==null;return e(`section`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[t===void 0&&i(`div`,{className:`w-44`,children:i(P,{value:u,options:A,onChange:e=>l(e.target.value)})}),e(K,{variant:`secondary`,onClick:ne,disabled:F.isFetching,children:[F.isFetching?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(w,{className:`h-3.5 w-3.5`}),r(`common.refresh`,`Refresh`)]}),e(K,{onClick:()=>void fe(),disabled:d||R.length===0,children:[d?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(le,{className:`h-3.5 w-3.5`}),r(`eventsDebug.exportAll`,{count:String(R.length)})]}),R.length>0&&h.size<R.length&&i(K,{variant:`ghost`,onClick:ae,children:r(`eventsDebug.selectAll`,`Select all`)})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:i(rn,{i18nKey:`eventsDebug.debugMarkNote`,components:{code:i(`code`,{}),strong:i(`strong`,{})}})}),i(so,{}),F.isError&&i(W,{message:r(`eventsDebug.couldNotLoadTheMarked`,`Could not load the marked tracks.`)}),te&&!F.isError&&i(W,{message:uo}),p!==null&&i(W,{message:p}),S!==null&&i(W,{message:S}),F.data?.truncated===!0&&i(W,{message:r(`eventsDebug.aCameraFilledThePer`,`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`)}),(L.data?.vanished.length??0)>0&&i(`p`,{className:`text-xs text-foreground-subtle`,children:r(`eventsDebug.vanished`,{count:String(L.data?.vanished.length)})}),h.size>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[i(`span`,{className:`text-xs font-medium text-foreground`,children:r(`common.selectedCount`,{count:h.size})}),e(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[i(`span`,{title:$r?void 0:`Track flags arrive with the next server update`,children:e(K,{variant:`secondary`,onClick:()=>ce(`keep`),disabled:!$r||H,children:[b===`keep`?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(z,{className:`h-3.5 w-3.5`}),` `,r(`eventsDebug.keep`,`Keep`)]})}),i(`span`,{title:$r?void 0:`Track flags arrive with the next server update`,children:e(K,{onClick:()=>ce(`analyzed`),disabled:!$r||H,children:[b===`analyzed`?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(re,{className:`h-3.5 w-3.5`}),` `,r(`eventsDebug.analyzed`,`Analyzed`)]})}),i(K,{variant:`ghost`,onClick:oe,disabled:H,children:i(y,{className:`h-3.5 w-3.5`})})]})]}),T.length>0&&e(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border bg-surface px-3 py-2`,children:[i(`span`,{className:`text-xs text-foreground`,children:r(`eventsDebug.markedAnalyzed`,{count:String(T.length)})}),e(K,{variant:`ghost`,onClick:de,disabled:H,children:[i(B,{className:`h-3.5 w-3.5`}),` `,r(`eventsDebug.undo`)]}),i(K,{variant:`ghost`,onClick:()=>E([]),disabled:H,children:i(y,{className:`h-3.5 w-3.5`})})]}),F.isLoading?i(zt,{status:`pending`,pendingMessage:`Loading…`,testId:`debug-tracks-grid`}):R.length===0?i(yt,{icon:k,title:r(`eventsDebug.noTrackIsMarkedFor`,`No track is marked for debug`),description:r(`eventsDebug.markOneFromATrack`,`Mark one from a track's actions on the Feed to see it here.`)}):i(zt,{status:`ready`,testId:`debug-tracks-grid`,children:R.map(e=>{let t=ee.get(e.trackId);return i(Si,{row:e,cameraName:M(e.deviceId),nowMs:e.lastSeen,selected:h.has(eo(e.deviceId,e.trackId)),onToggleSelect:ie,onOpenDetail:v,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:i(mo,{track:e,report:t,analyzing:L.isFetching})},eo(e.deviceId,e.trackId))})}),_&&i(bi,{row:_,cameraName:M(_.deviceId),deleteAvailable:pr,onClose:()=>v(null),onDeleted:()=>{v(null),F.refetch()},onFlagsChanged:e=>{e.debug||(v(null),F.refetch())}})]})}c();function go({deviceId:t,debug:n}){let{t:r}=J(),[a,s]=o(!1);return i(Wt,{expanded:a||n,onExpandedChange:s,header:e(`span`,{className:`flex items-center gap-2 text-sm font-medium text-foreground`,children:[i(f,{className:`h-3.5 w-3.5`}),r(`archive.review.tools`,`Search, parked objects and debug`)]}),children:e(`div`,{className:`flex flex-col gap-3`,"data-testid":`archive-review-tools`,children:[i(Vi,{}),i(Ki,{deviceId:t}),i(Yi,{deviceId:t}),n&&i(ho,{deviceId:t})]})})}var _o=``;function vo(e){return e===`any`||e===`face`||e===`plate`}function yo({filters:t,zones:n,onChange:r,unchecked:a=0}){let{t:o}=J();return e(`div`,{className:`contents`,"data-testid":`archive-review-filters`,children:[n.length>0&&e(P,{wrapperClassName:`inline-block w-auto`,"aria-label":o(`archive.review.zone`,`Zone`),value:t.zone??_o,onChange:e=>r({...t,zone:e.target.value===_o?null:e.target.value}),children:[i(`option`,{value:_o,children:o(`archive.review.allZones`,`All zones`)}),n.map(e=>i(`option`,{value:e,children:e},e))]}),e(P,{wrapperClassName:`inline-block w-auto`,"aria-label":o(`archive.review.identity`,`Face or plate`),value:t.identity,onChange:e=>{let n=e.target.value;vo(n)&&r({...t,identity:n})},children:[i(`option`,{value:`any`,children:o(`archive.review.identityAny`,`Any subject`)}),i(`option`,{value:`face`,children:o(`archive.review.identityFace`,`With a face`)}),i(`option`,{value:`plate`,children:o(`archive.review.identityPlate`,`With a plate`)})]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(D,{checked:t.debug,onChange:e=>r({...t,debug:e.target.checked})}),o(`archive.camera.debugFilter`,`Debug-marked tracks only`)]}),a>0&&i(`span`,{className:`text-[11px] text-warning`,"data-testid":`archive-review-unchecked`,children:o(`archive.review.unchecked`,`Events not checked by this filter: {{count}}`,{count:a})})]})}c();function bo(){let e=Date.now(),t=new Date(e);return t.setHours(0,0,0,0),{fromMs:t.getTime(),toMs:e}}var xo=[];function So({deviceId:e}){return i(st,{deviceId:e,children:i(qe,{children:i(He,{children:i(ae,{children:i(et,{children:i(Co,{deviceId:e},e)})})})})})}function Co({deviceId:t}){let{t:a}=J(),[s,c]=o(bo),[l,u]=o(Mi),[d,f]=o(null),[p,m]=o(void 0),[h,g]=o(null),[_,v]=o(!1),[y,b]=o(null),[x,S]=o(null),[C,w]=o(`high`),[T,E]=o(null),[D,O]=o(null),k=Pt({deviceId:t}),A=n(()=>Rt(k.data??[]),[k.data]),j=y??Et(A,`recorder`),M=j===null||j===`recorder`,N=Fe(t,M?null:j,s),F=ot({deviceId:t,since:s.fromMs,until:s.toMs,limit:200,projection:`slim`}),I=F.data??xo,L=n(()=>Pi(I),[I]),ee=n(()=>Ni(I),[I]),R=n(()=>Ii(l,ee),[l,ee]),te=Li(l)||l.debug,z=n(()=>d===null?0:Ri(d.rows,l,ee),[d,l,ee]),ne=n(()=>d!==null&&(d.narrowed||te)?zi(d.rows):void 0,[d,te]),B=n(()=>({since:s.fromMs,until:s.toMs}),[s]),re=r(e=>c(e),[]),ie=r(e=>{if(E(null),M){S(null),m(t=>({atMs:e,nonce:(t?.nonce??0)+1}));return}let t=rt(N.clips,e);t===null&&E(e),S(t)},[M,N.clips]),ae=r((e,t)=>{if(b(e),E(null),e===`recorder`){S(null),m(e=>({atMs:t.timeRange.startMs,nonce:(e?.nonce??0)+1}));return}S(t)},[]),oe=k.status===`pending`?i(`span`,{className:`text-[11px] text-foreground-subtle`,role:`status`,children:a(`archive.review.sourcesLoading`,`Loading sources…`)}):k.status===`error`?i(`span`,{className:`text-[11px] text-danger`,role:`alert`,children:a(`archive.review.sourcesFailed`,`Sources could not be read — {{reason}}`,{reason:k.error?.message??a(`archive.review.noReason`,`no reason given`)})}):null,se=F.status===`error`?i(`span`,{className:`text-[11px] text-danger`,role:`alert`,"data-testid":`archive-review-tracks-failed`,children:a(`archive.review.tracksFailed`,`Track facts could not be read — {{reason}}`,{reason:F.error?.message??a(`archive.review.noReason`,`no reason given`)})}):null,ce=oe??(A.length>1?i(P,{wrapperClassName:`inline-block w-auto`,"aria-label":a(`archive.review.source`,`Source`),value:j??``,onChange:e=>{b(e.target.value),S(null),E(null)},children:A.map(e=>i(`option`,{value:e.value,children:e.label},e.value))}):null);return e(`div`,{className:`grid grid-cols-1 gap-3 lg:grid-cols-[minmax(0,calc(40vh*16/9))_minmax(20rem,1fr)]`,children:[i(`div`,{className:`order-1 flex min-w-0 flex-col gap-2 lg:order-none lg:col-start-1 lg:row-start-1`,children:i(`div`,{className:`mx-auto aspect-video w-full max-w-[calc(40vh*16/9)] overflow-hidden rounded-lg border border-border bg-black`,"data-testid":`archive-review-player`,children:i(wn,{deviceId:t})})}),e(`div`,{className:`order-3 flex min-w-0 flex-col gap-2 lg:order-none lg:col-start-2 lg:row-start-1 lg:max-h-[40vh] lg:overflow-y-auto`,"data-testid":`archive-review-events`,children:[T!==null&&i(W,{variant:`warning`,message:a(`archive.review.noClipAt`,`This source holds no clip at {{time}}. Pick another source or another moment.`,{time:new Date(T).toLocaleTimeString()})}),x!==null&&j!==null&&i(Nt,{deviceId:t,clip:x,profile:C,onProfileChange:w}),i(ji,{deviceId:t,window:B,rowFilter:R,onListChange:f,onSeek:ie,layout:`rows`,toolbarTarget:D})]}),i(`div`,{className:`order-2 flex min-w-0 flex-col gap-2 lg:order-none lg:col-span-2 lg:row-start-2`,children:i(ke,{deviceId:t,seekTo:p,onExportRange:(e,t)=>{v(!1),g({fromMs:e,toMs:t})},onViewChange:re,densityPoints:ne,toolbar:e(`div`,{className:`contents`,"data-testid":`archive-review-bar`,children:[ce,_&&e(`span`,{className:`text-[11px] text-success`,role:`status`,children:[a(`archive.review.exportQueued`,`Export queued.`),` `,i(tn,{to:Xt(t),className:`font-medium underline`,children:a(`archive.review.openExports`,`Open Library → Exports`)})]}),i(`span`,{ref:O,className:`contents`}),i(yo,{filters:l,zones:L,onChange:u,unchecked:z}),se]}),lanes:i(gt,{deviceId:t,options:A,view:s,selectedProvider:j,onPickClip:ae})})}),i(`div`,{className:`order-4 min-w-0 lg:order-none lg:col-span-2 lg:row-start-3`,children:i(go,{deviceId:t,debug:l.debug})}),h!==null&&i(vn,{onClose:()=>g(null),onCreated:()=>{g(null),v(!0)},initialDeviceId:t,initialRange:h})]})}function wo({deviceId:e}){return i(st,{deviceId:e,children:i(Qt,{deviceId:e,sectionFilter:e=>e.location===`top-tab`&&e.tab===`recording`})},e)}function To(e){return e.locationIds!==void 0&&e.locationIds.length>0?e.locationIds:e.locationId===null?[]:[e.locationId]}function Eo(e,t){let n=To(e);return n.length===0?q.t(`helpers.cameraDisk.defaultRoot`):n.map(e=>t.get(e)??e).join(` + `)}function Do(e,t,n){if(e.length===0)return null;let r=e[0];if(e.length===1&&r!==void 0)return{label:Eo(r,t),exact:!0};if(n===null)return null;let i=e.find(e=>To(e).includes(n));return i===void 0?null:{label:Eo(i,t),exact:!1}}c();var Oo=[{value:`retention`,labelKey:`recordings.storageSection.pruneRetention`},{value:`quota`,labelKey:`recordings.storageSection.pruneQuota`},{value:`operator`,labelKey:`recordings.storageSection.pruneOperator`}],ko=`—`;function Ao({data:t,row:a}){let{t:s}=J(),c=M(),u=l(),[d,f]=o(`retention`),p=Xe({}).data,m=r(()=>{u.invalidateQueries({queryKey:[[`recording`]]}),u.invalidateQueries({queryKey:[[`recordingArchive`]]}),u.invalidateQueries({queryKey:[[`pipelineAnalytics`]]})},[u]),h=Le({onSuccess:m}),g=ht({onSuccess:m}),_=mt({onSuccess:m}),v=n(()=>{let e=new Map((p??[]).map(e=>[e.id,e.displayName])),n=(p??[]).filter(e=>e.type===`recordings`),r=(n.find(e=>me(e)===`active`)??n[0])?.id??null;return Do(t.usage?.locations??[],e,r)},[p,t.usage?.locations]),y=r(async(e,t,n)=>c({title:e,message:t,confirmLabel:n,variant:`danger`}),[c]),b=async()=>{await y(s(`archive.space.pruneTitle`,`Apply retention to {{name}}?`,{name:a.name}),s(`archive.space.pruneMessage`,`Footage beyond the retention policy is permanently deleted.`),s(`archive.space.pruneNow`,`Prune now`))&&h.mutate({deviceId:a.deviceId,reason:d})},x=async()=>{await y(s(`archive.space.deleteFootageTitle`,`Delete all footage for {{name}}?`,{name:a.name}),s(`archive.space.deleteFootageMessage`,`Permanently deletes {{size}} of recorded footage. This cannot be undone.`,{size:a.footageBytes===null?ko:Y(a.footageBytes)}),s(`archive.space.deleteFootage`,`Delete footage`))&&g.mutate({deviceId:a.deviceId})},S=async()=>{await y(s(`archive.space.deleteEventsTitle`,`Delete all events for {{name}}?`,{name:a.name}),s(`archive.space.deleteEventsMessage`,`Permanently deletes the events and their media. This cannot be undone.`),s(`archive.space.deleteEvents`,`Delete events`))&&_.mutate({deviceId:a.deviceId})};return e(`div`,{className:`flex flex-col gap-4`,"data-testid":`archive-space`,children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-3`,children:[i(C,{label:s(`archive.space.footage`,`Footage`),icon:i(oe,{className:`h-3.5 w-3.5`}),footer:v===null?s(`archive.space.diskUnknown`,`Disk not reported`):v.exact?v.label:s(`archive.space.diskDefault`,`{{label}} (default)`,{label:v.label}),children:a.footageBytes===null?ko:Y(a.footageBytes)}),i(C,{label:s(`archive.space.events`,`Event storage`),footer:a.eventRows===null?void 0:s(`archive.space.eventRows`,`{{count}} events`,{count:a.eventRows}),children:a.eventBytes===null?ko:Y(a.eventBytes)}),i(C,{label:s(`archive.space.oldest`,`Oldest footage`),children:a.oldestMs===null?ko:new Date(a.oldestMs).toLocaleDateString()})]}),e(`div`,{className:`flex flex-col gap-2 rounded-lg border border-danger/40 p-3`,children:[i(`h3`,{className:`text-sm font-semibold text-danger`,children:s(`archive.space.danger`,`Danger zone`)}),e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[i(`span`,{className:`text-foreground-subtle`,children:s(`recordings.storageSection.pruneReason`,`Prune reason`)}),i(P,{wrapperClassName:`inline-block w-auto`,value:d,"aria-label":s(`recordings.storageSection.pruneReason`,`Prune reason`),onChange:e=>{let t=Oo.find(t=>t.value===e.target.value);t&&f(t.value)},children:Oo.map(e=>i(`option`,{value:e.value,children:s(e.labelKey)},e.value))})]}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(K,{variant:`secondary`,onClick:()=>void b(),disabled:h.isPending,children:[i(U,{className:`h-3.5 w-3.5`}),s(`archive.space.applyRetention`,`Apply retention now`)]}),e(K,{variant:`secondary`,onClick:()=>void x(),disabled:g.isPending,children:[i(se,{className:`h-3.5 w-3.5`}),s(`archive.space.deleteFootage`,`Delete footage`)]}),e(K,{variant:`secondary`,onClick:()=>void S(),disabled:_.isPending,children:[i(se,{className:`h-3.5 w-3.5`}),s(`archive.space.deleteEvents`,`Delete events`)]})]})]})]})}c();var jo=[`review`,`health`,`settings`];function Mo(e){return jo.some(t=>t===e)}function No({data:t}){let{t:n}=J(),[a,o]=$t(),s=a.get(Yt),c=a.get(en),l=Mo(c)?c:`review`,u=s===null?t.cameras[0]?.id??null:Number(s),d=r((e,t)=>{o(n=>{let r=new URLSearchParams(n);return r.set(e,t),r},{replace:!0})},[o]);if(u===null||!Number.isFinite(u))return i(yt,{icon:N,title:n(`archive.camera.none`,`No cameras yet`),description:n(`archive.camera.noneHint`,`Cameras appear here once one is added.`)});let f=t.rows.find(e=>e.deviceId===u),p=Yn(rr(t,u),Zn(t.findings,u));return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`archive-camera-section`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(P,{wrapperClassName:`inline-block w-auto`,value:u,onChange:e=>d(Yt,e.target.value),"aria-label":n(`archive.camera.picker`,`Camera`),children:t.cameras.map(e=>i(`option`,{value:e.id,children:e.name},e.id))}),p.map(t=>e(G,{variant:nr[t.state],children:[n(`archive.function.${t.fn}`,t.fn),` · `,n(`archive.functionState.${t.state}`,t.state)]},t.fn))]}),!t.isLoading&&f===void 0?i(yt,{icon:N,title:n(`archive.camera.unknown`,`Camera not found`),description:n(`archive.camera.unknownHint`,`This camera is not in the Archive. Pick one from the overview.`)}):e(Je,{appearance:`pills`,value:l,onValueChange:e=>d(en,e),className:`flex flex-col gap-3`,children:[e(Ft,{"aria-label":n(`archive.camera.sections`,`Camera sections`),children:[i(Ze,{value:`review`,children:n(`archive.camera.review`,`Review`)}),i(Ze,{value:`health`,children:n(`archive.camera.healthSpace`,`Health & space`)}),i(Ze,{value:`settings`,children:n(`archive.camera.settings`,`Settings`)})]}),i(Ot,{value:`review`,children:i(So,{deviceId:u})}),i(Ot,{value:`health`,children:e(`div`,{className:`flex flex-col gap-6`,children:[i(ir,{data:t,deviceId:u}),i(Vn,{data:t,deviceId:u}),f!==void 0&&i(Ao,{data:t,row:f})]})}),i(Ot,{value:`settings`,children:i(wo,{deviceId:u})})]})]})}c();var Po={recording:`success`,off:`default`,degraded:`warning`,unknown:`default`},Fo=`—`;function Io({rows:t,isLoading:r}){let{t:a}=J(),o=nn(),s=n(()=>[{key:`camera`,header:a(`archive.table.camera`,`Camera`),sortValue:e=>e.name,render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.name})},{key:`mode`,header:a(`archive.table.mode`,`Recording`),sortValue:e=>e.mode??``,render:e=>i(`span`,{className:`text-foreground-subtle`,children:e.mode===null?Fo:a(`archive.mode.${e.mode}`,e.mode)})},{key:`status`,header:a(`archive.table.status`,`Status`),sortValue:e=>e.state,render:t=>e(`span`,{className:`inline-flex items-center gap-1.5`,children:[i(G,{variant:Po[t.state],children:a(`archive.state.${t.state}`,t.state)}),t.warnings>0&&i(G,{variant:`warning`,children:a(`archive.table.warnings`,`{{count}} warning`,{count:t.warnings})})]})},{key:`footage`,header:a(`archive.table.footage`,`Footage`),align:`right`,nowrap:!0,sortValue:e=>e.footageBytes,render:e=>i(`span`,{className:`tabular-nums`,children:e.footageBytes===null?Fo:Y(e.footageBytes)})},{key:`events`,header:a(`archive.table.events`,`Events`),align:`right`,nowrap:!0,sortValue:e=>e.eventRows,render:e=>i(`span`,{className:`tabular-nums`,children:e.eventRows===null||e.eventBytes===null?Fo:`${e.eventRows.toLocaleString()} · ${Y(e.eventBytes)}`})},{key:`oldest`,header:a(`archive.table.oldest`,`Oldest footage`),align:`right`,nowrap:!0,sortValue:e=>e.oldestMs,render:e=>i(`span`,{className:`tabular-nums text-foreground-subtle`,children:e.oldestMs===null?Fo:new Date(e.oldestMs).toLocaleDateString()})}],[a]);return!r&&t.length===0?i(yt,{icon:N,title:a(`archive.table.noCameras`,`No cameras`),description:a(`archive.table.addACamera`,`Add a camera first.`)}):i(Kt,{columns:s,rows:t,rowKey:e=>e.deviceId,onRowClick:e=>o(Zt(e.deviceId)),minWidthPx:720,maxBodyHeight:xe,defaultSort:{columnKey:`camera`,dir:`asc`}})}var Lo=1440*60*1e3;function Ro(e){if(e.footageBytes===null||e.oldestMs===null)return null;let t=e.nowMs-e.oldestMs;return t<Lo?null:e.footageBytes/(t/Lo)}function zo(e,t){return e===null||t===null||t<=0?null:e/t}function Bo(e){let t=null;for(let n of e)n.oldestMs!==null&&(t===null||n.oldestMs<t)&&(t=n.oldestMs);return t}c();var Vo=`—`;function Ho({data:t}){let{t:r}=J(),{usage:a,footprint:o,rows:s,totals:c}=t,l=a!==null&&a.devicesRead!==`unavailable`,u=n(()=>Ro({footageBytes:l?a.totalUsedBytes:null,oldestMs:Bo(s),nowMs:Date.now()}),[l,a,s]),f=zo(n(()=>{let e=jn(a?.locations??[]);return e===null||e.knownVolumes===0?null:e.freeBytes},[a?.locations]),u);return e(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-5`,"data-testid":`archive-key-numbers`,children:[i(C,{label:r(`archive.keyNumbers.footage`,`Footage`),icon:i(oe,{className:`h-3.5 w-3.5`}),footer:l?void 0:r(`archive.keyNumbers.footageUnread`,`The recorder did not answer`),children:l?Y(a.totalUsedBytes):Vo}),i(C,{label:r(`archive.keyNumbers.eventStorage`,`Event storage`),icon:i(L,{className:`h-3.5 w-3.5`}),footer:o===null?r(`archive.keyNumbers.eventsUnread`,`The event store did not answer`):r(`archive.keyNumbers.eventRows`,`{{count}} events`,{count:o.totalRows}),children:o===null?Vo:Y(o.totalBytes)}),i(C,{label:r(`archive.keyNumbers.growth`,`Growth per day`),icon:i(d,{className:`h-3.5 w-3.5`}),footer:u===null?r(`archive.keyNumbers.growthUnknown`,`Needs a day of footage`):f===null?r(`archive.keyNumbers.daysUnknown`,`Free space unknown`):r(`archive.keyNumbers.daysLeft`,`{{days}} days of space left`,{days:Math.floor(f)}),children:u===null?Vo:Y(u)}),i(C,{label:r(`archive.keyNumbers.cameras`,`Cameras`),icon:i(N,{className:`h-3.5 w-3.5`}),footer:r(`archive.keyNumbers.cameraStates`,`{{degraded}} degraded · {{off}} off`,{degraded:c.degraded,off:c.off}),children:r(`archive.keyNumbers.recordingOf`,`{{recording}} of {{total}} recording`,{recording:c.recording,total:s.length})}),i(C,{label:r(`archive.keyNumbers.warnings`,`Open warnings`),icon:i(O,{className:`h-3.5 w-3.5`}),footer:t.findings===null?r(`archive.keyNumbers.digestPending`,`No health digest yet`):void 0,children:t.findings===null?Vo:String(c.warnings)})]})}c();var Uo={active:`success`,readonly:`default`,drain:`warning`,disabled:`danger`};function Wo(){let{t}=J(),n=On(),[r,a]=o(null);return n.locations.length===0?i(yt,{icon:oe,title:t(`archive.storage.none`,`No storage locations`),description:t(`archive.storage.noneHint`,`Add a location to start storing footage and events.`)}):e(u,{children:[i(`div`,{className:`grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3`,"data-testid":`archive-storage-cards`,children:n.locations.map(r=>{let o=En(r);return e(`div`,{className:`flex flex-col gap-2 rounded-lg border border-border bg-surface p-3`,children:[e(`div`,{className:`flex items-start justify-between gap-2`,children:[e(`div`,{className:`min-w-0`,children:[i(`div`,{className:`truncate text-sm font-medium text-foreground`,children:r.displayName}),e(`div`,{className:`text-[11px] text-foreground-subtle`,children:[r.type,r.nodeId===void 0?``:` · ${r.nodeId}`]})]}),i(G,{variant:Uo[o],children:Dn(o).label})]}),i(An,{location:r,ownedBytes:n.ownedBytesById.get(r.id)??null}),i(kn,{drain:n.drainOf(r)}),e(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`span`,{className:`text-[11px] text-foreground-subtle`,children:o===`active`?t(`archive.storage.writing`,`Taking new writes`):t(`archive.storage.notWriting`,`Not taking new writes`)}),i(K,{variant:`ghost`,onClick:()=>a(r),children:t(`archive.storage.manage`,`Manage`)})]})]},r.id)})}),r!==null&&i(Re,{open:!0,onOpenChange:e=>!e&&a(null),children:e(De,{width:`xl`,placement:`sheet-on-mobile`,scroll:`body`,children:[i(je,{children:i(Ue,{children:r.displayName})}),i(Ve,{children:i(Mn,{kinds:[r.type]})})]})})]})}c();var Go=1440*60*1e3,Ko=[1,7,30,90],qo=30;function Jo(){let{t}=J(),n=M(),a=l(),[s,c]=o(qo),u=jt({onSuccess:()=>{a.invalidateQueries({queryKey:[[`pipelineAnalytics`]]})}}),d=r(async()=>{await n({title:t(`recordings.eventsManagementSection.pruneTitle`,{count:s}),message:t(`recordings.eventsManagementSection.permanentlyDeletesEveryEventMotion`,`Permanently deletes every event (motion / object / audio) older than the cutoff across all cameras, and their media. This cannot be undone.`),confirmLabel:t(`recordings.eventsManagementSection.pruneEvents`,`Prune events`),variant:`danger`})&&u.mutate({olderThanMs:Date.now()-s*Go,reason:`retention`})},[n,u,s,t]);return e(`section`,{className:`flex flex-wrap items-center gap-2 text-xs`,"data-testid":`prune-events-by-age`,children:[i(`span`,{className:`text-foreground-subtle`,children:t(`recordings.eventsManagementSection.pruneEventsOlderThan`,`Prune events older than`)}),i(P,{wrapperClassName:`inline-block w-auto`,value:s,onChange:e=>c(Number(e.target.value)),"aria-label":t(`recordings.eventsManagementSection.pruneEventsOlderThan`,`Prune events older than`),children:Ko.map(e=>i(`option`,{value:e,children:t(`recordings.eventsManagementSection.ageDays`,{count:e})},e))}),e(K,{variant:`secondary`,onClick:()=>void d(),disabled:u.isPending,children:[u.isPending?i(V,{className:`h-3 w-3 animate-spin`}):i(U,{className:`h-3 w-3`}),t(`recordings.eventsManagementSection.pruneNow`,`Prune now`)]})]})}var Yo=`inline-flex w-fit items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`;c();var Xo=`storage-migration`,Zo=new Set([`orphans`,`debug-media`,`ghost-ledger`]);function Qo(e){return[`${e.orphansReclaimed} orphan rows (${Y(e.orphanBytesReclaimed)})`,e.includeDebugMedia?`${e.debugMediaReclaimed} debug files (${Y(e.debugMediaBytesReclaimed)})`:null,`${e.ghostsForgotten} ghost rows (${Y(e.ghostBytesForgotten)})`].filter(e=>e!==null).join(` · `)}function $o(){let{t:e}=J(),t=ze(Xo);return t===`pending`?null:t===`unknown`?i(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:e(`recordings.cleanupSection.couldNotCheckWhetherStorage`,`Could not check whether storage cleanup is installed on this hub.`)}):t===`present`?i(es,{}):null}function es(){let{t}=J(),n=M(),[r,a]=o(!1),[s,c]=o(null),l=it({},{refetchInterval:2e3}),u=l.data??null,d=u!==null&&Zo.has(u.phase),f=tt(),p=Bt(),m=async()=>{if(await n({title:t(`recordings.cleanupSection.runStorageCleanup`,`Run storage cleanup?`),message:r?t(`recordings.cleanupSection.reclaimsLeftoverAnalyticsRowsAnd`,`Reclaims leftover analytics rows and files, debug stills/filmstrips, and ghost footage rows on frozen locations. Safe to re-run.`):t(`recordings.cleanupSection.reclaimsLeftoverAnalyticsRowsAnd2`,`Reclaims leftover analytics rows and files, and ghost footage rows on frozen locations. Debug stills are left alone. Safe to re-run.`),confirmLabel:t(`recordings.cleanupSection.runCleanup`,`Run cleanup`),variant:`danger`})){c(null);try{await f.mutateAsync({includeDebugMedia:r}),await l.refetch()}catch(e){c(e instanceof Error?e.message:String(e))}}},h=async()=>{if(u&&await n({title:t(`recordings.cleanupSection.cancelCleanup`,`Cancel cleanup?`),message:t(`recordings.cleanupSection.stopsAfterTheCurrentStep`,`Stops after the current step. Work already done stays done.`),confirmLabel:t(`recordings.cleanupSection.cancelCleanup2`,`Cancel cleanup`),variant:`danger`}))try{await p.mutateAsync({jobId:u.jobId}),await l.refetch()}catch{}};return e(`section`,{className:`rounded-md border border-border bg-surface p-4`,children:[i(`h2`,{className:`text-sm font-semibold text-foreground`,children:t(`recordings.cleanupSection.cleanup`,`Cleanup`)}),i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:t(`recordings.cleanupSection.onePassOverLeftoverAnalytics`,`One pass over leftover analytics (database + files) and ghost footage rows on frozen locations. Does not time out — progress updates here until it finishes.`)}),e(`label`,{className:`mt-3 flex items-start gap-2 text-[11px] text-foreground`,children:[i(D,{checked:r,disabled:d,onChange:e=>{a(e.target.checked)},className:`mt-0.5 h-3.5 w-3.5 accent-primary`}),i(`span`,{children:t(`recordings.cleanupSection.alsoRemoveDebugMediaMotion`,`Also remove debug media (motion stills and track filmstrips)`)})]}),e(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[e(K,{variant:`unstyled`,type:`button`,disabled:d||f.isPending,onClick:()=>{m()},className:Yo,children:[(d||f.isPending)&&i(V,{className:`h-3 w-3 animate-spin`}),i(se,{className:`h-3 w-3`}),t(`recordings.cleanupSection.runCleanup`,`Run cleanup`)]}),d&&i(K,{variant:`unstyled`,type:`button`,onClick:()=>{h()},className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10`,children:t(`common.cancel`,`Cancel`)})]}),s&&i(`p`,{className:`mt-2 text-[11px] text-danger`,children:s}),u&&e(`div`,{className:`mt-3 space-y-1 rounded-md border border-border px-2.5 py-2`,children:[e(`p`,{className:`text-xs text-foreground`,children:[t(`recordings.cleanupSection.phase`,`Phase:`),` `,i(`span`,{className:`font-medium`,children:u.phase}),d&&i(V,{className:`ml-2 inline h-3 w-3 animate-spin text-primary`})]}),u.detail&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:u.detail}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:Qo(u)}),u.error&&i(`p`,{className:`text-[11px] text-danger`,children:u.error})]})]})}c();var ts=2e3;function ns(){let{t}=J(),n=M(),r=l(),o=Oe(),s=Be(void 0,{refetchInterval:e=>e.state.data?.state===`running`?ts:!1}),c=s.data,u=c?.state===`running`,d=u||o.isPending;a(()=>{c?.state!==`done`||c.finishedAtMs===null||(r.invalidateQueries({queryKey:[[`recording`]]}),r.invalidateQueries({queryKey:[[`pipelineAnalytics`]]}))},[c?.state,c?.finishedAtMs,r]);let f=async()=>{await n({title:t(`recordings.diskReconcileSection.reconcileStorageFromDisk`,`Reconcile storage from disk?`),message:t(`recordings.diskReconcileSection.makesTheDatabaseMatchThe`,`Makes the database match the filesystem: recordings index, tracks, events and media whose files are gone. Favourited tracks without files are deleted. Snapshot-less motion/audio events are deleted. Enrolled identities stay. This cannot be undone.`),confirmLabel:t(`recordings.diskReconcileSection.reconcile`,`Reconcile`),variant:`warning`})&&(await o.mutateAsync(),await s.refetch())},p=u?c.total>0?`Reconciling ${String(c.completed)}/${String(c.total)}…`:`Reconciling…`:o.isPending?`Reconciling…`:`Reconcile from disk`;return e(`section`,{className:`rounded-md border border-border bg-surface p-4`,children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:t(`recordings.diskReconcileSection.diskReconcile`,`Disk reconcile`)}),i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:t(`recordings.diskReconcileSection.deletesDatabaseRowsWhoseFiles`,`Deletes database rows whose files are gone. Enrolled identities stay.`)}),e(`div`,{className:`mt-3 flex flex-col gap-2`,children:[e(K,{variant:`unstyled`,type:`button`,onClick:()=>void f(),disabled:d,className:`inline-flex w-fit items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`,children:[d?i(V,{className:`h-3.5 w-3.5 animate-spin`}):i(oe,{className:`h-3.5 w-3.5`}),p]}),c?.state===`done`?e(`p`,{className:`text-[11px] text-foreground-subtle`,children:[t(`recordings.diskReconcileSection.lastRun`,`Last run:`),` `,t(`recordings.diskReconcileSection.summary`,{completed:String(c.completed),tracks:String(c.tracks),events:String(c.events),media:String(c.mediaDropped)}),c.failed.length>0?t(`recordings.diskReconcileSection.failed`,`, {{value1}} failed ({{value2}})`,{value1:String(c.failed.length),value2:c.failed.join(`, `)}):``,`.`]}):null,c?.state===`error`&&c.error!==null?e(`p`,{className:`text-[11px] text-destructive`,children:[t(`recordings.diskReconcileSection.reconcileFailed`,`Reconcile failed:`),` `,c.error]}):null]})]})}var rs=1e3,is=60*rs,as=60*is;function os(e){return e.toLocaleString(`en-US`)}function ss(e){if(!Number.isFinite(e)||e<0)return`—`;if(e>=as){let t=Math.floor(e/as),n=Math.round(e%as/is);return`${t.toString()}h ${n.toString()}m`}if(e>=is){let t=Math.floor(e/is),n=Math.round(e%is/rs);return`${t.toString()}m ${n.toString()}s`}return`${Math.max(0,Math.round(e/rs)).toString()}s`}function cs(e){let t=Math.max(0,e.observedAt-e.startedAt),n=e.filesTotal===null?`${os(e.filesMoved)} files`:`${os(e.filesMoved)} / ${os(e.filesTotal)} files`,r=e.filesTotal===null||e.filesTotal===0?null:Math.min(1,e.filesMoved/e.filesTotal),i=t>0&&e.filesMoved>0,a=i?`${Y(e.bytesMoved/t*rs)}/s`:null,o=e.filesTotal===null?null:e.filesTotal-e.filesMoved,s=!i||o===null||o<=0?null:`~${ss(o*t/e.filesMoved)} left`;return{counted:n,fraction:r,moved:`${Y(e.bytesMoved)} moved`,rate:a,eta:s}}function ls(e){let t=cs(e);return[t.counted,t.moved,t.rate,t.eta].filter(e=>e!==null).join(` · `)}c();var us=`storage-migration`,ds=[{id:`recordings`,labelKey:`recordings.storageMigrationSection.classRecordings`,locationType:`recordings`},{id:`recordingsLow`,labelKey:`recordings.storageMigrationSection.classRecordingsLow`,locationType:`recordingsLow`},{id:`eventMedia`,labelKey:`recordings.storageMigrationSection.classEventMedia`,locationType:`eventMedia`}],fs=new Set([`planning`,`sealing`,`pausing`,`moving`,`draining`,`verifying`,`repointing`,`refreshing`,`resuming`]);function ps(){let{t}=J(),n=ze(us);return n===`pending`?e(`div`,{className:`flex items-center gap-2 py-8 text-xs text-foreground-subtle`,children:[i(V,{className:`h-4 w-4 animate-spin`}),t(`migration.storageMigrationSection.checkingWhetherStorageMigrationIs`,`Checking whether storage migration is installed…`)]}):n===`unknown`?i(yt,{icon:O,title:t(`migration.storageMigrationSection.couldnTCheckWhetherStorage`,`Couldn't check whether storage migration is installed`),description:t(`migration.storageMigrationSection.theCapabilityRegistryDidNot`,`The capability registry did not answer, so this panel has nothing to report either way — it is not a statement that the capability is missing. Reload to ask again.`)}):n===`absent`?i(yt,{icon:b,title:t(`migration.storageMigrationSection.storageMigrationNotInstalled`,`Storage migration not installed`),description:t(`migration.storageMigrationSection.theCapabilityRegistryAnsweredNo`,`The capability registry answered: no addon in this cluster provides storage-migration. Once one is deployed, this panel moves recordings, low-res recordings and event media to new storage locations in one coordinated, verified operation.`)}):i(ms,{})}function ms(){let{t}=J(),r=M(),{data:a}=Xe({}),[s,c]=o({}),[l,u]=o({}),[d,f]=o(null),[p,m]=o(null),h=n(()=>{let e=new Map;for(let t of a??[]){let n=e.get(t.type);n?n.push(t):e.set(t.type,[t])}return e},[a]),g=n(()=>{let e=new Map;for(let t of a??[]){if(!fe(t))continue;let n=e.get(t.type);n?n.push(t.id):e.set(t.type,[t.id])}let t=new Map;for(let[n,r]of e)r.length===1&&t.set(n,r[0]);return t},[a]),_=Gt({},{refetchInterval:2e3}),v=_.data??null,x=v!==null&&fs.has(v.phase),S=n(()=>{let e={};for(let t of ds){let n=s[t.id];n&&(e[t.id]=n)}return Object.keys(e).length>0?e:void 0},[s]),C=n(()=>{let e={};for(let t of ds){if(!s[t.id])continue;let n=l[t.id]??g.get(t.locationType);n&&(e[t.id]=n)}return Object.keys(e).length>0?e:void 0},[s,l,g]),w=n(()=>({destinations:S??{},...C?{sources:C}:{}}),[S,C]),T=ct(w,{enabled:!1,retry:!1}),E=Ht(),D=bt(),O=async()=>{if(!S)return;m(null);let e=await T.refetch();if(e.error){m(e.error instanceof Error?e.error.message:String(e.error));return}f(e.data??null)},k=async()=>{if(S&&await r({title:t(`migration.storageMigrationSection.startStorageMigration`,`Start storage migration?`),message:t(`migration.storageMigrationSection.copiesTheSelectedClassesFrom`,`Copies the selected classes from the chosen source to the destination, verifies, then either makes the destination the default (if the source was) or disables the source. Safe to re-run if interrupted.`),confirmLabel:t(`migration.storageMigrationSection.startMigration`,`Start migration`),variant:`danger`})){m(null);try{await E.mutateAsync(w),f(null),await _.refetch()}catch(e){m(e instanceof Error?e.message:String(e))}}},A=async()=>{if(v&&await r({title:t(`migration.storageMigrationSection.cancelMigration`,`Cancel migration?`),message:t(`migration.storageMigrationSection.stopsTheInProgressMigration`,`Stops the in-progress migration. Data already moved and verified stays at the destination; anything already repointed is not reverted.`),confirmLabel:t(`migration.storageMigrationSection.cancelMigration2`,`Cancel migration`),variant:`danger`}))try{await D.mutateAsync({jobId:v.jobId}),await _.refetch()}catch{}};return e(`div`,{className:`flex flex-col gap-6`,children:[e(`section`,{className:`rounded-md border border-border bg-surface p-4`,children:[e(`h3`,{className:`flex items-center gap-1.5 text-sm font-semibold text-foreground`,children:[i(b,{className:`h-3.5 w-3.5`}),t(`migration.storageMigrationSection.storageMigration`,`Storage migration`)]}),i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:t(`migration.storageMigrationSection.moveRecordingsLowResRecordings`,`Move recordings, low-res recordings and/or event media from one location to another: copies via the recorder / pipeline-analytics movers, verifies, then either repoints the default (when the source was the default) or disables the source (when it was not). Skip a class with an empty destination.`)}),i(`div`,{className:`mt-3 grid grid-cols-1 gap-3 sm:grid-cols-3`,children:ds.map(n=>{let r=h.get(n.locationType)??[],a=g.get(n.locationType)??``;return e(`div`,{className:`space-y-2`,children:[i(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:t(n.labelKey)}),e(`div`,{className:`space-y-1`,children:[i(`label`,{htmlFor:`migration-from-${n.id}`,className:`text-[10px] text-foreground-subtle`,children:t(`recordings.storageMigrationSection.classFrom`,{label:t(n.labelKey)})}),i(P,{id:`migration-from-${n.id}`,value:l[n.id]??a,onChange:e=>{let t=e.target.value;u(e=>({...e,[n.id]:t}))},disabled:x,className:`w-full`,children:r.map(n=>e(`option`,{value:n.id,children:[n.displayName,fe(n)?``:` (${t(`recordings.storageMigrationSection.readOnly`)})`]},n.id))})]}),e(`div`,{className:`space-y-1`,children:[i(`label`,{htmlFor:`migration-dest-${n.id}`,className:`text-[10px] text-foreground-subtle`,children:t(`recordings.storageMigrationSection.classTo`,{label:t(n.labelKey)})}),e(P,{id:`migration-dest-${n.id}`,value:s[n.id]??``,onChange:e=>{let t=e.target.value;c(e=>({...e,[n.id]:t}))},disabled:x,className:`w-full`,children:[i(`option`,{value:``,children:t(`migration.storageMigrationSection.skip`,`— skip —`)}),r.map(e=>i(`option`,{value:e.id,children:e.displayName},e.id))]})]})]},n.id)})}),p&&i(`p`,{className:`mt-2 text-[11px] text-danger`,children:p}),e(`div`,{className:`mt-3 flex items-center gap-2`,children:[e(K,{variant:`unstyled`,type:`button`,onClick:()=>{O()},disabled:!S||T.isFetching||x,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover disabled:opacity-50`,children:[T.isFetching&&i(V,{className:`h-3 w-3 animate-spin`}),t(`migration.storageMigrationSection.plan`,`Plan`)]}),e(K,{variant:`unstyled`,type:`button`,onClick:()=>{k()},disabled:!S||E.isPending||x,className:`inline-flex items-center gap-1.5 rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50`,children:[E.isPending&&i(V,{className:`h-3 w-3 animate-spin`}),t(`migration.storageMigrationSection.startMigration`,`Start migration`)]})]}),d&&i(`div`,{className:`mt-3 divide-y divide-border rounded-md border border-border`,children:d.moves.length===0?i(`p`,{className:`px-2.5 py-1.5 text-[11px] text-foreground-subtle`,children:t(`migration.storageMigrationSection.nothingToMoveSelectedDestinations`,`Nothing to move — selected destinations match the current defaults.`)}):d.moves.map(t=>e(`div`,{className:`px-2.5 py-1.5 text-[11px] text-foreground`,children:[t.storageClass,`: `,t.fromLocationId,` → `,t.toLocationId]},`${t.storageClass}-${t.toLocationId}`))}),v&&e(`div`,{className:`mt-4 border-t border-border pt-3`,children:[e(`div`,{className:`flex items-center justify-between`,children:[i(`h4`,{className:`text-xs font-semibold text-foreground`,children:t(`migration.storageMigrationSection.migrationStatus`,`Migration status`)}),x&&e(K,{variant:`unstyled`,type:`button`,onClick:()=>{A()},className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10`,children:[i(y,{className:`h-3 w-3`}),t(`common.cancel`,`Cancel`)]})]}),e(`p`,{className:`mt-1 text-xs text-foreground`,children:[t(`migration.storageMigrationSection.phase`,`Phase:`),` `,i(`span`,{className:`font-medium`,children:v.phase}),x&&i(V,{className:`ml-2 inline h-3 w-3 animate-spin text-primary`})]}),v.error&&i(`p`,{className:`mt-1 text-[11px] text-danger`,children:v.error}),v.pausedParticipants.length>0&&e(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:[t(`migration.storageMigrationSection.paused`,`Paused:`),` `,v.pausedParticipants.join(`, `)]}),i(`div`,{className:`mt-2 divide-y divide-border rounded-md border border-border`,children:v.moves.map(e=>i(hs,{move:e},`${e.storageClass}-${e.fromLocationId}`))})]}),i(gs,{})]}),i(_s,{running:x}),i(ys,{})]})}function hs({move:t}){let{t:n}=J(),r=t.progress===null?null:cs(t.progress);return e(`div`,{className:`px-2.5 py-1.5 text-[11px]`,children:[e(`div`,{className:`flex items-center justify-between`,children:[e(`span`,{className:`text-foreground`,children:[t.storageClass,`: `,t.fromLocationId,` → `,t.toLocationId]}),e(`span`,{className:`text-foreground-subtle`,children:[t.state??n(`common.pending`),t.error?` (${t.error})`:``]})]}),t.progress!==null&&e(`div`,{className:`mt-1 space-y-1`,children:[r!==null&&r.fraction!==null&&i(`div`,{className:`h-1 w-full overflow-hidden rounded bg-border`,children:i(`div`,{className:`h-full bg-primary`,style:{width:`${(r.fraction*100).toFixed(1)}%`}})}),i(`p`,{className:`text-[10px] text-foreground-subtle`,children:ls(t.progress)})]})]})}function gs(){let{t}=J(),{data:n}=St({});return!n||n.length===0?null:e(`div`,{className:`mt-4 border-t border-border pt-3`,children:[i(`h4`,{className:`text-xs font-semibold text-foreground`,children:t(`migration.storageMigrationSection.migrationHistory`,`Migration history`)}),i(`div`,{className:`mt-2 divide-y divide-border rounded-md border border-border`,children:n.map(t=>e(`div`,{className:`px-2.5 py-1.5 text-[11px] text-foreground-subtle`,children:[i(`span`,{className:`font-medium text-foreground`,children:t.phase}),` · `,Object.entries(t.destinations).filter(e=>typeof e[1]==`string`).map(([e,t])=>`${e} → ${t}`).join(`, `),` · `,new Date(t.startedAt).toLocaleString()]},t.jobId))})]})}function _s({running:t}){let{t:n}=J(),r=M(),a=Ge({},{staleTime:1/0,refetchOnWindowFocus:!1}),s=At(),[c,l]=o(null),u=a.data??[];if(u.length===0)return null;let d=async e=>{if(await r({title:n(`migration.storageMigrationSection.drainRemaining`,`Drain remaining {{storageClass}}?`,{storageClass:e.storageClass}),message:`Moves what is still on ${e.fromLocationId} to ${e.toLocationId}. Nothing is paused and no default is changed — this is the second half of a migration, run on its own. It is resumable: cancelling leaves everything readable from both locations.`,confirmLabel:n(`migration.storageMigrationSection.drainRemaining2`,`Drain remaining`),variant:`danger`})){l(null);try{await s.mutateAsync({classes:[e.storageClass]}),await a.refetch()}catch(e){l(e instanceof Error?e.message:String(e))}}};return e(`section`,{className:`rounded-md border border-border bg-surface p-4`,children:[e(`div`,{className:`flex items-start justify-between gap-2`,children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:n(`migration.storageMigrationSection.leftOnTheOldLocation`,`Left on the old location`)}),e(`div`,{className:`flex shrink-0 items-center gap-2`,children:[i(`span`,{className:`text-[10px] text-foreground-subtle`,children:a.dataUpdatedAt>0?n(`migration.storageMigrationSection.measured`,`Measured {{value1}}`,{value1:new Date(a.dataUpdatedAt).toLocaleTimeString()}):n(`migration.storageMigrationSection.measuredNever`,`Measured — never`)}),i(K,{variant:`unstyled`,type:`button`,onClick:()=>{a.refetch()},disabled:a.isFetching,className:`rounded border border-border px-2 py-1 text-[10px] font-medium text-foreground-subtle hover:bg-surface-hover hover:text-foreground disabled:opacity-50`,children:a.isFetching?n(`migration.storageMigrationSection.counting`,`Counting…`):n(`common.refresh`,`Refresh`)})]})]}),i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:n(`migration.storageMigrationSection.aMigrationRepointsFirstAnd`,`A migration repoints first and drains behind. If the drain was cancelled, failed, or was interrupted by a restart, the data below is still on the source — readable, but not where the defaults now point. Draining moves it; it changes no default and pauses nothing.`)}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:n(`migration.storageMigrationSection.thisCountIsTakenOn`,`This count is taken on demand: measuring it walks the whole media collection, so it is not refreshed on a timer. Press Refresh after a drain finishes.`)}),c&&i(`p`,{className:`mt-2 text-[11px] text-danger`,children:c}),i(`div`,{className:`mt-2 divide-y divide-border rounded-md border border-border`,children:u.map(r=>e(`div`,{className:`flex items-center justify-between gap-2 px-2.5 py-1.5 text-[11px]`,children:[e(`span`,{className:`text-foreground`,children:[r.storageClass,`: `,r.fromLocationId,` → `,r.toLocationId,i(`span`,{className:`ml-2 text-foreground-subtle`,children:vs(r)})]}),i(K,{variant:`unstyled`,type:`button`,onClick:()=>{d(r)},disabled:t||s.isPending,className:`shrink-0 rounded border border-border px-2 py-1 text-[10px] font-medium text-foreground-subtle hover:bg-surface-hover hover:text-foreground disabled:opacity-50`,children:n(`migration.storageMigrationSection.drainRemaining2`,`Drain remaining`)})]},`${r.storageClass}-${r.fromLocationId}`))})]})}function vs(e){if(e.items===null)return q.t(`recordings.storageMigrationSection.residueUnknown`);let t=e.items.toLocaleString(`en-US`);return e.bytes===null?q.t(`recordings.storageMigrationSection.residueRows`,{count:e.items,items:t}):q.t(`recordings.storageMigrationSection.residueSegments`,{count:e.items,items:t,size:Y(e.bytes)})}function ys(){let{t}=J(),{data:n}=ut({},{refetchInterval:2e3}),r=(n??[]).filter(e=>e.migrationJobId===null&&e.job.state===`running`);return r.length===0?null:e(`section`,{className:`rounded-md border border-border bg-surface p-4`,children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:t(`migration.storageMigrationSection.moversRunningOutsideAMigration`,`Movers running outside a migration`)}),i(`div`,{className:`mt-2 divide-y divide-border rounded-md border border-border`,children:r.map(t=>e(`div`,{className:`px-2.5 py-1.5 text-[11px]`,children:[e(`div`,{className:`text-foreground`,children:[t.lane,`: `,t.job.fromLocationId,` → `,t.job.toLocationId]}),i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:ls({filesMoved:t.job.filesMoved,filesTotal:t.job.filesTotal,bytesMoved:t.job.bytesMoved,startedAt:t.job.startedAt,observedAt:t.observedAt})})]},t.job.jobId))})]})}c();function bs({openOnMount:t}){let{t:n}=J(),[r,s]=o(t);return a(()=>{t&&s(!0)},[t]),i(Wt,{expanded:r,onExpandedChange:s,header:e(`span`,{className:`flex items-center gap-2 text-sm font-medium text-foreground`,children:[i(p,{className:`h-3.5 w-3.5`}),n(`archive.tools.title`,`Tools`),i(`span`,{className:`text-[11px] font-normal text-foreground-subtle`,children:n(`archive.tools.subtitle`,`Storage migration, prune events, cleanup, reconcile from disk`)})]}),children:e(`div`,{className:`flex flex-col gap-6`,"data-testid":`archive-tools`,children:[e(`section`,{className:`flex flex-col gap-2`,children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:n(`archive.tools.migration`,`Move storage`)}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`archive.tools.migrationHint`,`Copy footage, low-res footage or event media to a new location, verify, then repoint the default. Applies to every camera.`)}),i(ps,{})]}),e(`section`,{className:`flex flex-col gap-2`,children:[i(`h3`,{className:`text-sm font-semibold text-foreground`,children:n(`archive.tools.pruneEvents`,`Prune old events`)}),i(Jo,{})]}),i($o,{}),i(ns,{})]})})}c();function xs({data:t}){let{t:n}=J(),{hash:r}=on();return a(()=>{r.length>1&&document.getElementById(r.slice(1))?.scrollIntoView({block:`start`})},[r]),e(`div`,{className:`flex flex-col gap-4`,children:[i(Ho,{data:t}),i(Ae,{headingId:`archive-storage`,title:n(`archive.section.storage`,`Storage`),icon:oe,children:i(`div`,{className:`p-3`,children:i(Wo,{})})}),i(Ae,{headingId:`archive-cameras`,title:n(`archive.section.cameras`,`Cameras`),icon:N,children:i(Io,{rows:t.rows,isLoading:t.isLoading})}),i(`div`,{id:`activity`,children:i(Ae,{headingId:`archive-activity`,title:n(`archive.section.activity`,`Activity & health`),icon:x,children:i(`div`,{className:`p-3`,children:i(Vn,{data:t})})})}),i(`div`,{id:`tools`,children:i(bs,{openOnMount:r===`#tools`})})]})}c();function Ss(){let e=We({isCamera:!0,projection:`slim`}),t=Pe({},{refetchOnWindowFocus:!1}),r=kt({},{refetchOnWindowFocus:!1}),i=_t({},{refetchOnWindowFocus:!1}),a=Ee({history:1},{refetchOnWindowFocus:!1}),o=n(()=>(e.data??[]).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data]),s=t.data??null,c=s!==null&&s.devicesRead!==`unavailable`,l=r.data??null,u=i.data??null,d=a.data?.latest??null,f=d===null?null:d.findings,p=n(()=>er({cameras:o,footage:c?s.devices:null,events:l===null?null:l.devices,statuses:u,findings:f}),[o,c,s,l,u,f]);return{cameras:o,rows:p,totals:n(()=>tr(p),[p]),usage:s,footprint:l,statuses:u,findings:f,digestAtMs:d===null?null:d.generatedAt,isLoading:e.isLoading||t.isLoading||r.isLoading}}function Cs(){let{t:e}=J(),t=Ss();return i(sn,{icon:_e,title:e(`nav.archive`,`Archive`),subtitle:e(`archive.subtitle`,`Recorded footage and captured events — what they occupy, where they are written, and how each camera is doing.`),paramName:an,defaultSection:`overview`,sectionsLabel:e(`archive.sections`,`Archive sections`),sections:[{id:`overview`,label:e(`archive.section.overview`,`Overview`),content:i(xs,{data:t})},{id:`cameras`,label:e(`archive.section.cameras`,`Cameras`),ownedParams:[Yt,en],content:i(No,{data:t})}]})}export{Cs as ArchivePage};