@camstack/addon-admin-ui 1.2.489 → 1.2.491
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.
- package/dist/assets/{AddonAssetIcon-C0cWByHj.js → AddonAssetIcon-C-W05jOS.js} +1 -1
- package/dist/assets/{Addons-DtmmHLxt.js → Addons-DzzCgAq-.js} +1 -1
- package/dist/assets/{AdminPage-D6Yva5zf.js → AdminPage-Dy-fEJbf.js} +1 -1
- package/dist/assets/{AdminSectionedPage-ytDsnoAA.js → AdminSectionedPage-CLYqZKQj.js} +1 -1
- package/dist/assets/AiProfiles-CgwzlUVs.js +3 -0
- package/dist/assets/{BrokerEditorDialog-CTEagRft.js → BrokerEditorDialog-BfNVIR0c.js} +1 -1
- package/dist/assets/Build-CkP-FHmg.js +40 -0
- package/dist/assets/{Calendars-BzsJnrEA.js → Calendars-CJ9P43Kk.js} +1 -1
- package/dist/assets/{Cluster-C2D1ovUW.js → Cluster-BY0AJ7Y8.js} +1 -1
- package/dist/assets/{CompositionBlockEditor-CYmfatQE.js → CompositionBlockEditor-CosgjAjy.js} +1 -1
- package/dist/assets/{CompositionEditorPage-B5Cgu9cj.js → CompositionEditorPage-CJx0RCW8.js} +1 -1
- package/dist/assets/{Data-ChStbBhF.js → Data-B9ZuZX-A.js} +1 -1
- package/dist/assets/DeviceDetail-CB185X1z.js +2 -0
- package/dist/assets/{DeviceDoActionFields-GHZBRE4Q.js → DeviceDoActionFields-Bb2ej2cH.js} +1 -1
- package/dist/assets/{Devices-Bzyikktm.js → Devices-BF4EQ5d8.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-ClpQaFoO.js → EmbedPlayerPage-evY5cBae.js} +1 -1
- package/dist/assets/HelperWizard-CD_0QhkR.js +2 -0
- package/dist/assets/{History-C6N6VRgs.js → History-afx6dKjt.js} +1 -1
- package/dist/assets/{Identity-CvFSqL46.js → Identity-BrjQOQ40.js} +1 -1
- package/dist/assets/{IntegrationDetail-AVnEA7GO.js → IntegrationDetail-DWTyAAj6.js} +1 -1
- package/dist/assets/{IntegrationHub-BqWPAkYu.js → IntegrationHub-BXbnNmwc.js} +1 -1
- package/dist/assets/{Integrations-CBEyPYvE.js → Integrations-B_RGvZtR.js} +1 -1
- package/dist/assets/{Integrations-BYiw8_da.js → Integrations-kKJWlcWD.js} +1 -1
- package/dist/assets/{Library-BcuUHsq3.js → Library-jWD_BsMv.js} +1 -1
- package/dist/assets/{Locations-BrPK_nfE.js → Locations-Da36xo8K.js} +1 -1
- package/dist/assets/{Logs-D_Jnlf_J.js → Logs-DWUljlNw.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-C1WSjh5s.js → MaskShapeCanvas-BvI_4dLm.js} +1 -1
- package/dist/assets/{MotionZonesSettings-BB6LidaW.js → MotionZonesSettings-BvSmNtWZ.js} +1 -1
- package/dist/assets/{MyAccess-DjL1Z681.js → MyAccess-DyOUww3e.js} +1 -1
- package/dist/assets/{Network-DjKf4STc.js → Network-f3eno7Nz.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-ivvFi7qU.js → NodeAddonsSettingsPanel-TyErVJaa.js} +1 -1
- package/dist/assets/Notifications-Bx6F55kk.js +1 -0
- package/dist/assets/Pipeline-yNzjqrit.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-CSdKuS75.js → PrivacyMaskSettings-BBpPNBYz.js} +1 -1
- package/dist/assets/{Recordings-Ce8DTG1O.js → Recordings-Ci4LULiQ.js} +1 -1
- package/dist/assets/{ScanNetworkModal-81xkyJSk.js → ScanNetworkModal-Dn_Cbh-y.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-ucsduhsM.js → SceneMonitorEditor-CuPQcK5y.js} +1 -1
- package/dist/assets/{SessionsList-Dgrg9zT1.js → SessionsList-DRYMTqqU.js} +1 -1
- package/dist/assets/{Showroom-CkHdCDH1.js → Showroom-Hd3Y1pZa.js} +1 -1
- package/dist/assets/{System-HvIXTTB1.js → System-C4I1BL8G.js} +1 -1
- package/dist/assets/{Terminal-CwE2WbSi.js → Terminal-DZwz7oSc.js} +1 -1
- package/dist/assets/{Viewer-B6suHwLq.js → Viewer-Dupx7vL4.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BkS64PhS.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CWGVTk4s.js} +1 -1
- package/dist/assets/{addon-icons-context-BY_MClqz.js → addon-icons-context-CzTWZHSh.js} +1 -1
- package/dist/assets/{archive-DSecC29S.js → archive-COytoRbW.js} +1 -1
- package/dist/assets/{assignment-candidates-CCD35Rpj.js → assignment-candidates-6WyXElcY.js} +1 -1
- package/dist/assets/{authed-media-Dow1_6zk.js → authed-media-BYn8KpCA.js} +1 -1
- package/dist/assets/{bell-off-kKEnaAlY.js → bell-off-CqaftCCC.js} +1 -1
- package/dist/assets/{board-model-CGmvb_0S.js → board-model-BnBpDyVJ.js} +1 -1
- package/dist/assets/{boxes-D29FuJd_.js → boxes-DiH5aKPU.js} +1 -1
- package/dist/assets/circle-slash-DjmuKPXI.js +1 -0
- package/dist/assets/client-CoTSmvjZ.js +358 -0
- package/dist/assets/{cloud-upload-CNHrN4UO.js → cloud-upload-CydKKaEp.js} +1 -1
- package/dist/assets/crop-FLPers4o.js +1 -0
- package/dist/assets/{device-integration-icon-Dg_7SOuH.js → device-integration-icon-BJlT_oa3.js} +1 -1
- package/dist/assets/device-picker-model-GAczoeeF.js +1 -0
- package/dist/assets/{dist-pyNtUJBC.js → dist-ByomGInQ.js} +1 -1
- package/dist/assets/dist-yzJdpluK.js +358 -0
- package/dist/assets/{eraser-DQdA4r-4.js → eraser-BvwiPI1u.js} +1 -1
- package/dist/assets/{format-CvRuKl82.js → format-pVRrtm44.js} +1 -1
- package/dist/assets/{hard-drive-download-BWtxkXEP.js → hard-drive-download-qh4K1hU8.js} +1 -1
- package/dist/assets/{hostInit-C4zImIaq.js → hostInit-BSSPz1Tp.js} +1 -1
- package/dist/assets/i18n-CI5vBtLY.js +1 -0
- package/dist/assets/{icons-CeHJ12H1.js → icons-wHAKhjV4.js} +1 -1
- package/dist/assets/{index-4kmzPYxW.js → index-B5aMjANu.js} +3 -3
- package/dist/assets/{key-ibd36DX6.js → key-GQVUlMPP.js} +1 -1
- package/dist/assets/{key-round-Cx5S95mB.js → key-round-BYU9tibU.js} +1 -1
- package/dist/assets/{layers-f2rCYTNI.js → layers-wvbWI8iv.js} +1 -1
- package/dist/assets/{linked-devices-model-DBaDc0Fe.js → linked-devices-model-CXZKHslN.js} +1 -1
- package/dist/assets/{list-ordered-DVEuSX72.js → list-ordered-DcXCNlr1.js} +1 -1
- package/dist/assets/{location-owned-usage-D20qY7jM.js → location-owned-usage-BP75gZgA.js} +1 -1
- package/dist/assets/{log-in-YSzSSnpb.js → log-in-BEcXcuRp.js} +1 -1
- package/dist/assets/{memory-stick-BxkFX9Lp.js → memory-stick-CzBkDqRK.js} +1 -1
- package/dist/assets/{message-square-plus-CReLm1AI.js → message-square-plus-DAfPpZoi.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-3901d897.js → mf-entry-bootstrap-0-2a116f23.js} +2 -2
- package/dist/assets/{mic-off-CzIbHCeE.js → mic-off-DJsgLuRv.js} +1 -1
- package/dist/assets/{monitor-off-D6AnJas6.js → monitor-off-BIDr69WD.js} +1 -1
- package/dist/assets/{monitor-smartphone-BYEnK_6t.js → monitor-smartphone-0cl5JG2q.js} +1 -1
- package/dist/assets/mount-GAczoeeF.js +1 -0
- package/dist/assets/{player-overlays-nQJCQERn.js → player-overlays-DN3wN3kB.js} +1 -1
- package/dist/assets/{recycle-CWMxz1Q3.js → recycle-6xhPDDKa.js} +1 -1
- package/dist/assets/remoteEntry-CxXnwLxt.js +1 -0
- package/dist/assets/{scan-eye-t_4fVxI4.js → scan-eye-C_qPMtrX.js} +1 -1
- package/dist/assets/{scissors-DL5nVl1a.js → scissors-5gO0XeLA.js} +1 -1
- package/dist/assets/{search-x-CbPl9Xi3.js → search-x-LetCZ_ep.js} +1 -1
- package/dist/assets/{send-BQl_zLK4.js → send-BfNViT0x.js} +1 -1
- package/dist/assets/{settings-2-7F6aVC_u.js → settings-2-T7g84dNm.js} +1 -1
- package/dist/assets/{sigma-kEBBYTCa.js → sigma-BlXZ2aw7.js} +1 -1
- package/dist/assets/{speaker-CkI0pe60.js → speaker-Ca-uaBj6.js} +1 -1
- package/dist/assets/src-DaPCpXY_.js +67 -0
- package/dist/assets/{step-inspector-model-HSCaPOVt.js → step-inspector-model-CQm0mKvR.js} +1 -1
- package/dist/assets/{table-2-Cukv2oib.js → table-2-CxbhwUvc.js} +1 -1
- package/dist/assets/{timer-reset-hysIbh2s.js → timer-reset-BZJJw_vy.js} +1 -1
- package/dist/assets/{ungroup-D4Nql8ck.js → ungroup-B0PNlyKk.js} +1 -1
- package/dist/assets/{unlink-DNVVxO6S.js → unlink-BTcNOC7C.js} +1 -1
- package/dist/assets/{usb-DNmhv4AW.js → usb-CVx1D-fe.js} +1 -1
- package/dist/assets/{use-scenes-feed-BUQTm5ig.js → use-scenes-feed-CyaFpfUP.js} +1 -1
- package/dist/assets/{use-stationary-objects-B4f1cFoy.js → use-stationary-objects-CE5HpIjg.js} +1 -1
- package/dist/assets/useEventInvalidation-GAczoeeF.js +1 -0
- package/dist/assets/{useNodeUrlSelection-BKSL_pMO.js → useNodeUrlSelection-DzLKeuVO.js} +1 -1
- package/dist/assets/user-round-DmS1e16J.js +1 -0
- package/dist/assets/{user-x-DGZKKLZG.js → user-x-CDW03V4s.js} +1 -1
- package/dist/assets/{video-DEeXGFHo.js → video-CWc9XxJk.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CF1E4s_B.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Dq9ZgXY3.js} +2 -2
- package/dist/index.html +9 -9
- package/dist/server/addon.js +22 -6
- package/package.json +1 -1
- package/dist/assets/AiProfiles-Dr62eghf.js +0 -3
- package/dist/assets/Build-B8CmNZth.js +0 -40
- package/dist/assets/DeviceDetail-B4rdvagQ.js +0 -2
- package/dist/assets/HelperWizard-C9VjtAAi.js +0 -2
- package/dist/assets/Notifications-Ck0_YzEY.js +0 -1
- package/dist/assets/Pipeline-4J5lhNWd.js +0 -1
- package/dist/assets/circle-slash-BEdaE_jf.js +0 -1
- package/dist/assets/client-CdHPjeIs.js +0 -358
- package/dist/assets/crop-E8rhIxyE.js +0 -1
- package/dist/assets/device-picker-model-CdWcoivb.js +0 -1
- package/dist/assets/dist-CMh2DitE.js +0 -358
- package/dist/assets/i18n-Dgilx0WT.js +0 -1
- package/dist/assets/mount-CdWcoivb.js +0 -1
- package/dist/assets/remoteEntry-BNS8ga8f.js +0 -1
- package/dist/assets/src-DzfpPZrG.js +0 -67
- package/dist/assets/useEventInvalidation-CdWcoivb.js +0 -1
- package/dist/assets/user-round-I0Uty2ao.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{An as d,D as f,G as p,Gr as m,In as h,L as g,Lt as _,Mi as v,Ni as y,Oi as b,Q as x,Qt as S,Xt as C,Zi as w,Zr as T,dt as ee,ei as E,fn as D,kn as O,kr as k,ot as A,pn as j,sr as M,xn as N}from"./player-overlays-nQJCQERn.js";import{Fr as P,Ir as F,Ya as I}from"./client-CdHPjeIs.js";import{n as L,t as R}from"./send-BQl_zLK4.js";import{t as te}from"./message-square-plus-CReLm1AI.js";import{$r as z,Cn as B,Dr as V,Er as H,Fr as U,Hn as ne,Or as W,Qn as re,Sn as G,Tr as K,Wn as ie,Zr as ae,bn as q,bt as oe,ft as J,id as Y,ld as se,mt as ce,oi as X,or as le,rt as ue,ud as de,xo as fe,xt as pe}from"./src-DzfpPZrG.js";import{t as Z}from"./i18n-Dgilx0WT.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-CdWcoivb.js";import{S as me,gr as he}from"./index-4kmzPYxW.js";import{t as ge}from"./AdminSectionedPage-ytDsnoAA.js";import{t as _e}from"./AdminPage-D6Yva5zf.js";c();var ve=`__redacted__`,ye=[`llm`,`listProfiles`],be=[`llm`,`listProfileKinds`],xe=[`llm`,`getDefaults`],Se=[`llm`,`listRuntimeNodes`],Ce=[`llm`,`listModelCatalog`],we=[`llm`,`getUsage`],Te=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],Ee=new Map([[`cloud`,E],[`plug`,O],[`cpu`,T],[`server`,D],[`sparkles`,S]]);function De(e){return Ee.get(e)??y}function Oe(e){return typeof e==`string`&&e.length>0?e:void 0}function ke(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Ae(e){return e===!0}function je(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Me={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Ne(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:Z.t(`ai.appleUnknown`),detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:Z.t(`ai.appleAvailable`),detail:Z.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Me[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:Z.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:Z.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var Pe={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`};function Fe(e){return e.reachable?e.status===void 0?`success`:Pe[e.status.state]:`danger`}function Ie(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Ne(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Ne(e);t.push({id:`apple`,labelKey:`ai.featureApple`,tone:n.tone,detail:n.labelDefault})}let r=e.status?.vramBytes;return r!==void 0&&r>0&&t.push({id:`gpu`,labelKey:`ai.featureGpu`,tone:`info`,detail:null}),t}function Le(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:F.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:F.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:F.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:F.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 Re=[`temperature`,`topP`,`topK`,`maxTokens`,`contextLength`,`systemPrompt`],ze=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function Be(e,t){let n=Le();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Ve(e){let t=Be(e,Re);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function He(e){let t=Be(e,ze);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function Ue(e){return e===null?{}:{temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled}}function We(e,t){return{...e.features,...t?.features}}function Ge(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ke(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?ke(i[e])??t:n??t,o=e=>r.includes(e)?ke(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`systemPrompt`)?Oe(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,F.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,F.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,F.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,F.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:Ae(i.retryEnabled),maxAttempts:ke(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?Ae(i.toolsEnabled):t?.toolsEnabled??!1,...s===void 0?{}:{temperature:s},...c===void 0?{}:{topP:c},...l===void 0?{}:{topK:l},...u===void 0?{}:{maxTokens:u},...d===void 0?{}:{contextLength:d},...f===void 0?{}:{systemPrompt:f},providerConfig:n.providerConfig}}var qe=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function Je(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Ye({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=A(),[d,f]=o(``),[p,h]=o(null),[g,_]=o(!1),v=s({queryKey:Ce,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),y=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:t})}),b=l({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),_(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),x=l({mutationFn:e=>u.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{_(!0),y.refetch()}}),S=s({queryKey:Se,enabled:x.isPending,refetchInterval:x.isPending?qe:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,C=n(()=>{let e=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(y.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(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]},[v.data,y.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=v.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=y.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},T=e=>{d.trim()!==``&&b.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(pe,{label:c(`ai.model`,`Model`),required:!0,children:i(Y,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:Je(r),options:C,onChange:e=>w(e.target.value)})}),i(pe,{label:c(`ai.hfTitle`,`Add a model from Hugging Face`),description:c(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`),children:e(`div`,{className:`flex gap-2`,children:[i(se,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>f(e.target.value),placeholder:c(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())}}),e(z,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||b.isPending,onClick:()=>T(),children:[b.isPending?i(M,{className:`h-3.5 w-3.5 animate-spin`}):i(j,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),b.isError&&i(K,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(K,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(z,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),b.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>T(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(X,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(X,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(z,{size:`sm`,type:`button`,disabled:x.isPending||g,onClick:()=>x.mutate(p.model),children:[x.isPending?i(M,{className:`h-3.5 w-3.5 animate-spin`}):i(m,{className:`h-3.5 w-3.5`}),g?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),S!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:S.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:S.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:S.file,index:S.fileIndex,count:S.fileCount,done:$(S.downloadedBytes),total:S.totalBytes===void 0?``:` / ${$(S.totalBytes)}`})})]}),x.isError&&i(K,{message:x.error instanceof Error?x.error.message:c(`common.error`,`Error`)})]})]})}function Xe({value:t,onChange:n}){let{t:r}=Q(),a=A(),o=s({queryKey:Se,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(M,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=Ne(a),s=o.nodeId===t;return e(`button`,{type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(X,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function Ze(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Qe({providerConfig:e,onProviderConfigChange:t}){return i(Xe,{value:Ze(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function $e({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=P.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(Ye,{nodeId:Ze(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 et=new Map([[`ai/apple-node`,Qe],[`ai/managed-model`,$e]]);function tt(e){return et.get(e)??null}c();function nt({kind:e,className:t}){return i(De(e.icon),{className:t,"aria-hidden":!0})}function rt({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>je(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(ce,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(oe,{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(nt,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function it(e){return(e?.sections??[]).flatMap(e=>e.fields)}function at(...e){let t={};for(let n of e)for(let e of it(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function ot(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function st(e,t){return it(e).filter(e=>`required`in e&&e.required===!0&&!ot(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var ct={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 lt(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:We(e,n).vision}}function ut({kind:t,existing:r,onSave:a,onCancel:s,onChangeKind:c,saving:d,error:p}){let{t:m}=Q(),h=A(),[_,v]=o(r?.name??t.label),[y,b]=o(()=>r===null?at(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[x,S]=o(()=>Ue(r)),[C,T]=o(()=>lt(t,r)),[ee,E]=o(!1),D=t.providerWidgets??[],O=D.filter(e=>e.placement===`connection`),k=D.find(e=>e.placement===`model`)??null,j=n(()=>[...I(t.connectionSchema)].some(e=>r?.providerConfig[e]===ve),[r,t.connectionSchema]),P=l({mutationFn:()=>h.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:y,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&T(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:We(t,r).vision}})}}),F=Ge(t,P.data?.ok===!0?P.data.models:null),L=F.find(e=>e.id===C.id),R=We(t,L),te=Ve(t.profileFields),B=He(t.profileFields),V=st(t.connectionSchema,y),H=D.some(e=>(e.requires??[]).some(e=>!ot(y[e]))),U=t.modelCatalog===`fetch`&&k===null,W=it(t.connectionSchema).length>0||O.length>0,G=e=>{T({id:e,supportsVision:We(t,F.find(t=>t.id===e)).vision})},ie=d||_.trim()===``||C.id.trim()===``||V.length>0||H,ae=()=>{a(Ke(t,r,{name:_.trim(),model:C.id.trim(),supportsVision:t.visionEditable?C.supportsVision:!1,common:x,providerConfig:y}))},oe=r===null?m(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):m(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),J=e=>{let n=tt(e);return n===null?i(K,{variant:`warning`,message:m(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})}):i(n,{descriptor:t,providerConfig:y,onProviderConfigChange:b,model:C,onModelChange:T},e)};return i(ce,{open:!0,onClose:s,title:oe,error:p,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[V.length>0&&i(X,{variant:`warning`,children:m(`ai.missingRequired`,`required: {{fields}}`,{fields:V.join(`, `)})}),V.length===0&&H&&i(X,{variant:`warning`,children:m(`ai.completeProvider`,`complete the provider settings`)}),V.length===0&&!H&&C.id.trim()===``&&i(X,{variant:`warning`,children:m(`ai.pickModelFirst`,`pick a model`)}),e(z,{size:`sm`,type:`button`,disabled:ie,onClick:ae,children:[d&&i(M,{className:`h-3.5 w-3.5 animate-spin`}),r===null?m(`ai.createProfile`,`Create profile`):m(`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(nt,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(X,{variant:`neutral`,children:t.addonId}),c!==void 0&&e(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:c,children:[i(w,{className:`h-3.5 w-3.5`}),m(`ai.changeKind`,`Change type`)]})]}),i(pe,{label:m(`ai.name`,`Name`),required:!0,children:i(se,{id:`ai-profile-name`,"aria-label":m(`ai.name`,`Name`),value:_,onChange:e=>v(e.target.value),placeholder:t.label})}),W&&i(q,{headingId:`ai-editor-connection`,title:m(`ai.sectionConnection`,`Connection`),actions:U?e(z,{size:`sm`,variant:`secondary`,type:`button`,disabled:P.isPending,onClick:()=>P.mutate(),"data-testid":`ai-verify-models`,children:[P.isPending?i(M,{className:`h-3.5 w-3.5 animate-spin`}):i(N,{className:`h-3.5 w-3.5`}),m(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[it(t.connectionSchema).length>0&&i(le,{bare:!0,schema:t.connectionSchema,values:y,onChange:b}),O.map(e=>J(e.id)),j&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:m(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)}),P.data?.ok===!0&&i(X,{variant:`success`,"data-testid":`ai-models-found`,children:m(`ai.modelsFound`,`{{count}} models found`,{count:P.data.models.length})}),P.data?.ok===!1&&i(K,{title:m(ct[P.data.code]?.key??`ai.listNetwork`,ct[P.data.code]?.fallback??`Endpoint unreachable`),message:P.data.message}),P.isError&&i(K,{message:P.error instanceof Error?P.error.message:m(`common.error`,`Error`)})]})}),i(q,{headingId:`ai-editor-model`,title:m(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${f} space-y-3`,children:[k===null?e(u,{children:[F.length>0&&i(Y,{id:`ai-model-pick`,"aria-label":m(`ai.selectModel`,`Select a model…`),value:L===void 0?``:L.id,options:[{value:``,label:m(`ai.selectModel`,`Select a model…`)},...F.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&G(e.target.value)}}),i(pe,{label:m(`ai.customModel`,`Model id`),description:m(`ai.customModelHint`,`Pick one from the list, or type any model id the provider accepts.`),required:!0,children:i(se,{id:`ai-model-id`,"aria-label":m(`ai.customModel`,`Model id`),value:C.id,onChange:e=>T({...C,id:e.target.value}),placeholder:F[0]?.id??`model-id`})})]}):J(k.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(C.supportsVision||!t.visionEditable&&R.vision)&&i(X,{variant:`info`,children:m(`ai.featureVision`,`vision`)}),R.tools&&i(X,{variant:`neutral`,children:m(`ai.featureTools`,`tools`)}),R.streaming&&i(X,{variant:`neutral`,children:m(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(pe,{orientation:`horizontal`,label:m(`ai.supportsVision`,`Supports vision`),description:m(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(ne,{checked:C.supportsVision,onCheckedChange:e=>T({...C,supportsVision:e}),"aria-label":m(`ai.supportsVision`,`Supports vision`)})})]})}),te!==null&&i(q,{headingId:`ai-editor-generation`,title:m(`ai.sectionGeneration`,`Generation`),children:i(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:i(le,{bare:!0,schema:te,values:x,onChange:S})})}),(B!==null||t.advancedSchema!==void 0)&&i(re,{expanded:ee,onExpandedChange:E,header:i(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:m(`ai.sectionAdvanced`,`Advanced`)}),children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[B!==null&&i(le,{bare:!0,schema:B,values:x,onChange:S}),t.advancedSchema!==void 0&&i(le,{bare:!0,schema:t.advancedSchema,values:y,onChange:b})]})})]})})}c();function dt(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(nt,{kind:r,className:`h-4 w-4 text-foreground-subtle`})}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block truncate font-medium text-foreground`,children:n.name}),t.testResult?.id===n.id&&i(`span`,{className:`block truncate ${t.testResult.ok?`text-success`:`text-danger`}`,children:t.testResult.text})]})]})}},{key:`kind`,header:t.t(`ai.colKind`,`Kind`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground-muted`,children:t.kindByName.get(e.kind)?.label??e.kind})},{key:`model`,header:t.t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:t.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:e=>e.supportsVision?i(X,{variant:`info`,style:`outline`,children:t.t(`ai.vision`,`vision`)}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:t.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?i(X,{variant:`default`,children:e.providerConfig.nodeId}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:t.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:e=>i(ne,{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(z,{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(M,{className:`h-3.5 w-3.5 animate-spin`}):i(R,{className:`h-3.5 w-3.5`})}),i(z,{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(h,{className:`h-3.5 w-3.5`})}),i(z,{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(_,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function ft(){let{t}=Q(),c=A(),{state:u,openEdit:d,close:p}=J(),m=ae(),[h,_]=o(null),[v,y]=o(null),[b,x]=o(null),C=s({queryKey:ye,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),w=s({queryKey:be,queryFn:async()=>(await c.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),T=()=>{C.refetch()},ee=r(()=>{_(null),x(null),p()},[p]);a(()=>{u.mode===`closed`&&_(null)},[u.mode]);let E=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{ee(),T()},onError:e=>x(e instanceof Error?e.message:t(`ai.saveFailed`,`Save failed`))}),D=l({mutationFn:e=>c.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:T}),O=l({mutationFn:e=>c.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>y({id:t.id,ok:e.ok,text:e.ok?Z.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),k=C.data??[],j=n(()=>w.data??[],[w.data]),M=n(()=>{let e=new Map;for(let t of j)e.set(t.kind,t);return e},[j]),N=u.mode===`edit`?k.find(e=>e.id===u.id)??null:null,P=N===null?null:M.get(N.kind)??null,F=u.mode===`new`&&h===null,I=u.mode===`new`?h:P,L=u.mode===`edit`?N:null,R=I!==null&&(u.mode===`new`||L!==null),te=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`})&&D.mutate(e)};return e(`div`,{className:g,children:[i(pt,{profiles:k}),i(q,{headingId:`ai-profiles-list`,title:t(`ai.profilesList`,`Profiles`),children:C.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-profiles-loading`,children:[i(W,{className:`h-8 w-full`}),i(W,{className:`h-8 w-full`}),i(W,{className:`h-8 w-full`})]}):C.isError?i(`div`,{className:f,children:i(K,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:C.error instanceof Error?C.error.message:t(`common.error`,`Error`),onRetry:()=>void C.refetch()})}):k.length===0?i(H,{icon:S,title:t(`ai.noProfilesTitle`,`No AI profiles yet`),description:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):i(G,{columns:dt({kindByName:M,testResult:v,testingId:O.isPending?O.variables?.id??null:null,t,onToggle:e=>E.mutate({...e,enabled:!e.enabled}),onTest:e=>O.mutate(e),onEdit:e=>{M.has(e.kind)&&(x(null),_(null),d(e.id))},onDelete:e=>void te(e)}),rows:k,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:B})}),F&&i(rt,{kinds:j,onCancel:ee,onPick:e=>{x(null),_(e)}}),R&&I!==null&&i(ut,{kind:I,existing:L,saving:E.isPending,error:b,onSave:e=>E.mutate(e),onCancel:ee,...u.mode===`new`?{onChangeKind:()=>{x(null),_(null)}}:{}})]})}function pt({profiles:t}){let{t:n}=Q(),r=A(),a=s({queryKey:xe,queryFn:()=>r.trpcClient.llm.getDefaults.query({})}),o=l({mutationFn:e=>r.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?n(`ai.defaultVision`,`Default vision profile`):n(`ai.defaultText`,`Default text profile`);return i(q,{headingId:`ai-profiles-defaults`,title:n(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:Te.map(({purpose:r,visionOnly:a})=>{let s=a?t.filter(e=>e.supportsVision):t,l=c(r),d=t.find(e=>e.id===l);return e(`div`,{children:[i(ie,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(Y,{id:`llm-default-${r}`,"aria-label":u(r),value:l,onChange:e=>o.mutate({purpose:r,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:n(`ai.none`,`None`)},...l!==``&&!s.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...s.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:n(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:n(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},r)})})})}c();var mt=5e3;function ht(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function gt(){let{t}=Q(),r=A(),a=s({queryKey:Se,refetchInterval:mt,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(X,{variant:Fe(n),children:n.reachable?n.status?.state??t(`ai.ready`,`ready`):t(`ai.unreachable`,`unreachable`)}),n.status?.downloadProgress!==void 0&&i(X,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:ht(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeatures`,`Features`),render:n=>{let r=Ie(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(X,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(q,{headingId:`ai-runtimes-list`,title:t(`ai.runtimesList`,`Nodes`),children:a.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[i(W,{className:`h-8 w-full`}),i(W,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:f,children:i(K,{title:t(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:a.error instanceof Error?a.error.message:t(`common.error`,`Error`),onRetry:()=>void a.refetch()})}):c.length===0?i(H,{icon:D,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(G,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:B})})}var _t=x(`/addon/ai/test-chat`),vt=x(`/addon/ai/test-chat/chats`),yt=6e5;function bt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),yt)}function xt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function St(e){if(!xt(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 Ct=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function wt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!xt(t))return null;switch(t.kind){case`status`:{let e=Ct.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:St(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*Tt(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=wt(e);t!==null&&(yield t)}a=r.indexOf(`
|
|
3
|
-
`)}}let e=r.trim();if(e.length>0){let t=wt(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Et(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Dt(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Ot(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 kt(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 At(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 jt=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],Mt=360*60*1e3,Nt=40,Pt=160,Ft={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function It(){let{t:c}=Q(),l=A(),[u,d]=o(``),[p,m]=o(``),[h,y]=o(``),[x,S]=o([]),[w,T]=o(null),[E,D]=o(`none`),[O,k]=o(`throwaway`),[j,M]=o(null),[N,P]=o([]),[F,I]=o(null),[L,B]=o(null),V=t(null);a(()=>()=>V.current?.abort(),[]);let H=r(async()=>{let e=await fetch(vt,{credentials:`same-origin`});e.ok&&P((await e.json()).chats??[])},[]);a(()=>{O===`persistent`&&H()},[O,H]);let U=s({queryKey:ye,queryFn:()=>l.trpcClient.llm.listProfiles.query({})}),ne=n(()=>(U.data??[]).filter(e=>e.enabled),[U.data]),W=ne.find(e=>e.id===u)??null,re=L!==null,G=r(async(e,t)=>{let n=new AbortController;V.current=n,I(null);let r=bt(W??{});B({...Ft,firstTokenTimeoutMs:r??0});let i=``,a=null,o,s=null,l=null,d;try{let c=await fetch(_t,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:n.signal,body:JSON.stringify({profileId:u,messages:e,...p.trim()===``?{}:{system:p.trim()},...t===void 0?{}:{attachment:t},...r===void 0?{}:{firstTokenTimeoutMs:r},...O===`persistent`?{persist:!0,...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 Tt(c.body))switch(e.kind){case`status`:B(t=>({...t??Ft,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,B(t=>({...t??Ft,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,B(e=>({...e??Ft,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||I(e instanceof Error?e.message:c(`common.error`,`Error`))}finally{V.current=null,B(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}])},[O,j,W,u,H,p,c]),ae=r(()=>{let e=h.trim();if(e===``||u===``||re)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...w===null?{}:{attachmentLabel:w.label,attachmentKind:w.ref.kind}},n=[...x,t];S(n),y(``);let r=w?.ref;T(null),D(`none`),G(O===`persistent`&&j!==null?[{role:`user`,content:e}]:Et(n),r)},[O,j,h,w,u,G,re,x]),oe=()=>V.current?.abort(),J=()=>{V.current?.abort(),S([]),T(null),y(``),I(null),B(null),M(null)},ce=async e=>{V.current?.abort();let t=await fetch(`${vt}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();M(e),S(Ot(n)),B(null),I(null)};return e(`div`,{className:g,children:[i(q,{headingId:`ai-test-setup`,title:c(`ai.testSetup`,`Setup`),children:e(`div`,{className:`${f} space-y-3`,children:[e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(ie,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:c(`ai.profile`,`Profile`)}),i(Y,{id:`ai-test-profile`,value:u,onChange:e=>d(e.target.value),options:[{value:``,label:c(`ai.selectProfile`,`Select a profile…`)},...ne.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),ne.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(ie,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:c(`ai.systemPrompt`,`System prompt (optional)`)}),i(se,{id:`ai-test-system`,value:p,onChange:e=>m(e.target.value),placeholder:c(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(ue,{label:c(`ai.chatMode`,`Conversation mode`),value:O,options:[{value:`throwaway`,label:c(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:c(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{k(e),e===`throwaway`&&M(null)}}),O===`persistent`&&e(`div`,{className:`space-y-2`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:c(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),e(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:J,children:[i(te,{className:`h-3.5 w-3.5`}),c(`ai.newChat`,`New chat`)]}),N.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:N.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.`)}),W!==null&&!W.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.`)})]})}),F!==null&&i(K,{title:c(`ai.chatFailed`,`The test call failed`),message:F}),e(q,{headingId:`ai-test-conversation`,title:c(`ai.testConversation`,`Conversation`),actions:e(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:x.length===0&&w===null,onClick:J,children:[i(_,{className:`h-3.5 w-3.5`}),c(`ai.clearChat`,`Clear`)]}),children:[i(Lt,{turns:x,live:L}),e(`div`,{className:`${f} space-y-2 border-t border-border`,children:[w!==null&&e(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[w.ref.kind===`snapshot`?i(b,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(v,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:w.label}),i(de,{size:`sm`,variant:`ghost`,type:`button`,icon:ee,"aria-label":c(`ai.removeAttachment`,`Remove attachment`),onClick:()=>T(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(z,{size:`sm`,variant:E===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>D(E===`snapshot`?`none`:`snapshot`),children:[i(b,{className:`h-3.5 w-3.5`}),c(`ai.attachSnapshot`,`Camera snapshot`)]}),e(z,{size:`sm`,variant:E===`track`?`primary`:`outline`,type:`button`,onClick:()=>D(E===`track`?`none`:`track`),children:[i(v,{className:`h-3.5 w-3.5`}),c(`ai.attachTrack`,`Recent track`)]})]}),E===`snapshot`&&i(Bt,{onPick:(e,t)=>{T({ref:{kind:`snapshot`,deviceId:e.id},label:c(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t})}),D(`none`)}}),E===`track`&&i(Ht,{onPick:(e,t)=>{T({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:c(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),D(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(se,{value:h,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ae())},placeholder:c(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":c(`ai.message`,`Message`)}),re?e(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:oe,children:[i(C,{className:`h-3.5 w-3.5`}),c(`ai.stop`,`Stop`)]}):e(z,{size:`sm`,type:`button`,disabled:h.trim()===``||u===``,onClick:ae,children:[i(R,{className:`h-3.5 w-3.5`}),c(`ai.send`,`Send`)]})]})]})]})]})}function Lt({turns:t,live:n}){let{t:r}=Q();return t.length===0&&n===null?i(H,{icon:L,title:r(`ai.chatEmptyTitle`,`No messages yet`),description:r(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):e(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto ${f}`,children:[t.map(e=>i(Rt,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(zt,{attachment:n.mediaSent}),n.text.length>0&&i(Rt,{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(M,{className:`h-3.5 w-3.5 animate-spin`}),At(n.phase,n.firstTokenTimeoutMs)]})]})]})}function Rt({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(zt,{attachment:t.attachment}),t.attachmentLabel!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachmentKind===`track`?i(v,{className:`h-3 w-3`}):i(b,{className:`h-3 w-3`}),t.attachmentLabel]}),t.attachment!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachment.kind===`snapshot`?i(b,{className:`h-3 w-3`}):i(v,{className:`h-3 w-3`}),kt(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 zt({attachment:e}){let{t}=Q(),n=Dt(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 Bt({onPick:e}){let{t}=Q(),n=fe({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(M,{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(Vt,{device:t,onPick:e},t.id))})}function Vt({device:t,onPick:n}){let{t:r}=Q(),a=U(t,`compact`),{src:o}=p(t.id,{width:Pt});return e(`button`,{type:`button`,onClick:()=>n(t,a),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[i(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:o!==null&&i(`img`,{src:o,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),e(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!t.online&&i(X,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function Ht({onPick:t}){let{t:r}=Q(),a=A(),o=fe({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:[...jt,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-Mt,limit:Nt,projection:`slim`})});if(o.isLoading||u.isLoading)return i(M,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=u.data?.tracks??[];return d.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noTracks`,`No track in the last 6 hours.`)}):i(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(n=>e(`button`,{type:`button`,onClick:()=>t(n,l.get(n.deviceId)??String(n.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[i(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:n.label??n.className}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:l.get(n.deviceId)??n.deviceId}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(n.lastSeen).toLocaleTimeString()})]},n.trackId))})}c();var Ut=1440*60*1e3,Wt=[1,7,30,90];function Gt(){let{t}=Q(),r=A(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*Ut},[a]),u=s({queryKey:ye,queryFn:()=>r.trpcClient.llm.listProfiles.query({})}),d=s({queryKey:[...we,a],queryFn:()=>r.trpcClient.llm.getUsage.query({since:l})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),m=n(()=>[{key:`day`,header:t(`ai.colDay`,`Day`),nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:t(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:t(`ai.colProfile`,`Profile`),render:e=>i(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:t(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:t(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:t(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:t(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,t]),h=d.data??[],g=i(`div`,{className:`w-36`,children:i(Y,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:Wt.map(e=>({value:String(e),label:t(`ai.lastDays`,`Last {{days}} days`,{days:e})})),onChange:e=>c(Number(e.target.value))})});return i(q,{headingId:`ai-usage-list`,title:t(`ai.usageList`,`Rollup`),actions:g,children:d.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-usage-loading`,children:[i(W,{className:`h-8 w-full`}),i(W,{className:`h-8 w-full`}),i(W,{className:`h-8 w-full`})]}):d.isError?i(`div`,{className:f,children:i(K,{title:t(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:t(`common.error`,`Error`),onRetry:()=>void d.refetch()})}):h.length===0?i(H,{icon:k,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(G,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:B})})}var Kt=`llm`,qt=[`profiles`,`runtimes`,`usage`,`test`],Jt=[`new`,`edit`];function Yt(e){return qt.some(t=>t===e)}function Xt(){let{t}=Q(),n=V(Kt),[r]=he(),{openNew:a}=J(),o=me(`/system/ai`,{t,isAdmin:!0})??{icon:S,title:t(`system.ai`,`AI`)};if(n!==`present`)return i(_e,{icon:o.icon,title:o.title,children:i(Zt,{presence:n})});let s=r.get(`tab`),c=Yt(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(z,{size:`sm`,type:`button`,"data-testid":`ai-add-profile`,onClick:a,children:[i(d,{className:`h-3.5 w-3.5`}),t(`ai.addProfile`,`Add profile`)]}):void 0;return i(ge,{icon:o.icon,title:o.title,subtitle:l[c],actions:u,defaultSection:`profiles`,sectionsLabel:`${o.title} sections`,sections:[{id:`profiles`,label:t(`ai.tabProfiles`,`Profiles`),content:i(ft,{}),ownedParams:Jt},{id:`runtimes`,label:t(`ai.tabRuntimes`,`Runtimes`),content:i(gt,{})},{id:`usage`,label:t(`ai.tabUsage`,`Usage`),content:i(Gt,{})},{id:`test`,label:t(`ai.tabTest`,`Test`),content:i(It,{})}]})}function Zt({presence:t}){let{t:n}=Q();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(W,{className:`h-8 w-64`}),i(W,{className:`h-40 w-full`})]}):t===`unknown`?i(K,{title:n(`ai.presenceUnknownTitle`,`Could not check whether AI is installed`),message:n(`ai.presenceUnknown`,`The hub did not answer the capability check. Reload the page to try again.`)}):i(H,{icon:S,title:n(`ai.absentTitle`,`AI is not installed`),description:n(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{Xt as AiProfilesPage,Xt as default};
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as p,In as m,Ji as h,Lt as g,Pt as _,Qi as v,Si as y,Tr as b,bi as x,ca as S,jn as C,mi as w,mn as ee,ot as T,pt as E,sr as D,yn as O}from"./player-overlays-nQJCQERn.js";import{Ci as k,Di as A,Gi as j,Ki as M,La as N,Oi as P,Qa as F,Ui as I,Wi as L,_i as R,ai as z,bi as B,ci as te,na as ne,qi as re,si as ie,ta as ae,un as oe}from"./client-CdHPjeIs.js";import{t as V}from"./boxes-D29FuJd_.js";import{n as se,r as ce,t as le}from"./ungroup-D4Nql8ck.js";import{s as ue}from"./video-DEeXGFHo.js";import{$r as H,Aa as de,Ba as fe,Cn as pe,Eo as U,Ho as me,Ir as he,Kt as ge,La as _e,Ma as ve,Na as ye,Nr as be,Ra as xe,Sd as Se,Sn as Ce,Tr as W,Un as we,Zr as Te,Zt as Ee,_o as De,br as Oe,cd as ke,en as Ae,ft as je,gn as Me,id as G,ja as Ne,ld as K,mt as Pe,od as Fe,oi as q,rn as Ie,sd as Le,vt as Re,wd as ze,xo as Be,za as Ve}from"./src-DzfpPZrG.js";import{t as J}from"./i18n-Dgilx0WT.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{P as He,S as Ue,dr as We,gr as Ge,h as Ke,m as qe,mr as Je,or as Ye,ur as X}from"./index-4kmzPYxW.js";import{t as Xe}from"./AdminSectionedPage-ytDsnoAA.js";import{t as Ze}from"./DeviceDoActionFields-GHZBRE4Q.js";import{B as Qe,p as $e,t as et,u as tt}from"./HelperWizard-C9VjtAAi.js";import{t as nt}from"./CompositionBlockEditor-CYmfatQE.js";var rt=`const AUTOMATION_RECIPE =`,it=`// 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 at(e){return e.includes(rt)}function ot(e){let t=e.indexOf(rt);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function st(e){let t=ot(e);if(t===null)return{ok:!1,reason:J.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:J.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=L.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?J.t(`helpers.recipeFromCode.schemaMismatch`):J.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function ct(e){let t=ot(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)}${it}${e.slice(i)}`}u();var lt=6e4;function ut(){let e=Be({projection:`slim`});return r(()=>(e.data??[]).filter(e=>oe(String(e.type))).map(e=>({id:e.id,name:e.name,stableId:e.stableId,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data])}function dt(e){let t=T();return l({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:lt,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function ft(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Z({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function pt(e){let t=dt(e.deviceId);if(t.data!==void 0)return ft(t.data,e.cap).find(t=>t.path===e.fieldPath)}function mt({value:t,devices:n,onChange:r}){let{t:i}=Y(),a=dt(t.deviceId),s=a.data??[],c=ft(s,t.cap);return e(f,{children:[e(`label`,{className:`min-w-[10rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.device`,`Device`)}),o(G,{value:String(t.deviceId),onChange:e=>r({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:i(`automation.fieldPicker.selectADevice`,`Select a device…`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.capability`,`Capability`)}),o(G,{value:t.cap,disabled:t.deviceId===0,onChange:e=>r({...t,cap:e.target.value,fieldPath:``}),options:[{value:``,label:ht(t.deviceId,s.length,a.isLoading)},...s.map(e=>({value:e.cap,label:e.cap}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.field`,`Field`)}),o(G,{value:t.fieldPath,disabled:t.cap===``,onChange:e=>r({...t,fieldPath:e.target.value}),options:[{value:``,label:c.length===0?i(`automation.fieldPicker.noReadableFields`,`No readable fields`):i(`automation.fieldPicker.selectAField`,`Select a field…`)},...c.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function ht(e,t,n){return e===0?J.t(`automation.fieldPicker.pickDeviceFirst`):n?J.t(`automation.fieldPicker.readingDevice`):t===0?J.t(`automation.fieldPicker.noReadableCaps`):J.t(`automation.fieldPicker.selectCap`)}var gt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function _t(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 gt}}function vt(e){switch(e){case`eq`:return J.t(`helpers.recipeParts.op_eq`);case`ne`:return J.t(`helpers.recipeParts.op_ne`);case`gt`:return J.t(`helpers.recipeParts.op_gt`);case`gte`:return J.t(`helpers.recipeParts.op_gte`);case`lt`:return J.t(`helpers.recipeParts.op_lt`);case`lte`:return J.t(`helpers.recipeParts.op_lte`);case`contains`:return J.t(`helpers.recipeParts.op_contains`);default:return J.t(`helpers.recipeParts.op_in`)}}function yt(e){return _t(e).map(e=>({value:e,label:vt(e)}))}function bt(e){switch(e){case`device-state`:return J.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return J.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return J.t(`helpers.recipeParts.trigger_schedule`);default:return J.t(`helpers.recipeParts.trigger_manual`)}}var xt={triggers:[],actions:[]};function St(e){switch(e){case`device-state`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};default:return{kind:`manual`}}}function Ct(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
|
|
4
|
-
`};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function wt(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function Tt(){return{kind:`expression`,expr:``,bindings:{}}}function Et(e,t,n){return e.map((e,r)=>r===t?n:e)}function Dt(e,t){return e.filter((e,n)=>n!==t)}function Ot(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=Dt(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function kt(e,t){return{...e,triggers:[...t]}}function At(e,t){return{...e,actions:[...t]}}var jt=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function Mt({actions:t,devices:n,devicesState:r=`answered`,onChange:i}){let{t:a}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:a(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((s,c)=>e(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(q,{variant:`default`,children:c+1}),e(`label`,{className:`w-40`,children:[o(Z,{children:a(`automation.actionList.step`,`Step`)}),o(G,{value:s.kind,onChange:e=>i(Et(t,c,Ct(Nt(e.target.value)))),options:jt.map(e=>({value:e.value,label:a(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(H,{variant:`ghost`,disabled:c===0,onClick:()=>i(Ot(t,c,c-1)),title:a(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(h,{className:`h-3.5 w-3.5`})}),o(H,{variant:`ghost`,disabled:c===t.length-1,onClick:()=>i(Ot(t,c,c+1)),title:a(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(v,{className:`h-3.5 w-3.5`})}),o(H,{variant:`ghost`,onClick:()=>i(Dt(t,c)),title:a(`automation.actionList.removeThisStep`,`Remove this step`),children:o(g,{className:`h-3.5 w-3.5`})})]})]}),s.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Z,{children:a(`automation.actionList.seconds`,`Seconds`)}),o(K,{type:`number`,min:0,max:300,value:String(s.seconds),onChange:e=>i(Et(t,c,{kind:`wait`,seconds:Number(e.target.value)}))})]}),s.kind===`code`&&e(`label`,{className:`block`,children:[o(Z,{children:a(`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:s.code,spellCheck:!1,onChange:e=>i(Et(t,c,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),s.kind===`cap`&&o(Ft,{action:s,devices:n,devicesState:r,onChange:e=>i(Et(t,c,e))})]},`${s.kind}-${String(c)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(H,{variant:`outline`,onClick:()=>i([...t,Ct(`cap`)]),children:[o(p,{className:`h-4 w-4`}),` `,a(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Nt(e){return jt.find(t=>t.value===e)?.value??`cap`}function Pt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function Ft({action:e,devices:t,devicesState:n,onChange:r}){return o(Ze,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:Pt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function It({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Y(),c=Ht(n,r,i);if(n?.kind===`boolean`)return o(G,{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(G,{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(K,{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(K,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Lt({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),s=Ht(t,n,r);return o(K,{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 Rt(e){return typeof e==`object`}function zt(e){return Rt(e)?e[0]??``:e}function Bt(e){return Rt(e)?e:typeof e==`boolean`?[]:[e]}function Vt(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Ht(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=De({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=N(o)?o:void 0,c=Vt(e?.quantity,s);if(c===void 0)return;let l=a?.display;return Ee({quantity:c,display:l,capName:n})}function Ut({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=pt(a),c=yt(s?.kind),l=t.operator===`in`,u=e=>{r({...t,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},d=e=>{let n=Wt(e,c);r({...t,operator:n,value:n===`in`?Bt(t.value):zt(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(mt,{value:a,devices:n,onChange:u}),e(`label`,{className:`min-w-[8rem]`,children:[o(Z,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(G,{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(Z,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Lt,{value:Bt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(It,{value:zt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function Wt(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Gt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Kt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),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(Z,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(K,{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(qt,{alias:e,source:r,devices:n,onRename:n=>s($t(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(en(t.bindings,e))},e)),e(H,{variant:`ghost`,onClick:()=>s({...t.bindings,[Qt(t.bindings)]:Gt}),children:[o(p,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function qt({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Y(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Xt(r,Yt(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(Z,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(K,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Z,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(G,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Gt),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(Z,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(K,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Jt(e.target.value)})})]}):o(mt,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Zt(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(H,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(g,{className:`h-3.5 w-3.5`})})]})}function Jt(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Yt(e){return e.kind===`global`?e.sourceStableId:``}function Xt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Zt(e,t){return e.find(e=>e.id===t)?.stableId??``}function Qt(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 $t(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function en(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function tn(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:tn(t)?t:{kind:`all`,children:[t]}}function nn(e,t){return t===null||tn(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function rn(e){return nn(e,Q(e))}function an(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?an(e.child,r):null;if(!tn(e))return null;let i=e.children[n];return i===void 0?null:an(i,r)}function on(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=on(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!tn(e))return e;let a=e.children[r];if(a===void 0)return e;let o=on(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 sn(e){return e===null?null:re({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function cn(e){let t=Q(e);return{depth:t.children.length===0?0:j(t),leaves:t.children.length===0?0:M(t),depthLimit:3,leafLimit:32}}function ln(e,t){let n=sn(t);return n===null?{ok:!0,recipe:nn(e,t)}:{ok:!1,reason:n}}function un(e,t){let n=Q(e);return ln(e,{kind:n.kind,children:[...n.children,t]})}function dn(e,t,n){return nn(e,on(Q(e),t,()=>n))}function fn(e,t){return nn(e,on(Q(e),t,()=>null))}function pn(e,t,n){return nn(e,on(Q(e),t,e=>tn(e)?{kind:n,children:e.children}:e))}function mn(e,t){return an(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:ln(e,on(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function hn(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 gn(e,t,n){if(t.length<2)return{ok:!1,reason:J.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:J.t(`helpers.recipeOps.differentGroups`)};let r=hn(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=an(i,r.path);if(a===null||!tn(a))return{ok:!1,reason:J.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:J.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 ln(e,on(i,r.path,()=>d))}function _n(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=an(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return ln(e,on(n,t,()=>r.child));if(!tn(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=hn(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=an(n,i.path);if(a===null||!tn(a))return{ok:!1,reason:J.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 ln(e,on(n,i.path,()=>o))}u();var vn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function yn(e){return e.join(`/`)}function bn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function xn({recipe:t,devices:n,onChange:i}){let{t:a}=Y(),[s,l]=c([]),[u,d]=c(null),f=Q(t),m=cn(t),h=r(()=>s.map(bn),[s]),g=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},_=gn(t,h,`all`),v=gn(t,h,`any`),y=h.length===1?mn(t,h[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:n,selected:new Set(s),onToggleSelect:e=>l(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(e,n)=>i(dn(t,e,n)),onRemove:e=>{l([]),i(fn(t,e))},onSetKind:(e,n)=>i(pn(t,e,n)),onUngroup:e=>g(_n(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(G,{value:f.kind,onChange:e=>i(pn(t,[],Sn(e.target.value))),options:vn.map(e=>({value:e.value,label:a(e.labelKey)}))})}),o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:m.depth,depthLimit:m.depthLimit,leaves:m.leaves,leafLimit:m.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(Cn,{container:f,path:[],handlers:b}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(H,{variant:`outline`,onClick:()=>g(un(t,wt())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(p,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(H,{variant:`outline`,onClick:()=>g(un(t,Tt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(ce,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(H,{variant:`ghost`,disabled:!_.ok,onClick:()=>g(_),title:_.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):_.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(H,{variant:`ghost`,disabled:!v.ok,onClick:()=>g(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(H,{variant:`ghost`,disabled:!y.ok,onClick:()=>g(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),u!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:u})]})}function Sn(e){return e===`any`?`any`:`all`}function Cn({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(wn,{node:e,path:[...t,r],handlers:n},yn([...t,r])))})}function wn({node:t,path:n,handlers:r}){let{t:i}=Y(),a=yn(n),s=o(we,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return tn(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(G,{value:t.kind,onChange:e=>r.onSetKind(n,Sn(e.target.value)),options:vn.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(H,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(le,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(H,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(g,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(Cn,{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(H,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(le,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(wn,{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(Ut,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(Kt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(H,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(g,{className:`h-3.5 w-3.5`})})]})}u();function Tn({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Y(),[l,u]=c(!1),d=Te(),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(H,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?y:x,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(H,{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(ue,{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(Me,{maxHeight:420,children:t})})]})}var En=[`device-state`,`device-event`,`schedule`,`manual`],Dn=Object.values(F).sort((e,t)=>e.localeCompare(t));function On({triggers:t,devices:n,onChange:r}){let{t:i}=Y();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(kn,{trigger:e,devices:n,position:i,onChange:e=>r(Et(t,i,e)),onRemove:()=>r(Dt(t,i))},`${e.kind}-${String(i)}`)),e(H,{variant:`outline`,onClick:()=>r([...t,St(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(p,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function kn({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=Y();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(`label`,{className:`min-w-[13rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.trigger`,`Trigger`)}),o(G,{value:t.kind,onChange:e=>i(St(An(e.target.value))),options:En.map(e=>({value:e,label:bt(e)}))})]}),o(H,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(g,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o(Mn,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(Pn,{trigger:t,devices:n,onChange:i}),t.kind===`schedule`&&e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(K,{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(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`manual`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function An(e){return En.find(t=>t===e)??`manual`}function jn(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 Mn({trigger:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=pt(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(f,{children:[o(mt,{value:a,devices:n,onChange:e=>r(jn(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{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(we,{checked:t.becomes===void 0,onChange:e=>r(jn(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(It,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(jn(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(we,{checked:t.edge===!0,onChange:e=>r(jn(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(Z,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(K,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(jn(a,{...c,forMs:Nn(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(K,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(jn(a,{...c,debounceMs:Nn(e.target.value)}))})]})]})}function Nn(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function Pn({trigger:t,devices:n,onChange:r}){let{t:i}=Y();return e(f,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(G,{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…`)},...Dn.map(e=>({value:e,label:e}))]})]}),e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(G,{value:t.deviceId===void 0?``:String(t.deviceId),onChange:e=>r({kind:`device-event`,category:t.category,...e.target.value===``?{}:{deviceId:Number(e.target.value)}}),options:[{value:``,label:i(`automation.triggerEditor.anyDevice`,`Any device`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]})]})}u();var Fn=`hub`;function In({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Y(),[p,m]=c(t?.name??``),[h,g]=c(()=>rn(n)),[_,v]=c(!1),y=ut(),b=re(h),x=r(()=>Rn(h),[h]),S=r(()=>zn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),C=p.trim()===``,w=C||b!==null||x!==null||S.code===null;return 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(K,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Ln,{step:`1`,title:f(`automation.automationEditor.when`,`When`),subtitle:f(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:o(On,{triggers:h.triggers,devices:y,onChange:e=>g(kt(h,e))})}),o(Ln,{step:`2`,title:f(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:f(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:o(xn,{recipe:h,devices:y,onChange:g})}),o(Ln,{step:`3`,title:f(`automation.automationEditor.then`,`Then`),subtitle:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Mt,{actions:h.actions,devices:y,onChange:e=>g(At(h,e))})}),o(Tn,{code:S.code,error:S.error,canEject:t!==null,ejecting:s,onEject:u}),b!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:b}),b===null&&x!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),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(H,{onClick:()=>{S.code!==null&&l({name:p.trim(),code:S.code,enabled:t?.enabled??!0,placement:Fn})},disabled:i||w,children:[i&&o(D,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(H,{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(ee,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,_?`▾`:`▸`]}),o(H,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),C&&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(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ae,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Ln({step:t,title:n,subtitle:r,children:i}){return e(`section`,{className:`border-l-2 border-border pl-4`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:t}),o(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:n}),o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i]})}function Rn(e){let t=L.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?J.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function zn(e,t){try{return{code:I({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Bn(e){if(!e.enabled)return{tone:`idle`,label:J.t(`helpers.coreBlockStatus.disabled`),detail:J.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:J.t(`helpers.coreBlockStatus.running`),detail:J.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??J.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??J.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??J.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Vn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Hn(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Un(e){let t=e=>{let t=Bn(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 Wn(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Bn(e).tone===`error`).length,n=e.filter(e=>Bn(e).tone===`ok`).length,r=[J.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(J.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(J.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function Gn({block:t,busy:n,confirming:r,logsOpen:i,unreadable:a,onEdit:s,onToggle:c,onToggleLogs:l,onAskDelete:u,onCancelDelete:d,onConfirmDelete:f}){let p=S(),{t:h}=Y(),_=Bn(t),v=ge(t.updatedAt,p);return e(`li`,{className:`flex flex-col gap-2 p-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(q,{variant:Vn(_.tone),children:_.label}),v!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`common.edited`,{when:v})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:_.detail}),a!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:h(`automation.editor.listUnreadable`,{reason:a})})]}),r?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),o(H,{variant:`danger`,onClick:e=>{e.stopPropagation(),f()},disabled:n,children:h(`common.delete`,`Delete`)}),o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),d()},children:h(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s()},disabled:a!==null,title:a===null?h(`common.edit`,`Edit`):h(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(m,{className:`h-4 w-4`})}),e(Fe,{children:[o(ke,{children:o(H,{variant:`ghost`,disabled:!0,title:h(`automation.automationList.runActions`,`Run actions`),children:o(C,{className:`h-4 w-4`})})}),o(Le,{children:h(`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(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:h(`automation.automationList.logs`,`Logs`),children:o(ee,{className:`h-4 w-4`})}),o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c(!t.enabled)},disabled:n,title:t.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`),children:t.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`)}),o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},title:h(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})]}),i&&e(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ae,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Kn({onCreate:t}){let{t:n}=Y();return o(Oe,{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(H,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var qn=[`coreBlocks`,`list`],Jn=5e3;function Yn(e){return e instanceof Error?e.message:String(e)}function Xn({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:f}){let{t:p}=Y(),m=T(),{state:h,openNew:g,openEdit:_,close:v}=je({editKey:`block`,newKey:`new`}),[y,b]=c(null),[x,S]=c(null),[C,w]=c(null),ee=n(null),D=h.mode!==`closed`;s(()=>{u&&(b(null),g(),a?.(null),f?.())},[u,f,a,g]);let O=l({queryKey:qn,refetchInterval:Jn,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),k=()=>{O.refetch()},A=O.data;s(()=>{i===void 0||ee.current===i||A?.find(e=>e.id===i&&at(e.code))!==void 0&&(ee.current=i,_(i),a?.(i))},[i,A,_,a]);let j=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),k()}}),M=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),k()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{S(null),k()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:k}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:ct(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{v(),b(null),k(),t(e.block.id)}}),I=O.data,L=Un((I??[]).filter(e=>at(e.code))),R=I!==void 0&&L.length===0,z=h.mode===`edit`?L.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,B=h.mode===`new`||z===null?null:Hn(L,z),te=B===null?null:st(B.code),ne=j.error===null?M.error===null?F.error===null?null:Yn(F.error):Yn(M.error):Yn(j.error),re=r(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=st(e.code);return o(`ul`,{className:`list-none`,children:o(Gn,{block:e,busy:P.isPending||N.isPending,confirming:x===e.id,logsOpen:C===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),a?.(e.id)},onToggle:t=>P.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>w(C===e.id?null:e.id),onAskDelete:()=>S(e.id),onCancelDelete:()=>S(null),onConfirmDelete:()=>N.mutate(e.id)})})},sortValue:e=>e.name}],[x,C,a,_,N,P,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:I===void 0?``:Wn(L)}),O.error!=null&&o(W,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Yn(O.error),onRetry:k}),R?o(Kn,{onCreate:()=>{b(null),g(),a?.(null)}}):o(Ce,{columns:re,rows:L,rowKey:e=>e.id,pageSize:25,maxBodyHeight:pe,emptyMessage:I===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{b(e),_(e.id),a?.(e.id)}}),o(Pe,{open:D,onClose:()=>{j.reset(),M.reset(),F.reset(),b(null),v(),a?.(null)},title:B===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:B.name}),icon:E,width:`xl`,testId:`automation-editor-panel`,children:o(In,{existing:B,initialRecipe:te!==null&&te.ok?te.recipe:xt,saving:j.isPending||M.isPending,saveError:ne,ejecting:F.isPending,onSave:e=>{B===null?j.mutate(e):M.mutate({blockId:B.id,block:e})},onEject:()=>{B!==null&&F.mutate(B)},onCancel:()=>{j.reset(),M.reset(),F.reset(),b(null),v(),a?.(null)}},B?.id??`new`)}),N.error!=null&&o(W,{message:Yn(N.error)}),P.error!=null&&o(W,{message:Yn(P.error)})]})}u();function Zn({mode:e,onTitle:t}){return o(e===`helper`?Qn:$n,{onTitle:t})}function Qn({onTitle:e}){let{t}=Y(),n=Je(),r=de(),i=me(),a=U({addonId:`composer`}),[l,u]=c(null),d=tr(l,t);return s(()=>{e(d)},[e,d]),o(`div`,{className:`flex flex-col gap-3`,"data-testid":`composition-create-form`,children:o(et,{purpose:`create`,initial:null,start:`template`,saving:r.isPending,onDraftChange:u,onSave:async(e,o)=>{let s=null,c=await $e(e,async(e,c)=>{let{block:l}=await r.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:e}}),u=await nr(l.id,async()=>(await a.refetch()).data??a.data);if(u===null)throw Error(t(`helper.devicePending`));s=u,c!==``&&await i.mutateAsync({deviceId:u,name:c}),o===`open`&&n(Ke(u),{replace:!0})}),l=s;return c.length>0||l===null?{kind:`refused`,lines:rr(c,t)}:{kind:`saved`,deviceId:l}}})})}function $n({onTitle:t}){let{t:n}=Y(),r=S(),i=Je(),a=de(),l=me(),u=U({addonId:`composer`}),[d,f]=c(ne.Sensor),[p,m]=c(ae.TemperatureSensor),[h,g]=c(``),[_,v]=c(null),y=Qe({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(G,{value:d,onChange:e=>{let t=Object.values(ne).find(t=>t===e.target.value);t!==void 0&&f(t)},options:Object.values(ne).map(e=>({value:e,label:ze(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`customize.identity.role`),o(G,{value:p??``,onChange:e=>m(Object.values(ae).find(t=>t===e.target.value)??null),options:[{value:``,label:n(`customize.identity.noRole`)},...Object.values(ae).map(e=>({value:e,label:Se(e,r).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(K,{"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(H,{disabled:y===null||a.isPending,onClick:()=>{y!==null&&er({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(qe(e),{replace:!0}),pending:n(`helper.devicePending`)})},children:n(`compositionEditor.save`)})]})}async function er(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 nr(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 tr(e,t){if(e===null)return t(`helper.newHelper`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);if(e.templateId===`appliance`&&e.appliance!==null)return t(`helper.newTitle.${e.appliance}`);if(e.templateId===`appliance`)return t(`helper.newHelper`);let n=R(e.templateId);return t(n===null?`helper.newHelper`:`helper.newTitle.${n.id}`)}async function nr(e,t){let n=`${B}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}function rr(e,t){return e.length>0?e:tt(t(`helper.devicePending`))}function ir(e){return{state:`answered`,byRef:new Map(e.map(e=>[A(e),e]))}}function ar(e,t){if(e.state!==`unanswered`)return e.byRef.get(A(t))??null}function or(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function sr(e){return P(e).map(e=>e.source)}function cr(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(...sr(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...sr(e))}let r=new Set;return n.filter(e=>{let t=A(e);return r.has(t)?!1:(r.add(t),!0)})}function lr(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:J.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[J.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[J.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??J.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function ur(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return lr(e);case`degraded`:return{tone:`pending`,label:J.t(`helpers.compositionRows.degraded`),reason:n??J.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:J.t(`helpers.compositionRows.failed`),reason:n??J.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:J.t(`helpers.compositionRows.notRunning`),reason:n??J.t(`helpers.compositionRows.notRunningReason`)}}}function dr(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:J.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:J.t(`helpers.compositionRows.unknown`),reason:J.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return ur(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.notReported`),reason:J.t(`helpers.compositionRows.noRecord`,{stored:r})}}function fr(e){return A(e)}function pr(e,t){let n=ar(t,e);return{key:A(e),label:n?n.name:fr(e),presence:or(n),deviceId:n?n.id:null}}function mr(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function hr(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:k(e.block.id),a=A(i),o=cr(e).filter(e=>A(e)!==a).map(e=>pr(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=ar(t,i),l=mr(e),u=dr(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=or(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:fr(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function gr(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function _r(e,t){return gr(e)-gr(t)||e.name.localeCompare(t.name)}function vr(e,t){let n=e.flatMap(e=>{let n=hr(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(_r),customizations:n.filter(e=>e.kind===`customization`).toSorted(_r)}}u();var yr=1e4;function br(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function xr(){let e=Ye();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:br(e.error)})}:ir(e.data)}function Sr(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Cr({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Y(),[i,a]=Ge(),s=_e({},{refetchInterval:yr}),l=xr(),u=je({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,p=d===null?Sr(i.get(`new`),t):null,m=p!==null,[h,g]=c(``),[_,v]=c(null),y=Ne(),b=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},x=s.data;return e(f,{children:[Tr(x,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),confirmingDelete:_,deleting:y.isPending,onAskDelete:v,onCancelDelete:()=>v(null),onConfirmDelete:e=>y.mutate({blockId:e},{onSuccess:()=>{v(null),s.refetch()}})}),o(Pe,{open:m||d!==null,onClose:b,title:m?h||r(p===`blank`?`helper.newComposition`:`helper.newHelper`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:V,width:`xl`,testId:`composed-device-editor`,children:m&&p!==null?o(Zn,{mode:p,onTitle:g},p):d===null?null:o(nt,{blockId:d})}),y.error!=null&&o(W,{message:br(y.error)})]})}function wr(t){return o(Oe,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:J.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[J.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Tr(e,t,n,r,i){if(t!=null&&e===void 0)return o(W,{title:J.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:br(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:J.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return wr(e.reason);let a=t==null?null:br(t);return o(Er,{lists:vr(e.views,r),fleet:r,refreshError:a,handlers:i})}function Er({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Y();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(Dr,{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(Dr,{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 Dr({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Y();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(Ce,{columns:Or(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:pe,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Or(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(kr,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},{key:`state`,header:J.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:Vn(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:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(jr,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>r.confirmingDelete===t.blockId?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`)}),o(H,{variant:`danger`,disabled:r.deleting,onClick:e=>{e.stopPropagation(),r.onConfirmDelete(t.blockId)},children:i(`common.delete`,`Delete`)}),o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),r.onCancelDelete()},children:i(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(H,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(H,{variant:`ghost`,title:i(`common.delete`,`Delete`),"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onAskDelete(t.blockId)},children:o(g,{className:`h-4 w-4`})})]})}),a}function kr({row:t}){let{t:n}=Y();return e(`div`,{className:`space-y-0.5`,children:[o(Ar,{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 Ar({row:e}){let{t}=Y(),n=he(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(We,{to:e.kind===`composed`?Ke(e.reportedDeviceId):qe(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function jr({sources:t}){let{t:n}=Y();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(We,{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 Mr(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 Nr(e){if(Array.isArray(e))return e}function Pr(e,t,n){return(t=Ur(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fr(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Ir(){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 Lr(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 Rr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Lr(Object(n),!0).forEach(function(t){Pr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Lr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function zr(e,t){if(e==null)return{};var n,r,i=Br(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 Br(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Vr(e,t){return Nr(e)||Fr(e,t)||Wr(e,t)||Ir()}function Hr(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 Ur(e){var t=Hr(e,`string`);return typeof t==`symbol`?t:t+``}function Wr(e,t){if(e){if(typeof e==`string`)return Mr(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)?Mr(e,t):void 0}}function Gr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Kr(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 qr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Kr(Object(n),!0).forEach(function(t){Gr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Kr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Jr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Yr(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 Xr(e){return{}.toString.call(e).includes(`Object`)}function Zr(e){return!Object.keys(e).length}function Qr(e){return typeof e==`function`}function $r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ei(e,t){return Xr(t)||ai(`changeType`),Object.keys(t).some(function(t){return!$r(e,t)})&&ai(`changeField`),t}function ti(e){Qr(e)||ai(`selectorType`)}function ni(e){Qr(e)||Xr(e)||ai(`handlerType`),Xr(e)&&Object.values(e).some(function(e){return!Qr(e)})&&ai(`handlersType`)}function ri(e){e||ai(`initialIsRequired`),Xr(e)||ai(`initialType`),Zr(e)&&ai(`initialContent`)}function ii(e,t){throw Error(e[t]||e.default)}var ai=Yr(ii)({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"}),oi={changes:ei,selector:ti,handler:ni,initial:ri};function si(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};oi.initial(e),oi.handler(t);var n={current:e},r=Yr(ui)(n,t),i=Yr(li)(n),a=Yr(oi.changes)(e),o=Yr(ci)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return oi.selector(e),e(n.current)}function c(e){Jr(r,i,a,o)(e)}return[s,c]}function ci(e,t){return Qr(t)?t(e.current):t}function li(e,t){return e.current=qr(qr({},e.current),t),t}function ui(e,t,n){return Qr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var di={create:si},fi={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function pi(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 mi(e){return{}.toString.call(e).includes(`Object`)}function hi(e){return e||yi(`configIsRequired`),mi(e)||yi(`configType`),e.urls?(gi(),{paths:{vs:e.urls.monacoBase}}):e}function gi(){console.warn(vi.deprecation)}function _i(e,t){throw Error(e[t]||e.default)}var vi={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
|
-
`},yi=pi(_i)(vi),bi={config:hi},xi=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Si(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Si(e[n],t[n]))}),Rr(Rr({},e),t)}var Ci={type:`cancelation`,msg:`operation is manually canceled`};function wi(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Ci):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Ti=[`monaco`],Ei=Vr(di.create({config:fi,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),Di=Ei[0],Oi=Ei[1];function ki(e){var t=bi.config(e),n=t.monaco,r=zr(t,Ti);Oi(function(e){return{config:Si(e.config,r),monaco:n}})}function Ai(){var e=Di(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Oi({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),wi(Li);if(window.monaco&&window.monaco.editor)return Fi(window.monaco),e.resolve(window.monaco),wi(Li);xi(ji,Ni)(Pi)}return wi(Li)}function ji(e){return document.body.appendChild(e)}function Mi(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function Ni(e){var t=Di(function(e){return{config:e.config,reject:e.reject}}),n=Mi(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function Pi(){var e=Di(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;Fi(n),e.resolve(n)},function(t){e.reject(t)})}function Fi(e){Di().monaco||Oi({monaco:e})}function Ii(){return Di(function(e){return e.monaco})}var Li=new Promise(function(e,t){return Oi({resolve:e,reject:t})}),Ri={config:ki,init:Ai,__getMonacoInstance:Ii};u();var zi={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},Bi={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function Vi({children:e}){return t.createElement(`div`,{style:Bi.container},e)}var Hi=Vi;function Ui({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...zi.wrapper,width:e,height:n},...s},!r&&t.createElement(Hi,null,i),t.createElement(`div`,{ref:a,style:{...zi.fullWidth,...!r&&zi.hide},className:o}))}var Wi=i(Ui);function Gi(e){s(e,[])}var Ki=Gi;function qi(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=qi;function Ji(){}function Yi(e,t,n,r){return Xi(e,r)||Zi(e,t,n,r)}function Xi(e,t){return e.editor.getModel(Qi(e,t))}function Zi(e,t,n,r){return e.editor.createModel(t,n,r?Qi(e,r):void 0)}function Qi(e,t){return e.Uri.parse(t)}function $i({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=Ji,onMount:S=Ji}){let[C,w]=c(!1),[ee,T]=c(!0),E=n(null),D=n(null),O=n(null),k=n(S),A=n(x),j=n(!1);Ki(()=>{let e=Ri.init();return e.then(e=>(D.current=e)&&T(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>E.current?P():e.cancel()}),$(()=>{if(E.current&&D.current){let t=E.current.getOriginalEditor(),n=Yi(D.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(E.current&&D.current){let e=E.current.getModifiedEditor(),t=Yi(D.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=E.current.getModifiedEditor();e.getOption(D.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{E.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=E.current.getModel();D.current.editor.setModelLanguage(e,o||i||`text`),D.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{D.current?.editor.setTheme(m)},[m],C),$(()=>{E.current?.updateOptions(g)},[g],C);let M=a(()=>{if(!D.current)return;A.current(D.current);let t=Yi(D.current,e||``,o||i||`text`,u||``),n=Yi(D.current,r||``,l||i||`text`,d||``);E.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),N=a(()=>{!j.current&&O.current&&(E.current=D.current.editor.createDiffEditor(O.current,{automaticLayout:!0,...g}),M(),D.current?.editor.setTheme(m),w(!0),j.current=!0)},[g,m,M]);s(()=>{C&&k.current(E.current,D.current)},[C]),s(()=>{!ee&&!C&&N()},[ee,C,N]);function P(){let e=E.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),E.current?.dispose()}return t.createElement(Wi,{width:v,height:_,isEditorReady:C,loading:h,_ref:O,className:y,wrapperProps:b})}i($i);function ea(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var ta=ea,na=new Map;function ra({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=Ji,onMount:C=Ji,onChange:w,onValidate:ee=Ji}){let[T,E]=c(!1),[D,O]=c(!0),k=n(null),A=n(null),j=n(null),M=n(C),N=n(S),P=n(),F=n(o),I=ta(u),L=n(!1),R=n(!1);Ki(()=>{let e=Ri.init();return e.then(e=>(k.current=e)&&O(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>A.current?B():e.cancel()}),$(()=>{let t=Yi(k.current,e||o||``,r||l||``,u||i||``);t!==A.current?.getModel()&&(g&&na.set(I,A.current?.saveViewState()),A.current?.setModel(t),g&&A.current?.restoreViewState(na.get(u)))},[u],T),$(()=>{A.current?.updateOptions(m)},[m],T),$(()=>{!A.current||o===void 0||(A.current.getOption(k.current.editor.EditorOption.readOnly)?A.current.setValue(o):o!==A.current.getValue()&&(R.current=!0,A.current.executeEdits(``,[{range:A.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),A.current.pushUndoStop(),R.current=!1))},[o],T),$(()=>{let e=A.current?.getModel();e&&l&&k.current?.editor.setModelLanguage(e,l)},[l],T),$(()=>{f!==void 0&&A.current?.revealLine(f)},[f],T),$(()=>{k.current?.editor.setTheme(d)},[d],T);let z=a(()=>{if(!(!j.current||!k.current)&&!L.current){N.current(k.current);let t=u||i,n=Yi(k.current,o||e||``,r||l||``,t||``);A.current=k.current?.editor.create(j.current,{model:n,automaticLayout:!0,...m},h),g&&A.current.restoreViewState(na.get(t)),k.current.editor.setTheme(d),f!==void 0&&A.current.revealLine(f),E(!0),L.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{T&&M.current(A.current,k.current)},[T]),s(()=>{!D&&!T&&z()},[D,T,z]),F.current=o,s(()=>{T&&w&&(P.current?.dispose(),P.current=A.current?.onDidChangeModelContent(e=>{R.current||w(A.current.getValue(),e)}))},[T,w]),s(()=>{if(T){let e=k.current.editor.onDidChangeMarkers(e=>{let t=A.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=k.current.editor.getModelMarkers({resource:t});ee?.(e)}});return()=>{e?.dispose()}}return()=>{}},[T,ee]);function B(){P.current?.dispose(),_?g&&na.set(u,A.current.saveViewState()):A.current.getModel()?.dispose(),A.current.dispose()}return t.createElement(Wi,{width:v,height:y,isEditorReady:T,loading:p,_ref:j,className:b,wrapperProps:x})}var ia=i(ra);u();function aa(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 oa={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function sa(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...oa}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function ca({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,sa(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&&sa(e,r)},[r]),o(ia,{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 la(e){return e.some(e=>e.severity>=8)}var ua=[{id:`blank`,name:`Blank script`,get description(){return J.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 da(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 fa=ua.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 pa({existing:e,dirty:t,saving:n,restarting:r}){return e===null?J.t(`helpers.restartGate.saveFirstNoProcess`):n?J.t(`helpers.restartGate.saving`):r?J.t(`helpers.restartGate.restarting`):t?J.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:J.t(`helpers.restartGate.disabled`)}u();var ma=5e3;function ha(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 ga({blockId:t}){let{t:n}=Y(),i=z(t),a=Be({addonId:i,projection:`slim`},{refetchInterval:ma}),s=r(()=>ha(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(D,{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(X,{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(X,{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(We,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(be,{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 _a(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 va(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 ya(e){switch(e){case`refresh-channel-catalog`:return J.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return J.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return J.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return J.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return J.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return J.t(`build.scriptSettingsPanel.enableUnifi`)}}function ba(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function xa(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Sa(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=ba(e);n!==null&&(t[n]=xa(e))}return t}function Ca(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function wa({blockId:t}){let{t:n}=Y(),i=T(),s=ve({blockId:t},{retry:!1}),l=ye({blockId:t},{refetchInterval:1e4,retry:!1}),u=fe({onSuccess:()=>{l.refetch()}}),d=xe(),f=Ve(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=Ca(l.data)?l.data:null,S=r(()=>x===null?{}:Sa(x),[x]),C=p??S,w=a(e=>{m(e)},[]),ee=p!==null,E=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]),O=a(async(e,n)=>{if(_a(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:va(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(ya(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(D,{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(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(H,{size:`sm`,variant:`primary`,onClick:E,disabled:!ee||u.isPending||y,children:[u.isPending&&o(D,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(He,{schema:x,values:C,onChange:w,onAction:O}),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 Ta=`hub`;function Ea({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:p,onSave:m,onCancel:h}){let{t:g}=Y(),v=T(),y=Te(),{resolvedMode:b}=Ie(),x=te({code:t?.code??fa,files:t?.files,entry:t?.entry}),[S,C]=c(t?.name??``),[E,k]=c(x.files),[A,j]=c(x.entry),[M,N]=c(x.entry),[P,F]=c(t?.placement??Ta),[I,L]=c(t?.integrationId??``),[R,B]=c([]),[ne,re]=c(!1),[ie,ae]=c(`blank`),[oe,V]=c(null),[se,ce]=c(``),le=E[M]??``,ue=e=>{k(t=>({...t,[M]:e}))},de=Object.keys(E).toSorted(),fe=ua.length>1,pe=r(()=>[...n?.libs??[],...aa(E,M)],[n?.libs,E,M]),U=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:E,entry:A})}),me=r(()=>R.filter(e=>e.severity>=8),[R]),he=la(R),ge=S.trim()===``,_e=t===null?null:te(t),ve=t===null||_e===null||JSON.stringify(E)!==JSON.stringify(_e.files)||A!==_e.entry||S.trim()!==t.name||P!==t.placement||(I.trim()===``?void 0:I.trim())!==t.integrationId,ye=()=>{U.reset(),m({name:S.trim(),files:E,entry:A,enabled:t?.enabled??!0,placement:P,...I.trim()===``?{}:{integrationId:I.trim()}})},be=()=>{let e=da(Object.keys(E));k(t=>({...t,[e]:``})),N(e),V(e),ce(e)},xe=e=>{V(e),ce(e)},Se=()=>{if(oe===null)return;let e=oe,t=se.trim();if(V(null),!(t===``||t===e)){if(E[t]!==void 0){N(t);return}k(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),A===e&&j(t),N(t)}},Ce=async e=>{let t=ua.find(t=>t.id===e);if(t===void 0)return;let n=ua.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(E)===JSON.stringify(n.files)&&A===n.entry)&&!await y({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`})||(ae(e),k({...t.files}),j(t.entry),N(t.entry),(S.trim()===``||ie===`blank`)&&C(t.id===`blank`?``:t.name))},W=t===null?null:Bn(t),we=pa({existing:t,dirty:ve,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[W!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(q,{variant:Vn(W.tone),children:W.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(K,{className:`mt-1`,value:S,onChange:e=>C(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(K,{className:`mt-1`,value:I,onChange:e=>L(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&fe&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ie,onChange:e=>void Ce(e.target.value),"data-testid":`script-example-select`,children:ua.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(Re,{selectedNodeId:P,onSelect:F,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),P!==Ta&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(_,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(X,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[de.map(t=>oe===t?o(K,{value:se,onChange:e=>ce(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),V(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===M?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>N(t),onDoubleClick:()=>xe(t),title:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===A?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:be,"data-testid":`script-file-add`,children:g(`build.blockEditor.file`,`+ file`)}),M!==A&&o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>j(M),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(ca,{value:le,onChange:ue,path:`file:///${M}`,extraLibs:pe,onDiagnostics:B,dark:b===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:g(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),me.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:g(`build.blockEditor.errorsCannotSave`,{count:me.length})}),me.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:g(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),me.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:me.length-5})})]}),U.data!==void 0&&(U.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(w,{className:`h-3.5 w-3.5`}),` `,g(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[U.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(U.data.line)})}),U.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),U.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[g(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,Da(U.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(wa,{blockId:t.id}),o(ga,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(H,{variant:`outline`,onClick:()=>U.mutate(),disabled:U.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[U.isPending&&o(D,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(H,{onClick:ye,disabled:a||he||ge,children:[a&&o(D,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(H,{variant:`outline`,onClick:()=>p?.(),disabled:we!==null||p===void 0,title:we??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(O,{className:`h-4 w-4 animate-spin`}):o(O,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(H,{variant:`ghost`,onClick:()=>re(!ne),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[o(ee,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,ne?`▾`:`▸`]}),o(H,{variant:`ghost`,onClick:h,disabled:a,children:g(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[g(`build.blockEditor.errorsCount`,{count:me.length}),ve&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),ge&&o(q,{variant:`warning`,children:g(`build.blockEditor.nameRequired`,`Name required`)})]}),ne&&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(f,{children:o(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Ae,{addonId:z(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Da(e){return e instanceof Error?e.message:String(e)}u();var Oa=[`coreBlocks`,`list`],ka=[`coreBlocks`,`getTypeDefs`],Aa=5e3;function ja(e){return e instanceof Error?e.message:String(e)}function Ma({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let f=S(),{t:p}=Y(),m=T(),{state:h,openNew:_,openEdit:v,close:y}=je({editKey:`block`,newKey:`new`}),[b,x]=c(null),[C,w]=c(null),[E,D]=c(null),k=l({queryKey:Oa,refetchInterval:Aa,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=h.mode!==`closed`,j=l({queryKey:ka,enabled:A,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),M=()=>{k.refetch()},N=n(null),P=k.data;s(()=>{t===void 0||N.current===t||P?.find(e=>e.id===t&&ie(e)===`code`)!==void 0&&(N.current=t,v(t),i?.(t))},[t,P,v,i]),s(()=>{a&&(x(null),_(),i?.(null),u?.())},[a,u,i,_]);let F=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),v(e.block.id),i?.(e.block.id),M()}}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),v(e.block.id),i?.(e.block.id),M()}}),L=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),M()}}),R=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:M}),B=d({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:M}),te=Un((k.data??[]).filter(e=>ie(e)===`code`)),ne=k.data!==void 0&&te.length===0,re=F.isPending||I.isPending,ae=F.error===null?I.error===null?null:ja(I.error):ja(F.error),oe=h.mode===`edit`?te.find(e=>e.id===h.id)??(b!==null&&b.id===h.id?b:null):null,V=h.mode===`new`||oe===null?null:Hn(te,oe),ce=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=Bn(t),r=ge(t.updatedAt,f);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:Vn(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}),E===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(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ae,{addonId:z(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=R.isPending||L.isPending,r=B.isPending&&B.variables===t.id;return C===t.id?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),o(H,{variant:`danger`,onClick:()=>L.mutate(t.id),disabled:n,children:p(`common.delete`,`Delete`)}),o(H,{variant:`ghost`,onClick:()=>w(null),children:p(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(H,{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(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(O,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),D(E===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(ee,{className:`h-4 w-4`})}),o(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),R.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(H,{variant:`ghost`,onClick:e=>{e.stopPropagation(),w(t.id)},title:p(`common.delete`,`Delete`),children:o(g,{className:`h-4 w-4`})})]})}}],[C,E,i,v,L,B.isPending,B.variables,R,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:k.data===void 0?``:Wn(te)}),k.error!=null&&o(W,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:ja(k.error),onRetry:M}),o(Ce,{columns:ce,rows:te,rowKey:e=>e.id,pageSize:25,maxBodyHeight:pe,emptyMessage:ne?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):k.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(Pe,{open:A,onClose:()=>{F.reset(),I.reset(),B.reset(),x(null),y(),i?.(null)},title:V===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:se,width:`xl`,testId:`script-editor-panel`,children:o(Ea,{existing:V,typeDefs:j.data,typeDefsLoading:j.isLoading,saving:re,saveError:ae,restarting:B.isPending,restartError:B.error===null?null:ja(B.error),onRestart:V===null?void 0:()=>B.mutate(V.id),onSave:e=>{let t=V;t===null?F.mutate(e):I.mutate({blockId:t.id,block:e})},onCancel:()=>{F.reset(),I.reset(),B.reset(),x(null),y(),i?.(null)}})}),L.error!=null&&o(W,{message:ja(L.error)}),R.error!=null&&o(W,{message:ja(R.error)}),B.error!=null&&o(W,{message:ja(B.error)})]})}var Na=[`automations`,`scripts`,`custom-device`];function Pa(e){return e!==null&&Na.some(t=>t===e)}var Fa=[`coreBlocks`,`list`,`build-counts`],Ia=[`block`,`create`,`new`];function La(e){return e.filter(e=>ie(e)===`code`).length}function Ra(e){return e.filter(e=>at(e.code)).length}function za(e,t){return t===null?e:`${e} (${String(t)})`}function Ba(){let{t}=Y(),n=T(),[r,i]=Ge(),a=r.get(`tab`),s=Pa(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:Fa,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:La(u),f=u===void 0?null:Ra(u),m=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),h=m.data?.state===`loaded`?m.data.views.length:null,g=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})},_=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})},v=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})},y=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},x=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})},S=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},C=s===`automations`?`New automation`:`New script`,w=Ue(`/build`,{t,isAdmin:!0})??{icon:b,title:t(`nav.build`,`Build-your-self`)};return o(Xe,{icon:w.icon,title:w.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${w.title} sections`,fill:!0,actions:s===`custom-device`?e(`div`,{className:`flex flex-wrap gap-2`,children:[e(H,{type:`button`,variant:`outline`,onClick:()=>x(`blank`),"data-testid":`build-new-composition`,children:[o(p,{className:`h-4 w-4`}),` `,t(`helper.newComposition`)]}),e(H,{type:`button`,onClick:()=>x(`helper`),"data-testid":`build-new-helper`,children:[o(p,{className:`h-4 w-4`}),` `,t(`helper.newHelper`)]})]}):e(H,{type:`button`,onClick:y,"data-testid":`build-new`,children:[o(p,{className:`h-4 w-4`}),` `,C]}),sections:[{id:`automations`,label:za(`Automations`,f),ownedParams:Ia,content:o(Xn,{onOpenScripts:g,initialBlockId:s===`automations`?r.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:s===`automations`&&c,onCreateConsumed:S})},{id:`scripts`,label:za(`Scripts`,d),ownedParams:Ia,content:o(Ma,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:v,createRequested:s===`scripts`&&c,onCreateConsumed:S})},{id:`custom-device`,label:za(`Custom Device`,h),ownedParams:Ia,content:o(Cr,{createRequested:s===`custom-device`&&c,onCreateConsumed:S})}]})}export{Ba as BuildPage};
|