@camstack/addon-admin-ui 1.2.477 → 1.2.478

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 (52) hide show
  1. package/dist/assets/{Addons-CbHidHOJ.js → Addons-DAuTfOiO.js} +1 -1
  2. package/dist/assets/{AdminSectionedPage-DtiHBXGC.js → AdminSectionedPage-BByl6Zss.js} +1 -1
  3. package/dist/assets/{AiProfiles-7FToWDqj.js → AiProfiles-Cvu3UHy2.js} +1 -1
  4. package/dist/assets/{BrokerForm-D5-q8F_8.js → BrokerForm-D6ln7R0A.js} +1 -1
  5. package/dist/assets/{Build-DwW5kYsa.js → Build-C0J5ce6Z.js} +1 -1
  6. package/dist/assets/{Calendars-BhMRY6EV.js → Calendars-G5xKjOn2.js} +1 -1
  7. package/dist/assets/{Cluster-z11q6anB.js → Cluster-w5Kcsast.js} +1 -1
  8. package/dist/assets/{CompositionBlockEditor-CElNVsCR.js → CompositionBlockEditor-BsmLsHO7.js} +1 -1
  9. package/dist/assets/{CompositionEditorPage-NzgZB76B.js → CompositionEditorPage-AIRu6m_i.js} +1 -1
  10. package/dist/assets/{Data-D_U-HkwO.js → Data-r1IoElgA.js} +1 -1
  11. package/dist/assets/{DeviceDetail-D89wXQHP.js → DeviceDetail-Dz6PV7rK.js} +1 -1
  12. package/dist/assets/{DeviceDoActionFields-Bj4gX0r-.js → DeviceDoActionFields-gklZW8H7.js} +1 -1
  13. package/dist/assets/{Devices-BnhDZU3y.js → Devices-z5XqFK0f.js} +1 -1
  14. package/dist/assets/{HelperWizard-CrXHYd19.js → HelperWizard-B5Evcb8G.js} +1 -1
  15. package/dist/assets/{History-BsJBR2zt.js → History-DLllXIdk.js} +1 -1
  16. package/dist/assets/{Identity-B_6I_sCY.js → Identity-gwaZ5bXU.js} +1 -1
  17. package/dist/assets/{IntegrationDetail-B9L7AfYy.js → IntegrationDetail-P1tm0l2J.js} +1 -1
  18. package/dist/assets/{IntegrationHub-CSaA690G.js → IntegrationHub-Dv8jClEP.js} +1 -1
  19. package/dist/assets/{Integrations-B-KtSB_m.js → Integrations-B9RbWg-F.js} +1 -1
  20. package/dist/assets/Integrations-BLXg84-0.js +1 -0
  21. package/dist/assets/{Library-3dGkOQB5.js → Library-BXbZKXfl.js} +1 -1
  22. package/dist/assets/{Locations-Bh5GRDCv.js → Locations-CjHnNjAh.js} +1 -1
  23. package/dist/assets/{Logs-diqSxXEc.js → Logs-D7ADXC_5.js} +1 -1
  24. package/dist/assets/{MyAccess-BqulMSGv.js → MyAccess-id2Dmf9N.js} +1 -1
  25. package/dist/assets/{Network-C8Gpb2Vn.js → Network-BS9VI_eu.js} +1 -1
  26. package/dist/assets/{NodeAddonsSettingsPanel-Dq6sGWkR.js → NodeAddonsSettingsPanel-GEn1r68w.js} +1 -1
  27. package/dist/assets/{Notifications-C5w5t75z.js → Notifications-CIXn3wxj.js} +1 -1
  28. package/dist/assets/{Pipeline-CjumfHMc.js → Pipeline-B6AdA9Ua.js} +1 -1
  29. package/dist/assets/{Recordings-DE76fgEt.js → Recordings-2Ej5v6LZ.js} +1 -1
  30. package/dist/assets/{ScanNetworkModal-DXzDOpxk.js → ScanNetworkModal-CJoDRy24.js} +1 -1
  31. package/dist/assets/{SessionsList-Ca-zN1Fi.js → SessionsList-CMV9rDkY.js} +1 -1
  32. package/dist/assets/{Showroom-B9HZ38O5.js → Showroom-eCnhoQBD.js} +1 -1
  33. package/dist/assets/{System-CHEbMPI_.js → System-AxGI_wdI.js} +1 -1
  34. package/dist/assets/{Terminal-CWFZuQLg.js → Terminal-Br0QNfMN.js} +1 -1
  35. package/dist/assets/{assignment-candidates-BcnFMc1B.js → assignment-candidates-BMhC6h3l.js} +1 -1
  36. package/dist/assets/{board-model-gmvqxkjB.js → board-model--9Jw6SCm.js} +1 -1
  37. package/dist/assets/{device-integration-icon-0oWIIjcP.js → device-integration-icon-DEZs4Umq.js} +1 -1
  38. package/dist/assets/{format-CIO4xeN9.js → format-fYneBFV6.js} +1 -1
  39. package/dist/assets/i18n-D0o08mg-.js +1 -0
  40. package/dist/assets/{index-D4ZlWCxy.css → index-D4id__eL.css} +1 -1
  41. package/dist/assets/index-XXQ5yMw_.js +4 -0
  42. package/dist/assets/{linked-devices-model-BoOq02QT.js → linked-devices-model-DMEJU3bE.js} +1 -1
  43. package/dist/assets/{location-owned-usage-IF2k-L3A.js → location-owned-usage-8xhfNE7j.js} +1 -1
  44. package/dist/assets/{mf-entry-bootstrap-0-f45a46c2.js → mf-entry-bootstrap-0-dcdd32c2.js} +1 -1
  45. package/dist/assets/{step-inspector-model-CyqFN-LU.js → step-inspector-model-CI19RBoT.js} +1 -1
  46. package/dist/assets/{useNodeUrlSelection-DGV2ltbG.js → useNodeUrlSelection-DWbo46bM.js} +1 -1
  47. package/dist/index.html +4 -4
  48. package/dist/server/addon.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/assets/Integrations-CMW4LOX-.js +0 -1
  51. package/dist/assets/i18n-xhwARoF0.js +0 -1
  52. package/dist/assets/index-C3uCLHv0.js +0 -4
