@camstack/addon-admin-ui 1.2.473 → 1.2.474

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/assets/{AddonAssetIcon-DmwaRNVP.js → AddonAssetIcon-DNTjc2uq.js} +1 -1
  2. package/dist/assets/Addons-CPaW6tLw.js +4 -0
  3. package/dist/assets/{AdminPage-B-1YjUaD.js → AdminPage-B4QlIiKh.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-DCas2jUy.js → AdminSectionedPage-BIoU14zn.js} +1 -1
  5. package/dist/assets/AiProfiles-FpbSg3kP.js +3 -0
  6. package/dist/assets/{BrokerForm-x5UJk9ci.js → BrokerForm-CU4X3nL7.js} +1 -1
  7. package/dist/assets/Build-C2qKCizt.js +40 -0
  8. package/dist/assets/Calendars-BRTmlFIt.js +1 -0
  9. package/dist/assets/{Cluster-DaFXU71S.js → Cluster-BvxOiIZ7.js} +1 -1
  10. package/dist/assets/CompositionCreateForm-DCUy3waQ.js +1 -0
  11. package/dist/assets/{CompositionEditorPage-B_ERZESY.js → CompositionEditorPage-syg6YTJF.js} +1 -1
  12. package/dist/assets/Data-VG64mGmK.js +2 -0
  13. package/dist/assets/DeviceDetail-tZevLHDV.js +2 -0
  14. package/dist/assets/{DeviceDoActionFields-BETAvCYe.js → DeviceDoActionFields-BmEM1vFn.js} +1 -1
  15. package/dist/assets/{Devices-C1DTPVnZ.js → Devices-B-b5cUYn.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-Bw6TIHbX.js → EmbedPlayerPage-CI3OOtRg.js} +1 -1
  17. package/dist/assets/HelperWizard-4637ctxc.js +2 -0
  18. package/dist/assets/History-BJcol9mz.js +1 -0
  19. package/dist/assets/Identity-CjEfAbi1.js +1 -0
  20. package/dist/assets/IntegrationDetail-DLncDXox.js +1 -0
  21. package/dist/assets/{IntegrationHub-DahW4X5K.js → IntegrationHub-B1soAFk9.js} +1 -1
  22. package/dist/assets/Integrations-DtQc1eDp.js +1 -0
  23. package/dist/assets/Integrations-xxkUIJ67.js +1 -0
  24. package/dist/assets/{Library-gaMbp-Fr.js → Library-DbHcY62a.js} +1 -1
  25. package/dist/assets/Locations-CfYQkG2R.js +3 -0
  26. package/dist/assets/{Logs-CtH4NMql.js → Logs-CMYLVX21.js} +1 -1
  27. package/dist/assets/{MaskShapeCanvas-Byp9XgNC.js → MaskShapeCanvas-BnMDm4ev.js} +1 -1
  28. package/dist/assets/{MotionZonesSettings-C35beRsS.js → MotionZonesSettings-DKqDt4OB.js} +1 -1
  29. package/dist/assets/{MyAccess-Dj5hcaLN.js → MyAccess-CjUd-G8J.js} +1 -1
  30. package/dist/assets/{Network-D-v-cA54.js → Network-Dudx2Fcg.js} +1 -1
  31. package/dist/assets/{NodeAddonsSettingsPanel-CW_M8Xge.js → NodeAddonsSettingsPanel-9_q0f4bE.js} +1 -1
  32. package/dist/assets/Notifications-DE5Wtais.js +1 -0
  33. package/dist/assets/{Pipeline-C85hColk.js → Pipeline-r8TFI-Fa.js} +1 -1
  34. package/dist/assets/{PrivacyMaskSettings-SPaH91xV.js → PrivacyMaskSettings-DZ2mewnu.js} +1 -1
  35. package/dist/assets/Recordings-BrpMcrZw.js +1 -0
  36. package/dist/assets/{ScanNetworkModal-ClvLQ-ol.js → ScanNetworkModal-DhahS87x.js} +1 -1
  37. package/dist/assets/{SceneMonitorEditor-BvqnlZ2i.js → SceneMonitorEditor-CH7F9rZo.js} +1 -1
  38. package/dist/assets/SessionsList-BbD9LSdf.js +2 -0
  39. package/dist/assets/{Showroom-jPZcBd6K.js → Showroom-BX1LrKmF.js} +1 -1
  40. package/dist/assets/{System-B5Ny1ozj.js → System-CvErxLx3.js} +1 -1
  41. package/dist/assets/{Terminal-DYLSrpsL.js → Terminal-COEKXIAj.js} +3 -3
  42. package/dist/assets/{Viewer-GqkHpMmf.js → Viewer-BW9JCbu_.js} +1 -1
  43. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BlUFdak1.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-B4AOEb1R.js} +1 -1
  44. package/dist/assets/{addon-icons-context-BUi2hqSA.js → addon-icons-context-Bus8wGvh.js} +1 -1
  45. package/dist/assets/{archive-Bs9ToeWK.js → archive-BTmhmQQp.js} +1 -1
  46. package/dist/assets/{assignment-candidates-e6s6JtrJ.js → assignment-candidates-C4DL_rSh.js} +1 -1
  47. package/dist/assets/{authed-media-BWhmwHt2.js → authed-media-C8FW8mvx.js} +1 -1
  48. package/dist/assets/{bell-off-CosUv2Rj.js → bell-off-DsAerV0u.js} +1 -1
  49. package/dist/assets/{board-model-BtdRuNBI.js → board-model-CnpzmN9f.js} +1 -1
  50. package/dist/assets/{boxes-CA7Sh4JV.js → boxes-DT6bkxUA.js} +1 -1
  51. package/dist/assets/circle-slash-BFwh1Zbg.js +1 -0
  52. package/dist/assets/{client-DIBstlq5.js → client-BbPYrWg7.js} +14 -14
  53. package/dist/assets/{cloud-upload-olZ1M2tJ.js → cloud-upload-iGrXLaxX.js} +1 -1
  54. package/dist/assets/crop-FX76GBoF.js +1 -0
  55. package/dist/assets/{device-integration-icon-656UPgnE.js → device-integration-icon-XVdZ9pIS.js} +1 -1
  56. package/dist/assets/device-picker-model-B5MjkWnS.js +1 -0
  57. package/dist/assets/{dist-G4Cxki3p.js → dist-Bd_kB5yG.js} +1 -1
  58. package/dist/assets/{eraser-CABcfjb2.js → eraser-L4lKjV-e.js} +1 -1
  59. package/dist/assets/{format-BYDOzxSv.js → format-BTMQLjGl.js} +1 -1
  60. package/dist/assets/{hard-drive-download-ClcxzAVo.js → hard-drive-download-cfcxCkzE.js} +1 -1
  61. package/dist/assets/{hostInit-DXWqqcl-.js → hostInit-BBq0iCeL.js} +1 -1
  62. package/dist/assets/{i18n-D3CF2V_j.js → i18n-BO6gCPcC.js} +1 -1
  63. package/dist/assets/{icons-BmpL14Dq.js → icons-Cv_Dcjty.js} +1 -1
  64. package/dist/assets/{index-Cskol4XA.js → index-C8XwyZGE.js} +3 -3
  65. package/dist/assets/{key-CURebvKJ.js → key-e3_N15fG.js} +1 -1
  66. package/dist/assets/{key-round-BTmR8Ca5.js → key-round-x0Ig1rd2.js} +1 -1
  67. package/dist/assets/{layers-BCzFIxnd.js → layers-T4HoHbdn.js} +1 -1
  68. package/dist/assets/{linked-devices-model-Uzvgx-iv.js → linked-devices-model-CObOrxIk.js} +1 -1
  69. package/dist/assets/{list-ordered-BpmnL-Ze.js → list-ordered-I4dBVzRf.js} +1 -1
  70. package/dist/assets/{location-owned-usage-ChLz8liX.js → location-owned-usage-D17U3uzz.js} +1 -1
  71. package/dist/assets/{log-in-hW2oGppQ.js → log-in-B1D0wNrs.js} +1 -1
  72. package/dist/assets/{memory-stick-DJEnjf6G.js → memory-stick-DYS3v1CU.js} +1 -1
  73. package/dist/assets/{message-square-plus-CZ2oQ3Vr.js → message-square-plus-D64e2l9L.js} +1 -1
  74. package/dist/assets/{mf-entry-bootstrap-0-0c9682e8.js → mf-entry-bootstrap-0-c6a36508.js} +2 -2
  75. package/dist/assets/{mic-off-KFKpp3gz.js → mic-off-hTqpFTxe.js} +1 -1
  76. package/dist/assets/{monitor-off-Cn5TAK6N.js → monitor-off-Bj-JQM7b.js} +1 -1
  77. package/dist/assets/{monitor-smartphone-Jvu4UJGi.js → monitor-smartphone-CyTSF3mW.js} +1 -1
  78. package/dist/assets/mount-B5MjkWnS.js +1 -0
  79. package/dist/assets/{player-overlays-B_ZfVBiA.js → player-overlays-CvKnZb5M.js} +1 -1
  80. package/dist/assets/{recycle-BDm5DJUQ.js → recycle-BLx8Nd-6.js} +1 -1
  81. package/dist/assets/remoteEntry-DBUvkI6n.js +1 -0
  82. package/dist/assets/{scan-eye-C7MTwcP4.js → scan-eye-CrOhuNWQ.js} +1 -1
  83. package/dist/assets/{scissors-BQnPBcjw.js → scissors-C6HYvaxr.js} +1 -1
  84. package/dist/assets/{search-x-DEyDFvNT.js → search-x-C8eiZDQW.js} +1 -1
  85. package/dist/assets/{send-B3qo7thK.js → send-CNzJmniJ.js} +1 -1
  86. package/dist/assets/{settings-2-C0X8oPpn.js → settings-2-Ccb0AMXU.js} +1 -1
  87. package/dist/assets/{speaker-pcRBhz9y.js → speaker-BsE4hqmg.js} +1 -1
  88. package/dist/assets/src-DKc14e9G.js +67 -0
  89. package/dist/assets/step-inspector-model-BeIQx3rW.js +1 -0
  90. package/dist/assets/{timer-reset-CCky8ePa.js → timer-reset-Tun-zcxs.js} +1 -1
  91. package/dist/assets/{ungroup-iaoDNnXe.js → ungroup-BdxY8QDj.js} +1 -1
  92. package/dist/assets/{unlink-8OutaYJL.js → unlink-BVODHZoC.js} +1 -1
  93. package/dist/assets/{usb-DL2I9kcC.js → usb-i2JzfEjl.js} +1 -1
  94. package/dist/assets/{use-scenes-feed-4lpCQaI1.js → use-scenes-feed-CUQxwk-v.js} +1 -1
  95. package/dist/assets/{use-stationary-objects-P_tT9TQq.js → use-stationary-objects-Cqmb4Ymg.js} +1 -1
  96. package/dist/assets/useEventInvalidation-B5MjkWnS.js +1 -0
  97. package/dist/assets/{useNodeUrlSelection-CiraZrDp.js → useNodeUrlSelection-rnUQLTfb.js} +1 -1
  98. package/dist/assets/user-round-BkFCDGbj.js +1 -0
  99. package/dist/assets/{user-x-DYn__Nok.js → user-x-CIq05NC_.js} +1 -1
  100. package/dist/assets/{video-BcVXMTle.js → video-CJw8Jnle.js} +1 -1
  101. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CXWzeD1i.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BWKP-Fxc.js} +2 -2
  102. package/dist/index.html +9 -9
  103. package/dist/server/addon.js +1 -1
  104. package/package.json +1 -1
  105. package/dist/assets/Addons-Ch5dCeth.js +0 -4
  106. package/dist/assets/AiProfiles-ChvfjsXv.js +0 -3
  107. package/dist/assets/Build-CUVwS9XA.js +0 -40
  108. package/dist/assets/Calendars-BMLzvBb6.js +0 -1
  109. package/dist/assets/CompositionCreateForm-BxelZLtf.js +0 -1
  110. package/dist/assets/Data-CMHfgMXt.js +0 -2
  111. package/dist/assets/DeviceDetail-CAtDRoZZ.js +0 -2
  112. package/dist/assets/History-BXTYUTxj.js +0 -1
  113. package/dist/assets/Identity-DTOixhZS.js +0 -1
  114. package/dist/assets/IntegrationDetail-CnINeomo.js +0 -1
  115. package/dist/assets/Integrations-Dex6zRMx.js +0 -1
  116. package/dist/assets/Integrations-HN2iCOqd.js +0 -1
  117. package/dist/assets/Locations-haT1EJbm.js +0 -3
  118. package/dist/assets/Notifications-r5w4Ne2O.js +0 -1
  119. package/dist/assets/Recordings-ZYwRaSrC.js +0 -1
  120. package/dist/assets/SessionsList-BCDysQfs.js +0 -2
  121. package/dist/assets/circle-slash-0Ca1BMK0.js +0 -1
  122. package/dist/assets/crop-BZM3UFyT.js +0 -1
  123. package/dist/assets/device-picker-model-yjEyEWyS.js +0 -1
  124. package/dist/assets/event-targets-CHOtaC2B.js +0 -2
  125. package/dist/assets/mount-yjEyEWyS.js +0 -1
  126. package/dist/assets/remoteEntry-7WZh94sn.js +0 -1
  127. package/dist/assets/src-BVr0SnD-.js +0 -67
  128. package/dist/assets/step-inspector-model-DjRSZkVO.js +0 -1
  129. package/dist/assets/useEventInvalidation-yjEyEWyS.js +0 -1
  130. package/dist/assets/user-round-4ZziAKb6.js +0 -1
