@camstack/addon-admin-ui 1.2.331 → 1.2.333

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 (109) hide show
  1. package/dist/assets/{AddonCollectionPage-DpIQBL-z.js → AddonCollectionPage-CIoBP3mw.js} +1 -1
  2. package/dist/assets/Addons-CYurife8.js +1 -0
  3. package/dist/assets/{AdminTabs-CIqJ81O1.js → AdminTabs-B6i9albo.js} +1 -1
  4. package/dist/assets/AiProfiles-DefatWNN.js +3 -0
  5. package/dist/assets/{BrokerForm-Dys69RO8.js → BrokerForm-G9XrjKGE.js} +1 -1
  6. package/dist/assets/{Build-ByaMsUZu.js → Build-CK9gMbbG.js} +1 -1
  7. package/dist/assets/{Calendars-aLTbzETg.js → Calendars-BU6Opl9z.js} +1 -1
  8. package/dist/assets/{Capabilities-vKNWJXIH.js → Capabilities-BcBe9s9N.js} +1 -1
  9. package/dist/assets/{Cluster-CM_TU9eP.js → Cluster-BGRlp6bl.js} +1 -1
  10. package/dist/assets/CompositionEditor-BfaSspe0.js +1 -0
  11. package/dist/assets/CompositionEditorPage-BWKUZAx6.js +1 -0
  12. package/dist/assets/{Data-Co1Ru5wl.js → Data-DEJ5vWM-.js} +1 -1
  13. package/dist/assets/DetectionIntelligence-Cc_2j_mn.js +1 -0
  14. package/dist/assets/{DeviceDetail-Cp6xqV94.js → DeviceDetail-DxJV7LWW.js} +1 -1
  15. package/dist/assets/DeviceDoActionFields-C6Nra0tf.js +1 -0
  16. package/dist/assets/{Devices-CKSZmwEn.js → Devices-C-W0tVdZ.js} +1 -1
  17. package/dist/assets/EmbedPlayerPage-Oe0FvFvc.js +1 -0
  18. package/dist/assets/Events-BdA-6EKT.js +1 -0
  19. package/dist/assets/Identity-C_IYW5aQ.js +1 -0
  20. package/dist/assets/IntegrationDetail-Czw5cBu7.js +1 -0
  21. package/dist/assets/{Integrations-DRcMDP4-.js → Integrations-CsFlTyRZ.js} +1 -1
  22. package/dist/assets/Integrations-OGUJuSLW.js +1 -0
  23. package/dist/assets/Locations-CVb8yN7M.js +3 -0
  24. package/dist/assets/{Logs-DAXcD2Ag.js → Logs-BbynUTpr.js} +1 -1
  25. package/dist/assets/{MotionZonesSettings-CiD4d9Ko.js → MotionZonesSettings-Dmy-ak3d.js} +1 -1
  26. package/dist/assets/MyAccess-B5Uxj7sU.js +2 -0
  27. package/dist/assets/Network-CrBcxi3k.js +1 -0
  28. package/dist/assets/NodeAddonsSettingsPanel-Cz-r_jWX.js +1 -0
  29. package/dist/assets/{NodeInferenceDevices-DG7m5Y7w.js → NodeInferenceDevices-doGYVV9k.js} +1 -1
  30. package/dist/assets/Notifications-BrTqbS8-.js +1 -0
  31. package/dist/assets/Pipeline-DtJwSOxo.js +1 -0
  32. package/dist/assets/Plates-BhYnK-Qp.js +1 -0
  33. package/dist/assets/{PrivacyMaskSettings-CEoJQQNL.js → PrivacyMaskSettings-gkZ-rfwF.js} +1 -1
  34. package/dist/assets/Recordings-CiHg63L8.js +1 -0
  35. package/dist/assets/{ScanNetworkModal-JEhQBxc0.js → ScanNetworkModal-Dr6k6rqq.js} +1 -1
  36. package/dist/assets/{SceneMonitorEditor-C7nLYtWS.js → SceneMonitorEditor-BMMaRKDr.js} +1 -1
  37. package/dist/assets/{Scenes-BpPVAE-1.js → Scenes-D9zdPqnF.js} +1 -1
  38. package/dist/assets/{Settings-CfK7VUrn.js → Settings-BZFl8FPw.js} +1 -1
  39. package/dist/assets/{Showroom-Ci8uBRT6.js → Showroom-CGTdP_g0.js} +1 -1
  40. package/dist/assets/{StorageLocationsPanel-CZTMZPVY.js → StorageLocationsPanel-DAo5m1nf.js} +1 -1
  41. package/dist/assets/{Terminal-BPhklMPi.js → Terminal--lzgL3Lj.js} +1 -1
  42. package/dist/assets/{Viewer-DKC1UyF1.js → Viewer-IeXI_isS.js} +1 -1
  43. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-xWBvqyND.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bcj9N3f0.js} +1 -1
  44. package/dist/assets/{archive-Cudlo5P7.js → archive-qf7N61oH.js} +1 -1
  45. package/dist/assets/authed-media-C9V1ivi6.js +1 -0
  46. package/dist/assets/{boxes-DIXdAt9T.js → boxes-DI7VfA4R.js} +1 -1
  47. package/dist/assets/circle-slash-0zFYNJN7.js +1 -0
  48. package/dist/assets/client-DdkMztV3.js +357 -0
  49. package/dist/assets/{debounced-invalidate-CHSCMizx.js → debounced-invalidate-VXpqhQzk.js} +1 -1
  50. package/dist/assets/{device-integration-icon-D0JHl1uT.js → device-integration-icon-CQ0lcROK.js} +1 -1
  51. package/dist/assets/device-picker-model-J_d064JI.js +1 -0
  52. package/dist/assets/dist-B67uohsT.js +357 -0
  53. package/dist/assets/dist-C46hxek7.js +1 -0
  54. package/dist/assets/{face-bbox-B9Tyg9NW.js → face-bbox-C6dI1IVr.js} +1 -1
  55. package/dist/assets/{hard-drive-download-Dc_abYTk.js → hard-drive-download-BeXr3Yea.js} +1 -1
  56. package/dist/assets/{hostInit-D6ltpv22.js → hostInit-GxNoqHp-.js} +1 -1
  57. package/dist/assets/{index-wFUqYEfd.js → index-C3bM5bVy.js} +3 -3
  58. package/dist/assets/{layers-BKQnUkD2.js → layers-CEVsj3Mc.js} +1 -1
  59. package/dist/assets/location-owned-usage-DaMm5XW4.js +1 -0
  60. package/dist/assets/{mf-entry-bootstrap-0-4930a9c7.js → mf-entry-bootstrap-0-8e3d3b2f.js} +2 -2
  61. package/dist/assets/mount-J_d064JI.js +1 -0
  62. package/dist/assets/notification-schedule-field-AJALoXSU.js +1 -0
  63. package/dist/assets/player-overlays-DcmYuIcm.js +1 -0
  64. package/dist/assets/remoteEntry-AD1D53Cu.js +1 -0
  65. package/dist/assets/{send-BDpImfaU.js → send-Pxs6MTZ3.js} +1 -1
  66. package/dist/assets/{settings-2-CR-WDPMe.js → settings-2-ByTmMAiB.js} +1 -1
  67. package/dist/assets/{square-check-big-CsHHs7_N.js → square-check-big-3sO0xl1v.js} +1 -1
  68. package/dist/assets/{src-De0k1ip_.js → src-P5a2SjeK.js} +3 -3
  69. package/dist/assets/{use-scenes-feed-Bo_WZsYm.js → use-scenes-feed-C0imVbjH.js} +1 -1
  70. package/dist/assets/{use-stationary-objects-Da0t43FO.js → use-stationary-objects-DXtL7ZNW.js} +1 -1
  71. package/dist/assets/useEventInvalidation-J_d064JI.js +1 -0
  72. package/dist/assets/{useNodeUrlSelection-CBUJxmpe.js → useNodeUrlSelection-CgmUsFO-.js} +1 -1
  73. package/dist/assets/user-round-DORFYqPs.js +1 -0
  74. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Cz-1ztlx.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CrirQ440.js} +2 -2
  75. package/dist/index.html +7 -7
  76. package/dist/server/addon.js +11 -2
  77. package/package.json +1 -1
  78. package/dist/assets/Addons-DV6azXtV.js +0 -1
  79. package/dist/assets/AiProfiles-DeT1Enb2.js +0 -3
  80. package/dist/assets/CompositionEditor-DjaR5c8a.js +0 -1
  81. package/dist/assets/CompositionEditorPage-DUNmLk9Z.js +0 -1
  82. package/dist/assets/DetectionIntelligence-wOP9P-Rx.js +0 -1
  83. package/dist/assets/DeviceDoActionFields-B-UaI7n-.js +0 -1
  84. package/dist/assets/EmbedPlayerPage-DLsOxS55.js +0 -1
  85. package/dist/assets/Events-Dyc68nae.js +0 -1
  86. package/dist/assets/Identity-D9V5bdov.js +0 -1
  87. package/dist/assets/IntegrationDetail-dT9dySHX.js +0 -1
  88. package/dist/assets/Integrations-DVuPFBKi.js +0 -1
  89. package/dist/assets/Locations-bMH9yI6x.js +0 -3
  90. package/dist/assets/MyAccess-Od0asOaP.js +0 -2
  91. package/dist/assets/Network-BZoW2JSJ.js +0 -1
  92. package/dist/assets/NodeAddonsSettingsPanel-DuTlgAWG.js +0 -1
  93. package/dist/assets/Notifications-DDG3Z8FY.js +0 -1
  94. package/dist/assets/Pipeline-DMtisKG3.js +0 -1
  95. package/dist/assets/Plates-DKbIAPin.js +0 -1
  96. package/dist/assets/Recordings-B5326osa.js +0 -1
  97. package/dist/assets/authed-media-Bf77DHiU.js +0 -1
  98. package/dist/assets/circle-slash-dArMQdeW.js +0 -1
  99. package/dist/assets/device-picker-model-C3GxEmbZ.js +0 -1
  100. package/dist/assets/dist-C99tjf3g.js +0 -1
  101. package/dist/assets/dist-CUXVcnid.js +0 -357
  102. package/dist/assets/location-owned-usage-BWn9-eob.js +0 -1
  103. package/dist/assets/mount-C3GxEmbZ.js +0 -1
  104. package/dist/assets/notification-schedule-field-BzLlAfqp.js +0 -1
  105. package/dist/assets/player-overlays-BHG5CSFQ.js +0 -1
  106. package/dist/assets/remoteEntry-DRuu7Vh_.js +0 -1
  107. package/dist/assets/src-BpnJ-sMW.js +0 -357
  108. package/dist/assets/useEventInvalidation-C3GxEmbZ.js +0 -1
  109. package/dist/assets/user-round-B_-xKzQ7.js +0 -1
