@camstack/addon-admin-ui 1.2.430 → 1.2.431

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 (119) hide show
  1. package/dist/assets/{AddonAssetIcon-BWUL7eDI.js → AddonAssetIcon-CngGyUbH.js} +1 -1
  2. package/dist/assets/{Addons-2-Q9J_R-.js → Addons-COSbX7Q1.js} +1 -1
  3. package/dist/assets/{AdminPage-DMiMIHwu.js → AdminPage-BFQa1eDk.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-DKH0UpKh.js → AdminSectionedPage-Bb00eMTj.js} +1 -1
  5. package/dist/assets/{AiProfiles-DQ5YpTn5.js → AiProfiles-DGok1qYw.js} +1 -1
  6. package/dist/assets/{BrokerForm-wEqc4cpx.js → BrokerForm-NDMOvAlu.js} +1 -1
  7. package/dist/assets/{Build-DIaw3f01.js → Build-BPgFXVbn.js} +1 -1
  8. package/dist/assets/{Calendars-BpyELuD4.js → Calendars-DLuwgZXW.js} +1 -1
  9. package/dist/assets/{Cluster-CfJQLikz.js → Cluster-BUBVih9A.js} +1 -1
  10. package/dist/assets/{ClusterStepModel-B_1igjPf.js → ClusterStepModel-DzduELev.js} +1 -1
  11. package/dist/assets/{CompositionEditor-DYkQHem0.js → CompositionEditor-DTgOmFqj.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-DDBZOcqy.js → CompositionEditorPage-D73l3mqU.js} +1 -1
  13. package/dist/assets/{Data-7qDFkx-Q.js → Data-Wqos-WHl.js} +1 -1
  14. package/dist/assets/{DeviceDetail-Dy2NTHbz.js → DeviceDetail-CwmpXUmk.js} +1 -1
  15. package/dist/assets/{DeviceDoActionFields-DmKzugUt.js → DeviceDoActionFields-DKOJoFJc.js} +1 -1
  16. package/dist/assets/{Devices-COzPWkpB.js → Devices-D_SKAo6X.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-CD4jAYaX.js → EmbedPlayerPage-DI4ac8Wo.js} +1 -1
  18. package/dist/assets/Identity-C25gG2Mh.js +1 -0
  19. package/dist/assets/{IntegrationDetail-CP91fqQF.js → IntegrationDetail-L73oZLMf.js} +1 -1
  20. package/dist/assets/{IntegrationHub-DMx7fLHV.js → IntegrationHub-DuVgrEey.js} +1 -1
  21. package/dist/assets/{Integrations-Blb_S3_f.js → Integrations-CUPpCCtl.js} +1 -1
  22. package/dist/assets/{Integrations-BzqzbXQ2.js → Integrations-Cgm8qaox.js} +1 -1
  23. package/dist/assets/{Library-Cqg-Y18g.js → Library-Dm0AivX3.js} +1 -1
  24. package/dist/assets/{Locations-EQXaWxpY.js → Locations-B2TjRBpQ.js} +1 -1
  25. package/dist/assets/{Logs-hQ_F2BI5.js → Logs-CeX1xx9_.js} +1 -1
  26. package/dist/assets/{MaskShapeCanvas-BkBmWJHu.js → MaskShapeCanvas-GZ2ZMDcz.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-Ctl81l__.js → MotionZonesSettings-B5gIoLVC.js} +1 -1
  28. package/dist/assets/{MyAccess-D8vfWKFy.js → MyAccess-DJvaTHrq.js} +1 -1
  29. package/dist/assets/Network-D0uak4Dc.js +1 -0
  30. package/dist/assets/{NodeAddonsSettingsPanel-DMEeQbDW.js → NodeAddonsSettingsPanel-kmgNnVID.js} +1 -1
  31. package/dist/assets/{Notifications-BtrpoxXL.js → Notifications-DP0iwqUM.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-DEbHPS5X.js → PrivacyMaskSettings-DWCvE7XZ.js} +1 -1
  33. package/dist/assets/{Recordings-BrGa72HR.js → Recordings-r5KE18a6.js} +1 -1
  34. package/dist/assets/{ScanNetworkModal-CTjVwV69.js → ScanNetworkModal-CHWsBmiM.js} +1 -1
  35. package/dist/assets/{SceneMonitorEditor-DgNqz_fJ.js → SceneMonitorEditor-BNFYspNy.js} +1 -1
  36. package/dist/assets/{SessionsList-CzSpm8u5.js → SessionsList-OvrBa2rd.js} +1 -1
  37. package/dist/assets/{Showroom-DC0Rdsfa.js → Showroom-DNgHGmg0.js} +1 -1
  38. package/dist/assets/{System-ByMuYkyz.js → System-CcDzJj6C.js} +1 -1
  39. package/dist/assets/{Terminal-CLof2QSK.js → Terminal-DpGR-56V.js} +1 -1
  40. package/dist/assets/{Viewer-CLEBXqqR.js → Viewer-vqCH_LqM.js} +1 -1
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CxVe8UPZ.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DR_v3lvi.js} +1 -1
  42. package/dist/assets/{addon-icons-context-B6iVhWXv.js → addon-icons-context-B2Gmu49a.js} +1 -1
  43. package/dist/assets/{archive-WKa1b0o1.js → archive-CoV271Ga.js} +1 -1
  44. package/dist/assets/{authed-media-B0bKjjhb.js → authed-media-BSx10sm9.js} +1 -1
  45. package/dist/assets/{bell-off-DQeMLsEK.js → bell-off-CQHJCxaC.js} +1 -1
  46. package/dist/assets/{board-model-DIWD11Nh.js → board-model-lagHZiI7.js} +1 -1
  47. package/dist/assets/{boxes-DMqqPR7T.js → boxes-DKr2EDaB.js} +1 -1
  48. package/dist/assets/circle-slash-D1CG5tRc.js +1 -0
  49. package/dist/assets/client-CqsEJzhO.js +358 -0
  50. package/dist/assets/{cloud-upload-8Rtciaox.js → cloud-upload-D3IJwdmA.js} +1 -1
  51. package/dist/assets/crop-sD8BDahL.js +1 -0
  52. package/dist/assets/{device-integration-icon-BRxzTJPF.js → device-integration-icon-BHf83qVT.js} +1 -1
  53. package/dist/assets/device-picker-model-JBC8n4FU.js +1 -0
  54. package/dist/assets/dist-C3lDDHVX.js +358 -0
  55. package/dist/assets/{dist-BiqTDJU8.js → dist-Dlrgg5It.js} +1 -1
  56. package/dist/assets/{eraser-AtBM6hp_.js → eraser-BRuYxYS4.js} +1 -1
  57. package/dist/assets/{hard-drive-download-COMXm0vT.js → hard-drive-download-B14E8eTo.js} +1 -1
  58. package/dist/assets/{history-CNH6Hwzl.js → history-Dn2pnfaZ.js} +1 -1
  59. package/dist/assets/{hostInit-Cn-rvYrx.js → hostInit-3qW3eaSU.js} +1 -1
  60. package/dist/assets/i18n-B-IeyHf7.js +1 -0
  61. package/dist/assets/icons-CvJTX54k.js +1 -0
  62. package/dist/assets/{index-IBVizVRk.js → index-mBJW996X.js} +3 -3
  63. package/dist/assets/key-EeG_L4W9.js +1 -0
  64. package/dist/assets/{key-round-DhUJVMTJ.js → key-round-C9pPg55h.js} +1 -1
  65. package/dist/assets/{layers-BNtkJA8b.js → layers-DhxisKd7.js} +1 -1
  66. package/dist/assets/{linked-devices-model-DXpryeZj.js → linked-devices-model-CTfAwc1p.js} +1 -1
  67. package/dist/assets/{list-ordered-DE6semVl.js → list-ordered-Ckqq8GR7.js} +1 -1
  68. package/dist/assets/{location-owned-usage-4K4CCW-I.js → location-owned-usage-eDtNCANy.js} +1 -1
  69. package/dist/assets/{log-in-k_3OshGq.js → log-in-CAiH8-Mq.js} +1 -1
  70. package/dist/assets/{memory-stick--pKqiId8.js → memory-stick-Bir-K-V7.js} +1 -1
  71. package/dist/assets/{message-square-plus-DD_p-LBd.js → message-square-plus-B_0WwbBk.js} +1 -1
  72. package/dist/assets/{mf-entry-bootstrap-0-b5dba7ed.js → mf-entry-bootstrap-0-c62ae51c.js} +2 -2
  73. package/dist/assets/{mic-off-abkMqo-Z.js → mic-off-D5kT_DDX.js} +1 -1
  74. package/dist/assets/{monitor-off-Btwz3hik.js → monitor-off-DzKNd6eJ.js} +1 -1
  75. package/dist/assets/{monitor-smartphone-CewWbhfo.js → monitor-smartphone-D3ZPy75c.js} +1 -1
  76. package/dist/assets/mount-JBC8n4FU.js +1 -0
  77. package/dist/assets/{notification-schedule-field-DALe8QBw.js → notification-schedule-field-DaKiveMR.js} +1 -1
  78. package/dist/assets/{octagon-alert-B-H38qMt.js → octagon-alert-BYNvsZ0Q.js} +1 -1
  79. package/dist/assets/{player-overlays-CTjp5_0E.js → player-overlays-DFTWiQ8-.js} +1 -1
  80. package/dist/assets/{recycle-om2m5njd.js → recycle-DJUuC9xt.js} +1 -1
  81. package/dist/assets/remoteEntry-BhYjusn-.js +1 -0
  82. package/dist/assets/{scan-eye-RPomUFSt.js → scan-eye-_otUiDbW.js} +1 -1
  83. package/dist/assets/{scissors-oLO0ZxF2.js → scissors-BU04yNa7.js} +1 -1
  84. package/dist/assets/{search-x-By7QfPjb.js → search-x-Djycej4Y.js} +1 -1
  85. package/dist/assets/{send-CWuZ-VHG.js → send-BNY2bJqA.js} +1 -1
  86. package/dist/assets/{settings-2-DrkSvhIU.js → settings-2-BxpLi7pY.js} +1 -1
  87. package/dist/assets/{speaker-Bi1HndpO.js → speaker-BspD0ixN.js} +1 -1
  88. package/dist/assets/src-CE3hNyCx.js +67 -0
  89. package/dist/assets/{timer-reset-CX_75T7d.js → timer-reset-CPRU92uv.js} +1 -1
  90. package/dist/assets/{ungroup-CQ9vK9Rb.js → ungroup-oYlFn3LE.js} +1 -1
  91. package/dist/assets/{unlink-DRIRCsre.js → unlink-D0eJ5vAc.js} +1 -1
  92. package/dist/assets/{usb-CSAqtgKZ.js → usb-C24Ua3ty.js} +1 -1
  93. package/dist/assets/{use-scenes-feed-B3oVDWHB.js → use-scenes-feed-DzzIer2d.js} +1 -1
  94. package/dist/assets/{use-stationary-objects-D8Q3fSKJ.js → use-stationary-objects-C-l1Z5zI.js} +1 -1
  95. package/dist/assets/useEventInvalidation-JBC8n4FU.js +1 -0
  96. package/dist/assets/{useNodeUrlSelection-CbhdLJkk.js → useNodeUrlSelection-Ba-ed7zb.js} +1 -1
  97. package/dist/assets/user-round-JzUTTasm.js +1 -0
  98. package/dist/assets/{user-x-fVEkryXF.js → user-x-CdpX6b_D.js} +1 -1
  99. package/dist/assets/{video-C9XbLIGZ.js → video-vLKHp9E_.js} +1 -1
  100. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CWUvAVp2.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D83o1ikp.js} +2 -2
  101. package/dist/index.html +10 -10
  102. package/dist/server/addon.js +167 -25
  103. package/package.json +1 -1
  104. package/dist/assets/Identity-BnBFoIrz.js +0 -1
  105. package/dist/assets/Network-BYFc8leF.js +0 -1
  106. package/dist/assets/circle-slash-HW5fnitA.js +0 -1
  107. package/dist/assets/client-Ck3kx2Z0.js +0 -358
  108. package/dist/assets/crop-BCuJfQIp.js +0 -1
  109. package/dist/assets/device-picker-model-DUsOqTKW.js +0 -1
  110. package/dist/assets/dist-D4jmeWXJ.js +0 -358
  111. package/dist/assets/file-up-DvSwIdQI.js +0 -1
  112. package/dist/assets/i18n-DWijAvai.js +0 -1
  113. package/dist/assets/icons-BzZe_Qg7.js +0 -1
  114. package/dist/assets/key-B62K9GgX.js +0 -1
  115. package/dist/assets/mount-DUsOqTKW.js +0 -1
  116. package/dist/assets/remoteEntry-Dmuue8--.js +0 -1
  117. package/dist/assets/src-CoNs4bys.js +0 -67
  118. package/dist/assets/useEventInvalidation-DUsOqTKW.js +0 -1
  119. package/dist/assets/user-round-DhADiv-t.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-B6iVhWXv.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-B2Gmu49a.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,4 +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{Hr as d,It as f,Ln as p,Nt as m,On as h,Ot as g,Q as _,ar as v,bi as y,di as b,dn as x,dt as S,en as C,fn as w,gi as ee,ln as T,ri as E,wn as te,yi as ne,yn as D}from"./player-overlays-CTjp5_0E.js";import{c as O}from"./video-C9XbLIGZ.js";import{t as re}from"./octagon-alert-B-H38qMt.js";import{Ti as ie}from"./client-Ck3kx2Z0.js";import{$l as k,An as ae,Ar as oe,Bn as se,Br as A,Cr as j,Dn as ce,En as le,Er as M,Fr as ue,Ir as N,Lr as de,Mr as P,Or as F,Pr as fe,Q as I,Qo as pe,Sr as L,Tn as R,Tr as me,Tt as z,U as he,Vr as B,Xn as V,Zn as ge,_u as H,ar as U,br as W,jn as _e,jr as G,kn as ve,kr as K,mu as ye,vr as be,wr as xe,wt as Se,xr as q,zr as J}from"./src-CoNs4bys.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import"./mount-DUsOqTKW.js";import{Q as X,Y as Z,et as Ce}from"./index-IBVizVRk.js";import{t as we}from"./AdminPage-DMiMIHwu.js";import{t as Q}from"./NodeAddonsSettingsPanel-DMEeQbDW.js";import{n as Te,t as Ee}from"./useNodeUrlSelection-CbhdLJkk.js";e();var De={queued:{icon:E,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:v,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:D,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:y,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:re,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Oe({item:e}){let{t}=Y(),n=De[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 ke=new Set([`completed`,`failed`,`partially-failed`,`cancelled`]),Ae=new Set([`done`,`failed`,`skipped`]);function je(e){return!Ae.has(e.phase)&&!ke.has(e.jobState)}function Me(e,t){let n=new Map,r=[...e].sort((e,t)=>e.createdAtMs-t.createdAtMs);for(let e of r){let r=ke.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 Ne(){let{data:e}=K({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=H(ie.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 Me([...n.values()],Date.now())},[e,t])}var Pe={queued:{icon:E,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:v,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:y,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:re,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:C,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function Fe({progress:e}){let{t}=Y(),n=Pe[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 Ie(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 Le(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function Re(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(Le)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
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{Hr as d,It as f,Ln as p,Nt as m,On as h,Ot as g,Q as _,ar as v,bi as y,di as b,dn as x,dt as S,en as C,fn as w,gi as ee,ln as T,ri as E,wn as te,yi as ne,yn as D}from"./player-overlays-DFTWiQ8-.js";import{c as O}from"./video-vLKHp9E_.js";import{t as re}from"./octagon-alert-BYNvsZ0Q.js";import{Ti as ie}from"./client-CqsEJzhO.js";import{$l as k,An as ae,Ar as oe,Bn as se,Br as A,Cr as j,Dn as ce,En as le,Er as M,Fr as ue,Ir as N,Lr as de,Mr as P,Or as F,Pr as fe,Q as I,Qo as pe,Sr as L,Tn as R,Tr as me,Tt as z,U as he,Vr as B,Xn as V,Zn as ge,_u as H,ar as U,br as W,jn as _e,jr as G,kn as ve,kr as K,mu as ye,vr as be,wr as xe,wt as Se,xr as q,zr as J}from"./src-CE3hNyCx.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import"./mount-JBC8n4FU.js";import{Q as X,Y as Z,et as Ce}from"./index-mBJW996X.js";import{t as we}from"./AdminPage-BFQa1eDk.js";import{t as Q}from"./NodeAddonsSettingsPanel-kmgNnVID.js";import{n as Te,t as Ee}from"./useNodeUrlSelection-Ba-ed7zb.js";e();var De={queued:{icon:E,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:v,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:D,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:y,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:re,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Oe({item:e}){let{t}=Y(),n=De[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 ke=new Set([`completed`,`failed`,`partially-failed`,`cancelled`]),Ae=new Set([`done`,`failed`,`skipped`]);function je(e){return!Ae.has(e.phase)&&!ke.has(e.jobState)}function Me(e,t){let n=new Map,r=[...e].sort((e,t)=>e.createdAtMs-t.createdAtMs);for(let e of r){let r=ke.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 Ne(){let{data:e}=K({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=H(ie.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 Me([...n.values()],Date.now())},[e,t])}var Pe={queued:{icon:E,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:v,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:v,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:y,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:re,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:C,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function Fe({progress:e}){let{t}=Y(),n=Pe[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 Ie(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 Le(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function Re(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(Le)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
2
2
  `)}function ze(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
3
  `)}var Be={uninstalled:`uninstalled`,"not-installed":`was not installed`,refused:`REFUSED`,failed:`FAILED`,"pending-reconnect":`offline — removed when it reconnects`};function Ve(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)}: ${Be[r.outcome]}${e}`),r.error!==void 0&&n.push(` ${r.error}`);for(let e of r.warnings)n.push(` ${e}`)}return n.join(`