@@ -1 +1 @@
1
- import{$ as e,J as t,x as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{n as r}from"./addon-icons-context-BUi2hqSA.js";e();var i={md:{tile:`h-10 w-10 rounded-lg`,img:`h-7 w-7 rounded-md p-1`,fallback:`h-5 w-5`},sm:{tile:`h-5 w-5 rounded`,img:`h-5 w-5 rounded p-0.5`,fallback:`h-3.5 w-3.5`}};function a({addonId:e,fallback:a,tileClassName:o,size:s=`md`}){let[c,l]=t(!1),u=r(e),d=i[s];return n(`div`,{className:`${d.tile} flex items-center justify-center shrink-0 ${o}`,children:c||!u?n(a,{className:d.fallback,"aria-hidden":!0}):n(`img`,{src:u,alt:``,className:`${d.img} bg-white ring-1 ring-black/5`,onError:()=>l(!0)})})}export{a as t};
1
+ import{$ as e,J as t,x as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{n as r}from"./addon-icons-context-Bus8wGvh.js";e();var i={md:{tile:`h-10 w-10 rounded-lg`,img:`h-7 w-7 rounded-md p-1`,fallback:`h-5 w-5`},sm:{tile:`h-5 w-5 rounded`,img:`h-5 w-5 rounded p-0.5`,fallback:`h-3.5 w-3.5`}};function a({addonId:e,fallback:a,tileClassName:o,size:s=`md`}){let[c,l]=t(!1),u=r(e),d=i[s];return n(`div`,{className:`${d.tile} flex items-center justify-center shrink-0 ${o}`,children:c||!u?n(a,{className:d.fallback,"aria-hidden":!0}):n(`img`,{src:u,alt:``,className:`${d.img} bg-white ring-1 ring-black/5`,onError:()=>l(!0)})})}export{a as t};
@@ -0,0 +1,4 @@
1
+ import{$ as e,B as t,G as n,J as r,L as i,S as a,b as o,o as s,q as c,x as l,z as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{It as d,Nt as f,Ot as p,Q as m,Rn as h,Si as g,Tn as _,Wr as v,ai as y,bn as b,dt as x,fn as S,kn as C,or as w,pi as ee,pn as te,tn as T,un as E,vi as ne,xi as re}from"./player-overlays-CvKnZb5M.js";import{Da as D}from"./client-BbPYrWg7.js";import{i as O,l as ie}from"./video-CJw8Jnle.js";import{Ai as k,Ci as A,Ei as ae,Fi as oe,Gr as j,Hr as M,Ni as se,Oi as ce,Ot as le,Pi as N,Qr as P,Si as F,Ti as I,Ur as ue,Zs as L,Zu as de,_i as R,_r as z,bi as B,en as fe,fd as pe,fi as V,fr as me,gi as he,gr as ge,hd as H,hi as _e,ji as U,ki as ve,mi as W,mr as ye,pr as be,tn as xe,vi as Se,vr as Ce,wi as we,yi as Te,yt as G}from"./src-DKc14e9G.js";import{t as K}from"./useTranslation-D3Is_4B6.js";import"./mount-B5MjkWnS.js";import{fr as q,lr as J,mr as Ee}from"./index-C8XwyZGE.js";import{t as Y}from"./AdminPage-B4QlIiKh.js";import{t as X}from"./NodeAddonsSettingsPanel-9_q0f4bE.js";import{n as Z,t as De}from"./useNodeUrlSelection-rnUQLTfb.js";function Oe(e){if(e===void 0)return null;switch(e.state){case`failed`:case`refused`:case`missing`:case`crashed`:return{kind:e.state,...e.reason===void 0?{}:{reason:e.reason}};default:return null}}e();var ke={queued:{icon:y,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:w,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:b,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:g,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:O,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Ae({item:e}){let{t}=K(),n=ke[e.status],r=n.icon;return a(`span`,{className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded ${n.bg}`,title:e.error,children:[l(r,{className:`w-2.5 h-2.5 ${n.spin?`animate-spin`:``}`}),t(n.labelKey)]})}var je=new Set([`completed`,`failed`,`partially-failed`,`cancelled`]),Q=new Set([`done`,`failed`,`skipped`]);function Me(e){return!Q.has(e.phase)&&!je.has(e.jobState)}function Ne(e,t){let n=new Map,r=[...e].sort((e,t)=>e.createdAtMs-t.createdAtMs);for(let e of r){let r=je.has(e.state);for(let i of e.tasks)r&&i.finishedAtMs!==null&&t-i.finishedAtMs>6e4||n.set(i.packageName,{jobId:e.jobId,packageName:i.packageName,phase:i.phase,fromVersion:i.fromVersion,toVersion:i.toVersion,error:i.error,jobState:e.state,finishedAtMs:i.finishedAtMs})}return n}function Pe(){let{data:e}=A({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=H(D.AddonsJobProgress,e=>e.job.jobId);return n(()=>{let n=new Map;for(let t of e??[])n.set(t.jobId,t);for(let[e,r]of t)n.set(e,r.job);return Ne([...n.values()],Date.now())},[e,t])}var Fe={queued:{icon:y,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:w,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:w,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:w,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:w,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:w,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:w,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:g,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:O,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:T,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function Ie({progress:e}){let{t}=K(),n=Fe[e.phase],r=n.icon,i=e.error??`${e.packageName}: ${e.fromVersion??`?`} → ${e.toVersion}`;return a(`span`,{"data-testid":`addon-job-progress`,className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded shrink-0 ${n.cls}`,title:i,children:[l(r,{className:`w-2.5 h-2.5 ${n.spin?`animate-spin`:``}`}),t(n.labelKey),a(`span`,{className:`font-mono`,children:[`→ `,e.toVersion]})]})}function Le(e,t){return e.filter(e=>e.packageName===t).slice().sort((e,t)=>e.isHub===t.isHub?e.nodeName.localeCompare(t.nodeName):e.isHub?-1:1)}function Re(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function ze(e,t,n){let r=[`${e} will be uninstalled from ${t.length} node(s). Its runners stop, its capabilities are deregistered and its code is deleted:`,...t.map(Re)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
2
+ `)}function Be(e,t,n){let r=[`${e} will be uninstalled from ${t}: its runners stop and its code is deleted.`];return n.length>0&&r.push(`It stays installed on: ${n.map(e=>e.nodeName).join(`, `)}. Use "Everywhere" to remove it from every node.`),r.push(`This cannot be undone.`),r.join(`
3
+ `)}var Ve={uninstalled:`uninstalled`,"not-installed":`was not installed`,refused:`REFUSED`,failed:`FAILED`,"pending-reconnect":`offline — removed when it reconnects`};function He(e,t){let n=[];for(let r of e.results){let e=r.runnersStopped.length>0?` (stopped ${r.runnersStopped.join(`, `)})`:``;n.push(`${t(r.nodeId)}: ${Ve[r.outcome]}${e}`),r.error!==void 0&&n.push(` ${r.error}`);for(let e of r.warnings)n.push(` ${e}`)}return n.join(`
4
+ `)}var Ue={},We=3e4,Ge=`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-border text-foreground-subtle hover:text-red-400 hover:border-red-500/30 hover:bg-red-500/10 disabled:opacity-50 transition-colors`;function Ke({packageName:e,displayName:t,selectedNode:n,hideNodeAction:r,disabled:i}){let{t:o}=K(),c=s(),u=ue(),f=M(),p=F(Ue,{staleTime:We}),m=p.data?.installations??[],h=(p.data?.unreachable??[]).map(e=>e.nodeId),g=Le(m,e),_=e=>g.find(t=>t.nodeId===e)?.nodeName??(e===n.id?n.name:e),v=N({onSettled:()=>{c.invalidateQueries({queryKey:[[`addons`]]}),c.invalidateQueries({queryKey:[[`addonPages`]]}),c.invalidateQueries({queryKey:[[`capabilities`]]}),c.invalidateQueries({queryKey:[[`nodes`]]})}}),y=async e=>{await f({title:e.success?o(`addons.addonUninstallControls.uninstalled`,`{{displayName}} uninstalled`,{displayName:t}):o(`addons.addonUninstallControls.notEveryNodeWasCleaned`,`{{displayName}}: not every node was cleaned`,{displayName:t}),message:He(e,_),variant:e.success?`default`:`danger`})},b=async n=>{try{await y(await v.mutateAsync({packageName:e,...n}))}catch(e){await f({title:o(`addons.addonUninstallControls.uninstallFailed`,`Uninstall {{displayName}} failed`,{displayName:t}),message:e instanceof Error?e.message:String(e),variant:`danger`})}},x=async()=>{let e=g.filter(e=>e.nodeId!==n.id);await u({title:o(`addons.addonUninstallControls.uninstallFrom`,`Uninstall {{displayName}} from {{name}}?`,{displayName:t,name:n.name}),message:Be(t,n.name,e),confirmLabel:o(`addons.addonUninstallControls.uninstall`,`Uninstall`),variant:`danger`})&&await b(n.isHub?{}:{nodeId:n.id})},S=async()=>{let n=(await p.refetch()).data;if(n===void 0){await f({title:o(`addons.addonUninstallControls.cannotListTheNodes`,`Cannot list the nodes`),message:o(`addons.addonUninstallControls.theHubDidNotAnswer`,`The hub did not answer which nodes have this package — nothing was removed.`),variant:`danger`});return}let r=Le(n.installations,e);await u({title:o(`addons.addonUninstallControls.uninstallEverywhere`,`Uninstall {{displayName}} everywhere?`,{displayName:t}),message:ze(t,r,n.unreachable.map(e=>e.nodeId)),confirmLabel:o(`addons.addonUninstallControls.uninstallFromNodeS`,`Uninstall from {{length}} node(s)`,{length:r.length}),variant:`danger`})&&await b({everywhere:!0})},C=v.isPending||i===!0;return a(`div`,{className:`flex items-center gap-1.5`,children:[r!==!0&&a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),x()},disabled:C,className:Ge,title:o(`addons.addonUninstallControls.uninstallFrom2`,`Uninstall from {{name}}`,{name:n.name}),children:[l(d,{className:`h-3 w-3`}),v.isPending?o(`addons.addonUninstallControls.removing`,`Removing...`):o(`addons.addonUninstallControls.uninstall`,`Uninstall`)]}),(g.length>1||r===!0||h.length>0)&&a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),S()},disabled:C,className:Ge,title:o(`addons.addonUninstallControls.uninstallFromEveryNodeThat`,`Uninstall from every node that has it`),children:[l(ie,{className:`h-3 w-3`}),g.length>0?o(`addons.uninstallControls.everywhereCount`,{count:g.length}):o(`addons.uninstallControls.everywhere`)]})]})}function qe({packageName:e,currentVersion:t,installSource:n,onInstall:r,onClose:i,onSelect:s,selectedVersion:c}){let{t:u}=K(),d=n===`upload`||n===`local`,{data:f,isLoading:m}=Se({name:e});return a(`div`,{className:`fixed z-50 w-72 rounded-lg border border-border bg-surface shadow-xl overflow-hidden`,style:{top:`auto`,bottom:`auto`},ref:e=>{if(!e)return;let t=e.parentElement?.getBoundingClientRect();if(!t)return;let n=window.innerHeight-t.bottom,r=t.top;n<280&&r>n?(e.style.bottom=`${window.innerHeight-t.top+4}px`,e.style.top=`auto`):(e.style.top=`${t.bottom+4}px`,e.style.bottom=`auto`),e.style.right=`${window.innerWidth-t.right}px`},onClick:e=>e.stopPropagation(),children:[a(`div`,{className:`flex items-center justify-between px-3 py-2 border-b border-border`,children:[l(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle font-medium`,children:u(`addons.versionPicker.versions`,`Versions`)}),l(`button`,{type:`button`,onClick:i,className:`text-foreground-subtle hover:text-foreground`,children:l(x,{className:`h-3 w-3`})})]}),d&&a(`div`,{className:`flex items-start gap-2 px-3 py-2 border-b border-border bg-cyan-500/10 text-[10px]`,children:[l(p,{className:`h-3 w-3 mt-0.5 text-cyan-500 shrink-0`}),a(`div`,{className:`text-cyan-700 dark:text-cyan-200`,children:[l(`span`,{className:`font-semibold`,children:u(`addons.versionPicker.inPlace`,{kind:n===`upload`?u(`addons.versionPicker.uploadedCopy`,`Uploaded copy`):u(`addons.versionPicker.localCopy`,`Local copy`)})}),` `,l(J,{i18nKey:`addons.versionPicker.reinstall`,values:{version:t},components:{mono:l(`span`,{className:`font-mono`})}})]})]}),m&&a(`div`,{className:`flex items-center justify-center gap-2 py-6 text-[10px] text-foreground-subtle`,children:[l(w,{className:`h-3.5 w-3.5 animate-spin`}),u(`addons.versionPicker.loadingVersions`,`Loading versions...`)]}),f&&l(`div`,{className:`max-h-64 overflow-auto divide-y divide-border`,children:f.map(e=>{let n=e.version===t,i=s!==void 0&&e.version===c,d=/-(alpha|beta|rc|dev|canary|next)/i.test(e.version),f=a(o,{children:[l(`span`,{className:`font-mono flex-1 text-left ${n?`text-primary font-semibold`:d?`text-amber-400`:`text-foreground`}`,children:e.version}),n&&l(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium bg-primary/10 text-primary`,children:u(`common.current`)}),e.distTags.map(e=>l(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e===`latest`?`bg-emerald-500/15 text-emerald-400`:e===`beta`?`bg-amber-500/15 text-amber-400`:`bg-gray-500/15 text-gray-400`}`,children:e},e)),e.deprecated&&l(`span`,{className:`text-[9px] text-red-400 line-through`,children:u(`common.deprecated`)}),l(`span`,{className:`text-[9px] text-foreground-subtle shrink-0`,children:new Date(e.publishedAt).toLocaleDateString()})]});return s?a(`button`,{type:`button`,"aria-label":u(`addons.versionPicker.select`,`Select {{version}}`,{version:e.version}),onClick:()=>s(e.version),className:`w-full flex items-center gap-2 px-3 py-2 text-[11px] ${i?`bg-primary/5`:`hover:bg-surface-hover`} transition-colors`,children:[f,i?l(g,{className:`h-3 w-3 text-primary shrink-0`}):l(`span`,{className:`w-3 shrink-0`})]},e.version):a(`div`,{className:`flex items-center gap-2 px-3 py-2 text-[11px] ${n?`bg-primary/5`:`hover:bg-surface-hover`} transition-colors`,children:[f,l(`button`,{type:`button`,onClick:()=>r(e.version),className:`shrink-0 rounded p-0.5 hover:bg-primary/20 text-foreground-subtle hover:text-primary transition-colors`,title:n?u(`addons.versionPicker.reInstallFromNpm`,`Re-install {{version}} from npm`,{version:e.version}):u(`addons.versionPicker.install`,`Install {{version}}`,{version:e.version}),children:l(v,{className:`h-3 w-3`})})]},e.version)})}),f&&f.length===0&&l(`div`,{className:`py-4 text-center text-[10px] text-foreground-subtle`,children:u(`addons.versionPicker.noVersionsFound`,`No versions found`)})]})}e();var Je=`device-export`;function Ye(e){return e.capabilities.some(e=>(typeof e==`string`?e:e.name)===Je)}function Xe(e){return e!==`local`&&e!==`upload`}function Ze({isBundle:e,installSource:t,addonId:n,iconPath:i,color:o}){let[s,c]=r(!1),u=o?{backgroundColor:`${o.startsWith(`#`)?o:`#${o}`}26`}:void 0,d=e?`bg-indigo-500/20 text-indigo-700 dark:text-indigo-300`:`bg-purple-500/20 text-purple-700 dark:text-purple-300`,f=n&&i?m(`/api/addon-assets/${n}/${i}`):null,g=!!f&&!s;return a(`div`,{className:`relative flex-shrink-0`,children:[l(`div`,{className:`h-8 w-8 rounded-md flex items-center justify-center ${u?``:d}`,style:u,children:g?l(`img`,{src:f,alt:n,className:`h-4 w-4`,onError:()=>c(!0)}):l(e?h:_,{className:`h-3.5 w-3.5`})}),t===`local`&&l(`span`,{className:`absolute -top-1.5 -left-1.5 text-[7px] font-bold leading-none bg-orange-500 text-white px-1 py-0.5 rounded -rotate-12 shadow-sm`,children:`DEV`}),Xe(t)&&l(`span`,{className:`absolute -top-1 -left-1 w-4 h-4 rounded bg-[#cb3837] flex items-center justify-center -rotate-12 shadow-sm`,children:l(`svg`,{viewBox:`0 0 780 250`,className:`w-[11px] h-[11px]`,children:l(`path`,{fill:`#fff`,d:`M240 250h100V50h100v200h340V0H0v250z`})})}),t===`upload`&&l(`span`,{className:`absolute -top-1.5 -left-1.5 flex items-center justify-center h-4 w-4 rounded bg-cyan-500 -rotate-12 shadow-sm`,children:l(p,{className:`h-2.5 w-2.5 text-white`})})]})}function Qe({version:e,availableUpdate:t,selectedVersion:n,isUpdating:r,installSource:i,disabled:o,onUpdate:s,onOpenPicker:c,children:u}){let{t:d}=K();if(r)return a(`span`,{className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border border-blue-500/30 bg-blue-500/10 text-blue-400 shrink-0`,children:[l(w,{className:`h-3 w-3 animate-spin`}),d(`addons.addonCard.updating`,`Updating…`)]});if(t){let r=n??t;return a(`div`,{className:`relative inline-flex items-center gap-1 shrink-0`,children:[s&&a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),s()},disabled:o,className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-semibold border border-blue-500/30 bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,title:d(`addons.addonCard.updateTo`,`Update to {{target}}`,{target:r}),children:[l(v,{className:`h-3 w-3`}),d(`addons.addonCard.update`,`Update`)]}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),c()},disabled:o,"aria-label":d(`addons.addonCard.selectVersionToInstall`,`Select version to install`),title:d(`addons.addonCard.installedUpdateAvailableSelectedTap`,`Installed {{version}} — update available. Selected {{target}}; tap to choose another version.`,{version:e,target:r}),className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-bold font-mono border border-amber-500/40 bg-amber-500/15 text-amber-500 hover:bg-amber-500/25 animate-pulse disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,children:[l(`span`,{className:`font-normal opacity-70`,children:e}),l(`span`,{className:`font-normal opacity-70`,children:`→`}),r,l(re,{className:`h-3 w-3`})]}),u]})}return a(`div`,{className:`relative inline-flex items-center gap-1 shrink-0`,children:[a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),c()},disabled:o,className:[`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-bold font-mono border transition-colors disabled:opacity-50 disabled:cursor-not-allowed`,i===`local`?`border-orange-500/30 bg-orange-500/10 text-orange-400 hover:bg-orange-500/20`:`border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20`].join(` `),title:d(`addons.addonCard.versionTapToViewAll`,`Version {{version}} — tap to view all versions`,{version:e}),children:[e,l(re,{className:`h-3 w-3 opacity-50`})]}),u]})}function $e({addonId:e}){let t=s(),{data:n=`inherit`}=_e({addonId:e}),r=k({onSuccess:()=>{t.invalidateQueries({queryKey:[[`addons`,`getAddonAutoUpdate`]]})}});return l(`div`,{className:`flex rounded-lg border border-border overflow-hidden text-[10px] font-medium`,children:[`inherit`,`off`,`latest`,`beta`].map(t=>l(`button`,{type:`button`,onClick:n=>{n.stopPropagation(),r.mutate({addonId:e,channel:t})},disabled:r.isPending,className:`px-2.5 py-1 transition-colors capitalize ${n===t?t===`inherit`?`bg-gray-700/50 text-gray-700 dark:text-gray-300`:t===`off`?`bg-gray-700 text-gray-700 dark:text-gray-300`:t===`latest`?`bg-blue-500/20 text-blue-400`:`bg-amber-500/20 text-amber-400`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`} ${t===`inherit`?``:`border-l border-border`}`,children:t},t))})}var et={id:`hub`,name:`Hub`,isHub:!0};function tt({addon:e,agents:n=[],clusterStatus:i,hideVersion:c,availableUpdate:u,onUpdate:d,isUpdating:f,jobProgress:p,bundle:m,bulkItem:g,disabledByBulk:_,isSystem:v,selectedNode:y}){let{t:S}=K(),[w,ee]=r(!1),[T,D]=r(!1),[ie,k]=r(!1),[A,oe]=r(null);t(()=>{oe(null)},[u]);let M=A??u,[se,N]=r(!1),[P,F]=r(!1),[I,ue]=r(`logs`),L=s(),de=q(),{manifest:R}=e,B=e.installedOn??[],pe=!m&&!R.protected&&R.removable!==!1,V=!!m,he=m?.displayName??R.name,H=m?.packageName??R.packageName,_e=m?.version??R.packageVersion??R.version,U=m?.installSource??e.installSource,ve=m?m.bundle?.description??m.addons[0]?.manifest.description:R.description,W=ae({onSuccess:()=>{L.invalidateQueries({queryKey:[[`addons`]]})}}),Se=Te({onSuccess:()=>{L.invalidateQueries({queryKey:[[`addons`]]}),L.invalidateQueries({queryKey:[[`addonPages`]]}),L.invalidateQueries({queryKey:[[`capabilities`]]}),L.invalidateQueries({queryKey:[[`integrations`]]})}}),we=ce({onSuccess:()=>{L.invalidateQueries({queryKey:[[`addons`]]}),L.invalidateQueries({queryKey:[[`alerts`]]})}}),G=e.health,J=G?.phase===`failed`&&!G.inGracePeriod,Ee=J&&G?.nextRetryAt&&!G.retrying,Y=Oe(e.process);return a(`div`,{className:`rounded-md border bg-surface overflow-hidden ${J?`border-red-500/50`:`border-border`}`,children:[J&&G&&a(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[l(O,{className:`h-4 w-4 text-danger shrink-0 mt-0.5`}),a(`div`,{className:`flex-1 min-w-0`,children:[l(`div`,{className:`text-xs font-semibold text-danger`,children:S(`addons.addonCard.failedToLoad`,{attempt:G.retryCount})}),l(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:G.lastError?.message??S(`addons.addonCard.unknownError`,`Unknown error`)}),Ee&&G.nextRetryAt&&l(`div`,{className:`text-[10px] text-foreground-subtle mt-1`,children:S(`addons.addonCard.autoRetryAt`,{time:new Date(G.nextRetryAt).toLocaleTimeString()})})]}),a(`button`,{type:`button`,disabled:we.isPending||G.retrying,onClick:e=>{e.stopPropagation(),we.mutate({packageName:H})},className:`inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-semibold border border-red-400/40 bg-red-400/10 text-red-700 dark:text-red-300 hover:bg-red-400/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0`,title:S(`addons.addonCard.resetRetryCounterAndForce`,`Reset retry counter and force immediate reload`),children:[l(b,{className:`h-3 w-3 ${we.isPending||G.retrying?`animate-spin`:``}`}),S(`addons.addonCard.retryNow`,`Retry now`)]})]}),Y!==null&&a(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[l(O,{className:`h-4 w-4 text-danger shrink-0 mt-0.5`}),a(`div`,{className:`flex-1 min-w-0`,children:[l(`div`,{className:`text-xs font-semibold text-danger`,children:S(`addons.addonCard.processProblem.${Y.kind}`)}),Y.reason!==void 0&&l(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:Y.reason})]})]}),a(`div`,{className:`flex items-start gap-2.5 px-3 py-2`,children:[l(Ze,{isBundle:V||!!R.components&&R.components.length>1,installSource:U,addonId:V?m.addons[0]?.manifest.id:R.id,iconPath:V?m.bundle?.icon??m.addons[0]?.manifest.icon:R.icon,color:V?m.addons[0]?.manifest.color:R.color}),a(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`flex items-start justify-between gap-2`,children:[l(`span`,{className:`text-xs font-semibold text-foreground truncate min-w-0`,children:he}),!c&&l(Qe,{version:_e,availableUpdate:u,...M===void 0?{}:{selectedVersion:M},isUpdating:f,installSource:U,disabled:_,...d&&M!==void 0?{onUpdate:()=>d(M)}:{},onOpenPicker:()=>k(e=>!e),children:ie&&l(qe,{packageName:H,currentVersion:_e,...U?{installSource:U}:{},...u!==void 0&&M!==void 0?{selectedVersion:M,onSelect:e=>{oe(e),k(!1)}}:{},onInstall:e=>{k(!1),Se.mutate({packageName:H,version:e})},onClose:()=>k(!1)})})]}),a(`div`,{className:`flex flex-wrap items-center gap-x-1.5 gap-y-1 mt-0.5`,children:[H!==he&&l(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate max-w-full`,children:H}),V&&a(`span`,{className:`text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium shrink-0 inline-flex items-center gap-1`,children:[l(h,{className:`h-3 w-3`}),m.addons.length]}),v&&a(`span`,{className:`text-[10px] rounded-full bg-amber-500/15 text-amber-700 dark:text-amber-300 px-2 py-0.5 font-medium shrink-0 inline-flex items-center gap-1`,title:S(`addons.addonCard.systemPackageUpdatingRestartsThe`,`System package — updating restarts the hub`),children:[l(b,{className:`h-3 w-3`}),S(`addons.addonCard.system`,`System`)]}),g!=null&&l(Ae,{item:g}),p!=null&&l(Ie,{progress:p})]}),ve&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-1 line-clamp-1`,children:ve}),!V&&e.process&&a(`div`,{className:`flex flex-wrap items-center gap-1.5 mt-1`,children:[l(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.mode===`forked`?`bg-blue-500/15 text-blue-400`:`bg-gray-500/15 text-gray-400`}`,children:e.process.mode===`forked`?S(`addons.addonCard.forked`):S(`addons.addonCard.inProcess`)}),e.process.pid!=null&&a(`span`,{className:`text-[9px] font-mono text-foreground-subtle`,children:[`PID `,e.process.pid]}),l(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.state===`running`?`bg-emerald-500/15 text-emerald-400`:Y===null?`bg-gray-500/15 text-gray-400`:`bg-red-500/15 text-red-400`}`,children:e.process.state})]})]})]}),!V&&a(`div`,{className:`flex items-center gap-1 px-3 py-1 border-t border-border/50 bg-surface-hover/20`,children:[a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),W.mutate({addonId:R.id})},disabled:W.isPending||_,className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border border-border text-foreground-subtle hover:text-blue-400 hover:border-blue-500/30 hover:bg-blue-500/10 disabled:opacity-50 transition-colors`,children:[l(b,{className:`h-3 w-3 ${W.isPending?`animate-spin`:``}`}),S(`addons.addonCard.restart`,`Restart`)]}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),N(e=>!e)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${se?`border-primary/30 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10`}`,children:[l(te,{className:`h-3 w-3`}),S(`addons.addonCard.logs`,`Logs`)]}),!V&&a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),F(!0)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${P?`border-primary/30 bg-primary/10 text-primary`:`border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10`}`,children:[l(E,{className:`h-3 w-3`}),S(`addons.addonCard.settings`,`Settings`)]}),l(`div`,{className:`flex-1`}),pe&&l(Ke,{packageName:R.packageName,displayName:R.name,selectedNode:y??et,disabled:_})]}),i&&i.nodes.length>1&&!V&&a(`div`,{className:`border-t border-border px-3 py-1.5 bg-muted/10`,children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle mb-1.5`,children:S(`addons.addonCard.clusterDeployment`,`Cluster Deployment`)}),l(`div`,{className:`space-y-1`,children:i.nodes.map(e=>a(`div`,{className:`flex items-center gap-2 text-[10px]`,children:[l(`div`,{className:`h-1.5 w-1.5 rounded-full shrink-0 ${e.status===`offline`?`bg-muted-foreground/30`:e.synced?`bg-success`:`bg-amber-500`}`}),l(`span`,{className:`font-medium text-foreground min-w-[60px]`,children:e.name}),l(`span`,{className:`font-mono text-foreground-subtle`,children:e.version}),!e.synced&&e.status!==`offline`&&l(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20`,children:S(`addons.addonCard.outdated`)}),e.status===`offline`&&l(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground`,children:S(`common.offline`)}),e.synced&&e.status!==`offline`&&l(`span`,{className:`text-[9px] text-success`,children:S(`common.synced`)})]},e.nodeId))})]}),se&&!V&&a(`div`,{className:`border-t border-border`,children:[a(`div`,{className:`flex items-center px-3 py-0.5 bg-surface-hover/20 border-b border-border/50`,children:[a(`div`,{className:`flex rounded border border-border overflow-hidden text-[9px]`,children:[l(`button`,{type:`button`,onClick:()=>ue(`logs`),className:`px-2 py-0.5 transition-colors ${I===`logs`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:S(`addons.addonCard.logs`,`Logs`)}),l(`button`,{type:`button`,onClick:()=>ue(`events`),className:`px-2 py-0.5 border-l border-border transition-colors ${I===`events`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:S(`addons.addonCard.events`,`Events`)})]}),l(`div`,{className:`flex-1`}),l(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),N(!1)},className:`text-foreground-subtle hover:text-foreground`,children:l(x,{className:`h-3.5 w-3.5`})})]}),I===`logs`&&l(xe,{addonId:R.id,maxHeight:`max-h-64`,showFilters:!1}),I===`events`&&l(fe,{addonId:R.id,category:`addon.*`,maxHeight:`max-h-64`})]}),V&&a(o,{children:[l(`button`,{type:`button`,onClick:()=>ee(e=>!e),className:`w-full flex items-center justify-center border-t border-border py-1 hover:bg-surface-hover/50 transition-colors`,children:l(w?ne:re,{className:`h-3.5 w-3.5 text-foreground-subtle`})}),w&&l(`div`,{className:`border-t border-border px-2.5 py-1.5 space-y-1.5`,children:m.addons.map(e=>l(tt,{addon:e,agents:n,hideVersion:!0},e.manifest.id))})]}),P&&!V&&l(me,{open:!0,onOpenChange:e=>!e&&F(!1),children:a(ye,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[l(z,{children:a(Ce,{className:`flex items-center gap-2`,children:[l(E,{className:`h-4 w-4 text-primary`}),S(`addons.addonCard.settingsTitle`,{name:he})]})}),a(be,{className:`space-y-4`,children:[l(`div`,{className:`text-[10px] text-foreground-subtle mb-2`,children:S(`addons.addonCard.clusterWideSettingsOneValue`,`Cluster-wide settings — one value for every node. Per-node settings live under Cluster → the node → Settings.`)}),l(X,{nodeId:null,addonIds:[R.id],level:`global`,fieldScope:`cluster`,emptyMessage:S(`addons.addonCard.thisAddonExposesNoCluster`,`This addon exposes no cluster-wide settings. Anything it can configure is per-node — open it from Cluster → the node → Settings.`)}),Ye(R)&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:S(`addons.addonCard.deviceExport`,`Device export`)}),l(le,{addonId:R.id,onOpenDevice:e=>de(`/devices/${e}`)})]}),Xe(U)&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:S(`addons.addonCard.autoUpdate`,`Auto-Update`)}),l($e,{addonId:R.id})]}),R.components&&R.components.length>0&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:S(`addons.addonCard.components`,{count:R.components.length})}),l(`div`,{className:`flex flex-wrap gap-1`,children:R.components.map(e=>l(`span`,{className:`text-[10px] rounded bg-background border border-border px-1.5 py-0.5 text-foreground-subtle font-mono`,children:e},e))})]}),n.length>=2&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:S(`addons.addonCard.installedOn`,`Installed on`)}),a(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[B.length===0&&l(`span`,{className:`text-[10px] text-foreground-subtle`,children:S(`addons.addonCard.hubLocal`,`Hub (local)`)}),B.map(e=>l(`span`,{className:`rounded-full bg-surface-hover border border-border px-2 py-0.5 text-[10px] text-foreground-subtle`,children:e},e)),a(`div`,{className:`relative`,children:[a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),D(e=>!e)},className:`inline-flex items-center gap-1 rounded-full border border-dashed border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground hover:border-primary transition-colors`,title:S(`addons.addonCard.installOnMoreAgents`,`Install on more agents`),children:[l(C,{className:`h-3 w-3`}),S(`addons.addonCard.addAgent`,`Add agent`)]}),T&&a(`div`,{className:`absolute left-0 top-full mt-1 z-10 min-w-[160px] rounded-md border border-border bg-surface shadow-lg overflow-hidden`,children:[n.filter(e=>!e.isHub&&!B.includes(e.name)).map(e=>l(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),D(!1)},className:`w-full text-left px-3 py-1.5 text-[10px] text-foreground hover:bg-surface-hover transition-colors`,children:e.name},e.id)),n.filter(e=>!e.isHub&&!B.includes(e.name)).length===0&&l(`div`,{className:`px-3 py-1.5 text-[10px] text-foreground-subtle`,children:S(`addons.addonCard.noAvailableAgents`,`No available agents`)})]})]})]})]})]}),l(ge,{children:l(j,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>F(!1),children:S(`common.close`,`Close`)})})]})})]})}e();var nt=`.tgz,.tar.gz,.zip`;function rt({onUploadSuccess:e}){let{t}=K(),[n,s]=r(!1),u=c(null),d=i(async t=>{s(!0);let n=new FormData;n.append(`file`,t);let r=localStorage.getItem(`camstack_admin_token`)??``;try{(await(await fetch(m(`/api/addons/upload`),{method:`POST`,headers:{Authorization:`Bearer ${r}`},body:n})).json()).success&&e()}finally{s(!1)}},[e]);return a(o,{children:[l(`input`,{ref:u,type:`file`,accept:nt,onChange:i(e=>{let t=e.target.files?.[0];t&&d(t),e.target.value=``},[d]),className:`hidden`}),a(`button`,{type:`button`,onClick:()=>u.current?.click(),disabled:n,className:`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors`,children:[n?l(w,{className:`w-3.5 h-3.5 animate-spin`}):l(p,{className:`w-3.5 h-3.5`}),n?t(`addons.addonUploadZone.uploading`,`Uploading...`):t(`addons.addonUploadZone.upload`,`Upload`)]})]})}var it=new Set([`@camstack/system`,`@camstack/types`,`@camstack/sdk`,`@camstack/ui-library`,`@camstack/addon-agent-ui`]);function at(e,t){let n=new Map;for(let r of e){if(r.isHub||r.onHub||it.has(r.packageName)||!t.isHub&&r.nodeId!==t.id)continue;let e=n.get(r.packageName)??[];e.push(r),n.set(r.packageName,e)}return[...n].map(([e,t])=>({packageName:e,rows:t})).sort((e,t)=>e.packageName.localeCompare(t.packageName))}function ot({selectedNode:e}){let{t}=K(),{data:n}=F(Ue,{staleTime:We});if(n===void 0)return null;let r=at(n.installations,e),i=n.unreachable.filter(t=>e.isHub||t.nodeId===e.id);return r.length===0&&i.length===0?null:a(`div`,{className:`rounded-lg border border-warning/30 bg-warning/5 px-3 py-2.5 space-y-2`,children:[a(`div`,{className:`flex items-center gap-2 text-[11px] font-semibold text-foreground`,children:[l(f,{className:`h-3.5 w-3.5 text-warning`}),e.isHub?t(`addons.nodeOnlyPackagesPanel.installedOnAgentsButNot`,`Installed on agents but not on the hub`):t(`addons.nodeOnlyPackagesPanel.installedOnButNotOn`,`Installed on {{name}} but not on the hub`,{name:e.name})]}),i.length>0&&l(`div`,{className:`text-[10px] text-foreground-subtle`,children:t(`addons.nodeOnlyPackagesPanel.unreachable`,{nodes:i.map(e=>e.nodeId).join(`, `)})}),r.map(t=>a(`div`,{className:`flex items-center justify-between gap-3 flex-wrap rounded-md border border-border bg-surface px-3 py-2`,children:[a(`div`,{className:`min-w-0`,children:[l(`div`,{className:`text-xs font-mono text-foreground break-all`,children:t.packageName}),l(`div`,{className:`text-[10px] text-foreground-subtle`,children:t.rows.map(e=>`${e.nodeName}${e.version===null?``:` ${e.version}`}${e.isOnline?``:` (offline)`}`).join(` · `)})]}),l(Ke,{packageName:t.packageName,displayName:t.packageName,selectedNode:e,hideNodeAction:e.isHub})]},t.packageName))]})}function st({addon:e,installing:t,onInstall:n}){let{t:r}=K();return a(`div`,{className:`flex items-center gap-3 px-3 py-2 hover:bg-surface-hover transition-colors`,children:[l(`div`,{className:`w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center text-primary text-[9px] font-bold shrink-0`,children:e.name.replace(`@camstack/addon-`,``).charAt(0).toUpperCase()}),a(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`flex items-baseline gap-2 min-w-0`,children:[l(`span`,{className:`text-[11px] font-semibold break-words`,children:e.name.replace(/^@camstack\/(addon-)?/,``)}),a(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:[`v`,e.version]})]}),l(`div`,{className:`font-mono text-[9px] text-foreground-subtle/80 truncate`,children:e.name}),e.description&&l(`div`,{className:`text-[10px] text-foreground-subtle truncate`,children:e.description})]}),e.installed?l(P,{variant:`success`,icon:l(g,{className:`h-3 w-3`}),children:e.installedVersion??r(`system.capabilityCatalog.installed`,`Installed`)}):a(j,{size:`sm`,onClick:()=>n(e.name),disabled:t,className:`shrink-0`,children:[t?l(w,{className:`h-3 w-3 animate-spin`}):l(v,{className:`h-3 w-3`}),r(`system.capabilityCatalog.install`,`Install`)]})]})}function ct({capability:e,installing:t,onInstall:n}){let{t:r}=K(),{data:i,isPending:o,isError:s}=ve({capability:e}),c;if(s)c=l(`div`,{className:`px-3 py-2 text-xs text-danger`,children:r(`system.capabilityCatalog.couldNotSearchTheNpm`,`Could not search the npm catalog right now. Try again in a moment.`)});else if(o||i===void 0)c=a(`div`,{className:`flex items-center gap-2 px-3 py-2 text-xs text-foreground-subtle`,children:[l(w,{className:`h-3 w-3 animate-spin`}),r(`system.capabilityCatalog.searchingTheNpmCatalog`,`Searching the npm catalog…`)]});else{let a=i.filter(e=>!e.installed);c=a.length===0?l(`div`,{className:`px-3 py-2 text-xs text-foreground-subtle`,children:i.length===0?r(`system.capabilityCatalog.noPublishedAddonDeclaresThe`,`No published addon declares the "{{capability}}" capability.`,{capability:e}):r(`system.capabilityCatalog.everyPublishedAddonThatDeclares`,`Every published addon that declares "{{capability}}" is already installed.`,{capability:e})}):l(`div`,{className:`divide-y divide-border`,children:a.map(e=>l(st,{addon:e,installing:t,onInstall:n},e.name))})}return a(`section`,{className:`rounded-md border border-border bg-surface overflow-hidden`,"aria-label":r(`system.capabilityCatalog.availableToInstall`,`Available to install`),children:[l(`h2`,{className:`px-3 py-1.5 text-[10px] uppercase tracking-wide text-foreground-subtle border-b border-border`,children:r(`system.capabilityCatalog.availableToInstall`,`Available to install`)}),c]})}e();function lt(e){return e===`npm`||e===`dev`?e:null}var ut=`rounded-full border border-primary bg-primary/10 px-2 py-0.5 text-[10px] text-foreground`,dt=`rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-muted hover:bg-surface-hover`,ft=[{seconds:900,label:`15m`},{seconds:3600,label:`1h`},{seconds:21600,label:`6h`},{seconds:43200,label:`12h`},{seconds:86400,label:`24h`}],pt=new Set([`@camstack/system`,`@camstack/types`,`@camstack/sdk`,`@camstack/shm-ring`,`@camstack/ui-library`]);function mt(e){return e!==void 0&&pt.has(e)}var ht={id:`hub`,name:`Hub`,isHub:!0,isOnline:!0};function gt(e,t){let n=e??`hub-only`;return n===`any-node`?!0:n===`hub-only`?t:!t}function _t(e){return e===`local`?`dev`:`npm`}function vt(e){let t=e;if(!t?.manifest)return null;let n={...t.manifest,name:t.manifest.name??t.manifest.id,version:t.manifest.version??`0.0.0`,capabilities:t.manifest.capabilities??[]},r=t.process,i=r?{pid:r.pid,mode:r.mode===`forked`?`forked`:`in-process`,state:r.state??`unknown`,...r.reason===void 0?{}:{reason:r.reason}}:void 0,a=t.health,o=t.declaration?.execution,s=t.manifest.execution,c=o?.placement??s?.placement;return{manifest:n,enabled:!0,source:t.source,installSource:t.installSource,installedOn:[],...i?{process:i}:{},hasBackup:t.hasBackup,...a?{health:a}:{},...c?{placement:c}:{}}}function yt(e){let t=new Map,n=[];for(let r of e){let e=r.manifest.packageName;if(!e){n.push(r);continue}let i=t.get(e);if(i)i.addons.push(r);else{let n=r.manifest.bundle,i={packageName:e,displayName:n?.displayName??r.manifest.packageDisplayName??r.manifest.name,version:r.manifest.packageVersion,addons:[r],...r.installSource===void 0?{}:{installSource:r.installSource},...n===void 0?{}:{bundle:n}};t.set(e,i)}}let r=[];for(let e of t.values())e.bundle!==void 0||e.addons.length>=2?r.push({bundle:e,representative:e.addons[0]}):r.push(e.addons[0]);return r.push(...n),r}function $(e){return`bundle`in e}function bt({addons:e,clusterStatus:o,selectedNode:d,onRefresh:f,isRefreshing:p}){let{t:m}=K(),h=s(),[g,_]=r(``),y=u(g),[x,C]=r(!1),te=c(null);t(()=>{if(!x)return;let e=e=>{te.current&&!te.current.contains(e.target)&&C(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[x]);let{data:T}=we({nodeId:d.id}),E=n(()=>{let e=new Map;for(let t of T??[])e.set(t.name,t.latestVersion);return e},[T]),ne=n(()=>(T??[]).filter(e=>!e.isSystem).length,[T]),[re,D]=r(()=>new Set),[O,ie]=r(()=>new Map),k=i(e=>{D(t=>new Set(t).add(e))},[]),A=i(e=>{D(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),ae=i((e,t)=>{ie(n=>new Map(n).set(e,t))},[]),j=i(e=>{ie(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},[]),M=oe({onMutate:e=>{k(e.name),j(e.name)},onSuccess:(e,t)=>{A(t.name);let n=e;if(n&&n.success===!1){ae(t.name,n.error??`Update failed (no error message returned by server)`);return}h.invalidateQueries({queryKey:[[`addons`]]}),h.invalidateQueries({queryKey:[[`addons`,`listUpdates`]]})},onError:(e,t)=>{A(t.name),ae(t.name,e instanceof Error?e.message:String(e))}}),ce=Pe(),le=c(new Set);t(()=>{let e=new Set;for(let[t,n]of ce)Me(n)&&e.add(t);let t=[...le.current].some(t=>!e.has(t));le.current=e,t&&(h.invalidateQueries({queryKey:[[`addons`]]}),h.invalidateQueries({queryKey:[[`addons`,`listUpdates`]]}))},[ce,h]);let{data:N}=he(void 0),P=V({onSuccess:()=>{h.invalidateQueries({queryKey:[[`addons`,`getAutoUpdateSettings`]]})}}),F=U({onSuccess:()=>{h.invalidateQueries({queryKey:[[`addons`,`getAutoUpdateSettings`]]})}}),{data:I,isFetching:L}=ve({query:y||void 0},{enabled:x}),z=se(),{data:B}=R(void 0),fe=B?.requestedAt,[pe,me]=r(null),[ge,H]=r(!1);t(()=>{if(B?.kind===`framework-bulk-update`&&B.requestedAt!==pe){me(B.requestedAt),H(!0);let e=window.setTimeout(()=>H(!1),6e3);return()=>window.clearTimeout(e)}},[fe,pe,B]),ue();let _e=i(async()=>{let e=(T??[]).filter(e=>!e.isSystem);if(e.length!==0){if(!d.isHub){for(let t of e)await M.mutateAsync({name:t.name,version:t.latestVersion,nodeId:d.id});return}await z.mutateAsync({kind:`update`,targets:e.map(e=>({name:e.name,version:e.latestVersion})),nodeIds:[d.id]})}},[T,d.id,d.isHub,z,M]),W=Te({onSuccess:()=>{h.invalidateQueries({queryKey:[[`addons`]]}),h.invalidateQueries({queryKey:[[`addonPages`]]}),h.invalidateQueries({queryKey:[[`capabilities`]]}),h.invalidateQueries({queryKey:[[`integrations`]]})}}),[ye,be]=r(`type`),[xe,Se]=r(()=>typeof window>`u`?`grouped`:window.localStorage.getItem(`camstack.addons.viewMode`)===`flat`?`flat`:`grouped`),Ce=e=>{Se(e),typeof window<`u`&&window.localStorage.setItem(`camstack.addons.viewMode`,e)},[G,q]=Ee(),J=G.get(`capability`),Y=G.get(`updatable`)===`1`,X=G.get(`error`)===`1`,Z=lt(G.get(`source`)),De=i(e=>{let t=new URLSearchParams(G);e?t.set(`updatable`,`1`):t.delete(`updatable`),q(t,{replace:!0})},[G,q]),ke=i(e=>{let t=new URLSearchParams(G);e?t.set(`error`,`1`):t.delete(`error`),q(t,{replace:!0})},[G,q]),Ae=i(e=>{let t=new URLSearchParams(G);e===null?t.delete(`source`):t.set(`source`,e),q(t,{replace:!0})},[G,q]),je=n(()=>e.filter(e=>Oe(e.process)!==null).length,[e]),Q=n(()=>{let t=e.filter(e=>!mt(e.manifest.packageName));return d.isHub||(t=t.filter(e=>gt(e.placement,d.isHub))),J&&(t=t.filter(e=>(e.manifest.capabilities??[]).some(e=>(typeof e==`string`?e:e.name)===J))),Y&&(t=t.filter(e=>{let t=e.manifest.packageName;return t!==void 0&&E.has(t)})),Z!==null&&(t=t.filter(e=>_t(e.installSource)===Z)),X&&(t=t.filter(e=>Oe(e.process)!==null)),t},[e,d.isHub,J,Y,Z,X,E]),Ne=()=>{let e=new URLSearchParams(G);e.delete(`capability`),q(e,{replace:!0})},Fe=xe===`flat`?Q:yt(Q),Ie=n(()=>{let e=[...Fe];switch(ye){case`type`:e.sort((e,t)=>{let n=+!$(e),r=+!$(t);if(n!==r)return n-r;let i=$(e)?e.bundle.displayName:e.manifest.name,a=$(t)?t.bundle.displayName:t.manifest.name;return i.localeCompare(a)});break;case`name`:e.sort((e,t)=>{let n=$(e)?e.bundle.displayName:e.manifest.name,r=$(t)?t.bundle.displayName:t.manifest.name;return n.localeCompare(r)});break;case`source`:e.sort((e,t)=>{let n=$(e)?e.bundle.installSource??``:e.installSource??``,r=$(t)?t.bundle.installSource??``:t.installSource??``;return n.localeCompare(r)});break}return e},[Fe,ye]);return a(`div`,{className:`space-y-3`,children:[[...O.entries()].map(([e,t])=>l(`div`,{className:`rounded-md border border-danger/30 bg-danger/5 px-2.5 py-1.5 text-[11px]`,children:a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`space-y-0.5`,children:[l(`div`,{className:`font-medium text-danger`,children:m(`systemPage.addons.updateFailed`,{name:e})}),l(`div`,{className:`text-foreground-subtle font-mono`,children:t})]}),l(`button`,{type:`button`,onClick:()=>j(e),className:`text-foreground-subtle hover:text-foreground text-[10px]`,children:m(`common.dismiss`)})]})},e)),a(`div`,{className:`flex items-center gap-x-2 gap-y-1.5 flex-wrap`,children:[a(`div`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:m(`admin.system.addons.sort`,`Sort:`)}),a(`select`,{value:ye,onChange:e=>be(e.target.value),className:`rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:outline-none focus:border-primary/50`,children:[l(`option`,{value:`type`,children:m(`admin.system.addons.bundlesFirst`,`Bundles first`)}),l(`option`,{value:`name`,children:m(`admin.system.addons.name`,`Name`)}),l(`option`,{value:`source`,children:m(`admin.system.addons.installSource`,`Install source`)})]})]}),a(`div`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:m(`admin.system.addons.view`,`View:`)}),l(`div`,{className:`flex rounded-md border border-border overflow-hidden text-[10px] font-medium`,children:[`grouped`,`flat`].map(e=>l(`button`,{type:`button`,onClick:()=>Ce(e),className:`px-2 py-1 transition-colors capitalize ${xe===e?`bg-primary/10 text-primary`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`}`,title:e===`grouped`?m(`admin.system.addons.groupMultiAddonPackagesInto`,`Group multi-addon packages into a bundle card`):m(`admin.system.addons.showEveryAddonAsIts`,`Show every addon as its own card`),children:e},e))})]}),d.isHub&&a(`div`,{className:`flex items-center gap-1.5`,children:[l(b,{className:`h-3 w-3 text-foreground-subtle`}),l(`span`,{className:`text-[10px] text-foreground-subtle`,children:m(`admin.system.addons.autoUpdate`,`Auto-Update:`)}),l(`div`,{className:`flex rounded-md border border-border overflow-hidden text-[10px] font-medium`,children:[`off`,`latest`,`beta`].map(e=>l(`button`,{type:`button`,onClick:()=>P.mutate({channel:e}),disabled:P.isPending,className:`px-2 py-1 transition-colors capitalize ${N?.channel===e?e===`off`?`bg-gray-700 text-gray-200`:e===`latest`?`bg-blue-500/20 text-blue-400`:`bg-amber-500/20 text-amber-400`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`} ${e===`off`?``:`border-l border-border`}`,children:e},e))})]}),d.isHub&&a(`div`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:m(`admin.system.addons.checkEvery`,`Check every:`)}),l(`select`,{className:`rounded-md border border-border bg-transparent px-1.5 py-1 text-[10px] font-medium text-foreground-subtle`,value:N?.updateCheckIntervalSeconds??21600,disabled:F.isPending||N===void 0,onChange:e=>{N!==void 0&&F.mutate({channel:N.channel,updateCheckIntervalSeconds:Number(e.target.value)})},children:ft.map(e=>l(`option`,{value:e.seconds,children:e.label},e.seconds))})]}),ne>0&&a(`button`,{type:`button`,onClick:()=>void _e(),disabled:z.isPending,className:`flex items-center gap-1 px-2 py-1 text-[11px] rounded-md bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 border border-blue-500/30 disabled:opacity-50 transition-colors font-medium`,children:[z.isPending?l(w,{className:`w-3 h-3 animate-spin`}):l(v,{className:`w-3 h-3`}),z.isPending?m(`admin.system.addons.updating`,`Updating…`):m(`admin.system.addons.updateAll`,`Update All ({{nonSystemUpdateCount}})`,{nonSystemUpdateCount:ne})]}),a(`button`,{type:`button`,onClick:f,disabled:p||z.isPending,className:`flex items-center gap-1 px-2 py-1 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors`,children:[l(b,{className:`w-3 h-3 ${p?`animate-spin`:``}`}),m(`common.refresh`,`Refresh`)]})]}),a(`div`,{className:`flex flex-wrap items-center gap-1.5`,role:`group`,"aria-label":m(`admin.system.addons.filterInstalledAddons`,`Filter installed addons`),children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:m(`admin.system.addons.filter`,`Filter:`)}),[{id:`updatable`,label:m(`admin.system.addons.updatable`,`Updatable`),pressed:Y,toggle:()=>De(!Y)},{id:`error`,label:m(`admin.system.addons.inError`,`In error ({{count}})`,{count:je}),pressed:X,toggle:()=>ke(!X)},{id:`npm`,label:`npm`,pressed:Z===`npm`,toggle:()=>Ae(Z===`npm`?null:`npm`)},{id:`dev`,label:m(`admin.system.addons.dev`,`Dev`),pressed:Z===`dev`,toggle:()=>Ae(Z===`dev`?null:`dev`)}].map(e=>l(`button`,{type:`button`,"aria-pressed":e.pressed,onClick:e.toggle,className:e.pressed?ut:dt,children:e.label},e.id))]}),a(`div`,{className:`flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-2`,children:[a(`div`,{className:`relative flex-1 min-w-0 sm:min-w-[200px]`,ref:te,children:[l(de,{type:`text`,value:g,onChange:e=>{_(e.target.value),C(!0)},onFocus:()=>C(!0),placeholder:m(`admin.system.addons.searchAddonsOnNpm`,`Search addons on npm...`),"aria-label":m(`admin.system.addons.searchAddonsOnNpm2`,`Search addons on npm`),disabled:z.isPending,leftSlot:l(S,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),rightSlot:L?l(w,{className:`h-3 w-3 animate-spin`}):void 0}),x&&I&&I.length>0&&a(`div`,{className:`absolute left-0 right-0 top-full mt-1 z-40 rounded-md border border-border bg-surface shadow-xl overflow-hidden`,children:[I.length>0&&l(`div`,{className:`px-3 py-1.5 text-[10px] uppercase tracking-wide text-foreground-subtle border-b border-border`,children:m(`systemPage.addons.npmResults`,{count:I.length})}),I&&I.length>0&&l(`div`,{className:`max-h-72 overflow-auto divide-y divide-border`,children:I.map(e=>l(st,{addon:e,installing:W.isPending,onInstall:e=>W.mutate({packageName:e})},e.name))})]})]}),l(rt,{onUploadSuccess:()=>{h.invalidateQueries({queryKey:[[`addons`]]}),f()}})]}),J&&a(`div`,{className:`flex items-center gap-2 px-2.5 py-1.5 rounded-md bg-primary/10 border border-primary/30 text-xs`,children:[l(`span`,{className:`text-foreground-subtle`,children:m(`admin.system.addons.filteringByCapability`,`Filtering by capability:`)}),l(`span`,{className:`font-mono text-primary font-semibold`,children:J}),l(`button`,{type:`button`,onClick:Ne,className:`ml-auto text-xs text-foreground-subtle hover:text-foreground underline`,children:m(`admin.system.addons.clear`,`Clear`)})]}),J&&l(ct,{capability:J,installing:W.isPending,onInstall:e=>W.mutate({packageName:e})}),J&&Q.length>0&&l(`h2`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:m(`admin.system.addons.installed`,`Installed`)}),ge&&a(`div`,{className:`fixed top-[calc(env(safe-area-inset-top)+1rem)] right-[calc(env(safe-area-inset-right)+1rem)] z-50 flex items-start gap-2 px-3 py-2.5 rounded-md border border-green-500/30 bg-green-500/10 shadow-lg backdrop-blur-sm max-w-sm pointer-events-auto`,children:[l(ee,{className:`w-4 h-4 shrink-0 mt-0.5 text-green-400`}),a(`div`,{children:[l(`div`,{className:`text-[11px] font-semibold text-foreground`,children:m(`admin.system.addons.bulkUpdateCompleted`,`Bulk update completed`)}),l(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:m(`admin.system.addons.systemPackagesUpdatedHubRestarted`,`System packages updated — hub restarted successfully.`)})]})]}),Q.length===0&&l(`div`,{className:`text-xs text-foreground-subtle`,children:e.length===0?m(`admin.system.addons.noAddonsInstalled`,`No addons installed`):J?m(`admin.system.addons.noInstalledAddonDeclaresThe`,`No installed addon declares the "{{capabilityFilter}}" capability. Any addon you can install appears under "Available to install" above.`,{capabilityFilter:J}):m(`admin.system.addons.noAddonsCompatibleWithPlacement`,`No addons compatible with {{name}} (placement filter active)`,{name:d.name})}),l(`div`,{className:`space-y-1.5`,children:Ie.map(e=>{let t=$(e)?e.bundle.packageName:e.manifest.packageName,n=E.get(t),r=$(e)?e.representative:e,i=n?e=>M.mutate({name:t,version:e,nodeId:d.id}):void 0,a=ce.get(t)??null,s=a!==null&&Me(a);return l(tt,{addon:r,clusterStatus:o?.[r.manifest.id],bundle:$(e)?e.bundle:void 0,availableUpdate:n,isUpdating:re.has(t)||s,jobProgress:a,onUpdate:i,disabledByBulk:z.isPending,selectedNode:d},$(e)?t:e.manifest.id)})})]})}function xt(){let{t:e}=K(),n=s(),{data:r}=L(void 0),{nodes:i}=pe(),{selection:o,selectNode:u,requestedNodeId:d}=De(i.length>0?i:[ht]),f=o.node??ht,p=f.id,m=i.length>0?o.staleNodeId:null,{data:h,isLoading:g,isError:_}=B({nodeId:p}),v=W(),y=I(),x=v.isPending||y.isPending,S=async()=>{await v.mutateAsync({nodeId:p}),await y.mutateAsync(),n.invalidateQueries({queryKey:[[`addons`]]})},C=c(v);C.current=v;let w=c(d??`hub`);t(()=>{C.current.mutate({nodeId:w.current})},[]);let ee=(h??[]).map(vt).filter(e=>e!==null);return a(Y,{children:[a(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[l(G,{selectedNodeId:p,onSelect:u}),a(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[!g&&!_&&l(`span`,{className:`text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium`,children:e(`systemPage.addons.installedCount`,{count:ee.length})}),a(`button`,{type:`button`,onClick:()=>void S(),disabled:x,className:`inline-flex items-center gap-1 px-2 py-1 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors`,title:e(`admin.system.addons.reFetchAddonsCheckNpm`,`Re-fetch addons + check npm for new versions`),children:[l(b,{className:`w-3 h-3 ${x?`animate-spin`:``}`}),e(`admin.system.addons.checkForUpdates`,`Check for updates`)]})]})]}),l(Z,{staleNodeId:m,shownNodeName:f.name}),l(ot,{selectedNode:f}),g&&l(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:e(`common.loading`,`Loading…`)}),_&&l(`div`,{className:`text-xs text-danger`,children:e(`admin.system.addons.failedToLoadAddons`,`Failed to load addons`)}),!g&&!_&&l(bt,{addons:ee,clusterStatus:r,selectedNode:f,onRefresh:()=>void S(),isRefreshing:x})]})}export{xt as AddonsPage};
@@ -1 +1 @@
1
- import{b as e,x as t}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{_t as n}from"./src-BVr0SnD-.js";function r({icon:r,title:i,subtitle:a,actions:o,nav:s,embedded:c=!1,children:l}){return c?t(e,{children:l}):t(n,{icon:r,title:i,subtitle:a,actions:o,nav:s,children:l})}export{r as t};
1
+ import{b as e,x as t}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{vt as n}from"./src-DKc14e9G.js";function r({icon:r,title:i,subtitle:a,actions:o,nav:s,embedded:c=!1,children:l}){return c?t(e,{children:l}):t(n,{icon:r,title:i,subtitle:a,actions:o,nav:s,children:l})}export{r as t};
@@ -1 +1 @@
1
- import{$ as e,L as t,x as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{ht as r}from"./src-BVr0SnD-.js";import{mr as i}from"./index-Cskol4XA.js";e();function a({paramName:e=`tab`,defaultSection:a,sections:o,...s}){let[c,l]=i(),u=a??o[0]?.id??``,d=c.get(e),f=o.some(e=>e.id===d)?d??u:u,p=t((t,n)=>{l(r=>{let i=new URLSearchParams(r);for(let e of n)i.delete(e);return i.set(e,t),i},{replace:!0})},[e,l]);return n(r,{...s,paramName:e,defaultSection:a,sections:o,activeSection:f,onSectionChange:p})}export{a as t};
1
+ import{$ as e,L as t,x as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{gt as r}from"./src-DKc14e9G.js";import{mr as i}from"./index-C8XwyZGE.js";e();function a({paramName:e=`tab`,defaultSection:a,sections:o,...s}){let[c,l]=i(),u=a??o[0]?.id??``,d=c.get(e),f=o.some(e=>e.id===d)?d??u:u,p=t((t,n)=>{l(r=>{let i=new URLSearchParams(r);for(let e of n)i.delete(e);return i.set(e,t),i},{replace:!0})},[e,l]);return n(r,{...s,paramName:e,defaultSection:a,sections:o,activeSection:f,onSectionChange:p})}export{a as t};
@@ -0,0 +1,3 @@
1
+ import{$ as e,B as t,G as n,J as r,L as i,S as a,a as o,b as s,q 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-CEHpkaJP.js";import{$r as d,D as f,Di as p,Fn as m,G as h,It as g,L as _,Mi as v,On as y,Or as b,Q as x,Wr as S,Xi as C,Xr as w,Yt as T,Zt as E,bn as D,dn as ee,dt as O,fn as k,ji as A,kn as j,or as M,ot as N}from"./player-overlays-CvKnZb5M.js";import{Ar as P,kr as F,wa as I}from"./client-BbPYrWg7.js";import{n as L,t as R}from"./send-CNzJmniJ.js";import{t as te}from"./message-square-plus-D64e2l9L.js";import{$n as z,Cn as B,Dr as V,Er as H,Gn as U,Gr as W,Ku as ne,Or as re,Qr as G,Qu as ie,St as K,Un as q,Ur as ae,Zu as J,ht as oe,kr as Y,pt as se,rt as ce,sr as le,uo as ue,wn as de,xn as X,xt as fe}from"./src-DKc14e9G.js";import{t as Z}from"./i18n-BO6gCPcC.js";import{t as Q}from"./useTranslation-D3Is_4B6.js";import"./mount-B5MjkWnS.js";import{mr as pe,x as me}from"./index-C8XwyZGE.js";import{t as he}from"./AdminSectionedPage-BIoU14zn.js";import{t as ge}from"./AdminPage-B4QlIiKh.js";e();var _e=`__redacted__`,ve=[`llm`,`listProfiles`],ye=[`llm`,`listProfileKinds`],be=[`llm`,`getDefaults`],xe=[`llm`,`listRuntimeNodes`],Se=[`llm`,`listModelCatalog`],Ce=[`llm`,`getUsage`],we=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],Te=new Map([[`cloud`,d],[`plug`,y],[`cpu`,w],[`server`,ee],[`sparkles`,E]]);function Ee(e){return Te.get(e)??v}function De(e){return typeof e==`string`&&e.length>0?e:void 0}function Oe(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 ke(e){return e===!0}function Ae(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 je={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 Me(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=je[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 Ne={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`};function Pe(e){return e.reachable?e.status===void 0?`success`:Ne[e.status.state]:`danger`}function Fe(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Me(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Me(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 Ie(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:P.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:P.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:P.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:P.idleMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutIdleHint`)}],retry:[{type:`boolean`,key:`retryEnabled`,label:Z.t(`helpers.aiProfileForm.retry`),description:Z.t(`helpers.aiProfileForm.retryHint`)},{type:`number`,key:`retryMaxAttempts`,label:Z.t(`helpers.aiProfileForm.retryMaxAttempts`),min:1,max:5,default:1,showWhen:{field:`retryEnabled`,equals:!0}}],toolsEnabled:[{type:`boolean`,key:`toolsEnabled`,label:Z.t(`helpers.aiProfileForm.toolsEnabled`),description:Z.t(`helpers.aiProfileForm.toolsEnabledHint`)}]}}var Le=[`temperature`,`topP`,`topK`,`maxTokens`,`contextLength`,`systemPrompt`],Re=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function ze(e,t){let n=Ie();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Be(e){let t=ze(e,Le);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function Ve(e){let t=ze(e,Re);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function He(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 Ue(e,t){return{...e.features,...t?.features}}function We(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ge(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?Oe(i[e])??t:n??t,o=e=>r.includes(e)?Oe(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`systemPrompt`)?De(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,P.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,P.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,P.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,P.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:ke(i.retryEnabled),maxAttempts:Oe(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?ke(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 Ke=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function qe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Je({nodeId:e,value:t,onChange:i}){let{t:s}=Q(),c=N(),[d,f]=r(``),[p,m]=r(null),[h,g]=r(!1),_=o({queryKey:Se,queryFn:()=>c.trpcClient.llm.listModelCatalog.query({})}),v=o({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>c.trpcClient.llm.listNodeModels.query({nodeId:e})}),y=l({mutationFn:e=>c.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&i({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:t=>c.trpcClient.llm.installModel.mutate({nodeId:e,model:t}),onSuccess:()=>{g(!0),v.refetch()}}),x=o({queryKey:xe,enabled:b.isPending,refetchInterval:b.isPending?Ke:!1,queryFn:()=>c.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,C=n(()=>{let t=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(t=>({value:`node:${t.file}`,label:s(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:t.file,size:$(t.sizeBytes),node:e})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:s(`ai.selectModel`,`Select a model…`)},...t,...n,...r]},[_.data,v.data,p,e,s]),w=e=>{if(e===``){i(null);return}if(e===`custom`){if(p?.ok!==!0)return;i({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);i({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&i({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},T=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return a(`div`,{className:`space-y-3`,children:[u(K,{label:s(`ai.model`,`Model`),required:!0,children:u(ne,{id:`ai-model`,"aria-label":s(`ai.model`,`Model`),value:qe(t),options:C,onChange:e=>w(e.target.value)})}),u(K,{label:s(`ai.hfTitle`,`Add a model from Hugging Face`),description:s(`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:a(`div`,{className:`flex gap-2`,children:[u(J,{"aria-label":s(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>f(e.target.value),placeholder:s(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())}}),a(W,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>T(),children:[y.isPending?u(M,{className:`h-3.5 w-3.5 animate-spin`}):u(k,{className:`h-3.5 w-3.5`}),s(`ai.hfCheck`,`Check`)]})]})}),y.isError&&u(H,{message:y.error instanceof Error?y.error.message:s(`common.error`,`Error`)}),p?.ok===!1&&u(H,{message:p.message,action:a(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>u(W,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&u(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>T(p.requiredBytes),children:s(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&a(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[a(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),u(G,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),u(G,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),a(`div`,{className:`flex items-center gap-2`,children:[a(W,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?u(M,{className:`h-3.5 w-3.5 animate-spin`}):u(S,{className:`h-3.5 w-3.5`}),h?s(`ai.hfInstalled`,`Downloaded`):s(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),x!==void 0&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:x.phase===`verifying`?s(`ai.hfVerifying`,`verifying {{file}}…`,{file:x.file}):s(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:x.file,index:x.fileIndex,count:x.fileCount,done:$(x.downloadedBytes),total:x.totalBytes===void 0?``:` / ${$(x.totalBytes)}`})})]}),b.isError&&u(H,{message:b.error instanceof Error?b.error.message:s(`common.error`,`Error`)})]})]})}function Ye({value:e,onChange:t}){let{t:n}=Q(),r=N(),i=o({queryKey:xe,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})});return a(`div`,{children:[u(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:n(`ai.appleNode`,`Mac that runs it`)}),i.isPending&&a(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(M,{className:`h-3.5 w-3.5 animate-spin`}),n(`ai.appleAsking`,`Asking the nodes…`)]}),i.isError&&u(`p`,{className:`text-[11px] text-danger`,children:i.error instanceof Error?i.error.message:n(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),i.isSuccess&&i.data.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),i.isSuccess&&i.data.length>0&&u(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:i.data.map(r=>{let i=Me(r),o=i.nodeId===e;return a(`button`,{type:`button`,role:`radio`,"aria-checked":o,disabled:!i.selectable&&!o,onClick:()=>t(i.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${o?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block font-medium text-foreground`,children:i.nodeId}),i.detail!==null&&u(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:i.detail})]}),u(G,{variant:i.tone,children:n(i.labelKey,i.labelDefault)})]},i.nodeId)})}),u(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:n(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function Xe(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Ze({providerConfig:e,onProviderConfigChange:t}){return u(Ye,{value:Xe(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function Qe({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let i=F.safeParse(e.model),a=i.success?{model:i.data,modelId:n.id,supportsVision:n.supportsVision}:null;return u(Je,{nodeId:Xe(e,`nodeId`)??`hub`,value:a,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 $e=new Map([[`ai/apple-node`,Ze],[`ai/managed-model`,Qe]]);function et(e){return $e.get(e)??null}e();function tt({kind:e,className:t}){return u(Ee(e.icon),{className:t,"aria-hidden":!0})}function nt({kinds:e,onPick:t,onCancel:r}){let{t:i}=Q(),a=n(()=>Ae(e),[e]),o=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return u(oe,{open:!0,onClose:r,title:i(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:u(fe,{emptyMessage:i(`ai.noKinds`,`No AI provider is installed.`),onPick:e=>{let n=o.get(e);n!==void 0&&t(n)},groups:a.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:u(tt,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function rt(e){return(e?.sections??[]).flatMap(e=>e.fields)}function it(...e){let t={};for(let n of e)for(let e of rt(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function at(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function ot(e,t){return rt(e).filter(e=>`required`in e&&e.required===!0&&!at(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var st={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 ct(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:Ue(e,n).vision}}function lt({kind:e,existing:t,onSave:i,onCancel:o,onChangeKind:c,saving:d,error:p}){let{t:m}=Q(),h=N(),[g,v]=r(t?.name??e.label),[y,b]=r(()=>t===null?it(e.connectionSchema,e.advancedSchema):{...t.providerConfig}),[x,S]=r(()=>He(t)),[w,T]=r(()=>ct(e,t)),[E,ee]=r(!1),O=e.providerWidgets??[],k=O.filter(e=>e.placement===`connection`),A=O.find(e=>e.placement===`model`)??null,j=n(()=>[...I(e.connectionSchema)].some(e=>t?.providerConfig[e]===_e),[t,e.connectionSchema]),P=l({mutationFn:()=>h.trpcClient.llm.listModels.mutate({addonId:e.addonId,kind:e.kind,connection:y,...t===null?{}:{profileId:t.id}}),onSuccess:t=>{t.ok&&T(n=>{let r=t.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ue(e,r).vision}})}}),F=We(e,P.data?.ok===!0?P.data.models:null),L=F.find(e=>e.id===w.id),R=Ue(e,L),te=Be(e.profileFields),B=Ve(e.profileFields),V=ot(e.connectionSchema,y),U=O.some(e=>(e.requires??[]).some(e=>!at(y[e]))),re=e.modelCatalog===`fetch`&&A===null,ie=rt(e.connectionSchema).length>0||k.length>0,ae=t=>{T({id:t,supportsVision:Ue(e,F.find(e=>e.id===t)).vision})},Y=d||g.trim()===``||w.id.trim()===``||V.length>0||U,se=()=>{i(Ge(e,t,{name:g.trim(),model:w.id.trim(),supportsVision:e.visionEditable?w.supportsVision:!1,common:x,providerConfig:y}))},ce=t===null?m(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):m(`ai.editProfile`,`Edit {{name}}`,{name:t.name}),ue=t=>{let n=et(t);return n===null?u(H,{variant:`warning`,message:m(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:t})}):u(n,{descriptor:e,providerConfig:y,onProviderConfigChange:b,model:w,onModelChange:T},t)};return u(oe,{open:!0,onClose:o,title:ce,error:p,width:`lg`,testId:`ai-profile-editor`,footer:a(s,{children:[V.length>0&&u(G,{variant:`warning`,children:m(`ai.missingRequired`,`required: {{fields}}`,{fields:V.join(`, `)})}),V.length===0&&U&&u(G,{variant:`warning`,children:m(`ai.completeProvider`,`complete the provider settings`)}),V.length===0&&!U&&w.id.trim()===``&&u(G,{variant:`warning`,children:m(`ai.pickModelFirst`,`pick a model`)}),a(W,{size:`sm`,type:`button`,disabled:Y,onClick:se,children:[d&&u(M,{className:`h-3.5 w-3.5 animate-spin`}),t===null?m(`ai.createProfile`,`Create profile`):m(`ai.saveChanges`,`Save changes`)]})]}),children:a(`div`,{className:_,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`ai-editor-provider`,children:[u(tt,{kind:e,className:`h-4 w-4 text-foreground-subtle`}),u(`span`,{className:`text-xs font-medium text-foreground`,children:e.label}),u(G,{variant:`neutral`,children:e.addonId}),c!==void 0&&a(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:c,children:[u(C,{className:`h-3.5 w-3.5`}),m(`ai.changeKind`,`Change type`)]})]}),u(K,{label:m(`ai.name`,`Name`),required:!0,children:u(J,{id:`ai-profile-name`,"aria-label":m(`ai.name`,`Name`),value:g,onChange:e=>v(e.target.value),placeholder:e.label})}),ie&&u(X,{headingId:`ai-editor-connection`,title:m(`ai.sectionConnection`,`Connection`),actions:re?a(W,{size:`sm`,variant:`secondary`,type:`button`,disabled:P.isPending,onClick:()=>P.mutate(),"data-testid":`ai-verify-models`,children:[P.isPending?u(M,{className:`h-3.5 w-3.5 animate-spin`}):u(D,{className:`h-3.5 w-3.5`}),m(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:a(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[rt(e.connectionSchema).length>0&&u(le,{bare:!0,schema:e.connectionSchema,values:y,onChange:b}),k.map(e=>ue(e.id)),j&&u(`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&&u(G,{variant:`success`,"data-testid":`ai-models-found`,children:m(`ai.modelsFound`,`{{count}} models found`,{count:P.data.models.length})}),P.data?.ok===!1&&u(H,{title:m(st[P.data.code]?.key??`ai.listNetwork`,st[P.data.code]?.fallback??`Endpoint unreachable`),message:P.data.message}),P.isError&&u(H,{message:P.error instanceof Error?P.error.message:m(`common.error`,`Error`)})]})}),u(X,{headingId:`ai-editor-model`,title:m(`ai.sectionModel`,`Model`),children:a(`div`,{className:`${f} space-y-3`,children:[A===null?a(s,{children:[F.length>0&&u(ne,{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!==``&&ae(e.target.value)}}),u(K,{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:u(J,{id:`ai-model-id`,"aria-label":m(`ai.customModel`,`Model id`),value:w.id,onChange:e=>T({...w,id:e.target.value}),placeholder:F[0]?.id??`model-id`})})]}):ue(A.id),a(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(w.supportsVision||!e.visionEditable&&R.vision)&&u(G,{variant:`info`,children:m(`ai.featureVision`,`vision`)}),R.tools&&u(G,{variant:`neutral`,children:m(`ai.featureTools`,`tools`)}),R.streaming&&u(G,{variant:`neutral`,children:m(`ai.featureStreaming`,`streaming`)})]}),e.visionEditable&&u(K,{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:u(q,{checked:w.supportsVision,onCheckedChange:e=>T({...w,supportsVision:e}),"aria-label":m(`ai.supportsVision`,`Supports vision`)})})]})}),te!==null&&u(X,{headingId:`ai-editor-generation`,title:m(`ai.sectionGeneration`,`Generation`),children:u(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:u(le,{bare:!0,schema:te,values:x,onChange:S})})}),(B!==null||e.advancedSchema!==void 0)&&u(z,{expanded:E,onExpandedChange:ee,header:u(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:m(`ai.sectionAdvanced`,`Advanced`)}),children:a(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[B!==null&&u(le,{bare:!0,schema:B,values:x,onChange:S}),e.advancedSchema!==void 0&&u(le,{bare:!0,schema:e.advancedSchema,values:y,onChange:b})]})})]})})}e();function ut(e){return[{key:`name`,header:e.t(`ai.colProfile`,`Profile`),render:t=>{let n=e.kindByName.get(t.kind);return a(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:n?.label??t.kind,children:n===void 0?u(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):u(tt,{kind:n,className:`h-4 w-4 text-foreground-subtle`})}),a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block truncate font-medium text-foreground`,children:t.name}),e.testResult?.id===t.id&&u(`span`,{className:`block truncate ${e.testResult.ok?`text-success`:`text-danger`}`,children:e.testResult.text})]})]})}},{key:`kind`,header:e.t(`ai.colKind`,`Kind`),nowrap:!0,render:t=>u(`span`,{className:`text-foreground-muted`,children:e.kindByName.get(t.kind)?.label??t.kind})},{key:`model`,header:e.t(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:e.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:t=>t.supportsVision?u(G,{variant:`info`,style:`outline`,children:e.t(`ai.vision`,`vision`)}):u(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:e.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?u(G,{variant:`default`,children:e.providerConfig.nodeId}):u(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>u(q,{checked:t.enabled,onCheckedChange:()=>e.onToggle(t),"aria-label":Z.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:t.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>a(`span`,{className:`flex items-center justify-end gap-1`,children:[u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),"aria-label":e.t(`ai.test`,`Test`),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?u(M,{className:`h-3.5 w-3.5 animate-spin`}):u(R,{className:`h-3.5 w-3.5`})}),u(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),"aria-label":e.t(`common.edit`,`Edit`),title:e.t(`common.edit`,`Edit`),children:u(m,{className:`h-3.5 w-3.5`})}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),"aria-label":e.t(`common.delete`,`Delete`),title:e.t(`common.delete`,`Delete`),children:u(g,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function dt(){let{t:e}=Q(),s=N(),{state:c,openEdit:d,close:p}=se(),m=ae(),[h,g]=r(null),[v,y]=r(null),[b,x]=r(null),S=o({queryKey:ve,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),C=o({queryKey:ye,queryFn:async()=>(await s.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),w=()=>{S.refetch()},T=i(()=>{g(null),x(null),p()},[p]);t(()=>{c.mode===`closed`&&g(null)},[c.mode]);let D=l({mutationFn:e=>s.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{T(),w()},onError:t=>x(t instanceof Error?t.message:e(`ai.saveFailed`,`Save failed`))}),ee=l({mutationFn:e=>s.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:w}),O=l({mutationFn:e=>s.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>y({id:t.id,ok:e.ok,text:e.ok?Z.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),k=S.data??[],A=n(()=>C.data??[],[C.data]),j=n(()=>{let e=new Map;for(let t of A)e.set(t.kind,t);return e},[A]),M=c.mode===`edit`?k.find(e=>e.id===c.id)??null:null,P=M===null?null:j.get(M.kind)??null,F=c.mode===`new`&&h===null,I=c.mode===`new`?h:P,L=c.mode===`edit`?M:null,R=I!==null&&(c.mode===`new`||L!==null),te=async t=>{await m({title:e(`ai.deleteProfileTitle`,`Delete profile?`),message:e(`ai.deleteProfileMessage`,`Delete "{{name}}". Features that name it will no longer get an answer from it.`,{name:t.name}),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`})&&ee.mutate(t)};return a(`div`,{className:_,children:[u(ft,{profiles:k}),u(X,{headingId:`ai-profiles-list`,title:e(`ai.profilesList`,`Profiles`),children:S.isPending?a(`div`,{className:`${f} space-y-2`,"data-testid":`ai-profiles-loading`,children:[u(Y,{className:`h-8 w-full`}),u(Y,{className:`h-8 w-full`}),u(Y,{className:`h-8 w-full`})]}):S.isError?u(`div`,{className:f,children:u(H,{title:e(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:e(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):k.length===0?u(V,{icon:E,title:e(`ai.noProfilesTitle`,`No AI profiles yet`),description:e(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):u(B,{columns:ut({kindByName:j,testResult:v,testingId:O.isPending?O.variables?.id??null:null,t:e,onToggle:e=>D.mutate({...e,enabled:!e.enabled}),onTest:e=>O.mutate(e),onEdit:e=>{j.has(e.kind)&&(x(null),g(null),d(e.id))},onDelete:e=>void te(e)}),rows:k,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:de})}),F&&u(nt,{kinds:A,onCancel:T,onPick:e=>{x(null),g(e)}}),R&&I!==null&&u(lt,{kind:I,existing:L,saving:D.isPending,error:b,onSave:e=>D.mutate(e),onCancel:T,...c.mode===`new`?{onChangeKind:()=>{x(null),g(null)}}:{}})]})}function ft({profiles:e}){let{t}=Q(),n=N(),r=o({queryKey:be,queryFn:()=>n.trpcClient.llm.getDefaults.query({})}),i=l({mutationFn:e=>n.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{r.refetch()}}),s=e=>(r.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,c=e=>e===`vision`?t(`ai.defaultVision`,`Default vision profile`):t(`ai.defaultText`,`Default text profile`);return u(X,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:u(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:we.map(({purpose:n,visionOnly:r})=>{let o=r?e.filter(e=>e.supportsVision):e,l=s(n),d=e.find(e=>e.id===l);return a(`div`,{children:[u(U,{className:`mb-1 block`,htmlFor:`llm-default-${n}`,children:c(n)}),u(ne,{id:`llm-default-${n}`,"aria-label":c(n),value:l,onChange:e=>i.mutate({purpose:n,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:t(`ai.none`,`None`)},...l!==``&&!o.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...o.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&u(`p`,{className:`mt-1 text-xs text-danger`,children:t(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&u(`p`,{className:`mt-1 text-xs text-warning`,children:t(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),i.error!=null&&u(`p`,{className:`mt-1 text-xs text-danger`,children:String(i.error)})]},n)})})})}e();var pt=5e3;function mt(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ht(){let{t:e}=Q(),t=N(),r=o({queryKey:xe,refetchInterval:pt,queryFn:()=>t.trpcClient.llm.listRuntimeNodes.query({})}),i=n(()=>[{key:`node`,header:e(`ai.colNode`,`Node`),render:e=>u(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:e(`ai.colState`,`State`),nowrap:!0,render:t=>a(`span`,{className:`flex items-center gap-1.5`,children:[u(G,{variant:Pe(t),children:t.reachable?t.status?.state??e(`ai.ready`,`ready`):e(`ai.unreachable`,`unreachable`)}),t.status?.downloadProgress!==void 0&&u(G,{variant:`info`,children:`${String(Math.round(t.status.downloadProgress*100))}%`})]})},{key:`model`,header:e(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:e(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:mt(e.disk.modelsBytes)})},{key:`features`,header:e(`ai.colFeatures`,`Features`),render:t=>{let n=Fe(t);if(n.length===0)return u(`span`,{className:`text-foreground-subtle`,children:`—`});let r=n.flatMap(e=>e.detail===null?[]:[e.detail]);return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[u(`span`,{className:`flex flex-wrap gap-1`,children:n.map(t=>u(G,{variant:t.tone,children:e(t.labelKey)},t.id))}),r.length>0&&u(`span`,{className:`text-foreground-subtle`,children:r.join(` · `)})]})}},{key:`error`,header:e(`ai.colError`,`Error`),render:e=>e.error===void 0?u(`span`,{className:`text-foreground-subtle`,children:`—`}):u(`span`,{className:`text-danger`,children:e.error})}],[e]),s=r.data??[];return u(X,{headingId:`ai-runtimes-list`,title:e(`ai.runtimesList`,`Nodes`),children:r.isPending?a(`div`,{className:`${f} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[u(Y,{className:`h-8 w-full`}),u(Y,{className:`h-8 w-full`})]}):r.isError?u(`div`,{className:f,children:u(H,{title:e(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:r.error instanceof Error?r.error.message:e(`common.error`,`Error`),onRetry:()=>void r.refetch()})}):s.length===0?u(V,{icon:ee,title:e(`ai.noRuntimesTitle`,`No runtime nodes`),description:e(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):u(B,{columns:i,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:de})})}var gt=x(`/addon/ai/test-chat`),_t=x(`/addon/ai/test-chat/chats`),vt=6e5;function yt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),vt)}function bt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xt(e){if(!bt(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 St=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Ct(e){let t;try{t=JSON.parse(e)}catch{return null}if(!bt(t))return null;switch(t.kind){case`status`:{let e=St.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:xt(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*wt(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=Ct(e);t!==null&&(yield t)}a=r.indexOf(`
3
+ `)}}let e=r.trim();if(e.length>0){let t=Ct(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Tt(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Et(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Dt(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 Ot(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 kt(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`)}}e();var At=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],jt=360*60*1e3,Mt=40,Nt=160,Pt={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Ft(){let{t:e}=Q(),s=N(),[l,d]=r(``),[m,h]=r(``),[v,y]=r(``),[b,x]=r([]),[S,C]=r(null),[w,E]=r(`none`),[D,ee]=r(`throwaway`),[k,j]=r(null),[M,P]=r([]),[F,I]=r(null),[L,z]=r(null),B=c(null);t(()=>()=>B.current?.abort(),[]);let V=i(async()=>{let e=await fetch(_t,{credentials:`same-origin`});e.ok&&P((await e.json()).chats??[])},[]);t(()=>{D===`persistent`&&V()},[D,V]);let re=o({queryKey:ve,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),G=n(()=>(re.data??[]).filter(e=>e.enabled),[re.data]),K=G.find(e=>e.id===l)??null,q=L!==null,ae=i(async(t,n)=>{let r=new AbortController;B.current=r,I(null);let i=yt(K??{});z({...Pt,firstTokenTimeoutMs:i??0});let a=``,o=null,s,c=null,u=null,d;try{let e=await fetch(gt,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:r.signal,body:JSON.stringify({profileId:l,messages:t,...m.trim()===``?{}:{system:m.trim()},...n===void 0?{}:{attachment:n},...i===void 0?{}:{firstTokenTimeoutMs:i},...D===`persistent`?{persist:!0,...k===null?{}:{conversationId:k}}:{}})});if(!e.ok||e.body===null){let t=await e.text().catch(()=>``);throw Error(t.length>0?t:`HTTP ${String(e.status)}`)}for await(let t of wt(e.body))switch(t.kind){case`status`:z(e=>({...e??Pt,phase:t.phase}));break;case`meta`:o=t.mediaSent,s=t.model,z(e=>({...e??Pt,firstTokenTimeoutMs:t.firstTokenTimeoutMs,mediaSent:t.mediaSent}));break;case`token`:a+=t.text,z(e=>({...e??Pt,text:a}));break;case`done`:u={outputTokens:t.outputTokens,latencyMs:t.latencyMs},d=t.conversationId;break;case`error`:c=`${t.code}: ${t.message}`;break}}catch(t){r.signal.aborted||I(t instanceof Error?t.message:e(`common.error`,`Error`))}finally{B.current=null,z(null)}d!==void 0&&(j(d),V());let f=r.signal.aborted&&a.length>0;c===null&&a.length===0&&!f||x(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:c??a,...c===null?{}:{failed:!0},...o===null?{}:{attachment:o},...s!==void 0&&c===null?{model:s}:{},...u===null?{}:u}])},[D,k,K,l,V,m,e]),oe=i(()=>{let e=v.trim();if(e===``||l===``||q)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...S===null?{}:{attachmentLabel:S.label,attachmentKind:S.ref.kind}},n=[...b,t];x(n),y(``);let r=S?.ref;C(null),E(`none`),ae(D===`persistent`&&k!==null?[{role:`user`,content:e}]:Tt(n),r)},[D,k,v,S,l,ae,q,b]),Y=()=>B.current?.abort(),se=()=>{B.current?.abort(),x([]),C(null),y(``),I(null),z(null),j(null)},le=async e=>{B.current?.abort();let t=await fetch(`${_t}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();j(e),x(Dt(n)),z(null),I(null)};return a(`div`,{className:_,children:[u(X,{headingId:`ai-test-setup`,title:e(`ai.testSetup`,`Setup`),children:a(`div`,{className:`${f} space-y-3`,children:[a(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[a(`div`,{children:[u(U,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:e(`ai.profile`,`Profile`)}),u(ne,{id:`ai-test-profile`,value:l,onChange:e=>d(e.target.value),options:[{value:``,label:e(`ai.selectProfile`,`Select a profile…`)},...G.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),G.length===0&&!re.isLoading&&u(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:e(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),a(`div`,{children:[u(U,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:e(`ai.systemPrompt`,`System prompt (optional)`)}),u(J,{id:`ai-test-system`,value:m,onChange:e=>h(e.target.value),placeholder:e(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),u(ce,{label:e(`ai.chatMode`,`Conversation mode`),value:D,options:[{value:`throwaway`,label:e(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:e(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{ee(e),e===`throwaway`&&j(null)}}),D===`persistent`&&a(`div`,{className:`space-y-2`,children:[u(`p`,{className:`text-xs text-foreground-subtle`,children:e(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),a(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:se,children:[u(te,{className:`h-3.5 w-3.5`}),e(`ai.newChat`,`New chat`)]}),M.length>0&&u(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:M.map(e=>u(`button`,{type:`button`,onClick:()=>void le(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-xs hover:bg-surface-hover ${e.id===k?`bg-primary/10`:``}`,children:u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),u(`p`,{className:`text-xs text-foreground-subtle`,children:e(`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.`)}),K!==null&&!K.supportsVision&&u(`p`,{className:`text-xs text-warning`,children:e(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]})}),F!==null&&u(H,{title:e(`ai.chatFailed`,`The test call failed`),message:F}),a(X,{headingId:`ai-test-conversation`,title:e(`ai.testConversation`,`Conversation`),actions:a(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:b.length===0&&S===null,onClick:se,children:[u(g,{className:`h-3.5 w-3.5`}),e(`ai.clearChat`,`Clear`)]}),children:[u(It,{turns:b,live:L}),a(`div`,{className:`${f} space-y-2 border-t border-border`,children:[S!==null&&a(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[S.ref.kind===`snapshot`?u(p,{className:`h-3.5 w-3.5 text-foreground-subtle`}):u(A,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:S.label}),u(ie,{size:`sm`,variant:`ghost`,type:`button`,icon:O,"aria-label":e(`ai.removeAttachment`,`Remove attachment`),onClick:()=>C(null)})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(W,{size:`sm`,variant:w===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>E(w===`snapshot`?`none`:`snapshot`),children:[u(p,{className:`h-3.5 w-3.5`}),e(`ai.attachSnapshot`,`Camera snapshot`)]}),a(W,{size:`sm`,variant:w===`track`?`primary`:`outline`,type:`button`,onClick:()=>E(w===`track`?`none`:`track`),children:[u(A,{className:`h-3.5 w-3.5`}),e(`ai.attachTrack`,`Recent track`)]})]}),w===`snapshot`&&u(zt,{onPick:t=>{C({ref:{kind:`snapshot`,deviceId:t.id},label:e(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t.name})}),E(`none`)}}),w===`track`&&u(Vt,{onPick:(t,n)=>{C({ref:{kind:`track`,trackId:t.trackId,deviceId:t.deviceId},label:e(`ai.trackOf`,`{{class}} on {{name}}`,{class:t.label??t.className,name:n})}),E(`none`)}}),a(`div`,{className:`flex items-center gap-2`,children:[u(J,{value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),oe())},placeholder:e(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":e(`ai.message`,`Message`)}),q?a(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:Y,children:[u(T,{className:`h-3.5 w-3.5`}),e(`ai.stop`,`Stop`)]}):a(W,{size:`sm`,type:`button`,disabled:v.trim()===``||l===``,onClick:oe,children:[u(R,{className:`h-3.5 w-3.5`}),e(`ai.send`,`Send`)]})]})]})]})]})}function It({turns:e,live:t}){let{t:n}=Q();return e.length===0&&t===null?u(V,{icon:L,title:n(`ai.chatEmptyTitle`,`No messages yet`),description:n(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):a(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto ${f}`,children:[e.map(e=>u(Lt,{turn:e},e.id)),t!==null&&a(`div`,{className:`space-y-1`,children:[t.mediaSent!==null&&u(Rt,{attachment:t.mediaSent}),t.text.length>0&&u(Lt,{turn:{id:`live`,role:`assistant`,content:t.text},streaming:!0}),a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[u(M,{className:`h-3.5 w-3.5 animate-spin`}),kt(t.phase,t.firstTokenTimeoutMs)]})]})]})}function Lt({turn:e,streaming:t=!1}){let{t:n}=Q(),r=e.role===`user`,i=e.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return u(`div`,{className:`flex ${r?`justify-end`:`justify-start`}`,children:a(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${r?`border-primary/40 bg-primary/10`:i}`,children:[a(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[e.content,t&&u(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),e.attachment!==void 0&&u(Rt,{attachment:e.attachment}),e.attachmentLabel!==void 0&&a(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachmentKind===`track`?u(A,{className:`h-3 w-3`}):u(p,{className:`h-3 w-3`}),e.attachmentLabel]}),e.attachment!==void 0&&a(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachment.kind===`snapshot`?u(p,{className:`h-3 w-3`}):u(A,{className:`h-3 w-3`}),Ot(e.attachment)]}),e.model!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:n(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:e.model,value2:String(e.outputTokens??0),value3:String(e.latencyMs??0)})})]})})}function Rt({attachment:e}){let{t}=Q(),n=Et(e);return n===null?null:u(`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 zt({onPick:e}){let{t}=Q(),n=ue({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?u(M,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):u(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>u(Bt,{device:t,onPick:e},t.id))})}function Bt({device:e,onPick:t}){let{t:n}=Q(),{src:r}=h(e.id,{width:Nt});return a(`button`,{type:`button`,onClick:()=>t(e),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[u(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:r!==null&&u(`img`,{src:r,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),a(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!e.online&&u(G,{variant:`warning`,children:n(`common.off`)}),u(`span`,{className:`truncate text-[10px] text-foreground`,children:e.name})]})]})}function Vt({onPick:e}){let{t}=Q(),r=N(),i=ue({isCamera:!0,projection:`slim`}),s=n(()=>(i.data??[]).map(e=>e.id),[i.data]),c=n(()=>{let e=new Map;for(let t of i.data??[])e.set(t.id,t.name);return e},[i.data]),l=o({queryKey:[...At,s.length],enabled:s.length>0,queryFn:()=>r.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...s],since:Date.now()-jt,limit:Mt,projection:`slim`})});if(i.isLoading||l.isLoading)return u(M,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=l.data?.tracks??[];return d.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noTracks`,`No track in the last 6 hours.`)}):u(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(t=>a(`button`,{type:`button`,onClick:()=>e(t,c.get(t.deviceId)??String(t.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[u(A,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className}),u(`span`,{className:`shrink-0 text-foreground-subtle`,children:c.get(t.deviceId)??t.deviceId}),u(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(t.lastSeen).toLocaleTimeString()})]},t.trackId))})}e();var Ht=1440*60*1e3,Ut=[1,7,30,90];function Wt(){let{t:e}=Q(),t=N(),[i,s]=r(7),c=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(i-1)*Ht},[i]),l=o({queryKey:ve,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),d=o({queryKey:[...Ce,i],queryFn:()=>t.trpcClient.llm.getUsage.query({since:c})}),p=n(()=>{let e=new Map;for(let t of l.data??[])e.set(t.id,t.name);return e},[l.data]),m=n(()=>[{key:`day`,header:e(`ai.colDay`,`Day`),nowrap:!0,render:e=>u(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:e(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>u(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:e(`ai.colProfile`,`Profile`),render:e=>u(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:e(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:e(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:e(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:e(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,e]),h=d.data??[],g=u(`div`,{className:`w-36`,children:u(ne,{"aria-label":e(`ai.window`,`Window`),value:String(i),options:Ut.map(t=>({value:String(t),label:e(`ai.lastDays`,`Last {{days}} days`,{days:t})})),onChange:e=>s(Number(e.target.value))})});return u(X,{headingId:`ai-usage-list`,title:e(`ai.usageList`,`Rollup`),actions:g,children:d.isPending?a(`div`,{className:`${f} space-y-2`,"data-testid":`ai-usage-loading`,children:[u(Y,{className:`h-8 w-full`}),u(Y,{className:`h-8 w-full`}),u(Y,{className:`h-8 w-full`})]}):d.isError?u(`div`,{className:f,children:u(H,{title:e(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:e(`common.error`,`Error`),onRetry:()=>void d.refetch()})}):h.length===0?u(V,{icon:b,title:e(`ai.noUsage`,`No AI calls in this window.`)}):u(B,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:de})})}var Gt=`llm`,Kt=[`profiles`,`runtimes`,`usage`,`test`],qt=[`new`,`edit`];function Jt(e){return Kt.some(t=>t===e)}function Yt(){let{t:e}=Q(),t=re(Gt),[n]=pe(),{openNew:r}=se(),i=me(`/system/ai`,{t:e,isAdmin:!0})??{icon:E,title:e(`system.ai`,`AI`)};if(t!==`present`)return u(ge,{icon:i.icon,title:i.title,children:u(Xt,{presence:t})});let o=n.get(`tab`),s=Jt(o)?o:`profiles`,c={profiles:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),runtimes:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),usage:e(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),test:e(`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.`)},l=s===`profiles`?a(W,{size:`sm`,type:`button`,"data-testid":`ai-add-profile`,onClick:r,children:[u(j,{className:`h-3.5 w-3.5`}),e(`ai.addProfile`,`Add profile`)]}):void 0;return u(he,{icon:i.icon,title:i.title,subtitle:c[s],actions:l,defaultSection:`profiles`,sectionsLabel:`${i.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:u(dt,{}),ownedParams:qt},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:u(ht,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:u(Wt,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:u(Ft,{})}]})}function Xt({presence:e}){let{t}=Q();return e===`pending`?a(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[u(Y,{className:`h-8 w-64`}),u(Y,{className:`h-40 w-full`})]}):e===`unknown`?u(H,{title:t(`ai.presenceUnknownTitle`,`Could not check whether AI is installed`),message:t(`ai.presenceUnknown`,`The hub did not answer the capability check. Reload the page to try again.`)}):u(V,{icon:E,title:t(`ai.absentTitle`,`AI is not installed`),description:t(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{Yt as AiProfilesPage,Yt as default};
@@ -1 +1 @@
1
- import{$ as e,B as t,G as n,J as r,S as i,x as a}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{or as o}from"./player-overlays-B_ZfVBiA.js";import{ma as s}from"./client-DIBstlq5.js";import{Wr as c,cr as l,oa as u,pa as d}from"./src-BVr0SnD-.js";import{t as f}from"./useTranslation-D3Is_4B6.js";import{P as p,lr as m}from"./index-Cskol4XA.js";e();function h(e,t){let n=e=>e.map(e=>e.type===`group`?{...e,fields:n(e.fields)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:n(e.fields)}))}:e.type===`info`&&typeof e.content==`string`?{...e,content:e.content.split(`{{brokerId}}`).join(t)}:e);return{...e,sections:e.sections.map(e=>({...e,fields:n(e.fields)}))}}function g(e,t){if(!e)return t;let n=new Set;for(let r of e.sections){let e=r.fields;for(let r of e)!(`key`in r)||typeof r.key!=`string`||l(r,t,e)&&n.add(r.key)}let r={};for(let[e,i]of Object.entries(t))n.has(e)&&(r[e]=i);return r}function _({kind:e,addonId:l,brokerId:_,initialValues:v,onSubmit:y,onCancel:b,submitLabel:x,disabled:S}){let{t:C}=f(),[w,T]=r(v??{}),[E,D]=r(null),O=u({kind:e,...l===void 0?{}:{addonId:l}}),k=n(()=>{let e=O.data;if(e&&typeof e==`object`&&`sections`in e&&Array.isArray(e.sections)){let t=e;return s(_===void 0?t:h(t,_),w)}},[O.data,_,w]);t(()=>{v!==void 0&&T(v)},[v]);let A=d(),j=async()=>{D(null);let t=g(k,w);try{let n=await A.mutateAsync({kind:e,settings:t,...l===void 0?{}:{addonId:l}});D(n.ok?{ok:!0}:{ok:!1,error:n.error})}catch(e){D({ok:!1,error:e instanceof Error?e.message:String(e)})}};return i(`div`,{className:`space-y-3`,children:[O.isLoading&&i(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[a(o,{className:`h-3.5 w-3.5 animate-spin`}),` `,C(`brokers.brokerForm.loadingSchema`)]}),k&&a(p,{schema:k,values:w,onChange:T}),O.isError&&i(`div`,{className:`rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]`,children:[C(`brokers.brokerForm.failedToLoadSettingsSchema`,`Failed to load settings schema:`),` `,O.error instanceof Error?O.error.message:C(`brokers.brokerForm.unknownError`,`Unknown error`)]}),!k&&!O.isLoading&&!O.isError&&a(`div`,{className:`rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300`,children:a(m,{i18nKey:`brokers.brokerForm.noSchema`,values:{kind:e},components:{code:a(`code`,{className:`font-mono`})}})}),E&&a(`div`,{className:`rounded border px-3 py-2 text-[11px] ${E.ok?`border-success/30 bg-success/5 text-success`:`border-danger/30 bg-danger/5 text-danger`}`,children:E.ok?C(`brokers.brokerForm.connectionOk`,`Connection OK.`):C(`brokers.brokerForm.testFailed`,`Test failed: {{value1}}`,{value1:E.error??`unknown error`})}),i(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[a(c,{variant:`outline`,size:`sm`,onClick:b,children:C(`common.cancel`,`Cancel`)}),i(`div`,{className:`flex items-center gap-2`,children:[a(c,{variant:`outline`,size:`sm`,onClick:()=>{j()},disabled:A.isPending||!k,children:A.isPending?C(`brokers.brokerForm.testing`,`Testing…`):C(`brokers.brokerForm.testConnection`,`Test connection`)}),a(c,{variant:`primary`,size:`sm`,onClick:()=>{let{_calendarCatalog:e,...t}=g(k,w);y(t)},disabled:!k||S,children:x??C(`common.save`,`Save`)})]})]})]})}export{_ as t};
1
+ import{$ as e,B as t,G as n,J as r,S as i,x as a}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{or as o}from"./player-overlays-CvKnZb5M.js";import{_a as s}from"./client-BbPYrWg7.js";import{Gr as c,lr as l,ma as u,sa as d}from"./src-DKc14e9G.js";import{t as f}from"./useTranslation-D3Is_4B6.js";import{P as p,lr as m}from"./index-C8XwyZGE.js";e();function h(e,t){let n=e=>e.map(e=>e.type===`group`?{...e,fields:n(e.fields)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:n(e.fields)}))}:e.type===`info`&&typeof e.content==`string`?{...e,content:e.content.split(`{{brokerId}}`).join(t)}:e);return{...e,sections:e.sections.map(e=>({...e,fields:n(e.fields)}))}}function g(e,t){if(!e)return t;let n=new Set;for(let r of e.sections){let e=r.fields;for(let r of e)!(`key`in r)||typeof r.key!=`string`||l(r,t,e)&&n.add(r.key)}let r={};for(let[e,i]of Object.entries(t))n.has(e)&&(r[e]=i);return r}function _({kind:e,addonId:l,brokerId:_,initialValues:v,onSubmit:y,onCancel:b,submitLabel:x,disabled:S}){let{t:C}=f(),[w,T]=r(v??{}),[E,D]=r(null),O=d({kind:e,...l===void 0?{}:{addonId:l}}),k=n(()=>{let e=O.data;if(e&&typeof e==`object`&&`sections`in e&&Array.isArray(e.sections)){let t=e;return s(_===void 0?t:h(t,_),w)}},[O.data,_,w]);t(()=>{v!==void 0&&T(v)},[v]);let A=u(),j=async()=>{D(null);let t=g(k,w);try{let n=await A.mutateAsync({kind:e,settings:t,...l===void 0?{}:{addonId:l}});D(n.ok?{ok:!0}:{ok:!1,error:n.error})}catch(e){D({ok:!1,error:e instanceof Error?e.message:String(e)})}};return i(`div`,{className:`space-y-3`,children:[O.isLoading&&i(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[a(o,{className:`h-3.5 w-3.5 animate-spin`}),` `,C(`brokers.brokerForm.loadingSchema`)]}),k&&a(p,{schema:k,values:w,onChange:T}),O.isError&&i(`div`,{className:`rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]`,children:[C(`brokers.brokerForm.failedToLoadSettingsSchema`,`Failed to load settings schema:`),` `,O.error instanceof Error?O.error.message:C(`brokers.brokerForm.unknownError`,`Unknown error`)]}),!k&&!O.isLoading&&!O.isError&&a(`div`,{className:`rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300`,children:a(m,{i18nKey:`brokers.brokerForm.noSchema`,values:{kind:e},components:{code:a(`code`,{className:`font-mono`})}})}),E&&a(`div`,{className:`rounded border px-3 py-2 text-[11px] ${E.ok?`border-success/30 bg-success/5 text-success`:`border-danger/30 bg-danger/5 text-danger`}`,children:E.ok?C(`brokers.brokerForm.connectionOk`,`Connection OK.`):C(`brokers.brokerForm.testFailed`,`Test failed: {{value1}}`,{value1:E.error??`unknown error`})}),i(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[a(c,{variant:`outline`,size:`sm`,onClick:b,children:C(`common.cancel`,`Cancel`)}),i(`div`,{className:`flex items-center gap-2`,children:[a(c,{variant:`outline`,size:`sm`,onClick:()=>{j()},disabled:A.isPending||!k,children:A.isPending?C(`brokers.brokerForm.testing`,`Testing…`):C(`brokers.brokerForm.testConnection`,`Test connection`)}),a(c,{variant:`primary`,size:`sm`,onClick:()=>{let{_calendarCatalog:e,...t}=g(k,w);y(t)},disabled:!k||S,children:x??C(`common.save`,`Save`)})]})]})]})}export{_ as t};
@@ -0,0 +1,40 @@
1
+ import{$ as e,B as t,G as n,J as r,L as i,N as a,S as o,T as s,a as c,b as l,q 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-CEHpkaJP.js";import{An as p,Fn as m,It as h,Nt as g,Zi as _,kn as v,or as y,ot as b,pi as x,pn as S,pt as C,qi as w,sa as T,vn as E,wr as D,xi as O,yi as k}from"./player-overlays-CvKnZb5M.js";import{$r as A,Ci as j,Da as M,Si as N,_i as P,bi as F,dn as I,fa as L,fi as R,gi as z,ni as B,ti as V,xi as H,yi as ee}from"./client-BbPYrWg7.js";import{t as te}from"./boxes-DT6bkxUA.js";import{n as ne,r as re,t as ie}from"./ungroup-BdxY8QDj.js";import{s as ae}from"./video-CJw8Jnle.js";import{Cn as oe,Da as se,Ea as ce,Er as le,Gr as U,Ju as ue,Ku as W,Oa as de,Qr as G,Qt as K,Sa as fe,Ur as pe,Wn as me,Xu as he,Yu as ge,Zu as q,_n as _e,ht as ve,in as ye,ka as be,oo as xe,pt as Se,qt as Ce,tn as we,uo as Te,wn as Ee,xa as De,xr as Oe,yt as ke}from"./src-DKc14e9G.js";import{t as J}from"./i18n-BO6gCPcC.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{P as Ae,ar as je,lr as X,m as Me,mr as Ne,ur as Pe,x as Fe}from"./index-C8XwyZGE.js";import{t as Ie}from"./AdminSectionedPage-BIoU14zn.js";import{t as Le}from"./DeviceDoActionFields-BmEM1vFn.js";import{n as Re,t as ze}from"./CompositionCreateForm-DCUy3waQ.js";var Be=`const AUTOMATION_RECIPE =`,Ve=`// 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 He(e){return e.includes(Be)}function Ue(e){let t=e.indexOf(Be);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 We(e){let t=Ue(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=F.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 Ge(e){let t=Ue(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)}${Ve}${e.slice(i)}`}e();var Ke=6e4;function qe(){let e=Te({projection:`slim`});return n(()=>(e.data??[]).filter(e=>I(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 Je(e){let t=b();return c({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:Ke,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function Ye(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Z({children:e}){return f(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Xe(e){let t=Je(e.deviceId);if(t.data!==void 0)return Ye(t.data,e.cap).find(t=>t.path===e.fieldPath)}function Ze({value:e,devices:t,onChange:n}){let{t:r}=Y(),i=Je(e.deviceId),a=i.data??[],s=Ye(a,e.cap);return o(l,{children:[o(`label`,{className:`min-w-[10rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.device`,`Device`)}),f(W,{value:String(e.deviceId),onChange:e=>n({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:r(`automation.fieldPicker.selectADevice`,`Select a device…`)},...t.map(e=>({value:String(e.id),label:e.name}))]})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.capability`,`Capability`)}),f(W,{value:e.cap,disabled:e.deviceId===0,onChange:t=>n({...e,cap:t.target.value,fieldPath:``}),options:[{value:``,label:Qe(e.deviceId,a.length,i.isLoading)},...a.map(e=>({value:e.cap,label:e.cap}))]})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.fieldPicker.field`,`Field`)}),f(W,{value:e.fieldPath,disabled:e.cap===``,onChange:t=>n({...e,fieldPath:t.target.value}),options:[{value:``,label:s.length===0?r(`automation.fieldPicker.noReadableFields`,`No readable fields`):r(`automation.fieldPicker.selectAField`,`Select a field…`)},...s.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function Qe(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 $e=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function et(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 $e}}function tt(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 nt(e){return et(e).map(e=>({value:e,label:tt(e)}))}function rt(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 it={triggers:[],actions:[]};function at(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 ot(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 st(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function ct(){return{kind:`expression`,expr:``,bindings:{}}}function lt(e,t,n){return e.map((e,r)=>r===t?n:e)}function ut(e,t){return e.filter((e,n)=>n!==t)}function dt(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=ut(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function ft(e,t){return{...e,triggers:[...t]}}function pt(e,t){return{...e,actions:[...t]}}var mt=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function ht({actions:e,devices:t,devicesState:n=`answered`,onChange:r}){let{t:i}=Y();return o(`div`,{className:`space-y-2`,children:[e.length===0&&f(`p`,{className:`text-xs text-warning`,children:i(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),e.map((a,s)=>o(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(G,{variant:`default`,children:s+1}),o(`label`,{className:`w-40`,children:[f(Z,{children:i(`automation.actionList.step`,`Step`)}),f(W,{value:a.kind,onChange:t=>r(lt(e,s,ot(gt(t.target.value)))),options:mt.map(e=>({value:e.value,label:i(e.labelKey)}))})]}),o(`div`,{className:`ml-auto flex items-center gap-1`,children:[f(U,{variant:`ghost`,disabled:s===0,onClick:()=>r(dt(e,s,s-1)),title:i(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:f(w,{className:`h-3.5 w-3.5`})}),f(U,{variant:`ghost`,disabled:s===e.length-1,onClick:()=>r(dt(e,s,s+1)),title:i(`automation.actionList.runThisStepLater`,`Run this step later`),children:f(_,{className:`h-3.5 w-3.5`})}),f(U,{variant:`ghost`,onClick:()=>r(ut(e,s)),title:i(`automation.actionList.removeThisStep`,`Remove this step`),children:f(h,{className:`h-3.5 w-3.5`})})]})]}),a.kind===`wait`&&o(`label`,{className:`block w-32`,children:[f(Z,{children:i(`automation.actionList.seconds`,`Seconds`)}),f(q,{type:`number`,min:0,max:300,value:String(a.seconds),onChange:t=>r(lt(e,s,{kind:`wait`,seconds:Number(t.target.value)}))})]}),a.kind===`code`&&o(`label`,{className:`block`,children:[f(Z,{children:i(`automation.actionList.code`,`Code`)}),f(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:a.code,spellCheck:!1,onChange:t=>r(lt(e,s,{kind:`code`,code:t.target.value}))}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.actionList.codeHint`,components:{code:f(`code`,{})}})})]}),a.kind===`cap`&&f(vt,{action:a,devices:t,devicesState:n,onChange:t=>r(lt(e,s,t))})]},`${a.kind}-${String(s)}`)),o(`div`,{className:`flex items-center gap-2`,children:[o(U,{variant:`outline`,onClick:()=>r([...e,ot(`cap`)]),children:[f(v,{className:`h-4 w-4`}),` `,i(`automation.actionList.addStep`)]}),e.length>1&&f(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function gt(e){return mt.find(t=>t.value===e)?.value??`cap`}function _t(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function vt({action:e,devices:t,devicesState:n,onChange:r}){return f(Le,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:_t(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function yt({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),s=Tt(t,n,r);if(t?.kind===`boolean`)return f(W,{value:e===!0?`true`:`false`,onChange:e=>i(e.target.value===`true`),options:[{value:`true`,label:a(`common.true`)},{value:`false`,label:a(`common.false`)}]});if(t?.kind===`enum`&&t.enumValues!==void 0&&t.enumValues.length>0)return f(W,{value:String(e),onChange:e=>i(e.target.value),options:t.enumValues.map(e=>({value:e,label:e}))});if(t?.kind===`number`){let t=typeof e==`number`&&s?s.toDisplayValue(e):e;return o(`span`,{className:`inline-flex items-center gap-1`,children:[f(q,{type:`number`,value:typeof t==`number`?String(t):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&i(s?s.fromDisplayValue(t):t)}}),s!==void 0&&s.unit.length>0?f(`span`,{className:`text-xs text-foreground-subtle`,children:s.unit}):null]})}return f(q,{value:String(e),placeholder:a(`common.valueWord`),onChange:e=>i(e.target.value)})}function bt({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),o=Tt(t,n,r);return f(q,{value:(o?e.map(e=>typeof e==`number`?o.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=>o?o.fromDisplayValue(e):e):n)}})}function xt(e){return typeof e==`object`}function St(e){return xt(e)?e[0]??``:e}function Ct(e){return xt(e)?e:typeof e==`boolean`?[]:[e]}function wt(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Tt(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=xe({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=L(o)?o:void 0,c=wt(e?.quantity,s);if(c===void 0)return;let l=a?.display;return K({quantity:c,display:l,capName:n})}function Et({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=Xe(i),s=nt(a?.kind),c=e.operator===`in`,l=t=>{n({...e,deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath})},u=t=>{let r=Dt(t,s);n({...e,operator:r,value:r===`in`?Ct(e.value):St(e.value)})};return o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(Ze,{value:i,devices:t,onChange:l}),o(`label`,{className:`min-w-[8rem]`,children:[f(Z,{children:r(`automation.conditionRow.comparison`,`Comparison`)}),f(W,{value:e.operator,onChange:e=>u(e.target.value),options:s.map(e=>({value:e.value,label:e.label}))})]}),o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:r(`automation.conditionRow.value`,`Value`)}),c?f(bt,{value:Ct(e.value),field:a,deviceId:e.deviceId,cap:e.cap,onChange:t=>n({...e,value:t})}):f(yt,{value:St(e.value),field:a,deviceId:e.deviceId,cap:e.cap,onChange:t=>n({...e,value:t})})]})]})}function Dt(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Ot={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function kt({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i=Object.entries(e.bindings),a=t=>{n({kind:`expression`,expr:e.expr,bindings:t})};return o(`div`,{className:`space-y-2`,children:[o(`label`,{className:`block`,children:[f(Z,{children:r(`automation.expressionLeafRow.expression`,`Expression`)}),f(q,{value:e.expr,placeholder:r(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:t=>n({kind:`expression`,expr:t.target.value,bindings:e.bindings})}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:r(`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.`)})]}),o(`div`,{className:`space-y-1.5`,children:[i.length===0&&f(`p`,{className:`text-xs text-foreground-subtle`,children:r(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),i.map(([n,r])=>f(At,{alias:n,source:r,devices:t,onRename:t=>a(It(e.bindings,n,t)),onChange:t=>a({...e.bindings,[n]:t}),onRemove:()=>a(Lt(e.bindings,n))},n)),o(U,{variant:`ghost`,onClick:()=>a({...e.bindings,[Ft(e.bindings)]:Ot}),children:[f(v,{className:`h-3.5 w-3.5`}),` `,r(`common.name`)]})]})]})}function At({alias:e,source:t,devices:n,onRename:r,onChange:i,onRemove:a}){let{t:s}=Y(),c=t.kind===`literal`,l=c?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Nt(n,Mt(t)),cap:t.cap,fieldPath:t.fieldPath};return o(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[o(`label`,{className:`w-32`,children:[f(Z,{children:s(`automation.expressionLeafRow.name`,`Name`)}),f(q,{value:e,placeholder:s(`automation.expressionLeafRow.aliasExample`),onChange:e=>r(e.target.value)})]}),o(`label`,{className:`w-36`,children:[f(Z,{children:s(`automation.expressionLeafRow.reads`,`Reads`)}),f(W,{value:c?`literal`:`global`,onChange:e=>i(e.target.value===`literal`?{kind:`literal`,value:``}:Ot),options:[{value:`global`,label:s(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:s(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),c?o(`label`,{className:`min-w-[9rem] flex-1`,children:[f(Z,{children:s(`automation.expressionLeafRow.constant`,`Constant`)}),f(q,{value:t.value===null?``:String(t.value),placeholder:`5`,onChange:e=>i({kind:`literal`,value:jt(e.target.value)})})]}):f(Ze,{value:l,devices:n,onChange:e=>i({kind:`global`,sourceStableId:Pt(n,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),f(U,{variant:`ghost`,onClick:a,title:s(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:f(h,{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 Mt(e){return e.kind===`global`?e.sourceStableId:``}function Nt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Pt(e,t){return e.find(e=>e.id===t)?.stableId??``}function Ft(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 It(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Lt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Rt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:Rt(t)?t:{kind:`all`,children:[t]}}function zt(e,t){return t===null||Rt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Bt(e){return zt(e,Q(e))}function Vt(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?Vt(e.child,r):null;if(!Rt(e))return null;let i=e.children[n];return i===void 0?null:Vt(i,r)}function Ht(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=Ht(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!Rt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ht(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function Ut(e){return e===null?null:j({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function Wt(e){let t=Q(e);return{depth:t.children.length===0?0:H(t),leaves:t.children.length===0?0:N(t),depthLimit:3,leafLimit:32}}function Gt(e,t){let n=Ut(t);return n===null?{ok:!0,recipe:zt(e,t)}:{ok:!1,reason:n}}function Kt(e,t){let n=Q(e);return Gt(e,{kind:n.kind,children:[...n.children,t]})}function qt(e,t,n){return zt(e,Ht(Q(e),t,()=>n))}function Jt(e,t){return zt(e,Ht(Q(e),t,()=>null))}function Yt(e,t,n){return zt(e,Ht(Q(e),t,e=>Rt(e)?{kind:n,children:e.children}:e))}function Xt(e,t){return Vt(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:Gt(e,Ht(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function Zt(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function Qt(e,t,n){if(t.length<2)return{ok:!1,reason: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=Zt(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=Vt(i,r.path);if(a===null||!Rt(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 Gt(e,Ht(i,r.path,()=>d))}function $t(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=Vt(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return Gt(e,Ht(n,t,()=>r.child));if(!Rt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=Zt(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=Vt(n,i.path);if(a===null||!Rt(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 Gt(e,Ht(n,i.path,()=>o))}e();var en=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function tn(e){return e.join(`/`)}function nn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function rn({recipe:e,devices:t,onChange:i}){let{t:a}=Y(),[s,c]=r([]),[l,u]=r(null),d=Q(e),p=Wt(e),m=n(()=>s.map(nn),[s]),h=e=>{if(!e.ok){u(e.reason);return}u(null),c([]),i(e.recipe)},g=Qt(e,m,`all`),_=Qt(e,m,`any`),y=m.length===1?Xt(e,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:t,selected:new Set(s),onToggleSelect:e=>c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(t,n)=>i(qt(e,t,n)),onRemove:t=>{c([]),i(Jt(e,t))},onSetKind:(t,n)=>i(Yt(e,t,n)),onUngroup:t=>h($t(e,t))};return o(`div`,{className:`space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(G,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),f(`div`,{className:`w-32`,children:f(W,{value:d.kind,onChange:t=>i(Yt(e,[],an(t.target.value))),options:en.map(e=>({value:e.value,label:a(e.labelKey)}))})}),f(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),d.children.length===0?f(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):f(on,{container:d,path:[],handlers:b}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(U,{variant:`outline`,onClick:()=>h(Kt(e,st())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[f(v,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),o(U,{variant:`outline`,onClick:()=>h(Kt(e,ct())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[f(re,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),f(`span`,{className:`mx-1 h-5 w-px bg-border`}),f(U,{variant:`ghost`,disabled:!g.ok,onClick:()=>h(g),title:g.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):g.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),f(U,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):_.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),f(U,{variant:`ghost`,disabled:!y.ok,onClick:()=>h(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&f(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),l!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:l})]})}function an(e){return e===`any`?`any`:`all`}function on({container:e,path:t,handlers:n}){return f(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>f(sn,{node:e,path:[...t,r],handlers:n},tn([...t,r])))})}function sn({node:e,path:t,handlers:n}){let{t:r}=Y(),i=tn(t),a=f(me,{checked:n.selected.has(i),onChange:()=>n.onToggleSelect(i),"aria-label":r(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return Rt(e)?o(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[o(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,f(`div`,{className:`w-32`,children:f(W,{value:e.kind,onChange:e=>n.onSetKind(t,an(e.target.value)),options:en.map(e=>({value:e.value,label:r(e.labelKey)}))})}),o(U,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[f(ie,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.ungroup`)]}),f(U,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:f(h,{className:`h-3.5 w-3.5`})})]}),f(`div`,{className:`pl-4`,children:f(on,{container:e,path:t,handlers:n})})]}):e.kind===`not`?o(`div`,{className:`rounded border border-border p-2`,children:[o(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[a,f(G,{variant:`warning`,children:`NOT`}),o(U,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[f(ie,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.removeNot`)]})]}),f(`div`,{className:`pl-4`,children:f(sn,{node:e.child,path:[...t,0],handlers:n})})]}):o(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[f(`div`,{className:`pt-6`,children:a}),f(`div`,{className:`min-w-0 flex-1`,children:e.kind===`condition`?f(Et,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)}):f(kt,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)})}),f(U,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:f(h,{className:`h-3.5 w-3.5`})})]})}e();function cn({code:e,error:t,canEject:n,ejecting:i,onEject:a}){let{t:s}=Y(),[c,l]=r(!1),u=pe(),d=async()=>{await u({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 o(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[o(U,{variant:`ghost`,onClick:()=>l(!c),children:[f(c?O:k,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),f(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),o(U,{className:`ml-auto`,variant:`ghost`,disabled:!n||e===null||i,onClick:()=>void d(),title:n?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:[f(ae,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),c&&f(`div`,{className:`border-t border-border p-3`,children:e===null?f(`p`,{className:`text-xs text-warning`,children:t??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):f(_e,{maxHeight:420,children:e})})]})}var ln=[`device-state`,`device-event`,`schedule`,`manual`],un=Object.values(M).sort((e,t)=>e.localeCompare(t));function dn({triggers:e,devices:t,onChange:n}){let{t:r}=Y();return o(`div`,{className:`space-y-2`,children:[e.length===0&&f(`p`,{className:`text-xs text-warning`,children:r(`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.`)}),e.map((r,i)=>f(fn,{trigger:r,devices:t,position:i,onChange:t=>n(lt(e,i,t)),onRemove:()=>n(ut(e,i))},`${r.kind}-${String(i)}`)),o(U,{variant:`outline`,onClick:()=>n([...e,at(`device-state`)]),title:r(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[f(v,{className:`h-4 w-4`}),` `,r(`automation.triggerEditor.trigger`)]})]})}function fn({trigger:e,devices:t,position:n,onChange:r,onRemove:i}){let{t:a}=Y();return o(`div`,{className:`rounded border border-border p-3`,children:[o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(G,{variant:`default`,children:n===0?a(`automation.triggerEditor.when`,`When`):a(`automation.triggerEditor.orWhen`,`or when`)}),o(`label`,{className:`min-w-[13rem] flex-1`,children:[f(Z,{children:a(`automation.triggerEditor.trigger`,`Trigger`)}),f(W,{value:e.kind,onChange:e=>r(at(pn(e.target.value))),options:ln.map(e=>({value:e,label:rt(e)}))})]}),f(U,{variant:`ghost`,onClick:i,title:a(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:f(h,{className:`h-4 w-4`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[e.kind===`device-state`&&f(hn,{trigger:e,devices:t,onChange:r}),e.kind===`device-event`&&f(_n,{trigger:e,devices:t,onChange:r}),e.kind===`schedule`&&o(`label`,{className:`min-w-[14rem] flex-1`,children:[f(Z,{children:a(`automation.triggerEditor.cronExpression`,`Cron expression`)}),f(q,{value:e.cron,placeholder:`0 30 23 * * *`,onChange:e=>r({kind:`schedule`,cron:e.target.value})}),f(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:f(`code`,{})}})})]}),e.kind===`manual`&&f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:f(`strong`,{})}})})]})]})}function pn(e){return ln.find(t=>t===e)??`manual`}function mn(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function hn({trigger:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=Xe(i),s={...e.becomes===void 0?{}:{becomes:e.becomes},...e.edge===void 0?{}:{edge:e.edge},...e.forMs===void 0?{}:{forMs:e.forMs},...e.debounceMs===void 0?{}:{debounceMs:e.debounceMs}};return o(l,{children:[f(Ze,{value:i,devices:t,onChange:e=>n(mn(e,s))}),o(`div`,{className:`min-w-[11rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.becomes`,`Becomes`)}),o(`div`,{className:`flex items-center gap-2`,children:[o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(me,{checked:e.becomes===void 0,onChange:e=>n(mn(i,{...s,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),r(`automation.triggerEditor.anyChange`,`any change`)]}),e.becomes!==void 0&&f(yt,{value:e.becomes,field:a,deviceId:i.deviceId,cap:i.cap,onChange:e=>n(mn(i,{...s,becomes:e}))})]})]}),o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(me,{checked:e.edge===!0,onChange:e=>n(mn(i,{...s,...e.target.checked?{edge:!0}:{edge:void 0}}))}),r(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.heldForS`,`Held for (s)`)}),f(q,{type:`number`,min:0,value:e.forMs===void 0?``:String(e.forMs/1e3),placeholder:`0`,onChange:e=>n(mn(i,{...s,forMs:gn(e.target.value)}))})]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),f(q,{type:`number`,min:0,value:e.debounceMs===void 0?``:String(e.debounceMs/1e3),placeholder:`0`,onChange:e=>n(mn(i,{...s,debounceMs:gn(e.target.value)}))})]})]})}function gn(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function _n({trigger:e,devices:t,onChange:n}){let{t:r}=Y();return o(l,{children:[o(`label`,{className:`min-w-[15rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),f(W,{value:e.category,onChange:t=>n({kind:`device-event`,category:t.target.value,...e.deviceId===void 0?{}:{deviceId:e.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...un.map(e=>({value:e,label:e}))]})]}),o(`label`,{className:`min-w-[11rem] flex-1`,children:[f(Z,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),f(W,{value:e.deviceId===void 0?``:String(e.deviceId),onChange:t=>n({kind:`device-event`,category:e.category,...t.target.value===``?{}:{deviceId:Number(t.target.value)}}),options:[{value:``,label:r(`automation.triggerEditor.anyDevice`,`Any device`)},...t.map(e=>({value:String(e.id),label:e.name}))]})]})]})}e();var vn=`hub`;function yn({existing:e,initialRecipe:t,saving:i,saveError:a,ejecting:s,onSave:c,onEject:l,onCancel:u}){let{t:d}=Y(),[p,m]=r(e?.name??``),[h,g]=r(()=>Bt(t)),[_,v]=r(!1),b=qe(),x=j(h),C=n(()=>xn(h),[h]),w=n(()=>Sn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),T=p.trim()===``,E=T||x!==null||C!==null||w.code===null;return o(`div`,{className:`space-y-4`,children:[f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(G,{variant:`info`,children:d(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),o(`label`,{className:`block max-w-md text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:d(`automation.automationEditor.name`,`Name`)}),f(q,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:d(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),f(bn,{step:`1`,title:d(`automation.automationEditor.when`,`When`),subtitle:d(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:f(dn,{triggers:h.triggers,devices:b,onChange:e=>g(ft(h,e))})}),f(bn,{step:`2`,title:d(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:d(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:f(rn,{recipe:h,devices:b,onChange:g})}),f(bn,{step:`3`,title:d(`automation.automationEditor.then`,`Then`),subtitle:d(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:f(ht,{actions:h.actions,devices:b,onChange:e=>g(pt(h,e))})}),f(cn,{code:w.code,error:w.error,canEject:e!==null,ejecting:s,onEject:l}),x!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),x===null&&C!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:C}),a!==null&&f(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(U,{onClick:()=>{w.code!==null&&c({name:p.trim(),code:w.code,enabled:e?.enabled??!0,placement:vn})},disabled:i||E,children:[i&&f(y,{className:`h-4 w-4 animate-spin`}),` `,d(`common.save`)]}),o(U,{variant:`ghost`,onClick:()=>v(!_),disabled:e===null,title:e===null?d(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):d(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[f(S,{className:`h-4 w-4`}),` `,d(`common.logs`),` `,_?`▾`:`▸`]}),f(U,{variant:`ghost`,onClick:u,disabled:i,children:d(`common.close`,`Close`)}),T&&f(G,{variant:`warning`,children:d(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&e!==null&&o(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:A(e.id)},components:{code:f(`code`,{})}})}),f(we,{addonId:A(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function bn({step:e,title:t,subtitle:n,children:r}){return o(`section`,{className:`border-l-2 border-border pl-4`,children:[o(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[f(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:e}),f(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:t}),f(`span`,{className:`text-xs text-foreground-subtle`,children:n})]}),r]})}function xn(e){let t=F.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 Sn(e,t){try{return{code:ee({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Cn(e){if(!e.enabled)return{tone:`idle`,label: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 wn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Tn(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function En(e){let t=e=>{let t=Cn(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function Dn(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Cn(e).tone===`error`).length,n=e.filter(e=>Cn(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 On({block:e,busy:t,confirming:n,logsOpen:r,unreadable:i,onEdit:a,onToggle:s,onToggleLogs:c,onAskDelete:l,onCancelDelete:u,onConfirmDelete:d}){let g=T(),{t:_}=Y(),v=Cn(e),y=Ce(e.updatedAt,g);return o(`li`,{className:`flex flex-col gap-2 p-3`,children:[o(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[o(`div`,{className:`min-w-0 flex-1`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(`span`,{className:`truncate font-medium`,children:e.name}),f(G,{variant:wn(v.tone),children:v.label}),y!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:_(`common.edited`,{when:y})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:v.detail}),i!==null&&f(`p`,{className:`mt-0.5 text-xs text-warning`,children:_(`automation.editor.listUnreadable`,{reason:i})})]}),n?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:_(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),f(U,{variant:`danger`,onClick:e=>{e.stopPropagation(),d()},disabled:t,children:_(`common.delete`,`Delete`)}),f(U,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},children:_(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(U,{variant:`ghost`,onClick:e=>{e.stopPropagation(),a()},disabled:i!==null,title:i===null?_(`common.edit`,`Edit`):_(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:f(m,{className:`h-4 w-4`})}),o(ue,{children:[f(he,{children:f(U,{variant:`ghost`,disabled:!0,title:_(`automation.automationList.runActions`,`Run actions`),children:f(p,{className:`h-4 w-4`})})}),f(ge,{children:_(`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.`)})]}),f(U,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:_(`automation.automationList.logs`,`Logs`),children:f(S,{className:`h-4 w-4`})}),f(U,{variant:`ghost`,onClick:t=>{t.stopPropagation(),s(!e.enabled)},disabled:t,title:e.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`),children:e.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`)}),f(U,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:_(`common.delete`,`Delete`),children:f(h,{className:`h-4 w-4`})})]})]}),r&&o(`div`,{className:`rounded border border-border`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:A(e.id)},components:{code:f(`code`,{})}})}),f(we,{addonId:A(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function kn({onCreate:e}){let{t}=Y();return f(Oe,{children:o(`div`,{className:`space-y-2 p-4`,children:[f(`p`,{className:`text-sm text-foreground`,children:t(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),f(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:t(`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.`)}),f(U,{onClick:e,children:t(`automation.automationList.newAutomation`,`New automation`)})]})})}e();var An=[`coreBlocks`,`list`],jn=5e3;function Mn(e){return e instanceof Error?e.message:String(e)}function Nn({onOpenScripts:e,initialBlockId:i,onBlockIdChange:a,createRequested:s=!1,onCreateConsumed:l}){let{t:p}=Y(),m=b(),{state:h,openNew:g,openEdit:_,close:v}=Se({editKey:`block`,newKey:`new`}),[y,x]=r(null),[S,w]=r(null),[T,E]=r(null),D=u(null),O=h.mode!==`closed`;t(()=>{s&&(x(null),g(),a?.(null),l?.())},[s,l,a,g]);let k=c({queryKey:An,refetchInterval:jn,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;t(()=>{i===void 0||D.current===i||j?.find(e=>e.id===i&&He(e.code))!==void 0&&(D.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:Ge(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:t=>{v(),x(null),A(),e(t.block.id)}}),L=k.data,R=En((L??[]).filter(e=>He(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:Tn(R,B),H=V===null?null:We(V.code),ee=M.error===null?N.error===null?I.error===null?null:Mn(I.error):Mn(N.error):Mn(M.error),te=n(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=We(e.code);return f(`ul`,{className:`list-none`,children:f(On,{block:e,busy:F.isPending||P.isPending,confirming:S===e.id,logsOpen:T===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{x(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>E(T===e.id?null:e.id),onAskDelete:()=>w(e.id),onCancelDelete:()=>w(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[S,T,a,_,P,F,p]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:Dn(R)}),k.error!=null&&f(le,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Mn(k.error),onRetry:A}),z?f(kn,{onCreate:()=>{x(null),g(),a?.(null)}}):f(oe,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ee,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{x(e),_(e.id),a?.(e.id)}}),f(ve,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:C,width:`xl`,testId:`automation-editor-panel`,children:f(yn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:it,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&f(le,{message:Mn(P.error)}),F.error!=null&&f(le,{message:Mn(F.error)})]})}function Pn(e){return{state:`answered`,byRef:new Map(e.map(e=>[z(e),e]))}}function Fn(e,t){if(e.state!==`unanswered`)return e.byRef.get(z(t))??null}function In(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Ln(e){return P(e).map(e=>e.source)}function Rn(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...Ln(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Ln(e))}let r=new Set;return n.filter(e=>{let t=z(e);return r.has(t)?!1:(r.add(t),!0)})}function zn(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 Bn(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return zn(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 Vn(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 Bn(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 Hn(e){return z(e)}function Un(e,t){let n=Fn(t,e);return{key:z(e),label:n?n.name:Hn(e),presence:In(n),deviceId:n?n.id:null}}function Wn(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Gn(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:R(e.block.id),a=z(i),o=Rn(e).filter(e=>z(e)!==a).map(e=>Un(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Fn(t,i),l=Wn(e),u=Vn(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=In(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Hn(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function Kn(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function qn(e,t){return Kn(e)-Kn(t)||e.name.localeCompare(t.name)}function Jn(e,t){let n=e.flatMap(e=>{let n=Gn(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(qn),customizations:n.filter(e=>e.kind===`customization`).toSorted(qn)}}e();var Yn=1e4;function Xn(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Zn(){let e=je();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:Xn(e.error)})}:Pn(e.data)}function Qn({createRequested:e=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=ce({},{refetchInterval:Yn}),a=Zn(),s=Se({editKey:`block`,newKey:`new`});t(()=>{e&&(s.openNew(),n?.())},[e]);let c=i.data;if(i.error!=null&&c===void 0)return f(le,{title:r(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Xn(i.error),onRetry:()=>void i.refetch()});if(c===void 0)return f(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:r(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(c.state===`not-loaded`)return f(Oe,{children:o(`div`,{className:`space-y-1 p-4`,children:[f(`p`,{className:`text-sm text-warning`,children:r(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:[r(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),c.reason,`).`]})]})});let u=i.error==null?null:Xn(i.error),d=Jn(c.views,a),p=s.state.mode===`edit`?s.state.id:null,m=s.state.mode===`new`;return o(l,{children:[f($n,{lists:d,fleet:a,refreshError:u,onEditComposed:e=>s.openEdit(e)}),f(ve,{open:m||p!==null,onClose:()=>s.close(),title:m?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:te,width:`xl`,testId:`composed-device-editor`,children:m?f(ze,{}):p===null?null:f(Re,{blockId:p})})]})}function $n({lists:e,fleet:t,refreshError:n,onEditComposed:r}){let{t:i}=Y();return o(`div`,{className:`space-y-4`,children:[n!==null&&o(`p`,{className:`text-xs text-warning`,children:[i(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,n]}),t.state===`unanswered`&&o(`p`,{className:`text-xs text-warning`,children:[i(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,t.reason,`. No source is marked missing until it has.`]}),f(er,{title:i(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:i(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:e.composed,nameHeader:`Name`,emptyMessage:i(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:r}),f(er,{title:i(`build.customDeviceTab.customizations`,`Customizations`),hint:i(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:e.customizations,nameHeader:`Device`,emptyMessage:i(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:r})]})}function er({title:e,hint:t,rows:n,nameHeader:r,emptyMessage:i,kind:a,onEditComposed:s}){return o(`section`,{className:`space-y-2`,"aria-label":e,children:[o(`div`,{children:[f(`h3`,{className:`font-medium`,children:e}),f(`p`,{className:`text-xs text-foreground-subtle`,children:t})]}),f(Oe,{variant:`flat`,className:`p-0`,children:f(oe,{columns:tr(r,a,s),rows:n,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:Ee,emptyMessage:i,onRowClick:a===`composed`?e=>s(e.blockId):void 0})})]})}function tr(e,t,n){let r=[{key:`name`,header:e,sortValue:e=>e.name.toLowerCase(),render:e=>f(nr,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>f(`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:e=>o(`div`,{className:`space-y-0.5`,children:[f(G,{variant:wn(e.state.tone),children:e.state.label}),e.state.reason!==null&&f(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:e.state.reason})]})},{key:`sources`,header:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>f(ir,{sources:e.sources})}];return t===`composed`&&r.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>f(`div`,{className:`flex justify-end gap-1`,children:f(U,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),n(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),r}function nr({row:e}){let{t}=Y();return o(`div`,{className:`space-y-0.5`,children:[f(rr,{row:e}),e.namePresence===`missing`&&f(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:t(`build.customDeviceTab.deviceMissing`,`device missing`)}),f(`p`,{className:`text-[11px] text-foreground-subtle`,children:e.features.join(`, `)})]})}function rr({row:e}){let{t}=Y();return e.kind===`composed`?f(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?f(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:e.name})}):f(Pe,{to:Me(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function ir({sources:e}){let{t}=Y();return e.length===0?f(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):f(`ul`,{className:`space-y-0.5`,children:e.map(e=>o(`li`,{className:`text-xs`,children:[e.deviceId===null?f(`span`,{className:e.presence===`missing`?`text-danger`:`text-foreground`,children:e.label}):f(Pe,{to:`/devices/${String(e.deviceId)}`,className:`hover:underline`,children:e.label}),e.presence===`missing`&&f(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:t(`common.missing`)})]},e.key))})}function ar(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 or(e){if(Array.isArray(e))return e}function sr(e,t,n){return(t=gr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cr(e,t){var n=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 lr(){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 ur(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 dr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ur(Object(n),!0).forEach(function(t){sr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ur(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function fr(e,t){if(e==null)return{};var n,r,i=pr(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 pr(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 mr(e,t){return or(e)||cr(e,t)||_r(e,t)||lr()}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 gr(e){var t=hr(e,`string`);return typeof t==`symbol`?t:t+``}function _r(e,t){if(e){if(typeof e==`string`)return ar(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)?ar(e,t):void 0}}function vr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yr(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 br(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?yr(Object(n),!0).forEach(function(t){vr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function xr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Sr(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 Cr(e){return{}.toString.call(e).includes(`Object`)}function wr(e){return!Object.keys(e).length}function Tr(e){return typeof e==`function`}function Er(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dr(e,t){return Cr(t)||Mr(`changeType`),Object.keys(t).some(function(t){return!Er(e,t)})&&Mr(`changeField`),t}function Or(e){Tr(e)||Mr(`selectorType`)}function kr(e){Tr(e)||Cr(e)||Mr(`handlerType`),Cr(e)&&Object.values(e).some(function(e){return!Tr(e)})&&Mr(`handlersType`)}function Ar(e){e||Mr(`initialIsRequired`),Cr(e)||Mr(`initialType`),wr(e)&&Mr(`initialContent`)}function jr(e,t){throw Error(e[t]||e.default)}var Mr=Sr(jr)({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"}),Nr={changes:Dr,selector:Or,handler:kr,initial:Ar};function Pr(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Nr.initial(e),Nr.handler(t);var n={current:e},r=Sr(Lr)(n,t),i=Sr(Ir)(n),a=Sr(Nr.changes)(e),o=Sr(Fr)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Nr.selector(e),e(n.current)}function c(e){xr(r,i,a,o)(e)}return[s,c]}function Fr(e,t){return Tr(t)?t(e.current):t}function Ir(e,t){return e.current=br(br({},e.current),t),t}function Lr(e,t,n){return Tr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var Rr={create:Pr},zr={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function Br(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 Vr(e){return{}.toString.call(e).includes(`Object`)}function Hr(e){return e||Kr(`configIsRequired`),Vr(e)||Kr(`configType`),e.urls?(Ur(),{paths:{vs:e.urls.monacoBase}}):e}function Ur(){console.warn(Gr.deprecation)}function Wr(e,t){throw Error(e[t]||e.default)}var Gr={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
+ `},Kr=Br(Wr)(Gr),qr={config:Hr},Jr=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function Yr(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],Yr(e[n],t[n]))}),dr(dr({},e),t)}var Xr={type:`cancelation`,msg:`operation is manually canceled`};function Zr(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(Xr):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var Qr=[`monaco`],$r=mr(Rr.create({config:zr,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),ei=$r[0],ti=$r[1];function ni(e){var t=qr.config(e),n=t.monaco,r=fr(t,Qr);ti(function(e){return{config:Yr(e.config,r),monaco:n}})}function ri(){var e=ei(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(ti({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Zr(ui);if(window.monaco&&window.monaco.editor)return ci(window.monaco),e.resolve(window.monaco),Zr(ui);Jr(ii,oi)(si)}return Zr(ui)}function ii(e){return document.body.appendChild(e)}function ai(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function oi(e){var t=ei(function(e){return{config:e.config,reject:e.reject}}),n=ai(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function si(){var e=ei(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;ci(n),e.resolve(n)},function(t){e.reject(t)})}function ci(e){ei().monaco||ti({monaco:e})}function li(){return ei(function(e){return e.monaco})}var ui=new Promise(function(e,t){return ti({resolve:e,reject:t})}),di={config:ni,init:ri,__getMonacoInstance:li};e();var fi={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},pi={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function mi({children:e}){return s.createElement(`div`,{style:pi.container},e)}var hi=mi;function gi({width:e,height:t,isEditorReady:n,loading:r,_ref:i,className:a,wrapperProps:o}){return s.createElement(`section`,{style:{...fi.wrapper,width:e,height:t},...o},!n&&s.createElement(hi,null,r),s.createElement(`div`,{ref:i,style:{...fi.fullWidth,...!n&&fi.hide},className:a}))}var _i=a(gi);function vi(e){t(e,[])}var yi=vi;function bi(e,n,r=!0){let i=u(!0);t(i.current||!r?()=>{i.current=!1}:e,n)}var $=bi;function xi(){}function Si(e,t,n,r){return Ci(e,r)||wi(e,t,n,r)}function Ci(e,t){return e.editor.getModel(Ti(e,t))}function wi(e,t,n,r){return e.editor.createModel(t,n,r?Ti(e,r):void 0)}function Ti(e,t){return e.Uri.parse(t)}function Ei({original:e,modified:n,language:a,originalLanguage:o,modifiedLanguage:c,originalModelPath:l,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=xi,onMount:S=xi}){let[C,w]=r(!1),[T,E]=r(!0),D=u(null),O=u(null),k=u(null),A=u(S),j=u(x),M=u(!1);yi(()=>{let e=di.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=Si(O.current,e||``,o||a||`text`,l||``);n!==t.getModel()&&t.setModel(n)}},[l],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Si(O.current,n||``,c||a||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(n||``):n!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:n||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[n],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||a||`text`),O.current.editor.setModelLanguage(t,c||a||`text`)},[a,o,c],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=i(()=>{if(!O.current)return;j.current(O.current);let t=Si(O.current,e||``,o||a||`text`,l||``),r=Si(O.current,n||``,c||a||`text`,d||``);D.current?.setModel({original:t,modified:r})},[a,n,c,e,o,l,d]),P=i(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);t(()=>{C&&A.current(D.current,O.current)},[C]),t(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return s.createElement(_i,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}a(Ei);function Di(e){let n=u();return t(()=>{n.current=e},[e]),n.current}var Oi=Di,ki=new Map;function Ai({defaultValue:e,defaultLanguage:n,defaultPath:a,value:o,language:c,path:l,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=xi,onMount:C=xi,onChange:w,onValidate:T=xi}){let[E,D]=r(!1),[O,k]=r(!0),A=u(null),j=u(null),M=u(null),N=u(C),P=u(S),F=u(),I=u(o),L=Oi(l),R=u(!1),z=u(!1);yi(()=>{let e=di.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?V():e.cancel()}),$(()=>{let t=Si(A.current,e||o||``,n||c||``,l||a||``);t!==j.current?.getModel()&&(g&&ki.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(ki.get(l)))},[l],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&c&&A.current?.editor.setModelLanguage(e,c)},[c],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let B=i(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=l||a,r=Si(A.current,o||e||``,n||c||``,t||``);j.current=A.current?.editor.create(M.current,{model:r,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(ki.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,n,a,o,c,l,m,h,g,d,f]);t(()=>{E&&N.current(j.current,A.current)},[E]),t(()=>{!O&&!E&&B()},[O,E,B]),I.current=o,t(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),t(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function V(){F.current?.dispose(),_?g&&ki.set(l,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return s.createElement(_i,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var ji=a(Ai);e();function Mi(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 Ni={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function Pi(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...Ni}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function Fi({value:e,onChange:n,extraLibs:r=[],path:a=`file:///block.ts`,onDiagnostics:o,readOnly:s=!1,heightPx:c=420,dark:l=!0}){let d=u(null),p=i((e,t)=>{if(d.current=t,Pi(t,r),o===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{o(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,o]);return t(()=>{let e=d.current;e!==null&&Pi(e,r)},[r]),f(ji,{height:c,defaultLanguage:`typescript`,path:a,theme:l?`vs-dark`:`vs`,value:e,onChange:e=>n(e??``),onMount:p,options:{readOnly:s,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function Ii(e){return e.some(e=>e.severity>=8)}var Li=[{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 Ri(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 zi=Li.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 Bi({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`)}e();var Vi=5e3;function Hi(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 Ui({blockId:e}){let{t}=Y(),r=A(e),i=Te({addonId:r,projection:`slim`},{refetchInterval:Vi}),a=n(()=>Hi(i.data),[i.data]);return i.isLoading?o(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[f(y,{className:`h-3.5 w-3.5 animate-spin`}),` `,t(`build.scriptDevicesPanel.loading`)]}):i.isError?o(`p`,{className:`text-xs text-danger`,children:[t(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,i.error instanceof Error?i.error.message:String(i.error)]}):o(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[o(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`div`,{children:[f(`h4`,{className:`text-sm font-medium`,children:t(`build.scriptDevicesPanel.devices`,`Devices`)}),f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:r},components:{code:f(`code`,{className:`text-[11px]`})}})})]}),f(G,{variant:`default`,children:a.length})]}),a.length===0?f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:f(`code`,{})}})}):f(`ul`,{className:`space-y-3`,children:a.map(e=>f(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${e.id}`,children:o(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[f(Pe,{to:`/devices/${String(e.id)}`,className:`text-sm font-medium hover:underline`,title:t(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:e.name}),f(G,{variant:`info`,style:`outline`,children:e.type}),e.stableId!==void 0&&o(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,f(`code`,{children:e.stableId})]}),o(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,e.id]})]})},e.id))})]})}e();function Wi(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 Gi(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 Ki(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 qi(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function Ji(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function Yi(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=qi(e);n!==null&&(t[n]=Ji(e))}return t}function Xi(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function Zi({blockId:e}){let{t}=Y(),a=b(),s=De({blockId:e},{retry:!1}),c=fe({blockId:e},{refetchInterval:1e4,retry:!1}),l=be({onSuccess:()=>{c.refetch()}}),u=se(),d=de(),[p,m]=r(null),[h,g]=r(null),[_,v]=r(null),[x,S]=r(!1),C=Xi(c.data)?c.data:null,w=n(()=>C===null?{}:Yi(C),[C]),T=p??w,E=i(e=>{m(e)},[]),D=p!==null,O=i(()=>{p!==null&&(g(null),l.mutate({blockId:e,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[e,p,l]),k=i(async(t,n)=>{if(Wi(t)){S(!0),g(null),v(null);try{p!==null&&(await a.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:e,patch:p}),m(null)),await a.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:e,patch:Gi(t)}),s.data?.block?.enabled!==!0&&(await d.mutateAsync({blockId:e,enabled:!0}),v(Ki(t))),await u.mutateAsync({blockId:e}),await c.refetch(),t===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):t===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):t===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):t===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):t===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{S(!1)}}},[e,s.data?.block?.enabled,p,u,d,c,a.trpcClient.coreBlocks]);return c.isLoading?o(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[f(y,{className:`h-3.5 w-3.5 animate-spin`}),` `,t(`build.scriptSettingsPanel.loading`)]}):c.isError?o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[t(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,c.error instanceof Error?c.error.message:String(c.error)]}):C===null?null:o(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[o(`div`,{className:`flex items-center justify-between gap-2`,children:[o(`div`,{children:[f(`h4`,{className:`text-sm font-medium`,children:t(`build.scriptSettingsPanel.settings`,`Settings`)}),f(`p`,{className:`text-xs text-foreground-subtle`,children:f(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:f(`code`,{})}})})]}),o(U,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||l.isPending||x,children:[l.isPending&&f(y,{className:`h-3.5 w-3.5 animate-spin`}),t(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),f(Ae,{schema:C,values:T,onChange:E,onAction:k}),h===null?null:f(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:f(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}e();var Qi=`hub`;function $i({existing:e,typeDefs:t,typeDefsLoading:i,saving:a,saveError:s,restarting:c,restartError:u,onRestart:p,onSave:m,onCancel:h}){let{t:_}=Y(),v=b(),C=pe(),{resolvedMode:w}=ye(),T=B({code:e?.code??zi,files:e?.files,entry:e?.entry}),[D,O]=r(e?.name??``),[k,j]=r(T.files),[M,N]=r(T.entry),[P,F]=r(T.entry),[I,L]=r(e?.placement??Qi),[R,z]=r(e?.integrationId??``),[V,H]=r([]),[ee,te]=r(!1),[ne,re]=r(`blank`),[ie,ae]=r(null),[oe,se]=r(``),ce=k[P]??``,le=e=>{j(t=>({...t,[P]:e}))},ue=Object.keys(k).toSorted(),W=Li.length>1,de=n(()=>[...t?.libs??[],...Mi(k,P)],[t?.libs,k,P]),K=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:k,entry:M})}),fe=n(()=>V.filter(e=>e.severity>=8),[V]),me=Ii(V),he=D.trim()===``,ge=e===null?null:B(e),_e=e===null||ge===null||JSON.stringify(k)!==JSON.stringify(ge.files)||M!==ge.entry||D.trim()!==e.name||I!==e.placement||(R.trim()===``?void 0:R.trim())!==e.integrationId,ve=()=>{K.reset(),m({name:D.trim(),files:k,entry:M,enabled:e?.enabled??!0,placement:I,...R.trim()===``?{}:{integrationId:R.trim()}})},be=()=>{let e=Ri(Object.keys(k));j(t=>({...t,[e]:``})),F(e),ae(e),se(e)},xe=e=>{ae(e),se(e)},Se=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(k[t]!==void 0){F(t);return}j(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),M===e&&N(t),F(t)}},Ce=async e=>{let t=Li.find(t=>t.id===e);if(t===void 0)return;let n=Li.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(k)===JSON.stringify(n.files)&&M===n.entry)&&!await C({title:_(`build.blockEditor.loadExample`,`Load example`),message:_(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:_(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),j({...t.files}),N(t.entry),F(t.entry),(D.trim()===``||ne===`blank`)&&O(t.id===`blank`?``:t.name))},Te=e===null?null:Cn(e),Ee=Bi({existing:e,dirty:_e,saving:a,restarting:c});return o(`div`,{className:`space-y-4`,children:[Te!==null&&f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(G,{variant:wn(Te.tone),children:Te.label})}),o(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.name`,`Name`)}),f(q,{className:`mt-1`,value:D,onChange:e=>O(e.target.value),placeholder:_(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),f(q,{className:`mt-1`,value:R,onChange:e=>z(e.target.value),placeholder:_(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),e===null&&W&&o(`label`,{className:`block text-sm`,children:[f(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.startFrom`,`Start from`)}),f(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ne,onChange:e=>void Ce(e.target.value),"data-testid":`script-example-select`,children:Li.map(e=>o(`option`,{value:e.id,children:[e.name,` — `,e.description]},e.id))})]}),o(`div`,{children:[f(ke,{selectedNodeId:I,onSelect:L,label:_(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),I!==Qi&&o(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[f(g,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),f(`span`,{children:f(X,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:f(`strong`,{})}})})]})]}),o(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[o(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ue.map(e=>ie===e?f(q,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),ae(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":_(`build.blockEditor.renameFile`,`Rename file`)},e):o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${e===P?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>F(e),onDoubleClick:()=>xe(e),title:_(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${e}`,children:[e,e===M?` · ${_(`build.blockEditor.entry`)}`:``]},e)),f(`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:_(`build.blockEditor.file`,`+ file`)}),P!==M&&f(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>N(P),title:_(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:_(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?f(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:_(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):f(Fi,{value:ce,onChange:le,path:`file:///${P}`,extraLibs:de,onDiagnostics:H,dark:w===`dark`,heightPx:560})]}),t!==void 0&&t.libs.length===0&&f(`p`,{className:`text-xs text-warning`,children:_(`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.`)}),fe.length>0&&o(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[f(`p`,{className:`font-medium text-danger`,children:_(`build.blockEditor.errorsCannotSave`,{count:fe.length})}),fe.slice(0,5).map(e=>f(`p`,{className:`text-danger`,children:_(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),fe.length>5&&f(`p`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.moreErrors`,{count:fe.length-5})})]}),K.data!==void 0&&(K.data.ok?o(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[f(x,{className:`h-3.5 w-3.5`}),` `,_(`build.blockEditor.compiledOk`)]}):o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[K.data.line!==void 0&&f(`span`,{className:`mr-1`,children:_(`build.blockEditor.errorLine`,{line:String(K.data.line)})}),K.data.error??_(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),K.error!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[_(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,ea(K.error)]}),s!==null&&f(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&f(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),e!==null&&o(`div`,{className:`space-y-3`,children:[f(Zi,{blockId:e.id}),f(Ui,{blockId:e.id})]}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(U,{variant:`outline`,onClick:()=>K.mutate(),disabled:K.isPending||a,title:_(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[K.isPending&&f(y,{className:`h-4 w-4 animate-spin`}),` `,_(`common.compile`)]}),o(U,{onClick:ve,disabled:a||me||he,children:[a&&f(y,{className:`h-4 w-4 animate-spin`}),` `,_(`common.save`)]}),o(U,{variant:`outline`,onClick:()=>p?.(),disabled:Ee!==null||p===void 0,title:Ee??_(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[c?f(E,{className:`h-4 w-4 animate-spin`}):f(E,{className:`h-4 w-4`}),` `,_(`build.blockEditor.restart`,`Restart`)]}),o(U,{variant:`ghost`,onClick:()=>te(!ee),title:_(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[f(S,{className:`h-4 w-4`}),` `,_(`common.logs`),` `,ee?`▾`:`▸`]}),f(U,{variant:`ghost`,onClick:h,disabled:a,children:_(`common.close`,`Close`)}),o(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[_(`build.blockEditor.errorsCount`,{count:fe.length}),_e&&e!==null?` · ${_(`build.blockEditor.unsavedChanges`)}`:``]}),he&&f(G,{variant:`warning`,children:_(`build.blockEditor.nameRequired`,`Name required`)})]}),ee&&o(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:e===null?_(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):f(l,{children:f(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:A(e.id)},components:{code:f(`code`,{})}})})}),e!==null&&f(we,{addonId:A(e.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function ea(e){return e instanceof Error?e.message:String(e)}e();var ta=[`coreBlocks`,`list`],na=[`coreBlocks`,`getTypeDefs`],ra=5e3;function ia(e){return e instanceof Error?e.message:String(e)}function aa({initialBlockId:e,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:s}={}){let l=T(),{t:p}=Y(),m=b(),{state:g,openNew:_,openEdit:v,close:y}=Se({editKey:`block`,newKey:`new`}),[x,C]=r(null),[w,D]=r(null),[O,k]=r(null),j=c({queryKey:ta,refetchInterval:ra,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),M=g.mode!==`closed`,N=c({queryKey:na,enabled:M,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),P=()=>{j.refetch()},F=u(null),I=j.data;t(()=>{e===void 0||F.current===e||I?.find(t=>t.id===e&&V(t)===`code`)!==void 0&&(F.current=e,v(e),i?.(e))},[e,I,v,i]),t(()=>{a&&(C(null),_(),i?.(null),s?.())},[a,s,i,_]);let L=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{C(e.block),v(e.block.id),i?.(e.block.id),P()}}),R=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{C(e.block),v(e.block.id),i?.(e.block.id),P()}}),z=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{D(null),P()}}),B=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:P}),H=d({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:P}),ee=En((j.data??[]).filter(e=>V(e)===`code`)),te=j.data!==void 0&&ee.length===0,re=L.isPending||R.isPending,ie=L.error===null?R.error===null?null:ia(R.error):ia(L.error),ae=g.mode===`edit`?ee.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,se=g.mode===`new`||ae===null?null:Tn(ee,ae),ce=n(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:e=>{let t=Cn(e),n=Ce(e.updatedAt,l);return o(`div`,{className:`min-w-0`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(`span`,{className:`truncate font-medium`,children:e.name}),f(G,{variant:wn(t.tone),children:t.label}),f(G,{variant:`info`,children:e.placement}),n!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:n})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.detail}),O===e.id&&o(`div`,{className:`mt-2 rounded border border-border`,children:[f(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:f(X,{i18nKey:`common.logsOf`,values:{id:A(e.id)},components:{code:f(`code`,{})}})}),f(we,{addonId:A(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=B.isPending||z.isPending,n=H.isPending&&H.variables===e.id;return w===e.id?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),f(U,{variant:`danger`,onClick:()=>z.mutate(e.id),disabled:t,children:p(`common.delete`,`Delete`)}),f(U,{variant:`ghost`,onClick:()=>D(null),children:p(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(U,{variant:`ghost`,onClick:t=>{t.stopPropagation(),C(e),v(e.id),i?.(e.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),f(U,{variant:`ghost`,onClick:t=>{t.stopPropagation(),H.mutate(e.id)},disabled:t||n||!e.enabled,title:e.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:f(E,{className:`h-4 w-4${n?` animate-spin`:``}`})}),f(U,{variant:`ghost`,onClick:t=>{t.stopPropagation(),k(O===e.id?null:e.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:f(S,{className:`h-4 w-4`})}),f(U,{variant:`ghost`,onClick:t=>{t.stopPropagation(),B.mutate({blockId:e.id,enabled:!e.enabled})},disabled:t,title:e.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:e.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),f(U,{variant:`ghost`,onClick:t=>{t.stopPropagation(),D(e.id)},title:p(`common.delete`,`Delete`),children:f(h,{className:`h-4 w-4`})})]})}}],[w,O,i,v,z,H.isPending,H.variables,B,p]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:j.data===void 0?``:Dn(ee)}),j.error!=null&&f(le,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:ia(j.error),onRetry:P}),f(oe,{columns:ce,rows:ee,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ee,emptyMessage:te?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):j.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{C(e),v(e.id),i?.(e.id)}}),f(ve,{open:M,onClose:()=>{L.reset(),R.reset(),H.reset(),C(null),y(),i?.(null)},title:se===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:se.name}),icon:ne,width:`xl`,testId:`script-editor-panel`,children:f($i,{existing:se,typeDefs:N.data,typeDefsLoading:N.isLoading,saving:re,saveError:ie,restarting:H.isPending,restartError:H.error===null?null:ia(H.error),onRestart:se===null?void 0:()=>H.mutate(se.id),onSave:e=>{let t=se;t===null?L.mutate(e):R.mutate({blockId:t.id,block:e})},onCancel:()=>{L.reset(),R.reset(),H.reset(),C(null),y(),i?.(null)}})}),z.error!=null&&f(le,{message:ia(z.error)}),B.error!=null&&f(le,{message:ia(B.error)}),H.error!=null&&f(le,{message:ia(H.error)})]})}var oa=[`automations`,`scripts`,`custom-device`];function sa(e){return e!==null&&oa.some(t=>t===e)}var ca=[`coreBlocks`,`list`,`build-counts`],la=[`block`,`create`];function ua(e){return e.filter(e=>V(e)===`code`).length}function da(e){return e.filter(e=>He(e.code)).length}function fa(e,t){return t===null?e:`${e} (${String(t)})`}function pa(){let{t:e}=Y(),t=b(),[n,r]=Ne(),i=n.get(`tab`),a=sa(i)?i:`automations`,s=n.get(`create`)===`1`,l=c({queryKey:ca,refetchInterval:5e3,queryFn:async()=>(await t.trpcClient.coreBlocks.list.query({})).blocks}).data,u=l===void 0?null:ua(l),d=l===void 0?null:da(l),p=c({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>t.trpcClient.coreBlocks.listCompositions.query({})}),m=p.data?.state===`loaded`?p.data.views.length:null,h=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},g=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{r(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},y=()=>{r(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},x=()=>{r(e=>{let t=new URLSearchParams(e);return t.delete(`create`),t},{replace:!0})},S=a===`automations`?`New automation`:a===`scripts`?`New script`:`New composition`,C=Fe(`/build`,{t:e,isAdmin:!0})??{icon:D,title:e(`nav.build`,`Build-your-self`)};return f(Ie,{icon:C.icon,title:C.title,subtitle:e(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${C.title} sections`,fill:!0,actions:o(U,{type:`button`,onClick:y,"data-testid":`build-new`,children:[f(v,{className:`h-4 w-4`}),` `,S]}),sections:[{id:`automations`,label:fa(`Automations`,d),ownedParams:la,content:f(Nn,{onOpenScripts:h,initialBlockId:a===`automations`?n.get(`block`)??void 0:void 0,onBlockIdChange:g,createRequested:a===`automations`&&s,onCreateConsumed:x})},{id:`scripts`,label:fa(`Scripts`,u),ownedParams:la,content:f(aa,{initialBlockId:a===`scripts`?n.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:a===`scripts`&&s,onCreateConsumed:x})},{id:`custom-device`,label:fa(`Custom Device`,m),ownedParams:la,content:f(Qn,{createRequested:a===`custom-device`&&s,onCreateConsumed:x})}]})}export{pa as BuildPage};
@@ -0,0 +1 @@
1
+ import{$ as e,G as t,J as n,L as r,S as i,b as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{bi as s,yi as c}from"./player-overlays-CvKnZb5M.js";import{nr as l,tr as u}from"./client-BbPYrWg7.js";import{h as d}from"./video-CJw8Jnle.js";import{Gr as f,_a as p,_r as m,fr as h,ga as g,gr as _,ha as v,mr as y,pr as b,va as x,vr as S}from"./src-DKc14e9G.js";import{t as C}from"./i18n-BO6gCPcC.js";import{t as w}from"./useTranslation-D3Is_4B6.js";import{lr as T,ur as ee}from"./index-C8XwyZGE.js";import{t as E}from"./AdminPage-B4QlIiKh.js";e();var D=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function O(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function k(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function A(e){let t=e.getDay();return O(k(e,t===0?-6:1-t))}function j(e,t){if(t===`day`){let t=O(e);return{startMs:t.getTime(),endMs:k(t,1).getTime()}}if(t===`week`){let t=A(e);return{startMs:t.getTime(),endMs:k(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=A(n),a=k(A(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function M(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=A(e),n=k(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function N(e,t,n){return t===`day`?k(e,n):t===`week`?k(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function P(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function F(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function I(e){if(e.allDay===!0)return C.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function L(e){let t=u(e),n=new Date(t.startMs),r=new Date(t.endMs),i={weekday:`short`,year:`numeric`,month:`short`,day:`numeric`};if(e.allDay===!0){let e=O(n),t=k(O(r),-1);return V(e,t)?C.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):C.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return V(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function R({label:e,children:t}){return i(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[o(`dt`,{className:`text-foreground-subtle`,children:e}),o(`dd`,{className:`min-w-0 break-words text-foreground`,children:t})]})}function z({ev:e,calendarName:t,color:n,onClose:r}){let{t:a}=w();return o(h,{open:!0,onOpenChange:e=>!e&&r(),children:i(y,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[o(m,{children:i(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[o(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:n},"aria-hidden":!0}),o(S,{className:`min-w-0 break-words`,children:e.title})]})}),o(b,{children:i(`dl`,{className:`space-y-3`,children:[o(R,{label:a(`systemPage.calendars.when`,`When`),children:L(e)}),o(R,{label:a(`systemPage.calendars.calendar`,`Calendar`),children:t}),e.location!==void 0&&e.location.length>0?o(R,{label:a(`systemPage.calendars.location`,`Location`),children:e.location}):null,e.description!==void 0&&e.description.length>0?o(R,{label:a(`systemPage.calendars.description`,`Description`),children:o(`span`,{className:`whitespace-pre-wrap`,children:e.description})}):null]})}),o(_,{children:o(f,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function B(e,t){return e.filter(e=>l(e,t))}function V(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function H({mode:e,onChange:t}){let{t:n}=w(),r=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return o(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:r.map(n=>o(`button`,{type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function U({calendars:e,onToggleVisible:t,onColorChange:n,busy:r}){let{t:a}=w();return i(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[o(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:a(`systemPage.calendars.calendars`,`Calendars`)}),o(`ul`,{className:`space-y-1`,children:e.map(e=>i(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface`,children:[o(`input`,{type:`checkbox`,className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:e.visible,disabled:r,onChange:n=>t(e.id,n.target.checked),"aria-label":a(`systemPage.calendars.show`,`Show {{name}}`,{name:e.name}),"data-testid":`calendars-visible-${e.id}`}),o(`input`,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:e.color,disabled:r,onChange:t=>n(e.id,t.target.value.toUpperCase()),"aria-label":a(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:e.name}),"data-testid":`calendars-color-${e.id}`}),i(`div`,{className:`min-w-0 flex-1`,children:[o(`div`,{className:`truncate text-sm font-medium ${e.visible?`text-foreground`:`text-foreground-subtle`}`,children:e.name}),i(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[F(e),e.enabled?``:` · ${a(`systemPage.calendars.unavailableAtSource`)}`]})]})]},e.id))})]})}function W({ev:e,color:t,compact:n,onSelect:r}){return o(`button`,{type:`button`,className:n?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:t},title:e.title,onClick:()=>r(e),"data-testid":`calendars-event-${e.id}`,children:n?e.title:i(a,{children:[o(`div`,{className:`font-medium`,children:e.title}),o(`div`,{className:`opacity-90`,children:I(e)})]})})}function G({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let{t:s}=w(),{startMs:c,endMs:l}=j(e,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=k(e,1))u.push(e);let d=e.getMonth();return i(`div`,{"data-testid":`calendars-month`,children:[o(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:D.map(e=>o(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),o(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(e=>{let c=O(e).getTime(),l=B(t,c),u=e.getMonth()!==d,f=V(e,r);return i(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[o(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:e.getDate()}),i(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>o(W,{ev:e,color:n.get(e.calendarId)??`#64748B`,compact:!0,onSelect:a},e.id)),l.length>3?o(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function K({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let s=A(e);return o(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>k(s,t)).map(e=>{let s=O(e).getTime(),c=B(t,s);return i(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[o(`div`,{className:V(e,r)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:e.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),o(`div`,{className:`space-y-1`,children:c.length===0?o(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>o(W,{ev:e,color:n.get(e.calendarId)??`#64748B`,onSelect:a},e.id))})]},s)})})}function q({anchor:e,events:t,colorById:n,calName:r,onSelectEvent:a}){let{t:s}=w(),c=B(t,O(e).getTime());return c.length===0?o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):o(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(e=>o(`li`,{children:i(`button`,{type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>a(e),"data-testid":`calendars-event-${e.id}`,children:[o(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:n.get(e.calendarId)??`#64748B`}}),i(`div`,{className:`min-w-0`,children:[o(`div`,{className:`font-medium text-sm text-foreground`,children:e.title}),i(`div`,{className:`text-xs text-foreground-subtle`,children:[I(e),` · `,r.get(e.calendarId)??e.calendarId]}),e.location!==void 0&&e.location.length>0?o(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:e.location}):null]})]})},e.id))})}function J(){let{t:e}=w(),a=g(),l=v({}),u=x(),[f,m]=n(`month`),[h,_]=n(()=>O(new Date)),[y,b]=n(null),S=t(()=>O(new Date),[]),C=a.isSuccess,D=l.isSuccess&&l.data!==void 0?l.data:void 0,k=t(()=>!C||a.data===void 0?[]:a.data.map(e=>P(e,D)),[C,a.data,D]),A=t(()=>k.filter(e=>e.visible),[k]),F=t(()=>A.map(e=>e.id),[A]),I=t(()=>j(h,f),[h,f]),L=p({startMs:I.startMs,endMs:I.endMs,calendarIds:[...F]},{enabled:C&&F.length>0}),R=L.data??[],B=t(()=>{let e=new Map;for(let t of k)e.set(t.id,t.color);return e},[k]),V=t(()=>{let e=new Map;for(let t of k)e.set(t.id,t.name);return e},[k]),W=r((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>l.refetch())},[l,u]),J=r((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>l.refetch())},[l,u]),Y=r(()=>_(O(new Date)),[]),X=r(()=>_(e=>N(e,f,-1)),[f]),Z=r(()=>_(e=>N(e,f,1)),[f]),Q=`inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-surface text-foreground hover:bg-primary/5 disabled:opacity-50`,$;return $=a.isPending?o(`p`,{className:`text-sm text-foreground-subtle`,children:e(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):a.isError?i(`p`,{className:`text-sm text-destructive`,children:[e(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,a.error.message]}):k.length===0?o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:o(T,{i18nKey:`systemPage.calendars.emptySources`,components:{link:o(ee,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):F.length===0?i(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[o(U,{calendars:k,onToggleVisible:W,onColorChange:J,busy:u.isPending}),o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:e(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):i(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[o(U,{calendars:k,onToggleVisible:W,onColorChange:J,busy:u.isPending}),i(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[i(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(H,{mode:f,onChange:m}),i(`div`,{className:`flex items-center gap-1`,children:[o(`button`,{type:`button`,className:Q,onClick:X,"aria-label":e(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:o(s,{className:`h-4 w-4`})}),o(`button`,{type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:Y,"data-testid":`calendars-today`,children:e(`systemPage.calendars.today`,`Today`)}),o(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":e(`common.next`,`Next`),"data-testid":`calendars-next`,children:o(c,{className:`h-4 w-4`})})]}),o(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:M(h,f)})]}),L.isPending?o(`p`,{className:`text-sm text-foreground-subtle`,children:e(`systemPage.calendars.loadingEvents`,`Loading events…`)}):L.isError?i(`p`,{className:`text-sm text-destructive`,children:[e(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,L.error.message]}):f===`month`?o(G,{anchor:h,events:R,colorById:B,today:S,onSelectEvent:b}):f===`week`?o(K,{anchor:h,events:R,colorById:B,today:S,onSelectEvent:b}):o(q,{anchor:h,events:R,colorById:B,calName:V,onSelectEvent:b})]})]}),i(E,{icon:d,title:e(`systemPage.calendars.calendars`,`Calendars`),subtitle:e(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,y===null?null:o(z,{ev:y,calendarName:V.get(y.calendarId)??y.calendarId,color:B.get(y.calendarId)??`#64748B`,onClose:()=>b(null)})]})}export{J as CalendarsPage,J as default};