@camstack/addon-admin-ui 1.2.529 → 1.2.530

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 (41) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/assets/{Addons-CZ_5JUVc.js → Addons-DRU_qk60.js} +1 -1
  3. package/dist/assets/{AdminSectionedPage-B_tSbkIV.js → AdminSectionedPage-Dv8ahC-U.js} +1 -1
  4. package/dist/assets/{AiProfiles-W2ByefcY.js → AiProfiles-BJrqkjtX.js} +1 -1
  5. package/dist/assets/{Build-BesaIcQt.js → Build-DTcg9gkb.js} +1 -1
  6. package/dist/assets/{Calendars-PHb_rEbJ.js → Calendars-x_EpS-cd.js} +1 -1
  7. package/dist/assets/{Cluster-CnMcgkaB.js → Cluster-aj2_8TZC.js} +1 -1
  8. package/dist/assets/{ComposedDeviceEditDialog-DlxMQhZP.js → ComposedDeviceEditDialog-DNGwDK80.js} +1 -1
  9. package/dist/assets/{CompositionBlockEditor-Ctx6d-qx.js → CompositionBlockEditor-O3eDPOLD.js} +1 -1
  10. package/dist/assets/{CompositionEditorPage-CVp1OM-C.js → CompositionEditorPage-D09wEj7N.js} +1 -1
  11. package/dist/assets/{Data-OpXlBhEa.js → Data-D4Sz8Rl9.js} +1 -1
  12. package/dist/assets/{DeviceDetail-CUzPIb4E.js → DeviceDetail-BE-C2aGY.js} +1 -1
  13. package/dist/assets/{Devices-DFfVPHVt.js → Devices-BBsDc0QJ.js} +1 -1
  14. package/dist/assets/{History-BLJJzgUt.js → History-TMZn0v_I.js} +1 -1
  15. package/dist/assets/{Identity-B_TiHuO-.js → Identity-DNIHuEKY.js} +1 -1
  16. package/dist/assets/{IntegrationDetail-DtTxTigM.js → IntegrationDetail-CYhU0hEL.js} +1 -1
  17. package/dist/assets/{IntegrationHub-BvDB6bjh.js → IntegrationHub-DviGnYgu.js} +1 -1
  18. package/dist/assets/{Integrations-CK3qys8g.js → Integrations-9bupF3uw.js} +1 -1
  19. package/dist/assets/{Integrations-Xub2OY5T.js → Integrations-B7okjAJ8.js} +1 -1
  20. package/dist/assets/{Library-CO10lVu2.js → Library-BHn4Iifg.js} +1 -1
  21. package/dist/assets/{Locations-CaL7Y2a3.js → Locations-BVaRTbq0.js} +1 -1
  22. package/dist/assets/{Logs-Bu40SOPP.js → Logs-DI7IZGug.js} +1 -1
  23. package/dist/assets/{MyAccess-CNQzuYsW.js → MyAccess-YiGVb3gF.js} +1 -1
  24. package/dist/assets/{Network-BBm6sZIX.js → Network-ZYEqAiF5.js} +1 -1
  25. package/dist/assets/{NodeAddonsSettingsPanel-DZwxKBXw.js → NodeAddonsSettingsPanel-Chb7RIE6.js} +1 -1
  26. package/dist/assets/{Notifications-BS4cbFH2.js → Notifications-DrVDMEuK.js} +1 -1
  27. package/dist/assets/{Pipeline-BhNYn1U-.js → Pipeline-BT9k34b_.js} +1 -1
  28. package/dist/assets/{Recordings-B8VQL_Ik.js → Recordings-Dl-l1Vzi.js} +1 -1
  29. package/dist/assets/{ScanNetworkModal-SyHjZF2T.js → ScanNetworkModal-Cq9BlXXk.js} +1 -1
  30. package/dist/assets/{SessionsList-BD87Vhfu.js → SessionsList-84zwfhuD.js} +1 -1
  31. package/dist/assets/{Showroom-BS88iBLb.js → Showroom-Crq5JUKV.js} +1 -1
  32. package/dist/assets/{System-D-Xj3jc0.js → System-CfurcyNZ.js} +1 -1
  33. package/dist/assets/{Terminal-DhbVA89N.js → Terminal-UyKanKPS.js} +1 -1
  34. package/dist/assets/{device-integration-icon-D-OosuOg.js → device-integration-icon-BpHHi90B.js} +1 -1
  35. package/dist/assets/{index-DMMw81r0.js → index-DGvsu0ui.js} +2 -2
  36. package/dist/assets/{mf-entry-bootstrap-0-dd19d57d.js → mf-entry-bootstrap-0-3390b09e.js} +1 -1
  37. package/dist/assets/{step-inspector-model-DINPtCNq.js → step-inspector-model-D6NC9QoX.js} +1 -1
  38. package/dist/assets/{useNodeUrlSelection-A-NDcCsx.js → useNodeUrlSelection-DytighTL.js} +1 -1
  39. package/dist/index.html +2 -2
  40. package/dist/server/addon.js +1 -1
  41. package/package.json +4 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.530] - 2026-10-31
11
+
12
+ ### Changed
13
+
14
+ - Admin UI is now hub-only: it is removed from agents that still carry it
15
+
10
16
  ## [1.2.529] - 2026-10-31
11
17
 
12
18
  ### Changed
