@camstack/addon-admin-ui 1.2.522 → 1.2.524

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 (153) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/assets/{AddonAssetIcon-DIfNr6QF.js → AddonAssetIcon-CYhJlTNc.js} +1 -1
  3. package/dist/assets/Addons-BRZelwav.js +5 -0
  4. package/dist/assets/{AdminPage-DPm4iuSn.js → AdminPage-B1Q3Lunl.js} +1 -1
  5. package/dist/assets/{AdminSectionedPage-ePUwCKQL.js → AdminSectionedPage-CDZfKkL5.js} +1 -1
  6. package/dist/assets/AiProfiles-DC8OxOmV.js +3 -0
  7. package/dist/assets/BrokerEditorDialog-BX5w7CMy.js +1 -0
  8. package/dist/assets/Build-BVaH843t.js +40 -0
  9. package/dist/assets/{Calendars-C4XQpa_i.js → Calendars-q3MUFOBU.js} +1 -1
  10. package/dist/assets/Cluster-BKvY1r-a.js +1 -0
  11. package/dist/assets/ComposedDeviceEditDialog-BLfm22uf.js +1 -0
  12. package/dist/assets/CompositionBlockEditor-CJhCzXua.js +2 -0
  13. package/dist/assets/{CompositionEditorPage-ofTerclJ.js → CompositionEditorPage-dOMxAK9V.js} +1 -1
  14. package/dist/assets/Data-BVPL4yIo.js +2 -0
  15. package/dist/assets/DeviceDetail-BO5_O1mV.js +2 -0
  16. package/dist/assets/{DeviceDoActionFields-CV-_oMrw.js → DeviceDoActionFields-B50ODgPq.js} +1 -1
  17. package/dist/assets/{Devices-N1YkeiNQ.js → Devices-CrdlW5-A.js} +1 -1
  18. package/dist/assets/{EmbedPlayerPage-BCAMYXmH.js → EmbedPlayerPage-JBC0G-2I.js} +1 -1
  19. package/dist/assets/History-BP1mlcwA.js +1 -0
  20. package/dist/assets/Identity-CY_zYbdN.js +1 -0
  21. package/dist/assets/IntegrationDetail-DCjuDqWm.js +1 -0
  22. package/dist/assets/IntegrationHub-DE2mwBdj.js +1 -0
  23. package/dist/assets/Integrations-BmHL7d-i.js +1 -0
  24. package/dist/assets/Integrations-CKAi9srg.js +1 -0
  25. package/dist/assets/{Library-Fjdy5AxG.js → Library-BrWQ54N7.js} +1 -1
  26. package/dist/assets/Locations-3qWlGxP3.js +3 -0
  27. package/dist/assets/{Logs-BD6TfZBm.js → Logs-DYi_B3vg.js} +1 -1
  28. package/dist/assets/{MaskShapeCanvas-Bv7J_UVF.js → MaskShapeCanvas-D8Ke0Dim.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-BZxXQ1bq.js → MotionZonesSettings--YqW3Onz.js} +1 -1
  30. package/dist/assets/MyAccess-DswPvXxB.js +2 -0
  31. package/dist/assets/Network-ChYmByS2.js +1 -0
  32. package/dist/assets/{NodeAddonsSettingsPanel-CE1Jh62u.js → NodeAddonsSettingsPanel-DtvhgNC4.js} +1 -1
  33. package/dist/assets/Notifications-5onsUC_w.js +1 -0
  34. package/dist/assets/Pipeline-CgmB5Be8.js +1 -0
  35. package/dist/assets/{PrivacyMaskSettings-Bic1_gT9.js → PrivacyMaskSettings-B-vpuYKA.js} +1 -1
  36. package/dist/assets/Recordings-Bglrn4rQ.js +1 -0
  37. package/dist/assets/RemoteGrid-C_9BszV-.js +1 -0
  38. package/dist/assets/{ScanNetworkModal-CZGf5C-T.js → ScanNetworkModal-BnhOMFd1.js} +1 -1
  39. package/dist/assets/{SceneMonitorEditor-Bd7aOOIg.js → SceneMonitorEditor-CkaBEtmE.js} +1 -1
  40. package/dist/assets/SessionsList--FQem8XB.js +2 -0
  41. package/dist/assets/{Showroom-DqFW96-i.js → Showroom-B9J1IdLQ.js} +1 -1
  42. package/dist/assets/{System-DTyumt9L.js → System-BVE97mrs.js} +1 -1
  43. package/dist/assets/Templates-CvoAkIdF.js +1 -0
  44. package/dist/assets/{Terminal-DIjGMS_3.js → Terminal-ieNh6d83.js} +5 -5
  45. package/dist/assets/{Viewer-B92j2D9F.js → Viewer-CAf7sAU0.js} +1 -1
  46. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DugEb7xj.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bi1zqe4S.js} +1 -1
  47. package/dist/assets/{addon-icons-context-CDyNgrka.js → addon-icons-context-RPiI9H0L.js} +1 -1
  48. package/dist/assets/{archive-BKuD6-O9.js → archive-DQvuyIac.js} +1 -1
  49. package/dist/assets/{assignment-candidates-DRst7VCd.js → assignment-candidates-83kFfE1Z.js} +1 -1
  50. package/dist/assets/{authed-media-DxWmG5JA.js → authed-media-BSoR_xYF.js} +1 -1
  51. package/dist/assets/{bell-off-7L6K5pJk.js → bell-off-C3u183tq.js} +1 -1
  52. package/dist/assets/{board-model-C9BgTio0.js → board-model-sARab1AV.js} +1 -1
  53. package/dist/assets/{boxes-BYgmIZEw.js → boxes-CVkAEP7e.js} +1 -1
  54. package/dist/assets/circle-slash-C86XHeiD.js +1 -0
  55. package/dist/assets/client-DcvpIFoh.js +674 -0
  56. package/dist/assets/{cloud-upload-C40Dp7qu.js → cloud-upload-CHQjI4ZF.js} +1 -1
  57. package/dist/assets/crop-Ct8elLRy.js +1 -0
  58. package/dist/assets/{device-integration-icon-4rilmB_4.js → device-integration-icon-DCuiIOlj.js} +1 -1
  59. package/dist/assets/device-picker-model-BvJkcx-a.js +1 -0
  60. package/dist/assets/{dist-CJ9iy42m.js → dist-B5lzpDFY.js} +1 -1
  61. package/dist/assets/dist-BSrNHoV1.js +674 -0
  62. package/dist/assets/{file-up-DhY5nof7.js → file-up-C9_pj2VT.js} +1 -1
  63. package/dist/assets/{format-BccZ2tds.js → format-DGQA45Ye.js} +1 -1
  64. package/dist/assets/grip-vertical-C_VoFjYu.js +1 -0
  65. package/dist/assets/{hard-drive-download-gFidUJGC.js → hard-drive-download-DiC0khcq.js} +1 -1
  66. package/dist/assets/{hostInit-CDWllEW4.js → hostInit-Dq6hIrVo.js} +1 -1
  67. package/dist/assets/{i18n-COiZcYwm.js → i18n-C-H4BlYV.js} +1 -1
  68. package/dist/assets/icons-C7pfBl-Q.js +1 -0
  69. package/dist/assets/index-DjwiZ7qT.css +2 -0
  70. package/dist/assets/index-o6kBNilE.js +4 -0
  71. package/dist/assets/{key-CKmpBvKe.js → key-Cz6uvkUc.js} +1 -1
  72. package/dist/assets/{key-round-DMWVlifP.js → key-round-B9WTP907.js} +1 -1
  73. package/dist/assets/{layers-Bo1tC_4O.js → layers-DGMlfnn4.js} +1 -1
  74. package/dist/assets/{linked-devices-model-BGb4eOlL.js → linked-devices-model-D6PgoQtW.js} +1 -1
  75. package/dist/assets/{list-ordered-BAebxGoz.js → list-ordered-wHEw5a_e.js} +1 -1
  76. package/dist/assets/location-owned-usage-B-4MuD-Z.js +1 -0
  77. package/dist/assets/{log-in-CUgGOn9k.js → log-in-Da7IGp_j.js} +1 -1
  78. package/dist/assets/{memory-stick-CsWM7ppk.js → memory-stick-BLbgKSl7.js} +1 -1
  79. package/dist/assets/{message-square-plus-C-LDprie.js → message-square-plus-CMdSHNUk.js} +1 -1
  80. package/dist/assets/{mf-entry-bootstrap-0-2a2a5e72.js → mf-entry-bootstrap-0-e016a0f6.js} +2 -2
  81. package/dist/assets/{mic-off-BmNdC4XW.js → mic-off-CIzR-elk.js} +1 -1
  82. package/dist/assets/{monitor-off-DhTBAYUp.js → monitor-off-lToaeJ-K.js} +1 -1
  83. package/dist/assets/{monitor-smartphone-6kCGO3r1.js → monitor-smartphone-Dr1ELple.js} +1 -1
  84. package/dist/assets/mount-BvJkcx-a.js +1 -0
  85. package/dist/assets/{player-overlays-C_WpL6a6.js → player-overlays-oTS1TZZY.js} +1 -1
  86. package/dist/assets/{recycle-Di1EQ0Qy.js → recycle-BNUPyJ7u.js} +1 -1
  87. package/dist/assets/remoteEntry-BK4ei3jy.js +1 -0
  88. package/dist/assets/{ruler-cSAzAdF0.js → ruler-CvDT4Z7Y.js} +1 -1
  89. package/dist/assets/{scan-eye-6vO-dwZC.js → scan-eye-BhxGMB3E.js} +1 -1
  90. package/dist/assets/{scissors-MIPuZwTY.js → scissors-C-pdrglA.js} +1 -1
  91. package/dist/assets/{search-x-Jgy5Olce.js → search-x-wBrdZZXu.js} +1 -1
  92. package/dist/assets/{send-CnArxdfm.js → send-D5hwnH6i.js} +1 -1
  93. package/dist/assets/{settings-2-Cc7_8hT4.js → settings-2-D64sFGFI.js} +1 -1
  94. package/dist/assets/{shapes-B6yDXStU.js → shapes-HTfCvSL2.js} +1 -1
  95. package/dist/assets/{sigma-q5eaqxJ5.js → sigma-BYdS13dc.js} +1 -1
  96. package/dist/assets/{speaker-CbeO5md6.js → speaker-DCCyafUF.js} +1 -1
  97. package/dist/assets/src-XEHc18wE.js +67 -0
  98. package/dist/assets/{step-inspector-model-CNx3I9Xq.js → step-inspector-model-a05i0m0c.js} +1 -1
  99. package/dist/assets/{table-2-Dl4UBoV9.js → table-2-BgDon14h.js} +1 -1
  100. package/dist/assets/{timer-reset-Bp1VJ4jU.js → timer-reset-Dst_i1Qg.js} +1 -1
  101. package/dist/assets/{unlink-DoHrrlyB.js → unlink-CmmNdYky.js} +1 -1
  102. package/dist/assets/{usb-uGk5FuUX.js → usb-BCFcIAg4.js} +1 -1
  103. package/dist/assets/{use-device-bound-caps-Di0CbhM4.js → use-device-bound-caps-CI6zlnII.js} +1 -1
  104. package/dist/assets/{use-scenes-feed-hWCFwCtN.js → use-scenes-feed-junBfGeR.js} +1 -1
  105. package/dist/assets/{use-stationary-objects-DJ9JfRWk.js → use-stationary-objects-blP9Y5SS.js} +1 -1
  106. package/dist/assets/useEventInvalidation-BvJkcx-a.js +1 -0
  107. package/dist/assets/{useNodeUrlSelection-DdAqNTrP.js → useNodeUrlSelection-Cb470tqR.js} +1 -1
  108. package/dist/assets/user-round-D3ZUZuP3.js +1 -0
  109. package/dist/assets/{user-x-KqDnAcpq.js → user-x-891p2Gny.js} +1 -1
  110. package/dist/assets/{variable-vSgKlDpd.js → variable-HM7A54CP.js} +1 -1
  111. package/dist/assets/{video-DgFhEP51.js → video-Dx3E7zlj.js} +1 -1
  112. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CmMSAYDD.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DHe9cBRl.js} +2 -2
  113. package/dist/index.html +10 -10
  114. package/dist/server/addon.js +323 -4
  115. package/package.json +1 -1
  116. package/dist/assets/Addons-BMftFNTU.js +0 -5
  117. package/dist/assets/AiProfiles-CACYaJ0b.js +0 -3
  118. package/dist/assets/BrokerEditorDialog-CUIedISr.js +0 -1
  119. package/dist/assets/Build-CDoXaCVA.js +0 -40
  120. package/dist/assets/Cluster-DBLF--XA.js +0 -1
  121. package/dist/assets/ComposedDeviceEditDialog-ck2hidMF.js +0 -1
  122. package/dist/assets/CompositionBlockEditor-HRq0m67C.js +0 -2
  123. package/dist/assets/Data-C9r_81YQ.js +0 -2
  124. package/dist/assets/DeviceDetail-K5apsJzR.js +0 -2
  125. package/dist/assets/History-C0dKdfBD.js +0 -1
  126. package/dist/assets/Identity--_TOjAWM.js +0 -1
  127. package/dist/assets/IntegrationDetail-DxggdnLq.js +0 -1
  128. package/dist/assets/IntegrationHub-DkYLz05p.js +0 -1
  129. package/dist/assets/Integrations-ABu-h5-i.js +0 -1
  130. package/dist/assets/Integrations-DaHd5Vd8.js +0 -1
  131. package/dist/assets/Locations-GGj9C5iu.js +0 -3
  132. package/dist/assets/MyAccess-SIQg6S5M.js +0 -2
  133. package/dist/assets/Network-BodjnB-l.js +0 -1
  134. package/dist/assets/Notifications-BuPf6osG.js +0 -1
  135. package/dist/assets/Pipeline-7z4wW50e.js +0 -1
  136. package/dist/assets/Recordings-BigRN2P0.js +0 -1
  137. package/dist/assets/RemoteGrid-BI5deYM9.js +0 -1
  138. package/dist/assets/SessionsList-BDOJmeXy.js +0 -2
  139. package/dist/assets/Templates-dAk_L8cs.js +0 -1
  140. package/dist/assets/circle-slash-DSfcxndq.js +0 -1
  141. package/dist/assets/client-Clemlz5W.js +0 -674
  142. package/dist/assets/crop-CnSchINM.js +0 -1
  143. package/dist/assets/device-picker-model-ojy8FewR.js +0 -1
  144. package/dist/assets/dist-B-uSoSKi.js +0 -674
  145. package/dist/assets/icons-DrXFX-WI.js +0 -1
  146. package/dist/assets/index-B0SLrMzs.js +0 -4
  147. package/dist/assets/index-DnHMM2c9.css +0 -2
  148. package/dist/assets/location-owned-usage-Bmczv2-v.js +0 -1
  149. package/dist/assets/mount-ojy8FewR.js +0 -1
  150. package/dist/assets/remoteEntry-B3Z2iNH7.js +0 -1
  151. package/dist/assets/src-BuD4BDe3.js +0 -67
  152. package/dist/assets/useEventInvalidation-ojy8FewR.js +0 -1
  153. package/dist/assets/user-round-BdixCoAv.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,Pi as _,Pn as v,Pr as y,Q as b,Ri as x,Vn as S,Zr as C,_n as w,dt as T,fr as E,gt as D,oi as O,ra as k,ri as A,rn as j,st as M,tn as N,vn as P,zi as F}from"./player-overlays-C_WpL6a6.js";import{Qr as I,Xr as L,Zr as R,ko as z}from"./client-Clemlz5W.js";import{n as B,t as ee}from"./send-CnArxdfm.js";import{t as te}from"./message-square-plus-C-LDprie.js";import{Ar as V,Br as H,Ct as U,Dn as W,Ed as ne,Md as re,Mo as G,Mr as ie,Nr as K,On as q,St as ae,Tn as J,Yn as oe,at as se,ci as Y,dr as ce,ei as X,gt as le,jd as ue,jr as de,mt as fe,qn as pe,rr as me}from"./src-BuD4BDe3.js";import{t as Z}from"./i18n-COiZcYwm.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-ojy8FewR.js";import{T as he,yr as ge}from"./index-B0SLrMzs.js";import{t as _e}from"./AdminSectionedPage-ePUwCKQL.js";import{t as ve}from"./AdminPage-DPm4iuSn.js";c();var ye=`__redacted__`,be=[`llm`,`listProfiles`],xe=[`llm`,`listProfileKinds`],Se=[`llm`,`getDefaults`],Ce=[`llm`,`listRuntimeNodes`],we=[`llm`,`listModelCatalog`],Te=[`llm`,`getUsage`],Ee=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],De=new Map([[`cloud`,O],[`plug`,v],[`cpu`,A],[`server`,w],[`sparkles`,j]]);function Oe(e){return De.get(e)??F}function ke(e){return typeof e==`string`&&e.length>0?e:void 0}function Ae(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 je(e){return e===!0}function Me(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 Ne={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 Pe(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=Ne[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 Fe={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`},Ie={ready:`ai.stateReady`,downloading:`ai.stateDownloading`,starting:`ai.stateStarting`,stopped:`ai.stateStopped`,crashed:`ai.stateCrashed`,failed:`ai.stateFailed`};function Le(e){return e.reachable?e.status===void 0?`ai.stateReady`:Ie[e.status.state]:`ai.unreachable`}function Re(e){return e.reachable?e.status===void 0?`success`:Fe[e.status.state]:`danger`}function ze(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Pe(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Pe(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}var Be=`default`;function Ve(e){let t=L.shape.reasoningEffort.safeParse(e);return t.success?t.data:void 0}function He(){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}],reasoningEffort:[{type:`select`,key:`reasoningEffort`,label:Z.t(`helpers.aiProfileForm.reasoningEffort`),default:Be,options:[{value:Be,label:Z.t(`helpers.aiProfileForm.reasoningDefault`)},{value:`off`,label:Z.t(`helpers.aiProfileForm.reasoningOff`)},{value:`low`,label:Z.t(`helpers.aiProfileForm.reasoningLow`)},{value:`medium`,label:Z.t(`helpers.aiProfileForm.reasoningMedium`)},{value:`high`,label:Z.t(`helpers.aiProfileForm.reasoningHigh`)}],description:Z.t(`helpers.aiProfileForm.reasoningEffortHint`)}],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:I.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:I.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:I.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:I.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 Ue=[`temperature`,`topP`,`topK`,`maxTokens`,`reasoningEffort`,`contextLength`,`systemPrompt`],We=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function Ge(e,t){let n=He();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Ke(e){let t=Ge(e,Ue);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function qe(e){let t=Ge(e,We);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function Je(e){return e===null?{}:{temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,reasoningEffort:e.reasoningEffort??Be,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 Ye(e,t){return{...e.features,...t?.features}}function Xe(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ze(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?Ae(i[e])??t:n??t,o=e=>r.includes(e)?Ae(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`reasoningEffort`)?Ve(i.reasoningEffort):t?.reasoningEffort,p=r.includes(`systemPrompt`)?ke(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`,I.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,I.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,I.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,I.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:je(i.retryEnabled),maxAttempts:Ae(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?je(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},...f===void 0?{}:{reasoningEffort:f},...d===void 0?{}:{contextLength:d},...p===void 0?{}:{systemPrompt:p},providerConfig:n.providerConfig}}var Qe=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function $e(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function et({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=T(),[d,f]=o(``),[p,m]=o(null),[h,g]=o(!1),_=s({queryKey:we,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:Ce,enabled:b.isPending,refetchInterval:b.isPending?Qe:!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]),w=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})},D=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(U,{label:c(`ai.model`,`Model`),required:!0,children:i(ne,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:$e(r),options:S,onChange:e=>w(e.target.value)})}),i(U,{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(ue,{"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(),D())}}),e(X,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>D(),children:[y.isPending?i(E,{className:`h-3.5 w-3.5 animate-spin`}):i(P,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),y.isError&&i(V,{message:y.error instanceof Error?y.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(V,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(X,{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(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>D(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(Y,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(Y,{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(X,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?i(E,{className:`h-3.5 w-3.5 animate-spin`}):i(C,{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(V,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)})]})]})}function tt({value:t,onChange:n}){let{t:r}=Q(),a=T(),o=s({queryKey:Ce,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(E,{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=Pe(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(Y,{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 nt(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function rt({providerConfig:e,onProviderConfigChange:t}){return i(tt,{value:nt(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function it({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=R.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(et,{nodeId:nt(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 at=new Map([[`ai/apple-node`,rt],[`ai/managed-model`,it]]);function ot(e){return at.get(e)??null}c();function st({kind:e,className:t}){return i(Oe(e.icon),{className:t,"aria-hidden":!0})}function ct({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>Me(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(le,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(ae,{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(st,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function lt(e){return(e?.sections??[]).flatMap(e=>e.fields)}function ut(...e){let t={};for(let n of e)for(let e of lt(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function dt(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function ft(e,t){return lt(e).filter(e=>`required`in e&&e.required===!0&&!dt(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var pt={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 mt(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:Ye(e,n).vision}}function ht({kind:t,existing:r,onSave:s,onCancel:c,onChangeKind:p,saving:m,error:h}){let{t:_}=Q(),v=T(),[y,b]=o(r?.name??t.label),[x,S]=o(()=>r===null?ut(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[C,w]=o(()=>Je(r)),[D,O]=o(()=>mt(t,r)),[A,j]=o(!1),M=t.providerWidgets??[],N=M.filter(e=>e.placement===`connection`),P=M.find(e=>e.placement===`model`)??null,F=n(()=>[...z(t.connectionSchema)].some(e=>r?.providerConfig[e]===ye),[r,t.connectionSchema]),I=l({mutationFn:()=>v.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:x,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&O(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ye(t,r).vision}})}}),L=Xe(t,I.data?.ok===!0?I.data.models:null),R=L.find(e=>e.id===D.id),B=Ye(t,R),ee=Ke(t.profileFields),te=qe(t.profileFields),H=ft(t.connectionSchema,x),W=M.some(e=>(e.requires??[]).some(e=>!dt(x[e]))),re=t.modelCatalog===`fetch`&&P===null,G=lt(t.connectionSchema).length>0||N.length>0,ie=r!==null&&re&&H.length===0;a(()=>{ie&&I.mutate()},[]);let K=e=>{O({id:e,supportsVision:Ye(t,L.find(t=>t.id===e)).vision})},q=m||y.trim()===``||D.id.trim()===``||H.length>0||W,ae=()=>{s(Ze(t,r,{name:y.trim(),model:D.id.trim(),supportsVision:t.visionEditable?D.supportsVision:!1,common:C,providerConfig:x}))},oe=r===null?_(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):_(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),se=e=>{let n=ot(e);return n===null?i(V,{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:D,onModelChange:O},e)};return i(le,{open:!0,onClose:c,title:oe,error:h,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[H.length>0&&i(Y,{variant:`warning`,children:_(`ai.missingRequired`,`required: {{fields}}`,{fields:H.join(`, `)})}),H.length===0&&W&&i(Y,{variant:`warning`,children:_(`ai.completeProvider`,`complete the provider settings`)}),H.length===0&&!W&&D.id.trim()===``&&i(Y,{variant:`warning`,children:_(`ai.pickModelFirst`,`pick a model`)}),e(X,{size:`sm`,type:`button`,disabled:q,onClick:ae,children:[m&&i(E,{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(st,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(Y,{variant:`neutral`,children:t.addonId}),p!==void 0&&e(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:p,children:[i(k,{className:`h-3.5 w-3.5`}),_(`ai.changeKind`,`Change type`)]})]}),i(U,{label:_(`ai.name`,`Name`),required:!0,children:i(ue,{id:`ai-profile-name`,"aria-label":_(`ai.name`,`Name`),value:y,onChange:e=>b(e.target.value),placeholder:t.label})}),G&&i(J,{headingId:`ai-editor-connection`,title:_(`ai.sectionConnection`,`Connection`),actions:re?e(X,{size:`sm`,variant:`secondary`,type:`button`,disabled:I.isPending,onClick:()=>I.mutate(),"data-testid":`ai-verify-models`,children:[I.isPending?i(E,{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:[lt(t.connectionSchema).length>0&&i(ce,{bare:!0,schema:t.connectionSchema,values:x,onChange:S}),N.map(e=>se(e.id)),F&&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.`)}),I.data?.ok===!0&&i(Y,{variant:`success`,"data-testid":`ai-models-found`,children:_(`ai.modelsFound`,`{{count}} models found`,{count:I.data.models.length})}),I.data?.ok===!1&&i(V,{title:_(pt[I.data.code]?.key??`ai.listNetwork`,pt[I.data.code]?.fallback??`Endpoint unreachable`),message:I.data.message}),I.isError&&i(V,{message:I.error instanceof Error?I.error.message:_(`common.error`,`Error`)})]})}),i(J,{headingId:`ai-editor-model`,title:_(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${d} space-y-3`,children:[P===null?e(u,{children:[L.length>0&&i(ne,{id:`ai-model-pick`,"aria-label":_(`ai.selectModel`,`Select a model…`),value:R===void 0?``:R.id,options:[{value:``,label:_(`ai.selectModel`,`Select a model…`)},...L.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&K(e.target.value)}}),i(U,{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(ue,{id:`ai-model-id`,"aria-label":_(`ai.customModel`,`Model id`),value:D.id,onChange:e=>{let n=L.find(t=>t.id===e.target.value);O(n===void 0?{...D,id:e.target.value}:{id:e.target.value,supportsVision:Ye(t,n).vision})},placeholder:L[0]?.id??`model-id`})})]}):se(P.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(D.supportsVision||!t.visionEditable&&B.vision)&&i(Y,{variant:`info`,children:_(`ai.featureVision`,`vision`)}),B.tools&&i(Y,{variant:`neutral`,children:_(`ai.featureTools`,`tools`)}),B.streaming&&i(Y,{variant:`neutral`,children:_(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(U,{orientation:`horizontal`,label:_(`ai.supportsVision`,`Supports vision`),description:_(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(pe,{checked:D.supportsVision,onCheckedChange:e=>O({...D,supportsVision:e}),"aria-label":_(`ai.supportsVision`,`Supports vision`)})})]})}),ee!==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(ce,{bare:!0,schema:ee,values:C,onChange:w})})}),(te!==null||t.advancedSchema!==void 0)&&i(me,{expanded:A,onExpandedChange:j,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:[te!==null&&i(ce,{bare:!0,schema:te,values:C,onChange:w}),t.advancedSchema!==void 0&&i(ce,{bare:!0,schema:t.advancedSchema,values:x,onChange:S})]})})]})})}c();function gt(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(st,{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(Y,{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(Y,{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(pe,{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(X,{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(E,{className:`h-3.5 w-3.5 animate-spin`}):i(ee,{className:`h-3.5 w-3.5`})}),i(X,{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(S,{className:`h-3.5 w-3.5`})}),i(X,{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 _t(){let{t}=Q(),c=T(),{state:u,openEdit:f,close:p}=fe(),m=M(),[h,_]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:be,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),C=s({queryKey:xe,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()},E=r(()=>{_(null),x(null),p()},[p]);a(()=>{u.mode===`closed`&&_(null)},[u.mode]);let D=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{E(),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}),k=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}`})}),A=S.data??[],N=n(()=>C.data??[],[C.data]),P=n(()=>{let e=new Map;for(let t of N)e.set(t.kind,t);return e},[N]),F=u.mode===`edit`?A.find(e=>e.id===u.id)??null:null,I=F===null?null:P.get(F.kind)??null,L=u.mode===`new`&&h===null,R=u.mode===`new`?h:I,z=u.mode===`edit`?F:null,B=R!==null&&(u.mode===`new`||z!==null),ee=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(vt,{profiles:A}),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(K,{className:`h-8 w-full`}),i(K,{className:`h-8 w-full`}),i(K,{className:`h-8 w-full`})]}):S.isError?i(`div`,{className:d,children:i(V,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:t(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):A.length===0?i(de,{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(W,{columns:gt({kindByName:P,testResult:v,testingId:k.isPending?k.variables?.id??null:null,t,onToggle:e=>D.mutate({...e,enabled:!e.enabled}),onTest:e=>k.mutate(e),onEdit:e=>{P.has(e.kind)&&(x(null),_(null),f(e.id))},onDelete:e=>void ee(e)}),rows:A,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:q})}),L&&i(ct,{kinds:N,onCancel:E,onPick:e=>{x(null),_(e)}}),B&&R!==null&&i(ht,{kind:R,existing:z,saving:D.isPending,error:b,onSave:e=>D.mutate(e),onCancel:E,...u.mode===`new`?{onChangeKind:()=>{x(null),_(null)}}:{}})]})}function vt({profiles:t}){let{t:n}=Q(),r=T(),a=s({queryKey:Se,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:Ee.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(oe,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(ne,{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 yt=5e3;function bt(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function xt(){let{t}=Q(),r=T(),a=s({queryKey:Ce,refetchInterval:yt,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(Y,{variant:Re(n),children:t(Le(n))}),n.status?.downloadProgress!==void 0&&i(Y,{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?`—`:bt(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeature`,`Feature`),render:n=>{let r=ze(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(Y,{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(K,{className:`h-8 w-full`}),i(K,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:d,children:i(V,{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(de,{icon:w,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(W,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:q})})}var St=b(`/addon/ai/test-chat`),Ct=b(`/addon/ai/test-chat/chats`),wt=6e5;function Tt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),wt)}function Et(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dt(e){if(!Et(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 Ot=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function kt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Et(t))return null;switch(t.kind){case`status`:{let e=Ot.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:Dt(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*At(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=kt(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=kt(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function jt(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Mt(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Nt(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 Pt(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 Ft(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 It=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],Lt=360*60*1e3,Rt=40,zt=160,Bt={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Vt(){let{t:c}=Q(),l=T(),[u,f]=o(``),[p,m]=o(``),[v,y]=o(``),[b,S]=o([]),[C,w]=o(null),[E,O]=o(`none`),[k,A]=o(`throwaway`),[j,M]=o(null),[P,F]=o([]),[I,L]=o(null),[R,z]=o(null),B=t(null);a(()=>()=>B.current?.abort(),[]);let H=r(async()=>{let e=await fetch(Ct,{credentials:`same-origin`});e.ok&&F((await e.json()).chats??[])},[]);a(()=>{k===`persistent`&&H()},[k,H]);let U=s({queryKey:be,queryFn:()=>l.trpcClient.llm.listProfiles.query({})}),W=n(()=>(U.data??[]).filter(e=>e.enabled),[U.data]),G=W.find(e=>e.id===u)??null,ie=R!==null,K=r(async(e,t)=>{let n=new AbortController;B.current=n,L(null);let r=Tt(G??{});z({...Bt,firstTokenTimeoutMs:r??0});let i=``,a=null,o,s=null,l=null,d;try{let c=await fetch(St,{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},...k===`persistent`?{persist:!0,...j===null?{}:{conversationId:j}}:{}})});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 At(c.body))switch(e.kind){case`status`:z(t=>({...t??Bt,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,z(t=>({...t??Bt,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,z(e=>({...e??Bt,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||L(e instanceof Error?e.message:c(`common.error`,`Error`))}finally{B.current=null,z(null)}d!==void 0&&(M(d),H());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}])},[k,j,G,u,H,p,c]),q=r(()=>{let e=v.trim();if(e===``||u===``||ie)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...C===null?{}:{attachmentLabel:C.label,attachmentKind:C.ref.kind}},n=[...b,t];S(n),y(``);let r=C?.ref;w(null),O(`none`),K(k===`persistent`&&j!==null?[{role:`user`,content:e}]:jt(n),r)},[k,j,v,C,u,K,ie,b]),ae=()=>B.current?.abort(),Y=()=>{B.current?.abort(),S([]),w(null),y(``),L(null),z(null),M(null)},ce=async e=>{B.current?.abort();let t=await fetch(`${Ct}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();M(e),S(Nt(n)),z(null),L(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(oe,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:c(`ai.profile`,`Profile`)}),i(ne,{id:`ai-test-profile`,value:u,onChange:e=>f(e.target.value),options:[{value:``,label:c(`ai.selectProfile`,`Select a profile…`)},...W.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),W.length===0&&!U.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(oe,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:c(`ai.systemPrompt`,`System prompt (optional)`)}),i(ue,{id:`ai-test-system`,value:p,onChange:e=>m(e.target.value),placeholder:c(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(se,{label:c(`ai.chatMode`,`Conversation mode`),value:k,options:[{value:`throwaway`,label:c(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:c(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{A(e),e===`throwaway`&&M(null)}}),k===`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(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:Y,children:[i(te,{className:`h-3.5 w-3.5`}),c(`ai.newChat`,`New chat`)]}),P.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:P.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===j?`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.`)}),G!==null&&!G.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.`)})]})}),I!==null&&i(V,{title:c(`ai.chatFailed`,`The test call failed`),message:I}),e(J,{headingId:`ai-test-conversation`,title:c(`ai.testConversation`,`Conversation`),actions:e(X,{size:`sm`,variant:`ghost`,type:`button`,disabled:b.length===0&&C===null,onClick:Y,children:[i(h,{className:`h-3.5 w-3.5`}),c(`ai.clearChat`,`Clear`)]}),children:[i(Ht,{turns:b,live:R}),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(_,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(x,{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(re,{size:`sm`,variant:`ghost`,type:`button`,icon:D,"aria-label":c(`ai.removeAttachment`,`Remove attachment`),onClick:()=>w(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{size:`sm`,variant:E===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>O(E===`snapshot`?`none`:`snapshot`),children:[i(_,{className:`h-3.5 w-3.5`}),c(`ai.attachSnapshot`,`Camera snapshot`)]}),e(X,{size:`sm`,variant:E===`track`?`primary`:`outline`,type:`button`,onClick:()=>O(E===`track`?`none`:`track`),children:[i(x,{className:`h-3.5 w-3.5`}),c(`ai.attachTrack`,`Recent track`)]})]}),E===`snapshot`&&i(Gt,{onPick:(e,t)=>{w({ref:{kind:`snapshot`,deviceId:e.id},label:c(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t})}),O(`none`)}}),E===`track`&&i(qt,{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})}),O(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(ue,{value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),q())},placeholder:c(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":c(`ai.message`,`Message`)}),ie?e(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:ae,children:[i(N,{className:`h-3.5 w-3.5`}),c(`ai.stop`,`Stop`)]}):e(X,{size:`sm`,type:`button`,disabled:v.trim()===``||u===``,onClick:q,children:[i(ee,{className:`h-3.5 w-3.5`}),c(`ai.send`,`Send`)]})]})]})]})]})}function Ht({turns:t,live:n}){let{t:r}=Q();return t.length===0&&n===null?i(de,{icon:B,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(Ut,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(Wt,{attachment:n.mediaSent}),n.text.length>0&&i(Ut,{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(E,{className:`h-3.5 w-3.5 animate-spin`}),Ft(n.phase,n.firstTokenTimeoutMs)]})]})]})}function Ut({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(Wt,{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(x,{className:`h-3 w-3`}):i(_,{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(_,{className:`h-3 w-3`}):i(x,{className:`h-3 w-3`}),Pt(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 Wt({attachment:e}){let{t}=Q(),n=Mt(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 Gt({onPick:e}){let{t}=Q(),n=G({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(E,{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(Kt,{device:t,onPick:e},t.id))})}function Kt({device:t,onPick:n}){let{t:r}=Q(),a=H(t,`compact`),{src:o}=m(t.id,{width:zt});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(Y,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function qt({onPick:t}){let{t:r}=Q(),a=T(),o=G({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:[...It,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-Lt,limit:Rt,projection:`slim`})});if(o.isLoading||u.isLoading)return i(E,{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(x,{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 Jt=1440*60*1e3,Yt=[1,7,30,90];function Xt(){let{t}=Q(),r=T(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*Jt},[a]),u=s({queryKey:be,queryFn:()=>r.trpcClient.llm.listProfiles.query({})}),f=s({queryKey:[...Te,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(ne,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:Yt.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(K,{className:`h-8 w-full`}),i(K,{className:`h-8 w-full`}),i(K,{className:`h-8 w-full`})]}):f.isError?i(`div`,{className:d,children:i(V,{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(de,{icon:y,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(W,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:q})})}var Zt=`llm`,Qt=[`profiles`,`runtimes`,`usage`,`test`],$t=[`new`,`edit`];function en(e){return Qt.some(t=>t===e)}function tn(){let{t}=Q(),n=ie(Zt),[r]=ge(),{openNew:a}=fe(),o=he(`/system/ai`,{t,isAdmin:!0})??{icon:j,title:t(`system.ai`,`AI`)};if(n!==`present`)return i(ve,{icon:o.icon,title:o.title,children:i(nn,{presence:n})});let s=r.get(`tab`),c=en(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(X,{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(_e,{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(_t,{}),ownedParams:$t},{id:`runtimes`,label:t(`ai.tabRuntimes`,`Runtimes`),content:i(xt,{})},{id:`usage`,label:t(`ai.tabUsage`,`Usage`),content:i(Xt,{})},{id:`test`,label:t(`ai.tabTest`,`Test`),content:i(Vt,{})}]})}function nn({presence:t}){let{t:n}=Q();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(K,{className:`h-8 w-64`}),i(K,{className:`h-40 w-full`})]}):t===`unknown`?i(V,{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(de,{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{tn as AiProfilesPage,tn as default};
@@ -1 +0,0 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,et as s,o as c,x as l}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Kr as u,Q as d,fr as f}from"./player-overlays-C_WpL6a6.js";import{So as p}from"./client-Clemlz5W.js";import{t as m}from"./log-in-CUgGOn9k.js";import{Aa as h,Ar as g,Ea as _,Fa as v,Na as y,Sr as b,Ta as x,_r as S,ei as C,gr as w,ka as T,pr as E,vr as D,wa as O,xr as k,yr as A}from"./src-BuD4BDe3.js";import{t as j}from"./i18n-COiZcYwm.js";import{t as M}from"./useTranslation-BJr-n0es.js";import"./mount-ojy8FewR.js";import{L as ee,g as te,pr as N}from"./index-B0SLrMzs.js";s();function P(e,t){let n=e=>e.map(e=>e.type===`group`?{...e,fields:n(e.fields)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:n(e.fields)}))}:e.type===`info`&&typeof e.content==`string`?{...e,content:e.content.split(`{{brokerId}}`).join(t)}:e);return{...e,sections:e.sections.map(e=>({...e,fields:n(e.fields)}))}}var F=`broker-advanced`;function I(e){return`key`in e&&typeof e.key==`string`&&`label`in e}function L(e){let t=new Set;for(let n of e){if(!I(n))continue;let e=n.showWhen;if(e===void 0)continue;let r=Array.isArray(e)?e:[e];for(let e of r)typeof e==`object`&&e&&`field`in e&&typeof e.field==`string`&&t.add(e.field)}return t}function ne(e,t,n){return!I(e)||e.showWhen!==void 0||t.has(e.key)?!1:n&&e.filledBySignIn===!0?!0:e.default!==void 0||e.defaultByCountry!==void 0}function re(e,t){let n=[],r=[];for(let i of e.sections){let e=L(i.fields),a=[];for(let r of i.fields)ne(r,e,t.hasSignIn)?n.push(r):a.push(r);if(a.length>0)r.push({...i,fields:a});else if(i.description!==void 0){let{description:e,...t}=i;r.push({...t,fields:[{type:`info`,key:`${i.id}-note`,label:``,content:e}]})}}return n.length>0&&r.push({id:F,title:t.advancedTitle,style:`accordion`,defaultCollapsed:!0,columns:1,fields:n}),{...e,sections:r}}function ie(e){if(e===void 0)return null;let t=/[-_]([A-Za-z]{2})(?:[-_]|$)/.exec(e);return t?.[1]===void 0?null:t[1].toUpperCase()}function ae(e,t,n){if(e===void 0||t===null)return{};let r={};for(let i of e.sections)for(let e of i.fields){if(!I(e)||n[e.key]!==void 0)continue;let i=e.defaultByCountry;i!==void 0&&t in i&&(r[e.key]=i[t])}return r}var oe=[`starting`,`awaiting-login`,`captured`,`error`,`cancelled`];function R(e){return typeof e==`object`&&!!e}function se(e){return R(e)&&typeof e.sessionId==`string`&&typeof e.loginUrl==`string`}function ce(e){return R(e)&&typeof e.sessionId==`string`&&typeof e.phase==`string`&&oe.includes(e.phase)}function le(e){return R(e)&&typeof e.brokerId==`string`}function z(){return{"Content-Type":`application/json`,Authorization:`Bearer ${localStorage.getItem(`camstack_admin_token`)??``}`}}async function B(e,t){try{return await e.json()}catch{throw Error(`${t} failed: HTTP ${e.status}`)}}function V(e){let t=R(e)&&typeof e.error==`string`?e.error:`Unknown error`;return Error(t)}async function H(e,t,n){let r=await fetch(d(e),{method:`POST`,headers:z(),body:JSON.stringify(t)}),i=await B(r,`Sign-in ${e.split(`/`).pop()??`request`}`);if(!r.ok)throw V(i);if(!n(i))throw Error(`Unexpected response from server`);return i}function ue(e,t){return H(`${e}/start`,t,se)}async function de(e,t){let n=new URLSearchParams({sessionId:t}),r=await fetch(d(`${e}/status?${n.toString()}`),{headers:{Authorization:z().Authorization??``}}),i=await B(r,`Sign-in status`);if(!r.ok)throw V(i);if(!ce(i))throw Error(`Unexpected status response from server`);return i}function fe(e,t){return H(`${e}/commit`,{...t},le)}async function pe(e,t){try{await fetch(d(`${e}/cancel`),{method:`POST`,headers:z(),body:JSON.stringify({sessionId:t})})}catch{}}var me=2e3;function he(e){return e.startsWith(`/`)&&!e.startsWith(`//`)?new URL(e,window.location.origin).toString():e}function ge({basePath:n,name:s,brokerId:c,getSettings:d,disabled:p,onSignedIn:h}){let{t:_}=M(),[v,y]=o({kind:`idle`}),b=t(!0),x=t(null),S=t(null),w=r(()=>{S.current!==null&&clearInterval(S.current),S.current=null},[]),T=r(()=>{w();let e=x.current;x.current=null,e!==null&&pe(n,e)},[n,w]);a(()=>(b.current=!0,()=>{b.current=!1,T()}),[T]);let E=r(e=>{w(),b.current&&y({kind:`error`,message:e})},[w]),D=r(async e=>{w(),b.current&&y({kind:`committing`});try{let t=await fe(n,{sessionId:e,name:s,...c===void 0?{}:{brokerId:c}});x.current=null,b.current&&h(t.brokerId)}catch(e){E(e instanceof Error?e.message:String(e))}},[n,c,E,s,h,w]),O=r(e=>{w(),S.current=setInterval(()=>{(async()=>{try{let t=await de(n,e);if(t.phase===`captured`)return void await D(e);if(t.phase===`error`)return E(t.error??_(`brokers.signIn.proxyError`));if(t.phase===`cancelled`){w(),b.current&&y({kind:`idle`});return}b.current&&y({kind:`waiting`,loginUrl:t.loginUrl,ready:t.phase===`awaiting-login`})}catch{}})()},me)},[n,D,E,w,_]),k=async()=>{T(),y({kind:`starting`});try{let e=await ue(n,d());x.current=e.sessionId,y({kind:`waiting`,loginUrl:e.loginUrl,ready:!1}),O(e.sessionId)}catch(e){E(e instanceof Error?e.message:String(e))}};return v.kind===`idle`||v.kind===`error`?e(`div`,{className:`space-y-2`,children:[v.kind===`error`&&i(g,{message:v.message}),i(`p`,{className:`text-xs text-foreground-muted`,children:_(`brokers.signIn.intro`)}),e(C,{variant:`primary`,size:`sm`,disabled:p===!0||s.trim().length===0,onClick:()=>void k(),children:[i(m,{className:`h-3.5 w-3.5`}),` `,v.kind===`error`?_(`common.retry`):_(`brokers.signIn.start`)]})]}):v.kind===`starting`||v.kind===`committing`?e(`div`,{className:`flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-3 text-xs text-foreground-subtle`,children:[i(f,{className:`h-4 w-4 animate-spin flex-shrink-0`}),v.kind===`starting`?_(`brokers.signIn.starting`):_(`brokers.signIn.saving`)]}):e(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:[v.ready?e(l,{children:[i(`p`,{className:`text-xs font-semibold text-foreground`,children:_(`brokers.signIn.openLink`)}),i(`p`,{className:`text-[11px] text-foreground-subtle`,children:_(`brokers.signIn.afterLogin`)}),e(C,{variant:`primary`,size:`sm`,onClick:()=>window.open(he(v.loginUrl),`_blank`,`noopener,noreferrer`),children:[i(u,{className:`h-3.5 w-3.5`}),` `,_(`brokers.signIn.openLoginPage`)]})]}):e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(f,{className:`h-4 w-4 animate-spin flex-shrink-0`}),_(`brokers.signIn.waitingForProxy`)]}),e(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[e(`span`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(f,{className:`h-3 w-3 animate-spin`}),` `,_(`brokers.signIn.waitingForLogin`)]}),i(C,{variant:`outline`,size:`sm`,onClick:()=>{T(),y({kind:`idle`})},children:_(`brokers.signIn.cancel`)})]})]})}s();function U(e,t){if(!e)return t;let n=new Set;for(let r of e.sections){let e=r.fields;for(let r of e)!(`key`in r)||typeof r.key!=`string`||E(r,t,e)&&n.add(r.key)}let r={};for(let[e,i]of Object.entries(t))n.has(e)&&(r[e]=i);return r}function W({kind:t,addonId:r,brokerId:s,initialValues:c,onSubmit:l,onCancel:u,submitLabel:d,disabled:m,signIn:h}){let{t:g}=M(),[y,b]=o(c??{}),[x,S]=o(null),w=_({kind:t,...r===void 0?{}:{addonId:r}}),T=n(()=>{let e=w.data;if(e&&typeof e==`object`&&`sections`in e&&Array.isArray(e.sections)){let t=e;return re(p(s===void 0?t:P(t,s),y),{hasSignIn:h!==void 0,advancedTitle:g(`brokers.brokerForm.advanced`)})}},[w.data,s,y,h!==void 0,g]);a(()=>{c!==void 0&&b(c)},[c]);let E=ie(typeof navigator>`u`?void 0:navigator.language);a(()=>{if(c!==void 0)return;let e=ae(T,E,y);Object.keys(e).length>0&&b(t=>({...e,...t}))},[T,E,c,y]);let D=v(),O=async()=>{S(null);let e=U(T,y);try{let n=await D.mutateAsync({kind:t,settings:e,...r===void 0?{}:{addonId:r}});S(n.ok?{ok:!0}:{ok:!1,error:n.error})}catch(e){S({ok:!1,error:e instanceof Error?e.message:String(e)})}},k=()=>{let{_calendarCatalog:e,...t}=U(T,y);l(t)},A=()=>{let e=new Set;for(let t of T?.sections??[])for(let n of t.fields)I(n)&&n.filledBySignIn===!0&&e.add(n.key);let t=U(T,y);return Object.fromEntries(Object.entries(t).filter(([t])=>!e.has(t)))};return e(`div`,{className:`space-y-3`,children:[h!==void 0&&i(ge,{basePath:h.basePath,name:h.name,...h.brokerId===void 0?{}:{brokerId:h.brokerId},getSettings:A,disabled:m===!0,onSignedIn:h.onSignedIn}),w.isLoading&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(f,{className:`h-3.5 w-3.5 animate-spin`}),` `,g(`brokers.brokerForm.loadingSchema`)]}),T&&i(ee,{schema:T,values:y,onChange:b}),w.isError&&e(`div`,{className:`rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]`,children:[g(`brokers.brokerForm.failedToLoadSettingsSchema`,`Failed to load settings schema:`),` `,w.error instanceof Error?w.error.message:g(`brokers.brokerForm.unknownError`,`Unknown error`)]}),!T&&!w.isLoading&&!w.isError&&i(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:i(N,{i18nKey:`brokers.brokerForm.noSchema`,values:{kind:t},components:{code:i(`code`,{className:`font-mono`})}})}),x&&i(`div`,{className:`rounded border px-3 py-2 text-[11px] ${x.ok?`border-success/30 bg-success/5 text-success`:`border-danger/30 bg-danger/5 text-danger`}`,children:x.ok?g(`brokers.brokerForm.connectionOk`,`Connection OK.`):g(`brokers.brokerForm.testFailed`,`Test failed: {{value1}}`,{value1:x.error??`unknown error`})}),e(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[i(C,{variant:`outline`,size:`sm`,onClick:u,children:g(`common.cancel`,`Cancel`)}),e(`div`,{className:`flex items-center gap-2`,children:[i(C,{variant:`outline`,size:`sm`,onClick:()=>{O()},disabled:D.isPending||!T,children:D.isPending?g(`brokers.brokerForm.testing`,`Testing…`):g(`brokers.brokerForm.testConnection`,`Test connection`)}),i(C,{variant:h===void 0?`primary`:`outline`,size:`sm`,onClick:k,disabled:!T||m,children:d??g(`common.save`,`Save`)})]})]})]})}s();function G(e){return e===void 0?``:`${e.addonId??``}::${e.kind}`}function K(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.id==`string`):[]}function _e(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e&&typeof e.addonId==`string`&&Array.isArray(e.kinds)):[]}function q(e){return typeof e==`string`&&e.length>0?e:void 0}function ve(e){let t=new Map;for(let n of e.providers)if(!(e.addonId!==void 0&&n.addonId!==e.addonId))for(let r of n.kinds){if(e.kind!==void 0&&r.kind!==e.kind)continue;let i=q(r.interactiveConnectPath),a=q(r.interactiveDisconnectPath),o=q(r.signIn?.basePath);t.set(`${n.addonId}::${r.kind}`,{addonId:n.addonId,kind:r.kind,label:r.label,...i===void 0?{}:{interactiveConnectPath:i},...a===void 0?{}:{interactiveDisconnectPath:a},...o===void 0?{}:{signInBasePath:o}})}for(let n of e.brokers)e.kind!==void 0&&n.kind!==e.kind||[...t.values()].some(e=>e.kind===n.kind)||t.set(`::${n.kind}`,{kind:n.kind,label:n.kind});return[...t.values()]}function J(e){let t=h(),r=T(e.kind===void 0?{}:{kind:e.kind});return{options:n(()=>ve({providers:_e(t.data),brokers:K(r.data).filter(t=>e.addonId===void 0||t.addonId===e.addonId),...e.addonId===void 0?{}:{addonId:e.addonId},...e.kind===void 0?{}:{kind:e.kind}}),[t.data,r.data,e.addonId,e.kind]),isLoading:t.isLoading===!0}}var Y=`kind`,X=`name`,Z=`restore`,Q=`restoreId`;function ye(e,t={allowRestore:!0}){let n=[];return e.length>1&&n.push({type:`select`,key:Y,label:j.t(`helpers.brokerIdentitySchema.kind`),options:e.map(e=>({value:e.key,label:e.label}))}),n.push({type:`text`,key:X,label:j.t(`helpers.brokerIdentitySchema.name`),placeholder:j.t(`helpers.brokerIdentitySchema.namePlaceholder`),required:!0}),t.allowRestore&&n.push({type:`boolean`,key:Z,label:j.t(`helpers.brokerIdentitySchema.restore`),description:j.t(`helpers.brokerIdentitySchema.restoreHint`)},{type:`text`,key:Q,label:j.t(`helpers.brokerIdentitySchema.originalId`),placeholder:`ha_004`,required:!0,showWhen:{field:Z,equals:!0}}),{sections:[{id:`broker-identity`,title:j.t(`helpers.brokerIdentitySchema.title`),columns:1,fields:n}]}}function be(e){let t=t=>{let n=e[t];return typeof n==`string`?n.trim():``},n=t(Y);if(n===``)return{ok:!1,problem:`Pick a kind.`};let r=t(X);if(r===``)return{ok:!1,problem:`Enter a name before saving.`};if(e.restore!==!0)return{ok:!0,identity:{kindKey:n,name:r,restoreId:null}};let i=t(Q);return i===``?{ok:!1,problem:`Enter the original id, or turn restore off to create a new broker.`}:{ok:!0,identity:{kindKey:n,name:r,restoreId:i}}}s();function $({title:t,subtitle:n,onClose:r,children:a}){return i(w,{open:!0,onOpenChange:e=>!e&&r(),children:e(D,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[e(k,{children:[i(b,{children:t}),n&&i(A,{children:n})]}),i(S,{className:`space-y-3 pr-1`,children:a})]})})}function xe(e,t){let n=new Set(t.map(e=>e.trim().toLowerCase()));if(!n.has(e.toLowerCase()))return e;for(let t=2;;t++){let r=`${e} ${t}`;if(!n.has(r.toLowerCase()))return r}}function Se(e){return e.broker===void 0?i(Ce,{...e}):i(we,{...e,broker:e.broker})}function Ce({kind:r,addonId:s,onClose:u,onSaved:d}){let{t:p}=M(),m=c(),{options:h,isLoading:_}=J({...s===void 0?{}:{addonId:s},...r===void 0?{}:{kind:r}}),v=T({}),y=n(()=>K(v.data).map(e=>e.name),[v.data]),[b,x]=o({[X]:``,[Z]:!1,[Q]:``}),[S,C]=o(null),w=h.find(e=>G(e)===b.kind)??h[0],E=G(w),D=w===void 0?``:xe(w.label,y),k=t(``);a(()=>{E!==``&&x(e=>{let t=typeof e.name==`string`?e[X]:``,n=t===``||t===k.current;k.current=D;let r=n?D:t;return e.kind===E&&t===r?e:{...e,[Y]:E,[X]:r}})},[E,D]);let A=n(()=>ye(h.map(e=>({key:G(e),label:e.label})),{allowRestore:w?.signInBasePath===void 0}),[h,w?.signInBasePath]),j=e=>{m.invalidateQueries({queryKey:[[`broker`,`list`]]}),d(e)},N=O({onSuccess:e=>{let t=typeof e==`object`&&e&&typeof e.id==`string`?e.id:null,n=w?.interactiveConnectPath;t!==null&&n!==void 0&&te(n,t,()=>{m.invalidateQueries({queryKey:[[`broker`,`list`]]})}),t!==null&&j(t)}}),P=be(b),F=P.ok?P.identity.name:``,I=e=>{if(w!==void 0){if(!P.ok){C(P.problem);return}C(null),N.mutate({kind:w.kind,name:P.identity.name,settings:e,...P.identity.restoreId===null?{}:{id:P.identity.restoreId},...w.addonId===void 0?{}:{addonId:w.addonId}})}},L=N.isPending;return i($,{title:p(`brokers.editor.createTitle`),subtitle:p(`brokers.editor.createSubtitle`),onClose:L?()=>{}:u,children:_&&h.length===0?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(f,{className:`h-3.5 w-3.5 animate-spin`}),` `,p(`brokers.editor.loadingKinds`)]}):w===void 0?i(g,{message:p(`brokers.editor.noProvider`)}):e(l,{children:[i(ee,{schema:A,values:b,onChange:x}),S!==null&&i(g,{message:S}),N.isError&&i(g,{message:N.error instanceof Error?N.error.message:String(N.error)}),i(W,{kind:w.kind,...w.addonId===void 0?{}:{addonId:w.addonId},onSubmit:I,onCancel:u,submitLabel:p(L?`brokers.editor.creating`:`brokers.editor.create`),disabled:L,...w.signInBasePath===void 0?{}:{signIn:{basePath:w.signInBasePath,name:F,onSignedIn:j}}},E)]})})}function we({broker:t,onClose:r,onSaved:a}){let{t:o}=M(),s=c(),{options:l}=J({addonId:t.addonId,kind:t.kind}),u=l.find(e=>e.kind===t.kind)?.signInBasePath,d=x({id:t.id,addonId:t.addonId}),p=y({onSuccess:()=>{s.invalidateQueries({queryKey:[[`broker`,`list`]]}),s.invalidateQueries({queryKey:[[`broker`,`getSettings`],{input:{id:t.id,addonId:t.addonId}}]}),a(t.id)}}),m=n(()=>{let e=d.data;return e&&typeof e==`object`?{...e}:{}},[d.data]),h=p.isPending;return i($,{title:o(`brokers.brokerManager.edit`,`Edit {{name}}`,{name:t.name}),subtitle:`${t.kind} · ${t.id}`,onClose:h?()=>{}:r,children:d.isLoading?e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(f,{className:`h-3.5 w-3.5 animate-spin`}),` `,o(`brokers.brokerManager.loadingSettings`)]}):d.isError?e(`div`,{className:`space-y-3`,children:[i(g,{message:o(`brokers.brokerManager.loadSettingsFailed`,{message:d.error instanceof Error?d.error.message:o(`common.unknownError`)})}),i(`div`,{className:`flex justify-end`,children:i(C,{variant:`outline`,size:`sm`,onClick:r,children:o(`common.close`,`Close`)})})]}):e(`div`,{className:`space-y-3`,children:[p.isError&&i(g,{message:p.error instanceof Error?p.error.message:String(p.error)}),i(W,{kind:t.kind,addonId:t.addonId,brokerId:t.id,initialValues:m,onSubmit:e=>p.mutate({id:t.id,settings:e,addonId:t.addonId}),onCancel:r,submitLabel:h?o(`brokers.brokerManager.saving`):o(`common.save`,`Save`),disabled:h,...u===void 0?{}:{signIn:{basePath:u,name:t.name,brokerId:t.id,onSignedIn:e=>{s.invalidateQueries({queryKey:[[`broker`,`list`]]}),a(e)}}}})]})})}export{K as n,J as r,Se as t};
@@ -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{Ar as m,Ei as h,Fn as g,Ht as _,In as v,Ni as y,Oi as b,Tr as x,Vn as S,bi as C,dt as w,ea as T,fr as E,ia as D,ma as O,mr as k,st as A,vt as j,wn as M,yn as N,zt as P}from"./player-overlays-C_WpL6a6.js";import{Fa as F,Gi as I,Mo as L,Pa as R,Pi as z,Si as B,Ti as V,Vi as H,Yi as U,Zi as ee,_a as te,_o as ne,ba as re,ga as ie,ha as ae,ma as oe,pa as se,va as ce,wi as le,ya as ue}from"./client-Clemlz5W.js";import{t as de}from"./boxes-BYgmIZEw.js";import{i as fe,n as W,r as pe,t as me}from"./variable-vSgKlDpd.js";import{s as he}from"./video-DgFhEP51.js";import{$t as ge,Ad as _e,Ar as G,Ba as ve,Cd as ye,Ci as be,Dn as xe,Ed as K,Ha as Se,Ja as Ce,Jd as we,Jn as Te,Jt as Ee,Ka as De,Mo as Oe,Nr as ke,Od as Ae,On as je,Oo as Me,Ro as Ne,Rr as Pe,Sr as Fe,Tn as Ie,Tr as Le,Ua as Re,Va as ze,Vr as Be,Xa as Ve,Xd as He,Ya as Ue,Za as We,_i as Ge,an as Ke,at as qe,bi as Je,br as Ye,bt as Xe,ci as q,cn as Ze,ei as J,en as Qe,es as $e,gi as et,gr as tt,gt as nt,jd as Y,jr as rt,kd as it,mt as at,ri as ot,vr as st,xi as ct,xn as lt,xr as ut,yi as dt}from"./src-BuD4BDe3.js";import{t as X}from"./i18n-COiZcYwm.js";import{t as Z}from"./useTranslation-BJr-n0es.js";import{L as ft,T as pt,_r as mt,h as ht,lr as gt,m as _t,mr as vt,pr as yt,yr as bt}from"./index-B0SLrMzs.js";import{t as xt}from"./AdminSectionedPage-ePUwCKQL.js";import{n as St}from"./format-BccZ2tds.js";import{a as Ct,c as wt,i as Tt,l as Et,n as Dt,o as Ot,r as kt,s as At,t as jt}from"./ComposedDeviceEditDialog-ck2hidMF.js";import{C as Mt,G as Nt,Q as Pt,Y as Ft,a as It,at as Lt,b as Rt,g as zt,i as Bt,n as Vt,nt as Ht,o as Ut,r as Wt,w as Gt,y as Kt}from"./CompositionBlockEditor-HRq0m67C.js";var qt=`const AUTOMATION_RECIPE =`,Jt=`// 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 Yt(e){return e.includes(qt)}function Xt(e){let t=e.indexOf(qt);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 Zt(e){let t=Xt(e);if(t===null)return{ok:!1,reason:X.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:X.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=ie.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?X.t(`helpers.recipeFromCode.schemaMismatch`):X.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function Qt(e){let t=Xt(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)}${Jt}${e.slice(i)}`}u();var $t={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},en={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},tn={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function nn(){let{t:e}=Z();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 rn({traces:t,selectedId:n,onSelect:r}){let{t:i}=Z(),a=nn(),s=t===void 0?[]:t.toReversed();return o(Ie,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:x,children:t===void 0?o(ke,{className:`m-3 h-16`}):s.length===0?o(rt,{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(q,{variant:$t[t.outcome],children:a(t.outcome)}),t.repeat>1&&o(q,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:St(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 an(e){return en[e]}function on({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`:en[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 ${tn[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}function Q({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function sn(e){let t=Tt(e.deviceId);if(t.data!==void 0)return Dt(t.data,e.cap).find(t=>t.path===e.fieldPath)}function cn({value:t,devices:n,onChange:r}){let{t:i}=Z(),[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(J,{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(b,{className:`size-3.5 shrink-0`})]}),a&&o(ln,{value:t,devices:n,onCancel:()=>s(!1),onConfirm:e=>{s(!1),r(e)}})]})}function ln({value:t,devices:n,onCancel:i,onConfirm:a}){let{t:s}=Z(),l=Oe({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(Lt(l.data).find(e=>e.id===t.deviceId)??null));let v=s(`automation.fieldPicker.title`,`Device value`);return o(tt,{open:!0,onOpenChange:e=>!e&&i(),children:e(st,{width:`xl`,children:[o(ut,{children:o(Fe,{children:v})}),o(Pt,{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(Ye,{className:`flex flex-wrap gap-2`,children:[o(J,{variant:`ghost`,onClick:i,children:s(`common.cancel`,`Cancel`)}),o(J,{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 un=1e4;function dn(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 pn({step:t,onChange:n}){let{t:r}=Z(),i=Je({},{refetchInterval:un});if(i.data===void 0)return o(ke,{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(mn,{variable:e,value:t.variables?.[e.name],onChange:r=>n(fn(t,dn(t.variables,e.name,r)))},e.name))})]})}function mn({variable:t,value:n,onChange:r}){let{t:i}=Z(),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(wt,{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(Et,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Y,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}var hn=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function gn(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 hn}}function _n(e){switch(e){case`eq`:return X.t(`helpers.recipeParts.op_eq`);case`ne`:return X.t(`helpers.recipeParts.op_ne`);case`gt`:return X.t(`helpers.recipeParts.op_gt`);case`gte`:return X.t(`helpers.recipeParts.op_gte`);case`lt`:return X.t(`helpers.recipeParts.op_lt`);case`lte`:return X.t(`helpers.recipeParts.op_lte`);case`contains`:return X.t(`helpers.recipeParts.op_contains`);default:return X.t(`helpers.recipeParts.op_in`)}}function vn(e){return gn(e).map(e=>({value:e,label:_n(e)}))}function yn(e){switch(e){case`device-state`:return X.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return X.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return X.t(`helpers.recipeParts.trigger_schedule`);case`stationary`:return X.t(`flow.trigger.stationary`);case`detection`:return X.t(`flow.trigger.detection`);case`interval`:return X.t(`flow.trigger.interval`);default:return X.t(`helpers.recipeParts.trigger_manual`)}}var bn={triggers:[],actions:[]};function xn(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 Sn(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 Cn(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function wn(){return{kind:`stationary-present`,deviceId:0}}function Tn(){return{kind:`expression`,expr:``,bindings:{}}}function En(e,t,n){return e.map((e,r)=>r===t?n:e)}function Dn(e,t){return e.filter((e,n)=>n!==t)}function On(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=Dn(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function kn(e,t){return{...e,triggers:[...t]}}function An(e,t){return{...e,actions:[...t]}}var jn=[{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 Mn({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,onChange:c}){let{t:l}=Z(),u=jn.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`:an(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(q,{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(En(t,d,Sn(Nn(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(J,{variant:`ghost`,disabled:d===0,onClick:()=>c(On(t,d,d-1)),title:l(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(T,{className:`h-3.5 w-3.5`})}),o(J,{variant:`ghost`,disabled:d===t.length-1,onClick:()=>c(On(t,d,d+1)),title:l(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(D,{className:`h-3.5 w-3.5`})}),o(J,{variant:`ghost`,onClick:()=>c(Dn(t,d)),title:l(`automation.actionList.removeThisStep`,`Remove this step`),children:o(_,{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(Y,{type:`number`,min:0,max:300,value:String(i.seconds),onChange:e=>c(En(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(En(t,d,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(yt,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`cap`&&o(Ct,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>c(En(t,d,e))}),i.kind===`action`&&o(pn,{step:i,onChange:e=>c(En(t,d,e))})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(J,{variant:`outline`,onClick:()=>c([...t,Sn(u[0]?.value??`cap`)]),children:[o(g,{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 Nn(e){return jn.find(t=>t.value===e)?.value??`cap`}function Pn(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function Fn(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 In(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 Ln(e,t){if(e.length===0)return[];let[n,...r]=e.map(e=>e.kind===`detection`?Fn(t):e.kind===`stationary`?In(t):[]);return n===void 0?[]:n.filter(e=>r.every(t=>t.some(t=>t.name===e.name)))}var Rn=`conditions`;function zn(e){return e===void 0||e.trim()===``?null:e}function Bn(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function Vn(e){return e.steps.map(e=>({index:Bn(e.path),tone:e.outcome===`ok`?`pass`:e.outcome===`error`?`fail`:`idle`,message:zn(e.message)}))}function Hn(e){let t=e.conditions.find(e=>e.path===Rn);return t===void 0?null:{tone:t.outcome===`pass`?`pass`:t.outcome===`fail`?`fail`:`idle`,reason:zn(t.reason)}}function Un(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:zn(e.verdict?.reason)}}function Wn(e){let t=Vn(e);return{when:{tone:e.trigger.outcome===`pass`?`pass`:`fail`,reason:zn(e.trigger.reason)},condition:Hn(e),thenBlock:Un(e,t),steps:t}}function Gn(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}var Kn={name:``,steps:[],variables:[]};function qn(e){return e===null?Kn:{name:e.name,steps:e.steps??[],variables:e.variables??[]}}function Jn(e){let t=[],n=e=>{t.includes(e)||t.push(e)},r=e=>{if(At(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 Yn(e){let t=new Set(e.variables.map(e=>e.name));return Jn(e.steps).find(e=>!t.has(e))??null}function Xn(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=>!tr(e.name));if(t!==void 0)return{ok:!1,reason:{kind:`bad-name`,name:t.name}};let n=nr(e.variables)[0];if(n!==void 0)return{ok:!1,reason:{kind:`duplicate`,name:n}};let r=Yn(e);if(r!==null)return{ok:!1,reason:{kind:`undeclared`,name:r}};let i=se.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 Zn(e,t,n){return At(e)?e.$var===t?{$var:n}:e:Array.isArray(e)?e.map(e=>Zn(e,t,n)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Zn(r,t,n)])):e}function Qn(e,t,n){if(e.kind!==`cap`)return e;let r=At(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,Zn(r,t,n)]));return{...e,deviceId:r,...i===void 0?{}:{args:i}}}function $n(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=>Qn(e,r.name,n))}}function er(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 tr(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function nr(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 rr=[`number`,`string`,`boolean`,`select`];function ir(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function ar(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 or(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function sr(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function cr({variables:t,onChange:n,onRename:r}){let{t:i}=Z(),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(Ie,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:me,actions:e(J,{variant:`outline`,size:`sm`,onClick:()=>n([...t,er(t)]),children:[o(g,{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(Y,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!tr(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(Y,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,sr(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(wt,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:rr.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=rr.find(t=>t===e.target.value);t!==void 0&&s(l,ir(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(lr,{variable:c,onChange:e=>s(l,or(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(Y,{"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,ar(c,e.target.value))})]}),o(J,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(_,{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 lr({variable:e,onChange:t}){let{t:n}=Z(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(Et,{"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(wt,{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(Y,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var ur=5e3;function dr(e){return e.kind===`cap`||e.kind===`wait`}function fr(e){return e instanceof Error?e.message:String(e)}function pr(){let{t:e}=Z();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 mr({entry:t,onClose:n,onSaved:i}){let{t:a}=Z(),s=d(),l=A(),u=kt(),f=pr(),[m,h]=c(()=>qn(t)),[g,y]=c(null),b=t!==null&&t.readOnly,x=()=>{s.invalidateQueries({queryKey:[[`actions`]]})},S=et({onSuccess:e=>{x(),i(e.action.id)}}),C=be({onSuccess:x}),w=Ge({onSuccess:()=>{x(),n()}}),T=ct({onSuccess:x}),D=dt({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:ur}),O=D.data?.traces.find(e=>e.runId===g)??null,j=r(()=>O===null?null:Wn(O),[O]),M=Xn(m),N=r(()=>Pn(m.variables,a),[m.variables,a]),P=S.isPending||C.isPending,F=S.error??C.error??w.error??T.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(k,{className:`h-4 w-4 text-foreground-muted`}),o(Y,{"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(q,{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(cr,{variables:m.variables,onChange:e=>h({...m,variables:e}),onRename:(e,t)=>h($n(m,e,t))}),o(on,{step:`steps`,title:a(`actions.editor.steps`,`Steps`),trace:j===null?null:j.thenBlock,children:o(Mn,{actions:m.steps,devices:u,allowedKinds:[`cap`,`wait`],variables:N,onChange:e=>h({...m,steps:e.filter(dr)})})})]}),!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(G,{message:fr(F)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!b&&e(J,{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(E,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(J,{variant:`outline`,disabled:T.isPending||I,title:I?a(`actions.editor.runNeedsDefaults`,`Give each required variable a default to run it from here.`):void 0,onClick:()=>T.mutate({actionId:t.id}),children:[o(v,{className:`h-4 w-4`}),` `,a(`actions.editor.runNow`,`Run now`)]}),t!==null&&!b&&e(J,{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(_,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(J,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(rn,{traces:t===null?[]:D.data?.traces,selectedId:g,onSelect:y})})]})}u();var hr=5e3;function gr(e){return e instanceof Error?e.message:String(e)}function _r(){let{t:e}=Z();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}=Z(),a=d(),c=_r(),{state:l,openNew:u,openEdit:f,close:m}=at({editKey:`action`,newKey:`new`}),h=Je({},{refetchInterval:hr}),_=ct({onSuccess:()=>void a.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(u(),n?.())},[t,n,u]);let y=h.data??[],b=l.mode===`edit`?y.find(e=>e.id===l.id)??null:null,x=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(q,{variant:`info`,children:e.addonId}):o(q,{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:`-`}):St(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(q,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(J,{variant:`outline`,size:`sm`,disabled:_.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),_.mutate({actionId:t.id})},children:[o(v,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[_,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.`)}),_.error!=null&&o(G,{message:gr(_.error)}),h.data===void 0?h.error==null?o(ke,{className:`h-24 w-full`}):o(G,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:gr(h.error),onRetry:()=>void h.refetch()}):y.length===0?o(rt,{icon:k,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(J,{onClick:u,children:[o(g,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(p,{children:[h.error!=null&&o(G,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:gr(h.error),onRetry:()=>void h.refetch()}),o(xe,{columns:x,rows:y,rowKey:e=>e.id,pageSize:25,maxBodyHeight:je,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>f(e.id)})]})]}):o(mr,{entry:b,onClose:m,onSaved:f},b?.id??`new`)}function yr({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Z(),c=Tr(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(Y,{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(Y,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function br({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Z(),s=Tr(t,n,r);return o(Y,{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 xr(e){return typeof e==`object`&&!re(e)}function Sr(e){return re(e)?e.value:xr(e)?e[0]??``:e}function Cr(e){return re(e)?[e.value]:xr(e)?e:typeof e==`boolean`?[]:[e]}function wr(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Tr(e,t,n){let r=Qe(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=Me({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=ne(s)?s:void 0,l=wr(e?.quantity,c);if(l===void 0)return;let u=o?.display;return ge({quantity:l,display:u,capName:n,unitPreferences:r})}function Er({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=sn(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=Dr(e,c);r({...t,operator:n,value:n===`in`?Cr(t.value):Sr(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(cn,{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(br,{value:Cr(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(yr,{value:Sr(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function Dr(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Or={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function kr({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),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(Y,{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(Ar,{alias:e,source:r,devices:n,onRename:n=>s(Ir(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Lr(t.bindings,e))},e)),e(J,{variant:`ghost`,onClick:()=>s({...t.bindings,[Fr(t.bindings)]:Or}),children:[o(g,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function Ar({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Z(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Nr(r,Mr(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(Y,{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:``}:Or),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(Y,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:jr(e.target.value)})})]}):o(cn,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Pr(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(J,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(_,{className:`h-3.5 w-3.5`})})]})}function jr(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Mr(e){return e.kind===`global`?e.sourceStableId:``}function Nr(e,t){return e.find(e=>e.stableId===t)?.id??0}function Pr(e,t){return e.find(e=>e.id===t)?.stableId??``}function Fr(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 Ir(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Lr(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Rr(e){return e.kind===`all`||e.kind===`any`}function zr(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:Rr(t)?t:{kind:`all`,children:[t]}}function Br(e,t){return t===null||Rr(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Vr(e){return Br(e,zr(e))}function Hr(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?Hr(e.child,r):null;if(!Rr(e))return null;let i=e.children[n];return i===void 0?null:Hr(i,r)}function Ur(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=Ur(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!Rr(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ur(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 Wr(e){return e===null?null:ue({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function Gr(e){let t=zr(e);return{depth:t.children.length===0?0:te(t),leaves:t.children.length===0?0:ce(t),depthLimit:3,leafLimit:32}}function Kr(e,t){let n=Wr(t);return n===null?{ok:!0,recipe:Br(e,t)}:{ok:!1,reason:n}}function qr(e,t){let n=zr(e);return Kr(e,{kind:n.kind,children:[...n.children,t]})}function Jr(e,t,n){return Br(e,Ur(zr(e),t,()=>n))}function Yr(e,t){return Br(e,Ur(zr(e),t,()=>null))}function Xr(e,t,n){return Br(e,Ur(zr(e),t,e=>Rr(e)?{kind:n,children:e.children}:e))}function Zr(e,t){return Hr(zr(e),t)===null?{ok:!1,reason:X.t(`helpers.recipeOps.rowGone`)}:Kr(e,Ur(zr(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function Qr(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 $r(e,t,n){if(t.length<2)return{ok:!1,reason:X.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:X.t(`helpers.recipeOps.differentGroups`)};let r=Qr(t[0]??[]);if(r===null)return{ok:!1,reason:X.t(`helpers.recipeOps.rootGroup`)};let i=zr(e),a=Hr(i,r.path);if(a===null||!Rr(a))return{ok:!1,reason:X.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:X.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 Kr(e,Ur(i,r.path,()=>d))}function ei(e,t){if(t.length===0)return{ok:!1,reason:X.t(`helpers.recipeOps.outerNotGroup`)};let n=zr(e),r=Hr(n,t);if(r===null)return{ok:!1,reason:X.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return Kr(e,Ur(n,t,()=>r.child));if(!Rr(r))return{ok:!1,reason:X.t(`helpers.recipeOps.rowIsCondition`)};let i=Qr(t);if(i===null)return{ok:!1,reason:X.t(`helpers.recipeOps.noParent`)};let a=Hr(n,i.path);if(a===null||!Rr(a))return{ok:!1,reason:X.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 Kr(e,Ur(n,i.path,()=>o))}var ti=`text-xs text-foreground-subtle`;function ni({children:e}){return o(`span`,{className:ti,children:e})}function ri(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function ii(){let{t:e}=Z();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 ai({selected:t,onChange:n,hint:r}){let{t:i}=Z(),a=ii(),s=oe.map(e=>e.id),c=t.filter(e=>!s.includes(e));return e(`div`,{className:`space-y-1`,children:[o(ni,{children:i(`flow.scene.class`,`Class`)}),o(`div`,{className:`flex flex-wrap gap-2`,children:[...s,...c].map(e=>o(J,{size:`sm`,variant:t.includes(e)?`primary`:`outline`,"aria-pressed":t.includes(e),onClick:()=>n(ri(t,e)),children:a(e)},e))}),r!==void 0&&o(`p`,{className:ti,children:r})]})}function oi({devices:t,selected:n,onChange:r}){let{t:i}=Z(),a=t.filter(e=>e.type===F.Camera);return e(`div`,{className:`space-y-1`,children:[o(ni,{children:i(`flow.scene.cameras`,`Cameras`)}),o(Ot,{devices:a,selection:`multiple`,noun:`camera`,value:n,testId:`scene-cameras`,onChange:r})]})}function si({device:t,deviceId:n,selected:r,onToggle:i}){let a=ye({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:ti,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(J,{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 ci({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Z();if(n.length===0)return null;let s=e=>{let t=ri(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(ni,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(si,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:ti,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var li=100;function ui({trigger:t,devices:n,onChange:r}){let{t:i}=Z(),a=Math.round((t.minScore??0)*li),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/li})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(ai,{selected:t.classes,onChange:e=>r({...t,classes:[...e]})}),o(oi,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(ci,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(ni,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/li).toFixed(2)})}),o(`input`,{type:`range`,min:0,max:li,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 di({trigger:t,devices:n,onChange:r}){let{t:i}=Z();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(ai,{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(oi,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(ci,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(qe,{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}=Z();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(ni,{children:r(`flow.scene.every`,`Every`)}),o(Et,{"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(ni,{children:r(`flow.scene.minutes`,`minutes`)})]})}function pi({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=n.filter(e=>e.type===F.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(ni,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(Ot,{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(ai,{selected:t.classes??[],onChange:s,hint:t.classes===void 0?i(`flow.scene.anyClass`,`None picked: any class counts.`):void 0}),o(ci,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:c})]})}u();var mi=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function hi(e){return e.join(`/`)}function gi(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function _i({recipe:t,devices:n,onChange:i}){let{t:a}=Z(),[s,l]=c([]),[u,d]=c(null),f=zr(t),p=Gr(t),m=r(()=>s.map(gi),[s]),h=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},_=$r(t,m,`all`),v=$r(t,m,`any`),b=m.length===1?Zr(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(Jr(t,e,n)),onRemove:e=>{l([]),i(Yr(t,e))},onSetKind:(e,n)=>i(Xr(t,e,n)),onUngroup:e=>h(ei(t,e))};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(q,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),o(`div`,{className:`w-32`,children:o(K,{value:f.kind,onChange:e=>i(Xr(t,[],vi(e.target.value))),options:mi.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(yi,{container:f,path:[],handlers:x}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,onClick:()=>h(qr(t,Cn())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(g,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(J,{variant:`outline`,onClick:()=>h(qr(t,Tn())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(fe,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),e(J,{variant:`outline`,onClick:()=>h(qr(t,wn())),title:a(`flow.scene.addParkedTitle`,`True while an object is parked on a camera, in a zone`),children:[o(y,{className:`h-4 w-4`}),` `,a(`flow.scene.addParked`,`Parked object`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(J,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):_.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(J,{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(J,{variant:`ghost`,disabled:!b.ok,onClick:()=>h(b),title:b.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):b.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 yi({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(bi,{node:e,path:[...t,r],handlers:n},hi([...t,r])))})}function bi({node:t,path:n,handlers:r}){let{t:i}=Z(),a=hi(n),s=o(Te,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return Rr(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:mi.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(J,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(W,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(J,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(_,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(yi,{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(q,{variant:`warning`,children:`NOT`}),e(J,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(W,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(bi,{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(Er,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):t.kind===`expression`?o(kr,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(pi,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(J,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(_,{className:`h-3.5 w-3.5`})})]})}u();function xi({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Z(),[l,u]=c(!1),d=A(),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(J,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?b:h,{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(J,{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(he,{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(lt,{maxHeight:420,children:t})})]})}var Si=[`detection`,`stationary`,`device-state`,`device-event`,`schedule`,`interval`,`manual`],Ci={detection:`scene`,stationary:`scene`,"device-state":`device`,"device-event":`device`,schedule:`time`,interval:`time`,manual:`manual`};function wi(){let{t:e}=Z(),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 Si.map(e=>({value:e,label:yn(e),description:n[e],group:t[Ci[e]]}))}var Ti=Object.values(L).sort((e,t)=>e.localeCompare(t));function Ei({triggers:t,devices:n,onChange:r}){let{t:i}=Z();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(Di,{trigger:e,devices:n,position:i,onChange:e=>r(En(t,i,e)),onRemove:()=>r(Dn(t,i))},`${e.kind}-${String(i)}`)),e(J,{variant:`outline`,onClick:()=>r([...t,xn(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(g,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function Di({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=Z(),c=wi();return e(`div`,{className:`rounded border border-border p-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(q,{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(ot,{mode:`single`,singleDisplay:`field`,options:c,value:t.kind,onChange:e=>{e!==t.kind&&i(xn(Oi(e)))}})]}),o(J,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(_,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o(Ai,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(Mi,{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(Y,{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(yt,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`detection`&&o(ui,{trigger:t,devices:n,onChange:i}),t.kind===`stationary`&&o(di,{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(yt,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function Oi(e){return Si.find(t=>t===e)??`manual`}function ki(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 Ai({trigger:t,devices:n,onChange:r}){let{t:i}=Z(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=sn(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(cn,{value:a,devices:n,onChange:e=>r(ki(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(Te,{checked:t.becomes===void 0,onChange:e=>r(ki(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(yr,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(ki(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Te,{checked:t.edge===!0,onChange:e=>r(ki(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(Y,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(ki(a,{...c,forMs:ji(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(Y,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(ki(a,{...c,debounceMs:ji(e.target.value)}))})]})]})}function ji(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function Mi({trigger:t,devices:n,onChange:r}){let{t:i}=Z();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…`)},...Ti.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(Ot,{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 Ni=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Pi=2,Fi=30;function Ii(e){return e.runMode??{mode:`single`}}function Li(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function Ri(e){switch(e){case`queued`:return{mode:`queued`,max:Pi};case`parallel`:return{mode:`parallel`,max:Pi};case`cooldown`:return{mode:`cooldown`,minutes:Fi};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function zi(e){return Ni.find(t=>t===e)??`single`}function Bi({value:t,onChange:n}){let{t:r}=Z(),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(wt,{widthClass:`w-56`,value:t.mode,options:Ni.map(e=>({value:e,label:i[e]})),onChange:e=>n(Ri(zi(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(Et,{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(Et,{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 Vi=`hub`,Hi=5e3;function Ui({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Z(),[p,m]=c(t?.name??``),[h,g]=c(()=>Vr(n)),[_,v]=c(!1),[y,b]=c(null),x=De({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:Hi}),S=x.data?.traces.find(e=>e.runId===y)??null,C=r(()=>S===null?null:Wn(S),[S]),w=r(()=>Ln(h.triggers,f),[h.triggers,f]),T=kt(),D=ue(h),O=r(()=>Wi(h),[h]),k=r(()=>Gi(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(q,{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(Y,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(on,{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(Ei,{triggers:h.triggers,devices:T,onChange:e=>g(kn(h,e))})}),o(on,{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(_i,{recipe:h,devices:T,onChange:g})}),o(on,{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(Mn,{actions:h.actions,devices:T,variables:w,stepTones:C===null?void 0:h.actions.map((e,t)=>Gn(C,t)??`idle`),onChange:e=>g(An(h,e))})}),o(on,{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(Bi,{value:Ii(h),onChange:e=>g(Li(h,e))})}),o(xi,{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(J,{onClick:()=>{k.code!==null&&l({name:p.trim(),code:k.code,enabled:t?.enabled??!0,placement:Vi})},disabled:i||j,children:[i&&o(E,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(J,{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(J,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),A&&o(q,{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(yt,{i18nKey:`common.logsOf`,values:{id:B(t.id)},components:{code:o(`code`,{})}})}),o(Ke,{addonId:B(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(rn,{traces:t===null?[]:x.data?.traces,selectedId:y,onSelect:b})})]})}function Wi(e){let t=ie.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?X.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Gi(e,t){try{return{code:ae({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Ki(e){if(!e.enabled)return{tone:`idle`,label:X.t(`helpers.coreBlockStatus.disabled`),detail:X.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:X.t(`helpers.coreBlockStatus.running`),detail:X.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:X.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??X.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:X.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??X.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:X.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??X.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function qi(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Ji(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Yi(e){let t=e=>{let t=Ki(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 Xi(e){if(e.length===0)return X.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Ki(e).tone===`error`).length,n=e.filter(e=>Ki(e).tone===`ok`).length,r=[X.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(X.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(X.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function Zi({block:t,logsOpen:n,unreadable:r}){let i=O(),{t:a}=Z(),s=Ki(t),c=Ee(t.updatedAt,i);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(q,{variant:qi(s.tone),children:s.label}),c!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.edited`,{when:c})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:s.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:a(`automation.editor.listUnreadable`,{reason:r})}),n&&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(yt,{i18nKey:`common.logsOf`,values:{id:B(t.id)},components:{code:o(`code`,{})}})}),o(Ke,{addonId:B(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Qi({block:t,busy:n,unreadable:r,onEdit:i,onToggle:a,onToggleLogs:s,onDelete:c}){let{t:l}=Z();return e(`div`,{className:`flex justify-end gap-1`,children:[o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),i()},disabled:r!==null,title:r===null?l(`common.edit`,`Edit`):l(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(S,{className:`h-4 w-4`})}),e(Ae,{children:[o(_e,{children:o(J,{variant:`ghost`,disabled:!0,title:l(`automation.automationList.runActions`,`Run actions`),children:o(v,{className:`h-4 w-4`})})}),o(it,{children:l(`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(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s()},title:l(`automation.automationList.logs`,`Logs`),children:o(N,{className:`h-4 w-4`})}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),a(!t.enabled)},disabled:n,title:t.enabled?l(`common.disable`,`Disable`):l(`common.enable`,`Enable`),children:t.enabled?l(`common.disable`,`Disable`):l(`common.enable`,`Enable`)}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:l(`common.delete`,`Delete`),children:o(_,{className:`h-4 w-4`})})]})}function $i({onCreate:t}){let{t:n}=Z();return o(Le,{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(J,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var ea=[`coreBlocks`,`list`],ta=5e3;function na(e){return e instanceof Error?e.message:String(e)}function ra({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:d}){let{t:p}=Z(),m=w(),{state:h,openNew:g,openEdit:_,close:v}=at({editKey:`block`,newKey:`new`}),[y,b]=c(null),x=A(),[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:ea,refetchInterval:ta,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),O=()=>{D.refetch()},k=D.data;s(()=>{i===void 0||T.current===i||k?.find(e=>e.id===i&&Yt(e.code))!==void 0&&(T.current=i,_(i),a?.(i))},[i,k,_,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:Qt(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=Yi((L??[]).filter(e=>Yt(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:Ji(R,B),H=V===null?null:Zt(V.code),U=M.error===null?N.error===null?I.error===null?null:na(I.error):na(N.error):na(M.error),ee=r(()=>[{key:`name`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=Zt(e.code);return o(Zi,{block:e,logsOpen:S===e.id,unreadable:t.ok?null:t.reason})},sortValue:e=>e.name},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=Zt(e.code);return o(Qi,{block:e,busy:F.isPending||P.isPending,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)})}})}}],[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(j,{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(Ui,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:bn,saving:M.isPending||N.isPending,saveError:U,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(G,{message:na(P.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:Xi(R)}),D.error!=null&&o(G,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:na(D.error),onRetry:O}),z?o($i,{onCreate:()=>{b(null),g(),a?.(null)}}):o(xe,{columns:ee,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:je,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(G,{message:na(P.error)}),F.error!=null&&o(G,{message:na(F.error)})]})}u();function ia({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Z(),u=Ft(!0),[d,f]=c({}),[p,m]=c(s(t.nameKey)),[h,g]=c(null),[_,v]=c([]),[y,b]=c(!1),x=r(()=>u.kind===`known`?new Map(u.value.map(e=>[U({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[U(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:Mt(u.value,S)}:u,[u,S]),w=Wt(t,d),T=u.kind===`known`?Gt(u.value,w,!1):null,E=t.build(d),D=Bt(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(U(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:s(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[s(`preset.name`),o(Y,{"aria-label":s(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),o(`ul`,{className:`flex flex-col gap-2`,"aria-label":s(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[s(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[Ht(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(J,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(J,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:s(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&o(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:s(`preset.missing`,{slots:D.map(e=>s(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[o(`h3`,{className:`text-xs font-medium text-foreground`,children:s(`preset.preview`)}),o(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?o(`li`,{children:s(`preset.previewFeature`,{cap:Ht(e.cap,l.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),o(Ut,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(J,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),i(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:s(`preset.create`)}),o(J,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(Rt,{open:h!==null,title:h===null?``:s(`preset.pickTitle`,{slot:s(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>s(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}u();var aa=`preset`;function oa({mode:e,onTitle:t}){return o(e===`helper`?sa:ca,{onTitle:t})}function sa({onTitle:e}){let{t}=Z(),r=mt(),i=ve(),a=$e(),l=Ne({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=bt(),g=It(m.get(aa)),_=g===null?ua(u,t):t(g.labelKey);s(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(aa):n.set(aa,e),n},{replace:!0}),y=async(e,n)=>{try{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:e}}),s=await ma(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:zt(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(_t(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:zt(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(ca,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Vt,{fillHeight:!0,onFreeComposition:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,n)=>{let o=null,s=await Kt(e,async(s,c)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:s}});d=t.id,b.current={draft:e,blockId:d}}let f=await ma(d,async()=>(await l.refetch()).data??l.data);if(f===null)throw Error(t(`helper.devicePending`));o=f,b.current=null,c!==``&&await a.mutateAsync({deviceId:f,name:c}),n===`open`&&r(ht(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:ha(s,t)}:{kind:`saved`,deviceId:c}}})}):o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(ia,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function ca({onTitle:t}){let{t:n}=Z(),r=O(),i=mt(),a=ve(),l=$e(),u=Ne({addonId:`composer`}),[d,f]=c(F.Sensor),[p,m]=c(R.TemperatureSensor),[h,g]=c(``),[_,v]=c(null),y=Nt({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(F).find(t=>t===e.target.value);t!==void 0&&f(t)},options:Object.values(F).map(e=>({value:e,label:He(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(R).find(t=>t===e.target.value)??null),options:[{value:``,label:n(`customize.identity.noRole`)},...Object.values(R).map(e=>({value:e,label:we(e,r).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(Y,{"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(J,{disabled:y===null||a.isPending,onClick:()=>{y!==null&&la({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(_t(e),{replace:!0}),pending:n(`helper.devicePending`)})},children:n(`compositionEditor.save`)})]})}async function la(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 ma(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 ua(e,t){if(e===null)return t(`helper.newComposed`);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.newComposed`);let n=z(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}async function da(e,t){let n=`${H}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var fa=10,pa=400;async function ma(e,t,n=pa){for(let r=0;r<fa;r+=1){let r=await da(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}function ha(e,t){return e.length>0?e:zt(t(`helper.devicePending`))}function ga(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`appliance`:return{section:`group`,kind:`appliance`};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function _a(e){return{state:`answered`,byRef:new Map(e.map(e=>[U(e),e]))}}function va(e,t){if(e.state!==`unanswered`)return e.byRef.get(U(t))??null}function ya(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function ba(e){return ee(e).map(e=>e.source)}function xa(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(...ba(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...ba(e))}let r=new Set;return n.filter(e=>{let t=U(e);return r.has(t)?!1:(r.add(t),!0)})}function Sa(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:X.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[X.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[X.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??X.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:X.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function Ca(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Sa(e);case`degraded`:return{tone:`pending`,label:X.t(`helpers.compositionRows.degraded`),reason:n??X.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:X.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:X.t(`helpers.compositionRows.failed`),reason:n??X.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:X.t(`helpers.compositionRows.notRunning`),reason:n??X.t(`helpers.compositionRows.notRunningReason`)}}}function wa(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:X.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:X.t(`helpers.compositionRows.unknown`),reason:X.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return Ca(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:X.t(`helpers.compositionRows.notReported`),reason:X.t(`helpers.compositionRows.noRecord`,{stored:r})}}function Ta(e){return U(e)}function Ea(e,t){let n=va(t,e);return{key:U(e),label:n?n.name:Ta(e),presence:ya(n),deviceId:n?n.id:null}}function Da(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Oa(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:I(e.block.id),a=U(i),o=xa(e).filter(e=>U(e)!==a).map(e=>Ea(e,t)),s=n.features.map(e=>e.enabled===!1?X.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=va(t,i),l=Da(e),u=wa(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}`,origin:ga(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=ya(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Ta(r.device),namePresence:d,type:c?c.type:null,origin:ga(n),features:s,state:u,sources:o,reportedDeviceId:l}}function ka(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Aa(e,t){return ka(e)-ka(t)||e.name.localeCompare(t.name)}function ja(e,t){let n=e.flatMap(e=>{let n=Oa(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Aa),customizations:n.filter(e=>e.kind===`customization`).toSorted(Aa)}}u();var Ma=1e4;function Na(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Pa(){let e=gt();return e.data===void 0?{state:`unanswered`,reason:e.error==null?X.t(`build.customDeviceTab.deviceListPending`):X.t(`build.customDeviceTab.deviceListUnreadable`,{error:Na(e.error)})}:_a(e.data)}function Fa(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Ia({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Z(),[i,a]=bt(),s=Ce({},{refetchInterval:Ma}),l=Pa(),u=at({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?Fa(i.get(`new`),t):null,m=f!==null,[h,g]=c(``),_=A(),v=ze(),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:[Ra(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(nt,{open:m,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:de,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(oa,{mode:f,onTitle:g},f)}),o(jt,{blockId:d,onClose:y}),v.error!=null&&o(G,{message:Na(v.error)})]})}function La(t){return o(Le,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:X.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[X.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Ra(e,t,n,r,i){if(t!=null&&e===void 0)return o(G,{title:X.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Na(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:X.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return La(e.reason);let a=t==null?null:Na(t);return o(za,{lists:ja(e.views,r),fleet:r,refreshError:a,handlers:i})}function za({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Z();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(Ba,{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(Ba,{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 Ba({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Z();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(xe,{columns:Va(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:je,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Va(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(Ua,{row:e})},{key:`type`,header:X.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??X.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:X.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>Ha(e.origin,i),render:e=>o(q,{variant:`default`,"data-testid":`composed-origin-badge`,children:Ha(e.origin,i)})}]:[],{key:`state`,header:X.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(q,{variant:qi(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:X.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Ga,{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(J,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(J,{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(_,{className:`h-4 w-4`})})]})}),a}function Ha(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function Ua({row:t}){let{t:n}=Z();return e(`div`,{className:`space-y-0.5`,children:[o(Wa,{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 Wa({row:e}){let{t}=Z(),n=Be(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(vt,{to:e.kind===`composed`?ht(e.reportedDeviceId):_t(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Ga({sources:t}){let{t:n}=Z();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(vt,{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 Ka(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 qa(e){if(Array.isArray(e))return e}function Ja(e,t,n){return(t=ro(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ya(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 Xa(){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 Za(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 Qa(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Za(Object(n),!0).forEach(function(t){Ja(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Za(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function $a(e,t){if(e==null)return{};var n,r,i=eo(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 eo(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 to(e,t){return qa(e)||Ya(e,t)||io(e,t)||Xa()}function no(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 ro(e){var t=no(e,`string`);return typeof t==`symbol`?t:t+``}function io(e,t){if(e){if(typeof e==`string`)return Ka(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)?Ka(e,t):void 0}}function ao(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oo(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 so(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?oo(Object(n),!0).forEach(function(t){ao(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oo(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function co(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function lo(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 uo(e){return{}.toString.call(e).includes(`Object`)}function fo(e){return!Object.keys(e).length}function po(e){return typeof e==`function`}function mo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ho(e,t){return uo(t)||bo(`changeType`),Object.keys(t).some(function(t){return!mo(e,t)})&&bo(`changeField`),t}function go(e){po(e)||bo(`selectorType`)}function _o(e){po(e)||uo(e)||bo(`handlerType`),uo(e)&&Object.values(e).some(function(e){return!po(e)})&&bo(`handlersType`)}function vo(e){e||bo(`initialIsRequired`),uo(e)||bo(`initialType`),fo(e)&&bo(`initialContent`)}function yo(e,t){throw Error(e[t]||e.default)}var bo=lo(yo)({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"}),xo={changes:ho,selector:go,handler:_o,initial:vo};function So(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};xo.initial(e),xo.handler(t);var n={current:e},r=lo(To)(n,t),i=lo(wo)(n),a=lo(xo.changes)(e),o=lo(Co)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return xo.selector(e),e(n.current)}function c(e){co(r,i,a,o)(e)}return[s,c]}function Co(e,t){return po(t)?t(e.current):t}function wo(e,t){return e.current=so(so({},e.current),t),t}function To(e,t,n){return po(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var Eo={create:So},Do={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Oo(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 ko(e){return{}.toString.call(e).includes(`Object`)}function Ao(e){return e||Po(`configIsRequired`),ko(e)||Po(`configType`),e.urls?(jo(),{paths:{vs:e.urls.monacoBase}}):e}function jo(){console.warn(No.deprecation)}function Mo(e,t){throw Error(e[t]||e.default)}var No={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
- `},Po=Oo(Mo)(No),Fo={config:Ao},Io=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Lo(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Lo(e[n],t[n]))}),Qa(Qa({},e),t)}var Ro={type:`cancelation`,msg:`operation is manually canceled`};function zo(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Ro):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Bo=[`monaco`],Vo=to(Eo.create({config:Do,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),Ho=Vo[0],Uo=Vo[1];function Wo(e){var t=Fo.config(e),n=t.monaco,r=$a(t,Bo);Uo(function(e){return{config:Lo(e.config,r),monaco:n}})}function Go(){var e=Ho(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Uo({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),zo(Qo);if(window.monaco&&window.monaco.editor)return Xo(window.monaco),e.resolve(window.monaco),zo(Qo);Io(Ko,Jo)(Yo)}return zo(Qo)}function Ko(e){return document.body.appendChild(e)}function qo(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function Jo(e){var t=Ho(function(e){return{config:e.config,reject:e.reject}}),n=qo(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function Yo(){var e=Ho(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;Xo(n),e.resolve(n)},function(t){e.reject(t)})}function Xo(e){Ho().monaco||Uo({monaco:e})}function Zo(){return Ho(function(e){return e.monaco})}var Qo=new Promise(function(e,t){return Uo({resolve:e,reject:t})}),$o={config:Wo,init:Go,__getMonacoInstance:Zo};u();var es={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},ts={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function ns({children:e}){return t.createElement(`div`,{style:ts.container},e)}var rs=ns;function is({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...es.wrapper,width:e,height:n},...s},!r&&t.createElement(rs,null,i),t.createElement(`div`,{ref:a,style:{...es.fullWidth,...!r&&es.hide},className:o}))}var as=i(is);function os(e){s(e,[])}var ss=os;function cs(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=cs;function ls(){}function us(e,t,n,r){return ds(e,r)||fs(e,t,n,r)}function ds(e,t){return e.editor.getModel(ps(e,t))}function fs(e,t,n,r){return e.editor.createModel(t,n,r?ps(e,r):void 0)}function ps(e,t){return e.Uri.parse(t)}function ms({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=ls,onMount:S=ls}){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=$o.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=us(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=us(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=us(O.current,e||``,o||i||`text`,u||``),n=us(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(as,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(ms);function hs(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var gs=hs,_s=new Map;function vs({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=ls,onMount:C=ls,onChange:w,onValidate:T=ls}){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=gs(u),R=n(!1),z=n(!1);ss(()=>{let e=$o.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=us(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&_s.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(_s.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=us(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(_s.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&&_s.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(as,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var ys=i(vs);u();function bs(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 xs={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Ss(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...xs}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function Cs({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,Ss(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&&Ss(e,r)},[r]),o(ys,{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 ws(e){return e.some(e=>e.severity>=8)}var Ts=[{id:`blank`,name:`Blank script`,get description(){return X.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 Es(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 Ds=Ts.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 Os({existing:e,dirty:t,saving:n,restarting:r}){return e===null?X.t(`helpers.restartGate.saveFirstNoProcess`):n?X.t(`helpers.restartGate.saving`):r?X.t(`helpers.restartGate.restarting`):t?X.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:X.t(`helpers.restartGate.disabled`)}u();var ks=5e3;function As(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 js({blockId:t}){let{t:n}=Z(),i=B(t),a=Oe({addonId:i,projection:`slim`},{refetchInterval:ks}),s=r(()=>As(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(E,{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(yt,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(q,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(yt,{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(vt,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Pe,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(q,{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 Ms(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 Ns(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 Ps(e){switch(e){case`refresh-channel-catalog`:return X.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return X.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return X.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return X.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return X.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return X.t(`build.scriptSettingsPanel.enableUnifi`)}}function Fs(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Is(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Ls(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=Fs(e);n!==null&&(t[n]=Is(e))}return t}function Rs(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function zs({blockId:t}){let{t:n}=Z(),i=w(),s=Se({blockId:t},{retry:!1}),l=Re({blockId:t},{refetchInterval:1e4,retry:!1}),u=We({onSuccess:()=>{l.refetch()}}),d=Ue(),f=Ve(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=Rs(l.data)?l.data:null,S=r(()=>x===null?{}:Ls(x),[x]),C=p??S,T=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(Ms(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:Ns(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(Ps(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(E,{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(yt,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(J,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||u.isPending||y,children:[u.isPending&&o(E,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(ft,{schema:x,values:C,onChange:T,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 Bs=`hub`;function Vs({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:m,onCancel:h}){let{t:g}=Z(),_=w(),v=A(),{resolvedMode:y}=Ze(),b=V({code:t?.code??Ds,files:t?.files,entry:t?.entry}),[x,S]=c(t?.name??``),[T,D]=c(b.files),[O,k]=c(b.entry),[j,F]=c(b.entry),[I,L]=c(t?.placement??Bs),[R,z]=c(t?.integrationId??``),[H,U]=c([]),[ee,te]=c(!1),[ne,re]=c(`blank`),[ie,ae]=c(null),[oe,se]=c(``),ce=T[j]??``,le=e=>{D(t=>({...t,[j]:e}))},ue=Object.keys(T).toSorted(),de=Ts.length>1,fe=r(()=>[...n?.libs??[],...bs(T,j)],[n?.libs,T,j]),W=f({mutationFn:()=>_.trpcClient.coreBlocks.compile.mutate({files:T,entry:O})}),pe=r(()=>H.filter(e=>e.severity>=8),[H]),me=ws(H),he=x.trim()===``,ge=t===null?null:V(t),_e=t===null||ge===null||JSON.stringify(T)!==JSON.stringify(ge.files)||O!==ge.entry||x.trim()!==t.name||I!==t.placement||(R.trim()===``?void 0:R.trim())!==t.integrationId,G=()=>{W.reset(),m({name:x.trim(),files:T,entry:O,enabled:t?.enabled??!0,placement:I,...R.trim()===``?{}:{integrationId:R.trim()}})},ve=()=>{let e=Es(Object.keys(T));D(t=>({...t,[e]:``})),F(e),ae(e),se(e)},ye=e=>{ae(e),se(e)},be=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(T[t]!==void 0){F(t);return}D(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),O===e&&k(t),F(t)}},xe=async e=>{let t=Ts.find(t=>t.id===e);if(t===void 0)return;let n=Ts.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(T)===JSON.stringify(n.files)&&O===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`})||(re(e),D({...t.files}),k(t.entry),F(t.entry),(x.trim()===``||ne===`blank`)&&S(t.id===`blank`?``:t.name))},K=t===null?null:Ki(t),Se=Os({existing:t,dirty:_e,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[K!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(q,{variant:qi(K.tone),children:K.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(Y,{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(Y,{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&&de&&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 xe(e.target.value),"data-testid":`script-example-select`,children:Ts.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(Xe,{selectedNodeId:I,onSelect:L,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),I!==Bs&&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(yt,{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:[ue.map(t=>ie===t?o(Y,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>be(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),be()),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===j?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>F(t),onDoubleClick:()=>ye(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===O?` · ${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:ve,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),j!==O&&o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>k(j),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(Cs,{value:ce,onChange:le,path:`file:///${j}`,extraLibs:fe,onDiagnostics:U,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.`)}),pe.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:pe.length})}),pe.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}`)),pe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:pe.length-5})})]}),W.data!==void 0&&(W.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(C,{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:[W.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(W.data.line)})}),W.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),W.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:`),` `,Hs(W.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(zs,{blockId:t.id}),o(js,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(J,{variant:`outline`,onClick:()=>W.mutate(),disabled:W.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[W.isPending&&o(E,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(J,{onClick:G,disabled:a||me||he,children:[a&&o(E,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(J,{variant:`outline`,onClick:()=>d?.(),disabled:Se!==null||d===void 0,title:Se??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(M,{className:`h-4 w-4 animate-spin`}):o(M,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(J,{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(J,{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:pe.length}),_e&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),he&&o(q,{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(yt,{i18nKey:`build.blockEditor.logsOf`,values:{id:B(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Ke,{addonId:B(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Hs(e){return e instanceof Error?e.message:String(e)}u();var Us=[`coreBlocks`,`list`],Ws=[`coreBlocks`,`getTypeDefs`],Gs=5e3;function Ks(e){return e instanceof Error?e.message:String(e)}function qs({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=O(),{t:p}=Z(),m=w(),{state:h,openNew:g,openEdit:v,close:y}=at({editKey:`block`,newKey:`new`}),[b,x]=c(null),S=A(),[C,T]=c(null),E=l({queryKey:Us,refetchInterval:Gs,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),D=h.mode!==`closed`,k=l({queryKey:Ws,enabled:D,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),j=()=>{E.refetch()},P=n(null),F=E.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&le(e)===`code`)!==void 0&&(P.current=t,v(t),i?.(t))},[t,F,v,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),v(e.block.id),i?.(e.block.id),j()}}),L=f({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),v(e.block.id),i?.(e.block.id),j()}}),R=f({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:j}),z=f({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:j}),V=f({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:j}),H=Yi((E.data??[]).filter(e=>le(e)===`code`)),U=E.data!==void 0&&H.length===0,ee=I.isPending||L.isPending,te=I.error===null?L.error===null?null:Ks(L.error):Ks(I.error),ne=h.mode===`edit`?H.find(e=>e.id===h.id)??(b!==null&&b.id===h.id?b:null):null,re=h.mode===`new`||ne===null?null:Ji(H,ne),ie=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=Ki(t),r=Ee(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(q,{variant:qi(n.tone),children:n.label}),o(q,{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(yt,{i18nKey:`common.logsOf`,values:{id:B(t.id)},components:{code:o(`code`,{})}})}),o(Ke,{addonId:B(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=V.isPending&&V.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),x(t),v(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(J,{variant:`ghost`,onClick:e=>{e.stopPropagation(),V.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(M,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(J,{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(J,{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(J,{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(_,{className:`h-4 w-4`})})]})}}],[S,C,i,v,R,V.isPending,V.variables,z,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:E.data===void 0?``:Xi(H)}),E.error!=null&&o(G,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Ks(E.error),onRetry:j}),o(xe,{columns:ie,rows:H,rowKey:e=>e.id,pageSize:25,maxBodyHeight:je,emptyMessage:U?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),v(e.id),i?.(e.id)}}),o(nt,{open:D,onClose:()=>{I.reset(),L.reset(),V.reset(),x(null),y(),i?.(null)},title:re===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:re.name}),icon:pe,width:`xl`,testId:`script-editor-panel`,children:o(Vs,{existing:re,typeDefs:k.data,typeDefsLoading:k.isLoading,saving:ee,saveError:te,restarting:V.isPending,restartError:V.error===null?null:Ks(V.error),onRestart:re===null?void 0:()=>V.mutate(re.id),onSave:e=>{let t=re;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),V.reset(),x(null),y(),i?.(null)}})}),R.error!=null&&o(G,{message:Ks(R.error)}),z.error!=null&&o(G,{message:Ks(z.error)}),V.error!=null&&o(G,{message:Ks(V.error)})]})}var Js=[`automations`,`actions`,`scripts`,`custom-device`];function Ys(e){return e!==null&&Js.some(t=>t===e)}var Xs=[`coreBlocks`,`list`,`build-counts`],Zs=[`actions`,`list`,`build-counts`],Qs=[`block`,`action`,`create`,`new`];function $s(e){return e.filter(e=>le(e)===`code`).length}function ec(e){return e.filter(e=>Yt(e.code)).length}function tc(e,t){return t===null?e:`${e} (${String(t)})`}function nc(){let{t}=Z(),n=w(),[r,i]=bt(),a=r.get(`tab`),s=Ys(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Xs,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:$s(u),f=u===void 0?null:ec(u),p=l({queryKey:Zs,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),h=p.data===void 0?null:p.data.length,_=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=_.data?.state===`loaded`?_.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=pt(`/build`,{t,isAdmin:!0})??{icon:m,title:t(`nav.build`,`Build-your-self`)};return o(xt,{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(J,{type:`button`,onClick:()=>C(`helper`),"data-testid":`build-new-composed`,children:[o(g,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(J,{type:`button`,onClick:S,"data-testid":`build-new`,children:[o(g,{className:`h-4 w-4`}),` `,E]}),sections:[{id:`automations`,label:tc(t(`build.tabAutomations`,`Automations`),f),ownedParams:Qs,content:o(ra,{onOpenScripts:y,initialBlockId:s===`automations`?r.get(`block`)??void 0:void 0,onBlockIdChange:b,createRequested:s===`automations`&&c,onCreateConsumed:T})},{id:`actions`,label:tc(t(`build.tabActions`,`Actions`),h),ownedParams:Qs,content:o(vr,{createRequested:s===`actions`&&c,onCreateConsumed:T})},{id:`scripts`,label:tc(t(`build.tabCode`,`Code`),d),ownedParams:Qs,content:o(qs,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:x,createRequested:s===`scripts`&&c,onCreateConsumed:T})},{id:`custom-device`,label:tc(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:Qs,content:o(Ia,{createRequested:s===`custom-device`&&c,onCreateConsumed:T})}]})}export{nc as BuildPage};