@@ -1,3 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,a,b as o,q as s,t as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{W as d,Z as f,_t as p,at as m,ct as h,st as g,vt as _}from"./player-overlays-BHG5CSFQ.js";import{$t as v,Cn as y,Gi as b,Gu as x,Hn as S,Jt as C,Kl as w,Kt as T,Nu as E,Qt as D,Sl as O,Sn as k,Tt as A,Wu as j,Xt as M,Zt as N,_n as P,au as F,bn as I,id as ee,k as te,ou as L,qt as R,sd as z,td as B,tn as V,un as H,vu as ne,wd as U,wt as W,xu as G,yu as K}from"./src-De0k1ip_.js";import{t as re}from"./boxes-DIXdAt9T.js";import{t as ie}from"./send-BDpImfaU.js";import{Dn as q}from"./src-BpnJ-sMW.js";import{t as J}from"./useTranslation-Bc5yH9V9.js";import"./mount-C3GxEmbZ.js";import{t as Y}from"./AdminPage-CiKtOLQm.js";import{t as ae}from"./AdminTabs-CIqJ81O1.js";var oe=_(`message-square-plus`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M12 8v6`,key:`1ib9pf`}],[`path`,{d:`M9 11h6`,key:`1fldmi`}]]);n();var se=[`llm`,`listProfiles`],ce=[`llm`,`listProfileKinds`],le=[`llm`,`getDefaults`],ue=[`llm`,`listRuntimeNodes`],de=[`llm`,`listModelCatalog`],fe=[`llm`,`getUsage`],pe=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],me=new Map(Object.entries({openai:z,anthropic:z,google:z,"openai-compatible":ne,"managed-local":ee,"apple-foundation":ee}));function he(e){return me.get(e)??null}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Q(e){return e===!0}function ge(e){return{model:e.model,baseUrl:e.baseUrl,apiKey:e.apiKey,supportsVision:e.supportsVision,temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled,contextSize:e.runtime?.contextSize,gpuLayers:e.runtime?.gpuLayers,threads:e.runtime?.threads,parallel:e.runtime?.parallel,idleStopMinutes:e.runtime?.idleStopMinutes,batchSize:e.runtime?.batchSize,ubatchSize:e.runtime?.ubatchSize,flashAttention:e.runtime?.flashAttention,mlock:e.runtime?.mlock,noMmap:e.runtime?.noMmap,cacheTypeK:e.runtime?.cacheTypeK,cacheTypeV:e.runtime?.cacheTypeV,extraArgs:be(e.runtime?.extraArgs??[])}}var _e=[`f32`,`f16`,`q8_0`,`q5_1`,`q5_0`,`q4_1`,`q4_0`];function ve(e){return typeof e==`string`&&_e.includes(e)?e:void 0}function ye(e){let t=[],n=``,r=null;for(let i of e){if(r!==null){i===r?r=null:n+=i;continue}if(i===`"`||i===`'`){r=i;continue}if(/\s/.test(i)){n!==``&&t.push(n),n=``;continue}n+=i}return n!==``&&t.push(n),t}function be(e){return e.map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)}var xe=[`--jinja`,`--cont-batching`];function Se(e,t,n){let r=Z(e.threads),i=Z(e.batchSize),a=Z(e.ubatchSize),o=ve(e.cacheTypeK),s=ve(e.cacheTypeV);return{nodeId:t,engine:`llama-cpp`,model:n,extraArgs:[...ye(X(e.extraArgs)??``)],contextSize:Z(e.contextSize)??4096,gpuLayers:Z(e.gpuLayers)??0,...r===void 0?{}:{threads:r},parallel:Z(e.parallel)??1,...i===void 0?{}:{batchSize:i},...a===void 0?{}:{ubatchSize:a},flashAttention:Q(e.flashAttention),mlock:Q(e.mlock),noMmap:Q(e.noMmap),...o===void 0?{}:{cacheTypeK:o},...s===void 0?{}:{cacheTypeV:s},autoStart:Q(e.autoStart),idleStopMinutes:Z(e.idleStopMinutes)??30}}function Ce(e,t,n,r,i){let a={id:n?.id??crypto.randomUUID(),name:t,kind:e,addonId:`ai`,enabled:n?.enabled??!0,model:X(r.model)??n?.model??``,supportsVision:i?.supportsVision??Q(r.supportsVision),timeoutMs:Z(r.timeoutMs)??q.totalMs,connectTimeoutMs:Z(r.connectTimeoutMs)??q.connectMs,firstTokenTimeoutMs:Z(r.firstTokenTimeoutMs)??q.firstTokenMs,idleTimeoutMs:Z(r.idleTimeoutMs)??q.idleMs,retry:{enabled:Q(r.retryEnabled),maxAttempts:Z(r.retryMaxAttempts)??1},toolsEnabled:Q(r.toolsEnabled)},o=X(r.baseUrl),s=X(r.apiKey),c=Z(r.temperature),l=Z(r.topP),u=Z(r.topK),d=Z(r.maxTokens),f=Z(r.contextLength),p=X(r.systemPrompt);return{...a,...o===void 0?{}:{baseUrl:o},...s===void 0?{}:{apiKey:s},...c===void 0?{}:{temperature:c},...l===void 0?{}:{topP:l},...u===void 0?{}:{topK:u},...d===void 0?{}:{maxTokens:d},...f===void 0?{}:{contextLength:f},...p===void 0?{}:{systemPrompt:p},...i===void 0?{}:{model:i.modelId,runtime:Se(r,i.nodeId,i.model)}}}function we(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Te=`apple-system`;function Ee(e,t,n,r){return{...Ce(`apple-foundation`,e,t,n),model:Te,supportsVision:!1,appleFoundation:{nodeId:r}}}var De={deviceNotEligible:{key:`ai.appleNotEligible`,text:`not eligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,text:`Apple Intelligence off`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,text:`model downloading`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,text:`macOS too old`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,text:`helper missing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,text:`helper crashed`,tone:`danger`}};function Oe(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:`unknown`,detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:`available`,detail:`macOS ${n.osVersion} · ${n.imageInput?`text + images`:`text only`}`,tone:`success`};case`unavailable`:{let t=De[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:t.text,detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:`not a Mac`,detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var ke=2e3;function $(e){return`${(e/1e9).toFixed(2)} GB`}function Ae(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function je({nodeId:e,value:t,onChange:n}){let{t:o}=J(),u=m(),[d,f]=s(``),[p,h]=s(null),[g,_]=s(!1),v=a({queryKey:de,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),b=a({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:e})}),x=c({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),_(!1),e.ok&&n({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),C=c({mutationFn:t=>u.trpcClient.llm.installModel.mutate({nodeId:e,model:t}),onSuccess:()=>{_(!0),b.refetch()}}),w=a({queryKey:ue,enabled:C.isPending,refetchInterval:C.isPending?ke:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,T=i(()=>{let t=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(b.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(t=>({value:`node:${t.file}`,label:o(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:t.file,size:$(t.sizeBytes),node:e})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:o(`ai.selectModel`,`Select a model…`)},...t,...n,...r]},[v.data,b.data,p,e,o]),D=e=>{if(e===``){n(null);return}if(e===`custom`){if(p?.ok!==!0)return;n({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),r=v.data?.find(e=>e.id===t);n({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:r?.purpose===`vision`});return}let t=e.slice(5),r=b.data?.find(e=>e.file===t);r?.path!==void 0&&n({model:{kind:`path`,path:r.path},modelId:t,supportsVision:!1})},O=e=>{d.trim()!==``&&x.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return r(`div`,{className:`space-y-2`,children:[r(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-model`,children:o(`ai.model`,`Model`)}),l(k,{id:`ai-model`,value:Ae(t),options:T,onChange:e=>D(e.target.value)})]}),r(`div`,{className:`rounded-md border border-border bg-surface-subtle px-3 py-2.5`,children:[l(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:o(`ai.hfTitle`,`Add a model from Hugging Face`)}),l(`p`,{className:`mb-2 text-[10px] leading-relaxed text-foreground-subtle`,children:o(`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.`)}),r(`div`,{className:`flex gap-2`,children:[l(V,{value:d,onChange:e=>f(e.target.value),placeholder:`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`,onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),O())}}),r(y,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||x.isPending,onClick:()=>O(),children:[x.isPending?l(E,{className:`h-3.5 w-3.5 animate-spin`}):l(L,{className:`h-3.5 w-3.5`}),o(`ai.hfCheck`,`Check`)]})]}),x.isError&&l(`p`,{className:`mt-2 text-[11px] text-danger`,children:x.error instanceof Error?x.error.message:o(`common.error`,`Error`)}),p?.ok===!1&&r(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-2.5 py-2`,children:[l(`p`,{className:`text-[11px] text-danger`,children:p.message}),p.candidates!==void 0&&p.candidates.length>0&&l(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:p.candidates.map(e=>l(`button`,{type:`button`,className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:border-primary/50`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),x.mutate({ref:t})},children:e},e))}),p.requiredBytes!==void 0&&l(y,{size:`sm`,variant:`secondary`,type:`button`,className:`mt-2`,onClick:()=>O(p.requiredBytes),children:o(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]}),p?.ok===!0&&r(`div`,{className:`mt-2 rounded-md border border-border bg-surface px-2.5 py-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[l(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),l(S,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),l(S,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),r(`div`,{className:`mt-2 flex items-center gap-2`,children:[r(y,{size:`sm`,type:`button`,disabled:C.isPending||g,onClick:()=>C.mutate(p.model),children:[C.isPending?l(E,{className:`h-3.5 w-3.5 animate-spin`}):l(B,{className:`h-3.5 w-3.5`}),g?o(`ai.hfInstalled`,`Downloaded`):o(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),w!==void 0&&l(`span`,{className:`text-[10px] text-foreground-subtle`,children:w.phase===`verifying`?o(`ai.hfVerifying`,`verifying {{file}}…`,{file:w.file}):o(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:w.file,index:w.fileIndex,count:w.fileCount,done:$(w.downloadedBytes),total:w.totalBytes===void 0?``:` / ${$(w.totalBytes)}`})})]}),C.isError&&l(`p`,{className:`mt-1.5 text-[11px] text-danger`,children:C.error instanceof Error?C.error.message:o(`common.error`,`Error`)})]})]})]})}function Me({value:e,onChange:t}){let{t:n}=J(),i=m(),o=a({queryKey:ue,queryFn:()=>i.trpcClient.llm.listRuntimeNodes.query({})});return r(`div`,{children:[l(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:n(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&r(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(E,{className:`h-3.5 w-3.5 animate-spin`}),n(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&l(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:n(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&l(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&l(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(i=>{let a=Oe(i),o=a.nodeId===e;return r(`button`,{type:`button`,role:`radio`,"aria-checked":o,disabled:!a.selectable&&!o,onClick:()=>t(a.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 ${o?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[r(`span`,{className:`min-w-0`,children:[l(`span`,{className:`block font-medium text-foreground`,children:a.nodeId}),a.detail!==null&&l(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:a.detail})]}),l(S,{variant:a.tone,children:n(a.labelKey,a.labelDefault)})]},a.nodeId)})}),l(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:n(`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.`)})]})}n();function Ne({kind:e,className:t}){let n=he(e.kind);return n===null?l(`span`,{className:t,children:e.icon}):l(n,{className:t})}function Pe({kinds:e,onPick:t,onCancel:n}){let{t:a}=J(),o=i(()=>we(e),[e]);return l(T,{open:!0,onOpenChange:e=>!e&&n(),children:r(C,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[l(N,{children:l(D,{children:a(`ai.chooseKind`,`Choose a profile type`)})}),r(R,{className:`space-y-4 pr-1`,children:[o.length===0&&l(`p`,{className:`text-xs text-foreground-subtle`,children:a(`ai.noKinds`,`No AI provider is installed.`)}),o.map(e=>r(`div`,{children:[l(`div`,{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e.addonId}),l(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.kinds.map(n=>r(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs transition-colors hover:border-primary/50 hover:bg-surface-hover`,children:[l(Ne,{kind:n,className:`h-5 w-5 text-foreground-subtle`}),l(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]}),l(M,{children:l(y,{size:`sm`,variant:`secondary`,type:`button`,onClick:n,children:a(`common.cancel`,`Cancel`)})})]})})}function Fe({kind:e,existing:t,onSave:n,onCancel:a,saving:c,error:u}){let{t:d}=J(),f=e.kind===`managed-local`,p=e.kind===`apple-foundation`,[m,h]=s(t?.appleFoundation?.nodeId??null),[g,_]=s(t?.name??e.label),[v,b]=s(()=>t===null?{}:ge(t)),[x,w]=s(t?.runtime?.nodeId??`hub`),[O,k]=s(()=>t?.runtime===void 0?null:{model:t.runtime.model,modelId:t.model,supportsVision:t.supportsVision}),A=i(()=>ye(X(v.extraArgs)??``),[v.extraArgs]),j=()=>{if(p){if(m===null)return;n(Ee(g,t,v,m));return}if(!f){n(Ce(e.kind,g,t,v));return}O!==null&&n(Ce(e.kind,g,t,v,{nodeId:x,model:O.model,modelId:O.modelId,supportsVision:O.supportsVision}))},P=c||g.trim()===``||f&&O===null||p&&m===null;return l(T,{open:!0,onOpenChange:e=>!e&&a(),children:r(C,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[l(N,{children:r(D,{className:`flex items-center gap-2`,children:[l(Ne,{kind:e,className:`h-4 w-4 text-foreground-subtle`}),t===null?d(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):d(`ai.editProfile`,`Edit {{name}}`,{name:t.name})]})}),r(R,{className:`space-y-3 pr-1`,children:[u!==null&&l(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:u}),r(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-profile-name`,children:d(`ai.name`,`Name`)}),l(V,{id:`ai-profile-name`,value:g,onChange:e=>_(e.target.value),placeholder:e.label})]}),f&&r(o,{children:[l(te,{selectedNodeId:x,onSelect:w,label:d(`ai.runtimeNode`,`Runtime node`),alwaysShow:!0}),l(je,{nodeId:x,value:O,onChange:k}),r(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-extra-args`,children:d(`ai.extraArgs`,`Additional llama-server arguments`)}),l(V,{id:`ai-extra-args`,value:X(v.extraArgs)??``,onChange:e=>b({...v,extraArgs:e.target.value}),placeholder:xe.join(` `)}),A.length>0&&l(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:A.map((e,t)=>l(S,{variant:`default`,children:e},`${e}-${String(t)}`))}),l(`p`,{className:`mt-1 text-[10px] leading-relaxed text-foreground-subtle`,children:d(`ai.extraArgsHint`,`Flags this form does not already own. Vision models generally need --jinja; some language-only models do not like it. Context size, GPU layers, parallel slots, flash attention and the KV-cache types are set in the fields below — repeating one here is rejected at start.`)})]})]}),p&&l(Me,{value:m,onChange:h}),l(H,{schema:e.configSchema,values:v,onChange:b}),t!==null&&l(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)})]}),r(M,{children:[f&&O===null&&l(S,{variant:`warning`,children:d(`ai.pickModelFirst`,`pick a model`)}),p&&m===null&&l(S,{variant:`warning`,children:d(`ai.pickAppleNodeFirst`,`pick a Mac`)}),l(y,{size:`sm`,variant:`secondary`,type:`button`,onClick:a,children:d(`common.cancel`,`Cancel`)}),r(y,{size:`sm`,type:`button`,disabled:P,onClick:j,children:[c&&l(E,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`ai.createProfile`,`Create profile`):d(`ai.saveChanges`,`Save changes`)]})]})]})})}n();function Ie(e){return[{key:`name`,header:e.t(`ai.colProfile`,`Profile`),render:t=>{let n=e.kindByName.get(t.kind);return r(`span`,{className:`flex items-center gap-2`,children:[l(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:n?.label??t.kind,children:n===void 0?l(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):l(Ne,{kind:n,className:`h-4 w-4 text-foreground-subtle`})}),r(`span`,{className:`min-w-0`,children:[l(`span`,{className:`block truncate text-sm font-medium text-foreground`,children:t.name}),e.testResult?.id===t.id&&l(`span`,{className:`block truncate text-[10px] ${e.testResult.ok?`text-success`:`text-danger`}`,children:e.testResult.text})]})]})}},{key:`kind`,header:e.t(`ai.colKind`,`Kind`),nowrap:!0,render:t=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByName.get(t.kind)?.label??t.kind})},{key:`model`,header:e.t(`ai.colModel`,`Model`),render:e=>l(`span`,{className:`text-[11px] text-foreground`,children:e.model})},{key:`vision`,header:e.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:t=>t.supportsVision?l(S,{variant:`info`,style:`outline`,children:e.t(`ai.vision`,`vision`)}):l(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})},{key:`node`,header:e.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>e.runtime===void 0?l(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):l(S,{variant:`default`,children:e.runtime.nodeId})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>l(v,{checked:t.enabled,onCheckedChange:()=>e.onToggle(t),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>r(`span`,{className:`flex items-center justify-end gap-1`,children:[l(y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?l(E,{className:`h-3.5 w-3.5 animate-spin`}):l(ie,{className:`h-3.5 w-3.5`})}),l(y,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),title:e.t(`common.edit`,`Edit`),children:l(G,{className:`h-3.5 w-3.5`})}),l(y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:e.t(`common.delete`,`Delete`),children:l(g,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Le(){let{t:e}=J(),t=m(),[n,o]=s({mode:`closed`}),[u,d]=s(null),[f,p]=s(null),h=a({queryKey:se,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),g=a({queryKey:ce,queryFn:async()=>(await t.trpcClient.llm.listProfileKinds.query({})).map(e=>({...e,configSchema:e.configSchema}))}),_=()=>{h.refetch()},v=c({mutationFn:e=>t.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{o({mode:`closed`}),p(null),_()},onError:t=>p(t instanceof Error?t.message:e(`ai.saveFailed`,`Save failed`))}),b=c({mutationFn:e=>t.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:_}),x=c({mutationFn:e=>t.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>d({id:t.id,ok:e.ok,text:e.ok?`${e.text} (${String(e.usage.outputTokens)} tok, ${String(e.latencyMs)}ms)`:`${e.code}: ${e.message}`})}),S=h.data??[],C=i(()=>g.data??[],[g.data]),T=i(()=>{let e=new Map;for(let t of C)e.set(t.kind,t);return e},[C]);return r(Y,{icon:w,title:e(`ai.profilesTitle`,`AI profiles`),subtitle:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),actions:r(y,{size:`sm`,type:`button`,onClick:()=>{p(null),o({mode:`pick-kind`})},children:[l(K,{className:`h-3.5 w-3.5`}),e(`ai.addProfile`,`Add profile`)]}),children:[h.isError&&l(I,{title:e(`ai.loadFailed`,`Failed to load profiles`),message:h.error instanceof Error?h.error.message:e(`common.error`,`Error`),onRetry:()=>void h.refetch()}),l(Re,{profiles:S}),h.isLoading&&l(`div`,{className:`flex items-center justify-center py-16`,children:l(E,{className:`h-6 w-6 animate-spin text-primary`})}),!h.isLoading&&S.length===0&&l(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}),S.length>0&&l(P,{children:l(W,{columns:Ie({kindByName:T,testResult:u,testingId:x.isPending?x.variables?.id??null:null,t:e,onToggle:e=>v.mutate({...e,enabled:!e.enabled,apiKey:`__redacted__`}),onTest:e=>x.mutate(e),onEdit:e=>{let t=T.get(e.kind);t!==void 0&&(p(null),o({mode:`form`,kind:t,profile:e}))},onDelete:e=>b.mutate(e)}),rows:S,rowKey:e=>e.id,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),n.mode===`pick-kind`&&l(Pe,{kinds:C,onCancel:()=>o({mode:`closed`}),onPick:e=>o({mode:`form`,kind:e,profile:null})}),n.mode===`form`&&l(Fe,{kind:n.kind,existing:n.profile,saving:v.isPending,error:f,onSave:e=>v.mutate(e),onCancel:()=>o({mode:`closed`})})]})}function Re({profiles:e}){let{t}=J(),n=m(),i=a({queryKey:le,queryFn:()=>n.trpcClient.llm.getDefaults.query({})}),o=c({mutationFn:e=>n.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{i.refetch()}}),s=e=>(i.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?t(`ai.defaultVision`,`Default vision profile`):t(`ai.defaultText`,`Default text profile`);return l(P,{children:l(`div`,{className:`grid gap-4 p-4 sm:grid-cols-2`,children:pe.map(({purpose:n,visionOnly:i})=>{let a=i?e.filter(e=>e.supportsVision):e,c=s(n),d=e.find(e=>e.id===c);return r(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`llm-default-${n}`,children:u(n)}),r(`select`,{id:`llm-default-${n}`,"aria-label":u(n),className:`h-7 w-full rounded-md border border-border bg-surface px-2.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:c,onChange:e=>o.mutate({purpose:n,profileId:e.target.value===``?null:e.target.value}),children:[l(`option`,{value:``,children:t(`ai.none`,`None`)}),c!==``&&!a.some(e=>e.id===c)&&l(`option`,{value:c,children:d?.name??c}),a.map(e=>r(`option`,{value:e.id,children:[e.name,` · `,e.model]},e.id))]}),c!==``&&d===void 0&&l(`p`,{className:`mt-1 text-[10px] text-danger`,children:t(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&l(`p`,{className:`mt-1 text-[10px] text-warning`,children:t(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&l(`p`,{className:`mt-1 text-[10px] text-danger`,children:String(o.error)})]},n)})})})}n();var ze=5e3;function Be(e){return`${(e/1e9).toFixed(1)} GB`}function Ve(){let{t:e}=J(),t=m(),n=a({queryKey:ue,refetchInterval:ze,queryFn:()=>t.trpcClient.llm.listRuntimeNodes.query({})}),o=i(()=>[{key:`node`,header:e(`ai.colNode`,`Node`),render:e=>l(`span`,{className:`text-sm font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:e(`ai.colState`,`State`),nowrap:!0,render:t=>r(`span`,{className:`flex items-center gap-1.5`,children:[l(S,{variant:t.reachable?`success`:`danger`,children:t.reachable?t.status?.state??e(`ai.ready`,`ready`):e(`ai.unreachable`,`unreachable`)}),t.status?.downloadProgress!==void 0&&l(S,{variant:`info`,children:`${String(Math.round(t.status.downloadProgress*100))}%`})]})},{key:`model`,header:e(`ai.colModel`,`Model`),render:e=>l(`span`,{className:`text-[11px] text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:e(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.disk===void 0?`—`:Be(e.disk.modelsBytes)})},{key:`apple`,header:e(`ai.colApple`,`Apple on-device`),render:t=>{let n=Oe(t);return r(`span`,{className:`flex flex-col items-start gap-0.5`,children:[l(S,{variant:n.tone,children:e(n.labelKey,n.labelDefault)}),n.detail!==null&&l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n.detail})]})}},{key:`error`,header:e(`ai.colError`,`Error`),render:e=>e.error===void 0?l(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):l(`span`,{className:`text-[11px] text-danger`,children:e.error})}],[e]),s=n.data??[];return r(Y,{icon:F,title:e(`ai.runtimesTitle`,`Managed runtimes`),subtitle: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.`),children:[n.isError&&l(I,{title:e(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:n.error instanceof Error?n.error.message:e(`common.error`,`Error`),onRetry:()=>void n.refetch()}),s.length===0?l(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):l(P,{children:l(W,{columns:o,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:A})})]})}var He=f(`/addon/ai/test-chat`),Ue=f(`/addon/ai/test-chat/chats`),We=6e5;function Ge(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),We)}function Ke(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qe(e){if(!Ke(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 Je=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Ye(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ke(t))return null;switch(t.kind){case`status`:{let e=Je.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:qe(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:`the provider returned an error`};default:return null}}async function*Xe(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=Ye(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=Ye(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Ze(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Qe(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function $e(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 et(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 tt(e,t){switch(e){case`resolving-image`:return`fetching the picture…`;case`connecting`:return`connecting to the provider…`;case`first-token-wait`:return t>0?`the model is loading / thinking — a cold load can take minutes (up to ${String(Math.round(t/1e3))}s)`:`the model is loading / thinking — a cold load can take minutes`;case`streaming`:return`answering…`}}n();var nt=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],rt=360*60*1e3,it=40,at=160,ot={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function st(){let{t:n}=J(),o=m(),[c,d]=s(``),[f,_]=s(``),[v,b]=s(``),[S,C]=s([]),[w,T]=s(null),[E,D]=s(`none`),[A,j]=s(`throwaway`),[M,N]=s(null),[F,ee]=s([]),[te,L]=s(null),[R,z]=s(null),B=t(null);u(()=>()=>B.current?.abort(),[]);let H=e(async()=>{let e=await fetch(Ue,{credentials:`same-origin`});e.ok&&ee((await e.json()).chats??[])},[]);u(()=>{A===`persistent`&&H()},[A,H]);let ne=a({queryKey:se,queryFn:()=>o.trpcClient.llm.listProfiles.query({})}),W=i(()=>(ne.data??[]).filter(e=>e.enabled),[ne.data]),G=W.find(e=>e.id===c)??null,K=R!==null,re=e(async(e,t)=>{let r=new AbortController;B.current=r,L(null);let i=Ge(G??{});z({...ot,firstTokenTimeoutMs:i??0});let a=``,o=null,s,l=null,u=null,d;try{let n=await fetch(He,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:r.signal,body:JSON.stringify({profileId:c,messages:e,...f.trim()===``?{}:{system:f.trim()},...t===void 0?{}:{attachment:t},...i===void 0?{}:{firstTokenTimeoutMs:i},...A===`persistent`?{persist:!0,...M===null?{}:{conversationId:M}}:{}})});if(!n.ok||n.body===null){let e=await n.text().catch(()=>``);throw Error(e.length>0?e:`HTTP ${String(n.status)}`)}for await(let e of Xe(n.body))switch(e.kind){case`status`:z(t=>({...t??ot,phase:e.phase}));break;case`meta`:o=e.mediaSent,s=e.model,z(t=>({...t??ot,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:a+=e.text,z(e=>({...e??ot,text:a}));break;case`done`:u={outputTokens:e.outputTokens,latencyMs:e.latencyMs},d=e.conversationId;break;case`error`:l=`${e.code}: ${e.message}`;break}}catch(e){r.signal.aborted||L(e instanceof Error?e.message:n(`common.error`,`Error`))}finally{B.current=null,z(null)}d!==void 0&&(N(d),H());let p=r.signal.aborted&&a.length>0;l===null&&a.length===0&&!p||C(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:l??a,...l===null?{}:{failed:!0},...o===null?{}:{attachment:o},...s!==void 0&&l===null?{model:s}:{},...u===null?{}:u}])},[A,M,G,c,H,f,n]),q=e(()=>{let e=v.trim();if(e===``||c===``||K)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...w===null?{}:{attachmentLabel:w.label,attachmentKind:w.ref.kind}},n=[...S,t];C(n),b(``);let r=w?.ref;T(null),D(`none`),re(A===`persistent`&&M!==null?[{role:`user`,content:e}]:Ze(n),r)},[A,M,v,w,c,re,K,S]),ae=()=>B.current?.abort(),ce=()=>{B.current?.abort(),C([]),T(null),b(``),L(null),z(null),N(null)},le=async e=>{B.current?.abort();let t=await fetch(`${Ue}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();N(e),C($e(n)),z(null),L(null)};return r(Y,{icon:x,title:n(`ai.testTitle`,`Test chat`),subtitle:n(A===`persistent`?`ai.testSubtitlePersistent`:`ai.testSubtitle`,A===`persistent`?`Conversations are saved for you and can be reopened. Throwaway mode is still available.`:`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.`),actions:r(y,{size:`sm`,variant:`secondary`,type:`button`,disabled:S.length===0&&w===null,onClick:ce,children:[l(g,{className:`h-3.5 w-3.5`}),n(`ai.clearChat`,`Clear`)]}),children:[r(P,{className:`space-y-3 p-4`,children:[r(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[r(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-test-profile`,children:n(`ai.profile`,`Profile`)}),l(k,{id:`ai-test-profile`,value:c,onChange:e=>d(e.target.value),options:[{value:``,label:n(`ai.selectProfile`,`Select a profile…`)},...W.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),W.length===0&&!ne.isLoading&&l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:n(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),r(`div`,{children:[l(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-test-system`,children:n(`ai.systemPrompt`,`System prompt (optional)`)}),l(V,{id:`ai-test-system`,value:f,onChange:e=>_(e.target.value),placeholder:n(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l(y,{size:`sm`,variant:A===`throwaway`?`primary`:`outline`,type:`button`,onClick:()=>{j(`throwaway`),N(null)},children:n(`ai.throwawayMode`,`Throwaway`)}),l(y,{size:`sm`,variant:A===`persistent`?`primary`:`outline`,type:`button`,onClick:()=>j(`persistent`),children:n(`ai.saveConversation`,`Save conversation`)})]}),A===`persistent`&&r(`div`,{className:`space-y-2`,children:[l(`div`,{className:`flex items-center gap-2`,children:r(y,{size:`sm`,variant:`secondary`,type:`button`,onClick:ce,children:[l(oe,{className:`h-3.5 w-3.5`}),n(`ai.newChat`,`New chat`)]})}),F.length>0&&l(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:F.map(e=>l(`button`,{type:`button`,onClick:()=>void le(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover ${e.id===M?`bg-primary/10`:``}`,children:l(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),l(`p`,{className:`text-[10px] text-foreground-subtle`,children:n(`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.`)}),G!==null&&!G.supportsVision&&l(`p`,{className:`text-[10px] text-warning`,children:n(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]}),te!==null&&l(I,{title:n(`ai.chatFailed`,`The test call failed`),message:te}),l(ct,{turns:S,live:R}),r(P,{className:`space-y-2 p-3`,children:[w!==null&&r(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-surface px-2.5 py-1.5`,children:[w.ref.kind===`snapshot`?l(p,{className:`h-3.5 w-3.5 text-foreground-subtle`}):l(U,{className:`h-3.5 w-3.5 text-foreground-subtle`}),l(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-foreground`,children:w.label}),l(y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>T(null),children:l(O,{className:`h-3.5 w-3.5`})})]}),r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(y,{size:`sm`,variant:E===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>D(E===`snapshot`?`none`:`snapshot`),children:[l(p,{className:`h-3.5 w-3.5`}),n(`ai.attachSnapshot`,`Camera snapshot`)]}),r(y,{size:`sm`,variant:E===`track`?`primary`:`outline`,type:`button`,onClick:()=>D(E===`track`?`none`:`track`),children:[l(U,{className:`h-3.5 w-3.5`}),n(`ai.attachTrack`,`Recent track`)]})]}),E===`snapshot`&&l(dt,{onPick:e=>{T({ref:{kind:`snapshot`,deviceId:e.id},label:n(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:e.name})}),D(`none`)}}),E===`track`&&l(pt,{onPick:(e,t)=>{T({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:n(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),D(`none`)}}),r(`div`,{className:`flex items-center gap-2`,children:[l(V,{value:v,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),q())},placeholder:n(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":n(`ai.message`,`Message`)}),K?r(y,{size:`sm`,variant:`secondary`,type:`button`,onClick:ae,children:[l(h,{className:`h-3.5 w-3.5`}),n(`ai.stop`,`Stop`)]}):r(y,{size:`sm`,type:`button`,disabled:v.trim()===``||c===``,onClick:q,children:[l(ie,{className:`h-3.5 w-3.5`}),n(`ai.send`,`Send`)]})]})]})]})}function ct({turns:e,live:t}){let{t:n}=J();return e.length===0&&t===null?l(`div`,{className:`py-12 text-center text-xs text-foreground-subtle`,children:n(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):l(P,{children:r(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto p-3`,children:[e.map(e=>l(lt,{turn:e},e.id)),t!==null&&r(`div`,{className:`space-y-1`,children:[t.mediaSent!==null&&l(ut,{attachment:t.mediaSent}),t.text.length>0&&l(lt,{turn:{id:`live`,role:`assistant`,content:t.text},streaming:!0}),r(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[l(E,{className:`h-3.5 w-3.5 animate-spin`}),tt(t.phase,t.firstTokenTimeoutMs)]})]})]})})}function lt({turn:e,streaming:t=!1}){let n=e.role===`user`,i=e.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return l(`div`,{className:`flex ${n?`justify-end`:`justify-start`}`,children:r(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${n?`border-primary/40 bg-primary/10`:i}`,children:[r(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[e.content,t&&l(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),e.attachment!==void 0&&l(ut,{attachment:e.attachment}),e.attachmentLabel!==void 0&&r(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachmentKind===`track`?l(U,{className:`h-3 w-3`}):l(p,{className:`h-3 w-3`}),e.attachmentLabel]}),e.attachment!==void 0&&r(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachment.kind===`snapshot`?l(p,{className:`h-3 w-3`}):l(U,{className:`h-3 w-3`}),et(e.attachment)]}),e.model!==void 0&&l(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`${e.model} · ${String(e.outputTokens??0)} tok · ${String(e.latencyMs??0)} ms`})]})})}function ut({attachment:e}){let t=Qe(e);return t===null?null:l(`img`,{src:t,alt:`sent to the model`,className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function dt({onPick:e}){let{t}=J(),n=b({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?l(E,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?l(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):l(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>l(ft,{device:t,onPick:e},t.id))})}function ft({device:e,onPick:t}){let{src:n}=d(e.id,{width:at});return r(`button`,{type:`button`,onClick:()=>t(e),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[l(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:n!==null&&l(`img`,{src:n,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),r(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!e.online&&l(S,{variant:`warning`,children:`off`}),l(`span`,{className:`truncate text-[10px] text-foreground`,children:e.name})]})]})}function pt({onPick:e}){let{t}=J(),n=m(),o=b({isCamera:!0,projection:`slim`}),s=i(()=>(o.data??[]).map(e=>e.id),[o.data]),c=i(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),u=a({queryKey:[...nt,s.length],enabled:s.length>0,queryFn:()=>n.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...s],since:Date.now()-rt,limit:it,projection:`slim`})});if(o.isLoading||u.isLoading)return l(E,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=u.data?.tracks??[];return d.length===0?l(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noTracks`,`No track in the last 6 hours.`)}):l(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(t=>r(`button`,{type:`button`,onClick:()=>e(t,c.get(t.deviceId)??String(t.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[l(U,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),l(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className}),l(`span`,{className:`shrink-0 text-foreground-subtle`,children:c.get(t.deviceId)??t.deviceId}),l(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(t.lastSeen).toLocaleTimeString()})]},t.trackId))})}n();var mt=1440*60*1e3,ht=[1,7,30,90];function gt(){let{t:e}=J(),t=m(),[n,o]=s(7),c=i(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(n-1)*mt},[n]),u=a({queryKey:se,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),d=a({queryKey:[...fe,n],queryFn:()=>t.trpcClient.llm.getUsage.query({since:c})}),f=i(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),p=i(()=>[{key:`day`,header:e(`ai.colDay`,`Day`),nowrap:!0,render:e=>e.day},{key:`consumer`,header:e(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>l(`span`,{className:`text-[11px] text-foreground`,children:e.consumer})},{key:`profile`,header:e(`ai.colProfile`,`Profile`),render:e=>l(`span`,{className:`text-[11px] text-foreground`,children:f.get(e.profileId)??e.profileId})},{key:`calls`,header:e(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>String(e.calls)},{key:`okErr`,header:e(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>l(`span`,{className:e.errorCalls>0?`text-danger`:void 0,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:e(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>`${String(e.inputTokens)} / ${String(e.outputTokens)}`},{key:`latency`,header:e(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>String(Math.round(e.avgLatencyMs))}],[f,e]),h=d.data??[];return r(Y,{icon:j,title:e(`ai.usageTitle`,`Usage`),subtitle: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.`),actions:l(`div`,{className:`w-40`,children:l(k,{"aria-label":e(`ai.window`,`Window`),value:String(n),options:ht.map(t=>({value:String(t),label:e(`ai.lastDays`,`Last {{days}} days`,{days:t})})),onChange:e=>o(Number(e.target.value))})}),children:[d.isError&&l(I,{title:e(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:e(`common.error`,`Error`),onRetry:()=>void d.refetch()}),h.length===0?l(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noUsage`,`No AI calls in this window.`)}):l(P,{children:l(W,{columns:p,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:A})})]})}function _t(){let{t:e}=J();return l(`div`,{className:`flex flex-col p-4`,children:l(ae,{tabs:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),icon:re,content:l(Le,{})},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),icon:F,content:l(Ve,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),icon:j,content:l(gt,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),icon:x,content:l(st,{})}]})})}export{_t as AiProfilesPage,_t as default};
@@ -1 +0,0 @@
1
- import{G as e,I as t,K as n,Q as r,S as i,b as a,q as o,x as s,z as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as l}from"./player-overlays-BHG5CSFQ.js";import{Cn as u,Gi as d,Hn as f,Pn as p,Wi as m,ba as h,bn as g,c as _,ci as v,et as y,mi as b,nt as x}from"./src-De0k1ip_.js";import{$n as S,Gn as C,Gt as w,Jn as T,Jt as E,Kn as ee,Kt as te,Qn as D,Vn as O,Wn as ne,Wt as re,Xn as ie,Yn as ae,Zn as k,lr as A,nn as oe,nr as se,qt as ce,rr as j,ur as le}from"./src-BpnJ-sMW.js";import{t as M}from"./useTranslation-Bc5yH9V9.js";r();function ue(e){return{target:{kind:`new`,type:e},name:``,features:[]}}function de(e){return{target:{kind:`existing`,device:e},name:``,features:[]}}function N(e,t){return{target:e.target,name:t,features:e.features.flatMap(e=>e.kind===`fields`?[e]:[])}}function P(e,t,n){return{...e,features:e.features.map(e=>e.cap===t?n(e):e)}}function F(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function fe(e,t){switch(t.type){case`set-new-type`:return e.target.kind===`new`?{...e,target:{...e.target,type:t.deviceType}}:e;case`set-new-role`:{if(e.target.kind!==`new`)return e;let{role:n,...r}=e.target;return{...e,target:t.role===null?r:{...r,role:t.role}}}case`set-name`:return{...e,name:t.name};case`add-feature`:return e.features.some(e=>e.cap===t.cap)?e:{...e,features:[...e.features,{kind:`fields`,cap:t.cap,fields:{}}]};case`remove-feature`:return{...e,features:e.features.filter(e=>e.cap!==t.cap)};case`set-field`:return P(e,t.cap,e=>({...e,fields:{...e.fields,[t.path]:t.source}}));case`clear-field`:return P(e,t.cap,e=>({...e,fields:F(e.fields,t.path)}));case`remove-binding`:return P(e,t.cap,e=>{let n=e.fields[t.path];return n?.kind===`expression`?{...e,fields:{...e.fields,[t.path]:{...n,bindings:F(n.bindings,t.bindingName)}}}:e});case`copy-feature`:return P(e,t.cap,e=>({...e,fields:{...e.fields,...Object.fromEntries(t.paths.map(e=>[e,{kind:`from`,source:t.from,cap:t.sourceCap,fieldPath:e}]))}}))}}function pe(e){let t=ee.safeParse({target:e.target,features:e.features});return t.success?{ok:!0,composition:t.data}:{ok:!1,problems:t.error.issues.map(e=>`${e.path.join(`.`)||`composition`}: ${e.message}`)}}function me(e,t){return JSON.stringify(e)!==JSON.stringify(t)}function he(e){for(let t=1;;t++){let n=`s${t}`;if(!e.includes(n))return n}}var ge=[`room`,`converted-sensor`,`derived-binary`],I={addonId:`provider-homeassistant`,stableId:`sensor.template_source`};function _e(){return N(ce({temperatureSources:w,motionSources:re,occupancyWindowMs:te}),`Room`)}function ve(){return N({target:{kind:`new`,type:j.Sensor},features:[{kind:`fields`,cap:`numeric-sensor`,fields:{value:{kind:`expression`,expr:`convert(v, "°C", "°F")`,bindings:{v:{kind:`from`,source:I,cap:`numeric-sensor`,fieldPath:`value`}}},unit:{kind:`expression`,expr:`"°F"`,bindings:{}},lastFetchedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Converted sensor`)}function ye(){return N({target:{kind:`new`,type:j.Sensor},features:[{kind:`fields`,cap:`binary`,fields:{on:{kind:`expression`,expr:`v > 20`,bindings:{v:{kind:`from`,source:I,cap:`temperature-sensor`,fieldPath:`celsius`}}},lastChangedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Derived binary`)}function be(e){switch(e){case`room`:return _e();case`converted-sensor`:return ve();case`derived-binary`:return ye()}}function xe(e,t){return typeof t==`number`&&Number.isFinite(t)&&t>0?{kind:`device`,path:`/devices/${t}`}:{kind:`editor`,path:`/build/compositions/${encodeURIComponent(e)}`}}var L=`rounded-lg border border-border bg-surface p-4`,Se=L;function Ce(e){return{addonId:e.addonId,stableId:e.stableId}}function R(e){return new Map(e.map(e=>[D(Ce(e)),e]))}function we(e,t,n){let r=e?.features??[],i=r.findIndex(e=>e.cap===n.cap);return{target:e?.target??{kind:`existing`,device:t},features:i===-1?[...r,n]:r.map((e,t)=>t===i?n:e)}}function Te(e,t){let n=e.features.filter(e=>e.cap!==t);return n.length===0?null:{target:e.target,features:n}}function Ee(e,t){let n=e?.features.find(e=>e.cap===t);return n!==void 0&&n.kind===`fields`?n:null}function z(e){return Array.isArray(e)?e.map(z):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,z(t)]))}function B(e){return JSON.stringify(z(e))}function De(e,t){return B(e)===B(t)}function V(e,t){return B(e)===B(t)}function Oe(e,t){switch(e.kind){case`pending`:return{kind:`refused`,reason:`the customization has not been read yet — try again`};case`unknown`:return{kind:`refused`,reason:`the customization could not be read: ${e.reason}`};case`not-loaded`:return{kind:`refused`,reason:`the customizations are not loaded yet: ${e.reason}`};case`none`:return t===null?{kind:`noop`}:{kind:`create`,input:{enabled:!0,composition:t}};case`present`:{let n=e.view.block.id;return t===null?{kind:`delete`,blockId:n}:B(t)===B(e.composition)?{kind:`noop`}:{kind:`update`,blockId:n,expectedUpdatedAt:e.view.block.updatedAt,composition:t}}}}function H(e,t){let n=e===`enum`?`string`:e,r=t.kind===`enum`?`string`:t.kind,i={source:t.source,cap:t.cap,fieldPath:t.fieldPath};return r===n?{kind:`from`,...i}:n===`number`&&r===`string`?{kind:`expression`,expr:`number(x)`,bindings:{x:{kind:`from`,...i}}}:null}function U(e){return{kind:`expression`,expr:e,bindings:{}}}function W(e){let t=H(`number`,e.percentage);return t===null?null:{kind:`fields`,cap:`battery`,fields:e.mode===`replace`?{percentage:t}:{percentage:t,charging:U(`"unknown"`),sleeping:U(`false`),lastUpdated:U(`now`)}}}var ke=[`percent`,...oe.options];function G(e,t){return t===`percent`?{level:e}:{"remaining.value":e,"remaining.unit":U(JSON.stringify(t))}}function Ae(e,t){let n=H(`number`,t.remaining);if(n===null||!C.test(t.key)||t.label.trim()===``)return null;let r={label:t.label.trim(),fields:G(n,t.unit)};return{kind:`fields`,cap:`consumables`,...e?.enabled===void 0?{}:{enabled:e.enabled},fields:e?.fields??{lastChangedAt:U(`now`),lastFetchedAt:U(`now`)},items:{...e?.items,[t.key]:r}}}function je(e){if(e.level!==void 0)return`percent`;let t=e[`remaining.unit`];if(t===void 0||t.kind!==`expression`)return null;try{let e=oe.safeParse(JSON.parse(t.expr));return e.success?e.data:null}catch{return null}}function Me(e){return Object.entries(e?.items??{}).map(([e,t])=>{let n=je(t.fields),r=K(t.fields.level??t.fields[`remaining.value`]),i=r===null?null:H(`number`,r);return n!==null&&i!==null&&De(G(i,n),t.fields)?{key:e,label:t.label,unit:n,source:r}:{key:e,label:t.label,unit:null,source:null}})}function Ne(e,t){let n=Object.fromEntries(Object.entries(e.items??{}).filter(([e])=>e!==t));return Object.keys(n).length===0?null:{...e,items:n}}function Pe(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48)}function Fe(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=Object.entries(t.bindings).filter(([e])=>e.startsWith(`active`)).flatMap(([,e])=>e.kind===`from`?[e.source]:[]);return[...new Map(n.map(e=>[D(e),e])).values()]}function Ie(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=t.bindings;return Object.entries(n).flatMap(([e,t])=>{if(!e.startsWith(`active`)||t.kind!==`from`)return[];let r=n[`changed${e.slice(6)}`];return r===void 0||r.kind!==`from`?[]:[{source:t.source,cap:t.cap,activeField:t.fieldPath,changedAtField:r.fieldPath}]})}function K(e){if(e===void 0)return null;if(e.kind===`from`){let{kind:t,...n}=e;return{...n,kind:`number`}}if(e.kind!==`expression`||e.expr!==`number(x)`)return null;let t=e.bindings.x;if(t===void 0||t.kind!==`from`||Object.keys(e.bindings).length!==1)return null;let{kind:n,...r}=t;return{...r,kind:`string`}}function Le(e,t){let n=K(e.fields.percentage);if(n===null)return!1;let r=W({percentage:n,mode:t}),{enabled:i,...a}=e;return r!==null&&V(a,r)}function q(e){return e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,location:e.location,type:e.type}))}function Re(e,t,n){let r=t.trim().toLowerCase();return r===``?[]:e.filter(e=>!n.includes(e.id)&&[e.name,e.stableId,e.location??``].some(e=>e.toLowerCase().includes(r))).toSorted((e,t)=>e.name.localeCompare(t.name)).slice(0,20)}function J(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=Object.getOwnPropertyDescriptor(n,e)?.value}return n}function ze(e,t,n,r){return r===null?{kind:`from`,source:e,cap:t,fieldPath:n.path}:H(r,{source:e,cap:t,fieldPath:n.path,kind:n.kind})}function Be(e,t,n,r){let i={addonId:e.addonId,stableId:e.stableId};return t.caps.flatMap(e=>e.fields.filter(e=>e.item!==!0).map(t=>({cap:e.cap,path:t.path,kind:t.kind,value:n===null?void 0:J(n[e.cap],t.path),source:ze(i,e.cap,t,r)})))}function Y(e,t){return t?e===void 0?`—`:e===null?`null`:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e):`…`}var Ve=[];function He({title:e,targetKind:t,excludeDeviceIds:n=Ve,onPick:r,onCancel:a}){let{t:c}=M(),[l,d]=o(null);return i(`aside`,{"aria-label":e,className:`rounded-lg border border-border bg-surface p-3 flex flex-col gap-2`,children:[s(`h3`,{className:`text-xs font-semibold`,children:e}),l===null?s(Ue,{excludeDeviceIds:n,onSelect:d}):s(We,{device:l,targetKind:t,onPick:r,onBack:()=>d(null)}),s(`div`,{children:s(u,{variant:`ghost`,onClick:a,children:c(`customize.picker.cancel`)})})]})}function Ue({excludeDeviceIds:e,onSelect:t}){let{t:n}=M(),[r,c]=o(``),l=d({projection:`slim`});return i(a,{children:[i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`customize.picker.search`),s(`input`,{type:`search`,"aria-label":n(`customize.picker.search`),className:`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`,value:r,onChange:e=>c(e.target.value)})]}),l.status===`pending`&&s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:n(`customize.picker.loadingDevices`)}),l.status===`error`&&s(g,{title:n(`customize.picker.devicesFailed`),message:l.error?.message??``}),l.status===`success`&&s(`ul`,{className:`flex flex-col gap-1`,children:Re(q(l.data),r,e).map(e=>s(`li`,{children:i(`button`,{type:`button`,className:`text-left text-[11px] hover:underline`,onClick:()=>t(e),children:[e.name,` `,i(`span`,{className:`text-foreground-subtle`,children:[`· `,e.stableId]})]})},e.id))})]})}function We({device:e,targetKind:t,selected:n,onPick:r,onBack:a}){let{t:o}=M(),c=m({deviceId:e.id}),l=h({deviceId:e.id});if(c.status===`pending`)return s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.picker.loadingFields`)});if(c.status===`error`)return s(g,{title:o(`customize.picker.fieldsFailed`),message:c.error?.message??``});let u=Be(e,c.data,l.status===`success`?l.data:null,t),d=u.filter(e=>e.source===null).length,f={addonId:e.addonId,stableId:e.stableId};return i(`div`,{className:`flex flex-col gap-1`,children:[i(`button`,{type:`button`,className:`text-left text-[11px] text-primary`,onClick:a,children:[`← `,e.name]}),l.status===`error`&&s(`p`,{role:`alert`,className:`text-[10px] text-warning`,children:o(`customize.picker.valuesFailed`,{reason:l.error?.message??``})}),s(`ul`,{role:`listbox`,"aria-label":o(`customize.picker.fields`),className:`flex flex-col gap-1`,children:u.map(t=>{let a=t.source;if(a===null)return null;let o=()=>r({device:e,ref:f,cap:t.cap,path:t.path,kind:t.kind,source:a,value:t.value});return i(`li`,{role:`option`,"aria-selected":n?.cap===t.cap&&n.path===t.path,tabIndex:0,className:`flex justify-between gap-2 text-[11px] cursor-pointer hover:bg-surface-hover rounded px-1`,onClick:o,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&o()},children:[i(`span`,{className:`font-mono`,children:[t.cap,`.`,t.path]}),s(`span`,{children:Y(t.value,l.status===`success`)})]},`${t.cap}.${t.path}`)})}),d>0&&t!==null&&s(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`customize.picker.hidden`,{count:d,kind:o(`customize.kinds.${t}`)})})]})}var Ge=`integration`;function X(e,t){switch(e.kind){case`from`:{let n=D(e.source);return`${t.get(n)??n} · ${e.cap}.${e.fieldPath}`}case`expression`:return e.expr;case`code`:return`code`}}function Ke(e,t){if(e.kind===`unreachable`)return{kind:`unknown`,reason:e.error};if(e.state===null)return{kind:`unknown`,reason:`the composer has not reported this customization yet`};let n=e.state.fields.find(t);return n===void 0?{kind:`unknown`,reason:`the composer reports no value for this field`}:n.state===`unavailable`?{kind:`unavailable`,reason:n.reason??`unavailable`}:{kind:`value`,value:n.value,staleReason:n.state===`stale`?n.reason??`stale`:null}}function qe(e,t,n,r){return{key:`${e.feature.cap}.${t}`,cap:e.feature.cap,field:t,origin:`composed`,mode:e.mode,from:X(n,e.input.sourceNames),value:e.enabled?Ke(e.input.state,r):{kind:`off`}}}function Je(e){let t=e.feature.cap;return Object.entries(e.feature.fields).map(([n,r])=>qe(e,n,r,e=>e.cap===t&&e.path===n&&e.item===void 0))}function Ye(e){let t=e.feature.cap;return Object.entries(e.feature.items??{}).flatMap(([n,r])=>Object.entries(r.fields).map(([r,i])=>qe(e,ae(ne,n,r),i,e=>e.cap===t&&e.path===r&&e.item?.arrayPath===`items`&&e.item.key===n)))}function Xe(e,t,n){if(e===null)return{kind:`unknown`,reason:`the device state could not be read`};let r=J(e[t],n),i=r===void 0?void 0:A(r);return i===void 0?{kind:`unknown`,reason:`not reported`}:{kind:`value`,value:i,staleReason:null}}function Ze(e){if(e.mode!==`replace`)return[];let t=e.feature.cap,n=new Set(Object.keys(e.feature.fields));return(e.input.nativeFields.get(t)??[]).filter(e=>!n.has(e)).map(n=>({key:`${t}.${n}`,cap:t,field:n,origin:`native`,mode:e.mode,from:Ge,value:Xe(e.input.snapshot,t,n)}))}function Qe(e){return e.composition.features.flatMap(t=>{if(t.kind!==`fields`)return[];let n={feature:t,mode:e.nativeCaps.has(t.cap)?`replace`:`add`,enabled:T(t),input:e};return[...Je(n),...Ye(n),...Ze(n)]})}var $e={min:`min(a, b, …)`,max:`max(a, b, …)`,abs:`abs(x)`,floor:`floor(x)`,ceil:`ceil(x)`,sqrt:`sqrt(x)`,round:`round(x, digits?)`,pow:`pow(x, y)`,clamp:`clamp(x, lo, hi)`,avg:`avg(a, b, …)`,sum:`sum(a, b, …)`,coalesce:`coalesce(a, b, …)`,age:`age(now, ts)`,convert:`convert(x, "from", "to")`,any:`any(a, b, …)`,all:`all(a, b, …)`,within:`within(ts, ms)`,number:`number(x)`,latest:`latest(ts, …)`,rose:`rose(level, changedAt, debounceMs?)`,count:`count(x)`},Z=/[A-Za-z_][A-Za-z0-9_]*$/;function et(e,t,n){let r=Z.exec(e.slice(0,t))?.[0]??``;if(r===``)return[];let i=n.filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`binding`,label:e,insert:e,hintKey:null})),a=`now`.startsWith(r)?[{kind:`now`,label:`now`,insert:`now`,hintKey:`compositionEditor.now`}]:[],o=[...le].filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`builtin`,label:$e[e]??e,insert:`${e}(`,hintKey:`compositionEditor.builtins.${e}`}));return[...i,...a,...o].slice(0,8)}function tt(e,t,n){let r=t-(Z.exec(e.slice(0,t))?.[0]??``).length;return{text:`${e.slice(0,r)}${n.insert}${e.slice(t)}`,cursor:r+n.insert.length}}r();function nt({label:e,value:t,bindings:r,onChange:a}){let{t:c}=M(),l=n(null),[u,d]=o(t.length),f=et(t,u,r);return i(`div`,{className:`flex flex-col gap-1`,children:[i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[e,s(`input`,{ref:l,className:`font-mono px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`,value:t,onChange:e=>{a(e.target.value),d(e.target.selectionStart??e.target.value.length)},onSelect:e=>d(e.currentTarget.selectionStart??t.length)})]}),f.length>0&&s(`ul`,{role:`listbox`,"aria-label":c(`compositionEditor.suggestions`),className:`rounded border border-border bg-surface text-[11px]`,children:f.map(e=>i(`li`,{role:`option`,"aria-selected":!1,tabIndex:0,className:`flex justify-between gap-2 px-1 cursor-pointer hover:bg-surface-hover`,onClick:()=>{let n=tt(t,u,e);a(n.text),d(n.cursor),l.current?.focus()},children:[s(`span`,{className:`font-mono`,children:e.label}),e.hintKey!==null&&s(`span`,{className:`text-foreground-subtle`,children:c(e.hintKey)})]},`${e.kind}:${e.label}`))})]})}function rt(e,t,n){if(e.kind===`code`)return{kind:`unavailable`,reason:`code fields arrive in slice 4`};if(e.kind===`expression`&&(O(e.expr,`rose`)||O(e.expr,`count`)))return{kind:`runtime-only`};let r=S(e).filter(e=>t.get(k(e.source,e.cap))?.kind!==`value`).map(ie);if(r.length>0)return{kind:`waiting`,missing:r};let i=E({source:e,now:n,read:e=>{let n=t.get(k(e.source,e.cap)),r=n?.kind===`value`?J(n.slice,e.fieldPath):void 0,i=r===void 0?void 0:A(r);return i===void 0?{state:`unavailable`,reason:`${e.cap}.${e.fieldPath} is not reported`,fatal:!1}:{state:`fresh`,value:i}}});return i.state===`unavailable`?{kind:`unavailable`,reason:i.reason}:{kind:`value`,value:i.value,stale:i.reason}}r();function it({sliceKey:e,deviceId:t,capName:n,onReading:r}){let i=_(l().trpcClient,t,n);return c(()=>{r(e,i===void 0?{kind:`pending`}:{kind:`value`,slice:i})},[e,i,r]),null}function at(e,t){return[...new Map(S(e).map(e=>[k(e.source,e.cap),e]))].map(([e,n])=>({key:e,read:n,device:t.get(D(n.source))}))}function ot({source:e}){let{t:n}=M(),r=d({projection:`slim`}),[a,c]=o(new Map),l=t((e,t)=>{c(n=>new Map([...n,[e,t]]))},[]),u=at(e,R(r.status===`success`?q(r.data):[])),f=r.status===`success`?u.filter(e=>e.device===void 0).map(e=>D(e.read.source)):[];return i(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px]`,children:[u.map(e=>e.device===void 0?null:s(it,{sliceKey:e.key,deviceId:e.device.id,capName:e.read.cap,onReading:l},e.key)),s(`span`,{className:`text-foreground-subtle`,children:n(`compositionEditor.preview.label`)}),r.status===`error`?s(`span`,{className:`text-warning`,children:n(`compositionEditor.preview.devicesFailed`,{reason:r.error?.message??``})}):f.length>0?s(`span`,{className:`text-warning`,children:n(`compositionEditor.preview.unknownDevice`,{sources:f.join(`, `)})}):s(st,{preview:rt(e,a,Date.now())})]})}function st({preview:e}){let{t}=M();switch(e.kind){case`value`:return i(`strong`,{children:[`→ `,Y(e.value,!0),e.stale===null?``:` (${e.stale})`]});case`unavailable`:return s(`span`,{className:`text-warning`,children:e.reason});case`waiting`:return s(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.waiting`,{sources:e.missing.join(`, `)})});case`runtime-only`:return s(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.runtimeOnly`)})}}r();function ct({path:e,kind:t,required:n,source:r,onSet:c,onClear:l,onRemoveBinding:d,sourceNames:f}){let{t:p}=M(),[m,h]=o(`idle`),g=r?.kind===`expression`?r:null;return i(`div`,{className:`flex flex-col gap-1 rounded border border-border p-2`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`font-mono text-[11px]`,children:e}),i(`span`,{className:`text-[10px] text-foreground-subtle`,children:[p(`customize.kinds.${t}`),n?` · ${p(`compositionEditor.required`)}`:``]}),s(u,{size:`sm`,variant:`outline`,onClick:()=>h(`take`),children:p(`compositionEditor.takeFrom`)}),s(u,{size:`sm`,variant:`outline`,"aria-pressed":g!==null,onClick:()=>c(g??{kind:`expression`,expr:`null`,bindings:{}}),children:p(`compositionEditor.formula`)}),r!==void 0&&s(u,{size:`sm`,variant:`ghost`,onClick:l,children:p(`compositionEditor.clear`)})]}),r?.kind===`from`&&s(`span`,{className:`text-[11px]`,children:X(r,f)}),g!==null&&i(a,{children:[s(nt,{label:p(`compositionEditor.formulaFor`,{path:e}),value:g.expr,bindings:Object.keys(g.bindings),onChange:e=>c({...g,expr:e})}),s(`ul`,{className:`text-[11px] flex flex-col gap-0.5`,children:Object.entries(g.bindings).map(([e,t])=>i(`li`,{className:`flex flex-wrap items-center gap-2`,children:[s(`span`,{className:`font-mono`,children:e}),s(`span`,{children:t.kind===`from`?X(t,f):JSON.stringify(t.value)}),s(u,{size:`sm`,variant:`ghost`,"aria-label":p(`compositionEditor.removeBinding`,{name:e}),onClick:()=>d(e),children:`×`})]},e))}),s(u,{size:`sm`,variant:`ghost`,onClick:()=>h(`add-binding`),children:p(`compositionEditor.addSource`)})]}),m!==`idle`&&s(He,{title:p(m===`take`?`compositionEditor.takeFrom`:`compositionEditor.addSource`),targetKind:m===`take`?t:null,onCancel:()=>h(`idle`),onPick:e=>{if(m===`take`)c(e.source);else if(g!==null){let t=he(Object.keys(g.bindings));c({...g,bindings:{...g.bindings,[t]:{kind:`from`,source:e.ref,cap:e.cap,fieldPath:e.path}}})}h(`idle`)}}),r!==void 0&&s(ot,{source:r})]})}r();function Q(e){return e===null||e.kind===`known`?null:e}function lt({draft:e,deviceType:t,nativeCaps:n,targetFields:r,dispatch:c}){let{t:l}=M(),p=v({deviceType:t}),m=d({projection:`slim`}),h=new Map([...R(m.status===`success`?q(m.data):[])].map(([e,t])=>[e,t.name])),[g,_]=o(null),y=Q(n)??Q(r),b=n?.kind===`known`?n.value:new Set,x=new Set(e.features.map(e=>e.cap)),S=p.status===`success`?p.data.caps.filter(e=>!x.has(e.cap)&&!b.has(e.cap)):[],C=[...b].filter(e=>!x.has(e)),w=e=>b.has(e)?((r?.kind===`known`?r.value.caps.find(t=>t.cap===e):void 0)?.fields??[]).filter(e=>e.item!==!0&&!e.path.includes(`.`)).map(e=>({path:e.path,kind:e.kind,required:!1})):((p.status===`success`?p.data.caps.find(t=>t.cap===e):void 0)?.fields??[]).map(e=>({path:e.path,kind:e.kind,required:e.required}));return y===null?i(a,{children:[i(`section`,{"aria-labelledby":`editor-features`,className:`${L} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),p.status===`pending`&&s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.checking`)}),p.status===`error`&&s(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.unknown`,{reason:p.error?.message??``})}),i(`div`,{className:`flex flex-wrap gap-1`,children:[e.features.map(e=>i(`span`,{className:`flex items-center gap-1 rounded border border-border px-1.5 text-[11px]`,children:[e.cap,s(f,{variant:b.has(e.cap)?`default`:`info`,children:b.has(e.cap)?l(`compositionEditor.replaces`):l(`compositionEditor.added`)}),s(`button`,{type:`button`,"aria-label":l(`compositionEditor.removeFeature`,{cap:e.cap}),onClick:()=>c({type:`remove-feature`,cap:e.cap}),children:`×`})]},e.cap)),S.map(e=>i(u,{size:`sm`,variant:`outline`,onClick:()=>c({type:`add-feature`,cap:e.cap}),children:[`+ `,e.cap]},e.cap)),C.map(e=>s(u,{size:`sm`,variant:`ghost`,onClick:()=>c({type:`add-feature`,cap:e}),children:l(`compositionEditor.replaceIn`,{cap:e})},e))]})]}),e.features.map(e=>i(`section`,{"aria-label":l(`compositionEditor.steps.fieldsOf`,{cap:e.cap}),className:`${L} flex flex-col gap-2`,children:[i(`div`,{className:`flex items-center justify-between`,children:[s(`h2`,{className:`text-sm font-semibold`,children:l(`compositionEditor.steps.fieldsOf`,{cap:e.cap})}),s(u,{size:`sm`,variant:`outline`,onClick:()=>_(e.cap),children:l(`compositionEditor.copyFeature`)})]}),g===e.cap&&s(He,{title:l(`compositionEditor.copyFeature`),targetKind:null,onCancel:()=>_(null),onPick:t=>{c({type:`copy-feature`,cap:e.cap,from:t.ref,sourceCap:t.cap,paths:w(e.cap).map(e=>e.path)}),_(null)}}),w(e.cap).map(t=>s(ct,{path:t.path,kind:t.kind,required:t.required,source:e.fields[t.path],onSet:n=>c({type:`set-field`,cap:e.cap,path:t.path,source:n}),onClear:()=>c({type:`clear-field`,cap:e.cap,path:t.path}),onRemoveBinding:n=>c({type:`remove-binding`,cap:e.cap,path:t.path,bindingName:n}),sourceNames:h},t.path))]},e.cap))]}):i(`section`,{"aria-labelledby":`editor-features`,className:`${L} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:y.kind===`unknown`?y.reason:l(`compositionEditor.reading`)})]})}var $=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function ut({draft:e,targetName:t,dispatch:n}){let{t:r}=M(),a=e.target;return i(`section`,{"aria-labelledby":`editor-target`,className:`${L} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-target`,className:`text-sm font-semibold`,children:r(`compositionEditor.steps.target`)}),a.kind===`existing`?s(`p`,{className:`text-[11px]`,children:r(`compositionEditor.existingTarget`,{name:t??`${a.device.addonId}/${a.device.stableId}`})}):i(`div`,{className:`grid grid-cols-3 gap-2`,children:[i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[r(`compositionEditor.targetType`),s(`select`,{className:$,value:a.type,onChange:e=>{let t=Object.values(j).find(t=>t===e.target.value);t!==void 0&&n({type:`set-new-type`,deviceType:t})},children:Object.values(j).map(e=>s(`option`,{value:e,children:x(e).label},e))})]}),i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[r(`customize.identity.role`),i(`select`,{className:$,value:a.role??``,onChange:e=>n({type:`set-new-role`,role:Object.values(se).find(t=>t===e.target.value)??null}),children:[s(`option`,{value:``,children:r(`customize.identity.noRole`)}),Object.values(se).map(e=>s(`option`,{value:e,children:y(e).label},e))]})]}),i(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[r(`compositionEditor.name`),s(`input`,{className:$,value:e.name,onChange:e=>n({type:`set-name`,name:e.target.value})})]})]})]})}r();function dt({draft:e,blockId:t,saving:n,onSave:r,onCancel:a}){let{t:l}=M(),d=b(),f=pe(e),p=f.ok?JSON.stringify(f.composition):``,[m,h]=o({key:``,state:{kind:`checking`}});c(()=>{if(!f.ok)return;let e=f.composition,n=setTimeout(()=>{d.mutateAsync({composition:e,...t===null?{}:{blockId:t}}).then(e=>h({key:p,state:e.ok?{kind:`ok`}:{kind:`refused`,problems:e.problems}})).catch(e=>h({key:p,state:{kind:`unknown`,reason:e instanceof Error?e.message:String(e)}}))},500);return()=>clearTimeout(n)},[p,t]);let g=f.ok?m.key===p?m.state:{kind:`checking`}:{kind:`invalid-draft`,problems:f.problems};return i(`section`,{"aria-labelledby":`editor-verify`,className:`${L} flex flex-col gap-2`,children:[s(`h2`,{id:`editor-verify`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.verify`)}),g.kind===`checking`&&s(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.verify.checking`)}),g.kind===`ok`&&s(`p`,{className:`text-[11px] text-success`,children:l(`compositionEditor.verify.ok`)}),g.kind===`unknown`&&s(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.verify.unknown`,{reason:g.reason})}),(g.kind===`invalid-draft`||g.kind===`refused`)&&s(`ul`,{role:`alert`,className:`flex flex-col gap-1 text-[11px] text-danger`,children:g.kind===`invalid-draft`?g.problems.map(e=>s(`li`,{children:e},e)):g.problems.map(e=>i(`li`,{children:[s(`span`,{className:`font-mono`,children:e.path}),` — `,e.message]},`${e.path}:${e.code}`))}),i(`div`,{className:`flex gap-2`,children:[s(u,{variant:`ghost`,onClick:a,children:l(`compositionEditor.cancel`)}),s(u,{disabled:g.kind!==`ok`||n||!f.ok,onClick:()=>f.ok&&r(f.composition),children:l(`compositionEditor.save`)})]})]})}r();function ft({initial:e,blockId:t,deviceType:n,targetName:r=null,nativeCaps:i,targetFields:a,save:c,onCancel:l,showTemplates:u=!1}){let[d,f]=o(e),p=`${d.name}:${d.features.map(e=>e.cap).join(`,`)}:${d.target.kind===`new`?d.target.type:`existing`}`;return s(pt,{seed:d,blockId:t,deviceType:n,targetName:r,nativeCaps:i,targetFields:a,showTemplates:u,onApplyTemplate:e=>{f(be(e))},save:c,onCancel:l},p)}function pt({seed:t,blockId:n,deviceType:r,targetName:a,nativeCaps:c,targetFields:l,showTemplates:d,onApplyTemplate:f,save:m,onCancel:h}){let{t:g}=M(),_=p(),[v,y]=e(fe,t),[b,x]=o(!1),[S,C]=o(null),w=async e=>{me(t,v)&&!await _({title:g(`compositionEditor.templates.confirmTitle`),message:g(`compositionEditor.templates.confirmMessage`),confirmLabel:g(`compositionEditor.templates.confirmApply`),variant:`danger`})||f(e)},T=v.target.kind===`new`?v.target.type:r,E=async e=>{x(!0);let t=await m(e,v.name);x(!1),C(t.kind===`refused`?t.reason:null)};return i(`div`,{className:`flex flex-col gap-4`,children:[d&&v.target.kind===`new`&&i(`div`,{className:`rounded-lg border border-border bg-surface p-4 flex flex-wrap gap-2`,"data-testid":`composition-templates`,children:[s(`span`,{className:`text-[11px] text-foreground-subtle self-center`,children:g(`compositionEditor.templates.label`)}),ge.map(e=>s(u,{size:`sm`,variant:`outline`,onClick:()=>void w(e),children:g(`compositionEditor.templates.${e}`)},e))]}),s(ut,{draft:v,targetName:a,dispatch:y}),s(lt,{draft:v,deviceType:T,nativeCaps:c,targetFields:l,dispatch:y}),s(dt,{draft:v,blockId:n,saving:b,onSave:e=>void E(e),onCancel:h}),S!==null&&s(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:S})]})}export{Te as C,de as D,N as E,ue as O,we as S,xe as T,K as _,We as a,Oe as b,q as c,Ae as d,Me as f,Pe as g,Le as h,Qe as i,ke as l,Ie as m,rt as n,Y as o,Fe as p,nt as r,J as s,ft as t,W as u,Ne as v,Se as w,V as x,Ee as y};
@@ -1 +0,0 @@
1
- import{S as e,x as t}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{bn as n,ni as r,oi as i,pi as a}from"./src-De0k1ip_.js";import{t as o}from"./boxes-DIXdAt9T.js";import{Rn as s,rr as c}from"./src-BpnJ-sMW.js";import{t as l}from"./useTranslation-Bc5yH9V9.js";import{M as u,N as d,P as f,s as p,t as m}from"./index-wFUqYEfd.js";import{t as h}from"./AdminPage-CiKtOLQm.js";import{E as g,O as _,T as v,t as y,w as b}from"./CompositionEditor-DjaR5c8a.js";var x=`new`;function S(e){return e instanceof Error?e.message:String(e)}function C(e){let t=e.trim();return t===``?{}:{name:t}}function w(){let{blockId:w}=f(),{t:T}=l(),E=d(),D=r(),O=a(),k=w===void 0||w===x,A=i({blockId:w??``},{enabled:!k}),j=()=>{E(m)},M=e=>t(h,{icon:o,title:T(`compositionEditor.pageTitle`),children:e}),N=e=>t(`section`,{className:`${b} flex flex-col gap-2`,children:e});if(k)return M(t(y,{initial:_(c.Sensor),blockId:null,deviceType:c.Sensor,nativeCaps:null,targetFields:null,showTemplates:!0,onCancel:j,save:async(e,t)=>{try{let{block:n}=await D.mutateAsync({block:{...C(t),enabled:!0,composition:e}});return E(v(n.id,null).path,{replace:!0}),{kind:`saved`}}catch(e){return{kind:`refused`,reason:S(e)}}}}));if(A.status===`pending`)return M(N(t(`p`,{role:`status`,children:T(`compositionEditor.loading`)})));if(A.status===`error`)return M(N(t(n,{title:T(`compositionEditor.loadFailed`),message:A.error.message})));if(A.data.state===`not-loaded`)return M(N(t(`p`,{role:`status`,children:T(`customize.status.notLoaded`,{reason:A.data.reason})})));let P=A.data.view;if(P===null)return M(N(t(`p`,{children:T(`compositionEditor.notFound`,{blockId:w})})));let F=s(P.block);if(F===null)return M(N(t(`p`,{children:T(`compositionEditor.notComposition`)})));if(F.target.kind===`existing`){let e=P.state.kind===`answered`?P.state.state?.deviceId??null:null;return M(N(e===null?t(`p`,{children:T(`compositionEditor.customizationUnknownDevice`)}):t(u,{className:`text-primary`,to:p(e),children:T(`compositionEditor.openOnDevice`)})))}let I=P.state.kind===`answered`?P.state.state?.deviceId??null:null,L=I===null?null:v(P.block.id,I);return M(e(`div`,{className:`flex flex-col gap-3`,children:[L!==null&&L.kind===`device`&&t(u,{className:`text-sm text-primary`,to:L.path,"data-testid":`open-composed-device`,children:T(`compositionEditor.openComposedDevice`,{id:I})}),t(y,{initial:g(F,P.block.name),blockId:P.block.id,deviceType:F.target.type,nativeCaps:null,targetFields:null,onCancel:j,save:async(e,t)=>{try{return await O.mutateAsync({blockId:P.block.id,expectedUpdatedAt:P.block.updatedAt,block:{...C(t),composition:e}}),await A.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:S(e)}}}},`${P.block.id}@${P.block.updatedAt}`)]}))}export{w as CompositionEditorPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,W as i,b as a,o,q as s,x as c,z as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as u,ct as d,ft as f,gt as p,ht as m,st as h,vt as g}from"./player-overlays-BHG5CSFQ.js";import{Aa as _,Ca as v,Cn as y,Da as b,Ea as x,Fl as S,Gi as C,Hn as w,Jt as T,Kl as E,Kt as D,Ll as O,Ma as k,Na as ee,Nl as A,Nu as j,Oa as M,Pn as N,Qt as P,Sa as F,Sl as I,Sn as L,Ta as R,Xt as z,Yt as B,Zt as V,cu as H,fu as U,ja as W,ka as te,pu as G,tn as K,wa as q,xa as ne,xu as re,yd as ie,yl as J,yu as Y}from"./src-De0k1ip_.js";import{i as ae,n as oe,r as se,t as ce}from"./face-bbox-B9Tyg9NW.js";import{t as X}from"./square-check-big-CsHHs7_N.js";import{t as Z}from"./user-round-B_-xKzQ7.js";import{Br as le}from"./src-BpnJ-sMW.js";import{L as ue}from"./index-wFUqYEfd.js";import{t as de}from"./AdminPage-CiKtOLQm.js";import{n as fe,r as pe}from"./authed-media-Bf77DHiU.js";import{a as me,c as he,f as ge,i as _e,l as ve,n as ye,o as be,p as xe,r as Se,s as Ce,t as we,u as Te}from"./debounced-invalidate-CHSCMizx.js";var Ee=g(`image-plus`,[[`path`,{d:`M16 5h6`,key:`1vod17`}],[`path`,{d:`M19 2v6`,key:`4bpg5p`}],[`path`,{d:`M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5`,key:`1ue2ih`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}]]);n();var De=`pipeline-analytics`,Oe=`photo.analyze`,ke=`photo.enroll`,Ae=`photo.discard`,je=18*1024*1024;function Me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function $(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function Ne(e,t){let n=e[t];return typeof n==`boolean`?n:null}function Pe(e){if(!Me(e))return null;let t=$(e,`x`),n=$(e,`y`),r=$(e,`width`),i=$(e,`height`);return t===null||n===null||r===null||i===null?null:{x:t,y:n,width:r,height:i}}function Fe(e){if(!Me(e))return null;let t=$(e,`detectionShortSidePx`),n=$(e,`score`);if(t===null||n===null)return null;let r=$(e,`magnitude`);return{detectionShortSidePx:t,score:n,...r===null?{}:{magnitude:r}}}function Ie(e){if(!Me(e))return null;let t=$(e,`faceIndex`),n=$(e,`score`),r=Ne(e,`enrollable`),i=Pe(e.bbox),a=Fe(e.quality);if(t===null||n===null||r===null||i===null||a===null)return null;let o=Q(e,`refusedReason`),s=Q(e,`alignedCropBase64`),c=Q(e,`modelId`);return{faceIndex:t,bbox:i,score:n,enrollable:r,quality:a,...o===null?{}:{refusedReason:o},...s===null?{}:{alignedCropBase64:s},...c===null?{}:{modelId:c}}}function Le(e){if(!Me(e))return null;let t=Q(e,`sessionId`),n=Q(e,`ranOnNodeId`),r=e.faces;if(t===null||n===null||!Array.isArray(r))return null;let i=[];for(let e of r){let t=Ie(e);t!==null&&i.push(t)}return{sessionId:t,ranOnNodeId:n,faces:i}}function Re(e){if(!Me(e))return null;let t=Q(e,`sampleId`),n=Q(e,`identityId`),r=Q(e,`modelId`);return t===null||n===null||r===null?null:{sampleId:t,identityId:n,modelId:r}}function ze(e,t,n){let r={...e};return n===null||n===``?delete r[t]:r[t]=n,r}function Be(e,t){return e.filter(e=>e.enrollable&&t[e.faceIndex]!==void 0).length}function Ve(e,t,n){let r=[];for(let i of t){if(!i.enrollable)continue;let t=n[i.faceIndex];t!==void 0&&r.push({sessionId:e,faceIndex:i.faceIndex,identityId:t})}return r}function He(e){switch(e){case`no-embedding`:return`Too small or too indistinct for the recognizer to measure — try a photo where this face is larger.`;case`no-model-id`:return`The recognizer did not report which model it used, so this face cannot be enrolled safely.`;case`no-aligned-crop`:return`The recognizer produced no aligned crop for this face, so there is nothing to store.`;case`magnitude`:return`Refused by the quality gate: the features look degenerate, and a sample like this matches everybody.`;default:return`This face is not usable as a sample.`}}function Ue(e,t){let n=[],r=[];for(let i of e)i.size>t.maxBytes?n.push(i.name):r.push(i);return{accepted:r.slice(0,t.maxCount),oversize:n,overflow:r.slice(t.maxCount).map(e=>e.name)}}async function We(e,t,n){let r=Array(e.length),i=e.map((e,t)=>({item:e,index:t})),a=0,o=async()=>{for(;;){let e=i[a];if(a+=1,e===void 0)return;r[e.index]=await n(e.item,e.index)}},s=Array.from({length:Math.max(1,Math.min(t,e.length))},()=>o());return await Promise.all(s),r}function Ge(e,t,n){return e.map(e=>e.photoIndex===t?{...e,...n}:e)}function Ke(e,t){return`${e}:${t}`}function qe(e,t,n,r){let i=ze(e[t]??{},n,r),a={...e};return Object.keys(i).length===0?delete a[t]:a[t]=i,a}function Je(e,t){let n=0;for(let r of e)r.analysis!==void 0&&(n+=Be(r.analysis.faces,t[r.photoIndex]??{}));return n}var Ye=`__new__`;function Xe(e,t,n){let r=[];for(let i of e){if(i.analysis===void 0)continue;let e=t[i.photoIndex]??{};for(let t of i.analysis.faces){if(!t.enrollable||e[t.faceIndex]!==`__new__`)continue;let a=(n[Ke(i.photoIndex,t.faceIndex)]??``).trim();if(a===``)return{kind:`error`,message:`${i.filename}: face ${t.faceIndex+1} is set to a new person but has no name.`};r.includes(a)||r.push(a)}}return{kind:`ok`,names:r}}function Ze(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=Number(i),o={};for(let[r,i]of Object.entries(a)){let a=Number(r);if(i!==`__new__`){o[a]=i;continue}let s=n[(t[Ke(e,a)]??``).trim()];s!==void 0&&(o[a]=s)}r[e]=o}return r}function Qe(e,t){let n=[];for(let r of e){if(r.analysis===void 0)continue;let e=Ve(r.analysis.sessionId,r.analysis.faces,t[r.photoIndex]??{});for(let t of e)n.push({photoIndex:r.photoIndex,request:t})}return n}function $e(e){return/expired/i.test(e)}function et(e){return e instanceof Error?e.message:String(e)}async function tt(e,t,n){let r=new Map(e.map(e=>[e.photoIndex,e])),i={},a=[],o=0,s=null,c=(e,t)=>`${r.get(e)?.filename??`photo ${e+1}`}, face ${t+1}`;for(let l of Qe(e,t)){let e=i[l.photoIndex],t=e===void 0?l.request:{...l.request,sessionId:e.sessionId};try{let e=await n.enroll(t);o+=1,s=e.modelId}catch(t){let u=et(t);if(!$e(u)||e!==void 0){a.push(`${c(l.photoIndex,l.request.faceIndex)}: ${u}`);continue}let d=r.get(l.photoIndex);if(d===void 0){a.push(`${c(l.photoIndex,l.request.faceIndex)}: ${u}`);continue}let f;try{f=await n.reanalyze(d)}catch(e){a.push(`${c(l.photoIndex,l.request.faceIndex)}: the analysis expired and re-analysing failed (${et(e)})`);continue}if(i[l.photoIndex]=f,f.faces.find(e=>e.faceIndex===l.request.faceIndex&&e.enrollable)===void 0){a.push(`${c(l.photoIndex,l.request.faceIndex)}: the analysis expired, and re-analysing no longer finds this face — assign it again from the fresh result`);continue}try{let e=await n.enroll({...l.request,sessionId:f.sessionId});o+=1,s=e.modelId}catch(e){a.push(`${c(l.photoIndex,l.request.faceIndex)}: ${et(e)}`)}}}return{enrolled:o,stampedModelId:s,failures:a,refreshedAnalyses:i}}var nt=[[`faceGallery`]],rt=``;function it(e){return new Promise((t,n)=>{let r=new FileReader;r.addEventListener(`error`,()=>n(Error(`the file could not be read`)),{once:!0}),r.addEventListener(`load`,()=>{let e=r.result;if(typeof e!=`string`){n(Error(`the file could not be read`));return}let i=e.indexOf(`,`);t(i>=0?e.slice(i+1):e)},{once:!0}),r.readAsDataURL(e)})}function at(e){return e instanceof Error?e.message:String(e)}function ot({face:e,identities:t,value:n,onChange:o,disabled:s}){let l=i(()=>[{value:rt,label:`Ignore this face`},...t.map(e=>({value:e.id,label:e.name})),{value:Ye,label:`+ New person…`}],[t]);return r(`div`,{className:`rounded-md border border-border bg-surface p-2`,children:[c(`div`,{className:`mb-2 aspect-square w-full overflow-hidden rounded border border-border bg-surface-hover`,children:e.alignedCropBase64?c(`img`,{src:`data:image/jpeg;base64,${e.alignedCropBase64}`,alt:`Face ${e.faceIndex+1}`,className:`h-full w-full object-cover`}):c(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:c(Z,{className:`h-8 w-8`})})}),e.enrollable?r(a,{children:[c(L,{options:l,value:n,disabled:s,onChange:e=>o(e.target.value),"aria-label":`Assign face ${e.faceIndex+1}`}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:[Math.round(e.quality.detectionShortSidePx),` px`,e.modelId?` · ${e.modelId}`:``]})]}):r(`div`,{className:`space-y-1`,children:[c(w,{variant:`warning`,className:`text-[10px]`,children:`Not usable`}),c(`p`,{className:`text-[10px] leading-tight text-foreground-subtle`,children:He(e.refusedReason)})]})]})}function st({photo:e,identities:t,draft:n,newNames:i,disabled:a,onAssign:o,onNameChange:s,onRetry:l}){let u=e.analysis?.faces??[],d=n[e.photoIndex]??{};return r(`div`,{className:`space-y-2`,children:[r(`div`,{className:`flex items-center gap-2 border-b border-border pb-1`,children:[c(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.filename}),e.status===`analyzing`||e.status===`queued`?r(`span`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,children:[c(j,{className:`h-3 w-3 animate-spin`}),` analysing…`]}):null,e.status===`analyzed`&&e.analysis!==void 0&&r(`span`,{className:`text-xs text-foreground-subtle`,children:[u.length,` face`,u.length===1?``:`s`,` · analysed on`,` `,e.analysis.ranOnNodeId]}),e.status===`failed`&&r(y,{variant:`secondary`,size:`sm`,disabled:a,onClick:l,children:[c(U,{className:`h-3 w-3`}),` Retry`]})]}),e.status===`failed`&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:[c(O,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),r(`span`,{children:[`This photo could not be analysed: `,e.error??`unknown error`,`. The other photos are unaffected.`]})]}),e.status===`analyzed`&&u.length===0&&c(`p`,{className:`text-xs text-foreground-subtle`,children:`No faces were found in this photo. A face has to be reasonably large and facing the camera for the detector to measure it.`}),u.length>0&&c(`div`,{className:`grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-5`,children:u.map(e=>c(ot,{face:e,identities:t,value:d[e.faceIndex]??rt,disabled:a,onChange:t=>o(e.faceIndex,t)},e.faceIndex))}),u.filter(e=>d[e.faceIndex]===Ye).map(t=>r(`div`,{className:`flex items-center gap-2`,children:[r(`span`,{className:`w-28 shrink-0 truncate text-xs text-foreground-subtle`,children:[`Face `,t.faceIndex+1]}),c(`input`,{className:`h-7 flex-1 rounded-md border border-border bg-surface px-2.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,placeholder:`New person name… (type the same name under another face to reuse it)`,value:i[Ke(e.photoIndex,t.faceIndex)]??``,onChange:e=>s(t.faceIndex,e.target.value)})]},t.faceIndex))]})}function ct({open:n,onOpenChange:a}){let l=u(),d=o(),f=t(null),{data:p}=x(),m=F(),[h,g]=s([]),[_,v]=s(!1),[b,S]=s(null),[C,w]=s({}),[E,k]=s({}),[ee,A]=s(null),M=i(()=>(p??[]).map(e=>({id:e.id,name:e.name})),[p]),N=h.some(e=>e.status===`queued`||e.status===`analyzing`),I=N||_,L=e(e=>{for(let t of e){let e=t.analysis?.sessionId;e!==void 0&&l.trpcClient.addons.custom.mutate({addonId:De,action:Ae,input:{sessionId:e}}).catch(()=>void 0)}},[l]),R=e(()=>{g([]),w({}),k({}),S(null),A(null),f.current&&(f.current.value=``)},[]),H=e(()=>{L(h),R(),a(!1)},[L,a,h,R]),U=e(async e=>{let t=Le(await l.trpcClient.addons.custom.mutate({addonId:De,action:Oe,input:{photoBase64:e.photoBase64,filename:e.filename}}));if(t===null)throw Error(`the server replied with something this page could not read`);return t},[l]),W=e(async e=>{g(t=>Ge(t,e.photoIndex,{status:`analyzing`,error:void 0}));try{let t=await U(e);g(n=>Ge(n,e.photoIndex,{status:`analyzed`,analysis:t}))}catch(t){g(n=>Ge(n,e.photoIndex,{status:`failed`,error:at(t)}))}},[U]),te=e(async e=>{if(e.length===0)return;L(h),R();let t=Ue(e,{maxCount:12,maxBytes:je}),n=[];t.oversize.length>0&&n.push(`Over the ${Math.round(je/(1024*1024))} MB limit and skipped: ${t.oversize.join(`, `)}.`),t.overflow.length>0&&n.push(`A batch holds at most 12 photos — not analysed: ${t.overflow.join(`, `)}. Enrol them in a second round.`),n.length>0&&S(n.join(` `));let r;try{r=await Promise.all(t.accepted.map(async(e,t)=>({photoIndex:t,filename:e.name,photoBase64:await it(e),status:`queued`})))}catch(e){S(at(e));return}g(r),await We(r,2,e=>W(e))},[L,h,R,W]),G=Je(h,C),K=e(async()=>{v(!0),S(null),A(null);try{let e=Xe(h,C,E);if(e.kind===`error`){S(e.message);return}let t={};for(let n of e.names)t[n]=(await m.mutateAsync({name:n})).id;let n=await tt(h,Ze(C,E,t),{enroll:async e=>{let t=Re(await l.trpcClient.addons.custom.mutate({addonId:De,action:ke,input:e}));if(t===null)throw Error(`unreadable reply`);return t},reanalyze:e=>U(e)});Object.keys(n.refreshedAnalyses).length>0&&g(e=>e.map(e=>{let t=n.refreshedAnalyses[e.photoIndex];return t===void 0?e:{...e,status:`analyzed`,analysis:t}})),d.invalidateQueries({queryKey:nt}),n.failures.length>0&&S(n.failures.join(` · `)),A(n.enrolled===0?`Nothing was enrolled.`:`Enrolled ${n.enrolled} sample${n.enrolled===1?``:`s`}${n.stampedModelId===null?``:` with ${n.stampedModelId}`}.`)}catch(e){S(at(e))}finally{v(!1)}},[U,m,C,E,h,d,l]),q=h.filter(e=>e.status===`analyzed`).length;return c(D,{open:n,onOpenChange:e=>e?a(!0):H(),children:r(T,{className:`max-w-3xl`,children:[r(V,{children:[c(P,{children:`Enrol from photos`}),c(B,{children:`Every photo is analysed with the same face detector the cameras use, and all the faces found are reviewed below in one pass, grouped by photo. Assign each face to a person, or leave it ignored.`})]}),r(`div`,{className:`rounded-md border border-border bg-surface-hover px-3 py-2 text-xs text-foreground-subtle`,children:[`For reliable recognition use `,c(`strong`,{children:`at least 3 photos per person`}),`, taken at different times, with different poses and lighting — you can select them all at once. Several frames from the same moment count as one — they do not add information.`]}),r(`div`,{className:`flex items-center gap-2`,children:[c(`input`,{ref:f,type:`file`,accept:`image/jpeg,image/png,image/webp`,multiple:!0,className:`hidden`,onChange:e=>void te(Array.from(e.target.files??[]))}),r(y,{variant:`secondary`,size:`sm`,disabled:I,onClick:()=>f.current?.click(),children:[N?c(j,{className:`h-3.5 w-3.5 animate-spin`}):c(Ee,{className:`h-3.5 w-3.5`}),`Choose photos`]}),h.length>0&&r(`span`,{className:`text-xs text-foreground-subtle`,children:[q,`/`,h.length,` photo`,h.length===1?``:`s`,` analysed`]})]}),b!==null&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:[c(O,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),c(`span`,{children:b})]}),ee!==null&&c(`div`,{className:`rounded-md border border-success/40 bg-success/10 px-3 py-2 text-xs text-success`,children:ee}),h.length>0&&c(`div`,{className:`max-h-[50vh] space-y-4 overflow-y-auto pr-1`,children:h.map(e=>c(st,{photo:e,identities:M,draft:C,newNames:E,disabled:I,onAssign:(t,n)=>w(r=>qe(r,e.photoIndex,t,n===rt?null:n)),onNameChange:(t,n)=>k(r=>({...r,[Ke(e.photoIndex,t)]:n})),onRetry:()=>void W(e)},e.photoIndex))}),r(z,{children:[c(y,{variant:`secondary`,onClick:H,disabled:_,children:`Close`}),r(y,{variant:`primary`,onClick:()=>void K(),disabled:I||G===0,children:[_?c(j,{className:`h-3.5 w-3.5 animate-spin`}):null,`Enrol `,G,` face`,G===1?``:`s`]})]})]})})}n();var lt=[[`faceGallery`]];function ut({identityId:e}){let t=o(),{data:n,isLoading:i}=b({identityId:e}),a=te();function s(n){a.mutate({identityId:e,sampleId:n.id},{onSettled:()=>{t.invalidateQueries({queryKey:lt})}})}return i?r(`div`,{className:`flex items-center gap-2 py-3 text-xs text-foreground-subtle`,children:[c(j,{className:`h-3.5 w-3.5 animate-spin`}),`Loading samples…`]}):!n||n.length===0?c(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:`No samples yet.`}):c(`div`,{className:`mt-2 grid grid-cols-4 gap-2 sm:grid-cols-6 md:grid-cols-8`,children:n.map(e=>r(`div`,{className:`group relative aspect-square overflow-hidden rounded-md border border-border bg-surface`,children:[e.base64?c(`img`,{src:`data:image/jpeg;base64,${e.base64}`,alt:`Sample`,className:`h-full w-full object-cover`}):c(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:c(Z,{className:`h-6 w-6`})}),e.source===`photo`&&c(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 p-0.5 text-white`,title:`Enrolled from an uploaded photo`,children:c(Ee,{className:`h-3 w-3`})}),c(`button`,{type:`button`,onClick:()=>s(e),disabled:a.isPending,className:`absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 transition-opacity group-hover:opacity-100 disabled:cursor-not-allowed`,"aria-label":`Remove sample`,children:c(I,{className:`h-4 w-4 text-white`})})]},e.id))})}function dt({identity:e,expanded:t,onToggle:n}){let i=o(),[l,u]=s(``),[d,f]=s(!1),[g,v]=s(!1),b=_(),x=q();function S(){u(e.name),f(!0)}function C(){f(!1),u(``)}function E(){let t=l.trim();if(!t||t===e.name){C();return}b.mutate({id:e.id,name:t},{onSettled:()=>{i.invalidateQueries({queryKey:lt}),C()}})}function O(){x.mutate({id:e.id},{onSettled:()=>{i.invalidateQueries({queryKey:lt}),v(!1)}})}return r(`div`,{className:`rounded-md border border-border bg-surface`,children:[r(`div`,{className:`flex items-center gap-2 px-3 py-2`,children:[c(`div`,{className:`h-8 w-8 shrink-0 overflow-hidden rounded-full border border-border bg-surface-hover`,children:c(oe,{mediaId:e.coverMediaId,base64:e.coverBase64,alt:e.name,className:`h-full w-full object-cover`,placeholder:c(`div`,{className:`flex h-full w-full items-center justify-center`,children:c(Z,{className:`h-4 w-4 text-foreground-subtle`})})})}),c(`div`,{className:`flex flex-1 min-w-0 items-center gap-2`,children:d?r(a,{children:[c(K,{value:l,onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&E(),e.key===`Escape`&&C()},className:`h-6 text-xs`,autoFocus:!0}),c(`button`,{type:`button`,onClick:E,disabled:b.isPending,className:`text-success hover:text-success/80 disabled:opacity-50`,"aria-label":`Confirm rename`,children:c(ie,{className:`h-3.5 w-3.5`})}),c(`button`,{type:`button`,onClick:C,className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Cancel rename`,children:c(I,{className:`h-3.5 w-3.5`})})]}):c(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name})}),c(w,{variant:`default`,className:`text-[10px]`,children:e.sampleCount}),!d&&r(`div`,{className:`flex items-center gap-1`,children:[c(`button`,{type:`button`,onClick:S,className:`p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground`,"aria-label":`Rename`,children:c(re,{className:`h-3.5 w-3.5`})}),c(`button`,{type:`button`,onClick:()=>v(!0),className:`p-1 rounded hover:bg-danger/10 text-foreground-subtle hover:text-danger`,"aria-label":`Delete`,children:c(h,{className:`h-3.5 w-3.5`})})]}),c(`button`,{type:`button`,onClick:n,className:`p-1 rounded hover:bg-surface-hover text-foreground-subtle`,"aria-label":t?`Collapse`:`Expand`,children:c(t?p:m,{className:`h-3.5 w-3.5`})})]}),t&&c(`div`,{className:`border-t border-border px-3 pb-3 pt-2`,children:c(ut,{identityId:e.id})}),c(D,{open:g,onOpenChange:e=>!e&&v(!1),children:r(T,{children:[r(V,{children:[c(P,{children:`Delete person`}),r(B,{children:[`Delete `,c(`strong`,{children:e.name}),` and all their samples? This cannot be undone.`]})]}),r(z,{children:[c(y,{variant:`secondary`,onClick:()=>v(!1),children:`Cancel`}),r(y,{variant:`danger`,onClick:O,disabled:x.isPending,children:[x.isPending?c(j,{className:`h-3.5 w-3.5 animate-spin`}):null,`Delete`]})]})]})})]})}function ft(){let e=o(),[t,n]=s(``),i=F();function a(){let r=t.trim();r&&i.mutate({name:r},{onSettled:()=>{e.invalidateQueries({queryKey:lt}),n(``)}})}return r(`div`,{className:`flex items-center gap-2 pt-2`,children:[c(K,{placeholder:`New person name…`,value:t,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&a()},className:`h-7 text-xs flex-1`}),r(y,{variant:`primary`,size:`sm`,onClick:a,disabled:i.isPending||!t.trim(),children:[i.isPending?c(j,{className:`h-3.5 w-3.5 animate-spin`}):c(Y,{className:`h-3.5 w-3.5`}),`Add`]})]})}function pt(){let{data:e,isLoading:t}=x(),[n,i]=s(null),[a,o]=s(!1);function l(e){i(t=>t===e?null:e)}return t?r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[c(j,{className:`h-4 w-4 animate-spin`}),`Loading people…`]}):r(`div`,{className:`space-y-2`,children:[(!e||e.length===0)&&c(`p`,{className:`py-2 text-xs text-foreground-subtle`,children:`No people enrolled yet. Add one below.`}),e?.map(e=>c(dt,{identity:e,expanded:n===e.id,onToggle:()=>l(e.id)},e.id)),c(ft,{}),c(`div`,{className:`pt-1`,children:r(y,{variant:`secondary`,size:`sm`,onClick:()=>o(!0),children:[c(Ee,{className:`h-3.5 w-3.5`}),`Enrol from a photo`]})}),c(ct,{open:a,onOpenChange:o})]})}function mt(e){let t=e.cropUrl!==void 0&&e.cropUrl.length>0,n=e.base64!==void 0&&e.base64.length>0;return!t&&!n}function ht(e){return e.filter(mt).map(e=>e.faceId)}function gt(e){let t=0;for(let n of e)mt(n)&&(t+=1);return t}function _t(e){return e==null?null:e.cropUrl!==void 0&&e.cropUrl.length>0?e.cropUrl:e.base64!==void 0&&e.base64.length>0?`data:image/jpeg;base64,${e.base64}`:null}n();var vt=[[`faceGallery`]];function yt({faceIds:e,identities:t,onDone:n}){let i=o(),a=ne(),l=F(),[u,d]=s(``),[f,p]=s(!1),[m,h]=s(null),g=e!==null&&e.length>0,_=e?.length??0;function v(){p(!1),d(``),h(null)}function b(){v(),n()}function x(t){!e||e.length===0||a.mutate({faceIds:[...e],identityId:t},{onSettled:()=>{i.invalidateQueries({queryKey:vt}),b()}})}function S(){!e||!u.trim()||l.mutate({name:u.trim()},{onSuccess:e=>{e?.id&&x(e.id)},onError:()=>{i.invalidateQueries({queryKey:vt}),b()}})}let C=a.isPending||l.isPending;return c(D,{open:g,onOpenChange:e=>!e&&b(),children:r(T,{children:[r(V,{children:[c(P,{children:_>1?`Assign ${String(_)} faces to person`:`Assign face to person`}),c(B,{children:`Select an existing person or create a new one.`})]}),c(`div`,{className:`space-y-1 max-h-56 overflow-y-auto`,children:t.map(e=>r(`button`,{type:`button`,onClick:()=>h(e.id),className:`w-full rounded-md px-3 py-2 text-left text-xs transition-colors ${m===e.id?`bg-primary/12 text-primary`:`hover:bg-surface-hover text-foreground`}`,children:[c(`span`,{className:`font-medium`,children:e.name}),r(`span`,{className:`ml-2 text-foreground-subtle`,children:[e.sampleCount,` samples`]})]},e.id))}),f?c(`div`,{className:`flex items-center gap-2 pt-2 border-t border-border`,children:c(K,{placeholder:`New person name…`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&S()},autoFocus:!0,className:`flex-1`})}):c(`button`,{type:`button`,onClick:()=>{h(null),p(!0)},className:`mt-2 w-full rounded-md border border-dashed border-border px-3 py-2 text-left text-xs text-foreground-subtle hover:border-primary hover:text-primary transition-colors`,children:`+ New person…`}),r(z,{children:[c(y,{variant:`secondary`,onClick:b,disabled:C,children:`Cancel`}),f?r(y,{variant:`primary`,onClick:S,disabled:C||!u.trim(),children:[C&&c(j,{className:`h-3.5 w-3.5 animate-spin`}),`Create & assign`]}):r(y,{variant:`primary`,onClick:()=>m&&x(m),disabled:C||!m,children:[C&&c(j,{className:`h-3.5 w-3.5 animate-spin`}),`Assign`,_>1?` ${String(_)}`:``]})]})]})})}n();function bt(e){let[t,n]=s(null),[r,i]=s(null),[a,o]=s(!1);return l(()=>{if(n(null),i(null),o(!1),e===void 0)return;let t=!1,r=null;return(async()=>{try{let i=await fe(pe(e));if(t)return;r=URL.createObjectURL(i),n(r)}catch{t||o(!0)}})(),()=>{t=!0,r&&URL.revokeObjectURL(r)}},[e]),l(()=>{if(!t)return;let e=new Image;return e.onload=()=>i({width:e.naturalWidth,height:e.naturalHeight}),e.onerror=()=>o(!0),e.src=t,()=>{e.onload=null,e.onerror=null}},[t]),{frameSrc:t,naturalWidth:r?.width??null,naturalHeight:r?.height??null,failed:a}}function xt(e){let t=e.filter(e=>e.url.length>0);return t.length===0?null:t.find(e=>/crop|face/i.test(e.kind))??t[0]}function St({label:e,value:t}){return r(`div`,{className:`flex items-baseline justify-between gap-3 py-1.5 border-b border-border/60 last:border-0`,children:[c(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),c(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground`,children:t})]})}function Ct({box:e}){return c(`div`,{className:`pointer-events-none absolute rounded-[3px] border-2 border-primary shadow-[0_0_0_9999px_rgba(0,0,0,0.28)]`,style:{left:`${String(e.x*100)}%`,top:`${String(e.y*100)}%`,width:`${String(e.width*100)}%`,height:`${String(e.height*100)}%`},children:c(`span`,{className:`absolute -top-4 left-0 rounded bg-primary px-1 text-[9px] font-semibold uppercase tracking-wide text-white`,children:`Face`})})}function wt({face:e,cameraName:t,onClose:n,onAssign:a,onUnassign:o,onDelete:l,actionsPending:u}){let{data:d,isFetching:p}=R({faceId:e?.faceId??``},{enabled:e!==null}),[m,g]=s(`frame`),{frameSrc:_,naturalWidth:v,naturalHeight:b,failed:x}=bt(e?.keyFrameMediaId),S=i(()=>{let t=xt(d??[]);return t?t.url:_t(e)},[d,e]),C=i(()=>!e?.faceBbox||v===null||b===null?null:ce(e.faceBbox,v,b),[e?.faceBbox,v,b]);if(e===null)return null;let w=e.keyFrameMediaId!==void 0&&!x,E=w&&m===`frame`,O=e.assigned?e.identityName??`Assigned`:e.recognizedIdentityId?`${e.identityName??`Recognized`} (suggested)`:`Unassigned`;return c(D,{open:!0,onOpenChange:e=>!e&&n(),children:r(T,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Face detail`,className:`flex max-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:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[r(`header`,{className:`flex shrink-0 items-start justify-between gap-2 border-b border-border px-4 py-3`,children:[r(`div`,{className:`min-w-0`,children:[c(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:`Face detail`}),c(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:t})]}),c(`button`,{type:`button`,onClick:n,className:`rounded p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Close`,children:c(I,{className:`h-4 w-4`})})]}),r(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[w&&r(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5 text-xs`,children:[r(`button`,{type:`button`,onClick:()=>g(`frame`),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 transition-colors ${m===`frame`?`bg-primary/12 font-medium text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[c(H,{className:`h-3.5 w-3.5`}),` Full frame`]}),r(`button`,{type:`button`,onClick:()=>g(`crop`),className:`flex flex-1 items-center justify-center gap-1 rounded px-2 py-1 transition-colors ${m===`crop`?`bg-primary/12 font-medium text-primary`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[c(ae,{className:`h-3.5 w-3.5`}),` Crop`]})]}),E&&_?c(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:c(ye,{src:_,alt:`Full frame with detected face`,fit:`natural`,className:`w-full`,overlay:C?c(Ct,{box:C}):void 0})}):S?r(`div`,{className:`relative aspect-square w-full overflow-hidden rounded-lg border border-border`,children:[c(ye,{src:S,alt:`Detected face`,className:`h-full w-full`}),p&&c(`div`,{className:`absolute right-2 top-2 rounded-full bg-black/50 p-1 text-white`,children:c(j,{className:`h-3.5 w-3.5 animate-spin`})})]}):r(`div`,{className:`flex aspect-square w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-warning/5 text-foreground-subtle`,children:[c(f,{className:`h-8 w-8 text-warning/70`}),c(`span`,{className:`text-[11px] font-medium uppercase tracking-wide text-warning/80`,children:`No image`}),c(`span`,{className:`px-6 text-center text-[10px] text-foreground-subtle`,children:`The crop media for this face could not be resolved (a pre-fix orphan). Safe to delete.`})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[c(St,{label:`Camera`,value:t}),c(St,{label:`Captured`,value:xe(e.timestamp)}),c(St,{label:`Track`,value:e.trackId}),c(St,{label:`Identity`,value:O})]})]}),r(`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:[e.assigned?r(y,{variant:`secondary`,onClick:()=>o(e.faceId),disabled:u,children:[c(se,{className:`h-3.5 w-3.5`}),` Detach`]}):r(y,{variant:`primary`,onClick:()=>a(e.faceId),disabled:u,children:[c(A,{className:`h-3.5 w-3.5`}),` Assign`]}),r(y,{variant:`secondary`,onClick:()=>l(e.faceId),disabled:u,children:[c(h,{className:`h-3.5 w-3.5`}),` Delete`]})]})]})})}function Tt(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function Et(e,t){return e.faceIds.filter(e=>!t.has(e))}function Dt(e,t){return e.faceIds.filter(e=>t(e))}n();var Ot=[[`faceGallery`]],kt=20,At=.3,jt=.9,Mt=.05,Nt=.5,Pt=2,Ft=10,It=2;function Lt({cluster:e,face:t,active:n,onSelect:i}){let a=_t(t);return r(`button`,{type:`button`,onClick:i,className:`flex shrink-0 flex-col items-center gap-1.5 rounded-md border p-2 text-center transition-colors md:w-full md:flex-row md:gap-2.5 md:text-left ${n?`border-primary bg-primary/8`:`border-border bg-surface hover:bg-surface-hover`}`,children:[c(`div`,{className:`h-24 w-24 shrink-0 overflow-hidden rounded bg-surface-hover`,children:a===null?c(f,{className:`h-24 w-24 p-6 text-foreground-subtle`}):c(`img`,{src:a,alt:``,loading:`lazy`,decoding:`async`,className:`h-24 w-24 object-cover`})}),r(`span`,{className:`w-24 text-[11px] leading-tight text-foreground-subtle md:w-auto`,children:[e.size,` faces · `,Math.round(e.cohesion*100),`% alike`]})]})}function Rt({face:e,cameraName:t,nowMs:n,excluded:i,onToggleExclude:a,onDelete:o,deletePending:s}){let l=_t(e);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden transition-opacity ${i?`border-border opacity-40 grayscale`:`border-border`}`,children:[r(`div`,{className:`aspect-square relative overflow-hidden bg-surface-hover`,children:[l===null?r(`div`,{className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,children:[c(f,{className:`h-7 w-7 text-warning/70`}),c(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:`No crop`})]}):c(ye,{src:l,alt:`Face from ${t}`,className:`h-full w-full`}),c(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),a()},className:`absolute right-1 top-1 z-10 rounded-full bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":i?`Include face`:`Exclude face`,title:i?`Include`:`Exclude`,children:c(i?S:I,{className:`h-3.5 w-3.5`})})]}),r(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[c(`p`,{className:`text-[10px] font-medium text-foreground truncate`,title:t,children:t}),c(`p`,{className:`text-[10px] text-foreground-subtle truncate`,children:ge(e.timestamp,n)})]}),c(`div`,{className:`mt-1 flex items-center justify-end border-t border-border/60 px-1 py-0.5`,children:c(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),o()},disabled:s,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40`,"aria-label":`Delete face`,title:`Delete face`,children:s?c(j,{className:`h-4 w-4 animate-spin`}):c(h,{className:`h-4 w-4`})})})]})}function zt({open:e,onClose:t,byId:n,cameraName:u,nowMs:d,identities:f,selectMany:p}){let m=o(),h=N(),g=v(),[_,b]=s(Nt),[x,S]=s(It),[C,w]=s(null),[O,k]=s({}),[ee,M]=s(null),{data:P,isFetching:F,refetch:L}=W({threshold:_,minClusterSize:x,limit:kt},{enabled:e}),R=P??[];l(()=>{k({})},[_,x]),l(()=>{if(R.length===0){w(null);return}R.some(e=>e.representativeFaceId===C)||w(R[0]?.representativeFaceId??null)},[R]);let z=i(()=>R.find(e=>e.representativeFaceId===C)??null,[R,C]),B=z?O[z.representativeFaceId]??new Set:new Set,V=i(()=>z?Dt(z,e=>n.has(e)):[],[z,n]),H=z?z.faceIds.length-V.length:0,U=z?Et({...z,faceIds:V},B):[];function te(e){if(!z)return;let t=z.representativeFaceId;k(n=>({...n,[t]:Tt(n[t]??new Set,e)}))}function K(){m.invalidateQueries({queryKey:Ot})}async function q(e){await h({title:`Delete face`,message:`Permanently deletes this face crop. This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&g.mutate({faceId:e},{onSettled:K})}function ne(){M(null),t()}function re(){U.length!==0&&(p(U),ne())}return r(D,{open:e,onOpenChange:e=>!e&&ne(),children:[r(T,{placement:`sheet-on-mobile`,width:`lg`,"aria-label":`Look-alike groups`,className:`flex max-h-[92dvh] flex-col gap-0 overflow-hidden p-0 md:max-w-4xl`,children:[r(`header`,{className:`flex shrink-0 flex-col gap-2 border-b border-border px-4 py-3`,children:[r(`div`,{className:`flex items-center justify-between gap-2`,children:[r(`div`,{className:`flex items-center gap-1.5 text-sm font-semibold text-foreground`,children:[c(E,{className:`h-4 w-4 text-primary`}),` Look-alike groups`]}),c(`button`,{type:`button`,onClick:ne,className:`rounded p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Close`,children:c(I,{className:`h-4 w-4`})})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[r(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Threshold`,c(`input`,{type:`range`,min:At,max:jt,step:Mt,value:_,onChange:e=>b(Number(e.target.value)),className:`h-1.5 w-28 cursor-pointer accent-primary`}),c(`span`,{className:`w-8 shrink-0 text-right font-mono text-[11px] tabular-nums text-foreground`,children:_.toFixed(2)})]}),r(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Min size`,c(`input`,{type:`number`,min:Pt,max:Ft,step:1,value:x,onChange:e=>S(Math.min(Ft,Math.max(Pt,Number(e.target.value)||Pt))),className:`w-12 rounded border border-border bg-background px-1.5 py-0.5 text-xs text-foreground`})]}),r(y,{variant:`secondary`,onClick:()=>{k({}),L()},disabled:F,children:[F?c(j,{className:`h-3.5 w-3.5 animate-spin`}):c(G,{className:`h-3.5 w-3.5`}),`Re-analyze`]})]})]}),c(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-4 py-3 md:flex-row`,children:F&&R.length===0?r(`div`,{className:`flex flex-1 items-center justify-center gap-2 py-8 text-xs text-foreground-subtle`,children:[c(j,{className:`h-4 w-4 animate-spin`}),` Finding similar faces…`]}):R.length===0?c(`div`,{className:`flex flex-1 items-center justify-center py-8 text-xs text-foreground-subtle`,children:`No look-alike groups at this threshold.`}):r(a,{children:[c(`div`,{className:`flex gap-2 overflow-x-auto pb-1 md:hidden`,children:R.map(e=>c(Lt,{cluster:e,face:n.get(e.representativeFaceId),active:e.representativeFaceId===C,onSelect:()=>w(e.representativeFaceId)},e.representativeFaceId))}),c(`div`,{className:`hidden shrink-0 flex-col gap-2 overflow-y-auto md:flex md:w-56`,children:R.map(e=>c(Lt,{cluster:e,face:n.get(e.representativeFaceId),active:e.representativeFaceId===C,onSelect:()=>w(e.representativeFaceId)},e.representativeFaceId))}),c(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:z&&r(a,{children:[H>0&&r(`p`,{className:`mb-2 text-[11px] text-foreground-subtle`,children:[H,` not loaded — excluded from actions`]}),c(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(13rem,1fr))] gap-2`,children:V.map(e=>{let t=n.get(e);return t?c(Rt,{face:t,cameraName:u(t.deviceId),nowMs:d,excluded:B.has(e),onToggleExclude:()=>te(e),onDelete:()=>void q(e),deletePending:g.isPending&&g.variables?.faceId===e},e):null})})]})})]})}),r(`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:[c(y,{variant:`secondary`,onClick:re,disabled:U.length===0,children:`Select in gallery`}),r(y,{variant:`primary`,onClick:()=>M(U),disabled:U.length===0,children:[c(A,{className:`h-3.5 w-3.5`}),` Adopt (`,U.length,`)`]})]})]}),c(yt,{faceIds:ee,identities:f,onDone:()=>M(null)})]})}n();var Bt=[[`faceGallery`]],Vt=500,Ht=120;function Ut({face:e,cameraName:t,nowMs:n,selected:i,onToggleSelect:a,onAssign:s,onOpenDetail:l}){let u=o(),p=k(),m=v(),g=()=>{u.invalidateQueries({queryKey:Bt})},_=()=>l(e.faceId),y=_t(e);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${i?`border-primary ring-1 ring-primary`:`border-border`}`,children:[r(`div`,{className:`aspect-square relative overflow-hidden bg-surface-hover`,children:[y===null?r(`button`,{type:`button`,onClick:_,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-warning/5 text-foreground-subtle`,title:`No crop image — the face's crop media is missing (a pre-fix orphan). Safe to delete.`,children:[c(f,{className:`h-7 w-7 text-warning/70`}),c(`span`,{className:`text-[9px] font-medium uppercase tracking-wide text-warning/80`,children:`No crop`})]}):c(`img`,{src:y,alt:`Face from ${t}`,onClick:_,loading:`lazy`,decoding:`async`,className:`h-full w-full cursor-zoom-in object-cover`}),c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(e.faceId)},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":i?`Deselect`:`Select`,children:i?c(X,{className:`h-4 w-4 text-primary`}):c(d,{className:`h-4 w-4`})})]}),r(`div`,{className:`min-w-0 px-2 pt-1.5 space-y-0.5`,children:[c(`p`,{className:`text-[10px] font-medium text-foreground truncate`,title:t,children:t}),c(`p`,{className:`text-[10px] text-foreground-subtle truncate`,children:ge(e.timestamp,n)}),e.identityName&&c(`p`,{className:`text-[10px] font-medium text-primary truncate`,title:e.identityName,children:e.identityName})]}),r(`div`,{className:`mt-1 flex items-center gap-0.5 border-t border-border/60 px-1 py-0.5`,children:[e.assigned?c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),p.mutate({faceId:e.faceId},{onSettled:g})},disabled:p.isPending,className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-warning/10 hover:text-warning disabled:opacity-40`,"aria-label":`Detach face`,title:`Detach`,children:p.isPending?c(j,{className:`h-4 w-4 animate-spin`}):c(se,{className:`h-4 w-4`})}):c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),s(e.faceId)},className:`rounded p-1.5 text-foreground-subtle transition-colors hover:bg-primary/10 hover:text-primary`,"aria-label":`Assign face to person`,title:`Assign to person`,children:c(A,{className:`h-4 w-4`})}),c(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),m.mutate({faceId:e.faceId},{onSettled:g})},disabled:m.isPending,className:`ml-auto rounded p-1.5 text-foreground-subtle transition-colors hover:bg-danger/10 hover:text-danger disabled:opacity-40`,"aria-label":`Delete face`,title:`Delete face`,children:m.isPending?c(j,{className:`h-4 w-4 animate-spin`}):c(h,{className:`h-4 w-4`})})]})]})}var Wt=[{label:`All`,value:`all`},{label:`Unassigned`,value:`unassigned`},{label:`Recognized`,value:`recognized`}];function Gt(){let e=o(),[t,n]=s(`all`),[l,u]=s(Ce),[d,p]=s(new Set),[m,g]=s(new Set),[_,b]=s(null),[S,w]=s(!1),[T,D]=s(null),{data:O,isLoading:N}=M({limit:Vt,filter:t,includeCrops:!1},{refetchInterval:3e4}),{data:P=[]}=x(),{data:F}=C({isCamera:!0,projection:`slim`}),L=ne(),R=k(),z=ee(),B=v(),V=Date.now(),H=O??[],U=i(()=>{let e=new Map;for(let t of F??[])e.set(t.id,t.name);return e},[F]),W=e=>U.get(e)??`Camera #${String(e)}`,te=i(()=>he(H).map(e=>({id:e,name:W(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[H,U]),G=i(()=>ve(Te(H,l),d),[H,l,d]),K=be(G,Ht,i(()=>JSON.stringify([t,l.fromMs,l.toMs,[...d].sort((e,t)=>e-t)]),[t,l.fromMs,l.toMs,d])),q=i(()=>new Map(H.map(e=>[e.faceId,e])),[H]),re=i(()=>gt(G),[G]),ie=T===null?null:q.get(T)??null,J=()=>{e.invalidateQueries({queryKey:Bt})},Y=()=>g(new Set);function ae(e){g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function oe(e){g(t=>{let n=new Set(t);for(let t of e)n.add(t);return n})}function ce(){oe(ht(G))}let X=[...m],Z=L.isPending||z.isPending||B.isPending,le=R.isPending||B.isPending;function ue(){X.length!==0&&z.mutate({faceIds:X},{onSettled:()=>{J(),Y()}})}function de(){X.length!==0&&Promise.allSettled(X.map(e=>B.mutateAsync({faceId:e}))).then(()=>{J(),Y()})}function fe(e){D(null),b([e])}function pe(e){R.mutate({faceId:e},{onSettled:J}),D(null)}function ge(e){B.mutate({faceId:e},{onSettled:J}),D(null)}let ye=G.length!==H.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[c(`div`,{className:`flex items-center gap-1`,children:Wt.map(e=>c(`button`,{type:`button`,onClick:()=>n(e.value),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${t===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:e.label},e.value))}),c(Se,{onChange:u}),c(_e,{cameras:te,selected:d,onChange:p}),r(`button`,{type:`button`,onClick:()=>w(!0),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${S?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[c(E,{className:`h-3.5 w-3.5`}),` Similar groups`]}),!N&&re>0&&r(`button`,{type:`button`,onClick:ce,className:`ml-auto flex items-center gap-1 rounded-md px-2.5 py-1 text-xs text-warning/90 transition-colors hover:bg-warning/10`,title:`Select every visible face whose crop image is missing so you can delete the orphans in one pass`,children:[c(f,{className:`h-3.5 w-3.5`}),` Select `,re,` crop-less`]}),!N&&c(`span`,{className:`text-[10px] text-foreground-subtle ${re>0?`ml-2`:`ml-auto`}`,children:ye?`${String(G.length)} of ${String(H.length)} faces`:`${String(G.length)} face${G.length===1?``:`s`}`})]}),m.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[m.size,` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[r(y,{variant:`primary`,onClick:()=>b(X),disabled:Z,children:[c(A,{className:`h-3.5 w-3.5`}),` Assign`]}),r(y,{variant:`secondary`,onClick:ue,disabled:Z,children:[z.isPending?c(j,{className:`h-3.5 w-3.5 animate-spin`}):c(se,{className:`h-3.5 w-3.5`}),` `,`Detach`]}),r(y,{variant:`secondary`,onClick:de,disabled:Z,children:[c(h,{className:`h-3.5 w-3.5`}),` Delete`]}),c(y,{variant:`ghost`,onClick:Y,disabled:Z,children:c(I,{className:`h-3.5 w-3.5`})})]})]}),N&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[c(j,{className:`h-4 w-4 animate-spin`}),` Loading faces…`]}),!N&&G.length===0&&c(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:H.length>0?`No faces match the current date / camera filters.`:`No faces found for this filter.`}),!N&&G.length>0&&r(a,{children:[c(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(6.5rem,1fr))] gap-2`,children:K.pageItems.map(e=>c(Ut,{face:e,cameraName:W(e.deviceId),nowMs:V,selected:m.has(e.faceId),onToggleSelect:ae,onAssign:e=>b([e]),onOpenDetail:D},e.faceId))}),c(me,{currentPage:K.page,totalItems:K.totalItems,pageSize:K.pageSize,onPageChange:K.setPage,itemNoun:`faces`})]}),c(wt,{face:ie,cameraName:ie?W(ie.deviceId):``,onClose:()=>D(null),onAssign:fe,onUnassign:pe,onDelete:ge,actionsPending:le}),c(yt,{faceIds:_,identities:P,onDone:()=>{b(null),Y()}}),c(zt,{open:S,onClose:()=>w(!1),byId:q,cameraName:W,nowMs:V,identities:P,selectMany:oe})]})}n();var Kt=[[`faceGallery`]],qt=2e3;function Jt(){let e=o(),n=t(e);n.current=e;let r=t(void 0);r.current||=we({delayMs:qt,invalidate:()=>{n.current.invalidateQueries({queryKey:Kt})}}),l(()=>()=>r.current?.cancel(),[]),J(le.PipelineAnalyticsFaceGalleryChanged,()=>{r.current?.trigger()})}function Yt(){return Jt(),c(de,{icon:ue,title:`Faces`,subtitle:`Manage enrolled identities and assign detected face crops to people.`,children:r(`section`,{className:`space-y-3`,children:[r(`div`,{children:[c(`h2`,{className:`text-sm font-semibold text-foreground mb-1`,children:`People`}),c(`p`,{className:`text-xs text-foreground-subtle mb-3`,children:`Enrolled identities used for face recognition. Expand a row to view or remove training samples.`}),c(pt,{})]}),r(`div`,{className:`pt-4 border-t border-border`,children:[c(`h2`,{className:`text-sm font-semibold text-foreground mb-1`,children:`Recent detected faces`}),c(`p`,{className:`text-xs text-foreground-subtle mb-3`,children:`Face crops captured by the detection pipeline. Assign them to a person to build recognition training data.`}),c(Gt,{})]})]})})}export{Yt as DetectionIntelligencePage};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,a as r,x as i}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{at as a}from"./player-overlays-BHG5CSFQ.js";import{f as o}from"./src-De0k1ip_.js";import{At as s,Dt as c,Et as l,Ot as u,Tt as d,jt as f,kt as p,wt as m}from"./src-BpnJ-sMW.js";import"./notification-schedule-field-BzLlAfqp.js";e();var h=6e4;function g(e){let t=a();return r({queryKey:[`device-do-action`,`bound-caps`,e],enabled:e>0,staleTime:h,queryFn:async()=>{let n=await t.trpcClient.deviceManager.getBindings.query({deviceId:e});return[...new Set(n.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t))}})}function _(e){let t=a(),n=[...new Set(e.filter(e=>e>0))].sort((e,t)=>e-t);return r({queryKey:[`device-do-action`,`bound-caps-batch`,n],enabled:n.length>0,staleTime:h,queryFn:async()=>{let e=await t.trpcClient.deviceManager.getBindingsBatch.query({deviceIds:n}),r=new Map;for(let t of e)r.set(t.deviceId,[...new Set(t.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t)));return r}})}var v=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,y=`block text-[11px] font-medium text-foreground`,b=`deviceId`;function x(e,t){return t.length===0?0:t.length===1?t[0]:t.find(t=>!e.includes(t))??t[t.length-1]}function S(e,t,n){if(t.length===0)return[];if(t.length===1)return t;let r=t.find(t=>!e.includes(t));if(r===void 0)return t;let i=n(r);if(i===void 0)return[r];let a=e[0]??t.find(e=>e!==r);if(a===void 0)return[r];let o=n(a);return o===void 0||!f(o,i)?[r]:t.filter(e=>{let t=n(e);return t!==void 0&&f(o,t)})}function C(e){return e.length===0?0:e.length===1?e[0]:[...e]}function w(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function T(e,t){return{deviceId:e,cap:t.cap,method:t.method,...t.args===void 0?{}:{args:{...t.args}}}}function E(e,t){return`Custom: ${e}.${t}`}function D({value:e,onChange:r,devices:a,listState:h,fleet:D,allowTriggerDevice:O=!1,allowMultiSameFamily:k=!1,testId:A=`device-do-action`}){let j=typeof e.deviceId!=`number`&&!Array.isArray(e.deviceId),M=w(e.deviceId),N=n(()=>a.filter(e=>p(String(e.type??``))),[a]),P=n(()=>{let e=new Map;for(let t of N)t.type!==void 0&&t.type!==null&&e.set(t.id,String(t.type));return e},[N]),F=n(()=>{if(!k||M.length===0)return N;let e=P.get(M[0]);return e===void 0?N:N.filter(t=>{if(M.includes(t.id))return!0;let n=t.type!==void 0&&t.type!==null?String(t.type):void 0;return n!==void 0&&f(e,n)})},[k,M,N,P]),I=g(!k&&M.length===1?M[0]:0),L=_(k?M:[]),R=n(()=>j?c():M.length===0?[]:k?L.isLoading&&L.data===void 0?[]:l(M.map(e=>({boundCaps:L.data?.get(e),deviceType:P.get(e)}))):I.data===void 0&&I.isLoading?[]:d({boundCaps:I.data,deviceType:P.get(M[0])}),[j,M,k,L.data,L.isLoading,I.data,I.isLoading,P]),z=u(e.cap,e.method,e.args),B=s(e.cap,e.method,e.args),V=e.cap!==``&&e.method!==``&&B===null&&(j||M.length>0),H=k?L.isLoading:I.isLoading,U=k?L.isError:I.isError,W=t=>{if(t.startsWith(`custom:`))return;let n=m.find(e=>e.id===t);n!==void 0&&r(T(j?e.deviceId:M.length>0?C(M):N[0]?.id??0,n))};return t(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,"data-testid":A,children:[O&&t(`div`,{className:`w-full max-w-xs`,children:[i(`label`,{className:y,children:`Target`}),t(`select`,{className:v,"data-testid":`${A}-target`,value:j?`trigger`:`device`,onChange:e=>{if(e.target.value===`trigger`){r({deviceId:{$var:b},cap:``,method:``});return}r({deviceId:N[0]?.id??0,cap:``,method:``})},children:[i(`option`,{value:`device`,children:`Specific device`}),i(`option`,{value:`trigger`,children:`The device that triggered this run`})]})]}),!j&&t(`div`,{"data-testid":`${A}-device`,children:[t(`label`,{className:y,children:[`Device`,k?`s`:``]}),i(o,{devices:F,listState:h,...D===void 0?{}:{fleet:D},value:[...M],onChange:e=>{r({deviceId:C(k?S(M,e,e=>P.get(e)):(()=>{let t=x(M,e);return t>0?[t]:[]})()),cap:``,method:``})},emptyLabel:k?`No devices selected`:`No device selected`,noun:`device`,testId:`${A}-device-picker`}),k&&M.length>1&&i(`p`,{className:`mt-1 text-[11px] text-foreground-subtle`,children:`Same family only — the action runs on each selected device.`})]}),t(`div`,{className:`w-full max-w-sm`,children:[i(`label`,{className:y,children:`Action`}),t(`select`,{className:v,"data-testid":`${A}-action`,value:z===`custom:${e.cap}.${e.method}`?z:B?.id??``,disabled:!j&&(M.length===0||H),onChange:e=>W(e.target.value),children:[i(`option`,{value:``,children:!j&&M.length===0?`Pick a device first`:H?`Loading actions…`:R.length===0?`No actions for this device`:`Select an action…`}),V&&i(`option`,{value:z,children:E(e.cap,e.method)}),R.map(e=>i(`option`,{value:e.id,children:e.label},e.id))]}),U&&i(`p`,{className:`mt-1 text-[11px] text-warning`,children:`Could not read this device’s capabilities.`})]}),B?.openArgs!==void 0&&B.openArgs.length>0&&i(`div`,{className:`flex flex-col gap-2`,children:B.openArgs.map(n=>{let a=e.args?.[n.key],o=typeof a==`string`||typeof a==`number`?String(a):``;return t(`div`,{className:`w-full max-w-sm`,children:[i(`label`,{className:y,htmlFor:`${A}-${n.key}`,children:n.label}),i(`input`,{id:`${A}-${n.key}`,className:v,"data-testid":`${A}-${n.key}`,type:n.kind===`number`?`number`:`text`,value:o,onChange:t=>{let i=t.target.value,a=e.args===void 0?{}:{...e.args};if(i===``)delete a[n.key];else if(n.kind===`number`){let e=Number(i);Number.isNaN(e)?delete a[n.key]:a[n.key]=e}else a[n.key]=i;r(Object.keys(a).length>0?{...e,args:a}:{deviceId:e.deviceId,cap:e.cap,method:e.method})}})]},n.key)})})]})}export{D as t};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,d as r,q as i,u as a,x as o,z as s}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{rt as c}from"./player-overlays-BHG5CSFQ.js";import{a as l,bl as u,bt as d,gt as f,kt as p}from"./src-De0k1ip_.js";import{Pr as m}from"./src-BpnJ-sMW.js";import{D as h,M as g,O as _,P as v,T as y,y as b}from"./__vite-browser-external-Cc3gW-QT.js";e();var x=v([_({kind:y(`adaptive`)}),_({kind:y(`profile`),profile:m})]),S=_({serverUrl:g().min(1),token:g().min(1),deviceId:h().int().nonnegative(),target:x,muted:b()});function C(e,t){let n=t===void 0?{type:`state`,state:e}:{type:`state`,state:e,message:t};window.ReactNativeWebView?.postMessage(JSON.stringify(n))}function w(e){switch(e){case`playing`:return`playing`;case`error`:return`error`;case`connecting`:case`disconnected`:case`idle`:return`connecting`}}function T(e){return e.kind===`adaptive`?{kind:`adaptive`}:{kind:`profile`,profile:e.profile}}function E(e){return e.kind===`adaptive`?`embed:adaptive`:`embed:profile:${e.profile}`}function D(){let e=window.__CAMSTACK_EMBED__;if(e==null)return{ok:!1,error:`window.__CAMSTACK_EMBED__ is not set`};let t=S.safeParse(e);return t.success?{ok:!0,config:t.data}:{ok:!1,error:t.error.issues.map(e=>`${e.path.join(`.`)||`(root)`}: ${e.message}`).join(`; `)}}function O({message:e}){return s(()=>{C(`error`,e)},[e]),t(`div`,{style:{position:`fixed`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:`#000`,color:`#f87171`,fontFamily:`system-ui, sans-serif`,fontSize:13,padding:16,textAlign:`center`},children:[`Embed config error: `,e]})}function k({system:e,deviceId:t,initialTarget:r,initialMuted:a}){let[c,u]=i(r),[d,f]=i(a),{handleOffer:m,getIceServers:h,addIceCandidate:g,getIceCandidates:_,closeSession:v,getSessionState:y,getSessionDebug:b}=l(e.trpcClient,t),S=n(()=>T(c),[c]),D=n(()=>(e,t)=>m(S,e,t),[m,S]),O=n(()=>(e,t,n)=>m(n,t,e),[m]);s(()=>(window.__camstackEmbed={setMuted:e=>f(e),setTarget:e=>{let t=x.safeParse(e);t.success&&u(t.data)}},()=>{window.__camstackEmbed&&delete window.__camstackEmbed}),[]);let k=E(c);return o(`div`,{style:{position:`fixed`,inset:0,width:`100vw`,height:`100vh`,background:`#000`},children:o(p,{serverUrl:e.serverUrl,streamKey:k,autoPlay:!0,muted:d,showControls:!1,className:`w-full h-full`,getSessionDebug:b,handleOffer:D,reoffer:O,getSessionState:y,getIceServers:h,addIceCandidate:g,getIceCandidates:_,closeSession:v,onStateChange:e=>C(w(e)),onError:e=>C(`error`,e)},k)})}function A(){let e=n(()=>D(),[]),t=n(()=>{if(!e.ok)return null;let t=d({serverUrl:e.config.serverUrl,token:e.config.token}),n=new r({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});return f(n),{system:t,queryClient:n}},[e]);return s(()=>{if(t)return()=>{t.system.close()}},[t]),e.ok?t?o(c,{system:t.system,children:o(a,{client:t.queryClient,children:o(u.Provider,{client:t.system.trpcClient,queryClient:t.queryClient,children:o(k,{system:t.system,deviceId:e.config.deviceId,initialTarget:e.config.target,initialMuted:e.config.muted})})})}):o(O,{message:`Failed to initialise the embed player`}):o(O,{message:e.error})}export{A as EmbedPlayerPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,U as i,W as a,a as o,b as s,o as c,q as l,x as u,z as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{X as f,Z as p,at as m,ct as h,ft as g,gt as _,ht as v,st as y,vt as b}from"./player-overlays-BHG5CSFQ.js";import{Ao as x,Bn as S,Bo as C,Cn as w,Do as T,Dt as E,Fl as D,Fn as O,Fo as k,Gi as ee,Gl as A,Hd as j,Hl as M,Hn as N,Ho as P,Io as te,Jo as F,Jt as ne,Kl as re,Ko as ie,Kt as I,Lo as L,Mo as R,Mu as z,Nn as B,No as ae,Nu as V,Pn as oe,Po as se,Q as H,Ro as U,Sd as W,Sl as ce,Sn as G,Uo as le,Vn as ue,Vo as de,Wo as fe,Xo as pe,Yo as me,_n as he,ad as ge,bn as K,cn as _e,ds as ve,fo as ye,in as be,ko as xe,ld as Se,lr as Ce,md as we,ml as Te,od as Ee,ou as De,pl as Oe,pu as ke,qo as Ae,qu as je,ss as Me,td as Ne,tn as Pe,xs as Fe,yd as Ie,yl as Le}from"./src-De0k1ip_.js";import{t as Re}from"./square-check-big-CsHHs7_N.js";import{Br as ze,En as Be}from"./src-BpnJ-sMW.js";import{t as Ve}from"./useTranslation-Bc5yH9V9.js";import"./mount-C3GxEmbZ.js";import{t as He}from"./AdminPage-CiKtOLQm.js";import{a as Ue,i as We,r as Ge,t as Ke}from"./authed-media-Bf77DHiU.js";import{a as qe,c as Je,d as Ye,f as Xe,i as Ze,n as Qe,o as $e,p as et,r as tt,s as nt,t as rt}from"./debounced-invalidate-CHSCMizx.js";import{t as it}from"./use-stationary-objects-Da0t43FO.js";import{t as at}from"./AdminTabs-CIqJ81O1.js";import{t as ot}from"./format-size-DIxKXxtj.js";var st=b(`arrow-down-wide-narrow`,[[`path`,{d:`m3 16 4 4 4-4`,key:`1co6wj`}],[`path`,{d:`M7 20V4`,key:`1yoxec`}],[`path`,{d:`M11 4h10`,key:`1w87gc`}],[`path`,{d:`M11 8h7`,key:`djye34`}],[`path`,{d:`M11 12h4`,key:`q8tih4`}]]),ct=b(`circle-dashed`,[[`path`,{d:`M10.1 2.182a10 10 0 0 1 3.8 0`,key:`5ilxe3`}],[`path`,{d:`M13.9 21.818a10 10 0 0 1-3.8 0`,key:`11zvb9`}],[`path`,{d:`M17.609 3.721a10 10 0 0 1 2.69 2.7`,key:`1iw5b2`}],[`path`,{d:`M2.182 13.9a10 10 0 0 1 0-3.8`,key:`c0bmvh`}],[`path`,{d:`M20.279 17.609a10 10 0 0 1-2.7 2.69`,key:`1ruxm7`}],[`path`,{d:`M21.818 10.1a10 10 0 0 1 0 3.8`,key:`qkgqxc`}],[`path`,{d:`M3.721 6.391a10 10 0 0 1 2.7-2.69`,key:`1mcia2`}],[`path`,{d:`M6.391 20.279a10 10 0 0 1-2.69-2.7`,key:`1fvljs`}]]),lt=b(`circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),ut=b(`graduation-cap`,[[`path`,{d:`M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z`,key:`j76jl0`}],[`path`,{d:`M22 10v6`,key:`1lu8f3`}],[`path`,{d:`M6 12.5V16a6 3 0 0 0 12 0v-3.5`,key:`1r8lef`}]]),dt=b(`square-parking`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 17V7h4a3 3 0 0 1 0 6H9`,key:`1dfk2c`}]]);n();function ft(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 pt=720*60*60*1e3;function mt(e){let t=[];for(let n of e)t.push(...n);return t}function ht(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function gt(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 _t(e,t){return`${String(e)}:${t}`}function vt(e,t){let n=new Map,r=new Set;for(let i of e){let e=_t(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 yt(e,t){return{since:e.fromMs??t-pt,until:e.toMs??t}}var bt=[`native`,`raster`,`standin`];function xt(e){return bt.some(t=>t===e)}var St={standin:{label:`stand-in`,title:`Stand-in: this tile is a face or plate detail crop copied in because no frame of the subject was captured. It is not a best shot.`,tone:`warning`},raster:{label:`low-res`,title:`Raster crop: a sub-native cut of the subject, not a native capture. Honest, but lower resolution than a best shot.`,tone:`info`}};function Ct(e){return e===`standin`?St.standin:e===`raster`?St.raster:null}var wt={"no-key-frame":`No key frame existed at close, so no native tile could be cut.`,"no-best-seen-bbox":`No subject box was ever recorded, so there was nothing to cut around.`,"derive-returned-null":`The close-time crop was attempted and produced nothing.`,"derive-threw":`The close-time crop failed with an error.`,"derive-not-wired":`No close-time crop was wired on this node.`,"no-media-store":`The node was shutting down mid-close.`,"no-thumbnail":`The track closed with no tile of any kind.`,"standin-tile":`The track closed with a detail crop standing in for the subject.`,"raster-tile":`The track closed with a sub-native raster crop of the subject.`,"native-tile":`The track closed with a native tile.`};function Tt(e){if(e===void 0)return null;let t=e.trim();if(t.length===0)return null;let n=t.split(/\s+/),r=n[0]??t,i=[];for(let e of n.slice(1)){let t=e.indexOf(`=`);t===-1?i.push({key:e,value:null}):i.push({key:e.slice(0,t),value:e.slice(t+1)})}return{sentence:wt[r]??r,detail:i,raw:t}}function Et(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 Dt({row:e,cameraName:t,nowMs:n,onOpenDetail:i,selected:a=!1,onToggleSelect:o,score:s,provenance:c,footer:l}){let d=Ue(e.mediaId===void 0?We(`track`,e.trackId):Ge(e.mediaId)),f=Math.round(e.importance*100),p=s===void 0?void 0:Math.round(s*100),m=Et(e.windowMs),_=()=>i(e),v=Ct(c);return r(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${a?`border-primary ring-1 ring-primary`:`border-border`}`,children:[r(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[d.src?u(`img`,{src:d.src,alt:`Event from ${t}`,onClick:_,className:`h-full w-full cursor-zoom-in object-cover`}):u(`button`,{type:`button`,onClick:_,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:d.failed?`Key-event media unavailable`:`No key-event media`,children:u(g,{className:`h-6 w-6 opacity-60`})}),o&&u(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),o(_t(e.deviceId,e.trackId))},className:`absolute left-0 top-0 z-10 rounded-br-md bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":a?`Deselect`:`Select`,children:a?u(Re,{className:`h-4 w-4 text-primary`}):u(h,{className:`h-4 w-4`})}),p!==void 0&&r(`span`,{className:`absolute left-1 top-1 z-10 rounded bg-primary/85 px-1.5 py-0.5 text-[10px] font-semibold text-white tabular-nums`,title:`CLIP semantic-match score`,children:[String(p),`%`]}),f>0&&u(`span`,{className:`absolute right-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white`,children:String(f)}),v!==null&&u(`span`,{className:`absolute bottom-1 right-1 z-10 rounded px-1.5 py-0.5 text-[10px] font-semibold text-white ${v.tone===`warning`?`bg-warning/90`:`bg-black/70`}`,title:v.title,children:v.label}),(e.markForTrain===!0||e.debug===!0||e.favourited===!0)&&r(`span`,{className:`absolute bottom-1 left-1 z-10 flex gap-1`,children:[e.markForTrain===!0&&u(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Marked for training`,"aria-label":`Marked for training`,children:u(ut,{className:`h-3 w-3`})}),e.debug===!0&&u(`span`,{className:`rounded bg-black/70 p-0.5 text-white`,title:`Flagged for debug`,"aria-label":`Flagged for debug`,children:u(W,{className:`h-3 w-3`})}),e.favourited===!0&&u(`span`,{className:`rounded bg-primary/85 p-0.5 text-white`,title:`Favourited`,"aria-label":`Favourited`,children:u(A,{className:`h-3 w-3`})})]})]}),r(`button`,{type:`button`,onClick:_,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[r(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:e.className,children:[e.className,ft(e)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,ft(e)]}):null]}),u(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:t,children:t}),r(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:Xe(e.timestamp,n)}),m&&u(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:m})]})]}),l!==void 0&&u(`div`,{className:`px-2 pb-1.5`,children:l})]})}var Ot=1400,kt=`Admin-gated URL — opens only inside an authenticated session`;function At({label:t,value:n,title:i}){let[a,o]=l(!1),s=O();return d(()=>{if(!a)return;let e=setTimeout(()=>o(!1),Ot);return()=>clearTimeout(e)},[a]),r(`button`,{type:`button`,onClick:e(()=>{(async()=>{try{await navigator.clipboard.writeText(n),o(!0)}catch{await s({title:`Copy the media URL`,message:`Clipboard access was refused. Select the URL below and copy it manually.`,label:`${t} URL`,defaultValue:n,readOnly:!0,cancelLabel:`Close`})}})()},[n,t,s]),title:i,"aria-label":`Copy ${t} URL`,className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${a?`border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[u(a?Ie:ge,{className:`h-2.5 w-2.5 shrink-0`}),u(`span`,{className:`truncate`,children:a?`Copied`:t})]})}function jt({localUrl:e,publicUrl:t}){return r(`div`,{className:`flex flex-wrap gap-1`,children:[u(At,{label:`Local`,value:e,title:`Copy LAN URL — ${kt}`}),t&&u(At,{label:`Public`,value:t,title:`Copy public URL — ${kt}`})]})}var Mt={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 Nt(e){return e in Mt}function Pt(e){return Nt(e)?Mt[e]:e}function Ft(e,t){return`${e}${t}`}n();var It=3e4;function Lt(t){let[n,r]=l(null),i=e(e=>{r(t=>t??e)},[]);return d(()=>{t||r(null)},[t]),{publicOrigin:n,probes:t?u(Rt,{onOrigin:i}):null}}function Rt({onOrigin:e}){let{data:t}=Ce({capName:`network-access`});return u(s,{children:(t??[]).map(t=>u(zt,{addonId:t.addonId,onOrigin:e},t.addonId))})}function zt({addonId:e,onOrigin:t}){let{data:n}=ye({addonId:e},{refetchInterval:It,retry:!1});return d(()=>{let e=n?Be.safeParse(n):null,r=e?.success?e.data.endpoint?.url:void 0;if(r)try{t(new URL(r).origin)}catch{}},[n,t]),null}var q=typeof me==`function`,Bt=`Track flags arrive with the next server update`;function Vt(){return{mutateAsync:async()=>{throw Error(`setTrackFlags unavailable`)},isPending:!1}}var Ht=q?me:Vt;function Ut(e){if(typeof e!=`object`||!e||!(`trackId`in e)||!(`markForTrain`in e)||!(`debug`in e)||!(`favourited`in e))return null;let{trackId:t,markForTrain:n,debug:r,favourited:i}=e;return typeof t!=`string`||typeof n!=`boolean`||typeof r!=`boolean`||typeof i!=`boolean`?null:{trackId:t,markForTrain:n,debug:r,favourited:i}}n();function Wt({label:e,hint:t,checked:n,disabled:i,title:a,icon:o,onToggle:s}){return r(`button`,{type:`button`,role:`switch`,"aria-checked":n,"aria-label":e,disabled:i,title:a,onClick:s,className:`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left transition-colors disabled:opacity-50 ${n?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[u(`span`,{className:n?`text-primary`:`text-foreground-subtle`,children:o}),r(`span`,{className:`min-w-0 flex-1`,children:[u(`span`,{className:`block text-[11px] font-medium text-foreground`,children:e}),u(`span`,{className:`block text-[10px] text-foreground-subtle`,children:t})]}),u(`span`,{"aria-hidden":`true`,className:`h-4 w-7 shrink-0 rounded-full p-0.5 transition-colors ${n?`bg-primary`:`bg-border`}`,children:u(`span`,{className:`block h-3 w-3 rounded-full bg-white transition-transform ${n?`translate-x-3`:``}`})})]})}function Gt({deviceId:e,trackId:t,markForTrain:n,debug:i,favourited:a,onChange:o}){let s=Ht(),c=B(),[d,f]=l(null),p=d?.markForTrain??n===!0,m=d?.debug??i===!0,h=d?.favourited??a===!0,g=!q||s.isPending,_=q?void 0:Bt,v=n=>{g||(async()=>{try{let r=Ut(await s.mutateAsync({deviceId:e,trackId:t,flags:n}));if(!r)return;f(r),o?.(r)}catch(e){let t=e instanceof Error?e.message:``;await c({title:`Could not update this track`,message:t===``?`Could not update this track. Check the server logs.`:t,variant:`danger`})}})()};return r(`div`,{className:`grid gap-1.5 sm:grid-cols-2`,children:[u(Wt,{label:`Mark for training`,hint:`Keeps this track and its media past retention`,checked:p,disabled:g,..._===void 0?{}:{title:_},icon:u(ut,{className:`h-4 w-4`}),onToggle:()=>v({markForTrain:!p})}),u(Wt,{label:`Debug`,hint:`Flag this track for diagnostic attention`,checked:m,disabled:g,..._===void 0?{}:{title:_},icon:u(W,{className:`h-4 w-4`}),onToggle:()=>v({debug:!m})}),u(Wt,{label:`Favourited`,hint:`Keeps this track and its media past retention`,checked:h,disabled:g,..._===void 0?{}:{title:_},icon:u(A,{className:`h-4 w-4`}),onToggle:()=>v({favourited:!h})})]})}var J=100,Kt=120,qt={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},Y=e=>e<0?0:e>1?1:e,Jt=e=>Math.round(e*100)/100;function Yt(e,t){if(e.length<=t)return[...e];let n=(e.length-1)/(t-1),r=[];for(let i=0;i<t;i++)r.push(e[Math.round(i*n)]);return r[r.length-1]=e[e.length-1],r}function Xt(e,t,n){if(e.length===0||t===null)return qt;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return qt;let a=Yt(e,n?.maxPoints??Kt).map(e=>({x:Jt(Y(e.x/r)*J),y:Jt(Y(e.y/i)*J)})),o=a[0]??null,s=a[a.length-1]??null,c=a.length>=2?a.map(e=>`${e.x},${e.y}`).join(` `):``,l=(n?.snapshots??[]).map(e=>({x:Jt(Y(e.x/r)*J),y:Jt(Y(e.y/i)*J),mediaId:e.mediaId})),u=null,d=-1;for(let t of e){let e=Y(t.bbox.w/r)*Y(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:Jt(Y(u.bbox.x/r)*J),y:Jt(Y(u.bbox.y/i)*J),w:Jt(Y(u.bbox.w/r)*J),h:Jt(Y(u.bbox.h/i)*J)}:null}}var Zt=typeof xe==`function`,Qt=`Track deletion arrives with the next server update`;function $t(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var en=Zt?xe:$t;n();var tn=15e3,nn=f();function rn({url:e,label:t}){let{src:n,failed:r}=Ue(e);return n===null?u(`div`,{className:`flex h-full w-full items-center justify-center bg-surface-hover`,children:r?u(g,{className:`h-4 w-4 text-foreground-subtle opacity-60`}):u(V,{className:`h-4 w-4 animate-spin text-foreground-subtle opacity-70`})}):u(`img`,{src:n,alt:t,className:`h-full w-full object-cover`})}var an=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),on=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`,`sceneFrame`,`lastSceneFrame`]);function sn(e){let[t,n]=l(null);return d(()=>{if(n(null),!e)return;let t=!1,r=new Image;return r.onload=()=>{t||n({width:r.naturalWidth,height:r.naturalHeight})},r.src=e,()=>{t=!0,r.onload=null}},[e]),t}function cn({overlay:e,onPickSnapshot:t}){return!e.polyline&&!e.peakBox&&e.snapshots.length===0?null:r(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[e.peakBox&&u(`rect`,{x:e.peakBox.x,y:e.peakBox.y,width:e.peakBox.w,height:e.peakBox.h,fill:`none`,stroke:`#f59e0b`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&u(`polyline`,{points:e.polyline,fill:`none`,stroke:`#38bdf8`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),e.points.map((e,t)=>u(`circle`,{cx:e.x,cy:e.y,r:1,fill:`#38bdf8`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),e.snapshots.map((e,n)=>u(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`#0ea5e9`,fillOpacity:.95,stroke:`#082f49`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:t?`pointer-events-auto cursor-pointer`:void 0,onClick:t?n=>{n.stopPropagation(),t(e.mediaId)}:void 0,children:u(`title`,{children:`Snapshot checkpoint — click to view this frame`})},`snap-${String(e.mediaId)}-${String(n)}`)),e.start&&u(`circle`,{cx:e.start.x,cy:e.start.y,r:2.4,fill:`#22c55e`,stroke:`#052e16`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&u(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`#ef4444`,stroke:`#450a0a`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function X({label:e,value:t,mono:n}){return r(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[u(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),u(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground ${n?`font-mono text-[11px]`:``}`,title:t,children:t})]})}function ln({row:t,cameraName:n,deleteAvailable:i,onClose:o,onDeleted:c,onFlagsChanged:f}){let p=m(),h=B(),_=oe(),v=en(),b=t!==null,x=t?.deviceId??0,S=t?.trackId??``,C=t?.timestamp??0,T=t?.windowMs??0,{data:E}=se({deviceId:x,trackId:S},{enabled:b}),{data:D}=le({trackId:S,deviceId:x},{enabled:b}),O=E?.bestEventId===void 0?void 0:Number(E.bestEventId),{data:k}=U({ownerType:`object`,eventId:O??0,deviceId:x},{enabled:b&&O!==void 0&&Number.isFinite(O)}),{data:ee}=Te({deviceId:x},{enabled:b}),A=(ee??[]).find(e=>e.addonId!==void 0)?.addonId,{data:j}=Oe({deviceId:x,since:C-tn,until:C+T+tn,provider:A??``},{enabled:b&&A!==void 0}),[M,N]=l(null),[P,te]=l(!1),{publicOrigin:F,probes:re}=Lt(b);d(()=>{N(null)},[x,S]);let ie=a(()=>{let e=D??[],t=k??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[D,k]),L=M??ie,R=Ue(L?L.url:void 0),z=a(()=>{let e=new Set,t=[];for(let n of[...k??[],...D??[]])e.has(n.mediaId)||(e.add(n.mediaId),t.push(n));return t},[k,D]),ae=a(()=>z.find(e=>an.has(e.kind))??null,[z]),H=sn(Ue(ae?ae.url:void 0).src),W=a(()=>Xt(E?.positions??[],H,{snapshots:(E?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaId:e.mediaId}))}),[E?.positions,E?.snapshots,H]),G=e(e=>{let t=z.find(t=>t.mediaId===e);t&&N(t)},[z]);if(t===null)return null;let ue=R.src,de=L?.kind,fe=de!==void 0&&on.has(de)&&H!==null&&(E?.positions.length??0)>=2,pe=j&&j.length>0?j[0]:null,me=()=>{pe&&(te(!0),(async()=>{try{let e=await p.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:pe.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{h({title:`Clip unavailable`,message:`Could not resolve clip playback. Check the server logs.`,variant:`warning`})}finally{te(!1)}})())},he=()=>{!i||v.isPending||(async()=>{if(await _({title:`Delete track`,message:`Delete this track and every image and clip captured for it? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`}))try{await v.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),c()}catch{await h({title:`Delete failed`,message:`Failed to delete this track. Check the server logs.`,variant:`danger`})}})()},ge=Math.round(t.importance*100),K=E?.importanceReason?`${String(ge)}% · ${E.importanceReason}`:`${String(ge)}%`,_e=E?.zonesVisited&&E.zonesVisited.length>0?E.zonesVisited.join(`, `):`—`,ve=E?.audioLabels&&E.audioLabels.length>0?E.audioLabels:t.audioLabels&&t.audioLabels.length>0?t.audioLabels:void 0,ye=ve===void 0?`—`:ve.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `),be=E?E.totalDistance.toFixed(2):`—`,xe=Tt(E?.previewMissReason),Se=et(E?E.firstSeen:C),Ce=E?et(E.lastSeen):`—`;return u(I,{open:!0,onOpenChange:e=>!e&&o(),children:r(ne,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Event detail`,className:`flex h-[92dvh] flex-col gap-0 overflow-hidden p-0 bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none md:bottom-auto md:left-1/2 md:right-auto md:top-1/2 md:h-auto md:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[r(`header`,{className:`flex shrink-0 items-start justify-between gap-2 border-b border-border px-4 py-3`,children:[r(`div`,{className:`min-w-0`,children:[r(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,ft(t)?r(`span`,{className:`text-foreground-subtle`,children:[` · `,ft(t)]}):null]}),u(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:n})]}),u(`button`,{type:`button`,onClick:o,className:`rounded p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Close`,children:u(ce,{className:`h-4 w-4`})})]}),r(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[ue?u(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:u(Qe,{src:ue,alt:`Key frame from ${n}`,fit:`natural`,className:`w-full`,overlay:fe?u(cn,{overlay:W,onPickSnapshot:G}):void 0})}):u(`div`,{className:`flex aspect-video w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-surface-hover text-foreground-subtle`,children:R.failed?r(s,{children:[u(g,{className:`h-8 w-8 opacity-60`}),u(`span`,{className:`text-[11px]`,children:`Key-frame media unavailable`})]}):u(V,{className:`h-6 w-6 animate-spin opacity-70`})}),z.length>0&&u(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:z.map(e=>{let t=Pt(e.kind),n=Ft(nn,e.url),i=F?Ft(F,e.url):null;return r(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[u(`button`,{type:`button`,onClick:()=>N(e),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${t} · ${et(e.timestamp)}`,children:u(rn,{url:e.url,label:t})}),r(`figcaption`,{className:`min-w-0 px-0.5`,children:[u(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:t,children:t}),u(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:et(e.timestamp),children:Ye(e.timestamp)})]}),u(jt,{localUrl:n,publicUrl:i})]},e.mediaId)})}),re,pe&&r(w,{variant:`secondary`,onClick:me,disabled:P,children:[P?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(je,{className:`h-3.5 w-3.5`}),` `,`View clip`]}),u(Gt,{deviceId:t.deviceId,trackId:t.trackId,...(E?.markForTrain??t.markForTrain)===void 0?{}:{markForTrain:E?.markForTrain??t.markForTrain},...(E?.debug??t.debug)===void 0?{}:{debug:E?.debug??t.debug},...(E?.favourited??t.favourited)===void 0?{}:{favourited:E?.favourited??t.favourited},onChange:f}),xe!==null&&r(`div`,{className:`rounded-lg border border-warning/40 bg-warning/8 px-3 py-2`,children:[u(`p`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:`Best shot`}),u(`p`,{className:`mt-0.5 text-xs text-foreground`,children:xe.sentence}),u(`code`,{className:`mt-1 block break-all font-mono text-[10px] text-foreground-subtle`,children:xe.raw})]}),r(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[u(X,{label:`Camera`,value:n}),u(X,{label:`Class`,value:t.className}),u(X,{label:`Label`,value:t.label??`—`}),u(X,{label:`Sub-label`,value:t.subLabel??`—`}),u(X,{label:`Importance`,value:K}),u(X,{label:`Zones visited`,value:_e}),u(X,{label:`Audio heard`,value:ye}),u(X,{label:`Total distance`,value:be}),u(X,{label:`First seen`,value:Se}),u(X,{label:`Last seen`,value:Ce}),u(X,{label:`Track`,value:t.trackId,mono:!0})]})]}),u(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:u(`span`,{title:i?void 0:Qt,children:r(w,{variant:`secondary`,onClick:he,disabled:!i||v.isPending,children:[v.isPending?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete track`]})})})]})})}var un={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`},dn={setRelation:`debug.gt.setRelation`,setPurity:`debug.gt.setPurity`,list:`debug.gt.list`},fn=p(`/addon/pipeline-analytics/tape-export`),pn=10*6e4;function mn(e){return`${fn}?tapeId=${encodeURIComponent(e)}`}var hn=`The server answered in a shape this build does not understand.`;function gn(e){return e instanceof Error?e.message:`The action failed.`}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function _n(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 vn(e,t){let n=e[t];return typeof n==`boolean`?n:null}function yn(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 bn(e){return e===`off`||e===`recording`||e===`refused`||e===`failing`||e===`unknown`}function xn(e){if(!Z(e))return null;let t=Q(e,`deviceId`),n=e.state,r=Q(e,`gapsSinceArmed`),i=_n(e,`segmentsHeld`),a=_n(e,`bytesLastHour`),o=_n(e,`bytesHeld`);if(t===null||!bn(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 Sn(e){return Z(e)?yn(e.cameras,xn):null}function Cn(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=vn(e,`reviewed`),f=vn(e,`released`),p=yn(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 wn(e){return Z(e)?yn(e.tapes,Cn):null}function Tn(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=vn(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 En(e){if(!Z(e))return null;let t=$(e,`tapeId`),n=Q(e,`deviceId`),r=Q(e,`fromMs`),i=Q(e,`toMs`),a=vn(e,`reviewed`),o=yn(e.lanes,Tn);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 Dn(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 On(e){if(!Z(e))return null;let t=e.status;if(t===`released`){let n=Q(e,`unpinned`),r=vn(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 kn(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 An(e){switch(e.status){case`released`:case`deleted`:return null;case`already-released`:return`This tape was already released.`;case`not-found`:return`That tape no longer exists — it may have been released or deleted elsewhere.`;case`pins-owed`:return`Refused: this tape still names pins not yet taken back. Try again shortly — the ledger settles them automatically.`;case`unavailable`:return`Unavailable on this node: ${e.reason}`}}function jn(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 Mn(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 Nn(e){if(!Z(e))return null;let t=yn(e.relations,jn),n=yn(e.purities,Mn),r=vn(e,`truncated`);return t===null||n===null||r===null?null:{relations:t,purities:n,truncated:r}}function Pn(e){if(!e.truncated)return null;let t=e.relations.length+e.purities.length;return`Showing the first ${String(t)} marks — more exist for this window.`}function Fn(e){return e.filter(e=>e.segmentsHeld===null||e.segmentsHeld>0).map(e=>({deviceId:e.deviceId,segmentsUnknown:e.segmentsHeld===null}))}function In(e){return e.slice(1).map((t,n)=>({trackId:e[n]??t,otherTrackId:t}))}function Ln(e){return e.flatMap((t,n)=>e.slice(n+1).map(e=>({trackId:t,otherTrackId:e})))}function Rn(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 zn(e){switch(e.state){case`off`:return`Off`;case`recording`:return`Recording`;case`refused`:return`Refused: ${e.reason??`unknown reason`}`;case`failing`:return`Failing: ${e.reason??`unknown reason`}`;case`unknown`:return`Unknown: ${e.reason??`unknown reason`}`}}var Bn={"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 Vn(e,t){let n=Bn[e]??`Refused (${e}).`;return t.length>0?`${n} ${t}`:n}function Hn(e){if(e.length===0)return null;let t=new Date(e).getTime();return Number.isFinite(t)?t:null}function Un(e){return e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function Wn(e){return e===null?`unknown`:Un(e)}function Gn(e){return e===null?`unknown`:String(e)}function Kn(e,t){let n=t.trim();return e===404?`This tape no longer exists on this node (unknown tape).`:e===503?n.length>0?n:`Tapes are unavailable on this node.`:e===500?n.length>0?n:`The export could not be read (the tape may have just been released or deleted).`:`Download failed (${String(e)}).`}n();function qn({cameras:e,call:t,onPromoted:n}){let[i,a]=l(``),[o,s]=l(``),[c,d]=l(``),[f,p]=l(``),[m,h]=l(``),[g,_]=l(`auto`),[v,y]=l(!1),[b,x]=l(null),S=async()=>{let r=Number.parseInt(i===``?e[0]?.value??``:i,10),a=Hn(o),s=Hn(c);if(!Number.isFinite(r)||a===null||s===null){x(`Pick a camera and both ends of the window.`);return}y(!0),x(null);try{let e=Dn(await t(un.promote,{deviceId:r,fromMs:a,toMs:s,scenario:f,...m.trim().length>0?{note:m.trim()}:{},...g===`day`||g===`ir`?{lighting:g}:{}}));e===null?x(hn):e.ok?(x(`Promoted ${e.tapeId}: ${String(e.frames)} frames, ${Un(e.bytes)}, ${String(e.pinnedTracks)} tracks pinned`+(e.state===`incomplete`?` — incomplete (it has gaps) and cannot become a case.`:`.`)),n()):x(Vn(e.reason,e.detail))}catch(e){x(gn(e))}finally{y(!1)}};return r(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`w-40`,children:u(G,{value:i,options:[...e],onChange:e=>a(e.target.value),"aria-label":`Camera`})}),u(Pe,{type:`datetime-local`,"aria-label":`From`,value:o,onChange:e=>s(e.target.value),className:`w-48`}),u(Pe,{type:`datetime-local`,"aria-label":`To`,value:c,onChange:e=>d(e.target.value),className:`w-48`}),u(Pe,{"aria-label":`Scenario`,placeholder:`615-door-groups`,value:f,onChange:e=>p(e.target.value),className:`w-44`}),u(Pe,{"aria-label":`Note`,placeholder:`optional note`,value:m,onChange:e=>h(e.target.value),className:`w-52`}),u(`div`,{className:`w-28`,children:u(G,{value:g,"aria-label":`Lighting`,options:[{value:`auto`,label:`Lighting: auto`},{value:`day`,label:`day`},{value:`ir`,label:`ir`}],onChange:e=>_(e.target.value)})}),r(w,{onClick:()=>void S(),disabled:v||e.length===0,children:[v?u(V,{className:`h-3.5 w-3.5 animate-spin`}):null,` Promote window`]}),u(`p`,{className:`w-full text-xs text-foreground-subtle`,children:`A promoted tape may be shared as a test case — keep the scenario slug and note free of names or other personal data.`}),b!==null&&u(`p`,{className:`w-full text-xs text-foreground`,children:b})]})}var Jn=`pipeline-analytics`,Yn=`debug.listTracks`,Xn=`debug.analyze`,Zn=p(`/addon/pipeline-analytics/debug-export`);function Qn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $n(e,t){let n=e[t];return typeof n==`string`?n:null}function er(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function tr(e,t){let n=e[t];return typeof n==`boolean`?n:null}function nr(e){return e===`error`||e===`warn`||e===`info`}function rr(e){if(!Qn(e))return null;let t=$n(e,`code`),n=$n(e,`detail`),r=e.severity;return t===null||n===null||!nr(r)?null:{code:t,severity:r,detail:n}}function ir(e){if(!Qn(e))return null;let t=$n(e,`trackId`),n=er(e,`deviceId`),r=$n(e,`className`),i=er(e,`firstSeen`),a=er(e,`lastSeen`),o=er(e,`durationMs`),s=tr(e,`active`);if(t===null||n===null||r===null||i===null||a===null||o===null||s===null)return null;let c=$n(e,`label`),l=$n(e,`subLabel`),u=$n(e,`previewMissReason`),d=tr(e,`markForTrain`),f=tr(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:er(e,`importance`)??0,bestEventId:$n(e,`bestEventId`)??``,...d===null?{}:{markForTrain:d},...f===null?{}:{favourited:f},debug:!0,...u===null||u.length===0?{}:{previewMissReason:u}}}function ar(e){let t=ir(e);if(t===null||!Qn(e))return null;let n=er(e,`mediaCount`),r=er(e,`eventCount`),i=er(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=rr(e);t!==null&&c.push(t)}let l=e.thumbnailProvenance;return{...t,mediaCount:n,mediaKinds:s,eventCount:r,positionCount:i,findings:c,...xt(l)?{thumbnailProvenance:l}:{}}}function or(e){if(!Qn(e))return null;let t=tr(e,`truncated`),n=e.tracks;if(t===null||!Array.isArray(n))return null;let r=[];for(let e of n){let t=ir(e);if(t===null)return null;r.push(t)}return{tracks:r,truncated:t}}function sr(e){if(!Qn(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=ar(e);if(t===null)return null;r.push(t)}return{reports:r,vanished:n.filter(e=>typeof e==`string`)}}var cr={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 lr(e){return cr[e]??e}var ur={error:0,warn:1,info:2};function dr(e){return e.toSorted((e,t)=>ur[e.severity]-ur[t.severity]||e.code.localeCompare(t.code))}function fr(e){return e.length===0?Zn:`${Zn}?deviceIds=${e.join(`,`)}`}function pr(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 mr(e,t){return`${String(e)}:${t}`}function hr(e,t){let n=[],r=new Set;for(let i of e){let e=mr(i.deviceId,i.trackId);!t.has(e)||r.has(e)||(r.add(e),n.push({deviceId:i.deviceId,trackId:i.trackId}))}return n}n();function gr({tapeId:e,call:t,onClose:n,onChanged:i}){let a=o({queryKey:[`events-debug`,`tapes`,`tracks`,e],queryFn:async()=>En(await t(un.tracks,{tapeId:e}))}),s=a.data??null,c=o({queryKey:[`events-debug`,`tapes`,`marks`,e],enabled:s!==null,queryFn:async()=>s===null?null:Nn(await t(dn.list,{deviceId:s.deviceId,since:s.fromMs-pn,until:s.toMs+pn,limit:5e3}))}),[d,f]=l([]),[p,m]=l(``),[h,g]=l(null),_=e=>f(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),v=async e=>{g(null);try{for(let[n,r]of e)await t(n,r);f([]),await c.refetch(),i()}catch(e){g(gn(e))}};if(s===null)return a.isLoading?u(`p`,{className:`text-xs`,children:`Loading the tape…`}):u(K,{message:hn});let y=s.deviceId,b=(e,t)=>v(e.map(e=>[dn.setRelation,{deviceId:y,...e,relation:t}])),x=e=>{let t=Number.parseFloat(p),n=e===`mixed`&&Number.isFinite(t)?s.fromMs+t*1e3:void 0;return v(d.map(t=>[dn.setPurity,{deviceId:y,trackId:t,purity:e,...n===void 0?{}:{switchAtMs:Math.round(n)}}]))},S=c.data==null?null:Pn(c.data);return r(`div`,{className:`space-y-2 rounded-md border border-primary/40 px-3 py-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[r(`span`,{className:`text-xs font-medium`,children:[s.tapeId,` — `,String(s.lanes.length),` tracks`]}),u(w,{disabled:d.length<2,onClick:()=>void b(In(d),`same-subject`),children:`Same subject`}),u(w,{variant:`secondary`,disabled:d.length<2,onClick:()=>void b(Ln(d),`different-subjects`),children:`Different subjects`}),u(Pe,{"aria-label":`Changed at (s from tape start)`,placeholder:`changed at s`,value:p,onChange:e=>m(e.target.value),className:`w-28`}),u(w,{variant:`secondary`,disabled:d.length!==1,onClick:()=>void x(`mixed`),children:`Mixed`}),u(w,{variant:`secondary`,disabled:d.length===0,onClick:()=>void x(`not-a-subject`),children:`Not a subject`}),u(w,{variant:s.reviewed?`secondary`:`primary`,onClick:()=>void v([[un.review,{tapeId:s.tapeId,reviewed:!s.reviewed}]]).then(()=>a.refetch()),children:s.reviewed?`Mark not reviewed`:`Mark reviewed`}),u(w,{variant:`ghost`,onClick:n,children:`Close`})]}),h!==null&&u(K,{message:h}),S!==null&&u(K,{variant:`warning`,message:S}),u(`ul`,{className:`space-y-1`,children:s.lanes.toSorted((e,t)=>e.firstT-t.firstT).map(e=>u(_r,{lane:e,marks:c.data===null||c.data===void 0?[]:Rn(e.trackId,c.data),selected:d.includes(e.trackId),onToggle:()=>_(e.trackId)},e.trackId))})]})}function _r({lane:e,marks:t,selected:n,onToggle:i}){let{src:a}=Ue(e.stillStored?We(`track`,e.trackId):void 0);return r(`li`,{className:`flex items-center gap-2 text-xs`,children:[u(`input`,{type:`checkbox`,"aria-label":`select ${e.trackId}`,checked:n,onChange:i}),a===null?u(`div`,{className:`h-10 w-10 rounded bg-surface-hover`}):u(`img`,{src:a,alt:e.trackId,className:`h-10 w-10 rounded object-cover`}),u(`span`,{className:`font-mono`,children:e.trackId}),u(`span`,{children:e.cls}),r(`span`,{className:`text-foreground-subtle`,children:[pr(e.firstT),` → `,pr(e.lastT),` · `,String(e.boundFrames),` `,`frames`]}),!e.stillStored&&u(`span`,{className:`text-foreground-subtle`,children:`not stored — marked through the tape`}),t.map(e=>u(N,{variant:`info`,children:e},e))]})}n();var vr=`camstack_admin_token`;function yr(){let e=m();return(t,n)=>e.trpcClient.addons.custom.mutate({addonId:Jn,action:t,input:n})}async function br(e,t){let n=localStorage.getItem(vr),r={};n!==null&&(r.Authorization=`Bearer ${n}`);let i=await fetch(mn(e),{headers:r});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(Kn(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 xr(){let[e,t]=l(!1);return u(_e,{expanded:e,onExpandedChange:t,header:u(`span`,{className:`text-sm font-medium text-foreground`,children:`Tracking tapes`}),children:u(Sr,{})})}function Sr(){let e=yr(),t=ee({isCamera:!0,projection:`slim`}),n=a(()=>{let e=new Map;for(let n of t.data??[])e.set(n.id,n.name);return t=>e.get(t)??`Camera ${String(t)}`},[t.data]),i=o({queryKey:[`events-debug`,`tapes`,`status`],queryFn:async()=>Sn(await e(un.status,{}))}),s=o({queryKey:[`events-debug`,`tapes`,`list`],queryFn:async()=>wn(await e(un.list,{}))}),[c,d]=l(null),[f,p]=l(null),m=async e=>{p(null);try{await br(e.id,`${e.scenario}.tape-bundle.json.gz`)}catch(e){p(gn(e))}},h=async t=>{let n=On(await e(un.release,{tapeId:t.id}));if(n===null)throw Error(hn);let r=An(n);if(r!==null)throw Error(r);await s.refetch()},g=async t=>{let n=kn(await e(un.remove,{tapeId:t.id}));if(n===null)throw Error(hn);let r=An(n);if(r!==null)throw Error(r);await s.refetch()};return r(`div`,{className:`space-y-3`,children:[r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A camera records while its `,u(`strong`,{children:`Record the track history`}),` switch (camera settings → Tracking) is on; segments are kept 24 h. Promote a window worth keeping, label it in the review, mark it reviewed, download it and turn it into a test case with`,` `,u(`code`,{children:`npm run tracking-bench -- case`}),`.`]}),f!==null&&u(K,{message:f}),i.isLoading&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading camera status…`}),i.data===null&&u(K,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[u(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[u(`th`,{children:`Camera`}),u(`th`,{children:`State`}),u(`th`,{children:`Frames/min`}),u(`th`,{children:`Last hour`}),u(`th`,{children:`Held`}),u(`th`,{children:`Gaps`})]})}),u(`tbody`,{children:(i.data??[]).map(e=>r(`tr`,{children:[u(`td`,{children:n(e.deviceId)}),u(`td`,{children:u(N,{variant:e.state===`recording`?`success`:e.state===`off`?`default`:e.state===`unknown`?`warning`:`danger`,children:zn(e)})}),u(`td`,{children:e.framesPerMin===void 0?`—`:String(Math.round(e.framesPerMin))}),u(`td`,{title:e.shelfError,children:Wn(e.bytesLastHour)}),r(`td`,{title:e.shelfError,children:[Gn(e.segmentsHeld),` seg · `,Wn(e.bytesHeld)]}),u(`td`,{children:String(e.gapsSinceArmed)})]},e.deviceId))})]}),u(qn,{cameras:Fn(i.data??[]).map(e=>({value:String(e.deviceId),label:e.segmentsUnknown?`${n(e.deviceId)} (segments unknown)`:n(e.deviceId)})),call:e,onPromoted:()=>void s.refetch()}),s.isLoading&&u(`p`,{className:`text-xs text-foreground-subtle`,children:`Loading promoted tapes…`}),s.data===null&&u(K,{message:`The server answered in a shape this build does not understand.`}),r(`table`,{className:`w-full text-xs`,children:[u(`thead`,{children:r(`tr`,{className:`text-left text-foreground-subtle`,children:[u(`th`,{children:`Scenario`}),u(`th`,{children:`Camera`}),u(`th`,{children:`Window`}),u(`th`,{children:`State`}),u(`th`,{children:`Tracks`}),u(`th`,{})]})}),u(`tbody`,{children:(s.data??[]).map(e=>r(`tr`,{children:[u(`td`,{children:e.scenario}),u(`td`,{children:n(e.deviceId)}),r(`td`,{children:[new Date(e.fromMs).toLocaleString(),` · `,pr(e.toMs-e.fromMs),` `,`· `,e.lighting]}),r(`td`,{children:[u(N,{variant:e.state===`complete`?`success`:`warning`,children:e.state}),` `,e.reviewed&&u(N,{variant:`info`,children:`reviewed`}),` `,e.released&&u(N,{children:`released`})]}),r(`td`,{children:[String(e.tracksStillStored),`/`,String(e.tracks.length),` stored`]}),r(`td`,{className:`space-x-1 text-right`,children:[u(w,{variant:`secondary`,"aria-label":`Review ${e.scenario}`,onClick:()=>d(e.id),children:`Review`}),u(w,{variant:`ghost`,"aria-label":`Download ${e.scenario}`,onClick:()=>void m(e),children:u(Ne,{className:`h-3.5 w-3.5`})}),u(E,{label:`Release`,icon:z,title:`Release ${e.scenario}?`,description:`Releasing returns this tape's pinned tracks to ordinary retention — they can be pruned from then on. The promoted bundle itself is kept until deleted.`,confirmLabel:`Release`,triggerVariant:`ghost`,confirmVariant:`danger`,disabled:e.released,action:()=>h(e)}),u(E,{label:`Delete`,icon:y,title:`Delete ${e.scenario}?`,description:`Deleting removes the promoted bundle and its index row for good. Its tracks' pins are released first — this cannot be undone.`,confirmLabel:`Delete`,triggerVariant:`ghost`,confirmVariant:`danger`,action:()=>g(e)})]})]},e.id))})]}),c!==null&&u(gr,{tapeId:c,call:e,onClose:()=>d(null),onChanged:()=>void s.refetch()})]})}n();var Cr=`all`,wr=`The server answered in a shape this build does not understand.`,Tr={error:`danger`,warn:`warning`,info:`info`};function Er({findings:e}){return e.length===0?u(N,{variant:`success`,children:`no anomaly found`}):u(`div`,{className:`flex flex-wrap gap-1`,children:dr(e).map(e=>u(N,{variant:Tr[e.severity],title:e.detail,children:lr(e.code)},e.code))})}function Dr({track:e,report:t,analyzing:n}){let i=Tt(t?.previewMissReason??e.previewMissReason);return r(`div`,{className:`space-y-1 border-t border-border pt-1.5`,children:[t===void 0?u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n?`analysing…`:`not analysed`}):r(s,{children:[u(Er,{findings:t.findings}),r(`p`,{className:`text-[10px] text-foreground-subtle`,title:t.mediaKinds.length>0?t.mediaKinds.join(`, `):`no media of any kind`,children:[String(t.mediaCount),` media · `,String(t.eventCount),` events ·`,` `,String(t.positionCount),` positions`]})]}),i!==null&&u(`p`,{className:`text-[10px] text-foreground-subtle`,title:i.raw,children:i.sentence})]})}function Or(){let e=m(),[t,n]=l(Cr),[i,s]=l(!1),[c,d]=l(null),[f,p]=l(new Set),[h,g]=l(null),[_,v]=l(null),[y,b]=l(null),[x,S]=l([]),C=Ht(),T=ee({isCamera:!0,projection:`slim`}),E=a(()=>[{value:Cr,label:`All cameras`},...(T.data??[]).map(e=>({value:String(e.id),label:e.name}))],[T.data]),O=a(()=>{let e=new Map;for(let t of T.data??[])e.set(t.id,t.name);return e},[T.data]),k=e=>O.get(e)??`Camera ${String(e)}`,j=a(()=>t===Cr?[]:[Number.parseInt(t,10)],[t]),M=o({queryKey:[`events-debug`,`list`,j],queryFn:async()=>or(await e.trpcClient.addons.custom.mutate({addonId:Jn,action:Yn,input:j.length===0?{}:{deviceIds:j}}))}),N=a(()=>(M.data?.tracks??[]).map(e=>e.trackId),[M.data]),P=o({queryKey:[`events-debug`,`analyze`,N],enabled:N.length>0,queryFn:async()=>sr(await e.trpcClient.addons.custom.mutate({addonId:Jn,action:Xn,input:{trackIds:N}}))}),te=a(()=>{let e=new Map;for(let t of P.data?.reports??[])e.set(t.trackId,t);return e},[P.data]),F=M.data?.tracks??[],ne=M.data===null||P.data===null,re=()=>{M.refetch(),P.refetch()},ie=e=>{p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},I=()=>{p(new Set(F.map(e=>mr(e.deviceId,e.trackId))))},L=()=>p(new Set),R=async(e,t)=>{let n=e===`analyzed`?{debug:!1}:{favourited:!0},r=0,i=[];for(let e of t)try{await C.mutateAsync({deviceId:e.deviceId,trackId:e.trackId,flags:n}),r+=1}catch{i.push(e.trackId)}return{applied:r,refused:i}},z=e=>{if(!q||_!==null)return;let t=hr(F,f);t.length!==0&&(v(e),b(null),(async()=>{let n=await R(e,t);v(null);let r=new Set(n.refused);p(new Set(t.filter(e=>r.has(e.trackId)).map(e=>mr(e.deviceId,e.trackId)))),e===`analyzed`&&S(t.filter(e=>!r.has(e.trackId))),n.refused.length>0&&b(`${String(n.refused.length)} of ${String(t.length)} were refused by the server and are still selected. Check the hub log.`),M.refetch()})())},B=()=>{let e=x;e.length===0||_!==null||(v(`analyzed`),b(null),(async()=>{for(let t of e)try{await C.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,flags:{debug:!0}})}catch{b(`Some tracks could not be re-marked. Refresh and try again.`)}v(null),S([]),M.refetch()})())},ae=async()=>{s(!0),d(null);try{await Ke(fr(j),`camstack-debug.zip`)}catch(e){d(e instanceof Error?e.message:`Export failed.`)}finally{s(!1)}},oe=_!==null;return u(He,{children:r(`section`,{className:`space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(`div`,{className:`w-44`,children:u(G,{value:t,options:E,onChange:e=>n(e.target.value)})}),r(w,{variant:`secondary`,onClick:re,disabled:M.isFetching,children:[M.isFetching?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(ke,{className:`h-3.5 w-3.5`}),`Refresh`]}),r(w,{onClick:()=>void ae(),disabled:i||F.length===0,children:[i?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(Ne,{className:`h-3.5 w-3.5`}),`Export all (`,String(F.length),`)`]}),F.length>0&&f.size<F.length&&u(w,{variant:`ghost`,onClick:I,children:`Select all`})]}),r(`p`,{className:`text-xs text-foreground-subtle`,children:[`A `,u(`code`,{children:`debug`}),` mark does not pin retention — this lists the marked tracks that still exist. A track whose media was evicted shows as missing media. Use `,u(`strong`,{children:`Keep`}),` `,`to hold a selection against pruning while you investigate, and `,u(`strong`,{children:`Analyzed`}),` `,`to un-mark the ones you are finished with.`]}),u(xr,{}),M.isError&&u(K,{message:`Could not load the marked tracks.`}),ne&&!M.isError&&u(K,{message:wr}),c!==null&&u(K,{message:c}),y!==null&&u(K,{message:y}),M.data?.truncated===!0&&u(K,{message:`A camera filled the per-camera cap — some marked tracks are not listed. Un-mark a few, or filter to one camera.`}),(P.data?.vanished.length??0)>0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:[String(P.data?.vanished.length),` marked track(s) were evicted between the list and the analysis.`]}),f.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[String(f.size),` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[u(`span`,{title:q?void 0:`Track flags arrive with the next server update`,children:r(w,{variant:`secondary`,onClick:()=>z(`keep`),disabled:!q||oe,children:[_===`keep`?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(A,{className:`h-3.5 w-3.5`}),` `,`Keep`]})}),u(`span`,{title:q?void 0:`Track flags arrive with the next server update`,children:r(w,{onClick:()=>z(`analyzed`),disabled:!q||oe,children:[_===`analyzed`?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(Ie,{className:`h-3.5 w-3.5`}),` `,`Analyzed`]})}),u(w,{variant:`ghost`,onClick:L,disabled:oe,children:u(ce,{className:`h-3.5 w-3.5`})})]})]}),x.length>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border bg-surface px-3 py-2`,children:[r(`span`,{className:`text-xs text-foreground`,children:[String(x.length),` track(s) marked analyzed and removed from this list.`]}),r(w,{variant:`ghost`,onClick:B,disabled:oe,children:[u(D,{className:`h-3.5 w-3.5`}),` Undo`]}),u(w,{variant:`ghost`,onClick:()=>S([]),disabled:oe,children:u(ce,{className:`h-3.5 w-3.5`})})]}),M.isLoading?u(he,{children:u(`div`,{className:`px-3 py-6 text-center text-xs text-foreground-subtle`,children:`Loading…`})}):F.length===0?u(he,{children:r(`div`,{className:`flex flex-col items-center gap-2 px-3 py-8 text-center`,children:[u(W,{className:`h-5 w-5 text-foreground-subtle`}),u(`p`,{className:`text-xs text-foreground-subtle`,children:`No track is marked for debug. Mark one from a track's actions to see it here.`})]})}):u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:F.map(e=>{let t=te.get(e.trackId);return u(Dt,{row:e,cameraName:k(e.deviceId),nowMs:e.lastSeen,selected:f.has(mr(e.deviceId,e.trackId)),onToggleSelect:ie,onOpenDetail:g,...t?.thumbnailProvenance===void 0?{}:{provenance:t.thumbnailProvenance},footer:u(Dr,{track:e,report:t,analyzing:P.isFetching})},mr(e.deviceId,e.trackId))})}),h&&u(ln,{row:h,cameraName:k(h.deviceId),deleteAvailable:Zt,onClose:()=>g(null),onDeleted:()=>{g(null),M.refetch()},onFlagsChanged:e=>{e.debug||(g(null),M.refetch())}})]})})}var kr=200,Ar=3e4,jr=[];function Mr(e){let t=m(),n=e.deviceIds.length>0,r=[...e.deviceIds].sort((e,t)=>e-t),{data:i,isLoading:a}=o({queryKey:[`events-feed`,r,e.since,e.until,e.minImportance??null,e.classFilter??null],enabled:n,staleTime:Ar,refetchInterval:Ar,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEventsBatch.query({deviceIds:r,since:e.since,until:e.until,limit:kr,...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:ht(mt(i??jr),`importance`),isLoading:n&&a}}n();var Nr=[`events-feed`],Pr=2e3;function Fr(n){let r=c(),i=n?.paused===!0,a=t(r);a.current=r;let o=t(i);o.current=i;let[s,u]=l(!1),f=e(()=>{a.current.invalidateQueries({queryKey:Nr})},[]),p=t(void 0);p.current||=rt({delayMs:Pr,invalidate:()=>{o.current?u(!0):f()}}),d(()=>()=>p.current?.cancel(),[]),d(()=>{i||!s||(u(!1),f())},[i,s,f]);let m=e(()=>{u(!1),f()},[f]);return Le(ze.PipelineAnalyticsDetectionEvent,()=>{p.current?.trigger()}),Le(ze.PipelineAnalyticsTrackEnded,()=>{p.current?.trigger()}),{pending:s,refreshNow:m}}n();function Ir({groups:e,selected:t,onChange:n,loading:i=!1}){let{t:o}=Ve(),[s,c]=l(!1),[d,f]=l(``),[p,m]=l(new Set),h=d.trim().toLowerCase(),g=e=>h.length===0||S(e,o).toLowerCase().includes(h),y=a(()=>e.map(e=>({macro:e.macro,subs:e.subs.filter(t=>g(t)||g(e.macro))})).filter(e=>g(e.macro)||e.subs.length>0),[e,h]),b=e=>m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),x=e=>{let r=new Set(t),i=t.has(e.macro.kind)&&e.subs.every(e=>t.has(e.kind)),a=[e.macro.kind,...e.subs.map(e=>e.kind)];if(i)for(let e of a)r.delete(e);else for(let e of a)r.add(e);n(r)},C=e=>{let r=new Set(t);r.has(e)?r.delete(e):r.add(e),n(r)},w=()=>n(new Set),T=t.size;return r(`div`,{className:`relative`,children:[r(`button`,{type:`button`,onClick:()=>c(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${T>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[u(M,{className:`h-3.5 w-3.5`}),T>0?`Kinds (${String(T)})`:`Kinds`,u(_,{className:`h-3 w-3`})]}),s&&r(`div`,{className:`absolute z-20 mt-1 max-h-80 w-64 overflow-auto rounded-md border border-border bg-surface p-2 shadow-lg`,children:[r(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[u(De,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`input`,{type:`text`,value:d,onChange:e=>f(e.target.value),placeholder:`Search kinds…`,className:`w-full bg-transparent py-1 text-xs outline-none`}),T>0&&u(`button`,{type:`button`,onClick:w,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:`Clear`})]}),y.length===0&&u(`div`,{className:`px-1 py-2 text-[11px] text-foreground-subtle`,children:i?`Loading kinds…`:h.length>0?`No kind matches that search.`:`These cameras advertise no event kinds.`}),y.map(e=>{let n=ue(e.macro.iconId),i=p.has(e.macro.kind)||h.length>0,a=t.has(e.macro.kind);return r(`div`,{className:`mb-0.5`,children:[r(`div`,{className:`flex items-center gap-1`,children:[e.subs.length>0?u(`button`,{type:`button`,onClick:()=>b(e.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Expand`,children:u(i?_:v,{className:`h-3 w-3`})}):u(`span`,{className:`w-3`}),r(`label`,{className:`flex flex-1 cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[u(`input`,{type:`checkbox`,checked:a,onChange:()=>x(e),className:`accent-primary`}),u(n,{className:`h-3.5 w-3.5`,style:{color:e.macro.color}}),u(`span`,{className:`font-medium`,children:S(e.macro,o)})]})]}),i&&e.subs.map(e=>{let n=ue(e.iconId);return r(`label`,{className:`ml-5 flex cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[u(`input`,{type:`checkbox`,checked:t.has(e.kind),onChange:()=>C(e.kind),className:`accent-primary`}),u(n,{className:`h-3.5 w-3.5`,style:{color:e.color}}),u(`span`,{children:S(e,o)})]},e.kind)})]},e.macro.kind)})]})]})}function Lr(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 Rr(e,t){return{...t,kind:e,labelKey:`eventKind.${e}`,label:e.charAt(0).toUpperCase()+e.slice(1),iconId:e,parentKind:null,level:`macro`}}var zr=new Set([`detection`,`package`]);function Br(e,t){return[...Lr(e,t).values()].filter(e=>e.parentKind===null&&zr.has(e.category)).sort((e,t)=>e.label.localeCompare(t.label))}function Vr(e,t){let n=Lr(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,Rr(e,n))}return[...i.values()].map(e=>({macro:e,subs:[...r.get(e.kind)??[]].sort((e,t)=>e.label.localeCompare(t.label))})).sort((e,t)=>e.macro.label.localeCompare(t.macro.label))}n();function Hr(){let[n,r]=l(!1),i=t(null),[a,o]=l(0),s=e(e=>{i.current!==e&&(i.current=e,o(e=>e+1))},[]);return d(()=>{let e=i.current;if(!e||typeof IntersectionObserver>`u`){r(!1);return}let t=new IntersectionObserver(e=>{let t=e[e.length-1];t&&r(!t.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return t.observe(e),()=>t.disconnect()},[a]),{ref:s,scrolledPast:n}}n();var Ur=[`events-feed`],Wr=60,Gr=[{value:`importance`,label:`Importance`,icon:st},{value:`time`,label:`Recent`,icon:Se}];function Kr(){let e=c(),t=B(),n=oe(),[i,o]=l(nt),[f,p]=l(new Set),[m,h]=l(new Set),[g,_]=l(0),[v,b]=l(`time`),[x,S]=l(new Set),[C,T]=l(null),[E,D]=l(()=>Date.now());d(()=>{let e=setInterval(()=>D(Date.now()),6e4);return()=>clearInterval(e)},[]);let{since:O,until:k}=a(()=>yt({fromMs:i.fromMs,toMs:i.toMs},E),[i.fromMs,i.toMs,E]),A=Hr(),{pending:j,refreshNow:M}=Fr({paused:C!==null||x.size>0||A.scrolledPast}),{data:N=[]}=ee({isCamera:!0,projection:`slim`}),P=a(()=>N.map(e=>e.id),[N]),{data:te,isLoading:F}=L({deviceIds:P},{enabled:P.length>0,staleTime:5*6e4}),ne=a(()=>Vr(te??[],f),[te,f]),re=en(),ie=re.isPending,{rows:I,isLoading:R}=Mr({deviceIds:P,since:O,until:k,minImportance:g>0?g:void 0,classFilter:m.size===1?[...m][0]:void 0}),z=a(()=>{let e=new Map;for(let t of N??[])e.set(t.id,t.name);return e},[N]),ae=e=>z.get(e)??`Camera #${String(e)}`,se=a(()=>Je(I).map(e=>({id:e,name:ae(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[I,z]),H=a(()=>ht(gt(I,{cameras:f,classes:m,minImportance:g}),v),[I,f,m,g,v]),U=$e(H,Wr,a(()=>JSON.stringify([[...f].sort((e,t)=>e-t),[...m].sort(),g,v,O,k]),[f,m,g,v,O,k])),W=()=>{e.invalidateQueries({queryKey:Ur})},G=()=>S(new Set);function le(e){S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function ue(){if(x.size===0||!Zt)return;let e=vt(I,x),t=[...e.values()].reduce((e,t)=>e+t.length,0);t!==0&&(async()=>{await n({title:`Delete ${String(t)} track${t===1?``:`s`}`,message:`Delete ${String(t)} track${t===1?``:`s`} and every image and clip captured for ${t===1?`it`:`them`}? This cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&de(e)})()}function de(e){let n=[...e];Promise.allSettled(n.map(([e,t])=>re.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{W();let r=[],i=new Set;e.forEach((e,t)=>{let a=n[t];if(!a)return;let[o,s]=a;if(e.status===`fulfilled`)for(let e of s)i.add(_t(o,e));else r.push(o)}),S(e=>{let t=new Set(e);for(let e of i)t.delete(e);return t}),r.length>0&&t({title:`Some tracks were not deleted`,message:`Failed to delete tracks on: ${r.map(e=>ae(e)).join(`, `)}. They remain selected — retry, or check the server logs.`,variant:`danger`})})}let fe=H.length!==I.length;return r(`div`,{className:`relative space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(tt,{onChange:o}),u(Ze,{cameras:se,selected:f,onChange:p}),u(Ir,{groups:ne,selected:m,onChange:h,loading:F}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(`span`,{children:`Min score`}),u(`input`,{type:`range`,min:0,max:1,step:.05,value:g,onChange:e=>_(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":`Minimum importance`}),u(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(g*100)})]}),u(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Gr.map(e=>{let t=e.icon;return r(`button`,{type:`button`,onClick:()=>b(e.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${v===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[u(t,{className:`h-3.5 w-3.5`}),` `,e.label]},e.value)})}),!R&&u(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:fe?`${String(H.length)} of ${String(I.length)} events`:`${String(H.length)} event${H.length===1?``:`s`}`})]}),x.size>0&&r(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[r(`span`,{className:`text-xs font-medium text-foreground`,children:[x.size,` selected`]}),r(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[u(`span`,{title:Zt?void 0:`Track deletion arrives with the next server update`,children:r(w,{variant:`secondary`,onClick:ue,disabled:!Zt||ie,children:[ie?u(V,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),u(w,{variant:`ghost`,onClick:G,disabled:ie,children:u(ce,{className:`h-3.5 w-3.5`})})]})]}),R&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(V,{className:`h-4 w-4 animate-spin`}),` Loading events…`]}),!R&&H.length===0&&u(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:`No key events in this window.`}),j&&u(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:u(`button`,{type:`button`,onClick:M,className:`rounded-full border border-primary/40 bg-surface px-3 py-1 text-[11px] font-medium text-primary shadow-sm hover:bg-primary/10`,children:`New events — refresh`})}),!R&&H.length>0&&r(s,{children:[u(`div`,{ref:A.ref,"aria-hidden":!0,className:`h-0`}),u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:U.pageItems.map(e=>u(Dt,{row:e,cameraName:ae(e.deviceId),nowMs:E,selected:x.has(_t(e.deviceId,e.trackId)),onToggleSelect:le,onOpenDetail:T},_t(e.deviceId,e.trackId)))}),u(qe,{currentPage:U.page,totalItems:U.totalItems,pageSize:U.pageSize,onPageChange:U.setPage,itemNoun:`events`})]}),C&&u(ln,{row:C,cameraName:ae(C.deviceId),deleteAvailable:Zt,onClose:()=>T(null),onDeleted:()=>{W(),T(null)},onFlagsChanged:e=>{T(t=>t&&t.trackId===e.trackId?{...t,markForTrain:e.markForTrain,debug:e.debug,favourited:e.favourited}:t)}})]})}n();var qr=50,Jr=350,Yr=[{value:`loose`,label:`Loose`,title:`The search model's own floor`},{value:`balanced`,label:`Balanced`,title:`1.25× the search model's floor`},{value:`strict`,label:`Strict`,title:`1.5× the search model's floor`}];function Xr(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 Zr({onActiveChange:e}){let[t,n]=l(``),[i,o]=l(`loose`),[s,c]=l(null),[f,p]=l(null),[m,h]=l(null),g=H(t,Jr).trim(),_=g.length>0;d(()=>{e(_)},[_,e]);let[v,y]=l(()=>Date.now());d(()=>{let e=setInterval(()=>y(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:b=[]}=ee({isCamera:!0,projection:`slim`}),x=a(()=>{let e=new Map;for(let t of b)e.set(t.id,t.name);return e},[b]),C=e=>x.get(e)??`Camera #${String(e)}`,w=a(()=>b.map(e=>e.id),[b]),{data:T}=L({deviceIds:w},{enabled:w.length>0,staleTime:5*6e4}),E=a(()=>Br(T??[],new Set(f===null?[]:[f])),[T,f]);d(()=>{s!==null&&(E.some(e=>e.kind===s)||c(null))},[E,s]);let{data:D,isFetching:O,isError:k,error:A}=Ae({text:g,strictness:i,limit:qr,classFilter:s??void 0,deviceId:f??void 0},{enabled:_}),j=a(()=>[...D??[]].sort((e,t)=>t.score-e.score).map(e=>({...Xr(e),score:e.score})),[D]);function M(e){c(t=>t===e?null:e)}return r(`div`,{className:`space-y-3`,children:[r(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`div`,{className:`relative min-w-[16rem] flex-1`,children:[u(De,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),u(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Semantic search — describe what you're looking for…`,className:`h-9 w-full rounded-md border border-border bg-background pl-8 pr-8 text-sm text-foreground placeholder:text-foreground-subtle focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":`Semantic event search`}),t&&u(`button`,{type:`button`,onClick:()=>n(``),className:`absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Clear search`,children:u(ce,{className:`h-3.5 w-3.5`})})]}),O&&_&&u(V,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),r(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[u(`div`,{className:`flex items-center gap-1`,children:E.map(e=>u(`button`,{type:`button`,onClick:()=>M(e.kind),className:`rounded-md px-2.5 py-1 text-xs transition-colors ${s===e.kind?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:S(e)},e.kind))}),r(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(`span`,{children:`Camera`}),r(`select`,{value:f===null?``:String(f),onChange:e=>p(e.target.value===``?null:Number(e.target.value)),className:`h-7 rounded-md border border-border bg-background px-1.5 text-xs text-foreground focus:border-primary focus:outline-none`,"aria-label":`Filter by camera`,children:[u(`option`,{value:``,children:`All`}),b.map(e=>u(`option`,{value:String(e.id),children:e.name},e.id))]})]}),r(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(`span`,{children:`Match`}),u(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:Yr.map(e=>u(`button`,{type:`button`,onClick:()=>o(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${i===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:e.title,children:e.label},e.value))})]}),_&&!O&&!k&&r(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[j.length,` match`,j.length===1?``:`es`]})]})]}),_&&r(`div`,{className:`space-y-3`,children:[k&&r(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,A instanceof Error?A.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!k&&O&&j.length===0&&r(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[u(V,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!k&&!O&&j.length===0&&r(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:[`No semantic matches for “`,g,`”. Try a looser match threshold or a different phrasing.`]}),!k&&j.length>0&&u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:j.map(e=>u(Dt,{row:e,cameraName:C(e.deviceId),nowMs:v,score:e.score,onOpenDetail:h},e.id))})]}),m&&u(ln,{row:m,cameraName:C(m.deviceId),deleteAvailable:Zt,onClose:()=>h(null),onDeleted:()=>h(null)})]})}n();function Qr(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return`just now`;if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function $r({row:e,cameraName:t,nowMs:n}){let i=Ue(e.keyFrameMediaId===void 0?void 0:Ge(e.keyFrameMediaId));return r(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[r(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[i.src?u(`img`,{src:i.src,alt:`Parked ${e.className} on ${t}`,className:`h-full w-full object-cover`}):u(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:u(dt,{className:`h-6 w-6`})}),u(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium capitalize text-white`,children:e.label??e.className})]}),r(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[u(`span`,{className:`truncate text-[11px] text-foreground`,children:t}),r(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`parked `,Qr(n,e.becameStationaryAt)]})]})]})}function ei(){let[e,t]=l(!1),n=Date.now(),{data:i=[]}=ee({isCamera:!0,projection:`slim`}),o=a(()=>i.map(e=>e.id),[i]),s=a(()=>{let e=new Map;for(let t of i)e.set(t.id,t.name);return e},[i]),{rows:c,unreadableCount:d}=it(o);return c.length===0&&d===0?null:r(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[r(`button`,{type:`button`,onClick:()=>t(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[u(e?_:v,{className:`h-4 w-4 text-foreground-subtle`}),u(dt,{className:`h-4 w-4 text-foreground-subtle`}),u(`span`,{className:`text-sm font-semibold text-foreground`,children:`Stationary`}),u(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:c.length}),u(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:`Parked objects — kept out of the event feed`}),d>0?r(`span`,{className:`ml-2 text-[11px] text-warning`,children:[d,` camera`,d===1?``:`s`,` could not be read`]}):null]}),e&&u(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:c.map(e=>u($r,{row:e,cameraName:s.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:n},e.id))})]})}n();function ti(){let[e,t]=l(!1);return u(He,{children:r(`section`,{className:`space-y-3`,children:[u(Zr,{onActiveChange:t}),!e&&u(ei,{}),!e&&u(Kr,{})]})})}var ni=[`person`,`vehicle`,`animal`,`package`,`face`,`plate`],ri=new Set(ni);function ii(e){let t=e?.trim().toLowerCase();return t===void 0||t===``?null:ri.has(t)?`"${t}" is a macro class, not a label — person / postman / Marco are three different tiers`:null}function ai({annotations:e,selectedIndex:t,onSelect:n,onChange:i,onDelete:a}){return e.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle p-3`,children:[`No subject on this frame yet. Drag on the image to draw one, or ask the pipeline for a proposal. Annotate `,u(`strong`,{children:`every`}),` subject — a frame with one box and three unlabelled people teaches the model that two thirds of the people in it are background.`]}):u(`ul`,{className:`divide-y divide-border`,children:e.map((e,o)=>{let s=o===t,c=ii(e.label),l=ii(e.subLabel);return r(`li`,{className:`p-2.5 space-y-1.5 ${s?`bg-surface-hover`:``}`,onFocus:()=>{n(o)},children:[r(`div`,{className:`flex items-center gap-2`,children:[u(G,{className:`w-28`,value:e.macroClass,options:ni.map(e=>({value:e,label:e})),onChange:e=>{let t=ni.find(t=>t===e.target.value);t!==void 0&&i(o,{macroClass:t})}}),u(G,{className:`w-32`,value:e.kind,options:[{value:`subject`,label:`subject`},{value:`model_error`,label:`model error`}],onChange:e=>{i(o,{kind:e.target.value===`model_error`?`model_error`:`subject`})}}),e.source===`assist`&&r(N,{variant:`info`,children:[e.assistModelId??`assist`,e.assistScore===void 0?``:` ${e.assistScore.toFixed(2)}`]}),u(w,{variant:`ghost`,size:`sm`,"aria-label":`Delete this subject`,onClick:()=>{a(o)},children:u(y,{className:`h-3 w-3`})})]}),r(`div`,{className:`flex items-center gap-2`,children:[u(Pe,{className:`flex-1`,placeholder:`label (postman, van, cat…)`,value:e.label??``,onChange:e=>{i(o,{label:e.target.value})}}),u(Pe,{className:`flex-1`,placeholder:`sub-label (a name, a plate…)`,value:e.subLabel??``,onChange:e=>{i(o,{subLabel:e.target.value})}})]}),c!==null&&u(`p`,{className:`text-[11px] text-danger`,children:c}),l!==null&&u(`p`,{className:`text-[11px] text-danger`,children:l})]},`${String(o)}-${String(e.bbox.x)}`)})})}function oi(e){return e.every(e=>ii(e.label)===null&&ii(e.subLabel)===null&&ri.has(e.macroClass))}function si(e){return e<0?0:e>1?1:e}function ci(e,t,n,r){if(!(e>0)||!(t>0)||!(n>0)||!(r>0))return null;let i=Math.min(e/n,t/r),a=n*i,o=r*i;return{left:(e-a)/2,top:(t-o)/2,width:a,height:o}}function li(e,t,n){return{x:si((e-n.left)/n.width),y:si((t-n.top)/n.height)}}function ui(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),w:Math.abs(t.x-e.x),h:Math.abs(t.y-e.y)}}function di(e){return e.w>=.01&&e.h>=.01}function fi(e,t){return{left:t.left+e.x*t.width,top:t.top+e.y*t.height,width:e.w*t.width,height:e.h*t.height}}function pi(e,t){let n=-1,r=1/0;return e.forEach((e,i)=>{if(!(t.x>=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h))return;let a=e.w*e.h;a<r&&(n=i,r=a)}),n}n();function mi({imageSrc:n,imageWidth:a,imageHeight:o,boxes:s,selectedIndex:c,onSelect:d,onDraw:f}){let p=t(null),[m,h]=l({w:0,h:0}),[g,_]=l(null);i(()=>{let e=p.current;if(e===null)return;let t=new ResizeObserver(()=>{h({w:e.clientWidth,h:e.clientHeight})});return t.observe(e),h({w:e.clientWidth,h:e.clientHeight}),()=>{t.disconnect()}},[]);let v=ci(m.w,m.h,a,o),y=e(e=>{let t=p.current;if(t===null||v===null)return null;let n=t.getBoundingClientRect();return li(e.clientX-n.left,e.clientY-n.top,v)},[v]);return r(`div`,{ref:p,className:`relative w-full h-full min-h-[280px] bg-surface-sunken select-none touch-none`,onPointerDown:e=>{let t=y(e);t!==null&&(e.currentTarget.setPointerCapture(e.pointerId),_({start:t,current:ui(t,t)}))},onPointerMove:e=>{if(g===null)return;let t=y(e);t!==null&&_({start:g.start,current:ui(g.start,t)})},onPointerUp:()=>{if(g===null)return;let e=g.current;_(null),di(e)?f(e):d(pi(s.map(e=>e.bbox),g.start))},children:[u(`img`,{src:n,alt:`Frame being annotated`,className:`absolute inset-0 w-full h-full object-contain pointer-events-none`}),v!==null&&s.map((e,t)=>{let n=fi(e.bbox,v),i=e.kind===`model_error`,a=t===c,o=i?`#ef4444`:a?`#22c55e`:`#3b82f6`;return u(`div`,{className:`absolute pointer-events-none`,style:{left:n.left,top:n.top,width:n.width,height:n.height,border:`${a?`2px`:`1px`} ${i?`dashed`:`solid`} ${o}`,opacity:e.source===`assist`&&!a?.65:1},children:r(`span`,{className:`absolute -top-4 left-0 text-[10px] px-1 rounded`,style:{background:o,color:`#08121f`},children:[e.label??e.macroClass,i?` ✕`:``]})},`${String(t)}-${String(e.bbox.x)}-${String(e.bbox.y)}`)}),g!==null&&v!==null&&u(`div`,{className:`absolute border border-dashed border-primary pointer-events-none`,style:fi(g.current,v)})]})}n();function hi(){let e=k({}),t=R({}),n=te({}),[i,a]=l(null),[o,s]=l(null),c=async(e,t,n)=>{a(e),s(null);try{await Ke(p(t),n)}catch(e){s(e instanceof Error?e.message:String(e))}finally{a(null)}},d=e.data,f=d!==void 0&&d.trackCount===0;return r(`div`,{className:`rounded-md border border-border bg-surface p-3 space-y-2`,children:[r(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground flex-1`,children:`Export dataset`}),r(w,{variant:`secondary`,size:`sm`,disabled:t.data===void 0||i!==null,onClick:()=>{t.data!==void 0&&c(`annotated`,t.data.url,`camstack-retrain-export.tar`)},children:[i===`annotated`?u(V,{className:`h-3 w-3 animate-spin`}):u(Ne,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Annotated dataset`})]}),r(w,{variant:`secondary`,size:`sm`,disabled:n.data===void 0||f||i!==null,onClick:()=>{n.data!==void 0&&c(`marked`,n.data.url,`camstack-training-export.tar`)},children:[i===`marked`?u(V,{className:`h-3 w-3 animate-spin`}):u(Ne,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Marked media`})]})]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.isError?`The export summary could not be read, so the size of the marked set is unknown — not zero.`:d===void 0?`Measuring the marked set…`:f?`No track is marked for training: the marked-media archive would be empty. The annotated dataset can still hold frames from tracks already completed — this count does not measure those.`:`${String(d.trackCount)} marked track${d.trackCount===1?``:`s`} · ${String(d.fileCount)} file${d.fileCount===1?``:`s`} · ${ot(d.byteCount)}${d.truncated?` · more marked tracks exist than one pass carries`:``}`}),(t.isError||n.isError)&&u(`p`,{className:`text-[11px] text-danger`,children:`An export data plane is not available on the node that answered — no archive can be streamed from here.`}),o!==null&&r(`p`,{className:`text-[11px] text-danger`,children:[`Download failed: `,o]})]})}function gi(e){return e>=1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.round(e/1e3)} KB`}function _i({candidates:e,copies:t,activeFrameId:n,refusals:i,isSelecting:a,onSelectCandidate:o,onOpenCopy:s,onRemoveCopy:c}){let l=new Set(t.map(e=>e.sourceMediaId)),d=e.filter(e=>!l.has(e.mediaId));return r(`div`,{className:`space-y-3`,children:[r(`section`,{children:[r(`h3`,{className:`text-xs font-semibold text-foreground mb-1.5`,children:[`In the dataset (`,t.length,`)`]}),t.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No frame copied yet. Selecting a frame copies it into retrain storage immediately — the dataset stops depending on the track's own media from that moment.`}):u(`ul`,{className:`flex flex-wrap gap-2`,children:t.map(e=>u(`li`,{children:r(`div`,{className:`rounded-md border px-2 py-1.5 text-[11px] ${e.frameId===n?`border-primary bg-surface-hover`:`border-border`}`,children:[r(`button`,{type:`button`,className:`flex items-center gap-1.5 text-left`,onClick:()=>{s(e.frameId)},children:[u(Ie,{className:`h-3 w-3 text-success`}),u(`span`,{className:`font-medium text-foreground`,children:e.sourceKind}),r(`span`,{className:`text-foreground-subtle`,children:[e.width,`×`,e.height,` · `,gi(e.sizeBytes)]})]}),r(`button`,{type:`button`,"aria-label":`Remove this frame from the dataset`,className:`mt-1 flex items-center gap-1 text-foreground-muted hover:text-danger`,onClick:()=>{c(e.frameId)},children:[u(y,{className:`h-3 w-3`}),`remove`]})]})},e.frameId))})]}),r(`section`,{children:[r(`h3`,{className:`text-xs font-semibold text-foreground mb-1.5`,children:[`Available frames (`,d.length,`)`]}),d.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.length===0?`This track has no whole, unannotated frame left — its media aged out before it was marked. Anything already copied above is still usable.`:`Every available frame is already in the dataset.`}):u(`ul`,{className:`flex flex-wrap gap-2`,children:d.map(e=>{let t=i.get(e.mediaId);return r(`li`,{children:[r(w,{variant:`secondary`,size:`sm`,disabled:a||t!==void 0,onClick:()=>{o(e.mediaId)},children:[a?u(V,{className:`h-3 w-3 animate-spin`}):u(t===void 0?Ee:g,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:e.kind}),u(`span`,{className:`ml-1 text-foreground-subtle`,children:gi(e.sizeBytes)})]}),t!==void 0&&u(N,{variant:`danger`,className:`ml-1`,children:t})]},e.mediaId)})})]})]})}function vi(e){return e.frameCount===0?`untouched`:e.annotationCount===0?`started`:`ready`}var yi={untouched:{icon:lt,label:`to do`,variant:`default`},started:{icon:ct,label:`frames only`,variant:`info`},ready:{icon:we,label:`annotated`,variant:`success`}};function bi(e){return new Date(e).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}function xi({tracks:e,isLoading:t,selectedTrackId:n,deviceNames:i,onSelect:a}){return t?r(`div`,{className:`flex items-center gap-2 p-4 text-xs text-foreground-subtle`,children:[u(V,{className:`h-3.5 w-3.5 animate-spin`}),`Loading staging tracks…`]}):e.length===0?u(`div`,{className:`p-4 text-xs text-foreground-subtle`,children:`Nothing in staging. Mark a track for training from the viewer or the Events grid and it appears here.`}):u(`ul`,{className:`divide-y divide-border`,children:e.map(e=>{let t=yi[vi(e)],o=t.icon;return u(`li`,{children:r(`button`,{type:`button`,onClick:()=>{a(e)},className:`w-full text-left px-3 py-2 flex items-start gap-2 hover:bg-surface-hover ${e.trackId===n?`bg-surface-hover`:``}`,children:[u(o,{className:`h-3.5 w-3.5 mt-0.5 shrink-0 text-foreground-subtle`}),r(`span`,{className:`min-w-0 flex-1`,children:[r(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-xs font-medium text-foreground truncate`,children:e.label??e.className}),u(N,{variant:t.variant,children:t.label})]}),r(`span`,{className:`block text-[11px] text-foreground-subtle truncate`,children:[i.get(e.deviceId)??`Camera ${String(e.deviceId)}`,` ·`,` `,bi(e.lastSeen)]}),r(`span`,{className:`block text-[11px] text-foreground-muted`,children:[e.frameCount,` frame`,e.frameCount===1?``:`s`,` ·`,` `,e.annotationCount,` subject`,e.annotationCount===1?``:`s`]})]})]})},e.trackId)})})}var Si=`object-detection`;function Ci(e,t){for(let n of e){if(n.addonId===t)return n;let e=n.children===void 0?void 0:Ci(n.children,t);if(e!==void 0)return e}}function wi(e,t){for(let n of e.slots){let e=n.addons.find(e=>e.id===t);if(e!==void 0)return e}}function Ti(e){let{status:t,nodeDevices:n,schema:r,resolvedSteps:i}=e;if(t===void 0)return{kind:`unknown`,gap:`pending`};if(t.detection===null)return{kind:`unknown`,gap:t.degraded.some(e=>e.stage===`detection`)?`placement-unreadable`:`detection-off`};let a=t.detection;if(n===void 0||r===void 0||i===void 0)return{kind:`unknown`,gap:`pending`};if(!n.reachable)return{kind:`unknown`,gap:`node-unreachable`};let o=n.devices.find(e=>e.backend===a.engine.backend&&e.device===a.engine.device);if(o===void 0)return{kind:`unknown`,gap:`device-unknown`};let s=wi(r,Si);if(s===void 0)return{kind:`unknown`,gap:`step-unknown`};let c=be({catalog:s,device:o,override:Ci(i,Si)?.modelId,base:o.steps?.[Si]?.modelId});return c===void 0?{kind:`unknown`,gap:`no-model`}:{kind:`resolved`,nodeId:a.nodeId,modelId:c,minScore:s.models.find(e=>e.id===c)?.defaultConfidence??s.defaultConfidence}}n();var Ei=`person`,Di={pending:`Reading which detector this camera runs…`,"placement-unreadable":`The detection stage of this camera could not be read, so the model it runs is unknown — not absent.`,"detection-off":`This camera runs no object detector, so there is no proposal to mirror.`,"node-unreachable":`The node that detects for this camera did not answer about its accelerators.`,"device-unknown":`The node does not list the accelerator this camera detects on — asking another one would propose with a different model.`,"step-unknown":`That node carries no object-detection step in its catalog.`,"no-model":`No object-detection model on that accelerator can be resolved for this camera.`};function Oi(){let[t,n]=l(null),[i,o]=l(null),[c,f]=l([]),[p,m]=l(-1),[h,g]=l(new Map),[_,v]=l(null),y=ee({projection:`slim`,isCamera:!0}),b=a(()=>{let e=new Map;for(let t of y.data??[])e.set(t.id,t.name);return e},[y.data]),S=P({}),E=de({trackId:t?.trackId??``},{enabled:t!==null}),D=C({trackId:t?.trackId??``},{enabled:t!==null}),O=ae({frameId:i??``},{enabled:i!==null}),k=F(),A=x(),j=fe(),M=ie(),te=T(),ne=Me({deviceIds:t===null?[]:[t.deviceId]},{enabled:t!==null,staleTime:3e4}),I=ne.data?.[0]?.detection?.nodeId??null,L=ve({nodeId:I??``},{enabled:I!==null,staleTime:3e4}),R=pe({nodeId:I??``},{enabled:I!==null,staleTime:3e4}),z=Fe({deviceId:t?.deviceId??0},{enabled:t!==null,staleTime:3e4}),B=a(()=>Ti({status:ne.data?.[0],nodeDevices:L.data,schema:R.data,resolvedSteps:z.data?.steps}),[ne.data,L.data,R.data,z.data]);d(()=>{if(i===null){f([]);return}f((D.data??[]).filter(e=>e.mediaKey===i).map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},...e.subLabel===void 0?{}:{subLabel:e.subLabel},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}))),m(-1)},[i,D.data]),d(()=>{let e=E.data?.copies??[];i===null&&e.length>0&&o(e[0].frameId)},[E.data,i]);let oe=e(e=>{n(e),o(null),f([]),g(new Map),v(null)},[]),se=e(async e=>{if(t===null)return;let n=await k.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,mediaIds:[e]});if(n.refused.length>0){let e=new Map(h);for(let t of n.refused)e.set(t.sourceMediaId,t.reason);g(e)}n.copied.length>0&&o(n.copied[0].frameId),await E.refetch(),await S.refetch()},[t,k,h,E,S]),H=e(async e=>{t!==null&&(await A.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,frameId:e}),i===e&&o(null),await E.refetch(),await D.refetch(),await S.refetch())},[t,A,i,E,D,S]),U=e(async e=>{if(t===null||i===null)return;if(v(null),B.kind!==`resolved`){v(Di[B.gap]);return}let n=await j.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,frameId:i,subject:e===`package`?{kind:`package`}:{kind:`objects`,modelId:B.modelId,minScore:B.minScore},nodeId:B.nodeId});if(n.kind===`refused`){v(n.reason===`no-zone`?`A package proposal runs on the zone crop only — this camera has no zone, and running the detector on the whole frame at 0.35 proposes furniture.`:`The pipeline refused: ${n.reason}${n.detail===void 0?``:` — ${n.detail}`}`);return}f(e=>[...e,...n.proposals.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label===void 0?{}:{label:e.label},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}))]),v(`${n.proposals.length} proposal${n.proposals.length===1?``:`s`} from ${n.modelId}`+(n.belowThreshold>0?` — ${n.belowThreshold} more were below ${n.minScore.toFixed(2)}`:``))},[t,i,j,B]),W=e(e=>{f(t=>[...t,{bbox:e,macroClass:Ei,kind:`subject`,source:`operator`}]),m(c.length)},[c.length]),ce=e((e,t)=>{f(n=>n.map((n,r)=>r===e?{...n,...t}:n))},[]),G=e(e=>{f(t=>t.filter((t,n)=>n!==e)),m(-1)},[]),le=e(async()=>{t===null||i===null||(await M.mutateAsync({deviceId:t.deviceId,trackId:t.trackId,frameId:i,annotations:c.map(e=>({bbox:e.bbox,macroClass:e.macroClass,...e.label!==void 0&&e.label!==``?{label:e.label}:{},...e.subLabel!==void 0&&e.subLabel!==``?{subLabel:e.subLabel}:{},kind:e.kind,source:e.source,...e.assistModelId===void 0?{}:{assistModelId:e.assistModelId},...e.assistScore===void 0?{}:{assistScore:e.assistScore}}))}),await D.refetch(),await S.refetch(),v(`Annotations saved.`))},[t,i,c,M,D,S]),ue=e(async()=>{if(t===null)return;let e=await te.mutateAsync({deviceId:t.deviceId,trackId:t.trackId});v(e.changed?`Track completed — it is now trained, and its own media is evictable again.`:e.reason===`no-frames-copied`?`Refused: no frame was ever copied into the dataset. Completing would let retention delete material nothing was extracted from.`:`Refused: ${e.reason??`unknown`}`),await S.refetch(),e.changed&&n(null)},[t,te,S]),me=O.data,he=oi(c)&&i!==null;return r(He,{subtitle:`Turn the tracks you marked for training into an annotated dataset. Selecting a frame copies it — the dataset never depends on media that can be swept.`,actions:t===null?null:r(w,{size:`sm`,onClick:()=>void ue(),children:[u(ut,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Complete track`})]}),children:[_!==null&&u(`div`,{className:`rounded-md border border-border bg-surface px-3 py-2 text-xs text-foreground`,children:_}),u(hi,{}),r(`div`,{className:`grid grid-cols-1 lg:grid-cols-[minmax(0,260px)_minmax(0,1fr)] gap-4`,children:[r(`aside`,{className:`rounded-md border border-border bg-surface overflow-hidden`,children:[r(`div`,{className:`px-3 py-2 border-b border-border flex items-center justify-between`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground`,children:`Staging`}),u(N,{children:S.data?.length??0})]}),u(xi,{tracks:S.data??[],isLoading:S.isLoading,selectedTrackId:t?.trackId??null,deviceNames:b,onSelect:oe})]}),u(`section`,{className:`space-y-3 min-w-0`,children:t===null?u(`p`,{className:`text-xs text-foreground-subtle`,children:`Pick a track from the staging list to start annotating it.`}):r(s,{children:[u(`div`,{className:`rounded-md border border-border bg-surface p-3`,children:u(_i,{candidates:E.data?.candidates??[],copies:E.data?.copies??[],activeFrameId:i,refusals:h,isSelecting:k.isPending,onSelectCandidate:e=>void se(e),onOpenCopy:o,onRemoveCopy:e=>void H(e)})}),i!==null&&r(`div`,{className:`grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(0,380px)] gap-3`,children:[u(`div`,{className:`rounded-md border border-border overflow-hidden`,children:me===void 0?r(`div`,{className:`flex items-center gap-2 p-6 text-xs text-foreground-subtle`,children:[u(V,{className:`h-3.5 w-3.5 animate-spin`}),`Loading the frame…`]}):u(mi,{imageSrc:`data:image/jpeg;base64,${me.base64}`,imageWidth:me.width,imageHeight:me.height,boxes:c,selectedIndex:p,onSelect:m,onDraw:W})}),r(`div`,{className:`rounded-md border border-border bg-surface flex flex-col min-h-0`,children:[r(`div`,{className:`px-3 py-2 border-b border-border flex items-center gap-2`,children:[u(`h2`,{className:`text-xs font-semibold text-foreground flex-1`,children:`Subjects`}),r(w,{variant:`secondary`,size:`sm`,disabled:j.isPending||B.kind!==`resolved`,onClick:()=>void U(`objects`),children:[u(re,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Propose`})]}),r(w,{variant:`secondary`,size:`sm`,disabled:j.isPending||B.kind!==`resolved`,onClick:()=>void U(`package`),children:[u(re,{className:`h-3 w-3`}),u(`span`,{className:`ml-1`,children:`Packages`})]})]}),u(`div`,{className:`px-3 py-1 border-b border-border text-[11px] text-foreground-subtle`,children:B.kind===`resolved`?`Proposals come from ${B.modelId} at ${B.minScore.toFixed(2)}, on ${B.nodeId} — what this camera really runs.`:Di[B.gap]}),u(`div`,{className:`flex-1 overflow-y-auto`,children:u(ai,{annotations:c,selectedIndex:p,onSelect:m,onChange:ce,onDelete:G})}),r(`div`,{className:`px-3 py-2 border-t border-border flex items-center justify-between`,children:[r(`span`,{className:`text-[11px] text-foreground-subtle`,children:[c.filter(e=>e.kind===`model_error`).length,` marked as model errors`]}),u(w,{size:`sm`,disabled:!he||M.isPending,onClick:()=>void le(),children:`Save frame`})]})]})]})]})})]})]})}function ki(){return u(`div`,{className:`flex flex-col p-4`,children:u(at,{tabs:[{id:`feed`,label:`Feed`,icon:j,content:u(ti,{})},{id:`retrain`,label:`Retrain`,icon:ut,content:u(Oi,{})},{id:`debug`,label:`Debug`,icon:W,content:u(Or,{})}]})})}export{ki as EventsPage};