@@ -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{Ai as d,Dn as f,Ei as p,Gn as m,Ht as h,Mn as g,Pt as _,Q as v,Qr as y,gn as b,gt as x,ki as S,ot as C,pi as w,pr as T,sn as E,st as ee,vn as D,xi as te,yn as ne,zt as re}from"./player-overlays-DpZIxQHp.js";import{Zo as O}from"./client-BvflqtP1.js";import{d as ie,i as k}from"./video-D0guHpd1.js";import{$i as ae,Bi as A,Ct as j,Er as oe,Gi as M,Gn as N,Hi as se,Ii as P,Ji as F,Jn as I,Ki as ce,Kn as L,Li as R,Mt as z,Oc as B,Pd as le,Pi as V,Qi as ue,Ri as de,Sr as fe,Tr as pe,Ui as me,Vi as H,Yi as he,Zi as ge,af as U,br as _e,cf as W,cn as ve,ea as ye,fi as G,ia as be,ii as K,na as xe,qi as Se,qn as Ce,ra as we,sn as Te,wr as Ee,xr as q,zd as De,zi as Oe}from"./src-KDhMZ5Ob.js";import{t as J}from"./Trans-Bsz5Pghy.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import"./mount-2dkiqOI6.js";import{Q as X,et as ke}from"./index-DMMw81r0.js";import{t as Z}from"./AdminPage-DmkuRREx.js";import{t as Ae}from"./NodeAddonsSettingsPanel-DZwxKBXw.js";import{t as je}from"./framework-packages-B7oma9J4.js";import{n as Q,t as Me}from"./useNodeUrlSelection-A-NDcCsx.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:w,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:T,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:f,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:d,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:k,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Fe({item:e}){let{t:n}=Y(),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`]),Le=new Set([`done`,`failed`,`skipped`]);function Re(e){return!Le.has(e.phase)&&!Ie.has(e.jobState)}function ze(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 Be(){let{data:e}=ce({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=W(O.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 ze([...n.values()],Date.now())},[e,t])}var Ve={queued:{icon:w,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:T,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:d,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:k,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:E,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function He({progress:e}){let{t:n}=Y(),r=Ve[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 Ue(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 We(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function Ge(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(We)];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{Ai as d,Dn as f,Ei as p,Gn as m,Ht as h,Mn as g,Pt as _,Q as v,Qr as y,gn as b,gt as x,ki as S,ot as C,pi as w,pr as T,sn as E,st as ee,vn as D,xi as te,yn as ne,zt as re}from"./player-overlays-DpZIxQHp.js";import{Zo as O}from"./client-BvflqtP1.js";import{d as ie,i as k}from"./video-D0guHpd1.js";import{$i as ae,Bi as A,Ct as j,Er as oe,Gi as M,Gn as N,Hi as se,Ii as P,Ji as F,Jn as I,Ki as ce,Kn as L,Li as R,Mt as z,Oc as B,Pd as le,Pi as V,Qi as ue,Ri as de,Sr as fe,Tr as pe,Ui as me,Vi as H,Yi as he,Zi as ge,af as U,br as _e,cf as W,cn as ve,ea as ye,fi as G,ia as be,ii as K,na as xe,qi as Se,qn as Ce,ra as we,sn as Te,wr as Ee,xr as q,zd as De,zi as Oe}from"./src-KDhMZ5Ob.js";import{t as J}from"./Trans-Bsz5Pghy.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import"./mount-2dkiqOI6.js";import{Q as X,et as ke}from"./index-DGvsu0ui.js";import{t as Z}from"./AdminPage-DmkuRREx.js";import{t as Ae}from"./NodeAddonsSettingsPanel-Chb7RIE6.js";import{t as je}from"./framework-packages-B7oma9J4.js";import{n as Q,t as Me}from"./useNodeUrlSelection-DytighTL.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:w,bg:`bg-muted text-foreground-subtle`,labelKey:`addons.addonRowBadge.queued`},updating:{icon:T,bg:`bg-primary/10 text-primary`,labelKey:`addons.addonRowBadge.updating`,spin:!0},"done-pending-restart":{icon:f,bg:`bg-amber-500/10 text-amber-700`,labelKey:`addons.addonRowBadge.pendingRestart`},done:{icon:d,bg:`bg-success/10 text-success`,labelKey:`addons.addonRowBadge.done`},failed:{icon:k,bg:`bg-danger/10 text-danger`,labelKey:`addons.addonRowBadge.failed`}};function Fe({item:e}){let{t:n}=Y(),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`]),Le=new Set([`done`,`failed`,`skipped`]);function Re(e){return!Le.has(e.phase)&&!Ie.has(e.jobState)}function ze(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 Be(){let{data:e}=ce({activeOnly:!0},{refetchOnWindowFocus:!1,refetchInterval:e=>(e.state.data?.length??0)>0?3e3:!1}),{map:t}=W(O.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 ze([...n.values()],Date.now())},[e,t])}var Ve={queued:{icon:w,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.queued`},fetching:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.fetching`,spin:!0},staged:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.staged`,spin:!0},validating:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.validating`,spin:!0},applying:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.applying`,spin:!0},restarting:{icon:T,cls:`bg-amber-500/10 text-amber-600 dark:text-amber-400`,labelKey:`addons.jobProgress.restarting`,spin:!0},applied:{icon:T,cls:`bg-primary/10 text-primary`,labelKey:`addons.jobProgress.finalizing`,spin:!0},done:{icon:d,cls:`bg-success/10 text-success`,labelKey:`addons.jobProgress.updated`},failed:{icon:k,cls:`bg-danger/10 text-danger`,labelKey:`addons.jobProgress.failed`},skipped:{icon:E,cls:`bg-muted text-foreground-subtle`,labelKey:`addons.jobProgress.skipped`}};function He({progress:e}){let{t:n}=Y(),r=Ve[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 Ue(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 We(e){let t=e.version===null?``:` ${e.version}`,n=e.isOnline?``:` (offline: removed when it reconnects)`;return`- ${e.nodeName}${t}${n}`}function Ge(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(We)];return n.length>0&&r.push(`Could not ask: ${n.join(`, `)} — not included.`),r.push(`This cannot be undone.`),r.join(`
2
2
  `)}function Ke(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 qe={uninstalled:`uninstalled`,"not-installed":`was not installed`,refused:`REFUSED`,failed:`FAILED`,"pending-reconnect":`offline — removed when it reconnects`};function Je(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)}: ${qe[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 Ye={},Xe=3e4,Ze=`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 Qe({packageName:e,displayName:n,selectedNode:r,hideNodeAction:i,disabled:o}){let{t:s}=Y(),c=l(),u=ee(),d=C(),f=M(Ye,{staleTime:Xe}),p=f.data?.installations??[],m=(f.data?.unreachable??[]).map(e=>e.nodeId),g=Ue(p,e),_=e=>g.find(t=>t.nodeId===e)?.nodeName??(e===r.id?r.name:e),v=we({onSettled:()=>{c.invalidateQueries({queryKey:[[`addons`]]}),c.invalidateQueries({queryKey:[[`addonPages`]]}),c.invalidateQueries({queryKey:[[`capabilities`]]}),c.invalidateQueries({queryKey:[[`nodes`]]})}}),y=async e=>{await d({title:e.success?s(`addons.addonUninstallControls.uninstalled`,`{{displayName}} uninstalled`,{displayName:n}):s(`addons.addonUninstallControls.notEveryNodeWasCleaned`,`{{displayName}}: not every node was cleaned`,{displayName:n}),message:Je(e,_),variant:e.success?`default`:`danger`})},b=async t=>{try{await y(await v.mutateAsync({packageName:e,...t}))}catch(e){await d({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:Ke(n,r.name,e),confirmLabel:s(`addons.addonUninstallControls.uninstall`,`Uninstall`),variant:`danger`})&&await b(r.isHub?{}:{nodeId:r.id})},S=async()=>{let t=(await f.refetch()).data;if(t===void 0){await d({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=Ue(t.installations,e);await u({title:s(`addons.addonUninstallControls.uninstallEverywhere`,`Uninstall {{displayName}} everywhere?`,{displayName:n}),message:Ge(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})},w=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:w,className:Ze,title:s(`addons.addonUninstallControls.uninstallFrom2`,`Uninstall from {{name}}`,{name:r.name}),children:[a(h,{className:`h-3 w-3`}),v.isPending?s(`addons.addonUninstallControls.removing`,`Removing...`):s(`addons.addonUninstallControls.uninstall`,`Uninstall`)]}),(g.length>1||i===!0||m.length>0)&&t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),S()},disabled:w,className:Ze,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 $e(e){return typeof e.deprecated==`string`&&e.deprecated.length>0}function et(e,t){return t?e:e.filter(e=>e.distTags.includes(`latest`)||!$e(e))}function tt(e){return e.length-et(e,!1).length}c();function nt({packageName:e,currentVersion:n,installSource:r,onInstall:i,onClose:o,onSelect:c,selectedVersion:l}){let{t:f}=Y(),p=r===`upload`||r===`local`,[m,h]=s(!1),{data:g,isLoading:v,isError:b}=H({name:e}),S=g?et(g,m):[],C=g?tt(g):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:f(`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`})})]}),p&&t(`div`,{className:`flex items-start gap-2 px-3 py-2 border-b border-border bg-cyan-500/10 text-[10px]`,children:[a(_,{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:f(`addons.versionPicker.inPlace`,{kind:r===`upload`?f(`addons.versionPicker.uploadedCopy`,`Uploaded copy`):f(`addons.versionPicker.localCopy`,`Local copy`)})}),` `,a(J,{i18nKey:`addons.versionPicker.reinstall`,values:{version:n},components:{mono:a(`span`,{className:`font-mono`})}})]})]}),v&&t(`div`,{className:`flex items-center justify-center gap-2 py-6 text-[10px] text-foreground-subtle`,children:[a(T,{className:`h-3.5 w-3.5 animate-spin`}),f(`addons.versionPicker.loadingVersions`,`Loading versions...`)]}),b&&a(`div`,{className:`px-3 py-4 text-center text-[10px] text-danger`,children:f(`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),p=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:f(`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)),$e(e)&&a(`span`,{className:`text-[9px] text-red-400 line-through`,children:f(`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":f(`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:[p,o?a(d,{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:[p,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?f(`addons.versionPicker.reInstallFromNpm`,`Re-install {{version}} from npm`,{version:e.version}):f(`addons.versionPicker.install`,`Install {{version}}`,{version:e.version}),children:a(y,{className:`h-3 w-3`})})]},e.version)})}),!v&&!b&&g&&g.length===0&&a(`div`,{className:`py-4 text-center text-[10px] text-foreground-subtle`,children:f(`addons.versionPicker.noVersionsFound`,`No versions found`)}),C>0&&a(K,{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?f(`addons.versionPicker.hideOlder`,`Hide older versions`):f(`addons.versionPicker.showOlder`,`Show older versions ({{count}})`,{count:C})})]})}c();var rt=`device-export`;function it(e){return e.capabilities.some(e=>(typeof e==`string`?e:e.name)===rt)}function at(e){return e!==`local`&&e!==`upload`}function ot({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?v(`/api/addon-assets/${r}/${i}`):null,p=!!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:p?a(`img`,{src:f,alt:r,className:`h-4 w-4`,onError:()=>l(!0)}):a(e?m:g,{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`}),at(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(_,{className:`h-2.5 w-2.5 text-white`})})]})}function st({version:e,availableUpdate:n,selectedVersion:r,isUpdating:i,installSource:o,disabled:s,onUpdate:c,onOpenPicker:l,children:u}){let{t:d}=Y();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(T,{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(y,{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(S,{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(S,{className:`h-3 w-3 opacity-50`})]}),u]})}function ct({addonId:e}){let t=l(),{data:n=`inherit`}=R({addonId:e}),r=ae({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 lt={id:`hub`,name:`Hub`,isHub:!0};function ut({addon:e,clusterStatus:n,hideVersion:r,availableUpdate:i,onUpdate:c,isUpdating:d,jobProgress:h,bundle:g,bulkItem:_,disabledByBulk:v,isSystem:y,selectedNode:C}){let{t:w}=Y(),[T,E]=s(!1),[ee,D]=s(!1),[te,re]=s(null);o(()=>{re(null)},[i]);let O=te??i,[ie,ae]=s(!1),[A,j]=s(!1),[M,N]=s(`logs`),P=l(),F=X(),{manifest:I}=e,ce=!g&&!I.protected&&I.removable!==!1,L=!!g,R=g?.displayName??I.name,B=g?.packageName??I.packageName,le=g?.version??I.packageVersion??I.version,V=g?.installSource??e.installSource,ue=g?g.bundle?.description??g.addons[0]?.manifest.description:I.description,de=he({onSuccess:()=>{P.invalidateQueries({queryKey:[[`addons`]]})}}),me=se({onSuccess:()=>{P.invalidateQueries({queryKey:[[`addons`]]}),P.invalidateQueries({queryKey:[[`addonPages`]]}),P.invalidateQueries({queryKey:[[`capabilities`]]}),P.invalidateQueries({queryKey:[[`integrations`]]})}}),H=ge({onSuccess:()=>{P.invalidateQueries({queryKey:[[`addons`]]}),P.invalidateQueries({queryKey:[[`alerts`]]})}}),U=e.health,W=U?.phase===`failed`&&!U.inGracePeriod,ye=W&&U?.nextRetryAt&&!U.retrying,G=Ne(e.process);return t(`div`,{className:`rounded-md border bg-surface overflow-hidden ${W?`border-red-500/50`:`border-border`}`,children:[W&&U&&t(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[a(k,{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:w(`addons.addonCard.failedToLoad`,{attempt:U.retryCount})}),a(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:U.lastError?.message??w(`addons.addonCard.unknownError`,`Unknown error`)}),ye&&U.nextRetryAt&&a(`div`,{className:`text-[10px] text-foreground-subtle mt-1`,children:w(`addons.addonCard.autoRetryAt`,{time:new Date(U.nextRetryAt).toLocaleTimeString()})})]}),t(`button`,{type:`button`,disabled:H.isPending||U.retrying,onClick:e=>{e.stopPropagation(),H.mutate({packageName:B})},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:w(`addons.addonCard.resetRetryCounterAndForce`,`Reset retry counter and force immediate reload`),children:[a(f,{className:`h-3 w-3 ${H.isPending||U.retrying?`animate-spin`:``}`}),w(`addons.addonCard.retryNow`,`Retry now`)]})]}),G!==null&&t(`div`,{className:`bg-danger/10 border-b border-danger/30 px-3 py-2 flex items-start gap-2`,children:[a(k,{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:w(`addons.addonCard.processProblem.${G.kind}`)}),G.reason!==void 0&&a(`div`,{className:`text-[11px] text-foreground mt-0.5 break-words font-mono`,children:G.reason})]})]}),t(`div`,{className:`flex items-start gap-2.5 px-3 py-2`,children:[a(ot,{isBundle:L||!!I.components&&I.components.length>1,installSource:V,addonId:L?g.addons[0]?.manifest.id:I.id,iconPath:L?g.bundle?.icon??g.addons[0]?.manifest.icon:I.icon,color:L?g.addons[0]?.manifest.color:I.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:R}),!r&&a(st,{version:le,availableUpdate:i,...O===void 0?{}:{selectedVersion:O},isUpdating:d,installSource:V,disabled:v,...c&&O!==void 0?{onUpdate:()=>c(O)}:{},onOpenPicker:()=>D(e=>!e),children:ee&&a(nt,{packageName:B,currentVersion:le,...V?{installSource:V}:{},...i!==void 0&&O!==void 0?{selectedVersion:O,onSelect:e=>{re(e),D(!1)}}:{},onInstall:e=>{D(!1),me.mutate({packageName:B,version:e})},onClose:()=>D(!1)})})]}),t(`div`,{className:`flex flex-wrap items-center gap-x-1.5 gap-y-1 mt-0.5`,children:[B!==R&&a(`span`,{className:`text-[10px] text-foreground-subtle font-mono truncate max-w-full`,children:B}),L&&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(m,{className:`h-3 w-3`}),g.addons.length]}),y&&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:w(`addons.addonCard.systemPackageUpdatingRestartsThe`,`System package — updating restarts the hub`),children:[a(f,{className:`h-3 w-3`}),w(`addons.addonCard.system`,`System`)]}),_!=null&&a(Fe,{item:_}),h!=null&&a(He,{progress:h})]}),ue&&a(`p`,{className:`text-[10px] text-foreground-subtle mt-1 line-clamp-1`,children:ue}),!L&&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`?w(`addons.addonCard.forked`):w(`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`:G===null?`bg-gray-500/15 text-gray-400`:`bg-red-500/15 text-red-400`}`,children:e.process.state})]})]})]}),!L&&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(),de.mutate({addonId:I.id})},disabled:de.isPending||v,className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border border-border text-foreground-subtle hover:text-blue-400 hover:border-blue-500/30 hover:bg-blue-500/10 disabled:opacity-50 transition-colors`,children:[a(f,{className:`h-3 w-3 ${de.isPending?`animate-spin`:``}`}),w(`addons.addonCard.restart`,`Restart`)]}),t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ae(e=>!e)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${ie?`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(ne,{className:`h-3 w-3`}),w(`addons.addonCard.logs`,`Logs`)]}),!L&&t(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),j(!0)},className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium border transition-colors ${A?`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(b,{className:`h-3 w-3`}),w(`addons.addonCard.settings`,`Settings`)]}),a(`div`,{className:`flex-1`}),ce&&a(Qe,{packageName:I.packageName,displayName:I.name,selectedNode:C??lt,disabled:v})]}),n&&n.nodes.length>1&&!L&&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:w(`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:w(`addons.addonCard.outdated`)}),e.status===`offline`&&a(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground`,children:w(`common.offline`)}),e.synced&&e.status!==`offline`&&a(`span`,{className:`text-[9px] text-success`,children:w(`common.synced`)})]},e.nodeId))})]}),ie&&!L&&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:()=>N(`logs`),className:`px-2 py-0.5 transition-colors ${M===`logs`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:w(`addons.addonCard.logs`,`Logs`)}),a(`button`,{type:`button`,onClick:()=>N(`events`),className:`px-2 py-0.5 border-l border-border transition-colors ${M===`events`?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`}`,children:w(`addons.addonCard.events`,`Events`)})]}),a(`div`,{className:`flex-1`}),a(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),ae(!1)},className:`text-foreground-subtle hover:text-foreground`,children:a(x,{className:`h-3.5 w-3.5`})})]}),M===`logs`&&a(ve,{addonId:I.id,maxHeight:`max-h-64`,showFilters:!1}),M===`events`&&a(Te,{addonId:I.id,category:`addon.*`,maxHeight:`max-h-64`})]}),L&&t(u,{children:[a(`button`,{type:`button`,onClick:()=>E(e=>!e),className:`w-full flex items-center justify-center border-t border-border py-1 hover:bg-surface-hover/50 transition-colors`,children:a(T?p:S,{className:`h-3.5 w-3.5 text-foreground-subtle`})}),T&&a(`div`,{className:`border-t border-border px-2.5 py-1.5 space-y-1.5`,children:g.addons.map(e=>a(ut,{addon:e,hideVersion:!0},e.manifest.id))})]}),A&&!L&&a(_e,{open:!0,onOpenChange:e=>!e&&j(!1),children:t(fe,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(pe,{children:t(oe,{className:`flex items-center gap-2`,children:[a(b,{className:`h-4 w-4 text-primary`}),w(`addons.addonCard.settingsTitle`,{name:R})]})}),t(q,{className:`space-y-4`,children:[a(`div`,{className:`text-[10px] text-foreground-subtle mb-2`,children:w(`addons.addonCard.clusterWideSettingsOneValue`,`Cluster-wide settings — one value for every node. Per-node settings live under Cluster → the node → Settings.`)}),a(Ae,{nodeId:null,addonIds:[I.id],level:`global`,fieldScope:`cluster`,emptyMessage:w(`addons.addonCard.thisAddonExposesNoCluster`,`This addon exposes no cluster-wide settings. Anything it can configure is per-node — open it from Cluster → the node → Settings.`)}),it(I)&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:w(`addons.addonCard.deviceExport`,`Device export`)}),a(z,{addonId:I.id,onOpenDevice:e=>F(`/devices/${e}`)})]}),at(V)&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:w(`addons.addonCard.autoUpdate`,`Auto-Update`)}),a(ct,{addonId:I.id})]}),I.components&&I.components.length>0&&t(`div`,{children:[a(`div`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:w(`addons.addonCard.components`,{count:I.components.length})}),a(`div`,{className:`flex flex-wrap gap-1`,children:I.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(Ee,{children:a(K,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>j(!1),children:w(`common.close`,`Close`)})})]})})]})}c();var dt=`.tgz,.tar.gz,.zip`;function ft({onUploadSuccess:e}){let{t:r}=Y(),[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(v(`/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:dt,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(T,{className:`w-3.5 h-3.5 animate-spin`}):a(_,{className:`w-3.5 h-3.5`}),o?r(`addons.addonUploadZone.uploading`,`Uploading...`):r(`addons.addonUploadZone.upload`,`Upload`)]})]})}var pt=/```[^\n]*\n([\s\S]*?)```/g;function mt(e){let t=[],n=0;for(let r of e.matchAll(pt)){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 ht(e){let t=e.trim();return t.startsWith(`https://`)||t.startsWith(`http://`)?t:null}function gt(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?ht(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 _t(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{bt as r}from"./src-KDhMZ5Ob.js";import{et as i}from"./index-DMMw81r0.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{bt as r}from"./src-KDhMZ5Ob.js";import{et as i}from"./index-DGvsu0ui.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{Bi as d,D as f,Dn as p,Fi as m,Fn as h,Fr as g,G as _,Hn as v,Ht as y,In as b,L as x,Q as S,Qr as C,_n as w,dt as T,gt as E,ia as D,ii as O,pr as k,rn as A,si as j,st as M,tn as N,vn as P,zi as F}from"./player-overlays-DpZIxQHp.js";import{Jo as ee,ai as I,ii as L,oi as R}from"./client-BvflqtP1.js";import{n as z,t as te}from"./send-Dd0BBamd.js";import{t as ne}from"./message-square-plus-rkd_X0vs.js";import{An as B,Bd as re,Dn as V,Et as H,Fr as U,Io as W,Ir as ie,Lr as G,Pd as K,Pr as q,Tt as ae,Wr as oe,Yn as se,Zn as ce,_t as J,ar as le,ct as ue,fi as Y,ii as X,kn as de,pr as fe,yt as pe,zd as me}from"./src-KDhMZ5Ob.js";import{t as Z}from"./i18n-Bg2ooh3q.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-2dkiqOI6.js";import{b as he,et as ge}from"./index-DMMw81r0.js";import{t as _e}from"./AdminSectionedPage-B_tSbkIV.js";import{t as ve}from"./AdminPage-DmkuRREx.js";c();var ye=`__redacted__`,be=[`llm`,`listProfiles`],xe=[`llm`,`listProfileKinds`],Se=[`llm`,`getDefaults`],Ce=[`llm`,`listRuntimeNodes`],we=[`llm`,`listModelCatalog`],Te=[`llm`,`getUsage`],Ee=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],De=new Map([[`cloud`,j],[`plug`,h],[`cpu`,O],[`server`,w],[`sparkles`,A]]);function Oe(e){return De.get(e)??d}function ke(e){return typeof e==`string`&&e.length>0?e:void 0}function Ae(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function je(e){return e===!0}function Me(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Ne={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Pe(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:Z.t(`ai.appleUnknown`),detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:Z.t(`ai.appleAvailable`),detail:Z.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Ne[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:Z.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:Z.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var Fe={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`},Ie={ready:`ai.stateReady`,downloading:`ai.stateDownloading`,starting:`ai.stateStarting`,stopped:`ai.stateStopped`,crashed:`ai.stateCrashed`,failed:`ai.stateFailed`};function Le(e){return e.reachable?e.status===void 0?`ai.stateReady`:Ie[e.status.state]:`ai.unreachable`}function Re(e){return e.reachable?e.status===void 0?`success`:Fe[e.status.state]:`danger`}function ze(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Pe(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Pe(e);t.push({id:`apple`,labelKey:`ai.featureApple`,tone:n.tone,detail:n.labelDefault})}let r=e.status?.vramBytes;return r!==void 0&&r>0&&t.push({id:`gpu`,labelKey:`ai.featureGpu`,tone:`info`,detail:null}),t}var Be=`default`;function Ve(e){let t=L.shape.reasoningEffort.safeParse(e);return t.success?t.data:void 0}function He(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],reasoningEffort:[{type:`select`,key:`reasoningEffort`,label:Z.t(`helpers.aiProfileForm.reasoningEffort`),default:Be,options:[{value:Be,label:Z.t(`helpers.aiProfileForm.reasoningDefault`)},{value:`off`,label:Z.t(`helpers.aiProfileForm.reasoningOff`)},{value:`low`,label:Z.t(`helpers.aiProfileForm.reasoningLow`)},{value:`medium`,label:Z.t(`helpers.aiProfileForm.reasoningMedium`)},{value:`high`,label:Z.t(`helpers.aiProfileForm.reasoningHigh`)}],description:Z.t(`helpers.aiProfileForm.reasoningEffortHint`)}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:R.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:R.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:R.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:R.idleMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutIdleHint`)}],retry:[{type:`boolean`,key:`retryEnabled`,label:Z.t(`helpers.aiProfileForm.retry`),description:Z.t(`helpers.aiProfileForm.retryHint`)},{type:`number`,key:`retryMaxAttempts`,label:Z.t(`helpers.aiProfileForm.retryMaxAttempts`),min:1,max:5,default:1,showWhen:{field:`retryEnabled`,equals:!0}}],toolsEnabled:[{type:`boolean`,key:`toolsEnabled`,label:Z.t(`helpers.aiProfileForm.toolsEnabled`),description:Z.t(`helpers.aiProfileForm.toolsEnabledHint`)}]}}var Ue=[`temperature`,`topP`,`topK`,`maxTokens`,`reasoningEffort`,`contextLength`,`systemPrompt`],We=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function Ge(e,t){let n=He();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Ke(e){let t=Ge(e,Ue);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function qe(e){let t=Ge(e,We);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function Je(e){return e===null?{}:{temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,reasoningEffort:e.reasoningEffort??Be,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled}}function Ye(e,t){return{...e.features,...t?.features}}function Xe(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ze(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?Ae(i[e])??t:n??t,o=e=>r.includes(e)?Ae(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`reasoningEffort`)?Ve(i.reasoningEffort):t?.reasoningEffort,p=r.includes(`systemPrompt`)?ke(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,R.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,R.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,R.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,R.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:je(i.retryEnabled),maxAttempts:Ae(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?je(i.toolsEnabled):t?.toolsEnabled??!1,...s===void 0?{}:{temperature:s},...c===void 0?{}:{topP:c},...l===void 0?{}:{topK:l},...u===void 0?{}:{maxTokens:u},...f===void 0?{}:{reasoningEffort:f},...d===void 0?{}:{contextLength:d},...p===void 0?{}:{systemPrompt:p},providerConfig:n.providerConfig}}var Qe=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function $e(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function et({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=T(),[d,f]=o(``),[p,m]=o(null),[h,g]=o(!1),_=s({queryKey:we,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),v=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:t})}),y=l({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:e=>u.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{g(!0),v.refetch()}}),x=s({queryKey:Ce,enabled:b.isPending,refetchInterval:b.isPending?Qe:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,S=n(()=>{let e=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:$(e.sizeBytes),node:t})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[_.data,v.data,p,t,c]),w=e=>{if(e===``){a(null);return}if(e===`custom`){if(p?.ok!==!0)return;a({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},E=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(H,{label:c(`ai.model`,`Model`),required:!0,children:i(K,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:$e(r),options:S,onChange:e=>w(e.target.value)})}),i(H,{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(me,{"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(),E())}}),e(X,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>E(),children:[y.isPending?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(P,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),y.isError&&i(q,{message:y.error instanceof Error?y.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(q,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(X,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>E(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(Y,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(Y,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(X,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(C,{className:`h-3.5 w-3.5`}),h?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),x!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:x.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:x.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:x.file,index:x.fileIndex,count:x.fileCount,done:$(x.downloadedBytes),total:x.totalBytes===void 0?``:` / ${$(x.totalBytes)}`})})]}),b.isError&&i(q,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)})]})]})}function tt({value:t,onChange:n}){let{t:r}=Q(),a=T(),o=s({queryKey:Ce,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(k,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=Pe(a),s=o.nodeId===t;return e(`button`,{type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(Y,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function nt(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function rt({providerConfig:e,onProviderConfigChange:t}){return i(tt,{value:nt(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function it({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=I.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(et,{nodeId:nt(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var at=new Map([[`ai/apple-node`,rt],[`ai/managed-model`,it]]);function ot(e){return at.get(e)??null}c();function st({kind:e,className:t}){return i(Oe(e.icon),{className:t,"aria-hidden":!0})}function ct({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>Me(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(pe,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(ae,{emptyMessage:a(`ai.noKinds`,`No AI provider is installed.`),onPick:e=>{let n=s.get(e);n!==void 0&&t(n)},groups:o.map(e=>({id:e.addonId,label:e.addonId,tiles:e.kinds.map(t=>({key:`${e.addonId}:${t.kind}`,label:t.label,testId:`ai-kind-${t.kind}`,icon:i(st,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function lt(e){return(e?.sections??[]).flatMap(e=>e.fields)}function ut(...e){let t={};for(let n of e)for(let e of lt(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function dt(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function ft(e,t){return lt(e).filter(e=>`required`in e&&e.required===!0&&!dt(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var pt={auth:{key:`ai.listAuth`,fallback:`Credentials refused`},network:{key:`ai.listNetwork`,fallback:`Endpoint unreachable`},unsupported:{key:`ai.listUnsupported`,fallback:`No model list`},invalid:{key:`ai.listInvalid`,fallback:`Connection incomplete`}};function mt(e,t){if(t!==null)return{id:t.model,supportsVision:t.supportsVision};let n=e.modelCatalog===`static`&&e.staticModels?.length===1?e.staticModels?.[0]:void 0;return{id:n?.id??``,supportsVision:Ye(e,n).vision}}function ht({kind:t,existing:r,onSave:s,onCancel:c,onChangeKind:d,saving:m,error:h}){let{t:g}=Q(),_=T(),[v,y]=o(r?.name??t.label),[b,S]=o(()=>r===null?ut(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[C,w]=o(()=>Je(r)),[E,O]=o(()=>mt(t,r)),[A,j]=o(!1),M=t.providerWidgets??[],N=M.filter(e=>e.placement===`connection`),P=M.find(e=>e.placement===`model`)??null,F=n(()=>[...ee(t.connectionSchema)].some(e=>r?.providerConfig[e]===ye),[r,t.connectionSchema]),I=l({mutationFn:()=>_.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:b,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&O(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ye(t,r).vision}})}}),L=Xe(t,I.data?.ok===!0?I.data.models:null),R=L.find(e=>e.id===E.id),z=Ye(t,R),te=Ke(t.profileFields),ne=qe(t.profileFields),B=ft(t.connectionSchema,b),re=M.some(e=>(e.requires??[]).some(e=>!dt(b[e]))),U=t.modelCatalog===`fetch`&&P===null,W=lt(t.connectionSchema).length>0||N.length>0,ie=r!==null&&U&&B.length===0;a(()=>{ie&&I.mutate()},[]);let G=e=>{O({id:e,supportsVision:Ye(t,L.find(t=>t.id===e)).vision})},ae=m||v.trim()===``||E.id.trim()===``||B.length>0||re,oe=()=>{s(Ze(t,r,{name:v.trim(),model:E.id.trim(),supportsVision:t.visionEditable?E.supportsVision:!1,common:C,providerConfig:b}))},ce=r===null?g(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):g(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),J=e=>{let n=ot(e);return n===null?i(q,{variant:`warning`,message:g(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})}):i(n,{descriptor:t,providerConfig:b,onProviderConfigChange:S,model:E,onModelChange:O},e)};return i(pe,{open:!0,onClose:c,title:ce,error:h,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[B.length>0&&i(Y,{variant:`warning`,children:g(`ai.missingRequired`,`required: {{fields}}`,{fields:B.join(`, `)})}),B.length===0&&re&&i(Y,{variant:`warning`,children:g(`ai.completeProvider`,`complete the provider settings`)}),B.length===0&&!re&&E.id.trim()===``&&i(Y,{variant:`warning`,children:g(`ai.pickModelFirst`,`pick a model`)}),e(X,{size:`sm`,type:`button`,disabled:ae,onClick:oe,children:[m&&i(k,{className:`h-3.5 w-3.5 animate-spin`}),r===null?g(`ai.createProfile`,`Create profile`):g(`ai.saveChanges`,`Save changes`)]})]}),children:e(`div`,{className:x,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`ai-editor-provider`,children:[i(st,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(Y,{variant:`neutral`,children:t.addonId}),d!==void 0&&e(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:d,children:[i(D,{className:`h-3.5 w-3.5`}),g(`ai.changeKind`,`Change type`)]})]}),i(H,{label:g(`ai.name`,`Name`),required:!0,children:i(me,{id:`ai-profile-name`,"aria-label":g(`ai.name`,`Name`),value:v,onChange:e=>y(e.target.value),placeholder:t.label})}),W&&i(V,{headingId:`ai-editor-connection`,title:g(`ai.sectionConnection`,`Connection`),actions:U?e(X,{size:`sm`,variant:`secondary`,type:`button`,disabled:I.isPending,onClick:()=>I.mutate(),"data-testid":`ai-verify-models`,children:[I.isPending?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(p,{className:`h-3.5 w-3.5`}),g(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[lt(t.connectionSchema).length>0&&i(fe,{bare:!0,schema:t.connectionSchema,values:b,onChange:S}),N.map(e=>J(e.id)),F&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:g(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)}),I.data?.ok===!0&&i(Y,{variant:`success`,"data-testid":`ai-models-found`,children:g(`ai.modelsFound`,`{{count}} models found`,{count:I.data.models.length})}),I.data?.ok===!1&&i(q,{title:g(pt[I.data.code]?.key??`ai.listNetwork`,pt[I.data.code]?.fallback??`Endpoint unreachable`),message:I.data.message}),I.isError&&i(q,{message:I.error instanceof Error?I.error.message:g(`common.error`,`Error`)})]})}),i(V,{headingId:`ai-editor-model`,title:g(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${f} space-y-3`,children:[P===null?e(u,{children:[L.length>0&&i(K,{id:`ai-model-pick`,"aria-label":g(`ai.selectModel`,`Select a model…`),value:R===void 0?``:R.id,options:[{value:``,label:g(`ai.selectModel`,`Select a model…`)},...L.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&G(e.target.value)}}),i(H,{label:g(`ai.customModel`,`Model id`),description:g(`ai.customModelHint`,`Pick one from the list, or type any model id the provider accepts.`),required:!0,children:i(me,{id:`ai-model-id`,"aria-label":g(`ai.customModel`,`Model id`),value:E.id,onChange:e=>{let n=L.find(t=>t.id===e.target.value);O(n===void 0?{...E,id:e.target.value}:{id:e.target.value,supportsVision:Ye(t,n).vision})},placeholder:L[0]?.id??`model-id`})})]}):J(P.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(E.supportsVision||!t.visionEditable&&z.vision)&&i(Y,{variant:`info`,children:g(`ai.featureVision`,`vision`)}),z.tools&&i(Y,{variant:`neutral`,children:g(`ai.featureTools`,`tools`)}),z.streaming&&i(Y,{variant:`neutral`,children:g(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(H,{orientation:`horizontal`,label:g(`ai.supportsVision`,`Supports vision`),description:g(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(se,{checked:E.supportsVision,onCheckedChange:e=>O({...E,supportsVision:e}),"aria-label":g(`ai.supportsVision`,`Supports vision`)})})]})}),te!==null&&i(V,{headingId:`ai-editor-generation`,title:g(`ai.sectionGeneration`,`Generation`),children:i(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:i(fe,{bare:!0,schema:te,values:C,onChange:w})})}),(ne!==null||t.advancedSchema!==void 0)&&i(le,{expanded:A,onExpandedChange:j,header:i(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:g(`ai.sectionAdvanced`,`Advanced`)}),children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[ne!==null&&i(fe,{bare:!0,schema:ne,values:C,onChange:w}),t.advancedSchema!==void 0&&i(fe,{bare:!0,schema:t.advancedSchema,values:b,onChange:S})]})})]})})}c();function gt(t){return[{key:`name`,header:t.t(`ai.colProfile`,`Profile`),render:n=>{let r=t.kindByName.get(n.kind);return e(`span`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:r?.label??n.kind,children:r===void 0?i(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):i(st,{kind:r,className:`h-4 w-4 text-foreground-subtle`})}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block truncate font-medium text-foreground`,children:n.name}),t.testResult?.id===n.id&&i(`span`,{className:`block truncate ${t.testResult.ok?`text-success`:`text-danger`}`,children:t.testResult.text})]})]})}},{key:`kind`,header:t.t(`ai.colKind`,`Kind`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground-muted`,children:t.kindByName.get(e.kind)?.label??e.kind})},{key:`model`,header:t.t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:t.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:e=>e.supportsVision?i(Y,{variant:`info`,style:`outline`,children:t.t(`ai.vision`,`vision`)}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:t.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?i(Y,{variant:`default`,children:e.providerConfig.nodeId}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:t.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:e=>i(se,{checked:e.enabled,onCheckedChange:()=>t.onToggle(e),"aria-label":Z.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:e.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[i(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest(n),"aria-label":t.t(`ai.test`,`Test`),title:t.t(`ai.test`,`Test`),children:t.testingId===n.id?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(te,{className:`h-3.5 w-3.5`})}),i(X,{size:`sm`,variant:`ghost`,type:`button`,disabled:!t.kindByName.has(n.kind),onClick:()=>t.onEdit(n),"aria-label":t.t(`common.edit`,`Edit`),title:t.t(`common.edit`,`Edit`),children:i(v,{className:`h-3.5 w-3.5`})}),i(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDelete(n),"aria-label":t.t(`common.delete`,`Delete`),title:t.t(`common.delete`,`Delete`),children:i(y,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function _t(){let{t}=Q(),c=T(),{state:u,openEdit:d,close:p}=J(),m=M(),[h,g]=o(null),[_,v]=o(null),[y,b]=o(null),S=s({queryKey:be,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),C=s({queryKey:xe,queryFn:async()=>(await c.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),w=()=>{S.refetch()},E=r(()=>{g(null),b(null),p()},[p]);a(()=>{u.mode===`closed`&&g(null)},[u.mode]);let D=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{E(),w()},onError:e=>b(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)=>v({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}`})}),j=S.data??[],N=n(()=>C.data??[],[C.data]),P=n(()=>{let e=new Map;for(let t of N)e.set(t.kind,t);return e},[N]),F=u.mode===`edit`?j.find(e=>e.id===u.id)??null:null,ee=F===null?null:P.get(F.kind)??null,I=u.mode===`new`&&h===null,L=u.mode===`new`?h:ee,R=u.mode===`edit`?F:null,z=L!==null&&(u.mode===`new`||R!==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:x,children:[i(vt,{profiles:j}),i(V,{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(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):S.isError?i(`div`,{className:f,children:i(q,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:t(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):j.length===0?i(U,{icon:A,title:t(`ai.noProfilesTitle`,`No AI profiles yet`),description:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):i(de,{columns:gt({kindByName:P,testResult:_,testingId:k.isPending?k.variables?.id??null:null,t,onToggle:e=>D.mutate({...e,enabled:!e.enabled}),onTest:e=>k.mutate(e),onEdit:e=>{P.has(e.kind)&&(b(null),g(null),d(e.id))},onDelete:e=>void te(e)}),rows:j,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:B})}),I&&i(ct,{kinds:N,onCancel:E,onPick:e=>{b(null),g(e)}}),z&&L!==null&&i(ht,{kind:L,existing:R,saving:D.isPending,error:y,onSave:e=>D.mutate(e),onCancel:E,...u.mode===`new`?{onChangeKind:()=>{b(null),g(null)}}:{}})]})}function vt({profiles:t}){let{t:n}=Q(),r=T(),a=s({queryKey:Se,queryFn:()=>r.trpcClient.llm.getDefaults.query({})}),o=l({mutationFn:e=>r.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?n(`ai.defaultVision`,`Default vision profile`):n(`ai.defaultText`,`Default text profile`);return i(V,{headingId:`ai-profiles-defaults`,title:n(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:Ee.map(({purpose:r,visionOnly:a})=>{let s=a?t.filter(e=>e.supportsVision):t,l=c(r),d=t.find(e=>e.id===l);return e(`div`,{children:[i(ce,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(K,{id:`llm-default-${r}`,"aria-label":u(r),value:l,onChange:e=>o.mutate({purpose:r,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:n(`ai.none`,`None`)},...l!==``&&!s.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...s.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:n(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:n(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},r)})})})}c();var yt=5e3;function bt(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function xt(){let{t}=Q(),r=T(),a=s({queryKey:Ce,refetchInterval:yt,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(Y,{variant:Re(n),children:t(Le(n))}),n.status?.downloadProgress!==void 0&&i(Y,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:bt(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeature`,`Feature`),render:n=>{let r=ze(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(Y,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(V,{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(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:f,children:i(q,{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(U,{icon:w,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(de,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:B})})}var St=S(`/addon/ai/test-chat`),Ct=S(`/addon/ai/test-chat/chats`),wt=6e5;function Tt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),wt)}function Et(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dt(e){if(!Et(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Ot=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function kt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Et(t))return null;switch(t.kind){case`status`:{let e=Ot.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Dt(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:Z.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*At(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
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{Bi as d,D as f,Dn as p,Fi as m,Fn as h,Fr as g,G as _,Hn as v,Ht as y,In as b,L as x,Q as S,Qr as C,_n as w,dt as T,gt as E,ia as D,ii as O,pr as k,rn as A,si as j,st as M,tn as N,vn as P,zi as F}from"./player-overlays-DpZIxQHp.js";import{Jo as ee,ai as I,ii as L,oi as R}from"./client-BvflqtP1.js";import{n as z,t as te}from"./send-Dd0BBamd.js";import{t as ne}from"./message-square-plus-rkd_X0vs.js";import{An as B,Bd as re,Dn as V,Et as H,Fr as U,Io as W,Ir as ie,Lr as G,Pd as K,Pr as q,Tt as ae,Wr as oe,Yn as se,Zn as ce,_t as J,ar as le,ct as ue,fi as Y,ii as X,kn as de,pr as fe,yt as pe,zd as me}from"./src-KDhMZ5Ob.js";import{t as Z}from"./i18n-Bg2ooh3q.js";import{t as Q}from"./useTranslation-BJr-n0es.js";import"./mount-2dkiqOI6.js";import{b as he,et as ge}from"./index-DGvsu0ui.js";import{t as _e}from"./AdminSectionedPage-Dv8ahC-U.js";import{t as ve}from"./AdminPage-DmkuRREx.js";c();var ye=`__redacted__`,be=[`llm`,`listProfiles`],xe=[`llm`,`listProfileKinds`],Se=[`llm`,`getDefaults`],Ce=[`llm`,`listRuntimeNodes`],we=[`llm`,`listModelCatalog`],Te=[`llm`,`getUsage`],Ee=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],De=new Map([[`cloud`,j],[`plug`,h],[`cpu`,O],[`server`,w],[`sparkles`,A]]);function Oe(e){return De.get(e)??d}function ke(e){return typeof e==`string`&&e.length>0?e:void 0}function Ae(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function je(e){return e===!0}function Me(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Ne={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Pe(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:Z.t(`ai.appleUnknown`),detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:Z.t(`ai.appleAvailable`),detail:Z.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Ne[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:Z.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:Z.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var Fe={ready:`success`,downloading:`info`,starting:`info`,stopped:`danger`,crashed:`danger`,failed:`danger`},Ie={ready:`ai.stateReady`,downloading:`ai.stateDownloading`,starting:`ai.stateStarting`,stopped:`ai.stateStopped`,crashed:`ai.stateCrashed`,failed:`ai.stateFailed`};function Le(e){return e.reachable?e.status===void 0?`ai.stateReady`:Ie[e.status.state]:`ai.unreachable`}function Re(e){return e.reachable?e.status===void 0?`success`:Fe[e.status.state]:`danger`}function ze(e){if(!e.reachable)return[];let t=[],n=e.apple;if(n?.state===`available`)t.push({id:`apple`,labelKey:`ai.featureApple`,tone:`success`,detail:Pe(e).detail}),n.imageInput&&t.push({id:`apple-images`,labelKey:`ai.featureAppleImages`,tone:`success`,detail:null});else if(n?.state===`unavailable`){let n=Pe(e);t.push({id:`apple`,labelKey:`ai.featureApple`,tone:n.tone,detail:n.labelDefault})}let r=e.status?.vramBytes;return r!==void 0&&r>0&&t.push({id:`gpu`,labelKey:`ai.featureGpu`,tone:`info`,detail:null}),t}var Be=`default`;function Ve(e){let t=L.shape.reasoningEffort.safeParse(e);return t.success?t.data:void 0}function He(){return{temperature:[{type:`slider`,key:`temperature`,label:Z.t(`helpers.aiProfileForm.temperature`),min:0,max:2,step:.1,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`,description:Z.t(`helpers.aiProfileForm.temperatureHint`)}],topP:[{type:`slider`,key:`topP`,label:Z.t(`helpers.aiProfileForm.topP`),min:0,max:1,step:.05,showValue:!0,showStepper:!0,nullable:!0,nullLabel:`Provider default`}],topK:[{type:`number`,key:`topK`,label:Z.t(`helpers.aiProfileForm.topK`),min:1}],maxTokens:[{type:`number`,key:`maxTokens`,label:Z.t(`helpers.aiProfileForm.maxTokens`),min:1}],reasoningEffort:[{type:`select`,key:`reasoningEffort`,label:Z.t(`helpers.aiProfileForm.reasoningEffort`),default:Be,options:[{value:Be,label:Z.t(`helpers.aiProfileForm.reasoningDefault`)},{value:`off`,label:Z.t(`helpers.aiProfileForm.reasoningOff`)},{value:`low`,label:Z.t(`helpers.aiProfileForm.reasoningLow`)},{value:`medium`,label:Z.t(`helpers.aiProfileForm.reasoningMedium`)},{value:`high`,label:Z.t(`helpers.aiProfileForm.reasoningHigh`)}],description:Z.t(`helpers.aiProfileForm.reasoningEffortHint`)}],contextLength:[{type:`number`,key:`contextLength`,label:Z.t(`helpers.aiProfileForm.contextLength`),min:512,unit:`tokens`,description:Z.t(`helpers.aiProfileForm.contextLengthHint`)}],systemPrompt:[{type:`textarea`,key:`systemPrompt`,label:Z.t(`helpers.aiProfileForm.systemPrompt`),rows:4,maxLength:4e3,span:2,description:Z.t(`helpers.aiProfileForm.systemPromptHint`)}],timeoutMs:[{type:`number`,key:`timeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutTotal`),min:1e3,default:R.totalMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutTotalHint`)}],connectTimeoutMs:[{type:`number`,key:`connectTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutConnect`),min:500,default:R.connectMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutConnectHint`)}],firstTokenTimeoutMs:[{type:`number`,key:`firstTokenTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutFirstToken`),min:1e3,default:R.firstTokenMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutFirstTokenHint`)}],idleTimeoutMs:[{type:`number`,key:`idleTimeoutMs`,label:Z.t(`helpers.aiProfileForm.timeoutIdle`),min:1e3,default:R.idleMs,unit:`ms`,description:Z.t(`helpers.aiProfileForm.timeoutIdleHint`)}],retry:[{type:`boolean`,key:`retryEnabled`,label:Z.t(`helpers.aiProfileForm.retry`),description:Z.t(`helpers.aiProfileForm.retryHint`)},{type:`number`,key:`retryMaxAttempts`,label:Z.t(`helpers.aiProfileForm.retryMaxAttempts`),min:1,max:5,default:1,showWhen:{field:`retryEnabled`,equals:!0}}],toolsEnabled:[{type:`boolean`,key:`toolsEnabled`,label:Z.t(`helpers.aiProfileForm.toolsEnabled`),description:Z.t(`helpers.aiProfileForm.toolsEnabledHint`)}]}}var Ue=[`temperature`,`topP`,`topK`,`maxTokens`,`reasoningEffort`,`contextLength`,`systemPrompt`],We=[`timeoutMs`,`connectTimeoutMs`,`firstTokenTimeoutMs`,`idleTimeoutMs`,`retry`,`toolsEnabled`];function Ge(e,t){let n=He();return t.filter(t=>e.includes(t)).flatMap(e=>n[e])}function Ke(e){let t=Ge(e,Ue);return t.length===0?null:{sections:[{id:`generation`,title:Z.t(`helpers.aiProfileForm.generation`),fields:t}]}}function qe(e){let t=Ge(e,We);return t.length===0?null:{sections:[{id:`bounds`,title:Z.t(`helpers.aiProfileForm.bounds`),fields:t}]}}function Je(e){return e===null?{}:{temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,reasoningEffort:e.reasoningEffort??Be,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled}}function Ye(e,t){return{...e.features,...t?.features}}function Xe(e,t){return t===null?e.modelCatalog===`static`?e.staticModels??[]:[]:t}function Ze(e,t,n){let r=e.profileFields,i=n.common,a=(e,t,n)=>r.includes(e)?Ae(i[e])??t:n??t,o=e=>r.includes(e)?Ae(i[e]):t?.[e],s=o(`temperature`),c=o(`topP`),l=o(`topK`),u=o(`maxTokens`),d=o(`contextLength`),f=r.includes(`reasoningEffort`)?Ve(i.reasoningEffort):t?.reasoningEffort,p=r.includes(`systemPrompt`)?ke(i.systemPrompt):t?.systemPrompt;return{id:t?.id??crypto.randomUUID(),name:n.name,kind:e.kind,addonId:e.addonId.length>0?e.addonId:`ai`,enabled:t?.enabled??!0,model:n.model,supportsVision:n.supportsVision,timeoutMs:a(`timeoutMs`,R.totalMs,t?.timeoutMs),connectTimeoutMs:a(`connectTimeoutMs`,R.connectMs,t?.connectTimeoutMs),firstTokenTimeoutMs:a(`firstTokenTimeoutMs`,R.firstTokenMs,t?.firstTokenTimeoutMs),idleTimeoutMs:a(`idleTimeoutMs`,R.idleMs,t?.idleTimeoutMs),retry:r.includes(`retry`)?{enabled:je(i.retryEnabled),maxAttempts:Ae(i.retryMaxAttempts)??1}:t?.retry??{enabled:!1,maxAttempts:1},toolsEnabled:r.includes(`toolsEnabled`)?je(i.toolsEnabled):t?.toolsEnabled??!1,...s===void 0?{}:{temperature:s},...c===void 0?{}:{topP:c},...l===void 0?{}:{topK:l},...u===void 0?{}:{maxTokens:u},...f===void 0?{}:{reasoningEffort:f},...d===void 0?{}:{contextLength:d},...p===void 0?{}:{systemPrompt:p},providerConfig:n.providerConfig}}var Qe=2e3;function $(e){return Z.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function $e(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function et({nodeId:t,value:r,onChange:a}){let{t:c}=Q(),u=T(),[d,f]=o(``),[p,m]=o(null),[h,g]=o(!1),_=s({queryKey:we,queryFn:()=>u.trpcClient.llm.listModelCatalog.query({})}),v=s({queryKey:[`llm`,`listNodeModels`,t],queryFn:()=>u.trpcClient.llm.listNodeModels.query({nodeId:t})}),y=l({mutationFn:e=>u.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&a({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:e=>u.trpcClient.llm.installModel.mutate({nodeId:t,model:e}),onSuccess:()=>{g(!0),v.refetch()}}),x=s({queryKey:Ce,enabled:b.isPending,refetchInterval:b.isPending?Qe:!1,queryFn:()=>u.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(e=>e.nodeId===t)?.status?.download,S=n(()=>{let e=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(e=>({value:`node:${e.file}`,label:c(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:e.file,size:$(e.sizeBytes),node:t})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:c(`ai.selectModel`,`Select a model…`)},...e,...n,...r]},[_.data,v.data,p,t,c]),w=e=>{if(e===``){a(null);return}if(e===`custom`){if(p?.ok!==!0)return;a({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);a({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&a({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},E=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return e(`div`,{className:`space-y-3`,children:[i(H,{label:c(`ai.model`,`Model`),required:!0,children:i(K,{id:`ai-model`,"aria-label":c(`ai.model`,`Model`),value:$e(r),options:S,onChange:e=>w(e.target.value)})}),i(H,{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(me,{"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(),E())}}),e(X,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>E(),children:[y.isPending?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(P,{className:`h-3.5 w-3.5`}),c(`ai.hfCheck`,`Check`)]})]})}),y.isError&&i(q,{message:y.error instanceof Error?y.error.message:c(`common.error`,`Error`)}),p?.ok===!1&&i(q,{message:p.message,action:e(`div`,{className:`flex flex-wrap items-center gap-1`,children:[(p.candidates??[]).map(e=>i(X,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e)),p.requiredBytes!==void 0&&i(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:()=>E(p.requiredBytes),children:c(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]})}),p?.ok===!0&&e(`div`,{className:`space-y-2 rounded-md border border-border bg-surface p-2.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[i(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),i(Y,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),i(Y,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),e(`div`,{className:`flex items-center gap-2`,children:[e(X,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(C,{className:`h-3.5 w-3.5`}),h?c(`ai.hfInstalled`,`Downloaded`):c(`ai.hfInstall`,`Download to {{node}}`,{node:t})]}),x!==void 0&&i(`span`,{className:`text-[10px] text-foreground-subtle`,children:x.phase===`verifying`?c(`ai.hfVerifying`,`verifying {{file}}…`,{file:x.file}):c(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:x.file,index:x.fileIndex,count:x.fileCount,done:$(x.downloadedBytes),total:x.totalBytes===void 0?``:` / ${$(x.totalBytes)}`})})]}),b.isError&&i(q,{message:b.error instanceof Error?b.error.message:c(`common.error`,`Error`)})]})]})}function tt({value:t,onChange:n}){let{t:r}=Q(),a=T(),o=s({queryKey:Ce,queryFn:()=>a.trpcClient.llm.listRuntimeNodes.query({})});return e(`div`,{children:[i(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:r(`ai.appleNode`,`Mac that runs it`)}),o.isPending&&e(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[i(k,{className:`h-3.5 w-3.5 animate-spin`}),r(`ai.appleAsking`,`Asking the nodes…`)]}),o.isError&&i(`p`,{className:`text-[11px] text-danger`,children:o.error instanceof Error?o.error.message:r(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),o.isSuccess&&o.data.length===0&&i(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),o.isSuccess&&o.data.length>0&&i(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:o.data.map(a=>{let o=Pe(a),s=o.nodeId===t;return e(`button`,{type:`button`,role:`radio`,"aria-checked":s,disabled:!o.selectable&&!s,onClick:()=>n(o.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${s?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block font-medium text-foreground`,children:o.nodeId}),o.detail!==null&&i(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:o.detail})]}),i(Y,{variant:o.tone,children:r(o.labelKey,o.labelDefault)})]},o.nodeId)})}),i(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:r(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}function nt(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:null}function rt({providerConfig:e,onProviderConfigChange:t}){return i(tt,{value:nt(e,`nodeId`),onChange:n=>t({...e,nodeId:n})})}function it({providerConfig:e,onProviderConfigChange:t,model:n,onModelChange:r}){let a=I.safeParse(e.model),o=a.success?{model:a.data,modelId:n.id,supportsVision:n.supportsVision}:null;return i(et,{nodeId:nt(e,`nodeId`)??`hub`,value:o,onChange:n=>{if(n===null){let{model:n,...i}=e;t(i),r({id:``,supportsVision:!1});return}t({...e,model:n.model}),r({id:n.modelId,supportsVision:n.supportsVision})}})}var at=new Map([[`ai/apple-node`,rt],[`ai/managed-model`,it]]);function ot(e){return at.get(e)??null}c();function st({kind:e,className:t}){return i(Oe(e.icon),{className:t,"aria-hidden":!0})}function ct({kinds:e,onPick:t,onCancel:r}){let{t:a}=Q(),o=n(()=>Me(e),[e]),s=n(()=>new Map(e.map(e=>[`${e.addonId}:${e.kind}`,e])),[e]);return i(pe,{open:!0,onClose:r,title:a(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:i(ae,{emptyMessage:a(`ai.noKinds`,`No AI provider is installed.`),onPick:e=>{let n=s.get(e);n!==void 0&&t(n)},groups:o.map(e=>({id:e.addonId,label:e.addonId,tiles:e.kinds.map(t=>({key:`${e.addonId}:${t.kind}`,label:t.label,testId:`ai-kind-${t.kind}`,icon:i(st,{kind:t,className:`h-5 w-5 text-foreground-subtle`})}))}))})})}function lt(e){return(e?.sections??[]).flatMap(e=>e.fields)}function ut(...e){let t={};for(let n of e)for(let e of lt(n))`default`in e&&e.default!==void 0&&(t[e.key]=e.default);return t}function dt(e){return e==null?!1:typeof e==`string`?e.trim().length>0:!0}function ft(e,t){return lt(e).filter(e=>`required`in e&&e.required===!0&&!dt(t[e.key])).map(e=>`label`in e&&typeof e.label==`string`?e.label:e.key)}var pt={auth:{key:`ai.listAuth`,fallback:`Credentials refused`},network:{key:`ai.listNetwork`,fallback:`Endpoint unreachable`},unsupported:{key:`ai.listUnsupported`,fallback:`No model list`},invalid:{key:`ai.listInvalid`,fallback:`Connection incomplete`}};function mt(e,t){if(t!==null)return{id:t.model,supportsVision:t.supportsVision};let n=e.modelCatalog===`static`&&e.staticModels?.length===1?e.staticModels?.[0]:void 0;return{id:n?.id??``,supportsVision:Ye(e,n).vision}}function ht({kind:t,existing:r,onSave:s,onCancel:c,onChangeKind:d,saving:m,error:h}){let{t:g}=Q(),_=T(),[v,y]=o(r?.name??t.label),[b,S]=o(()=>r===null?ut(t.connectionSchema,t.advancedSchema):{...r.providerConfig}),[C,w]=o(()=>Je(r)),[E,O]=o(()=>mt(t,r)),[A,j]=o(!1),M=t.providerWidgets??[],N=M.filter(e=>e.placement===`connection`),P=M.find(e=>e.placement===`model`)??null,F=n(()=>[...ee(t.connectionSchema)].some(e=>r?.providerConfig[e]===ye),[r,t.connectionSchema]),I=l({mutationFn:()=>_.trpcClient.llm.listModels.mutate({addonId:t.addonId,kind:t.kind,connection:b,...r===null?{}:{profileId:r.id}}),onSuccess:e=>{e.ok&&O(n=>{let r=e.models.find(e=>e.id===n.id);return r===void 0?n:{id:n.id,supportsVision:Ye(t,r).vision}})}}),L=Xe(t,I.data?.ok===!0?I.data.models:null),R=L.find(e=>e.id===E.id),z=Ye(t,R),te=Ke(t.profileFields),ne=qe(t.profileFields),B=ft(t.connectionSchema,b),re=M.some(e=>(e.requires??[]).some(e=>!dt(b[e]))),U=t.modelCatalog===`fetch`&&P===null,W=lt(t.connectionSchema).length>0||N.length>0,ie=r!==null&&U&&B.length===0;a(()=>{ie&&I.mutate()},[]);let G=e=>{O({id:e,supportsVision:Ye(t,L.find(t=>t.id===e)).vision})},ae=m||v.trim()===``||E.id.trim()===``||B.length>0||re,oe=()=>{s(Ze(t,r,{name:v.trim(),model:E.id.trim(),supportsVision:t.visionEditable?E.supportsVision:!1,common:C,providerConfig:b}))},ce=r===null?g(`ai.newProfile`,`New {{kind}} profile`,{kind:t.label}):g(`ai.editProfile`,`Edit {{name}}`,{name:r.name}),J=e=>{let n=ot(e);return n===null?i(q,{variant:`warning`,message:g(`ai.unknownWidget`,`This provider needs an editor part this build does not have ({{id}}).`,{id:e})}):i(n,{descriptor:t,providerConfig:b,onProviderConfigChange:S,model:E,onModelChange:O},e)};return i(pe,{open:!0,onClose:c,title:ce,error:h,width:`lg`,testId:`ai-profile-editor`,footer:e(u,{children:[B.length>0&&i(Y,{variant:`warning`,children:g(`ai.missingRequired`,`required: {{fields}}`,{fields:B.join(`, `)})}),B.length===0&&re&&i(Y,{variant:`warning`,children:g(`ai.completeProvider`,`complete the provider settings`)}),B.length===0&&!re&&E.id.trim()===``&&i(Y,{variant:`warning`,children:g(`ai.pickModelFirst`,`pick a model`)}),e(X,{size:`sm`,type:`button`,disabled:ae,onClick:oe,children:[m&&i(k,{className:`h-3.5 w-3.5 animate-spin`}),r===null?g(`ai.createProfile`,`Create profile`):g(`ai.saveChanges`,`Save changes`)]})]}),children:e(`div`,{className:x,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`ai-editor-provider`,children:[i(st,{kind:t,className:`h-4 w-4 text-foreground-subtle`}),i(`span`,{className:`text-xs font-medium text-foreground`,children:t.label}),i(Y,{variant:`neutral`,children:t.addonId}),d!==void 0&&e(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:d,children:[i(D,{className:`h-3.5 w-3.5`}),g(`ai.changeKind`,`Change type`)]})]}),i(H,{label:g(`ai.name`,`Name`),required:!0,children:i(me,{id:`ai-profile-name`,"aria-label":g(`ai.name`,`Name`),value:v,onChange:e=>y(e.target.value),placeholder:t.label})}),W&&i(V,{headingId:`ai-editor-connection`,title:g(`ai.sectionConnection`,`Connection`),actions:U?e(X,{size:`sm`,variant:`secondary`,type:`button`,disabled:I.isPending,onClick:()=>I.mutate(),"data-testid":`ai-verify-models`,children:[I.isPending?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(p,{className:`h-3.5 w-3.5`}),g(`ai.verifyModels`,`Verify & load models`)]}):void 0,children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[lt(t.connectionSchema).length>0&&i(fe,{bare:!0,schema:t.connectionSchema,values:b,onChange:S}),N.map(e=>J(e.id)),F&&i(`p`,{className:`text-[10px] text-foreground-subtle`,children:g(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)}),I.data?.ok===!0&&i(Y,{variant:`success`,"data-testid":`ai-models-found`,children:g(`ai.modelsFound`,`{{count}} models found`,{count:I.data.models.length})}),I.data?.ok===!1&&i(q,{title:g(pt[I.data.code]?.key??`ai.listNetwork`,pt[I.data.code]?.fallback??`Endpoint unreachable`),message:I.data.message}),I.isError&&i(q,{message:I.error instanceof Error?I.error.message:g(`common.error`,`Error`)})]})}),i(V,{headingId:`ai-editor-model`,title:g(`ai.sectionModel`,`Model`),children:e(`div`,{className:`${f} space-y-3`,children:[P===null?e(u,{children:[L.length>0&&i(K,{id:`ai-model-pick`,"aria-label":g(`ai.selectModel`,`Select a model…`),value:R===void 0?``:R.id,options:[{value:``,label:g(`ai.selectModel`,`Select a model…`)},...L.map(e=>({value:e.id,label:e.label??e.id}))],onChange:e=>{e.target.value!==``&&G(e.target.value)}}),i(H,{label:g(`ai.customModel`,`Model id`),description:g(`ai.customModelHint`,`Pick one from the list, or type any model id the provider accepts.`),required:!0,children:i(me,{id:`ai-model-id`,"aria-label":g(`ai.customModel`,`Model id`),value:E.id,onChange:e=>{let n=L.find(t=>t.id===e.target.value);O(n===void 0?{...E,id:e.target.value}:{id:e.target.value,supportsVision:Ye(t,n).vision})},placeholder:L[0]?.id??`model-id`})})]}):J(P.id),e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`ai-model-features`,children:[(E.supportsVision||!t.visionEditable&&z.vision)&&i(Y,{variant:`info`,children:g(`ai.featureVision`,`vision`)}),z.tools&&i(Y,{variant:`neutral`,children:g(`ai.featureTools`,`tools`)}),z.streaming&&i(Y,{variant:`neutral`,children:g(`ai.featureStreaming`,`streaming`)})]}),t.visionEditable&&i(H,{orientation:`horizontal`,label:g(`ai.supportsVision`,`Supports vision`),description:g(`ai.supportsVisionHint`,`A vision call against a text-only profile is refused, never downgraded.`),children:i(se,{checked:E.supportsVision,onCheckedChange:e=>O({...E,supportsVision:e}),"aria-label":g(`ai.supportsVision`,`Supports vision`)})})]})}),te!==null&&i(V,{headingId:`ai-editor-generation`,title:g(`ai.sectionGeneration`,`Generation`),children:i(`div`,{className:`p-2 sm:p-3 lg:p-4`,children:i(fe,{bare:!0,schema:te,values:C,onChange:w})})}),(ne!==null||t.advancedSchema!==void 0)&&i(le,{expanded:A,onExpandedChange:j,header:i(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:g(`ai.sectionAdvanced`,`Advanced`)}),children:e(`div`,{className:`p-2 sm:p-3 lg:p-4 space-y-3`,children:[ne!==null&&i(fe,{bare:!0,schema:ne,values:C,onChange:w}),t.advancedSchema!==void 0&&i(fe,{bare:!0,schema:t.advancedSchema,values:b,onChange:S})]})})]})})}c();function gt(t){return[{key:`name`,header:t.t(`ai.colProfile`,`Profile`),render:n=>{let r=t.kindByName.get(n.kind);return e(`span`,{className:`flex items-center gap-2`,children:[i(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:r?.label??n.kind,children:r===void 0?i(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):i(st,{kind:r,className:`h-4 w-4 text-foreground-subtle`})}),e(`span`,{className:`min-w-0`,children:[i(`span`,{className:`block truncate font-medium text-foreground`,children:n.name}),t.testResult?.id===n.id&&i(`span`,{className:`block truncate ${t.testResult.ok?`text-success`:`text-danger`}`,children:t.testResult.text})]})]})}},{key:`kind`,header:t.t(`ai.colKind`,`Kind`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground-muted`,children:t.kindByName.get(e.kind)?.label??e.kind})},{key:`model`,header:t.t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.model})},{key:`vision`,header:t.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:e=>e.supportsVision?i(Y,{variant:`info`,style:`outline`,children:t.t(`ai.vision`,`vision`)}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`node`,header:t.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>typeof e.providerConfig.nodeId==`string`?i(Y,{variant:`default`,children:e.providerConfig.nodeId}):i(`span`,{className:`text-foreground-subtle`,children:`—`})},{key:`enabled`,header:t.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:e=>i(se,{checked:e.enabled,onCheckedChange:()=>t.onToggle(e),"aria-label":Z.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:e.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(`span`,{className:`flex items-center justify-end gap-1`,children:[i(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest(n),"aria-label":t.t(`ai.test`,`Test`),title:t.t(`ai.test`,`Test`),children:t.testingId===n.id?i(k,{className:`h-3.5 w-3.5 animate-spin`}):i(te,{className:`h-3.5 w-3.5`})}),i(X,{size:`sm`,variant:`ghost`,type:`button`,disabled:!t.kindByName.has(n.kind),onClick:()=>t.onEdit(n),"aria-label":t.t(`common.edit`,`Edit`),title:t.t(`common.edit`,`Edit`),children:i(v,{className:`h-3.5 w-3.5`})}),i(X,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDelete(n),"aria-label":t.t(`common.delete`,`Delete`),title:t.t(`common.delete`,`Delete`),children:i(y,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function _t(){let{t}=Q(),c=T(),{state:u,openEdit:d,close:p}=J(),m=M(),[h,g]=o(null),[_,v]=o(null),[y,b]=o(null),S=s({queryKey:be,queryFn:()=>c.trpcClient.llm.listProfiles.query({})}),C=s({queryKey:xe,queryFn:async()=>(await c.trpcClient.llm.listProfileKinds.query({})).map(({connectionSchema:e,advancedSchema:t,...n})=>({...n,connectionSchema:e,...t===void 0?{}:{advancedSchema:t}}))}),w=()=>{S.refetch()},E=r(()=>{g(null),b(null),p()},[p]);a(()=>{u.mode===`closed`&&g(null)},[u.mode]);let D=l({mutationFn:e=>c.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{E(),w()},onError:e=>b(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)=>v({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}`})}),j=S.data??[],N=n(()=>C.data??[],[C.data]),P=n(()=>{let e=new Map;for(let t of N)e.set(t.kind,t);return e},[N]),F=u.mode===`edit`?j.find(e=>e.id===u.id)??null:null,ee=F===null?null:P.get(F.kind)??null,I=u.mode===`new`&&h===null,L=u.mode===`new`?h:ee,R=u.mode===`edit`?F:null,z=L!==null&&(u.mode===`new`||R!==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:x,children:[i(vt,{profiles:j}),i(V,{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(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):S.isError?i(`div`,{className:f,children:i(q,{title:t(`ai.loadFailed`,`Failed to load profiles`),message:S.error instanceof Error?S.error.message:t(`common.error`,`Error`),onRetry:()=>void S.refetch()})}):j.length===0?i(U,{icon:A,title:t(`ai.noProfilesTitle`,`No AI profiles yet`),description:t(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}):i(de,{columns:gt({kindByName:P,testResult:_,testingId:k.isPending?k.variables?.id??null:null,t,onToggle:e=>D.mutate({...e,enabled:!e.enabled}),onTest:e=>k.mutate(e),onEdit:e=>{P.has(e.kind)&&(b(null),g(null),d(e.id))},onDelete:e=>void te(e)}),rows:j,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:B})}),I&&i(ct,{kinds:N,onCancel:E,onPick:e=>{b(null),g(e)}}),z&&L!==null&&i(ht,{kind:L,existing:R,saving:D.isPending,error:y,onSave:e=>D.mutate(e),onCancel:E,...u.mode===`new`?{onChangeKind:()=>{b(null),g(null)}}:{}})]})}function vt({profiles:t}){let{t:n}=Q(),r=T(),a=s({queryKey:Se,queryFn:()=>r.trpcClient.llm.getDefaults.query({})}),o=l({mutationFn:e=>r.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{a.refetch()}}),c=e=>(a.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,u=e=>e===`vision`?n(`ai.defaultVision`,`Default vision profile`):n(`ai.defaultText`,`Default text profile`);return i(V,{headingId:`ai-profiles-defaults`,title:n(`ai.defaultsTitle`,`Defaults`),children:i(`div`,{className:`${f} grid gap-4 sm:grid-cols-2`,children:Ee.map(({purpose:r,visionOnly:a})=>{let s=a?t.filter(e=>e.supportsVision):t,l=c(r),d=t.find(e=>e.id===l);return e(`div`,{children:[i(ce,{className:`mb-1 block`,htmlFor:`llm-default-${r}`,children:u(r)}),i(K,{id:`llm-default-${r}`,"aria-label":u(r),value:l,onChange:e=>o.mutate({purpose:r,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:n(`ai.none`,`None`)},...l!==``&&!s.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...s.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&i(`p`,{className:`mt-1 text-xs text-danger`,children:n(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&i(`p`,{className:`mt-1 text-xs text-warning`,children:n(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),o.error!=null&&i(`p`,{className:`mt-1 text-xs text-danger`,children:String(o.error)})]},r)})})})}c();var yt=5e3;function bt(e){return Z.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function xt(){let{t}=Q(),r=T(),a=s({queryKey:Ce,refetchInterval:yt,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})}),o=n(()=>[{key:`node`,header:t(`ai.colNode`,`Node`),render:e=>i(`span`,{className:`font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:t(`ai.colState`,`State`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[i(Y,{variant:Re(n),children:t(Le(n))}),n.status?.downloadProgress!==void 0&&i(Y,{variant:`info`,children:`${String(Math.round(n.status.downloadProgress*100))}%`})]})},{key:`model`,header:t(`ai.colModel`,`Model`),render:e=>i(`span`,{className:`text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:t(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums text-foreground-muted`,children:e.disk===void 0?`—`:bt(e.disk.modelsBytes)})},{key:`features`,header:t(`ai.colFeature`,`Feature`),render:n=>{let r=ze(n);if(r.length===0)return i(`span`,{className:`text-foreground-subtle`,children:`—`});let a=r.flatMap(e=>e.detail===null?[]:[e.detail]);return e(`span`,{className:`flex flex-col items-start gap-0.5`,children:[i(`span`,{className:`flex flex-wrap gap-1`,children:r.map(e=>i(Y,{variant:e.tone,children:t(e.labelKey)},e.id))}),a.length>0&&i(`span`,{className:`text-foreground-subtle`,children:a.join(` · `)})]})}},{key:`error`,header:t(`ai.colError`,`Error`),render:e=>e.error===void 0?i(`span`,{className:`text-foreground-subtle`,children:`—`}):i(`span`,{className:`text-danger`,children:e.error})}],[t]),c=a.data??[];return i(V,{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(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):a.isError?i(`div`,{className:f,children:i(q,{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(U,{icon:w,title:t(`ai.noRuntimesTitle`,`No runtime nodes`),description:t(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):i(de,{columns:o,rows:c,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:B})})}var St=S(`/addon/ai/test-chat`),Ct=S(`/addon/ai/test-chat/chats`),wt=6e5;function Tt(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),wt)}function Et(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Dt(e){if(!Et(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Ot=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function kt(e){let t;try{t=JSON.parse(e)}catch{return null}if(!Et(t))return null;switch(t.kind){case`status`:{let e=Ot.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Dt(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:Z.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*At(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
2
  `);for(;a>=0;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length>0){let t=kt(e);t!==null&&(yield t)}a=r.indexOf(`
3
3
  `)}}let e=r.trim();if(e.length>0){let t=kt(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function jt(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Mt(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Nt(e){return e.messages.map((t,n)=>{let r=t.mediaSent??void 0;return{id:`${e.id}-${String(n)}`,role:t.role,content:t.content,...t.attachment===void 0?{}:{attachmentRef:t.attachment,attachmentKind:t.attachment.kind},...r===void 0?{}:{attachment:r}}})}function Pt(e){let t=e.sizeBytes<1024*1024?`${(e.sizeBytes/1024).toFixed(0)} KB`:`${(e.sizeBytes/(1024*1024)).toFixed(1)} MB`,n=[e.kind===`snapshot`?`camera snapshot`:`track best-shot`,t];return e.mediaKind!==void 0&&n.push(e.mediaKind),e.capturedAt!==void 0&&n.push(new Date(e.capturedAt).toLocaleTimeString()),n.join(` · `)}function Ft(e,t){switch(e){case`resolving-image`:return Z.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return Z.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?Z.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):Z.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return Z.t(`helpers.aiTestChat.phaseAnswering`)}}c();var It=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],Lt=360*60*1e3,Rt=40,zt=160,Bt={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function Vt(){let{t:c}=Q(),l=T(),[u,d]=o(``),[p,h]=o(``),[g,_]=o(``),[v,b]=o([]),[S,C]=o(null),[w,D]=o(`none`),[O,k]=o(`throwaway`),[A,j]=o(null),[M,P]=o([]),[ee,I]=o(null),[L,R]=o(null),z=t(null);a(()=>()=>z.current?.abort(),[]);let B=r(async()=>{let e=await fetch(Ct,{credentials:`same-origin`});e.ok&&P((await e.json()).chats??[])},[]);a(()=>{O===`persistent`&&B()},[O,B]);let H=s({queryKey:be,queryFn:()=>l.trpcClient.llm.listProfiles.query({})}),U=n(()=>(H.data??[]).filter(e=>e.enabled),[H.data]),W=U.find(e=>e.id===u)??null,ie=L!==null,G=r(async(e,t)=>{let n=new AbortController;z.current=n,I(null);let r=Tt(W??{});R({...Bt,firstTokenTimeoutMs:r??0});let i=``,a=null,o,s=null,l=null,d;try{let c=await fetch(St,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:n.signal,body:JSON.stringify({profileId:u,messages:e,...p.trim()===``?{}:{system:p.trim()},...t===void 0?{}:{attachment:t},...r===void 0?{}:{firstTokenTimeoutMs:r},...O===`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 At(c.body))switch(e.kind){case`status`:R(t=>({...t??Bt,phase:e.phase}));break;case`meta`:a=e.mediaSent,o=e.model,R(t=>({...t??Bt,firstTokenTimeoutMs:e.firstTokenTimeoutMs,mediaSent:e.mediaSent}));break;case`token`:i+=e.text,R(e=>({...e??Bt,text:i}));break;case`done`:l={outputTokens:e.outputTokens,latencyMs:e.latencyMs},d=e.conversationId;break;case`error`:s=`${e.code}: ${e.message}`;break}}catch(e){n.signal.aborted||I(e instanceof Error?e.message:c(`common.error`,`Error`))}finally{z.current=null,R(null)}d!==void 0&&(j(d),B());let f=n.signal.aborted&&i.length>0;s===null&&i.length===0&&!f||b(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:s??i,...s===null?{}:{failed:!0},...a===null?{}:{attachment:a},...o!==void 0&&s===null?{model:o}:{},...l===null?{}:l}])},[O,A,W,u,B,p,c]),ae=r(()=>{let e=g.trim();if(e===``||u===``||ie)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...S===null?{}:{attachmentLabel:S.label,attachmentKind:S.ref.kind}},n=[...v,t];b(n),_(``);let r=S?.ref;C(null),D(`none`),G(O===`persistent`&&A!==null?[{role:`user`,content:e}]:jt(n),r)},[O,A,g,S,u,G,ie,v]),oe=()=>z.current?.abort(),se=()=>{z.current?.abort(),b([]),C(null),_(``),I(null),R(null),j(null)},J=async e=>{z.current?.abort();let t=await fetch(`${Ct}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();j(e),b(Nt(n)),R(null),I(null)};return e(`div`,{className:x,children:[i(V,{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(ce,{className:`mb-1 block`,htmlFor:`ai-test-profile`,children:c(`ai.profile`,`Profile`)}),i(K,{id:`ai-test-profile`,value:u,onChange:e=>d(e.target.value),options:[{value:``,label:c(`ai.selectProfile`,`Select a profile…`)},...U.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),U.length===0&&!H.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(ce,{className:`mb-1 block`,htmlFor:`ai-test-system`,children:c(`ai.systemPrompt`,`System prompt (optional)`)}),i(me,{id:`ai-test-system`,value:p,onChange:e=>h(e.target.value),placeholder:c(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),i(ue,{label:c(`ai.chatMode`,`Conversation mode`),value:O,options:[{value:`throwaway`,label:c(`ai.throwawayMode`,`Throwaway`)},{value:`persistent`,label:c(`ai.saveConversation`,`Save conversation`)}],onChange:e=>{k(e),e===`throwaway`&&j(null)}}),O===`persistent`&&e(`div`,{className:`space-y-2`,children:[i(`p`,{className:`text-xs text-foreground-subtle`,children:c(`ai.testSubtitlePersistent`,`Conversations are saved for you and can be reopened. Throwaway mode is still available.`)}),e(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:se,children:[i(ne,{className:`h-3.5 w-3.5`}),c(`ai.newChat`,`New chat`)]}),M.length>0&&i(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:M.map(e=>i(`button`,{type:`button`,onClick:()=>void J(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.`)}),W!==null&&!W.supportsVision&&i(`p`,{className:`text-xs text-warning`,children:c(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]})}),ee!==null&&i(q,{title:c(`ai.chatFailed`,`The test call failed`),message:ee}),e(V,{headingId:`ai-test-conversation`,title:c(`ai.testConversation`,`Conversation`),actions:e(X,{size:`sm`,variant:`ghost`,type:`button`,disabled:v.length===0&&S===null,onClick:se,children:[i(y,{className:`h-3.5 w-3.5`}),c(`ai.clearChat`,`Clear`)]}),children:[i(Ht,{turns:v,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(m,{className:`h-3.5 w-3.5 text-foreground-subtle`}):i(F,{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(re,{size:`sm`,variant:`ghost`,type:`button`,icon:E,"aria-label":c(`ai.removeAttachment`,`Remove attachment`),onClick:()=>C(null)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(X,{size:`sm`,variant:w===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>D(w===`snapshot`?`none`:`snapshot`),children:[i(m,{className:`h-3.5 w-3.5`}),c(`ai.attachSnapshot`,`Camera snapshot`)]}),e(X,{size:`sm`,variant:w===`track`?`primary`:`outline`,type:`button`,onClick:()=>D(w===`track`?`none`:`track`),children:[i(F,{className:`h-3.5 w-3.5`}),c(`ai.attachTrack`,`Recent track`)]})]}),w===`snapshot`&&i(Gt,{onPick:(e,t)=>{C({ref:{kind:`snapshot`,deviceId:e.id},label:c(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t})}),D(`none`)}}),w===`track`&&i(qt,{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})}),D(`none`)}}),e(`div`,{className:`flex items-center gap-2`,children:[i(me,{value:g,onChange:e=>_(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),ae())},placeholder:c(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":c(`ai.message`,`Message`)}),ie?e(X,{size:`sm`,variant:`secondary`,type:`button`,onClick:oe,children:[i(N,{className:`h-3.5 w-3.5`}),c(`ai.stop`,`Stop`)]}):e(X,{size:`sm`,type:`button`,disabled:g.trim()===``||u===``,onClick:ae,children:[i(te,{className:`h-3.5 w-3.5`}),c(`ai.send`,`Send`)]})]})]})]})]})}function Ht({turns:t,live:n}){let{t:r}=Q();return t.length===0&&n===null?i(U,{icon:z,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(Ut,{turn:e},e.id)),n!==null&&e(`div`,{className:`space-y-1`,children:[n.mediaSent!==null&&i(Wt,{attachment:n.mediaSent}),n.text.length>0&&i(Ut,{turn:{id:`live`,role:`assistant`,content:n.text},streaming:!0}),e(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[i(k,{className:`h-3.5 w-3.5 animate-spin`}),Ft(n.phase,n.firstTokenTimeoutMs)]})]})]})}function Ut({turn:t,streaming:n=!1}){let{t:r}=Q(),a=t.role===`user`,o=t.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return i(`div`,{className:`flex ${a?`justify-end`:`justify-start`}`,children:e(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${a?`border-primary/40 bg-primary/10`:o}`,children:[e(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[t.content,n&&i(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),t.attachment!==void 0&&i(Wt,{attachment:t.attachment}),t.attachmentLabel!==void 0&&e(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[t.attachmentKind===`track`?i(F,{className:`h-3 w-3`}):i(m,{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(m,{className:`h-3 w-3`}):i(F,{className:`h-3 w-3`}),Pt(t.attachment)]}),t.model!==void 0&&i(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:t.model,value2:String(t.outputTokens??0),value3:String(t.latencyMs??0)})})]})})}function Wt({attachment:e}){let{t}=Q(),n=Mt(e);return n===null?null:i(`img`,{src:n,alt:t(`system.aiTestChat.sentToTheModel`,`sent to the model`),className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function Gt({onPick:e}){let{t}=Q(),n=W({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?i(k,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?i(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):i(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>i(Kt,{device:t,onPick:e},t.id))})}function Kt({device:t,onPick:n}){let{t:r}=Q(),a=oe(t,`compact`),{src:o}=_(t.id,{width:zt});return e(`button`,{type:`button`,onClick:()=>n(t,a),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[i(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:o!==null&&i(`img`,{src:o,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),e(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!t.online&&i(Y,{variant:`warning`,children:r(`common.off`)}),i(`span`,{className:`truncate text-[10px] text-foreground`,children:a})]})]})}function qt({onPick:t}){let{t:r}=Q(),a=T(),o=W({isCamera:!0,projection:`slim`}),c=n(()=>(o.data??[]).map(e=>e.id),[o.data]),l=n(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),u=s({queryKey:[...It,c.length],enabled:c.length>0,queryFn:()=>a.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...c],since:Date.now()-Lt,limit:Rt,projection:`slim`})});if(o.isLoading||u.isLoading)return i(k,{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(F,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),i(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:n.label??n.className}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:l.get(n.deviceId)??n.deviceId}),i(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(n.lastSeen).toLocaleTimeString()})]},n.trackId))})}c();var Jt=1440*60*1e3,Yt=[1,7,30,90];function Xt(){let{t}=Q(),r=T(),[a,c]=o(7),l=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(a-1)*Jt},[a]),u=s({queryKey:be,queryFn:()=>r.trpcClient.llm.listProfiles.query({})}),d=s({queryKey:[...Te,a],queryFn:()=>r.trpcClient.llm.getUsage.query({since:l})}),p=n(()=>{let e=new Map;for(let t of u.data??[])e.set(t.id,t.name);return e},[u.data]),m=n(()=>[{key:`day`,header:t(`ai.colDay`,`Day`),nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:e.day})},{key:`consumer`,header:t(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>i(`span`,{className:`text-foreground`,children:e.consumer})},{key:`profile`,header:t(`ai.colProfile`,`Profile`),render:e=>i(`span`,{className:`text-foreground`,children:p.get(e.profileId)??e.profileId})},{key:`calls`,header:t(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(e.calls)})},{key:`okErr`,header:t(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums ${e.errorCalls>0?`text-danger`:``}`,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:t(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:`${String(e.inputTokens)} / ${String(e.outputTokens)}`})},{key:`latency`,header:t(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>i(`span`,{className:`tabular-nums`,children:String(Math.round(e.avgLatencyMs))})}],[p,t]),h=d.data??[],_=i(`div`,{className:`w-36`,children:i(K,{"aria-label":t(`ai.window`,`Window`),value:String(a),options:Yt.map(e=>({value:String(e),label:t(`ai.lastDays`,`Last {{days}} days`,{days:e})})),onChange:e=>c(Number(e.target.value))})});return i(V,{headingId:`ai-usage-list`,title:t(`ai.usageList`,`Rollup`),actions:_,children:d.isPending?e(`div`,{className:`${f} space-y-2`,"data-testid":`ai-usage-loading`,children:[i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`}),i(G,{className:`h-8 w-full`})]}):d.isError?i(`div`,{className:f,children:i(q,{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(U,{icon:g,title:t(`ai.noUsage`,`No AI calls in this window.`)}):i(de,{columns:m,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:B})})}var Zt=`llm`,Qt=[`profiles`,`runtimes`,`usage`,`test`],$t=[`new`,`edit`];function en(e){return Qt.some(t=>t===e)}function tn(){let{t}=Q(),n=ie(Zt),[r]=ge(),{openNew:a}=J(),o=he(`/system/ai`,{t,isAdmin:!0})??{icon:A,title:t(`system.ai`,`AI`)};if(n!==`present`)return i(ve,{icon:o.icon,title:o.title,children:i(nn,{presence:n})});let s=r.get(`tab`),c=en(s)?s:`profiles`,l={profiles:t(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),runtimes:t(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),usage:t(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),test:t(`ai.testSubtitle`,`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`)},u=c===`profiles`?e(X,{size:`sm`,type:`button`,"data-testid":`ai-add-profile`,onClick:a,children:[i(b,{className:`h-3.5 w-3.5`}),t(`ai.addProfile`,`Add profile`)]}):void 0;return i(_e,{icon:o.icon,title:o.title,subtitle:l[c],actions:u,defaultSection:`profiles`,sectionsLabel:`${o.title} sections`,sections:[{id:`profiles`,label:t(`ai.tabProfiles`,`Profiles`),content:i(_t,{}),ownedParams:$t},{id:`runtimes`,label:t(`ai.tabRuntimes`,`Runtimes`),content:i(xt,{})},{id:`usage`,label:t(`ai.tabUsage`,`Usage`),content:i(Xt,{})},{id:`test`,label:t(`ai.tabTest`,`Test`),content:i(Vt,{})}]})}function nn({presence:t}){let{t:n}=Q();return t===`pending`?e(`div`,{className:`space-y-3`,"data-testid":`ai-presence-pending`,children:[i(G,{className:`h-8 w-64`}),i(G,{className:`h-40 w-full`})]}):t===`unknown`?i(q,{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(U,{icon:A,title:n(`ai.absentTitle`,`AI is not installed`),description:n(`ai.absentDescription`,`Install the AI addon from System → Addons to add model profiles.`)})}export{tn as AiProfilesPage,tn as default};
@@ -1,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,o as d,t as f,x as p}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Di as m,Er as h,Hn as g,Ht as _,In as v,Ln as y,Tn as b,aa as x,dt as S,ha as C,hr as w,jr as T,ki as E,pr as D,st as O,ta as k,vt as A,xi as j,yn as M,zt as N}from"./player-overlays-DpZIxQHp.js";import{$a as P,$i as F,Aa as I,Ai as L,Ca as R,Da as z,Ea as ee,Fa as B,Hi as te,Ia as ne,Io as re,La as ie,Ma as ae,Mi as oe,Na as V,Ni as se,Oa as ce,Pa as le,Sa as ue,Ta as de,Yi as fe,Zo as pe,aa as me,eo as H,ja as he,ka as ge,nn as _e,ra as U,wa as ve,xa as ye,za as be}from"./client-BvflqtP1.js";import{t as xe}from"./boxes-BkzsIUkw.js";import{s as Se}from"./video-D0guHpd1.js";import{n as Ce,r as we,t as Te}from"./variable-BG_qKWYf.js";import{$a as Ee,Ad as De,An as Oe,B as ke,Ci as Ae,Cn as je,Ct as Me,Di as Ne,Dn as Pe,Fr as Fe,Ga as Ie,Gr as Le,Ho as Re,Hr as ze,Io as Be,Ka as Ve,Lr as He,Mo as Ue,Nd as We,Pd as W,Pr as G,Qa as Ge,Ql as Ke,R as qe,Ss as Je,Ti as Ye,Wa as Xe,Xa as Ze,Xn as Qe,Yn as $e,Zt as et,_t as tt,bi as nt,cn as rt,ct as it,eo as at,fi as K,if as ot,ii as q,is as st,kn as ct,kr as lt,nf as ut,nn as dt,qa as ft,rn as pt,si as mt,to as ht,un as gt,wi as _t,wt as vt,xi as yt,yt as bt,zd as J}from"./src-KDhMZ5Ob.js";import{t as Y}from"./i18n-Bg2ooh3q.js";import{t as X}from"./Trans-Bsz5Pghy.js";import{t as Z}from"./useTranslation-BJr-n0es.js";import{t as xt}from"./FormBuilder-BvQZWKCS.js";import{B as St,Q as Ct,S as wt,Y as Tt,b as Et,et as Dt,h as Ot,m as kt}from"./index-DMMw81r0.js";import{t as At}from"./AdminSectionedPage-B_tSbkIV.js";import{n as jt}from"./format-ChSVChsY.js";import{a as Mt,c as Nt,i as Pt,l as Ft,n as It,o as Lt,r as Rt,s as zt,t as Bt}from"./ComposedDeviceEditDialog-DlxMQhZP.js";import{C as Vt,G as Ht,Q as Ut,Y as Wt,a as Gt,at as Kt,b as qt,g as Jt,i as Yt,n as Xt,nt as Zt,o as Qt,r as $t,w as en,y as tn}from"./CompositionBlockEditor-Ctx6d-qx.js";var nn=`const AUTOMATION_RECIPE =`,rn=`// 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,o as d,t as f,x as p}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Di as m,Er as h,Hn as g,Ht as _,In as v,Ln as y,Tn as b,aa as x,dt as S,ha as C,hr as w,jr as T,ki as E,pr as D,st as O,ta as k,vt as A,xi as j,yn as M,zt as N}from"./player-overlays-DpZIxQHp.js";import{$a as P,$i as F,Aa as I,Ai as L,Ca as R,Da as z,Ea as ee,Fa as B,Hi as te,Ia as ne,Io as re,La as ie,Ma as ae,Mi as oe,Na as V,Ni as se,Oa as ce,Pa as le,Sa as ue,Ta as de,Yi as fe,Zo as pe,aa as me,eo as H,ja as he,ka as ge,nn as _e,ra as U,wa as ve,xa as ye,za as be}from"./client-BvflqtP1.js";import{t as xe}from"./boxes-BkzsIUkw.js";import{s as Se}from"./video-D0guHpd1.js";import{n as Ce,r as we,t as Te}from"./variable-BG_qKWYf.js";import{$a as Ee,Ad as De,An as Oe,B as ke,Ci as Ae,Cn as je,Ct as Me,Di as Ne,Dn as Pe,Fr as Fe,Ga as Ie,Gr as Le,Ho as Re,Hr as ze,Io as Be,Ka as Ve,Lr as He,Mo as Ue,Nd as We,Pd as W,Pr as G,Qa as Ge,Ql as Ke,R as qe,Ss as Je,Ti as Ye,Wa as Xe,Xa as Ze,Xn as Qe,Yn as $e,Zt as et,_t as tt,bi as nt,cn as rt,ct as it,eo as at,fi as K,if as ot,ii as q,is as st,kn as ct,kr as lt,nf as ut,nn as dt,qa as ft,rn as pt,si as mt,to as ht,un as gt,wi as _t,wt as vt,xi as yt,yt as bt,zd as J}from"./src-KDhMZ5Ob.js";import{t as Y}from"./i18n-Bg2ooh3q.js";import{t as X}from"./Trans-Bsz5Pghy.js";import{t as Z}from"./useTranslation-BJr-n0es.js";import{t as xt}from"./FormBuilder-BvQZWKCS.js";import{B as St,Q as Ct,S as wt,Y as Tt,b as Et,et as Dt,h as Ot,m as kt}from"./index-DGvsu0ui.js";import{t as At}from"./AdminSectionedPage-Dv8ahC-U.js";import{n as jt}from"./format-ChSVChsY.js";import{a as Mt,c as Nt,i as Pt,l as Ft,n as It,o as Lt,r as Rt,s as zt,t as Bt}from"./ComposedDeviceEditDialog-DNGwDK80.js";import{C as Vt,G as Ht,Q as Ut,Y as Wt,a as Gt,at as Kt,b as qt,g as Jt,i as Yt,n as Xt,nt as Zt,o as Qt,r as $t,w as en,y as tn}from"./CompositionBlockEditor-O3eDPOLD.js";var nn=`const AUTOMATION_RECIPE =`,rn=`// 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 an(e){return e.includes(nn)}function on(e){let t=e.indexOf(nn);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 sn(e){let t=on(e);if(t===null)return{ok:!1,reason:Y.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:Y.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=z.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Y.t(`helpers.recipeFromCode.schemaMismatch`):Y.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function cn(e){let t=on(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)}${rn}${e.slice(i)}`}u();var ln=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function un(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 ln}}function dn(e){switch(e){case`eq`:return Y.t(`helpers.recipeParts.op_eq`);case`ne`:return Y.t(`helpers.recipeParts.op_ne`);case`gt`:return Y.t(`helpers.recipeParts.op_gt`);case`gte`:return Y.t(`helpers.recipeParts.op_gte`);case`lt`:return Y.t(`helpers.recipeParts.op_lt`);case`lte`:return Y.t(`helpers.recipeParts.op_lte`);case`contains`:return Y.t(`helpers.recipeParts.op_contains`);default:return Y.t(`helpers.recipeParts.op_in`)}}function fn(e){return un(e).map(e=>({value:e,label:dn(e)}))}var pn=[`detection`,`stationary`,`device-becomes`,`device-event`,`schedule`,`interval`,`manual`],mn=[`device-is`,`stationary-present`,`expression`],hn=[...pn,...mn];function gn(e){switch(e){case`device-becomes`:return Y.t(`automation.whenTree.kind_device_becomes`);case`device-is`:return Y.t(`automation.whenTree.kind_device_is`);case`device-event`:return Y.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return Y.t(`helpers.recipeParts.trigger_schedule`);case`stationary`:return Y.t(`flow.trigger.stationary`);case`stationary-present`:return Y.t(`automation.whenTree.kind_stationary_present`);case`detection`:return Y.t(`flow.trigger.detection`);case`interval`:return Y.t(`flow.trigger.interval`);case`expression`:return Y.t(`automation.whenTree.kind_expression`);default:return Y.t(`helpers.recipeParts.trigger_manual`)}}var _n={when:{kind:`all`,children:[]},actions:[]};function vn(e){switch(e){case`device-becomes`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};case`detection`:return{kind:e,subjects:[{macro:`person`}],deviceIds:[]};case`stationary`:return{kind:e,deviceIds:[],phase:`appeared`};case`interval`:return{kind:e,minutes:5};case`device-is`:return{kind:e,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``};case`stationary-present`:return{kind:e,deviceId:0};case`expression`:return{kind:e,expr:``,bindings:{}};default:return{kind:`manual`}}}function yn(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
  `};case`action`:return{kind:e,actionId:``};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function bn(e,t,n){return e.map((e,r)=>r===t?n:e)}function xn(e,t){return e.filter((e,n)=>n!==t)}function Sn(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=xn(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function Cn(e,t){return{...e,actions:[...t]}}var wn=`when`;function Tn(e){return e===void 0||e.trim()===``?null:e}function En(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function Dn(e){return e.steps.map(e=>({index:En(e.path),tone:e.outcome===`ok`?`pass`:e.outcome===`error`?`fail`:`idle`,message:Tn(e.message)}))}function On(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=Tn(e.trigger.reason),r=e.conditions.find(e=>e.path===wn);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:Tn(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function kn(e,t){return e.outcome===`ran`?{tone:`pass`,reason:null}:e.outcome===`failed`||e.outcome===`aborted`?{tone:`fail`,reason:t.find(e=>e.tone===`fail`)?.message??null}:{tone:`idle`,reason:Tn(e.verdict?.reason)}}function An(e){let t=Dn(e);return{when:On(e),thenBlock:kn(e,t),steps:t}}function jn(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function Mn(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function Nn(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function Pn(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:Mn(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:Tn(e.reason),subject:Nn(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:Mn(e.expected),observed:e.observed===void 0?null:Mn(e.observed)})),steps:e.steps.map(e=>({index:En(e.path),kind:e.kind,tone:e.outcome===`ok`?`pass`:e.outcome===`error`?`fail`:`idle`,message:Tn(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:Mn(t)}))}))}}function Fn(e){return new Map(e.conditions.map(e=>[e.path,e.outcome]))}var In={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},Ln={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},Rn={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function zn(){let{t:e}=Z();return t=>{switch(t){case`ran`:return e(`flow.runs.outcomeRan`,`Ran`);case`failed`:return e(`flow.runs.outcomeFailed`,`Failed`);case`aborted`:return e(`flow.runs.outcomeAborted`,`Stopped`);case`skipped-trigger`:return e(`flow.runs.outcomeSkippedTrigger`,`Trigger not met`);case`skipped-conditions`:return e(`flow.runs.outcomeSkippedConditions`,`Skipped by conditions`);case`skipped-cooldown`:return e(`flow.runs.outcomeSkippedCooldown`,`Skipped by cooldown`);default:return e(`flow.runs.outcomeSkippedOverlap`,`Skipped by run mode`)}}}function Bn({traces:t,selectedId:n,onSelect:r}){let{t:i}=Z(),a=zn(),s=t===void 0?[]:t.toReversed();return o(Pe,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:h,children:t===void 0?o(He,{className:`m-3 h-16`}):s.length===0?o(Fe,{title:i(`flow.runs.emptyTitle`,`No runs yet`),description:i(`flow.runs.emptyDescription`,`Each run appears here with what it decided.`)}):e(p,{children:[o(`ul`,{className:`divide-y divide-border-subtle`,"data-testid":`runs-panel`,children:s.map(t=>{let i=t.runId===n;return e(`li`,{children:[e(`button`,{type:`button`,"aria-pressed":i,onClick:()=>r(i?null:t.runId),className:`flex w-full flex-col gap-1 px-3 py-2 text-left hover:bg-surface-hover ${i?`bg-primary/10`:``}`,children:[e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[o(K,{variant:In[t.outcome],children:a(t.outcome)}),t.repeat>1&&o(K,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:jt(t.lastAt)})]}),o(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]}),i&&o(Yn,{trace:t})]},t.runId)})}),o(`p`,{className:`border-t border-border-subtle px-3 py-2 text-xs text-foreground-subtle`,children:i(`flow.runs.hint`,`Select a run to colour the blocks: green passed, red failed, grey not evaluated.`)})]})})}var Vn={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},Hn={pass:`success`,fail:`danger`,idle:`neutral`},Un=[``,`pl-3`,`pl-6`,`pl-9`];function Wn({value:e}){let{t}=Z();return e.kind===`unknown`?o(`span`,{className:`italic text-foreground-subtle`,"data-testid":`trace-value-unknown`,children:t(`flow.runs.unknownValue`,`unknown`)}):o(`span`,{className:`font-mono text-foreground`,children:e.text})}function Gn({label:t,outcome:n,outcomeLabel:r,detail:i,expected:a,observed:s,depth:c=0}){let{t:l}=Z();return e(`li`,{className:`space-y-0.5 py-1 ${Un[Math.min(c,Un.length-1)]}`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(K,{variant:Vn[n],children:r}),o(`span`,{className:`min-w-0 break-words text-xs text-foreground`,children:t})]}),i!==void 0&&o(`div`,{className:`text-[11px] text-foreground-subtle`,children:i}),(a!==null||s!==null)&&e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[a!==null&&e(`span`,{children:[l(`flow.runs.expected`,`Expected`),` `,o(Wn,{value:a})]}),s!==null&&e(`span`,{children:[l(`flow.runs.observed`,`Observed`),` `,o(Wn,{value:s})]})]})]})}function Kn(){let{t:e}=Z();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function qn(e){let t=ge.safeParse(e);return t.success?dn(t.data):e}function Jn(e,t){return e.reason??e.subject??t}function Yn({trace:t}){let{t:n}=Z(),r=Kn(),i=Pn(t);return e(`div`,{className:`space-y-3 border-t border-border-subtle px-3 py-2`,"data-testid":`run-details`,children:[i.vars.length>0&&e(`section`,{children:[o(`h5`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-muted`,children:n(`flow.runs.triggerValues`,`Trigger`)}),o(`dl`,{className:`mt-1 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-xs`,children:i.vars.map(t=>e(`div`,{className:`contents`,children:[o(`dt`,{className:`text-foreground-subtle`,children:t.name}),o(`dd`,{className:`break-words`,children:o(Wn,{value:t.value})})]},t.name))})]}),i.conditions.length>0&&e(`section`,{children:[o(`h5`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-muted`,children:n(`flow.runs.whenValues`,`When`)}),o(`ul`,{className:`mt-1 divide-y divide-border-subtle`,children:i.conditions.map(e=>o(Gn,{depth:e.depth,label:Jn(e,e.kind),outcome:e.outcome,outcomeLabel:r(e.outcome),detail:e.subject!==null&&e.reason!==null?`${e.subject}${e.operator===null?``:` ${qn(e.operator)}`}`:void 0,expected:e.expected,observed:e.observed},e.path))})]}),i.steps.length>0&&e(`section`,{children:[o(`h5`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-muted`,children:n(`flow.runs.stepValues`,`Steps`)}),o(`ul`,{className:`mt-1 divide-y divide-border-subtle`,children:i.steps.map(t=>e(`li`,{className:`flex flex-wrap items-center gap-2 py-1 text-xs`,children:[o(K,{variant:Hn[t.tone],children:t.tone===`pass`?n(`flow.runs.stepOk`,`OK`):t.tone===`fail`?n(`flow.runs.stepError`,`Error`):n(`flow.runs.stepNotRun`,`Not run`)}),o(`span`,{className:`text-foreground-subtle`,children:`${String(t.index+1)}. ${t.kind}`}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message}),t.args.length>0&&o(`dl`,{className:`grid w-full grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 pl-2 text-[11px]`,"data-testid":`step-args`,children:t.args.map(t=>e(`div`,{className:`contents`,children:[o(`dt`,{className:`text-foreground-subtle`,children:t.name}),o(`dd`,{className:`break-words`,children:o(Wn,{value:t.value})})]},t.name))})]},t.index))})]})]})}function Xn(e){return Ln[e]}function Zn({step:t,title:n,hint:r,trace:i,children:a}){return e(`section`,{className:`rounded-lg border p-3 ${i===null?`border-border bg-surface`:Ln[i.tone]}`,"data-testid":`block-${t}`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`h4`,{className:`text-sm font-semibold uppercase tracking-wide`,children:n}),r!==void 0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i!==null&&i.reason!==null&&o(`p`,{className:`mb-2 text-xs font-medium ${Rn[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}function Q({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Qn(e){let t=Pt(e.deviceId);if(t.data!==void 0)return It(t.data,e.cap).find(t=>t.path===e.fieldPath)}function $n({value:t,devices:n,onChange:r}){let{t:i}=Z(),[a,s]=c(!1),l=n.find(e=>e.id===t.deviceId),u=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${l?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${t.cap}.${t.fieldPath}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[o(Q,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(q,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>s(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:u}),o(E,{className:`size-3.5 shrink-0`})]}),a&&o(er,{value:t,devices:n,onCancel:()=>s(!1),onConfirm:e=>{s(!1),r(e)}})]})}function er({value:t,devices:n,onCancel:i,onConfirm:a}){let{t:s}=Z(),l=Be({projection:`slim`}),u=r(()=>new Set(n.map(e=>e.id)),[n]),d=r(()=>e=>u.has(e.id),[u]),[f,m]=c(null),[h,g]=c(!1),[_,v]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!h&&l.status===`success`&&(g(!0),m(Kt(l.data).find(e=>e.id===t.deviceId)??null));let y=s(`automation.fieldPicker.title`,`Device value`);return o(bt,{open:!0,onClose:i,title:y,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(p,{children:[o(q,{variant:`ghost`,onClick:i,children:s(`common.cancel`,`Cancel`)}),o(q,{disabled:f===null||_===null,"data-testid":`field-picker-confirm`,onClick:()=>{f===null||_===null||a({deviceId:f.id,cap:_.cap,fieldPath:_.path})},children:s(`automation.fieldPicker.use`,`Use this value`)})]}),children:o(Ut,{kind:`formula`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:y,pickerTargetKind:null},device:f,field:_,deviceFilter:d,onDeviceChange:m,onFieldChange:v})})}var tr=1e4;function nr(e,t,n){let r=Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==t)),i=n===null?r:{...r,[t]:n};return Object.keys(i).length===0?void 0:i}function rr(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function ir({step:t,onChange:n}){let{t:r}=Z(),i=_t({},{refetchInterval:tr});if(i.data===void 0)return o(He,{className:`h-8 w-64`});let a=i.data.find(e=>e.id===t.actionId),s=t.actionId!==``&&a===void 0;return e(`div`,{className:`space-y-2`,"data-testid":`run-action-step`,children:[e(`label`,{className:`block max-w-sm`,children:[o(Q,{children:r(`automation.runAction.action`,`Action`)}),o(W,{value:t.actionId,onChange:e=>n({kind:`action`,actionId:e.target.value}),options:[{value:``,label:r(`automation.runAction.pick`,`Pick an action`)},...s?[{value:t.actionId,label:r(`automation.runAction.missing`,`Missing action ({{id}})`,{id:t.actionId})}]:[],...i.data.map(e=>({value:e.id,label:e.name}))]})]}),s&&o(`p`,{className:`text-xs text-danger`,children:r(`automation.runAction.missingHint`,`This action no longer exists. Pick another, or the step will fail.`)}),(a?.variables??[]).length>0&&o(`div`,{className:`flex flex-wrap items-end gap-3`,children:(a?.variables??[]).map(e=>o(ar,{variable:e,value:t.variables?.[e.name],onChange:r=>n(rr(t,nr(t.variables,e.name,r)))},e.name))})]})}function ar({variable:t,value:n,onChange:r}){let{t:i}=Z(),a=t.label??t.name,s=t.default===void 0?i(`automation.runAction.required`,`required`):i(`automation.runAction.defaultIs`,`default {{value}}`,{value:String(t.default)});if(t.type===`boolean`||t.type===`select`){let c=t.type===`boolean`?[{value:`true`,label:i(`common.yes`,`Yes`)},{value:`false`,label:i(`common.no`,`No`)}]:(t.options??[]).map(e=>({value:e,label:e}));return e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Nt,{widthClass:`w-40`,value:n===void 0?``:String(n),onChange:e=>{e.target.value===``?r(null):r(t.type===`boolean`?e.target.value===`true`:e.target.value)},options:[{value:``,label:s},...c]})]})}return t.type===`number`?e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Ft,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o(Q,{children:a}),o(J,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}var or=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function sr({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,onChange:c}){let{t:l}=Z(),u=or.filter(e=>i===void 0||i.includes(e.value));return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:l(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${s===void 0?`border-border`:Xn(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(K,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[o(Q,{children:l(`automation.actionList.step`,`Step`)}),o(W,{value:i.kind,onChange:e=>c(bn(t,d,yn(cr(e.target.value)))),options:u.map(e=>({value:e.value,label:l(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(q,{variant:`ghost`,disabled:d===0,onClick:()=>c(Sn(t,d,d-1)),title:l(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(k,{className:`h-3.5 w-3.5`})}),o(q,{variant:`ghost`,disabled:d===t.length-1,onClick:()=>c(Sn(t,d,d+1)),title:l(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(x,{className:`h-3.5 w-3.5`})}),o(q,{variant:`ghost`,onClick:()=>c(xn(t,d)),title:l(`automation.actionList.removeThisStep`,`Remove this step`),children:o(_,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Q,{children:l(`automation.actionList.seconds`,`Seconds`)}),o(J,{type:`number`,min:0,max:300,value:String(i.seconds),onChange:e=>c(bn(t,d,{kind:`wait`,seconds:Number(e.target.value)}))})]}),i.kind===`code`&&e(`label`,{className:`block`,children:[o(Q,{children:l(`automation.actionList.code`,`Code`)}),o(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:i.code,spellCheck:!1,onChange:e=>c(bn(t,d,{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`,{})}})})]}),i.kind===`cap`&&o(Mt,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>c(bn(t,d,e))}),i.kind===`action`&&o(ir,{step:i,onChange:e=>c(bn(t,d,e))})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>c([...t,yn(u[0]?.value??`cap`)]),children:[o(v,{className:`h-4 w-4`}),` `,l(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function cr(e){return or.find(t=>t.value===e)?.value??`cap`}function lr(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function ur(e){return[{name:`deviceId`,hint:e(`flow.scope.deviceId`,`the camera that saw it`)},{name:`className`,hint:e(`flow.scope.className`,`what it saw`)},{name:`trackId`,hint:e(`flow.scope.trackId`,`the track`)},{name:`score`,hint:e(`flow.scope.score`,`how sure the detector was`)}]}function dr(e){return[{name:`deviceId`,hint:e(`flow.scope.deviceId`,`the camera that saw it`)},{name:`className`,hint:e(`flow.scope.className`,`what it saw`)},{name:`phase`,hint:e(`flow.scope.phase`,`appeared or departed`)},{name:`entryId`,hint:e(`flow.scope.entryId`,`the stopped object`)}]}function fr(e){let t=[];return he(e,e=>{ae(e)&&t.push(e)}),t}function pr(e,t){let n=fr(e);if(n.length===0)return[];let[r,...i]=n.map(e=>e.kind===`detection`?ur(t):e.kind===`stationary`?dr(t):[]);return r===void 0?[]:r.filter(e=>i.every(t=>t.some(t=>t.name===e.name)))}var mr={name:``,steps:[],variables:[]};function hr(e){return e===null?mr:{name:e.name,steps:e.steps??[],variables:e.variables??[]}}function gr(e){let t=[],n=e=>{t.includes(e)||t.push(e)},r=e=>{if(zt(e)){n(e.$var);return}Array.isArray(e)?e.forEach(r):typeof e==`object`&&e&&Object.values(e).forEach(r)};for(let t of e)t.kind===`cap`&&(r(t.deviceId),r(t.args));return t}function _r(e){let t=new Set(e.variables.map(e=>e.name));return gr(e.steps).find(e=>!t.has(e))??null}function vr(e){if(e.name.trim()===``)return{ok:!1,reason:{kind:`name`}};if(e.steps.length===0)return{ok:!1,reason:{kind:`no-steps`}};let t=e.variables.find(e=>!Cr(e.name));if(t!==void 0)return{ok:!1,reason:{kind:`bad-name`,name:t.name}};let n=wr(e.variables)[0];if(n!==void 0)return{ok:!1,reason:{kind:`duplicate`,name:n}};let r=_r(e);if(r!==null)return{ok:!1,reason:{kind:`undeclared`,name:r}};let i=de.safeParse({name:e.name.trim(),steps:e.steps,...e.variables.length===0?{}:{variables:e.variables}});if(!i.success){let e=i.error.issues[0];return{ok:!1,reason:{kind:`schema`,message:`${e===void 0||e.path.length===0?``:`${e.path.join(`.`)}: `}${e?.message??`invalid`}`}}}return{ok:!0,input:i.data}}function yr(e,t,n){return zt(e)?e.$var===t?{$var:n}:e:Array.isArray(e)?e.map(e=>yr(e,t,n)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,r])=>[e,yr(r,t,n)])):e}function br(e,t,n){if(e.kind!==`cap`)return e;let r=zt(e.deviceId)&&e.deviceId.$var===t?{$var:n}:e.deviceId,i=e.args===void 0?void 0:Object.fromEntries(Object.entries(e.args).map(([e,r])=>[e,yr(r,t,n)]));return{...e,deviceId:r,...i===void 0?{}:{args:i}}}function xr(e,t,n){let r=e.variables[t];return r===void 0||r.name===n?e:{...e,variables:e.variables.map((e,r)=>r===t?{...e,name:n}:e),steps:e.steps.map(e=>br(e,r.name,n))}}function Sr(e){let t=new Set(e.map(e=>e.name)),n=`value`;for(let e=2;t.has(n);e++)n=`value${String(e)}`;return{name:n,type:`string`}}function Cr(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function wr(e){let t=new Set,n=new Set;for(let r of e)t.has(r.name)&&n.add(r.name),t.add(r.name);return[...n]}var Tr=[`number`,`string`,`boolean`,`select`];function Er(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function Dr(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function Or(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function kr(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function Ar({variables:t,onChange:n,onRename:r}){let{t:i}=Z(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return o(Pe,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:Te,actions:e(q,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Sr(t)]),children:[o(v,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),o(J,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!Cr(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),o(J,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,kr(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),o(Nt,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:Tr.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=Tr.find(t=>t===e.target.value);t!==void 0&&s(l,Er(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(jr,{variable:c,onChange:e=>s(l,Or(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(J,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,Dr(c,e.target.value))})]}),o(q,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(_,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function jr({variable:e,onChange:t}){let{t:n}=Z(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(Ft,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return o(Nt,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return o(J,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var Mr=5e3;function Nr(e){return e.kind===`cap`||e.kind===`wait`}function Pr(e){return e instanceof Error?e.message:String(e)}function Fr(){let{t:e}=Z();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function Ir({entry:t,onClose:n,onSaved:i}){let{t:a}=Z(),s=d(),l=O(),u=Rt(),f=Fr(),[m,h]=c(()=>hr(t)),[g,v]=c(null),b=t!==null&&t.readOnly,x=()=>{s.invalidateQueries({queryKey:[[`actions`]]})},S=nt({onSuccess:e=>{x(),i(e.action.id)}}),C=Ne({onSuccess:x}),T=yt({onSuccess:()=>{x(),n()}}),E=Ye({onSuccess:x}),k=Ae({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Mr}),A=k.data?.traces.find(e=>e.runId===g)??null,j=r(()=>A===null?null:An(A),[A]),M=vr(m),N=r(()=>lr(m.variables,a),[m.variables,a]),P=S.isPending||C.isPending,F=S.error??C.error??T.error??E.error,I=(t?.variables??[]).some(e=>e.required===!0&&e.default===void 0);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(w,{className:`h-4 w-4 text-foreground-muted`}),o(J,{"aria-label":a(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,disabled:b,placeholder:a(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>h({...m,name:e.target.value})}),o(K,{variant:b?`info`:`primary`,children:b?t?.addonId??``:a(`actions.source.internal`,`Internal`)})]}),b?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:a(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(p,{children:[o(Ar,{variables:m.variables,onChange:e=>h({...m,variables:e}),onRename:(e,t)=>h(xr(m,e,t))}),o(Zn,{step:`steps`,title:a(`actions.editor.steps`,`Steps`),trace:j===null?null:j.thenBlock,children:o(sr,{actions:m.steps,devices:u,allowedKinds:[`cap`,`wait`],variables:N,onChange:e=>h({...m,steps:e.filter(Nr)})})})]}),!M.ok&&!b&&m.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:f(M.reason)}),F!==null&&o(G,{message:Pr(F)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!b&&e(q,{onClick:()=>{M.ok&&(t===null?S.mutate({action:M.input}):C.mutate({actionId:t.id,action:M.input}))},disabled:P||!M.ok,children:[P&&o(D,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(q,{variant:`outline`,disabled:E.isPending||I,title:I?a(`actions.editor.runNeedsDefaults`,`Give each required variable a default to run it from here.`):void 0,onClick:()=>E.mutate({actionId:t.id}),children:[o(y,{className:`h-4 w-4`}),` `,a(`actions.editor.runNow`,`Run now`)]}),t!==null&&!b&&e(q,{variant:`ghost`,disabled:T.isPending,onClick:()=>{l({title:a(`actions.editor.deleteTitle`,`Delete this action?`),message:a(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&T.mutate({actionId:t.id})})},children:[o(_,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(q,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Bn,{traces:t===null?[]:k.data?.traces,selectedId:g,onSelect:v})})]})}u();var Lr=5e3;function Rr(e){return e instanceof Error?e.message:String(e)}function zr(){let{t:e}=Z();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function Br({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=Z(),a=d(),c=zr(),{state:l,openNew:u,openEdit:f,close:m}=tt({editKey:`action`,newKey:`new`}),h=_t({},{refetchInterval:Lr}),g=Ye({onSuccess:()=>void a.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(u(),n?.())},[t,n,u]);let _=h.data??[],b=l.mode===`edit`?_.find(e=>e.id===l.id)??null:null,x=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(K,{variant:`info`,children:e.addonId}):o(K,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):jt(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=c(e);return o(`span`,{title:e.status.lastError??void 0,children:o(K,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(q,{variant:`outline`,size:`sm`,disabled:g.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),g.mutate({actionId:t.id})},children:[o(y,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[g,c,i]);return l.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),g.error!=null&&o(G,{message:Rr(g.error)}),h.data===void 0?h.error==null?o(He,{className:`h-24 w-full`}):o(G,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:Rr(h.error),onRetry:()=>void h.refetch()}):_.length===0?o(Fe,{icon:w,title:i(`actions.list.emptyTitle`,`No actions yet`),description:i(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(q,{onClick:u,children:[o(v,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(p,{children:[h.error!=null&&o(G,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:Rr(h.error),onRetry:()=>void h.refetch()}),o(ct,{columns:x,rows:_,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Oe,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>f(e.id)})]})]}):o(Ir,{entry:b,onClose:m,onSaved:f},b?.id??`new`)}u();function Vr({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Z(),[l,u]=c(!1),d=O(),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?E:m,{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(Se,{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(je,{maxHeight:420,children:t})})]})}var Hr=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Ur=2,Wr=30;function Gr(e){return e.runMode??{mode:`single`}}function Kr(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function qr(e){switch(e){case`queued`:return{mode:`queued`,max:Ur};case`parallel`:return{mode:`parallel`,max:Ur};case`cooldown`:return{mode:`cooldown`,minutes:Wr};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function Jr(e){return Hr.find(t=>t===e)??`single`}function Yr({value:t,onChange:n}){let{t:r}=Z(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),o(Nt,{widthClass:`w-56`,value:t.mode,options:Hr.map(e=>({value:e,label:i[e]})),onChange:e=>n(qr(Jr(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),o(Ft,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),o(Ft,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),o(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var Xr;function Zr(){return Xr??=ue(_e),Xr}function Qr(e,t=Zr()){return ye(e,t)}function $r({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Z(),c=oi(n,r,i);if(n?.kind===`boolean`)return o(W,{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(W,{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(J,{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(J,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function ei({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Z(),s=oi(t,n,r);return o(J,{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 ti(e){return typeof e==`object`&&!be(e)}function ni(e){return be(e)?e.value:ti(e)?e[0]??``:e}function ri(e){return be(e)?[e.value]:ti(e)?e:typeof e==`boolean`?[]:[e]}function ii(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!re(t)||t===`none`||t===`device`))return ve(t).length>0?t:void 0}function ai(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function oi(e,t,n){let r=pt(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=Ue({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=re(s)?s:void 0,l=ai(e?.quantity,c);if(l===void 0)return;let u=o?.display;return dt({quantity:l,display:u,capName:n,unitPreferences:r})}function si({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qn(a),c=fn(s?.kind),l=t.operator===`in`,u=ii(s),d=u===void 0?void 0:R(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=ci(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...ri(t.value)]:ni(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o($n,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(W,{value:t.operator,onChange:e=>p(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(ei,{value:ri(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(qe,{quantity:u,storedUnit:d,value:typeof t.value==`number`?t.value:void 0,unit:t.unit,"aria-label":i(`automation.conditionRow.value`,`Value`),onChange:e=>{let n=ke(e,d);r({...t,value:n.value,unit:n.unit})}}):o($r,{value:ni(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function ci(e,t){return t.find(t=>t.value===e)?.value??`eq`}var li=Object.values(pe).sort((e,t)=>e.localeCompare(t));function ui({leaf:t,onChange:n}){let{t:r}=Z();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(J,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>n({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`,{})}})})]})}function di(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function fi(e,t){return{kind:`device-becomes`,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 pi({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Qn(a),c={...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}};return e(p,{children:[o($n,{value:a,devices:n,onChange:e=>r(fi(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Qe,{checked:t.becomes===void 0,onChange:e=>r(fi(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o($r,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(fi(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(Qe,{checked:t.edge===!0,onChange:e=>r(fi(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(J,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(fi(a,{...c,forMs:mi(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(J,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(fi(a,{...c,debounceMs:mi(e.target.value)}))})]})]})}function mi(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function hi({leaf:t,devices:n,onChange:r}){let{t:i}=Z();return e(p,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(W,{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…`)},...li.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(Lt,{devices:n,selection:`single`,value:t.deviceId===void 0?[]:[t.deviceId],emptyLabel:i(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>r({kind:`device-event`,category:t.category,...e[0]===void 0?{}:{deviceId:e[0]}})})]})]})}var gi={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function _i({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Q,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(J,{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(vi,{alias:e,source:r,devices:n,onRename:n=>s(wi(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Ti(t.bindings,e))},e)),e(q,{variant:`ghost`,onClick:()=>s({...t.bindings,[Ci(t.bindings)]:gi}),children:[o(v,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function vi({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Z(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:xi(r,bi(n)),cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Q,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(J,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Q,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(W,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:gi),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(J,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:yi(e.target.value)})})]}):o($n,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Si(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(_,{className:`h-3.5 w-3.5`})})]})}function yi(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function bi(e){return e.kind===`global`?e.sourceStableId:``}function xi(e,t){return e.find(e=>e.stableId===t)?.id??0}function Si(e,t){return e.find(e=>e.id===t)?.stableId??``}function Ci(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 wi(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Ti(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var Ei=`text-xs text-foreground-subtle`;function Di({children:e}){return o(`span`,{className:Ei,children:e})}function Oi(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function ki({devices:t,selected:n,onChange:r}){let{t:i}=Z(),a=t.filter(e=>e.type===H.Camera);return e(`div`,{className:`space-y-1`,children:[o(Di,{children:i(`flow.scene.cameras`,`Cameras`)}),o(Lt,{devices:a,selection:`multiple`,noun:`camera`,value:n,testId:`scene-cameras`,onChange:r})]})}function Ai({device:t,deviceId:n,selected:r,onToggle:i}){let a=De({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:Ei,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(q,{size:`sm`,variant:r.includes(e.id)?`primary`:`outline`,"aria-pressed":r.includes(e.id),onClick:()=>i(e.id),children:e.name},e.id))]})}function ji({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=Z();if(n.length===0)return null;let s=e=>{let t=Oi(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(Di,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(Ai,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:Ei,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var Mi=[`animal`,`person`,`vehicle`,`package`,`other`];function Ni(e){return Mi.find(t=>t===e)??`other`}function Pi(e){switch(e){case`animal`:return{macro:`animal`};case`person`:return{macro:`person`};case`vehicle`:return{macro:`vehicle`};case`package`:return{macro:`package`};default:return{macro:`other`,className:``}}}function Fi(){let{t:e}=Z();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return e(`automation.whenTree.macroOther`,`Other class`)}}}function Ii(e,t){let n={kind:`sub-class`,className:t};switch(e){case`animal`:return{macro:e,label:n};case`package`:return{macro:e,label:n};case`vehicle`:return{macro:e,label:n};default:return{macro:`person`}}}function Li(e,t){let n=ie(e).filter(t=>t!==e);return(t!==void 0&&!n.includes(t)?[...n,t]:n).map(e=>({value:e,label:e}))}function Ri({subject:e,onChange:t}){let{t:n}=Z(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=Li(e.macro,r);return i.length===0?null:o(W,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:r??``,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...i],onChange:n=>{let r=n.target.value;t(r===``?Pi(e.macro):Ii(e.macro,r))}})}function zi({onChange:e,subject:t}){let{t:n}=Z(),r=Je(),i=t.macro===`person`?t.label:void 0,a=r.data??[],s=a.map(e=>({value:e.id,label:e.name}));return i!==void 0&&!a.some(e=>e.id===i.identityId)&&s.push({value:i.identityId,label:i.name}),o(W,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:i?.identityId??``,options:[{value:``,label:n(`automation.whenTree.anyPerson`,`Anyone`)},...s],onChange:t=>{let n=t.target.value,r=s.find(e=>e.value===n);e(n===``||r===void 0?{macro:`person`}:{macro:`person`,label:{kind:`identity`,identityId:n,name:r.label}})}})}var Bi=`plate:`,Vi=`class:`,Hi=200;function Ui({onChange:e,subject:t}){let{t:n}=Z(),r=Ke({includeCrops:!1,limit:Hi}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=i?.kind===`sub-class`?i.className:void 0,c=[...new Set((r.data??[]).map(e=>e.text))];a!==void 0&&!c.includes(a)&&c.push(a);let l=a===void 0?s===void 0?``:`${Vi}${s}`:`${Bi}${a}`;return o(W,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:l,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...Li(`vehicle`,s).map(e=>({value:`${Vi}${e.value}`,label:e.label})),...c.map(e=>({value:`${Bi}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(Bi)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(Vi)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function Wi({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=Z(),c=Fi(),l=t.macro===`other`?[]:ne[t.macro],u=l.some(e=>e.kind===`cap`&&e.label===`identity`),d=l.some(e=>e.kind===`cap`&&e.label===`plate`);return e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`subject-row`,children:[o(`div`,{className:`w-36`,children:o(W,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:Mi.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=Ni(e.target.value);n!==t.macro&&i(Pi(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(J,{className:`w-40`,"aria-label":s(`automation.whenTree.className`,`Class name`),"data-testid":`subject-class-name`,placeholder:s(`automation.whenTree.classNamePlaceholder`,`Class name`),value:t.className,onChange:e=>i({macro:`other`,className:e.target.value})}):u&&!n?o(`div`,{className:`w-44`,children:o(zi,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o(Ui,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(Ri,{subject:t,onChange:i})}),a!==null&&o(q,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(_,{className:`h-3.5 w-3.5`})})]})}function Gi({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=Z(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(Wi,{subject:e,classLabelsOnly:r,verb:n===0?i:s(`automation.whenTree.orSubject`,`or`),onChange:e=>a(t.map((t,r)=>r===n?e:t)),onRemove:c?()=>a(t.filter((e,t)=>t!==n)):null},`${e.macro}-${String(n)}`)),t.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`flow.scene.anyClass`,`None picked: any class counts.`)}),e(q,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,Pi(`person`)]),children:[o(v,{className:`h-3.5 w-3.5`}),` `,t.length===0?s(`automation.whenTree.onlySomeClasses`,`Only some classes`):s(`automation.whenTree.addClass`,`Add a class`)]})]})}var Ki=100;function qi({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=Math.round((t.minScore??0)*Ki),s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/Ki})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(Gi,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o(ki,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(ji,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(Di,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/Ki).toFixed(2)})}),o(`input`,{type:`range`,min:0,max:Ki,value:a,"aria-label":i(`flow.scene.minScoreAria`,`Minimum score`),className:`block w-full max-w-sm accent-primary`,onChange:e=>c(Number(e.target.value))})]})]})}function Ji({leaf:t,devices:n,onChange:r}){let{t:i}=Z();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(Gi,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.parked`,`object`),onChange:e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})}}),o(ki,{devices:n,selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(ji,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(it,{label:i(`flow.scene.firesWhen`,`Fires when it`),value:t.phase,onChange:e=>r({...t,phase:e}),options:[{value:`appeared`,label:i(`flow.scene.phaseAppeared`,`Stopped (parked)`)},{value:`departed`,label:i(`flow.scene.phaseDeparted`,`Left`)}]})]})}function Yi({leaf:t,onChange:n}){let{t:r}=Z();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(Di,{children:r(`flow.scene.every`,`Every`)}),o(Ft,{"aria-label":r(`flow.scene.intervalMinutes`,`Minutes`),className:`w-20`,value:t.minutes,onValue:e=>{e!==null&&n({kind:`interval`,minutes:Math.round(e)})}}),o(Di,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Xi({leaf:t,devices:n,onChange:r}){let{t:i}=Z(),a=n.filter(e=>e.type===H.Camera),s=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},c=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},l=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[o(Di,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(Lt,{devices:a,selection:`single`,noun:`camera`,value:t.deviceId>0?[t.deviceId]:[],testId:`stationary-present-camera`,onChange:e=>{let n=e[0];n!==void 0&&n!==t.deviceId&&l(n)}})]}),o(Gi,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:s}),o(ji,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:c})]})}function Zi(e){return e.kind===`all`||e.kind===`any`}function Qi(e){return[`when`,...e].join(`.`)}function $i(e){let t=e.when;return Zi(t)?t:{kind:`all`,children:[t]}}function ea(e,t){return{...e,when:t}}function ta(e){return ea(e,$i(e))}function na(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?na(e.child,r):null;if(V(e))return null;let i=e.children[n];return i===void 0?null:na(i,r)}function ra(e,t,n){let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=ra(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(V(e))return e;let a=e.children[r];if(a===void 0)return e;let o=ra(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 ia(e,t,n){let r=$i(e);return ea(e,ra(r,t,n)??{kind:r.kind,children:[]})}function aa(e){return{kind:e,children:[vn(`device-is`)]}}function oa(e,t,n){return ia(e,t,e=>Zi(e)?{kind:e.kind,children:[...e.children,n]}:e)}function sa(e,t,n){return ia(e,t,()=>n)}function ca(e,t){return ia(e,t,()=>null)}function la(e,t,n){return ia(e,t,e=>Zi(e)?{kind:n,children:e.children}:e)}function ua(e,t){return t.length===0?e:ia(e,t,e=>({kind:`not`,child:e}))}function da(e,t){return ia(e,t,e=>e.kind===`not`?e.child:e)}function fa(e,t){let n=$i(e),r=na(n,t),i=t.slice(0,-1),a=t[t.length-1],o=na(n,i);return r===null||!Zi(r)||a===void 0||o===null||!Zi(o)?e:ia(e,i,()=>({kind:o.kind,children:[...o.children.slice(0,a),...r.children,...o.children.slice(a+1)]}))}function pa(e,t){if(e.kind===t)return e;if(e.kind===`device-is`&&t===`device-becomes`){let{deviceId:n,cap:r,fieldPath:i,operator:a,value:o}=e,s={kind:t,deviceId:n,cap:r,fieldPath:i};return a===`eq`&&!Array.isArray(o)&&typeof o!=`object`?{...s,becomes:o}:s}if(e.kind===`device-becomes`&&t===`device-is`){let{deviceId:n,cap:r,fieldPath:i,becomes:a}=e;return{kind:t,deviceId:n,cap:r,fieldPath:i,operator:`eq`,value:a??``}}return vn(t)}function ma(e){let t=$i(e),n=t.children.length===0;return{depth:n?0:B(t),leaves:n?0:I(t),depthLimit:4,leafLimit:32}}function ha(e,t){let n=$i(e),r=1,i=n;for(let e of t){let t=na(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function ga(e){let t=new Map,n=(e,r)=>{if(V(e))return!1;let i=e.kind===`not`?[e.child]:e.children,a=!1;if(i.forEach((e,t)=>{n(e,[...r,t])&&(a=!0)}),a)return!0;let o=le(e);return o===null?!1:(t.set(Qi(r),o),!0)};return n(e,[]),t}function _a(){let{t:e}=Z(),t={detection:e(`flow.triggerHint.detection`,`An object class is detected on a camera`),stationary:e(`flow.triggerHint.stationary`,`An object stops, or leaves`),"device-becomes":e(`automation.whenTree.hint_device_becomes`,`A device value takes a value`),"device-event":e(`flow.triggerHint.deviceEvent`,`An event on the system`),schedule:e(`flow.triggerHint.schedule`,`At a time of day`),interval:e(`flow.triggerHint.interval`,`Again and again, every few minutes`),manual:e(`flow.triggerHint.manual`,`Only when you run it`),"device-is":e(`automation.whenTree.hint_device_is`,`A device value is, right now`),"stationary-present":e(`automation.whenTree.hint_stationary_present`,`An object is parked on a camera, right now`),expression:e(`automation.whenTree.hint_expression`,`Arithmetic across device values, right now`)},n=e(`automation.whenTree.groupEvents`,`Happens (an event)`),r=e(`automation.whenTree.groupStates`,`Is true (a state)`);return hn.map(e=>({value:e,label:gn(e),description:t[e],group:pn.includes(e)?n:r}))}function va(e){return hn.find(t=>t===e)??null}function ya({leaf:t,devices:n,toneClass:r,onNegate:i,onChange:a,onRemove:s}){let{t:c}=Z(),l=_a(),u=ae(t);return e(`div`,{className:`rounded border p-2 ${r}`,"data-testid":`when-row`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`div`,{className:`min-w-[13rem] max-w-xs flex-1`,children:[o(Q,{children:c(`automation.whenTree.rowType`,`Row type`)}),o(mt,{mode:`single`,singleDisplay:`field`,options:l,value:t.kind,testId:`when-row-type`,optionTestIdPrefix:`when-kind`,onChange:e=>{let n=va(e);n!==null&&n!==t.kind&&a(pa(t,n))}})]}),o(K,{variant:u?`info`:`neutral`,"data-testid":`when-row-nature`,children:u?c(`automation.whenTree.natureEvent`,`Event`):c(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),i!==null&&o(q,{variant:`ghost`,onClick:i,title:c(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),o(q,{variant:`ghost`,onClick:s,title:c(`automation.whenTree.removeRow`,`Remove this row`),children:o(_,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(ba,{leaf:t,devices:n,onChange:a})})]})}function ba({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(pi,{leaf:e,devices:t,onChange:n});case`device-event`:return o(hi,{leaf:e,devices:t,onChange:n});case`schedule`:return o(ui,{leaf:e,onChange:n});case`interval`:return o(Yi,{leaf:e,onChange:n});case`manual`:return o(di,{});case`detection`:return o(qi,{leaf:e,devices:t,onChange:n});case`stationary`:return o(Ji,{leaf:e,devices:t,onChange:n});case`device-is`:return o(si,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(Xi,{leaf:e,devices:t,onChange:n});case`expression`:return o(_i,{leaf:e,devices:t,onChange:n})}}u();var xa=new Map;function Sa(e){return e===`any`?`any`:`all`}function Ca(e){return e===void 0?`border-border`:Xn(e===`pass`?`pass`:e===`fail`?`fail`:`idle`)}function wa({recipe:t,devices:n,onChange:i,outcomes:a=xa}){let{t:s}=Z(),c=$i(t),l=ma(t),u={recipe:t,devices:n,issues:r(()=>ga(c),[c]),outcomes:a,onChange:i},d=c.children.length===0;return e(`div`,{className:`space-y-2`,"data-testid":`when-tree`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`automation.whenTree.rule`,`An event starts a run when it happens and everything here is true at that moment. With only states, a run starts when they become true.`)}),o(ka,{block:c,path:[],ctx:u,underNot:!1,budgetText:s(`automation.whenTree.budget`,{depth:l.depth,depthLimit:l.depthLimit,leaves:l.leaves,leafLimit:l.leafLimit}),emptyHint:d?s(`automation.whenTree.empty`,`Add a row to say when this runs. Without one nothing can ever start this automation.`):null})]})}function Ta({node:e,path:t,ctx:n,underNot:r}){return V(e)?o(Ea,{leaf:e,path:t,ctx:n,underNot:r}):e.kind===`not`?o(Oa,{child:e.child,path:t,ctx:n}):o(ka,{block:e,path:t,ctx:n,underNot:r,budgetText:null,emptyHint:null})}function Ea({leaf:e,path:t,ctx:n,underNot:r}){return o(ya,{leaf:e,devices:n.devices,toneClass:Ca(n.outcomes?.get(Qi(t))),onNegate:r?null:()=>n.onChange(ua(n.recipe,t)),onChange:e=>n.onChange(sa(n.recipe,t,e)),onRemove:()=>n.onChange(ca(n.recipe,t))})}function Da({message:e}){return e===void 0?null:o(`p`,{role:`alert`,"data-testid":`when-issue`,className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:e})}function Oa({child:t,path:n,ctx:r}){let{t:i}=Z();return e(`div`,{className:`space-y-1.5 rounded border border-warning/40 p-2`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(K,{variant:`warning`,children:`NOT`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.whenTree.notHint`,`True when what is below is not`)}),o(`span`,{className:`flex-1`}),e(q,{variant:`ghost`,onClick:()=>r.onChange(da(r.recipe,n)),title:i(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(Ce,{className:`h-3.5 w-3.5`}),` `,i(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(Da,{message:r.issues.get(Qi(n))}),o(`div`,{className:`pl-3`,children:o(Ta,{node:t,path:[...n,0],ctx:r,underNot:!0})})]})}function ka({block:t,path:n,ctx:r,underNot:i,budgetText:a,emptyHint:s}){let{t:c}=Z(),l=n.length===0,u=ha(r.recipe,n),d=[{value:`all`,label:c(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:c(`automation.whenTree.anyOf`,`Any of (OR)`)}],f=s===null?r.issues.get(Qi(n)):void 0;return e(`div`,{className:`space-y-2 rounded border border-border bg-surface-subtle/40 p-2`,"data-testid":`when-block`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`div`,{className:`w-40`,children:o(W,{"aria-label":c(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:d,onChange:e=>r.onChange(la(r.recipe,n,Sa(e.target.value)))})}),a!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a}),o(`span`,{className:`flex-1`}),!l&&!i&&o(q,{variant:`ghost`,onClick:()=>r.onChange(ua(r.recipe,n)),title:c(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!l&&o(q,{variant:`ghost`,onClick:()=>r.onChange(fa(r.recipe,n)),title:c(`automation.whenTree.ungroup`,`Dissolve this block, keeping its rows`),children:o(Ce,{className:`h-3.5 w-3.5`})}),!l&&o(q,{variant:`ghost`,onClick:()=>r.onChange(ca(r.recipe,n)),title:c(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(_,{className:`h-3.5 w-3.5`})})]}),o(Da,{message:f}),s!==null&&o(`p`,{className:`text-xs text-warning`,children:s}),t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l border-border pl-3`,children:t.children.map((e,t)=>o(Ta,{node:e,path:[...n,t],ctx:r,underNot:!1},Qi([...n,t])))}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>r.onChange(oa(r.recipe,n,vn(`device-is`))),title:c(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(v,{className:`h-4 w-4`}),` `,c(`automation.whenTree.addRow`,`Add row`)]}),e(q,{variant:`outline`,disabled:!u,onClick:()=>r.onChange(oa(r.recipe,n,aa(t.kind===`all`?`any`:`all`))),title:u?c(`automation.whenTree.addBlockTitle`,`Add a nested block of rows`):c(`automation.whenTree.tooDeep`,`The rules nest at most {{max}} levels deep`,{max:ma(r.recipe).depthLimit}),children:[o(v,{className:`h-4 w-4`}),` `,c(`automation.whenTree.addBlock`,`Add block`)]})]})]})}u();var Aa=`hub`,ja=5e3;function Ma({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Z(),[p,m]=c(t?.name??``),[h,g]=c(()=>ta(n)),[_,v]=c(!1),[y,b]=c(null),x=Ze({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:ja}),S=x.data?.traces.find(e=>e.runId===y)??null,C=r(()=>S===null?null:An(S),[S]),w=r(()=>pr(h.when,f),[h.when,f]),T=r(()=>S===null?void 0:Fn(S),[S]),E=Rt(),O=ce(h),k=r(()=>Na(h),[h]),A=r(()=>Pa(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),j=p.trim()===``,N=j||O!==null||k!==null||A.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(J,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Zn,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:C===null?null:C.when,children:o(wa,{recipe:h,devices:E,outcomes:T,onChange:g})}),o(Zn,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:C===null?null:C.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(sr,{actions:h.actions,devices:E,variables:w,stepTones:C===null?void 0:h.actions.map((e,t)=>jn(C,t)??`idle`),onChange:e=>g(Cn(h,e))})}),o(Zn,{step:`mode`,title:f(`flow.runMode.title`,`Overlap`),trace:null,hint:f(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(Yr,{value:Gr(h),onChange:e=>g(Kr(h,e))})}),o(Vr,{code:A.code,error:A.error,canEject:t!==null,ejecting:s,onEject:u}),O!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:O}),O===null&&k!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:k}),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:()=>{A.code!==null&&l({name:p.trim(),code:A.code,enabled:t?.enabled??!0,placement:Aa})},disabled:i||N,children:[i&&o(D,{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`,"aria-expanded":_,children:[o(M,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(We,{expanded:_})]}),o(q,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),j&&o(K,{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:L(t.id)},components:{code:o(`code`,{})}})}),o(rt,{addonId:L(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Bn,{traces:t===null?[]:x.data?.traces,selectedId:y,onSelect:b})})]})}function Na(e){let t=z.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Y.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Pa(e,t){let n=Qr(t);if(!n.ok)return{code:null,error:n.error};try{return{code:ee({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Fa(e){if(!e.enabled)return{tone:`idle`,label:Y.t(`helpers.coreBlockStatus.disabled`),detail:Y.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Y.t(`helpers.coreBlockStatus.running`),detail:Y.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function Ia(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function La(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Ra(e){let t=e=>{let t=Fa(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 za(e){if(e.length===0)return Y.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Fa(e).tone===`error`).length,n=e.filter(e=>Fa(e).tone===`ok`).length,r=[Y.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Y.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Y.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var Ba=3e4;function Va({block:t,logsOpen:n,unreadable:r}){let i=C(),{t:a}=Z(),s=Fa(t),c=et(t.updatedAt,i);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(K,{variant:Ia(s.tone),children:s.label}),c!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.edited`,{when:c})})]}),(s.tone===`error`||s.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:s.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:a(`automation.editor.listUnreadable`,{reason:r})}),n&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:L(t.id)},components:{code:o(`code`,{})}})}),o(rt,{addonId:L(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var Ha=2;function Ua(e){let t=[];if(he(e.when,e=>{ae(e)&&t.push(gn(e.kind))}),t.length===0)return I(e.when)===0?``:Y.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,Ha).join(`, `),i=n.length-Ha;return i>0?`${r} +${i}`:r}function Wa({recipe:e}){let{t}=Z();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=Ua(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function Ga({blockId:t}){let{t:n}=Z(),r=Ze({blockId:t},{refetchInterval:Ba});if(r.data===void 0)return r.error===null||r.error===void 0?o(He,{className:`h-4 w-16`}):o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[jt(i.lastAt),a&&o(K,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function Ka({block:e,disabled:t,onToggle:n}){let{t:r}=Z();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o($e,{checked:e.enabled,disabled:t,onCheckedChange:n,"aria-label":e.enabled?r(`automation.automationList.disableNamed`,`Disable {{name}}`,{name:e.name}):r(`automation.automationList.enableNamed`,`Enable {{name}}`,{name:e.name})})})}function qa({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=Z();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(vt,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:g,disabled:e!==null,description:e===null?void 0:i(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),onClick:t},{id:`run`,label:i(`automation.automationList.runActions`,`Run actions`),icon:y,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:M,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:_,danger:!0,separatorBefore:!0,onClick:r}]})})}function Ja({onCreate:t}){let{t:n}=Z();return o(Fe,{icon:A,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(q,{onClick:t,"data-testid":`automation-empty-new`,children:[o(v,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var Ya=[`coreBlocks`,`list`],Xa=5e3;function Za(e){return e instanceof Error?e.message:String(e)}function Qa({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=Z(),u=S(),{state:d,openNew:p,openEdit:m,close:h}=tt({editKey:`block`,newKey:`new`}),g=O(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(p(),i?.())},[n,i,p]);let b=l({queryKey:Ya,refetchInterval:Xa,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),x=()=>{b.refetch()},C=e=>{h(),x(),wt({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},w=f({mutationFn:e=>u.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>C(e.block)}),T=f({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>C(e.block)}),E=f({mutationFn:e=>u.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:x}),D=f({mutationFn:e=>u.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:x}),k=f({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:cn(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{h(),x(),t(e.block.id)}}),j=b.data,M=Ra((j??[]).filter(e=>an(e.code))),N=j!==void 0&&M.length===0,P=d.mode===`edit`?M.find(e=>e.id===d.id)??null:null,F=d.mode===`edit`&&j!==void 0&&P===null;s(()=>{F&&h()},[F,h]);let I=P===null?null:sn(P.code),L=w.error===null?T.error===null?k.error===null?null:Za(k.error):Za(T.error):Za(w.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=sn(e.code);return o(Va,{block:e,logsOpen:_===e.id,unreadable:t.ok?null:t.reason})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=sn(e.code);return o(Wa,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>o(Ga,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(Ka,{block:e,disabled:D.isPending,onToggle:t=>D.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=sn(e.code);return o(qa,{unreadable:t.ok?null:t.reason,onEdit:()=>m(e.id),onToggleLogs:()=>v(_===e.id?null:e.id),onDelete:()=>{g({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&E.mutate(e.id)})}})}}],[g,_,m,E,D,a]);return y?d.mode===`edit`&&P===null?o(He,{className:`h-24 w-full`}):e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(A,{className:`h-4 w-4 text-foreground-muted`}),P===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:P.name})]}),o(Ma,{existing:P,initialRecipe:I!==null&&I.ok?I.recipe:_n,saving:w.isPending||T.isPending,saveError:L,ejecting:k.isPending,onSave:e=>{P===null?w.mutate(e):T.mutate({blockId:P.id,block:e})},onEject:()=>{P!==null&&k.mutate(P)},onCancel:()=>{w.reset(),T.reset(),k.reset(),h()}},P?.id??`new`),E.error!=null&&o(G,{message:Za(E.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:j===void 0?``:za(M)}),b.error!=null&&o(G,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Za(b.error),onRetry:x}),N?o(Ja,{onCreate:p}):o(ct,{columns:R,rows:M,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Oe,emptyMessage:j===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),E.error!=null&&o(G,{message:Za(E.error)}),D.error!=null&&o(G,{message:Za(D.error)})]})}u();function $a({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=Z(),u=Wt(!0),[d,f]=c({}),[p,m]=c(s(t.nameKey)),[h,g]=c(null),[_,v]=c([]),[y,b]=c(!1),x=r(()=>u.kind===`known`?new Map(u.value.map(e=>[U({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[U(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:Vt(u.value,S)}:u,[u,S]),w=$t(t,d),T=u.kind===`known`?en(u.value,w,!1):null,E=t.build(d),D=Yt(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(U(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:s(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[s(`preset.name`),o(J,{"aria-label":s(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),o(`ul`,{className:`flex flex-col gap-2`,"aria-label":s(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[s(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[Zt(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(q,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(q,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:s(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&o(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:s(`preset.missing`,{slots:D.map(e=>s(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[o(`h3`,{className:`text-xs font-medium text-foreground`,children:s(`preset.preview`)}),o(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?o(`li`,{children:s(`preset.previewFeature`,{cap:Zt(e.cap,l.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),o(Qt,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(q,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),i(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:s(`preset.create`)}),o(q,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(qt,{open:h!==null,title:h===null?``:s(`preset.pickTitle`,{slot:s(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>s(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}u();var eo=`preset`;function to({mode:e,onTitle:t}){return o(e===`helper`?no:ro,{onTitle:t})}function no({onTitle:e}){let{t}=Z(),r=Ct(),i=Xe(),a=st(),l=Re({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=Dt(),g=Gt(m.get(eo)),_=g===null?ao(u,t):t(g.labelKey);s(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(eo):n.set(eo,e),n},{replace:!0}),y=async(e,n)=>{try{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:e}}),s=await lo(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:Jt(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(kt(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:Jt(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(ro,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Xt,{fillHeight:!0,onFreeComposition:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,n)=>{let o=null,s=await tn(e,async(s,c)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:s}});d=t.id,b.current={draft:e,blockId:d}}let f=await lo(d,async()=>(await l.refetch()).data??l.data);if(f===null)throw Error(t(`helper.devicePending`));o=f,b.current=null,c!==``&&await a.mutateAsync({deviceId:f,name:c}),n===`open`&&r(Ot(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:uo(s,t)}:{kind:`saved`,deviceId:c}}})}):o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o($a,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function ro({onTitle:t}){let{t:n}=Z(),r=C(),i=Ct(),a=Xe(),l=st(),u=Re({addonId:`composer`}),[d,f]=c(H.Sensor),[p,m]=c(P.TemperatureSensor),[h,g]=c(``),[_,v]=c(null),y=Ht({type:d,role:p});return s(()=>{t(n(`helper.newComposition`))},[t,n]),e(`div`,{className:`flex flex-col gap-3`,"data-testid":`blank-composition-form`,children:[e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.targetType`),o(W,{value:d,onChange:e=>{let t=Object.values(H).find(t=>t===e.target.value);t!==void 0&&f(t)},options:Object.values(H).map(e=>({value:e,label:ot(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`customize.identity.role`),o(W,{value:p??``,onChange:e=>m(Object.values(P).find(t=>t===e.target.value)??null),options:[{value:``,label:n(`customize.identity.noRole`)},...Object.values(P).map(e=>({value:e,label:ut(e,r).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(J,{"aria-label":n(`compositionEditor.name`),value:h,onChange:e=>g(e.target.value)})]})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(q,{disabled:y===null||a.isPending,onClick:()=>{y!==null&&io({composition:y,name:h,create:e=>a.mutateAsync({block:e}),rename:(e,t)=>l.mutateAsync({deviceId:e,name:t}),readFleet:async()=>(await u.refetch()).data??u.data,onError:e=>v(e),onOpen:e=>i(kt(e),{replace:!0}),pending:n(`helper.devicePending`)})},children:n(`compositionEditor.save`)})]})}async function io(e){e.onError(null);try{let t=e.name.trim(),{block:n}=await e.create({...t===``?{}:{name:t},enabled:!0,composition:e.composition}),r=await lo(n.id,e.readFleet);if(r===null){e.onError(e.pending);return}t!==``&&await e.rename(r,t),e.onOpen(r)}catch(t){e.onError(t instanceof Error?t.message:String(t))}}function ao(e,t){if(e===null)return t(`helper.newComposed`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);if(e.templateId===`appliance`&&e.appliance!==null)return t(`helper.newTitle.${e.appliance}`);if(e.templateId===`appliance`)return t(`helper.newComposed`);let n=te(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}async function oo(e,t){let n=`${fe}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var so=10,co=400;async function lo(e,t,n=co){for(let r=0;r<so;r+=1){let r=await oo(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}function uo(e,t){return e.length>0?e:Jt(t(`helper.devicePending`))}function fo(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`appliance`:return{section:`group`,kind:`appliance`};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function po(e){return{state:`answered`,byRef:new Map(e.map(e=>[U(e),e]))}}function mo(e,t){if(e.state!==`unanswered`)return e.byRef.get(U(t))??null}function ho(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function go(e){return me(e).map(e=>e.source)}function _o(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(...go(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...go(e))}let r=new Set;return n.filter(e=>{let t=U(e);return r.has(t)?!1:(r.add(t),!0)})}function vo(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:Y.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Y.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Y.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Y.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function yo(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return vo(e);case`degraded`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.degraded`),reason:n??Y.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Y.t(`helpers.compositionRows.failed`),reason:n??Y.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Y.t(`helpers.compositionRows.notRunning`),reason:n??Y.t(`helpers.compositionRows.notRunningReason`)}}}function bo(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Y.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Y.t(`helpers.compositionRows.unknown`),reason:Y.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return yo(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.notReported`),reason:Y.t(`helpers.compositionRows.noRecord`,{stored:r})}}function xo(e){return U(e)}function So(e,t){let n=mo(t,e);return{key:U(e),label:n?n.name:xo(e),presence:ho(n),deviceId:n?n.id:null}}function Co(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function wo(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:F(e.block.id),a=U(i),o=_o(e).filter(e=>U(e)!==a).map(e=>So(e,t)),s=n.features.map(e=>e.enabled===!1?Y.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=mo(t,i),l=Co(e),u=bo(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,origin:fo(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=ho(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:xo(r.device),namePresence:d,type:c?c.type:null,origin:fo(n),features:s,state:u,sources:o,reportedDeviceId:l}}function To(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function Eo(e,t){return To(e)-To(t)||e.name.localeCompare(t.name)}function Do(e,t){let n=e.flatMap(e=>{let n=wo(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(Eo),customizations:n.filter(e=>e.kind===`customization`).toSorted(Eo)}}u();var Oo=1e4;function ko(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function Ao(){let e=St();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Y.t(`build.customDeviceTab.deviceListPending`):Y.t(`build.customDeviceTab.deviceListUnreadable`,{error:ko(e.error)})}:po(e.data)}function jo(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function Mo({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Z(),[i,a]=Dt(),s=Ge({},{refetchInterval:Oo}),l=Ao(),u=tt({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?jo(i.get(`new`),t):null,m=f!==null,[h,g]=c(``),_=O(),v=Ie(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=s.data;return e(p,{children:[Po(b,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void s.refetch()})})}}),o(bt,{open:m,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:xe,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(to,{mode:f,onTitle:g},f)}),o(Bt,{blockId:d,onClose:y}),v.error!=null&&o(G,{message:ko(v.error)})]})}function No(t){return o(lt,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Y.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Y.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function Po(e,t,n,r,i){if(t!=null&&e===void 0)return o(G,{title:Y.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:ko(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Y.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return No(e.reason);let a=t==null?null:ko(t);return o(Fo,{lists:Do(e.views,r),fleet:r,refreshError:a,handlers:i})}function Fo({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=Z();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(Io,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,handlers:i}),o(Io,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,handlers:i})]})}function Io({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=Z();return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(ct,{columns:Lo(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:Oe,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Lo(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(zo,{row:e})},{key:`type`,header:Y.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Y.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Y.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>Ro(e.origin,i),render:e=>o(K,{variant:`default`,"data-testid":`composed-origin-badge`,children:Ro(e.origin,i)})}]:[],{key:`state`,header:Y.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(K,{variant:Ia(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:Y.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Vo,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[o(q,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(q,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(_,{className:`h-4 w-4`})})]})}),a}function Ro(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function zo({row:t}){let{t:n}=Z();return e(`div`,{className:`space-y-0.5`,children:[o(Bo,{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 Bo({row:e}){let{t}=Z(),n=Le(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(Tt,{to:e.kind===`composed`?Ot(e.reportedDeviceId):kt(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Vo({sources:t}){let{t:n}=Z();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(Tt,{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 Ho(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 Uo(e){if(Array.isArray(e))return e}function Wo(e,t,n){return(t=$o(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Go(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 Ko(){throw TypeError(`Invalid attempt to destructure non-iterable instance.