@camstack/addon-admin-ui 1.2.439 → 1.2.440

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 (136) hide show
  1. package/dist/assets/{AddonAssetIcon-BDSwFXgm.js → AddonAssetIcon-DoCqXzAv.js} +1 -1
  2. package/dist/assets/Addons-CrSVEbe3.js +4 -0
  3. package/dist/assets/{AdminPage-CgbWYJ_a.js → AdminPage-KGO_m_yt.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-Cx5lBMEy.js → AdminSectionedPage-BiMhPKOP.js} +1 -1
  5. package/dist/assets/AiProfiles-D8mKo1K9.js +3 -0
  6. package/dist/assets/{BrokerForm-vhYWxL3G.js → BrokerForm-yx58WRgh.js} +1 -1
  7. package/dist/assets/{Build-DU8TYYdP.js → Build-BArewEF3.js} +5 -5
  8. package/dist/assets/{Calendars-nXT3Wrbf.js → Calendars-BdN8ZQmv.js} +1 -1
  9. package/dist/assets/{Cluster-i581brrb.js → Cluster-Bn5YZafT.js} +1 -1
  10. package/dist/assets/{ClusterStepModel-COT7-UPr.js → ClusterStepModel-DPmlzTfm.js} +1 -1
  11. package/dist/assets/CompositionEditor-BhL25d6e.js +1 -0
  12. package/dist/assets/CompositionEditorPage-BwqVkeY-.js +1 -0
  13. package/dist/assets/Data-BvY-zVHv.js +2 -0
  14. package/dist/assets/DeviceDetail-g2esa6u-.js +2 -0
  15. package/dist/assets/{DeviceDoActionFields-B1mTzp5D.js → DeviceDoActionFields-C6f9gioM.js} +1 -1
  16. package/dist/assets/Devices-CtivG8K9.js +1 -0
  17. package/dist/assets/{EmbedPlayerPage-BPwqAqDS.js → EmbedPlayerPage-BD-Z7zz-.js} +1 -1
  18. package/dist/assets/Identity-BQNP0wku.js +1 -0
  19. package/dist/assets/IntegrationDetail-CzEG-I4B.js +1 -0
  20. package/dist/assets/IntegrationHub-tqxee2Rm.js +1 -0
  21. package/dist/assets/Integrations-C7Ptcn3c.js +1 -0
  22. package/dist/assets/Integrations-GZm_SrQK.js +1 -0
  23. package/dist/assets/Library-ToUHY4O3.js +1 -0
  24. package/dist/assets/Locations-CPFCvUKd.js +3 -0
  25. package/dist/assets/{Logs-DQzkH4DL.js → Logs-Ds6SPC6o.js} +1 -1
  26. package/dist/assets/{MaskShapeCanvas-B01TLLz0.js → MaskShapeCanvas-BoY32Qvt.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-Ccp-7wRO.js → MotionZonesSettings-DBW4jTEr.js} +1 -1
  28. package/dist/assets/{MyAccess-d8Soqp8x.js → MyAccess-2mSUBp14.js} +1 -1
  29. package/dist/assets/{Network-DUXIj2Zk.js → Network-BddKO6B1.js} +1 -1
  30. package/dist/assets/{NodeAddonsSettingsPanel-BfK00QUN.js → NodeAddonsSettingsPanel-CIISQuIL.js} +1 -1
  31. package/dist/assets/Notifications-DWJcnXvV.js +1 -0
  32. package/dist/assets/{PrivacyMaskSettings-BnmGNc7h.js → PrivacyMaskSettings-z8P3R0fA.js} +1 -1
  33. package/dist/assets/Recordings-g1Jxg_Lr.js +1 -0
  34. package/dist/assets/{ScanNetworkModal-BuYymusi.js → ScanNetworkModal-D7N2aC7y.js} +1 -1
  35. package/dist/assets/{SceneMonitorEditor-COIi86yu.js → SceneMonitorEditor-CyjEekEM.js} +1 -1
  36. package/dist/assets/SessionsList-bmTxxIOE.js +2 -0
  37. package/dist/assets/{Showroom-B-HvuRyq.js → Showroom-PlFtcQrL.js} +1 -1
  38. package/dist/assets/{System-D1S9FZIN.js → System-DxszqVYV.js} +1 -1
  39. package/dist/assets/{Terminal-VExSxhFn.js → Terminal-BMG2w8DZ.js} +3 -3
  40. package/dist/assets/{Viewer-CNtlq-6t.js → Viewer-CRLD_tt7.js} +1 -1
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-B5lRPMSE.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-GapjKGVe.js} +1 -1
  42. package/dist/assets/{addon-icons-context-O3QiZWCa.js → addon-icons-context-BrgGsfoE.js} +1 -1
  43. package/dist/assets/{archive-NnMWQRLb.js → archive-Dx-auPAN.js} +1 -1
  44. package/dist/assets/{authed-media-B64j5Vsu.js → authed-media-MhMmWNH3.js} +1 -1
  45. package/dist/assets/{bell-off-DR6rLD11.js → bell-off-BQQTURVF.js} +1 -1
  46. package/dist/assets/{board-model-CUEDqTvL.js → board-model-Bdetmchn.js} +1 -1
  47. package/dist/assets/{boxes-B64NRkVe.js → boxes-BIK98bHo.js} +1 -1
  48. package/dist/assets/circle-slash-DKE4hxbW.js +1 -0
  49. package/dist/assets/client-Cy6wyTLQ.js +358 -0
  50. package/dist/assets/{cloud-upload-Ck1AcqSa.js → cloud-upload-FvK6xW2I.js} +1 -1
  51. package/dist/assets/crop-7vsE3Qcd.js +1 -0
  52. package/dist/assets/{device-integration-icon-CdWFmoUD.js → device-integration-icon-ClmWzwM_.js} +1 -1
  53. package/dist/assets/device-picker-model-DVvq9nYp.js +1 -0
  54. package/dist/assets/dist-BPMeH1J4.js +358 -0
  55. package/dist/assets/dist-CEnfZ10I.js +1 -0
  56. package/dist/assets/{eraser-CHm7ildU.js → eraser-CUAqtnBD.js} +1 -1
  57. package/dist/assets/{hard-drive-download-DVmQAuw3.js → hard-drive-download-XGtks2vE.js} +1 -1
  58. package/dist/assets/{history-2q2gbNuR.js → history-DqvhlzWX.js} +1 -1
  59. package/dist/assets/{hostInit-BJE3f_CH.js → hostInit-DzBGXsvZ.js} +1 -1
  60. package/dist/assets/i18n-B1bxeya5.js +1 -0
  61. package/dist/assets/{icons-DQaWDMUW.js → icons-DNRi-jSy.js} +1 -1
  62. package/dist/assets/index-CN7xsFJi.css +2 -0
  63. package/dist/assets/index-yoPG03d0.js +4 -0
  64. package/dist/assets/{key-N9xPL69Y.js → key-bw9xhRgT.js} +1 -1
  65. package/dist/assets/{key-round-DetnHyGS.js → key-round-BngMS2dZ.js} +1 -1
  66. package/dist/assets/{layers-DdcQNtFW.js → layers-CIl8QXpN.js} +1 -1
  67. package/dist/assets/{linked-devices-model-Ca0JeX-b.js → linked-devices-model-CclOXMLj.js} +1 -1
  68. package/dist/assets/{list-ordered-CG0tknH1.js → list-ordered-_52_xrQ7.js} +1 -1
  69. package/dist/assets/location-owned-usage-5eb6nny3.js +1 -0
  70. package/dist/assets/{log-in-eXylJY9j.js → log-in-DH9Lu6bJ.js} +1 -1
  71. package/dist/assets/{memory-stick-DASwwt0F.js → memory-stick-CzaP6KiN.js} +1 -1
  72. package/dist/assets/{message-square-plus-DqkHZSG8.js → message-square-plus-vMywres_.js} +1 -1
  73. package/dist/assets/{mf-entry-bootstrap-0-3bcba670.js → mf-entry-bootstrap-0-54468006.js} +2 -2
  74. package/dist/assets/{mic-off-Dn3D8U5T.js → mic-off-Da09u2hl.js} +1 -1
  75. package/dist/assets/{monitor-off-BFFE28-j.js → monitor-off-jOOWdiSg.js} +1 -1
  76. package/dist/assets/{monitor-smartphone-Df6JhoUF.js → monitor-smartphone-D_W4zyWO.js} +1 -1
  77. package/dist/assets/mount-DVvq9nYp.js +1 -0
  78. package/dist/assets/notification-schedule-field-LytDFkpQ.js +1 -0
  79. package/dist/assets/{player-overlays-CikRdqm6.js → player-overlays-CCZE3o8q.js} +1 -1
  80. package/dist/assets/{recycle-CeQJmMoH.js → recycle-BVcCaHVd.js} +1 -1
  81. package/dist/assets/remoteEntry-BOaeaEWk.js +1 -0
  82. package/dist/assets/{scan-eye-uX_isL7a.js → scan-eye-CHwWv39K.js} +1 -1
  83. package/dist/assets/{scissors-Bi6HP2Jp.js → scissors-BrUBwnKn.js} +1 -1
  84. package/dist/assets/{search-x-CScyd-pU.js → search-x-BcR2pidC.js} +1 -1
  85. package/dist/assets/{send-D2QbbJQk.js → send-8R5TbxHN.js} +1 -1
  86. package/dist/assets/{settings-2-CkjM7VHr.js → settings-2-C4PaSGfb.js} +1 -1
  87. package/dist/assets/{speaker-C3Z3o0NO.js → speaker-CBRM7GNH.js} +1 -1
  88. package/dist/assets/src-Cw4W7OtK.js +67 -0
  89. package/dist/assets/{timer-reset-C_TvCMnb.js → timer-reset-DlfKkTg_.js} +1 -1
  90. package/dist/assets/{ungroup-IELE1M3H.js → ungroup-BzlNECzG.js} +1 -1
  91. package/dist/assets/{unlink-CLHtJAsY.js → unlink-HIuzqEig.js} +1 -1
  92. package/dist/assets/{usb-DncvObAi.js → usb-DqboQtO8.js} +1 -1
  93. package/dist/assets/{use-scenes-feed-BgX1JX4l.js → use-scenes-feed-Cnl4Is6T.js} +1 -1
  94. package/dist/assets/{use-stationary-objects-BzSycd9M.js → use-stationary-objects-DmFWTPK0.js} +1 -1
  95. package/dist/assets/useEventInvalidation-DVvq9nYp.js +1 -0
  96. package/dist/assets/{useNodeUrlSelection-D3zWAXku.js → useNodeUrlSelection-CSh6gqLc.js} +1 -1
  97. package/dist/assets/user-round-C4K7vDWN.js +1 -0
  98. package/dist/assets/{user-x-B-NhZXl-.js → user-x-ciro8k7Z.js} +1 -1
  99. package/dist/assets/{video-IXUGebu2.js → video-BJUj4GaK.js} +1 -1
  100. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-5Br3X_S3.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CwjeQPZx.js} +2 -2
  101. package/dist/index.html +11 -11
  102. package/dist/server/addon.js +252 -45
  103. package/package.json +1 -1
  104. package/dist/assets/Addons-BNdKgh4A.js +0 -4
  105. package/dist/assets/AiProfiles-Bcw_Zupz.js +0 -3
  106. package/dist/assets/CompositionEditor-ChpgaVIC.js +0 -1
  107. package/dist/assets/CompositionEditorPage-ChGD20-A.js +0 -1
  108. package/dist/assets/Data-NVQyqefj.js +0 -2
  109. package/dist/assets/DeviceDetail-UQPY3O77.js +0 -2
  110. package/dist/assets/Devices-DNkljEPT.js +0 -1
  111. package/dist/assets/Identity-SFG32MYD.js +0 -1
  112. package/dist/assets/IntegrationDetail-DOpZe3Ca.js +0 -1
  113. package/dist/assets/IntegrationHub-DbxSPB_Z.js +0 -1
  114. package/dist/assets/Integrations--ssC4t1F.js +0 -1
  115. package/dist/assets/Integrations-6eDOiK1G.js +0 -1
  116. package/dist/assets/Library-Bi_LuV1_.js +0 -1
  117. package/dist/assets/Locations-Cg0m1b4l.js +0 -3
  118. package/dist/assets/Notifications-M4WZNbHV.js +0 -1
  119. package/dist/assets/Recordings-DalG2LLq.js +0 -1
  120. package/dist/assets/SessionsList-CoUCGhgk.js +0 -2
  121. package/dist/assets/circle-slash-CEYz4tuU.js +0 -1
  122. package/dist/assets/client-Ca-96r9I.js +0 -358
  123. package/dist/assets/crop-C-IooyeF.js +0 -1
  124. package/dist/assets/device-picker-model-Dep-E57-.js +0 -1
  125. package/dist/assets/dist-BSOkO07t.js +0 -1
  126. package/dist/assets/dist-vJSNSRqs.js +0 -358
  127. package/dist/assets/i18n-ATfMbes1.js +0 -1
  128. package/dist/assets/index-CIQcOfrF.js +0 -4
  129. package/dist/assets/index-M0Q7O5pF.css +0 -2
  130. package/dist/assets/location-owned-usage-CPVIHMbS.js +0 -1
  131. package/dist/assets/mount-Dep-E57-.js +0 -1
  132. package/dist/assets/notification-schedule-field-DX8l1Z0c.js +0 -1
  133. package/dist/assets/remoteEntry-B_6E82lR.js +0 -1
  134. package/dist/assets/src-Bt0KiIin.js +0 -67
  135. package/dist/assets/useEventInvalidation-Dep-E57-.js +0 -1
  136. package/dist/assets/user-round-BCHxFTod.js +0 -1