4
4
  `)}var He={},Ue=3e4,We=`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 Ge({packageName:e,displayName:t,selectedNode:n,hideNodeAction:r,disabled:i}){let{t:o}=Y(),c=s(),u=ge(),d=V(),p=F(He,{staleTime:Ue}),m=p.data?.installations??[],h=(p.data?.unreachable??[]).map(e=>e.nodeId),g=Ie(m,e),_=e=>g.find(t=>t.nodeId===e)?.nodeName??(e===n.id?n.name:e),v=A({onSettled:()=>{c.invalidateQueries({queryKey:[[`addons`]]}),c.invalidateQueries({queryKey:[[`addonPages`]]}),c.invalidateQueries({queryKey:[[`capabilities`]]}),c.invalidateQueries({queryKey:[[`nodes`]]})}}),y=async e=>{await d({title:e.success?o(`addons.addonUninstallControls.uninstalled`,`{{displayName}} uninstalled`,{displayName:t}):o(`addons.addonUninstallControls.notEveryNodeWasCleaned`,`{{displayName}}: not every node was cleaned`,{displayName:t}),message:Ve(e,_),variant:e.success?`default`:`danger`})},b=async n=>{try{await y(await v.mutateAsync({packageName:e,...n}))}catch(e){await d({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:ze(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 d({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=Ie(n.installations,e);await u({title:o(`addons.addonUninstallControls.uninstallEverywhere`,`Uninstall {{displayName}} everywhere?`,{displayName:t}),message:Re(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:We,title:o(`addons.addonUninstallControls.uninstallFrom2`,`Uninstall from {{name}}`,{name:n.name}),children:[l(f,{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:We,title:o(`addons.addonUninstallControls.uninstallFromEveryNodeThat`,`Uninstall from every node that has it`),children:[l(O,{className:`h-3 w-3`}),g.length>0?o(`addons.uninstallControls.everywhereCount`,{count:g.length}):o(`addons.uninstallControls.everywhere`)]})]})}function Ke({packageName:e,currentVersion:t,installSource:n,onInstall:r,onClose:i,onSelect:s,selectedVersion:c}){let{t:u}=Y(),f=n===`upload`||n===`local`,{data:p,isLoading:m}=xe({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(S,{className:`h-3 w-3`})})]}),f&&a(`div`,{className:`flex items-start gap-2 px-3 py-2 border-b border-border bg-cyan-500/10 text-[10px]`,children:[l(g,{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(Z,{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(v,{className:`h-3.5 w-3.5 animate-spin`}),u(`addons.versionPicker.loadingVersions`,`Loading versions...`)]}),p&&l(`div`,{className:`max-h-64 overflow-auto divide-y divide-border`,children:p.map(e=>{let n=e.version===t,i=s!==void 0&&e.version===c,f=/-(alpha|beta|rc|dev|canary|next)/i.test(e.version),p=a(o,{children:[l(`span`,{className:`font-mono flex-1 text-left ${n?`text-primary font-semibold`:f?`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:[p,i?l(y,{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:[p,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(d,{className:`h-3 w-3`})})]},e.version)})}),p&&p.length===0&&l(`div`,{className:`py-4 text-center text-[10px] text-foreground-subtle`,children:u(`addons.versionPicker.noVersionsFound`,`No versions found`)})]})}e();var qe=`device-export`;function Je(e){return e.capabilities.some(e=>(typeof e==`string`?e:e.name)===qe)}function Ye(e){return e!==`local`&&e!==`upload`}function Xe({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?_(`/api/addon-assets/${n}/${i}`):null,m=!!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:m?l(`img`,{src:f,alt:n,className:`h-4 w-4`,onError:()=>c(!0)}):l(e?p:te,{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`}),Ye(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(g,{className:`h-2.5 w-2.5 text-white`})})]})}function Ze({version:e,availableUpdate:t,selectedVersion:n,isUpdating:r,installSource:i,disabled:o,onUpdate:s,onOpenPicker:c,children:u}){let{t:f}=Y();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(v,{className:`h-3 w-3 animate-spin`}),f(`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:f(`addons.addonCard.updateTo`,`Update to {{target}}`,{target:r}),children:[l(d,{className:`h-3 w-3`}),f(`addons.addonCard.update`,`Update`)]}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),c()},disabled:o,"aria-label":f(`addons.addonCard.selectVersionToInstall`,`Select version to install`),title:f(`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(ne,{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:f(`addons.addonCard.versionTapToViewAll`,`Version {{version}} — tap to view all versions`,{version:e}),children:[e,l(ne,{className:`h-3 w-3 opacity-50`})]}),u]})}function Qe({addonId:e}){let t=s(),{data:n=`inherit`}=q({addonId:e}),r=N({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 $e={id:`hub`,name:`Hub`,isHub:!0};function et({addon:e,agents:n=[],clusterStatus:i,hideVersion:c,availableUpdate:u,onUpdate:d,isUpdating:f,jobProgress:m,bundle:g,bulkItem:_,disabledByBulk:v,isSystem:y,selectedNode:b}){let{t:x}=Y(),[C,E]=r(!1),[te,O]=r(!1),[ie,k]=r(!1),[oe,A]=r(null);t(()=>{A(null)},[u]);let j=oe??u,[M,ue]=r(!1),[N,de]=r(!1),[F,pe]=r(`logs`),L=s(),he=X(),{manifest:B}=e,V=e.installedOn??[],ge=!g&&!B.protected&&B.removable!==!1,H=!!g,U=g?.displayName??B.name,W=g?.packageName??B.packageName,G=g?.version??B.packageVersion??B.version,K=g?.installSource??e.installSource,ye=g?g.bundle?.description??g.addons[0]?.manifest.description:B.description,be=P({onSuccess:()=>{L.invalidateQueries({queryKey:[[`addons`]]})}}),xe=me({onSuccess:()=>{L.invalidateQueries({queryKey:[[`addons`]]}),L.invalidateQueries({queryKey:[[`addonPages`]]}),L.invalidateQueries({queryKey:[[`capabilities`]]}),L.invalidateQueries({queryKey:[[`integrations`]]})}}),q=fe({onSuccess:()=>{L.invalidateQueries({queryKey:[[`addons`]]}),L.invalidateQueries({queryKey:[[`alerts`]]})}}),J=e.health,Z=J?.phase===`failed`&&!J.inGracePeriod,Ce=Z&&J?.nextRetryAt&&!J.retrying;return a(`div`,{className:`rounded-md border bg-surface overflow-hidden ${Z?`border-red-500/50`:`border-border`}`,children:[Z&&J&&a(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[l(re,{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:x(`addons.addonCard.failedToLoad`,{attempt:J.retryCount})}),l(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:J.lastError?.message??x(`addons.addonCard.unknownError`,`Unknown error`)}),Ce&&J.nextRetryAt&&l(`div`,{className:`text-[10px] text-foreground-subtle mt-1`,children:x(`addons.addonCard.autoRetryAt`,{time:new Date(J.nextRetryAt).toLocaleTimeString()})})]}),a(`button`,{type:`button`,disabled:q.isPending||J.retrying,onClick:e=>{e.stopPropagation(),q.mutate({packageName:W})},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:x(`addons.addonCard.resetRetryCounterAndForce`,`Reset retry counter and force immediate reload`),children:[l(D,{className:`h-3 w-3 ${q.isPending||J.retrying?`animate-spin`:``}`}),x(`addons.addonCard.retryNow`,`Retry now`)]})]}),a(`div`,{className:`flex items-start gap-2.5 px-3 py-2`,children:[l(Xe,{isBundle:H||!!B.components&&B.components.length>1,installSource:K,addonId:H?g.addons[0]?.manifest.id:B.id,iconPath:H?g.bundle?.icon??g.addons[0]?.manifest.icon:B.icon,color:H?g.addons[0]?.manifest.color:B.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:U}),!c&&l(Ze,{version:G,availableUpdate:u,...j===void 0?{}:{selectedVersion:j},isUpdating:f,installSource:K,disabled:v,...d&&j!==void 0?{onUpdate:()=>d(j)}:{},onOpenPicker:()=>k(e=>!e),children:ie&&l(Ke,{packageName:W,currentVersion:G,...K?{installSource:K}:{},...u!==void 0&&j!==void 0?{selectedVersion:j,onSelect:e=>{A(e),k(!1)}}:{},onInstall:e=>{k(!1),xe.mutate({packageName:W,version:e})},onClose:()=>k(!1)})})]}),a(`div`,{className:`flex flex-wrap items-center gap-x-1.5 gap-y-1 mt-0.5`,children:[W!==U&&l(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate max-w-full`,children:W}),H&&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(p,{className:`h-3 w-3`}),g.addons.length]}),y&&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:x(`addons.addonCard.systemPackageUpdatingRestartsThe`,`System package — updating restarts the hub`),children:[l(D,{className:`h-3 w-3`}),x(`addons.addonCard.system`,`System`)]}),_!=null&&l(Oe,{item:_}),m!=null&&l(Fe,{progress:m})]}),ye&&l(`p`,{className:`text-[10px] text-foreground-subtle mt-1 line-clamp-1`,children:ye}),!H&&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`?x(`addons.addonCard.forked`):x(`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`:e.process.state===`crashed`||e.process.state===`failed`?`bg-red-500/15 text-red-400`:`bg-gray-500/15 text-gray-400`}`,children:e.process.state})]})]})]}),!H&&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(),be.mutate({addonId:B.id})},disabled:be.isPending||v,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(D,{className:`h-3 w-3 ${be.isPending?`animate-spin`:``}`}),x(`addons.addonCard.restart`,`Restart`)]}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ue(e=>!e)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${M?`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(w,{className:`h-3 w-3`}),x(`addons.addonCard.logs`,`Logs`)]}),!H&&a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),de(!0)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${N?`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(T,{className:`h-3 w-3`}),x(`addons.addonCard.settings`,`Settings`)]}),l(`div`,{className:`flex-1`}),ge&&l(Ge,{packageName:B.packageName,displayName:B.name,selectedNode:b??$e,disabled:v})]}),i&&i.nodes.length>1&&!H&&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:x(`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:x(`addons.addonCard.outdated`)}),e.status===`offline`&&l(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground`,children:x(`common.offline`)}),e.synced&&e.status!==`offline`&&l(`span`,{className:`text-[9px] text-success`,children:x(`common.synced`)})]},e.nodeId))})]}),M&&!H&&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:()=>pe(`logs`),className:`px-2 py-0.5 transition-colors ${F===`logs`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:x(`addons.addonCard.logs`,`Logs`)}),l(`button`,{type:`button`,onClick:()=>pe(`events`),className:`px-2 py-0.5 border-l border-border transition-colors ${F===`events`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:x(`addons.addonCard.events`,`Events`)})]}),l(`div`,{className:`flex-1`}),l(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ue(!1)},className:`text-foreground-subtle hover:text-foreground`,children:l(S,{className:`h-3.5 w-3.5`})})]}),F===`logs`&&l(z,{addonId:B.id,maxHeight:`max-h-64`,showFilters:!1}),F===`events`&&l(Se,{addonId:B.id,category:`addon.*`,maxHeight:`max-h-64`})]}),H&&a(o,{children:[l(`button`,{type:`button`,onClick:()=>E(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(C?ee:ne,{className:`h-3.5 w-3.5 text-foreground-subtle`})}),C&&l(`div`,{className:`border-t border-border px-2.5 py-1.5 space-y-1.5`,children:g.addons.map(e=>l(et,{addon:e,agents:n,hideVersion:!0},e.manifest.id))})]}),N&&!H&&l(R,{open:!0,onOpenChange:e=>!e&&de(!1),children:a(ce,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[l(ae,{children:a(_e,{className:`flex items-center gap-2`,children:[l(T,{className:`h-4 w-4 text-primary`}),x(`addons.addonCard.settingsTitle`,{name:U})]})}),a(le,{className:`space-y-4`,children:[l(`div`,{className:`text-[10px] text-foreground-subtle mb-2`,children:x(`addons.addonCard.clusterWideSettingsOneValue`,`Cluster-wide settings — one value for every node. Per-node settings live under Cluster → the node → Settings.`)}),l(Q,{nodeId:null,addonIds:[B.id],level:`global`,fieldScope:`cluster`,emptyMessage:x(`addons.addonCard.thisAddonExposesNoCluster`,`This addon exposes no cluster-wide settings. Anything it can configure is per-node — open it from Cluster → the node → Settings.`)}),Je(B)&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:x(`addons.addonCard.deviceExport`,`Device export`)}),l(I,{addonId:B.id,onOpenDevice:e=>he(`/devices/${e}`)})]}),Ye(K)&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:x(`addons.addonCard.autoUpdate`,`Auto-Update`)}),l(Qe,{addonId:B.id})]}),B.components&&B.components.length>0&&a(`div`,{children:[l(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:x(`addons.addonCard.components`,{count:B.components.length})}),l(`div`,{className:`flex flex-wrap gap-1`,children:B.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:x(`addons.addonCard.installedOn`,`Installed on`)}),a(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[V.length===0&&l(`span`,{className:`text-[10px] text-foreground-subtle`,children:x(`addons.addonCard.hubLocal`,`Hub (local)`)}),V.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(),O(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:x(`addons.addonCard.installOnMoreAgents`,`Install on more agents`),children:[l(h,{className:`h-3 w-3`}),x(`addons.addonCard.addAgent`,`Add agent`)]}),te&&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&&!V.includes(e.name)).map(e=>l(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),O(!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&&!V.includes(e.name)).length===0&&l(`div`,{className:`px-3 py-1.5 text-[10px] text-foreground-subtle`,children:x(`addons.addonCard.noAvailableAgents`,`No available agents`)})]})]})]})]})]}),l(ve,{children:l(se,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>de(!1),children:x(`common.close`,`Close`)})})]})})]})}e();var tt=`.tgz,.tar.gz,.zip`;function nt({onUploadSuccess:e}){let{t}=Y(),[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(_(`/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:tt,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(v,{className:`w-3.5 h-3.5 animate-spin`}):l(g,{className:`w-3.5 h-3.5`}),n?t(`addons.addonUploadZone.uploading`,`Uploading...`):t(`addons.addonUploadZone.upload`,`Upload`)]})]})}var rt=new Set([`@camstack/system`,`@camstack/types`,`@camstack/sdk`,`@camstack/ui-library`,`@camstack/addon-agent-ui`]);function it(e,t){let n=new Map;for(let r of e){if(r.isHub||r.onHub||rt.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 at({selectedNode:e}){let{t}=Y(),{data:n}=F(He,{staleTime:Ue});if(n===void 0)return null;let r=it(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(m,{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(Ge,{packageName:t.packageName,displayName:t.packageName,selectedNode:e,hideNodeAction:e.isHub})]},t.packageName))]})}function ot({addon:e,installing:t,onInstall:n}){let{t:r}=Y();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(U,{variant:`success`,icon:l(y,{className:`h-3 w-3`}),children:e.installedVersion??r(`system.capabilityCatalog.installed`,`Installed`)}):a(se,{size:`sm`,onClick:()=>n(e.name),disabled:t,className:`shrink-0`,children:[t?l(v,{className:`h-3 w-3 animate-spin`}):l(d,{className:`h-3 w-3`}),r(`system.capabilityCatalog.install`,`Install`)]})]})}function st({capability:e,installing:t,onInstall:n}){let{t:r}=Y(),{data:i,isPending:o,isError:s}=ue({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(v,{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(ot,{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 ct(e){return e===`npm`||e===`dev`?e:null}var lt=`rounded-full border border-primary bg-primary/10 px-2 py-0.5 text-[10px] text-foreground`,ut=`rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-muted hover:bg-surface-hover`,dt=[{seconds:900,label:`15m`},{seconds:3600,label:`1h`},{seconds:21600,label:`6h`},{seconds:43200,label:`12h`},{seconds:86400,label:`24h`}],ft=new Set([`@camstack/system`,`@camstack/types`,`@camstack/sdk`,`@camstack/shm-ring`,`@camstack/ui-library`]);function pt(e){return e!==void 0&&ft.has(e)}var mt={id:`hub`,name:`Hub`,isHub:!0,isOnline:!0};function ht(e,t){let n=e??`hub-only`;return n===`any-node`?!0:n===`hub-only`?t:!t}function gt(e){return e===`local`?`dev`:`npm`}function _t(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`}: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 vt(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 yt({addons:e,clusterStatus:o,selectedNode:f,onRefresh:p,isRefreshing:m}){let{t:h}=Y(),g=s(),[_,y]=r(``),S=u(_),[C,w]=r(!1),ee=c(null);t(()=>{if(!C)return;let e=e=>{ee.current&&!ee.current.contains(e.target)&&w(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[C]);let{data:T}=oe({nodeId:f.id}),E=n(()=>{let e=new Map;for(let t of T??[])e.set(t.name,t.latestVersion);return e},[T]),te=n(()=>(T??[]).filter(e=>!e.isSystem).length,[T]),[ne,O]=r(()=>new Set),[re,ie]=r(()=>new Map),ae=i(e=>{O(t=>new Set(t).add(e))},[]),se=i(e=>{O(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),A=i((e,t)=>{ie(n=>new Map(n).set(e,t))},[]),ce=i(e=>{ie(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},[]),le=B({onMutate:e=>{ae(e.name),ce(e.name)},onSuccess:(e,t)=>{se(t.name);let n=e;if(n&&n.success===!1){A(t.name,n.error??`Update failed (no error message returned by server)`);return}g.invalidateQueries({queryKey:[[`addons`]]}),g.invalidateQueries({queryKey:[[`addons`,`listUpdates`]]})},onError:(e,t)=>{se(t.name),A(t.name,e instanceof Error?e.message:String(e))}}),M=Ne(),N=c(new Set);t(()=>{let e=new Set;for(let[t,n]of M)je(n)&&e.add(t);let t=[...N.current].some(t=>!e.has(t));N.current=e,t&&(g.invalidateQueries({queryKey:[[`addons`]]}),g.invalidateQueries({queryKey:[[`addons`,`listUpdates`]]}))},[M,g]);let{data:P}=L(void 0),F=be({onSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`,`getAutoUpdateSettings`]]})}}),fe=de({onSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`,`getAutoUpdateSettings`]]})}}),{data:I,isFetching:pe}=ue({query:S||void 0},{enabled:C}),R=J(),{data:z}=j(void 0),he=z?.requestedAt,[V,H]=r(null),[U,W]=r(!1);t(()=>{if(z?.kind===`framework-bulk-update`&&z.requestedAt!==V){H(z.requestedAt),W(!0);let e=window.setTimeout(()=>W(!1),6e3);return()=>window.clearTimeout(e)}},[he,V,z]),ge();let _e=i(async()=>{let e=(T??[]).filter(e=>!e.isSystem);if(e.length!==0){if(!f.isHub){for(let t of e)await le.mutateAsync({name:t.name,version:t.latestVersion,nodeId:f.id});return}await R.mutateAsync({kind:`update`,targets:e.map(e=>({name:e.name,version:e.latestVersion})),nodeIds:[f.id]})}},[T,f.id,f.isHub,R,le]),G=me({onSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`]]}),g.invalidateQueries({queryKey:[[`addonPages`]]}),g.invalidateQueries({queryKey:[[`capabilities`]]}),g.invalidateQueries({queryKey:[[`integrations`]]})}}),[ve,K]=r(`type`),[ye,xe]=r(()=>typeof window>`u`?`grouped`:window.localStorage.getItem(`camstack.addons.viewMode`)===`flat`?`flat`:`grouped`),Se=e=>{xe(e),typeof window<`u`&&window.localStorage.setItem(`camstack.addons.viewMode`,e)},[q,X]=Ce(),Z=q.get(`capability`),we=q.get(`updatable`)===`1`,Q=ct(q.get(`source`)),Te=i(e=>{let t=new URLSearchParams(q);e?t.set(`updatable`,`1`):t.delete(`updatable`),X(t,{replace:!0})},[q,X]),Ee=i(e=>{let t=new URLSearchParams(q);e===null?t.delete(`source`):t.set(`source`,e),X(t,{replace:!0})},[q,X]),De=n(()=>{let t=e.filter(e=>!pt(e.manifest.packageName));return f.isHub||(t=t.filter(e=>ht(e.placement,f.isHub))),Z&&(t=t.filter(e=>(e.manifest.capabilities??[]).some(e=>(typeof e==`string`?e:e.name)===Z))),we&&(t=t.filter(e=>{let t=e.manifest.packageName;return t!==void 0&&E.has(t)})),Q!==null&&(t=t.filter(e=>gt(e.installSource)===Q)),t},[e,f.isHub,Z,we,Q,E]),Oe=()=>{let e=new URLSearchParams(q);e.delete(`capability`),X(e,{replace:!0})},ke=ye===`flat`?De:vt(De),Ae=n(()=>{let e=[...ke];switch(ve){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},[ke,ve]);return a(`div`,{className:`space-y-3`,children:[[...re.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:h(`systemPage.addons.updateFailed`,{name:e})}),l(`div`,{className:`text-foreground-subtle font-mono`,children:t})]}),l(`button`,{type:`button`,onClick:()=>ce(e),className:`text-foreground-subtle hover:text-foreground text-[10px]`,children:h(`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:h(`admin.system.addons.sort`,`Sort:`)}),a(`select`,{value:ve,onChange:e=>K(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:h(`admin.system.addons.bundlesFirst`,`Bundles first`)}),l(`option`,{value:`name`,children:h(`admin.system.addons.name`,`Name`)}),l(`option`,{value:`source`,children:h(`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:h(`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:()=>Se(e),className:`px-2 py-1 transition-colors capitalize ${ye===e?`bg-primary/10 text-primary`:`bg-transparent text-foreground-subtle hover:bg-surface-hover`}`,title:e===`grouped`?h(`admin.system.addons.groupMultiAddonPackagesInto`,`Group multi-addon packages into a bundle card`):h(`admin.system.addons.showEveryAddonAsIts`,`Show every addon as its own card`),children:e},e))})]}),f.isHub&&a(`div`,{className:`flex items-center gap-1.5`,children:[l(D,{className:`h-3 w-3 text-foreground-subtle`}),l(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`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:()=>F.mutate({channel:e}),disabled:F.isPending,className:`px-2 py-1 transition-colors capitalize ${P?.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))})]}),f.isHub&&a(`div`,{className:`flex items-center gap-1.5`,children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`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:P?.updateCheckIntervalSeconds??21600,disabled:fe.isPending||P===void 0,onChange:e=>{P!==void 0&&fe.mutate({channel:P.channel,updateCheckIntervalSeconds:Number(e.target.value)})},children:dt.map(e=>l(`option`,{value:e.seconds,children:e.label},e.seconds))})]}),te>0&&a(`button`,{type:`button`,onClick:()=>void _e(),disabled:R.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:[R.isPending?l(v,{className:`w-3 h-3 animate-spin`}):l(d,{className:`w-3 h-3`}),R.isPending?h(`admin.system.addons.updating`,`Updating…`):h(`admin.system.addons.updateAll`,`Update All ({{nonSystemUpdateCount}})`,{nonSystemUpdateCount:te})]}),a(`button`,{type:`button`,onClick:p,disabled:m||R.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(D,{className:`w-3 h-3 ${m?`animate-spin`:``}`}),h(`common.refresh`,`Refresh`)]})]}),a(`div`,{className:`flex flex-wrap items-center gap-1.5`,role:`group`,"aria-label":h(`admin.system.addons.filterInstalledAddons`,`Filter installed addons`),children:[l(`span`,{className:`text-[10px] text-foreground-subtle`,children:h(`admin.system.addons.filter`,`Filter:`)}),[{id:`updatable`,label:h(`admin.system.addons.updatable`,`Updatable`),pressed:we,toggle:()=>Te(!we)},{id:`npm`,label:`npm`,pressed:Q===`npm`,toggle:()=>Ee(Q===`npm`?null:`npm`)},{id:`dev`,label:h(`admin.system.addons.dev`,`Dev`),pressed:Q===`dev`,toggle:()=>Ee(Q===`dev`?null:`dev`)}].map(e=>l(`button`,{type:`button`,"aria-pressed":e.pressed,onClick:e.toggle,className:e.pressed?lt:ut,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:ee,children:[l(k,{type:`text`,value:_,onChange:e=>{y(e.target.value),w(!0)},onFocus:()=>w(!0),placeholder:h(`admin.system.addons.searchAddonsOnNpm`,`Search addons on npm...`),"aria-label":h(`admin.system.addons.searchAddonsOnNpm2`,`Search addons on npm`),disabled:R.isPending,leftSlot:l(x,{className:`h-3.5 w-3.5`,"aria-hidden":!0}),rightSlot:pe?l(v,{className:`h-3 w-3 animate-spin`}):void 0}),C&&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:h(`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(ot,{addon:e,installing:G.isPending,onInstall:e=>G.mutate({packageName:e})},e.name))})]})]}),l(nt,{onUploadSuccess:()=>{g.invalidateQueries({queryKey:[[`addons`]]}),p()}})]}),Z&&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:h(`admin.system.addons.filteringByCapability`,`Filtering by capability:`)}),l(`span`,{className:`font-mono text-primary font-semibold`,children:Z}),l(`button`,{type:`button`,onClick:Oe,className:`ml-auto text-xs text-foreground-subtle hover:text-foreground underline`,children:h(`admin.system.addons.clear`,`Clear`)})]}),Z&&l(st,{capability:Z,installing:G.isPending,onInstall:e=>G.mutate({packageName:e})}),Z&&De.length>0&&l(`h2`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:h(`admin.system.addons.installed`,`Installed`)}),U&&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(b,{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:h(`admin.system.addons.bulkUpdateCompleted`,`Bulk update completed`)}),l(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:h(`admin.system.addons.systemPackagesUpdatedHubRestarted`,`System packages updated — hub restarted successfully.`)})]})]}),De.length===0&&l(`div`,{className:`text-xs text-foreground-subtle`,children:e.length===0?h(`admin.system.addons.noAddonsInstalled`,`No addons installed`):Z?h(`admin.system.addons.noInstalledAddonDeclaresThe`,`No installed addon declares the "{{capabilityFilter}}" capability. Any addon you can install appears under "Available to install" above.`,{capabilityFilter:Z}):h(`admin.system.addons.noAddonsCompatibleWithPlacement`,`No addons compatible with {{name}} (placement filter active)`,{name:f.name})}),l(`div`,{className:`space-y-1.5`,children:Ae.map(e=>{let t=$(e)?e.bundle.packageName:e.manifest.packageName,n=E.get(t),r=$(e)?e.representative:e,i=n?e=>le.mutate({name:t,version:e,nodeId:f.id}):void 0,a=M.get(t)??null,s=a!==null&&je(a);return l(et,{addon:r,clusterStatus:o?.[r.manifest.id],bundle:$(e)?e.bundle:void 0,availableUpdate:n,isUpdating:ne.has(t)||s,jobProgress:a,onUpdate:i,disabledByBulk:R.isPending,selectedNode:f},$(e)?t:e.manifest.id)})})]})}function bt(){let{t:e}=Y(),n=s(),{data:r}=pe(void 0),{nodes:i}=ye(),{selection:o,selectNode:u,requestedNodeId:d}=Ee(i.length>0?i:[mt]),f=o.node??mt,p=f.id,m=i.length>0?o.staleNodeId:null,{data:h,isLoading:g,isError:_}=M({nodeId:p}),v=W(),y=G(),b=v.isPending||y.isPending,x=async()=>{await v.mutateAsync({nodeId:p}),await y.mutateAsync(),n.invalidateQueries({queryKey:[[`addons`]]})},S=c(v);S.current=v;let C=c(d??`hub`);t(()=>{S.current.mutate({nodeId:C.current})},[]);let w=(h??[]).map(_t).filter(e=>e!==null);return a(we,{children:[a(`div`,{className:`flex items-center justify-between gap-2 flex-wrap`,children:[l(he,{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:w.length})}),a(`button`,{type:`button`,onClick:()=>void x(),disabled:b,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(D,{className:`w-3 h-3 ${b?`animate-spin`:``}`}),e(`admin.system.addons.checkForUpdates`,`Check for updates`)]})]})]}),l(Te,{staleNodeId:m,shownNodeName:f.name}),l(at,{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(yt,{addons:w,clusterStatus:r,selectedNode:f,onRefresh:()=>void x(),isRefreshing:b})]})}export{bt 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{H as n}from"./src-CoNs4bys.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{H as n}from"./src-CE3hNyCx.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{B as r}from"./src-CoNs4bys.js";import{et as i}from"./index-IBVizVRk.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{B as r}from"./src-CE3hNyCx.js";import{et as i}from"./index-mBJW996X.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,3 +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{D as d,Dn as f,G as p,Hr as m,It as h,Jr as g,Jt as _,Oi as v,On as y,Pn as b,Q as x,Tr as S,Xt as C,Zr as w,ar as T,dn as E,dt as D,kr as ee,ot as O,un as k,wi as A}from"./player-overlays-CTjp5_0E.js";import{t as te}from"./message-square-plus-DD_p-LBd.js";import{t as j}from"./send-CWuZ-VHG.js";import{Wn as M}from"./client-Ck3kx2Z0.js";import{$l as N,Bn as P,Jl as F,L as ne,Ln as I,Pn as L,U as re,Ut as R,Vt as z,Wt as B,ar as V,bn as H,ha as U,in as W,z as G}from"./src-CoNs4bys.js";import{t as K}from"./i18n-DWijAvai.js";import{t as q}from"./useTranslation-D3Is_4B6.js";import"./mount-DUsOqTKW.js";import{C as J}from"./index-IBVizVRk.js";import{t as ie}from"./AdminSectionedPage-DKH0UpKh.js";import{t as ae}from"./AdminPage-DMiMIHwu.js";e();var oe=[`llm`,`listProfiles`],se=[`llm`,`listProfileKinds`],ce=[`llm`,`getDefaults`],Y=[`llm`,`listRuntimeNodes`],le=[`llm`,`listModelCatalog`],ue=[`llm`,`getUsage`],de=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],fe=new Map(Object.entries({openai:w,anthropic:w,google:w,"openai-compatible":f,"managed-local":g,"apple-foundation":g}));function pe(e){return fe.get(e)??null}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Q(e){return e===!0}function me(e){return{model:e.model,baseUrl:e.baseUrl,apiKey:e.apiKey,supportsVision:e.supportsVision,temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled,contextSize:e.runtime?.contextSize,gpuLayers:e.runtime?.gpuLayers,threads:e.runtime?.threads,parallel:e.runtime?.parallel,idleStopMinutes:e.runtime?.idleStopMinutes,batchSize:e.runtime?.batchSize,ubatchSize:e.runtime?.ubatchSize,flashAttention:e.runtime?.flashAttention,mlock:e.runtime?.mlock,noMmap:e.runtime?.noMmap,cacheTypeK:e.runtime?.cacheTypeK,cacheTypeV:e.runtime?.cacheTypeV,extraArgs:ve(e.runtime?.extraArgs??[])}}var he=[`f32`,`f16`,`q8_0`,`q5_1`,`q5_0`,`q4_1`,`q4_0`];function ge(e){return typeof e==`string`&&he.includes(e)?e:void 0}function _e(e){let t=[],n=``,r=null;for(let i of e){if(r!==null){i===r?r=null:n+=i;continue}if(i===`"`||i===`'`){r=i;continue}if(/\s/.test(i)){n!==``&&t.push(n),n=``;continue}n+=i}return n!==``&&t.push(n),t}function ve(e){return e.map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)}var ye=[`--jinja`,`--cont-batching`];function be(e,t,n){let r=Z(e.threads),i=Z(e.batchSize),a=Z(e.ubatchSize),o=ge(e.cacheTypeK),s=ge(e.cacheTypeV);return{nodeId:t,engine:`llama-cpp`,model:n,extraArgs:[..._e(X(e.extraArgs)??``)],contextSize:Z(e.contextSize)??4096,gpuLayers:Z(e.gpuLayers)??0,...r===void 0?{}:{threads:r},parallel:Z(e.parallel)??1,...i===void 0?{}:{batchSize:i},...a===void 0?{}:{ubatchSize:a},flashAttention:Q(e.flashAttention),mlock:Q(e.mlock),noMmap:Q(e.noMmap),...o===void 0?{}:{cacheTypeK:o},...s===void 0?{}:{cacheTypeV:s},autoStart:Q(e.autoStart),idleStopMinutes:Z(e.idleStopMinutes)??30}}function xe(e,t,n,r,i){let a={id:n?.id??crypto.randomUUID(),name:t,kind:e,addonId:`ai`,enabled:n?.enabled??!0,model:X(r.model)??n?.model??``,supportsVision:i?.supportsVision??Q(r.supportsVision),timeoutMs:Z(r.timeoutMs)??M.totalMs,connectTimeoutMs:Z(r.connectTimeoutMs)??M.connectMs,firstTokenTimeoutMs:Z(r.firstTokenTimeoutMs)??M.firstTokenMs,idleTimeoutMs:Z(r.idleTimeoutMs)??M.idleMs,retry:{enabled:Q(r.retryEnabled),maxAttempts:Z(r.retryMaxAttempts)??1},toolsEnabled:Q(r.toolsEnabled)},o=X(r.baseUrl),s=X(r.apiKey),c=Z(r.temperature),l=Z(r.topP),u=Z(r.topK),d=Z(r.maxTokens),f=Z(r.contextLength),p=X(r.systemPrompt);return{...a,...o===void 0?{}:{baseUrl:o},...s===void 0?{}:{apiKey:s},...c===void 0?{}:{temperature:c},...l===void 0?{}:{topP:l},...u===void 0?{}:{topK:u},...d===void 0?{}:{maxTokens:d},...f===void 0?{}:{contextLength:f},...p===void 0?{}:{systemPrompt:p},...i===void 0?{}:{model:i.modelId,runtime:be(r,i.nodeId,i.model)}}}function Se(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Ce=`apple-system`;function we(e,t,n,r){return{...xe(`apple-foundation`,e,t,n),model:Ce,supportsVision:!1,appleFoundation:{nodeId:r}}}var Te={deviceNotEligible:{key:`ai.appleNotEligible`,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 Ee(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:K.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:K.t(`ai.appleAvailable`),detail:K.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Te[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:K.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:K.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var De=2e3;function $(e){return K.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function Oe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function ke({nodeId:e,value:t,onChange:i}){let{t:s}=q(),c=O(),[d,f]=r(``),[p,h]=r(null),[g,_]=r(!1),v=o({queryKey:le,queryFn:()=>c.trpcClient.llm.listModelCatalog.query({})}),y=o({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>c.trpcClient.llm.listNodeModels.query({nodeId:e})}),b=l({mutationFn:e=>c.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),_(!1),e.ok&&i({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),x=l({mutationFn:t=>c.trpcClient.llm.installModel.mutate({nodeId:e,model:t}),onSuccess:()=>{_(!0),y.refetch()}}),S=o({queryKey:Y,enabled:x.isPending,refetchInterval:x.isPending?De:!1,queryFn:()=>c.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,C=n(()=>{let t=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(y.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(t=>({value:`node:${t.file}`,label: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]},[v.data,y.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=v.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=y.data?.find(e=>e.file===t);n?.path!==void 0&&i({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},D=e=>{d.trim()!==``&&b.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return a(`div`,{className:`space-y-2`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-model`,children:s(`ai.model`,`Model`)}),u(F,{id:`ai-model`,value:Oe(t),options:C,onChange:e=>w(e.target.value)})]}),a(`div`,{className:`rounded-md border border-border bg-surface-subtle px-3 py-2.5`,children:[u(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:s(`ai.hfTitle`,`Add a model from Hugging Face`)}),u(`p`,{className:`mb-2 text-[10px] leading-relaxed text-foreground-subtle`,children: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.`)}),a(`div`,{className:`flex gap-2`,children:[u(N,{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(),D())}}),a(P,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||b.isPending,onClick:()=>D(),children:[b.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(E,{className:`h-3.5 w-3.5`}),s(`ai.hfCheck`,`Check`)]})]}),b.isError&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:b.error instanceof Error?b.error.message:s(`common.error`,`Error`)}),p?.ok===!1&&a(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-2.5 py-2`,children:[u(`p`,{className:`text-[11px] text-danger`,children:p.message}),p.candidates!==void 0&&p.candidates.length>0&&u(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:p.candidates.map(e=>u(`button`,{type:`button`,className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:border-primary/50`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),b.mutate({ref:t})},children:e},e))}),p.requiredBytes!==void 0&&u(P,{size:`sm`,variant:`secondary`,type:`button`,className:`mt-2`,onClick:()=>D(p.requiredBytes),children:s(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]}),p?.ok===!0&&a(`div`,{className:`mt-2 rounded-md border border-border bg-surface px-2.5 py-2`,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(V,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),u(V,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),a(`div`,{className:`mt-2 flex items-center gap-2`,children:[a(P,{size:`sm`,type:`button`,disabled:x.isPending||g,onClick:()=>x.mutate(p.model),children:[x.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(m,{className:`h-3.5 w-3.5`}),g?s(`ai.hfInstalled`,`Downloaded`):s(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),S!==void 0&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:S.phase===`verifying`?s(`ai.hfVerifying`,`verifying {{file}}…`,{file:S.file}):s(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:S.file,index:S.fileIndex,count:S.fileCount,done:$(S.downloadedBytes),total:S.totalBytes===void 0?``:` / ${$(S.totalBytes)}`})})]}),x.isError&&u(`p`,{className:`mt-1.5 text-[11px] text-danger`,children:x.error instanceof Error?x.error.message:s(`common.error`,`Error`)})]})]})]})}function Ae({value:e,onChange:t}){let{t:n}=q(),r=O(),i=o({queryKey:Y,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(T,{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=Ee(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(V,{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.`)})]})}e();function je({kind:e,className:t}){let n=pe(e.kind);return n===null?u(`span`,{className:t,children:e.icon}):u(n,{className:t})}function Me({kinds:e,onPick:t,onCancel:r}){let{t:i}=q(),o=n(()=>Se(e),[e]);return u(G,{open:!0,onClose:r,title:i(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:a(`div`,{className:`space-y-4`,children:[o.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:i(`ai.noKinds`,`No AI provider is installed.`)}),o.map(e=>a(`div`,{children:[u(`div`,{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e.addonId}),u(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.kinds.map(n=>a(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs transition-colors hover:border-primary/50 hover:bg-surface-hover`,children:[u(je,{kind:n,className:`h-5 w-5 text-foreground-subtle`}),u(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})})}function Ne({kind:e,existing:t,onSave:i,onCancel:o,saving:c,error:l}){let{t:d}=q(),f=e.kind===`managed-local`,p=e.kind===`apple-foundation`,[m,h]=r(t?.appleFoundation?.nodeId??null),[g,_]=r(t?.name??e.label),[v,y]=r(()=>t===null?{}:me(t)),[b,x]=r(t?.runtime?.nodeId??`hub`),[S,C]=r(()=>t?.runtime===void 0?null:{model:t.runtime.model,modelId:t.model,supportsVision:t.supportsVision}),w=n(()=>_e(X(v.extraArgs)??``),[v.extraArgs]),E=()=>{if(p){if(m===null)return;i(we(g,t,v,m));return}if(!f){i(xe(e.kind,g,t,v));return}S!==null&&i(xe(e.kind,g,t,v,{nodeId:b,model:S.model,modelId:S.modelId,supportsVision:S.supportsVision}))},D=c||g.trim()===``||f&&S===null||p&&m===null;return u(G,{open:!0,onClose:o,title:t===null?d(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):d(`ai.editProfile`,`Edit {{name}}`,{name:t.name}),error:l,width:`lg`,testId:`ai-profile-editor`,footer:a(s,{children:[f&&S===null&&u(V,{variant:`warning`,children:d(`ai.pickModelFirst`,`pick a model`)}),p&&m===null&&u(V,{variant:`warning`,children:d(`ai.pickAppleNodeFirst`,`pick a Mac`)}),a(P,{size:`sm`,type:`button`,disabled:D,onClick:E,children:[c&&u(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`ai.createProfile`,`Create profile`):d(`ai.saveChanges`,`Save changes`)]})]}),children:a(`div`,{className:`space-y-3`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-profile-name`,children:d(`ai.name`,`Name`)}),u(N,{id:`ai-profile-name`,value:g,onChange:e=>_(e.target.value),placeholder:e.label})]}),f&&a(s,{children:[u(re,{selectedNodeId:b,onSelect:x,label:d(`ai.runtimeNode`,`Runtime node`),alwaysShow:!0}),u(ke,{nodeId:b,value:S,onChange:C}),a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-extra-args`,children:d(`ai.extraArgs`,`Additional llama-server arguments`)}),u(N,{id:`ai-extra-args`,value:X(v.extraArgs)??``,onChange:e=>y({...v,extraArgs:e.target.value}),placeholder:ye.join(` `)}),w.length>0&&u(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:w.map((e,t)=>u(V,{variant:`default`,children:e},`${e}-${String(t)}`))}),u(`p`,{className:`mt-1 text-[10px] leading-relaxed text-foreground-subtle`,children:d(`ai.extraArgsHint`,`Flags this form does not already own. Vision models generally need --jinja; some language-only models do not like it. Context size, GPU layers, parallel slots, flash attention and the KV-cache types are set in the fields below — repeating one here is rejected at start.`)})]})]}),p&&u(Ae,{value:m,onChange:h}),u(H,{schema:e.configSchema,values:v,onChange:y}),t!==null&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)})]})})}e();function Pe(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(je,{kind:n,className:`h-4 w-4 text-foreground-subtle`})}),a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block truncate text-sm font-medium text-foreground`,children:t.name}),e.testResult?.id===t.id&&u(`span`,{className:`block truncate text-[10px] ${e.testResult.ok?`text-success`:`text-danger`}`,children:e.testResult.text})]})]})}},{key:`kind`,header:e.t(`ai.colKind`,`Kind`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByName.get(t.kind)?.label??t.kind})},{key:`model`,header:e.t(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.model})},{key:`vision`,header:e.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:t=>t.supportsVision?u(V,{variant:`info`,style:`outline`,children:e.t(`ai.vision`,`vision`)}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})},{key:`node`,header:e.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>e.runtime===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(V,{variant:`default`,children:e.runtime.nodeId})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>u(W,{checked:t.enabled,onCheckedChange:()=>e.onToggle(t),"aria-label":K.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(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(j,{className:`h-3.5 w-3.5`})}),u(P,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),title:e.t(`common.edit`,`Edit`),children:u(b,{className:`h-3.5 w-3.5`})}),u(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:e.t(`common.delete`,`Delete`),children:u(h,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Fe(){let{t:e}=q(),s=O(),{state:c,openNew:d,openEdit:f,close:p}=ne(),[m,h]=r(null),[g,_]=r(null),[v,b]=r(null),x=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),S=o({queryKey:se,queryFn:async()=>(await s.trpcClient.llm.listProfileKinds.query({})).map(e=>({...e,configSchema:e.configSchema}))}),w=()=>{x.refetch()},E=i(()=>{h(null),b(null),p()},[p]);t(()=>{c.mode===`closed`&&h(null)},[c.mode]);let D=l({mutationFn:e=>s.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{E(),w()},onError:t=>b(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}),k=l({mutationFn:e=>s.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>_({id:t.id,ok:e.ok,text:e.ok?K.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),A=x.data??[],te=n(()=>S.data??[],[S.data]),j=n(()=>{let e=new Map;for(let t of te)e.set(t.kind,t);return e},[te]),M=c.mode===`edit`?A.find(e=>e.id===c.id)??null:null,N=M===null?null:j.get(M.kind)??null,F=c.mode===`new`&&m===null,L=c.mode===`new`?m:N,re=c.mode===`edit`?M:null,B=L!==null&&(c.mode===`new`||re!==null);return a(ae,{embedded:!0,icon:C,title:e(`ai.profilesTitle`,`AI profiles`),subtitle:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),children:[u(`div`,{className:`flex justify-end`,children:a(P,{size:`sm`,type:`button`,onClick:()=>{b(null),h(null),d()},children:[u(y,{className:`h-3.5 w-3.5`}),e(`ai.addProfile`,`Add profile`)]})}),x.isError&&u(I,{title:e(`ai.loadFailed`,`Failed to load profiles`),message:x.error instanceof Error?x.error.message:e(`common.error`,`Error`),onRetry:()=>void x.refetch()}),u(Ie,{profiles:A}),x.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(T,{className:`h-6 w-6 animate-spin text-primary`})}),!x.isLoading&&A.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}),A.length>0&&u(z,{headingId:`ai-profiles-list`,title:e(`ai.profilesList`,`Profiles`),children:u(R,{columns:Pe({kindByName:j,testResult:g,testingId:k.isPending?k.variables?.id??null:null,t:e,onToggle:e=>D.mutate({...e,enabled:!e.enabled,apiKey:`__redacted__`}),onTest:e=>k.mutate(e),onEdit:e=>{j.has(e.kind)&&(b(null),h(null),f(e.id))},onDelete:e=>ee.mutate(e)}),rows:A,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:`max-h-[60vh]`})}),F&&u(Me,{kinds:te,onCancel:E,onPick:e=>{b(null),h(e)}}),B&&L!==null&&u(Ne,{kind:L,existing:re,saving:D.isPending,error:v,onSave:e=>D.mutate(e),onCancel:E})]})}function Ie({profiles:e}){let{t}=q(),n=O(),r=o({queryKey:ce,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(z,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:u(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:de.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(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`llm-default-${n}`,children:c(n)}),u(F,{id:`llm-default-${n}`,"aria-label":c(n),className:`h-7 text-xs`,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-[10px] 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-[10px] 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-[10px] text-danger`,children:String(i.error)})]},n)})})})}e();var Le=5e3;function Re(e){return K.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ze(){let{t:e}=q(),t=O(),r=o({queryKey:Y,refetchInterval:Le,queryFn:()=>t.trpcClient.llm.listRuntimeNodes.query({})}),i=n(()=>[{key:`node`,header:e(`ai.colNode`,`Node`),render:e=>u(`span`,{className:`text-sm 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(V,{variant:t.reachable?`success`:`danger`,children:t.reachable?t.status?.state??e(`ai.ready`,`ready`):e(`ai.unreachable`,`unreachable`)}),t.status?.downloadProgress!==void 0&&u(V,{variant:`info`,children:`${String(Math.round(t.status.downloadProgress*100))}%`})]})},{key:`model`,header:e(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:e(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.disk===void 0?`—`:Re(e.disk.modelsBytes)})},{key:`apple`,header:e(`ai.colApple`,`Apple on-device`),render:t=>{let n=Ee(t);return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[u(V,{variant:n.tone,children:e(n.labelKey,n.labelDefault)}),n.detail!==null&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n.detail})]})}},{key:`error`,header:e(`ai.colError`,`Error`),render:e=>e.error===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(`span`,{className:`text-[11px] text-danger`,children:e.error})}],[e]),s=r.data??[];return a(ae,{embedded:!0,icon:k,title:e(`ai.runtimesTitle`,`Managed runtimes`),subtitle:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),children:[r.isError&&u(I,{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(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):u(z,{headingId:`ai-runtimes-list`,title:e(`ai.runtimesList`,`Nodes`),children:u(R,{columns:i,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:B})})]})}var Be=x(`/addon/ai/test-chat`),Ve=x(`/addon/ai/test-chat/chats`),He=6e5;function Ue(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),He)}function We(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e){if(!We(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Ke=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function qe(e){let t;try{t=JSON.parse(e)}catch{return null}if(!We(t))return null;switch(t.kind){case`status`:{let e=Ke.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Ge(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:K.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*Je(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
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{D as d,Dn as f,G as p,Hr as m,It as h,Jr as g,Jt as _,Oi as v,On as y,Pn as b,Q as x,Tr as S,Xt as C,Zr as w,ar as T,dn as E,dt as D,kr as ee,ot as O,un as k,wi as A}from"./player-overlays-DFTWiQ8-.js";import{t as te}from"./message-square-plus-B_0WwbBk.js";import{t as j}from"./send-BNY2bJqA.js";import{Wn as M}from"./client-CqsEJzhO.js";import{$l as N,Bn as P,Jl as F,L as ne,Ln as I,Pn as L,U as re,Ut as R,Vt as z,Wt as B,ar as V,bn as H,ha as U,in as W,z as G}from"./src-CE3hNyCx.js";import{t as K}from"./i18n-B-IeyHf7.js";import{t as q}from"./useTranslation-D3Is_4B6.js";import"./mount-JBC8n4FU.js";import{C as J}from"./index-mBJW996X.js";import{t as ie}from"./AdminSectionedPage-Bb00eMTj.js";import{t as ae}from"./AdminPage-BFQa1eDk.js";e();var oe=[`llm`,`listProfiles`],se=[`llm`,`listProfileKinds`],ce=[`llm`,`getDefaults`],Y=[`llm`,`listRuntimeNodes`],le=[`llm`,`listModelCatalog`],ue=[`llm`,`getUsage`],de=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],fe=new Map(Object.entries({openai:w,anthropic:w,google:w,"openai-compatible":f,"managed-local":g,"apple-foundation":g}));function pe(e){return fe.get(e)??null}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Q(e){return e===!0}function me(e){return{model:e.model,baseUrl:e.baseUrl,apiKey:e.apiKey,supportsVision:e.supportsVision,temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled,contextSize:e.runtime?.contextSize,gpuLayers:e.runtime?.gpuLayers,threads:e.runtime?.threads,parallel:e.runtime?.parallel,idleStopMinutes:e.runtime?.idleStopMinutes,batchSize:e.runtime?.batchSize,ubatchSize:e.runtime?.ubatchSize,flashAttention:e.runtime?.flashAttention,mlock:e.runtime?.mlock,noMmap:e.runtime?.noMmap,cacheTypeK:e.runtime?.cacheTypeK,cacheTypeV:e.runtime?.cacheTypeV,extraArgs:ve(e.runtime?.extraArgs??[])}}var he=[`f32`,`f16`,`q8_0`,`q5_1`,`q5_0`,`q4_1`,`q4_0`];function ge(e){return typeof e==`string`&&he.includes(e)?e:void 0}function _e(e){let t=[],n=``,r=null;for(let i of e){if(r!==null){i===r?r=null:n+=i;continue}if(i===`"`||i===`'`){r=i;continue}if(/\s/.test(i)){n!==``&&t.push(n),n=``;continue}n+=i}return n!==``&&t.push(n),t}function ve(e){return e.map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)}var ye=[`--jinja`,`--cont-batching`];function be(e,t,n){let r=Z(e.threads),i=Z(e.batchSize),a=Z(e.ubatchSize),o=ge(e.cacheTypeK),s=ge(e.cacheTypeV);return{nodeId:t,engine:`llama-cpp`,model:n,extraArgs:[..._e(X(e.extraArgs)??``)],contextSize:Z(e.contextSize)??4096,gpuLayers:Z(e.gpuLayers)??0,...r===void 0?{}:{threads:r},parallel:Z(e.parallel)??1,...i===void 0?{}:{batchSize:i},...a===void 0?{}:{ubatchSize:a},flashAttention:Q(e.flashAttention),mlock:Q(e.mlock),noMmap:Q(e.noMmap),...o===void 0?{}:{cacheTypeK:o},...s===void 0?{}:{cacheTypeV:s},autoStart:Q(e.autoStart),idleStopMinutes:Z(e.idleStopMinutes)??30}}function xe(e,t,n,r,i){let a={id:n?.id??crypto.randomUUID(),name:t,kind:e,addonId:`ai`,enabled:n?.enabled??!0,model:X(r.model)??n?.model??``,supportsVision:i?.supportsVision??Q(r.supportsVision),timeoutMs:Z(r.timeoutMs)??M.totalMs,connectTimeoutMs:Z(r.connectTimeoutMs)??M.connectMs,firstTokenTimeoutMs:Z(r.firstTokenTimeoutMs)??M.firstTokenMs,idleTimeoutMs:Z(r.idleTimeoutMs)??M.idleMs,retry:{enabled:Q(r.retryEnabled),maxAttempts:Z(r.retryMaxAttempts)??1},toolsEnabled:Q(r.toolsEnabled)},o=X(r.baseUrl),s=X(r.apiKey),c=Z(r.temperature),l=Z(r.topP),u=Z(r.topK),d=Z(r.maxTokens),f=Z(r.contextLength),p=X(r.systemPrompt);return{...a,...o===void 0?{}:{baseUrl:o},...s===void 0?{}:{apiKey:s},...c===void 0?{}:{temperature:c},...l===void 0?{}:{topP:l},...u===void 0?{}:{topK:u},...d===void 0?{}:{maxTokens:d},...f===void 0?{}:{contextLength:f},...p===void 0?{}:{systemPrompt:p},...i===void 0?{}:{model:i.modelId,runtime:be(r,i.nodeId,i.model)}}}function Se(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Ce=`apple-system`;function we(e,t,n,r){return{...xe(`apple-foundation`,e,t,n),model:Ce,supportsVision:!1,appleFoundation:{nodeId:r}}}var Te={deviceNotEligible:{key:`ai.appleNotEligible`,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 Ee(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:K.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:K.t(`ai.appleAvailable`),detail:K.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Te[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:K.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:K.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var De=2e3;function $(e){return K.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function Oe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function ke({nodeId:e,value:t,onChange:i}){let{t:s}=q(),c=O(),[d,f]=r(``),[p,h]=r(null),[g,_]=r(!1),v=o({queryKey:le,queryFn:()=>c.trpcClient.llm.listModelCatalog.query({})}),y=o({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>c.trpcClient.llm.listNodeModels.query({nodeId:e})}),b=l({mutationFn:e=>c.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),_(!1),e.ok&&i({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),x=l({mutationFn:t=>c.trpcClient.llm.installModel.mutate({nodeId:e,model:t}),onSuccess:()=>{_(!0),y.refetch()}}),S=o({queryKey:Y,enabled:x.isPending,refetchInterval:x.isPending?De:!1,queryFn:()=>c.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,C=n(()=>{let t=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(y.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(t=>({value:`node:${t.file}`,label: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]},[v.data,y.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=v.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=y.data?.find(e=>e.file===t);n?.path!==void 0&&i({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},D=e=>{d.trim()!==``&&b.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return a(`div`,{className:`space-y-2`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-model`,children:s(`ai.model`,`Model`)}),u(F,{id:`ai-model`,value:Oe(t),options:C,onChange:e=>w(e.target.value)})]}),a(`div`,{className:`rounded-md border border-border bg-surface-subtle px-3 py-2.5`,children:[u(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:s(`ai.hfTitle`,`Add a model from Hugging Face`)}),u(`p`,{className:`mb-2 text-[10px] leading-relaxed text-foreground-subtle`,children: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.`)}),a(`div`,{className:`flex gap-2`,children:[u(N,{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(),D())}}),a(P,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||b.isPending,onClick:()=>D(),children:[b.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(E,{className:`h-3.5 w-3.5`}),s(`ai.hfCheck`,`Check`)]})]}),b.isError&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:b.error instanceof Error?b.error.message:s(`common.error`,`Error`)}),p?.ok===!1&&a(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-2.5 py-2`,children:[u(`p`,{className:`text-[11px] text-danger`,children:p.message}),p.candidates!==void 0&&p.candidates.length>0&&u(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:p.candidates.map(e=>u(`button`,{type:`button`,className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:border-primary/50`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),b.mutate({ref:t})},children:e},e))}),p.requiredBytes!==void 0&&u(P,{size:`sm`,variant:`secondary`,type:`button`,className:`mt-2`,onClick:()=>D(p.requiredBytes),children:s(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]}),p?.ok===!0&&a(`div`,{className:`mt-2 rounded-md border border-border bg-surface px-2.5 py-2`,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(V,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),u(V,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),a(`div`,{className:`mt-2 flex items-center gap-2`,children:[a(P,{size:`sm`,type:`button`,disabled:x.isPending||g,onClick:()=>x.mutate(p.model),children:[x.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(m,{className:`h-3.5 w-3.5`}),g?s(`ai.hfInstalled`,`Downloaded`):s(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),S!==void 0&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:S.phase===`verifying`?s(`ai.hfVerifying`,`verifying {{file}}…`,{file:S.file}):s(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:S.file,index:S.fileIndex,count:S.fileCount,done:$(S.downloadedBytes),total:S.totalBytes===void 0?``:` / ${$(S.totalBytes)}`})})]}),x.isError&&u(`p`,{className:`mt-1.5 text-[11px] text-danger`,children:x.error instanceof Error?x.error.message:s(`common.error`,`Error`)})]})]})]})}function Ae({value:e,onChange:t}){let{t:n}=q(),r=O(),i=o({queryKey:Y,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(T,{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=Ee(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(V,{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.`)})]})}e();function je({kind:e,className:t}){let n=pe(e.kind);return n===null?u(`span`,{className:t,children:e.icon}):u(n,{className:t})}function Me({kinds:e,onPick:t,onCancel:r}){let{t:i}=q(),o=n(()=>Se(e),[e]);return u(G,{open:!0,onClose:r,title:i(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:a(`div`,{className:`space-y-4`,children:[o.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:i(`ai.noKinds`,`No AI provider is installed.`)}),o.map(e=>a(`div`,{children:[u(`div`,{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e.addonId}),u(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.kinds.map(n=>a(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs transition-colors hover:border-primary/50 hover:bg-surface-hover`,children:[u(je,{kind:n,className:`h-5 w-5 text-foreground-subtle`}),u(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})})}function Ne({kind:e,existing:t,onSave:i,onCancel:o,saving:c,error:l}){let{t:d}=q(),f=e.kind===`managed-local`,p=e.kind===`apple-foundation`,[m,h]=r(t?.appleFoundation?.nodeId??null),[g,_]=r(t?.name??e.label),[v,y]=r(()=>t===null?{}:me(t)),[b,x]=r(t?.runtime?.nodeId??`hub`),[S,C]=r(()=>t?.runtime===void 0?null:{model:t.runtime.model,modelId:t.model,supportsVision:t.supportsVision}),w=n(()=>_e(X(v.extraArgs)??``),[v.extraArgs]),E=()=>{if(p){if(m===null)return;i(we(g,t,v,m));return}if(!f){i(xe(e.kind,g,t,v));return}S!==null&&i(xe(e.kind,g,t,v,{nodeId:b,model:S.model,modelId:S.modelId,supportsVision:S.supportsVision}))},D=c||g.trim()===``||f&&S===null||p&&m===null;return u(G,{open:!0,onClose:o,title:t===null?d(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):d(`ai.editProfile`,`Edit {{name}}`,{name:t.name}),error:l,width:`lg`,testId:`ai-profile-editor`,footer:a(s,{children:[f&&S===null&&u(V,{variant:`warning`,children:d(`ai.pickModelFirst`,`pick a model`)}),p&&m===null&&u(V,{variant:`warning`,children:d(`ai.pickAppleNodeFirst`,`pick a Mac`)}),a(P,{size:`sm`,type:`button`,disabled:D,onClick:E,children:[c&&u(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`ai.createProfile`,`Create profile`):d(`ai.saveChanges`,`Save changes`)]})]}),children:a(`div`,{className:`space-y-3`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-profile-name`,children:d(`ai.name`,`Name`)}),u(N,{id:`ai-profile-name`,value:g,onChange:e=>_(e.target.value),placeholder:e.label})]}),f&&a(s,{children:[u(re,{selectedNodeId:b,onSelect:x,label:d(`ai.runtimeNode`,`Runtime node`),alwaysShow:!0}),u(ke,{nodeId:b,value:S,onChange:C}),a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-extra-args`,children:d(`ai.extraArgs`,`Additional llama-server arguments`)}),u(N,{id:`ai-extra-args`,value:X(v.extraArgs)??``,onChange:e=>y({...v,extraArgs:e.target.value}),placeholder:ye.join(` `)}),w.length>0&&u(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:w.map((e,t)=>u(V,{variant:`default`,children:e},`${e}-${String(t)}`))}),u(`p`,{className:`mt-1 text-[10px] leading-relaxed text-foreground-subtle`,children:d(`ai.extraArgsHint`,`Flags this form does not already own. Vision models generally need --jinja; some language-only models do not like it. Context size, GPU layers, parallel slots, flash attention and the KV-cache types are set in the fields below — repeating one here is rejected at start.`)})]})]}),p&&u(Ae,{value:m,onChange:h}),u(H,{schema:e.configSchema,values:v,onChange:y}),t!==null&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)})]})})}e();function Pe(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(je,{kind:n,className:`h-4 w-4 text-foreground-subtle`})}),a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block truncate text-sm font-medium text-foreground`,children:t.name}),e.testResult?.id===t.id&&u(`span`,{className:`block truncate text-[10px] ${e.testResult.ok?`text-success`:`text-danger`}`,children:e.testResult.text})]})]})}},{key:`kind`,header:e.t(`ai.colKind`,`Kind`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByName.get(t.kind)?.label??t.kind})},{key:`model`,header:e.t(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.model})},{key:`vision`,header:e.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:t=>t.supportsVision?u(V,{variant:`info`,style:`outline`,children:e.t(`ai.vision`,`vision`)}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})},{key:`node`,header:e.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>e.runtime===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(V,{variant:`default`,children:e.runtime.nodeId})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>u(W,{checked:t.enabled,onCheckedChange:()=>e.onToggle(t),"aria-label":K.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(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(j,{className:`h-3.5 w-3.5`})}),u(P,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),title:e.t(`common.edit`,`Edit`),children:u(b,{className:`h-3.5 w-3.5`})}),u(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:e.t(`common.delete`,`Delete`),children:u(h,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Fe(){let{t:e}=q(),s=O(),{state:c,openNew:d,openEdit:f,close:p}=ne(),[m,h]=r(null),[g,_]=r(null),[v,b]=r(null),x=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),S=o({queryKey:se,queryFn:async()=>(await s.trpcClient.llm.listProfileKinds.query({})).map(e=>({...e,configSchema:e.configSchema}))}),w=()=>{x.refetch()},E=i(()=>{h(null),b(null),p()},[p]);t(()=>{c.mode===`closed`&&h(null)},[c.mode]);let D=l({mutationFn:e=>s.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{E(),w()},onError:t=>b(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}),k=l({mutationFn:e=>s.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>_({id:t.id,ok:e.ok,text:e.ok?K.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),A=x.data??[],te=n(()=>S.data??[],[S.data]),j=n(()=>{let e=new Map;for(let t of te)e.set(t.kind,t);return e},[te]),M=c.mode===`edit`?A.find(e=>e.id===c.id)??null:null,N=M===null?null:j.get(M.kind)??null,F=c.mode===`new`&&m===null,L=c.mode===`new`?m:N,re=c.mode===`edit`?M:null,B=L!==null&&(c.mode===`new`||re!==null);return a(ae,{embedded:!0,icon:C,title:e(`ai.profilesTitle`,`AI profiles`),subtitle:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),children:[u(`div`,{className:`flex justify-end`,children:a(P,{size:`sm`,type:`button`,onClick:()=>{b(null),h(null),d()},children:[u(y,{className:`h-3.5 w-3.5`}),e(`ai.addProfile`,`Add profile`)]})}),x.isError&&u(I,{title:e(`ai.loadFailed`,`Failed to load profiles`),message:x.error instanceof Error?x.error.message:e(`common.error`,`Error`),onRetry:()=>void x.refetch()}),u(Ie,{profiles:A}),x.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(T,{className:`h-6 w-6 animate-spin text-primary`})}),!x.isLoading&&A.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}),A.length>0&&u(z,{headingId:`ai-profiles-list`,title:e(`ai.profilesList`,`Profiles`),children:u(R,{columns:Pe({kindByName:j,testResult:g,testingId:k.isPending?k.variables?.id??null:null,t:e,onToggle:e=>D.mutate({...e,enabled:!e.enabled,apiKey:`__redacted__`}),onTest:e=>k.mutate(e),onEdit:e=>{j.has(e.kind)&&(b(null),h(null),f(e.id))},onDelete:e=>ee.mutate(e)}),rows:A,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:`max-h-[60vh]`})}),F&&u(Me,{kinds:te,onCancel:E,onPick:e=>{b(null),h(e)}}),B&&L!==null&&u(Ne,{kind:L,existing:re,saving:D.isPending,error:v,onSave:e=>D.mutate(e),onCancel:E})]})}function Ie({profiles:e}){let{t}=q(),n=O(),r=o({queryKey:ce,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(z,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:u(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:de.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(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`llm-default-${n}`,children:c(n)}),u(F,{id:`llm-default-${n}`,"aria-label":c(n),className:`h-7 text-xs`,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-[10px] 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-[10px] 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-[10px] text-danger`,children:String(i.error)})]},n)})})})}e();var Le=5e3;function Re(e){return K.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ze(){let{t:e}=q(),t=O(),r=o({queryKey:Y,refetchInterval:Le,queryFn:()=>t.trpcClient.llm.listRuntimeNodes.query({})}),i=n(()=>[{key:`node`,header:e(`ai.colNode`,`Node`),render:e=>u(`span`,{className:`text-sm 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(V,{variant:t.reachable?`success`:`danger`,children:t.reachable?t.status?.state??e(`ai.ready`,`ready`):e(`ai.unreachable`,`unreachable`)}),t.status?.downloadProgress!==void 0&&u(V,{variant:`info`,children:`${String(Math.round(t.status.downloadProgress*100))}%`})]})},{key:`model`,header:e(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:e(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.disk===void 0?`—`:Re(e.disk.modelsBytes)})},{key:`apple`,header:e(`ai.colApple`,`Apple on-device`),render:t=>{let n=Ee(t);return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[u(V,{variant:n.tone,children:e(n.labelKey,n.labelDefault)}),n.detail!==null&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n.detail})]})}},{key:`error`,header:e(`ai.colError`,`Error`),render:e=>e.error===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(`span`,{className:`text-[11px] text-danger`,children:e.error})}],[e]),s=r.data??[];return a(ae,{embedded:!0,icon:k,title:e(`ai.runtimesTitle`,`Managed runtimes`),subtitle:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),children:[r.isError&&u(I,{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(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):u(z,{headingId:`ai-runtimes-list`,title:e(`ai.runtimesList`,`Nodes`),children:u(R,{columns:i,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:B})})]})}var Be=x(`/addon/ai/test-chat`),Ve=x(`/addon/ai/test-chat/chats`),He=6e5;function Ue(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),He)}function We(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e){if(!We(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Ke=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function qe(e){let t;try{t=JSON.parse(e)}catch{return null}if(!We(t))return null;switch(t.kind){case`status`:{let e=Ke.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Ge(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:K.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*Je(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
2
  `);for(;a>=0;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length>0){let t=qe(e);t!==null&&(yield t)}a=r.indexOf(`
3
3
  `)}}let e=r.trim();if(e.length>0){let t=qe(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Ye(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Xe(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Ze(e){return e.messages.map((t,n)=>{let r=t.mediaSent??void 0;return{id:`${e.id}-${String(n)}`,role:t.role,content:t.content,...t.attachment===void 0?{}:{attachmentRef:t.attachment,attachmentKind:t.attachment.kind},...r===void 0?{}:{attachment:r}}})}function Qe(e){let t=e.sizeBytes<1024*1024?`${(e.sizeBytes/1024).toFixed(0)} KB`:`${(e.sizeBytes/(1024*1024)).toFixed(1)} MB`,n=[e.kind===`snapshot`?`camera snapshot`:`track best-shot`,t];return e.mediaKind!==void 0&&n.push(e.mediaKind),e.capturedAt!==void 0&&n.push(new Date(e.capturedAt).toLocaleTimeString()),n.join(` · `)}function $e(e,t){switch(e){case`resolving-image`:return K.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return K.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?K.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):K.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return K.t(`helpers.aiTestChat.phaseAnswering`)}}e();var et=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],tt=360*60*1e3,nt=40,rt=160,it={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function at(){let{t:e}=q(),s=O(),[l,d]=r(``),[f,p]=r(``),[m,g]=r(``),[y,b]=r([]),[x,S]=r(null),[C,w]=r(`none`),[T,E]=r(`throwaway`),[k,M]=r(null),[ne,re]=r([]),[R,z]=r(null),[B,V]=r(null),H=c(null);t(()=>()=>H.current?.abort(),[]);let U=i(async()=>{let e=await fetch(Ve,{credentials:`same-origin`});e.ok&&re((await e.json()).chats??[])},[]);t(()=>{T===`persistent`&&U()},[T,U]);let W=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),G=n(()=>(W.data??[]).filter(e=>e.enabled),[W.data]),K=G.find(e=>e.id===l)??null,J=B!==null,ie=i(async(t,n)=>{let r=new AbortController;H.current=r,z(null);let i=Ue(K??{});V({...it,firstTokenTimeoutMs:i??0});let a=``,o=null,s,c=null,u=null,d;try{let e=await fetch(Be,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:r.signal,body:JSON.stringify({profileId:l,messages:t,...f.trim()===``?{}:{system:f.trim()},...n===void 0?{}:{attachment:n},...i===void 0?{}:{firstTokenTimeoutMs:i},...T===`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 Je(e.body))switch(t.kind){case`status`:V(e=>({...e??it,phase:t.phase}));break;case`meta`:o=t.mediaSent,s=t.model,V(e=>({...e??it,firstTokenTimeoutMs:t.firstTokenTimeoutMs,mediaSent:t.mediaSent}));break;case`token`:a+=t.text,V(e=>({...e??it,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||z(t instanceof Error?t.message:e(`common.error`,`Error`))}finally{H.current=null,V(null)}d!==void 0&&(M(d),U());let p=r.signal.aborted&&a.length>0;c===null&&a.length===0&&!p||b(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}])},[T,k,K,l,U,f,e]),se=i(()=>{let e=m.trim();if(e===``||l===``||J)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...x===null?{}:{attachmentLabel:x.label,attachmentKind:x.ref.kind}},n=[...y,t];b(n),g(``);let r=x?.ref;S(null),w(`none`),ie(T===`persistent`&&k!==null?[{role:`user`,content:e}]:Ye(n),r)},[T,k,m,x,l,ie,J,y]),ce=()=>H.current?.abort(),Y=()=>{H.current?.abort(),b([]),S(null),g(``),z(null),V(null),M(null)},le=async e=>{H.current?.abort();let t=await fetch(`${Ve}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();M(e),b(Ze(n)),V(null),z(null)};return a(ae,{embedded:!0,icon:ee,title:e(`ai.testTitle`,`Test chat`),subtitle:e(T===`persistent`?`ai.testSubtitlePersistent`:`ai.testSubtitle`,T===`persistent`?`Conversations are saved for you and can be reopened. Throwaway mode is still available.`:`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`),children:[u(`div`,{className:`flex justify-end`,children:a(P,{size:`sm`,variant:`secondary`,type:`button`,disabled:y.length===0&&x===null,onClick:Y,children:[u(h,{className:`h-3.5 w-3.5`}),e(`ai.clearChat`,`Clear`)]})}),a(L,{className:`space-y-3 p-4`,children:[a(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-test-profile`,children:e(`ai.profile`,`Profile`)}),u(F,{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&&!W.isLoading&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:e(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-test-system`,children:e(`ai.systemPrompt`,`System prompt (optional)`)}),u(N,{id:`ai-test-system`,value:f,onChange:e=>p(e.target.value),placeholder:e(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(P,{size:`sm`,variant:T===`throwaway`?`primary`:`outline`,type:`button`,onClick:()=>{E(`throwaway`),M(null)},children:e(`ai.throwawayMode`,`Throwaway`)}),u(P,{size:`sm`,variant:T===`persistent`?`primary`:`outline`,type:`button`,onClick:()=>E(`persistent`),children:e(`ai.saveConversation`,`Save conversation`)})]}),T===`persistent`&&a(`div`,{className:`space-y-2`,children:[u(`div`,{className:`flex items-center gap-2`,children:a(P,{size:`sm`,variant:`secondary`,type:`button`,onClick:Y,children:[u(te,{className:`h-3.5 w-3.5`}),e(`ai.newChat`,`New chat`)]})}),ne.length>0&&u(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:ne.map(e=>u(`button`,{type:`button`,onClick:()=>void le(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover ${e.id===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-[10px] 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-[10px] text-warning`,children:e(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]}),R!==null&&u(I,{title:e(`ai.chatFailed`,`The test call failed`),message:R}),u(ot,{turns:y,live:B}),a(L,{className:`space-y-2 p-3`,children:[x!==null&&a(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-surface px-2.5 py-1.5`,children:[x.ref.kind===`snapshot`?u(A,{className:`h-3.5 w-3.5 text-foreground-subtle`}):u(v,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-foreground`,children:x.label}),u(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>S(null),children:u(D,{className:`h-3.5 w-3.5`})})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(P,{size:`sm`,variant:C===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>w(C===`snapshot`?`none`:`snapshot`),children:[u(A,{className:`h-3.5 w-3.5`}),e(`ai.attachSnapshot`,`Camera snapshot`)]}),a(P,{size:`sm`,variant:C===`track`?`primary`:`outline`,type:`button`,onClick:()=>w(C===`track`?`none`:`track`),children:[u(v,{className:`h-3.5 w-3.5`}),e(`ai.attachTrack`,`Recent track`)]})]}),C===`snapshot`&&u(lt,{onPick:t=>{S({ref:{kind:`snapshot`,deviceId:t.id},label:e(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t.name})}),w(`none`)}}),C===`track`&&u(dt,{onPick:(t,n)=>{S({ref:{kind:`track`,trackId:t.trackId,deviceId:t.deviceId},label:e(`ai.trackOf`,`{{class}} on {{name}}`,{class:t.label??t.className,name:n})}),w(`none`)}}),a(`div`,{className:`flex items-center gap-2`,children:[u(N,{value:m,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),se())},placeholder:e(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":e(`ai.message`,`Message`)}),J?a(P,{size:`sm`,variant:`secondary`,type:`button`,onClick:ce,children:[u(_,{className:`h-3.5 w-3.5`}),e(`ai.stop`,`Stop`)]}):a(P,{size:`sm`,type:`button`,disabled:m.trim()===``||l===``,onClick:se,children:[u(j,{className:`h-3.5 w-3.5`}),e(`ai.send`,`Send`)]})]})]})]})}function ot({turns:e,live:t}){let{t:n}=q();return e.length===0&&t===null?u(`div`,{className:`py-12 text-center text-xs text-foreground-subtle`,children:n(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):u(L,{children:a(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto p-3`,children:[e.map(e=>u(st,{turn:e},e.id)),t!==null&&a(`div`,{className:`space-y-1`,children:[t.mediaSent!==null&&u(ct,{attachment:t.mediaSent}),t.text.length>0&&u(st,{turn:{id:`live`,role:`assistant`,content:t.text},streaming:!0}),a(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(T,{className:`h-3.5 w-3.5 animate-spin`}),$e(t.phase,t.firstTokenTimeoutMs)]})]})]})})}function st({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(ct,{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(v,{className:`h-3 w-3`}):u(A,{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(A,{className:`h-3 w-3`}):u(v,{className:`h-3 w-3`}),Qe(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 ct({attachment:e}){let{t}=q(),n=Xe(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 lt({onPick:e}){let{t}=q(),n=U({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?u(T,{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(ut,{device:t,onPick:e},t.id))})}function ut({device:e,onPick:t}){let{t:n}=q(),{src:r}=p(e.id,{width:rt});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(V,{variant:`warning`,children:n(`common.off`)}),u(`span`,{className:`truncate text-[10px] text-foreground`,children:e.name})]})]})}function dt({onPick:e}){let{t}=q(),r=O(),i=U({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:[...et,s.length],enabled:s.length>0,queryFn:()=>r.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...s],since:Date.now()-tt,limit:nt,projection:`slim`})});if(i.isLoading||l.isLoading)return u(T,{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(v,{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 ft=1440*60*1e3,pt=[1,7,30,90];function mt(){let{t:e}=q(),t=O(),[i,s]=r(7),c=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(i-1)*ft},[i]),l=o({queryKey:oe,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),d=o({queryKey:[...ue,i],queryFn:()=>t.trpcClient.llm.getUsage.query({since:c})}),f=n(()=>{let e=new Map;for(let t of l.data??[])e.set(t.id,t.name);return e},[l.data]),p=n(()=>[{key:`day`,header:e(`ai.colDay`,`Day`),nowrap:!0,render:e=>e.day},{key:`consumer`,header:e(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.consumer})},{key:`profile`,header:e(`ai.colProfile`,`Profile`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:f.get(e.profileId)??e.profileId})},{key:`calls`,header:e(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>String(e.calls)},{key:`okErr`,header:e(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:e.errorCalls>0?`text-danger`:void 0,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:e(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>`${String(e.inputTokens)} / ${String(e.outputTokens)}`},{key:`latency`,header:e(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>String(Math.round(e.avgLatencyMs))}],[f,e]),m=d.data??[];return a(ae,{embedded:!0,icon:S,title:e(`ai.usageTitle`,`Usage`),subtitle:e(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),actions:u(`div`,{className:`w-40`,children:u(F,{"aria-label":e(`ai.window`,`Window`),value:String(i),options:pt.map(t=>({value:String(t),label:e(`ai.lastDays`,`Last {{days}} days`,{days:t})})),onChange:e=>s(Number(e.target.value))})}),children:[d.isError&&u(I,{title:e(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:e(`common.error`,`Error`),onRetry:()=>void d.refetch()}),m.length===0?u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noUsage`,`No AI calls in this window.`)}):u(z,{headingId:`ai-usage-list`,title:e(`ai.usageList`,`Rollup`),children:u(R,{columns:p,rows:m,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:B})})]})}function ht(){let{t:e}=q(),t=J(`/system/ai`,{t:e,isAdmin:!0})??{icon:C,title:e(`system.ai`,`AI`)};return u(ie,{icon:t.icon,title:t.title,defaultSection:`profiles`,sectionsLabel:`${t.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:u(Fe,{})},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:u(ze,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:u(mt,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:u(at,{})}]})}export{ht as AiProfilesPage,ht 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{ar as o}from"./player-overlays-CTjp5_0E.js";import{yi as s}from"./client-Ck3kx2Z0.js";import{Bn as c,Sn as l,bi as u,pi as d}from"./src-CoNs4bys.js";import{t as f}from"./useTranslation-D3Is_4B6.js";import{L as p,Y as m}from"./index-IBVizVRk.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};
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{ar as o}from"./player-overlays-DFTWiQ8-.js";import{yi as s}from"./client-CqsEJzhO.js";import{Bn as c,Sn as l,bi as u,pi as d}from"./src-CE3hNyCx.js";import{t as f}from"./useTranslation-D3Is_4B6.js";import{L as p,Y as m}from"./index-mBJW996X.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};
@@ -1,4 +1,4 @@
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{It as p,Ji as m,Nt as h,On as g,Pn as _,Wi as v,_i as y,_n as b,ar as x,di as S,fn as C,ia as w,kn as T,ot as E,pt as D,xr as O,yi as k}from"./player-overlays-CTjp5_0E.js";import{t as A}from"./boxes-DMqqPR7T.js";import{n as j,r as M,t as N}from"./ungroup-CQ9vK9Rb.js";import{o as P}from"./video-C9XbLIGZ.js";import{Dr as F,Fr as I,Ir as L,Lr as R,Mr as z,Nr as B,Or as V,Pr as H,Sr as ee,Ti as te,Wt as ne,fr as re,hr as ie,mr as ae,pr as oe}from"./client-Ck3kx2Z0.js";import{$l as U,Bn as W,Di as se,Dt as ce,Fi as le,Ii as ue,Jl as G,L as de,Ln as fe,Lt as K,Mi as pe,Ni as me,Oi as he,Pi as ge,Pn as _e,Ql as ve,Ti as ye,Tt as be,U as xe,Ut as Se,Wt as Ce,Xl as we,Zl as Te,Zn as Ee,an as De,ar as q,ha as Oe,ki as ke,vt as Ae,z as je}from"./src-CoNs4bys.js";import{t as J}from"./i18n-DWijAvai.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{C as Me,L as Ne,U as Pe,X as Fe,Y as X,et as Ie,x as Le}from"./index-IBVizVRk.js";import{t as Re}from"./AdminSectionedPage-DKH0UpKh.js";import{t as ze}from"./DeviceDoActionFields-DmKzugUt.js";import{E as Be,O as Ve,t as He}from"./CompositionEditor-DYkQHem0.js";var Ue=`const AUTOMATION_RECIPE =`,We=`// EJECTED from the visual automation editor — this file is now hand-owned.
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{It as p,Ji as m,Nt as h,On as g,Pn as _,Wi as v,_i as y,_n as b,ar as x,di as S,fn as C,ia as w,kn as T,ot as E,pt as D,xr as O,yi as k}from"./player-overlays-DFTWiQ8-.js";import{t as A}from"./boxes-DKr2EDaB.js";import{n as j,r as M,t as N}from"./ungroup-oYlFn3LE.js";import{o as P}from"./video-vLKHp9E_.js";import{Dr as F,Fr as I,Ir as L,Lr as R,Mr as z,Nr as B,Or as V,Pr as H,Sr as ee,Ti as te,Wt as ne,fr as re,hr as ie,mr as ae,pr as oe}from"./client-CqsEJzhO.js";import{$l as U,Bn as W,Di as se,Dt as ce,Fi as le,Ii as ue,Jl as G,L as de,Ln as fe,Lt as K,Mi as pe,Ni as me,Oi as he,Pi as ge,Pn as _e,Ql as ve,Ti as ye,Tt as be,U as xe,Ut as Se,Wt as Ce,Xl as we,Zl as Te,Zn as Ee,an as De,ar as q,ha as Oe,ki as ke,vt as Ae,z as je}from"./src-CE3hNyCx.js";import{t as J}from"./i18n-B-IeyHf7.js";import{t as Y}from"./useTranslation-D3Is_4B6.js";import{C as Me,L as Ne,U as Pe,X as Fe,Y as X,et as Ie,x as Le}from"./index-mBJW996X.js";import{t as Re}from"./AdminSectionedPage-Bb00eMTj.js";import{t as ze}from"./DeviceDoActionFields-DKOJoFJc.js";import{E as Be,O as Ve,t as He}from"./CompositionEditor-DTgOmFqj.js";var Ue=`const AUTOMATION_RECIPE =`,We=`// EJECTED from the visual automation editor — this file is now hand-owned.
2
2
  // The recipe that produced it was removed with it, on purpose: while it was
3
3
  // here the editor could re-open this block and overwrite everything below.`;function Ge(e){return e.includes(Ue)}function Ke(e){let t=e.indexOf(Ue);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 qe(e){let t=Ke(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=H.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 Je(e){let t=Ke(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)}${We}${e.slice(i)}`}e();var Ye=6e4;function Xe(){let e=Oe({projection:`slim`});return n(()=>(e.data??[]).filter(e=>ne(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 Ze(e){let t=E();return c({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:Ye,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function Qe(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 $e(e){let t=Ze(e.deviceId);if(t.data!==void 0)return Qe(t.data,e.cap).find(t=>t.path===e.fieldPath)}function et({value:e,devices:t,onChange:n}){let{t:r}=Y(),i=Ze(e.deviceId),a=i.data??[],s=Qe(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(G,{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(G,{value:e.cap,disabled:e.deviceId===0,onChange:t=>n({...e,cap:t.target.value,fieldPath:``}),options:[{value:``,label:tt(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(G,{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 tt(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 nt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function rt(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 nt}}function it(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 at(e){return rt(e).map(e=>({value:e,label:it(e)}))}function ot(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 st={triggers:[],actions:[]};function ct(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 lt(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
4
  `};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function ut(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function dt(){return{kind:`expression`,expr:``,bindings:{}}}function ft(e,t,n){return e.map((e,r)=>r===t?n:e)}function pt(e,t){return e.filter((e,n)=>n!==t)}function mt(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=pt(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function ht(e,t){return{...e,triggers:[...t]}}function gt(e,t){return{...e,actions:[...t]}}var _t=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function vt({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(q,{variant:`default`,children:s+1}),o(`label`,{className:`w-40`,children:[f(Z,{children:i(`automation.actionList.step`,`Step`)}),f(G,{value:a.kind,onChange:t=>r(ft(e,s,lt(yt(t.target.value)))),options:_t.map(e=>({value:e.value,label:i(e.labelKey)}))})]}),o(`div`,{className:`ml-auto flex items-center gap-1`,children:[f(W,{variant:`ghost`,disabled:s===0,onClick:()=>r(mt(e,s,s-1)),title:i(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:f(v,{className:`h-3.5 w-3.5`})}),f(W,{variant:`ghost`,disabled:s===e.length-1,onClick:()=>r(mt(e,s,s+1)),title:i(`automation.actionList.runThisStepLater`,`Run this step later`),children:f(m,{className:`h-3.5 w-3.5`})}),f(W,{variant:`ghost`,onClick:()=>r(pt(e,s)),title:i(`automation.actionList.removeThisStep`,`Remove this step`),children:f(p,{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(U,{type:`number`,min:0,max:300,value:String(a.seconds),onChange:t=>r(ft(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(ft(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(xt,{action:a,devices:t,devicesState:n,onChange:t=>r(ft(e,s,t))})]},`${a.kind}-${String(s)}`)),o(`div`,{className:`flex items-center gap-2`,children:[o(W,{variant:`outline`,onClick:()=>r([...e,lt(`cap`)]),children:[f(g,{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 yt(e){return _t.find(t=>t.value===e)?.value??`cap`}function bt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function xt({action:e,devices:t,devicesState:n,onChange:r}){return f(ze,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:bt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function St({value:e,field:t,onChange:n}){let{t:r}=Y();return t?.kind===`boolean`?f(G,{value:e===!0?`true`:`false`,onChange:e=>n(e.target.value===`true`),options:[{value:`true`,label:r(`common.true`)},{value:`false`,label:r(`common.false`)}]}):t?.kind===`enum`&&t.enumValues!==void 0&&t.enumValues.length>0?f(G,{value:String(e),onChange:e=>n(e.target.value),options:t.enumValues.map(e=>({value:e,label:e}))}):t?.kind===`number`?f(U,{type:`number`,value:typeof e==`number`?String(e):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&n(t)}}):f(U,{value:String(e),placeholder:r(`common.valueWord`),onChange:e=>n(e.target.value)})}function Ct({value:e,field:t,onChange:n}){let{t:r}=Y();return f(U,{value:e.join(`, `),placeholder:r(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let r=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(t?.kind===`number`?r.map(e=>Number(e)).filter(e=>!Number.isNaN(e)):r)}})}function wt(e){return typeof e==`object`}function Tt(e){return wt(e)?e[0]??``:e}function Et(e){return wt(e)?e:typeof e==`boolean`?[]:[e]}function Dt({leaf:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=$e(i),s=at(a?.kind),c=e.operator===`in`,l=t=>{n({...e,deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath})},u=t=>{let r=Ot(t,s);n({...e,operator:r,value:r===`in`?Et(e.value):Tt(e.value)})};return o(`div`,{className:`flex flex-wrap items-end gap-2`,children:[f(et,{value:i,devices:t,onChange:l}),o(`label`,{className:`min-w-[8rem]`,children:[f(Z,{children:r(`automation.conditionRow.comparison`,`Comparison`)}),f(G,{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(Ct,{value:Et(e.value),field:a,onChange:t=>n({...e,value:t})}):f(St,{value:Tt(e.value),field:a,onChange:t=>n({...e,value:t})})]})]})}function Ot(e,t){return t.find(t=>t.value===e)?.value??`eq`}var kt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function At({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(U,{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(jt,{alias:n,source:r,devices:t,onRename:t=>a(Lt(e.bindings,n,t)),onChange:t=>a({...e.bindings,[n]:t}),onRemove:()=>a(Rt(e.bindings,n))},n)),o(W,{variant:`ghost`,onClick:()=>a({...e.bindings,[It(e.bindings)]:kt}),children:[f(g,{className:`h-3.5 w-3.5`}),` `,r(`common.name`)]})]})]})}function jt({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:Pt(n,Nt(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(U,{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(G,{value:c?`literal`:`global`,onChange:e=>i(e.target.value===`literal`?{kind:`literal`,value:``}:kt),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(U,{value:t.value===null?``:String(t.value),placeholder:`5`,onChange:e=>i({kind:`literal`,value:Mt(e.target.value)})})]}):f(et,{value:l,devices:n,onChange:e=>i({kind:`global`,sourceStableId:Ft(n,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),f(W,{variant:`ghost`,onClick:a,title:s(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:f(p,{className:`h-3.5 w-3.5`})})]})}function Mt(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Nt(e){return e.kind===`global`?e.sourceStableId:``}function Pt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Ft(e,t){return e.find(e=>e.id===t)?.stableId??``}function It(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 Lt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Rt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function zt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:zt(t)?t:{kind:`all`,children:[t]}}function Bt(e,t){return t===null||zt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Vt(e){return Bt(e,Q(e))}function Ht(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?Ht(e.child,r):null;if(!zt(e))return null;let i=e.children[n];return i===void 0?null:Ht(i,r)}function Ut(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=Ut(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!zt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=Ut(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 Wt(e){return e===null?null:R({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function Gt(e){let t=Q(e);return{depth:t.children.length===0?0:I(t),leaves:t.children.length===0?0:L(t),depthLimit:3,leafLimit:32}}function Kt(e,t){let n=Wt(t);return n===null?{ok:!0,recipe:Bt(e,t)}:{ok:!1,reason:n}}function qt(e,t){let n=Q(e);return Kt(e,{kind:n.kind,children:[...n.children,t]})}function Jt(e,t,n){return Bt(e,Ut(Q(e),t,()=>n))}function Yt(e,t){return Bt(e,Ut(Q(e),t,()=>null))}function Xt(e,t,n){return Bt(e,Ut(Q(e),t,e=>zt(e)?{kind:n,children:e.children}:e))}function Zt(e,t){return Ht(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:Kt(e,Ut(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function Qt(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 $t(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=Qt(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=Ht(i,r.path);if(a===null||!zt(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 Kt(e,Ut(i,r.path,()=>d))}function en(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=Ht(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return Kt(e,Ut(n,t,()=>r.child));if(!zt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=Qt(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=Ht(n,i.path);if(a===null||!zt(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 Kt(e,Ut(n,i.path,()=>o))}e();var tn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function nn(e){return e.join(`/`)}function rn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function an({recipe:e,devices:t,onChange:i}){let{t:a}=Y(),[s,c]=r([]),[l,u]=r(null),d=Q(e),p=Gt(e),m=n(()=>s.map(rn),[s]),h=e=>{if(!e.ok){u(e.reason);return}u(null),c([]),i(e.recipe)},_=$t(e,m,`all`),v=$t(e,m,`any`),y=m.length===1?Zt(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(Jt(e,t,n)),onRemove:t=>{c([]),i(Yt(e,t))},onSetKind:(t,n)=>i(Xt(e,t,n)),onUngroup:t=>h(en(e,t))};return o(`div`,{className:`space-y-2`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[f(q,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),f(`div`,{className:`w-32`,children:f(G,{value:d.kind,onChange:t=>i(Xt(e,[],on(t.target.value))),options:tn.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(sn,{container:d,path:[],handlers:b}),o(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(W,{variant:`outline`,onClick:()=>h(qt(e,ut())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[f(g,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),o(W,{variant:`outline`,onClick:()=>h(qt(e,dt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[f(M,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),f(`span`,{className:`mx-1 h-5 w-px bg-border`}),f(W,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):_.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),f(W,{variant:`ghost`,disabled:!v.ok,onClick:()=>h(v),title:v.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):v.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),f(W,{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 on(e){return e===`any`?`any`:`all`}function sn({container:e,path:t,handlers:n}){return f(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>f(cn,{node:e,path:[...t,r],handlers:n},nn([...t,r])))})}function cn({node:e,path:t,handlers:n}){let{t:r}=Y(),i=nn(t),a=f(De,{checked:n.selected.has(i),onChange:()=>n.onToggleSelect(i),"aria-label":r(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return zt(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(G,{value:e.kind,onChange:e=>n.onSetKind(t,on(e.target.value)),options:tn.map(e=>({value:e.value,label:r(e.labelKey)}))})}),o(W,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[f(N,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.ungroup`)]}),f(W,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:f(p,{className:`h-3.5 w-3.5`})})]}),f(`div`,{className:`pl-4`,children:f(sn,{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(q,{variant:`warning`,children:`NOT`}),o(W,{variant:`ghost`,onClick:()=>n.onUngroup(t),title:r(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[f(N,{className:`h-3.5 w-3.5`}),` `,r(`automation.conditionTree.removeNot`)]})]}),f(`div`,{className:`pl-4`,children:f(cn,{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(Dt,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)}):f(At,{leaf:e,devices:n.devices,onChange:e=>n.onUpdate(t,e)})}),f(W,{variant:`ghost`,onClick:()=>n.onRemove(t),title:r(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:f(p,{className:`h-3.5 w-3.5`})})]})}e();function ln({code:e,error:t,canEject:n,ejecting:i,onEject:a}){let{t:s}=Y(),[c,l]=r(!1),u=Ee(),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(W,{variant:`ghost`,onClick:()=>l(!c),children:[f(c?k:y,{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(W,{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(P,{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(K,{maxHeight:420,children:e})})]})}var un=[`device-state`,`device-event`,`schedule`,`manual`],dn=Object.values(te).sort((e,t)=>e.localeCompare(t));function fn({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(pn,{trigger:r,devices:t,position:i,onChange:t=>n(ft(e,i,t)),onRemove:()=>n(pt(e,i))},`${r.kind}-${String(i)}`)),o(W,{variant:`outline`,onClick:()=>n([...e,ct(`device-state`)]),title:r(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[f(g,{className:`h-4 w-4`}),` `,r(`automation.triggerEditor.trigger`)]})]})}function pn({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(q,{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(G,{value:e.kind,onChange:e=>r(ct(mn(e.target.value))),options:un.map(e=>({value:e,label:ot(e)}))})]}),f(W,{variant:`ghost`,onClick:i,title:a(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:f(p,{className:`h-4 w-4`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[e.kind===`device-state`&&f(gn,{trigger:e,devices:t,onChange:r}),e.kind===`device-event`&&f(vn,{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(U,{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 mn(e){return un.find(t=>t===e)??`manual`}function hn(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 gn({trigger:e,devices:t,onChange:n}){let{t:r}=Y(),i={deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath},a=$e(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(et,{value:i,devices:t,onChange:e=>n(hn(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(De,{checked:e.becomes===void 0,onChange:e=>n(hn(i,{...s,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),r(`automation.triggerEditor.anyChange`,`any change`)]}),e.becomes!==void 0&&f(St,{value:e.becomes,field:a,onChange:e=>n(hn(i,{...s,becomes:e}))})]})]}),o(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[f(De,{checked:e.edge===!0,onChange:e=>n(hn(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(U,{type:`number`,min:0,value:e.forMs===void 0?``:String(e.forMs/1e3),placeholder:`0`,onChange:e=>n(hn(i,{...s,forMs:_n(e.target.value)}))})]}),o(`label`,{className:`w-28`,children:[f(Z,{children:r(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),f(U,{type:`number`,min:0,value:e.debounceMs===void 0?``:String(e.debounceMs/1e3),placeholder:`0`,onChange:e=>n(hn(i,{...s,debounceMs:_n(e.target.value)}))})]})]})}function _n(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function vn({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(G,{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…`)},...dn.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(G,{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 yn=`hub`;function bn({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(()=>Vt(t)),[_,v]=r(!1),y=Xe(),b=R(h),S=n(()=>Sn(h),[h]),w=n(()=>Cn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),T=p.trim()===``,E=T||b!==null||S!==null||w.code===null;return o(`div`,{className:`space-y-4`,children:[f(`div`,{className:`flex flex-wrap items-center gap-2`,children:f(q,{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(U,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:d(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),f(xn,{step:`1`,title:d(`automation.automationEditor.when`,`When`),subtitle:d(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:f(fn,{triggers:h.triggers,devices:y,onChange:e=>g(ht(h,e))})}),f(xn,{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(an,{recipe:h,devices:y,onChange:g})}),f(xn,{step:`3`,title:d(`automation.automationEditor.then`,`Then`),subtitle:d(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:f(vt,{actions:h.actions,devices:y,onChange:e=>g(gt(h,e))})}),f(ln,{code:w.code,error:w.error,canEject:e!==null,ejecting:s,onEject:l}),b!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:b}),b===null&&S!==null&&f(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:S}),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(W,{onClick:()=>{w.code!==null&&c({name:p.trim(),code:w.code,enabled:e?.enabled??!0,placement:yn})},disabled:i||E,children:[i&&f(x,{className:`h-4 w-4 animate-spin`}),` `,d(`common.save`)]}),o(W,{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(C,{className:`h-4 w-4`}),` `,d(`common.logs`),` `,_?`▾`:`▸`]}),f(W,{variant:`ghost`,onClick:u,disabled:i,children:d(`common.close`,`Close`)}),T&&f(q,{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:re(e.id)},components:{code:f(`code`,{})}})}),f(be,{addonId:re(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function xn({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 Sn(e){let t=H.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 Cn(e,t){try{return{code:B({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function wn(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 Tn(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function En(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Dn(e){let t=e=>{let t=wn(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 On(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>wn(e).tone===`error`).length,n=e.filter(e=>wn(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 kn({block:e,busy:t,confirming:n,logsOpen:r,unreadable:i,onEdit:a,onToggle:s,onToggleLogs:c,onAskDelete:l,onCancelDelete:u,onConfirmDelete:d}){let m=w(),{t:h}=Y(),g=wn(e),v=Ae(e.updatedAt,m);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(q,{variant:Tn(g.tone),children:g.label}),v!==null&&f(`span`,{className:`text-xs text-foreground-subtle`,children:h(`common.edited`,{when:v})})]}),f(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:g.detail}),i!==null&&f(`p`,{className:`mt-0.5 text-xs text-warning`,children:h(`automation.editor.listUnreadable`,{reason:i})})]}),n?o(`div`,{className:`flex justify-end gap-1`,children:[f(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),f(W,{variant:`danger`,onClick:e=>{e.stopPropagation(),d()},disabled:t,children:h(`common.delete`,`Delete`)}),f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},children:h(`common.cancel`,`Cancel`)})]}):o(`div`,{className:`flex justify-end gap-1`,children:[f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),a()},disabled:i!==null,title:i===null?h(`common.edit`,`Edit`):h(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:f(_,{className:`h-4 w-4`})}),o(we,{children:[f(ve,{children:f(W,{variant:`ghost`,disabled:!0,title:h(`automation.automationList.runActions`,`Run actions`),children:f(T,{className:`h-4 w-4`})})}),f(Te,{children:h(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c()},title:h(`automation.automationList.logs`,`Logs`),children:f(C,{className:`h-4 w-4`})}),f(W,{variant:`ghost`,onClick:t=>{t.stopPropagation(),s(!e.enabled)},disabled:t,title:e.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`),children:e.enabled?h(`common.disable`,`Disable`):h(`common.enable`,`Enable`)}),f(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:h(`common.delete`,`Delete`),children:f(p,{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:re(e.id)},components:{code:f(`code`,{})}})}),f(be,{addonId:re(e.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function An({onCreate:e}){let{t}=Y();return f(_e,{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(W,{onClick:e,children:t(`automation.automationList.newAutomation`,`New automation`)})]})})}e();var jn=[`coreBlocks`,`list`],Mn=5e3;function Nn(e){return e instanceof Error?e.message:String(e)}function Pn({onOpenScripts:e,initialBlockId:i,onBlockIdChange:a,createRequested:s=!1,onCreateConsumed:l}){let{t:p}=Y(),m=E(),{state:h,openNew:g,openEdit:_,close:v}=de({editKey:`block`,newKey:`new`}),[y,b]=r(null),[x,S]=r(null),[C,w]=r(null),T=u(null),O=h.mode!==`closed`;t(()=>{s&&(b(null),g(),a?.(null),l?.())},[s,l,a,g]);let k=c({queryKey:jn,refetchInterval:Mn,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;t(()=>{i===void 0||T.current===i||j?.find(e=>e.id===i&&Ge(e.code))!==void 0&&(T.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{S(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:Je(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:t=>{v(),b(null),A(),e(t.block.id)}}),L=k.data,R=Dn((L??[]).filter(e=>Ge(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:En(R,B),H=V===null?null:qe(V.code),ee=M.error===null?N.error===null?I.error===null?null:Nn(I.error):Nn(N.error):Nn(M.error),te=n(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=qe(e.code);return f(`ul`,{className:`list-none`,children:f(kn,{block:e,busy:F.isPending||P.isPending,confirming:x===e.id,logsOpen:C===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{b(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>w(C===e.id?null:e.id),onAskDelete:()=>S(e.id),onCancelDelete:()=>S(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[x,C,a,_,P,F,p]);return o(`div`,{className:`space-y-3`,children:[f(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:On(R)}),k.error!=null&&f(fe,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Nn(k.error),onRetry:A}),z?f(An,{onCreate:()=>{b(null),g(),a?.(null)}}):f(Se,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ce,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{b(e),_(e.id),a?.(e.id)}}),f(je,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),b(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:D,width:`xl`,testId:`automation-editor-panel`,children:f(bn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:st,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(),b(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&f(fe,{message:Nn(P.error)}),F.error!=null&&f(fe,{message:Nn(F.error)})]})}function Fn(e){return{state:`answered`,byRef:new Map(e.map(e=>[F(e),e]))}}function In(e,t){if(e.state!==`unanswered`)return e.byRef.get(F(t))??null}function Ln(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Rn(e){return V(e).map(e=>e.source)}function zn(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(...Rn(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Rn(e))}let r=new Set;return n.filter(e=>{let t=F(e);return r.has(t)?!1:(r.add(t),!0)})}function Bn(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label: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 Vn(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return Bn(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 Hn(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 Vn(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 Un(e){return F(e)}function Wn(e,t){let n=In(t,e);return{key:F(e),label:n?n.name:Un(e),presence:Ln(n),deviceId:n?n.id:null}}function Gn(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function Kn(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:ee(e.block.id),a=F(i),o=zn(e).filter(e=>F(e)!==a).map(e=>Wn(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=In(t,i),l=Gn(e),u=Hn(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=Ln(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:Un(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function qn(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Jn(e,t){return qn(e)-qn(t)||e.name.localeCompare(t.name)}function Yn(e,t){let n=e.flatMap(e=>{let n=Kn(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Jn),customizations:n.filter(e=>e.kind===`customization`).toSorted(Jn)}}e();var Xn=1e4;function Zn(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Qn(e){let t=e.trim();return t===``?{}:{name:t}}function $n(){let e=Pe();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:Zn(e.error)})}:Fn(e.data)}function er({createRequested:e=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=pe({},{refetchInterval:Xn}),a=$n(),s=de({editKey:`block`,newKey:`new`});t(()=>{e&&(s.openNew(),n?.())},[e]);let c=i.data;if(i.error!=null&&c===void 0)return f(fe,{title:r(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:Zn(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(_e,{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:Zn(i.error),d=Yn(c.views,a),p=s.state.mode===`edit`?s.state.id:null,m=s.state.mode===`new`;return o(l,{children:[f(rr,{lists:d,fleet:a,refreshError:u,onEditComposed:e=>s.openEdit(e)}),f(je,{open:m||p!==null,onClose:()=>s.close(),title:m?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:A,width:`xl`,testId:`composed-device-editor`,children:m?f(tr,{onClose:()=>s.close(),onCreated:e=>{i.refetch(),s.openEdit(e)}}):p===null?null:f(nr,{blockId:p,onClose:()=>s.close(),onSaved:()=>void i.refetch()})})]})}function tr({onClose:e,onCreated:t}){let n=ye();return f(He,{initial:Ve(z.Sensor),blockId:null,deviceType:z.Sensor,nativeCaps:null,targetFields:null,showTemplates:!0,onCancel:e,save:async(e,r)=>{try{let{block:i}=await n.mutateAsync({block:{...Qn(r),enabled:!0,composition:e}});return t(i.id),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}})}function nr({blockId:e,onClose:t,onSaved:n}){let{t:r}=Y(),i=ue(),a=ke({blockId:e});if(a.status===`pending`)return f(`p`,{role:`status`,children:r(`compositionEditor.loading`)});if(a.status===`error`)return f(fe,{title:r(`compositionEditor.loadFailed`),message:a.error.message});if(a.data.state===`not-loaded`)return f(`p`,{role:`status`,children:r(`customize.status.notLoaded`,{reason:a.data.reason})});let o=a.data.view;if(o===null)return f(`p`,{children:r(`compositionEditor.notFound`,{blockId:e})});let s=oe(o.block);if(s===null)return f(`p`,{children:r(`compositionEditor.notComposition`)});if(s.target.kind===`existing`){let e=o.state.kind===`answered`?o.state.state?.deviceId??null:null;return e===null?f(`p`,{children:r(`compositionEditor.customizationUnknownDevice`)}):f(Fe,{className:`text-primary`,to:Le(e),children:r(`compositionEditor.openOnDevice`)})}return f(He,{initial:Be(s,o.block.name),blockId:o.block.id,deviceType:s.target.type,nativeCaps:null,targetFields:null,onCancel:t,save:async(e,t)=>{try{return await i.mutateAsync({blockId:o.block.id,expectedUpdatedAt:o.block.updatedAt,block:{...Qn(t),composition:e}}),await a.refetch(),n(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:Zn(e)}}}},`${o.block.id}@${o.block.updatedAt}`)}function rr({lists:e,fleet:t,refreshError:n,onEditComposed:r}){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(ir,{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(ir,{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 ir({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(_e,{variant:`flat`,className:`p-0`,children:f(Se,{columns:ar(r,a,s),rows:n,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:Ce,emptyMessage:i,onRowClick:a===`composed`?e=>s(e.blockId):void 0})})]})}function ar(e,t,n){let r=[{key:`name`,header:e,sortValue:e=>e.name.toLowerCase(),render:e=>f(or,{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(q,{variant:Tn(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(cr,{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(W,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),n(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),r}function or({row:e}){let{t}=Y();return o(`div`,{className:`space-y-0.5`,children:[f(sr,{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 sr({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(Fe,{to:Le(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function cr({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(Fe,{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 lr(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ur(e){if(Array.isArray(e))return e}function dr(e,t,n){return(t=br(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fr(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function pr(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
@@ -1 +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{_i as s,vi as c}from"./player-overlays-CTjp5_0E.js";import{m as l}from"./video-C9XbLIGZ.js";import{bn as u,yn as d}from"./client-Ck3kx2Z0.js";import{An as f,Bn as p,Ci as m,Dn as h,En as g,Si as _,Tn as v,jn as y,kn as b,wi as x,xi as S}from"./src-CoNs4bys.js";import{t as C}from"./i18n-DWijAvai.js";import{t as w}from"./useTranslation-D3Is_4B6.js";import{X as T,Y as E}from"./index-IBVizVRk.js";import{t as D}from"./AdminPage-DMiMIHwu.js";e();var O=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function k(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function A(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function j(e){let t=e.getDay();return k(A(e,t===0?-6:1-t))}function M(e,t){if(t===`day`){let t=k(e);return{startMs:t.getTime(),endMs:A(t,1).getTime()}}if(t===`week`){let t=j(e);return{startMs:t.getTime(),endMs:A(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=j(n),a=A(j(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function N(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=j(e),n=A(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 P(e,t,n){return t===`day`?A(e,n):t===`week`?A(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function F(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 I(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function L(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 R(e){let t=d(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=k(n),t=A(k(r),-1);return H(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 H(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 z({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 B({ev:e,calendarName:t,color:n,onClose:r}){let{t:a}=w();return o(v,{open:!0,onOpenChange:e=>!e&&r(),children:i(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[o(f,{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(y,{className:`min-w-0 break-words`,children:e.title})]})}),o(g,{children:i(`dl`,{className:`space-y-3`,children:[o(z,{label:a(`systemPage.calendars.when`,`When`),children:R(e)}),o(z,{label:a(`systemPage.calendars.calendar`,`Calendar`),children:t}),e.location!==void 0&&e.location.length>0?o(z,{label:a(`systemPage.calendars.location`,`Location`),children:e.location}):null,e.description!==void 0&&e.description.length>0?o(z,{label:a(`systemPage.calendars.description`,`Description`),children:o(`span`,{className:`whitespace-pre-wrap`,children:e.description})}):null]})}),o(b,{children:o(p,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function V(e,t){return e.filter(e=>u(e,t))}function H(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function U({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 W({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:[I(e),e.enabled?``:` · ${a(`systemPage.calendars.unavailableAtSource`)}`]})]})]},e.id))})]})}function G({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:L(e)})]})})}function K({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let{t:s}=w(),{startMs:c,endMs:l}=M(e,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(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:O.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=k(e).getTime(),l=V(t,c),u=e.getMonth()!==d,f=H(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(G,{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 q({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let s=j(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)=>A(s,t)).map(e=>{let s=k(e).getTime(),c=V(t,s);return i(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[o(`div`,{className:H(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(G,{ev:e,color:n.get(e.calendarId)??`#64748B`,onSelect:a},e.id))})]},s)})})}function J({anchor:e,events:t,colorById:n,calName:r,onSelectEvent:a}){let{t:s}=w(),c=V(t,k(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:[L(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 Y(){let{t:e}=w(),a=_(),u=S({}),d=x(),[f,p]=n(`month`),[h,g]=n(()=>k(new Date)),[v,y]=n(null),b=t(()=>k(new Date),[]),C=a.isSuccess,O=u.isSuccess&&u.data!==void 0?u.data:void 0,A=t(()=>!C||a.data===void 0?[]:a.data.map(e=>F(e,O)),[C,a.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(h,f),[h,f]),R=m({startMs:L.startMs,endMs:L.endMs,calendarIds:[...I]},{enabled:C&&I.length>0}),z=R.data??[],V=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.color);return e},[A]),H=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.name);return e},[A]),G=r((e,t)=>{d.mutateAsync({calendarId:e,visible:t}).then(()=>u.refetch())},[u,d]),Y=r((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&d.mutateAsync({calendarId:e,color:t}).then(()=>u.refetch())},[u,d]),X=r(()=>g(k(new Date)),[]),Z=r(()=>g(e=>P(e,f,-1)),[f]),ee=r(()=>g(e=>P(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]}):A.length===0?o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:o(E,{i18nKey:`systemPage.calendars.emptySources`,components:{link:o(T,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?i(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[o(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:d.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(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:d.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(U,{mode:f,onChange:p}),i(`div`,{className:`flex items-center gap-1`,children:[o(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":e(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:o(c,{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:X,"data-testid":`calendars-today`,children:e(`systemPage.calendars.today`,`Today`)}),o(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":e(`common.next`,`Next`),"data-testid":`calendars-next`,children:o(s,{className:`h-4 w-4`})})]}),o(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(h,f)})]}),R.isPending?o(`p`,{className:`text-sm text-foreground-subtle`,children:e(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?i(`p`,{className:`text-sm text-destructive`,children:[e(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):f===`month`?o(K,{anchor:h,events:z,colorById:V,today:b,onSelectEvent:y}):f===`week`?o(q,{anchor:h,events:z,colorById:V,today:b,onSelectEvent:y}):o(J,{anchor:h,events:z,colorById:V,calName:H,onSelectEvent:y})]})]}),i(D,{icon:l,title:e(`systemPage.calendars.calendars`,`Calendars`),subtitle:e(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,v===null?null:o(B,{ev:v,calendarName:H.get(v.calendarId)??v.calendarId,color:V.get(v.calendarId)??`#64748B`,onClose:()=>y(null)})]})}export{Y as CalendarsPage,Y as default};
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{_i as s,vi as c}from"./player-overlays-DFTWiQ8-.js";import{m as l}from"./video-vLKHp9E_.js";import{bn as u,yn as d}from"./client-CqsEJzhO.js";import{An as f,Bn as p,Ci as m,Dn as h,En as g,Si as _,Tn as v,jn as y,kn as b,wi as x,xi as S}from"./src-CE3hNyCx.js";import{t as C}from"./i18n-B-IeyHf7.js";import{t as w}from"./useTranslation-D3Is_4B6.js";import{X as T,Y as E}from"./index-mBJW996X.js";import{t as D}from"./AdminPage-BFQa1eDk.js";e();var O=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function k(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function A(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function j(e){let t=e.getDay();return k(A(e,t===0?-6:1-t))}function M(e,t){if(t===`day`){let t=k(e);return{startMs:t.getTime(),endMs:A(t,1).getTime()}}if(t===`week`){let t=j(e);return{startMs:t.getTime(),endMs:A(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=j(n),a=A(j(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function N(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=j(e),n=A(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 P(e,t,n){return t===`day`?A(e,n):t===`week`?A(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function F(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 I(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function L(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 R(e){let t=d(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=k(n),t=A(k(r),-1);return H(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 H(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 z({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 B({ev:e,calendarName:t,color:n,onClose:r}){let{t:a}=w();return o(v,{open:!0,onOpenChange:e=>!e&&r(),children:i(h,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[o(f,{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(y,{className:`min-w-0 break-words`,children:e.title})]})}),o(g,{children:i(`dl`,{className:`space-y-3`,children:[o(z,{label:a(`systemPage.calendars.when`,`When`),children:R(e)}),o(z,{label:a(`systemPage.calendars.calendar`,`Calendar`),children:t}),e.location!==void 0&&e.location.length>0?o(z,{label:a(`systemPage.calendars.location`,`Location`),children:e.location}):null,e.description!==void 0&&e.description.length>0?o(z,{label:a(`systemPage.calendars.description`,`Description`),children:o(`span`,{className:`whitespace-pre-wrap`,children:e.description})}):null]})}),o(b,{children:o(p,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:a(`common.close`,`Close`)})})]})})}function V(e,t){return e.filter(e=>u(e,t))}function H(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function U({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 W({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:[I(e),e.enabled?``:` · ${a(`systemPage.calendars.unavailableAtSource`)}`]})]})]},e.id))})]})}function G({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:L(e)})]})})}function K({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let{t:s}=w(),{startMs:c,endMs:l}=M(e,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(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:O.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=k(e).getTime(),l=V(t,c),u=e.getMonth()!==d,f=H(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(G,{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 q({anchor:e,events:t,colorById:n,today:r,onSelectEvent:a}){let s=j(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)=>A(s,t)).map(e=>{let s=k(e).getTime(),c=V(t,s);return i(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[o(`div`,{className:H(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(G,{ev:e,color:n.get(e.calendarId)??`#64748B`,onSelect:a},e.id))})]},s)})})}function J({anchor:e,events:t,colorById:n,calName:r,onSelectEvent:a}){let{t:s}=w(),c=V(t,k(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:[L(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 Y(){let{t:e}=w(),a=_(),u=S({}),d=x(),[f,p]=n(`month`),[h,g]=n(()=>k(new Date)),[v,y]=n(null),b=t(()=>k(new Date),[]),C=a.isSuccess,O=u.isSuccess&&u.data!==void 0?u.data:void 0,A=t(()=>!C||a.data===void 0?[]:a.data.map(e=>F(e,O)),[C,a.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(h,f),[h,f]),R=m({startMs:L.startMs,endMs:L.endMs,calendarIds:[...I]},{enabled:C&&I.length>0}),z=R.data??[],V=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.color);return e},[A]),H=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.name);return e},[A]),G=r((e,t)=>{d.mutateAsync({calendarId:e,visible:t}).then(()=>u.refetch())},[u,d]),Y=r((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&d.mutateAsync({calendarId:e,color:t}).then(()=>u.refetch())},[u,d]),X=r(()=>g(k(new Date)),[]),Z=r(()=>g(e=>P(e,f,-1)),[f]),ee=r(()=>g(e=>P(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]}):A.length===0?o(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:o(E,{i18nKey:`systemPage.calendars.emptySources`,components:{link:o(T,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?i(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[o(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:d.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(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:d.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(U,{mode:f,onChange:p}),i(`div`,{className:`flex items-center gap-1`,children:[o(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":e(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:o(c,{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:X,"data-testid":`calendars-today`,children:e(`systemPage.calendars.today`,`Today`)}),o(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":e(`common.next`,`Next`),"data-testid":`calendars-next`,children:o(s,{className:`h-4 w-4`})})]}),o(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(h,f)})]}),R.isPending?o(`p`,{className:`text-sm text-foreground-subtle`,children:e(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?i(`p`,{className:`text-sm text-destructive`,children:[e(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):f===`month`?o(K,{anchor:h,events:z,colorById:V,today:b,onSelectEvent:y}):f===`week`?o(q,{anchor:h,events:z,colorById:V,today:b,onSelectEvent:y}):o(J,{anchor:h,events:z,colorById:V,calName:H,onSelectEvent:y})]})]}),i(D,{icon:l,title:e(`systemPage.calendars.calendars`,`Calendars`),subtitle:e(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,v===null?null:o(B,{ev:v,calendarName:H.get(v.calendarId)??v.calendarId,color:V.get(v.calendarId)??`#64748B`,onClose:()=>y(null)})]})}export{Y as CalendarsPage,Y as default};