@camstack/addon-admin-ui 1.2.505 → 1.2.507

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 (124) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/assets/{AddonAssetIcon-CvrR3ZEp.js → AddonAssetIcon-BP6wggBn.js} +1 -1
  3. package/dist/assets/{Addons-CtYXCXR3.js → Addons-BByydqJ9.js} +1 -1
  4. package/dist/assets/{AdminPage-CRBjpZ4t.js → AdminPage-C24QbcFs.js} +1 -1
  5. package/dist/assets/{AdminSectionedPage-O_gaWBic.js → AdminSectionedPage-Dj6jU_7A.js} +1 -1
  6. package/dist/assets/AiProfiles-CAdvqX3L.js +3 -0
  7. package/dist/assets/{BrokerEditorDialog--vuPcV-I.js → BrokerEditorDialog-DvynfPt_.js} +1 -1
  8. package/dist/assets/Build-BwIB30Ez.js +40 -0
  9. package/dist/assets/{Calendars-D82HISef.js → Calendars-Bi6uaUyD.js} +1 -1
  10. package/dist/assets/{Cluster-D-6ztV8U.js → Cluster-BvMk0ecH.js} +1 -1
  11. package/dist/assets/{CompositionBlockEditor-BdgsCxJZ.js → CompositionBlockEditor-CtDesZ-k.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-B91Y66Yn.js → CompositionEditorPage-B_Bz_uet.js} +1 -1
  13. package/dist/assets/{Data-q4PMBaIS.js → Data-Bi2TJqdc.js} +1 -1
  14. package/dist/assets/DeviceDetail-trFE_wrk.js +2 -0
  15. package/dist/assets/{DeviceDoActionFields-D-6QkJSs.js → DeviceDoActionFields-CTwsKNgQ.js} +1 -1
  16. package/dist/assets/{Devices-DJs8xwIW.js → Devices-Cpj1qi1_.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-CohChj9F.js → EmbedPlayerPage-DQXbWoop.js} +1 -1
  18. package/dist/assets/HelperWizard-BPQAjrEW.js +2 -0
  19. package/dist/assets/{History-Bt4HOJAj.js → History-DHBf_F9r.js} +1 -1
  20. package/dist/assets/{Identity-Chnmwk7d.js → Identity-R0UVdCby.js} +1 -1
  21. package/dist/assets/{IntegrationDetail-BWf4S4PI.js → IntegrationDetail-5PqYttVA.js} +1 -1
  22. package/dist/assets/{IntegrationHub-CruhQ18c.js → IntegrationHub-2FGWiuhL.js} +1 -1
  23. package/dist/assets/{Integrations-Orv4u7hu.js → Integrations-Bapm_dQX.js} +1 -1
  24. package/dist/assets/{Integrations-swzrdB7i.js → Integrations-sFzMeZSP.js} +1 -1
  25. package/dist/assets/{Library-CUQkRmgv.js → Library-C13RH4-r.js} +1 -1
  26. package/dist/assets/{Locations-BZ9_OyBS.js → Locations-D06IW9NQ.js} +1 -1
  27. package/dist/assets/{Logs-Czk-XHEo.js → Logs-DDnRy0yw.js} +1 -1
  28. package/dist/assets/{MaskShapeCanvas-DnJ8OyvO.js → MaskShapeCanvas-B-mYS6nx.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-BZ-C5Bpc.js → MotionZonesSettings-Aeho9WQB.js} +1 -1
  30. package/dist/assets/{MyAccess-Bk_kcdO9.js → MyAccess-BjUjf7mc.js} +1 -1
  31. package/dist/assets/{Network-DbdD1jRj.js → Network-CGq3kfd1.js} +1 -1
  32. package/dist/assets/{NodeAddonsSettingsPanel-Bxo7RX_t.js → NodeAddonsSettingsPanel-nr3AtHjM.js} +1 -1
  33. package/dist/assets/{Notifications-jDLOdxxr.js → Notifications-BBwZ6mAQ.js} +1 -1
  34. package/dist/assets/{Pipeline-CdRFK7Ht.js → Pipeline-CQaYioeF.js} +1 -1
  35. package/dist/assets/{PrivacyMaskSettings-CwqJt7F1.js → PrivacyMaskSettings-D7Qd8kqz.js} +1 -1
  36. package/dist/assets/{Recordings-ByMTLru0.js → Recordings-CDtBM0sR.js} +1 -1
  37. package/dist/assets/{ScanNetworkModal-C_wbwoQJ.js → ScanNetworkModal-2DJqoErA.js} +1 -1
  38. package/dist/assets/{SceneMonitorEditor-_eTUV0Nt.js → SceneMonitorEditor-swVXSp84.js} +1 -1
  39. package/dist/assets/{SessionsList-NSwapFYQ.js → SessionsList-C2DE6o9h.js} +1 -1
  40. package/dist/assets/{Showroom-BPdeCFff.js → Showroom-CiNnUFnm.js} +1 -1
  41. package/dist/assets/{System-6U5y0D0r.js → System-DUagyEFx.js} +1 -1
  42. package/dist/assets/{Terminal-CtSs7HaV.js → Terminal-DOi0WVnX.js} +1 -1
  43. package/dist/assets/{Viewer-Cy6OOx-f.js → Viewer-CWHOfvCC.js} +1 -1
  44. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BrKy-SMz.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BIxGxCUM.js} +1 -1
  45. package/dist/assets/{addon-icons-context-9dO49JJv.js → addon-icons-context-DTBXQew3.js} +1 -1
  46. package/dist/assets/{archive-8x-tu1s7.js → archive-BSo6LE4j.js} +1 -1
  47. package/dist/assets/{assignment-candidates-rjmoo-gF.js → assignment-candidates-ssCj0u1L.js} +1 -1
  48. package/dist/assets/{authed-media-DG3fVpcG.js → authed-media-DcEPr23B.js} +1 -1
  49. package/dist/assets/{bell-off-DMfxbtq4.js → bell-off-DMeS_hlL.js} +1 -1
  50. package/dist/assets/{board-model-WWlJx1cg.js → board-model-C-MbLK-9.js} +1 -1
  51. package/dist/assets/{boxes-BWAGJm1O.js → boxes-BTvNvGv0.js} +1 -1
  52. package/dist/assets/circle-slash-HrJDRa4V.js +1 -0
  53. package/dist/assets/client-BfSvmYES.js +674 -0
  54. package/dist/assets/{cloud-upload-CKs-pNsZ.js → cloud-upload-DTtO2M5N.js} +1 -1
  55. package/dist/assets/crop-CjhqWNNc.js +1 -0
  56. package/dist/assets/{device-integration-icon-CNzVUpNN.js → device-integration-icon-JsR0CLjC.js} +1 -1
  57. package/dist/assets/device-picker-model-Ddc4zMvm.js +1 -0
  58. package/dist/assets/{dist-D1lJ0amf.js → dist-D-rENHS9.js} +1 -1
  59. package/dist/assets/dist-jcYq2P8G.js +674 -0
  60. package/dist/assets/{eraser-Dboyt7DT.js → eraser-Uty9NVHm.js} +1 -1
  61. package/dist/assets/{format-CqUoeB6x.js → format-CNIP6R5z.js} +1 -1
  62. package/dist/assets/{hard-drive-download-9FzNEeA3.js → hard-drive-download-DLDeO7fX.js} +1 -1
  63. package/dist/assets/{hostInit-DUNsyymc.js → hostInit-FnGO3hOX.js} +1 -1
  64. package/dist/assets/i18n-DSyzqlc8.js +1 -0
  65. package/dist/assets/icons-Dczhpsut.js +1 -0
  66. package/dist/assets/{index-BQucBhdz.js → index-pdmtHrdH.js} +3 -3
  67. package/dist/assets/{key-DsZMsE3B.js → key-By6EbR0p.js} +1 -1
  68. package/dist/assets/{key-round-DP5HddQT.js → key-round-iLs-jOxg.js} +1 -1
  69. package/dist/assets/{layers-Ce8hM9RV.js → layers-BtBDzlwx.js} +1 -1
  70. package/dist/assets/{linked-devices-model-CwQqHHq3.js → linked-devices-model-BeSuCS67.js} +1 -1
  71. package/dist/assets/{list-ordered-Bok3LKqI.js → list-ordered-c42OqqHj.js} +1 -1
  72. package/dist/assets/{location-owned-usage-caMWTIh0.js → location-owned-usage-ge-GKuvo.js} +1 -1
  73. package/dist/assets/{log-in-Dy7V-B3B.js → log-in-Ct1VkFa-.js} +1 -1
  74. package/dist/assets/{memory-stick-B1MtzV7u.js → memory-stick-Dl2x1-yz.js} +1 -1
  75. package/dist/assets/{message-square-plus-B8tlaZRC.js → message-square-plus-CKYpcVyW.js} +1 -1
  76. package/dist/assets/{mf-entry-bootstrap-0-508d81ce.js → mf-entry-bootstrap-0-a877a78a.js} +2 -2
  77. package/dist/assets/{mic-off-BoPPgEuI.js → mic-off-BXQiquS1.js} +1 -1
  78. package/dist/assets/{monitor-off-NYPljllc.js → monitor-off-vUbCNV5T.js} +1 -1
  79. package/dist/assets/{monitor-smartphone-BjvCzSKA.js → monitor-smartphone-DBSJpBW_.js} +1 -1
  80. package/dist/assets/mount-Ddc4zMvm.js +1 -0
  81. package/dist/assets/{player-overlays-DkX009EX.js → player-overlays-CBiSRAea.js} +1 -1
  82. package/dist/assets/{recycle-DGYdB0Wq.js → recycle-BZmGhg7x.js} +1 -1
  83. package/dist/assets/remoteEntry-74d4RYnC.js +1 -0
  84. package/dist/assets/{scan-eye-Ch-0lhIO.js → scan-eye-BoLgRLC0.js} +1 -1
  85. package/dist/assets/{scissors-B6VydNaF.js → scissors-DGLihVCk.js} +1 -1
  86. package/dist/assets/{search-x-BdKhxUyE.js → search-x-sFaeXhxz.js} +1 -1
  87. package/dist/assets/{send-bQSpRVGI.js → send-Bg3Ccdt2.js} +1 -1
  88. package/dist/assets/{settings-2-D6b4Y6jH.js → settings-2-CwllFEZ8.js} +1 -1
  89. package/dist/assets/sigma-CdYqmDXM.js +1 -0
  90. package/dist/assets/{speaker-zhX4f3kb.js → speaker-BrOcLiaC.js} +1 -1
  91. package/dist/assets/{src-B6o0JOTn.js → src-m4PqxQbt.js} +10 -10
  92. package/dist/assets/{step-inspector-model-B9toNvbs.js → step-inspector-model-Dm3OtX4n.js} +1 -1
  93. package/dist/assets/{table-2-CkdRK3-h.js → table-2-Dy55Hbv-.js} +1 -1
  94. package/dist/assets/{timer-reset-GRtPzP8x.js → timer-reset-CW-sk1hO.js} +1 -1
  95. package/dist/assets/{unlink--JN-bzY3.js → unlink-CP1a9eIg.js} +1 -1
  96. package/dist/assets/{usb-DVsgUDG3.js → usb-CZ6MXIrF.js} +1 -1
  97. package/dist/assets/{use-scenes-feed-Cqw88fnG.js → use-scenes-feed-BgoS7G9m.js} +1 -1
  98. package/dist/assets/{use-stationary-objects-4q9AsEzW.js → use-stationary-objects-CZz2fTb8.js} +1 -1
  99. package/dist/assets/useEventInvalidation-Ddc4zMvm.js +1 -0
  100. package/dist/assets/{useNodeUrlSelection-DmVrPFLh.js → useNodeUrlSelection-BqU7uE66.js} +1 -1
  101. package/dist/assets/user-round-DK8xHLhd.js +1 -0
  102. package/dist/assets/{user-x-CpK7WtDd.js → user-x-BHGXDb0d.js} +1 -1
  103. package/dist/assets/{variable-CTjWqiYN.js → variable-BspSKoPT.js} +1 -1
  104. package/dist/assets/{video-DP_1jY7p.js → video-DcplYxeY.js} +1 -1
  105. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BKjBUyzU.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DarJ7yW1.js} +2 -2
  106. package/dist/index.html +9 -9
  107. package/dist/server/addon.js +13 -1
  108. package/package.json +1 -1
  109. package/dist/assets/AiProfiles-DVFetD_E.js +0 -3
  110. package/dist/assets/Build-B7n9F9d7.js +0 -40
  111. package/dist/assets/DeviceDetail-pPQkOmhX.js +0 -2
  112. package/dist/assets/HelperWizard-D34R-al-.js +0 -2
  113. package/dist/assets/circle-slash-C5LGZ7Jt.js +0 -1
  114. package/dist/assets/client-DXl30Qia.js +0 -674
  115. package/dist/assets/crop-CKoE-7yI.js +0 -1
  116. package/dist/assets/device-picker-model-B2lLKlrB.js +0 -1
  117. package/dist/assets/dist-pI3sPmA5.js +0 -674
  118. package/dist/assets/i18n-DDYls5dY.js +0 -1
  119. package/dist/assets/icons-wUSx9AFv.js +0 -1
  120. package/dist/assets/mount-B2lLKlrB.js +0 -1
  121. package/dist/assets/remoteEntry-B_HQRuMC.js +0 -1
  122. package/dist/assets/sigma-HnZfIS_X.js +0 -1
  123. package/dist/assets/useEventInvalidation-B2lLKlrB.js +0 -1
  124. package/dist/assets/user-round-DkmA2RnU.js +0 -1