@@ -1,3 +0,0 @@
1
- import{$ as e,B as t,G as n,J as r,L as i,S as a,a as o,b as s,q as c,t as l,x as u}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{$r as d,Ai as f,D as p,Dr as m,Ei as h,Fn as g,G as _,It as v,On as y,Q as b,Wr as x,Xr as S,Yt as C,Zt as w,dn as T,dt as ee,fn as E,jr as D,kn as te,or as O,ot as k}from"./player-overlays-CikRdqm6.js";import{Wn as A}from"./client-Ca-96r9I.js";import{t as j}from"./message-square-plus-DqkHZSG8.js";import{t as M}from"./send-D2QbbJQk.js";import{B as ne,Bn as N,Cn as re,H as P,K as F,Kt as I,Ln as L,Ql as R,Un as z,Wt as B,cr as V,qt as H,ru as U,sn as W,va as G}from"./src-Bt0KiIin.js";import{t as K}from"./i18n-ATfMbes1.js";import{t as q}from"./useTranslation-D3Is_4B6.js";import"./mount-Dep-E57-.js";import{w as ie}from"./index-CIQcOfrF.js";import{t as ae}from"./AdminSectionedPage-Cx5lBMEy.js";import{t as J}from"./AdminPage-CgbWYJ_a.js";e();var oe=[`llm`,`listProfiles`],se=[`llm`,`listProfileKinds`],ce=[`llm`,`getDefaults`],Y=[`llm`,`listRuntimeNodes`],le=[`llm`,`listModelCatalog`],ue=[`llm`,`getUsage`],de=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],fe=new Map(Object.entries({openai:d,anthropic:d,google:d,"openai-compatible":y,"managed-local":S,"apple-foundation":S}));function pe(e){return fe.get(e)??null}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Q(e){return e===!0}function me(e){return{model:e.model,baseUrl:e.baseUrl,apiKey:e.apiKey,supportsVision:e.supportsVision,temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled,contextSize:e.runtime?.contextSize,gpuLayers:e.runtime?.gpuLayers,threads:e.runtime?.threads,parallel:e.runtime?.parallel,idleStopMinutes:e.runtime?.idleStopMinutes,batchSize:e.runtime?.batchSize,ubatchSize:e.runtime?.ubatchSize,flashAttention:e.runtime?.flashAttention,mlock:e.runtime?.mlock,noMmap:e.runtime?.noMmap,cacheTypeK:e.runtime?.cacheTypeK,cacheTypeV:e.runtime?.cacheTypeV,extraArgs:ve(e.runtime?.extraArgs??[])}}var he=[`f32`,`f16`,`q8_0`,`q5_1`,`q5_0`,`q4_1`,`q4_0`];function ge(e){return typeof e==`string`&&he.includes(e)?e:void 0}function _e(e){let t=[],n=``,r=null;for(let i of e){if(r!==null){i===r?r=null:n+=i;continue}if(i===`"`||i===`'`){r=i;continue}if(/\s/.test(i)){n!==``&&t.push(n),n=``;continue}n+=i}return n!==``&&t.push(n),t}function ve(e){return e.map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)}var ye=[`--jinja`,`--cont-batching`];function be(e,t,n){let r=Z(e.threads),i=Z(e.batchSize),a=Z(e.ubatchSize),o=ge(e.cacheTypeK),s=ge(e.cacheTypeV);return{nodeId:t,engine:`llama-cpp`,model:n,extraArgs:[..._e(X(e.extraArgs)??``)],contextSize:Z(e.contextSize)??4096,gpuLayers:Z(e.gpuLayers)??0,...r===void 0?{}:{threads:r},parallel:Z(e.parallel)??1,...i===void 0?{}:{batchSize:i},...a===void 0?{}:{ubatchSize:a},flashAttention:Q(e.flashAttention),mlock:Q(e.mlock),noMmap:Q(e.noMmap),...o===void 0?{}:{cacheTypeK:o},...s===void 0?{}:{cacheTypeV:s},autoStart:Q(e.autoStart),idleStopMinutes:Z(e.idleStopMinutes)??30}}function xe(e,t,n,r,i){let a={id:n?.id??crypto.randomUUID(),name:t,kind:e,addonId:`ai`,enabled:n?.enabled??!0,model:X(r.model)??n?.model??``,supportsVision:i?.supportsVision??Q(r.supportsVision),timeoutMs:Z(r.timeoutMs)??A.totalMs,connectTimeoutMs:Z(r.connectTimeoutMs)??A.connectMs,firstTokenTimeoutMs:Z(r.firstTokenTimeoutMs)??A.firstTokenMs,idleTimeoutMs:Z(r.idleTimeoutMs)??A.idleMs,retry:{enabled:Q(r.retryEnabled),maxAttempts:Z(r.retryMaxAttempts)??1},toolsEnabled:Q(r.toolsEnabled)},o=X(r.baseUrl),s=X(r.apiKey),c=Z(r.temperature),l=Z(r.topP),u=Z(r.topK),d=Z(r.maxTokens),f=Z(r.contextLength),p=X(r.systemPrompt);return{...a,...o===void 0?{}:{baseUrl:o},...s===void 0?{}:{apiKey:s},...c===void 0?{}:{temperature:c},...l===void 0?{}:{topP:l},...u===void 0?{}:{topK:u},...d===void 0?{}:{maxTokens:d},...f===void 0?{}:{contextLength:f},...p===void 0?{}:{systemPrompt:p},...i===void 0?{}:{model:i.modelId,runtime:be(r,i.nodeId,i.model)}}}function Se(e){let t=new Map;for(let n of e){let e=t.get(n.addonId)??[];e.push(n),t.set(n.addonId,e)}return[...t.entries()].map(([e,t])=>({addonId:e,kinds:t}))}var Ce=`apple-system`;function we(e,t,n,r){return{...xe(`apple-foundation`,e,t,n),model:Ce,supportsVision:!1,appleFoundation:{nodeId:r}}}var Te={deviceNotEligible:{key:`ai.appleNotEligible`,tone:`default`},appleIntelligenceNotEnabled:{key:`ai.appleIntelligenceOff`,tone:`warning`},modelNotReady:{key:`ai.appleModelNotReady`,tone:`warning`},osTooOld:{key:`ai.appleOsTooOld`,tone:`default`},helperMissing:{key:`ai.appleHelperMissing`,tone:`danger`},helperCrashed:{key:`ai.appleHelperCrashed`,tone:`danger`}};function Ee(e){let t=t=>({nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleUnknown`,labelDefault:K.t(`ai.appleUnknown`),detail:t,tone:`default`});if(!e.reachable)return t(e.error??null);let n=e.apple;if(n===void 0)return t(null);switch(n.state){case`available`:return{nodeId:e.nodeId,selectable:!0,labelKey:`ai.appleAvailable`,labelDefault:K.t(`ai.appleAvailable`),detail:K.t(n.imageInput?`helpers.aiPage.appleDetailImages`:`helpers.aiPage.appleDetailText`,{version:n.osVersion}),tone:`success`};case`unavailable`:{let t=Te[n.reason];return{nodeId:e.nodeId,selectable:!1,labelKey:t.key,labelDefault:K.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:K.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var De=2e3;function $(e){return K.t(`system.aiModelPicker.sizeGb`,{value:(e/1e9).toFixed(2)})}function Oe(e){return e===null?``:e.model.kind===`catalog`?`catalog:${e.model.catalogId}`:e.model.kind===`path`?`node:${e.modelId}`:`custom`}function ke({nodeId:e,value:t,onChange:i}){let{t:s}=q(),c=k(),[d,f]=r(``),[p,m]=r(null),[h,g]=r(!1),_=o({queryKey:le,queryFn:()=>c.trpcClient.llm.listModelCatalog.query({})}),v=o({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>c.trpcClient.llm.listNodeModels.query({nodeId:e})}),y=l({mutationFn:e=>c.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{m(e),g(!1),e.ok&&i({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),b=l({mutationFn:t=>c.trpcClient.llm.installModel.mutate({nodeId:e,model:t}),onSuccess:()=>{g(!0),v.refetch()}}),S=o({queryKey:Y,enabled:b.isPending,refetchInterval:b.isPending?De:!1,queryFn:()=>c.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,C=n(()=>{let t=(_.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(v.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(t=>({value:`node:${t.file}`,label:s(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:t.file,size:$(t.sizeBytes),node:e})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:s(`ai.selectModel`,`Select a model…`)},...t,...n,...r]},[_.data,v.data,p,e,s]),w=e=>{if(e===``){i(null);return}if(e===`custom`){if(p?.ok!==!0)return;i({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=_.data?.find(e=>e.id===t);i({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=v.data?.find(e=>e.file===t);n?.path!==void 0&&i({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},T=e=>{d.trim()!==``&&y.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return a(`div`,{className:`space-y-2`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-model`,children:s(`ai.model`,`Model`)}),u(R,{id:`ai-model`,value:Oe(t),options:C,onChange:e=>w(e.target.value)})]}),a(`div`,{className:`rounded-md border border-border bg-surface-subtle px-3 py-2.5`,children:[u(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:s(`ai.hfTitle`,`Add a model from Hugging Face`)}),u(`p`,{className:`mb-2 text-[10px] leading-relaxed text-foreground-subtle`,children:s(`ai.hfHint`,`Paste a GGUF file URL, or type org/repo — add :QUANT (e.g. unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M) when the repo publishes more than one quantization.`)}),a(`div`,{className:`flex gap-2`,children:[u(U,{value:d,onChange:e=>f(e.target.value),placeholder:s(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),T())}}),a(z,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||y.isPending,onClick:()=>T(),children:[y.isPending?u(O,{className:`h-3.5 w-3.5 animate-spin`}):u(E,{className:`h-3.5 w-3.5`}),s(`ai.hfCheck`,`Check`)]})]}),y.isError&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:y.error instanceof Error?y.error.message:s(`common.error`,`Error`)}),p?.ok===!1&&a(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-2.5 py-2`,children:[u(`p`,{className:`text-[11px] text-danger`,children:p.message}),p.candidates!==void 0&&p.candidates.length>0&&u(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:p.candidates.map(e=>u(`button`,{type:`button`,className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:border-primary/50`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),y.mutate({ref:t})},children:e},e))}),p.requiredBytes!==void 0&&u(z,{size:`sm`,variant:`secondary`,type:`button`,className:`mt-2`,onClick:()=>T(p.requiredBytes),children:s(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]}),p?.ok===!0&&a(`div`,{className:`mt-2 rounded-md border border-border bg-surface px-2.5 py-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),u(V,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),u(V,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),a(`div`,{className:`mt-2 flex items-center gap-2`,children:[a(z,{size:`sm`,type:`button`,disabled:b.isPending||h,onClick:()=>b.mutate(p.model),children:[b.isPending?u(O,{className:`h-3.5 w-3.5 animate-spin`}):u(x,{className:`h-3.5 w-3.5`}),h?s(`ai.hfInstalled`,`Downloaded`):s(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),S!==void 0&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:S.phase===`verifying`?s(`ai.hfVerifying`,`verifying {{file}}…`,{file:S.file}):s(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:S.file,index:S.fileIndex,count:S.fileCount,done:$(S.downloadedBytes),total:S.totalBytes===void 0?``:` / ${$(S.totalBytes)}`})})]}),b.isError&&u(`p`,{className:`mt-1.5 text-[11px] text-danger`,children:b.error instanceof Error?b.error.message:s(`common.error`,`Error`)})]})]})]})}function Ae({value:e,onChange:t}){let{t:n}=q(),r=k(),i=o({queryKey:Y,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})});return a(`div`,{children:[u(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:n(`ai.appleNode`,`Mac that runs it`)}),i.isPending&&a(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(O,{className:`h-3.5 w-3.5 animate-spin`}),n(`ai.appleAsking`,`Asking the nodes…`)]}),i.isError&&u(`p`,{className:`text-[11px] text-danger`,children:i.error instanceof Error?i.error.message:n(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),i.isSuccess&&i.data.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),i.isSuccess&&i.data.length>0&&u(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:i.data.map(r=>{let i=Ee(r),o=i.nodeId===e;return a(`button`,{type:`button`,role:`radio`,"aria-checked":o,disabled:!i.selectable&&!o,onClick:()=>t(i.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${o?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block font-medium text-foreground`,children:i.nodeId}),i.detail!==null&&u(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:i.detail})]}),u(V,{variant:i.tone,children:n(i.labelKey,i.labelDefault)})]},i.nodeId)})}),u(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:n(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}e();function je({kind:e,className:t}){let n=pe(e.kind);return n===null?u(`span`,{className:t,children:e.icon}):u(n,{className:t})}function Me({kinds:e,onPick:t,onCancel:r}){let{t:i}=q(),o=n(()=>Se(e),[e]);return u(P,{open:!0,onClose:r,title:i(`ai.chooseKind`,`Choose a profile type`),width:`lg`,testId:`ai-kind-picker`,children:a(`div`,{className:`space-y-4`,children:[o.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:i(`ai.noKinds`,`No AI provider is installed.`)}),o.map(e=>a(`div`,{children:[u(`div`,{className:`mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:e.addonId}),u(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.kinds.map(n=>a(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs transition-colors hover:border-primary/50 hover:bg-surface-hover`,children:[u(je,{kind:n,className:`h-5 w-5 text-foreground-subtle`}),u(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})})}function Ne({kind:e,existing:t,onSave:i,onCancel:o,saving:c,error:l}){let{t:d}=q(),f=e.kind===`managed-local`,p=e.kind===`apple-foundation`,[m,h]=r(t?.appleFoundation?.nodeId??null),[g,_]=r(t?.name??e.label),[v,y]=r(()=>t===null?{}:me(t)),[b,x]=r(t?.runtime?.nodeId??`hub`),[S,C]=r(()=>t?.runtime===void 0?null:{model:t.runtime.model,modelId:t.model,supportsVision:t.supportsVision}),w=n(()=>_e(X(v.extraArgs)??``),[v.extraArgs]),T=()=>{if(p){if(m===null)return;i(we(g,t,v,m));return}if(!f){i(xe(e.kind,g,t,v));return}S!==null&&i(xe(e.kind,g,t,v,{nodeId:b,model:S.model,modelId:S.modelId,supportsVision:S.supportsVision}))},ee=c||g.trim()===``||f&&S===null||p&&m===null;return u(P,{open:!0,onClose:o,title:t===null?d(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):d(`ai.editProfile`,`Edit {{name}}`,{name:t.name}),error:l,width:`lg`,testId:`ai-profile-editor`,footer:a(s,{children:[f&&S===null&&u(V,{variant:`warning`,children:d(`ai.pickModelFirst`,`pick a model`)}),p&&m===null&&u(V,{variant:`warning`,children:d(`ai.pickAppleNodeFirst`,`pick a Mac`)}),a(z,{size:`sm`,type:`button`,disabled:ee,onClick:T,children:[c&&u(O,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`ai.createProfile`,`Create profile`):d(`ai.saveChanges`,`Save changes`)]})]}),children:a(`div`,{className:`space-y-3`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-profile-name`,children:d(`ai.name`,`Name`)}),u(U,{id:`ai-profile-name`,value:g,onChange:e=>_(e.target.value),placeholder:e.label})]}),f&&a(s,{children:[u(F,{selectedNodeId:b,onSelect:x,label:d(`ai.runtimeNode`,`Runtime node`),alwaysShow:!0}),u(ke,{nodeId:b,value:S,onChange:C}),a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-extra-args`,children:d(`ai.extraArgs`,`Additional llama-server arguments`)}),u(U,{id:`ai-extra-args`,value:X(v.extraArgs)??``,onChange:e=>y({...v,extraArgs:e.target.value}),placeholder:ye.join(` `)}),w.length>0&&u(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:w.map((e,t)=>u(V,{variant:`default`,children:e},`${e}-${String(t)}`))}),u(`p`,{className:`mt-1 text-[10px] leading-relaxed text-foreground-subtle`,children:d(`ai.extraArgsHint`,`Flags this form does not already own. Vision models generally need --jinja; some language-only models do not like it. Context size, GPU layers, parallel slots, flash attention and the KV-cache types are set in the fields below — repeating one here is rejected at start.`)})]})]}),p&&u(Ae,{value:m,onChange:h}),u(re,{schema:e.configSchema,values:v,onChange:y}),t!==null&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)})]})})}e();function Pe(e){return[{key:`name`,header:e.t(`ai.colProfile`,`Profile`),render:t=>{let n=e.kindByName.get(t.kind);return a(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:n?.label??t.kind,children:n===void 0?u(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):u(je,{kind:n,className:`h-4 w-4 text-foreground-subtle`})}),a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block truncate text-sm font-medium text-foreground`,children:t.name}),e.testResult?.id===t.id&&u(`span`,{className:`block truncate text-[10px] ${e.testResult.ok?`text-success`:`text-danger`}`,children:e.testResult.text})]})]})}},{key:`kind`,header:e.t(`ai.colKind`,`Kind`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByName.get(t.kind)?.label??t.kind})},{key:`model`,header:e.t(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.model})},{key:`vision`,header:e.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:t=>t.supportsVision?u(V,{variant:`info`,style:`outline`,children:e.t(`ai.vision`,`vision`)}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})},{key:`node`,header:e.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>e.runtime===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(V,{variant:`default`,children:e.runtime.nodeId})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>u(W,{checked:t.enabled,onCheckedChange:()=>e.onToggle(t),"aria-label":K.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:t.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>a(`span`,{className:`flex items-center justify-end gap-1`,children:[u(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?u(O,{className:`h-3.5 w-3.5 animate-spin`}):u(M,{className:`h-3.5 w-3.5`})}),u(z,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),title:e.t(`common.edit`,`Edit`),children:u(g,{className:`h-3.5 w-3.5`})}),u(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:e.t(`common.delete`,`Delete`),children:u(v,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Fe(){let{t:e}=q(),s=k(),{state:c,openNew:d,openEdit:f,close:p}=ne(),[m,h]=r(null),[g,_]=r(null),[v,y]=r(null),b=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),x=o({queryKey:se,queryFn:async()=>(await s.trpcClient.llm.listProfileKinds.query({})).map(e=>({...e,configSchema:e.configSchema}))}),S=()=>{b.refetch()},C=i(()=>{h(null),y(null),p()},[p]);t(()=>{c.mode===`closed`&&h(null)},[c.mode]);let T=l({mutationFn:e=>s.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{C(),S()},onError:t=>y(t instanceof Error?t.message:e(`ai.saveFailed`,`Save failed`))}),ee=l({mutationFn:e=>s.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:S}),E=l({mutationFn:e=>s.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>_({id:t.id,ok:e.ok,text:e.ok?K.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),D=b.data??[],A=n(()=>x.data??[],[x.data]),j=n(()=>{let e=new Map;for(let t of A)e.set(t.kind,t);return e},[A]),M=c.mode===`edit`?D.find(e=>e.id===c.id)??null:null,re=M===null?null:j.get(M.kind)??null,P=c.mode===`new`&&m===null,F=c.mode===`new`?m:re,L=c.mode===`edit`?M:null,R=F!==null&&(c.mode===`new`||L!==null);return a(J,{embedded:!0,icon:w,title:e(`ai.profilesTitle`,`AI profiles`),subtitle:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),children:[u(`div`,{className:`flex justify-end`,children:a(z,{size:`sm`,type:`button`,onClick:()=>{y(null),h(null),d()},children:[u(te,{className:`h-3.5 w-3.5`}),e(`ai.addProfile`,`Add profile`)]})}),b.isError&&u(N,{title:e(`ai.loadFailed`,`Failed to load profiles`),message:b.error instanceof Error?b.error.message:e(`common.error`,`Error`),onRetry:()=>void b.refetch()}),u(Ie,{profiles:D}),b.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(O,{className:`h-6 w-6 animate-spin text-primary`})}),!b.isLoading&&D.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}),D.length>0&&u(B,{headingId:`ai-profiles-list`,title:e(`ai.profilesList`,`Profiles`),children:u(I,{columns:Pe({kindByName:j,testResult:g,testingId:E.isPending?E.variables?.id??null:null,t:e,onToggle:e=>T.mutate({...e,enabled:!e.enabled,apiKey:`__redacted__`}),onTest:e=>E.mutate(e),onEdit:e=>{j.has(e.kind)&&(y(null),h(null),f(e.id))},onDelete:e=>ee.mutate(e)}),rows:D,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:`max-h-[60vh]`})}),P&&u(Me,{kinds:A,onCancel:C,onPick:e=>{y(null),h(e)}}),R&&F!==null&&u(Ne,{kind:F,existing:L,saving:T.isPending,error:v,onSave:e=>T.mutate(e),onCancel:C})]})}function Ie({profiles:e}){let{t}=q(),n=k(),r=o({queryKey:ce,queryFn:()=>n.trpcClient.llm.getDefaults.query({})}),i=l({mutationFn:e=>n.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{r.refetch()}}),s=e=>(r.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,c=e=>e===`vision`?t(`ai.defaultVision`,`Default vision profile`):t(`ai.defaultText`,`Default text profile`);return u(B,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:u(`div`,{className:`${p} grid gap-4 sm:grid-cols-2`,children:de.map(({purpose:n,visionOnly:r})=>{let o=r?e.filter(e=>e.supportsVision):e,l=s(n),d=e.find(e=>e.id===l);return a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`llm-default-${n}`,children:c(n)}),u(R,{id:`llm-default-${n}`,"aria-label":c(n),className:`h-7 text-xs`,value:l,onChange:e=>i.mutate({purpose:n,profileId:e.target.value===``?null:e.target.value}),options:[{value:``,label:t(`ai.none`,`None`)},...l!==``&&!o.some(e=>e.id===l)?[{value:l,label:d?.name??l}]:[],...o.map(e=>({value:e.id,label:`${e.name} · ${e.model}`}))]}),l!==``&&d===void 0&&u(`p`,{className:`mt-1 text-[10px] text-danger`,children:t(`ai.defaultMissing`,`This default names a profile that no longer exists.`)}),d!==void 0&&!d.enabled&&u(`p`,{className:`mt-1 text-[10px] text-warning`,children:t(`ai.defaultDisabled`,`This default profile is disabled — callers resolve to no profile.`)}),i.error!=null&&u(`p`,{className:`mt-1 text-[10px] text-danger`,children:String(i.error)})]},n)})})})}e();var Le=5e3;function Re(e){return K.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ze(){let{t:e}=q(),t=k(),r=o({queryKey:Y,refetchInterval:Le,queryFn:()=>t.trpcClient.llm.listRuntimeNodes.query({})}),i=n(()=>[{key:`node`,header:e(`ai.colNode`,`Node`),render:e=>u(`span`,{className:`text-sm font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:e(`ai.colState`,`State`),nowrap:!0,render:t=>a(`span`,{className:`flex items-center gap-1.5`,children:[u(V,{variant:t.reachable?`success`:`danger`,children:t.reachable?t.status?.state??e(`ai.ready`,`ready`):e(`ai.unreachable`,`unreachable`)}),t.status?.downloadProgress!==void 0&&u(V,{variant:`info`,children:`${String(Math.round(t.status.downloadProgress*100))}%`})]})},{key:`model`,header:e(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:e(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.disk===void 0?`—`:Re(e.disk.modelsBytes)})},{key:`apple`,header:e(`ai.colApple`,`Apple on-device`),render:t=>{let n=Ee(t);return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[u(V,{variant:n.tone,children:e(n.labelKey,n.labelDefault)}),n.detail!==null&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n.detail})]})}},{key:`error`,header:e(`ai.colError`,`Error`),render:e=>e.error===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(`span`,{className:`text-[11px] text-danger`,children:e.error})}],[e]),s=r.data??[];return a(J,{embedded:!0,icon:T,title:e(`ai.runtimesTitle`,`Managed runtimes`),subtitle:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),children:[r.isError&&u(N,{title:e(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:r.error instanceof Error?r.error.message:e(`common.error`,`Error`),onRetry:()=>void r.refetch()}),s.length===0?u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):u(B,{headingId:`ai-runtimes-list`,title:e(`ai.runtimesList`,`Nodes`),children:u(I,{columns:i,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:H})})]})}var Be=b(`/addon/ai/test-chat`),Ve=b(`/addon/ai/test-chat/chats`),He=6e5;function Ue(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),He)}function We(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e){if(!We(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Ke=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function qe(e){let t;try{t=JSON.parse(e)}catch{return null}if(!We(t))return null;switch(t.kind){case`status`:{let e=Ke.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Ge(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:K.t(`helpers.aiTestChat.providerError`)};default:return null}}async function*Je(e){let t=e.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
- `);for(;a>=0;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length>0){let t=qe(e);t!==null&&(yield t)}a=r.indexOf(`
3
- `)}}let e=r.trim();if(e.length>0){let t=qe(e);t!==null&&(yield t)}}finally{t.releaseLock()}}function Ye(e){return e.filter(e=>e.failed!==!0&&e.content.length>0).map(e=>({role:e.role,content:e.content}))}function Xe(e){return e.thumbnailBase64===void 0||e.thumbnailBase64.length===0?null:`data:${e.mimeType};base64,${e.thumbnailBase64}`}function Ze(e){return e.messages.map((t,n)=>{let r=t.mediaSent??void 0;return{id:`${e.id}-${String(n)}`,role:t.role,content:t.content,...t.attachment===void 0?{}:{attachmentRef:t.attachment,attachmentKind:t.attachment.kind},...r===void 0?{}:{attachment:r}}})}function Qe(e){let t=e.sizeBytes<1024*1024?`${(e.sizeBytes/1024).toFixed(0)} KB`:`${(e.sizeBytes/(1024*1024)).toFixed(1)} MB`,n=[e.kind===`snapshot`?`camera snapshot`:`track best-shot`,t];return e.mediaKind!==void 0&&n.push(e.mediaKind),e.capturedAt!==void 0&&n.push(new Date(e.capturedAt).toLocaleTimeString()),n.join(` · `)}function $e(e,t){switch(e){case`resolving-image`:return K.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return K.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?K.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):K.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return K.t(`helpers.aiTestChat.phaseAnswering`)}}e();var et=[`pipelineAnalytics`,`listRecentTracks`,`ai-test`],tt=360*60*1e3,nt=40,rt=160,it={phase:`connecting`,firstTokenTimeoutMs:0,text:``,mediaSent:null};function at(){let{t:e}=q(),s=k(),[l,d]=r(``),[p,m]=r(``),[g,_]=r(``),[y,b]=r([]),[x,S]=r(null),[w,T]=r(`none`),[E,te]=r(`throwaway`),[O,A]=r(null),[ne,re]=r([]),[P,F]=r(null),[I,B]=r(null),V=c(null);t(()=>()=>V.current?.abort(),[]);let H=i(async()=>{let e=await fetch(Ve,{credentials:`same-origin`});e.ok&&re((await e.json()).chats??[])},[]);t(()=>{E===`persistent`&&H()},[E,H]);let W=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),G=n(()=>(W.data??[]).filter(e=>e.enabled),[W.data]),K=G.find(e=>e.id===l)??null,ie=I!==null,ae=i(async(t,n)=>{let r=new AbortController;V.current=r,F(null);let i=Ue(K??{});B({...it,firstTokenTimeoutMs:i??0});let a=``,o=null,s,c=null,u=null,d;try{let e=await fetch(Be,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:r.signal,body:JSON.stringify({profileId:l,messages:t,...p.trim()===``?{}:{system:p.trim()},...n===void 0?{}:{attachment:n},...i===void 0?{}:{firstTokenTimeoutMs:i},...E===`persistent`?{persist:!0,...O===null?{}:{conversationId:O}}:{}})});if(!e.ok||e.body===null){let t=await e.text().catch(()=>``);throw Error(t.length>0?t:`HTTP ${String(e.status)}`)}for await(let t of Je(e.body))switch(t.kind){case`status`:B(e=>({...e??it,phase:t.phase}));break;case`meta`:o=t.mediaSent,s=t.model,B(e=>({...e??it,firstTokenTimeoutMs:t.firstTokenTimeoutMs,mediaSent:t.mediaSent}));break;case`token`:a+=t.text,B(e=>({...e??it,text:a}));break;case`done`:u={outputTokens:t.outputTokens,latencyMs:t.latencyMs},d=t.conversationId;break;case`error`:c=`${t.code}: ${t.message}`;break}}catch(t){r.signal.aborted||F(t instanceof Error?t.message:e(`common.error`,`Error`))}finally{V.current=null,B(null)}d!==void 0&&(A(d),H());let f=r.signal.aborted&&a.length>0;c===null&&a.length===0&&!f||b(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:c??a,...c===null?{}:{failed:!0},...o===null?{}:{attachment:o},...s!==void 0&&c===null?{model:s}:{},...u===null?{}:u}])},[E,O,K,l,H,p,e]),se=i(()=>{let e=g.trim();if(e===``||l===``||ie)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...x===null?{}:{attachmentLabel:x.label,attachmentKind:x.ref.kind}},n=[...y,t];b(n),_(``);let r=x?.ref;S(null),T(`none`),ae(E===`persistent`&&O!==null?[{role:`user`,content:e}]:Ye(n),r)},[E,O,g,x,l,ae,ie,y]),ce=()=>V.current?.abort(),Y=()=>{V.current?.abort(),b([]),S(null),_(``),F(null),B(null),A(null)},le=async e=>{V.current?.abort();let t=await fetch(`${Ve}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();A(e),b(Ze(n)),B(null),F(null)};return a(J,{embedded:!0,icon:D,title:e(`ai.testTitle`,`Test chat`),subtitle:e(E===`persistent`?`ai.testSubtitlePersistent`:`ai.testSubtitle`,E===`persistent`?`Conversations are saved for you and can be reopened. Throwaway mode is still available.`:`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`),children:[u(`div`,{className:`flex justify-end`,children:a(z,{size:`sm`,variant:`secondary`,type:`button`,disabled:y.length===0&&x===null,onClick:Y,children:[u(v,{className:`h-3.5 w-3.5`}),e(`ai.clearChat`,`Clear`)]})}),a(L,{className:`space-y-3 p-4`,children:[a(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-test-profile`,children:e(`ai.profile`,`Profile`)}),u(R,{id:`ai-test-profile`,value:l,onChange:e=>d(e.target.value),options:[{value:``,label:e(`ai.selectProfile`,`Select a profile…`)},...G.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),G.length===0&&!W.isLoading&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:e(`ai.noEnabledProfiles`,`No enabled profile. Add one on the Profiles tab.`)})]}),a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-test-system`,children:e(`ai.systemPrompt`,`System prompt (optional)`)}),u(U,{id:`ai-test-system`,value:p,onChange:e=>m(e.target.value),placeholder:e(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(z,{size:`sm`,variant:E===`throwaway`?`primary`:`outline`,type:`button`,onClick:()=>{te(`throwaway`),A(null)},children:e(`ai.throwawayMode`,`Throwaway`)}),u(z,{size:`sm`,variant:E===`persistent`?`primary`:`outline`,type:`button`,onClick:()=>te(`persistent`),children:e(`ai.saveConversation`,`Save conversation`)})]}),E===`persistent`&&a(`div`,{className:`space-y-2`,children:[u(`div`,{className:`flex items-center gap-2`,children:a(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:Y,children:[u(j,{className:`h-3.5 w-3.5`}),e(`ai.newChat`,`New chat`)]})}),ne.length>0&&u(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:ne.map(e=>u(`button`,{type:`button`,onClick:()=>void le(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover ${e.id===O?`bg-primary/10`:``}`,children:u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e(`ai.streamNote`,`The answer streams as the model produces it. A cold model can take a while to load — the status line says which phase it is in.`)}),K!==null&&!K.supportsVision&&u(`p`,{className:`text-[10px] text-warning`,children:e(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]}),P!==null&&u(N,{title:e(`ai.chatFailed`,`The test call failed`),message:P}),u(ot,{turns:y,live:I}),a(L,{className:`space-y-2 p-3`,children:[x!==null&&a(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-surface px-2.5 py-1.5`,children:[x.ref.kind===`snapshot`?u(h,{className:`h-3.5 w-3.5 text-foreground-subtle`}):u(f,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-foreground`,children:x.label}),u(z,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>S(null),children:u(ee,{className:`h-3.5 w-3.5`})})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(z,{size:`sm`,variant:w===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>T(w===`snapshot`?`none`:`snapshot`),children:[u(h,{className:`h-3.5 w-3.5`}),e(`ai.attachSnapshot`,`Camera snapshot`)]}),a(z,{size:`sm`,variant:w===`track`?`primary`:`outline`,type:`button`,onClick:()=>T(w===`track`?`none`:`track`),children:[u(f,{className:`h-3.5 w-3.5`}),e(`ai.attachTrack`,`Recent track`)]})]}),w===`snapshot`&&u(lt,{onPick:t=>{S({ref:{kind:`snapshot`,deviceId:t.id},label:e(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t.name})}),T(`none`)}}),w===`track`&&u(dt,{onPick:(t,n)=>{S({ref:{kind:`track`,trackId:t.trackId,deviceId:t.deviceId},label:e(`ai.trackOf`,`{{class}} on {{name}}`,{class:t.label??t.className,name:n})}),T(`none`)}}),a(`div`,{className:`flex items-center gap-2`,children:[u(U,{value:g,onChange:e=>_(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),se())},placeholder:e(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":e(`ai.message`,`Message`)}),ie?a(z,{size:`sm`,variant:`secondary`,type:`button`,onClick:ce,children:[u(C,{className:`h-3.5 w-3.5`}),e(`ai.stop`,`Stop`)]}):a(z,{size:`sm`,type:`button`,disabled:g.trim()===``||l===``,onClick:se,children:[u(M,{className:`h-3.5 w-3.5`}),e(`ai.send`,`Send`)]})]})]})]})}function ot({turns:e,live:t}){let{t:n}=q();return e.length===0&&t===null?u(`div`,{className:`py-12 text-center text-xs text-foreground-subtle`,children:n(`ai.chatEmpty`,`Pick a profile, optionally attach a camera snapshot or a recent track, and send a message. Nothing here is saved.`)}):u(L,{children:a(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto p-3`,children:[e.map(e=>u(st,{turn:e},e.id)),t!==null&&a(`div`,{className:`space-y-1`,children:[t.mediaSent!==null&&u(ct,{attachment:t.mediaSent}),t.text.length>0&&u(st,{turn:{id:`live`,role:`assistant`,content:t.text},streaming:!0}),a(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(O,{className:`h-3.5 w-3.5 animate-spin`}),$e(t.phase,t.firstTokenTimeoutMs)]})]})]})})}function st({turn:e,streaming:t=!1}){let{t:n}=q(),r=e.role===`user`,i=e.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return u(`div`,{className:`flex ${r?`justify-end`:`justify-start`}`,children:a(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${r?`border-primary/40 bg-primary/10`:i}`,children:[a(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[e.content,t&&u(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),e.attachment!==void 0&&u(ct,{attachment:e.attachment}),e.attachmentLabel!==void 0&&a(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachmentKind===`track`?u(f,{className:`h-3 w-3`}):u(h,{className:`h-3 w-3`}),e.attachmentLabel]}),e.attachment!==void 0&&a(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachment.kind===`snapshot`?u(h,{className:`h-3 w-3`}):u(f,{className:`h-3 w-3`}),Qe(e.attachment)]}),e.model!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:n(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:e.model,value2:String(e.outputTokens??0),value3:String(e.latencyMs??0)})})]})})}function ct({attachment:e}){let{t}=q(),n=Xe(e);return n===null?null:u(`img`,{src:n,alt:t(`system.aiTestChat.sentToTheModel`,`sent to the model`),className:`mt-1 max-h-32 rounded-md border border-border object-contain`})}function lt({onPick:e}){let{t}=q(),n=G({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?u(O,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):u(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>u(ut,{device:t,onPick:e},t.id))})}function ut({device:e,onPick:t}){let{t:n}=q(),{src:r}=_(e.id,{width:rt});return a(`button`,{type:`button`,onClick:()=>t(e),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[u(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:r!==null&&u(`img`,{src:r,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),a(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!e.online&&u(V,{variant:`warning`,children:n(`common.off`)}),u(`span`,{className:`truncate text-[10px] text-foreground`,children:e.name})]})]})}function dt({onPick:e}){let{t}=q(),r=k(),i=G({isCamera:!0,projection:`slim`}),s=n(()=>(i.data??[]).map(e=>e.id),[i.data]),c=n(()=>{let e=new Map;for(let t of i.data??[])e.set(t.id,t.name);return e},[i.data]),l=o({queryKey:[...et,s.length],enabled:s.length>0,queryFn:()=>r.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...s],since:Date.now()-tt,limit:nt,projection:`slim`})});if(i.isLoading||l.isLoading)return u(O,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=l.data?.tracks??[];return d.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noTracks`,`No track in the last 6 hours.`)}):u(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(t=>a(`button`,{type:`button`,onClick:()=>e(t,c.get(t.deviceId)??String(t.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[u(f,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className}),u(`span`,{className:`shrink-0 text-foreground-subtle`,children:c.get(t.deviceId)??t.deviceId}),u(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(t.lastSeen).toLocaleTimeString()})]},t.trackId))})}e();var ft=1440*60*1e3,pt=[1,7,30,90];function mt(){let{t:e}=q(),t=k(),[i,s]=r(7),c=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(i-1)*ft},[i]),l=o({queryKey:oe,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),d=o({queryKey:[...ue,i],queryFn:()=>t.trpcClient.llm.getUsage.query({since:c})}),f=n(()=>{let e=new Map;for(let t of l.data??[])e.set(t.id,t.name);return e},[l.data]),p=n(()=>[{key:`day`,header:e(`ai.colDay`,`Day`),nowrap:!0,render:e=>e.day},{key:`consumer`,header:e(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.consumer})},{key:`profile`,header:e(`ai.colProfile`,`Profile`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:f.get(e.profileId)??e.profileId})},{key:`calls`,header:e(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>String(e.calls)},{key:`okErr`,header:e(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:e.errorCalls>0?`text-danger`:void 0,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:e(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>`${String(e.inputTokens)} / ${String(e.outputTokens)}`},{key:`latency`,header:e(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>String(Math.round(e.avgLatencyMs))}],[f,e]),h=d.data??[];return a(J,{embedded:!0,icon:m,title:e(`ai.usageTitle`,`Usage`),subtitle:e(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),actions:u(`div`,{className:`w-40`,children:u(R,{"aria-label":e(`ai.window`,`Window`),value:String(i),options:pt.map(t=>({value:String(t),label:e(`ai.lastDays`,`Last {{days}} days`,{days:t})})),onChange:e=>s(Number(e.target.value))})}),children:[d.isError&&u(N,{title:e(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:e(`common.error`,`Error`),onRetry:()=>void d.refetch()}),h.length===0?u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noUsage`,`No AI calls in this window.`)}):u(B,{headingId:`ai-usage-list`,title:e(`ai.usageList`,`Rollup`),children:u(I,{columns:p,rows:h,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:H})})]})}function ht(){let{t:e}=q(),t=ie(`/system/ai`,{t:e,isAdmin:!0})??{icon:w,title:e(`system.ai`,`AI`)};return u(ae,{icon:t.icon,title:t.title,defaultSection:`profiles`,sectionsLabel:`${t.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:u(Fe,{})},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:u(ze,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:u(mt,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:u(at,{})}]})}export{ht as AiProfilesPage,ht as default};
@@ -1 +0,0 @@
1
- import{$ as e,B as t,J as n,K as r,L as i,S as a,b as o,q as s,x as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{D as l,O as u,V as d,oa as f,ot as p}from"./player-overlays-CikRdqm6.js";import{Cr as m,Dr as h,Er as g,Mr as _,Or as v,Rr as y,Tr as b,an as x,br as S,cn as C,gr as w,jr as T,ln as ee,on as te,sn as ne,vn as E,wr as re,xr as ie,yr as ae,zr as oe}from"./client-Ca-96r9I.js";import{Bi as se,Bn as D,Pi as ce,Un as O,_a as le,_u as ue,cr as de,er as fe,hu as pe,qa as me,ru as he,s as ge,va as k}from"./src-Bt0KiIin.js";import{t as A}from"./i18n-ATfMbes1.js";import{t as j}from"./useTranslation-D3Is_4B6.js";e();function _e(e){return{target:{kind:`new`,type:e},name:``,features:[]}}function ve(e){return{target:{kind:`existing`,device:e},name:``,features:[]}}function M(e,t){return{target:e.target,name:t,features:e.features.flatMap(e=>e.kind===`fields`?[e]:[])}}function N(e,t,n){return{...e,features:e.features.map(e=>e.cap===t?n(e):e)}}function P(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ye(e,t){switch(t.type){case`set-new-type`:return e.target.kind===`new`?{...e,target:{...e.target,type:t.deviceType}}:e;case`set-new-role`:{if(e.target.kind!==`new`)return e;let{role:n,...r}=e.target;return{...e,target:t.role===null?r:{...r,role:t.role}}}case`set-name`:return{...e,name:t.name};case`add-feature`:return e.features.some(e=>e.cap===t.cap)?e:{...e,features:[...e.features,{kind:`fields`,cap:t.cap,fields:{}}]};case`remove-feature`:return{...e,features:e.features.filter(e=>e.cap!==t.cap)};case`set-field`:return N(e,t.cap,e=>({...e,fields:{...e.fields,[t.path]:t.source}}));case`clear-field`:return N(e,t.cap,e=>({...e,fields:P(e.fields,t.path)}));case`remove-binding`:return N(e,t.cap,e=>{let n=e.fields[t.path];return n?.kind===`expression`?{...e,fields:{...e.fields,[t.path]:{...n,bindings:P(n.bindings,t.bindingName)}}}:e});case`copy-feature`:return N(e,t.cap,e=>({...e,fields:{...e.fields,...Object.fromEntries(t.paths.map(e=>[e,{kind:`from`,source:t.from,cap:t.sourceCap,fieldPath:e}]))}}))}}function be(e){let t=ie.safeParse({target:e.target,features:e.features});return t.success?{ok:!0,composition:t.data}:{ok:!1,problems:t.error.issues.map(e=>`${e.path.join(`.`)||`composition`}: ${e.message}`)}}function xe(e,t){return JSON.stringify(e)!==JSON.stringify(t)}function Se(e){for(let t=1;;t++){let n=`s${t}`;if(!e.includes(n))return n}}var Ce=[`room`,`converted-sensor`,`derived-binary`],F={addonId:`provider-homeassistant`,stableId:`sensor.template_source`};function we(){return M(C({temperatureSources:te,motionSources:x,occupancyWindowMs:ne}),`Room`)}function Te(){return M({target:{kind:`new`,type:_.Sensor},features:[{kind:`fields`,cap:`numeric-sensor`,fields:{value:{kind:`expression`,expr:`convert(v, "°C", "°F")`,bindings:{v:{kind:`from`,source:F,cap:`numeric-sensor`,fieldPath:`value`}}},unit:{kind:`expression`,expr:`"°F"`,bindings:{}},lastFetchedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Converted sensor`)}function Ee(){return M({target:{kind:`new`,type:_.Sensor},features:[{kind:`fields`,cap:`binary`,fields:{on:{kind:`expression`,expr:`v > 20`,bindings:{v:{kind:`from`,source:F,cap:`temperature-sensor`,fieldPath:`celsius`}}},lastChangedAt:{kind:`expression`,expr:`now`,bindings:{}}}}]},`Derived binary`)}function De(e){switch(e){case`room`:return we();case`converted-sensor`:return Te();case`derived-binary`:return Ee()}}function Oe(e,t){return typeof t==`number`&&Number.isFinite(t)&&t>0?{kind:`device`,path:`/devices/${t}`}:{kind:`editor`,path:`/build/compositions/${encodeURIComponent(e)}`}}var I=`rounded-lg border border-border bg-surface p-4`,ke=I;function Ae(e){return{addonId:e.addonId,stableId:e.stableId}}function L(e){return new Map(e.map(e=>[h(Ae(e)),e]))}function je(e,t,n){let r=e?.features??[],i=r.findIndex(e=>e.cap===n.cap);return{target:e?.target??{kind:`existing`,device:t},features:i===-1?[...r,n]:r.map((e,t)=>t===i?n:e)}}function Me(e,t){let n=e.features.filter(e=>e.cap!==t);return n.length===0?null:{target:e.target,features:n}}function Ne(e,t){let n=e?.features.find(e=>e.cap===t);return n!==void 0&&n.kind===`fields`?n:null}function R(e){return Array.isArray(e)?e.map(R):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,R(t)]))}function z(e){return JSON.stringify(R(e))}function Pe(e,t){return z(e)===z(t)}function B(e,t){return z(e)===z(t)}function Fe(e,t){switch(e.kind){case`pending`:return{kind:`refused`,reason:A.t(`helpers.customizationSave.notReadYet`)};case`unknown`:return{kind:`refused`,reason:`the customization could not be read: ${e.reason}`};case`not-loaded`:return{kind:`refused`,reason:`the customizations are not loaded yet: ${e.reason}`};case`none`:return t===null?{kind:`noop`}:{kind:`create`,input:{enabled:!0,composition:t}};case`present`:{let n=e.view.block.id;return t===null?{kind:`delete`,blockId:n}:z(t)===z(e.composition)?{kind:`noop`}:{kind:`update`,blockId:n,expectedUpdatedAt:e.view.block.updatedAt,composition:t}}}}function V(e,t){let n=e===`enum`?`string`:e,r=t.kind===`enum`?`string`:t.kind,i={source:t.source,cap:t.cap,fieldPath:t.fieldPath};return r===n?{kind:`from`,...i}:n===`number`&&r===`string`?{kind:`expression`,expr:`number(x)`,bindings:{x:{kind:`from`,...i}}}:null}function H(e){return{kind:`expression`,expr:e,bindings:{}}}function U(e){let t=V(`number`,e.percentage);return t===null?null:{kind:`fields`,cap:`battery`,fields:e.mode===`replace`?{percentage:t}:{percentage:t,charging:H(`"unknown"`),sleeping:H(`false`),lastUpdated:H(`now`)}}}var Ie=[`percent`,...E.options];function W(e,t){return t===`percent`?{level:e}:{"remaining.value":e,"remaining.unit":H(JSON.stringify(t))}}function Le(e,t){let n=V(`number`,t.remaining);if(n===null||!S.test(t.key)||t.label.trim()===``)return null;let r={label:t.label.trim(),fields:W(n,t.unit)};return{kind:`fields`,cap:`consumables`,...e?.enabled===void 0?{}:{enabled:e.enabled},fields:e?.fields??{lastChangedAt:H(`now`),lastFetchedAt:H(`now`)},items:{...e?.items,[t.key]:r}}}function Re(e){if(e.level!==void 0)return`percent`;let t=e[`remaining.unit`];if(t===void 0||t.kind!==`expression`)return null;try{let e=E.safeParse(JSON.parse(t.expr));return e.success?e.data:null}catch{return null}}function ze(e){return Object.entries(e?.items??{}).map(([e,t])=>{let n=Re(t.fields),r=G(t.fields.level??t.fields[`remaining.value`]),i=r===null?null:V(`number`,r);return n!==null&&i!==null&&Pe(W(i,n),t.fields)?{key:e,label:t.label,unit:n,source:r}:{key:e,label:t.label,unit:null,source:null}})}function Be(e,t){let n=Object.fromEntries(Object.entries(e.items??{}).filter(([e])=>e!==t));return Object.keys(n).length===0?null:{...e,items:n}}function Ve(e){return e.toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,48)}function He(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=Object.entries(t.bindings).filter(([e])=>e.startsWith(`active`)).flatMap(([,e])=>e.kind===`from`?[e.source]:[]);return[...new Map(n.map(e=>[h(e),e])).values()]}function Ue(e){let t=e.fields.lastPressedAt;if(t===void 0||t.kind!==`expression`)return[];let n=t.bindings;return Object.entries(n).flatMap(([e,t])=>{if(!e.startsWith(`active`)||t.kind!==`from`)return[];let r=n[`changed${e.slice(6)}`];return r===void 0||r.kind!==`from`?[]:[{source:t.source,cap:t.cap,activeField:t.fieldPath,changedAtField:r.fieldPath}]})}function G(e){if(e===void 0)return null;if(e.kind===`from`){let{kind:t,...n}=e;return{...n,kind:`number`}}if(e.kind!==`expression`||e.expr!==`number(x)`)return null;let t=e.bindings.x;if(t===void 0||t.kind!==`from`||Object.keys(e.bindings).length!==1)return null;let{kind:n,...r}=t;return{...r,kind:`string`}}function We(e,t){let n=G(e.fields.percentage);if(n===null)return!1;let r=U({percentage:n,mode:t}),{enabled:i,...a}=e;return r!==null&&B(a,r)}function K(e){return e.map(e=>({id:e.id,name:e.name,addonId:e.addonId,stableId:e.stableId,location:e.location,type:e.type}))}function Ge(e,t,n){let r=t.trim().toLowerCase();return r===``?[]:e.filter(e=>!n.includes(e.id)&&[e.name,e.stableId,e.location??``].some(e=>e.toLowerCase().includes(r))).toSorted((e,t)=>e.name.localeCompare(t.name)).slice(0,20)}function q(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=Object.getOwnPropertyDescriptor(n,e)?.value}return n}function Ke(e,t,n,r){return r===null?{kind:`from`,source:e,cap:t,fieldPath:n.path}:V(r,{source:e,cap:t,fieldPath:n.path,kind:n.kind})}function qe(e,t,n,r){let i={addonId:e.addonId,stableId:e.stableId};return t.caps.flatMap(e=>e.fields.filter(e=>e.item!==!0).map(t=>({cap:e.cap,path:t.path,kind:t.kind,value:n===null?void 0:q(n[e.cap],t.path),source:Ke(i,e.cap,t,r)})))}function J(e,t){return t?e===void 0?`—`:e===null?`null`:typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e):`…`}var Je=[];function Y({title:e,targetKind:t,excludeDeviceIds:r=Je,onPick:i,onCancel:o}){let{t:s}=j(),[f,p]=n(null);return a(`aside`,{"aria-label":e,className:`${u} ${l} flex flex-col gap-2`,children:[c(`h3`,{className:d,children:e}),f===null?c(Ye,{excludeDeviceIds:r,onSelect:p}):c(X,{device:f,targetKind:t,onPick:i,onBack:()=>p(null)}),c(`div`,{children:c(O,{variant:`ghost`,size:`sm`,onClick:o,children:s(`customize.picker.cancel`)})})]})}function Ye({excludeDeviceIds:e,onSelect:t}){let{t:r}=j(),[i,s]=n(``),l=k({projection:`slim`});return a(o,{children:[a(`label`,{className:`flex flex-col gap-1 text-[11px] text-foreground-subtle`,children:[r(`customize.picker.search`),c(he,{type:`search`,"aria-label":r(`customize.picker.search`),value:i,onChange:e=>s(e.target.value)})]}),l.status===`pending`&&c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:r(`customize.picker.loadingDevices`)}),l.status===`error`&&c(D,{title:r(`customize.picker.devicesFailed`),message:l.error?.message??``}),l.status===`success`&&c(`ul`,{className:`flex flex-col gap-1`,children:Ge(K(l.data),i,e).map(e=>c(`li`,{children:a(`button`,{type:`button`,className:`text-left text-[11px] hover:underline`,onClick:()=>t(e),children:[e.name,` `,a(`span`,{className:`text-foreground-subtle`,children:[`· `,e.stableId]})]})},e.id))})]})}function X({device:e,targetKind:t,selected:n,onPick:r,onBack:i}){let{t:o}=j(),s=le({deviceId:e.id}),l=me({deviceId:e.id});if(s.status===`pending`)return c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:o(`customize.picker.loadingFields`)});if(s.status===`error`)return c(D,{title:o(`customize.picker.fieldsFailed`),message:s.error?.message??``});let u=qe(e,s.data,l.status===`success`?l.data:null,t),d=u.filter(e=>e.source===null).length,f={addonId:e.addonId,stableId:e.stableId};return a(`div`,{className:`flex flex-col gap-1`,children:[a(`button`,{type:`button`,className:`text-left text-[11px] text-primary`,onClick:i,children:[`← `,e.name]}),l.status===`error`&&c(`p`,{role:`alert`,className:`text-[10px] text-warning`,children:o(`customize.picker.valuesFailed`,{reason:l.error?.message??``})}),c(`ul`,{role:`listbox`,"aria-label":o(`customize.picker.fields`),className:`flex flex-col gap-1`,children:u.map(t=>{let i=t.source;if(i===null)return null;let o=()=>r({device:e,ref:f,cap:t.cap,path:t.path,kind:t.kind,source:i,value:t.value});return a(`li`,{role:`option`,"aria-selected":n?.cap===t.cap&&n.path===t.path,tabIndex:0,className:`flex justify-between gap-2 text-[11px] cursor-pointer hover:bg-surface-hover rounded px-1`,onClick:o,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&o()},children:[a(`span`,{className:`font-mono`,children:[t.cap,`.`,t.path]}),c(`span`,{children:J(t.value,l.status===`success`)})]},`${t.cap}.${t.path}`)})}),d>0&&t!==null&&c(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`customize.picker.hidden`,{count:d,kind:o(`customize.kinds.${t}`)})})]})}var Xe=`integration`;function Z(e,t){switch(e.kind){case`from`:{let n=h(e.source);return`${t.get(n)??n} · ${e.cap}.${e.fieldPath}`}case`expression`:return e.expr;case`code`:return`code`}}function Ze(e,t){if(e.kind===`unreachable`)return{kind:`unknown`,reason:e.error};if(e.state===null)return{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.composerNotReported`)};let n=e.state.fields.find(t);return n===void 0?{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.noValue`)}:n.state===`unavailable`?{kind:`unavailable`,reason:n.reason??A.t(`common.unavailable`)}:{kind:`value`,value:n.value,staleReason:n.state===`stale`?n.reason??A.t(`common.stale`):null}}function Q(e,t,n,r){return{key:`${e.feature.cap}.${t}`,cap:e.feature.cap,field:t,origin:`composed`,mode:e.mode,from:Z(n,e.input.sourceNames),value:e.enabled?Ze(e.input.state,r):{kind:`off`}}}function Qe(e){let t=e.feature.cap;return Object.entries(e.feature.fields).map(([n,r])=>Q(e,n,r,e=>e.cap===t&&e.path===n&&e.item===void 0))}function $e(e){let t=e.feature.cap;return Object.entries(e.feature.items??{}).flatMap(([n,r])=>Object.entries(r.fields).map(([r,i])=>Q(e,re(ae,n,r),i,e=>e.cap===t&&e.path===r&&e.item?.arrayPath===`items`&&e.item.key===n)))}function et(e,t,n){if(e===null)return{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.stateUnreadable`)};let r=q(e[t],n),i=r===void 0?void 0:y(r);return i===void 0?{kind:`unknown`,reason:A.t(`helpers.fieldsTableRows.notReported`)}:{kind:`value`,value:i,staleReason:null}}function tt(e){if(e.mode!==`replace`)return[];let t=e.feature.cap,n=new Set(Object.keys(e.feature.fields));return(e.input.nativeFields.get(t)??[]).filter(e=>!n.has(e)).map(n=>({key:`${t}.${n}`,cap:t,field:n,origin:`native`,mode:e.mode,from:Xe,value:et(e.input.snapshot,t,n)}))}function nt(e){return e.composition.features.flatMap(t=>{if(t.kind!==`fields`)return[];let n={feature:t,mode:e.nativeCaps.has(t.cap)?`replace`:`add`,enabled:m(t),input:e};return[...Qe(n),...$e(n),...tt(n)]})}var rt={min:`min(a, b, …)`,max:`max(a, b, …)`,abs:`abs(x)`,floor:`floor(x)`,ceil:`ceil(x)`,sqrt:`sqrt(x)`,round:`round(x, digits?)`,pow:`pow(x, y)`,clamp:`clamp(x, lo, hi)`,avg:`avg(a, b, …)`,sum:`sum(a, b, …)`,coalesce:`coalesce(a, b, …)`,age:`age(now, ts)`,convert:`convert(x, "from", "to")`,any:`any(a, b, …)`,all:`all(a, b, …)`,within:`within(ts, ms)`,number:`number(x)`,latest:`latest(ts, …)`,rose:`rose(level, changedAt, debounceMs?)`,count:`count(x)`},it=/[A-Za-z_][A-Za-z0-9_]*$/;function at(e,t,n){let r=it.exec(e.slice(0,t))?.[0]??``;if(r===``)return[];let i=n.filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`binding`,label:e,insert:e,hintKey:null})),a=`now`.startsWith(r)?[{kind:`now`,label:`now`,insert:`now`,hintKey:`compositionEditor.now`}]:[],o=[...oe].filter(e=>e.startsWith(r)).toSorted().map(e=>({kind:`builtin`,label:rt[e]??e,insert:`${e}(`,hintKey:`compositionEditor.builtins.${e}`}));return[...i,...a,...o].slice(0,8)}function ot(e,t,n){let r=t-(it.exec(e.slice(0,t))?.[0]??``).length;return{text:`${e.slice(0,r)}${n.insert}${e.slice(t)}`,cursor:r+n.insert.length}}e();function st({label:e,value:t,bindings:r,onChange:i}){let{t:o}=j(),l=s(null),[u,d]=n(t.length),f=at(t,u,r);return a(`div`,{className:`flex flex-col gap-1`,children:[a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[e,c(`input`,{ref:l,className:`font-mono px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`,value:t,onChange:e=>{i(e.target.value),d(e.target.selectionStart??e.target.value.length)},onSelect:e=>d(e.currentTarget.selectionStart??t.length)})]}),f.length>0&&c(`ul`,{role:`listbox`,"aria-label":o(`compositionEditor.suggestions`),className:`rounded border border-border bg-surface text-[11px]`,children:f.map(e=>a(`li`,{role:`option`,"aria-selected":!1,tabIndex:0,className:`flex justify-between gap-2 px-1 cursor-pointer hover:bg-surface-hover`,onClick:()=>{let n=ot(t,u,e);i(n.text),d(n.cursor),l.current?.focus()},children:[c(`span`,{className:`font-mono`,children:e.label}),e.hintKey!==null&&c(`span`,{className:`text-foreground-subtle`,children:o(e.hintKey)})]},`${e.kind}:${e.label}`))})]})}function ct(e,t,n){if(e.kind===`code`)return{kind:`unavailable`,reason:A.t(`helpers.fieldPreview.codeFields`)};if(e.kind===`expression`&&(w(e.expr,`rose`)||w(e.expr,`count`)))return{kind:`runtime-only`};let r=v(e).filter(e=>t.get(g(e.source,e.cap))?.kind!==`value`).map(b);if(r.length>0)return{kind:`waiting`,missing:r};let i=ee({source:e,now:n,read:e=>{let n=t.get(g(e.source,e.cap)),r=n?.kind===`value`?q(n.slice,e.fieldPath):void 0,i=r===void 0?void 0:y(r);return i===void 0?{state:`unavailable`,reason:A.t(`helpers.fieldPreview.notReported`,{path:`${e.cap}.${e.fieldPath}`}),fatal:!1}:{state:`fresh`,value:i}}});return i.state===`unavailable`?{kind:`unavailable`,reason:i.reason}:{kind:`value`,value:i.value,stale:i.reason}}e();function lt({sliceKey:e,deviceId:n,capName:r,onReading:i}){let a=ge(p().trpcClient,n,r);return t(()=>{i(e,a===void 0?{kind:`pending`}:{kind:`value`,slice:a})},[e,a,i]),null}function ut(e,t){return[...new Map(v(e).map(e=>[g(e.source,e.cap),e]))].map(([e,n])=>({key:e,read:n,device:t.get(h(n.source))}))}function dt({source:e}){let{t}=j(),r=k({projection:`slim`}),[o,s]=n(new Map),l=i((e,t)=>{s(n=>new Map([...n,[e,t]]))},[]),u=ut(e,L(r.status===`success`?K(r.data):[])),d=r.status===`success`?u.filter(e=>e.device===void 0).map(e=>h(e.read.source)):[];return a(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px]`,children:[u.map(e=>e.device===void 0?null:c(lt,{sliceKey:e.key,deviceId:e.device.id,capName:e.read.cap,onReading:l},e.key)),c(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.label`)}),r.status===`error`?c(`span`,{className:`text-warning`,children:t(`compositionEditor.preview.devicesFailed`,{reason:r.error?.message??``})}):d.length>0?c(`span`,{className:`text-warning`,children:t(`compositionEditor.preview.unknownDevice`,{sources:d.join(`, `)})}):c(ft,{preview:ct(e,o,Date.now())})]})}function ft({preview:e}){let{t}=j();switch(e.kind){case`value`:return a(`strong`,{children:[`→ `,J(e.value,!0),e.stale===null?``:` (${e.stale})`]});case`unavailable`:return c(`span`,{className:`text-warning`,children:e.reason});case`waiting`:return c(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.waiting`,{sources:e.missing.join(`, `)})});case`runtime-only`:return c(`span`,{className:`text-foreground-subtle`,children:t(`compositionEditor.preview.runtimeOnly`)})}}e();function pt({path:e,kind:t,required:r,source:i,onSet:s,onClear:l,onRemoveBinding:u,sourceNames:d}){let{t:f}=j(),[p,m]=n(`idle`),h=i?.kind===`expression`?i:null;return a(`div`,{className:`flex flex-col gap-1 rounded border border-border p-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[c(`span`,{className:`font-mono text-[11px]`,children:e}),a(`span`,{className:`text-[10px] text-foreground-subtle`,children:[f(`customize.kinds.${t}`),r?` · ${f(`compositionEditor.required`)}`:``]}),c(O,{size:`sm`,variant:`outline`,onClick:()=>m(`take`),children:f(`compositionEditor.takeFrom`)}),c(O,{size:`sm`,variant:`outline`,"aria-pressed":h!==null,onClick:()=>s(h??{kind:`expression`,expr:`null`,bindings:{}}),children:f(`compositionEditor.formula`)}),i!==void 0&&c(O,{size:`sm`,variant:`ghost`,onClick:l,children:f(`compositionEditor.clear`)})]}),i?.kind===`from`&&c(`span`,{className:`text-[11px]`,children:Z(i,d)}),h!==null&&a(o,{children:[c(st,{label:f(`compositionEditor.formulaFor`,{path:e}),value:h.expr,bindings:Object.keys(h.bindings),onChange:e=>s({...h,expr:e})}),c(`ul`,{className:`text-[11px] flex flex-col gap-0.5`,children:Object.entries(h.bindings).map(([e,t])=>a(`li`,{className:`flex flex-wrap items-center gap-2`,children:[c(`span`,{className:`font-mono`,children:e}),c(`span`,{children:t.kind===`from`?Z(t,d):JSON.stringify(t.value)}),c(O,{size:`sm`,variant:`ghost`,"aria-label":f(`compositionEditor.removeBinding`,{name:e}),onClick:()=>u(e),children:`×`})]},e))}),c(O,{size:`sm`,variant:`ghost`,onClick:()=>m(`add-binding`),children:f(`compositionEditor.addSource`)})]}),p!==`idle`&&c(Y,{title:f(p===`take`?`compositionEditor.takeFrom`:`compositionEditor.addSource`),targetKind:p===`take`?t:null,onCancel:()=>m(`idle`),onPick:e=>{if(p===`take`)s(e.source);else if(h!==null){let t=Se(Object.keys(h.bindings));s({...h,bindings:{...h.bindings,[t]:{kind:`from`,source:e.ref,cap:e.cap,fieldPath:e.path}}})}m(`idle`)}}),i!==void 0&&c(dt,{source:i})]})}e();function mt(e){return e===null||e.kind===`known`?null:e}function ht({draft:e,deviceType:t,nativeCaps:r,targetFields:i,dispatch:s}){let{t:l}=j(),u=ce({deviceType:t}),d=k({projection:`slim`}),f=new Map([...L(d.status===`success`?K(d.data):[])].map(([e,t])=>[e,t.name])),[p,m]=n(null),h=mt(r)??mt(i),g=r?.kind===`known`?r.value:new Set,_=new Set(e.features.map(e=>e.cap)),v=u.status===`success`?u.data.caps.filter(e=>!_.has(e.cap)&&!g.has(e.cap)):[],y=[...g].filter(e=>!_.has(e)),b=e=>g.has(e)?((i?.kind===`known`?i.value.caps.find(t=>t.cap===e):void 0)?.fields??[]).filter(e=>e.item!==!0&&!e.path.includes(`.`)).map(e=>({path:e.path,kind:e.kind,required:!1})):((u.status===`success`?u.data.caps.find(t=>t.cap===e):void 0)?.fields??[]).map(e=>({path:e.path,kind:e.kind,required:e.required}));return h===null?a(o,{children:[a(`section`,{"aria-labelledby":`editor-features`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),u.status===`pending`&&c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.checking`)}),u.status===`error`&&c(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.unknown`,{reason:u.error?.message??``})}),a(`div`,{className:`flex flex-wrap gap-1`,children:[e.features.map(e=>a(`span`,{className:`flex items-center gap-1 rounded border border-border px-1.5 text-[11px]`,children:[e.cap,c(de,{variant:g.has(e.cap)?`default`:`info`,children:g.has(e.cap)?l(`compositionEditor.replaces`):l(`compositionEditor.added`)}),c(`button`,{type:`button`,"aria-label":l(`compositionEditor.removeFeature`,{cap:e.cap}),onClick:()=>s({type:`remove-feature`,cap:e.cap}),children:`×`})]},e.cap)),v.map(e=>a(O,{size:`sm`,variant:`outline`,onClick:()=>s({type:`add-feature`,cap:e.cap}),children:[`+ `,e.cap]},e.cap)),y.map(e=>c(O,{size:`sm`,variant:`ghost`,onClick:()=>s({type:`add-feature`,cap:e}),children:l(`compositionEditor.replaceIn`,{cap:e})},e))]})]}),e.features.map(e=>a(`section`,{"aria-label":l(`compositionEditor.steps.fieldsOf`,{cap:e.cap}),className:`${I} flex flex-col gap-2`,children:[a(`div`,{className:`flex items-center justify-between`,children:[c(`h2`,{className:`text-sm font-semibold`,children:l(`compositionEditor.steps.fieldsOf`,{cap:e.cap})}),c(O,{size:`sm`,variant:`outline`,onClick:()=>m(e.cap),children:l(`compositionEditor.copyFeature`)})]}),p===e.cap&&c(Y,{title:l(`compositionEditor.copyFeature`),targetKind:null,onCancel:()=>m(null),onPick:t=>{s({type:`copy-feature`,cap:e.cap,from:t.ref,sourceCap:t.cap,paths:b(e.cap).map(e=>e.path)}),m(null)}}),b(e.cap).map(t=>c(pt,{path:t.path,kind:t.kind,required:t.required,source:e.fields[t.path],onSet:n=>s({type:`set-field`,cap:e.cap,path:t.path,source:n}),onClear:()=>s({type:`clear-field`,cap:e.cap,path:t.path}),onRemoveBinding:n=>s({type:`remove-binding`,cap:e.cap,path:t.path,bindingName:n}),sourceNames:f},t.path))]},e.cap))]}):a(`section`,{"aria-labelledby":`editor-features`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-features`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.features`)}),c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:h.kind===`unknown`?h.reason:l(`compositionEditor.reading`)})]})}var $=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function gt({draft:e,targetName:t,dispatch:n}){let r=f(),{t:i}=j(),o=e.target;return a(`section`,{"aria-labelledby":`editor-target`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-target`,className:`text-sm font-semibold`,children:i(`compositionEditor.steps.target`)}),o.kind===`existing`?c(`p`,{className:`text-[11px]`,children:i(`compositionEditor.existingTarget`,{name:t??`${o.device.addonId}/${o.device.stableId}`})}):a(`div`,{className:`grid grid-cols-3 gap-2`,children:[a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[i(`compositionEditor.targetType`),c(`select`,{className:$,value:o.type,onChange:e=>{let t=Object.values(_).find(t=>t===e.target.value);t!==void 0&&n({type:`set-new-type`,deviceType:t})},children:Object.values(_).map(e=>c(`option`,{value:e,children:ue(e,r).label},e))})]}),a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[i(`customize.identity.role`),a(`select`,{className:$,value:o.role??``,onChange:e=>n({type:`set-new-role`,role:Object.values(T).find(t=>t===e.target.value)??null}),children:[c(`option`,{value:``,children:i(`customize.identity.noRole`)}),Object.values(T).map(e=>c(`option`,{value:e,children:pe(e,r).label},e))]})]}),a(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[i(`compositionEditor.name`),c(`input`,{className:$,value:e.name,onChange:e=>n({type:`set-name`,name:e.target.value})})]})]})]})}e();function _t({draft:e,blockId:r,saving:i,onSave:o,onCancel:s}){let{t:l}=j(),u=se(),d=be(e),f=d.ok?JSON.stringify(d.composition):``,[p,m]=n({key:``,state:{kind:`checking`}});t(()=>{if(!d.ok)return;let e=d.composition,t=setTimeout(()=>{u.mutateAsync({composition:e,...r===null?{}:{blockId:r}}).then(e=>m({key:f,state:e.ok?{kind:`ok`}:{kind:`refused`,problems:e.problems}})).catch(e=>m({key:f,state:{kind:`unknown`,reason:e instanceof Error?e.message:String(e)}}))},500);return()=>clearTimeout(t)},[f,r]);let h=d.ok?p.key===f?p.state:{kind:`checking`}:{kind:`invalid-draft`,problems:d.problems};return a(`section`,{"aria-labelledby":`editor-verify`,className:`${I} flex flex-col gap-2`,children:[c(`h2`,{id:`editor-verify`,className:`text-sm font-semibold`,children:l(`compositionEditor.steps.verify`)}),h.kind===`checking`&&c(`p`,{role:`status`,className:`text-[11px] text-foreground-subtle`,children:l(`compositionEditor.verify.checking`)}),h.kind===`ok`&&c(`p`,{className:`text-[11px] text-success`,children:l(`compositionEditor.verify.ok`)}),h.kind===`unknown`&&c(`p`,{role:`alert`,className:`text-[11px] text-warning`,children:l(`compositionEditor.verify.unknown`,{reason:h.reason})}),(h.kind===`invalid-draft`||h.kind===`refused`)&&c(`ul`,{role:`alert`,className:`flex flex-col gap-1 text-[11px] text-danger`,children:h.kind===`invalid-draft`?h.problems.map(e=>c(`li`,{children:e},e)):h.problems.map(e=>a(`li`,{children:[c(`span`,{className:`font-mono`,children:e.path}),` — `,e.message]},`${e.path}:${e.code}`))}),a(`div`,{className:`flex gap-2`,children:[c(O,{variant:`ghost`,onClick:s,children:l(`compositionEditor.cancel`)}),c(O,{disabled:h.kind!==`ok`||i||!d.ok,onClick:()=>d.ok&&o(d.composition),children:l(`compositionEditor.save`)})]})]})}e();function vt({initial:e,blockId:t,deviceType:r,targetName:i=null,nativeCaps:a,targetFields:o,save:s,onCancel:l,showTemplates:u=!1}){let[d,f]=n(e),p=`${d.name}:${d.features.map(e=>e.cap).join(`,`)}:${d.target.kind===`new`?d.target.type:`existing`}`;return c(yt,{seed:d,blockId:t,deviceType:r,targetName:i,nativeCaps:a,targetFields:o,showTemplates:u,onApplyTemplate:e=>{f(De(e))},save:s,onCancel:l},p)}function yt({seed:e,blockId:t,deviceType:i,targetName:o,nativeCaps:s,targetFields:l,showTemplates:u,onApplyTemplate:d,save:f,onCancel:p}){let{t:m}=j(),h=fe(),[g,_]=r(ye,e),[v,y]=n(!1),[b,x]=n(null),S=async t=>{xe(e,g)&&!await h({title:m(`compositionEditor.templates.confirmTitle`),message:m(`compositionEditor.templates.confirmMessage`),confirmLabel:m(`compositionEditor.templates.confirmApply`),variant:`danger`})||d(t)},C=g.target.kind===`new`?g.target.type:i,w=async e=>{y(!0);let t=await f(e,g.name);y(!1),x(t.kind===`refused`?t.reason:null)};return a(`div`,{className:`flex flex-col gap-4`,children:[u&&g.target.kind===`new`&&a(`div`,{className:`rounded-lg border border-border bg-surface p-4 flex flex-wrap gap-2`,"data-testid":`composition-templates`,children:[c(`span`,{className:`text-[11px] text-foreground-subtle self-center`,children:m(`compositionEditor.templates.label`)}),Ce.map(e=>c(O,{size:`sm`,variant:`outline`,onClick:()=>void S(e),children:m(`compositionEditor.templates.${e}`)},e))]}),c(gt,{draft:g,targetName:o,dispatch:_}),c(ht,{draft:g,deviceType:C,nativeCaps:s,targetFields:l,dispatch:_}),c(_t,{draft:g,blockId:t,saving:v,onSave:e=>void w(e),onCancel:p}),b!==null&&c(`p`,{role:`alert`,className:`text-[11px] text-danger break-words`,children:b})]})}export{Me as C,ve as D,M as E,_e as O,je as S,Oe as T,G as _,X as a,Fe as b,K as c,Le as d,ze as f,Ve as g,We as h,nt as i,Ie as l,Ue as m,ct as n,J as o,He as p,st as r,q as s,vt as t,U as u,Be as v,ke as w,B as x,Ne as y};
@@ -1 +0,0 @@
1
- import{S as e,x as t}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{Mr as n,pr as r}from"./client-Ca-96r9I.js";import{t as i}from"./boxes-B64NRkVe.js";import{Bn as a,Mi as o,Oi as s,zi as c}from"./src-Bt0KiIin.js";import{t as l}from"./useTranslation-D3Is_4B6.js";import{$ as u,Z as d,et as f,g as p,x as m}from"./index-CIQcOfrF.js";import{E as h,O as g,T as _,t as v,w as y}from"./CompositionEditor-ChpgaVIC.js";import{t as b}from"./AdminPage-CgbWYJ_a.js";var x=`new`;function S(e){return e instanceof Error?e.message:String(e)}function C(e){let t=e.trim();return t===``?{}:{name:t}}function w(){let{blockId:w}=f(),{t:T}=l(),E=u(),D=s(),O=c(),k=w===void 0||w===x,A=o({blockId:w??``},{enabled:!k}),j=()=>{E(p)},M=e=>t(b,{icon:i,title:T(`compositionEditor.pageTitle`),children:e}),N=e=>t(`section`,{className:`${y} flex flex-col gap-2`,children:e});if(k)return M(t(v,{initial:g(n.Sensor),blockId:null,deviceType:n.Sensor,nativeCaps:null,targetFields:null,showTemplates:!0,onCancel:j,save:async(e,t)=>{try{let{block:n}=await D.mutateAsync({block:{...C(t),enabled:!0,composition:e}});return E(_(n.id,null).path,{replace:!0}),{kind:`saved`}}catch(e){return{kind:`refused`,reason:S(e)}}}}));if(A.status===`pending`)return M(N(t(`p`,{role:`status`,children:T(`compositionEditor.loading`)})));if(A.status===`error`)return M(N(t(a,{title:T(`compositionEditor.loadFailed`),message:A.error.message})));if(A.data.state===`not-loaded`)return M(N(t(`p`,{role:`status`,children:T(`customize.status.notLoaded`,{reason:A.data.reason})})));let P=A.data.view;if(P===null)return M(N(t(`p`,{children:T(`compositionEditor.notFound`,{blockId:w})})));let F=r(P.block);if(F===null)return M(N(t(`p`,{children:T(`compositionEditor.notComposition`)})));if(F.target.kind===`existing`){let e=P.state.kind===`answered`?P.state.state?.deviceId??null:null;return M(N(e===null?t(`p`,{children:T(`compositionEditor.customizationUnknownDevice`)}):t(d,{className:`text-primary`,to:m(e),children:T(`compositionEditor.openOnDevice`)})))}let I=P.state.kind===`answered`?P.state.state?.deviceId??null:null,L=I===null?null:_(P.block.id,I);return M(e(`div`,{className:`flex flex-col gap-3`,children:[L!==null&&L.kind===`device`&&t(d,{className:`text-sm text-primary`,to:L.path,"data-testid":`open-composed-device`,children:T(`compositionEditor.openComposedDevice`,{id:I})}),t(v,{initial:h(F,P.block.name),blockId:P.block.id,deviceType:F.target.type,nativeCaps:null,targetFields:null,onCancel:j,save:async(e,t)=>{try{return await O.mutateAsync({blockId:P.block.id,expectedUpdatedAt:P.block.updatedAt,block:{...C(t),composition:e}}),await A.refetch(),{kind:`saved`}}catch(e){return{kind:`refused`,reason:S(e)}}}},`${P.block.id}@${P.block.updatedAt}`)]}))}export{w as CompositionEditorPage};
@@ -1,2 +0,0 @@
1
- import{$ as e,B as t,G as n,J as r,L as i,S as a,b as o,o as s,x as c}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEHpkaJP.js";import{An as l,D as u,Fn as d,It as f,Ji as p,Jr as m,Nt as h,Q as g,Wi as _,Wr as v,Yi as y,Zr as b,ai as x,fn as S,ir as C,kn as w,or as T,pi as E,rr as D,si as O,vn as k,xi as A,yi as j}from"./player-overlays-CikRdqm6.js";import{n as M,t as N}from"./cloud-upload-Ck1AcqSa.js";import{t as P}from"./circle-slash-CEYz4tuU.js";import{t as F}from"./hard-drive-download-DVmQAuw3.js";import{$r as I,An as ee,B as L,Bn as R,F as te,Gc as z,H as ne,I as re,Ir as ie,J as B,Kc as ae,Kt as oe,Mn as se,Nc as ce,Nn as le,On as ue,Pn as de,Ql as fe,Qr as pe,Un as V,V as me,Vn as he,Wc as ge,ai as _e,ci as ve,cn as ye,cr as be,di as xe,ei as Se,er as H,fi as Ce,ii as we,iu as U,kn as Te,li as Ee,ni as De,oi as Oe,ol as ke,pi as Ae,qc as je,qt as Me,ra as Ne,ri as Pe,ru as Fe,si as Ie,ti as Le,ui as Re}from"./src-Bt0KiIin.js";import{t as W}from"./i18n-ATfMbes1.js";import{t as G}from"./useTranslation-D3Is_4B6.js";import"./mount-Dep-E57-.js";import{X as ze,w as Be}from"./index-CIQcOfrF.js";import{t as Ve}from"./AdminSectionedPage-Cx5lBMEy.js";import{t as He}from"./AdminPage-CgbWYJ_a.js";import{n as Ue}from"./authed-media-B64j5Vsu.js";import{t as K}from"./format-size-DIxKXxtj.js";import{a as We,c as Ge,l as Ke,n as qe,o as Je,s as Ye,t as Xe,u as Ze}from"./location-owned-usage-CPVIHMbS.js";e();function Qe(e){return Object.entries(e).map(([e,t])=>`${e} ${t}`).join(` · `)}function $e(e){return e.reduce((e,t)=>e+Object.values(t.stores).reduce((e,t)=>e+t,0),0)}function et(){let{t:e}=G(),t=H(),n=Ne(),[i,s]=r(null),[l,u]=r(null),d=async e=>{u(null);try{s(await n.mutateAsync({confirm:e}))}catch(e){u(e instanceof Error?e.message:String(e))}},p=async()=>{i===null||i.status!==`dry-run`||await t({title:e(`systemPage.deletedDevices.confirmTitle`,`Delete the data of deleted devices?`),message:i.devices.map(e=>`#${e.deviceId}: ${Qe(e.stores)}`).join(`
2
- `),confirmLabel:e(`systemPage.deletedDevices.confirmLabel`,`Delete`),variant:`danger`})&&await d(!0)},m=[{key:`device`,header:e(`systemPage.deletedDevices.device`,`Device`),render:e=>`#${e.deviceId}`},{key:`stores`,header:e(`systemPage.deletedDevices.stores`,`Data held`),nowrap:!1,render:e=>Qe(e.stores)}];return a(`div`,{className:`space-y-4`,"data-testid":`deleted-devices-data`,children:[c(`p`,{className:`text-sm text-muted-foreground`,children:e(`systemPage.deletedDevices.intro`,`Data that still belongs to devices that were deleted before deletions were recorded: footage, events, history and per-addon settings. Scanning deletes nothing; deleting asks first and shows what goes.`)}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(V,{variant:`outline`,onClick:()=>void d(!1),disabled:n.isPending,"data-testid":`deleted-devices-scan`,children:[n.isPending?c(T,{className:`mr-2 h-4 w-4 animate-spin`}):c(S,{className:`mr-2 h-4 w-4`}),e(`systemPage.deletedDevices.scan`,`Scan`)]}),i?.status===`dry-run`&&i.devices.length>0?a(V,{variant:`danger`,onClick:()=>void p(),disabled:n.isPending,"data-testid":`deleted-devices-delete`,children:[c(f,{className:`mr-2 h-4 w-4`}),e(`systemPage.deletedDevices.delete`,`Delete the data of {{count}} devices…`,{count:i.devices.length})]}):null]}),l===null?null:c(`p`,{className:`text-sm text-danger`,children:l}),i?.status===`skipped`?c(`p`,{className:`text-sm text-warning`,"data-testid":`deleted-devices-skipped`,children:e(`systemPage.deletedDevices.skipped`,`Nothing was listed or deleted: the device list could not be trusted ({{reason}}). Try again.`,{reason:i.reason??``})}):null,i!==null&&i.status!==`skipped`?a(o,{children:[c(`p`,{className:`text-sm`,"data-testid":`deleted-devices-summary`,children:i.status===`cleaned`?e(`systemPage.deletedDevices.cleaned`,`Deleted {{rows}} items of {{count}} devices.`,{rows:$e(i.devices),count:i.devices.length}):e(`systemPage.deletedDevices.found`,`{{count}} deleted devices still hold {{rows}} items.`,{rows:$e(i.devices),count:i.devices.length})}),c(oe,{columns:m,rows:i.devices,rowKey:e=>e.deviceId,emptyMessage:e(`systemPage.deletedDevices.none`,`No data belongs to a deleted device.`)}),i.unreachable.length>0?c(`p`,{className:`text-xs text-muted-foreground`,children:e(`systemPage.deletedDevices.unreachable`,`Not asked (unreachable): {{names}}`,{names:i.unreachable.join(`, `)})}):null]}):null]})}e();function tt(){let{t:e}=G(),r=s(),i=H(),{data:o,isLoading:l,isError:u}=je({}),d=ae(),f=n(()=>d.data??[],[d.data]),{data:p}=ce({},{refetchOnWindowFocus:!1}),m=n(()=>Xe(o??[],p?.locations),[o,p?.locations]),{data:h}=z({},{refetchOnWindowFocus:!1}),g=n(()=>We(h),[h]),{state:_,openNew:v,openEdit:y,close:b}=L(),[x,S]=me(`type`),C=()=>{S(null),b()},w=e=>{S(e),v()},T=e=>{S(null),y(e.id)},E=o??[],D=_.mode===`edit`?E.find(e=>e.id===_.id)??null:null;t(()=>{_.mode===`new`&&(x===null||x===``)&&(S(null),b())},[_.mode,x,b,S]),t(()=>{_.mode===`edit`&&!l&&D===null&&(S(null),b())},[_.mode,l,D,b,S]),t(()=>{_.mode===`closed`&&x!==null&&S(null)},[_.mode,x,S]);let O=ge({onSuccess:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]})}}),k=ke({onSuccess:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]})}}),A=async(t,n)=>{Ke(n)&&!await i({title:e(`system.storage.disable`,`Disable "{{displayName}}"?`,{displayName:t.displayName}),message:e(`system.storage.nothingIsDeletedSetThe`,`{{consequence}} Nothing is deleted — set the location back to Read-only or Active to bring its footage back.`,{consequence:Ge(n).consequence}),confirmLabel:e(`common.disable`,`Disable`),variant:`danger`})||k.mutate(Ye(t,{mode:n}))},j=async t=>{if(await i({title:e(`system.storage.deleteLocation`,`Delete location "{{displayName}}"?`,{displayName:t.displayName}),message:e(`system.storage.thisRemovesTheLocationRecord`,`This removes the location record. Files on disk are not deleted; the underlying directory or remote path stays untouched.`),confirmLabel:e(`common.delete`,`Delete`),variant:`danger`}))try{await O.mutateAsync({id:t.id}),_.mode===`edit`&&_.id===t.id&&C()}catch(n){await i({title:e(`system.storage.deleteAnyway`,`Delete anyway?`),message:e(`system.storage.forcingNote`,{error:n instanceof Error?n.message:String(n)}),confirmLabel:e(`system.storage.forceDelete`,`Force delete`),variant:`danger`})&&O.mutate({id:t.id,force:!0},{onSuccess:()=>{_.mode===`edit`&&_.id===t.id&&C()}})}},M=n(()=>{let e=new Map;for(let t of o??[]){let n=e.get(t.type);n?n.push(t):e.set(t.type,[t])}return e},[o]),N=l||d.isLoading,P=u||d.isError,F=_.mode===`new`&&x!==null&&x!==``,I=_.mode===`edit`&&D!==null;return a(He,{embedded:!0,children:[N&&c(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:e(`system.storage.loadingLocations`,`Loading locations…`)}),P&&c(`div`,{className:`text-xs text-danger`,children:e(`system.storage.failedToLoadStorageLocations`,`Failed to load storage locations.`)}),!N&&!P&&a(`div`,{className:`space-y-3`,children:[f.length===0&&c(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-4 text-center text-[11px] text-foreground-subtle italic`,children:e(`system.storage.noStorageLocationsDeclaredBy`,`No storage locations declared by any installed addon.`)}),f.map(e=>c(qe,{type:e.id,displayName:e.displayName,description:e.description,cardinality:e.cardinality,locations:M.get(e.id)??[],onAdd:w,onEdit:T,onDelete:e=>{j(e)},ownedBytesById:m,drainById:g,onSetMode:(e,t)=>{A(e,t)}},e.id))]}),F&&x!==null&&c(Ze,{initialType:x,onClose:C,onCreated:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]}),C()}}),I&&D!==null&&c(Je,{location:D,onClose:C,onSaved:()=>{r.invalidateQueries({queryKey:[[`storage`,`listLocations`]]}),C()}})]})}var nt={settings:{labelKey:`helpers.backupDatabases.settings.label`,descriptionKey:`helpers.backupDatabases.settings.description`},events:{labelKey:`helpers.backupDatabases.events.label`,descriptionKey:`helpers.backupDatabases.events.description`},history:{labelKey:`helpers.backupDatabases.history.label`,descriptionKey:`helpers.backupDatabases.history.description`}},rt=Object.keys(nt),q=[`settings`];function it(){return W.t(`helpers.backupDatabases.notCreated`)}function J(e){return W.t(nt[e].labelKey)}function at(e){return W.t(nt[e].descriptionKey)}function Y(e){let t=new Set(e);return rt.filter(e=>t.has(e))}function X(e){return e!==void 0&&e.length>0?Y(e):q}function ot(e){return Y(e)}function st(e,t){return t===void 0||!t.answered?`unknown`:t.databases.includes(e)?`present`:`absent`}function ct(e,t,n){return st(e,t)===`absent`&&!n.has(e)}function lt(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function ut(e){return!e.includes(`settings`)}function dt(e){return{databases:[...ot(e)]}}function ft(e,t){return e!==void 0&&e.length>0?Y(e):t!==void 0&&t.length>0?Y(t.map(e=>e.databaseId??`settings`)):q}function Z({databases:e}){let{t}=G();return a(`span`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`backup-database-badges`,children:[e.map(e=>c(be,{variant:e===`settings`?`primary`:`info`,style:`fill`,size:`sm`,children:J(e)},e)),ut(e)&&c(be,{variant:`warning`,style:`fill`,size:`sm`,children:t(`backup.backupDatabaseBadges.snapshotsOnly`,`Snapshots only`)})]})}e();var pt=[[`backup`,`listDestinations`]],mt=[`backup`,`listArchives`];function ht({destinationId:e,restoreSupported:t,onOpenRestoreWizard:o}){let{t:l}=G(),u=s(),d=H(),{data:p,isLoading:m,isError:h}=we({destinationId:e}),g=p??[],_=I({onSuccess:()=>{u.invalidateQueries({queryKey:[[...mt]]}),u.invalidateQueries({queryKey:pt})}}),y=i(async t=>{await d({title:l(`backup.archiveList.deleteThisArchive`,`Delete this archive?`),message:l(`backup.archiveList.permanentlyDeletesAndFrees`,`Permanently deletes "{{value1}}" and frees {{value2}}.`,{value1:t.label??t.id,value2:K(t.sizeBytes)}),confirmLabel:l(`common.delete`,`Delete`),variant:`danger`})&&_.mutate({destinationId:e,backupId:t.id})},[d,e,_,l]),[b,x]=r(null),S=i(async t=>{x(t.id);try{let n=await Ue(gt(e,t.id)),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${t.label??t.id}.tar.gz${t.encryption===void 0?``:`.csbk`}`,document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r)}finally{x(null)}},[e]),C=n(()=>[...g].toSorted((e,t)=>t.createdAt-e.createdAt),[g]);return m?c(`div`,{className:`text-xs text-foreground-subtle animate-pulse py-2`,children:l(`backup.archiveList.loadingArchives`,`Loading archives…`)}):h?c(`div`,{className:`text-xs text-danger py-2`,children:l(`backup.archiveList.failedToReadManifestFor`,`Failed to read manifest for this destination`)}):C.length===0?c(`div`,{className:`text-xs text-foreground-subtle italic py-2`,children:l(`backup.archiveList.noArchivesAtThisDestination`,`No archives at this destination yet.`)}):c(oe,{columns:[{key:`when`,header:l(`backup.archiveList.when`,`When`),sortValue:e=>e.createdAt,render:e=>c(`span`,{className:`tabular-nums`,children:_t(e.createdAt)})},{key:`label`,header:l(`backup.archiveList.label`,`Label`),sortValue:e=>e.label??null,render:e=>a(`span`,{className:`inline-flex items-center gap-1`,children:[e.encryption!==void 0&&c(D,{className:`h-3 w-3 text-success`,"aria-label":l(`backup.archiveList.encryptedRestoreNeedsBackupKey`,`encrypted — restore needs backup key {{keyId}}`,{keyId:e.encryption.keyId})}),e.label??c(`span`,{className:`text-foreground-subtle italic`,children:`—`})]})},{key:`databases`,header:l(`backup.archiveList.databases`,`Databases`),nowrap:!1,notSortableReason:`Database badges`,render:e=>c(Z,{databases:X(e.databases)})},{key:`includes`,header:l(`backup.archiveList.files`,`Files`),nowrap:!1,notSortableReason:`Location list`,render:e=>e.locations.length>0?c(`span`,{className:`text-foreground-subtle`,children:e.locations.join(`, `)}):c(`span`,{className:`text-foreground-subtle italic`,children:l(`common.none`)})},{key:`size`,header:l(`backup.archiveList.size`,`Size`),align:`right`,sortValue:e=>e.sizeBytes,render:e=>c(`span`,{className:`tabular-nums`,children:K(e.sizeBytes)})},{key:`actions`,header:``,align:`right`,notSortableReason:`Actions`,render:n=>a(`span`,{className:`flex items-center justify-end gap-1`,children:[a(V,{variant:`ghost`,size:`sm`,onClick:()=>{S(n)},disabled:b===n.id,title:l(`backup.archiveList.downloadArchive`,`Download archive`),children:[b===n.id?c(T,{className:`h-3 w-3 animate-spin`}):c(v,{className:`h-3 w-3`}),l(`backup.archiveList.download`,`Download`)]}),t&&o&&a(V,{variant:`ghost`,size:`sm`,onClick:()=>o({destinationId:e,archiveId:n.id}),title:l(`backup.archiveList.restoreFromThisArchive`,`Restore from this archive`),children:[c(k,{className:`h-3 w-3`}),l(`backup.archiveList.restore`,`Restore`)]}),c(U,{variant:`ghost`,size:`sm`,icon:f,"aria-label":l(`backup.archiveList.delete`,`Delete {{value1}}`,{value1:n.label??n.id}),disabled:_.isPending,onClick:()=>{y(n)}})]})}],rows:C,rowKey:e=>e.id,minWidthPx:760,emptyMessage:l(`backup.archiveList.noArchivesAtThisDestination`,`No archives at this destination yet.`)})}function gt(e,t){return g(`/api/backup/download/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}function _t(e){return new Date(e).toLocaleString(void 0,{day:`2-digit`,month:`short`,year:`numeric`,hour:`2-digit`,minute:`2-digit`})}e();var vt=[[`backup`,`listSchedules`]];function yt({onEdit:e,onOpenRestoreWizard:t}){let{t:o}=G(),{data:s,isLoading:l,isError:u,error:d,refetch:f}=ve(),p=s??[],m=Oe().data??[],h=n(()=>{let e=new Map;for(let t of m)e.set(t.id,t);return e},[m]),[g,_]=r(null),v=i(e=>{_(t=>t===e?null:e)},[]),y=g===null?null:p.find(e=>e.id===g)??null,b=n(()=>bt({destById:h,expandedId:g,onToggleExpand:v,onEdit:e}),[h,g,v,e]);return l?a(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle animate-pulse`,children:[c(T,{className:`h-3.5 w-3.5 animate-spin`}),o(`backup.backupEntriesTable.loadingBackupEntries`,`Loading backup entries…`)]}):u?c(R,{title:o(`backup.backupEntriesTable.failedToLoadBackupEntries`,`Failed to load backup entries`),message:d instanceof Error?d.message:o(`backup.backupEntriesTable.unknownError`,`Unknown error`),onRetry:()=>void f()}):p.length===0?c(he,{icon:M,title:o(`backup.backupEntriesTable.noBackupEntriesYet`,`No backup entries yet`),description:o(`backup.backupEntriesTable.createOneToScheduleBackups`,`Create one to schedule backups across one or more storage locations.`)}):a(`div`,{className:`space-y-2`,children:[c(oe,{columns:b,rows:p,rowKey:e=>e.id,minWidthPx:980,maxBodyHeight:Me,emptyMessage:o(`backup.backupEntriesTable.noBackupEntriesYet`,`No backup entries yet`),onRowClick:t=>e(t)}),y!==null&&c(Dt,{row:y,destById:h,...t?{onOpenRestoreWizard:t}:{}})]})}function bt(e){return[{key:`expand`,header:``,width:`w-8`,nowrap:!0,notSortableReason:`Expand control`,render:t=>{let n=e.expandedId===t.id;return c(U,{variant:`ghost`,size:`sm`,icon:n?A:j,"aria-label":n?W.t(`backup.backupEntriesTable.hideArchives`,`Hide archives`):W.t(`backup.backupEntriesTable.showArchives`,`Show archives`),"aria-expanded":n,onClick:n=>{n.stopPropagation(),e.onToggleExpand(t.id)}})}},{key:`entry`,header:W.t(`backup.backupEntriesTable.entry`,`Entry`),sortValue:e=>e.label,render:e=>a(`span`,{className:`flex min-w-0 flex-col`,children:[c(`span`,{className:`truncate font-medium text-foreground`,children:e.label||W.t(`backup.backupEntriesTable.unnamed`,`(unnamed)`)}),e.lastRunAt!==void 0&&c(`span`,{className:`text-[10px] text-foreground-subtle`,children:W.t(`backup.backupEntriesTable.lastRun`,{when:new Date(e.lastRunAt).toLocaleString()})})]})},{key:`enabled`,header:W.t(`backup.backupEntriesTable.enabled`,`Enabled`),width:`w-20`,nowrap:!0,sortValue:e=>+!!e.enabled,render:e=>c(`span`,{onClick:e=>e.stopPropagation(),children:c(wt,{row:e})})},{key:`databases`,header:W.t(`backup.backupEntriesTable.backsUp`,`Backs up`),nowrap:!1,notSortableReason:`Database badges`,render:e=>c(Z,{databases:X(e.databases)})},{key:`locations`,header:W.t(`backup.backupEntriesTable.locations`,`Locations`),nowrap:!1,notSortableReason:`Location chips`,render:t=>c(xt,{row:t,destById:e.destById})},{key:`retention`,header:W.t(`backup.backupEntriesTable.retention`,`Retention`),width:`w-24`,nowrap:!0,sortValue:e=>e.retentionCount,render:e=>c(`span`,{onClick:e=>e.stopPropagation(),children:c(Tt,{row:e})})},{key:`schedule`,header:W.t(`backup.backupEntriesTable.schedule`,`Schedule`),width:`w-48`,nowrap:!0,sortValue:e=>e.cron,render:e=>c(St,{row:e})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Actions`,render:t=>c(`span`,{onClick:e=>e.stopPropagation(),children:c(Et,{row:t,onEdit:()=>e.onEdit(t)})})}]}function xt({row:e,destById:t}){let{t:n}=G();return e.locationIds.length===0?c(`span`,{className:`text-[11px] italic text-danger`,children:n(`backup.backupEntriesTable.noLocations`,`No locations`)}):c(`span`,{className:`flex flex-wrap gap-1`,children:e.locationIds.map(e=>c(`span`,{className:`inline-flex items-center rounded border border-border bg-background px-1.5 py-0.5 text-[10px] text-foreground`,title:e,children:t.get(e)?.displayName??e},e))})}function St({row:e}){let{t}=G(),n=e.cron.trim().length>0;return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[a(`span`,{className:`inline-flex items-center gap-1`,children:[c(M,{className:`h-3 w-3 text-foreground-subtle`}),c(`span`,{className:`font-mono text-[11px] text-foreground`,children:n?e.cron:t(`backup.backupEntriesTable.manual`,`Manual`)})]}),n&&e.nextRunAt!==void 0&&c(`span`,{className:`text-[10px] text-foreground-subtle`,children:W.t(`common.nextRun`,{when:new Date(e.nextRunAt).toLocaleString()})})]})}function Ct(e){return n(()=>({id:e.id,label:e.label,cron:e.cron,locationIds:[...e.locationIds],retentionCount:e.retentionCount,...e.dataSources?{dataSources:[...e.dataSources]}:{},...e.databases?{databases:[...e.databases]}:{}}),[e])}function wt({row:e}){let{t}=G(),n=s(),r=Ae({onSuccess:()=>{n.invalidateQueries({queryKey:vt})}}),i=Ct(e);return c(`label`,{className:`inline-flex cursor-pointer items-center`,children:c(`input`,{type:`checkbox`,className:`accent-primary`,checked:e.enabled,disabled:r.isPending,onChange:e=>r.mutate({...i,enabled:e.target.checked}),"aria-label":t(`backup.backupEntriesTable.enable`,`Enable {{value1}}`,{value1:e.label||e.id})})})}function Tt({row:e}){let{t:n}=G(),i=s(),a=Ae({onSuccess:()=>{i.invalidateQueries({queryKey:vt})}}),o=Ct(e),[l,u]=r(String(e.retentionCount));return t(()=>{u(String(e.retentionCount))},[e.retentionCount]),c(Fe,{type:`number`,min:1,max:1e3,value:l,disabled:a.isPending,onChange:e=>u(e.target.value),onBlur:()=>{let t=Number.parseInt(l,10);if(Number.isNaN(t)||t<1){u(String(e.retentionCount));return}t!==e.retentionCount&&a.mutate({...o,enabled:e.enabled,retentionCount:t})},onKeyDown:t=>{t.key===`Enter`&&t.target.blur(),t.key===`Escape`&&u(String(e.retentionCount))},className:`w-16`,"aria-label":n(`backup.backupEntriesTable.retentionFor`,`Retention for {{value1}}`,{value1:e.label||e.id})})}function Et({row:e,onEdit:t}){let{t:n}=G(),r=s(),i=H(),o=Se({onSuccess:()=>{r.invalidateQueries({queryKey:vt})}}),u=Ce({onMutate:()=>{r.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})},onSuccess:()=>{r.invalidateQueries({queryKey:[[`backup`,`listArchives`]]}),r.invalidateQueries({queryKey:[[`backup`,`listDestinations`]]}),r.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})}}),p=()=>{e.locationIds.length!==0&&u.mutate({destinations:[...e.locationIds],...e.dataSources&&e.dataSources.length>0?{locations:[...e.dataSources]}:{},label:e.label,retentionCount:e.retentionCount,databases:[...X(e.databases)]})},m=async()=>{await i({title:n(`backup.backupEntriesTable.deleteBackupEntry`,`Delete backup entry?`),message:n(`backup.backupEntriesTable.willStopRunningExistingArchives`,`"{{value1}}" will stop running. Existing archives are kept.`,{value1:e.label||e.id}),confirmLabel:n(`common.delete`,`Delete`),variant:`warning`})&&o.mutate({id:e.id})};return a(`span`,{className:`flex items-center justify-end gap-1.5`,children:[a(V,{size:`sm`,type:`button`,onClick:p,disabled:u.isPending||e.locationIds.length===0,title:n(`backup.backupEntriesTable.runThisEntryNow`,`Run this entry now`),children:[u.isPending?c(T,{className:`h-3 w-3 animate-spin`}):c(l,{className:`h-3 w-3`}),n(`backup.backupEntriesTable.runNow`,`Run now`)]}),c(U,{variant:`ghost`,size:`sm`,icon:d,"aria-label":n(`backup.backupEntriesTable.edit`,`Edit {{value1}}`,{value1:e.label||e.id}),onClick:t}),c(U,{variant:`ghost`,size:`sm`,icon:f,"aria-label":n(`backup.backupEntriesTable.delete`,`Delete {{value1}}`,{value1:e.label||e.id}),disabled:o.isPending,onClick:()=>{m()}})]})}function Dt({row:e,destById:t,onOpenRestoreWizard:n}){let{t:r}=G();return a(`div`,{className:`space-y-4 rounded-lg border border-border bg-background/30 px-4 py-3`,children:[c(`p`,{className:`text-[11px] font-medium text-foreground-subtle`,children:r(`backup.backupEntriesTable.archivesFor`,{name:e.label||e.id})}),e.locationIds.length===0&&c(`p`,{className:`text-xs italic text-foreground-subtle`,children:r(`backup.backupEntriesTable.thisEntryHasNoLocations`,`This entry has no locations selected.`)}),e.locationIds.map(e=>a(`div`,{className:`space-y-1.5`,children:[c(`div`,{className:`text-[11px] font-medium text-foreground-subtle`,children:t.get(e)?.displayName??e}),c(ht,{destinationId:e,restoreSupported:t.get(e)?.restoreSupported??!0,...n?{onOpenRestoreWizard:n}:{}})]},e))]})}function Ot({selected:e,onChange:t,disabled:n=!1,testId:r=`backup-databases`}){let{t:i}=G(),o=_e().data,s=e.size>0&&ut(Y(e)),l=e.size===0?`Pick at least one.`:s?`Snapshots only: configuration and files are not part of this backup.`:null;return c(B,{label:i(`backup.backupDatabasePicker.whatToBackUp`,`What to back up`),required:!0,...l===null?{}:{description:l},children:c(`div`,{className:`divide-y divide-border rounded border border-border bg-background`,"data-testid":r,children:rt.map(s=>{let l=st(s,o),u=n||ct(s,o,e);return a(`label`,{className:`flex items-start gap-2 px-3 py-2 text-xs ${u?`opacity-60`:`cursor-pointer hover:bg-primary/5`}`,children:[c(ye,{checked:e.has(s),disabled:u,onChange:()=>t(lt(e,s)),"data-testid":`${r}-${s}`}),a(`span`,{className:`min-w-0 flex-1`,children:[a(`span`,{className:`flex flex-wrap items-center gap-1.5 text-foreground`,children:[J(s),l===`absent`&&c(be,{variant:`neutral`,size:`sm`,children:i(`backup.backupDatabasePicker.notCreatedYet`,`Not created yet`)})]}),c(`span`,{className:`block text-[11px] text-foreground-subtle`,children:l===`absent`?it():at(s)})]})]},s)})})})}e();function kt({onClose:e}){let{t}=G(),n=s(),[i,o]=r(new Set(q)),u=Ce({onMutate:()=>{n.invalidateQueries({queryKey:[[`backup`,`listRuns`]]})},onSuccess:()=>{n.invalidateQueries({queryKey:[[`backup`,`listArchives`]]}),n.invalidateQueries({queryKey:[[`backup`,`listDestinations`]]}),n.invalidateQueries({queryKey:[[`backup`,`listRuns`]]}),e()}});return c(ue,{open:!0,onOpenChange:t=>!t&&e(),children:a(ee,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(le,{children:[c(de,{children:t(`backup.backupNowDialog.backUpNow`,`Back up now`)}),c(`p`,{className:`text-xs text-foreground-subtle`,children:t(`backup.backupNowDialog.runsOnceAndWritesThe`,`Runs once and writes the archive to every enabled backup location.`)})]}),c(Te,{children:a(`div`,{className:`p-4`,children:[c(Ot,{selected:i,onChange:o,disabled:u.isPending,testId:`backup-now-databases`}),u.error&&c(`p`,{role:`alert`,className:`pt-2 text-xs text-danger`,children:u.error.message})]})}),a(se,{children:[c(V,{variant:`outline`,size:`sm`,onClick:e,children:t(`common.cancel`,`Cancel`)}),a(V,{size:`sm`,onClick:()=>{i.size!==0&&u.mutate(dt(i))},disabled:i.size===0||u.isPending,"data-testid":`backup-now-run`,children:[u.isPending?c(T,{className:`h-3.5 w-3.5 animate-spin`}):c(l,{className:`h-3.5 w-3.5`}),t(`backup.backupNowDialog.backUpNow`,`Back up now`)]})]})]})})}e();function At(e){return e===null?`—`:new Date(e).toLocaleString()}function jt(e){let t=new Blob([`${e.secretKey}\n`],{type:`text/plain`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=`camstack-backup-key-${e.keyId}.txt`,r.click(),URL.revokeObjectURL(n)}function Mt({revealed:e,onDone:t}){let{t:n}=G(),[i,o]=r(!1),[s,l]=r(!1);return c(ue,{open:!0,onOpenChange:e=>!e&&i&&t(),children:a(ee,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,className:`border-danger/40`,"aria-labelledby":`backup-key-title`,children:[c(le,{children:c(de,{id:`backup-key-title`,children:n(`backup.encryptionCard.yourKey`,{keyId:e.keyId})})}),a(Te,{className:`space-y-3`,children:[a(`p`,{className:`flex items-start gap-2 rounded-md border border-danger/40 bg-danger/10 p-2 text-xs text-foreground`,children:[c(h,{className:`mt-0.5 h-4 w-4 shrink-0 text-danger`}),c(`span`,{children:n(`backup.backupEncryptionCard.thisKeyIsShownOnly`,`This key is shown only once. CamStack does not keep it — not the hub, not its database, not its backups. Without it, an encrypted backup cannot be restored by anyone, including you. Store it in a password manager or print it, away from this server.`)})]}),c(`div`,{className:`break-all rounded-md border border-border bg-background p-2 font-mono text-xs text-foreground select-all`,children:e.secretKey}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(V,{size:`sm`,variant:`outline`,onClick:()=>{navigator.clipboard?.writeText(e.secretKey).then(()=>l(!0))},children:[c(b,{className:`mr-1 h-3.5 w-3.5`}),s?n(`backup.backupEncryptionCard.copied`,`Copied`):n(`common.copy`,`Copy`)]}),a(V,{size:`sm`,variant:`outline`,onClick:()=>jt(e),children:[c(v,{className:`mr-1 h-3.5 w-3.5`}),n(`backup.backupEncryptionCard.downloadAsFile`,`Download as file`)]})]}),a(`label`,{className:`flex items-center gap-2 text-xs text-foreground`,children:[c(`input`,{type:`checkbox`,checked:i,onChange:e=>o(e.target.checked),className:`accent-primary`}),n(`backup.backupEncryptionCard.iHaveStoredThisKey`,`I have stored this key somewhere safe, off this server.`)]})]}),c(se,{children:c(V,{size:`sm`,disabled:!i,onClick:t,children:n(`backup.backupEncryptionCard.iHaveStoredIt`,`I have stored it`)})})]})})}function Nt(){let{t:e}=G(),t=De(),n=xe(),i=Le(),s=H(),[l,u]=r(null),[d,f]=r(null),p=t.data?.enabled??!1,m=t.data?.active??null,h=(t.data?.keys??[]).filter(e=>e.retiredAt!==null),g=async()=>{if(await s({title:p?e(`backup.backupEncryptionCard.replaceTheBackupKey`,`Replace the backup key`):e(`backup.backupEncryptionCard.encryptBackups`,`Encrypt backups`),message:p?e(`backup.backupEncryptionCard.aNewKeyIsGenerated`,`A new key is generated and shown once; new backups are encrypted to it. Older backups keep needing the key they were made with — keep that one too.`):e(`backup.backupEncryptionCard.aBackupKeyIsGenerated`,`A backup key is generated and shown once. Every new backup is encrypted to it, and restoring one will ask for it. Existing backups stay as they are.`),confirmLabel:p?e(`backup.backupEncryptionCard.generateANewKey`,`Generate a new key`):e(`backup.backupEncryptionCard.generateTheKey`,`Generate the key`),variant:`warning`})){f(null);try{let e=await n.mutateAsync({});u({keyId:e.keyId,secretKey:e.secretKey})}catch(e){f(e instanceof Error?e.message:String(e))}}},_=async()=>{if(await s({title:e(`backup.backupEncryptionCard.turnBackupEncryptionOff`,`Turn backup encryption off`),message:e(`backup.backupEncryptionCard.newBackupsWillBeWritten`,`New backups will be written unencrypted. Existing encrypted backups still need their key to be restored.`),confirmLabel:e(`backup.backupEncryptionCard.turnOff`,`Turn off`),variant:`danger`})){f(null);try{await i.mutateAsync({}),t.refetch()}catch(e){f(e instanceof Error?e.message:String(e))}}};return a(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-4`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`flex items-center gap-2`,children:[p?c(D,{className:`h-4 w-4 text-success`}):c(C,{className:`h-4 w-4 text-foreground-subtle`}),c(`h2`,{className:`text-sm font-semibold text-foreground`,children:e(`backup.backupEncryptionCard.encryption`,`Encryption`)}),c(`span`,{className:`text-xs text-foreground-subtle`,children:p&&m!==null?e(`backup.backupEncryptionCard.onKeySince`,`On — key {{keyId}}, since {{value2}}`,{keyId:m.keyId,value2:At(m.createdAt)}):e(`backup.backupEncryptionCard.offBackupsAreNotEncrypted`,`Off — backups are not encrypted`)})]}),c(`div`,{className:`flex gap-2`,children:p?a(o,{children:[c(V,{size:`sm`,variant:`outline`,disabled:n.isPending,onClick:()=>void g(),children:e(`backup.backupEncryptionCard.replaceKey`,`Replace key`)}),c(V,{size:`sm`,variant:`outline`,disabled:i.isPending,onClick:()=>void _(),children:e(`backup.backupEncryptionCard.turnOff`,`Turn off`)})]}):c(V,{size:`sm`,disabled:n.isPending,onClick:()=>void g(),children:e(`backup.backupEncryptionCard.enableEncryption`,`Enable encryption`)})})]}),c(`p`,{className:`text-xs text-foreground-subtle`,children:e(`backup.backupEncryptionCard.archivesAreEncryptedOnThis`,`Archives are encrypted on this server before they reach any destination. The server keeps only a public key, so it can encrypt scheduled backups but cannot decrypt them — only your backup key can. Covers the database snapshot, config.yaml, addon data (HomeKit pairing, Matter fabric, Tailscale state) and TLS.`)}),h.length>0&&a(`div`,{className:`text-xs`,children:[c(`p`,{className:`text-foreground-subtle`,children:e(`backup.backupEncryptionCard.olderKeysBackupsMadeWith`,`Older keys (backups made with them still need them):`)}),c(`ul`,{className:`font-mono text-foreground`,children:h.map(e=>a(`li`,{children:[e.keyId,` · `,At(e.createdAt),` → `,At(e.retiredAt)]},e.keyId))})]}),d!==null&&c(`p`,{className:`text-xs text-danger`,children:d}),l!==null&&c(Mt,{revealed:l,onDone:()=>{u(null),t.refetch()}})]})}e();var Pt=[{id:`manual`,labelKey:`backup.cronEditor.presetManual`,cron:``},{id:`hourly`,labelKey:`backup.cronEditor.presetHourly`,cron:`0 * * * *`,descriptionKey:`backup.cronEditor.presetHourlyDesc`},{id:`every-3h`,labelKey:`backup.cronEditor.preset3h`,cron:`0 */3 * * *`,description:`00:00, 03:00, 06:00, 09:00 …`},{id:`every-6h`,labelKey:`backup.cronEditor.preset6h`,cron:`0 */6 * * *`,description:`00:00, 06:00, 12:00, 18:00`},{id:`daily-3am`,labelKey:`backup.cronEditor.presetDaily`,cron:`0 3 * * *`,descriptionKey:`backup.cronEditor.presetDailyDesc`},{id:`weekly-sun`,labelKey:`backup.cronEditor.presetWeekly`,cron:`0 3 * * 0`,descriptionKey:`backup.cronEditor.presetWeeklyDesc`}];function Ft(e){let t=e.trim();for(let e of Pt)if(e.cron===t)return e.id;return`custom`}function It({value:e,onChange:n,previewCount:i=5,disabled:o=!1}){let{t:s}=G(),l=Ft(e),[u,d]=r(l===`custom`);t(()=>{l!==`custom`&&d(!1)},[l]);let f=zt(e,250),p=Ee({cron:f,count:i},{enabled:f.trim().length>0}),m=p.data??null,h=e=>{d(!1),n(e.cron)},g=u||l===`custom`;return a(`div`,{className:`space-y-3`,children:[a(`div`,{className:`space-y-1`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:s(`backup.cronEditor.schedulePreset`,`Schedule preset`)}),a(`div`,{className:`flex flex-wrap gap-1.5`,children:[Pt.map(e=>c(`button`,{type:`button`,onClick:()=>h(e),disabled:o,className:`rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 `+(!u&&l===e.id?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground`),title:e.descriptionKey===void 0?e.description??s(e.labelKey):s(e.descriptionKey),children:s(e.labelKey)},e.id)),c(`button`,{type:`button`,onClick:()=>{d(!0),e.trim().length===0&&n(`0 3 * * *`)},disabled:o,className:`rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 `+(g?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground`),children:s(`backup.cronEditor.custom`,`Custom…`)})]})]}),g&&a(`div`,{className:`space-y-1`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:s(`backup.cronEditor.cronExpression5FieldPosix`,`Cron expression (5-field POSIX)`)}),c(`input`,{type:`text`,value:e,onChange:e=>n(e.target.value),disabled:o,placeholder:`0 3 * * *`,spellCheck:!1,className:`w-full rounded border border-border bg-background px-2 py-1.5 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`}),a(`p`,{className:`text-[10px] text-foreground-subtle`,children:[s(`backup.cronEditor.format`,`Format:`),` `,c(ze,{i18nKey:`backup.cronEditor.formatLine`,components:{code:c(`span`,{className:`font-mono`})}})]})]}),c(Lt,{cron:f,preview:m,loading:p.isFetching})]})}function Lt({cron:e,preview:t,loading:n}){let{t:r}=G();return n&&t===null?a(`div`,{className:`flex items-center gap-2 rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:[c(T,{className:`h-3 w-3 animate-spin`}),r(`backup.cronEditor.validating`,`Validating…`)]}):t===null?null:t.ok?t.nextRuns.length===0?c(`div`,{className:`rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:r(`backup.cronEditor.noFutureRunsMatchThis`,`No future runs match this expression.`)}):a(`div`,{className:`space-y-1`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:r(`backup.cronEditor.nextRuns`,`Next runs`)}),c(`ul`,{className:`rounded border border-border bg-background/40 divide-y divide-border`,children:t.nextRuns.map((e,t)=>a(`li`,{className:`flex items-center justify-between px-3 py-1.5 text-[11px]`,children:[c(`span`,{className:`text-foreground tabular-nums`,children:new Date(e).toLocaleString()}),c(`span`,{className:`text-foreground-subtle text-[10px] tabular-nums`,children:Rt(e)})]},`${e}-${t}`))})]}):c(`div`,{className:`rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:t.error??r(`backup.cronEditor.invalidCronExpression`,`Invalid cron expression`)})}function Rt(e){let t=e-Date.now();if(t<=0)return W.t(`helpers.relativeTime.now`);let n=Math.floor(t/1e3);if(n<60)return W.t(`helpers.relativeTime.inSeconds`,{count:n});let r=Math.floor(n/60);if(r<60)return W.t(`helpers.relativeTime.inMinutes`,{count:r});let i=Math.floor(r/60);if(i<24)return W.t(`helpers.relativeTime.inHours`,{count:i});let a=Math.floor(i/24);return W.t(`helpers.relativeTime.inDays`,{count:a})}function zt(e,i){let[a,o]=r(e),s=n(()=>e,[e]);return t(()=>{let e=setTimeout(()=>o(s),i);return()=>clearTimeout(e)},[s,i]),a}e();var Bt=[[`backup`,`listSchedules`]];function Vt({entry:e,onClose:t,onSaved:i}){let{t:o}=G(),l=s(),u=Oe(),d=u.data??[],[f,p]=r(e?.label??``),[m,h]=r(e?.cron??`0 3 * * *`),[g,_]=r(e?.enabled??!0),[v,y]=r(String(e?.retentionCount??7)),[b,x]=r(new Set(e?.locationIds??[])),[S,C]=r(new Set(e===null?q:X(e.databases))),w=Ae({onSuccess:()=>{l.invalidateQueries({queryKey:Bt}),i()}}),E=e=>{x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},D=Number.parseInt(v,10),O=n(()=>f.trim().length>0&&b.size>0&&S.size>0&&!Number.isNaN(D)&&D>=1&&D<=1e3,[f,b,S,D]),k=()=>{O&&w.mutate({...e?{id:e.id}:{},label:f.trim(),cron:m.trim(),enabled:g,locationIds:Array.from(b),retentionCount:D,databases:[...ot(S)]})},A=w.error instanceof Error?w.error.message:null;return c(ne,{open:!0,onClose:t,title:e?o(`backup.backupEntryModal.editBackupEntry`,`Edit backup entry`):o(`backup.backupEntryModal.newBackupEntry`,`New backup entry`),icon:M,error:A,width:`lg`,testId:`backup-entry-form`,footer:a(V,{size:`sm`,type:`button`,onClick:k,disabled:!O||w.isPending,children:[w.isPending?c(T,{className:`h-3.5 w-3.5 animate-spin`}):null,e?o(`common.save`,`Save`):o(`backup.backupEntryModal.createEntry`,`Create entry`)]}),children:a(`div`,{className:`space-y-4`,children:[c(B,{label:o(`backup.backupEntryModal.name`,`Name`),required:!0,children:c(Fe,{value:f,onChange:e=>p(e.target.value),placeholder:o(`backup.backupEntryModal.nightlyOffsite`,`Nightly offsite`),autoFocus:!0,"data-testid":`backup-entry-name`})}),a(B,{label:o(`backup.backupEntryModal.locationsSelected`,`Locations ({{value1}} selected)`,{value1:String(b.size)}),required:!0,children:[u.isLoading&&a(`div`,{className:`flex items-center gap-2 px-1 py-2 text-xs text-foreground-subtle`,children:[c(T,{className:`h-3.5 w-3.5 animate-spin`}),o(`backup.backupEntryModal.loadingLocations`,`Loading locations…`)]}),!u.isLoading&&d.length===0&&c(`div`,{className:`rounded border border-border bg-background px-3 py-2 text-xs text-foreground-subtle italic`,children:o(`backup.backupEntryModal.noBackupsStorageLocationsConfigured`,"No `backups` storage locations configured. Add one in Settings → Storage first.")}),d.length>0&&c(`div`,{className:`max-h-52 divide-y divide-border overflow-y-auto rounded border border-border bg-background`,children:d.map(e=>a(`label`,{className:`flex cursor-pointer items-center justify-between px-3 py-2 text-xs hover:bg-primary/5`,children:[a(`div`,{className:`flex items-center gap-2`,children:[c(`input`,{type:`checkbox`,checked:b.has(e.id),onChange:()=>E(e.id),className:`accent-primary`}),c(`span`,{className:`text-foreground`,children:e.displayName})]}),a(`div`,{className:`flex items-center gap-1.5`,children:[c(`span`,{className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-foreground-subtle`,children:e.kind}),c(`span`,{className:`font-mono text-[10px] text-foreground-subtle`,children:e.id})]})]},e.id))})]}),c(Ot,{selected:S,onChange:C,disabled:w.isPending,testId:`backup-entry-databases`}),a(`div`,{className:`grid grid-cols-2 gap-3`,children:[c(B,{label:o(`backup.backupEntryModal.retentionArchivesKept`,`Retention (archives kept)`),required:!0,children:c(Fe,{type:`number`,min:1,max:1e3,value:v,onChange:e=>y(e.target.value),"data-testid":`backup-entry-retention`})}),c(B,{label:o(`backup.backupEntryModal.enabled`,`Enabled`),description:o(`backup.backupEntryModal.runOnScheduleWhenChecked`,`Run on schedule when checked.`),children:a(`label`,{className:`inline-flex cursor-pointer items-center gap-2 py-1.5 text-xs text-foreground`,children:[c(`input`,{type:`checkbox`,checked:g,onChange:e=>_(e.target.checked),className:`accent-primary`,"data-testid":`backup-entry-enabled`}),c(`span`,{children:o(`backup.backupEntryModal.runOnSchedule`,`Run on schedule`)})]})})]}),c(B,{label:o(`backup.backupEntryModal.schedule`,`Schedule`),children:c(It,{value:m,onChange:h,disabled:w.isPending})})]})})}e();var Ht=2e3,Ut=5e3;function Q(e){return e.state===`queued`||e.state===`running`}function Wt(e){if(e.state===`queued`)return{title:W.t(`backup.backupRunsPanel.cancelQueuedBackupRun`,`Cancel queued backup run?`),message:W.t(`backup.backupRunsPanel.thisRunHasNotStarted`,`This run has not started. Cancelling removes it from the queue — nothing has been written, nothing is deleted.`),confirmLabel:W.t(`backup.backupRunsPanel.cancelRun`,`Cancel run`),variant:`warning`};let t=e.completedDestinationIds.length,n=t>0?`${t===1?`The 1 destination`:`The ${t} destinations`} that already completed KEEP${t===1?`S`:``} the archive.`:`No destination has completed yet, so nothing will be kept.`;return{title:W.t(`backup.backupRunsPanel.stopThisBackupRun`,`Stop this backup run?`),message:W.t(`backup.backupRunsPanel.theHalfWrittenStagingArchive`,`The half-written staging archive is deleted and the destination currently uploading discards its partial copy. {{keptSentence}}`,{keptSentence:n}),confirmLabel:W.t(`backup.backupRunsPanel.stopRun`,`Stop run`),variant:`danger`}}function Gt(){let e=H(),[t,n]=r(null),a=Ie(void 0,{refetchInterval:e=>(e.state.data??[]).some(Q)?Ht:Ut}),o=pe({onSettled:()=>{n(null),a.refetch()}}),s=i(async t=>{await e(Wt(t))&&(n(t.id),o.mutate({runId:t.id}))},[e,o]);return c(Kt,{queryState:a.isError?`error`:a.data===void 0?`pending`:`ready`,runs:a.data??[],cancelingId:t,onCancelRequest:e=>{s(e)},now:Date.now()})}function Kt({queryState:e,runs:t,cancelingId:n,onCancelRequest:r,now:i}){let{t:o}=G(),s=e===`ready`&&t.some(Q),l=t.filter(e=>e.state===`running`),u=t.filter(e=>e.state===`queued`),d=t.filter(e=>!Q(e)),f=[...l,...u,...d];return a(`section`,{className:`rounded-lg border border-border bg-surface`,children:[a(`div`,{className:`flex items-center gap-2 px-3 py-2 border-b border-border`,children:[c(`h2`,{className:`text-xs font-semibold text-foreground`,children:o(`backup.backupRunsPanel.runs`,`Runs`)}),s&&a(`span`,{className:`inline-flex items-center gap-1 text-[10px] font-medium text-primary`,title:o(`backup.backupRunsPanel.aBackupRunIsIn`,`A backup run is in progress`),children:[c(`span`,{className:`h-1.5 w-1.5 rounded-full bg-primary animate-pulse`}),o(`backup.runsPanel.live`)]}),c(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:o(`backup.backupRunsPanel.oneRunExecutesAtA`,`One run executes at a time — queued runs wait in line.`)})]}),e===`pending`&&c(`div`,{className:`px-3 py-2.5 text-xs text-foreground-subtle animate-pulse`,children:o(`backup.backupRunsPanel.checkingForBackupRuns`,`Checking for backup runs…`)}),e===`error`&&c(`div`,{className:`px-3 py-2.5 text-xs text-danger`,children:o(`backup.backupRunsPanel.couldNotReadBackupRuns`,`Could not read backup runs — the orchestrator did not answer.`)}),e===`ready`&&t.length===0&&c(`div`,{className:`px-3 py-2.5 text-xs text-foreground-subtle italic`,children:o(`backup.backupRunsPanel.noBackupRunsYetRuns`,`No backup runs yet. Runs appear here the moment one starts — manual or scheduled.`)}),e===`ready`&&t.length>0&&c(`div`,{className:`overflow-x-auto`,children:a(`table`,{className:`w-full text-xs min-w-[720px]`,children:[c(`thead`,{children:a(`tr`,{className:`text-foreground-subtle bg-background/30`,children:[c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.run`,`Run`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.state`,`State`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.progress`,`Progress`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.destinations`,`Destinations`)}),c(`th`,{className:`text-left px-3 py-1.5 font-medium`,children:o(`backup.backupRunsPanel.timing`,`Timing`)}),c(`th`,{className:`text-right px-3 py-1.5 font-medium w-28`,children:o(`backup.backupRunsPanel.actions`,`Actions`)})]})}),c(`tbody`,{children:f.map(e=>c(qt,{run:e,canceling:n===e.id,onCancelRequest:r,now:i},e.id))})]})})]})}function qt({run:e,canceling:t,onCancelRequest:n,now:r}){let{t:i}=G(),o=Q(e);return a(`tr`,{className:`border-t border-border hover:bg-primary/5 align-top`,children:[a(`td`,{className:`px-3 py-2`,children:[c(`div`,{className:`text-foreground`,children:e.label??c(`span`,{className:`text-foreground-subtle italic`,children:i(`backup.runsPanel.manual`)})}),c(`div`,{className:`text-[10px] text-foreground-subtle font-mono`,title:e.id,children:e.id.slice(0,8)})]}),a(`td`,{className:`px-3 py-2`,children:[c(Jt,{run:e}),e.state===`failed`&&e.error!==void 0&&c(`div`,{className:`mt-1 text-[10px] text-danger max-w-56 truncate`,title:e.error,children:e.error})]}),c(`td`,{className:`px-3 py-2`,children:c(Yt,{run:e})}),c(`td`,{className:`px-3 py-2`,children:c(Xt,{run:e})}),c(`td`,{className:`px-3 py-2 text-foreground-subtle tabular-nums`,children:c(Zt,{run:e,now:r})}),c(`td`,{className:`px-3 py-2`,children:c(`div`,{className:`flex justify-end`,children:o&&a(`button`,{onClick:()=>n(e),disabled:t,className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50`,title:e.state===`queued`?i(`backup.backupRunsPanel.removeThisRunFromThe`,`Remove this run from the queue before it starts`):i(`backup.backupRunsPanel.stopThisRunTheHalf`,`Stop this run — the half-written archive is discarded`),children:[t?c(T,{className:`h-3 w-3 animate-spin`}):c(_,{className:`h-3 w-3`}),e.state===`queued`?i(`common.cancel`,`Cancel`):i(`backup.backupRunsPanel.stop`,`Stop`)]})})})]})}function Jt({run:e}){let{t}=G();switch(e.state){case`queued`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:[c(x,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.queued`,`Queued`)]});case`running`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`,children:[c(T,{className:`h-3 w-3 animate-spin`}),e.phase===`uploading`?t(`backup.backupRunsPanel.uploading`,`Uploading`):t(`backup.backupRunsPanel.buildingArchive`,`Building archive`)]});case`succeeded`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-success/10 px-1.5 py-0.5 text-[10px] font-medium text-success`,children:[c(E,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.succeeded`,`Succeeded`)]});case`failed`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-danger/10 px-1.5 py-0.5 text-[10px] font-medium text-danger`,children:[c(O,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.failed`,`Failed`)]});case`cancelled`:return a(`span`,{className:`inline-flex items-center gap-1 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300`,title:t(`backup.backupRunsPanel.stoppedBeforeCompletingEveryDestination`,`Stopped before completing every destination — not a success`),children:[c(P,{className:`h-3 w-3`}),t(`backup.backupRunsPanel.stopped`,`Stopped`)]})}}function Yt({run:e}){let{t}=G();if(e.state===`queued`)return c(`span`,{className:`text-foreground-subtle`,children:e.queuePosition===void 0?c(`span`,{className:`italic`,children:t(`backup.backupRunsPanel.waitingItsTurn`,`waiting its turn`)}):a(`span`,{className:`inline-flex items-center gap-1`,children:[c(`span`,{className:e.queuePosition===1?`rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary`:`rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium`,children:Qt(e.queuePosition)}),t(`backup.backupRunsPanel.inLine`,`in line`)]})});if(e.state===`running`&&e.phase===`building`)return a(`span`,{className:`inline-flex items-center gap-1.5 text-foreground`,children:[c(F,{className:`h-3 w-3 text-primary`}),c(`span`,{className:`tabular-nums font-medium animate-pulse`,children:K(e.stagedBytes)}),c(`span`,{className:`text-foreground-subtle`,children:t(`backup.backupRunsPanel.stagedSoFar`,`staged so far`)})]});if(e.state===`running`){let n=e.archiveSizeBytes;return a(`span`,{className:`inline-flex items-center gap-1.5 text-foreground`,children:[c(N,{className:`h-3 w-3 text-primary`}),a(`span`,{className:`tabular-nums font-medium`,children:[K(e.uploadedBytes),n===void 0?``:` / ${K(n)}`]}),c(`span`,{className:`text-foreground-subtle`,children:t(`backup.backupRunsPanel.toCurrentDestination`,`to current destination`)})]})}let n=e.archiveSizeBytes??(e.stagedBytes>0?e.stagedBytes:void 0);return n===void 0?c(`span`,{className:`text-foreground-subtle italic`,children:`—`}):c(`span`,{className:`tabular-nums text-foreground`,children:t(`backup.runsPanel.archiveSize`,{size:K(n)})})}function Xt({run:e}){let{t}=G(),n=e.destinationIds.length,r=e.completedDestinationIds.length,i=e.failedDestinationIds.length;return n===0?c(`span`,{className:`text-foreground-subtle italic`,children:t(`backup.backupRunsPanel.notResolvedYet`,`not resolved yet`)}):a(`div`,{className:`flex flex-col gap-0.5`,children:[c(`span`,{className:`text-foreground-subtle`,title:e.destinationIds.join(`, `),children:t(`backup.runsPanel.targets`,{count:n})}),a(`span`,{className:`inline-flex items-center gap-2 text-[10px]`,children:[r>0&&c(`span`,{className:`text-success`,title:t(`backup.backupRunsPanel.keptTheirArchive`,`Kept their archive: {{value1}}`,{value1:e.completedDestinationIds.join(`, `)}),children:t(`backup.runsPanel.completed`,{count:r})}),i>0&&c(`span`,{className:`text-danger`,title:t(`backup.backupRunsPanel.failed2`,`Failed: {{value1}}`,{value1:e.failedDestinationIds.join(`, `)}),children:t(`backup.runsPanel.failedCount`,{count:i})})]})]})}function Zt({run:e,now:t}){let{t:n}=G();return e.state===`queued`?c(`span`,{children:n(`backup.runsPanel.queuedAgo`,{elapsed:$t(t-e.requestedAt)})}):e.startedAt===void 0?c(`span`,{children:`—`}):e.finishedAt===void 0?c(`span`,{children:n(`backup.runsPanel.runningFor`,{elapsed:$t(t-e.startedAt)})}):a(`div`,{className:`flex flex-col gap-0.5`,children:[c(`span`,{children:en(e.finishedAt)}),c(`span`,{className:`text-[10px]`,children:n(`backup.runsPanel.took`,{elapsed:$t(e.finishedAt-e.startedAt)})})]})}function Qt(e){if(e<=1)return`next`;let t=e%100;if(t>=11&&t<=13)return`${e}th`;switch(e%10){case 1:return`${e}st`;case 2:return`${e}nd`;case 3:return`${e}rd`;default:return`${e}th`}}function $t(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${String(t%60).padStart(2,`0`)}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,`0`)}m`}function en(e){return new Date(e).toLocaleString(void 0,{day:`2-digit`,month:`short`,hour:`2-digit`,minute:`2-digit`})}e();var tn=[[`backup`,`list`]];function nn({initialDestinationId:e,initialArchiveId:i,onClose:o,onScheduled:l}){let{t:u}=G(),d=s(),[f,m]=r(e&&i?2:1),[h,g]=r(e),[_,v]=r(i),[b,x]=r(new Set),[S,C]=r(``),{data:w}=Oe(),E=w??[],{data:D,isLoading:O}=we({destinationId:h??``},{enabled:!!h}),A=D??[];t(()=>{if(h!==void 0)return;let e=E.filter(e=>e.restoreSupported);e.length===1&&g(e[0].id)},[h,E]);let{data:j}=Pe({destinationId:h??``,backupId:_??``},{enabled:!!h&&!!_}),M=n(()=>j?.locations??[],[j]);t(()=>{M.length!==0&&x(e=>e.size===0?new Set(M):e)},[M]);let N=Re({onSuccess:()=>{d.invalidateQueries({queryKey:tn}),l(),o()}}),P=e=>{x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},F=A.find(e=>e.id===_),I=F?.encryption!==void 0,L=ft(F?.databases,j?.sqliteSnapshots),R=ut(L),te=!!h&&!!_,z=R||b.size>0,ne=te&&z&&!N.isPending&&(!I||S.trim().length>0),re=()=>{!h||!_||N.mutate({destinationId:h,backupId:_,...R?{}:{locations:[...b]},...I?{backupSecretKey:S.trim()}:{}})};return c(ue,{open:!0,onOpenChange:e=>!e&&o(),children:a(ee,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,children:[a(le,{children:[c(de,{children:u(`backup.restoreWizard.restoreBackup`,`Restore Backup`)}),c(`p`,{className:`text-xs text-foreground-subtle`,children:u(`backup.restoreWizard.stepOf`,{step:f,name:f===1?u(`backup.restoreWizard.pickSource`,`pick source`):f===2?u(`backup.restoreWizard.pickLocations`,`pick locations`):u(`backup.restoreWizard.confirmStep`)})})]}),a(Te,{children:[f===1&&c(rn,{destinations:E,destinationId:h,onPickDestination:e=>{g(e),v(void 0),x(new Set)},archives:A,archivesLoading:O,archiveId:_,onPickArchive:v}),f===2&&c(an,{locations:M,picked:b,onToggle:P,databases:L,snapshotsOnly:R}),f===3&&c(on,{destinationName:E.find(e=>e.id===h)?.displayName??h??``,archive:F,picked:[...b],databases:L,snapshotsOnly:R}),f===3&&F?.encryption!==void 0&&c(sn,{keyId:F.encryption.keyId,value:S,onChange:C}),f===3&&N.error&&c(`p`,{role:`alert`,className:`px-4 pb-2 text-xs text-danger`,children:N.error.message})]}),a(se,{className:`justify-between`,children:[c(`div`,{children:f>1&&a(V,{variant:`outline`,size:`sm`,onClick:()=>m(e=>e===3?2:1),children:[c(y,{className:`h-3 w-3`}),u(`common.back`,`Back`)]})}),a(`div`,{className:`flex items-center gap-2`,children:[c(V,{variant:`outline`,size:`sm`,onClick:o,children:u(`common.cancel`,`Cancel`)}),f<3?a(V,{size:`sm`,disabled:f===1&&!te||f===2&&!z,onClick:()=>m(e=>e===1?2:3),children:[u(`common.next`,`Next`),c(p,{className:`h-3 w-3`})]}):a(V,{size:`sm`,onClick:re,disabled:!ne,children:[N.isPending?c(T,{className:`h-3.5 w-3.5 animate-spin`}):c(k,{className:`h-3.5 w-3.5`}),u(`backup.restoreWizard.scheduleRestore`,`Schedule Restore`)]})]})]})]})})}function rn({destinations:e,destinationId:t,onPickDestination:n,archives:r,archivesLoading:i,archiveId:o,onPickArchive:s}){let{t:l}=G(),u=e.filter(e=>e.restoreSupported);return a(`div`,{className:`p-4 space-y-3`,children:[a(`div`,{className:`space-y-1.5`,children:[c(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:l(`backup.restoreWizard.destination`,`Destination`)}),c(fe,{value:t??``,onChange:e=>n(e.target.value),options:[{value:``,label:l(`backup.restoreWizard.selectDestination`,`Select destination…`)},...u.map(e=>({value:e.id,label:`${e.displayName} (${e.kind})`}))]})]}),a(`div`,{className:`space-y-1.5`,children:[c(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:l(`backup.restoreWizard.archive`,`Archive`)}),!t&&c(`div`,{className:`text-xs text-foreground-subtle italic`,children:l(`backup.restoreWizard.pickADestinationFirst`,`Pick a destination first.`)}),t&&i&&c(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:l(`backup.restoreWizard.readingArchives`,`Reading archives…`)}),t&&!i&&r.length===0&&c(`div`,{className:`text-xs text-foreground-subtle italic`,children:l(`backup.restoreWizard.noArchivesAvailableAtThis`,`No archives available at this destination.`)}),t&&r.length>0&&c(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto`,children:r.map(e=>{let t=o===e.id;return a(`label`,{className:`flex items-center justify-between px-3 py-2 text-xs cursor-pointer ${t?`bg-primary/10`:`hover:bg-primary/5`}`,children:[a(`div`,{className:`flex items-center gap-2`,children:[c(`input`,{type:`radio`,name:`archive`,checked:t,onChange:()=>s(e.id),className:`accent-primary`}),a(`div`,{children:[a(`div`,{className:`flex items-center gap-1 font-medium text-foreground`,children:[e.encryption!==void 0&&c(D,{className:`h-3 w-3 text-success`,"aria-label":l(`backup.restoreWizard.encryptedKey`,`encrypted (key {{keyId}})`,{keyId:e.encryption.keyId})}),e.label??e.id]}),c(`div`,{className:`text-[10px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()}),c(`div`,{className:`pt-1`,children:c(Z,{databases:ft(e.databases,void 0)})})]})]}),c(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums`,children:K(e.sizeBytes)})]},e.id)})})]})]})}function an({locations:e,picked:t,onToggle:n,databases:r,snapshotsOnly:i}){let{t:o}=G();return i?a(`div`,{className:`space-y-3 p-4`,children:[a(`div`,{className:`space-y-1.5`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:o(`backup.restoreWizard.databasesInThisArchive`,`Databases in this archive`)}),c(Z,{databases:r})]}),c(`div`,{className:`rounded border border-info/30 bg-info/10 px-3 py-2 text-[11px] text-info`,children:o(`backup.restoreWizard.snapshotsOnlyRestoringThisArchive`,`Snapshots only: restoring this archive replaces just these databases. It does NOT touch configuration, addons, addon data or certificates.`)})]}):e.length===0?c(`div`,{className:`p-4`,children:c(`div`,{className:`text-xs text-foreground-subtle`,children:o(`backup.restoreWizard.loadingArchiveManifestIfThis`,`Loading archive manifest… If this persists, the archive may predate manifests — restoring will apply everything in the tarball.`)})}):a(`div`,{className:`p-4 space-y-3`,children:[a(`div`,{className:`space-y-1.5`,children:[c(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:o(`backup.restoreWizard.databasesInThisArchive`,`Databases in this archive`)}),c(Z,{databases:r})]}),c(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:o(`backup.restoreWizard.selectedEntriesWillOverwriteLive`,`Selected entries will overwrite live data on the next server restart. Unchecked entries stay current.`)}),a(`div`,{className:`space-y-1.5`,children:[c(`label`,{className:`text-[10px] text-foreground-subtle uppercase tracking-wide`,children:o(`common.apply`,`Apply`)}),c(`div`,{className:`rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto`,children:e.map(e=>a(`label`,{className:`flex items-center gap-2 px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer`,children:[c(`input`,{type:`checkbox`,checked:t.has(e),onChange:()=>n(e),className:`accent-primary`}),c(`span`,{className:`font-mono text-foreground`,children:e}),c(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:ln(e)})]},e))})]})]})}function on({destinationName:e,archive:t,picked:n,databases:r,snapshotsOnly:i}){let{t:o}=G();return a(`div`,{className:`p-4 space-y-3 text-xs`,children:[c(`div`,{className:`rounded border border-warning/30 bg-warning/10 px-3 py-2 text-warning`,children:o(`backup.restoreWizard.restoreIsAppliedAtNext`,`Restore is applied at next server boot. Active connections will drop when you restart.`)}),a(`dl`,{className:`space-y-1.5`,children:[c($,{term:`Destination`,value:e}),c($,{term:`Archive`,value:t?.label??t?.id??`—`}),t&&c($,{term:`Created`,value:`${new Date(t.createdAt).toLocaleString()} · ${K(t.sizeBytes)}`}),c($,{term:`Databases`,value:r.map(e=>J(e)).join(`, `)}),c($,{term:`Locations`,value:i?`none (configuration is not touched)`:n.length>0?n.join(`, `):`— (full archive)`})]})]})}function sn({keyId:e,value:t,onChange:n}){let{t:r}=G();return a(`div`,{className:`space-y-1.5 px-4 pb-3`,children:[c(`label`,{htmlFor:`restore-backup-key`,className:`text-[10px] uppercase tracking-wide text-foreground-subtle`,children:r(`backup.restoreWizard.backupKey`,`Backup key`)}),c(`input`,{id:`restore-backup-key`,type:`password`,autoComplete:`off`,spellCheck:!1,value:t,onChange:e=>n(e.target.value),placeholder:r(`backup.restoreWizard.camstackBackupSecretV1`,`camstack-backup-secret-v1:…`),className:`w-full rounded border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`}),c(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(ze,{i18nKey:`backup.restoreWizard.encryptedTo`,values:{keyId:e},components:{mono:c(`span`,{className:`font-mono`})}})})]})}function $({term:e,value:t}){return a(`div`,{className:`flex justify-between gap-3`,children:[c(`dt`,{className:`text-foreground-subtle`,children:e}),c(`dd`,{className:`text-foreground font-mono text-right truncate`,children:t})]})}var cn={db:`Database`,addons:`Addon configs`,"addons-data":`Addon data`,tls:`TLS certificates`,cache:`Cache`,data:`Top-level data`};function ln(e){return cn[e]??``}e();function un(){let{t:e}=G(),n=H(),i=ie(),{state:o,openNew:s,openEdit:u,close:d}=L({editKey:`edit`,newKey:`new`}),f=ve(),p=f.data??[],[m,h]=r(null),[g,_]=r(!1),[v,y]=r(!1),[b,x]=r(!1),S=o.mode===`edit`?p.find(e=>e.id===o.id)??null:null;t(()=>{o.mode===`edit`&&!f.isLoading&&S===null&&d()},[o.mode,f.isLoading,S,d]);let C=o.mode===`new`||o.mode===`edit`&&S!==null,E=async()=>{await n({title:e(`system.backup.restartServerNow`,`Restart server now?`),message:e(`system.backup.activeConnectionsWillDropAnd`,`Active connections will drop and the apply-backup hook will run before boot.`),confirmLabel:e(`system.backup.restart`,`Restart`),variant:`warning`})&&i.mutate({confirm:!0})};return a(He,{embedded:!0,children:[a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,"data-testid":`backup-actions`,children:[a(V,{variant:`outline`,size:`sm`,type:`button`,onClick:()=>x(!0),"data-testid":`backup-now`,children:[c(l,{className:`h-3.5 w-3.5`}),e(`system.backup.backUpNow`,`Back up now`)]}),a(V,{variant:`outline`,size:`sm`,type:`button`,onClick:()=>_(!0),children:[c(k,{className:`h-3.5 w-3.5`}),e(`system.backup.restore`,`Restore…`)]}),a(V,{size:`sm`,type:`button`,onClick:s,"data-testid":`backup-new-entry`,children:[c(w,{className:`h-3.5 w-3.5`}),e(`system.backup.newEntry`,`New entry`)]})]}),v&&c(`div`,{className:`rounded-lg border border-warning/30 bg-warning/10 px-3 py-2.5 text-xs text-warning`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{className:`flex items-center gap-2`,children:[c(k,{className:`h-3.5 w-3.5`}),c(`span`,{children:e(`system.backup.restoreScheduledRestartTheServer`,`Restore scheduled. Restart the server to apply.`)})]}),a(V,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>{E()},disabled:i.isPending,children:[i.isPending?c(T,{className:`h-3.5 w-3.5 animate-spin`}):c(k,{className:`h-3.5 w-3.5`}),e(`system.backup.restartNow`,`Restart Now`)]})]})}),c(Nt,{}),c(Gt,{}),c(yt,{onEdit:e=>u(e.id),onOpenRestoreWizard:e=>h(e)}),C&&c(Vt,{entry:S,onClose:d,onSaved:d}),b&&c(kt,{onClose:()=>x(!1)}),(m||g)&&c(nn,{...m?{initialDestinationId:m.destinationId,initialArchiveId:m.archiveId}:{},onClose:()=>{h(null),_(!1)},onScheduled:()=>y(!0)})]})}function dn(){let{t:e}=G();return a(`div`,{className:u,children:[c(`p`,{className:`mb-3 text-xs text-foreground-muted`,children:e(`systemPage.data.entriesIntro`,`Operator-created rows stored as record entry kinds. Password fields come from each kind schema.`)}),c(re,{})]})}function fn(){let{t:e}=G();return a(`div`,{className:u,children:[c(`p`,{className:`mb-3 text-xs text-foreground-muted`,children:e(`systemPage.data.recordsIntro`,`Every declared record kind on this hub. Secret fields are redacted in row previews.`)}),c(te,{})]})}function pn(){let{t:e}=G(),t=Be(`/system/data`,{t:e,isAdmin:!0})??{icon:m,title:e(`system.data`,`Data`)};return c(Ve,{icon:t.icon,title:t.title,defaultSection:`storage`,sectionsLabel:`${t.title} sections`,sections:[{id:`storage`,label:e(`systemPage.data.storage`,`Storage`),content:c(tt,{})},{id:`entries`,label:e(`systemPage.data.entries`,`Entries`),content:c(dn,{})},{id:`records`,label:e(`systemPage.data.records`,`Records`),content:c(fn,{})},{id:`backup`,label:e(`systemPage.data.backup`,`Backup`),content:c(un,{})},{id:`deleted-devices`,label:e(`systemPage.data.deletedDevices`,`Deleted devices`),content:c(et,{})}]})}export{pn as DataPage};