@camstack/addon-admin-ui 1.2.397 → 1.2.399

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/assets/{AddonAssetIcon-7ZvCceV6.js → AddonAssetIcon-DRk5tFmQ.js} +1 -1
  2. package/dist/assets/{AddonIntegrationBody-CmsA9jC5.js → AddonIntegrationBody-BokvIE2T.js} +1 -1
  3. package/dist/assets/Addons-eoG6yhVR.js +4 -0
  4. package/dist/assets/{AdminPage-eik5HL7w.js → AdminPage-LJSPjGaV.js} +1 -1
  5. package/dist/assets/{AdminSectionedPage-Dj5EzIqk.js → AdminSectionedPage-Dmz5o8uT.js} +1 -1
  6. package/dist/assets/AiProfiles-CeyoQkna.js +3 -0
  7. package/dist/assets/BrokerForm-UsE-opKN.js +1 -0
  8. package/dist/assets/Build-BJTgUvs3.js +40 -0
  9. package/dist/assets/{Calendars-DF3EOrCw.js → Calendars-hNy0XH9U.js} +1 -1
  10. package/dist/assets/Cluster-DL2F6C0r.js +1 -0
  11. package/dist/assets/ClusterStepModel-BMV2GNMb.js +1 -0
  12. package/dist/assets/CompositionEditor-D8K5gqDy.js +1 -0
  13. package/dist/assets/{CompositionEditorPage-BOTNyxzw.js → CompositionEditorPage-BcxlauFW.js} +1 -1
  14. package/dist/assets/Data-DJzLYSz8.js +1 -0
  15. package/dist/assets/DeviceDetail-BxQ2qayC.js +2 -0
  16. package/dist/assets/{DeviceDoActionFields-DPIQv0Gp.js → DeviceDoActionFields-CvF7Gep-.js} +1 -1
  17. package/dist/assets/{Devices-X3jFUswR.js → Devices-CLznFJt2.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-CXBuVqsj.js → EmbedPlayerPage-CZkHg-Z5.js} +1 -1
  19. package/dist/assets/Identity-DQuyqFAW.js +1 -0
  20. package/dist/assets/IntegrationDetail-ClkIqZkc.js +1 -0
  21. package/dist/assets/Integrations-Di2rQcGB.js +1 -0
  22. package/dist/assets/Integrations-tr28SRdu.js +1 -0
  23. package/dist/assets/Library-BoOL6cQN.js +1 -0
  24. package/dist/assets/Locations-ddLOQn97.js +3 -0
  25. package/dist/assets/{Logs-C8EFuHw0.js → Logs-DOMXl7b_.js} +1 -1
  26. package/dist/assets/{MotionZonesSettings-BQocc7WN.js → MotionZonesSettings-VFYF5C3z.js} +1 -1
  27. package/dist/assets/MyAccess-BvNfguhI.js +2 -0
  28. package/dist/assets/Network-xLYgrYEu.js +1 -0
  29. package/dist/assets/{NodeAddonsSettingsPanel-BCFsPpmx.js → NodeAddonsSettingsPanel-DNm2sNWd.js} +1 -1
  30. package/dist/assets/Notifications-C77viP5y.js +1 -0
  31. package/dist/assets/{PrivacyMaskSettings-CIOFdwm5.js → PrivacyMaskSettings-CcLxP0Q6.js} +1 -1
  32. package/dist/assets/Recordings-a6r7fxRd.js +1 -0
  33. package/dist/assets/{ScanNetworkModal-C9-sEf0w.js → ScanNetworkModal-yeTJMkLN.js} +1 -1
  34. package/dist/assets/{SceneMonitorEditor-B4Xa4X5o.js → SceneMonitorEditor-DB1NGsuu.js} +1 -1
  35. package/dist/assets/SessionsList-JKR36vEz.js +2 -0
  36. package/dist/assets/{Showroom-DbgC7jrf.js → Showroom-uPs2cinU.js} +1 -1
  37. package/dist/assets/{System-UCSG2wyb.js → System-iyC6su3q.js} +1 -1
  38. package/dist/assets/{Terminal-BN5uwTST.js → Terminal-B_bk9YuG.js} +3 -3
  39. package/dist/assets/{Viewer-sX4O6bY5.js → Viewer-hCw4DvsX.js} +1 -1
  40. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D6MiVNmX.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D4evVvwt.js} +1 -1
  41. package/dist/assets/{archive-C3YvN3bo.js → archive-D3wNUMUT.js} +1 -1
  42. package/dist/assets/{authed-media-CadypKga.js → authed-media-B-33JcKf.js} +1 -1
  43. package/dist/assets/{boxes-I78qynMn.js → boxes-PrddLfOG.js} +1 -1
  44. package/dist/assets/circle-slash-BOrPYytm.js +1 -0
  45. package/dist/assets/client-1JBRoe76.js +357 -0
  46. package/dist/assets/crop-ChT009Qt.js +1 -0
  47. package/dist/assets/{device-integration-icon-DqKmRTQS.js → device-integration-icon-BVEgrVH7.js} +1 -1
  48. package/dist/assets/device-picker-model-DD88fyzH.js +1 -0
  49. package/dist/assets/dist-CEvY94M_.js +357 -0
  50. package/dist/assets/{dist-BXnRXTui.js → dist-_pgvIUGn.js} +1 -1
  51. package/dist/assets/{format-size-D8E_VMta.js → format-size-CI1h5otl.js} +1 -1
  52. package/dist/assets/{history-GFLGqkV_.js → history-B0sqAabA.js} +1 -1
  53. package/dist/assets/{hostInit-iPWvYWG7.js → hostInit-D4-UgrFJ.js} +1 -1
  54. package/dist/assets/{index-DtcBoptX.css → index-C6r9IlW4.css} +1 -1
  55. package/dist/assets/index-V6k1XLI7.js +4 -0
  56. package/dist/assets/{layers-D5TeeKqH.js → layers-Bg1NrUAX.js} +1 -1
  57. package/dist/assets/{location-owned-usage-DmAH-1FL.js → location-owned-usage-CG3xos_0.js} +1 -1
  58. package/dist/assets/log-in-DwkWn-LJ.js +1 -0
  59. package/dist/assets/{mf-entry-bootstrap-0-53adc98f.js → mf-entry-bootstrap-0-0ee3f006.js} +2 -2
  60. package/dist/assets/{monitor-smartphone-CEvv3FjX.js → monitor-smartphone-J97h7fMI.js} +1 -1
  61. package/dist/assets/mount-DD88fyzH.js +1 -0
  62. package/dist/assets/notification-schedule-field-Bnhm4lQH.js +1 -0
  63. package/dist/assets/{octagon-alert-bX5m_c3-.js → octagon-alert-D1Sw5N86.js} +1 -1
  64. package/dist/assets/{player-overlays-mP7nvLXZ.js → player-overlays-9CMoB0XN.js} +1 -1
  65. package/dist/assets/remoteEntry-nN8yf3LF.js +1 -0
  66. package/dist/assets/{send-3vh-Sv9u.js → send-D9__QB6r.js} +1 -1
  67. package/dist/assets/{settings-2-CIYonoB2.js → settings-2-DEwPBiUG.js} +1 -1
  68. package/dist/assets/{src-BeE19PxU.js → src-Ca4gNAmP.js} +8 -8
  69. package/dist/assets/{use-scenes-feed-Dch15Gtk.js → use-scenes-feed-72EeOPdE.js} +1 -1
  70. package/dist/assets/{use-stationary-objects-CAgVm5qH.js → use-stationary-objects-BxmIxHKh.js} +1 -1
  71. package/dist/assets/useEventInvalidation-DD88fyzH.js +1 -0
  72. package/dist/assets/{useNodeUrlSelection-C2aUQ5pz.js → useNodeUrlSelection-CM809DR6.js} +1 -1
  73. package/dist/assets/user-round-BuAM59Jp.js +1 -0
  74. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D2o8TmMv.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-qbX0hoWb.js} +2 -2
  75. package/dist/index.html +28 -10
  76. package/dist/server/addon.js +9 -2
  77. package/package.json +1 -1
  78. package/dist/assets/Addons-B0lqxfjl.js +0 -4
  79. package/dist/assets/AiProfiles-BYQcaDzE.js +0 -3
  80. package/dist/assets/BrokerForm-Oa4W78DW.js +0 -1
  81. package/dist/assets/Build-DTkrXnV9.js +0 -40
  82. package/dist/assets/Cluster-9ZOqQRY0.js +0 -1
  83. package/dist/assets/ClusterStepModel-ZEYxPYn0.js +0 -1
  84. package/dist/assets/CompositionEditor-Cv06FJwk.js +0 -1
  85. package/dist/assets/Data-Ct8SqRSf.js +0 -1
  86. package/dist/assets/DeviceDetail-Dn0-0JDf.js +0 -2
  87. package/dist/assets/Identity-bdrVgYed.js +0 -1
  88. package/dist/assets/IntegrationDetail-BFt35GRb.js +0 -1
  89. package/dist/assets/Integrations-TPrR0bGF.js +0 -1
  90. package/dist/assets/Integrations-vjs0FPms.js +0 -1
  91. package/dist/assets/Library-Ck49o54W.js +0 -1
  92. package/dist/assets/Locations-aqPkrde8.js +0 -3
  93. package/dist/assets/MyAccess-C8p-J8wW.js +0 -2
  94. package/dist/assets/Network-CaDC37pB.js +0 -1
  95. package/dist/assets/Notifications-B2CuenV0.js +0 -1
  96. package/dist/assets/Recordings-1xAqwANe.js +0 -1
  97. package/dist/assets/SessionsList-0Ev1b1-K.js +0 -2
  98. package/dist/assets/circle-slash-C5FeKGvp.js +0 -1
  99. package/dist/assets/client-D5nV-lIF.js +0 -357
  100. package/dist/assets/crop-GRVPmcCZ.js +0 -1
  101. package/dist/assets/device-picker-model-irtdVS9Y.js +0 -1
  102. package/dist/assets/dist-CgEPs7ts.js +0 -357
  103. package/dist/assets/index-I1VJhtqM.js +0 -4
  104. package/dist/assets/mount-irtdVS9Y.js +0 -1
  105. package/dist/assets/notification-schedule-field-B_0lw5Ql.js +0 -1
  106. package/dist/assets/remoteEntry-P7nyMvXh.js +0 -1
  107. package/dist/assets/useEventInvalidation-irtdVS9Y.js +0 -1
  108. package/dist/assets/user-round-D2N1DqIB.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{D as d,G as f,Q as p,ct as m,lt as h,ot as g,vt as _,yt as v}from"./player-overlays-mP7nvLXZ.js";import{Bd as y,Ed as b,Gn as x,Hn as S,Ht as C,Kn as w,L as T,Qd as E,Ql as D,Qu as O,Ru as k,Tn as A,U as j,Ut as M,Vt as N,Yd as P,Zu as F,_f as I,dd as ee,dr as L,ef as R,ln as z,md as B,mu as te,ud as V,ya as H,z as U,zd as W,zn as ne}from"./src-BeE19PxU.js";import{t as re}from"./send-3vh-Sv9u.js";import{Wn as G}from"./client-D5nV-lIF.js";import{t as K}from"./useTranslation-Bc5yH9V9.js";import"./mount-irtdVS9Y.js";import{C as q}from"./index-I1VJhtqM.js";import{t as ie}from"./AdminSectionedPage-Dj5EzIqk.js";import{t as J}from"./AdminPage-eik5HL7w.js";var ae=v(`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 oe=[`llm`,`listProfiles`],se=[`llm`,`listProfileKinds`],ce=[`llm`,`getDefaults`],Y=[`llm`,`listRuntimeNodes`],le=[`llm`,`listModelCatalog`],ue=[`llm`,`getUsage`],de=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],fe=new Map(Object.entries({openai:R,anthropic:R,google:R,"openai-compatible":V,"managed-local":E,"apple-foundation":E}));function pe(e){return fe.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 me(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:ve(e.runtime?.extraArgs??[])}}var he=[`f32`,`f16`,`q8_0`,`q5_1`,`q5_0`,`q4_1`,`q4_0`];function ge(e){return typeof e==`string`&&he.includes(e)?e:void 0}function _e(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 ve(e){return e.map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)}var ye=[`--jinja`,`--cont-batching`];function be(e,t,n){let r=Z(e.threads),i=Z(e.batchSize),a=Z(e.ubatchSize),o=ge(e.cacheTypeK),s=ge(e.cacheTypeV);return{nodeId:t,engine:`llama-cpp`,model:n,extraArgs:[..._e(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 xe(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)??G.totalMs,connectTimeoutMs:Z(r.connectTimeoutMs)??G.connectMs,firstTokenTimeoutMs:Z(r.firstTokenTimeoutMs)??G.firstTokenMs,idleTimeoutMs:Z(r.idleTimeoutMs)??G.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:be(r,i.nodeId,i.model)}}}function Se(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 Ce=`apple-system`;function we(e,t,n,r){return{...xe(`apple-foundation`,e,t,n),model:Ce,supportsVision:!1,appleFoundation:{nodeId:r}}}var Te={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 Ee(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=Te[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 De=2e3;function $(e){return`${(e/1e9).toFixed(2)} GB`}function Oe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function ke({nodeId:e,value:t,onChange:n}){let{t:o}=K(),u=g(),[d,f]=s(``),[p,m]=s(null),[h,_]=s(!1),v=a({queryKey:le,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),y=a({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:e})}),S=c({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(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),y.refetch()}}),T=a({queryKey:Y,enabled:C.isPending,refetchInterval:C.isPending?De:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,E=i(()=>{let t=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(y.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,y.data,p,e,o]),k=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=y.data?.find(e=>e.file===t);r?.path!==void 0&&n({model:{kind:`path`,path:r.path},modelId:t,supportsVision:!1})},A=e=>{d.trim()!==``&&S.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(x,{id:`ai-model`,value:Oe(t),options:E,onChange:e=>k(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(D,{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(),A())}}),r(w,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||S.isPending,onClick:()=>A(),children:[S.isPending?l(b,{className:`h-3.5 w-3.5 animate-spin`}):l(O,{className:`h-3.5 w-3.5`}),o(`ai.hfCheck`,`Check`)]})]}),S.isError&&l(`p`,{className:`mt-2 text-[11px] text-danger`,children:S.error instanceof Error?S.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),S.mutate({ref:t})},children:e},e))}),p.requiredBytes!==void 0&&l(w,{size:`sm`,variant:`secondary`,type:`button`,className:`mt-2`,onClick:()=>A(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(L,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),l(L,{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(w,{size:`sm`,type:`button`,disabled:C.isPending||h,onClick:()=>C.mutate(p.model),children:[C.isPending?l(b,{className:`h-3.5 w-3.5 animate-spin`}):l(P,{className:`h-3.5 w-3.5`}),h?o(`ai.hfInstalled`,`Downloaded`):o(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),T!==void 0&&l(`span`,{className:`text-[10px] text-foreground-subtle`,children:T.phase===`verifying`?o(`ai.hfVerifying`,`verifying {{file}}…`,{file:T.file}):o(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:T.file,index:T.fileIndex,count:T.fileCount,done:$(T.downloadedBytes),total:T.totalBytes===void 0?``:` / ${$(T.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 Ae({value:e,onChange:t}){let{t:n}=K(),i=g(),o=a({queryKey:Y,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(b,{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=Ee(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(L,{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 je({kind:e,className:t}){let n=pe(e.kind);return n===null?l(`span`,{className:t,children:e.icon}):l(n,{className:t})}function Me({kinds:e,onPick:t,onCancel:n}){let{t:a}=K(),o=i(()=>Se(e),[e]);return l(U,{open:!0,onClose:n,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:r(`div`,{className:`space-y-4`,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(je,{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))]})})}function Ne({kind:e,existing:t,onSave:n,onCancel:a,saving:c,error:u}){let{t:d}=K(),f=e.kind===`managed-local`,p=e.kind===`apple-foundation`,[m,h]=s(t?.appleFoundation?.nodeId??null),[g,_]=s(t?.name??e.label),[v,y]=s(()=>t===null?{}:me(t)),[x,S]=s(t?.runtime?.nodeId??`hub`),[C,T]=s(()=>t?.runtime===void 0?null:{model:t.runtime.model,modelId:t.model,supportsVision:t.supportsVision}),E=i(()=>_e(X(v.extraArgs)??``),[v.extraArgs]),O=()=>{if(p){if(m===null)return;n(we(g,t,v,m));return}if(!f){n(xe(e.kind,g,t,v));return}C!==null&&n(xe(e.kind,g,t,v,{nodeId:x,model:C.model,modelId:C.modelId,supportsVision:C.supportsVision}))},k=c||g.trim()===``||f&&C===null||p&&m===null;return l(U,{open:!0,onClose:a,title:t===null?d(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):d(`ai.editProfile`,`Edit {{name}}`,{name:t.name}),error:u,width:`lg`,testId:`ai-profile-editor`,footer:r(o,{children:[f&&C===null&&l(L,{variant:`warning`,children:d(`ai.pickModelFirst`,`pick a model`)}),p&&m===null&&l(L,{variant:`warning`,children:d(`ai.pickAppleNodeFirst`,`pick a Mac`)}),r(w,{size:`sm`,type:`button`,disabled:k,onClick:O,children:[c&&l(b,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`ai.createProfile`,`Create profile`):d(`ai.saveChanges`,`Save changes`)]})]}),children:r(`div`,{className:`space-y-3`,children:[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(D,{id:`ai-profile-name`,value:g,onChange:e=>_(e.target.value),placeholder:e.label})]}),f&&r(o,{children:[l(j,{selectedNodeId:x,onSelect:S,label:d(`ai.runtimeNode`,`Runtime node`),alwaysShow:!0}),l(ke,{nodeId:x,value:C,onChange:T}),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(D,{id:`ai-extra-args`,value:X(v.extraArgs)??``,onChange:e=>y({...v,extraArgs:e.target.value}),placeholder:ye.join(` `)}),E.length>0&&l(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:E.map((e,t)=>l(L,{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(Ae,{value:m,onChange:h}),l(A,{schema:e.configSchema,values:v,onChange:y}),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.`)})]})})}n();function Pe(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(je,{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(L,{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(L,{variant:`default`,children:e.runtime.nodeId})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>l(z,{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(w,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?l(b,{className:`h-3.5 w-3.5 animate-spin`}):l(re,{className:`h-3.5 w-3.5`})}),l(w,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),title:e.t(`common.edit`,`Edit`),children:l(B,{className:`h-3.5 w-3.5`})}),l(w,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:e.t(`common.delete`,`Delete`),children:l(m,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Fe(){let{t}=K(),n=g(),{state:o,openNew:d,openEdit:f,close:p}=T(),[m,h]=s(null),[_,v]=s(null),[y,x]=s(null),E=a({queryKey:oe,queryFn:()=>n.trpcClient.llm.listProfiles.query({})}),D=a({queryKey:se,queryFn:async()=>(await n.trpcClient.llm.listProfileKinds.query({})).map(e=>({...e,configSchema:e.configSchema}))}),O=()=>{E.refetch()},A=e(()=>{h(null),x(null),p()},[p]);u(()=>{o.mode===`closed`&&h(null)},[o.mode]);let j=c({mutationFn:e=>n.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{A(),O()},onError:e=>x(e instanceof Error?e.message:t(`ai.saveFailed`,`Save failed`))}),M=c({mutationFn:e=>n.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:O}),P=c({mutationFn:e=>n.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>v({id:t.id,ok:e.ok,text:e.ok?`${e.text} (${String(e.usage.outputTokens)} tok, ${String(e.latencyMs)}ms)`:`${e.code}: ${e.message}`})}),F=E.data??[],I=i(()=>D.data??[],[D.data]),L=i(()=>{let e=new Map;for(let t of I)e.set(t.kind,t);return e},[I]),R=o.mode===`edit`?F.find(e=>e.id===o.id)??null:null,z=R===null?null:L.get(R.kind)??null,B=o.mode===`new`&&m===null,te=o.mode===`new`?m:z,V=o.mode===`edit`?R:null,H=te!==null&&(o.mode===`new`||V!==null);return r(J,{embedded:!0,icon:k,title:t(`ai.profilesTitle`,`AI profiles`),subtitle:t(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),actions:r(w,{size:`sm`,type:`button`,onClick:()=>{x(null),h(null),d()},children:[l(ee,{className:`h-3.5 w-3.5`}),t(`ai.addProfile`,`Add profile`)]}),children:[E.isError&&l(S,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:E.error instanceof Error?E.error.message:t(`common.error`,`Error`),onRetry:()=>void E.refetch()}),l(Ie,{profiles:F}),E.isLoading&&l(`div`,{className:`flex items-center justify-center py-16`,children:l(b,{className:`h-6 w-6 animate-spin text-primary`})}),!E.isLoading&&F.length===0&&l(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}),F.length>0&&l(N,{headingId:`ai-profiles-list`,title:t(`ai.profilesList`,`Profiles`),children:l(C,{columns:Pe({kindByName:L,testResult:_,testingId:P.isPending?P.variables?.id??null:null,t,onToggle:e=>j.mutate({...e,enabled:!e.enabled,apiKey:`__redacted__`}),onTest:e=>P.mutate(e),onEdit:e=>{L.has(e.kind)&&(x(null),h(null),f(e.id))},onDelete:e=>M.mutate(e)}),rows:F,rowKey:e=>e.id,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),B&&l(Me,{kinds:I,onCancel:A,onPick:e=>{x(null),h(e)}}),H&&te!==null&&l(Ne,{kind:te,existing:V,saving:j.isPending,error:y,onSave:e=>j.mutate(e),onCancel:A})]})}function Ie({profiles:e}){let{t}=K(),n=g(),i=a({queryKey:ce,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(N,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:l(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:de.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)}),l(x,{id:`llm-default-${n}`,"aria-label":u(n),className:`h-7 text-xs`,value:c,onChange:e=>o.mutate({purpose:n,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:t(`ai.none`,`None`)},...c!==``&&!a.some(e=>e.id===c)?[{value:c,label:d?.name??c}]:[],...a.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),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 Le=5e3;function Re(e){return`${(e/1e9).toFixed(1)} GB`}function ze(){let{t:e}=K(),t=g(),n=a({queryKey:Y,refetchInterval:Le,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(L,{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(L,{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?`—`:Re(e.disk.modelsBytes)})},{key:`apple`,header:e(`ai.colApple`,`Apple on-device`),render:t=>{let n=Ee(t);return r(`span`,{className:`flex flex-col items-start gap-0.5`,children:[l(L,{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(J,{embedded:!0,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(S,{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(N,{headingId:`ai-runtimes-list`,title:e(`ai.runtimesList`,`Nodes`),children:l(C,{columns:o,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:M})})]})}var Be=p(`/addon/ai/test-chat`),Ve=p(`/addon/ai/test-chat/chats`),He=6e5;function Ue(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),He)}function We(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e){if(!We(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 Ke=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function qe(e){let t;try{t=JSON.parse(e)}catch{return null}if(!We(t))return null;switch(t.kind){case`status`:{let e=Ke.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:Ge(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*Je(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=qe(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=qe(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Ye(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Xe(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Ze(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 Qe(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 $e(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 et=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],tt=360*60*1e3,nt=40,rt=160,it={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function at(){let{t:n}=K(),o=g(),[c,d]=s(``),[f,p]=s(``),[v,b]=s(``),[C,T]=s([]),[E,O]=s(null),[k,A]=s(`none`),[j,M]=s(`throwaway`),[N,P]=s(null),[F,ee]=s([]),[L,R]=s(null),[z,B]=s(null),V=t(null);u(()=>()=>V.current?.abort(),[]);let H=e(async()=>{let e=await fetch(Ve,{credentials:`same-origin`});e.ok&&ee((await e.json()).chats??[])},[]);u(()=>{j===`persistent`&&H()},[j,H]);let U=a({queryKey:oe,queryFn:()=>o.trpcClient.llm.listProfiles.query({})}),W=i(()=>(U.data??[]).filter(e=>e.enabled),[U.data]),G=W.find(e=>e.id===c)??null,q=z!==null,ie=e(async(e,t)=>{let r=new AbortController;V.current=r,R(null);let i=Ue(G??{});B({...it,firstTokenTimeoutMs:i??0});let a=``,o=null,s,l=null,u=null,d;try{let n=await fetch(Be,{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},...j===`persistent`?{persist:!0,...N===null?{}:{conversationId:N}}:{}})});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 Je(n.body))switch(e.kind){case`status`:B(t=>({...t??it,phase:e.phase}));break;case`meta`:o=e.mediaSent,s=e.model,B(t=>({...t??it,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:a+=e.text,B(e=>({...e??it,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||R(e instanceof Error?e.message:n(`common.error`,`Error`))}finally{V.current=null,B(null)}d!==void 0&&(P(d),H());let p=r.signal.aborted&&a.length>0;l===null&&a.length===0&&!p||T(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}])},[j,N,G,c,H,f,n]),se=e(()=>{let e=v.trim();if(e===``||c===``||q)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...E===null?{}:{attachmentLabel:E.label,attachmentKind:E.ref.kind}},n=[...C,t];T(n),b(``);let r=E?.ref;O(null),A(`none`),ie(j===`persistent`&&N!==null?[{role:`user`,content:e}]:Ye(n),r)},[j,N,v,E,c,ie,q,C]),ce=()=>V.current?.abort(),Y=()=>{V.current?.abort(),T([]),O(null),b(``),R(null),B(null),P(null)},le=async e=>{V.current?.abort();let t=await fetch(`${Ve}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();P(e),T(Ze(n)),B(null),R(null)};return r(J,{embedded:!0,icon:y,title:n(`ai.testTitle`,`Test chat`),subtitle:n(j===`persistent`?`ai.testSubtitlePersistent`:`ai.testSubtitle`,j===`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(w,{size:`sm`,variant:`secondary`,type:`button`,disabled:C.length===0&&E===null,onClick:Y,children:[l(m,{className:`h-3.5 w-3.5`}),n(`ai.clearChat`,`Clear`)]}),children:[r(ne,{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(x,{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&&!U.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(D,{id:`ai-test-system`,value:f,onChange:e=>p(e.target.value),placeholder:n(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[l(w,{size:`sm`,variant:j===`throwaway`?`primary`:`outline`,type:`button`,onClick:()=>{M(`throwaway`),P(null)},children:n(`ai.throwawayMode`,`Throwaway`)}),l(w,{size:`sm`,variant:j===`persistent`?`primary`:`outline`,type:`button`,onClick:()=>M(`persistent`),children:n(`ai.saveConversation`,`Save conversation`)})]}),j===`persistent`&&r(`div`,{className:`space-y-2`,children:[l(`div`,{className:`flex items-center gap-2`,children:r(w,{size:`sm`,variant:`secondary`,type:`button`,onClick:Y,children:[l(ae,{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===N?`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.`)})]}),L!==null&&l(S,{title:n(`ai.chatFailed`,`The test call failed`),message:L}),l(ot,{turns:C,live:z}),r(ne,{className:`space-y-2 p-3`,children:[E!==null&&r(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-surface px-2.5 py-1.5`,children:[E.ref.kind===`snapshot`?l(_,{className:`h-3.5 w-3.5 text-foreground-subtle`}):l(I,{className:`h-3.5 w-3.5 text-foreground-subtle`}),l(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-foreground`,children:E.label}),l(w,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>O(null),children:l(te,{className:`h-3.5 w-3.5`})})]}),r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(w,{size:`sm`,variant:k===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>A(k===`snapshot`?`none`:`snapshot`),children:[l(_,{className:`h-3.5 w-3.5`}),n(`ai.attachSnapshot`,`Camera snapshot`)]}),r(w,{size:`sm`,variant:k===`track`?`primary`:`outline`,type:`button`,onClick:()=>A(k===`track`?`none`:`track`),children:[l(I,{className:`h-3.5 w-3.5`}),n(`ai.attachTrack`,`Recent track`)]})]}),k===`snapshot`&&l(lt,{onPick:e=>{O({ref:{kind:`snapshot`,deviceId:e.id},label:n(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:e.name})}),A(`none`)}}),k===`track`&&l(dt,{onPick:(e,t)=>{O({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:n(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),A(`none`)}}),r(`div`,{className:`flex items-center gap-2`,children:[l(D,{value:v,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),se())},placeholder:n(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":n(`ai.message`,`Message`)}),q?r(w,{size:`sm`,variant:`secondary`,type:`button`,onClick:ce,children:[l(h,{className:`h-3.5 w-3.5`}),n(`ai.stop`,`Stop`)]}):r(w,{size:`sm`,type:`button`,disabled:v.trim()===``||c===``,onClick:se,children:[l(re,{className:`h-3.5 w-3.5`}),n(`ai.send`,`Send`)]})]})]})]})}function ot({turns:e,live:t}){let{t:n}=K();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(ne,{children:r(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto p-3`,children:[e.map(e=>l(st,{turn:e},e.id)),t!==null&&r(`div`,{className:`space-y-1`,children:[t.mediaSent!==null&&l(ct,{attachment:t.mediaSent}),t.text.length>0&&l(st,{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(b,{className:`h-3.5 w-3.5 animate-spin`}),$e(t.phase,t.firstTokenTimeoutMs)]})]})]})})}function st({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(ct,{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(I,{className:`h-3 w-3`}):l(_,{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(_,{className:`h-3 w-3`}):l(I,{className:`h-3 w-3`}),Qe(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 ct({attachment:e}){let t=Xe(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 lt({onPick:e}){let{t}=K(),n=H({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?l(b,{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(ut,{device:t,onPick:e},t.id))})}function ut({device:e,onPick:t}){let{src:n}=f(e.id,{width:rt});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(L,{variant:`warning`,children:`off`}),l(`span`,{className:`truncate text-[10px] text-foreground`,children:e.name})]})]})}function dt({onPick:e}){let{t}=K(),n=g(),o=H({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:[...et,s.length],enabled:s.length>0,queryFn:()=>n.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...s],since:Date.now()-tt,limit:nt,projection:`slim`})});if(o.isLoading||u.isLoading)return l(b,{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(I,{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 ft=1440*60*1e3,pt=[1,7,30,90];function mt(){let{t:e}=K(),t=g(),[n,o]=s(7),c=i(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(n-1)*ft},[n]),u=a({queryKey:oe,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),d=a({queryKey:[...ue,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]),m=d.data??[];return r(J,{embedded:!0,icon:W,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(x,{"aria-label":e(`ai.window`,`Window`),value:String(n),options:pt.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(S,{title:e(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:e(`common.error`,`Error`),onRetry:()=>void d.refetch()}),m.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(N,{headingId:`ai-usage-list`,title:e(`ai.usageList`,`Rollup`),children:l(C,{columns:p,rows:m,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:M})})]})}function ht(){let{t:e}=K(),t=q(`/system/ai`,{t:e,isAdmin:!0})??{icon:k,title:e(`system.ai`,`AI`)};return l(ie,{icon:t.icon,title:t.title,defaultSection:`profiles`,sectionsLabel:`${t.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:l(Fe,{})},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:l(ze,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:l(mt,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:l(at,{})}]})}export{ht as AiProfilesPage,ht as default};
@@ -1 +0,0 @@
1
- import{Q as e,S as t,W as n,q 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{Dn as a,Ed as o,Kn as s,Ti as c,vi as l}from"./src-BeE19PxU.js";import{I as u}from"./index-I1VJhtqM.js";e();function d(e,t){if(!e)return t;let n=new Set;for(let r of e.sections){let e=r.fields;for(let r of e)!(`key`in r)||typeof r.key!=`string`||a(r,t,e)&&n.add(r.key)}let r={};for(let[e,i]of Object.entries(t))n.has(e)&&(r[e]=i);return r}function f({kind:e,addonId:a,initialValues:f,onSubmit:p,onCancel:m,submitLabel:h,disabled:g}){let[_,v]=r(f??{}),[y,b]=r(null),x=l({kind:e,...a===void 0?{}:{addonId:a}}),S=n(()=>{let e=x.data;if(e&&typeof e==`object`&&`sections`in e&&Array.isArray(e.sections))return e},[x.data]),C=c(),w=async()=>{b(null);let t=d(S,_);try{let n=await C.mutateAsync({kind:e,settings:t,...a===void 0?{}:{addonId:a}});b(n.ok?{ok:!0}:{ok:!1,error:n.error})}catch(e){b({ok:!1,error:e instanceof Error?e.message:String(e)})}};return t(`div`,{className:`space-y-3`,children:[x.isLoading&&t(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(o,{className:`h-3.5 w-3.5 animate-spin`}),` Loading schema…`]}),S&&i(u,{schema:S,values:_,onChange:v}),x.isError&&t(`div`,{className:`rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]`,children:[`Failed to load settings schema:`,` `,x.error instanceof Error?x.error.message:`Unknown error`]}),!S&&!x.isLoading&&!x.isError&&t(`div`,{className:`rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300`,children:[`No settings schema available for kind `,i(`code`,{className:`font-mono`,children:e}),`. Its broker addon may not be installed or running.`]}),y&&i(`div`,{className:`rounded border px-3 py-2 text-[11px] ${y.ok?`border-success/30 bg-success/5 text-success`:`border-danger/30 bg-danger/5 text-danger`}`,children:y.ok?`Connection OK.`:`Test failed: ${y.error??`unknown error`}`}),t(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[i(s,{variant:`outline`,size:`sm`,onClick:m,children:`Cancel`}),t(`div`,{className:`flex items-center gap-2`,children:[i(s,{variant:`outline`,size:`sm`,onClick:()=>{w()},disabled:C.isPending||!S,children:C.isPending?`Testing…`:`Test connection`}),i(s,{variant:`primary`,size:`sm`,onClick:()=>{p(d(S,_))},disabled:!S||g,children:h??`Save`})]})]})]})}export{f as t};
@@ -1,40 +0,0 @@
1
- import{I as e,K as t,M as n,Q as r,S as i,T as a,W as o,a as s,b as c,q as l,t as u,x as d,z as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{_t as p,ct as m,gt as h,ot as g,yt as _}from"./player-overlays-mP7nvLXZ.js";import{$u as v,Ai as y,Bi as b,Dt as x,Ed as S,Gn as C,Hn as w,Ht as T,Kn as E,L as D,Ld as O,Li as k,Lt as A,Mi as j,Ni as M,Of as N,Pi as P,Ql as F,Ri as I,Tt as L,U as R,Ut as ee,Vi as z,Xl as B,Yl as V,Zl as H,dd as U,dr as W,fd as te,gu as ne,id as re,jf as ie,ku as ae,md as oe,rr as se,sf as ce,un as le,vt as ue,ya as de,z as fe,zi as pe,zn as me}from"./src-BeE19PxU.js";import{t as G}from"./boxes-I78qynMn.js";import{Ar as K,Dr as he,Er as ge,Or as _e,Sr as ve,cr as ye,gr as be,jr as xe,kr as Se,lr as Ce,or as q,qt as we,sr as Te,vi as Ee,xr as De}from"./client-D5nV-lIF.js";import{t as Oe}from"./useTranslation-Bc5yH9V9.js";import{$ as ke,C as Ae,H as je,I as Me,S as Ne,Y as Pe,tt as Fe}from"./index-I1VJhtqM.js";import{t as Ie}from"./AdminSectionedPage-Dj5EzIqk.js";import{t as Le}from"./DeviceDoActionFields-DPIQv0Gp.js";import{E as Re,O as ze,t as Be}from"./CompositionEditor-Cv06FJwk.js";var Ve=_(`braces`,[[`path`,{d:`M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1`,key:`ezmyqa`}],[`path`,{d:`M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1`,key:`e1hn23`}]]),He=_(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),Ue=_(`ungroup`,[[`rect`,{width:`8`,height:`6`,x:`5`,y:`4`,rx:`1`,key:`nzclkv`}],[`rect`,{width:`8`,height:`6`,x:`11`,y:`14`,rx:`1`,key:`4tytwb`}]]),We=`const AUTOMATION_RECIPE =`,Ge=`// EJECTED from the visual automation editor — this file is now hand-owned.
2
- // The recipe that produced it was removed with it, on purpose: while it was
3
- // here the editor could re-open this block and overwrite everything below.`;function Ke(e){return e.includes(We)}function qe(e){let t=e.indexOf(We);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function Je(e){let t=qe(e);if(t===null)return{ok:!1,reason:`this block carries no AUTOMATION_RECIPE literal`};let n;try{n=JSON.parse(t.json)}catch(e){return{ok:!1,reason:`the embedded recipe is not readable JSON: ${e instanceof Error?e.message:String(e)}`}}let r=_e.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:`the embedded recipe does not match the recipe schema${e===void 0?``:` at ${e.path.join(`.`)}: ${e.message}`}`}}return{ok:!0,recipe:r.data}}function Ye(e){let t=qe(e);if(t===null)return e;let n=e.slice(t.literalEnd),r=/^\s*as\s+const/.exec(n),i=t.literalEnd+(r===null?0:r[0].length);return`${e.slice(0,t.declStart)}${Ge}${e.slice(i)}`}r();var Xe=6e4;function Ze(){let e=de({projection:`slim`});return o(()=>(e.data??[]).filter(e=>we(String(e.type))).map(e=>({id:e.id,name:e.name,stableId:e.stableId,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data])}function Qe(e){let t=g();return s({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:Xe,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function $e(e,t){return e.find(e=>e.cap===t)?.fields??[]}function J({children:e}){return d(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function et(e){let t=Qe(e.deviceId);if(t.data!==void 0)return $e(t.data,e.cap).find(t=>t.path===e.fieldPath)}function tt({value:e,devices:t,onChange:n}){let r=Qe(e.deviceId),a=r.data??[],o=$e(a,e.cap);return i(c,{children:[i(`label`,{className:`min-w-[10rem] flex-1`,children:[d(J,{children:`Device`}),d(C,{value:String(e.deviceId),onChange:e=>n({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:`Select a device…`},...t.map(e=>({value:String(e.id),label:e.name}))]})]}),i(`label`,{className:`min-w-[9rem] flex-1`,children:[d(J,{children:`Capability`}),d(C,{value:e.cap,disabled:e.deviceId===0,onChange:t=>n({...e,cap:t.target.value,fieldPath:``}),options:[{value:``,label:nt(e.deviceId,a.length,r.isLoading)},...a.map(e=>({value:e.cap,label:e.cap}))]})]}),i(`label`,{className:`min-w-[9rem] flex-1`,children:[d(J,{children:`Field`}),d(C,{value:e.fieldPath,disabled:e.cap===``,onChange:t=>n({...e,fieldPath:t.target.value}),options:[{value:``,label:o.length===0?`No readable fields`:`Select a field…`},...o.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function nt(e,t,n){return e===0?`Pick a device first`:n?`Reading this device…`:t===0?`This device reports no readable capabilities`:`Select a capability…`}var rt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function it(e){switch(e){case`boolean`:return[`eq`,`ne`];case`number`:return[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`];case`string`:case`enum`:return[`eq`,`ne`,`contains`,`in`];default:return rt}}function at(e){switch(e){case`eq`:return`is`;case`ne`:return`is not`;case`gt`:return`is above`;case`gte`:return`is at least`;case`lt`:return`is below`;case`lte`:return`is at most`;case`contains`:return`contains`;default:return`is one of`}}function ot(e){return it(e).map(e=>({value:e,label:at(e)}))}function st(e){switch(e){case`device-state`:return`A device field changes`;case`device-event`:return`An event happens`;case`schedule`:return`On a schedule`;default:return`Only when run by hand`}}var ct={triggers:[],actions:[]};function lt(e){switch(e){case`device-state`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};default:return{kind:`manual`}}}function ut(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
4
- `};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function dt(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function ft(){return{kind:`expression`,expr:``,bindings:{}}}function pt(e,t,n){return e.map((e,r)=>r===t?n:e)}function mt(e,t){return e.filter((e,n)=>n!==t)}function ht(e,t,n){let r=e[t];if(r===void 0)return e;let i=Math.min(Math.max(n,0),e.length-1);if(i===t)return e;let a=mt(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function gt(e,t){return{...e,triggers:[...t]}}function _t(e,t){return{...e,actions:[...t]}}var vt=[{value:`cap`,label:`Do something`},{value:`wait`,label:`Wait`},{value:`code`,label:`Run code`}];function yt({actions:e,devices:t,devicesState:n=`answered`,onChange:r}){return i(`div`,{className:`space-y-2`,children:[e.length===0&&d(`p`,{className:`text-xs text-warning`,children:`No actions yet. An automation that does nothing is not an automation.`}),e.map((a,o)=>i(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[i(`div`,{className:`flex flex-wrap items-end gap-2`,children:[d(W,{variant:`default`,children:o+1}),i(`label`,{className:`w-40`,children:[d(J,{children:`Step`}),d(C,{value:a.kind,onChange:t=>r(pt(e,o,ut(bt(t.target.value)))),options:vt.map(e=>({value:e.value,label:e.label}))})]}),i(`div`,{className:`ml-auto flex items-center gap-1`,children:[d(E,{variant:`ghost`,disabled:o===0,onClick:()=>r(ht(e,o,o-1)),title:`Run this step earlier`,children:d(N,{className:`h-3.5 w-3.5`})}),d(E,{variant:`ghost`,disabled:o===e.length-1,onClick:()=>r(ht(e,o,o+1)),title:`Run this step later`,children:d(ie,{className:`h-3.5 w-3.5`})}),d(E,{variant:`ghost`,onClick:()=>r(mt(e,o)),title:`Remove this step`,children:d(m,{className:`h-3.5 w-3.5`})})]})]}),a.kind===`wait`&&i(`label`,{className:`block w-32`,children:[d(J,{children:`Seconds`}),d(F,{type:`number`,min:0,max:300,value:String(a.seconds),onChange:t=>r(pt(e,o,{kind:`wait`,seconds:Number(t.target.value)}))})]}),a.kind===`code`&&i(`label`,{className:`block`,children:[d(J,{children:`Code`}),d(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:a.code,spellCheck:!1,onChange:t=>r(pt(e,o,{kind:`code`,code:t.target.value}))}),i(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:[`Compiled into this automation's own block by the same compiler as a script — not evaluated at run time. `,d(`code`,{children:`ctx`}),` and `,d(`code`,{children:`vars`}),` are in scope.`]})]}),a.kind===`cap`&&d(St,{action:a,devices:t,devicesState:n,onChange:t=>r(pt(e,o,t))})]},`${a.kind}-${String(o)}`)),i(`div`,{className:`flex items-center gap-2`,children:[i(E,{variant:`outline`,onClick:()=>r([...e,ut(`cap`)]),children:[d(U,{className:`h-4 w-4`}),` Step`]}),e.length>1&&d(`span`,{className:`text-xs text-foreground-subtle`,children:`Steps run in order and stop at the first failure.`})]})]})}function bt(e){return vt.find(t=>t.value===e)?.value??`cap`}function xt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function St({action:e,devices:t,devicesState:n,onChange:r}){return d(Le,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:xt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function Ct({value:e,field:t,onChange:n}){return t?.kind===`boolean`?d(C,{value:e===!0?`true`:`false`,onChange:e=>n(e.target.value===`true`),options:[{value:`true`,label:`true`},{value:`false`,label:`false`}]}):t?.kind===`enum`&&t.enumValues!==void 0&&t.enumValues.length>0?d(C,{value:String(e),onChange:e=>n(e.target.value),options:t.enumValues.map(e=>({value:e,label:e}))}):t?.kind===`number`?d(F,{type:`number`,value:typeof e==`number`?String(e):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&n(t)}}):d(F,{value:String(e),placeholder:`value`,onChange:e=>n(e.target.value)})}function wt({value:e,field:t,onChange:n}){return d(F,{value:e.join(`, `),placeholder:`one, two, three`,onChange:e=>{let r=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(t?.kind===`number`?r.map(e=>Number(e)).filter(e=>!Number.isNaN(e)):r)}})}function Tt(e){return typeof e==`object`}function Et(e){return Tt(e)?e[0]??``:e}function Dt(e){return Tt(e)?e:typeof e==`boolean`?[]:[e]}function Ot({leaf:e,devices:t,onChange:n}){let r={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=et(r),o=ot(a?.kind),s=e.operator===`in`,c=t=>{n({...e,deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath})},l=t=>{let r=kt(t,o);n({...e,operator:r,value:r===`in`?Dt(e.value):Et(e.value)})};return i(`div`,{className:`flex flex-wrap items-end gap-2`,children:[d(tt,{value:r,devices:t,onChange:c}),i(`label`,{className:`min-w-[8rem]`,children:[d(J,{children:`Comparison`}),d(C,{value:e.operator,onChange:e=>l(e.target.value),options:o.map(e=>({value:e.value,label:e.label}))})]}),i(`label`,{className:`min-w-[9rem] flex-1`,children:[d(J,{children:`Value`}),s?d(wt,{value:Dt(e.value),field:a,onChange:t=>n({...e,value:t})}):d(Ct,{value:Et(e.value),field:a,onChange:t=>n({...e,value:t})})]})]})}function kt(e,t){return t.find(t=>t.value===e)?.value??`eq`}var At={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function jt({leaf:e,devices:t,onChange:n}){let r=Object.entries(e.bindings),a=t=>{n({kind:`expression`,expr:e.expr,bindings:t})};return i(`div`,{className:`space-y-2`,children:[i(`label`,{className:`block`,children:[d(J,{children:`Expression`}),d(F,{value:e.expr,placeholder:`indoor - outdoor > 5`,onChange:t=>n({kind:`expression`,expr:t.target.value,bindings:e.bindings})}),d(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`})]}),i(`div`,{className:`space-y-1.5`,children:[r.length===0&&d(`p`,{className:`text-xs text-foreground-subtle`,children:`No names bound yet. An expression reads devices only through these.`}),r.map(([n,r])=>d(Mt,{alias:n,source:r,devices:t,onRename:t=>a(Rt(e.bindings,n,t)),onChange:t=>a({...e.bindings,[n]:t}),onRemove:()=>a(zt(e.bindings,n))},n)),i(E,{variant:`ghost`,onClick:()=>a({...e.bindings,[Lt(e.bindings)]:At}),children:[d(U,{className:`h-3.5 w-3.5`}),` Name`]})]})]})}function Mt({alias:e,source:t,devices:n,onRename:r,onChange:a,onRemove:o}){let s=t.kind===`literal`,c=s?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Ft(n,Pt(t)),cap:t.cap,fieldPath:t.fieldPath};return i(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[i(`label`,{className:`w-32`,children:[d(J,{children:`Name`}),d(F,{value:e,placeholder:`indoor`,onChange:e=>r(e.target.value)})]}),i(`label`,{className:`w-36`,children:[d(J,{children:`Reads`}),d(C,{value:s?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:At),options:[{value:`global`,label:`A device field`},{value:`literal`,label:`A constant`}]})]}),s?i(`label`,{className:`min-w-[9rem] flex-1`,children:[d(J,{children:`Constant`}),d(F,{value:t.value===null?``:String(t.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Nt(e.target.value)})})]}):d(tt,{value:c,devices:n,onChange:e=>a({kind:`global`,sourceStableId:It(n,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),d(E,{variant:`ghost`,onClick:o,title:`Remove this name`,children:d(m,{className:`h-3.5 w-3.5`})})]})}function Nt(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Pt(e){return e.kind===`global`?e.sourceStableId:``}function Ft(e,t){return e.find(e=>e.stableId===t)?.id??0}function It(e,t){return e.find(e=>e.id===t)?.stableId??``}function Lt(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function Rt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function zt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Y(e){return e.kind===`all`||e.kind===`any`}function X(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:Y(t)?t:{kind:`all`,children:[t]}}function Bt(e,t){return t===null||Y(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Vt(e){return Bt(e,X(e))}function Ht(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ht(e.child,r):null;if(!Y(e))return null;let i=e.children[n];return i===void 0?null:Ht(i,r)}function Z(e,t,n){if(t.length===0)return n(e);let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=Z(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!Y(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Z(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function Ut(e){return e===null?null:xe({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function Wt(e){let t=X(e);return{depth:t.children.length===0?0:Se(t),leaves:t.children.length===0?0:K(t),depthLimit:3,leafLimit:32}}function Gt(e,t){let n=Ut(t);return n===null?{ok:!0,recipe:Bt(e,t)}:{ok:!1,reason:n}}function Kt(e,t){let n=X(e);return Gt(e,{kind:n.kind,children:[...n.children,t]})}function qt(e,t,n){return Bt(e,Z(X(e),t,()=>n))}function Jt(e,t){return Bt(e,Z(X(e),t,()=>null))}function Yt(e,t,n){return Bt(e,Z(X(e),t,e=>Y(e)?{kind:n,children:e.children}:e))}function Xt(e,t){return Ht(X(e),t)===null?{ok:!1,reason:`that row is no longer there`}:Gt(e,Z(X(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function Zt(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function Qt(e,t,n){if(t.length<2)return{ok:!1,reason:`select at least two rows — a group of one is just the row`};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:`those rows are in different groups — a group can only be made from rows side by side`};let r=Zt(t[0]??[]);if(r===null)return{ok:!1,reason:`the root list cannot be grouped into itself`};let i=X(e),a=Ht(i,r.path);if(a===null||!Y(a))return{ok:!1,reason:`those rows are inside a NOT — remove it before grouping them`};let o=[...t.map(e=>e[e.length-1]??-1)].sort((e,t)=>e-t),s=o.map(e=>a.children[e]).filter(e=>e!==void 0);if(s.length!==o.length)return{ok:!1,reason:`one of the selected rows is no longer there`};let c=a.children.filter((e,t)=>!o.includes(t)),l=o[0]??0,u={kind:n,children:s},d={kind:a.kind,children:[...c.slice(0,l),u,...c.slice(l)]};return Gt(e,Z(i,r.path,()=>d))}function $t(e,t){if(t.length===0)return{ok:!1,reason:`the outer list is not a group — there is nothing to dissolve`};let n=X(e),r=Ht(n,t);if(r===null)return{ok:!1,reason:`that group is no longer there`};if(r.kind===`not`)return Gt(e,Z(n,t,()=>r.child));if(!Y(r))return{ok:!1,reason:`that row is a condition, not a group`};let i=Zt(t);if(i===null)return{ok:!1,reason:`that group has no parent to dissolve into`};let a=Ht(n,i.path);if(a===null||!Y(a))return{ok:!1,reason:`a group inside a NOT cannot be dissolved in place`};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return Gt(e,Z(n,i.path,()=>o))}r();var en=[{value:`all`,label:`ALL of`},{value:`any`,label:`ANY of`}];function tn(e){return e.join(`/`)}function nn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function rn({recipe:e,devices:t,onChange:n}){let[r,a]=l([]),[s,c]=l(null),u=X(e),f=Wt(e),p=o(()=>r.map(nn),[r]),m=e=>{if(!e.ok){c(e.reason);return}c(null),a([]),n(e.recipe)},h=Qt(e,p,`all`),g=Qt(e,p,`any`),_=p.length===1?Xt(e,p[0]??[]):{ok:!1,reason:`select exactly one row to negate`},v={devices:t,selected:new Set(r),onToggleSelect:e=>a(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(t,r)=>n(qt(e,t,r)),onRemove:t=>{a([]),n(Jt(e,t))},onSetKind:(t,r)=>n(Yt(e,t,r)),onUngroup:t=>m($t(e,t))};return i(`div`,{className:`space-y-2`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(W,{variant:`default`,children:`And only if`}),d(`div`,{className:`w-32`,children:d(C,{value:u.kind,onChange:t=>n(Yt(e,[],an(t.target.value))),options:en})}),i(`span`,{className:`text-xs text-foreground-subtle`,children:[`depth `,f.depth,`/`,f.depthLimit,` · `,f.leaves,`/`,f.leafLimit,` conditions`]})]}),u.children.length===0?d(`p`,{className:`text-xs text-foreground-subtle`,children:`No conditions. The actions run every time a trigger fires.`}):d(on,{container:u,path:[],handlers:v}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(E,{variant:`outline`,onClick:()=>m(Kt(e,dt())),title:`Compare one device field to a value`,children:[d(U,{className:`h-4 w-4`}),` Condition`]}),i(E,{variant:`outline`,onClick:()=>m(Kt(e,ft())),title:`Arithmetic across device fields — the bounded expression engine`,children:[d(Ve,{className:`h-4 w-4`}),` Expression`]}),d(`span`,{className:`mx-1 h-5 w-px bg-border`}),d(E,{variant:`ghost`,disabled:!h.ok,onClick:()=>m(h),title:h.ok?`All selected rows must be true`:h.reason,children:`Group as ALL`}),d(E,{variant:`ghost`,disabled:!g.ok,onClick:()=>m(g),title:g.ok?`Any one of the selected rows is enough`:g.reason,children:`Group as ANY`}),d(E,{variant:`ghost`,disabled:!_.ok,onClick:()=>m(_),title:_.ok?`Invert the selected row`:_.reason,children:`NOT`}),r.length>0&&i(`span`,{className:`text-xs text-foreground-subtle`,children:[r.length,` selected`]})]}),s!==null&&d(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:s})]})}function an(e){return e===`any`?`any`:`all`}function on({container:e,path:t,handlers:n}){return d(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>d(sn,{node:e,path:[...t,r],handlers:n},tn([...t,r])))})}function sn({node:e,path:t,handlers:n}){let r=tn(t),a=d(le,{checked:n.selected.has(r),onChange:()=>n.onToggleSelect(r),"aria-label":`Select this row for grouping`});return Y(e)?i(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[i(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,d(`div`,{className:`w-32`,children:d(C,{value:e.kind,onChange:e=>n.onSetKind(t,an(e.target.value)),options:en})}),i(E,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:`Dissolve this group, keeping its rows`,children:[d(Ue,{className:`h-3.5 w-3.5`}),` Ungroup`]}),d(E,{variant:`ghost`,onClick:()=>n.onRemove(t),title:`Delete this group and everything in it`,children:d(m,{className:`h-3.5 w-3.5`})})]}),d(`div`,{className:`pl-4`,children:d(on,{container:e,path:t,handlers:n})})]}):e.kind===`not`?i(`div`,{className:`rounded border border-border p-2`,children:[i(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,d(W,{variant:`warning`,children:`NOT`}),i(E,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:`Remove the NOT, keeping the row`,children:[d(Ue,{className:`h-3.5 w-3.5`}),` Remove NOT`]})]}),d(`div`,{className:`pl-4`,children:d(sn,{node:e.child,path:[...t,0],handlers:n})})]}):i(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[d(`div`,{className:`pt-6`,children:a}),d(`div`,{className:`min-w-0 flex-1`,children:e.kind===`condition`?d(Ot,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)}):d(jt,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)})}),d(E,{variant:`ghost`,onClick:()=>n.onRemove(t),title:`Remove this condition`,children:d(m,{className:`h-3.5 w-3.5`})})]})}r();function cn({code:e,error:t,canEject:n,ejecting:r,onEject:a}){let[o,s]=l(!1),c=se(),u=async()=>{await c({title:`Eject to code — this cannot be undone`,message:`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`,confirmLabel:`Eject to code`,cancelLabel:`Keep it visual`,variant:`warning`})&&a()};return i(`div`,{className:`rounded border border-border`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[i(E,{variant:`ghost`,onClick:()=>s(!o),children:[d(o?p:h,{className:`h-4 w-4`}),`Generated code`]}),d(`span`,{className:`text-xs text-foreground-subtle`,children:`Derived from the recipe above — regenerated on every save, never edited here.`}),i(E,{className:`ml-auto`,variant:`ghost`,disabled:!n||e===null||r,onClick:()=>void u(),title:n?`Take permanent ownership of this code as a script`:`Save the automation first — there is no stored block to eject yet`,children:[d(Fe,{className:`h-4 w-4`}),` Eject to code`]})]}),o&&d(`div`,{className:`border-t border-border p-3`,children:e===null?d(`p`,{className:`text-xs text-warning`,children:t??`The recipe is not complete enough to generate a block yet.`}):d(A,{maxHeight:420,children:e})})]})}var ln=[`device-state`,`device-event`,`schedule`,`manual`],un=Object.values(Ee).sort((e,t)=>e.localeCompare(t));function dn({triggers:e,devices:t,onChange:n}){return i(`div`,{className:`space-y-2`,children:[e.length===0&&d(`p`,{className:`text-xs text-warning`,children:`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`}),e.map((r,i)=>d(fn,{trigger:r,devices:t,position:i,onChange:t=>n(pt(e,i,t)),onRemove:()=>n(mt(e,i))},`${r.kind}-${String(i)}`)),i(E,{variant:`outline`,onClick:()=>n([...e,lt(`device-state`)]),title:`Add another way this automation can start`,children:[d(U,{className:`h-4 w-4`}),` Trigger`]})]})}function fn({trigger:e,devices:t,position:n,onChange:r,onRemove:a}){return i(`div`,{className:`rounded border border-border p-3`,children:[i(`div`,{className:`flex flex-wrap items-end gap-2`,children:[d(W,{variant:`default`,children:n===0?`When`:`or when`}),i(`label`,{className:`min-w-[13rem] flex-1`,children:[d(J,{children:`Trigger`}),d(C,{value:e.kind,onChange:e=>r(lt(pn(e.target.value))),options:ln.map(e=>({value:e,label:st(e)}))})]}),d(E,{variant:`ghost`,onClick:a,title:`Remove this trigger`,children:d(m,{className:`h-4 w-4`})})]}),i(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[e.kind===`device-state`&&d(hn,{trigger:e,devices:t,onChange:r}),e.kind===`device-event`&&d(_n,{trigger:e,devices:t,onChange:r}),e.kind===`schedule`&&i(`label`,{className:`min-w-[14rem] flex-1`,children:[d(J,{children:`Cron expression`}),d(F,{value:e.cron,placeholder:`0 30 23 * * *`,onChange:e=>r({kind:`schedule`,cron:e.target.value})}),i(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:[`Six fields, seconds first. `,d(`code`,{children:`0 30 23 * * *`}),` is every night at 23:30.`]})]}),e.kind===`manual`&&i(`p`,{className:`text-xs text-foreground-subtle`,children:[`Runs only when someone presses `,d(`strong`,{children:`Run actions`}),`. The conditions are still evaluated — a manual run is a run, not an override.`]})]})]})}function pn(e){return ln.find(t=>t===e)??`manual`}function mn(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function hn({trigger:e,devices:t,onChange:n}){let r={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=et(r),o={...e.becomes===void 0?{}:{becomes:e.becomes},...e.edge===void 0?{}:{edge:e.edge},...e.forMs===void 0?{}:{forMs:e.forMs},...e.debounceMs===void 0?{}:{debounceMs:e.debounceMs}};return i(c,{children:[d(tt,{value:r,devices:t,onChange:e=>n(mn(e,o))}),i(`div`,{className:`min-w-[11rem] flex-1`,children:[d(J,{children:`Becomes`}),i(`div`,{className:`flex items-center gap-2`,children:[i(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[d(le,{checked:e.becomes===void 0,onChange:e=>n(mn(r,{...o,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),`any change`]}),e.becomes!==void 0&&d(Ct,{value:e.becomes,field:a,onChange:e=>n(mn(r,{...o,becomes:e}))})]})]}),i(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[d(le,{checked:e.edge===!0,onChange:e=>n(mn(r,{...o,...e.target.checked?{edge:!0}:{edge:void 0}}))}),`only on a change`]}),i(`label`,{className:`w-28`,children:[d(J,{children:`Held for (s)`}),d(F,{type:`number`,min:0,value:e.forMs===void 0?``:String(e.forMs/1e3),placeholder:`0`,onChange:e=>n(mn(r,{...o,forMs:gn(e.target.value)}))})]}),i(`label`,{className:`w-28`,children:[d(J,{children:`Debounce (s)`}),d(F,{type:`number`,min:0,value:e.debounceMs===void 0?``:String(e.debounceMs/1e3),placeholder:`0`,onChange:e=>n(mn(r,{...o,debounceMs:gn(e.target.value)}))})]})]})}function gn(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function _n({trigger:e,devices:t,onChange:n}){return i(c,{children:[i(`label`,{className:`min-w-[15rem] flex-1`,children:[d(J,{children:`Event category`}),d(C,{value:e.category,onChange:t=>n({kind:`device-event`,category:t.target.value,...e.deviceId===void 0?{}:{deviceId:e.deviceId}}),options:[{value:``,label:`Select an event…`},...un.map(e=>({value:e,label:e}))]})]}),i(`label`,{className:`min-w-[11rem] flex-1`,children:[d(J,{children:`From device`}),d(C,{value:e.deviceId===void 0?``:String(e.deviceId),onChange:t=>n({kind:`device-event`,category:e.category,...t.target.value===``?{}:{deviceId:Number(t.target.value)}}),options:[{value:``,label:`Any device`},...t.map(e=>({value:String(e.id),label:e.name}))]})]})]})}r();var vn=`hub`;function yn({existing:e,initialRecipe:t,saving:n,saveError:r,ejecting:a,onSave:s,onEject:c,onCancel:u}){let[f,p]=l(e?.name??``),[m,h]=l(()=>Vt(t)),[g,_]=l(!1),y=Ze(),b=xe(m),x=o(()=>xn(m),[m]),C=o(()=>Sn(f.trim()===``?`Untitled automation`:f.trim(),m),[f,m]),w=f.trim()===``,T=w||b!==null||x!==null||C.code===null;return i(`div`,{className:`space-y-4`,children:[d(`div`,{className:`flex flex-wrap items-center gap-2`,children:d(W,{variant:`info`,children:`runs on the hub`})}),i(`label`,{className:`block max-w-md text-sm`,children:[d(`span`,{className:`text-foreground-subtle`,children:`Name`}),d(F,{className:`mt-1`,value:f,onChange:e=>p(e.target.value),placeholder:`What this automation does`})]}),d(bn,{step:`1`,title:`When`,subtitle:`Any one of these starts a run.`,children:d(dn,{triggers:m.triggers,devices:y,onChange:e=>h(gt(m,e))})}),d(bn,{step:`2`,title:`And only if`,subtitle:`Checked after a trigger fires. Nothing runs unless this is true.`,children:d(rn,{recipe:m,devices:y,onChange:h})}),d(bn,{step:`3`,title:`Then`,subtitle:`In this order, stopping at the first failure.`,children:d(yt,{actions:m.actions,devices:y,onChange:e=>h(_t(m,e))})}),d(cn,{code:C.code,error:C.error,canEject:e!==null,ejecting:a,onEject:c}),b!==null&&d(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:b}),b===null&&x!==null&&d(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),r!==null&&d(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:r}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(E,{onClick:()=>{C.code!==null&&s({name:f.trim(),code:C.code,enabled:e?.enabled??!0,placement:vn})},disabled:n||T,children:[n&&d(S,{className:`h-4 w-4 animate-spin`}),` Save`]}),i(E,{variant:`ghost`,onClick:()=>_(!g),disabled:e===null,title:e===null?`Logs appear once the automation has been saved and started`:`Show this automation's process logs`,"data-testid":`automation-logs-toggle`,children:[d(v,{className:`h-4 w-4`}),` Logs `,g?`▾`:`▸`]}),d(E,{variant:`ghost`,onClick:u,disabled:n,children:`Close`}),w&&d(W,{variant:`warning`,children:`Name required`})]}),g&&e!==null&&i(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[i(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:[`Logs — `,d(`code`,{children:q(e.id)})]}),d(L,{addonId:q(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function bn({step:e,title:t,subtitle:n,children:r}){return i(`section`,{className:`border-l-2 border-border pl-4`,children:[i(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[d(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:e}),d(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:t}),d(`span`,{className:`text-xs text-foreground-subtle`,children:n})]}),r]})}function xn(e){let t=_e.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?`this automation is not complete yet`:`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Sn(e,t){try{return{code:he({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Cn(e){if(!e.enabled)return{tone:`idle`,label:`Disabled`,detail:`Not started — the block is turned off.`};switch(e.status){case`running`:return{tone:`ok`,label:`Running`,detail:`One process, supervised.`};case`starting`:return{tone:`pending`,label:`Starting`,detail:e.lastError??`Waiting for the process to report ready.`};case`failed`:return{tone:`error`,label:`Failed`,detail:e.lastError??`Failed with no reason recorded — check the node logs.`};default:return{tone:`error`,label:`Not running`,detail:e.lastError??`Enabled but no process is running. The supervisor reconciles every 15s; if this persists, the node may not be running a block supervisor.`}}}function wn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Tn(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function En(e){let t=e=>{let t=Cn(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function Dn(e){if(e.length===0)return`No blocks yet.`;let t=e.filter(e=>Cn(e).tone===`error`).length,n=e.filter(e=>Cn(e).tone===`ok`).length,r=[`${String(e.length)} block${e.length===1?``:`s`}`];return n>0&&r.push(`${String(n)} running`),t>0&&r.push(`${String(t)} NOT running`),r.join(` · `)}function On({block:e,busy:t,confirming:n,logsOpen:r,unreadable:a,onEdit:o,onToggle:s,onToggleLogs:c,onAskDelete:l,onCancelDelete:u,onConfirmDelete:f}){let p=Cn(e),h=ue(e.updatedAt);return i(`li`,{className:`flex flex-col gap-2 p-3`,children:[i(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[i(`div`,{className:`min-w-0 flex-1`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`span`,{className:`truncate font-medium`,children:e.name}),d(W,{variant:wn(p.tone),children:p.label}),h!==null&&i(`span`,{className:`text-xs text-foreground-subtle`,children:[`edited `,h]})]}),d(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:p.detail}),a!==null&&i(`p`,{className:`mt-0.5 text-xs text-warning`,children:[`Its recipe cannot be read (`,a,`), so it cannot be opened visually. The code is intact and still running — edit it as a script.`]})]}),n?i(`div`,{className:`flex justify-end gap-1`,children:[d(`span`,{className:`text-xs text-foreground-subtle`,children:`Delete this automation?`}),d(E,{variant:`danger`,onClick:e=>{e.stopPropagation(),f()},disabled:t,children:`Delete`}),d(E,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},children:`Cancel`})]}):i(`div`,{className:`flex justify-end gap-1`,children:[d(E,{variant:`ghost`,onClick:e=>{e.stopPropagation(),o()},disabled:a!==null,title:a===null?`Edit`:`This block cannot be opened visually`,children:d(oe,{className:`h-4 w-4`})}),i(V,{children:[d(H,{children:d(E,{variant:`ghost`,disabled:!0,title:`Run actions`,children:d(te,{className:`h-4 w-4`})})}),d(B,{children:`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`})]}),d(E,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:`Logs`,children:d(v,{className:`h-4 w-4`})}),d(E,{variant:`ghost`,onClick:t=>{t.stopPropagation(),s(!e.enabled)},disabled:t,title:e.enabled?`Disable`:`Enable`,children:e.enabled?`Disable`:`Enable`}),d(E,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:`Delete`,children:d(m,{className:`h-4 w-4`})})]})]}),r&&i(`div`,{className:`rounded border border-border`,children:[i(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:[`Logs — `,d(`code`,{children:q(e.id)})]}),d(L,{addonId:q(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function kn({onCreate:e}){return d(me,{children:i(`div`,{className:`space-y-2 p-4`,children:[d(`p`,{className:`text-sm text-foreground`,children:`No automations yet.`}),d(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`}),d(E,{onClick:e,children:`New automation`})]})})}r();var An=[`coreBlocks`,`list`],jn=5e3;function Mn(e){return e instanceof Error?e.message:String(e)}function Nn({onOpenScripts:e,initialBlockId:n,onBlockIdChange:r,createRequested:a=!1,onCreateConsumed:c}){let p=g(),{state:m,openNew:h,openEdit:_,close:v}=D({editKey:`block`,newKey:`new`}),[y,b]=l(null),[x,S]=l(null),[C,E]=l(null),O=t(null),k=m.mode!==`closed`;f(()=>{a&&(b(null),h(),r?.(null),c?.())},[a,c,r,h]);let A=s({queryKey:An,refetchInterval:jn,queryFn:async()=>(await p.trpcClient.coreBlocks.list.query({})).blocks}),j=()=>{A.refetch()},M=A.data;f(()=>{n===void 0||O.current===n||M?.find(e=>e.id===n&&Ke(e.code))!==void 0&&(O.current=n,_(n),r?.(n))},[n,M,_,r]);let N=u({mutationFn:e=>p.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),r?.(e.block.id),j()}}),P=u({mutationFn:e=>p.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),r?.(e.block.id),j()}}),F=u({mutationFn:e=>p.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{S(null),j()}}),I=u({mutationFn:e=>p.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:j}),L=u({mutationFn:e=>p.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Ye(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:t=>{v(),b(null),j(),e(t.block.id)}}),R=A.data,z=En((R??[]).filter(e=>Ke(e.code))),B=R!==void 0&&z.length===0,V=m.mode===`edit`?z.find(e=>e.id===m.id)??(y!==null&&y.id===m.id?y:null):null,H=m.mode===`new`||V===null?null:Tn(z,V),U=H===null?null:Je(H.code),W=N.error===null?P.error===null?L.error===null?null:Mn(L.error):Mn(P.error):Mn(N.error),te=o(()=>[{key:`row`,header:`Automation`,nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=Je(e.code);return d(`ul`,{className:`list-none`,children:d(On,{block:e,busy:I.isPending||F.isPending,confirming:x===e.id,logsOpen:C===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),r?.(e.id)},onToggle:t=>I.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>E(C===e.id?null:e.id),onAskDelete:()=>S(e.id),onCancelDelete:()=>S(null),onConfirmDelete:()=>F.mutate(e.id)})})},sortValue:e=>e.name}],[x,C,r,_,F,I]);return i(`div`,{className:`space-y-3`,children:[d(`p`,{className:`text-xs text-foreground-subtle`,children:R===void 0?``:Dn(z)}),A.error!=null&&d(w,{title:`Could not read the automations`,message:Mn(A.error),onRetry:j}),B?d(kn,{onCreate:()=>{b(null),h(),r?.(null)}}):d(T,{columns:te,rows:z,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ee,mobileMode:`scroll`,emptyMessage:R===void 0?`Loading automations…`:`No automations yet.`,onRowClick:e=>{b(e),_(e.id),r?.(e.id)}}),d(fe,{open:k,onClose:()=>{N.reset(),P.reset(),L.reset(),b(null),v(),r?.(null)},title:H===null?`New automation`:`Edit ${H.name}`,icon:ne,width:`xl`,testId:`automation-editor-panel`,children:d(yn,{existing:H,initialRecipe:U!==null&&U.ok?U.recipe:ct,saving:N.isPending||P.isPending,saveError:W,ejecting:L.isPending,onSave:e=>{H===null?N.mutate(e):P.mutate({blockId:H.id,block:e})},onEject:()=>{H!==null&&L.mutate(H)},onCancel:()=>{N.reset(),P.reset(),L.reset(),b(null),v(),r?.(null)}},H?.id??`new`)}),F.error!=null&&d(w,{message:Mn(F.error)}),I.error!=null&&d(w,{message:Mn(I.error)})]})}function Pn(e){return{state:`answered`,byRef:new Map(e.map(e=>[De(e),e]))}}function Fn(e,t){if(e.state!==`unanswered`)return e.byRef.get(De(t))??null}function In(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Ln(e){return ve(e).map(e=>e.source)}function Rn(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...Ln(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Ln(e))}let r=new Set;return n.filter(e=>{let t=De(e);return r.has(t)?!1:(r.add(t),!0)})}function zn(e,t){return`${String(e)} ${t}${e===1?``:`s`}`}function Bn(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:`Running`,reason:null};let r=[...t.length>0?[`${zn(t.length,`field`)} unavailable`]:[],...n.length>0?[`${zn(n.length,`field`)} stale`]:[]].join(`, `),i=t[0]??n[0];return{tone:`pending`,label:`Running`,reason:`${r}${i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??`no reason recorded`}`}`}}function Vn(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Bn(e);case`degraded`:return{tone:`pending`,label:`Degraded`,reason:n??`Running with a field handed back to the device; no reason recorded.`};case`starting`:return{tone:`pending`,label:`Starting`,reason:n};case`failed`:return{tone:`error`,label:`Failed`,reason:n??`Failed with no reason recorded — check the composer logs.`};default:return{tone:`error`,label:`Not running`,reason:n??`Enabled but the composer is not running it.`}}}function Hn(e){let{block:t,state:n}=e;return t.enabled?n.kind===`unreachable`?{tone:`pending`,label:`Unknown`,reason:`The composer could not be asked: ${n.error}`}:n.state===null?{tone:`pending`,label:`Not reported yet`,reason:`The composer holds no record of this block yet (stored status: ${t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`}).`}:Vn(n.state,t.lastError):{tone:`idle`,label:`Off`,reason:null}}function Un(e){return De(e)}function Wn(e,t){let n=Fn(t,e);return{key:De(e),label:n?n.name:Un(e),presence:In(n),deviceId:n?n.id:null}}function Gn(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Kn(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:be(e.block.id),a=De(i),o=Rn(e).filter(e=>De(e)!==a).map(e=>Wn(e,t)),s=n.features.map(e=>e.enabled===!1?`${e.cap} (off)`:e.cap),c=Fn(t,i),l=Gn(e),u=Hn(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=In(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Un(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function qn(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Jn(e,t){return qn(e)-qn(t)||e.name.localeCompare(t.name)}function Yn(e,t){let n=e.flatMap(e=>{let n=Kn(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Jn),customizations:n.filter(e=>e.kind===`customization`).toSorted(Jn)}}r();var Xn=1e4;function Zn(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Qn(e){let t=e.trim();return t===``?{}:{name:t}}function $n(){let e=je();return e.data===void 0?{state:`unanswered`,reason:e.error==null?`the device list has not answered yet`:`the device list could not be read (${Zn(e.error)})`}:Pn(e.data)}function er({createRequested:e=!1,onCreateConsumed:t}={}){let n=k({},{refetchInterval:Xn}),r=$n(),a=D({editKey:`block`,newKey:`new`});f(()=>{e&&(a.openNew(),t?.())},[e]);let o=n.data;if(n.error!=null&&o===void 0)return d(w,{title:`Could not read the compositions`,message:Zn(n.error),onRetry:()=>void n.refetch()});if(o===void 0)return d(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:`Loading compositions…`});if(o.state===`not-loaded`)return d(me,{children:i(`div`,{className:`space-y-1 p-4`,children:[d(`p`,{className:`text-sm text-warning`,children:`The composition store has not been read yet.`}),i(`p`,{className:`text-xs text-foreground-subtle`,children:[`This is not the same as having none — the list appears once the hub has read it (`,o.reason,`).`]})]})});let s=n.error==null?null:Zn(n.error),l=Yn(o.views,r),u=a.state.mode===`edit`?a.state.id:null,p=a.state.mode===`new`;return i(c,{children:[d(rr,{lists:l,fleet:r,refreshError:s,onEditComposed:e=>a.openEdit(e)}),d(fe,{open:p||u!==null,onClose:()=>a.close(),title:p?`New composed device`:`Edit composed device`,icon:G,width:`xl`,testId:`composed-device-editor`,children:p?d(tr,{onClose:()=>a.close(),onCreated:e=>{n.refetch(),a.openEdit(e)}}):u===null?null:d(nr,{blockId:u,onClose:()=>a.close(),onSaved:()=>void n.refetch()})})]})}function tr({onClose:e,onCreated:t}){let n=y();return d(Be,{initial:ze(ge.Sensor),blockId:null,deviceType:ge.Sensor,nativeCaps:null,targetFields:null,showTemplates:!0,onCancel:e,save:async(e,r)=>{try{let{block:i}=await n.mutateAsync({block:{...Qn(r),enabled:!0,composition:e}});return t(i.id),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}})}function nr({blockId:e,onClose:t,onSaved:n}){let{t:r}=Oe(),i=z(),a=P({blockId:e});if(a.status===`pending`)return d(`p`,{role:`status`,children:r(`compositionEditor.loading`)});if(a.status===`error`)return d(w,{title:r(`compositionEditor.loadFailed`),message:a.error.message});if(a.data.state===`not-loaded`)return d(`p`,{role:`status`,children:r(`customize.status.notLoaded`,{reason:a.data.reason})});let o=a.data.view;if(o===null)return d(`p`,{children:r(`compositionEditor.notFound`,{blockId:e})});let s=Te(o.block);if(s===null)return d(`p`,{children:r(`compositionEditor.notComposition`)});if(s.target.kind===`existing`){let e=o.state.kind===`answered`?o.state.state?.deviceId??null:null;return e===null?d(`p`,{children:r(`compositionEditor.customizationUnknownDevice`)}):d(Pe,{className:`text-primary`,to:Ne(e),children:r(`compositionEditor.openOnDevice`)})}return d(Be,{initial:Re(s,o.block.name),blockId:o.block.id,deviceType:s.target.type,nativeCaps:null,targetFields:null,onCancel:t,save:async(e,t)=>{try{return await i.mutateAsync({blockId:o.block.id,expectedUpdatedAt:o.block.updatedAt,block:{...Qn(t),composition:e}}),await a.refetch(),n(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}},`${o.block.id}@${o.block.updatedAt}`)}function rr({lists:e,fleet:t,refreshError:n,onEditComposed:r}){return i(`div`,{className:`space-y-4`,children:[n!==null&&i(`p`,{className:`text-xs text-warning`,children:[`Showing the last answer — the latest refresh failed: `,n]}),t.state===`unanswered`&&i(`p`,{className:`text-xs text-warning`,children:[`Device names are shown as references: `,t.reason,`. No source is marked missing until it has.`]}),d(ir,{title:`Composed devices`,hint:`A new device whose state is derived from other devices.`,rows:e.composed,nameHeader:`Name`,emptyMessage:`No composed devices.`,kind:`composed`,onEditComposed:r}),d(ir,{title:`Customizations`,hint:`Fields added to or replaced on an existing device — one per device, edited from the device.`,rows:e.customizations,nameHeader:`Device`,emptyMessage:`No customizations.`,kind:`customization`,onEditComposed:r})]})}function ir({title:e,hint:t,rows:n,nameHeader:r,emptyMessage:a,kind:o,onEditComposed:s}){return i(`section`,{className:`space-y-2`,"aria-label":e,children:[i(`div`,{children:[d(`h3`,{className:`font-medium`,children:e}),d(`p`,{className:`text-xs text-foreground-subtle`,children:t})]}),d(me,{variant:`flat`,className:`p-0`,children:d(T,{columns:ar(r,o,s),rows:n,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,mobileMode:`scroll`,maxBodyHeight:ee,emptyMessage:a,onRowClick:o===`composed`?e=>s(e.blockId):void 0})})]})}function ar(e,t,n){let r=[{key:`name`,header:e,sortValue:e=>e.name.toLowerCase(),render:e=>d(or,{row:e})},{key:`type`,header:`Type`,sortValue:e=>e.type,render:e=>d(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??`unknown`})},{key:`state`,header:`State`,nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:e=>i(`div`,{className:`space-y-0.5`,children:[d(W,{variant:wn(e.state.tone),children:e.state.label}),e.state.reason!==null&&d(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:e.state.reason})]})},{key:`sources`,header:`Sources`,nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>d(cr,{sources:e.sources})}];return t===`composed`&&r.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>d(`div`,{className:`flex justify-end gap-1`,children:d(E,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),n(e.blockId)},children:`Edit`})})}),r}function or({row:e}){return i(`div`,{className:`space-y-0.5`,children:[d(sr,{row:e}),e.namePresence===`missing`&&d(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:`device missing`}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.features.join(`, `)})]})}function sr({row:e}){return e.kind===`composed`?d(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?i(`span`,{className:`text-xs text-foreground-subtle`,children:[e.name,` — device not reported yet`]}):d(Pe,{to:Ne(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function cr({sources:e}){return e.length===0?d(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):d(`ul`,{className:`space-y-0.5`,children:e.map(e=>i(`li`,{className:`text-xs`,children:[e.deviceId===null?d(`span`,{className:e.presence===`missing`?`text-danger`:`text-foreground`,children:e.label}):d(Pe,{to:`/devices/${String(e.deviceId)}`,className:`hover:underline`,children:e.label}),e.presence===`missing`&&d(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:`missing`})]},e.key))})}function lr(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ur(e){if(Array.isArray(e))return e}function dr(e,t,n){return(t=br(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fr(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function pr(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
5
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function hr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?mr(Object(n),!0).forEach(function(t){dr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function gr(e,t){if(e==null)return{};var n,r,i=_r(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function _r(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function vr(e,t){return ur(e)||fr(e,t)||xr(e,t)||pr()}function yr(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function br(e){var t=yr(e,`string`);return typeof t==`symbol`?t:t+``}function xr(e,t){if(e){if(typeof e==`string`)return lr(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?lr(e,t):void 0}}function Sr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Cr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cr(Object(n),!0).forEach(function(t){Sr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Er(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function Dr(e){return{}.toString.call(e).includes(`Object`)}function Or(e){return!Object.keys(e).length}function kr(e){return typeof e==`function`}function Ar(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function jr(e,t){return Dr(t)||Q(`changeType`),Object.keys(t).some(function(t){return!Ar(e,t)})&&Q(`changeField`),t}function Mr(e){kr(e)||Q(`selectorType`)}function Nr(e){kr(e)||Dr(e)||Q(`handlerType`),Dr(e)&&Object.values(e).some(function(e){return!kr(e)})&&Q(`handlersType`)}function Pr(e){e||Q(`initialIsRequired`),Dr(e)||Q(`initialType`),Or(e)&&Q(`initialContent`)}function Fr(e,t){throw Error(e[t]||e.default)}var Q=Er(Fr)({initialIsRequired:`initial state is required`,initialType:`initial state should be an object`,initialContent:`initial state shouldn't be an empty object`,handlerType:`handler should be an object or a function`,handlersType:`all handlers should be a functions`,selectorType:`selector should be a function`,changeType:`provided value of changes should be an object`,changeField:`it seams you want to change a field in the state which is not specified in the "initial" state`,default:"an unknown error accured in `state-local` package"}),Ir={changes:jr,selector:Mr,handler:Nr,initial:Pr};function Lr(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ir.initial(e),Ir.handler(t);var n={current:e},r=Er(Br)(n,t),i=Er(zr)(n),a=Er(Ir.changes)(e),o=Er(Rr)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Ir.selector(e),e(n.current)}function c(e){Tr(r,i,a,o)(e)}return[s,c]}function Rr(e,t){return kr(t)?t(e.current):t}function zr(e,t){return e.current=wr(wr({},e.current),t),t}function Br(e,t,n){return kr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var Vr={create:Lr},Hr={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Ur(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function Wr(e){return{}.toString.call(e).includes(`Object`)}function Gr(e){return e||Yr(`configIsRequired`),Wr(e)||Yr(`configType`),e.urls?(Kr(),{paths:{vs:e.urls.monacoBase}}):e}function Kr(){console.warn(Jr.deprecation)}function qr(e,t){throw Error(e[t]||e.default)}var Jr={configIsRequired:`the configuration object is required`,configType:`the configuration object should be an object`,default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
6
- You are using deprecated way of configuration.
7
-
8
- Instead of using
9
- monaco.config({ urls: { monacoBase: '...' } })
10
- use
11
- monaco.config({ paths: { vs: '...' } })
12
-
13
- For more please check the link https://github.com/suren-atoyan/monaco-loader#config
14
- `},Yr=Ur(qr)(Jr),Xr={config:Gr},Zr=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Qr(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Qr(e[n],t[n]))}),hr(hr({},e),t)}var $r={type:`cancelation`,msg:`operation is manually canceled`};function ei(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r($r):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var ti=[`monaco`],ni=vr(Vr.create({config:Hr,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),ri=ni[0],ii=ni[1];function ai(e){var t=Xr.config(e),n=t.monaco,r=gr(t,ti);ii(function(e){return{config:Qr(e.config,r),monaco:n}})}function oi(){var e=ri(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(ii({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),ei(pi);if(window.monaco&&window.monaco.editor)return di(window.monaco),e.resolve(window.monaco),ei(pi);Zr(si,li)(ui)}return ei(pi)}function si(e){return document.body.appendChild(e)}function ci(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function li(e){var t=ri(function(e){return{config:e.config,reject:e.reject}}),n=ci(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function ui(){var e=ri(function(e){return{config:e.config,resolve:e.resolve,reject:e.reject}}),t=window.require;t.config(e.config),t([`vs/editor/editor.main`],function(t){var n=t.m||t;di(n),e.resolve(n)},function(t){e.reject(t)})}function di(e){ri().monaco||ii({monaco:e})}function fi(){return ri(function(e){return e.monaco})}var pi=new Promise(function(e,t){return ii({resolve:e,reject:t})}),mi={config:ai,init:oi,__getMonacoInstance:fi};r();var hi={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},gi={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function _i({children:e}){return a.createElement(`div`,{style:gi.container},e)}var vi=_i;function yi({width:e,height:t,isEditorReady:n,loading:r,_ref:i,className:o,wrapperProps:s}){return a.createElement(`section`,{style:{...hi.wrapper,width:e,height:t},...s},!n&&a.createElement(vi,null,r),a.createElement(`div`,{ref:i,style:{...hi.fullWidth,...!n&&hi.hide},className:o}))}var bi=n(yi);function xi(e){f(e,[])}var Si=xi;function Ci(e,n,r=!0){let i=t(!0);f(i.current||!r?()=>{i.current=!1}:e,n)}var $=Ci;function wi(){}function Ti(e,t,n,r){return Ei(e,r)||Di(e,t,n,r)}function Ei(e,t){return e.editor.getModel(Oi(e,t))}function Di(e,t,n,r){return e.editor.createModel(t,n,r?Oi(e,r):void 0)}function Oi(e,t){return e.Uri.parse(t)}function ki({original:n,modified:r,language:i,originalLanguage:o,modifiedLanguage:s,originalModelPath:c,modifiedModelPath:u,keepCurrentOriginalModel:d=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=wi,onMount:S=wi}){let[C,w]=l(!1),[T,E]=l(!0),D=t(null),O=t(null),k=t(null),A=t(S),j=t(x),M=t(!1);Si(()=>{let e=mi.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let e=D.current.getOriginalEditor(),t=Ti(O.current,n||``,o||i||`text`,c||``);t!==e.getModel()&&e.setModel(t)}},[c],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Ti(O.current,r||``,s||i||`text`,u||``);t!==e.getModel()&&e.setModel(t)}},[u],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{D.current?.getModel()?.original.setValue(n||``)},[n],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,s||i||`text`)},[i,o,s],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=e(()=>{if(!O.current)return;j.current(O.current);let e=Ti(O.current,n||``,o||i||`text`,c||``),t=Ti(O.current,r||``,s||i||`text`,u||``);D.current?.setModel({original:e,modified:t})},[i,r,s,n,o,c,u]),P=e(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);f(()=>{C&&A.current(D.current,O.current)},[C]),f(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();d||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return a.createElement(bi,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}n(ki);function Ai(e){let n=t();return f(()=>{n.current=e},[e]),n.current}var ji=Ai,Mi=new Map;function Ni({defaultValue:n,defaultLanguage:r,defaultPath:i,value:o,language:s,path:c,theme:u=`light`,line:d,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=wi,onMount:C=wi,onChange:w,onValidate:T=wi}){let[E,D]=l(!1),[O,k]=l(!0),A=t(null),j=t(null),M=t(null),N=t(C),P=t(S),F=t(),I=t(o),L=ji(c),R=t(!1),ee=t(!1);Si(()=>{let e=mi.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?B():e.cancel()}),$(()=>{let e=Ti(A.current,n||o||``,r||s||``,c||i||``);e!==j.current?.getModel()&&(g&&Mi.set(L,j.current?.saveViewState()),j.current?.setModel(e),g&&j.current?.restoreViewState(Mi.get(c)))},[c],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(ee.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),ee.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&s&&A.current?.editor.setModelLanguage(e,s)},[s],E),$(()=>{d!==void 0&&j.current?.revealLine(d)},[d],E),$(()=>{A.current?.editor.setTheme(u)},[u],E);let z=e(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let e=c||i,t=Ti(A.current,o||n||``,r||s||``,e||``);j.current=A.current?.editor.create(M.current,{model:t,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(Mi.get(e)),A.current.editor.setTheme(u),d!==void 0&&j.current.revealLine(d),D(!0),R.current=!0}},[n,r,i,o,s,c,m,h,g,u,d]);f(()=>{E&&N.current(j.current,A.current)},[E]),f(()=>{!O&&!E&&z()},[O,E,z]),I.current=o,f(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{ee.current||w(j.current.getValue(),e)}))},[E,w]),f(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function B(){F.current?.dispose(),_?g&&Mi.set(c,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return a.createElement(bi,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var Pi=n(Ni);r();function Fi(e,t){let n=[];for(let[r,i]of Object.entries(e))r!==t&&(n.push({filePath:`file:///${r}`,content:i}),r.endsWith(`.ts`)&&n.push({filePath:`file:///${r.slice(0,-3)}.js`,content:i}));return n}var Ii={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Li(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Ii}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function Ri({value:n,onChange:r,extraLibs:i=[],path:a=`file:///block.ts`,onDiagnostics:o,readOnly:s=!1,heightPx:c=420,dark:l=!0}){let u=t(null),p=e((e,t)=>{if(u.current=t,Li(t,i),o===void 0)return;let n=e.getModel();if(n===null)return;let r=()=>{o(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(r),r()},[i,o]);return f(()=>{let e=u.current;e!==null&&Li(e,i)},[i]),d(Pi,{height:c,defaultLanguage:`typescript`,path:a,theme:l?`vs-dark`:`vs`,value:n,onChange:e=>r(e??``),onMount:p,options:{readOnly:s,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function zi(e){return e.some(e=>e.severity>=8)}var Bi=[{id:`blank`,name:`Blank script`,description:`Minimal hello + timer disposer`,entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
15
-
16
- /**
17
- * A core block. Runs in its own process, with the same \`ctx\` an addon gets.
18
- * Return a function to release whatever you took (timers, sockets, listeners).
19
- *
20
- * Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
21
- * '@camstack/types' and hang them off the shared Blocks integration.
22
- */
23
- export default function block(ctx: AddonContext) {
24
- ctx.logger.info('hello from a core block')
25
-
26
- const timer = setInterval(() => {
27
- ctx.logger.info('tick')
28
- }, 60_000)
29
-
30
- return () => {
31
- clearInterval(timer)
32
- }
33
- }
34
- `}}];function Vi(e){let t=e instanceof Set?e:new Set(e);if(!t.has(`file.ts`))return`file.ts`;let n=2;for(;t.has(`file-${String(n)}.ts`);)n+=1;return`file-${String(n)}.ts`}var Hi=Bi.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
35
-
36
- export default function block(ctx: AddonContext) {
37
- ctx.logger.info('hello from a core block')
38
- return () => undefined
39
- }
40
- `;function Ui({existing:e,dirty:t,saving:n,restarting:r}){return e===null?`Save the script first — there is no process to restart yet.`:n?`Saving…`:r?`Restarting…`:t?`Save first — a restart now would run the last SAVED code, not what is on screen.`:e.enabled?null:`This script is disabled. Enable it instead of restarting it.`}r();var Wi=5e3;function Gi(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=Reflect.get(n,`id`),r=Reflect.get(n,`name`),i=Reflect.get(n,`type`),a=Reflect.get(n,`stableId`);typeof e!=`number`||typeof r!=`string`||typeof i!=`string`||t.push({id:e,name:r,type:i,...typeof a==`string`?{stableId:a}:{}})}return t}function Ki({blockId:e}){let t=q(e),n=de({addonId:t,projection:`slim`},{refetchInterval:Wi}),r=o(()=>Gi(n.data),[n.data]);return n.isLoading?i(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(S,{className:`h-3.5 w-3.5 animate-spin`}),` Loading devices owned by this script…`]}):n.isError?i(`p`,{className:`text-xs text-danger`,children:[`Could not list devices:`,` `,n.error instanceof Error?n.error.message:String(n.error)]}):i(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[i(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{children:[d(`h4`,{className:`text-sm font-medium`,children:`Devices`}),i(`p`,{className:`text-xs text-foreground-subtle`,children:[`Declared by this script under the shared Blocks integration (`,d(`code`,{className:`text-[11px]`,children:t}),`). Open a device for its export section.`]})]}),d(W,{variant:`default`,children:r.length})]}),r.length===0?i(`p`,{className:`text-xs text-foreground-subtle`,children:[`No devices yet. Call `,d(`code`,{children:`reconcileBlockDevices(ctx, …)`}),` from the script (and Restart) to declare them.`]}):d(`ul`,{className:`space-y-3`,children:r.map(e=>d(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${e.id}`,children:i(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[d(Pe,{to:`/devices/${String(e.id)}`,className:`text-sm font-medium hover:underline`,title:`Open device detail`,children:e.name}),d(W,{variant:`info`,style:`outline`,children:e.type}),e.stableId!==void 0&&i(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,d(`code`,{children:e.stableId})]}),i(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,e.id]})]})},e.id))})]})}r();function qi(e){return e===`refresh-channel-catalog`||e===`send-tv-schedule-now`||e===`refresh-nordvpn-catalog`||e===`probe-nordvpn-italy`||e===`test-nordvpn-endpoint`||e===`refresh-unifi-catalog`}function Ji(e){let t=Date.now();switch(e){case`refresh-channel-catalog`:return{channelCatalogRefreshAt:t};case`send-tv-schedule-now`:return{sendNowAt:t};case`refresh-nordvpn-catalog`:return{nordVpnCatalogRefreshAt:t};case`probe-nordvpn-italy`:return{nordVpnProbeAt:t};case`test-nordvpn-endpoint`:return{nordVpnTestAt:t};case`refresh-unifi-catalog`:return{unifiCatalogRefreshAt:t}}}function Yi(e){switch(e){case`refresh-channel-catalog`:return`Script enabled so the channel catalog can scrape.`;case`send-tv-schedule-now`:return`Script enabled so the TV schedule can send.`;case`refresh-nordvpn-catalog`:return`Script enabled so the NordVPN catalog can refresh.`;case`probe-nordvpn-italy`:return`Script enabled so Italy stations can be probed.`;case`test-nordvpn-endpoint`:return`Script enabled so the VPN endpoint can be tested.`;case`refresh-unifi-catalog`:return`Script enabled so UniFi IDs can be fetched.`}}function Xi(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Zi(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Qi(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Xi(e);n!==null&&(t[n]=Zi(e))}return t}function $i(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function ea({blockId:t}){let n=g(),r=j({blockId:t},{retry:!1}),a=M({blockId:t},{refetchInterval:1e4,retry:!1}),s=b({onSuccess:()=>{a.refetch()}}),c=I(),u=pe(),[f,p]=l(null),[m,h]=l(null),[_,v]=l(null),[y,x]=l(!1),C=$i(a.data)?a.data:null,w=o(()=>C===null?{}:Qi(C),[C]),T=f??w,D=e(e=>{p(e)},[]),O=f!==null,k=e(()=>{f!==null&&(h(null),s.mutate({blockId:t,patch:f},{onSuccess:()=>p(null),onError:e=>h(e instanceof Error?e.message:String(e))}))},[t,f,s]),A=e(async(e,i)=>{if(qi(e)){x(!0),h(null),v(null);try{f!==null&&(await n.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:f}),p(null)),await n.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:Ji(e)}),r.data?.block?.enabled!==!0&&(await u.mutateAsync({blockId:t,enabled:!0}),v(Yi(e))),await c.mutateAsync({blockId:t}),await a.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){h(e instanceof Error?e.message:String(e))}finally{x(!1)}}},[t,r.data?.block?.enabled,f,c,u,a,n.trpcClient.coreBlocks]);return a.isLoading?i(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[d(S,{className:`h-3.5 w-3.5 animate-spin`}),` Loading script settings…`]}):a.isError?i(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[`Could not load settings:`,` `,a.error instanceof Error?a.error.message:String(a.error)]}):C===null?null:i(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[i(`div`,{className:`flex items-center justify-between gap-2`,children:[i(`div`,{children:[d(`h4`,{className:`text-sm font-medium`,children:`Settings`}),i(`p`,{className:`text-xs text-foreground-subtle`,children:[`Declared by this script's `,d(`code`,{children:`settingsSchema`}),` export.`]})]}),i(E,{size:`sm`,variant:`primary`,onClick:k,disabled:!O||s.isPending||y,children:[s.isPending&&d(S,{className:`h-3.5 w-3.5 animate-spin`}),`Save settings`]})]}),d(Me,{schema:C,values:T,onChange:D,onAction:A}),m===null?null:d(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:m}),_===null?null:d(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}r();var ta=`hub`;function na({existing:e,typeDefs:t,typeDefsLoading:n,saving:r,saveError:a,restarting:s,restartError:f,onRestart:p,onSave:m,onCancel:h}){let _=g(),y=se(),{resolvedMode:b}=x(),C=Ce({code:e?.code??Hi,files:e?.files,entry:e?.entry}),[w,T]=l(e?.name??``),[D,O]=l(C.files),[k,A]=l(C.entry),[j,M]=l(C.entry),[N,P]=l(e?.placement??ta),[I,ee]=l(e?.integrationId??``),[z,B]=l([]),[V,H]=l(!1),[U,te]=l(`blank`),[ne,ie]=l(null),[oe,le]=l(``),ue=D[j]??``,de=e=>{O(t=>({...t,[j]:e}))},fe=Object.keys(D).toSorted(),pe=Bi.length>1,me=o(()=>[...t?.libs??[],...Fi(D,j)],[t?.libs,D,j]),G=u({mutationFn:()=>_.trpcClient.coreBlocks.compile.mutate({files:D,entry:k})}),K=o(()=>z.filter(e=>e.severity>=8),[z]),he=zi(z),ge=w.trim()===``,_e=e===null?null:Ce(e),ve=e===null||_e===null||JSON.stringify(D)!==JSON.stringify(_e.files)||k!==_e.entry||w.trim()!==e.name||N!==e.placement||(I.trim()===``?void 0:I.trim())!==e.integrationId,ye=()=>{G.reset(),m({name:w.trim(),files:D,entry:k,enabled:e?.enabled??!0,placement:N,...I.trim()===``?{}:{integrationId:I.trim()}})},be=()=>{let e=Vi(Object.keys(D));O(t=>({...t,[e]:``})),M(e),ie(e),le(e)},xe=e=>{ie(e),le(e)},Se=()=>{if(ne===null)return;let e=ne,t=oe.trim();if(ie(null),!(t===``||t===e)){if(D[t]!==void 0){M(t);return}O(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),k===e&&A(t),M(t)}},we=async e=>{let t=Bi.find(t=>t.id===e);if(t===void 0)return;let n=Bi.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(D)===JSON.stringify(n.files)&&k===n.entry)&&!await y({title:`Load example`,message:`Replace the current editor contents with this example?`,confirmLabel:`Replace`,variant:`warning`})||(te(e),O({...t.files}),A(t.entry),M(t.entry),(w.trim()===``||U===`blank`)&&T(t.id===`blank`?``:t.name))},Te=e===null?null:Cn(e),Ee=Ui({existing:e,dirty:ve,saving:r,restarting:s});return i(`div`,{className:`space-y-4`,children:[Te!==null&&d(`div`,{className:`flex flex-wrap items-center gap-2`,children:d(W,{variant:wn(Te.tone),children:Te.label})}),i(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[i(`label`,{className:`block text-sm`,children:[d(`span`,{className:`text-foreground-subtle`,children:`Name`}),d(F,{className:`mt-1`,value:w,onChange:e=>T(e.target.value),placeholder:`What this script does`})]}),i(`label`,{className:`block text-sm`,children:[d(`span`,{className:`text-foreground-subtle`,children:`Integration (optional)`}),d(F,{className:`mt-1`,value:I,onChange:e=>ee(e.target.value),placeholder:`Leave empty for the shared system integration`})]})]}),e===null&&pe&&i(`label`,{className:`block text-sm`,children:[d(`span`,{className:`text-foreground-subtle`,children:`Start from`}),d(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:U,onChange:e=>void we(e.target.value),"data-testid":`script-example-select`,children:Bi.map(e=>i(`option`,{value:e.id,children:[e.name,` — `,e.description]},e.id))})]}),i(`div`,{children:[d(R,{selectedNodeId:N,onSelect:P,label:`Runs on`,alwaysShow:!0}),N!==ta&&i(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[d(ae,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),i(`span`,{children:[`Block execution is hub-only today. Saved with this placement the block will be stored and compiled, but it will report `,d(`strong`,{children:`Failed`}),` instead of running.`]})]})]}),i(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[i(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[fe.map(e=>ne===e?d(F,{value:oe,onChange:e=>le(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),ie(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":`Rename file`},e):i(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${e===j?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>M(e),onDoubleClick:()=>xe(e),title:`Double-click to rename`,"data-testid":`script-file-tab-${e}`,children:[e,e===k?` · entry`:``]},e)),d(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:be,"data-testid":`script-file-add`,children:`+ file`}),j!==k&&d(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>A(j),title:`Use this file as the compile entry`,children:`Set as entry`})]}),n?d(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:`Loading the node's type definitions…`}):d(Ri,{value:ue,onChange:de,path:`file:///${j}`,extraLibs:me,onDiagnostics:B,dark:b===`dark`,heightPx:560})]}),t!==void 0&&t.libs.length===0&&d(`p`,{className:`text-xs text-warning`,children:`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`}),K.length>0&&i(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[i(`p`,{className:`font-medium text-danger`,children:[K.length,` error`,K.length===1?``:`s`,` — the block cannot be saved.`]}),K.slice(0,5).map(e=>i(`p`,{className:`text-danger`,children:[`line `,e.line,`: `,e.message]},`${String(e.line)}:${String(e.column)}:${e.message}`)),K.length>5&&i(`p`,{className:`text-foreground-subtle`,children:[`…and `,K.length-5,` more.`]})]}),G.data!==void 0&&(G.data.ok?i(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[d(ce,{className:`h-3.5 w-3.5`}),` The node compiled this code. Nothing was saved.`]}):i(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[G.data.line===void 0?``:`line ${String(G.data.line)}: `,G.data.error??`the code does not compile`]})),G.error!==null&&i(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[`Could not reach the compiler: `,ra(G.error)]}),a!==null&&d(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),f!==null&&d(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:f}),e!==null&&i(`div`,{className:`space-y-3`,children:[d(ea,{blockId:e.id}),d(Ki,{blockId:e.id})]}),i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[i(E,{variant:`outline`,onClick:()=>G.mutate(),disabled:G.isPending||r,title:`Type-check on the node without saving`,children:[G.isPending&&d(S,{className:`h-4 w-4 animate-spin`}),` Compile`]}),i(E,{onClick:ye,disabled:r||he||ge,children:[r&&d(S,{className:`h-4 w-4 animate-spin`}),` Save`]}),i(E,{variant:`outline`,onClick:()=>p?.(),disabled:Ee!==null||p===void 0,title:Ee??`Stop the process and let the supervisor bring it back`,children:[s?d(re,{className:`h-4 w-4 animate-spin`}):d(re,{className:`h-4 w-4`}),` `,`Restart`]}),i(E,{variant:`ghost`,onClick:()=>H(!V),title:`Show this script's process logs`,"data-testid":`script-logs-toggle`,children:[d(v,{className:`h-4 w-4`}),` Logs `,V?`▾`:`▸`]}),d(E,{variant:`ghost`,onClick:h,disabled:r,children:`Close`}),i(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[`errors: `,K.length,ve&&e!==null?` · unsaved changes`:``]}),ge&&d(W,{variant:`warning`,children:`Name required`})]}),V&&i(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[d(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:e===null?`Logs appear once the script has been saved and started.`:i(c,{children:[`Logs — `,d(`code`,{children:q(e.id)})]})}),e!==null&&d(L,{addonId:q(e.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function ra(e){return e instanceof Error?e.message:String(e)}r();var ia=[`coreBlocks`,`list`],aa=[`coreBlocks`,`getTypeDefs`],oa=5e3;function sa(e){return e instanceof Error?e.message:String(e)}function ca({initialBlockId:e,onBlockIdChange:n,createRequested:r=!1,onCreateConsumed:a}={}){let c=g(),{state:p,openNew:h,openEdit:_,close:y}=D({editKey:`block`,newKey:`new`}),[b,x]=l(null),[S,C]=l(null),[O,k]=l(null),A=s({queryKey:ia,refetchInterval:oa,queryFn:async()=>(await c.trpcClient.coreBlocks.list.query({})).blocks}),j=p.mode!==`closed`,M=s({queryKey:aa,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>c.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{A.refetch()},P=t(null),F=A.data;f(()=>{e===void 0||P.current===e||F?.find(t=>t.id===e&&ye(t)===`code`)!==void 0&&(P.current=e,_(e),n?.(e))},[e,F,_,n]),f(()=>{r&&(x(null),h(),n?.(null),a?.())},[r,a,n,h]);let I=u({mutationFn:e=>c.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),n?.(e.block.id),N()}}),R=u({mutationFn:e=>c.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),n?.(e.block.id),N()}}),z=u({mutationFn:e=>c.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{C(null),N()}}),B=u({mutationFn:e=>c.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),V=u({mutationFn:e=>c.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),H=En((A.data??[]).filter(e=>ye(e)===`code`)),U=A.data!==void 0&&H.length===0,te=I.isPending||R.isPending,ne=I.error===null?R.error===null?null:sa(R.error):sa(I.error),ie=p.mode===`edit`?H.find(e=>e.id===p.id)??(b!==null&&b.id===p.id?b:null):null,ae=p.mode===`new`||ie===null?null:Tn(H,ie),oe=o(()=>[{key:`name`,header:`Name`,render:e=>{let t=Cn(e),n=ue(e.updatedAt);return i(`div`,{className:`min-w-0`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`span`,{className:`truncate font-medium`,children:e.name}),d(W,{variant:wn(t.tone),children:t.label}),d(W,{variant:`info`,children:e.placement}),n!==null&&i(`span`,{className:`text-xs text-foreground-subtle`,children:[`edited `,n]})]}),d(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.detail}),O===e.id&&i(`div`,{className:`mt-2 rounded border border-border`,children:[i(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:[`Logs — `,d(`code`,{children:q(e.id)})]}),d(L,{addonId:q(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=B.isPending||z.isPending,r=V.isPending&&V.variables===e.id;return S===e.id?i(`div`,{className:`flex justify-end gap-1`,children:[d(`span`,{className:`text-xs text-foreground-subtle`,children:`Delete this script?`}),d(E,{variant:`danger`,onClick:()=>z.mutate(e.id),disabled:t,children:`Delete`}),d(E,{variant:`ghost`,onClick:()=>C(null),children:`Cancel`})]}):i(`div`,{className:`flex justify-end gap-1`,children:[d(E,{variant:`ghost`,onClick:t=>{t.stopPropagation(),x(e),_(e.id),n?.(e.id)},title:`Edit`,children:`Edit`}),d(E,{variant:`ghost`,onClick:t=>{t.stopPropagation(),V.mutate(e.id)},disabled:t||r||!e.enabled,title:e.enabled?`Restart`:`Enable it instead — a disabled script has no process`,children:d(re,{className:`h-4 w-4${r?` animate-spin`:``}`})}),d(E,{variant:`ghost`,onClick:t=>{t.stopPropagation(),k(O===e.id?null:e.id)},title:`Logs`,children:d(v,{className:`h-4 w-4`})}),d(E,{variant:`ghost`,onClick:t=>{t.stopPropagation(),B.mutate({blockId:e.id,enabled:!e.enabled})},disabled:t,title:e.enabled?`Disable`:`Enable`,children:e.enabled?`Disable`:`Enable`}),d(E,{variant:`ghost`,onClick:t=>{t.stopPropagation(),C(e.id)},title:`Delete`,children:d(m,{className:`h-4 w-4`})})]})}}],[S,O,n,_,z,V.isPending,V.variables,B]);return i(`div`,{className:`space-y-3`,children:[d(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:Dn(H)}),A.error!=null&&d(w,{title:`Could not read the scripts`,message:sa(A.error),onRetry:N}),d(T,{columns:oe,rows:H,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ee,mobileMode:`scroll`,emptyMessage:U?`No scripts yet. A script is TypeScript the hub runs in its own process.`:A.data===void 0?`Loading scripts…`:`No scripts yet.`,onRowClick:e=>{x(e),_(e.id),n?.(e.id)}}),d(fe,{open:j,onClose:()=>{I.reset(),R.reset(),V.reset(),x(null),y(),n?.(null)},title:ae===null?`New script`:`Edit ${ae.name}`,icon:He,width:`xl`,testId:`script-editor-panel`,children:d(na,{existing:ae,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:te,saveError:ne,restarting:V.isPending,restartError:V.error===null?null:sa(V.error),onRestart:ae===null?void 0:()=>V.mutate(ae.id),onSave:e=>{let t=ae;t===null?I.mutate(e):R.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),R.reset(),V.reset(),x(null),y(),n?.(null)}})}),z.error!=null&&d(w,{message:sa(z.error)}),B.error!=null&&d(w,{message:sa(B.error)}),V.error!=null&&d(w,{message:sa(V.error)})]})}var la=[`automations`,`scripts`,`custom-device`];function ua(e){return e!==null&&la.some(t=>t===e)}var da=[`coreBlocks`,`list`,`build-counts`],fa=[`block`,`create`];function pa(e){return e.filter(e=>ye(e)===`code`).length}function ma(e){return e.filter(e=>Ke(e.code)).length}function ha(e,t){return t===null?e:`${e} (${String(t)})`}function ga(){let{t:e}=Oe(),t=g(),[n,r]=ke(),a=n.get(`tab`),o=ua(a)?a:`automations`,c=n.get(`create`)===`1`,l=s({queryKey:da,refetchInterval:5e3,queryFn:async()=>(await t.trpcClient.coreBlocks.list.query({})).blocks}).data,u=l===void 0?null:pa(l),f=l===void 0?null:ma(l),p=s({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>t.trpcClient.coreBlocks.listCompositions.query({})}),m=p.data?.state===`loaded`?p.data.views.length:null,h=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},v=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},y=()=>{r(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},b=()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`create`),t},{replace:!0})},x=o===`automations`?`New automation`:o===`scripts`?`New script`:`New composition`,S=Ae(`/build`,{t:e,isAdmin:!0})??{icon:O,title:e(`nav.build`,`Build-your-self`)};return d(Ie,{icon:S.icon,title:S.title,subtitle:`Automations, scripts and composed devices — what this installation does on its own.`,defaultSection:`automations`,sectionsLabel:`${S.title} sections`,fill:!0,actions:i(E,{type:`button`,onClick:y,"data-testid":`build-new`,children:[d(U,{className:`h-4 w-4`}),` `,x]}),sections:[{id:`automations`,label:ha(`Automations`,f),ownedParams:fa,content:d(Nn,{onOpenScripts:h,initialBlockId:o===`automations`?n.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:o===`automations`&&c,onCreateConsumed:b})},{id:`scripts`,label:ha(`Scripts`,u),ownedParams:fa,content:d(ca,{initialBlockId:o===`scripts`?n.get(`block`)??void 0:void 0,onBlockIdChange:v,createRequested:o===`scripts`&&c,onCreateConsumed:b})},{id:`custom-device`,label:ha(`Custom Device`,m),ownedParams:fa,content:d(er,{createRequested:o===`custom-device`&&c,onCreateConsumed:b})}]})}export{ga as BuildPage};
@@ -1 +0,0 @@
1
- import{I as e,K as t,Q as n,S as r,V as i,W as a,b as o,o as s,q as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{_t as d,ct as f,gt as p,ot as m,yt as h}from"./player-overlays-mP7nvLXZ.js";import{$u as g,Bc as _,Ed as v,Gs as y,Ht as b,Kd as x,Kn as S,Lc as C,Ls as w,M as T,Mf as E,Qd as D,Ql as O,Qu as k,Rc as A,Tt as j,U as M,Ut as N,Wt as P,Xo as ee,Xt as te,Yo as ne,Zu as re,_f as ie,_r as ae,ad as oe,as as se,cu as ce,ec as le,ff as F,gd as ue,gr as de,hr as fe,id as I,is as pe,ku as me,lf as he,lu as L,md as ge,mr as _e,mu as ve,ns as ye,oc as be,od as xe,rr as Se,rs as Ce,sl as we,wn as Te,wt as Ee,ya as De,zc as Oe}from"./src-BeE19PxU.js";import{n as ke,t as R}from"./format-size-D8E_VMta.js";import{Jr as Ae,Kr as je,Zr as Me,qr as Ne}from"./client-D5nV-lIF.js";import{t as z}from"./useTranslation-Bc5yH9V9.js";import{$ as Pe}from"./index-I1VJhtqM.js";import{t as Fe}from"./AdminPage-eik5HL7w.js";import{t as Ie}from"./NodeAddonsSettingsPanel-BCFsPpmx.js";import{f as Le,l as Re,m as ze,u as Be}from"./board-model-Bmts6hrg.js";import{n as Ve,t as He}from"./useNodeUrlSelection-C2aUQ5pz.js";var Ue=h(`memory-stick`,[[`path`,{d:`M12 12v-2`,key:`fwoke6`}],[`path`,{d:`M12 18v-2`,key:`qj6yno`}],[`path`,{d:`M16 12v-2`,key:`heuere`}],[`path`,{d:`M16 18v-2`,key:`s1ct0w`}],[`path`,{d:`M2 11h1.5`,key:`15p63e`}],[`path`,{d:`M20 18v-2`,key:`12ehxp`}],[`path`,{d:`M20.5 11H22`,key:`khsy7a`}],[`path`,{d:`M4 18v-2`,key:`1c3oqr`}],[`path`,{d:`M8 12v-2`,key:`1mwtfd`}],[`path`,{d:`M8 18v-2`,key:`qcmpov`}],[`rect`,{x:`2`,y:`6`,width:`20`,height:`10`,rx:`2`,key:`1qcswk`}]]);n();var We=`system-config-cluster`;function Ge(){return l(Te,{trpc:m().trpcClient,addonId:`system-config`,nodeId:`hub`,sectionIds:[We],bare:!0})}function Ke(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qe(e){if(!Ke(e))return null;let t=e.ticket;if(typeof t!=`string`||t.length===0)return null;let n=e.dashboardUrl;return typeof n==`string`&&n.length>0?{ticket:t,dashboardUrl:n}:{ticket:t}}function Je(e){let t=e.trim();return!(t.length===0||t.includes(`/`)||t.includes(`?`)||t.includes(`#`)||t.includes(`@`)||t.includes(`:`))}function B(e){return e.startsWith(`172.17.`)}function Ye(e){let t=/^100\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=64&&n<=127}function Xe(e){if(e.startsWith(`10.`)||e.startsWith(`192.168.`))return!0;let t=/^172\.(\d+)\./.exec(e);if(t===null)return!1;let n=Number(t[1]);return n>=16&&n<=31&&!B(e)}function Ze(e,t){if(typeof t==`string`&&Je(t))return t.trim();let n=e.filter(e=>!e.includes(`:`)),r=n.find(e=>!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!B(e)&&!Ye(e)&&Xe(e));if(r!==void 0)return r;for(let e of n)if(!e.startsWith(`127.`)&&!e.startsWith(`169.254.`)&&!B(e))return e;return null}function Qe(e){return`http://${e}:4444/`}function $e(e,t){let n=new URL(Qe(e));return n.searchParams.set(`ticket`,t),n.toString()}function et(){return window.open(`about:blank`,`_blank`)}function tt(e,t){return e===null||e.closed?!1:(e.location.href=t,!0)}function nt(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}function rt(e){return e===`running`?`running`:e===`crashed`||e===`failed`?`error`:`stopped`}var it=[`trace`,`debug`,`info`,`warn`,`error`];function at({proc:e,nodeId:t,defaultExpanded:n,activePanel:i,onTogglePanel:a}){let o=e.services??[],s=o.length===1,[u,f]=c(s||n),[m,h]=c(null),[_,v]=c(`info`),y=e.name.includes(`(core)`),b=Ce(),x=pe(),S=se(),C=async e=>{h(e);try{await b.mutateAsync({nodeId:t,addonId:e})}catch(e){console.error(`Failed to restart addon:`,e)}finally{h(null)}},w=async()=>{h(e.name);try{await x.mutateAsync({nodeId:t,processName:e.name})}catch(e){console.error(`Failed to restart process:`,e)}finally{h(null)}},E=async n=>{let r=`${t}/${e.name}`;try{await S.mutateAsync({nodeId:r,level:n}),v(n)}catch(e){console.error(`Failed to set log level:`,e)}};return r(`div`,{className:`border border-border/50 rounded-lg overflow-hidden`,children:[r(`div`,{role:s?void 0:`button`,tabIndex:s?void 0:0,onClick:s?void 0:()=>f(!u),onKeyDown:s?void 0:e=>{(e.key===`Enter`||e.key===` `)&&f(!u)},className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 w-full px-3 py-2 bg-muted/20 transition-colors text-left select-none ${s?``:`hover:bg-muted/40 cursor-pointer`}`,children:[s?l(`span`,{className:`h-3 w-3 shrink-0`}):l(u?d:p,{className:`h-3 w-3 text-muted-foreground shrink-0`}),y?l(re,{className:`h-3.5 w-3.5 text-primary shrink-0`}):l(ie,{className:`h-3.5 w-3.5 text-warning shrink-0`}),l(`span`,{className:`text-xs font-semibold min-w-0 flex-1 basis-full truncate sm:basis-auto`,children:e.name}),r(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:[`PID `,e.pid]}),l(T,{status:rt(e.state),label:e.state}),r(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:[e.cpuPercent,`% CPU`]}),l(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:R(e.memoryRss)}),l(`span`,{className:`text-[10px] text-muted-foreground tabular-nums shrink-0`,children:nt(e.uptimeSeconds)}),!y&&r(`div`,{className:`flex items-center gap-1`,onClick:e=>e.stopPropagation(),children:[r(_e,{children:[l(ae,{className:`text-[9px] px-1.5 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors font-mono`,title:`Set log level`,children:_}),l(fe,{align:`end`,className:`min-w-[70px] py-0.5`,children:it.map(e=>l(de,{onClick:()=>E(e),className:`h-auto px-2 py-1 text-[10px] font-mono ${e===_?`text-primary font-semibold`:``}`,children:e},e))})]}),l(`button`,{onClick:w,disabled:m===e.name,className:`p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:`Restart process`,children:l(I,{className:`h-3 w-3 ${m===e.name?`animate-spin`:``}`})})]})]}),u&&o.length>0&&l(`div`,{className:`divide-y divide-border/30`,children:o.map(e=>r(`div`,{children:[r(`div`,{className:`flex items-center gap-2 px-3 py-1.5 pl-9 hover:bg-muted/10 transition-colors`,children:[l(`div`,{className:`h-1.5 w-1.5 rounded-full shrink-0 ${e.status===`running`?`bg-success`:`bg-muted-foreground/30`}`}),l(`span`,{className:`text-xs font-medium flex-1 min-w-0 truncate`,children:e.addonId}),e.capabilities.length>0&&r(`div`,{className:`flex gap-1 flex-shrink-0`,children:[e.capabilities.slice(0,3).map(e=>l(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-info/10 text-info truncate max-w-[80px]`,children:e},e)),e.capabilities.length>3&&r(`span`,{className:`text-[9px] text-muted-foreground`,children:[`+`,e.capabilities.length-3]})]}),r(`div`,{className:`flex items-center gap-1 shrink-0`,children:[l(`button`,{onClick:()=>a(e.addonId,`logs`),className:`p-0.5 rounded transition-colors ${i?.addonId===e.addonId&&i.type===`logs`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:`Show logs for ${e.addonId}`,children:l(g,{className:`h-3 w-3`})}),l(`button`,{onClick:()=>a(e.addonId,`events`),className:`p-0.5 rounded transition-colors ${i?.addonId===e.addonId&&i.type===`events`?`bg-primary/10 text-primary`:`hover:bg-muted text-muted-foreground hover:text-foreground`}`,title:`Show events for ${e.addonId}`,children:l(xe,{className:`h-3 w-3`})}),l(`button`,{onClick:()=>C(e.addonId),disabled:m===e.addonId,className:`p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50`,title:`Restart ${e.addonId}`,children:l(I,{className:`h-3 w-3 ${m===e.addonId?`animate-spin`:``}`})})]})]}),i?.addonId===e.addonId&&i.type===`logs`&&l(`div`,{className:`border-t border-border/40 bg-muted/5`,children:l(j,{addonId:e.addonId,agentId:t,maxHeight:`max-h-48`,showFilters:!1,onClose:()=>a(e.addonId,`logs`)})}),i?.addonId===e.addonId&&i.type===`events`&&l(`div`,{className:`border-t border-border/40 bg-muted/5`,children:l(Ee,{addonId:e.addonId,category:`addon.*`,maxHeight:`max-h-48`,onClose:()=>a(e.addonId,`events`)})})]},e.addonId))}),u&&o.length===0&&l(`div`,{className:`px-3 py-2 pl-9 text-[10px] text-muted-foreground`,children:`No services`})]})}function ot({nodeId:e,processes:t}){let[n,r]=c(null),i=(e,t)=>{r(n=>n?.addonId===e&&n.type===t?null:{addonId:e,type:t})};return t.length===0?l(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:`No processes on this node`}):l(`div`,{className:`space-y-2 py-1`,children:t.map((t,r)=>l(at,{proc:t,nodeId:e,defaultExpanded:r===0,activePanel:n,onTogglePanel:i},t.name))})}var st={system:0,managed:1,root:2};n();function ct(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`}function lt(e,t=80){return e.length<=t?e:`…${e.slice(e.length-t+1)}`}function ut({nodeId:e}){let t=s(),n=L(`metrics.node-processes-snapshot`,t=>t.nodeId===e),{data:i}=ee({nodeId:e}),o=n?.processes??i,c=a(()=>o?[...o]:[],[o]),u=a(()=>[{key:`classification`,header:`Class`,sortValue:e=>st[e.classification],render:e=>l(`span`,{className:`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium ${e.classification===`root`?`bg-info/20 text-info`:e.classification===`system`?`bg-foreground-subtle/20 text-foreground-subtle`:`bg-success/20 text-success`}`,children:e.classification})},{key:`pid`,header:`PID`,align:`right`,sortValue:e=>e.pid,render:e=>l(`span`,{className:`font-mono`,children:e.pid})},{key:`ppid`,header:`PPID`,align:`right`,sortValue:e=>e.ppid,render:e=>l(`span`,{className:`font-mono text-foreground-subtle`,children:e.ppid})},{key:`addonId`,header:`Addon`,sortValue:e=>e.addonId,render:e=>l(`span`,{className:`text-foreground-subtle text-[11px]`,children:e.addonId??`—`})},{key:`command`,header:`Command`,nowrap:!1,render:e=>l(`span`,{className:`font-mono text-[10px] text-foreground-subtle break-all`,children:lt(e.command)})},{key:`cpuPercent`,header:`CPU%`,align:`right`,sortValue:e=>e.cpuPercent,render:e=>e.cpuPercent.toFixed(1)},{key:`memoryRssBytes`,header:`RSS`,align:`right`,sortValue:e=>e.memoryRssBytes,render:e=>R(e.memoryRssBytes)},{key:`uptimeSec`,header:`Uptime`,align:`right`,sortValue:e=>e.uptimeSec,render:e=>l(`span`,{className:`text-foreground-subtle`,children:ct(e.uptimeSec)})}],[]);return r(`div`,{className:`space-y-4`,children:[l(`div`,{className:`flex items-start justify-end gap-4`,children:r(`button`,{type:`button`,onClick:()=>t.invalidateQueries({queryKey:[[`metricsProvider`,`listNodeProcesses`]]}),className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:[l(oe,{className:`h-3 w-3`}),` Refresh`]})}),l(b,{columns:u,rows:c,rowKey:e=>e.pid,minWidthPx:880,mobileMode:`cards`,maxBodyHeight:N,emptyMessage:`Scanning…`})]})}var V={width:320,height:64},dt=.8,H=Math.ceil(8*dt-3)+1,U=V.width+34,W=V.height+H+1+11,ft=H+V.height+1+3+Math.ceil(8*dt),pt=[1,2,5,10],mt=[1,2,4,8,16,32,64,128,256,512,1024],ht=[1,1.5,2,2.5,3,4,5],G=[4,3,5,2],gt=1e-9;function _t(e,t){if(!Number.isFinite(e)||e<=0)return!1;if(t===`bytes`){if(!Number.isInteger(e))return!1;let t=e/1024**Math.floor(Math.log(e)/Math.log(1024));return ht.some(e=>Math.abs(t-e)<gt)}let n=e/10**Math.floor(Math.log10(e));return ht.some(e=>Math.abs(n-e)<gt)}function vt(e,t,n){let r=0;for(let t of e)t!==null&&t>r&&(r=t);if(r<=t)return t;if(n===`bytes`){let e=1024**Math.floor(Math.log(r)/Math.log(1024));for(let t of mt){let n=t*e;if(n>=r)return n}return 1024*e}let i=10**Math.floor(Math.log10(r));for(let e of pt){let t=e*i;if(t>=r)return t}return 10*i}function yt(e,t){if(!Number.isFinite(e)||e<=0)return[];let n=G.find(n=>_t(e/n,t))??G[G.length-1],r=e/n,i=[];for(let e=1;e<=n;e++)i.push(r*e);return i}var bt=2.5;function xt(e){return e*bt}function K(e,t,n,r){if(e.length===0)return[];let i=e[0].atMs,a=e.at(-1).atMs-i,o=n<=0?1:n,s=r!==void 0&&r>0?r:null;return e.map((r,c)=>{let l=a>0?(r.atMs-i)/a*t.width:c/Math.max(1,e.length-1)*t.width,u=c>0?e[c-1]:void 0;return{x:l,y:r.value===null?null:t.height-Math.min(r.value,n)/o*t.height,gapBefore:s!==null&&u!==void 0&&r.atMs-u.atMs>s}})}function St(e){let t=[],n=!1;for(let r of e){if(r.y===null){n=!1;continue}r.gapBefore&&(n=!1),t.push(`${n?`L`:`M`}${r.x.toFixed(1)},${r.y.toFixed(1)}`),n=!0}return t.join(` `)}function Ct(e,t){let n=[],r=[],i=()=>{if(r.length<2){r=[];return}let e=r.map((e,t)=>`${t===0?`M`:`L`}${e.x.toFixed(1)},${e.top.toFixed(1)}`),t=[...r].reverse().map(e=>`L${e.x.toFixed(1)},${e.bottom.toFixed(1)}`);n.push(`${e.join(` `)} ${t.join(` `)} Z`),r=[]};for(let n=0;n<e.length;n++){let a=e[n],o=t[n];if(!a||!o||a.y===null||o.y===null){i();continue}(a.gapBefore||o.gapBefore)&&i(),r.push({x:a.x,top:a.y,bottom:o.y})}return i(),n.join(` `)}function wt(e,t,n=3){if(e.length<2||n<2)return[];let r=e[0].atMs,i=e.at(-1).atMs-r;if(i<=0)return[];let a=[];for(let e=0;e<n;e++){let o=e/(n-1);a.push({atMs:r+i*o,x:o*t.width,anchor:e===0?`start`:e===n-1?`end`:`middle`})}return a}function Tt(e){return e.length<2?0:Math.max(0,e.at(-1).atMs-e[0].atMs)}function Et(e){let t=[];for(let n=1;n<e.length;n++){let r=e[n];r.gapBefore&&t.push({fromX:e[n-1].x,toX:r.x})}return t}function Dt(e,t){if(e.length===0)return null;let n=0,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].x-t);a<r&&(r=a,n=i)}return n}n();var q={main:`var(--color-chart-series-a)`,gc:`var(--color-chart-series-b)`},J=V,Ot={height:W};function kt({title:e,points:n,mainLabel:s,gcLabel:u,formatValue:d,emptyMessage:f,gapMs:p}){let m=i(),h=t(null),[g,_]=c(null),v=a(()=>{let e=n.map(e=>({atMs:e.atMs,value:e.main===null||e.gc===null?null:e.main+e.gc})),t=n.map(e=>({atMs:e.atMs,value:e.main})),r=vt(e.map(e=>e.value),25,`linear`),i=K(e,J,r,p),a=K(t,J,r,p),o=a.map(e=>({x:e.x,y:e.y===null?null:J.height,gapBefore:e.gapBefore}));return{max:r,ticks:yt(r,`linear`),upper:i,middle:a,base:o,gaps:Et(i),times:wt(e,J),spanMs:Tt(e)}},[n,p]),y=n.at(-1),b=g===null?void 0:n[g.index],x=b??y;return n.length===0||v.upper.every(e=>e.y===null)?l(X,{title:e,children:l(zt,{message:f})}):l(X,{title:e,legend:r(o,{children:[l(Rt,{color:q.main,label:s}),l(Rt,{color:q.gc,label:u})]}),readout:x&&x.main!==null&&x.gc!==null?r(o,{children:[b!==void 0&&l(Lt,{atMs:b.atMs,spanMs:v.spanMs}),l(Z,{color:q.main,text:d(x.main)}),l(Z,{color:q.gc,text:d(x.gc)})]}):null,children:r(`svg`,{ref:h,viewBox:`0 0 ${U} ${W}`,preserveAspectRatio:`none`,className:`w-full`,style:Ot,role:`img`,"aria-label":`${e}: ${s} and ${u} over time`,onMouseLeave:()=>_(null),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width===0)return;let n=(e.clientX-t.left)/t.width*U-34,r=Dt(v.upper,n);r!==null&&_({index:r,xPx:v.upper[r].x})},children:[l(At,{ticks:v.ticks,max:v.max,formatValue:d}),l(It,{ticks:v.times,spanMs:v.spanMs}),r(`g`,{transform:`translate(34,${H})`,clipPath:`url(#${m})`,children:[l(`clipPath`,{id:m,children:l(`rect`,{x:0,y:0,width:J.width,height:J.height})}),l(jt,{spans:v.gaps}),l(`path`,{d:Ct(v.middle,v.base),fill:q.main,fillOpacity:.85}),l(`path`,{d:Ct(v.upper,v.middle),fill:q.gc,fillOpacity:.85,stroke:`var(--color-surface, transparent)`,strokeWidth:2}),l(`path`,{d:St(v.upper),fill:`none`,stroke:q.gc,strokeWidth:2}),g!==null&&l(`line`,{x1:g.xPx,x2:g.xPx,y1:0,y2:J.height,stroke:`currentColor`,strokeWidth:1,className:`text-foreground-subtle`})]})]})})}function Y({title:e,points:n,formatValue:i,emptyMessage:s,axisFloor:u,axisScale:d=`linear`,gapMs:f}){let p=t(null),[m,h]=c(null),g=a(()=>{let e=vt(n.map(e=>e.value),u,d),t=K(n,J,e,f);return{max:e,ticks:yt(e,d),projected:t,gaps:Et(t),times:wt(n,J),spanMs:Tt(n)}},[n,u,d,f]),_=m===null?void 0:n[m.index],v=_??n.at(-1)??void 0;return n.length===0||g.projected.every(e=>e.y===null)?l(X,{title:e,children:l(zt,{message:s})}):l(X,{title:e,readout:v&&v.value!==null?r(o,{children:[_!==void 0&&l(Lt,{atMs:_.atMs,spanMs:g.spanMs}),l(Z,{color:q.main,text:i(v.value)})]}):null,children:r(`svg`,{ref:p,viewBox:`0 0 ${U} ${W}`,preserveAspectRatio:`none`,className:`w-full`,style:Ot,role:`img`,"aria-label":e,onMouseLeave:()=>h(null),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width===0)return;let n=(e.clientX-t.left)/t.width*U-34,r=Dt(g.projected,n);r!==null&&h({index:r,xPx:g.projected[r].x})},children:[l(At,{ticks:g.ticks,max:g.max,formatValue:i}),l(It,{ticks:g.times,spanMs:g.spanMs}),r(`g`,{transform:`translate(34,${H})`,children:[l(jt,{spans:g.gaps}),l(`path`,{d:St(g.projected),fill:`none`,stroke:q.main,strokeWidth:2}),m!==null&&l(`line`,{x1:m.xPx,x2:m.xPx,y1:0,y2:J.height,stroke:`currentColor`,strokeWidth:1,className:`text-foreground-subtle`})]})]})})}function At({ticks:e,max:t,formatValue:n}){let i=t<=0?1:t;return l(`g`,{className:`text-foreground-subtle`,children:e.map(e=>{let t=H+J.height-e/i*J.height;return r(`g`,{children:[l(`line`,{x1:34,x2:34+J.width,y1:t,y2:t,stroke:`currentColor`,strokeWidth:.5,strokeOpacity:.3}),l(`text`,{x:0,y:t+3,fontSize:8,fill:`currentColor`,children:n(e)})]},e)})})}function jt({spans:e}){return e.length===0?null:l(`g`,{className:`text-foreground-subtle`,children:e.map(e=>l(`rect`,{x:e.fromX,y:0,width:Math.max(1,e.toX-e.fromX),height:J.height,fill:`currentColor`,fillOpacity:.12,children:l(`title`,{children:`No samples in this interval — nothing was measured, nothing is drawn.`})},`${e.fromX}-${e.toX}`))})}var Mt=10*6e4,Nt={hour:`2-digit`,minute:`2-digit`},Pt={hour:`2-digit`,minute:`2-digit`,second:`2-digit`};function Ft(e,t){return new Date(e).toLocaleTimeString(void 0,t<Mt?Pt:Nt)}function It({ticks:e,spanMs:t}){return e.length===0?null:l(`g`,{className:`text-foreground-subtle`,children:e.map(e=>l(`text`,{x:34+e.x,y:ft,fontSize:8,textAnchor:e.anchor,fill:`currentColor`,children:Ft(e.atMs,t)},e.atMs))})}function Lt({atMs:e,spanMs:t}){return l(`span`,{className:`text-[10px] tabular-nums text-foreground-subtle`,children:Ft(e,t)})}function X({title:e,legend:t,readout:n,children:i}){return r(`div`,{className:`min-w-0`,children:[r(`div`,{className:`flex items-baseline justify-between gap-2 mb-1`,children:[l(`span`,{className:`text-[10px] uppercase tracking-wider text-foreground-subtle`,children:e}),l(`div`,{className:`flex items-center gap-2`,children:n})]}),i,t&&l(`div`,{className:`flex items-center gap-3 mt-1`,children:t})]})}function Rt({color:e,label:t}){return r(`span`,{className:`inline-flex items-center gap-1 text-[9px] text-foreground-subtle`,children:[l(`span`,{className:`inline-block h-2 w-2 rounded-[2px]`,style:{backgroundColor:e}}),t]})}function Z({color:e,text:t}){return r(`span`,{className:`inline-flex items-center gap-1 text-[11px] tabular-nums text-foreground`,children:[l(`span`,{className:`inline-block h-2 w-2 rounded-[2px]`,style:{backgroundColor:e}}),t]})}function zt({message:e}){return l(`div`,{className:`h-16 flex items-center justify-center rounded border border-dashed border-border text-[10px] text-foreground-subtle text-center px-2`,children:e})}function Bt(e,t){let n=e.at(-1);return n===void 0?[t]:t.atMs>n.atMs?[...e,t]:e.some(e=>e.atMs===t.atMs)?e:[...e,t].toSorted((e,t)=>e.atMs-t.atMs)}function Vt(e,t,n,r){let i=e.get(t),a=Bt(i?.points??[],r);if(i!==void 0&&a===i.points)return e;let o=new Map(e);return o.set(t,{key:t,kind:n,points:a.slice(Math.max(0,a.length-720))}),o}function Ht(e,t,n){let r=e;for(let e of Me(t,n))r=Vt(r,e.key,e.kind,e.point);return r}function Ut(e,t){let n=e;for(let e of t)for(let t of e.points)n=Vt(n,e.key,e.kind,t);return n}function Wt(e){let t=null;for(let n of e.values()){let e=n.points.at(-1);e!==void 0&&(t===null||e.atMs>t)&&(t=e.atMs)}return t}var Gt=12e4;function Kt(e,t){return e===null?!1:t-e>Gt}function qt(e){let t=e=>{let t=e.points.at(-1);return t===void 0?-1:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.key.localeCompare(n.key):r})}function Jt(e){for(let t of e.values()){let e=t.points.at(-1);if(e&&e.cpuMainPercent!==null)return!0}return!1}var Yt={key:`cpu`,dir:`desc`};function Xt(e){let t=e.points.at(-1);return t===void 0?null:t.cpuMainPercent!==null&&t.cpuGcPercent!==null?t.cpuMainPercent+t.cpuGcPercent:t.cpuLifetimePercent}function Zt(e){return e.points.at(-1)?.memoryRssBytes??null}function Qt(e,t,n){let r=n.trim().toLowerCase();return r===``?!0:e.toLowerCase().includes(r)||t.toLowerCase().includes(r)}function $t(e,t){return t===`memory`?Zt(e):Xt(e)}function en(e,t,n){let r=e.filter(e=>t.selectedKeys.size>0&&!t.selectedKeys.has(e.key)?!1:Qt(n(e),e.key,t.search)),i=(e,t)=>e.key.localeCompare(t.key);return[...r].toSorted((e,r)=>{if(t.sort.key===`name`){let a=n(e).localeCompare(n(r)),o=t.sort.dir===`asc`?a:-a;return o===0?i(e,r):o}let a=$t(e,t.sort.key),o=$t(r,t.sort.key);if(a===null&&o===null)return i(e,r);if(a===null)return 1;if(o===null)return-1;let s=t.sort.dir===`desc`?o-a:a-o;return s===0?i(e,r):s})}n();function tn(e,n=720){let r=L(`metrics.node-processes-snapshot`,t=>t.nodeId===e),[i,a]=c(new Map),[o,s]=c(void 0),l=t(null),{data:d,isPending:f}=ne({forNodeId:e,sinceMs:o,maxPoints:n});u(()=>{d!==void 0&&a(e=>{let t=Ut(e,d.series);return l.current=Wt(t),t})},[d]);let p=r?.timestamp;u(()=>{r==null||p===void 0||(Kt(l.current,p)&&s(l.current??0),a(e=>{let t=Ht(e,r.processes,p);return l.current=Wt(t),t}))},[p]),u(()=>{a(new Map),s(void 0),l.current=null},[e]);let m=0;for(let e of i.values())m=Math.max(m,e.points.length);return{series:qt(i),sampleCount:m,threadSplitAvailable:Jt(i),loadingRetained:f,durable:d?.durable??null,bucketMs:d?.bucketMs??null,cadenceMs:d?.cadenceMs??null,retainedSamples:d?.retainedSamples??null}}var nn=`__unclaimed__`;function rn(e,t){return{kind:e,deviceId:t,cpu:0,cpuKnown:!0,rss:0,rssKnown:!0,count:0,roles:new Set}}function an(e,t){return{key:e,kind:t.kind,deviceId:t.deviceId,cpuSeconds:t.cpuKnown?Math.round(t.cpu*100)/100:null,rssBytes:t.rssKnown?t.rss:null,unitCount:t.count,roles:[...t.roles].sort()}}function on(e,t){let n=new Map,r=new Set;for(let t of e){t.pid!==void 0&&r.add(t.pid);let e=t.deviceId!==null&&t.attribution!==`unattributable`,i=e?`device:${t.deviceId}`:`shared:${t.role}`,a=n.get(i)??rn(e?`camera`:`shared`,e?t.deviceId:null);a.count+=1,a.roles.add(t.role),t.cpuSeconds===void 0?a.cpuKnown=!1:a.cpu+=t.cpuSeconds,t.rssBytes===void 0?a.rssKnown=!1:a.rss+=t.rssBytes,n.set(i,a)}let i=[...n.entries()].map(([e,t])=>an(e,t));if(t===void 0)return i;let a=t.filter(e=>!r.has(e.pid));if(a.length===0)return i;let o=rn(`unclaimed`,null);for(let e of a)o.count+=1,o.rss+=e.memoryRssBytes;return o.cpuKnown=!1,[...i,an(nn,o)]}var sn=[{family:`decode`,attribution:`measured`,unit:`one forked decode-worker child per decode SESSION`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:118`,`packages/addon-pipeline/src/session-decode/fork-decode-worker.ts:131`,`packages/addon-pipeline/src/pipeline-runner/index.ts:2765`,`packages/types/src/process/child-cost-registry.ts:188`]},{family:`transcode`,attribution:`measured`,unit:`one ffmpeg child per (camera, encode plan)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/egress-transcode-manager.ts:960`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:282`,`packages/addon-pipeline/src/stream-broker/stream-broker/transcode-egress.ts:324`,`packages/types/src/ffmpeg/sharing-key.ts:139`]},{family:`recording`,attribution:`measured`,unit:`one passthrough ffmpeg per (camera, profile)`,perCamera:!0,wiredToday:!0,missingLink:``,evidence:[`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:33`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:217`,`packages/addon-pipeline/src/recorder/addon/segment-writer.ts:279`,`packages/addon-pipeline/src/recorder/addon/recording-controller.ts:1710`]},{family:`detection`,attribution:`accounted`,unit:`a SHARED inference pool per (node, runtime, device) — no per-camera process`,perCamera:!1,wiredToday:!0,missingLink:"Nothing is missing for COUNTING — per-camera inference milliseconds, processed/shed frames and bytes-to-pool are already accumulated. What is missing is any basis for CPU seconds: `deviceId` reaches the pool as a diagnostic label and selects nothing, so cost can only ever be apportioned, never measured. Since 2026-08-27 the pool DECLARES this itself, contributing `deviceId: null` + `attribution: unattributable` rather than leaving an observer to infer it — the renunciation is data, and it is still refused by the chart gate.",evidence:[`packages/addon-pipeline/src/detection-pipeline/provider.ts:540`,`packages/addon-pipeline/src/detection-pipeline/engine/shared-inference-pool.ts:413`,`packages/types/src/interfaces/inference-engine.ts:24`,`packages/addon-pipeline/src/pipeline-runner/timing-sampler.ts:63`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:353`,`packages/addon-pipeline/src/pipeline-runner/runner.ts:849`,`packages/addon-pipeline/src/pipeline-runner/frame-lazy-metrics.ts:100`]},{family:`streaming`,attribution:`measured`,unit:"one StreamBroker per `${deviceId}/${camStreamId}`, with an exact RTP ring byte counter",perCamera:!0,wiredToday:!1,missingLink:"The ffmpeg-backed ingest is now reported per camera, but that is the minority path. `rtpRingBytes` — the exact figure for the in-process case — is maintained on every push and drop and is still private and absent from `getStats()`. The three `EncodedRingBuffer`s track packets and duration and have no byte accumulator at all; the only byte figure they offer is `preRollBudgetBytes`, which is a BUDGET, not an occupancy.",evidence:[`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2895`,`packages/addon-pipeline/src/stream-broker/rtsp/ffmpeg-push-reader.ts:189`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:494`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:498`,`packages/addon-pipeline/src/stream-broker/stream-broker/stream-broker.ts:2505`,`packages/addon-pipeline/src/stream-broker/stream-broker/pre-roll.ts:269`]}];function cn(e){return e.attribution===`measured`&&e.wiredToday}function ln(){let e=new Set;for(let t of sn)cn(t)&&e.add(t.family);return e}var un=ln();function dn(e){return!un.has(e.role)||e.deviceId===null?!1:e.attribution===`measured`}function fn(e){return`${e.addonId}${e.role}${e.unit}${e.pid??`-`}`}function pn(){return{cpuSeconds:0,cpuKnown:!0,rssBytes:0,rssKnown:!0,unitCount:0,roles:new Set}}function mn(e,t,n){if(t.cpuSeconds===void 0)return null;if(e===void 0)return t.startedAtMs===void 0||t.startedAtMs<n?null:t.cpuSeconds;if(e.cpuSeconds===void 0||e.startedAtMs===void 0||t.startedAtMs===void 0||e.startedAtMs!==t.startedAtMs)return null;let r=t.cpuSeconds-e.cpuSeconds;return r<0?null:r}function hn(e){return Math.round(e*10)/10}function gn(e,t){let n=t.atMs-e.atMs;if(n<=0)return[];let r=n/1e3,i=new Map;for(let t of e.entries)dn(t)&&i.set(fn(t),t);let a=new Map,o=new Set;for(let n of t.entries){if(!dn(n)||n.deviceId===null)continue;let t=fn(n);o.add(t);let r=a.get(n.deviceId)??pn();r.unitCount+=1,r.roles.add(n.role);let s=mn(i.get(t),n,e.atMs);s===null?r.cpuKnown=!1:r.cpuSeconds+=s,n.rssBytes===void 0?r.rssKnown=!1:r.rssBytes+=n.rssBytes,a.set(n.deviceId,r)}for(let[e,t]of i){if(o.has(e)||t.deviceId===null)continue;let n=a.get(t.deviceId);n!==void 0&&(n.cpuKnown=!1)}return[...a.entries()].map(([e,n])=>({deviceId:e,point:{atMs:t.atMs,cpuPercent:n.cpuKnown?hn(n.cpuSeconds/r*100):null,rssBytes:n.rssKnown?n.rssBytes:null,unitCount:n.unitCount,roles:[...n.roles].toSorted()}}))}function _n(e,t){if(t.length===0)return e;let n=new Map(e);for(let e of t){let t=n.get(e.deviceId),r=t?.points.at(-1);if(r!==void 0&&e.point.atMs<=r.atMs)continue;let i=[...t?.points??[],e.point];n.set(e.deviceId,{deviceId:e.deviceId,points:i.slice(Math.max(0,i.length-720))})}return n}function vn(e){let t=e=>{for(let t=e.points.length-1;t>=0;t--){let n=e.points[t]?.cpuPercent;if(n!=null)return n}return-1};return[...e.values()].toSorted((e,n)=>{let r=t(n)-t(e);return r===0?e.deviceId-n.deviceId:r})}function yn(e){let t=e.indexOf(`@`);return t===-1?{addonId:e,nodeId:null}:{addonId:e.slice(0,t),nodeId:e.slice(t+1)}}function bn(e,t){let n=yn(e);return n.nodeId===null?t.isHub:n.nodeId===t.nodeId}function xn(e,t){return e.filter(e=>bn(e.addonId,t))}n();function Sn(e){let n=L(`metrics.node-processes-snapshot`,t=>t.nodeId===e.nodeId),r=we(void 0,{staleTime:1/0,refetchOnWindowFocus:!1}),[i,a]=c(new Map),o=t(null),s=t(r.refetch);s.current=r.refetch;let l=n?.timestamp;u(()=>{l!==void 0&&s.current()},[l]),u(()=>{a(new Map),o.current=null},[e.nodeId,e.isHub]);let d=r.data,f=r.dataUpdatedAt;u(()=>{if(d===void 0||f===0)return;let t={atMs:f,entries:xn(d,e)},n=o.current;if(o.current=t,n===null)return;let r=gn(n,t);r.length!==0&&a(e=>_n(e,r))},[d,f,e.nodeId,e.isHub]);let p=d===void 0?[]:xn(d,e),m=n?.processes,h=on(p,m);return{series:vn(i),unclaimed:h.find(e=>e.kind===`unclaimed`)??null,loading:r.isPending,error:r.error===null?null:r.error.message}}function Cn(e){let t=new Map;for(let n of e){let e=n.name?.trim();e===void 0||e===``||t.set(n.id,e)}return t}var wn=25,Tn=64*1024*1024,En=1e4;function Dn({scope:e,cadenceMs:t}){let{t:n}=z(),i=Sn(e),{data:a=[]}=De({isCamera:!0,projection:`slim`}),o=Cn(a),s=xt(t??En);return r(`section`,{className:`space-y-3`,children:[i.error!==null&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-[11px] text-destructive`,children:[l(me,{className:`h-3 w-3 mt-0.5 shrink-0`}),l(`span`,{children:n(`cameraLoad.readFailed`,`Could not read the load contributions: {{error}}. This is a failed read, NOT an idle cluster.`,{error:i.error})})]}),l(kn,{unclaimed:i.unclaimed}),i.series.length===0&&i.error===null&&l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:i.loading?n(`cameraLoad.loading`,`Reading what the addons report…`):n(`cameraLoad.waitingWindow`,`No per-camera window yet.`)}),l(`div`,{className:`space-y-3`,children:i.series.map(e=>r(`div`,{className:`rounded-lg border border-border p-3`,children:[r(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[l(On,{deviceId:e.deviceId,name:o.get(e.deviceId)}),l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`cameraLoad.unitCount`,`{{count}} unit(s): {{roles}}`,{count:e.points.at(-1)?.unitCount??0,roles:(e.points.at(-1)?.roles??[]).join(`, `)})})]}),r(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[l(Y,{title:n(`cameraLoad.cpuTitle`,`CPU % of one core (delta)`),points:e.points.map(e=>({atMs:e.atMs,value:e.cpuPercent})),formatValue:e=>`${e.toFixed(1)}%`,axisFloor:wn,gapMs:s,emptyMessage:n(`cameraLoad.cpuUnavailable`,`No measurable window yet.`)}),l(Y,{title:n(`cameraLoad.memoryTitle`,`Memory RSS`),points:e.points.map(e=>({atMs:e.atMs,value:e.rssBytes})),formatValue:R,axisFloor:Tn,axisScale:`bytes`,gapMs:s,emptyMessage:n(`cameraLoad.memoryUnavailable`,`No memory reported.`)})]})]},e.deviceId))})]})}function On({deviceId:e,name:t}){let{t:n}=z();return t===void 0?l(`span`,{className:`text-xs font-medium text-foreground`,children:n(`cameraLoad.deviceLabel`,`Camera {{deviceId}}`,{deviceId:e})}):r(`span`,{className:`flex items-baseline gap-1.5 min-w-0`,children:[l(`span`,{className:`text-xs font-medium text-foreground truncate`,children:t}),r(`span`,{className:`shrink-0 text-[10px] font-mono text-foreground-subtle`,children:[`#`,e]})]})}function kn({unclaimed:e}){let{t}=z();return e===null||e.unitCount===0?null:l(`div`,{className:`flex items-center gap-2`,children:l(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded-full bg-warning/10 text-warning font-medium tabular-nums`,children:t(`cameraLoad.unclaimedBadge`,`{{count}} unclaimed · {{rss}}`,{count:e.unitCount,rss:e.rssBytes===null?`—`:R(e.rssBytes)})})})}n();var An=256*1024*1024,jn=1e4;function Mn({nodeId:e,isHub:t}){let{t:n}=z(),{series:i,sampleCount:o,threadSplitAvailable:s,loadingRetained:u,bucketMs:d,cadenceMs:f}=tn(e),[p,m]=c(``),[h,g]=c(new Set),[_,v]=c(Yt),y=e=>e.key===`__root__`?n(`clusterLoad.bucketRoot`,`Node supervisor`):e.key===`__unattributed__`?n(`clusterLoad.bucketUnattributed`,`Unattributed processes`):e.key,b=xt(d??f??jn),x=a(()=>en(i,{search:p,selectedKeys:h,sort:_},y),[i,p,h,_]),S=e=>{g(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return r(`div`,{className:`space-y-4`,children:[l(Nn,{bucketMs:d,cadenceMs:f}),!s&&o>0&&r(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/5 px-3 py-2 text-[11px] text-warning`,children:[l(me,{className:`h-3 w-3 mt-0.5 shrink-0`}),l(`span`,{children:n(`clusterLoad.noThreadSplit`,`No thread-level CPU split on this node — /proc/<pid>/task is Linux-only, and the first sample after a restart has no window to measure. CPU below falls back to the ps lifetime AVERAGE, which is not a rate.`)})]}),o===0&&l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:u?n(`clusterLoad.loadingRetained`,`Reading the retained series from this node…`):n(`clusterLoad.waitingFirstSample`,`No retained samples for this node — waiting for the next snapshot (up to 20s). The chart needs two to draw a rate.`)}),i.length>0&&r(`div`,{className:`space-y-2`,children:[r(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`label`,{className:`relative flex-1 min-w-[160px]`,children:[l(k,{className:`pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-foreground-subtle`}),l(`input`,{type:`search`,value:p,onChange:e=>m(e.target.value),placeholder:n(`clusterLoad.searchPlaceholder`,`Find a runner…`),"aria-label":n(`clusterLoad.searchLabel`,`Find a runner`),className:`w-full rounded border border-border bg-background py-1 pl-7 pr-2 text-[11px] text-foreground placeholder:text-foreground-subtle`})]}),l(Pn,{sort:_,onChange:v})]}),r(`div`,{className:`flex flex-wrap items-center gap-1`,children:[i.map(e=>{let t=h.has(e.key);return l(`button`,{type:`button`,"aria-pressed":t,onClick:()=>S(e.key),className:`rounded-full border px-2 py-0.5 text-[10px] transition-colors ${t?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:y(e)},e.key)}),h.size>0&&r(`button`,{type:`button`,onClick:()=>g(new Set),className:`inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground`,children:[l(ve,{className:`h-2.5 w-2.5`}),n(`clusterLoad.clearFilter`,`All runners`)]})]})]}),i.length>0&&x.length===0&&l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-[11px] text-foreground-subtle`,children:n(`clusterLoad.noMatches`,`No runner matches this search on {{count}} present. The node is reporting — the filter is hiding them.`,{count:i.length})}),l(`div`,{className:`space-y-3`,children:x.map(e=>r(`div`,{className:`rounded-lg border border-border p-3`,children:[r(`div`,{className:`flex items-baseline justify-between gap-2 mb-2`,children:[l(`span`,{className:`text-xs font-medium text-foreground`,children:y(e)}),l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`clusterLoad.processCount`,`{{count}} process(es)`,{count:e.points.at(-1)?.processCount??0})})]}),r(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[l(kt,{title:s?n(`clusterLoad.cpuTitle`,`CPU % of one core`):n(`clusterLoad.cpuTitleLifetime`,`CPU % (ps lifetime average)`),mainLabel:n(`clusterLoad.seriesMain`,`Main threads`),gcLabel:n(`clusterLoad.seriesGc`,`GC / V8 helpers`),points:e.points.map(e=>({atMs:e.atMs,main:e.cpuMainPercent,gc:e.cpuGcPercent})),formatValue:e=>`${e.toFixed(0)}%`,gapMs:b,emptyMessage:n(`clusterLoad.cpuUnavailable`,`No thread split on this node. Lifetime average: {{avg}}%`,{avg:(e.points.at(-1)?.cpuLifetimePercent??0).toFixed(1)})}),l(Y,{title:n(`clusterLoad.memoryTitle`,`Memory RSS`),points:e.points.map(e=>({atMs:e.atMs,value:e.memoryRssBytes})),formatValue:R,axisFloor:An,axisScale:`bytes`,gapMs:b,emptyMessage:n(`clusterLoad.memoryUnavailable`,`No memory samples yet.`)})]})]},e.key))}),l(Dn,{scope:{nodeId:e,isHub:t},cadenceMs:f})]})}function Nn({bucketMs:e,cadenceMs:t}){let{t:n}=z();return e===null?null:l(`p`,{className:`text-[10px] text-foreground-subtle`,children:t!==null&&e>t?n(`clusterLoad.captionBucket`,`1 point = {{bucket}}s (bucket MAXIMUM, not a mean)`,{bucket:Math.round(e/1e3)}):n(`clusterLoad.captionRaw`,`1 point = 1 snapshot`)})}function Pn({sort:e,onChange:t}){let{t:n}=z(),i=[{key:`cpu`,label:n(`clusterLoad.sortCpu`,`CPU`)},{key:`memory`,label:n(`clusterLoad.sortMemory`,`Memory`)},{key:`name`,label:n(`clusterLoad.sortName`,`Name`)}];return r(`div`,{className:`flex items-center gap-1`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:n(`clusterLoad.sortBy`,`Sort by`)}),i.map(n=>{let i=e.key===n.key;return r(`button`,{type:`button`,"aria-pressed":i,onClick:()=>t(i?{key:n.key,dir:e.dir===`desc`?`asc`:`desc`}:{key:n.key,dir:n.key===`name`?`asc`:`desc`}),className:`rounded border px-1.5 py-0.5 text-[10px] transition-colors ${i?`border-primary bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground`}`,children:[n.label,i&&(e.dir===`desc`?` ↓`:` ↑`)]},n.key)})]})}var Fn=`No per-node settings on this node. Every other setting these addons expose is one value for the whole cluster — edit those in System → Settings, not here.`;function In({nodeId:e,addonIds:t}){return t.length===0?l(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:`No addons on this node`}):l(`div`,{className:`w-full py-2`,children:l(Ie,{nodeId:e,addonIds:t,level:`global`,fieldScope:`perNode`,emptyMessage:Fn,selfTabbed:!0})})}n();function Ln({nodeId:e,addons:t}){let n=s(),{data:r,isLoading:i}=w({nodeId:e}),o=a(()=>{let e=new Map;for(let n of t)for(let t of n.capabilities){let r=e.get(t)??[];r.push(n.id),e.set(t,r)}return[...e.entries()].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({capName:e,providers:t}))},[t]),c=be({onSuccess:()=>{n.invalidateQueries({queryKey:[[`pipelineOrchestrator`,`getCapabilityBindings`]]})}});return o.length===0?l(`div`,{className:`py-4 text-xs text-muted-foreground text-center`,children:`No capabilities on this node`}):l(b,{columns:[{key:`capName`,header:`Capability`,width:`w-1/2`,sortValue:e=>e.capName,render:e=>l(`span`,{className:`font-medium`,children:e.capName})},{key:`provider`,header:`Bound provider`,render:t=>{let n=r?.[t.capName]??t.providers[0]??``,a=t.providers.length===1;return l(`select`,{value:n,onChange:n=>c.mutate({nodeId:e,capName:t.capName,addonId:n.target.value}),disabled:a||c.isPending||i,className:`w-full rounded-md border border-border bg-surface px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-60`,title:a?`Only one provider installed — choice becomes available once a second addon registers this capability`:void 0,children:t.providers.map(e=>l(`option`,{value:e,children:e},e))})}}],rows:o,rowKey:e=>e.capName,minWidthPx:520,mobileMode:`cards`,maxBodyHeight:N})}n();function Rn(e){if(e==null)return`—`;let t=Math.floor(e/1e3),n=Math.floor(t/86400),r=Math.floor(t%86400/3600),i=Math.floor(t%3600/60);return n>0?`${n}d ${r}h ${i}m`:r>0?`${r}h ${i}m`:`${i}m`}function zn(e){let[t,n]=c(!1),[i,a]=c(e.name),o=s(),u=ye({onSuccess:()=>{o.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}}),d=(e.localIps??[]).filter(e=>!e.includes(`:`)),f=(e.localIps??[]).filter(e=>e.includes(`:`)),p=async()=>{if(!i.trim()||i===e.name){n(!1);return}try{await u.mutateAsync({nodeId:e.nodeId,name:i.trim()}),n(!1)}catch(e){console.error(`Rename failed:`,e)}},m=[[`Node ID`,l(`span`,{className:`font-mono text-xs`,children:e.nodeId})],[`Display Name`,t?r(`div`,{className:`flex items-center gap-1.5`,children:[l(`input`,{type:`text`,className:`flex-1 px-2 py-0.5 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&p(),e.key===`Escape`&&n(!1)},disabled:u.isPending,autoFocus:!0}),l(`button`,{onClick:()=>void p(),disabled:u.isPending,className:`p-0.5 text-success hover:bg-success/10 rounded`,title:`Save`,children:l(F,{className:`h-3.5 w-3.5`})}),l(`button`,{onClick:()=>n(!1),className:`p-0.5 text-muted-foreground hover:bg-muted rounded`,title:`Cancel`,children:l(ve,{className:`h-3.5 w-3.5`})})]}):r(`div`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-xs`,children:e.name}),!e.isHub&&l(`button`,{onClick:()=>{a(e.name),n(!0)},className:`p-0.5 text-muted-foreground hover:text-primary rounded`,title:`Rename`,children:l(ge,{className:`h-3 w-3`})})]})],[`Hostname`,l(`span`,{className:`text-xs`,children:e.hostname})],[`Role`,e.isHub?l(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium`,children:`Hub`}):l(`span`,{className:`text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-medium`,children:`Agent`})],[`Root Package`,e.rootPackage?r(`span`,{className:`font-mono text-xs`,children:[e.rootPackage.name,`@`,e.rootPackage.version]}):l(`span`,{className:`text-xs text-muted-foreground`,children:`—`})],[`Platform`,r(`span`,{className:`text-xs`,children:[e.platform,` / `,e.arch]})],[`CPU`,r(`span`,{className:`text-xs`,children:[e.cpuModel??`—`,` (`,e.cpuCores,` cores)`]})],[`Memory`,l(`span`,{className:`text-xs`,children:e.memoryMB>0?`${(e.memoryMB/1024).toFixed(1)} GB`:`—`})],[`Uptime`,l(`span`,{className:`text-xs`,children:Rn(e.uptime)})],[`Engines`,e.engines.length>0?l(`div`,{className:`flex flex-wrap gap-1`,children:e.engines.map(e=>l(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e))}):l(`span`,{className:`text-xs text-muted-foreground`,children:`—`})]];return d.length>0&&m.push([`IPv4`,l(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map((e,t)=>l(`span`,{className:`font-mono text-xs px-1.5 py-0.5 rounded bg-muted`,children:e},`${e}-${t}`))})]),f.length>0&&m.push([`IPv6`,l(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map((e,t)=>l(`span`,{className:`font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[280px]`,title:e,children:e},`${e}-${t}`))})]),l(`div`,{className:`py-2`,children:l(`table`,{className:`w-full text-sm`,children:l(`tbody`,{children:m.map(([e,t],n)=>r(`tr`,{className:n%2==0?`bg-muted/20`:``,children:[l(`td`,{className:`py-1.5 px-2 text-xs font-medium text-muted-foreground w-28 align-top whitespace-nowrap`,children:e}),l(`td`,{className:`py-1.5 px-2`,children:t})]},e))})})})}n();function Bn({nodeId:e,value:t,detectedHosts:n,status:i,errorMessage:a,onCommit:o}){let[s,d]=c(t??``);u(()=>{d(t??``)},[t]);let f=n[0],p=f===void 0?`auto-detect`:`auto: ${f}`,m=i===`pending`,h=s.trim(),g=h!==(t??``),_=g&&!m,y=()=>{_&&o(e,h.length>0?h:null)};return r(`div`,{className:`flex items-center gap-1.5`,children:[l(O,{"aria-label":`Reachable host for ${e}`,type:`text`,inputMode:`url`,autoComplete:`off`,spellCheck:!1,placeholder:p,value:s,disabled:m,onChange:e=>d(e.target.value),onBlur:y,onKeyDown:e=>{e.key===`Enter`&&y(),e.key===`Escape`&&d(t??``)},className:`w-36`}),r(S,{variant:`outline`,size:`sm`,onClick:y,disabled:!_,"aria-label":`Save reachable host for ${e}`,title:`Save reachable host`,children:[m?l(v,{className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):l(F,{className:`h-3 w-3`,"aria-hidden":`true`}),`Save`]}),!g&&!m&&i===`success`&&l(F,{className:`h-3.5 w-3.5 shrink-0 text-success`,"aria-label":`Saved`,role:`img`}),i===`error`&&l(`span`,{title:a??`Failed to save reachable host`,children:l(he,{className:`h-3.5 w-3.5 shrink-0 text-danger`,"aria-label":a??`Failed to save reachable host`,role:`img`})})]})}n();function Vn(e){let t=Ne.safeParse(Le(e,`color`));return t.success?t.data:null}function Hn(e,t){return t.variables?.agentNodeId===e?t.isPending?`pending`:t.isError?`error`:t.isSuccess?`success`:`idle`:`idle`}function Un({nodeId:e,detectedHosts:t}){let{t:n}=z(),i=s(),o=y(void 0),c=le({onSuccess:()=>Re(i)}),u=le({onSuccess:()=>Re(i)}),d=a(()=>o.data?.find(t=>t.nodeId===e)?.settings,[o.data,e]),f=Vn(d)??(o.isLoading?null:Ae(e)),p=ze(d,`reachableHost`),m=Hn(e,c),h=m===`error`?Be(c.error):null,g=t.filter(e=>!e.includes(`:`)),_=t=>{t!==f&&u.mutate({agentNodeId:e,color:t})};return r(`div`,{className:`rounded-lg border border-border bg-surface/40 divide-y divide-border px-3`,children:[l(P,{label:n(`nodes.general.nodeColour`,`Node colour`),children:l(`div`,{role:`group`,"aria-label":n(`nodes.general.nodeColourGroup`,`Node colour`),className:`flex flex-wrap gap-2`,children:je.map(e=>{let t=f===e;return l(S,{type:`button`,role:`radio`,"aria-checked":t,"aria-label":e,variant:`outline`,size:`sm`,disabled:o.isLoading||u.isPending,title:e,onClick:()=>_(e),className:`h-6 w-6 min-w-6 shrink-0 rounded-full border-0 p-0 ${te(e)} ${t?`ring-2 ring-primary ring-offset-2 ring-offset-background`:`opacity-80 hover:opacity-100`}`,children:l(`span`,{className:`sr-only`,children:e})},e)})})}),l(P,{label:n(`nodes.general.reachableHost`,`Reachable host`),children:l(Bn,{nodeId:e,value:p,detectedHosts:g,status:m,errorMessage:h,onCommit:(e,t)=>{c.mutate({agentNodeId:e,reachableHost:t})}})})]})}n();var Wn=[[`serverManagement`,`getServerPackageStatus`]];function Gn({label:e,tone:t}){return l(`span`,{className:`inline-flex items-center rounded px-2 py-0.5 text-[11px] font-medium ${{neutral:`bg-surface-muted text-foreground-subtle`,ok:`bg-success/15 text-success`,info:`bg-info/15 text-info`,warn:`bg-warning/15 text-warning`,error:`bg-danger/15 text-danger`}[t]}`,children:e})}function Q({label:e,value:t}){return r(`div`,{className:`flex items-center justify-between gap-4 text-sm`,children:[l(`span`,{className:`text-foreground-subtle`,children:e}),l(`span`,{className:`font-mono text-foreground`,children:t??`—`})]})}function Kn({runningVersion:e,latestVersion:t,seedVersion:n,nodeRuntimeVersion:i,labelRunning:a,labelLatest:o,labelSeed:s,labelRuntime:c}){return l(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-sm`,children:[{key:`running`,label:a,value:e},{key:`latest`,label:o,value:t},{key:`seed`,label:s,value:n},{key:`runtime`,label:c,value:i}].map(({key:e,label:t,value:n})=>r(`span`,{className:`inline-flex items-baseline gap-1`,children:[l(`span`,{className:`text-foreground-subtle`,children:t}),l(`span`,{className:`font-mono text-foreground`,children:n??`—`})]},e))})}var qn={ok:`border-success/40 bg-success/10 text-success`,warn:`border-warning/40 bg-warning/10 text-warning`,error:`border-danger/40 bg-danger/10 text-danger`};function Jn(e){return e.outcome===`failed`?`error`:(e.outcome,e.accepted?`ok`:`warn`)}function Yn(e,t){let n=t instanceof Error?t.message:String(t);return`${e(`serverManagement.outcomeDropped`,`The connection dropped and the result could not be confirmed. The node may be restarting — re-check the version above.`)} — ${n}`}function Xn({node:t}){let{t:n}=z(),i=s(),a=Se(),[o,u]=c(!1),[d,f]=c(null),p=t.isHub?void 0:{nodeId:t.id},m=Oe(p,{refetchInterval:1e4,enabled:t.isOnline,retry:1}),h=m.data??null,g=e(()=>{i.invalidateQueries({queryKey:Wn})},[i]),y=A({onSettled:g}),b=C({onSettled:g}),x=_({onSettled:g}),S=e(async()=>{if(h?.latestVersion==null){f({tone:`warn`,text:n(`serverManagement.outcomeNoTarget`,`No target version is known for this node — run "Check for update" first.`)});return}if(await a({title:n(`serverManagement.confirmUpdateTitle`,`Update node root package`),message:n(`serverManagement.confirmUpdateBody`,`Install {{pkg}}@{{version}} on "{{node}}" and restart to apply.`,{pkg:h.packageName,version:h.latestVersion,node:t.name}),confirmLabel:n(`serverManagement.confirmUpdateAction`,`Update & restart`)})){f(null);try{let e=await b.mutateAsync({version:h.latestVersion,...p});f({tone:Jn(e),text:e.message}),e.restarting&&u(!0)}catch(e){f({tone:`warn`,text:Yn(n,e)})}}},[b,a,t.name,p,h,n]),w=e(async()=>{if(await a({title:n(`serverManagement.confirmRestartTitle`,`Restart node`),message:n(`serverManagement.confirmRestartBody`,`Restart "{{node}}"? In-flight requests to this node are dropped.`,{node:t.name}),confirmLabel:n(`serverManagement.confirmRestartAction`,`Restart`),variant:`warning`})){f(null);try{let e=await x.mutateAsync(p);f({tone:Jn(e),text:e.message}),e.restarting&&u(!0)}catch(e){f({tone:`warn`,text:Yn(n,e)})}}},[a,t.name,x,p,n]),T=()=>{switch(h?.bootMode){case`data-root`:return{label:n(`serverManagement.bootDataRoot`,`runtime-updatable`),tone:`ok`};case`workspace`:return{label:n(`serverManagement.bootWorkspace`,`dev workspace`),tone:`info`};default:return{label:n(`serverManagement.bootBaked`,`baked image seed`),tone:`neutral`}}},D=()=>{if(h==null)return null;switch(h.updateState){case`checking`:return{label:n(`serverManagement.stateChecking`,`checking…`),tone:`info`};case`staging`:return{label:n(`serverManagement.stateStaging`,`updating…`),tone:`info`};case`pending-restart`:return{label:n(`serverManagement.statePending`,`restart pending`),tone:`warn`};default:return h.restartRequired===!0?{label:n(`serverManagement.stateRestartRequired`,`restart required`),tone:`warn`}:h.updateAvailable?{label:n(`serverManagement.stateUpdateAvailable`,`update available`),tone:`warn`}:{label:n(`serverManagement.stateUpToDate`,`up to date`),tone:`ok`}}},O=h?.bootMode===`workspace`,k=t.isOnline&&h!=null&&!O&&h.updateAvailable&&h.updateState===`idle`&&!b.isPending,j=t.isOnline&&h!=null&&h.updateState===`idle`&&!x.isPending,M=t.isOnline?D():null;return r(`div`,{className:`space-y-4 py-2`,children:[r(`div`,{className:`flex items-center justify-between gap-3`,children:[r(`div`,{className:`flex items-center gap-2 min-w-0`,children:[l(`span`,{className:`font-mono text-xs text-foreground-subtle truncate`,children:h?.packageName??t.rootPackage?.name??`@camstack/server`}),t.isOnline&&h!=null&&l(Gn,{...T()})]}),M!=null&&l(Gn,{...M})]}),!t.isOnline&&l(Q,{label:n(`serverManagement.lastReportedVersion`,`Last reported version`),value:t.rootPackage?.version??null}),t.isOnline&&m.isLoading&&r(`div`,{className:`flex items-center gap-2 text-sm text-foreground-subtle`,children:[l(v,{className:`h-4 w-4 animate-spin`}),n(`common.loading`,`Loading…`)]}),t.isOnline&&m.isError&&r(`div`,{className:`space-y-1.5`,children:[l(`p`,{className:`text-sm text-danger`,children:n(`serverManagement.loadError`,`Could not load the node root-package status.`)}),t.rootPackage!=null&&l(Q,{label:n(`serverManagement.lastReportedVersion`,`Last reported version`),value:t.rootPackage.version})]}),t.isOnline&&h!=null&&r(`div`,{className:`space-y-1.5`,children:[l(Kn,{runningVersion:h.runningVersion,latestVersion:h.latestVersion,seedVersion:h.seedVersion,nodeRuntimeVersion:h.nodeRuntimeVersion,labelRunning:n(`serverManagement.runningVersionShort`,`Running`),labelLatest:n(`serverManagement.latestVersionShort`,`Latest`),labelSeed:n(`serverManagement.imageSeedShort`,`Seed`),labelRuntime:n(`serverManagement.nodeRuntimeVersionShort`,`Node.js`)}),h.pendingVersion!=null&&l(Q,{label:n(`serverManagement.pendingVersion`,`Staged (applies on restart)`),value:h.pendingVersion}),h.installedVersion!=null&&h.installedVersion!==h.runningVersion&&l(Q,{label:n(`serverManagement.installedVersion`,`Installed on disk (runs after restart)`),value:h.installedVersion})]}),t.isOnline&&h?.imageContract?.state===`behind-series`&&r(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs leading-relaxed text-danger`,children:[l(`p`,{className:`mb-0.5 font-semibold`,children:n(`serverManagement.imageContractDiverged`,`Container image diverges from the deployment contract`)}),l(`p`,{children:h.imageContract.message})]}),t.isOnline&&O&&l(`p`,{className:`text-xs text-foreground-subtle`,children:n(`serverManagement.workspaceNote`,`Development workspace detected — runtime updates are disabled (the dev loop resolves code from the workspace).`)}),d!=null&&l(`p`,{role:`status`,className:`rounded border px-2 py-1.5 text-xs leading-relaxed ${qn[d.tone]}`,children:d.text}),o&&r(`div`,{className:`flex items-center gap-2 text-sm text-warning`,children:[l(v,{className:`h-4 w-4 animate-spin`}),n(`serverManagement.nodeRestarting`,`The node is restarting to apply the change…`)]}),t.isOnline&&r(`div`,{className:`flex flex-wrap items-center gap-2 pt-1`,children:[r(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:y.isPending||h?.updateState===`staging`,onClick:()=>y.mutate(p),children:[y.isPending?l(v,{className:`h-3.5 w-3.5 animate-spin`}):l(oe,{className:`h-3.5 w-3.5`}),n(`serverManagement.checkForUpdate`,`Check for update`)]}),k&&r(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50`,onClick:()=>void S(),children:[b.isPending?l(v,{className:`h-3.5 w-3.5 animate-spin`}):l(E,{className:`h-3.5 w-3.5`}),n(`serverManagement.updateTo`,`Update to {{version}}`,{version:h?.latestVersion??``})]}),r(`button`,{type:`button`,className:`inline-flex items-center gap-1.5 rounded border border-border px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-surface-muted disabled:opacity-50`,disabled:!j,onClick:()=>void w(),children:[x.isPending?l(v,{className:`h-3.5 w-3.5 animate-spin`}):l(I,{className:`h-3.5 w-3.5`}),n(`serverManagement.restart`,`Restart`)]})]}),t.isOnline&&h?.lastCheckedAtMs!=null&&r(`p`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[l(ke,{className:`h-3 w-3`}),n(`serverManagement.lastChecked`,`Last checked: {{when}}`,{when:new Date(h.lastCheckedAtMs).toLocaleString()})]})]})}n();function Zn(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`reachableHost`);return typeof t==`string`&&t.length>0?t:null}function Qn({node:t}){let n=m(),i=s(),[u,d]=c(`info`),[p,h]=c(!1),[g,_]=c(null),v=t.processes??[],b=t.addons.map(e=>e.id),S=y(void 0),C=a(()=>{let e=S.data?.find(e=>e.nodeId===t.id);return Zn(e?.settings)},[S.data,t.id]),[w,T]=c(!1),[E,O]=c(null),[k,A]=c(null),j=e(async()=>{if(w||t.isHub)return;let e=Ze(t.localIps??[],C);if(e===null){O(`No LAN IPv4 on this node — open its :4444 URL by hand.`),A(null);return}let r=et();T(!0),O(null),A(null);try{let i=qe(await n.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:t.id,dashboardBaseUrl:Qe(e)}})),a=i===null?null:i.dashboardUrl??$e(e,i.ticket);if(a===null){r?.close(),O(`Hub did not return an unlock ticket.`);return}tt(r,a)||(A(a),O(`Browser blocked the new tab — click the link below (or allow popups for this site).`))}catch(e){r?.close(),O(e instanceof Error?e.message:String(e))}finally{T(!1)}},[t.id,t.isHub,t.localIps,w,C,n.trpcClient]),M=async()=>{if(!p){h(!0),_(null);try{await n.trpcClient.pipelineOrchestrator.removeAgentSettings.mutate({agentNodeId:t.id}).catch(()=>void 0);let e=await n.trpcClient.clusterNodes.forgetNode.mutate({nodeId:t.id});_({tone:e.stillListed?`warn`:`ok`,text:e.message}),e.stillListed||i.invalidateQueries({queryKey:[[`nodes`,`topology`]]})}catch(e){_({tone:`warn`,text:`Forget failed: ${e instanceof Error?e.message:String(e)}`})}finally{h(!1)}}};return t.isOnline?r(`div`,{className:`border border-border rounded-xl`,children:[r(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30 border-b border-border rounded-t-xl`,children:[r(`div`,{className:`flex min-w-0 flex-1 basis-full items-center gap-x-2 gap-y-1 sm:basis-auto sm:flex-initial`,children:[l(`div`,{className:`w-2.5 h-2.5 rounded-full bg-success shrink-0`}),l(`span`,{className:`text-sm font-semibold shrink-0`,children:t.name}),r(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[t.cpuModel??t.platform,` ·`,` `,t.memoryMB>0?`${Math.round(t.memoryMB/1024)}GB`:``,` · `,t.arch]})]}),t.engines.map(e=>l(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium shrink-0`,children:e},e)),r(`div`,{className:`flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-1 text-xs text-muted-foreground w-full sm:ml-auto sm:w-auto`,children:[!t.isHub&&r(`button`,{type:`button`,onClick:()=>void j(),disabled:w,title:`Open this agent's status dashboard (unlocks with a short-lived hub ticket)`,className:`inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-xs text-foreground hover:bg-surface-hover disabled:opacity-50`,children:[l(x,{className:`h-3 w-3`}),w?`Opening…`:`Open dashboard`]}),r(`span`,{className:`flex items-center gap-1`,children:[l(D,{className:`h-3 w-3`}),` `,t.cpuPercent,`%`]}),r(`span`,{className:`flex items-center gap-1`,children:[l(Ue,{className:`h-3 w-3`}),` `,t.memoryPercent,`%`]})]})]}),(E!==null||k!==null)&&r(`p`,{role:`status`,className:`px-4 pt-2 text-xs text-warning`,children:[E,k!==null&&r(o,{children:[` `,l(`a`,{href:k,target:`_blank`,rel:`noreferrer`,className:`underline text-foreground`,children:`Open dashboard`})]})]}),l(`div`,{className:`sticky top-0 z-20 flex border-b border-border px-4 bg-background overflow-x-auto`,children:[`info`,`forks`,`processes`,`load`,`settings`,`capabilities`].map(e=>l(`button`,{onClick:()=>d(e),className:`shrink-0 whitespace-nowrap px-3 py-2 text-xs font-medium border-b-2 transition-colors ${u===e?`border-primary text-primary`:`border-transparent text-muted-foreground hover:text-foreground`}`,children:e===`info`?`General`:e===`forks`?`Forks (${v.length})`:e===`processes`?`Processes`:e===`load`?`Load`:e===`settings`?`Settings`:`Capabilities`},e))}),r(`div`,{className:`px-4 py-2`,children:[u===`info`&&r(`div`,{className:`space-y-3`,children:[l(zn,{nodeId:t.id,name:t.name,hostname:t.hostname,platform:t.platform,arch:t.arch,cpuModel:t.cpuModel,cpuCores:t.cpuCores,memoryMB:t.memoryMB,engines:t.engines,isHub:t.isHub,uptime:t.uptime,localIps:t.localIps,rootPackage:t.rootPackage}),l(Un,{nodeId:t.id,detectedHosts:t.localIps??[]}),l(`div`,{className:`border-t border-border pt-1`,children:l(Xn,{node:{id:t.id,name:t.name,isHub:t.isHub,isOnline:t.isOnline,rootPackage:t.rootPackage??null}})})]}),u===`forks`&&l(ot,{nodeId:t.id,processes:v}),u===`processes`&&l(ut,{nodeId:t.id}),u===`load`&&l(Mn,{nodeId:t.id,isHub:t.isHub}),u===`settings`&&l(In,{nodeId:t.id,addonIds:b}),u===`capabilities`&&l(Ln,{nodeId:t.id,addons:t.addons})]})]}):r(`div`,{className:`border border-border rounded-xl overflow-hidden opacity-60`,children:[r(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-4 py-3 bg-muted/30`,children:[l(`div`,{className:`w-2.5 h-2.5 rounded-full bg-destructive shrink-0`}),l(`span`,{className:`text-sm font-semibold shrink-0`,children:t.name}),r(`span`,{className:`text-xs text-muted-foreground min-w-0 truncate`,children:[t.cpuModel??t.platform,` ·`,` `,t.memoryMB>0?`${Math.round(t.memoryMB/1024)}GB`:``,` · `,t.arch]}),t.engines.map(e=>l(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:e},e)),t.rootPackage&&r(`span`,{className:`text-[10px] font-mono px-1.5 py-0.5 rounded bg-muted text-muted-foreground`,children:[t.rootPackage.name,`@`,t.rootPackage.version]}),l(`span`,{className:`ml-auto text-xs px-2 py-0.5 rounded-full bg-destructive/10 text-destructive`,children:`offline`})]}),r(`div`,{className:`flex items-center justify-between gap-3 px-4 py-3`,children:[r(`span`,{className:`text-xs text-muted-foreground`,children:[t.lastSeen?`Last seen ${new Date(t.lastSeen).toLocaleString()} — `:``,t.addons.length,` addon`,t.addons.length===1?``:`s`,` assigned; will resume when node reconnects`]}),r(`button`,{type:`button`,onClick:()=>void M(),disabled:p,title:`Forget this node — removes its saved history and pipeline assignments`,className:`flex items-center gap-1 text-xs px-2 py-1 rounded-md border border-border text-muted-foreground hover:text-destructive hover:border-destructive/50 disabled:opacity-50 transition-colors`,children:[l(f,{className:`h-3 w-3`}),p?`Forgetting…`:`Forget node`]})]}),g!=null&&l(`p`,{role:`status`,className:`px-4 pb-3 text-xs leading-relaxed ${g.tone===`ok`?`text-success`:`text-warning`}`,children:g.text})]})}var $=3,$n=7e3;function er(e){return[...e].sort((e,t)=>e.isHub===t.isHub?0:e.isHub?1:-1)}function tr(e){return e.isHub?{}:{nodeId:e.id}}function nr(e){return e.updateState===`staging`||e.updateState===`pending-restart`||e.pendingVersion!==null?!0:!e.updateAvailable}async function rr(e,t){let n=tr(e),r=`no answer`;for(let i=1;i<=$;i+=1)try{let r=await t.readStatus(n);return nr(r)?{nodeId:e.id,nodeName:e.name,outcome:`applied`,detail:`Connection dropped, and the node confirms the update landed (state ${r.updateState}, running ${r.runningVersion??`unknown`}).`}:{nodeId:e.id,nodeName:e.name,outcome:`failed`,detail:`Connection dropped and the node came back unchanged (still ${r.runningVersion??`unknown`}, update still available). Nothing was staged.`}}catch(e){r=e instanceof Error?e.message:String(e),i<$&&await t.wait($n)}return{nodeId:e.id,nodeName:e.name,outcome:`unconfirmed`,detail:`Connection dropped and the node could not be confirmed after ${$} attempts (${r}). It may be restarting — re-check this node.`}}function ir(e){return e.accepted?`applied`:e.outcome===`failed`?`failed`:`refused`}async function ar(e,t){let n=[];for(let r of er(e))try{let e=await t.apply(tr(r));n.push({nodeId:r.id,nodeName:r.name,outcome:ir(e),detail:e.message})}catch{n.push(await rr(r,t))}return n}n();function or(){let{nodes:e,isLoading:t}=ce(),n=a(()=>e??[],[e]);return{nodes:n,isLoading:t&&n.length===0}}var sr={applied:`border-success/40 bg-success/10 text-success`,refused:`border-warning/40 bg-warning/10 text-warning`,failed:`border-danger/40 bg-danger/10 text-danger`,unconfirmed:`border-warning/40 bg-warning/10 text-warning`};function cr(){let{t}=z(),n=Se(),{nodes:i,isLoading:s}=or(),[d,f]=Pe(),{selection:p,selectNode:h}=He(i),g=p.node,_=a(()=>i.filter(e=>e.isOnline),[i]),y=_.length,b=i.filter(e=>!e.isOnline).length,x=C(),w=m(),[T,D]=c(!1),[O,k]=c([]),A=d.get(`unlockNode`),j=d.get(`returnTo`),[N,P]=c(null);u(()=>{if(A===null||j===null)return;let e=!1;return(async()=>{try{let t=await w.trpcClient.addons.custom.mutate({addonId:`system-config`,action:`mintAgentUiUnlockTicket`,input:{nodeId:A,dashboardBaseUrl:j}});if(e)return;let n=qe(t),r=n===null?null:n.dashboardUrl??(()=>{let e=new URL(j);return e.searchParams.set(`ticket`,n.ticket),e.toString()})();if(r===null){P(`Could not mint an unlock ticket.`);return}let i=new URLSearchParams(d);i.delete(`unlockNode`),i.delete(`returnTo`),f(i,{replace:!0}),window.location.assign(r)}catch(t){e||P(t instanceof Error?t.message:String(t))}})(),()=>{e=!0}},[A,j,d,f,w.trpcClient]);let ee=e(async()=>{let e=_.map(e=>({id:e.id,name:e.name,isHub:e.isHub}));if(await n({title:t(`serverManagement.confirmUpdateAllTitle`,`Update all nodes`),message:t(`serverManagement.confirmUpdateAllBody`,`Update and restart every online node, agents first, hub last. Up-to-date nodes are skipped; this page reconnects when the hub comes back.`),confirmLabel:t(`serverManagement.confirmUpdateAllAction`,`Update all & restart`),variant:`warning`})){D(!0),k([]);try{k(await ar(e,{apply:e=>x.mutateAsync(e),readStatus:e=>w.trpcClient.serverManagement.getServerPackageStatus.query(e),wait:e=>new Promise(t=>setTimeout(t,e))}))}finally{D(!1)}}},[x,n,_,w,t]);return r(Fe,{icon:ue,title:t(`nav.nodes`,`Nodes`),subtitle:t(`cluster.subtitle`,`One node at a time — topology, packages and the cluster secret agents need to join.`),actions:r(o,{children:[y>0&&r(`span`,{className:`rounded-full bg-success/10 px-2 py-0.5 text-xs text-success`,children:[y,` online`]}),b>0&&r(`span`,{className:`rounded-full bg-destructive/10 px-2 py-0.5 text-xs text-destructive`,children:[b,` offline`]}),y>1&&r(S,{type:`button`,size:`sm`,disabled:T,title:t(`serverManagement.updateAllHint`,`Sequenced agents-first, hub-last — up-to-date nodes are skipped.`),onClick:()=>void ee(),children:[T?l(v,{className:`h-3.5 w-3.5 animate-spin`}):l(E,{className:`h-3.5 w-3.5`}),t(`serverManagement.updateAll`,`Update all nodes`)]})]}),children:[O.length>0&&l(`ul`,{"aria-label":`update-all-report`,className:`flex flex-col gap-1 text-xs`,children:O.map(e=>r(`li`,{"data-outcome":e.outcome,className:`rounded border px-2 py-1 ${sr[e.outcome]}`,children:[l(`span`,{className:`font-medium`,children:e.nodeName}),l(`span`,{className:`mx-1 uppercase tracking-wide`,children:e.outcome}),l(`span`,{className:`opacity-80`,children:e.detail})]},e.nodeId))}),N!==null&&r(`p`,{role:`alert`,className:`rounded border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,children:[`Unlock from agent failed: `,N]}),l(Ge,{}),s?l(`div`,{className:`flex items-center justify-center py-12 text-muted-foreground`,children:`Loading cluster topology...`}):g===null?l(`div`,{className:`rounded-md border border-dashed border-border px-3 py-6 text-center text-xs text-foreground-subtle`,children:t(`cluster.noNodes`,`No nodes in this cluster yet.`)}):r(`div`,{className:`flex flex-col gap-3`,children:[l(Ve,{staleNodeId:p.staleNodeId,shownNodeName:g.name}),l(M,{selectedNodeId:g.id,onSelect:h,allowOffline:!0,alwaysShow:!0}),l(Qn,{node:g})]})]})}export{cr as ClusterPage};