@@ -1,3 +0,0 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,t as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{D as d,En as f,Fn as p,G as m,Ht as h,L as g,Li as _,Ni as v,Pn as y,Pr as b,Q as x,Ri as S,Vn as C,Xr as w,_n as T,ai as E,dt as D,fr as O,gt as ee,na as k,ni as A,rn as j,st as te,tn as M,vn as N}from"./player-overlays-DkX009EX.js";import{Hr as P,Vr as F,ro as I}from"./client-DXl30Qia.js";import{n as L,t as R}from"./send-bQSpRVGI.js";import{t as ne}from"./message-square-plus-B8tlaZRC.js";import{Cn as z,Do as B,Dr as V,Er as H,Fr as U,Hn as W,Or as G,Qn as re,Sn as ie,Tr as K,Wn as ae,Yr as q,_d as oe,bn as J,bt as se,dd as Y,ft as ce,gd as le,mt as ue,or as de,ri as X,rt as fe,xt as pe}from"./src-B6o0JOTn.js";import{t as Z}from"./i18n-DDYls5dY.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-B2lLKlrB.js";import{T as me,yr as he}from"./index-BQucBhdz.js";import{t as ge}from"./AdminSectionedPage-O_gaWBic.js";import{t as _e}from"./AdminPage-CRBjpZ4t.js";c();var ve=`__redacted__`,ye=[`llm`,`listProfiles`],be=[`llm`,`listProfileKinds`],xe=[`llm`,`getDefaults`],Se=[`llm`,`listRuntimeNodes`],Ce=[`llm`,`listModelCatalog`],we=[`llm`,`getUsage`],Te=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],Ee=new Map([[`cloud`,E],[`plug`,y],[`cpu`,A],[`server`,T],[`sparkles`,j]]);function De(e){return Ee.get(e)??S}function Oe(e){return typeof e==`string`&&e.length>0?e:void 0}function ke(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 Ae(e){return e===!0}function je(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 Me={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Ne(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:Z.t(`ai.appleUnknown`),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:Z.t(`ai.appleAvailable`),detail:Z.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Me[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:Z.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:Z.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var Pe={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`},Fe={ready:`ai.stateReady`,downloading:`ai.stateDownloading`,starting:`ai.stateStarting`,stopped:`ai.stateStopped`,crashed:`ai.stateCrashed`,failed:`ai.stateFailed`};function Ie(e){return e.reachable?e.status===void 0?`ai.stateReady`:Fe[e.status.state]:`ai.unreachable`}function Le(e){return e.reachable?e.status===void 0?`success`:Pe[e.status.state]:`danger`}function Re(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Ne(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Ne(e);t.push({id:`apple`,labelKey:`ai.featureApple`,tone:n.tone,detail:n.labelDefault})}let r=e.status?.vramBytes;return r!==void 0&&r>0&&t.push({id:`gpu`,labelKey:`ai.featureGpu`,tone:`info`,detail:null}),t}function ze(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:P.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:P.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:P.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:P.idleMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutIdleHint`)}],retry:[{type:`boolean`,key:`retryEnabled`,label:Z.t(`helpers.aiProfileForm.retry`),description:Z.t(`helpers.aiProfileForm.retryHint`)},{type:`number`,key:`retryMaxAttempts`,label:Z.t(`helpers.aiProfileForm.retryMaxAttempts`),min:1,max:5,default:1,showWhen:{field:`retryEnabled`,equals:!0}}],toolsEnabled:[{type:`boolean`,key:`toolsEnabled`,label:Z.t(`helpers.aiProfileForm.toolsEnabled`),description:Z.t(`helpers.aiProfileForm.toolsEnabledHint`)}]}}var Be=[`temperature`,`topP`,`topK`,`maxTokens`,`contextLength`,`systemPrompt`],Ve=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function He(e,t){let n=ze();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Ue(e){let t=He(e,Be);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function We(e){let t=He(e,Ve);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function Ge(e){return e===null?{}:{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}}function Ke(e,t){return{...e.features,...t?.features}}function qe(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Je(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?ke(i[e])??t:n??t,o=e=>r.includes(e)?ke(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`systemPrompt`)?Oe(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,P.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,P.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,P.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,P.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:Ae(i.retryEnabled),maxAttempts:ke(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?Ae(i.toolsEnabled):t?.toolsEnabled??!1,...s===void 0?{}:{temperature:s},...c===void 0?{}:{topP:c},...l===void 0?{}:{topK:l},...u===void 0?{}:{maxTokens:u},...d===void 0?{}:{contextLength:d},...f===void 0?{}:{systemPrompt:f},providerConfig:n.providerConfig}}var Ye=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function Xe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Ze({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=D(),[d,f]=o(``),[p,m]=o(null),[h,g]=o(!1),_=s({queryKey:Ce,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),v=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:t})}),y=l({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:e=>u.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{g(!0),v.refetch()}}),x=s({queryKey:Se,enabled:b.isPending,refetchInterval:b.isPending?Ye:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,S=n(()=>{let e=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:$(e.sizeBytes),node:t})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[_.data,v.data,p,t,c]),C=e=>{if(e===``){a(null);return}if(e===`custom`){if(p?.ok!==!0)return;a({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},T=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(pe,{label:c(`ai.model`,`Model`),required:!0,children:i(Y,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:Xe(r),options:S,onChange:e=>C(e.target.value)})}),i(pe,{label:c(`ai.hfTitle`,`Add a model from Hugging Face`),description:c(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`),children:e(`div`,{className:`flex gap-2`,children:[i(le,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>f(e.target.value),placeholder:c(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())}}),e(q,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>T(),children:[y.isPending?i(O,{className:`h-3.5 w-3.5 animate-spin`}):i(N,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),y.isError&&i(K,{message:y.error instanceof Error?y.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(K,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(q,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>T(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(X,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(X,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(q,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?i(O,{className:`h-3.5 w-3.5 animate-spin`}):i(w,{className:`h-3.5 w-3.5`}),h?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),x!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:x.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:x.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:x.file,index:x.fileIndex,count:x.fileCount,done:$(x.downloadedBytes),total:x.totalBytes===void 0?``:` / ${$(x.totalBytes)}`})})]}),b.isError&&i(K,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)})]})]})}function Qe({value:t,onChange:n}){let{t:r}=Q(),a=D(),o=s({queryKey:Se,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(O,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=Ne(a),s=o.nodeId===t;return e(`button`,{type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(X,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function $e(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function et({providerConfig:e,onProviderConfigChange:t}){return i(Qe,{value:$e(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function tt({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=F.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(Ze,{nodeId:$e(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var nt=new Map([[`ai/apple-node`,et],[`ai/managed-model`,tt]]);function rt(e){return nt.get(e)??null}c();function it({kind:e,className:t}){return i(De(e.icon),{className:t,"aria-hidden":!0})}function at({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>je(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(ue,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(se,{emptyMessage:a(`ai.noKinds`,`No AI provider is installed.`),onPick:e=>{let n=s.get(e);n!==void 0&&t(n)},groups:o.map(e=>({id:e.addonId,label:e.addonId,tiles:e.kinds.map(t=>({key:`${e.addonId}:${t.kind}`,label:t.label,testId:`ai-kind-${t.kind}`,icon:i(it,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function ot(e){return(e?.sections??[]).flatMap(e=>e.fields)}function st(...e){let t={};for(let n of e)for(let e of ot(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function ct(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function lt(e,t){return ot(e).filter(e=>`required`in e&&e.required===!0&&!ct(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var ut={auth:{key:`ai.listAuth`,fallback:`Credentials refused`},network:{key:`ai.listNetwork`,fallback:`Endpoint unreachable`},unsupported:{key:`ai.listUnsupported`,fallback:`No model list`},invalid:{key:`ai.listInvalid`,fallback:`Connection incomplete`}};function dt(e,t){if(t!==null)return{id:t.model,supportsVision:t.supportsVision};let n=e.modelCatalog===`static`&&e.staticModels?.length===1?e.staticModels?.[0]:void 0;return{id:n?.id??``,supportsVision:Ke(e,n).vision}}function ft({kind:t,existing:r,onSave:s,onCancel:c,onChangeKind:p,saving:m,error:h}){let{t:_}=Q(),v=D(),[y,b]=o(r?.name??t.label),[x,S]=o(()=>r===null?st(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[C,w]=o(()=>Ge(r)),[T,E]=o(()=>dt(t,r)),[ee,A]=o(!1),j=t.providerWidgets??[],te=j.filter(e=>e.placement===`connection`),M=j.find(e=>e.placement===`model`)??null,N=n(()=>[...I(t.connectionSchema)].some(e=>r?.providerConfig[e]===ve),[r,t.connectionSchema]),P=l({mutationFn:()=>v.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:x,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&E(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ke(t,r).vision}})}}),F=qe(t,P.data?.ok===!0?P.data.models:null),L=F.find(e=>e.id===T.id),R=Ke(t,L),ne=Ue(t.profileFields),z=We(t.profileFields),B=lt(t.connectionSchema,x),V=j.some(e=>(e.requires??[]).some(e=>!ct(x[e]))),H=t.modelCatalog===`fetch`&&M===null,U=ot(t.connectionSchema).length>0||te.length>0,G=r!==null&&H&&B.length===0;a(()=>{G&&P.mutate()},[]);let ie=e=>{E({id:e,supportsVision:Ke(t,F.find(t=>t.id===e)).vision})},ae=m||y.trim()===``||T.id.trim()===``||B.length>0||V,oe=()=>{s(Je(t,r,{name:y.trim(),model:T.id.trim(),supportsVision:t.visionEditable?T.supportsVision:!1,common:C,providerConfig:x}))},se=r===null?_(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):_(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),ce=e=>{let n=rt(e);return n===null?i(K,{variant:`warning`,message:_(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})}):i(n,{descriptor:t,providerConfig:x,onProviderConfigChange:S,model:T,onModelChange:E},e)};return i(ue,{open:!0,onClose:c,title:se,error:h,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[B.length>0&&i(X,{variant:`warning`,children:_(`ai.missingRequired`,`required: {{fields}}`,{fields:B.join(`, `)})}),B.length===0&&V&&i(X,{variant:`warning`,children:_(`ai.completeProvider`,`complete the provider settings`)}),B.length===0&&!V&&T.id.trim()===``&&i(X,{variant:`warning`,children:_(`ai.pickModelFirst`,`pick a model`)}),e(q,{size:`sm`,type:`button`,disabled:ae,onClick:oe,children:[m&&i(O,{className:`h-3.5 w-3.5 animate-spin`}),r===null?_(`ai.createProfile`,`Create profile`):_(`ai.saveChanges`,`Save changes`)]})]}),children:e(`div`,{className:g,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`ai-editor-provider`,children:[i(it,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(X,{variant:`neutral`,children:t.addonId}),p!==void 0&&e(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:p,children:[i(k,{className:`h-3.5 w-3.5`}),_(`ai.changeKind`,`Change type`)]})]}),i(pe,{label:_(`ai.name`,`Name`),required:!0,children:i(le,{id:`ai-profile-name`,"aria-label":_(`ai.name`,`Name`),value:y,onChange:e=>b(e.target.value),placeholder:t.label})}),U&&i(J,{headingId:`ai-editor-connection`,title:_(`ai.sectionConnection`,`Connection`),actions:H?e(q,{size:`sm`,variant:`secondary`,type:`button`,disabled:P.isPending,onClick:()=>P.mutate(),"data-testid":`ai-verify-models`,children:[P.isPending?i(O,{className:`h-3.5 w-3.5 animate-spin`}):i(f,{className:`h-3.5 w-3.5`}),_(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[ot(t.connectionSchema).length>0&&i(de,{bare:!0,schema:t.connectionSchema,values:x,onChange:S}),te.map(e=>ce(e.id)),N&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:_(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)}),P.data?.ok===!0&&i(X,{variant:`success`,"data-testid":`ai-models-found`,children:_(`ai.modelsFound`,`{{count}} models found`,{count:P.data.models.length})}),P.data?.ok===!1&&i(K,{title:_(ut[P.data.code]?.key??`ai.listNetwork`,ut[P.data.code]?.fallback??`Endpoint unreachable`),message:P.data.message}),P.isError&&i(K,{message:P.error instanceof Error?P.error.message:_(`common.error`,`Error`)})]})}),i(J,{headingId:`ai-editor-model`,title:_(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${d} space-y-3`,children:[M===null?e(u,{children:[F.length>0&&i(Y,{id:`ai-model-pick`,"aria-label":_(`ai.selectModel`,`Select a model…`),value:L===void 0?``:L.id,options:[{value:``,label:_(`ai.selectModel`,`Select a model…`)},...F.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&ie(e.target.value)}}),i(pe,{label:_(`ai.customModel`,`Model id`),description:_(`ai.customModelHint`,`Pick one from the list, or type any model id the provider accepts.`),required:!0,children:i(le,{id:`ai-model-id`,"aria-label":_(`ai.customModel`,`Model id`),value:T.id,onChange:e=>{let n=F.find(t=>t.id===e.target.value);E(n===void 0?{...T,id:e.target.value}:{id:e.target.value,supportsVision:Ke(t,n).vision})},placeholder:F[0]?.id??`model-id`})})]}):ce(M.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(T.supportsVision||!t.visionEditable&&R.vision)&&i(X,{variant:`info`,children:_(`ai.featureVision`,`vision`)}),R.tools&&i(X,{variant:`neutral`,children:_(`ai.featureTools`,`tools`)}),R.streaming&&i(X,{variant:`neutral`,children:_(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(pe,{orientation:`horizontal`,label:_(`ai.supportsVision`,`Supports vision`),description:_(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(W,{checked:T.supportsVision,onCheckedChange:e=>E({...T,supportsVision:e}),"aria-label":_(`ai.supportsVision`,`Supports vision`)})})]})}),ne!==null&&i(J,{headingId:`ai-editor-generation`,title:_(`ai.sectionGeneration`,`Generation`),children:i(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:i(de,{bare:!0,schema:ne,values:C,onChange:w})})}),(z!==null||t.advancedSchema!==void 0)&&i(re,{expanded:ee,onExpandedChange:A,header:i(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:_(`ai.sectionAdvanced`,`Advanced`)}),children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[z!==null&&i(de,{bare:!0,schema:z,values:C,onChange:w}),t.advancedSchema!==void 0&&i(de,{bare:!0,schema:t.advancedSchema,values:x,onChange:S})]})})]})})}c();function pt(t){return[{key:`name`,header:t.t(`ai.colProfile`,`Profile`),render:n=>{let r=t.kindByName.get(n.kind);return e(`span`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:r?.label??n.kind,children:r===void 0?i(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):i(it,{kind:r,className:`h-4 w-4 text-foreground-subtle`})}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block truncate font-medium text-foreground`,children:n.name}),t.testResult?.id===n.id&&i(`span`,{className:`block truncate ${t.testResult.ok?`text-success`:`text-danger`}`,children:t.testResult.text})]})]})}},{key:`kind`,header:t.t(`ai.colKind`,`Kind`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground-muted`,children:t.kindByName.get(e.kind)?.label??e.kind})},{key:`model`,header:t.t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:t.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:e=>e.supportsVision?i(X,{variant:`info`,style:`outline`,children:t.t(`ai.vision`,`vision`)}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:t.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?i(X,{variant:`default`,children:e.providerConfig.nodeId}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:t.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:e=>i(W,{checked:e.enabled,onCheckedChange:()=>t.onToggle(e),"aria-label":Z.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:e.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest(n),"aria-label":t.t(`ai.test`,`Test`),title:t.t(`ai.test`,`Test`),children:t.testingId===n.id?i(O,{className:`h-3.5 w-3.5 animate-spin`}):i(R,{className:`h-3.5 w-3.5`})}),i(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:!t.kindByName.has(n.kind),onClick:()=>t.onEdit(n),"aria-label":t.t(`common.edit`,`Edit`),title:t.t(`common.edit`,`Edit`),children:i(C,{className:`h-3.5 w-3.5`})}),i(q,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDelete(n),"aria-label":t.t(`common.delete`,`Delete`),title:t.t(`common.delete`,`Delete`),children:i(h,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function mt(){let{t}=Q(),c=D(),{state:u,openEdit:f,close:p}=ce(),m=te(),[h,_]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:ye,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),C=s({queryKey:be,queryFn:async()=>(await c.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),w=()=>{S.refetch()},T=r(()=>{_(null),x(null),p()},[p]);a(()=>{u.mode===`closed`&&_(null)},[u.mode]);let E=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{T(),w()},onError:e=>x(e instanceof Error?e.message:t(`ai.saveFailed`,`Save failed`))}),O=l({mutationFn:e=>c.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:w}),ee=l({mutationFn:e=>c.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>y({id:t.id,ok:e.ok,text:e.ok?Z.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),k=S.data??[],A=n(()=>C.data??[],[C.data]),M=n(()=>{let e=new Map;for(let t of A)e.set(t.kind,t);return e},[A]),N=u.mode===`edit`?k.find(e=>e.id===u.id)??null:null,P=N===null?null:M.get(N.kind)??null,F=u.mode===`new`&&h===null,I=u.mode===`new`?h:P,L=u.mode===`edit`?N:null,R=I!==null&&(u.mode===`new`||L!==null),ne=async e=>{await m({title:t(`ai.deleteProfileTitle`,`Delete profile?`),message:t(`ai.deleteProfileMessage`,`Delete "{{name}}". Features that name it will no longer get an answer from it.`,{name:e.name}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&O.mutate(e)};return e(`div`,{className:g,children:[i(ht,{profiles:k}),i(J,{headingId:`ai-profiles-list`,title:t(`ai.profilesList`,`Profiles`),children:S.isPending?e(`div`,{className:`${d} space-y-2`,"data-testid":`ai-profiles-loading`,children:[i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):S.isError?i(`div`,{className:d,children:i(K,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:t(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):k.length===0?i(H,{icon:j,title:t(`ai.noProfilesTitle`,`No AI profiles yet`),description:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):i(ie,{columns:pt({kindByName:M,testResult:v,testingId:ee.isPending?ee.variables?.id??null:null,t,onToggle:e=>E.mutate({...e,enabled:!e.enabled}),onTest:e=>ee.mutate(e),onEdit:e=>{M.has(e.kind)&&(x(null),_(null),f(e.id))},onDelete:e=>void ne(e)}),rows:k,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:z})}),F&&i(at,{kinds:A,onCancel:T,onPick:e=>{x(null),_(e)}}),R&&I!==null&&i(ft,{kind:I,existing:L,saving:E.isPending,error:b,onSave:e=>E.mutate(e),onCancel:T,...u.mode===`new`?{onChangeKind:()=>{x(null),_(null)}}:{}})]})}function ht({profiles:t}){let{t:n}=Q(),r=D(),a=s({queryKey:xe,queryFn:()=>r.trpcClient.llm.getDefaults.query({})}),o=l({mutationFn:e=>r.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?n(`ai.defaultVision`,`Default vision profile`):n(`ai.defaultText`,`Default text profile`);return i(J,{headingId:`ai-profiles-defaults`,title:n(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:Te.map(({purpose:r,visionOnly:a})=>{let s=a?t.filter(e=>e.supportsVision):t,l=c(r),d=t.find(e=>e.id===l);return e(`div`,{children:[i(ae,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(Y,{id:`llm-default-${r}`,"aria-label":u(r),value:l,onChange:e=>o.mutate({purpose:r,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:n(`ai.none`,`None`)},...l!==``&&!s.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...s.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:n(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:n(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},r)})})})}c();var gt=5e3;function _t(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function vt(){let{t}=Q(),r=D(),a=s({queryKey:Se,refetchInterval:gt,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(X,{variant:Le(n),children:t(Ie(n))}),n.status?.downloadProgress!==void 0&&i(X,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:_t(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeature`,`Feature`),render:n=>{let r=Re(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(X,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(J,{headingId:`ai-runtimes-list`,title:t(`ai.runtimesList`,`Nodes`),children:a.isPending?e(`div`,{className:`${d} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:d,children:i(K,{title:t(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:a.error instanceof Error?a.error.message:t(`common.error`,`Error`),onRetry:()=>void a.refetch()})}):c.length===0?i(H,{icon:T,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(ie,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:z})})}var yt=x(`/addon/ai/test-chat`),bt=x(`/addon/ai/test-chat/chats`),xt=6e5;function St(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),xt)}function Ct(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wt(e){if(!Ct(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 Tt=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Et(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Ct(t))return null;switch(t.kind){case`status`:{let e=Tt.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:wt(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:Z.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*Dt(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=Et(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=Et(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Ot(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function kt(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function At(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 jt(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 Mt(e,t){switch(e){case`resolving-image`:return Z.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return Z.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?Z.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):Z.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return Z.t(`helpers.aiTestChat.phaseAnswering`)}}c();var Nt=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],Pt=360*60*1e3,Ft=40,It=160,Lt={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Rt(){let{t:c}=Q(),l=D(),[u,f]=o(``),[p,m]=o(``),[y,b]=o(``),[x,S]=o([]),[C,w]=o(null),[T,E]=o(`none`),[O,k]=o(`throwaway`),[A,j]=o(null),[te,N]=o([]),[P,F]=o(null),[I,L]=o(null),z=t(null);a(()=>()=>z.current?.abort(),[]);let B=r(async()=>{let e=await fetch(bt,{credentials:`same-origin`});e.ok&&N((await e.json()).chats??[])},[]);a(()=>{O===`persistent`&&B()},[O,B]);let V=s({queryKey:ye,queryFn:()=>l.trpcClient.llm.listProfiles.query({})}),H=n(()=>(V.data??[]).filter(e=>e.enabled),[V.data]),U=H.find(e=>e.id===u)??null,W=I!==null,G=r(async(e,t)=>{let n=new AbortController;z.current=n,F(null);let r=St(U??{});L({...Lt,firstTokenTimeoutMs:r??0});let i=``,a=null,o,s=null,l=null,d;try{let c=await fetch(yt,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:n.signal,body:JSON.stringify({profileId:u,messages:e,...p.trim()===``?{}:{system:p.trim()},...t===void 0?{}:{attachment:t},...r===void 0?{}:{firstTokenTimeoutMs:r},...O===`persistent`?{persist:!0,...A===null?{}:{conversationId:A}}:{}})});if(!c.ok||c.body===null){let e=await c.text().catch(()=>``);throw Error(e.length>0?e:`HTTP ${String(c.status)}`)}for await(let e of Dt(c.body))switch(e.kind){case`status`:L(t=>({...t??Lt,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,L(t=>({...t??Lt,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,L(e=>({...e??Lt,text:i}));break;case`done`:l={outputTokens:e.outputTokens,latencyMs:e.latencyMs},d=e.conversationId;break;case`error`:s=`${e.code}: ${e.message}`;break}}catch(e){n.signal.aborted||F(e instanceof Error?e.message:c(`common.error`,`Error`))}finally{z.current=null,L(null)}d!==void 0&&(j(d),B());let f=n.signal.aborted&&i.length>0;s===null&&i.length===0&&!f||S(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:s??i,...s===null?{}:{failed:!0},...a===null?{}:{attachment:a},...o!==void 0&&s===null?{model:o}:{},...l===null?{}:l}])},[O,A,U,u,B,p,c]),re=r(()=>{let e=y.trim();if(e===``||u===``||W)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...C===null?{}:{attachmentLabel:C.label,attachmentKind:C.ref.kind}},n=[...x,t];S(n),b(``);let r=C?.ref;w(null),E(`none`),G(O===`persistent`&&A!==null?[{role:`user`,content:e}]:Ot(n),r)},[O,A,y,C,u,G,W,x]),ie=()=>z.current?.abort(),se=()=>{z.current?.abort(),S([]),w(null),b(``),F(null),L(null),j(null)},ce=async e=>{z.current?.abort();let t=await fetch(`${bt}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();j(e),S(At(n)),L(null),F(null)};return e(`div`,{className:g,children:[i(J,{headingId:`ai-test-setup`,title:c(`ai.testSetup`,`Setup`),children:e(`div`,{className:`${d} space-y-3`,children:[e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(ae,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:c(`ai.profile`,`Profile`)}),i(Y,{id:`ai-test-profile`,value:u,onChange:e=>f(e.target.value),options:[{value:``,label:c(`ai.selectProfile`,`Select a profile…`)},...H.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),H.length===0&&!V.isLoading&&i(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:c(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),e(`div`,{children:[i(ae,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:c(`ai.systemPrompt`,`System prompt (optional)`)}),i(le,{id:`ai-test-system`,value:p,onChange:e=>m(e.target.value),placeholder:c(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(fe,{label:c(`ai.chatMode`,`Conversation mode`),value:O,options:[{value:`throwaway`,label:c(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:c(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{k(e),e===`throwaway`&&j(null)}}),O===`persistent`&&e(`div`,{className:`space-y-2`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:c(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),e(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:se,children:[i(ne,{className:`h-3.5 w-3.5`}),c(`ai.newChat`,`New chat`)]}),te.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:te.map(e=>i(`button`,{type:`button`,onClick:()=>void ce(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-xs hover:bg-surface-hover ${e.id===A?`bg-primary/10`:``}`,children:i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:c(`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.`)}),U!==null&&!U.supportsVision&&i(`p`,{className:`text-xs text-warning`,children:c(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]})}),P!==null&&i(K,{title:c(`ai.chatFailed`,`The test call failed`),message:P}),e(J,{headingId:`ai-test-conversation`,title:c(`ai.testConversation`,`Conversation`),actions:e(q,{size:`sm`,variant:`ghost`,type:`button`,disabled:x.length===0&&C===null,onClick:se,children:[i(h,{className:`h-3.5 w-3.5`}),c(`ai.clearChat`,`Clear`)]}),children:[i(zt,{turns:x,live:I}),e(`div`,{className:`${d} space-y-2 border-t border-border`,children:[C!==null&&e(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[C.ref.kind===`snapshot`?i(v,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(_,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:C.label}),i(oe,{size:`sm`,variant:`ghost`,type:`button`,icon:ee,"aria-label":c(`ai.removeAttachment`,`Remove attachment`),onClick:()=>w(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{size:`sm`,variant:T===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>E(T===`snapshot`?`none`:`snapshot`),children:[i(v,{className:`h-3.5 w-3.5`}),c(`ai.attachSnapshot`,`Camera snapshot`)]}),e(q,{size:`sm`,variant:T===`track`?`primary`:`outline`,type:`button`,onClick:()=>E(T===`track`?`none`:`track`),children:[i(_,{className:`h-3.5 w-3.5`}),c(`ai.attachTrack`,`Recent track`)]})]}),T===`snapshot`&&i(Ht,{onPick:(e,t)=>{w({ref:{kind:`snapshot`,deviceId:e.id},label:c(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t})}),E(`none`)}}),T===`track`&&i(Wt,{onPick:(e,t)=>{w({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:c(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),E(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(le,{value:y,onChange:e=>b(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),re())},placeholder:c(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":c(`ai.message`,`Message`)}),W?e(q,{size:`sm`,variant:`secondary`,type:`button`,onClick:ie,children:[i(M,{className:`h-3.5 w-3.5`}),c(`ai.stop`,`Stop`)]}):e(q,{size:`sm`,type:`button`,disabled:y.trim()===``||u===``,onClick:re,children:[i(R,{className:`h-3.5 w-3.5`}),c(`ai.send`,`Send`)]})]})]})]})]})}function zt({turns:t,live:n}){let{t:r}=Q();return t.length===0&&n===null?i(H,{icon:L,title:r(`ai.chatEmptyTitle`,`No messages yet`),description:r(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):e(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto ${d}`,children:[t.map(e=>i(Bt,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(Vt,{attachment:n.mediaSent}),n.text.length>0&&i(Bt,{turn:{id:`live`,role:`assistant`,content:n.text},streaming:!0}),e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(O,{className:`h-3.5 w-3.5 animate-spin`}),Mt(n.phase,n.firstTokenTimeoutMs)]})]})]})}function Bt({turn:t,streaming:n=!1}){let{t:r}=Q(),a=t.role===`user`,o=t.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return i(`div`,{className:`flex ${a?`justify-end`:`justify-start`}`,children:e(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${a?`border-primary/40 bg-primary/10`:o}`,children:[e(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[t.content,n&&i(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),t.attachment!==void 0&&i(Vt,{attachment:t.attachment}),t.attachmentLabel!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachmentKind===`track`?i(_,{className:`h-3 w-3`}):i(v,{className:`h-3 w-3`}),t.attachmentLabel]}),t.attachment!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachment.kind===`snapshot`?i(v,{className:`h-3 w-3`}):i(_,{className:`h-3 w-3`}),jt(t.attachment)]}),t.model!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:t.model,value2:String(t.outputTokens??0),value3:String(t.latencyMs??0)})})]})})}function Vt({attachment:e}){let{t}=Q(),n=kt(e);return n===null?null:i(`img`,{src:n,alt:t(`system.aiTestChat.sentToTheModel`,`sent to the model`),className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function Ht({onPick:e}){let{t}=Q(),n=B({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(O,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):i(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>i(Ut,{device:t,onPick:e},t.id))})}function Ut({device:t,onPick:n}){let{t:r}=Q(),a=U(t,`compact`),{src:o}=m(t.id,{width:It});return e(`button`,{type:`button`,onClick:()=>n(t,a),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[i(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:o!==null&&i(`img`,{src:o,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),e(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!t.online&&i(X,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function Wt({onPick:t}){let{t:r}=Q(),a=D(),o=B({isCamera:!0,projection:`slim`}),c=n(()=>(o.data??[]).map(e=>e.id),[o.data]),l=n(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),u=s({queryKey:[...Nt,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-Pt,limit:Ft,projection:`slim`})});if(o.isLoading||u.isLoading)return i(O,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=u.data?.tracks??[];return d.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noTracks`,`No track in the last 6 hours.`)}):i(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(n=>e(`button`,{type:`button`,onClick:()=>t(n,l.get(n.deviceId)??String(n.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[i(_,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:n.label??n.className}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:l.get(n.deviceId)??n.deviceId}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(n.lastSeen).toLocaleTimeString()})]},n.trackId))})}c();var Gt=1440*60*1e3,Kt=[1,7,30,90];function qt(){let{t}=Q(),r=D(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*Gt},[a]),u=s({queryKey:ye,queryFn:()=>r.trpcClient.llm.listProfiles.query({})}),f=s({queryKey:[...we,a],queryFn:()=>r.trpcClient.llm.getUsage.query({since:l})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),m=n(()=>[{key:`day`,header:t(`ai.colDay`,`Day`),nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:t(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:t(`ai.colProfile`,`Profile`),render:e=>i(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:t(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:t(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:t(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:t(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,t]),h=f.data??[],g=i(`div`,{className:`w-36`,children:i(Y,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:Kt.map(e=>({value:String(e),label:t(`ai.lastDays`,`Last {{days}} days`,{days:e})})),onChange:e=>c(Number(e.target.value))})});return i(J,{headingId:`ai-usage-list`,title:t(`ai.usageList`,`Rollup`),actions:g,children:f.isPending?e(`div`,{className:`${d} space-y-2`,"data-testid":`ai-usage-loading`,children:[i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):f.isError?i(`div`,{className:d,children:i(K,{title:t(`ai.usageFailed`,`Failed to read usage`),message:f.error instanceof Error?f.error.message:t(`common.error`,`Error`),onRetry:()=>void f.refetch()})}):h.length===0?i(H,{icon:b,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(ie,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:z})})}var Jt=`llm`,Yt=[`profiles`,`runtimes`,`usage`,`test`],Xt=[`new`,`edit`];function Zt(e){return Yt.some(t=>t===e)}function Qt(){let{t}=Q(),n=V(Jt),[r]=he(),{openNew:a}=ce(),o=me(`/system/ai`,{t,isAdmin:!0})??{icon:j,title:t(`system.ai`,`AI`)};if(n!==`present`)return i(_e,{icon:o.icon,title:o.title,children:i($t,{presence:n})});let s=r.get(`tab`),c=Zt(s)?s:`profiles`,l={profiles:t(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),runtimes:t(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),usage:t(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),test:t(`ai.testSubtitle`,`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`)},u=c===`profiles`?e(q,{size:`sm`,type:`button`,"data-testid":`ai-add-profile`,onClick:a,children:[i(p,{className:`h-3.5 w-3.5`}),t(`ai.addProfile`,`Add profile`)]}):void 0;return i(ge,{icon:o.icon,title:o.title,subtitle:l[c],actions:u,defaultSection:`profiles`,sectionsLabel:`${o.title} sections`,sections:[{id:`profiles`,label:t(`ai.tabProfiles`,`Profiles`),content:i(mt,{}),ownedParams:Xt},{id:`runtimes`,label:t(`ai.tabRuntimes`,`Runtimes`),content:i(vt,{})},{id:`usage`,label:t(`ai.tabUsage`,`Usage`),content:i(qt,{})},{id:`test`,label:t(`ai.tabTest`,`Test`),content:i(Rt,{})}]})}function $t({presence:t}){let{t:n}=Q();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(G,{className:`h-8 w-64`}),i(G,{className:`h-40 w-full`})]}):t===`unknown`?i(K,{title:n(`ai.presenceUnknownTitle`,`Could not check whether AI is installed`),message:n(`ai.presenceUnknown`,`The hub did not answer the capability check. Reload the page to try again.`)}):i(H,{icon:j,title:n(`ai.absentTitle`,`AI is not installed`),description:n(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{Qt as AiProfilesPage,Qt as default};
@@ -1,40 +0,0 @@
1
- import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,o as d,t as f,x as p}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$i as m,Ar as h,Di as g,Fn as _,Ht as v,In as y,Mi as b,Ti as x,Tr as S,Vn as C,dt as w,fr as T,mr as E,pa as D,ra as O,st as k,vt as A,wn as j,yi as M,yn as N,zt as P}from"./player-overlays-DkX009EX.js";import{$i as F,Ci as I,Ei as L,Ga as R,Ni as z,Pi as B,Qi as V,Xi as ee,Yi as te,Zi as ne,di as re,ea as ie,fn as H,ki as ae,la as oe,mi as se,on as ce,oo as le,pi as ue,ta as de,ua as fe}from"./client-DXl30Qia.js";import{t as pe}from"./boxes-BWAGJm1O.js";import{i as U,n as me,r as he,t as ge}from"./variable-CTjWqiYN.js";import{s as _e}from"./video-DP_1jY7p.js";import{$r as ve,Cn as ye,Co as be,Do as xe,Er as Se,Fa as Ce,Ga as we,Ia as Te,Ir as Ee,Jo as De,Ka as Oe,Kt as ke,La as Ae,Md as je,Mo as Me,Nr as Ne,Or as Pe,Pd as Fe,Qr as Ie,R as Le,Ra as Re,Sn as ze,Tr as W,Ua as Be,Un as Ve,Va as He,Wa as Ue,Yr as G,Zt as We,_r as Ge,bn as Ke,br as qe,cd as Je,ci as Ye,dd as K,di as Xe,dr as Ze,en as Qe,fi as $e,ft as et,gd as q,gi as tt,gn as nt,gr as rt,hd as it,hi as at,hr as ot,li as st,md as ct,mi as lt,mt as ut,pd as dt,pr as ft,ri as J,rn as pt,rt as mt,si as ht,ui as gt,vi as _t,vt}from"./src-B6o0JOTn.js";import{t as Y}from"./i18n-DDYls5dY.js";import{t as X}from"./useTranslation-BJr-n0es.js";import{L as yt,T as bt,_r as xt,h as St,lr as Ct,m as wt,mr as Tt,pr as Z,yr as Et}from"./index-BQucBhdz.js";import{t as Dt}from"./AdminSectionedPage-O_gaWBic.js";import{n as Ot}from"./format-CqUoeB6x.js";import{n as kt,t as At}from"./DeviceDoActionFields-D-6QkJSs.js";import{J as jt,P as Mt,V as Nt,p as Pt,t as Ft,u as It}from"./HelperWizard-D34R-al-.js";import{t as Lt}from"./CompositionBlockEditor-BdgsCxJZ.js";var Rt=`const AUTOMATION_RECIPE =`,zt=`// 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 Bt(e){return e.includes(Rt)}function Vt(e){let t=e.indexOf(Rt);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 Ht(e){let t=Vt(e);if(t===null)return{ok:!1,reason:Y.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:Y.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=V.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Y.t(`helpers.recipeFromCode.schemaMismatch`):Y.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function Ut(e){let t=Vt(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)}${zt}${e.slice(i)}`}u();function Wt(e){return e===void 0||!Number.isFinite(e)?``:String(e)}function Gt({value:e,onValue:t,onBrace:n,onBlur:r,...i}){let[a,s]=c(null);return o(q,{...i,inputMode:`decimal`,value:a??Wt(e),onChange:e=>{let r=e.target.value;if(r.includes(`{`)){n?.();return}s(r);let i=r.trim()===``?NaN:Number(r);t(Number.isFinite(i)?i:null)},onBlur:e=>{s(null),r?.(e)}})}function Kt({widthClass:e,...t}){return o(`span`,{className:`block max-w-full ${e}`,children:o(K,{...t})})}var qt=/(\{[A-Za-z0-9_]+\})/;function Jt(e){return e.toLowerCase().startsWith(`it`)?`it`:`en`}function Yt(e){return`${e.cap}:${e.id}`}function Xt(e){if(typeof e!=`object`||!e)return!1;let t=Object.keys(e);return t.length===1&&t[0]===`$var`&&typeof Reflect.get(e,`$var`)==`string`}function Zt(e){let t=[];for(let n of e.split(qt))n!==``&&(n.startsWith(`{`)&&n.endsWith(`}`)?t.push({kind:`slot`,key:n.slice(1,-1)}):t.push({kind:`text`,text:n}));return t}function Qt(e){let t=e.offer;switch(t.kind){case`number`:return{kind:`fixed`,value:t.min??0};case`enum`:{let e=t.values[0];return{kind:`fixed`,value:e===void 0?``:e.value}}case`boolean`:return{kind:`fixed`,value:!1};default:return{kind:`fixed`,value:``}}}function $t(e){return Object.fromEntries(e.openArgs.map(e=>[e.key,Qt(e)]))}function en(e,t){return Xt(e)?{kind:`var`,name:e.$var}:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?{kind:`fixed`,value:e}:Qt(t)}function tn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function nn(e,t){if(typeof t.deviceId!=`number`)return null;let n=t.args??{},r=null,i=-1;for(let a of e){if(a.cap!==t.cap||a.method!==t.method)continue;let e=Object.entries(a.args);e.every(([e,t])=>tn(n[e],t))&&e.length>i&&(r=a,i=e.length)}if(r===null)return null;let a=Object.fromEntries(r.openArgs.map(e=>[e.key,en(n[e.key],e)]));return{action:r,values:a}}function rn(e){return e.kind===`var`?{$var:e.name}:e.value}function an(e){return e.kind===`fixed`&&e.value===``}function on(e,t,n){let r={};for(let t of e.openArgs){let e=n[t.key]??Qt(t);t.optional===!0&&an(e)||(r[t.key]=rn(e))}let i={...e.args,...r};return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...Object.keys(i).length===0?{}:{args:i}}}function sn(e,t){if(t.kind===`var`)return null;let n=e.offer;return n.kind===`number`?typeof t.value!=`number`||!Number.isFinite(t.value)?`empty`:n.min!==void 0&&t.value<n.min?`below`:n.max!==void 0&&t.value>n.max?`above`:null:n.kind===`text`||n.kind===`dynamic`?e.optional===!0||t.value!==``?null:`empty`:null}u();function cn(e){return e.kind===`fixed`?String(e.value):``}function ln({arg:t,locale:n,variables:r,value:i,onChange:a}){let{t:s}=X(),[l,u]=c(!1),d=t.label[n],f=sn(t,i),p=i.kind===`var`?o(ve,{label:i.name,onRemove:()=>a(Qt(t))}):o(un,{arg:t,locale:n,value:i,onChange:a,onBrace:()=>u(!0)});return e(`span`,{className:`inline-flex flex-col gap-0.5 align-top`,"data-testid":`arg-${t.key}`,children:[e(`span`,{className:`inline-flex items-center gap-1`,children:[p,r.length>0&&e(ht,{open:l,onOpenChange:u,children:[o(gt,{"aria-label":s(`flow.arg.useVariable`,`Use a variable for {{label}}`,{label:d}),className:`h-8 rounded-md border border-border bg-surface px-2 font-mono text-xs text-foreground hover:bg-surface-hover`,children:`{x}`}),o(Ye,{children:r.map(e=>o(st,{onClick:()=>a({kind:`var`,name:e.name}),children:`${e.name} · ${e.hint}`},e.name))})]})]}),o(fn,{arg:t,value:i,issue:f})]})}function un({arg:e,locale:t,value:n,onChange:r,onBrace:i}){let{t:a}=X(),s=e.offer,c=e.label[t];return s.kind===`enum`?o(Kt,{widthClass:`w-40`,"aria-label":c,value:String(n.value),onChange:e=>{let t=s.values.find(t=>String(t.value)===e.target.value);t!==void 0&&r({kind:`fixed`,value:t.value})},options:s.values.map(e=>({value:String(e.value),label:e.label[t]}))}):s.kind===`boolean`?o(Kt,{widthClass:`w-28`,"aria-label":c,value:n.value===!0?`yes`:`no`,onChange:e=>r({kind:`fixed`,value:e.target.value===`yes`}),options:[{value:`yes`,label:a(`common.yes`,`Yes`)},{value:`no`,label:a(`common.no`,`No`)}]}):s.kind===`number`?o(dn,{label:c,unit:s.unit,value:n,onChange:r,onBrace:i}):o(q,{"aria-label":c,type:s.kind===`text`&&s.secret===!0?`password`:`text`,className:`w-40`,value:cn(n),onChange:e=>{if(e.target.value.includes(`{`)){i();return}r({kind:`fixed`,value:e.target.value})}})}function dn({label:t,unit:n,value:r,onChange:i,onBrace:a}){return e(p,{children:[o(Gt,{"aria-label":t,className:`w-20`,value:typeof r.value==`number`?r.value:void 0,onValue:e=>i({kind:`fixed`,value:e??NaN}),onBrace:a}),n!==void 0&&o(`span`,{className:`text-sm text-foreground-muted`,children:n})]})}function fn({arg:e,value:t,issue:n}){let{t:r}=X(),i=e.offer;if(t.kind!==`fixed`||i.kind!==`number`||i.min===void 0&&i.max===void 0)return null;let a=i.min!==void 0&&i.max!==void 0?r(`flow.arg.range`,`{{min}} to {{max}} {{unit}}`,{min:i.min,max:i.max,unit:i.unit??``}):i.min===void 0?r(`flow.arg.atMost`,`at most {{max}} {{unit}}`,{max:i.max,unit:i.unit??``}):r(`flow.arg.atLeast`,`at least {{min}} {{unit}}`,{min:i.min,unit:i.unit??``});return o(`span`,{className:`text-[11px] ${n===null?`text-foreground-subtle`:`text-danger`}`,role:n===null?void 0:`alert`,children:a.trim()})}u();function pn({devices:e,value:t,onChange:n,selection:i,noun:a=`device`,listState:s=`answered`,emptyLabel:c,testId:l}){return o(Le,{devices:r(()=>e.map(e=>({id:e.id,name:e.name,...e.type===void 0?{}:{type:e.type},location:e.location??null})),[e]),listState:s,value:[...t],onChange:e=>n(e),selection:i,noun:a,groupBy:`location`,...c===void 0?{}:{emptyLabel:c},testId:l})}u();function mn(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function hn(e,t,n){return e.map(e=>({value:Yt(e),label:e.label[t],description:e.phrase[t].replace(`{device}`,n)}))}function gn({step:t,devices:n,devicesState:i=`answered`,variables:a,onChange:s}){let{t:l,i18n:u}=X(),d=Jt(u.language),[f,p]=c(!1),m=typeof t.deviceId==`number`,h=typeof t.deviceId==`number`?t.deviceId:0,g=n.find(e=>e.id===h),_=kt(m?h:0),v=r(()=>_.data===void 0?[]:ce(_.data,g?.type),[_.data,g?.type]),y=r(()=>nn(v,t),[v,t]),b=t.cap===``,x=m&&h>0&&_.data===void 0&&!_.isError;if(!(m&&!f&&(b||y!==null||x)))return o(vn,{step:t,devices:n,devicesState:i,onChange:s,onBack:m&&!b&&y!==null?()=>p(!1):null});let S=n.filter(e=>H(e.type??``));return e(`div`,{className:`space-y-2`,"data-testid":`command-step`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[g?.type!==void 0&&o(J,{variant:`neutral`,children:g.type}),o(G,{variant:`ghost`,size:`sm`,className:`ml-auto`,onClick:()=>p(!0),"data-testid":`command-step-advanced`,children:l(`flow.command.advanced`,`Advanced`)})]}),e(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[o(pn,{devices:S,selection:`single`,listState:i,value:h>0?[h]:[],testId:`command-step-device`,onChange:e=>{let t=e[0]??0;t!==h&&s({kind:`cap`,deviceId:t,cap:``,method:``})}}),o(Ie,{mode:`single`,singleDisplay:`field`,options:hn(v,d,g?.name??``),value:y===null?``:Yt(y.action),placeholder:h===0?l(`flow.command.pickDeviceFirst`,`Pick a device first`):l(`flow.command.pickCommand`,`Pick a command`),disabled:h===0||x,searchable:v.length>=8,emptyMessage:l(`flow.command.noCommands`,`This device has no commands to offer.`),onChange:e=>{let t=v.find(t=>Yt(t)===e);t!==void 0&&s(on(t,h,$t(t)))}})]}),y!==null&&o(_n,{action:y.action,values:y.values,deviceName:g?.name??``,locale:d,variables:a,onChange:e=>s(on(y.action,h,e))})]})}function _n({action:e,values:t,deviceName:n,locale:r,variables:i,onChange:a}){let s=[];return Zt(e.phrase[r]).forEach((c,l)=>{if(c.kind===`text`){s.push(o(`span`,{children:c.text},`t${String(l)}`));return}if(c.key===`device`){s.push(o(`span`,{className:`font-medium`,children:n},`device`));return}let u=e.openArgs.find(e=>e.key===c.key),d=t[c.key];u===void 0||d===void 0||s.push(o(ln,{arg:u,locale:r,variables:i,value:d,onChange:e=>a({...t,[c.key]:e})},c.key))}),o(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-2 text-sm`,children:s})}function vn({step:t,devices:n,devicesState:r,onChange:i,onBack:a}){let{t:s}=X();return e(`div`,{className:`space-y-2`,"data-testid":`command-step-generic`,children:[a!==null&&o(G,{variant:`ghost`,size:`sm`,onClick:a,children:s(`flow.command.backToSentence`,`Back to the sentence`)}),o(At,{value:t,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:n,listState:r,onChange:e=>i({kind:`cap`,deviceId:mn(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})]})}var yn={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},bn={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},xn={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function Sn(){let{t:e}=X();return t=>{switch(t){case`ran`:return e(`flow.runs.outcomeRan`,`Ran`);case`failed`:return e(`flow.runs.outcomeFailed`,`Failed`);case`aborted`:return e(`flow.runs.outcomeAborted`,`Stopped`);case`skipped-trigger`:return e(`flow.runs.outcomeSkippedTrigger`,`Trigger not met`);case`skipped-conditions`:return e(`flow.runs.outcomeSkippedConditions`,`Skipped by conditions`);case`skipped-cooldown`:return e(`flow.runs.outcomeSkippedCooldown`,`Skipped by cooldown`);default:return e(`flow.runs.outcomeSkippedOverlap`,`Skipped by run mode`)}}}function Cn({traces:t,selectedId:n,onSelect:r}){let{t:i}=X(),a=Sn(),s=t===void 0?[]:t.toReversed();return o(Ke,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:S,children:t===void 0?o(Pe,{className:`m-3 h-16`}):s.length===0?o(Se,{title:i(`flow.runs.emptyTitle`,`No runs yet`),description:i(`flow.runs.emptyDescription`,`Each run appears here with what it decided.`)}):e(p,{children:[o(`ul`,{className:`divide-y divide-border-subtle`,"data-testid":`runs-panel`,children:s.map(t=>{let i=t.runId===n;return o(`li`,{children:e(`button`,{type:`button`,"aria-pressed":i,onClick:()=>r(i?null:t.runId),className:`flex w-full flex-col gap-1 px-3 py-2 text-left hover:bg-surface-hover ${i?`bg-primary/10`:``}`,children:[e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[o(J,{variant:yn[t.outcome],children:a(t.outcome)}),t.repeat>1&&o(J,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:Ot(t.lastAt)})]}),o(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),o(`p`,{className:`border-t border-border-subtle px-3 py-2 text-xs text-foreground-subtle`,children:i(`flow.runs.hint`,`Select a run to colour the blocks: green passed, red failed, grey not evaluated.`)})]})})}function wn(e){return bn[e]}function Tn({step:t,title:n,hint:r,trace:i,children:a}){return e(`section`,{className:`rounded-lg border p-3 ${i===null?`border-border bg-surface`:bn[i.tone]}`,"data-testid":`block-${t}`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`h4`,{className:`text-sm font-semibold uppercase tracking-wide`,children:n}),r!==void 0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i!==null&&i.reason!==null&&o(`p`,{className:`mb-2 text-xs font-medium ${xn[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}u();var En=6e4;function Dn(){let e=xe({projection:`slim`});return r(()=>(e.data??[]).filter(e=>H(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 On(e){let t=w();return l({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:En,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function kn(e,t){return e.find(e=>e.cap===t)?.fields??[]}u();function Q({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function An(e){let t=On(e.deviceId);if(t.data!==void 0)return kn(t.data,e.cap).find(t=>t.path===e.fieldPath)}function jn({value:t,devices:n,onChange:r}){let{t:i}=X(),[a,s]=c(!1),l=n.find(e=>e.id===t.deviceId),u=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${l?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${t.cap}.${t.fieldPath}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[o(Q,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(G,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>s(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:u}),o(g,{className:`size-3.5 shrink-0`})]}),a&&o(Mn,{value:t,devices:n,onCancel:()=>s(!1),onConfirm:e=>{s(!1),r(e)}})]})}function Mn({value:t,devices:n,onCancel:i,onConfirm:a}){let{t:s}=X(),l=xe({projection:`slim`}),u=r(()=>new Set(n.map(e=>e.id)),[n]),d=r(()=>e=>u.has(e.id),[u]),[f,p]=c(null),[m,h]=c(!1),[g,_]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!m&&l.status===`success`&&(h(!0),p(jt(l.data).find(e=>e.id===t.deviceId)??null));let v=s(`automation.fieldPicker.title`,`Device value`);return o(Ze,{open:!0,onOpenChange:e=>!e&&i(),children:e(ft,{width:`xl`,children:[o(rt,{children:o(Ge,{children:v})}),o(Nt,{kind:`formula`,enabled:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:v,pickerTargetKind:null},device:f,field:g,deviceFilter:d,onDeviceChange:p,onFieldChange:_}),e(ot,{className:`flex flex-wrap gap-2`,children:[o(G,{variant:`ghost`,onClick:i,children:s(`common.cancel`,`Cancel`)}),o(G,{disabled:f===null||g===null,"data-testid":`field-picker-confirm`,onClick:()=>{f===null||g===null||a({deviceId:f.id,cap:g.cap,fieldPath:g.path})},children:s(`automation.fieldPicker.use`,`Use this value`)})]})]})})}var Nn=1e4;function Pn(e,t,n){let r=Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==t)),i=n===null?r:{...r,[t]:n};return Object.keys(i).length===0?void 0:i}function Fn(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function In({step:t,onChange:n}){let{t:r}=X(),i=at({},{refetchInterval:Nn});if(i.data===void 0)return o(Pe,{className:`h-8 w-64`});let a=i.data.find(e=>e.id===t.actionId),s=t.actionId!==``&&a===void 0;return e(`div`,{className:`space-y-2`,"data-testid":`run-action-step`,children:[e(`label`,{className:`block max-w-sm`,children:[o(Q,{children:r(`automation.runAction.action`,`Action`)}),o(K,{value:t.actionId,onChange:e=>n({kind:`action`,actionId:e.target.value}),options:[{value:``,label:r(`automation.runAction.pick`,`Pick an action`)},...s?[{value:t.actionId,label:r(`automation.runAction.missing`,`Missing action ({{id}})`,{id:t.actionId})}]:[],...i.data.map(e=>({value:e.id,label:e.name}))]})]}),s&&o(`p`,{className:`text-xs text-danger`,children:r(`automation.runAction.missingHint`,`This action no longer exists. Pick another, or the step will fail.`)}),(a?.variables??[]).length>0&&o(`div`,{className:`flex flex-wrap items-end gap-3`,children:(a?.variables??[]).map(e=>o(Ln,{variable:e,value:t.variables?.[e.name],onChange:r=>n(Fn(t,Pn(t.variables,e.name,r)))},e.name))})]})}function Ln({variable:t,value:n,onChange:r}){let{t:i}=X(),a=t.label??t.name,s=t.default===void 0?i(`automation.runAction.required`,`required`):i(`automation.runAction.defaultIs`,`default {{value}}`,{value:String(t.default)});if(t.type===`boolean`||t.type===`select`){let c=t.type===`boolean`?[{value:`true`,label:i(`common.yes`,`Yes`)},{value:`false`,label:i(`common.no`,`No`)}]:(t.options??[]).map(e=>({value:e,label:e}));return e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Kt,{widthClass:`w-40`,value:n===void 0?``:String(n),onChange:e=>{e.target.value===``?r(null):r(t.type===`boolean`?e.target.value===`true`:e.target.value)},options:[{value:``,label:s},...c]})]})}return t.type===`number`?e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Gt,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o(Q,{children:a}),o(q,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}var Rn=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function zn(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 Rn}}function Bn(e){switch(e){case`eq`:return Y.t(`helpers.recipeParts.op_eq`);case`ne`:return Y.t(`helpers.recipeParts.op_ne`);case`gt`:return Y.t(`helpers.recipeParts.op_gt`);case`gte`:return Y.t(`helpers.recipeParts.op_gte`);case`lt`:return Y.t(`helpers.recipeParts.op_lt`);case`lte`:return Y.t(`helpers.recipeParts.op_lte`);case`contains`:return Y.t(`helpers.recipeParts.op_contains`);default:return Y.t(`helpers.recipeParts.op_in`)}}function Vn(e){return zn(e).map(e=>({value:e,label:Bn(e)}))}function Hn(e){switch(e){case`device-state`:return Y.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return Y.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return Y.t(`helpers.recipeParts.trigger_schedule`);case`stationary`:return Y.t(`flow.trigger.stationary`);case`detection`:return Y.t(`flow.trigger.detection`);case`interval`:return Y.t(`flow.trigger.interval`);default:return Y.t(`helpers.recipeParts.trigger_manual`)}}var Un={triggers:[],actions:[]};function Wn(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 * * *`};case`detection`:return{kind:e,classes:[],deviceIds:[]};case`stationary`:return{kind:e,deviceIds:[],phase:`appeared`};case`interval`:return{kind:e,minutes:5};default:return{kind:`manual`}}}function Gn(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
- `};case`action`:return{kind:e,actionId:``};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function Kn(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function qn(){return{kind:`stationary-present`,deviceId:0}}function Jn(){return{kind:`expression`,expr:``,bindings:{}}}function Yn(e,t,n){return e.map((e,r)=>r===t?n:e)}function Xn(e,t){return e.filter((e,n)=>n!==t)}function Zn(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=Xn(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Qn(e,t){return{...e,triggers:[...t]}}function $n(e,t){return{...e,actions:[...t]}}var er=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function tr({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,onChange:c}){let{t:l}=X(),u=er.filter(e=>i===void 0||i.includes(e.value));return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:l(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${s===void 0?`border-border`:wn(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(J,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[o(Q,{children:l(`automation.actionList.step`,`Step`)}),o(K,{value:i.kind,onChange:e=>c(Yn(t,d,Gn(nr(e.target.value)))),options:u.map(e=>({value:e.value,label:l(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(G,{variant:`ghost`,disabled:d===0,onClick:()=>c(Zn(t,d,d-1)),title:l(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(m,{className:`h-3.5 w-3.5`})}),o(G,{variant:`ghost`,disabled:d===t.length-1,onClick:()=>c(Zn(t,d,d+1)),title:l(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(O,{className:`h-3.5 w-3.5`})}),o(G,{variant:`ghost`,onClick:()=>c(Xn(t,d)),title:l(`automation.actionList.removeThisStep`,`Remove this step`),children:o(v,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Q,{children:l(`automation.actionList.seconds`,`Seconds`)}),o(q,{type:`number`,min:0,max:300,value:String(i.seconds),onChange:e=>c(Yn(t,d,{kind:`wait`,seconds:Number(e.target.value)}))})]}),i.kind===`code`&&e(`label`,{className:`block`,children:[o(Q,{children:l(`automation.actionList.code`,`Code`)}),o(`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:i.code,spellCheck:!1,onChange:e=>c(Yn(t,d,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`cap`&&o(gn,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>c(Yn(t,d,e))}),i.kind===`action`&&o(In,{step:i,onChange:e=>c(Yn(t,d,e))})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>c([...t,Gn(u[0]?.value??`cap`)]),children:[o(_,{className:`h-4 w-4`}),` `,l(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function nr(e){return er.find(t=>t.value===e)?.value??`cap`}function rr(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function ir(e){return[{name:`deviceId`,hint:e(`flow.scope.deviceId`,`the camera that saw it`)},{name:`className`,hint:e(`flow.scope.className`,`what it saw`)},{name:`trackId`,hint:e(`flow.scope.trackId`,`the track`)},{name:`score`,hint:e(`flow.scope.score`,`how sure the detector was`)}]}function ar(e){return[{name:`deviceId`,hint:e(`flow.scope.deviceId`,`the camera that saw it`)},{name:`className`,hint:e(`flow.scope.className`,`what it saw`)},{name:`phase`,hint:e(`flow.scope.phase`,`appeared or departed`)},{name:`entryId`,hint:e(`flow.scope.entryId`,`the stopped object`)}]}function or(e,t){if(e.length===0)return[];let[n,...r]=e.map(e=>e.kind===`detection`?ir(t):e.kind===`stationary`?ar(t):[]);return n===void 0?[]:n.filter(e=>r.every(t=>t.some(t=>t.name===e.name)))}var sr=`conditions`;function cr(e){return e===void 0||e.trim()===``?null:e}function lr(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function ur(e){return e.steps.map(e=>({index:lr(e.path),tone:e.outcome===`ok`?`pass`:e.outcome===`error`?`fail`:`idle`,message:cr(e.message)}))}function dr(e){let t=e.conditions.find(e=>e.path===sr);return t===void 0?null:{tone:t.outcome===`pass`?`pass`:t.outcome===`fail`?`fail`:`idle`,reason:cr(t.reason)}}function fr(e,t){return e.outcome===`ran`?{tone:`pass`,reason:null}:e.outcome===`failed`||e.outcome===`aborted`?{tone:`fail`,reason:t.find(e=>e.tone===`fail`)?.message??null}:{tone:`idle`,reason:cr(e.verdict?.reason)}}function pr(e){let t=ur(e);return{when:{tone:e.trigger.outcome===`pass`?`pass`:`fail`,reason:cr(e.trigger.reason)},condition:dr(e),thenBlock:fr(e,t),steps:t}}function mr(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}var hr={name:``,steps:[],variables:[]};function gr(e){return e===null?hr:{name:e.name,steps:e.steps??[],variables:e.variables??[]}}function _r(e){let t=[],n=e=>{t.includes(e)||t.push(e)},r=e=>{if(Xt(e)){n(e.$var);return}Array.isArray(e)?e.forEach(r):typeof e==`object`&&e&&Object.values(e).forEach(r)};for(let t of e)t.kind===`cap`&&(r(t.deviceId),r(t.args));return t}function vr(e){let t=new Set(e.variables.map(e=>e.name));return _r(e.steps).find(e=>!t.has(e))??null}function yr(e){if(e.name.trim()===``)return{ok:!1,reason:{kind:`name`}};if(e.steps.length===0)return{ok:!1,reason:{kind:`no-steps`}};let t=e.variables.find(e=>!wr(e.name));if(t!==void 0)return{ok:!1,reason:{kind:`bad-name`,name:t.name}};let n=Tr(e.variables)[0];if(n!==void 0)return{ok:!1,reason:{kind:`duplicate`,name:n}};let r=vr(e);if(r!==null)return{ok:!1,reason:{kind:`undeclared`,name:r}};let i=te.safeParse({name:e.name.trim(),steps:e.steps,...e.variables.length===0?{}:{variables:e.variables}});if(!i.success){let e=i.error.issues[0];return{ok:!1,reason:{kind:`schema`,message:`${e===void 0||e.path.length===0?``:`${e.path.join(`.`)}: `}${e?.message??`invalid`}`}}}return{ok:!0,input:i.data}}function br(e,t,n){return Xt(e)?e.$var===t?{$var:n}:e:Array.isArray(e)?e.map(e=>br(e,t,n)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,br(r,t,n)])):e}function xr(e,t,n){if(e.kind!==`cap`)return e;let r=Xt(e.deviceId)&&e.deviceId.$var===t?{$var:n}:e.deviceId,i=e.args===void 0?void 0:Object.fromEntries(Object.entries(e.args).map(([e,r])=>[e,br(r,t,n)]));return{...e,deviceId:r,...i===void 0?{}:{args:i}}}function Sr(e,t,n){let r=e.variables[t];return r===void 0||r.name===n?e:{...e,variables:e.variables.map((e,r)=>r===t?{...e,name:n}:e),steps:e.steps.map(e=>xr(e,r.name,n))}}function Cr(e){let t=new Set(e.map(e=>e.name)),n=`value`;for(let e=2;t.has(n);e++)n=`value${String(e)}`;return{name:n,type:`string`}}function wr(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function Tr(e){let t=new Set,n=new Set;for(let r of e)t.has(r.name)&&n.add(r.name),t.add(r.name);return[...n]}var Er=[`number`,`string`,`boolean`,`select`];function Dr(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function Or(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function kr(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Ar(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function jr({variables:t,onChange:n,onRename:r}){let{t:i}=X(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return o(Ke,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:ge,actions:e(G,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Cr(t)]),children:[o(_,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),o(q,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!wr(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),o(q,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,Ar(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),o(Kt,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:Er.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=Er.find(t=>t===e.target.value);t!==void 0&&s(l,Dr(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(Mr,{variable:c,onChange:e=>s(l,kr(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(q,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,Or(c,e.target.value))})]}),o(G,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(v,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Mr({variable:e,onChange:t}){let{t:n}=X(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(Gt,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return o(Kt,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return o(q,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var Nr=5e3;function Pr(e){return e.kind===`cap`||e.kind===`wait`}function Fr(e){return e instanceof Error?e.message:String(e)}function Ir(){let{t:e}=X();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function Lr({entry:t,onClose:n,onSaved:i}){let{t:a}=X(),s=d(),l=k(),u=Dn(),f=Ir(),[m,h]=c(()=>gr(t)),[g,_]=c(null),b=t!==null&&t.readOnly,x=()=>{s.invalidateQueries({queryKey:[[`actions`]]})},S=Xe({onSuccess:e=>{x(),i(e.action.id)}}),C=_t({onSuccess:x}),w=$e({onSuccess:()=>{x(),n()}}),D=tt({onSuccess:x}),O=lt({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Nr}),A=O.data?.traces.find(e=>e.runId===g)??null,j=r(()=>A===null?null:pr(A),[A]),M=yr(m),N=r(()=>rr(m.variables,a),[m.variables,a]),P=S.isPending||C.isPending,F=S.error??C.error??w.error??D.error,I=(t?.variables??[]).some(e=>e.required===!0&&e.default===void 0);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(E,{className:`h-4 w-4 text-foreground-muted`}),o(q,{"aria-label":a(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,disabled:b,placeholder:a(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>h({...m,name:e.target.value})}),o(J,{variant:b?`info`:`primary`,children:b?t?.addonId??``:a(`actions.source.internal`,`Internal`)})]}),b?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:a(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(p,{children:[o(jr,{variables:m.variables,onChange:e=>h({...m,variables:e}),onRename:(e,t)=>h(Sr(m,e,t))}),o(Tn,{step:`steps`,title:a(`actions.editor.steps`,`Steps`),trace:j===null?null:j.thenBlock,children:o(tr,{actions:m.steps,devices:u,allowedKinds:[`cap`,`wait`],variables:N,onChange:e=>h({...m,steps:e.filter(Pr)})})})]}),!M.ok&&!b&&m.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:f(M.reason)}),F!==null&&o(W,{message:Fr(F)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!b&&e(G,{onClick:()=>{M.ok&&(t===null?S.mutate({action:M.input}):C.mutate({actionId:t.id,action:M.input}))},disabled:P||!M.ok,children:[P&&o(T,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(G,{variant:`outline`,disabled:D.isPending||I,title:I?a(`actions.editor.runNeedsDefaults`,`Give each required variable a default to run it from here.`):void 0,onClick:()=>D.mutate({actionId:t.id}),children:[o(y,{className:`h-4 w-4`}),` `,a(`actions.editor.runNow`,`Run now`)]}),t!==null&&!b&&e(G,{variant:`ghost`,disabled:w.isPending,onClick:()=>{l({title:a(`actions.editor.deleteTitle`,`Delete this action?`),message:a(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&w.mutate({actionId:t.id})})},children:[o(v,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(G,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Cn,{traces:t===null?[]:O.data?.traces,selectedId:g,onSelect:_})})]})}u();var Rr=5e3;function zr(e){return e instanceof Error?e.message:String(e)}function Br(){let{t:e}=X();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function Vr({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),a=d(),c=Br(),{state:l,openNew:u,openEdit:f,close:p}=et({editKey:`action`,newKey:`new`}),m=at({},{refetchInterval:Rr}),h=tt({onSuccess:()=>void a.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(u(),n?.())},[t,n,u]);let g=m.data??[],v=l.mode===`edit`?g.find(e=>e.id===l.id)??null:null,b=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(J,{variant:`info`,children:e.addonId}):o(J,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):Ot(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=c(e);return o(`span`,{title:e.status.lastError??void 0,children:o(J,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(G,{variant:`outline`,size:`sm`,disabled:h.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),h.mutate({actionId:t.id})},children:[o(y,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[h,c,i]);return l.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),m.error!=null&&o(W,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:zr(m.error),onRetry:()=>void m.refetch()}),h.error!=null&&o(W,{message:zr(h.error)}),m.data!==void 0&&g.length===0?o(Se,{icon:E,title:i(`actions.list.emptyTitle`,`No actions yet`),description:i(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(G,{onClick:u,children:[o(_,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):o(ze,{columns:b,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ye,emptyMessage:i(`actions.list.loading`,`Loading actions…`),onRowClick:e=>f(e.id)})]}):o(Lr,{entry:v,onClose:p,onSaved:f},v?.id??`new`)}function Hr({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=X(),c=Jr(n,r,i);if(n?.kind===`boolean`)return o(K,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(K,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(q,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(q,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Ur({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=X(),s=Jr(t,n,r);return o(q,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function Wr(e){return typeof e==`object`}function Gr(e){return Wr(e)?e[0]??``:e}function Kr(e){return Wr(e)?e:typeof e==`boolean`?[]:[e]}function qr(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Jr(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=be({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=R(o)?o:void 0,c=qr(e?.quantity,s);if(c===void 0)return;let l=a?.display;return We({quantity:c,display:l,capName:n})}function Yr({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=An(a),c=Vn(s?.kind),l=t.operator===`in`,u=e=>{r({...t,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},d=e=>{let n=Xr(e,c);r({...t,operator:n,value:n===`in`?Kr(t.value):Gr(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(jn,{value:a,devices:n,onChange:u}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(K,{value:t.operator,onChange:e=>d(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Ur,{value:Kr(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(Hr,{value:Gr(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function Xr(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Zr={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Qr({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Q,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(q,{value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:e=>r({kind:`expression`,expr:e.target.value,bindings:t.bindings})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`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.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o($r,{alias:e,source:r,devices:n,onRename:n=>s(ai(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(oi(t.bindings,e))},e)),e(G,{variant:`ghost`,onClick:()=>s({...t.bindings,[ii(t.bindings)]:Zr}),children:[o(_,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function $r({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=X(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:ni(r,ti(n)),cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Q,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(q,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Q,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(K,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Zr),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(q,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:ei(e.target.value)})})]}):o(jn,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:ri(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(G,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(v,{className:`h-3.5 w-3.5`})})]})}function ei(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function ti(e){return e.kind===`global`?e.sourceStableId:``}function ni(e,t){return e.find(e=>e.stableId===t)?.id??0}function ri(e,t){return e.find(e=>e.id===t)?.stableId??``}function ii(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 ai(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function oi(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function si(e){return e.kind===`all`||e.kind===`any`}function ci(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:si(t)?t:{kind:`all`,children:[t]}}function li(e,t){return t===null||si(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function ui(e){return li(e,ci(e))}function di(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?di(e.child,r):null;if(!si(e))return null;let i=e.children[n];return i===void 0?null:di(i,r)}function fi(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=fi(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!si(e))return e;let a=e.children[r];if(a===void 0)return e;let o=fi(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 pi(e){return e===null?null:de({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function mi(e){let t=ci(e);return{depth:t.children.length===0?0:F(t),leaves:t.children.length===0?0:ie(t),depthLimit:3,leafLimit:32}}function hi(e,t){let n=pi(t);return n===null?{ok:!0,recipe:li(e,t)}:{ok:!1,reason:n}}function gi(e,t){let n=ci(e);return hi(e,{kind:n.kind,children:[...n.children,t]})}function _i(e,t,n){return li(e,fi(ci(e),t,()=>n))}function vi(e,t){return li(e,fi(ci(e),t,()=>null))}function yi(e,t,n){return li(e,fi(ci(e),t,e=>si(e)?{kind:n,children:e.children}:e))}function bi(e,t){return di(ci(e),t)===null?{ok:!1,reason:Y.t(`helpers.recipeOps.rowGone`)}:hi(e,fi(ci(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function xi(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 Si(e,t,n){if(t.length<2)return{ok:!1,reason:Y.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:Y.t(`helpers.recipeOps.differentGroups`)};let r=xi(t[0]??[]);if(r===null)return{ok:!1,reason:Y.t(`helpers.recipeOps.rootGroup`)};let i=ci(e),a=di(i,r.path);if(a===null||!si(a))return{ok:!1,reason:Y.t(`helpers.recipeOps.insideNot`)};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:Y.t(`helpers.recipeOps.selectedGone`)};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 hi(e,fi(i,r.path,()=>d))}function Ci(e,t){if(t.length===0)return{ok:!1,reason:Y.t(`helpers.recipeOps.outerNotGroup`)};let n=ci(e),r=di(n,t);if(r===null)return{ok:!1,reason:Y.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return hi(e,fi(n,t,()=>r.child));if(!si(r))return{ok:!1,reason:Y.t(`helpers.recipeOps.rowIsCondition`)};let i=xi(t);if(i===null)return{ok:!1,reason:Y.t(`helpers.recipeOps.noParent`)};let a=di(n,i.path);if(a===null||!si(a))return{ok:!1,reason:Y.t(`helpers.recipeOps.groupInNot`)};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return hi(e,fi(n,i.path,()=>o))}var wi=`text-xs text-foreground-subtle`;function Ti({children:e}){return o(`span`,{className:wi,children:e})}function Ei(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function Di(){let{t:e}=X();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return t}}}function Oi({selected:t,onChange:n,hint:r}){let{t:i}=X(),a=Di(),s=ee.map(e=>e.id),c=t.filter(e=>!s.includes(e));return e(`div`,{className:`space-y-1`,children:[o(Ti,{children:i(`flow.scene.class`,`Class`)}),o(`div`,{className:`flex flex-wrap gap-2`,children:[...s,...c].map(e=>o(G,{size:`sm`,variant:t.includes(e)?`primary`:`outline`,"aria-pressed":t.includes(e),onClick:()=>n(Ei(t,e)),children:a(e)},e))}),r!==void 0&&o(`p`,{className:wi,children:r})]})}function ki({devices:t,selected:n,onChange:r}){let{t:i}=X(),a=t.filter(e=>e.type===fe.Camera);return e(`div`,{className:`space-y-1`,children:[o(Ti,{children:i(`flow.scene.cameras`,`Cameras`)}),o(pn,{devices:a,selection:`multiple`,noun:`camera`,value:n,testId:`scene-cameras`,onChange:r})]})}function Ai({device:t,deviceId:n,selected:r,onToggle:i}){let a=Je({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:wi,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(G,{size:`sm`,variant:r.includes(e.id)?`primary`:`outline`,"aria-pressed":r.includes(e.id),onClick:()=>i(e.id),children:e.name},e.id))]})}function ji({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=X();if(n.length===0)return null;let s=e=>{let t=Ei(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(Ti,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(Ai,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:wi,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var Mi=100;function Ni({trigger:t,devices:n,onChange:r}){let{t:i}=X(),a=Math.round((t.minScore??0)*Mi),s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/Mi})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(Oi,{selected:t.classes,onChange:e=>r({...t,classes:[...e]})}),o(ki,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(ji,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(Ti,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/Mi).toFixed(2)})}),o(`input`,{type:`range`,min:0,max:Mi,value:a,"aria-label":i(`flow.scene.minScoreAria`,`Minimum score`),className:`block w-full max-w-sm accent-primary`,onChange:e=>c(Number(e.target.value))})]})]})}function Pi({trigger:t,devices:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(Oi,{selected:t.classes??[],onChange:e=>{let{classes:n,...i}=t;r(e.length===0?i:{...i,classes:[...e]})},hint:t.classes===void 0?i(`flow.scene.anyClass`,`None picked: any class counts.`):void 0}),o(ki,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(ji,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(mt,{label:i(`flow.scene.firesWhen`,`Fires when it`),value:t.phase,onChange:e=>r({...t,phase:e}),options:[{value:`appeared`,label:i(`flow.scene.phaseAppeared`,`Stopped (parked)`)},{value:`departed`,label:i(`flow.scene.phaseDeparted`,`Left`)}]})]})}function Fi({trigger:t,onChange:n}){let{t:r}=X();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(Ti,{children:r(`flow.scene.every`,`Every`)}),o(Gt,{"aria-label":r(`flow.scene.intervalMinutes`,`Minutes`),className:`w-20`,value:t.minutes,onValue:e=>{e!==null&&n({kind:`interval`,minutes:Math.round(e)})}}),o(Ti,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Ii({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=n.filter(e=>e.type===fe.Camera),s=e=>{let{classes:n,...i}=t;r(e.length===0?i:{...i,classes:[...e]})},c=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},l=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[o(Ti,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(pn,{devices:a,selection:`single`,noun:`camera`,value:t.deviceId>0?[t.deviceId]:[],testId:`stationary-present-camera`,onChange:e=>{let n=e[0];n!==void 0&&n!==t.deviceId&&l(n)}})]}),o(Oi,{selected:t.classes??[],onChange:s,hint:t.classes===void 0?i(`flow.scene.anyClass`,`None picked: any class counts.`):void 0}),o(ji,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:c})]})}u();var Li=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function Ri(e){return e.join(`/`)}function zi(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function Bi({recipe:t,devices:n,onChange:i}){let{t:a}=X(),[s,l]=c([]),[u,d]=c(null),f=ci(t),p=mi(t),m=r(()=>s.map(zi),[s]),h=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},g=Si(t,m,`all`),v=Si(t,m,`any`),y=m.length===1?bi(t,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},x={devices:n,selected:new Set(s),onToggleSelect:e=>l(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(e,n)=>i(_i(t,e,n)),onRemove:e=>{l([]),i(vi(t,e))},onSetKind:(e,n)=>i(yi(t,e,n)),onUngroup:e=>h(Ci(t,e))};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(J,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),o(`div`,{className:`w-32`,children:o(K,{value:f.kind,onChange:e=>i(yi(t,[],Vi(e.target.value))),options:Li.map(e=>({value:e.value,label:a(e.labelKey)}))})}),o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),f.children.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):o(Hi,{container:f,path:[],handlers:x}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>h(gi(t,Kn())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(_,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(G,{variant:`outline`,onClick:()=>h(gi(t,Jn())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(U,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),e(G,{variant:`outline`,onClick:()=>h(gi(t,qn())),title:a(`flow.scene.addParkedTitle`,`True while an object is parked on a camera, in a zone`),children:[o(b,{className:`h-4 w-4`}),` `,a(`flow.scene.addParked`,`Parked object`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(G,{variant:`ghost`,disabled:!g.ok,onClick:()=>h(g),title:g.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):g.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(G,{variant:`ghost`,disabled:!v.ok,onClick:()=>h(v),title:v.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):v.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),o(G,{variant:`ghost`,disabled:!y.ok,onClick:()=>h(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),u!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:u})]})}function Vi(e){return e===`any`?`any`:`all`}function Hi({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(Ui,{node:e,path:[...t,r],handlers:n},Ri([...t,r])))})}function Ui({node:t,path:n,handlers:r}){let{t:i}=X(),a=Ri(n),s=o(Ve,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return si(t)?e(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(`div`,{className:`w-32`,children:o(K,{value:t.kind,onChange:e=>r.onSetKind(n,Vi(e.target.value)),options:Li.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(G,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(me,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(G,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(v,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(Hi,{container:t,path:n,handlers:r})})]}):t.kind===`not`?e(`div`,{className:`rounded border border-border p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(J,{variant:`warning`,children:`NOT`}),e(G,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(me,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(Ui,{node:t.child,path:[...n,0],handlers:r})})]}):e(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[o(`div`,{className:`pt-6`,children:s}),o(`div`,{className:`min-w-0 flex-1`,children:t.kind===`condition`?o(Yr,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):t.kind===`expression`?o(Qr,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(Ii,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(G,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(v,{className:`h-3.5 w-3.5`})})]})}u();function Wi({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=X(),[l,u]=c(!1),d=k(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`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:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(G,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?g:x,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(G,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(_e,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(nt,{maxHeight:420,children:t})})]})}var Gi=[`detection`,`stationary`,`device-state`,`device-event`,`schedule`,`interval`,`manual`],Ki={detection:`scene`,stationary:`scene`,"device-state":`device`,"device-event":`device`,schedule:`time`,interval:`time`,manual:`manual`};function qi(){let{t:e}=X(),t={scene:e(`flow.triggerGroup.scene`,`Scene`),device:e(`flow.triggerGroup.device`,`Devices`),time:e(`flow.triggerGroup.time`,`Time`),manual:e(`flow.triggerGroup.manual`,`By hand`)},n={detection:e(`flow.triggerHint.detection`,`An object class is detected on a camera`),stationary:e(`flow.triggerHint.stationary`,`An object stops, or leaves`),"device-state":e(`flow.triggerHint.deviceState`,`A device value changes or takes a value`),"device-event":e(`flow.triggerHint.deviceEvent`,`An event on the system`),schedule:e(`flow.triggerHint.schedule`,`At a time of day`),interval:e(`flow.triggerHint.interval`,`Again and again, every few minutes`),manual:e(`flow.triggerHint.manual`,`Only when you run it`)};return Gi.map(e=>({value:e,label:Hn(e),description:n[e],group:t[Ki[e]]}))}var Ji=Object.values(le).sort((e,t)=>e.localeCompare(t));function Yi({triggers:t,devices:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:i(`automation.triggerEditor.noTriggersYetWithoutOne`,`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.`)}),t.map((e,i)=>o(Xi,{trigger:e,devices:n,position:i,onChange:e=>r(Yn(t,i,e)),onRemove:()=>r(Xn(t,i))},`${e.kind}-${String(i)}`)),e(G,{variant:`outline`,onClick:()=>r([...t,Wn(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(_,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function Xi({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=X(),c=qi();return e(`div`,{className:`rounded border border-border p-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(J,{variant:`default`,children:r===0?s(`automation.triggerEditor.when`,`When`):s(`automation.triggerEditor.orWhen`,`or when`)}),e(`div`,{className:`min-w-[13rem] flex-1`,children:[o(Q,{children:s(`automation.triggerEditor.trigger`,`Trigger`)}),o(Ie,{mode:`single`,singleDisplay:`field`,options:c,value:t.kind,onChange:e=>{e!==t.kind&&i(Wn(Zi(e)))}})]}),o(G,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(v,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o($i,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(ta,{trigger:t,devices:n,onChange:i}),t.kind===`schedule`&&e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:s(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(q,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>i({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`detection`&&o(Ni,{trigger:t,devices:n,onChange:i}),t.kind===`stationary`&&o(Pi,{trigger:t,devices:n,onChange:i}),t.kind===`interval`&&o(Fi,{trigger:t,onChange:i}),t.kind===`manual`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function Zi(e){return Gi.find(t=>t===e)??`manual`}function Qi(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 $i({trigger:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=An(a),c={...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}};return e(p,{children:[o(jn,{value:a,devices:n,onChange:e=>r(Qi(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Ve,{checked:t.becomes===void 0,onChange:e=>r(Qi(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(Hr,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(Qi(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Ve,{checked:t.edge===!0,onChange:e=>r(Qi(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(q,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(Qi(a,{...c,forMs:ea(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(q,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(Qi(a,{...c,debounceMs:ea(e.target.value)}))})]})]})}function ea(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function ta({trigger:t,devices:n,onChange:r}){let{t:i}=X();return e(p,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(K,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...Ji.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(pn,{devices:n,selection:`single`,value:t.deviceId===void 0?[]:[t.deviceId],emptyLabel:i(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>r({kind:`device-event`,category:t.category,...e[0]===void 0?{}:{deviceId:e[0]}})})]})]})}var na=[`single`,`restart`,`queued`,`parallel`,`cooldown`],ra=2,ia=30;function aa(e){return e.runMode??{mode:`single`}}function oa(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function sa(e){switch(e){case`queued`:return{mode:`queued`,max:ra};case`parallel`:return{mode:`parallel`,max:ra};case`cooldown`:return{mode:`cooldown`,minutes:ia};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function ca(e){return na.find(t=>t===e)??`single`}function la({value:t,onChange:n}){let{t:r}=X(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),o(Kt,{widthClass:`w-56`,value:t.mode,options:na.map(e=>({value:e,label:i[e]})),onChange:e=>n(sa(ca(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),o(Gt,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),o(Gt,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),o(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}u();var ua=`hub`,da=5e3;function fa({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=X(),[p,m]=c(t?.name??``),[h,g]=c(()=>ui(n)),[_,v]=c(!1),[y,b]=c(null),x=He({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:da}),S=x.data?.traces.find(e=>e.runId===y)??null,C=r(()=>S===null?null:pr(S),[S]),w=r(()=>or(h.triggers,f),[h.triggers,f]),E=Dn(),D=de(h),O=r(()=>pa(h),[h]),k=r(()=>ma(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),A=p.trim()===``,j=A||D!==null||O!==null||k.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[e(`div`,{className:`space-y-4`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:`info`,children:f(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(q,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Tn,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:C===null?null:C.when,hint:f(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:o(Yi,{triggers:h.triggers,devices:E,onChange:e=>g(Qn(h,e))})}),o(Tn,{step:`if`,title:f(`automation.automationEditor.andOnlyIf`,`And only if`),trace:C===null?null:C.condition,hint:f(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:o(Bi,{recipe:h,devices:E,onChange:g})}),o(Tn,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:C===null?null:C.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(tr,{actions:h.actions,devices:E,variables:w,stepTones:C===null?void 0:h.actions.map((e,t)=>mr(C,t)??`idle`),onChange:e=>g($n(h,e))})}),o(Tn,{step:`mode`,title:f(`flow.runMode.title`,`Overlap`),trace:null,hint:f(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(la,{value:aa(h),onChange:e=>g(oa(h,e))})}),o(Wi,{code:k.code,error:k.error,canEject:t!==null,ejecting:s,onEject:u}),D!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:D}),D===null&&O!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:O}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{onClick:()=>{k.code!==null&&l({name:p.trim(),code:k.code,enabled:t?.enabled??!0,placement:ua})},disabled:i||j,children:[i&&o(T,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(G,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[o(N,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,_?`▾`:`▸`]}),o(G,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),A&&o(J,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:re(t.id)},components:{code:o(`code`,{})}})}),o(Qe,{addonId:re(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Cn,{traces:t===null?[]:x.data?.traces,selectedId:y,onSelect:b})})]})}function pa(e){let t=V.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Y.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function ma(e,t){try{return{code:ne({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function ha(e){if(!e.enabled)return{tone:`idle`,label:Y.t(`helpers.coreBlockStatus.disabled`),detail:Y.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Y.t(`helpers.coreBlockStatus.running`),detail:Y.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function ga(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function _a(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function va(e){let t=e=>{let t=ha(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 ya(e){if(e.length===0)return Y.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>ha(e).tone===`error`).length,n=e.filter(e=>ha(e).tone===`ok`).length,r=[Y.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Y.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Y.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function ba({block:t,busy:n,logsOpen:r,unreadable:i,onEdit:a,onToggle:s,onToggleLogs:c,onDelete:l}){let u=D(),{t:d}=X(),f=ha(t),p=ke(t.updatedAt,u);return e(`li`,{className:`flex flex-col gap-2 p-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(J,{variant:ga(f.tone),children:f.label}),p!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:d(`common.edited`,{when:p})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:f.detail}),i!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:d(`automation.editor.listUnreadable`,{reason:i})})]}),e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),a()},disabled:i!==null,title:i===null?d(`common.edit`,`Edit`):d(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(C,{className:`h-4 w-4`})}),e(dt,{children:[o(it,{children:o(G,{variant:`ghost`,disabled:!0,title:d(`automation.automationList.runActions`,`Run actions`),children:o(y,{className:`h-4 w-4`})})}),o(ct,{children:d(`automation.automationList.runningAnAutomationByHand`,`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.`)})]}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:d(`automation.automationList.logs`,`Logs`),children:o(N,{className:`h-4 w-4`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s(!t.enabled)},disabled:n,title:t.enabled?d(`common.disable`,`Disable`):d(`common.enable`,`Enable`),children:t.enabled?d(`common.disable`,`Disable`):d(`common.enable`,`Enable`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:d(`common.delete`,`Delete`),children:o(v,{className:`h-4 w-4`})})]})]}),r&&e(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:re(t.id)},components:{code:o(`code`,{})}})}),o(Qe,{addonId:re(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function xa({onCreate:t}){let{t:n}=X();return o(qe,{children:e(`div`,{className:`space-y-2 p-4`,children:[o(`p`,{className:`text-sm text-foreground`,children:n(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),o(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:n(`automation.automationList.anAutomationIsATrigger`,`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.`)}),o(G,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var Sa=[`coreBlocks`,`list`],Ca=5e3;function wa(e){return e instanceof Error?e.message:String(e)}function Ta({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:d}){let{t:p}=X(),m=w(),{state:h,openNew:g,openEdit:_,close:v}=et({editKey:`block`,newKey:`new`}),[y,b]=c(null),x=k(),[S,C]=c(null),T=n(null),E=h.mode!==`closed`;s(()=>{u&&(b(null),g(),a?.(null),d?.())},[u,d,a,g]);let D=l({queryKey:Sa,refetchInterval:Ca,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),O=()=>{D.refetch()},j=D.data;s(()=>{i===void 0||T.current===i||j?.find(e=>e.id===i&&Bt(e.code))!==void 0&&(T.current=i,_(i),a?.(i))},[i,j,_,a]);let M=f({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),O()}}),N=f({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),O()}}),P=f({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:O}),F=f({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:O}),I=f({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Ut(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{v(),b(null),O(),t(e.block.id)}}),L=D.data,R=va((L??[]).filter(e=>Bt(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:_a(R,B),ee=V===null?null:Ht(V.code),te=M.error===null?N.error===null?I.error===null?null:wa(I.error):wa(N.error):wa(M.error),ne=r(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=Ht(e.code);return o(`ul`,{className:`list-none`,children:o(ba,{block:e,busy:F.isPending||P.isPending,logsOpen:S===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>C(S===e.id?null:e.id),onDelete:()=>{x({title:p(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:p(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:p(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&P.mutate(e.id)})}})})},sortValue:e=>e.name}],[x,S,a,_,P,F,p]);return E?e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(A,{className:`h-4 w-4 text-foreground-muted`}),V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name})]}),o(fa,{existing:V,initialRecipe:ee!==null&&ee.ok?ee.recipe:Un,saving:M.isPending||N.isPending,saveError:te,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)}},V?.id??`new`),P.error!=null&&o(W,{message:wa(P.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:ya(R)}),D.error!=null&&o(W,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:wa(D.error),onRetry:O}),z?o(xa,{onCreate:()=>{b(null),g(),a?.(null)}}):o(ze,{columns:ne,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ye,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{b(e),_(e.id),a?.(e.id)}}),P.error!=null&&o(W,{message:wa(P.error)}),F.error!=null&&o(W,{message:wa(F.error)})]})}u();function Ea({mode:e,onTitle:t}){return o(e===`helper`?Da:Oa,{onTitle:t})}function Da({onTitle:e}){let{t}=X(),n=xt(),r=Ce(),i=De(),a=Me({addonId:`composer`}),[l,u]=c(null),d=Aa(l,t);return s(()=>{e(d)},[e,d]),o(`div`,{className:`flex flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Ft,{purpose:`create`,initial:null,start:`template`,saving:r.isPending,onDraftChange:u,onSave:async(e,o)=>{let s=null,c=await Pt(e,async(e,c)=>{let{block:l}=await r.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:e}}),u=await ja(l.id,async()=>(await a.refetch()).data??a.data);if(u===null)throw Error(t(`helper.devicePending`));s=u,c!==``&&await i.mutateAsync({deviceId:u,name:c}),o===`open`&&n(St(u),{replace:!0})}),l=s;return c.length>0||l===null?{kind:`refused`,lines:Ma(c,t)}:{kind:`saved`,deviceId:l}}})})}function Oa({onTitle:t}){let{t:n}=X(),r=D(),i=xt(),a=Ce(),l=De(),u=Me({addonId:`composer`}),[d,f]=c(fe.Sensor),[p,m]=c(oe.TemperatureSensor),[h,g]=c(``),[_,v]=c(null),y=Mt({type:d,role:p});return s(()=>{t(n(`helper.newComposition`))},[t,n]),e(`div`,{className:`flex flex-col gap-3`,"data-testid":`blank-composition-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),o(K,{value:d,onChange:e=>{let t=Object.values(fe).find(t=>t===e.target.value);t!==void 0&&f(t)},options:Object.values(fe).map(e=>({value:e,label:Fe(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`customize.identity.role`),o(K,{value:p??``,onChange:e=>m(Object.values(oe).find(t=>t===e.target.value)??null),options:[{value:``,label:n(`customize.identity.noRole`)},...Object.values(oe).map(e=>({value:e,label:je(e,r).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(q,{"aria-label":n(`compositionEditor.name`),value:h,onChange:e=>g(e.target.value)})]})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(G,{disabled:y===null||a.isPending,onClick:()=>{y!==null&&ka({composition:y,name:h,create:e=>a.mutateAsync({block:e}),rename:(e,t)=>l.mutateAsync({deviceId:e,name:t}),readFleet:async()=>(await u.refetch()).data??u.data,onError:e=>v(e),onOpen:e=>i(wt(e),{replace:!0}),pending:n(`helper.devicePending`)})},children:n(`compositionEditor.save`)})]})}async function ka(e){e.onError(null);try{let t=e.name.trim(),{block:n}=await e.create({...t===``?{}:{name:t},enabled:!0,composition:e.composition}),r=await ja(n.id,e.readFleet);if(r===null){e.onError(e.pending);return}t!==``&&await e.rename(r,t),e.onOpen(r)}catch(t){e.onError(t instanceof Error?t.message:String(t))}}function Aa(e,t){if(e===null)return t(`helper.newHelper`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);if(e.templateId===`appliance`&&e.appliance!==null)return t(`helper.newTitle.${e.appliance}`);if(e.templateId===`appliance`)return t(`helper.newHelper`);let n=I(e.templateId);return t(n===null?`helper.newHelper`:`helper.newTitle.${n.id}`)}async function ja(e,t){let n=`${L}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}function Ma(e,t){return e.length>0?e:It(t(`helper.devicePending`))}function Na(e){return{state:`answered`,byRef:new Map(e.map(e=>[z(e),e]))}}function Pa(e,t){if(e.state!==`unanswered`)return e.byRef.get(z(t))??null}function Fa(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Ia(e){return B(e).map(e=>e.source)}function La(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(...Ia(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Ia(e))}let r=new Set;return n.filter(e=>{let t=z(e);return r.has(t)?!1:(r.add(t),!0)})}function Ra(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:Y.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Y.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Y.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Y.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function za(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Ra(e);case`degraded`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.degraded`),reason:n??Y.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Y.t(`helpers.compositionRows.failed`),reason:n??Y.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Y.t(`helpers.compositionRows.notRunning`),reason:n??Y.t(`helpers.compositionRows.notRunningReason`)}}}function Ba(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Y.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Y.t(`helpers.compositionRows.unknown`),reason:Y.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return za(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.notReported`),reason:Y.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Va(e){return z(e)}function Ha(e,t){let n=Pa(t,e);return{key:z(e),label:n?n.name:Va(e),presence:Fa(n),deviceId:n?n.id:null}}function Ua(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Wa(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:ae(e.block.id),a=z(i),o=La(e).filter(e=>z(e)!==a).map(e=>Ha(e,t)),s=n.features.map(e=>e.enabled===!1?Y.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Pa(t,i),l=Ua(e),u=Ba(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=Fa(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Va(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function Ga(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Ka(e,t){return Ga(e)-Ga(t)||e.name.localeCompare(t.name)}function qa(e,t){let n=e.flatMap(e=>{let n=Wa(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Ka),customizations:n.filter(e=>e.kind===`customization`).toSorted(Ka)}}u();var Ja=1e4;function Ya(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Xa(){let e=Ct();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Y.t(`build.customDeviceTab.deviceListPending`):Y.t(`build.customDeviceTab.deviceListUnreadable`,{error:Ya(e.error)})}:Na(e.data)}function Za(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Qa({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=X(),[i,a]=Et(),s=Be({},{refetchInterval:Ja}),l=Xa(),u=et({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?Za(i.get(`new`),t):null,m=f!==null,[h,g]=c(``),_=k(),v=Te(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=s.data;return e(p,{children:[eo(b,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void s.refetch()})})}}),o(ut,{open:m||d!==null,onClose:y,title:m?h||r(f===`blank`?`helper.newComposition`:`helper.newHelper`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:pe,width:`xl`,testId:`composed-device-editor`,children:m&&f!==null?o(Ea,{mode:f,onTitle:g},f):d===null?null:o(Lt,{blockId:d})}),v.error!=null&&o(W,{message:Ya(v.error)})]})}function $a(t){return o(qe,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Y.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Y.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function eo(e,t,n,r,i){if(t!=null&&e===void 0)return o(W,{title:Y.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Ya(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Y.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return $a(e.reason);let a=t==null?null:Ya(t);return o(to,{lists:qa(e.views,r),fleet:r,refreshError:a,handlers:i})}function to({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=X();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(no,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,handlers:i}),o(no,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,handlers:i})]})}function no({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=X();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(ze,{columns:ro(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:ye,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function ro(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(io,{row:e})},{key:`type`,header:Y.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Y.t(`common.unknownWord`)})},{key:`state`,header:Y.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(J,{variant:ga(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:Y.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(oo,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(G,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(v,{className:`h-4 w-4`})})]})}),a}function io({row:t}){let{t:n}=X();return e(`div`,{className:`space-y-0.5`,children:[o(ao,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function ao({row:e}){let{t}=X(),n=Ee(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(Tt,{to:e.kind===`composed`?St(e.reportedDeviceId):wt(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function oo({sources:t}){let{t:n}=X();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(Tt,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function so(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 co(e){if(Array.isArray(e))return e}function lo(e,t,n){return(t=yo(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function uo(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 fo(){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 po(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 mo(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?po(Object(n),!0).forEach(function(t){lo(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):po(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ho(e,t){if(e==null)return{};var n,r,i=go(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 go(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 _o(e,t){return co(e)||uo(e,t)||bo(e,t)||fo()}function vo(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 yo(e){var t=vo(e,`string`);return typeof t==`symbol`?t:t+``}function bo(e,t){if(e){if(typeof e==`string`)return so(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)?so(e,t):void 0}}function xo(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function So(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 Co(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?So(Object(n),!0).forEach(function(t){xo(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):So(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function wo(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function To(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 Eo(e){return{}.toString.call(e).includes(`Object`)}function Do(e){return!Object.keys(e).length}function Oo(e){return typeof e==`function`}function ko(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ao(e,t){return Eo(t)||Fo(`changeType`),Object.keys(t).some(function(t){return!ko(e,t)})&&Fo(`changeField`),t}function jo(e){Oo(e)||Fo(`selectorType`)}function Mo(e){Oo(e)||Eo(e)||Fo(`handlerType`),Eo(e)&&Object.values(e).some(function(e){return!Oo(e)})&&Fo(`handlersType`)}function No(e){e||Fo(`initialIsRequired`),Eo(e)||Fo(`initialType`),Do(e)&&Fo(`initialContent`)}function Po(e,t){throw Error(e[t]||e.default)}var Fo=To(Po)({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"}),Io={changes:Ao,selector:jo,handler:Mo,initial:No};function Lo(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Io.initial(e),Io.handler(t);var n={current:e},r=To(Bo)(n,t),i=To(zo)(n),a=To(Io.changes)(e),o=To(Ro)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Io.selector(e),e(n.current)}function c(e){wo(r,i,a,o)(e)}return[s,c]}function Ro(e,t){return Oo(t)?t(e.current):t}function zo(e,t){return e.current=Co(Co({},e.current),t),t}function Bo(e,t,n){return Oo(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var Vo={create:Lo},Ho={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Uo(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 Wo(e){return{}.toString.call(e).includes(`Object`)}function Go(e){return e||Yo(`configIsRequired`),Wo(e)||Yo(`configType`),e.urls?(Ko(),{paths:{vs:e.urls.monacoBase}}):e}function Ko(){console.warn(Jo.deprecation)}function qo(e,t){throw Error(e[t]||e.default)}var Jo={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
- `},Yo=Uo(qo)(Jo),Xo={config:Go},Zo=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Qo(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Qo(e[n],t[n]))}),mo(mo({},e),t)}var $o={type:`cancelation`,msg:`operation is manually canceled`};function es(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r($o):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var ts=[`monaco`],ns=_o(Vo.create({config:Ho,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),rs=ns[0],is=ns[1];function as(e){var t=Xo.config(e),n=t.monaco,r=ho(t,ts);is(function(e){return{config:Qo(e.config,r),monaco:n}})}function os(){var e=rs(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(is({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),es(ps);if(window.monaco&&window.monaco.editor)return ds(window.monaco),e.resolve(window.monaco),es(ps);Zo(ss,ls)(us)}return es(ps)}function ss(e){return document.body.appendChild(e)}function cs(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function ls(e){var t=rs(function(e){return{config:e.config,reject:e.reject}}),n=cs(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function us(){var e=rs(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;ds(n),e.resolve(n)},function(t){e.reject(t)})}function ds(e){rs().monaco||is({monaco:e})}function fs(){return rs(function(e){return e.monaco})}var ps=new Promise(function(e,t){return is({resolve:e,reject:t})}),ms={config:as,init:os,__getMonacoInstance:fs};u();var hs={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},gs={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function _s({children:e}){return t.createElement(`div`,{style:gs.container},e)}var vs=_s;function ys({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...hs.wrapper,width:e,height:n},...s},!r&&t.createElement(vs,null,i),t.createElement(`div`,{ref:a,style:{...hs.fullWidth,...!r&&hs.hide},className:o}))}var bs=i(ys);function xs(e){s(e,[])}var Ss=xs;function Cs(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=Cs;function ws(){}function Ts(e,t,n,r){return Es(e,r)||Ds(e,t,n,r)}function Es(e,t){return e.editor.getModel(Os(e,t))}function Ds(e,t,n,r){return e.editor.createModel(t,n,r?Os(e,r):void 0)}function Os(e,t){return e.Uri.parse(t)}function ks({original:e,modified:r,language:i,originalLanguage:o,modifiedLanguage:l,originalModelPath:u,modifiedModelPath:d,keepCurrentOriginalModel:f=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=ws,onMount:S=ws}){let[C,w]=c(!1),[T,E]=c(!0),D=n(null),O=n(null),k=n(null),A=n(S),j=n(x),M=n(!1);Ss(()=>{let e=ms.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 t=D.current.getOriginalEditor(),n=Ts(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Ts(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],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(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=Ts(O.current,e||``,o||i||`text`,u||``),n=Ts(O.current,r||``,l||i||`text`,d||``);D.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),P=a(()=>{!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]);s(()=>{C&&A.current(D.current,O.current)},[C]),s(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(bs,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(ks);function As(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var js=As,Ms=new Map;function Ns({defaultValue:e,defaultLanguage:r,defaultPath:i,value:o,language:l,path:u,theme:d=`light`,line:f,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=ws,onMount:C=ws,onChange:w,onValidate:T=ws}){let[E,D]=c(!1),[O,k]=c(!0),A=n(null),j=n(null),M=n(null),N=n(C),P=n(S),F=n(),I=n(o),L=js(u),R=n(!1),z=n(!1);Ss(()=>{let e=ms.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Ts(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&Ms.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Ms.get(u)))},[u],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()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=Ts(A.current,o||e||``,r||l||``,t||``);j.current=A.current?.editor.create(M.current,{model:n,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(Ms.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{E&&N.current(j.current,A.current)},[E]),s(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,s(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),s(()=>{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 V(){F.current?.dispose(),_?g&&Ms.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(bs,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var Ps=i(Ns);u();function Fs(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 Is={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Ls(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Is}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function Rs({value:e,onChange:t,extraLibs:r=[],path:i=`file:///block.ts`,onDiagnostics:c,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=n(null),p=a((e,t)=>{if(f.current=t,Ls(t,r),c===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{c(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,c]);return s(()=>{let e=f.current;e!==null&&Ls(e,r)},[r]),o(Ps,{height:u,defaultLanguage:`typescript`,path:i,theme:d?`vs-dark`:`vs`,value:e,onChange:e=>t(e??``),onMount:p,options:{readOnly:l,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function zs(e){return e.some(e=>e.severity>=8)}var Bs=[{id:`blank`,name:`Blank script`,get description(){return Y.t(`helpers.buildExamples.blankDescription`)},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 Vs(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 Hs=Bs.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 Us({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Y.t(`helpers.restartGate.saveFirstNoProcess`):n?Y.t(`helpers.restartGate.saving`):r?Y.t(`helpers.restartGate.restarting`):t?Y.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Y.t(`helpers.restartGate.disabled`)}u();var Ws=5e3;function Gs(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 Ks({blockId:t}){let{t:n}=X(),i=re(t),a=xe({addonId:i,projection:`slim`},{refetchInterval:Ws}),s=r(()=>Gs(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(T,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(J,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(Tt,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Ne,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(J,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function qs(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 Js(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 Ys(e){switch(e){case`refresh-channel-catalog`:return Y.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Y.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Y.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Y.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Y.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Y.t(`build.scriptSettingsPanel.enableUnifi`)}}function Xs(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Zs(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Qs(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Xs(e);n!==null&&(t[n]=Zs(e))}return t}function $s(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function ec({blockId:t}){let{t:n}=X(),i=w(),s=Ae({blockId:t},{retry:!1}),l=Re({blockId:t},{refetchInterval:1e4,retry:!1}),u=Oe({onSuccess:()=>{l.refetch()}}),d=Ue(),f=we(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=$s(l.data)?l.data:null,S=r(()=>x===null?{}:Qs(x),[x]),C=p??S,E=a(e=>{m(e)},[]),D=p!==null,O=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(qs(e)){b(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:Js(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(Ys(e))),await d.mutateAsync({blockId:t}),await l.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){g(e instanceof Error?e.message:String(e))}finally{b(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(T,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):x===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(G,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||u.isPending||y,children:[u.isPending&&o(T,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(yt,{schema:x,values:C,onChange:E,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var tc=`hub`;function nc({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:m,onCancel:h}){let{t:g}=X(),_=w(),v=k(),{resolvedMode:y}=pt(),b=se({code:t?.code??Hs,files:t?.files,entry:t?.entry}),[x,S]=c(t?.name??``),[C,E]=c(b.files),[D,O]=c(b.entry),[A,F]=c(b.entry),[I,L]=c(t?.placement??tc),[R,z]=c(t?.integrationId??``),[B,V]=c([]),[ee,te]=c(!1),[ne,ie]=c(`blank`),[H,ae]=c(null),[oe,ce]=c(``),le=C[A]??``,ue=e=>{E(t=>({...t,[A]:e}))},de=Object.keys(C).toSorted(),fe=Bs.length>1,pe=r(()=>[...n?.libs??[],...Fs(C,A)],[n?.libs,C,A]),U=f({mutationFn:()=>_.trpcClient.coreBlocks.compile.mutate({files:C,entry:D})}),me=r(()=>B.filter(e=>e.severity>=8),[B]),he=zs(B),ge=x.trim()===``,_e=t===null?null:se(t),ve=t===null||_e===null||JSON.stringify(C)!==JSON.stringify(_e.files)||D!==_e.entry||x.trim()!==t.name||I!==t.placement||(R.trim()===``?void 0:R.trim())!==t.integrationId,ye=()=>{U.reset(),m({name:x.trim(),files:C,entry:D,enabled:t?.enabled??!0,placement:I,...R.trim()===``?{}:{integrationId:R.trim()}})},be=()=>{let e=Vs(Object.keys(C));E(t=>({...t,[e]:``})),F(e),ae(e),ce(e)},xe=e=>{ae(e),ce(e)},Se=()=>{if(H===null)return;let e=H,t=oe.trim();if(ae(null),!(t===``||t===e)){if(C[t]!==void 0){F(t);return}E(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),D===e&&O(t),F(t)}},Ce=async e=>{let t=Bs.find(t=>t.id===e);if(t===void 0)return;let n=Bs.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(C)===JSON.stringify(n.files)&&D===n.entry)&&!await v({title:g(`build.blockEditor.loadExample`,`Load example`),message:g(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:g(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(ie(e),E({...t.files}),O(t.entry),F(t.entry),(x.trim()===``||ne===`blank`)&&S(t.id===`blank`?``:t.name))},we=t===null?null:ha(t),Te=Us({existing:t,dirty:ve,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[we!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(J,{variant:ga(we.tone),children:we.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.name`,`Name`)}),o(q,{className:`mt-1`,value:x,onChange:e=>S(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(q,{className:`mt-1`,value:R,onChange:e=>z(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&fe&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ne,onChange:e=>void Ce(e.target.value),"data-testid":`script-example-select`,children:Bs.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(vt,{selectedNodeId:I,onSelect:L,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),I!==tc&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(P,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(Z,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[de.map(t=>H===t?o(q,{value:oe,onChange:e=>ce(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),ae(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":g(`build.blockEditor.renameFile`,`Rename file`)},t):e(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${t===A?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>F(t),onDoubleClick:()=>xe(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===D?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(`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:g(`build.blockEditor.file`,`+ file`)}),A!==D&&o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>O(A),title:g(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:g(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:g(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(Rs,{value:le,onChange:ue,path:`file:///${A}`,extraLibs:pe,onDiagnostics:V,dark:y===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:g(`build.blockEditor.theNodeReturnedNoType`,`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.`)}),me.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:g(`build.blockEditor.errorsCannotSave`,{count:me.length})}),me.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:g(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),me.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:me.length-5})})]}),U.data!==void 0&&(U.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(M,{className:`h-3.5 w-3.5`}),` `,g(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[U.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(U.data.line)})}),U.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),U.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[g(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,rc(U.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(ec,{blockId:t.id}),o(Ks,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>U.mutate(),disabled:U.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[U.isPending&&o(T,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(G,{onClick:ye,disabled:a||he||ge,children:[a&&o(T,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(G,{variant:`outline`,onClick:()=>d?.(),disabled:Te!==null||d===void 0,title:Te??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(j,{className:`h-4 w-4 animate-spin`}):o(j,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(G,{variant:`ghost`,onClick:()=>te(!ee),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[o(N,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,ee?`▾`:`▸`]}),o(G,{variant:`ghost`,onClick:h,disabled:a,children:g(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[g(`build.blockEditor.errorsCount`,{count:me.length}),ve&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),ge&&o(J,{variant:`warning`,children:g(`build.blockEditor.nameRequired`,`Name required`)})]}),ee&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?g(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(p,{children:o(Z,{i18nKey:`build.blockEditor.logsOf`,values:{id:re(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Qe,{addonId:re(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function rc(e){return e instanceof Error?e.message:String(e)}u();var ic=[`coreBlocks`,`list`],ac=[`coreBlocks`,`getTypeDefs`],oc=5e3;function sc(e){return e instanceof Error?e.message:String(e)}function cc({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=D(),{t:p}=X(),m=w(),{state:h,openNew:g,openEdit:_,close:y}=et({editKey:`block`,newKey:`new`}),[b,x]=c(null),S=k(),[C,T]=c(null),E=l({queryKey:ic,refetchInterval:oc,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),O=h.mode!==`closed`,A=l({queryKey:ac,enabled:O,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),M=()=>{E.refetch()},P=n(null),F=E.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&ue(e)===`code`)!==void 0&&(P.current=t,_(t),i?.(t))},[t,F,_,i]),s(()=>{a&&(x(null),g(),i?.(null),u?.())},[a,u,i,g]);let I=f({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),i?.(e.block.id),M()}}),L=f({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),i?.(e.block.id),M()}}),R=f({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:M}),z=f({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:M}),B=f({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:M}),V=va((E.data??[]).filter(e=>ue(e)===`code`)),ee=E.data!==void 0&&V.length===0,te=I.isPending||L.isPending,ne=I.error===null?L.error===null?null:sc(L.error):sc(I.error),ie=h.mode===`edit`?V.find(e=>e.id===h.id)??(b!==null&&b.id===h.id?b:null):null,H=h.mode===`new`||ie===null?null:_a(V,ie),ae=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=ha(t),r=ke(t.updatedAt,d);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(J,{variant:ga(n.tone),children:n.label}),o(J,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),C===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(Z,{i18nKey:`common.logsOf`,values:{id:re(t.id)},components:{code:o(`code`,{})}})}),o(Qe,{addonId:re(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=z.isPending||R.isPending,r=B.isPending&&B.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),x(t),_(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(j,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),T(C===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(N,{className:`h-4 w-4`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),z.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),S({title:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`),message:p(`build.scriptsTab.deleteMessage`,`{{name}} and its source will be deleted. This cannot be undone.`,{name:t.name}),confirmLabel:p(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&R.mutate(t.id)})},title:p(`common.delete`,`Delete`),children:o(v,{className:`h-4 w-4`})})]})}}],[S,C,i,_,R,B.isPending,B.variables,z,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:E.data===void 0?``:ya(V)}),E.error!=null&&o(W,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:sc(E.error),onRetry:M}),o(ze,{columns:ae,rows:V,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ye,emptyMessage:ee?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):E.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{x(e),_(e.id),i?.(e.id)}}),o(ut,{open:O,onClose:()=>{I.reset(),L.reset(),B.reset(),x(null),y(),i?.(null)},title:H===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:H.name}),icon:he,width:`xl`,testId:`script-editor-panel`,children:o(nc,{existing:H,typeDefs:A.data,typeDefsLoading:A.isLoading,saving:te,saveError:ne,restarting:B.isPending,restartError:B.error===null?null:sc(B.error),onRestart:H===null?void 0:()=>B.mutate(H.id),onSave:e=>{let t=H;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),B.reset(),x(null),y(),i?.(null)}})}),R.error!=null&&o(W,{message:sc(R.error)}),z.error!=null&&o(W,{message:sc(z.error)}),B.error!=null&&o(W,{message:sc(B.error)})]})}var lc=[`automations`,`actions`,`scripts`,`custom-device`];function uc(e){return e!==null&&lc.some(t=>t===e)}var dc=[`coreBlocks`,`list`,`build-counts`],fc=[`actions`,`list`,`build-counts`],pc=[`block`,`action`,`create`,`new`];function mc(e){return e.filter(e=>ue(e)===`code`).length}function hc(e){return e.filter(e=>Bt(e.code)).length}function gc(e,t){return t===null?e:`${e} (${String(t)})`}function _c(){let{t}=X(),n=w(),[r,i]=Et(),a=r.get(`tab`),s=uc(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:dc,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:mc(u),f=u===void 0?null:hc(u),p=l({queryKey:fc,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,g=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=g.data?.state===`loaded`?g.data.views.length:null,y=e=>{i(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})},b=e=>{i(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})},x=e=>{i(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})},S=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},C=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`custom-device`),t.delete(`block`),t.delete(`create`),t.set(`new`,e),t},{replace:!0})},T=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},E=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):t(`build.newScript`,`New script`),D=bt(`/build`,{t,isAdmin:!0})??{icon:h,title:t(`nav.build`,`Build-your-self`)};return o(Dt,{icon:D.icon,title:D.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${D.title} sections`,fill:!0,actions:s===`custom-device`?e(`div`,{className:`flex flex-wrap gap-2`,children:[e(G,{type:`button`,variant:`outline`,onClick:()=>C(`blank`),"data-testid":`build-new-composition`,children:[o(_,{className:`h-4 w-4`}),` `,t(`helper.newComposition`)]}),e(G,{type:`button`,onClick:()=>C(`helper`),"data-testid":`build-new-helper`,children:[o(_,{className:`h-4 w-4`}),` `,t(`helper.newHelper`)]})]}):e(G,{type:`button`,onClick:S,"data-testid":`build-new`,children:[o(_,{className:`h-4 w-4`}),` `,E]}),sections:[{id:`automations`,label:gc(t(`build.tabAutomations`,`Automations`),f),ownedParams:pc,content:o(Ta,{onOpenScripts:y,initialBlockId:s===`automations`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`automations`&&c,onCreateConsumed:T})},{id:`actions`,label:gc(t(`build.tabActions`,`Actions`),m),ownedParams:pc,content:o(Vr,{createRequested:s===`actions`&&c,onCreateConsumed:T})},{id:`scripts`,label:gc(t(`build.tabCode`,`Code`),d),ownedParams:pc,content:o(cc,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:x,createRequested:s===`scripts`&&c,onCreateConsumed:T})},{id:`custom-device`,label:gc(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:pc,content:o(Qa,{createRequested:s===`custom-device`&&c,onCreateConsumed:T})}]})}export{_c as BuildPage};