@@ -1,4 +1,4 @@
1
- import{B as e,C as t,J as n,K as r,R as i,S as a,V as o,Y as s,et as c,o as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{It as d,Nt as f,Ot as p,Q as m,Rn as h,Si as g,Tn as _,Wr as v,ai as y,bn as b,dt as x,fn as S,or as C,pi as ee,pn as w,tn as T,un as E,vi as te,xi as ne}from"./player-overlays-Dbv95cvz.js";import{Na as re}from"./client-DvJxGh2F.js";import{i as D,l as ie}from"./video-D7jv0spx.js";import{$r as O,$s as ae,$u as oe,Ai as se,Bn as k,Di as A,Ei as ce,Fi as le,Hn as j,Ii as M,Ju as N,Kr as P,Li as ue,Mi as F,Ni as de,Oi as fe,Si as I,Ti as pe,Un as L,Ur as R,Vn as z,Wr as me,_d as B,_i as V,_r as he,bi as H,bt as ge,gi as U,hi as _e,hr as W,ji as ve,kt as ye,md as be,mr as xe,nn as G,pi as Se,pr as K,tn as Ce,vi as we,vr as Te,wi as Ee,xi as De,yi as Oe,yr as q}from"./src-DntJrWmU.js";import{t as J}from"./useTranslation-BJr-n0es.js";import"./mount-CUPf26ML.js";import{fr as Y,lr as X,mr as ke}from"./index-C3uCLHv0.js";import{t as Ae}from"./AdminPage-3JxWocN3.js";import{t as je}from"./NodeAddonsSettingsPanel-Dq6sGWkR.js";import{n as Z,t as Me}from"./useNodeUrlSelection-DGV2ltbG.js";function Ne(e){if(e===void 0)return null;switch(e.state){case`failed`:case`refused`:case`missing`:case`crashed`:return{kind:e.state,...e.reason===void 0?{}:{reason:e.reason}};default:return null}}c();var Pe={queued:{icon:y,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:C,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:b,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:g,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:D,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Fe({item:e}){let{t:n}=J(),r=Pe[e.status],i=r.icon;return t(`span`,{className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded ${r.bg}`,title:e.error,children:[a(i,{className:`w-2.5 h-2.5 ${r.spin?`animate-spin`:``}`}),n(r.labelKey)]})}var Ie=new Set([`completed`,`failed`,`partially-failed`,`cancelled`]),Q=new Set([`done`,`failed`,`skipped`]);function Le(e){return!Q.has(e.phase)&&!Ie.has(e.jobState)}function Re(e,t){let n=new Map,r=[...e].sort((e,t)=>e.createdAtMs-t.createdAtMs);for(let e of r){let r=Ie.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 ze(){let{data:e}=pe({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=B(re.AddonsJobProgress,e=>e.job.jobId);return r(()=>{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 Re([...n.values()],Date.now())},[e,t])}var Be={queued:{icon:y,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:C,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:g,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:D,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:T,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function Ve({progress:e}){let{t:n}=J(),r=Be[e.phase],i=r.icon,o=e.error??`${e.packageName}: ${e.fromVersion??`?`} → ${e.toVersion}`;return t(`span`,{"data-testid":`addon-job-progress`,className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded shrink-0 ${r.cls}`,title:o,children:[a(i,{className:`w-2.5 h-2.5 ${r.spin?`animate-spin`:``}`}),n(r.labelKey),t(`span`,{className:`font-mono`,children:[`→ `,e.toVersion]})]})}function He(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 Ue(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function We(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(Ue)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
1
+ import{B as e,C as t,J as n,K as r,R as i,S as a,V as o,Y as s,et as c,o as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{It as d,Nt as f,Ot as p,Q as m,Rn as h,Si as g,Tn as _,Wr as v,ai as y,bn as b,dt as x,fn as S,or as C,pi as ee,pn as w,tn as T,un as E,vi as te,xi as ne}from"./player-overlays-Dbv95cvz.js";import{Na as re}from"./client-DvJxGh2F.js";import{i as D,l as ie}from"./video-D7jv0spx.js";import{$r as O,$s as ae,$u as oe,Ai as se,Bn as k,Di as A,Ei as ce,Fi as le,Hn as j,Ii as M,Ju as N,Kr as P,Li as ue,Mi as F,Ni as de,Oi as fe,Si as I,Ti as pe,Un as L,Ur as R,Vn as z,Wr as me,_d as B,_i as V,_r as he,bi as H,bt as ge,gi as U,hi as _e,hr as W,ji as ve,kt as ye,md as be,mr as xe,nn as G,pi as Se,pr as K,tn as Ce,vi as we,vr as Te,wi as Ee,xi as De,yi as Oe,yr as q}from"./src-DntJrWmU.js";import{t as J}from"./useTranslation-BJr-n0es.js";import"./mount-CUPf26ML.js";import{fr as Y,lr as X,mr as ke}from"./index-XXQ5yMw_.js";import{t as Ae}from"./AdminPage-3JxWocN3.js";import{t as je}from"./NodeAddonsSettingsPanel-GEn1r68w.js";import{n as Z,t as Me}from"./useNodeUrlSelection-DWbo46bM.js";function Ne(e){if(e===void 0)return null;switch(e.state){case`failed`:case`refused`:case`missing`:case`crashed`:return{kind:e.state,...e.reason===void 0?{}:{reason:e.reason}};default:return null}}c();var Pe={queued:{icon:y,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:C,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:b,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:g,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:D,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Fe({item:e}){let{t:n}=J(),r=Pe[e.status],i=r.icon;return t(`span`,{className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded ${r.bg}`,title:e.error,children:[a(i,{className:`w-2.5 h-2.5 ${r.spin?`animate-spin`:``}`}),n(r.labelKey)]})}var Ie=new Set([`completed`,`failed`,`partially-failed`,`cancelled`]),Q=new Set([`done`,`failed`,`skipped`]);function Le(e){return!Q.has(e.phase)&&!Ie.has(e.jobState)}function Re(e,t){let n=new Map,r=[...e].sort((e,t)=>e.createdAtMs-t.createdAtMs);for(let e of r){let r=Ie.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 ze(){let{data:e}=pe({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=B(re.AddonsJobProgress,e=>e.job.jobId);return r(()=>{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 Re([...n.values()],Date.now())},[e,t])}var Be={queued:{icon:y,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:C,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:C,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:g,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:D,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:T,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function Ve({progress:e}){let{t:n}=J(),r=Be[e.phase],i=r.icon,o=e.error??`${e.packageName}: ${e.fromVersion??`?`} → ${e.toVersion}`;return t(`span`,{"data-testid":`addon-job-progress`,className:`inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded shrink-0 ${r.cls}`,title:o,children:[a(i,{className:`w-2.5 h-2.5 ${r.spin?`animate-spin`:``}`}),n(r.labelKey),t(`span`,{className:`font-mono`,children:[`→ `,e.toVersion]})]})}function He(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 Ue(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function We(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(Ue)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
2
2
  `)}function Ge(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 Ke={uninstalled:`uninstalled`,"not-installed":`was not installed`,refused:`REFUSED`,failed:`FAILED`,"pending-reconnect":`offline — removed when it reconnects`};function qe(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)}: ${Ke[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 Je={},Ye=3e4,Xe=`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 Ze({packageName:e,displayName:n,selectedNode:r,hideNodeAction:i,disabled:o}){let{t:s}=J(),c=l(),u=me(),f=R(),p=Ee(Je,{staleTime:Ye}),m=p.data?.installations??[],h=(p.data?.unreachable??[]).map(e=>e.nodeId),g=He(m,e),_=e=>g.find(t=>t.nodeId===e)?.nodeName??(e===r.id?r.name:e),v=M({onSettled:()=>{c.invalidateQueries({queryKey:[[`addons`]]}),c.invalidateQueries({queryKey:[[`addonPages`]]}),c.invalidateQueries({queryKey:[[`capabilities`]]}),c.invalidateQueries({queryKey:[[`nodes`]]})}}),y=async e=>{await f({title:e.success?s(`addons.addonUninstallControls.uninstalled`,`{{displayName}} uninstalled`,{displayName:n}):s(`addons.addonUninstallControls.notEveryNodeWasCleaned`,`{{displayName}}: not every node was cleaned`,{displayName:n}),message:qe(e,_),variant:e.success?`default`:`danger`})},b=async t=>{try{await y(await v.mutateAsync({packageName:e,...t}))}catch(e){await f({title:s(`addons.addonUninstallControls.uninstallFailed`,`Uninstall {{displayName}} failed`,{displayName:n}),message:e instanceof Error?e.message:String(e),variant:`danger`})}},x=async()=>{let e=g.filter(e=>e.nodeId!==r.id);await u({title:s(`addons.addonUninstallControls.uninstallFrom`,`Uninstall {{displayName}} from {{name}}?`,{displayName:n,name:r.name}),message:Ge(n,r.name,e),confirmLabel:s(`addons.addonUninstallControls.uninstall`,`Uninstall`),variant:`danger`})&&await b(r.isHub?{}:{nodeId:r.id})},S=async()=>{let t=(await p.refetch()).data;if(t===void 0){await f({title:s(`addons.addonUninstallControls.cannotListTheNodes`,`Cannot list the nodes`),message:s(`addons.addonUninstallControls.theHubDidNotAnswer`,`The hub did not answer which nodes have this package — nothing was removed.`),variant:`danger`});return}let r=He(t.installations,e);await u({title:s(`addons.addonUninstallControls.uninstallEverywhere`,`Uninstall {{displayName}} everywhere?`,{displayName:n}),message:We(n,r,t.unreachable.map(e=>e.nodeId)),confirmLabel:s(`addons.addonUninstallControls.uninstallFromNodeS`,`Uninstall from {{length}} node(s)`,{length:r.length}),variant:`danger`})&&await b({everywhere:!0})},C=v.isPending||o===!0;return t(`div`,{className:`flex items-center gap-1.5`,children:[i!==!0&&t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),x()},disabled:C,className:Xe,title:s(`addons.addonUninstallControls.uninstallFrom2`,`Uninstall from {{name}}`,{name:r.name}),children:[a(d,{className:`h-3 w-3`}),v.isPending?s(`addons.addonUninstallControls.removing`,`Removing...`):s(`addons.addonUninstallControls.uninstall`,`Uninstall`)]}),(g.length>1||i===!0||h.length>0)&&t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),S()},disabled:C,className:Xe,title:s(`addons.addonUninstallControls.uninstallFromEveryNodeThat`,`Uninstall from every node that has it`),children:[a(ie,{className:`h-3 w-3`}),g.length>0?s(`addons.uninstallControls.everywhereCount`,{count:g.length}):s(`addons.uninstallControls.everywhere`)]})]})}function Qe(e){return typeof e.deprecated==`string`&&e.deprecated.length>0}function $e(e,t){return t?e:e.filter(e=>e.distTags.includes(`latest`)||!Qe(e))}function et(e){return e.length-$e(e,!1).length}c();function tt({packageName:e,currentVersion:n,installSource:r,onInstall:i,onClose:o,onSelect:c,selectedVersion:l}){let{t:d}=J(),f=r===`upload`||r===`local`,[m,h]=s(!1),{data:_,isLoading:y,isError:b}=H({name:e}),S=_?$e(_,m):[],ee=_?et(_):0;return t(`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:[t(`div`,{className:`flex items-center justify-between px-3 py-2 border-b border-border`,children:[a(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle font-medium`,children:d(`addons.versionPicker.versions`,`Versions`)}),a(`button`,{type:`button`,onClick:o,className:`text-foreground-subtle hover:text-foreground`,children:a(x,{className:`h-3 w-3`})})]}),f&&t(`div`,{className:`flex items-start gap-2 px-3 py-2 border-b border-border bg-cyan-500/10 text-[10px]`,children:[a(p,{className:`h-3 w-3 mt-0.5 text-cyan-500 shrink-0`}),t(`div`,{className:`text-cyan-700 dark:text-cyan-200`,children:[a(`span`,{className:`font-semibold`,children:d(`addons.versionPicker.inPlace`,{kind:r===`upload`?d(`addons.versionPicker.uploadedCopy`,`Uploaded copy`):d(`addons.versionPicker.localCopy`,`Local copy`)})}),` `,a(X,{i18nKey:`addons.versionPicker.reinstall`,values:{version:n},components:{mono:a(`span`,{className:`font-mono`})}})]})]}),y&&t(`div`,{className:`flex items-center justify-center gap-2 py-6 text-[10px] text-foreground-subtle`,children:[a(C,{className:`h-3.5 w-3.5 animate-spin`}),d(`addons.versionPicker.loadingVersions`,`Loading versions...`)]}),b&&a(`div`,{className:`px-3 py-4 text-center text-[10px] text-danger`,children:d(`addons.versionPicker.registryError`,`Could not load versions from the registry.`)}),S.length>0&&a(`div`,{className:`max-h-64 overflow-auto divide-y divide-border`,children:S.map(e=>{let r=e.version===n,o=c!==void 0&&e.version===l,s=/-(alpha|beta|rc|dev|canary|next)/i.test(e.version),f=t(u,{children:[a(`span`,{className:`font-mono flex-1 text-left ${r?`text-primary font-semibold`:s?`text-amber-400`:`text-foreground`}`,children:e.version}),r&&a(`span`,{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium bg-primary/10 text-primary`,children:d(`common.current`)}),e.distTags.map(e=>a(`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)),Qe(e)&&a(`span`,{className:`text-[9px] text-red-400 line-through`,children:d(`common.deprecated`)}),a(`span`,{className:`text-[9px] text-foreground-subtle shrink-0`,children:new Date(e.publishedAt).toLocaleDateString()})]});return c?t(`button`,{type:`button`,"aria-label":d(`addons.versionPicker.select`,`Select {{version}}`,{version:e.version}),onClick:()=>c(e.version),className:`w-full flex items-center gap-2 px-3 py-2 text-[11px] ${o?`bg-primary/5`:`hover:bg-surface-hover`} transition-colors`,children:[f,o?a(g,{className:`h-3 w-3 text-primary shrink-0`}):a(`span`,{className:`w-3 shrink-0`})]},e.version):t(`div`,{className:`flex items-center gap-2 px-3 py-2 text-[11px] ${r?`bg-primary/5`:`hover:bg-surface-hover`} transition-colors`,children:[f,a(`button`,{type:`button`,onClick:()=>i(e.version),className:`shrink-0 rounded p-0.5 hover:bg-primary/20 text-foreground-subtle hover:text-primary transition-colors`,title:r?d(`addons.versionPicker.reInstallFromNpm`,`Re-install {{version}} from npm`,{version:e.version}):d(`addons.versionPicker.install`,`Install {{version}}`,{version:e.version}),children:a(v,{className:`h-3 w-3`})})]},e.version)})}),!y&&!b&&_&&_.length===0&&a(`div`,{className:`py-4 text-center text-[10px] text-foreground-subtle`,children:d(`addons.versionPicker.noVersionsFound`,`No versions found`)}),ee>0&&a(P,{type:`button`,variant:`ghost`,size:`sm`,className:`h-auto w-full justify-start rounded-none border-t border-border px-3 py-2 text-left text-[10px] font-normal text-foreground-subtle`,onClick:()=>h(e=>!e),children:m?d(`addons.versionPicker.hideOlder`,`Hide older versions`):d(`addons.versionPicker.showOlder`,`Show older versions ({{count}})`,{count:ee})})]})}c();var nt=`device-export`;function rt(e){return e.capabilities.some(e=>(typeof e==`string`?e:e.name)===nt)}function it(e){return e!==`local`&&e!==`upload`}function at({isBundle:e,installSource:n,addonId:r,iconPath:i,color:o}){let[c,l]=s(!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=r&&i?m(`/api/addon-assets/${r}/${i}`):null,g=!!f&&!c;return t(`div`,{className:`relative flex-shrink-0`,children:[a(`div`,{className:`h-8 w-8 rounded-md flex items-center justify-center ${u?``:d}`,style:u,children:g?a(`img`,{src:f,alt:r,className:`h-4 w-4`,onError:()=>l(!0)}):a(e?h:_,{className:`h-3.5 w-3.5`})}),n===`local`&&a(`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`}),it(n)&&a(`span`,{className:`absolute -top-1 -left-1 w-4 h-4 rounded bg-[#cb3837] flex items-center justify-center -rotate-12 shadow-sm`,children:a(`svg`,{viewBox:`0 0 780 250`,className:`w-[11px] h-[11px]`,children:a(`path`,{fill:`#fff`,d:`M240 250h100V50h100v200h340V0H0v250z`})})}),n===`upload`&&a(`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:a(p,{className:`h-2.5 w-2.5 text-white`})})]})}function ot({version:e,availableUpdate:n,selectedVersion:r,isUpdating:i,installSource:o,disabled:s,onUpdate:c,onOpenPicker:l,children:u}){let{t:d}=J();if(i)return t(`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:[a(C,{className:`h-3 w-3 animate-spin`}),d(`addons.addonCard.updating`,`Updating…`)]});if(n){let i=r??n;return t(`div`,{className:`relative inline-flex items-center gap-1 shrink-0`,children:[c&&t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),c()},disabled:s,className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-semibold border border-blue-500/30 bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors`,title:d(`addons.addonCard.updateTo`,`Update to {{target}}`,{target:i}),children:[a(v,{className:`h-3 w-3`}),d(`addons.addonCard.update`,`Update`)]}),t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),l()},disabled:s,"aria-label":d(`addons.addonCard.selectVersionToInstall`,`Select version to install`),title:d(`addons.addonCard.installedUpdateAvailableSelectedTap`,`Installed {{version}} — update available. Selected {{target}}; tap to choose another version.`,{version:e,target:i}),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:[a(`span`,{className:`font-normal opacity-70`,children:e}),a(`span`,{className:`font-normal opacity-70`,children:`→`}),i,a(ne,{className:`h-3 w-3`})]}),u]})}return t(`div`,{className:`relative inline-flex items-center gap-1 shrink-0`,children:[t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),l()},disabled:s,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`,o===`local`?`border-orange-500/30 bg-orange-500/10 text-orange-400 hover:bg-orange-500/20`:`border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20`].join(` `),title:d(`addons.addonCard.versionTapToViewAll`,`Version {{version}} — tap to view all versions`,{version:e}),children:[e,a(ne,{className:`h-3 w-3 opacity-50`})]}),u]})}function st({addonId:e}){let t=l(),{data:n=`inherit`}=U({addonId:e}),r=F({onSuccess:()=>{t.invalidateQueries({queryKey:[[`addons`,`getAddonAutoUpdate`]]})}});return a(`div`,{className:`flex rounded-lg border border-border overflow-hidden text-[10px] font-medium`,children:[`inherit`,`off`,`latest`,`beta`].map(t=>a(`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 ct={id:`hub`,name:`Hub`,isHub:!0};function lt({addon:e,clusterStatus:n,hideVersion:r,availableUpdate:i,onUpdate:c,isUpdating:d,jobProgress:f,bundle:p,bulkItem:m,disabledByBulk:g,isSystem:_,selectedNode:v}){let{t:y}=J(),[S,C]=s(!1),[ee,T]=s(!1),[re,ie]=s(null);o(()=>{ie(null)},[i]);let O=re??i,[ae,oe]=s(!1),[k,A]=s(!1),[ce,le]=s(`logs`),j=l(),M=Y(),{manifest:N}=e,ue=!p&&!N.protected&&N.removable!==!1,F=!!p,de=p?.displayName??N.name,I=p?.packageName??N.packageName,pe=p?.version??N.packageVersion??N.version,L=p?.installSource??e.installSource,R=p?p.bundle?.description??p.addons[0]?.manifest.description:N.description,z=fe({onSuccess:()=>{j.invalidateQueries({queryKey:[[`addons`]]})}}),me=De({onSuccess:()=>{j.invalidateQueries({queryKey:[[`addons`]]}),j.invalidateQueries({queryKey:[[`addonPages`]]}),j.invalidateQueries({queryKey:[[`capabilities`]]}),j.invalidateQueries({queryKey:[[`integrations`]]})}}),B=se({onSuccess:()=>{j.invalidateQueries({queryKey:[[`addons`]]}),j.invalidateQueries({queryKey:[[`alerts`]]})}}),V=e.health,H=V?.phase===`failed`&&!V.inGracePeriod,ge=H&&V?.nextRetryAt&&!V.retrying,U=Ne(e.process);return t(`div`,{className:`rounded-md border bg-surface overflow-hidden ${H?`border-red-500/50`:`border-border`}`,children:[H&&V&&t(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[a(D,{className:`h-4 w-4 text-danger shrink-0 mt-0.5`}),t(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`text-xs font-semibold text-danger`,children:y(`addons.addonCard.failedToLoad`,{attempt:V.retryCount})}),a(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:V.lastError?.message??y(`addons.addonCard.unknownError`,`Unknown error`)}),ge&&V.nextRetryAt&&a(`div`,{className:`text-[10px] text-foreground-subtle mt-1`,children:y(`addons.addonCard.autoRetryAt`,{time:new Date(V.nextRetryAt).toLocaleTimeString()})})]}),t(`button`,{type:`button`,disabled:B.isPending||V.retrying,onClick:e=>{e.stopPropagation(),B.mutate({packageName:I})},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:y(`addons.addonCard.resetRetryCounterAndForce`,`Reset retry counter and force immediate reload`),children:[a(b,{className:`h-3 w-3 ${B.isPending||V.retrying?`animate-spin`:``}`}),y(`addons.addonCard.retryNow`,`Retry now`)]})]}),U!==null&&t(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[a(D,{className:`h-4 w-4 text-danger shrink-0 mt-0.5`}),t(`div`,{className:`flex-1 min-w-0`,children:[a(`div`,{className:`text-xs font-semibold text-danger`,children:y(`addons.addonCard.processProblem.${U.kind}`)}),U.reason!==void 0&&a(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:U.reason})]})]}),t(`div`,{className:`flex items-start gap-2.5 px-3 py-2`,children:[a(at,{isBundle:F||!!N.components&&N.components.length>1,installSource:L,addonId:F?p.addons[0]?.manifest.id:N.id,iconPath:F?p.bundle?.icon??p.addons[0]?.manifest.icon:N.icon,color:F?p.addons[0]?.manifest.color:N.color}),t(`div`,{className:`flex-1 min-w-0`,children:[t(`div`,{className:`flex items-start justify-between gap-2`,children:[a(`span`,{className:`text-xs font-semibold text-foreground truncate min-w-0`,children:de}),!r&&a(ot,{version:pe,availableUpdate:i,...O===void 0?{}:{selectedVersion:O},isUpdating:d,installSource:L,disabled:g,...c&&O!==void 0?{onUpdate:()=>c(O)}:{},onOpenPicker:()=>T(e=>!e),children:ee&&a(tt,{packageName:I,currentVersion:pe,...L?{installSource:L}:{},...i!==void 0&&O!==void 0?{selectedVersion:O,onSelect:e=>{ie(e),T(!1)}}:{},onInstall:e=>{T(!1),me.mutate({packageName:I,version:e})},onClose:()=>T(!1)})})]}),t(`div`,{className:`flex flex-wrap items-center gap-x-1.5 gap-y-1 mt-0.5`,children:[I!==de&&a(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate max-w-full`,children:I}),F&&t(`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:[a(h,{className:`h-3 w-3`}),p.addons.length]}),_&&t(`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:y(`addons.addonCard.systemPackageUpdatingRestartsThe`,`System package — updating restarts the hub`),children:[a(b,{className:`h-3 w-3`}),y(`addons.addonCard.system`,`System`)]}),m!=null&&a(Fe,{item:m}),f!=null&&a(Ve,{progress:f})]}),R&&a(`p`,{className:`text-[10px] text-foreground-subtle mt-1 line-clamp-1`,children:R}),!F&&e.process&&t(`div`,{className:`flex flex-wrap items-center gap-1.5 mt-1`,children:[a(`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`?y(`addons.addonCard.forked`):y(`addons.addonCard.inProcess`)}),e.process.pid!=null&&t(`span`,{className:`text-[9px] font-mono text-foreground-subtle`,children:[`PID `,e.process.pid]}),a(`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`:U===null?`bg-gray-500/15 text-gray-400`:`bg-red-500/15 text-red-400`}`,children:e.process.state})]})]})]}),!F&&t(`div`,{className:`flex items-center gap-1 px-3 py-1 border-t border-border/50 bg-surface-hover/20`,children:[t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),z.mutate({addonId:N.id})},disabled:z.isPending||g,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:[a(b,{className:`h-3 w-3 ${z.isPending?`animate-spin`:``}`}),y(`addons.addonCard.restart`,`Restart`)]}),t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),oe(e=>!e)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${ae?`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:[a(w,{className:`h-3 w-3`}),y(`addons.addonCard.logs`,`Logs`)]}),!F&&t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),A(!0)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${k?`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:[a(E,{className:`h-3 w-3`}),y(`addons.addonCard.settings`,`Settings`)]}),a(`div`,{className:`flex-1`}),ue&&a(Ze,{packageName:N.packageName,displayName:N.name,selectedNode:v??ct,disabled:g})]}),n&&n.nodes.length>1&&!F&&t(`div`,{className:`border-t border-border px-3 py-1.5 bg-muted/10`,children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle mb-1.5`,children:y(`addons.addonCard.clusterDeployment`,`Cluster Deployment`)}),a(`div`,{className:`space-y-1`,children:n.nodes.map(e=>t(`div`,{className:`flex items-center gap-2 text-[10px]`,children:[a(`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`}`}),a(`span`,{className:`font-medium text-foreground min-w-[60px]`,children:e.name}),a(`span`,{className:`font-mono text-foreground-subtle`,children:e.version}),!e.synced&&e.status!==`offline`&&a(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20`,children:y(`addons.addonCard.outdated`)}),e.status===`offline`&&a(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground`,children:y(`common.offline`)}),e.synced&&e.status!==`offline`&&a(`span`,{className:`text-[9px] text-success`,children:y(`common.synced`)})]},e.nodeId))})]}),ae&&!F&&t(`div`,{className:`border-t border-border`,children:[t(`div`,{className:`flex items-center px-3 py-0.5 bg-surface-hover/20 border-b border-border/50`,children:[t(`div`,{className:`flex rounded border border-border overflow-hidden text-[9px]`,children:[a(`button`,{type:`button`,onClick:()=>le(`logs`),className:`px-2 py-0.5 transition-colors ${ce===`logs`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:y(`addons.addonCard.logs`,`Logs`)}),a(`button`,{type:`button`,onClick:()=>le(`events`),className:`px-2 py-0.5 border-l border-border transition-colors ${ce===`events`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:y(`addons.addonCard.events`,`Events`)})]}),a(`div`,{className:`flex-1`}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),oe(!1)},className:`text-foreground-subtle hover:text-foreground`,children:a(x,{className:`h-3.5 w-3.5`})})]}),ce===`logs`&&a(G,{addonId:N.id,maxHeight:`max-h-64`,showFilters:!1}),ce===`events`&&a(Ce,{addonId:N.id,category:`addon.*`,maxHeight:`max-h-64`})]}),F&&t(u,{children:[a(`button`,{type:`button`,onClick:()=>C(e=>!e),className:`w-full flex items-center justify-center border-t border-border py-1 hover:bg-surface-hover/50 transition-colors`,children:a(S?te:ne,{className:`h-3.5 w-3.5 text-foreground-subtle`})}),S&&a(`div`,{className:`border-t border-border px-2.5 py-1.5 space-y-1.5`,children:p.addons.map(e=>a(lt,{addon:e,hideVersion:!0},e.manifest.id))})]}),k&&!F&&a(K,{open:!0,onOpenChange:e=>!e&&A(!1),children:t(W,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(Te,{children:t(q,{className:`flex items-center gap-2`,children:[a(E,{className:`h-4 w-4 text-primary`}),y(`addons.addonCard.settingsTitle`,{name:de})]})}),t(xe,{className:`space-y-4`,children:[a(`div`,{className:`text-[10px] text-foreground-subtle mb-2`,children:y(`addons.addonCard.clusterWideSettingsOneValue`,`Cluster-wide settings — one value for every node. Per-node settings live under Cluster → the node → Settings.`)}),a(je,{nodeId:null,addonIds:[N.id],level:`global`,fieldScope:`cluster`,emptyMessage:y(`addons.addonCard.thisAddonExposesNoCluster`,`This addon exposes no cluster-wide settings. Anything it can configure is per-node — open it from Cluster → the node → Settings.`)}),rt(N)&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:y(`addons.addonCard.deviceExport`,`Device export`)}),a(ye,{addonId:N.id,onOpenDevice:e=>M(`/devices/${e}`)})]}),it(L)&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:y(`addons.addonCard.autoUpdate`,`Auto-Update`)}),a(st,{addonId:N.id})]}),N.components&&N.components.length>0&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:y(`addons.addonCard.components`,{count:N.components.length})}),a(`div`,{className:`flex flex-wrap gap-1`,children:N.components.map(e=>a(`span`,{className:`text-[10px] rounded bg-background border border-border px-1.5 py-0.5 text-foreground-subtle font-mono`,children:e},e))})]})]}),a(he,{children:a(P,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>A(!1),children:y(`common.close`,`Close`)})})]})})]})}c();var ut=`.tgz,.tar.gz,.zip`;function dt({onUploadSuccess:e}){let{t:r}=J(),[o,c]=s(!1),l=n(null),d=i(async t=>{c(!0);let n=new FormData;n.append(`file`,t);let r=localStorage.getItem(`camstack_admin_token`)??``;try{(await(await fetch(m(`/api/addons/upload`),{method:`POST`,headers:{Authorization:`Bearer ${r}`},body:n})).json()).success&&e()}finally{c(!1)}},[e]);return t(u,{children:[a(`input`,{ref:l,type:`file`,accept:ut,onChange:i(e=>{let t=e.target.files?.[0];t&&d(t),e.target.value=``},[d]),className:`hidden`}),t(`button`,{type:`button`,onClick:()=>l.current?.click(),disabled:o,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:[o?a(C,{className:`w-3.5 h-3.5 animate-spin`}):a(p,{className:`w-3.5 h-3.5`}),o?r(`addons.addonUploadZone.uploading`,`Uploading...`):r(`addons.addonUploadZone.upload`,`Upload`)]})]})}var ft=/```[^\n]*\n([\s\S]*?)```/g;function pt(e){let t=[],n=0;for(let r of e.matchAll(ft)){let i=r.index??0;i>n&&t.push({kind:`text`,body:e.slice(n,i)}),t.push({kind:`code`,body:r[1]??``}),n=i+r[0].length}return n<e.length&&t.push({kind:`text`,body:e.slice(n)}),t}function mt(e){let t=e.trim();return t.startsWith(`https://`)||t.startsWith(`http://`)?t:null}function ht(e,t){let n=[],r=/(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g,i=0,o=0;for(let s of e.matchAll(r)){let r=s.index??0;r>i&&n.push(e.slice(i,r));let c=s[0],l=`${t}-${o}`;if(o+=1,c.startsWith(`**`))n.push(a(`strong`,{children:c.slice(2,-2)},l));else if(c.startsWith("`"))n.push(a(`code`,{className:`font-mono text-[0.9em]`,children:c.slice(1,-1)},l));else{let e=/^\[([^\]]+)\]\(([^)]+)\)$/.exec(c),t=e?.[1]??c,r=e?mt(e[2]??``):null;n.push(r?a(`a`,{href:r,target:`_blank`,rel:`noreferrer noopener`,className:`text-primary underline`,children:t},l):a(`span`,{children:t},l))}i=r+c.length}return i<e.length&&n.push(e.slice(i)),n}function gt(e,t){let n=e.split(`
@@ -1 +1 @@
1
- import{R as e,S as t,et as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{_t as r}from"./src-DntJrWmU.js";import{mr as i}from"./index-C3uCLHv0.js";n();function a({paramName:n=`tab`,defaultSection:a,sections:o,...s}){let[c,l]=i(),u=a??o[0]?.id??``,d=c.get(n),f=o.some(e=>e.id===d)?d??u:u,p=e((e,t)=>{l(r=>{let i=new URLSearchParams(r);for(let e of t)i.delete(e);return i.set(n,e),i},{replace:!0})},[n,l]);return t(r,{...s,paramName:n,defaultSection:a,sections:o,activeSection:f,onSectionChange:p})}export{a as t};
1
+ import{R as e,S as t,et as n}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{_t as r}from"./src-DntJrWmU.js";import{mr as i}from"./index-XXQ5yMw_.js";n();function a({paramName:n=`tab`,defaultSection:a,sections:o,...s}){let[c,l]=i(),u=a??o[0]?.id??``,d=c.get(n),f=o.some(e=>e.id===d)?d??u:u,p=e((e,t)=>{l(r=>{let i=new URLSearchParams(r);for(let e of t)i.delete(e);return i.set(n,e),i},{replace:!0})},[n,l]);return t(r,{...s,paramName:n,defaultSection:a,sections:o,activeSection:f,onSectionChange:p})}export{a as t};
@@ -1,3 +1,3 @@
1
- import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,t as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$r as d,D as f,Di as p,Fn as m,G as h,It as g,L as _,Mi as v,On as y,Or as b,Q as x,Wr as S,Xi as C,Xr as w,Yt as T,Zt as E,bn as D,dn as O,dt as k,fn as A,ji as j,kn as M,or as N,ot as P}from"./player-overlays-Dbv95cvz.js";import{Aa as ee,Ar as F,jr as I}from"./client-DvJxGh2F.js";import{n as L,t as R}from"./send-402PlgqT.js";import{t as te}from"./message-square-plus-C4N5hy0x.js";import{$r as z,$u as ne,Ar as B,Ct as V,Dr as H,Ju as re,Kn as U,Kr as W,Or as G,Sn as K,St as ie,Tn as q,Wn as J,Wr as ae,cr as Y,ed as oe,er as se,fo as X,gt as ce,it as le,kr as ue,mt as de,wn as fe}from"./src-DntJrWmU.js";import{t as Z}from"./i18n-xhwARoF0.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-CUPf26ML.js";import{mr as pe,x as me}from"./index-C3uCLHv0.js";import{t as he}from"./AdminSectionedPage-DtiHBXGC.js";import{t as ge}from"./AdminPage-3JxWocN3.js";c();var _e=`__redacted__`,ve=[`llm`,`listProfiles`],ye=[`llm`,`listProfileKinds`],be=[`llm`,`getDefaults`],xe=[`llm`,`listRuntimeNodes`],Se=[`llm`,`listModelCatalog`],Ce=[`llm`,`getUsage`],we=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],Te=new Map([[`cloud`,d],[`plug`,y],[`cpu`,w],[`server`,O],[`sparkles`,E]]);function Ee(e){return Te.get(e)??v}function De(e){return typeof e==`string`&&e.length>0?e:void 0}function Oe(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function ke(e){return e===!0}function Ae(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var je={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Me(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:Z.t(`ai.appleUnknown`),detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:Z.t(`ai.appleAvailable`),detail:Z.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=je[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:Z.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:Z.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var Ne={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`};function Pe(e){return e.reachable?e.status===void 0?`success`:Ne[e.status.state]:`danger`}function Fe(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Me(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Me(e);t.push({id:`apple`,labelKey:`ai.featureApple`,tone:n.tone,detail:n.labelDefault})}let r=e.status?.vramBytes;return r!==void 0&&r>0&&t.push({id:`gpu`,labelKey:`ai.featureGpu`,tone:`info`,detail:null}),t}function Ie(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:I.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:I.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:I.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:I.idleMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutIdleHint`)}],retry:[{type:`boolean`,key:`retryEnabled`,label:Z.t(`helpers.aiProfileForm.retry`),description:Z.t(`helpers.aiProfileForm.retryHint`)},{type:`number`,key:`retryMaxAttempts`,label:Z.t(`helpers.aiProfileForm.retryMaxAttempts`),min:1,max:5,default:1,showWhen:{field:`retryEnabled`,equals:!0}}],toolsEnabled:[{type:`boolean`,key:`toolsEnabled`,label:Z.t(`helpers.aiProfileForm.toolsEnabled`),description:Z.t(`helpers.aiProfileForm.toolsEnabledHint`)}]}}var Le=[`temperature`,`topP`,`topK`,`maxTokens`,`contextLength`,`systemPrompt`],Re=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function ze(e,t){let n=Ie();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Be(e){let t=ze(e,Le);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function Ve(e){let t=ze(e,Re);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function He(e){return e===null?{}:{temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled}}function Ue(e,t){return{...e.features,...t?.features}}function We(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ge(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?Oe(i[e])??t:n??t,o=e=>r.includes(e)?Oe(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`systemPrompt`)?De(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,I.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,I.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,I.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,I.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:ke(i.retryEnabled),maxAttempts:Oe(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?ke(i.toolsEnabled):t?.toolsEnabled??!1,...s===void 0?{}:{temperature:s},...c===void 0?{}:{topP:c},...l===void 0?{}:{topK:l},...u===void 0?{}:{maxTokens:u},...d===void 0?{}:{contextLength:d},...f===void 0?{}:{systemPrompt:f},providerConfig:n.providerConfig}}var Ke=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function qe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Je({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=P(),[d,f]=o(``),[p,m]=o(null),[h,g]=o(!1),_=s({queryKey:Se,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),v=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:t})}),y=l({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:e=>u.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{g(!0),v.refetch()}}),x=s({queryKey:xe,enabled:b.isPending,refetchInterval:b.isPending?Ke:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,C=n(()=>{let e=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:$(e.sizeBytes),node:t})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[_.data,v.data,p,t,c]),w=e=>{if(e===``){a(null);return}if(e===`custom`){if(p?.ok!==!0)return;a({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},T=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(V,{label:c(`ai.model`,`Model`),required:!0,children:i(re,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:qe(r),options:C,onChange:e=>w(e.target.value)})}),i(V,{label:c(`ai.hfTitle`,`Add a model from Hugging Face`),description:c(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`),children:e(`div`,{className:`flex gap-2`,children:[i(ne,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>f(e.target.value),placeholder:c(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())}}),e(W,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>T(),children:[y.isPending?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(A,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),y.isError&&i(H,{message:y.error instanceof Error?y.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(H,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(W,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>T(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(z,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(z,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(W,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(S,{className:`h-3.5 w-3.5`}),h?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),x!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:x.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:x.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:x.file,index:x.fileIndex,count:x.fileCount,done:$(x.downloadedBytes),total:x.totalBytes===void 0?``:` / ${$(x.totalBytes)}`})})]}),b.isError&&i(H,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)})]})]})}function Ye({value:t,onChange:n}){let{t:r}=Q(),a=P(),o=s({queryKey:xe,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(N,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=Me(a),s=o.nodeId===t;return e(`button`,{type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(z,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function Xe(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Ze({providerConfig:e,onProviderConfigChange:t}){return i(Ye,{value:Xe(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function Qe({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=F.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(Je,{nodeId:Xe(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var $e=new Map([[`ai/apple-node`,Ze],[`ai/managed-model`,Qe]]);function et(e){return $e.get(e)??null}c();function tt({kind:e,className:t}){return i(Ee(e.icon),{className:t,"aria-hidden":!0})}function nt({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>Ae(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(ce,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(ie,{emptyMessage:a(`ai.noKinds`,`No AI provider is installed.`),onPick:e=>{let n=s.get(e);n!==void 0&&t(n)},groups:o.map(e=>({id:e.addonId,label:e.addonId,tiles:e.kinds.map(t=>({key:`${e.addonId}:${t.kind}`,label:t.label,testId:`ai-kind-${t.kind}`,icon:i(tt,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function rt(e){return(e?.sections??[]).flatMap(e=>e.fields)}function it(...e){let t={};for(let n of e)for(let e of rt(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function at(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function ot(e,t){return rt(e).filter(e=>`required`in e&&e.required===!0&&!at(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var st={auth:{key:`ai.listAuth`,fallback:`Credentials refused`},network:{key:`ai.listNetwork`,fallback:`Endpoint unreachable`},unsupported:{key:`ai.listUnsupported`,fallback:`No model list`},invalid:{key:`ai.listInvalid`,fallback:`Connection incomplete`}};function ct(e,t){if(t!==null)return{id:t.model,supportsVision:t.supportsVision};let n=e.modelCatalog===`static`&&e.staticModels?.length===1?e.staticModels?.[0]:void 0;return{id:n?.id??``,supportsVision:Ue(e,n).vision}}function lt({kind:t,existing:r,onSave:a,onCancel:s,onChangeKind:c,saving:d,error:p}){let{t:m}=Q(),h=P(),[g,v]=o(r?.name??t.label),[y,b]=o(()=>r===null?it(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[x,S]=o(()=>He(r)),[w,T]=o(()=>ct(t,r)),[E,O]=o(!1),k=t.providerWidgets??[],A=k.filter(e=>e.placement===`connection`),j=k.find(e=>e.placement===`model`)??null,M=n(()=>[...ee(t.connectionSchema)].some(e=>r?.providerConfig[e]===_e),[r,t.connectionSchema]),F=l({mutationFn:()=>h.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:y,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&T(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ue(t,r).vision}})}}),I=We(t,F.data?.ok===!0?F.data.models:null),L=I.find(e=>e.id===w.id),R=Ue(t,L),te=Be(t.profileFields),B=Ve(t.profileFields),U=ot(t.connectionSchema,y),G=k.some(e=>(e.requires??[]).some(e=>!at(y[e]))),ie=t.modelCatalog===`fetch`&&j===null,q=rt(t.connectionSchema).length>0||A.length>0,ae=e=>{T({id:e,supportsVision:Ue(t,I.find(t=>t.id===e)).vision})},oe=d||g.trim()===``||w.id.trim()===``||U.length>0||G,X=()=>{a(Ge(t,r,{name:g.trim(),model:w.id.trim(),supportsVision:t.visionEditable?w.supportsVision:!1,common:x,providerConfig:y}))},le=r===null?m(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):m(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),ue=e=>{let n=et(e);return n===null?i(H,{variant:`warning`,message:m(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})}):i(n,{descriptor:t,providerConfig:y,onProviderConfigChange:b,model:w,onModelChange:T},e)};return i(ce,{open:!0,onClose:s,title:le,error:p,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[U.length>0&&i(z,{variant:`warning`,children:m(`ai.missingRequired`,`required: {{fields}}`,{fields:U.join(`, `)})}),U.length===0&&G&&i(z,{variant:`warning`,children:m(`ai.completeProvider`,`complete the provider settings`)}),U.length===0&&!G&&w.id.trim()===``&&i(z,{variant:`warning`,children:m(`ai.pickModelFirst`,`pick a model`)}),e(W,{size:`sm`,type:`button`,disabled:oe,onClick:X,children:[d&&i(N,{className:`h-3.5 w-3.5 animate-spin`}),r===null?m(`ai.createProfile`,`Create profile`):m(`ai.saveChanges`,`Save changes`)]})]}),children:e(`div`,{className:_,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`ai-editor-provider`,children:[i(tt,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(z,{variant:`neutral`,children:t.addonId}),c!==void 0&&e(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:c,children:[i(C,{className:`h-3.5 w-3.5`}),m(`ai.changeKind`,`Change type`)]})]}),i(V,{label:m(`ai.name`,`Name`),required:!0,children:i(ne,{id:`ai-profile-name`,"aria-label":m(`ai.name`,`Name`),value:g,onChange:e=>v(e.target.value),placeholder:t.label})}),q&&i(K,{headingId:`ai-editor-connection`,title:m(`ai.sectionConnection`,`Connection`),actions:ie?e(W,{size:`sm`,variant:`secondary`,type:`button`,disabled:F.isPending,onClick:()=>F.mutate(),"data-testid":`ai-verify-models`,children:[F.isPending?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(D,{className:`h-3.5 w-3.5`}),m(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[rt(t.connectionSchema).length>0&&i(Y,{bare:!0,schema:t.connectionSchema,values:y,onChange:b}),A.map(e=>ue(e.id)),M&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:m(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)}),F.data?.ok===!0&&i(z,{variant:`success`,"data-testid":`ai-models-found`,children:m(`ai.modelsFound`,`{{count}} models found`,{count:F.data.models.length})}),F.data?.ok===!1&&i(H,{title:m(st[F.data.code]?.key??`ai.listNetwork`,st[F.data.code]?.fallback??`Endpoint unreachable`),message:F.data.message}),F.isError&&i(H,{message:F.error instanceof Error?F.error.message:m(`common.error`,`Error`)})]})}),i(K,{headingId:`ai-editor-model`,title:m(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${f} space-y-3`,children:[j===null?e(u,{children:[I.length>0&&i(re,{id:`ai-model-pick`,"aria-label":m(`ai.selectModel`,`Select a model…`),value:L===void 0?``:L.id,options:[{value:``,label:m(`ai.selectModel`,`Select a model…`)},...I.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&ae(e.target.value)}}),i(V,{label:m(`ai.customModel`,`Model id`),description:m(`ai.customModelHint`,`Pick one from the list, or type any model id the provider accepts.`),required:!0,children:i(ne,{id:`ai-model-id`,"aria-label":m(`ai.customModel`,`Model id`),value:w.id,onChange:e=>T({...w,id:e.target.value}),placeholder:I[0]?.id??`model-id`})})]}):ue(j.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(w.supportsVision||!t.visionEditable&&R.vision)&&i(z,{variant:`info`,children:m(`ai.featureVision`,`vision`)}),R.tools&&i(z,{variant:`neutral`,children:m(`ai.featureTools`,`tools`)}),R.streaming&&i(z,{variant:`neutral`,children:m(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(V,{orientation:`horizontal`,label:m(`ai.supportsVision`,`Supports vision`),description:m(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(J,{checked:w.supportsVision,onCheckedChange:e=>T({...w,supportsVision:e}),"aria-label":m(`ai.supportsVision`,`Supports vision`)})})]})}),te!==null&&i(K,{headingId:`ai-editor-generation`,title:m(`ai.sectionGeneration`,`Generation`),children:i(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:i(Y,{bare:!0,schema:te,values:x,onChange:S})})}),(B!==null||t.advancedSchema!==void 0)&&i(se,{expanded:E,onExpandedChange:O,header:i(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:m(`ai.sectionAdvanced`,`Advanced`)}),children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[B!==null&&i(Y,{bare:!0,schema:B,values:x,onChange:S}),t.advancedSchema!==void 0&&i(Y,{bare:!0,schema:t.advancedSchema,values:y,onChange:b})]})})]})})}c();function ut(t){return[{key:`name`,header:t.t(`ai.colProfile`,`Profile`),render:n=>{let r=t.kindByName.get(n.kind);return e(`span`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:r?.label??n.kind,children:r===void 0?i(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):i(tt,{kind:r,className:`h-4 w-4 text-foreground-subtle`})}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block truncate font-medium text-foreground`,children:n.name}),t.testResult?.id===n.id&&i(`span`,{className:`block truncate ${t.testResult.ok?`text-success`:`text-danger`}`,children:t.testResult.text})]})]})}},{key:`kind`,header:t.t(`ai.colKind`,`Kind`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground-muted`,children:t.kindByName.get(e.kind)?.label??e.kind})},{key:`model`,header:t.t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:t.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:e=>e.supportsVision?i(z,{variant:`info`,style:`outline`,children:t.t(`ai.vision`,`vision`)}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:t.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?i(z,{variant:`default`,children:e.providerConfig.nodeId}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:t.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:e=>i(J,{checked:e.enabled,onCheckedChange:()=>t.onToggle(e),"aria-label":Z.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:e.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[i(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest(n),"aria-label":t.t(`ai.test`,`Test`),title:t.t(`ai.test`,`Test`),children:t.testingId===n.id?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(R,{className:`h-3.5 w-3.5`})}),i(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:!t.kindByName.has(n.kind),onClick:()=>t.onEdit(n),"aria-label":t.t(`common.edit`,`Edit`),title:t.t(`common.edit`,`Edit`),children:i(m,{className:`h-3.5 w-3.5`})}),i(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDelete(n),"aria-label":t.t(`common.delete`,`Delete`),title:t.t(`common.delete`,`Delete`),children:i(g,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function dt(){let{t}=Q(),c=P(),{state:u,openEdit:d,close:p}=de(),m=ae(),[h,g]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:ve,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),C=s({queryKey:ye,queryFn:async()=>(await c.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),w=()=>{S.refetch()},T=r(()=>{g(null),x(null),p()},[p]);a(()=>{u.mode===`closed`&&g(null)},[u.mode]);let D=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{T(),w()},onError:e=>x(e instanceof Error?e.message:t(`ai.saveFailed`,`Save failed`))}),O=l({mutationFn:e=>c.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:w}),k=l({mutationFn:e=>c.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>y({id:t.id,ok:e.ok,text:e.ok?Z.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),A=S.data??[],j=n(()=>C.data??[],[C.data]),M=n(()=>{let e=new Map;for(let t of j)e.set(t.kind,t);return e},[j]),N=u.mode===`edit`?A.find(e=>e.id===u.id)??null:null,ee=N===null?null:M.get(N.kind)??null,F=u.mode===`new`&&h===null,I=u.mode===`new`?h:ee,L=u.mode===`edit`?N:null,R=I!==null&&(u.mode===`new`||L!==null),te=async e=>{await m({title:t(`ai.deleteProfileTitle`,`Delete profile?`),message:t(`ai.deleteProfileMessage`,`Delete "{{name}}". Features that name it will no longer get an answer from it.`,{name:e.name}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&O.mutate(e)};return e(`div`,{className:_,children:[i(ft,{profiles:A}),i(K,{headingId:`ai-profiles-list`,title:t(`ai.profilesList`,`Profiles`),children:S.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-profiles-loading`,children:[i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`})]}):S.isError?i(`div`,{className:f,children:i(H,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:t(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):A.length===0?i(G,{icon:E,title:t(`ai.noProfilesTitle`,`No AI profiles yet`),description:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):i(fe,{columns:ut({kindByName:M,testResult:v,testingId:k.isPending?k.variables?.id??null:null,t,onToggle:e=>D.mutate({...e,enabled:!e.enabled}),onTest:e=>k.mutate(e),onEdit:e=>{M.has(e.kind)&&(x(null),g(null),d(e.id))},onDelete:e=>void te(e)}),rows:A,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:q})}),F&&i(nt,{kinds:j,onCancel:T,onPick:e=>{x(null),g(e)}}),R&&I!==null&&i(lt,{kind:I,existing:L,saving:D.isPending,error:b,onSave:e=>D.mutate(e),onCancel:T,...u.mode===`new`?{onChangeKind:()=>{x(null),g(null)}}:{}})]})}function ft({profiles:t}){let{t:n}=Q(),r=P(),a=s({queryKey:be,queryFn:()=>r.trpcClient.llm.getDefaults.query({})}),o=l({mutationFn:e=>r.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?n(`ai.defaultVision`,`Default vision profile`):n(`ai.defaultText`,`Default text profile`);return i(K,{headingId:`ai-profiles-defaults`,title:n(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:we.map(({purpose:r,visionOnly:a})=>{let s=a?t.filter(e=>e.supportsVision):t,l=c(r),d=t.find(e=>e.id===l);return e(`div`,{children:[i(U,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(re,{id:`llm-default-${r}`,"aria-label":u(r),value:l,onChange:e=>o.mutate({purpose:r,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:n(`ai.none`,`None`)},...l!==``&&!s.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...s.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:n(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:n(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},r)})})})}c();var pt=5e3;function mt(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ht(){let{t}=Q(),r=P(),a=s({queryKey:xe,refetchInterval:pt,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(z,{variant:Pe(n),children:n.reachable?n.status?.state??t(`ai.ready`,`ready`):t(`ai.unreachable`,`unreachable`)}),n.status?.downloadProgress!==void 0&&i(z,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:mt(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeatures`,`Features`),render:n=>{let r=Fe(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(z,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(K,{headingId:`ai-runtimes-list`,title:t(`ai.runtimesList`,`Nodes`),children:a.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:f,children:i(H,{title:t(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:a.error instanceof Error?a.error.message:t(`common.error`,`Error`),onRetry:()=>void a.refetch()})}):c.length===0?i(G,{icon:O,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(fe,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:q})})}var gt=x(`/addon/ai/test-chat`),_t=x(`/addon/ai/test-chat/chats`),vt=6e5;function yt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),vt)}function bt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xt(e){if(!bt(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var St=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Ct(e){let t;try{t=JSON.parse(e)}catch{return null}if(!bt(t))return null;switch(t.kind){case`status`:{let e=St.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:xt(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:Z.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*wt(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
1
+ import{C as e,J as t,K as n,R as r,S as i,V as a,Y as o,a as s,et as c,t as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$r as d,D as f,Di as p,Fn as m,G as h,It as g,L as _,Mi as v,On as y,Or as b,Q as x,Wr as S,Xi as C,Xr as w,Yt as T,Zt as E,bn as D,dn as O,dt as k,fn as A,ji as j,kn as M,or as N,ot as P}from"./player-overlays-Dbv95cvz.js";import{Aa as ee,Ar as F,jr as I}from"./client-DvJxGh2F.js";import{n as L,t as R}from"./send-402PlgqT.js";import{t as te}from"./message-square-plus-C4N5hy0x.js";import{$r as z,$u as ne,Ar as B,Ct as V,Dr as H,Ju as re,Kn as U,Kr as W,Or as G,Sn as K,St as ie,Tn as q,Wn as J,Wr as ae,cr as Y,ed as oe,er as se,fo as X,gt as ce,it as le,kr as ue,mt as de,wn as fe}from"./src-DntJrWmU.js";import{t as Z}from"./i18n-D0o08mg-.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-CUPf26ML.js";import{mr as pe,x as me}from"./index-XXQ5yMw_.js";import{t as he}from"./AdminSectionedPage-BByl6Zss.js";import{t as ge}from"./AdminPage-3JxWocN3.js";c();var _e=`__redacted__`,ve=[`llm`,`listProfiles`],ye=[`llm`,`listProfileKinds`],be=[`llm`,`getDefaults`],xe=[`llm`,`listRuntimeNodes`],Se=[`llm`,`listModelCatalog`],Ce=[`llm`,`getUsage`],we=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],Te=new Map([[`cloud`,d],[`plug`,y],[`cpu`,w],[`server`,O],[`sparkles`,E]]);function Ee(e){return Te.get(e)??v}function De(e){return typeof e==`string`&&e.length>0?e:void 0}function Oe(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function ke(e){return e===!0}function Ae(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var je={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Me(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:Z.t(`ai.appleUnknown`),detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:Z.t(`ai.appleAvailable`),detail:Z.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=je[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:Z.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:Z.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var Ne={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`};function Pe(e){return e.reachable?e.status===void 0?`success`:Ne[e.status.state]:`danger`}function Fe(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Me(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Me(e);t.push({id:`apple`,labelKey:`ai.featureApple`,tone:n.tone,detail:n.labelDefault})}let r=e.status?.vramBytes;return r!==void 0&&r>0&&t.push({id:`gpu`,labelKey:`ai.featureGpu`,tone:`info`,detail:null}),t}function Ie(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:I.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:I.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:I.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:I.idleMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutIdleHint`)}],retry:[{type:`boolean`,key:`retryEnabled`,label:Z.t(`helpers.aiProfileForm.retry`),description:Z.t(`helpers.aiProfileForm.retryHint`)},{type:`number`,key:`retryMaxAttempts`,label:Z.t(`helpers.aiProfileForm.retryMaxAttempts`),min:1,max:5,default:1,showWhen:{field:`retryEnabled`,equals:!0}}],toolsEnabled:[{type:`boolean`,key:`toolsEnabled`,label:Z.t(`helpers.aiProfileForm.toolsEnabled`),description:Z.t(`helpers.aiProfileForm.toolsEnabledHint`)}]}}var Le=[`temperature`,`topP`,`topK`,`maxTokens`,`contextLength`,`systemPrompt`],Re=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function ze(e,t){let n=Ie();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Be(e){let t=ze(e,Le);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function Ve(e){let t=ze(e,Re);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function He(e){return e===null?{}:{temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled}}function Ue(e,t){return{...e.features,...t?.features}}function We(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ge(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?Oe(i[e])??t:n??t,o=e=>r.includes(e)?Oe(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`systemPrompt`)?De(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,I.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,I.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,I.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,I.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:ke(i.retryEnabled),maxAttempts:Oe(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?ke(i.toolsEnabled):t?.toolsEnabled??!1,...s===void 0?{}:{temperature:s},...c===void 0?{}:{topP:c},...l===void 0?{}:{topK:l},...u===void 0?{}:{maxTokens:u},...d===void 0?{}:{contextLength:d},...f===void 0?{}:{systemPrompt:f},providerConfig:n.providerConfig}}var Ke=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function qe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function Je({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=P(),[d,f]=o(``),[p,m]=o(null),[h,g]=o(!1),_=s({queryKey:Se,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),v=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:t})}),y=l({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:e=>u.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{g(!0),v.refetch()}}),x=s({queryKey:xe,enabled:b.isPending,refetchInterval:b.isPending?Ke:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,C=n(()=>{let e=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:$(e.sizeBytes),node:t})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[_.data,v.data,p,t,c]),w=e=>{if(e===``){a(null);return}if(e===`custom`){if(p?.ok!==!0)return;a({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},T=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(V,{label:c(`ai.model`,`Model`),required:!0,children:i(re,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:qe(r),options:C,onChange:e=>w(e.target.value)})}),i(V,{label:c(`ai.hfTitle`,`Add a model from Hugging Face`),description:c(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`),children:e(`div`,{className:`flex gap-2`,children:[i(ne,{"aria-label":c(`ai.hfTitle`,`Add a model from Hugging Face`),value:d,onChange:e=>f(e.target.value),placeholder:c(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())}}),e(W,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>T(),children:[y.isPending?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(A,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),y.isError&&i(H,{message:y.error instanceof Error?y.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(H,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(W,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>T(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(z,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(z,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(W,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(S,{className:`h-3.5 w-3.5`}),h?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),x!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:x.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:x.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:x.file,index:x.fileIndex,count:x.fileCount,done:$(x.downloadedBytes),total:x.totalBytes===void 0?``:` / ${$(x.totalBytes)}`})})]}),b.isError&&i(H,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)})]})]})}function Ye({value:t,onChange:n}){let{t:r}=Q(),a=P(),o=s({queryKey:xe,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(N,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=Me(a),s=o.nodeId===t;return e(`button`,{type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(z,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function Xe(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function Ze({providerConfig:e,onProviderConfigChange:t}){return i(Ye,{value:Xe(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function Qe({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=F.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(Je,{nodeId:Xe(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var $e=new Map([[`ai/apple-node`,Ze],[`ai/managed-model`,Qe]]);function et(e){return $e.get(e)??null}c();function tt({kind:e,className:t}){return i(Ee(e.icon),{className:t,"aria-hidden":!0})}function nt({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>Ae(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(ce,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(ie,{emptyMessage:a(`ai.noKinds`,`No AI provider is installed.`),onPick:e=>{let n=s.get(e);n!==void 0&&t(n)},groups:o.map(e=>({id:e.addonId,label:e.addonId,tiles:e.kinds.map(t=>({key:`${e.addonId}:${t.kind}`,label:t.label,testId:`ai-kind-${t.kind}`,icon:i(tt,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function rt(e){return(e?.sections??[]).flatMap(e=>e.fields)}function it(...e){let t={};for(let n of e)for(let e of rt(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function at(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function ot(e,t){return rt(e).filter(e=>`required`in e&&e.required===!0&&!at(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var st={auth:{key:`ai.listAuth`,fallback:`Credentials refused`},network:{key:`ai.listNetwork`,fallback:`Endpoint unreachable`},unsupported:{key:`ai.listUnsupported`,fallback:`No model list`},invalid:{key:`ai.listInvalid`,fallback:`Connection incomplete`}};function ct(e,t){if(t!==null)return{id:t.model,supportsVision:t.supportsVision};let n=e.modelCatalog===`static`&&e.staticModels?.length===1?e.staticModels?.[0]:void 0;return{id:n?.id??``,supportsVision:Ue(e,n).vision}}function lt({kind:t,existing:r,onSave:a,onCancel:s,onChangeKind:c,saving:d,error:p}){let{t:m}=Q(),h=P(),[g,v]=o(r?.name??t.label),[y,b]=o(()=>r===null?it(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[x,S]=o(()=>He(r)),[w,T]=o(()=>ct(t,r)),[E,O]=o(!1),k=t.providerWidgets??[],A=k.filter(e=>e.placement===`connection`),j=k.find(e=>e.placement===`model`)??null,M=n(()=>[...ee(t.connectionSchema)].some(e=>r?.providerConfig[e]===_e),[r,t.connectionSchema]),F=l({mutationFn:()=>h.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:y,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&T(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ue(t,r).vision}})}}),I=We(t,F.data?.ok===!0?F.data.models:null),L=I.find(e=>e.id===w.id),R=Ue(t,L),te=Be(t.profileFields),B=Ve(t.profileFields),U=ot(t.connectionSchema,y),G=k.some(e=>(e.requires??[]).some(e=>!at(y[e]))),ie=t.modelCatalog===`fetch`&&j===null,q=rt(t.connectionSchema).length>0||A.length>0,ae=e=>{T({id:e,supportsVision:Ue(t,I.find(t=>t.id===e)).vision})},oe=d||g.trim()===``||w.id.trim()===``||U.length>0||G,X=()=>{a(Ge(t,r,{name:g.trim(),model:w.id.trim(),supportsVision:t.visionEditable?w.supportsVision:!1,common:x,providerConfig:y}))},le=r===null?m(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):m(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),ue=e=>{let n=et(e);return n===null?i(H,{variant:`warning`,message:m(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})}):i(n,{descriptor:t,providerConfig:y,onProviderConfigChange:b,model:w,onModelChange:T},e)};return i(ce,{open:!0,onClose:s,title:le,error:p,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[U.length>0&&i(z,{variant:`warning`,children:m(`ai.missingRequired`,`required: {{fields}}`,{fields:U.join(`, `)})}),U.length===0&&G&&i(z,{variant:`warning`,children:m(`ai.completeProvider`,`complete the provider settings`)}),U.length===0&&!G&&w.id.trim()===``&&i(z,{variant:`warning`,children:m(`ai.pickModelFirst`,`pick a model`)}),e(W,{size:`sm`,type:`button`,disabled:oe,onClick:X,children:[d&&i(N,{className:`h-3.5 w-3.5 animate-spin`}),r===null?m(`ai.createProfile`,`Create profile`):m(`ai.saveChanges`,`Save changes`)]})]}),children:e(`div`,{className:_,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`ai-editor-provider`,children:[i(tt,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(z,{variant:`neutral`,children:t.addonId}),c!==void 0&&e(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:c,children:[i(C,{className:`h-3.5 w-3.5`}),m(`ai.changeKind`,`Change type`)]})]}),i(V,{label:m(`ai.name`,`Name`),required:!0,children:i(ne,{id:`ai-profile-name`,"aria-label":m(`ai.name`,`Name`),value:g,onChange:e=>v(e.target.value),placeholder:t.label})}),q&&i(K,{headingId:`ai-editor-connection`,title:m(`ai.sectionConnection`,`Connection`),actions:ie?e(W,{size:`sm`,variant:`secondary`,type:`button`,disabled:F.isPending,onClick:()=>F.mutate(),"data-testid":`ai-verify-models`,children:[F.isPending?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(D,{className:`h-3.5 w-3.5`}),m(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[rt(t.connectionSchema).length>0&&i(Y,{bare:!0,schema:t.connectionSchema,values:y,onChange:b}),A.map(e=>ue(e.id)),M&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:m(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)}),F.data?.ok===!0&&i(z,{variant:`success`,"data-testid":`ai-models-found`,children:m(`ai.modelsFound`,`{{count}} models found`,{count:F.data.models.length})}),F.data?.ok===!1&&i(H,{title:m(st[F.data.code]?.key??`ai.listNetwork`,st[F.data.code]?.fallback??`Endpoint unreachable`),message:F.data.message}),F.isError&&i(H,{message:F.error instanceof Error?F.error.message:m(`common.error`,`Error`)})]})}),i(K,{headingId:`ai-editor-model`,title:m(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${f} space-y-3`,children:[j===null?e(u,{children:[I.length>0&&i(re,{id:`ai-model-pick`,"aria-label":m(`ai.selectModel`,`Select a model…`),value:L===void 0?``:L.id,options:[{value:``,label:m(`ai.selectModel`,`Select a model…`)},...I.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&ae(e.target.value)}}),i(V,{label:m(`ai.customModel`,`Model id`),description:m(`ai.customModelHint`,`Pick one from the list, or type any model id the provider accepts.`),required:!0,children:i(ne,{id:`ai-model-id`,"aria-label":m(`ai.customModel`,`Model id`),value:w.id,onChange:e=>T({...w,id:e.target.value}),placeholder:I[0]?.id??`model-id`})})]}):ue(j.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(w.supportsVision||!t.visionEditable&&R.vision)&&i(z,{variant:`info`,children:m(`ai.featureVision`,`vision`)}),R.tools&&i(z,{variant:`neutral`,children:m(`ai.featureTools`,`tools`)}),R.streaming&&i(z,{variant:`neutral`,children:m(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(V,{orientation:`horizontal`,label:m(`ai.supportsVision`,`Supports vision`),description:m(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(J,{checked:w.supportsVision,onCheckedChange:e=>T({...w,supportsVision:e}),"aria-label":m(`ai.supportsVision`,`Supports vision`)})})]})}),te!==null&&i(K,{headingId:`ai-editor-generation`,title:m(`ai.sectionGeneration`,`Generation`),children:i(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:i(Y,{bare:!0,schema:te,values:x,onChange:S})})}),(B!==null||t.advancedSchema!==void 0)&&i(se,{expanded:E,onExpandedChange:O,header:i(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:m(`ai.sectionAdvanced`,`Advanced`)}),children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[B!==null&&i(Y,{bare:!0,schema:B,values:x,onChange:S}),t.advancedSchema!==void 0&&i(Y,{bare:!0,schema:t.advancedSchema,values:y,onChange:b})]})})]})})}c();function ut(t){return[{key:`name`,header:t.t(`ai.colProfile`,`Profile`),render:n=>{let r=t.kindByName.get(n.kind);return e(`span`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:r?.label??n.kind,children:r===void 0?i(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):i(tt,{kind:r,className:`h-4 w-4 text-foreground-subtle`})}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block truncate font-medium text-foreground`,children:n.name}),t.testResult?.id===n.id&&i(`span`,{className:`block truncate ${t.testResult.ok?`text-success`:`text-danger`}`,children:t.testResult.text})]})]})}},{key:`kind`,header:t.t(`ai.colKind`,`Kind`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground-muted`,children:t.kindByName.get(e.kind)?.label??e.kind})},{key:`model`,header:t.t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:t.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:e=>e.supportsVision?i(z,{variant:`info`,style:`outline`,children:t.t(`ai.vision`,`vision`)}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:t.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?i(z,{variant:`default`,children:e.providerConfig.nodeId}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:t.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:e=>i(J,{checked:e.enabled,onCheckedChange:()=>t.onToggle(e),"aria-label":Z.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:e.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[i(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest(n),"aria-label":t.t(`ai.test`,`Test`),title:t.t(`ai.test`,`Test`),children:t.testingId===n.id?i(N,{className:`h-3.5 w-3.5 animate-spin`}):i(R,{className:`h-3.5 w-3.5`})}),i(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:!t.kindByName.has(n.kind),onClick:()=>t.onEdit(n),"aria-label":t.t(`common.edit`,`Edit`),title:t.t(`common.edit`,`Edit`),children:i(m,{className:`h-3.5 w-3.5`})}),i(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDelete(n),"aria-label":t.t(`common.delete`,`Delete`),title:t.t(`common.delete`,`Delete`),children:i(g,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function dt(){let{t}=Q(),c=P(),{state:u,openEdit:d,close:p}=de(),m=ae(),[h,g]=o(null),[v,y]=o(null),[b,x]=o(null),S=s({queryKey:ve,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),C=s({queryKey:ye,queryFn:async()=>(await c.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),w=()=>{S.refetch()},T=r(()=>{g(null),x(null),p()},[p]);a(()=>{u.mode===`closed`&&g(null)},[u.mode]);let D=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{T(),w()},onError:e=>x(e instanceof Error?e.message:t(`ai.saveFailed`,`Save failed`))}),O=l({mutationFn:e=>c.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:w}),k=l({mutationFn:e=>c.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>y({id:t.id,ok:e.ok,text:e.ok?Z.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),A=S.data??[],j=n(()=>C.data??[],[C.data]),M=n(()=>{let e=new Map;for(let t of j)e.set(t.kind,t);return e},[j]),N=u.mode===`edit`?A.find(e=>e.id===u.id)??null:null,ee=N===null?null:M.get(N.kind)??null,F=u.mode===`new`&&h===null,I=u.mode===`new`?h:ee,L=u.mode===`edit`?N:null,R=I!==null&&(u.mode===`new`||L!==null),te=async e=>{await m({title:t(`ai.deleteProfileTitle`,`Delete profile?`),message:t(`ai.deleteProfileMessage`,`Delete "{{name}}". Features that name it will no longer get an answer from it.`,{name:e.name}),confirmLabel:t(`common.delete`,`Delete`),variant:`danger`})&&O.mutate(e)};return e(`div`,{className:_,children:[i(ft,{profiles:A}),i(K,{headingId:`ai-profiles-list`,title:t(`ai.profilesList`,`Profiles`),children:S.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-profiles-loading`,children:[i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`})]}):S.isError?i(`div`,{className:f,children:i(H,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:t(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):A.length===0?i(G,{icon:E,title:t(`ai.noProfilesTitle`,`No AI profiles yet`),description:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):i(fe,{columns:ut({kindByName:M,testResult:v,testingId:k.isPending?k.variables?.id??null:null,t,onToggle:e=>D.mutate({...e,enabled:!e.enabled}),onTest:e=>k.mutate(e),onEdit:e=>{M.has(e.kind)&&(x(null),g(null),d(e.id))},onDelete:e=>void te(e)}),rows:A,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:q})}),F&&i(nt,{kinds:j,onCancel:T,onPick:e=>{x(null),g(e)}}),R&&I!==null&&i(lt,{kind:I,existing:L,saving:D.isPending,error:b,onSave:e=>D.mutate(e),onCancel:T,...u.mode===`new`?{onChangeKind:()=>{x(null),g(null)}}:{}})]})}function ft({profiles:t}){let{t:n}=Q(),r=P(),a=s({queryKey:be,queryFn:()=>r.trpcClient.llm.getDefaults.query({})}),o=l({mutationFn:e=>r.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?n(`ai.defaultVision`,`Default vision profile`):n(`ai.defaultText`,`Default text profile`);return i(K,{headingId:`ai-profiles-defaults`,title:n(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:we.map(({purpose:r,visionOnly:a})=>{let s=a?t.filter(e=>e.supportsVision):t,l=c(r),d=t.find(e=>e.id===l);return e(`div`,{children:[i(U,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(re,{id:`llm-default-${r}`,"aria-label":u(r),value:l,onChange:e=>o.mutate({purpose:r,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:n(`ai.none`,`None`)},...l!==``&&!s.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...s.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:n(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:n(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},r)})})})}c();var pt=5e3;function mt(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ht(){let{t}=Q(),r=P(),a=s({queryKey:xe,refetchInterval:pt,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(z,{variant:Pe(n),children:n.reachable?n.status?.state??t(`ai.ready`,`ready`):t(`ai.unreachable`,`unreachable`)}),n.status?.downloadProgress!==void 0&&i(z,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:mt(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeatures`,`Features`),render:n=>{let r=Fe(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(z,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(K,{headingId:`ai-runtimes-list`,title:t(`ai.runtimesList`,`Nodes`),children:a.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-runtimes-loading`,children:[i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:f,children:i(H,{title:t(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:a.error instanceof Error?a.error.message:t(`common.error`,`Error`),onRetry:()=>void a.refetch()})}):c.length===0?i(G,{icon:O,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(fe,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:q})})}var gt=x(`/addon/ai/test-chat`),_t=x(`/addon/ai/test-chat/chats`),vt=6e5;function yt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),vt)}function bt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xt(e){if(!bt(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var St=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function Ct(e){let t;try{t=JSON.parse(e)}catch{return null}if(!bt(t))return null;switch(t.kind){case`status`:{let e=St.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:xt(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:Z.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*wt(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
2
  `);for(;a>=0;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length>0){let t=Ct(e);t!==null&&(yield t)}a=r.indexOf(`
3
3
  `)}}let e=r.trim();if(e.length>0){let t=Ct(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Tt(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Et(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Dt(e){return e.messages.map((t,n)=>{let r=t.mediaSent??void 0;return{id:`${e.id}-${String(n)}`,role:t.role,content:t.content,...t.attachment===void 0?{}:{attachmentRef:t.attachment,attachmentKind:t.attachment.kind},...r===void 0?{}:{attachment:r}}})}function Ot(e){let t=e.sizeBytes<1024*1024?`${(e.sizeBytes/1024).toFixed(0)} KB`:`${(e.sizeBytes/(1024*1024)).toFixed(1)} MB`,n=[e.kind===`snapshot`?`camera snapshot`:`track best-shot`,t];return e.mediaKind!==void 0&&n.push(e.mediaKind),e.capturedAt!==void 0&&n.push(new Date(e.capturedAt).toLocaleTimeString()),n.join(` · `)}function kt(e,t){switch(e){case`resolving-image`:return Z.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return Z.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?Z.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):Z.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return Z.t(`helpers.aiTestChat.phaseAnswering`)}}c();var At=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],jt=360*60*1e3,Mt=40,Nt=160,Pt={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Ft(){let{t:c}=Q(),l=P(),[u,d]=o(``),[m,h]=o(``),[v,y]=o(``),[b,x]=o([]),[S,C]=o(null),[w,E]=o(`none`),[D,O]=o(`throwaway`),[A,M]=o(null),[N,ee]=o([]),[F,I]=o(null),[L,z]=o(null),B=t(null);a(()=>()=>B.current?.abort(),[]);let V=r(async()=>{let e=await fetch(_t,{credentials:`same-origin`});e.ok&&ee((await e.json()).chats??[])},[]);a(()=>{D===`persistent`&&V()},[D,V]);let G=s({queryKey:ve,queryFn:()=>l.trpcClient.llm.listProfiles.query({})}),ie=n(()=>(G.data??[]).filter(e=>e.enabled),[G.data]),q=ie.find(e=>e.id===u)??null,J=L!==null,ae=r(async(e,t)=>{let n=new AbortController;B.current=n,I(null);let r=yt(q??{});z({...Pt,firstTokenTimeoutMs:r??0});let i=``,a=null,o,s=null,l=null,d;try{let c=await fetch(gt,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:n.signal,body:JSON.stringify({profileId:u,messages:e,...m.trim()===``?{}:{system:m.trim()},...t===void 0?{}:{attachment:t},...r===void 0?{}:{firstTokenTimeoutMs:r},...D===`persistent`?{persist:!0,...A===null?{}:{conversationId:A}}:{}})});if(!c.ok||c.body===null){let e=await c.text().catch(()=>``);throw Error(e.length>0?e:`HTTP ${String(c.status)}`)}for await(let e of wt(c.body))switch(e.kind){case`status`:z(t=>({...t??Pt,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,z(t=>({...t??Pt,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,z(e=>({...e??Pt,text:i}));break;case`done`:l={outputTokens:e.outputTokens,latencyMs:e.latencyMs},d=e.conversationId;break;case`error`:s=`${e.code}: ${e.message}`;break}}catch(e){n.signal.aborted||I(e instanceof Error?e.message:c(`common.error`,`Error`))}finally{B.current=null,z(null)}d!==void 0&&(M(d),V());let f=n.signal.aborted&&i.length>0;s===null&&i.length===0&&!f||x(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:s??i,...s===null?{}:{failed:!0},...a===null?{}:{attachment:a},...o!==void 0&&s===null?{model:o}:{},...l===null?{}:l}])},[D,A,q,u,V,m,c]),Y=r(()=>{let e=v.trim();if(e===``||u===``||J)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...S===null?{}:{attachmentLabel:S.label,attachmentKind:S.ref.kind}},n=[...b,t];x(n),y(``);let r=S?.ref;C(null),E(`none`),ae(D===`persistent`&&A!==null?[{role:`user`,content:e}]:Tt(n),r)},[D,A,v,S,u,ae,J,b]),se=()=>B.current?.abort(),X=()=>{B.current?.abort(),x([]),C(null),y(``),I(null),z(null),M(null)},ce=async e=>{B.current?.abort();let t=await fetch(`${_t}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();M(e),x(Dt(n)),z(null),I(null)};return e(`div`,{className:_,children:[i(K,{headingId:`ai-test-setup`,title:c(`ai.testSetup`,`Setup`),children:e(`div`,{className:`${f} space-y-3`,children:[e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[i(U,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:c(`ai.profile`,`Profile`)}),i(re,{id:`ai-test-profile`,value:u,onChange:e=>d(e.target.value),options:[{value:``,label:c(`ai.selectProfile`,`Select a profile…`)},...ie.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),ie.length===0&&!G.isLoading&&i(`p`,{className:`mt-1 text-xs text-foreground-subtle`,children:c(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),e(`div`,{children:[i(U,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:c(`ai.systemPrompt`,`System prompt (optional)`)}),i(ne,{id:`ai-test-system`,value:m,onChange:e=>h(e.target.value),placeholder:c(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(le,{label:c(`ai.chatMode`,`Conversation mode`),value:D,options:[{value:`throwaway`,label:c(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:c(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{O(e),e===`throwaway`&&M(null)}}),D===`persistent`&&e(`div`,{className:`space-y-2`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:c(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),e(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:X,children:[i(te,{className:`h-3.5 w-3.5`}),c(`ai.newChat`,`New chat`)]}),N.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:N.map(e=>i(`button`,{type:`button`,onClick:()=>void ce(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-xs hover:bg-surface-hover ${e.id===A?`bg-primary/10`:``}`,children:i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),i(`p`,{className:`text-xs text-foreground-subtle`,children:c(`ai.streamNote`,`The answer streams as the model produces it. A cold model can take a while to load — the status line says which phase it is in.`)}),q!==null&&!q.supportsVision&&i(`p`,{className:`text-xs text-warning`,children:c(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]})}),F!==null&&i(H,{title:c(`ai.chatFailed`,`The test call failed`),message:F}),e(K,{headingId:`ai-test-conversation`,title:c(`ai.testConversation`,`Conversation`),actions:e(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:b.length===0&&S===null,onClick:X,children:[i(g,{className:`h-3.5 w-3.5`}),c(`ai.clearChat`,`Clear`)]}),children:[i(It,{turns:b,live:L}),e(`div`,{className:`${f} space-y-2 border-t border-border`,children:[S!==null&&e(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-background px-2.5 py-1.5`,children:[S.ref.kind===`snapshot`?i(p,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(j,{className:`h-3.5 w-3.5 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:S.label}),i(oe,{size:`sm`,variant:`ghost`,type:`button`,icon:k,"aria-label":c(`ai.removeAttachment`,`Remove attachment`),onClick:()=>C(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{size:`sm`,variant:w===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>E(w===`snapshot`?`none`:`snapshot`),children:[i(p,{className:`h-3.5 w-3.5`}),c(`ai.attachSnapshot`,`Camera snapshot`)]}),e(W,{size:`sm`,variant:w===`track`?`primary`:`outline`,type:`button`,onClick:()=>E(w===`track`?`none`:`track`),children:[i(j,{className:`h-3.5 w-3.5`}),c(`ai.attachTrack`,`Recent track`)]})]}),w===`snapshot`&&i(zt,{onPick:e=>{C({ref:{kind:`snapshot`,deviceId:e.id},label:c(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:e.name})}),E(`none`)}}),w===`track`&&i(Vt,{onPick:(e,t)=>{C({ref:{kind:`track`,trackId:e.trackId,deviceId:e.deviceId},label:c(`ai.trackOf`,`{{class}} on {{name}}`,{class:e.label??e.className,name:t})}),E(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(ne,{value:v,onChange:e=>y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Y())},placeholder:c(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":c(`ai.message`,`Message`)}),J?e(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:se,children:[i(T,{className:`h-3.5 w-3.5`}),c(`ai.stop`,`Stop`)]}):e(W,{size:`sm`,type:`button`,disabled:v.trim()===``||u===``,onClick:Y,children:[i(R,{className:`h-3.5 w-3.5`}),c(`ai.send`,`Send`)]})]})]})]})]})}function It({turns:t,live:n}){let{t:r}=Q();return t.length===0&&n===null?i(G,{icon:L,title:r(`ai.chatEmptyTitle`,`No messages yet`),description:r(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):e(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto ${f}`,children:[t.map(e=>i(Lt,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(Rt,{attachment:n.mediaSent}),n.text.length>0&&i(Lt,{turn:{id:`live`,role:`assistant`,content:n.text},streaming:!0}),e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(N,{className:`h-3.5 w-3.5 animate-spin`}),kt(n.phase,n.firstTokenTimeoutMs)]})]})]})}function Lt({turn:t,streaming:n=!1}){let{t:r}=Q(),a=t.role===`user`,o=t.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return i(`div`,{className:`flex ${a?`justify-end`:`justify-start`}`,children:e(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${a?`border-primary/40 bg-primary/10`:o}`,children:[e(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[t.content,n&&i(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),t.attachment!==void 0&&i(Rt,{attachment:t.attachment}),t.attachmentLabel!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachmentKind===`track`?i(j,{className:`h-3 w-3`}):i(p,{className:`h-3 w-3`}),t.attachmentLabel]}),t.attachment!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachment.kind===`snapshot`?i(p,{className:`h-3 w-3`}):i(j,{className:`h-3 w-3`}),Ot(t.attachment)]}),t.model!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:t.model,value2:String(t.outputTokens??0),value3:String(t.latencyMs??0)})})]})})}function Rt({attachment:e}){let{t}=Q(),n=Et(e);return n===null?null:i(`img`,{src:n,alt:t(`system.aiTestChat.sentToTheModel`,`sent to the model`),className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function zt({onPick:e}){let{t}=Q(),n=X({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(N,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):i(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>i(Bt,{device:t,onPick:e},t.id))})}function Bt({device:t,onPick:n}){let{t:r}=Q(),{src:a}=h(t.id,{width:Nt});return e(`button`,{type:`button`,onClick:()=>n(t),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[i(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:a!==null&&i(`img`,{src:a,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),e(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!t.online&&i(z,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:t.name})]})]})}function Vt({onPick:t}){let{t:r}=Q(),a=P(),o=X({isCamera:!0,projection:`slim`}),c=n(()=>(o.data??[]).map(e=>e.id),[o.data]),l=n(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),u=s({queryKey:[...At,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-jt,limit:Mt,projection:`slim`})});if(o.isLoading||u.isLoading)return i(N,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=u.data?.tracks??[];return d.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noTracks`,`No track in the last 6 hours.`)}):i(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(n=>e(`button`,{type:`button`,onClick:()=>t(n,l.get(n.deviceId)??String(n.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[i(j,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:n.label??n.className}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:l.get(n.deviceId)??n.deviceId}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(n.lastSeen).toLocaleTimeString()})]},n.trackId))})}c();var Ht=1440*60*1e3,Ut=[1,7,30,90];function Wt(){let{t}=Q(),r=P(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*Ht},[a]),u=s({queryKey:ve,queryFn:()=>r.trpcClient.llm.listProfiles.query({})}),d=s({queryKey:[...Ce,a],queryFn:()=>r.trpcClient.llm.getUsage.query({since:l})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),m=n(()=>[{key:`day`,header:t(`ai.colDay`,`Day`),nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:t(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:t(`ai.colProfile`,`Profile`),render:e=>i(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:t(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:t(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:t(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:t(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,t]),h=d.data??[],g=i(`div`,{className:`w-36`,children:i(re,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:Ut.map(e=>({value:String(e),label:t(`ai.lastDays`,`Last {{days}} days`,{days:e})})),onChange:e=>c(Number(e.target.value))})});return i(K,{headingId:`ai-usage-list`,title:t(`ai.usageList`,`Rollup`),actions:g,children:d.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-usage-loading`,children:[i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`}),i(B,{className:`h-8 w-full`})]}):d.isError?i(`div`,{className:f,children:i(H,{title:t(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:t(`common.error`,`Error`),onRetry:()=>void d.refetch()})}):h.length===0?i(G,{icon:b,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(fe,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:q})})}var Gt=`llm`,Kt=[`profiles`,`runtimes`,`usage`,`test`],qt=[`new`,`edit`];function Jt(e){return Kt.some(t=>t===e)}function Yt(){let{t}=Q(),n=ue(Gt),[r]=pe(),{openNew:a}=de(),o=me(`/system/ai`,{t,isAdmin:!0})??{icon:E,title:t(`system.ai`,`AI`)};if(n!==`present`)return i(ge,{icon:o.icon,title:o.title,children:i(Xt,{presence:n})});let s=r.get(`tab`),c=Jt(s)?s:`profiles`,l={profiles:t(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),runtimes:t(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),usage:t(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),test:t(`ai.testSubtitle`,`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`)},u=c===`profiles`?e(W,{size:`sm`,type:`button`,"data-testid":`ai-add-profile`,onClick:a,children:[i(M,{className:`h-3.5 w-3.5`}),t(`ai.addProfile`,`Add profile`)]}):void 0;return i(he,{icon:o.icon,title:o.title,subtitle:l[c],actions:u,defaultSection:`profiles`,sectionsLabel:`${o.title} sections`,sections:[{id:`profiles`,label:t(`ai.tabProfiles`,`Profiles`),content:i(dt,{}),ownedParams:qt},{id:`runtimes`,label:t(`ai.tabRuntimes`,`Runtimes`),content:i(ht,{})},{id:`usage`,label:t(`ai.tabUsage`,`Usage`),content:i(Wt,{})},{id:`test`,label:t(`ai.tabTest`,`Test`),content:i(Ft,{})}]})}function Xt({presence:t}){let{t:n}=Q();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(B,{className:`h-8 w-64`}),i(B,{className:`h-40 w-full`})]}):t===`unknown`?i(H,{title:n(`ai.presenceUnknownTitle`,`Could not check whether AI is installed`),message:n(`ai.presenceUnknown`,`The hub did not answer the capability check. Reload the page to try again.`)}):i(G,{icon:E,title:n(`ai.absentTitle`,`AI is not installed`),description:n(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{Yt as AiProfilesPage,Yt as default};
@@ -1 +1 @@
1
- import{C as e,K as t,S as n,V as r,Y as i,et as a}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{or as o}from"./player-overlays-Dbv95cvz.js";import{Ca as s}from"./client-DvJxGh2F.js";import{Kr as c,ga as l,la as u,ur as d}from"./src-DntJrWmU.js";import{t as f}from"./useTranslation-BJr-n0es.js";import{P as p,lr as m}from"./index-C3uCLHv0.js";a();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`||d(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:a,addonId:d,brokerId:_,initialValues:v,onSubmit:y,onCancel:b,submitLabel:x,disabled:S}){let{t:C}=f(),[w,T]=i(v??{}),[E,D]=i(null),O=u({kind:a,...d===void 0?{}:{addonId:d}}),k=t(()=>{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]);r(()=>{v!==void 0&&T(v)},[v]);let A=l(),j=async()=>{D(null);let e=g(k,w);try{let t=await A.mutateAsync({kind:a,settings:e,...d===void 0?{}:{addonId:d}});D(t.ok?{ok:!0}:{ok:!1,error:t.error})}catch(e){D({ok:!1,error:e instanceof Error?e.message:String(e)})}};return e(`div`,{className:`space-y-3`,children:[O.isLoading&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[n(o,{className:`h-3.5 w-3.5 animate-spin`}),` `,C(`brokers.brokerForm.loadingSchema`)]}),k&&n(p,{schema:k,values:w,onChange:T}),O.isError&&e(`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&&n(`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:n(m,{i18nKey:`brokers.brokerForm.noSchema`,values:{kind:a},components:{code:n(`code`,{className:`font-mono`})}})}),E&&n(`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`})}),e(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[n(c,{variant:`outline`,size:`sm`,onClick:b,children:C(`common.cancel`,`Cancel`)}),e(`div`,{className:`flex items-center gap-2`,children:[n(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`)}),n(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{C as e,K as t,S as n,V as r,Y as i,et as a}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{or as o}from"./player-overlays-Dbv95cvz.js";import{Ca as s}from"./client-DvJxGh2F.js";import{Kr as c,ga as l,la as u,ur as d}from"./src-DntJrWmU.js";import{t as f}from"./useTranslation-BJr-n0es.js";import{P as p,lr as m}from"./index-XXQ5yMw_.js";a();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`||d(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:a,addonId:d,brokerId:_,initialValues:v,onSubmit:y,onCancel:b,submitLabel:x,disabled:S}){let{t:C}=f(),[w,T]=i(v??{}),[E,D]=i(null),O=u({kind:a,...d===void 0?{}:{addonId:d}}),k=t(()=>{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]);r(()=>{v!==void 0&&T(v)},[v]);let A=l(),j=async()=>{D(null);let e=g(k,w);try{let t=await A.mutateAsync({kind:a,settings:e,...d===void 0?{}:{addonId:d}});D(t.ok?{ok:!0}:{ok:!1,error:t.error})}catch(e){D({ok:!1,error:e instanceof Error?e.message:String(e)})}};return e(`div`,{className:`space-y-3`,children:[O.isLoading&&e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[n(o,{className:`h-3.5 w-3.5 animate-spin`}),` `,C(`brokers.brokerForm.loadingSchema`)]}),k&&n(p,{schema:k,values:w,onChange:T}),O.isError&&e(`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&&n(`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:n(m,{i18nKey:`brokers.brokerForm.noSchema`,values:{kind:a},components:{code:n(`code`,{className:`font-mono`})}})}),E&&n(`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`})}),e(`div`,{className:`flex items-center justify-between gap-2 pt-1`,children:[n(c,{variant:`outline`,size:`sm`,onClick:b,children:C(`common.cancel`,`Cancel`)}),e(`div`,{className:`flex items-center gap-2`,children:[n(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`)}),n(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{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as p,Fn as m,It as h,Nt as g,Zi as _,kn as v,or as y,ot as b,pi as x,pn as S,pt as C,qi as w,sa as T,vn as E,wr as D,xi as O,yi as k}from"./player-overlays-Dbv95cvz.js";import{Di as A,Ei as j,Ii as M,Li as N,Na as P,Oi as F,Ti as I,bi as L,dn as R,ei as z,gi as B,ni as V,pi as H,ri as ee,va as te,wi as ne,xi as re}from"./client-DvJxGh2F.js";import{t as ie}from"./boxes-0ut2NdHU.js";import{n as ae,r as oe,t as se}from"./ungroup-3fOR8xo7.js";import{s as ce}from"./video-D7jv0spx.js";import{$r as U,$t as le,$u as W,Aa as ue,Ca as de,Dr as fe,Gn as G,Jt as pe,Ju as K,Kr as q,No as me,Oa as he,Qu as ge,Sr as _e,Tn as ve,Wr as ye,Xu as be,Zu as xe,_o as Se,an as Ce,bt as we,co as Te,dd as Ee,fo as De,gt as Oe,ja as ke,ka as Ae,ko as je,mt as Me,nn as Ne,pd as Pe,vn as Fe,wa as Ie,wn as Le,xa as Re}from"./src-DntJrWmU.js";import{t as J}from"./i18n-xhwARoF0.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{P as ze,ar as Be,fr as Ve,lr as X,m as He,mr as Ue,ur as We,x as Ge}from"./index-C3uCLHv0.js";import{t as Ke}from"./AdminSectionedPage-DtiHBXGC.js";import{t as qe}from"./DeviceDoActionFields-Bj4gX0r-.js";import{R as Je,f as Ye,t as Xe}from"./HelperWizard-CrXHYd19.js";import{t as Ze}from"./CompositionBlockEditor-CElNVsCR.js";var Qe=`const AUTOMATION_RECIPE =`,$e=`// EJECTED from the visual automation editor — this file is now hand-owned.
1
+ import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as p,Fn as m,It as h,Nt as g,Zi as _,kn as v,or as y,ot as b,pi as x,pn as S,pt as C,qi as w,sa as T,vn as E,wr as D,xi as O,yi as k}from"./player-overlays-Dbv95cvz.js";import{Di as A,Ei as j,Ii as M,Li as N,Na as P,Oi as F,Ti as I,bi as L,dn as R,ei as z,gi as B,ni as V,pi as H,ri as ee,va as te,wi as ne,xi as re}from"./client-DvJxGh2F.js";import{t as ie}from"./boxes-0ut2NdHU.js";import{n as ae,r as oe,t as se}from"./ungroup-3fOR8xo7.js";import{s as ce}from"./video-D7jv0spx.js";import{$r as U,$t as le,$u as W,Aa as ue,Ca as de,Dr as fe,Gn as G,Jt as pe,Ju as K,Kr as q,No as me,Oa as he,Qu as ge,Sr as _e,Tn as ve,Wr as ye,Xu as be,Zu as xe,_o as Se,an as Ce,bt as we,co as Te,dd as Ee,fo as De,gt as Oe,ja as ke,ka as Ae,ko as je,mt as Me,nn as Ne,pd as Pe,vn as Fe,wa as Ie,wn as Le,xa as Re}from"./src-DntJrWmU.js";import{t as J}from"./i18n-D0o08mg-.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{P as ze,ar as Be,fr as Ve,lr as X,m as He,mr as Ue,ur as We,x as Ge}from"./index-XXQ5yMw_.js";import{t as Ke}from"./AdminSectionedPage-BByl6Zss.js";import{t as qe}from"./DeviceDoActionFields-gklZW8H7.js";import{R as Je,f as Ye,t as Xe}from"./HelperWizard-B5Evcb8G.js";import{t as Ze}from"./CompositionBlockEditor-BsmLsHO7.js";var Qe=`const AUTOMATION_RECIPE =`,$e=`// 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 et(e){return e.includes(Qe)}function tt(e){let t=e.indexOf(Qe);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 nt(e){let t=tt(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=I.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 rt(e){let t=tt(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)}${$e}${e.slice(i)}`}u();var it=6e4;function at(){let e=De({projection:`slim`});return r(()=>(e.data??[]).filter(e=>R(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 ot(e){let t=b();return l({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:it,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function st(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Z({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function ct(e){let t=ot(e.deviceId);if(t.data!==void 0)return st(t.data,e.cap).find(t=>t.path===e.fieldPath)}function lt({value:t,devices:n,onChange:r}){let{t:i}=Y(),a=ot(t.deviceId),s=a.data??[],c=st(s,t.cap);return e(f,{children:[e(`label`,{className:`min-w-[10rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.device`,`Device`)}),o(K,{value:String(t.deviceId),onChange:e=>r({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:i(`automation.fieldPicker.selectADevice`,`Select a device…`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.capability`,`Capability`)}),o(K,{value:t.cap,disabled:t.deviceId===0,onChange:e=>r({...t,cap:e.target.value,fieldPath:``}),options:[{value:``,label:ut(t.deviceId,s.length,a.isLoading)},...s.map(e=>({value:e.cap,label:e.cap}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.field`,`Field`)}),o(K,{value:t.fieldPath,disabled:t.cap===``,onChange:e=>r({...t,fieldPath:e.target.value}),options:[{value:``,label:c.length===0?i(`automation.fieldPicker.noReadableFields`,`No readable fields`):i(`automation.fieldPicker.selectAField`,`Select a field…`)},...c.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function ut(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 dt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function ft(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 dt}}function pt(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 mt(e){return ft(e).map(e=>({value:e,label:pt(e)}))}function ht(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 gt={triggers:[],actions:[]};function _t(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 vt(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 yt(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function bt(){return{kind:`expression`,expr:``,bindings:{}}}function xt(e,t,n){return e.map((e,r)=>r===t?n:e)}function St(e,t){return e.filter((e,n)=>n!==t)}function Ct(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=St(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function wt(e,t){return{...e,triggers:[...t]}}function Tt(e,t){return{...e,actions:[...t]}}var Et=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function Dt({actions:t,devices:n,devicesState:r=`answered`,onChange:i}){let{t:a}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:a(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((s,c)=>e(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(U,{variant:`default`,children:c+1}),e(`label`,{className:`w-40`,children:[o(Z,{children:a(`automation.actionList.step`,`Step`)}),o(K,{value:s.kind,onChange:e=>i(xt(t,c,vt(Ot(e.target.value)))),options:Et.map(e=>({value:e.value,label:a(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(q,{variant:`ghost`,disabled:c===0,onClick:()=>i(Ct(t,c,c-1)),title:a(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(w,{className:`h-3.5 w-3.5`})}),o(q,{variant:`ghost`,disabled:c===t.length-1,onClick:()=>i(Ct(t,c,c+1)),title:a(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(_,{className:`h-3.5 w-3.5`})}),o(q,{variant:`ghost`,onClick:()=>i(St(t,c)),title:a(`automation.actionList.removeThisStep`,`Remove this step`),children:o(h,{className:`h-3.5 w-3.5`})})]})]}),s.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Z,{children:a(`automation.actionList.seconds`,`Seconds`)}),o(W,{type:`number`,min:0,max:300,value:String(s.seconds),onChange:e=>i(xt(t,c,{kind:`wait`,seconds:Number(e.target.value)}))})]}),s.kind===`code`&&e(`label`,{className:`block`,children:[o(Z,{children:a(`automation.actionList.code`,`Code`)}),o(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:s.code,spellCheck:!1,onChange:e=>i(xt(t,c,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),s.kind===`cap`&&o(At,{action:s,devices:n,devicesState:r,onChange:e=>i(xt(t,c,e))})]},`${s.kind}-${String(c)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>i([...t,vt(`cap`)]),children:[o(v,{className:`h-4 w-4`}),` `,a(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Ot(e){return Et.find(t=>t.value===e)?.value??`cap`}function kt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function At({action:e,devices:t,devicesState:n,onChange:r}){return o(qe,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:kt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function jt({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Y(),c=Lt(n,r,i);if(n?.kind===`boolean`)return o(K,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(K,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(W,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(W,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Mt({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),s=Lt(t,n,r);return o(W,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function Nt(e){return typeof e==`object`}function Pt(e){return Nt(e)?e[0]??``:e}function Ft(e){return Nt(e)?e:typeof e==`boolean`?[]:[e]}function It(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Lt(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=Te({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=te(o)?o:void 0,c=It(e?.quantity,s);if(c===void 0)return;let l=a?.display;return le({quantity:c,display:l,capName:n})}function Rt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=ct(a),c=mt(s?.kind),l=t.operator===`in`,u=e=>{r({...t,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},d=e=>{let n=zt(e,c);r({...t,operator:n,value:n===`in`?Ft(t.value):Pt(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(lt,{value:a,devices:n,onChange:u}),e(`label`,{className:`min-w-[8rem]`,children:[o(Z,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(K,{value:t.operator,onChange:e=>d(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Mt,{value:Ft(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(jt,{value:Pt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function zt(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Bt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Vt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Z,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(W,{value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:e=>r({kind:`expression`,expr:e.target.value,bindings:t.bindings})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o(Ht,{alias:e,source:r,devices:n,onRename:n=>s(Jt(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Yt(t.bindings,e))},e)),e(q,{variant:`ghost`,onClick:()=>s({...t.bindings,[qt(t.bindings)]:Bt}),children:[o(v,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function Ht({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Y(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Gt(r,Wt(n)),cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Z,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(W,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Z,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(K,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Bt),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(W,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Ut(e.target.value)})})]}):o(lt,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Kt(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(q,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(h,{className:`h-3.5 w-3.5`})})]})}function Ut(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Wt(e){return e.kind===`global`?e.sourceStableId:``}function Gt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Kt(e,t){return e.find(e=>e.id===t)?.stableId??``}function qt(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function Jt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Yt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Xt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:Xt(t)?t:{kind:`all`,children:[t]}}function Zt(e,t){return t===null||Xt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Qt(e){return Zt(e,Q(e))}function $t(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?$t(e.child,r):null;if(!Xt(e))return null;let i=e.children[n];return i===void 0?null:$t(i,r)}function en(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=en(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!Xt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=en(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 tn(e){return e===null?null:F({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function nn(e){let t=Q(e);return{depth:t.children.length===0?0:j(t),leaves:t.children.length===0?0:A(t),depthLimit:3,leafLimit:32}}function rn(e,t){let n=tn(t);return n===null?{ok:!0,recipe:Zt(e,t)}:{ok:!1,reason:n}}function an(e,t){let n=Q(e);return rn(e,{kind:n.kind,children:[...n.children,t]})}function on(e,t,n){return Zt(e,en(Q(e),t,()=>n))}function sn(e,t){return Zt(e,en(Q(e),t,()=>null))}function cn(e,t,n){return Zt(e,en(Q(e),t,e=>Xt(e)?{kind:n,children:e.children}:e))}function ln(e,t){return $t(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:rn(e,en(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function un(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 dn(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=un(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=$t(i,r.path);if(a===null||!Xt(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 rn(e,en(i,r.path,()=>d))}function fn(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=$t(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return rn(e,en(n,t,()=>r.child));if(!Xt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=un(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=$t(n,i.path);if(a===null||!Xt(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 rn(e,en(n,i.path,()=>o))}u();var pn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function mn(e){return e.join(`/`)}function hn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function gn({recipe:t,devices:n,onChange:i}){let{t:a}=Y(),[s,l]=c([]),[u,d]=c(null),f=Q(t),p=nn(t),m=r(()=>s.map(hn),[s]),h=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},g=dn(t,m,`all`),_=dn(t,m,`any`),y=m.length===1?ln(t,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:n,selected:new Set(s),onToggleSelect:e=>l(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(e,n)=>i(on(t,e,n)),onRemove:e=>{l([]),i(sn(t,e))},onSetKind:(e,n)=>i(cn(t,e,n)),onUngroup:e=>h(fn(t,e))};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(U,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),o(`div`,{className:`w-32`,children:o(K,{value:f.kind,onChange:e=>i(cn(t,[],_n(e.target.value))),options:pn.map(e=>({value:e.value,label:a(e.labelKey)}))})}),o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),f.children.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):o(vn,{container:f,path:[],handlers:b}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>h(an(t,yt())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(v,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(q,{variant:`outline`,onClick:()=>h(an(t,bt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(oe,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(q,{variant:`ghost`,disabled:!g.ok,onClick:()=>h(g),title:g.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):g.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(q,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):_.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),o(q,{variant:`ghost`,disabled:!y.ok,onClick:()=>h(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),u!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:u})]})}function _n(e){return e===`any`?`any`:`all`}function vn({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(yn,{node:e,path:[...t,r],handlers:n},mn([...t,r])))})}function yn({node:t,path:n,handlers:r}){let{t:i}=Y(),a=mn(n),s=o(G,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return Xt(t)?e(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(`div`,{className:`w-32`,children:o(K,{value:t.kind,onChange:e=>r.onSetKind(n,_n(e.target.value)),options:pn.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(q,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(q,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(h,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(vn,{container:t,path:n,handlers:r})})]}):t.kind===`not`?e(`div`,{className:`rounded border border-border p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(U,{variant:`warning`,children:`NOT`}),e(q,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(yn,{node:t.child,path:[...n,0],handlers:r})})]}):e(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[o(`div`,{className:`pt-6`,children:s}),o(`div`,{className:`min-w-0 flex-1`,children:t.kind===`condition`?o(Rt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(Vt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(q,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(h,{className:`h-3.5 w-3.5`})})]})}u();function bn({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Y(),[l,u]=c(!1),d=ye(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(q,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?O:k,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(q,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(ce,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(Fe,{maxHeight:420,children:t})})]})}var xn=[`device-state`,`device-event`,`schedule`,`manual`],Sn=Object.values(P).sort((e,t)=>e.localeCompare(t));function Cn({triggers:t,devices:n,onChange:r}){let{t:i}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:i(`automation.triggerEditor.noTriggersYetWithoutOne`,`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`)}),t.map((e,i)=>o(wn,{trigger:e,devices:n,position:i,onChange:e=>r(xt(t,i,e)),onRemove:()=>r(St(t,i))},`${e.kind}-${String(i)}`)),e(q,{variant:`outline`,onClick:()=>r([...t,_t(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(v,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function wn({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=Y();return e(`div`,{className:`rounded border border-border p-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(U,{variant:`default`,children:r===0?s(`automation.triggerEditor.when`,`When`):s(`automation.triggerEditor.orWhen`,`or when`)}),e(`label`,{className:`min-w-[13rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.trigger`,`Trigger`)}),o(K,{value:t.kind,onChange:e=>i(_t(Tn(e.target.value))),options:xn.map(e=>({value:e,label:ht(e)}))})]}),o(q,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(h,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o(Dn,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(kn,{trigger:t,devices:n,onChange:i}),t.kind===`schedule`&&e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(W,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>i({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`manual`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function Tn(e){return xn.find(t=>t===e)??`manual`}function En(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 Dn({trigger:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=ct(a),c={...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}};return e(f,{children:[o(lt,{value:a,devices:n,onChange:e=>r(En(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(G,{checked:t.becomes===void 0,onChange:e=>r(En(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(jt,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(En(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(G,{checked:t.edge===!0,onChange:e=>r(En(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(W,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(En(a,{...c,forMs:On(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(W,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(En(a,{...c,debounceMs:On(e.target.value)}))})]})]})}function On(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function kn({trigger:t,devices:n,onChange:r}){let{t:i}=Y();return e(f,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(K,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...Sn.map(e=>({value:e,label:e}))]})]}),e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(K,{value:t.deviceId===void 0?``:String(t.deviceId),onChange:e=>r({kind:`device-event`,category:t.category,...e.target.value===``?{}:{deviceId:Number(e.target.value)}}),options:[{value:``,label:i(`automation.triggerEditor.anyDevice`,`Any device`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]})]})}u();var An=`hub`;function jn({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Y(),[p,m]=c(t?.name??``),[h,g]=c(()=>Qt(n)),[_,v]=c(!1),b=at(),x=F(h),C=r(()=>Nn(h),[h]),w=r(()=>Pn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),T=p.trim()===``,E=T||x!==null||C!==null||w.code===null;return e(`div`,{className:`space-y-4`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(U,{variant:`info`,children:f(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(W,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Mn,{step:`1`,title:f(`automation.automationEditor.when`,`When`),subtitle:f(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:o(Cn,{triggers:h.triggers,devices:b,onChange:e=>g(wt(h,e))})}),o(Mn,{step:`2`,title:f(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:f(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:o(gn,{recipe:h,devices:b,onChange:g})}),o(Mn,{step:`3`,title:f(`automation.automationEditor.then`,`Then`),subtitle:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Dt,{actions:h.actions,devices:b,onChange:e=>g(Tt(h,e))})}),o(bn,{code:w.code,error:w.error,canEject:t!==null,ejecting:s,onEject:u}),x!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),x===null&&C!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:C}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{onClick:()=>{w.code!==null&&l({name:p.trim(),code:w.code,enabled:t?.enabled??!0,placement:An})},disabled:i||E,children:[i&&o(y,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(q,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[o(S,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,_?`▾`:`▸`]}),o(q,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),T&&o(U,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Mn({step:t,title:n,subtitle:r,children:i}){return e(`section`,{className:`border-l-2 border-border pl-4`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:t}),o(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:n}),o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i]})}function Nn(e){let t=I.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 Pn(e,t){try{return{code:ne({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Fn(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 In(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Ln(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Rn(e){let t=e=>{let t=Fn(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 zn(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Fn(e).tone===`error`).length,n=e.filter(e=>Fn(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 Bn({block:t,busy:n,confirming:r,logsOpen:i,unreadable:a,onEdit:s,onToggle:c,onToggleLogs:l,onAskDelete:u,onCancelDelete:d,onConfirmDelete:f}){let g=T(),{t:_}=Y(),v=Fn(t),y=pe(t.updatedAt,g);return e(`li`,{className:`flex flex-col gap-2 p-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(U,{variant:In(v.tone),children:v.label}),y!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:_(`common.edited`,{when:y})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:v.detail}),a!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:_(`automation.editor.listUnreadable`,{reason:a})})]}),r?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:_(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),o(q,{variant:`danger`,onClick:e=>{e.stopPropagation(),f()},disabled:n,children:_(`common.delete`,`Delete`)}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),d()},children:_(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s()},disabled:a!==null,title:a===null?_(`common.edit`,`Edit`):_(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(m,{className:`h-4 w-4`})}),e(be,{children:[o(ge,{children:o(q,{variant:`ghost`,disabled:!0,title:_(`automation.automationList.runActions`,`Run actions`),children:o(p,{className:`h-4 w-4`})})}),o(xe,{children:_(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:_(`automation.automationList.logs`,`Logs`),children:o(S,{className:`h-4 w-4`})}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c(!t.enabled)},disabled:n,title:t.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`),children:t.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`)}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},title:_(`common.delete`,`Delete`),children:o(h,{className:`h-4 w-4`})})]})]}),i&&e(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Vn({onCreate:t}){let{t:n}=Y();return o(_e,{children:e(`div`,{className:`space-y-2 p-4`,children:[o(`p`,{className:`text-sm text-foreground`,children:n(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),o(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:n(`automation.automationList.anAutomationIsATrigger`,`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`)}),o(q,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var Hn=[`coreBlocks`,`list`],Un=5e3;function Wn(e){return e instanceof Error?e.message:String(e)}function Gn({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:f}){let{t:p}=Y(),m=b(),{state:h,openNew:g,openEdit:_,close:v}=Me({editKey:`block`,newKey:`new`}),[y,x]=c(null),[S,w]=c(null),[T,E]=c(null),D=n(null),O=h.mode!==`closed`;s(()=>{u&&(x(null),g(),a?.(null),f?.())},[u,f,a,g]);let k=l({queryKey:Hn,refetchInterval:Un,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;s(()=>{i===void 0||D.current===i||j?.find(e=>e.id===i&&et(e.code))!==void 0&&(D.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:rt(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{v(),x(null),A(),t(e.block.id)}}),L=k.data,R=Rn((L??[]).filter(e=>et(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:Ln(R,B),H=V===null?null:nt(V.code),ee=M.error===null?N.error===null?I.error===null?null:Wn(I.error):Wn(N.error):Wn(M.error),te=r(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=nt(e.code);return o(`ul`,{className:`list-none`,children:o(Bn,{block:e,busy:F.isPending||P.isPending,confirming:S===e.id,logsOpen:T===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{x(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>E(T===e.id?null:e.id),onAskDelete:()=>w(e.id),onCancelDelete:()=>w(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[S,T,a,_,P,F,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:zn(R)}),k.error!=null&&o(fe,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Wn(k.error),onRetry:A}),z?o(Vn,{onCreate:()=>{x(null),g(),a?.(null)}}):o(Le,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ve,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{x(e),_(e.id),a?.(e.id)}}),o(Oe,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:C,width:`xl`,testId:`automation-editor-panel`,children:o(jn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:gt,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&o(fe,{message:Wn(P.error)}),F.error!=null&&o(fe,{message:Wn(F.error)})]})}u();var Kn=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function qn(){let{t}=Y(),n=T(),r=Ve(),i=Re(),a=me(),s=je(),l=Se({addonId:`composer`}),[u,d]=c(N.Sensor),[f,p]=c(M.TemperatureSensor),[m,h]=c(``),[g,_]=c(``),[v,y]=c(null),[b,x]=c(`choose`),S=Je({type:u,role:f});return b===`choose`?e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(`h2`,{className:`text-sm font-semibold`,children:t(`build.customDeviceTab.newComposedDevice`)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[o(q,{variant:`outline`,"data-testid":`blank-composition`,onClick:()=>x(`blank`),children:t(`helper.blank`)}),o(q,{"data-testid":`new-helper`,onClick:()=>x(`helper`),children:t(`helper.newHelper`)})]})]}):b===`helper`?e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(q,{variant:`ghost`,size:`sm`,onClick:()=>x(`choose`),children:t(`helper.back`)}),o(`h2`,{className:`text-sm font-semibold`,children:t(`helper.newHelper`)}),o(Xe,{initial:null,start:`template`,saving:i.isPending,onSave:e=>Ye(e,async(t,n)=>{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:t}}),c=`${H}${o.id}`,u=((await l.refetch()).data??l.data)?.find(e=>e.stableId===c);if(u!==void 0){n!==``&&await a.mutateAsync({deviceId:u.id,name:n}),e.room.trim()!==``&&await s.mutateAsync({deviceId:u.id,location:e.room.trim()}),r(He(u.id),{replace:!0});return}r(`/build/compositions/${encodeURIComponent(o.id)}`,{replace:!0})})})]}):e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(q,{variant:`ghost`,size:`sm`,onClick:()=>x(`choose`),children:t(`helper.back`)}),o(`h2`,{className:`text-sm font-semibold`,children:t(`build.customDeviceTab.newComposedDevice`)}),e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`compositionEditor.targetType`),o(K,{value:u,onChange:e=>{let t=Object.values(N).find(t=>t===e.target.value);t!==void 0&&d(t)},options:Object.values(N).map(e=>({value:e,label:Pe(e,n).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`customize.identity.role`),o(K,{value:f??``,onChange:e=>p(Object.values(M).find(t=>t===e.target.value)??null),options:[{value:``,label:t(`customize.identity.noRole`)},...Object.values(M).map(e=>({value:e,label:Ee(e,n).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`compositionEditor.name`),o(`input`,{className:Kn,value:m,onChange:e=>h(e.target.value)})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`customize.identity.room`),o(`input`,{className:Kn,value:g,onChange:e=>_(e.target.value)})]})]}),v!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:v}),o(q,{disabled:S===null||i.isPending,onClick:()=>{S!==null&&(async()=>{y(null);try{let e=m.trim(),{block:t}=await i.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),n=`${H}${t.id}`,o=((await l.refetch()).data??l.data)?.find(e=>e.stableId===n);if(o!==void 0){e!==``&&await a.mutateAsync({deviceId:o.id,name:e}),g.trim()!==``&&await s.mutateAsync({deviceId:o.id,location:g.trim()}),r(He(o.id),{replace:!0});return}r(`/build/compositions/${encodeURIComponent(t.id)}`,{replace:!0})}catch(e){y(e instanceof Error?e.message:String(e))}})()},children:t(`compositionEditor.save`)})]})}function Jn(e){return{state:`answered`,byRef:new Map(e.map(e=>[L(e),e]))}}function Yn(e,t){if(e.state!==`unanswered`)return e.byRef.get(L(t))??null}function Xn(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Zn(e){return re(e).map(e=>e.source)}function Qn(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(...Zn(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Zn(e))}let r=new Set;return n.filter(e=>{let t=L(e);return r.has(t)?!1:(r.add(t),!0)})}function $n(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 er(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return $n(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 tr(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 er(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 nr(e){return L(e)}function rr(e,t){let n=Yn(t,e);return{key:L(e),label:n?n.name:nr(e),presence:Xn(n),deviceId:n?n.id:null}}function ir(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function ar(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:B(e.block.id),a=L(i),o=Qn(e).filter(e=>L(e)!==a).map(e=>rr(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Yn(t,i),l=ir(e),u=tr(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=Xn(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:nr(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function or(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function sr(e,t){return or(e)-or(t)||e.name.localeCompare(t.name)}function cr(e,t){let n=e.flatMap(e=>{let n=ar(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(sr),customizations:n.filter(e=>e.kind===`customization`).toSorted(sr)}}var lr=1e4;function ur(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function dr(){let e=Be();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:ur(e.error)})}:Jn(e.data)}function fr({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=he({},{refetchInterval:lr}),a=dr(),s=Me({editKey:`block`,newKey:`new`}),c=s.state.mode===`edit`?s.state.id:null,l=c===null&&(t||s.state.mode===`new`),u=()=>{s.close(),n?.()},d=i.data;return e(f,{children:[mr(d,i.error,()=>void i.refetch(),a,{onEditComposed:e=>s.openEdit(e)}),o(Oe,{open:l||c!==null,onClose:u,title:l?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:ie,width:`xl`,testId:`composed-device-editor`,children:l?o(qn,{}):c===null?null:o(Ze,{blockId:c})})]})}function pr(t){return o(_e,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:J.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[J.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function mr(e,t,n,r,i){if(t!=null&&e===void 0)return o(fe,{title:J.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:ur(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:J.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return pr(e.reason);let a=t==null?null:ur(t);return o(hr,{lists:cr(e.views,r),fleet:r,refreshError:a,onEditComposed:i.onEditComposed})}function hr({lists:t,fleet:n,refreshError:r,onEditComposed:i}){let{t:a}=Y();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(gr,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:i}),o(gr,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:i})]})}function gr({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,onEditComposed:c}){return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(_e,{variant:`flat`,className:`p-0`,children:o(Le,{columns:_r(i,s,c),rows:r,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:ve,emptyMessage:a,onRowClick:s===`composed`?e=>c(e.blockId):void 0})})]})}function _r(t,n,r){let i=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(vr,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},{key:`state`,header:J.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(U,{variant:In(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(br,{sources:e.sources})}];return n===`composed`&&i.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>o(`div`,{className:`flex justify-end gap-1`,children:o(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),r(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),i}function vr({row:t}){let{t:n}=Y();return e(`div`,{className:`space-y-0.5`,children:[o(yr,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function yr({row:e}){let{t}=Y();return e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:e.name})}):o(We,{to:He(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function br({sources:t}){let{t:n}=Y();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(We,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function xr(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 Sr(e){if(Array.isArray(e))return e}function Cr(e,t,n){return(t=Mr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function wr(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 Tr(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
@@ -1 +1 @@
1
- import{C as e,K as t,R as n,S as r,Y as i,et 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-CEyXHAdg.js";import{bi as s,yi as c}from"./player-overlays-Dbv95cvz.js";import{nr as l,rr as u}from"./client-DvJxGh2F.js";import{h as d}from"./video-D7jv0spx.js";import{Kr as f,_a as p,_r as m,ba as h,hr as g,mr as _,pr as v,va as y,vr as b,ya as x,yr as S}from"./src-DntJrWmU.js";import{t as C}from"./i18n-xhwARoF0.js";import{t as w}from"./useTranslation-BJr-n0es.js";import{lr as T,ur as E}from"./index-C3uCLHv0.js";import{t as D}from"./AdminPage-3JxWocN3.js";a();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=l(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:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function B({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=w();return r(v,{open:!0,onOpenChange:e=>!e&&a(),children:e(g,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(b,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(S,{className:`min-w-0 break-words`,children:t.title})]})}),r(_,{children:e(`dl`,{className:`space-y-3`,children:[r(z,{label:o(`systemPage.calendars.when`,`When`),children:R(t)}),r(z,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(z,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(z,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(m,{children:r(f,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`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(),i=[{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 r(`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:i.map(n=>r(`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:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:o}=w();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:o(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface`,children:[r(`input`,{type:`checkbox`,className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:t.visible,disabled:a,onChange:e=>n(t.id,e.target.checked),"aria-label":o(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${t.id}`}),r(`input`,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:t.color,disabled:a,onChange:e=>i(t.id,e.target.value.toUpperCase()),"aria-label":o(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${t.id}`}),e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${t.visible?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[I(t),t.enabled?``:` · ${o(`systemPage.calendars.unavailableAtSource`)}`]})]})]},t.id))})]})}function G({ev:t,color:n,compact:i,onSelect:a}){return r(`button`,{type:`button`,className:i?`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:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(o,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:L(t)})]})})}function K({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=w(),{startMs:c,endMs:l}=M(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:O.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=k(t).getTime(),l=V(n,c),u=t.getMonth()!==d,f=H(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`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:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function q({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=j(t);return r(`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(t=>{let s=k(t).getTime(),c=V(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:H(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function J({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=w(),c=V(n,k(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(`button`,{type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[L(t),` · `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function Y(){let{t:a}=w(),o=y(),l=p({}),u=h(),[f,m]=i(`month`),[g,_]=i(()=>k(new Date)),[v,b]=i(null),S=t(()=>k(new Date),[]),C=o.isSuccess,O=l.isSuccess&&l.data!==void 0?l.data:void 0,A=t(()=>!C||o.data===void 0?[]:o.data.map(e=>F(e,O)),[C,o.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(g,f),[g,f]),R=x({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=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>l.refetch())},[l,u]),Y=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>l.refetch())},[l,u]),X=n(()=>_(k(new Date)),[]),Z=n(()=>_(e=>P(e,f,-1)),[f]),ee=n(()=>_(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 $=o.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):o.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,o.error.message]}):A.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(T,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(E,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(U,{mode:f,onChange:m}),e(`div`,{className:`flex items-center gap-1`,children:[r(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(s,{className:`h-4 w-4`})}),r(`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:a(`systemPage.calendars.today`,`Today`)}),r(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(c,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(g,f)})]}),R.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):f===`month`?r(K,{anchor:g,events:z,colorById:V,today:S,onSelectEvent:b}):f===`week`?r(q,{anchor:g,events:z,colorById:V,today:S,onSelectEvent:b}):r(J,{anchor:g,events:z,colorById:V,calName:H,onSelectEvent:b})]})]}),e(D,{icon:d,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,v===null?null:r(B,{ev:v,calendarName:H.get(v.calendarId)??v.calendarId,color:V.get(v.calendarId)??`#64748B`,onClose:()=>b(null)})]})}export{Y as CalendarsPage,Y as default};
1
+ import{C as e,K as t,R as n,S as r,Y as i,et 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-CEyXHAdg.js";import{bi as s,yi as c}from"./player-overlays-Dbv95cvz.js";import{nr as l,rr as u}from"./client-DvJxGh2F.js";import{h as d}from"./video-D7jv0spx.js";import{Kr as f,_a as p,_r as m,ba as h,hr as g,mr as _,pr as v,va as y,vr as b,ya as x,yr as S}from"./src-DntJrWmU.js";import{t as C}from"./i18n-D0o08mg-.js";import{t as w}from"./useTranslation-BJr-n0es.js";import{lr as T,ur as E}from"./index-XXQ5yMw_.js";import{t as D}from"./AdminPage-3JxWocN3.js";a();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=l(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:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function B({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=w();return r(v,{open:!0,onOpenChange:e=>!e&&a(),children:e(g,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(b,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(S,{className:`min-w-0 break-words`,children:t.title})]})}),r(_,{children:e(`dl`,{className:`space-y-3`,children:[r(z,{label:o(`systemPage.calendars.when`,`When`),children:R(t)}),r(z,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(z,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(z,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(m,{children:r(f,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`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(),i=[{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 r(`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:i.map(n=>r(`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:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:o}=w();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:o(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface`,children:[r(`input`,{type:`checkbox`,className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:t.visible,disabled:a,onChange:e=>n(t.id,e.target.checked),"aria-label":o(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${t.id}`}),r(`input`,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:t.color,disabled:a,onChange:e=>i(t.id,e.target.value.toUpperCase()),"aria-label":o(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${t.id}`}),e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${t.visible?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[I(t),t.enabled?``:` · ${o(`systemPage.calendars.unavailableAtSource`)}`]})]})]},t.id))})]})}function G({ev:t,color:n,compact:i,onSelect:a}){return r(`button`,{type:`button`,className:i?`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:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(o,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:L(t)})]})})}function K({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=w(),{startMs:c,endMs:l}=M(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:O.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=k(t).getTime(),l=V(n,c),u=t.getMonth()!==d,f=H(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`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:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function q({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=j(t);return r(`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(t=>{let s=k(t).getTime(),c=V(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:H(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function J({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=w(),c=V(n,k(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(`button`,{type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[L(t),` · `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function Y(){let{t:a}=w(),o=y(),l=p({}),u=h(),[f,m]=i(`month`),[g,_]=i(()=>k(new Date)),[v,b]=i(null),S=t(()=>k(new Date),[]),C=o.isSuccess,O=l.isSuccess&&l.data!==void 0?l.data:void 0,A=t(()=>!C||o.data===void 0?[]:o.data.map(e=>F(e,O)),[C,o.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(g,f),[g,f]),R=x({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=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>l.refetch())},[l,u]),Y=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>l.refetch())},[l,u]),X=n(()=>_(k(new Date)),[]),Z=n(()=>_(e=>P(e,f,-1)),[f]),ee=n(()=>_(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 $=o.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):o.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,o.error.message]}):A.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(T,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(E,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(U,{mode:f,onChange:m}),e(`div`,{className:`flex items-center gap-1`,children:[r(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(s,{className:`h-4 w-4`})}),r(`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:a(`systemPage.calendars.today`,`Today`)}),r(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(c,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(g,f)})]}),R.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):f===`month`?r(K,{anchor:g,events:z,colorById:V,today:S,onSelectEvent:b}):f===`week`?r(q,{anchor:g,events:z,colorById:V,today:S,onSelectEvent:b}):r(J,{anchor:g,events:z,colorById:V,calName:H,onSelectEvent:b})]})]}),e(D,{icon:d,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,v===null?null:r(B,{ev:v,calendarName:H.get(v.calendarId)??v.calendarId,color:V.get(v.calendarId)??`#64748B`,onClose:()=>b(null)})]})}export{Y as CalendarsPage,Y as default};