@camstack/addon-admin-ui 1.2.429 → 1.2.431

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/assets/{AddonAssetIcon-DR35yt0E.js → AddonAssetIcon-CngGyUbH.js} +1 -1
  2. package/dist/assets/{Addons-gkGgGpTC.js → Addons-COSbX7Q1.js} +2 -2
  3. package/dist/assets/{AdminPage-DAO24U0w.js → AdminPage-BFQa1eDk.js} +1 -1
  4. package/dist/assets/{AdminSectionedPage-B-qoE6ra.js → AdminSectionedPage-Bb00eMTj.js} +1 -1
  5. package/dist/assets/AiProfiles-DGok1qYw.js +3 -0
  6. package/dist/assets/{BrokerForm-B3xs9aBj.js → BrokerForm-NDMOvAlu.js} +1 -1
  7. package/dist/assets/{Build-DeMAJfjN.js → Build-BPgFXVbn.js} +4 -4
  8. package/dist/assets/{Calendars-VPH-vy-o.js → Calendars-DLuwgZXW.js} +1 -1
  9. package/dist/assets/Cluster-BUBVih9A.js +1 -0
  10. package/dist/assets/ClusterStepModel-DzduELev.js +1 -0
  11. package/dist/assets/{CompositionEditor-BrtLjoSu.js → CompositionEditor-DTgOmFqj.js} +1 -1
  12. package/dist/assets/{CompositionEditorPage-D51jS9td.js → CompositionEditorPage-D73l3mqU.js} +1 -1
  13. package/dist/assets/Data-Wqos-WHl.js +2 -0
  14. package/dist/assets/{DeviceDetail-D1qU_p1k.js → DeviceDetail-CwmpXUmk.js} +2 -2
  15. package/dist/assets/{DeviceDoActionFields-B62Nv4K7.js → DeviceDoActionFields-DKOJoFJc.js} +1 -1
  16. package/dist/assets/{Devices-Cf5Exjsk.js → Devices-D_SKAo6X.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-CnEcSJ8D.js → EmbedPlayerPage-DI4ac8Wo.js} +1 -1
  18. package/dist/assets/Identity-C25gG2Mh.js +1 -0
  19. package/dist/assets/IntegrationDetail-L73oZLMf.js +1 -0
  20. package/dist/assets/{IntegrationHub-DdjWEObX.js → IntegrationHub-DuVgrEey.js} +1 -1
  21. package/dist/assets/{Integrations-CU7Ll9U_.js → Integrations-CUPpCCtl.js} +1 -1
  22. package/dist/assets/{Integrations-uZB2ozhn.js → Integrations-Cgm8qaox.js} +1 -1
  23. package/dist/assets/{Library-DSuCaXt6.js → Library-Dm0AivX3.js} +1 -1
  24. package/dist/assets/Locations-B2TjRBpQ.js +3 -0
  25. package/dist/assets/{Logs-cm-1R2Z4.js → Logs-CeX1xx9_.js} +1 -1
  26. package/dist/assets/{MaskShapeCanvas-CM9D4FOf.js → MaskShapeCanvas-GZ2ZMDcz.js} +1 -1
  27. package/dist/assets/{MotionZonesSettings-DqS8ndiK.js → MotionZonesSettings-B5gIoLVC.js} +1 -1
  28. package/dist/assets/MyAccess-DJvaTHrq.js +2 -0
  29. package/dist/assets/Network-D0uak4Dc.js +1 -0
  30. package/dist/assets/{NodeAddonsSettingsPanel-BMat4ckt.js → NodeAddonsSettingsPanel-kmgNnVID.js} +1 -1
  31. package/dist/assets/{Notifications-EPQiEZ1t.js → Notifications-DP0iwqUM.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-Bis0PO01.js → PrivacyMaskSettings-DWCvE7XZ.js} +1 -1
  33. package/dist/assets/Recordings-r5KE18a6.js +1 -0
  34. package/dist/assets/{ScanNetworkModal-dHWFmbFe.js → ScanNetworkModal-CHWsBmiM.js} +1 -1
  35. package/dist/assets/{SceneMonitorEditor-SFMMIopn.js → SceneMonitorEditor-BNFYspNy.js} +1 -1
  36. package/dist/assets/SessionsList-OvrBa2rd.js +2 -0
  37. package/dist/assets/{Showroom-Er-hes9K.js → Showroom-DNgHGmg0.js} +1 -1
  38. package/dist/assets/{System-BDXxfgsq.js → System-CcDzJj6C.js} +1 -1
  39. package/dist/assets/{Terminal-B70jnm8e.js → Terminal-DpGR-56V.js} +5 -5
  40. package/dist/assets/{Viewer-BsGL5Dfa.js → Viewer-vqCH_LqM.js} +1 -1
  41. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C7iEnSHU.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DR_v3lvi.js} +1 -1
  42. package/dist/assets/{addon-icons-context--6Hi3qRW.js → addon-icons-context-B2Gmu49a.js} +1 -1
  43. package/dist/assets/{archive-DtcjevJM.js → archive-CoV271Ga.js} +1 -1
  44. package/dist/assets/{authed-media-LCmlAEZ5.js → authed-media-BSx10sm9.js} +1 -1
  45. package/dist/assets/{bell-off-eQBpwamg.js → bell-off-CQHJCxaC.js} +1 -1
  46. package/dist/assets/{board-model-wzCmdEKJ.js → board-model-lagHZiI7.js} +1 -1
  47. package/dist/assets/{boxes-DikDfAoo.js → boxes-DKr2EDaB.js} +1 -1
  48. package/dist/assets/circle-slash-D1CG5tRc.js +1 -0
  49. package/dist/assets/client-CqsEJzhO.js +358 -0
  50. package/dist/assets/{cloud-upload-DI9XunFf.js → cloud-upload-D3IJwdmA.js} +1 -1
  51. package/dist/assets/crop-sD8BDahL.js +1 -0
  52. package/dist/assets/{device-integration-icon-D2lWVDM2.js → device-integration-icon-BHf83qVT.js} +1 -1
  53. package/dist/assets/device-picker-model-JBC8n4FU.js +1 -0
  54. package/dist/assets/dist-C3lDDHVX.js +358 -0
  55. package/dist/assets/{dist-ChQzskeX.js → dist-Dlrgg5It.js} +1 -1
  56. package/dist/assets/{eraser-Dl5ROV0l.js → eraser-BRuYxYS4.js} +1 -1
  57. package/dist/assets/{hard-drive-download-B1ard6ym.js → hard-drive-download-B14E8eTo.js} +1 -1
  58. package/dist/assets/{history-BMhP0SFG.js → history-Dn2pnfaZ.js} +1 -1
  59. package/dist/assets/{hostInit-FCvre9AW.js → hostInit-3qW3eaSU.js} +1 -1
  60. package/dist/assets/i18n-B-IeyHf7.js +1 -0
  61. package/dist/assets/icons-CvJTX54k.js +1 -0
  62. package/dist/assets/{index-DvOECbab.js → index-mBJW996X.js} +3 -3
  63. package/dist/assets/key-EeG_L4W9.js +1 -0
  64. package/dist/assets/{key-round-yCDTbIQb.js → key-round-C9pPg55h.js} +1 -1
  65. package/dist/assets/{layers-c960YTPf.js → layers-DhxisKd7.js} +1 -1
  66. package/dist/assets/{linked-devices-model-CB7qgVjI.js → linked-devices-model-CTfAwc1p.js} +1 -1
  67. package/dist/assets/{list-ordered-C7hEwAd1.js → list-ordered-Ckqq8GR7.js} +1 -1
  68. package/dist/assets/{location-owned-usage-D28vwYJT.js → location-owned-usage-eDtNCANy.js} +1 -1
  69. package/dist/assets/{log-in-DFfxcqYz.js → log-in-CAiH8-Mq.js} +1 -1
  70. package/dist/assets/{memory-stick-BBfIGrWx.js → memory-stick-Bir-K-V7.js} +1 -1
  71. package/dist/assets/{message-square-plus-D8ZUT6rz.js → message-square-plus-B_0WwbBk.js} +1 -1
  72. package/dist/assets/{mf-entry-bootstrap-0-3035e647.js → mf-entry-bootstrap-0-c62ae51c.js} +2 -2
  73. package/dist/assets/{mic-off-w2mFOBi3.js → mic-off-D5kT_DDX.js} +1 -1
  74. package/dist/assets/{monitor-off-DPi_gm_c.js → monitor-off-DzKNd6eJ.js} +1 -1
  75. package/dist/assets/{monitor-smartphone-9Ife1Trw.js → monitor-smartphone-D3ZPy75c.js} +1 -1
  76. package/dist/assets/mount-JBC8n4FU.js +1 -0
  77. package/dist/assets/{notification-schedule-field-BuLfSYLZ.js → notification-schedule-field-DaKiveMR.js} +1 -1
  78. package/dist/assets/{octagon-alert-C-jH7VH_.js → octagon-alert-BYNvsZ0Q.js} +1 -1
  79. package/dist/assets/{player-overlays-D0U2dNvn.js → player-overlays-DFTWiQ8-.js} +1 -1
  80. package/dist/assets/{recycle-Bbki65G2.js → recycle-DJUuC9xt.js} +1 -1
  81. package/dist/assets/remoteEntry-BhYjusn-.js +1 -0
  82. package/dist/assets/{scan-eye-AfIM_Dlr.js → scan-eye-_otUiDbW.js} +1 -1
  83. package/dist/assets/{scissors-CnL6g0BO.js → scissors-BU04yNa7.js} +1 -1
  84. package/dist/assets/{search-x-eqJd3G8u.js → search-x-Djycej4Y.js} +1 -1
  85. package/dist/assets/{send-B72RQ9UL.js → send-BNY2bJqA.js} +1 -1
  86. package/dist/assets/{settings-2-CXZ6DVRg.js → settings-2-BxpLi7pY.js} +1 -1
  87. package/dist/assets/{speaker-CcCWWecW.js → speaker-BspD0ixN.js} +1 -1
  88. package/dist/assets/src-CE3hNyCx.js +67 -0
  89. package/dist/assets/{timer-reset-B9Lihcw9.js → timer-reset-CPRU92uv.js} +1 -1
  90. package/dist/assets/{ungroup-D753owNE.js → ungroup-oYlFn3LE.js} +1 -1
  91. package/dist/assets/{unlink-DzoLNfsq.js → unlink-D0eJ5vAc.js} +1 -1
  92. package/dist/assets/{usb-CuSU-_EY.js → usb-C24Ua3ty.js} +1 -1
  93. package/dist/assets/{use-scenes-feed-CZjJNxfD.js → use-scenes-feed-DzzIer2d.js} +1 -1
  94. package/dist/assets/{use-stationary-objects-BoGqWyLV.js → use-stationary-objects-C-l1Z5zI.js} +1 -1
  95. package/dist/assets/useEventInvalidation-JBC8n4FU.js +1 -0
  96. package/dist/assets/{useNodeUrlSelection-BA6CgjTU.js → useNodeUrlSelection-Ba-ed7zb.js} +1 -1
  97. package/dist/assets/user-round-JzUTTasm.js +1 -0
  98. package/dist/assets/{user-x-PK8sSsso.js → user-x-CdpX6b_D.js} +1 -1
  99. package/dist/assets/{video-BBtESt54.js → video-vLKHp9E_.js} +1 -1
  100. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BKfTL-9e.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D83o1ikp.js} +2 -2
  101. package/dist/index.html +10 -10
  102. package/dist/server/addon.js +192 -30
  103. package/package.json +1 -1
  104. package/dist/assets/AiProfiles-BXcreqZP.js +0 -3
  105. package/dist/assets/Cluster-B-k0M79z.js +0 -1
  106. package/dist/assets/ClusterStepModel-DaAc_6nI.js +0 -1
  107. package/dist/assets/Data-IfJuKcwc.js +0 -2
  108. package/dist/assets/Identity-DNE80jdX.js +0 -1
  109. package/dist/assets/IntegrationDetail-LKbiJFU3.js +0 -1
  110. package/dist/assets/Locations-BeaznsZS.js +0 -3
  111. package/dist/assets/MyAccess-Dxb11B6h.js +0 -2
  112. package/dist/assets/Network-BCDUHSB0.js +0 -1
  113. package/dist/assets/Recordings-BCeoXxL4.js +0 -1
  114. package/dist/assets/SessionsList-BRTwG3uv.js +0 -2
  115. package/dist/assets/circle-slash-YVgGJTpJ.js +0 -1
  116. package/dist/assets/client-DYbvGOid.js +0 -358
  117. package/dist/assets/crop-CxZbpOyK.js +0 -1
  118. package/dist/assets/device-picker-model-C4w1vbly.js +0 -1
  119. package/dist/assets/dist-CPO0KWoy.js +0 -358
  120. package/dist/assets/file-up-WS3s_T9x.js +0 -1
  121. package/dist/assets/i18n-Vb3uBp7P.js +0 -1
  122. package/dist/assets/icons-DocdgFuy.js +0 -1
  123. package/dist/assets/key-B1M6i1mf.js +0 -1
  124. package/dist/assets/mount-C4w1vbly.js +0 -1
  125. package/dist/assets/remoteEntry-DYVoozgD.js +0 -1
  126. package/dist/assets/src-CGxdJN_f.js +0 -67
  127. package/dist/assets/useEventInvalidation-C4w1vbly.js +0 -1
  128. package/dist/assets/user-round-CMg3Ndlt.js +0 -1
@@ -5388,7 +5388,7 @@ var ZodIssueCode = {
5388
5388
  var ZodFirstPartyTypeKind;
5389
5389
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5390
5390
  //#endregion
5391
- //#region ../types/dist/sleep-DRqxtc0C.mjs
5391
+ //#region ../types/dist/sleep-bwsTj221.mjs
5392
5392
  /**
5393
5393
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5394
5394
  * window to float samples (D455).
@@ -6639,7 +6639,6 @@ function createHandle(raw, opts) {
6639
6639
  const writeAddon = (patch) => write("addon", opts.addonTree(), void 0, patch, () => readStoredAddonBlob(raw), (p) => raw.writeAddonStore(p));
6640
6640
  const readAddonStoreResult = raw.readAddonStoreResult;
6641
6641
  const readAddonStoreKeyResult = raw.readAddonStoreKeyResult;
6642
- const readDeviceStoreBatch = raw.readDeviceStoreBatch;
6643
6642
  const overrides = {
6644
6643
  readAddonStore: async () => resolveRead("addon", await raw.readAddonStore()),
6645
6644
  ...readAddonStoreResult !== void 0 ? { readAddonStoreResult: async () => {
@@ -6663,12 +6662,12 @@ function createHandle(raw, opts) {
6663
6662
  };
6664
6663
  } } : {},
6665
6664
  readDeviceStore: async (deviceId) => resolveRead(`device:${deviceId}`, await raw.readDeviceStore(deviceId)),
6666
- ...readDeviceStoreBatch !== void 0 ? { readDeviceStoreBatch: async (deviceIds) => {
6667
- const rows = await readDeviceStoreBatch.call(raw, deviceIds);
6665
+ readDeviceStoreBatch: async (deviceIds) => {
6666
+ const rows = await raw.readDeviceStoreBatch(deviceIds);
6668
6667
  const out = /* @__PURE__ */ new Map();
6669
6668
  for (const [deviceId, blob] of rows) out.set(deviceId, await resolveRead(`device:${deviceId}`, blob));
6670
6669
  return out;
6671
- } } : {},
6670
+ },
6672
6671
  writeAddonStore: async (patch) => {
6673
6672
  await writeAddon(patch);
6674
6673
  },
@@ -7495,7 +7494,7 @@ var BaseAddon = class {
7495
7494
  return this._addonSecretTree;
7496
7495
  }
7497
7496
  deviceSecretTree() {
7498
- this._deviceSecretTree ??= secretTreeFromSchema(this.deviceSettingsSchema());
7497
+ this._deviceSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.deviceSettingsSchema()), this.secretStatePaths);
7499
7498
  return this._deviceSecretTree;
7500
7499
  }
7501
7500
  /**
@@ -7571,42 +7570,135 @@ var BaseAddon = class {
7571
7570
  this[timerOf] = timer;
7572
7571
  }
7573
7572
  /**
7574
- * Wrap `ctx.settings.readAddonStore()` with a short retry budget so a
7575
- * transient settings-store outage (mid-restart of sqlite-settings, tsx-watch
7576
- * swap, or any race where the SqliteSettingsBackend is between shutdown and
7577
- * re-initialize) doesn't propagate up into `initialize()` and leave the
7573
+ * Wrap `ctx.settings.readAddonStore()` with a retry budget so a transient
7574
+ * settings-store outage doesn't propagate up into `initialize()` and leave the
7578
7575
  * addon permanently broken.
7579
7576
  *
7580
- * Retry only the two known infra fingerprints. Anything else propagates so
7581
- * real bugs surface immediately. After the budget expires we fall back to
7582
- * `{}` (defaults) — the addon's first successful patch will rehydrate.
7577
+ * Two kinds of outage, two budgets:
7578
+ * - the store's own restart fingerprints (`SqliteSettingsBackend not
7579
+ * initialized`, `provider not available`): a short budget, then the addon
7580
+ * falls back to `{}` (defaults) - its first successful patch rehydrates;
7581
+ * - a TRANSPORT failure (the hub is restarting while this runner boots:
7582
+ * `discovery deadline exceeded`, `parent could not route`, a refused or
7583
+ * timed-out connection). Since D870 a runner's settings read THROWS instead
7584
+ * of answering `{}`, so without a budget a hub restart ends in a respawn
7585
+ * loop. A long, bounded budget; only after it the error propagates - the
7586
+ * addon never runs on defaults for a store it could not ask.
7587
+ * Anything else propagates immediately so real bugs surface.
7583
7588
  */
7584
7589
  async readAddonStoreWithRetry() {
7585
7590
  const settings = this.rawSettings();
7586
7591
  if (!settings) return {};
7587
- const delaysMs = [
7588
- 150,
7589
- 350,
7590
- 600,
7591
- 900
7592
- ];
7593
7592
  let lastErr;
7594
- for (let attempt = 0; attempt <= delaysMs.length; attempt++) try {
7593
+ for (let attempt = 0;; attempt++) try {
7595
7594
  const stored = await settings.readAddonStore() ?? {};
7596
7595
  this.settingsStoreReady = true;
7597
7596
  return stored;
7598
7597
  } catch (err) {
7599
7598
  lastErr = err;
7600
- const msg = err instanceof Error ? err.message : String(err);
7601
- if (!(msg.includes("SqliteSettingsBackend not initialized") || msg.includes("provider not available"))) throw err;
7602
- if (attempt === delaysMs.length) break;
7603
- await new Promise((r) => setTimeout(r, delaysMs[attempt]));
7599
+ const kind = classifyStoreError(err);
7600
+ if (kind === "permanent") throw err;
7601
+ const delay = (kind === "transport" ? TRANSPORT_RETRY_DELAYS_MS : RESTART_RETRY_DELAYS_MS)[attempt];
7602
+ if (delay === void 0) {
7603
+ if (kind === "transport") throw err;
7604
+ break;
7605
+ }
7606
+ await new Promise((r) => setTimeout(r, delay));
7604
7607
  }
7605
7608
  this.settingsStoreReady = false;
7606
7609
  this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults", { meta: { error: lastErr instanceof Error ? lastErr.message : String(lastErr) } });
7607
7610
  return {};
7608
7611
  }
7609
7612
  };
7613
+ /** The settings store's own restart fingerprints. */
7614
+ var RESTART_RETRY_DELAYS_MS = [
7615
+ 150,
7616
+ 350,
7617
+ 600,
7618
+ 900
7619
+ ];
7620
+ /** A hub restarting under a booting runner: ~100 s in total. */
7621
+ var TRANSPORT_RETRY_DELAYS_MS = [
7622
+ 150,
7623
+ 350,
7624
+ 600,
7625
+ 900,
7626
+ 2e3,
7627
+ 5e3,
7628
+ 1e4,
7629
+ 2e4,
7630
+ 3e4,
7631
+ 3e4
7632
+ ];
7633
+ var RESTART_FINGERPRINTS = ["SqliteSettingsBackend not initialized", "provider not available"];
7634
+ /** Node / socket error codes of a connection that did not happen or broke. */
7635
+ var TRANSPORT_CODES = new Set([
7636
+ "ECONNREFUSED",
7637
+ "ECONNRESET",
7638
+ "ETIMEDOUT",
7639
+ "EPIPE",
7640
+ "EHOSTUNREACH",
7641
+ "ENETUNREACH"
7642
+ ]);
7643
+ /** tRPC error codes that mean "the other side is not answering now", not "your call is wrong". */
7644
+ var UNAVAILABLE_TRPC_CODES = new Set([
7645
+ "TIMEOUT",
7646
+ "SERVICE_UNAVAILABLE",
7647
+ "BAD_GATEWAY",
7648
+ "GATEWAY_TIMEOUT"
7649
+ ]);
7650
+ /** The exact phrases OUR transport raises when it cannot reach the hub. */
7651
+ var TRANSPORT_PHRASES = [
7652
+ "discovery deadline exceeded",
7653
+ "parent could not route child unowned cap call",
7654
+ "UDS request timed out after",
7655
+ "channel closed"
7656
+ ];
7657
+ /** Moleculer error `type`s of a call that could not be served right now. */
7658
+ var MOLECULER_TRANSIENT_TYPES = new Set([
7659
+ "REQUEST_TIMEOUT",
7660
+ "SERVICE_NOT_FOUND",
7661
+ "SERVICE_NOT_AVAILABLE",
7662
+ "REQUEST_REJECTED",
7663
+ "BROKER_DISCONNECTED"
7664
+ ]);
7665
+ function stringProp(value, key) {
7666
+ if (typeof value !== "object" || value === null) return void 0;
7667
+ const found = Reflect.get(value, key);
7668
+ return typeof found === "string" ? found : void 0;
7669
+ }
7670
+ /** The code an error carries: its own, its cause's, or a tRPC `data.code`. */
7671
+ function errorCode(err) {
7672
+ const out = {};
7673
+ const cause = typeof err === "object" && err !== null ? Reflect.get(err, "cause") : void 0;
7674
+ const data = typeof err === "object" && err !== null ? Reflect.get(err, "data") : void 0;
7675
+ const node = stringProp(err, "code") ?? stringProp(cause, "code");
7676
+ if (node !== void 0) out.node = node;
7677
+ const trpc = stringProp(data, "code");
7678
+ if (trpc !== void 0) out.trpc = trpc;
7679
+ return out;
7680
+ }
7681
+ /**
7682
+ * Is a settings read failure worth retrying, and with which budget? Only
7683
+ * EXPLICIT signals count: a socket error code, a tRPC "unavailable" code, or
7684
+ * one of the exact phrases our own transport raises. A message that merely
7685
+ * contains "timed out" or "unreachable" is not evidence of anything, and
7686
+ * `settings store not wired` is a wiring bug that retrying cannot fix.
7687
+ */
7688
+ function classifyStoreError(err) {
7689
+ const message = err instanceof Error ? err.message : String(err);
7690
+ if (RESTART_FINGERPRINTS.some((f) => message.includes(f))) return "restart";
7691
+ const code = errorCode(err);
7692
+ if (code.node !== void 0 && TRANSPORT_CODES.has(code.node)) return "transport";
7693
+ if (code.trpc !== void 0 && UNAVAILABLE_TRPC_CODES.has(code.trpc)) return "transport";
7694
+ if (typeof err === "object" && err !== null) {
7695
+ if (Reflect.get(err, "retryable") === true) return "transport";
7696
+ const type = stringProp(err, "type");
7697
+ if (type !== void 0 && MOLECULER_TRANSIENT_TYPES.has(type)) return "transport";
7698
+ }
7699
+ if (TRANSPORT_PHRASES.some((f) => message.includes(f))) return "transport";
7700
+ return "permanent";
7701
+ }
7610
7702
  /**
7611
7703
  * Collect the keys of every field marked `perNode: true`, recursing into
7612
7704
  * layout containers (`group` fields and `sub-tabs` tabs) the same way
@@ -11719,11 +11811,10 @@ var ClipModelMetaSchema = object({
11719
11811
  /**
11720
11812
  * The `vector-store` index this model's vectors live in. ONE feature space
11721
11813
  * per index: two models share an index only when their vectors are ranked
11722
- * against each other, which for CLIP means never across families. MobileCLIP
11723
- * S1 and S2 share `object-clip` for history (separated by the row's
11724
- * `modelId`); any other model gets its own.
11814
+ * against each other, which for CLIP means never across families. Every
11815
+ * model gets its own.
11725
11816
  */
11726
- vectorIndex: string().regex(/^object-clip(-[a-z0-9][a-z0-9-]*)?$/),
11817
+ vectorIndex: string().regex(/^object-clip-[a-z0-9][a-z0-9-]*$/),
11727
11818
  /**
11728
11819
  * The text encoder's tokenizer, a declared SIBLING file of its onnx. The name
11729
11820
  * must be unique per tokenizer: every model's siblings land in ONE flat
@@ -15838,6 +15929,28 @@ id: union([string(), number()]) }), {
15838
15929
  kind: "mutation",
15839
15930
  auth: "admin"
15840
15931
  });
15932
+ /** One table of the settings database. */
15933
+ var StorageTableSchema = object({
15934
+ /** The table's full name, e.g. `recorder:addon-settings` or `addon-device-settings`. */
15935
+ name: string(),
15936
+ /** The owner prefix of a scoped name (`recorder` for `recorder:addon-settings`), else null. */
15937
+ owner: string().nullable(),
15938
+ rows: number().int().nonnegative(),
15939
+ /** Bytes the table's pages occupy (`dbstat`); null when the engine cannot measure. */
15940
+ bytes: number().int().nonnegative().nullable(),
15941
+ /** Declared by an addon since this engine process started (a running addon claims it). */
15942
+ declaredThisBoot: boolean()
15943
+ });
15944
+ method(object({ ownerPrefix: string().min(1).optional() }), object({ tables: array(StorageTableSchema) }), { auth: "admin" }), method(object({
15945
+ collection: string().min(1),
15946
+ expectRows: number().int().nonnegative()
15947
+ }), object({
15948
+ dropped: literal(true),
15949
+ rows: number().int().nonnegative()
15950
+ }), {
15951
+ kind: "mutation",
15952
+ auth: "admin"
15953
+ });
15841
15954
  /**
15842
15955
  * `keychain` — the hub's encrypted store of secret values (D787).
15843
15956
  *
@@ -16379,6 +16492,16 @@ method(object({}), KeychainStatusSchema, { auth: "admin" }), method(object({}),
16379
16492
  kind: "mutation",
16380
16493
  auth: "admin",
16381
16494
  caller: "required"
16495
+ }), method(object({
16496
+ ref: string().min(1),
16497
+ value: string().min(1)
16498
+ }), object({
16499
+ ref: string(),
16500
+ version: number().int()
16501
+ }), {
16502
+ kind: "mutation",
16503
+ auth: "admin",
16504
+ caller: "required"
16382
16505
  }), method(object({ refs: array(string().min(1)).max(1e3) }), object({
16383
16506
  deleted: array(string()).readonly(),
16384
16507
  kept: array(object({
@@ -54644,7 +54767,19 @@ var TlsStatusSchema = object({
54644
54767
  sans: array(string()),
54645
54768
  caCertPem: string().nullable(),
54646
54769
  reissueError: string().nullable(),
54647
- restartRequired: boolean()
54770
+ restartRequired: boolean(),
54771
+ /** An uploaded certificate is served but no CA is kept for it and it is not publicly signed (D873). */
54772
+ caMissing: boolean(),
54773
+ /** Does the hub's own generated CA carry a critical name constraint? `null` while it has none. */
54774
+ localCaConstrained: boolean().nullable(),
54775
+ /** ISO time the generated CA was replaced by a constrained one; devices must re-download it. */
54776
+ caReplacedAt: string().nullable(),
54777
+ /** The uploaded certificate kept on disk, selectable again after "Revert to generated". */
54778
+ storedUpload: object({
54779
+ leafFingerprintSha256: string(),
54780
+ validTo: string(),
54781
+ hasCa: boolean()
54782
+ }).nullable()
54648
54783
  });
54649
54784
  method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(object({
54650
54785
  /**
@@ -54700,6 +54835,9 @@ method(_void(), ListResultSchema), method(_void(), PreferredSchema), method(obje
54700
54835
  }), method(_void(), object({ pem: string() })), method(_void(), TlsStatusSchema, {
54701
54836
  kind: "mutation",
54702
54837
  auth: "admin"
54838
+ }), method(_void(), TlsStatusSchema, {
54839
+ kind: "mutation",
54840
+ auth: "admin"
54703
54841
  });
54704
54842
  object({
54705
54843
  /** Lifecycle state of the lock. `jammed` means the motor reported
@@ -63716,6 +63854,12 @@ Object.freeze({
63716
63854
  addonId: null,
63717
63855
  access: "create"
63718
63856
  },
63857
+ "keychainAdmin.importSecret": {
63858
+ capName: "keychain-admin",
63859
+ capScope: "system",
63860
+ addonId: null,
63861
+ access: "create"
63862
+ },
63719
63863
  "keychainAdmin.listAudit": {
63720
63864
  capName: "keychain-admin",
63721
63865
  capScope: "system",
@@ -64112,6 +64256,12 @@ Object.freeze({
64112
64256
  addonId: null,
64113
64257
  access: "create"
64114
64258
  },
64259
+ "localNetwork.useStoredUploadedCertificate": {
64260
+ capName: "local-network",
64261
+ capScope: "system",
64262
+ addonId: null,
64263
+ access: "create"
64264
+ },
64115
64265
  "lockControl.getStatus": {
64116
64266
  capName: "lock-control",
64117
64267
  capScope: "device",
@@ -67496,6 +67646,18 @@ Object.freeze({
67496
67646
  addonId: null,
67497
67647
  access: "create"
67498
67648
  },
67649
+ "storageAdmin.dropCollection": {
67650
+ capName: "storage-admin",
67651
+ capScope: "system",
67652
+ addonId: null,
67653
+ access: "delete"
67654
+ },
67655
+ "storageAdmin.listTables": {
67656
+ capName: "storage-admin",
67657
+ capScope: "system",
67658
+ addonId: null,
67659
+ access: "view"
67660
+ },
67499
67661
  "storageEvictable.evict": {
67500
67662
  capName: "storage-evictable",
67501
67663
  capScope: "system",
@@ -72668,7 +72830,7 @@ var AdminUIAddon = class extends BaseAddon {
72668
72830
  capability: adminUiCapability,
72669
72831
  provider: {
72670
72832
  getStaticDir: async () => ({ staticDir: resolveAdminUiDistDir() }),
72671
- getVersion: async () => ({ version: "1.2.429" })
72833
+ getVersion: async () => ({ version: "1.2.431" })
72672
72834
  }
72673
72835
  }];
72674
72836
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-admin-ui",
3
- "version": "1.2.429",
3
+ "version": "1.2.431",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Admin UI — Vite frontend build and server-side addon",
@@ -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{D as d,Dn as f,G as p,Hr as m,It as h,Jr as g,Jt as _,Oi as v,On as y,Pn as b,Q as x,Tr as S,Xt as C,Zr as w,ar as T,dn as E,dt as D,kr as ee,ot as O,un as k,wi as A}from"./player-overlays-D0U2dNvn.js";import{t as j}from"./message-square-plus-D8ZUT6rz.js";import{t as M}from"./send-B72RQ9UL.js";import{Wn as N}from"./client-DYbvGOid.js";import{Bn as P,L as te,Ln as ne,Pn as F,Ql as I,U as L,Ut as R,Vt as z,Wt as B,ar as V,bn as H,ha as U,in as W,ql as G,z as K}from"./src-CGxdJN_f.js";import{t as q}from"./i18n-Vb3uBp7P.js";import{t as J}from"./useTranslation-D3Is_4B6.js";import"./mount-C4w1vbly.js";import{C as re}from"./index-DvOECbab.js";import{t as ie}from"./AdminSectionedPage-B-qoE6ra.js";import{t as ae}from"./AdminPage-DAO24U0w.js";e();var oe=[`llm`,`listProfiles`],se=[`llm`,`listProfileKinds`],ce=[`llm`,`getDefaults`],Y=[`llm`,`listRuntimeNodes`],le=[`llm`,`listModelCatalog`],ue=[`llm`,`getUsage`],de=[{purpose:`vision`,visionOnly:!0},{purpose:`text`,visionOnly:!1}],fe=new Map(Object.entries({openai:w,anthropic:w,google:w,"openai-compatible":f,"managed-local":g,"apple-foundation":g}));function pe(e){return fe.get(e)??null}function X(e){return typeof e==`string`&&e.length>0?e:void 0}function Z(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Q(e){return e===!0}function me(e){return{model:e.model,baseUrl:e.baseUrl,apiKey:e.apiKey,supportsVision:e.supportsVision,temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxTokens,contextLength:e.contextLength,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,connectTimeoutMs:e.connectTimeoutMs,firstTokenTimeoutMs:e.firstTokenTimeoutMs,idleTimeoutMs:e.idleTimeoutMs,retryEnabled:e.retry.enabled,retryMaxAttempts:e.retry.maxAttempts,toolsEnabled:e.toolsEnabled,contextSize:e.runtime?.contextSize,gpuLayers:e.runtime?.gpuLayers,threads:e.runtime?.threads,parallel:e.runtime?.parallel,idleStopMinutes:e.runtime?.idleStopMinutes,batchSize:e.runtime?.batchSize,ubatchSize:e.runtime?.ubatchSize,flashAttention:e.runtime?.flashAttention,mlock:e.runtime?.mlock,noMmap:e.runtime?.noMmap,cacheTypeK:e.runtime?.cacheTypeK,cacheTypeV:e.runtime?.cacheTypeV,extraArgs:ve(e.runtime?.extraArgs??[])}}var he=[`f32`,`f16`,`q8_0`,`q5_1`,`q5_0`,`q4_1`,`q4_0`];function ge(e){return typeof e==`string`&&he.includes(e)?e:void 0}function _e(e){let t=[],n=``,r=null;for(let i of e){if(r!==null){i===r?r=null:n+=i;continue}if(i===`"`||i===`'`){r=i;continue}if(/\s/.test(i)){n!==``&&t.push(n),n=``;continue}n+=i}return n!==``&&t.push(n),t}function ve(e){return e.map(e=>/\s/.test(e)?`"${e}"`:e).join(` `)}var ye=[`--jinja`,`--cont-batching`];function be(e,t,n){let r=Z(e.threads),i=Z(e.batchSize),a=Z(e.ubatchSize),o=ge(e.cacheTypeK),s=ge(e.cacheTypeV);return{nodeId:t,engine:`llama-cpp`,model:n,extraArgs:[..._e(X(e.extraArgs)??``)],contextSize:Z(e.contextSize)??4096,gpuLayers:Z(e.gpuLayers)??0,...r===void 0?{}:{threads:r},parallel:Z(e.parallel)??1,...i===void 0?{}:{batchSize:i},...a===void 0?{}:{ubatchSize:a},flashAttention:Q(e.flashAttention),mlock:Q(e.mlock),noMmap:Q(e.noMmap),...o===void 0?{}:{cacheTypeK:o},...s===void 0?{}:{cacheTypeV:s},autoStart:Q(e.autoStart),idleStopMinutes:Z(e.idleStopMinutes)??30}}function xe(e,t,n,r,i){let a={id:n?.id??crypto.randomUUID(),name:t,kind:e,addonId:`ai`,enabled:n?.enabled??!0,model:X(r.model)??n?.model??``,supportsVision:i?.supportsVision??Q(r.supportsVision),timeoutMs:Z(r.timeoutMs)??N.totalMs,connectTimeoutMs:Z(r.connectTimeoutMs)??N.connectMs,firstTokenTimeoutMs:Z(r.firstTokenTimeoutMs)??N.firstTokenMs,idleTimeoutMs:Z(r.idleTimeoutMs)??N.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:q.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:q.t(`ai.appleAvailable`),detail:q.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:q.t(t.key),detail:n.detail,tone:t.tone}}case`unsupported-platform`:return{nodeId:e.nodeId,selectable:!1,labelKey:`ai.appleNotMac`,labelDefault:q.t(`ai.appleNotMac`),detail:n.platform,tone:`default`};case`unknown`:return t(n.error)}}var De=2e3;function $(e){return q.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}=J(),c=O(),[d,f]=r(``),[p,h]=r(null),[g,_]=r(!1),v=o({queryKey:le,queryFn:()=>c.trpcClient.llm.listModelCatalog.query({})}),y=o({queryKey:[`llm`,`listNodeModels`,e],queryFn:()=>c.trpcClient.llm.listNodeModels.query({nodeId:e})}),b=l({mutationFn:e=>c.trpcClient.llm.resolveModelRef.mutate(e),onSuccess:e=>{h(e),_(!1),e.ok&&i({model:e.model,modelId:e.label,supportsVision:e.purpose===`vision`})}}),x=l({mutationFn:t=>c.trpcClient.llm.installModel.mutate({nodeId:e,model:t}),onSuccess:()=>{_(!0),y.refetch()}}),S=o({queryKey:Y,enabled:x.isPending,refetchInterval:x.isPending?De:!1,queryFn:()=>c.trpcClient.llm.listRuntimeNodes.query({})}).data?.find(t=>t.nodeId===e)?.status?.download,C=n(()=>{let t=(v.data??[]).map(e=>({value:`catalog:${e.id}`,label:`${e.label} · ${e.quantization} · ${$(e.sizeBytes)}`})),n=(y.data??[]).filter(e=>e.catalogId===void 0&&e.path!==void 0).map(t=>({value:`node:${t.file}`,label:s(`ai.onNode`,`{{file}} · {{size}} · on {{node}}`,{file:t.file,size:$(t.sizeBytes),node:e})})),r=p?.ok===!0?[{value:`custom`,label:`${p.label} · ${$(p.totalBytes)}`}]:[];return[{value:``,label:s(`ai.selectModel`,`Select a model…`)},...t,...n,...r]},[v.data,y.data,p,e,s]),w=e=>{if(e===``){i(null);return}if(e===`custom`){if(p?.ok!==!0)return;i({model:p.model,modelId:p.label,supportsVision:p.purpose===`vision`});return}if(e.startsWith(`catalog:`)){let t=e.slice(8),n=v.data?.find(e=>e.id===t);i({model:{kind:`catalog`,catalogId:t},modelId:t,supportsVision:n?.purpose===`vision`});return}let t=e.slice(5),n=y.data?.find(e=>e.file===t);n?.path!==void 0&&i({model:{kind:`path`,path:n.path},modelId:t,supportsVision:!1})},D=e=>{d.trim()!==``&&b.mutate({ref:d.trim(),...e===void 0?{}:{maxBytes:e}})};return a(`div`,{className:`space-y-2`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-model`,children:s(`ai.model`,`Model`)}),u(G,{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(I,{value:d,onChange:e=>f(e.target.value),placeholder:s(`system.aiModelPicker.unslothQwen3635bA3b`,`unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M`),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),D())}}),a(P,{size:`sm`,variant:`secondary`,type:`button`,disabled:d.trim()===``||b.isPending,onClick:()=>D(),children:[b.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(E,{className:`h-3.5 w-3.5`}),s(`ai.hfCheck`,`Check`)]})]}),b.isError&&u(`p`,{className:`mt-2 text-[11px] text-danger`,children:b.error instanceof Error?b.error.message:s(`common.error`,`Error`)}),p?.ok===!1&&a(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-2.5 py-2`,children:[u(`p`,{className:`text-[11px] text-danger`,children:p.message}),p.candidates!==void 0&&p.candidates.length>0&&u(`div`,{className:`mt-1.5 flex flex-wrap gap-1`,children:p.candidates.map(e=>u(`button`,{type:`button`,className:`rounded border border-border bg-surface px-1.5 py-0.5 text-[10px] text-foreground hover:border-primary/50`,onClick:()=>{let t=`${d.trim().split(`:`)[0]??``}:${e}`;f(t),b.mutate({ref:t})},children:e},e))}),p.requiredBytes!==void 0&&u(P,{size:`sm`,variant:`secondary`,type:`button`,className:`mt-2`,onClick:()=>D(p.requiredBytes),children:s(`ai.hfOverride`,`Install anyway ({{size}})`,{size:$(p.requiredBytes)})})]}),p?.ok===!0&&a(`div`,{className:`mt-2 rounded-md border border-border bg-surface px-2.5 py-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] font-medium text-foreground`,children:p.label}),u(V,{variant:p.purpose===`vision`?`info`:`default`,children:p.purpose}),u(V,{variant:`default`,children:$(p.totalBytes)})]}),p.extraFilenames.length>0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s(`ai.hfExtras`,`Also downloads: {{files}}`,{files:p.extraFilenames.join(`, `)})}),a(`div`,{className:`mt-2 flex items-center gap-2`,children:[a(P,{size:`sm`,type:`button`,disabled:x.isPending||g,onClick:()=>x.mutate(p.model),children:[x.isPending?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(m,{className:`h-3.5 w-3.5`}),g?s(`ai.hfInstalled`,`Downloaded`):s(`ai.hfInstall`,`Download to {{node}}`,{node:e})]}),S!==void 0&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:S.phase===`verifying`?s(`ai.hfVerifying`,`verifying {{file}}…`,{file:S.file}):s(`ai.hfDownloading`,`{{file}} ({{index}}/{{count}}) — {{done}}{{total}}`,{file:S.file,index:S.fileIndex,count:S.fileCount,done:$(S.downloadedBytes),total:S.totalBytes===void 0?``:` / ${$(S.totalBytes)}`})})]}),x.isError&&u(`p`,{className:`mt-1.5 text-[11px] text-danger`,children:x.error instanceof Error?x.error.message:s(`common.error`,`Error`)})]})]})]})}function Ae({value:e,onChange:t}){let{t:n}=J(),r=O(),i=o({queryKey:Y,queryFn:()=>r.trpcClient.llm.listRuntimeNodes.query({})});return a(`div`,{children:[u(`div`,{className:`mb-1 text-[11px] font-medium text-foreground`,children:n(`ai.appleNode`,`Mac that runs it`)}),i.isPending&&a(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[u(T,{className:`h-3.5 w-3.5 animate-spin`}),n(`ai.appleAsking`,`Asking the nodes…`)]}),i.isError&&u(`p`,{className:`text-[11px] text-danger`,children:i.error instanceof Error?i.error.message:n(`ai.runtimesFailed`,`Failed to read runtime nodes`)}),i.isSuccess&&i.data.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:n(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}),i.isSuccess&&i.data.length>0&&u(`div`,{role:`radiogroup`,className:`space-y-1.5`,children:i.data.map(r=>{let i=Ee(r),o=i.nodeId===e;return a(`button`,{type:`button`,role:`radio`,"aria-checked":o,disabled:!i.selectable&&!o,onClick:()=>t(i.nodeId),className:`flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-left text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${o?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`}`,children:[a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block font-medium text-foreground`,children:i.nodeId}),i.detail!==null&&u(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:i.detail})]}),u(V,{variant:i.tone,children:n(i.labelKey,i.labelDefault)})]},i.nodeId)})}),u(`p`,{className:`mt-1.5 text-[10px] leading-relaxed text-foreground-subtle`,children:n(`ai.appleHint`,`Text only for now — notification titles and summaries. Apple refuses prompts framed as surveillance; when it does, the next profile in the chain answers instead.`)})]})}e();function je({kind:e,className:t}){let n=pe(e.kind);return n===null?u(`span`,{className:t,children:e.icon}):u(n,{className:t})}function Me({kinds:e,onPick:t,onCancel:r}){let{t:i}=J(),o=n(()=>Se(e),[e]);return u(K,{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}=J(),f=e.kind===`managed-local`,p=e.kind===`apple-foundation`,[m,h]=r(t?.appleFoundation?.nodeId??null),[g,_]=r(t?.name??e.label),[v,y]=r(()=>t===null?{}:me(t)),[b,x]=r(t?.runtime?.nodeId??`hub`),[S,C]=r(()=>t?.runtime===void 0?null:{model:t.runtime.model,modelId:t.model,supportsVision:t.supportsVision}),w=n(()=>_e(X(v.extraArgs)??``),[v.extraArgs]),E=()=>{if(p){if(m===null)return;i(we(g,t,v,m));return}if(!f){i(xe(e.kind,g,t,v));return}S!==null&&i(xe(e.kind,g,t,v,{nodeId:b,model:S.model,modelId:S.modelId,supportsVision:S.supportsVision}))},D=c||g.trim()===``||f&&S===null||p&&m===null;return u(K,{open:!0,onClose:o,title:t===null?d(`ai.newProfile`,`New {{kind}} profile`,{kind:e.label}):d(`ai.editProfile`,`Edit {{name}}`,{name:t.name}),error:l,width:`lg`,testId:`ai-profile-editor`,footer:a(s,{children:[f&&S===null&&u(V,{variant:`warning`,children:d(`ai.pickModelFirst`,`pick a model`)}),p&&m===null&&u(V,{variant:`warning`,children:d(`ai.pickAppleNodeFirst`,`pick a Mac`)}),a(P,{size:`sm`,type:`button`,disabled:D,onClick:E,children:[c&&u(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?d(`ai.createProfile`,`Create profile`):d(`ai.saveChanges`,`Save changes`)]})]}),children:a(`div`,{className:`space-y-3`,children:[a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`ai-profile-name`,children:d(`ai.name`,`Name`)}),u(I,{id:`ai-profile-name`,value:g,onChange:e=>_(e.target.value),placeholder:e.label})]}),f&&a(s,{children:[u(L,{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(I,{id:`ai-extra-args`,value:X(v.extraArgs)??``,onChange:e=>y({...v,extraArgs:e.target.value}),placeholder:ye.join(` `)}),w.length>0&&u(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:w.map((e,t)=>u(V,{variant:`default`,children:e},`${e}-${String(t)}`))}),u(`p`,{className:`mt-1 text-[10px] leading-relaxed text-foreground-subtle`,children:d(`ai.extraArgsHint`,`Flags this form does not already own. Vision models generally need --jinja; some language-only models do not like it. Context size, GPU layers, parallel slots, flash attention and the KV-cache types are set in the fields below — repeating one here is rejected at start.`)})]})]}),p&&u(Ae,{value:m,onChange:h}),u(H,{schema:e.configSchema,values:v,onChange:y}),t!==null&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`ai.secretHint`,`A stored API key is never shown. Leave it as-is to keep it; type a new value to replace it.`)})]})})}e();function Pe(e){return[{key:`name`,header:e.t(`ai.colProfile`,`Profile`),render:t=>{let n=e.kindByName.get(t.kind);return a(`span`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface`,title:n?.label??t.kind,children:n===void 0?u(`span`,{className:`text-xs text-foreground-subtle`,children:`?`}):u(je,{kind:n,className:`h-4 w-4 text-foreground-subtle`})}),a(`span`,{className:`min-w-0`,children:[u(`span`,{className:`block truncate text-sm font-medium text-foreground`,children:t.name}),e.testResult?.id===t.id&&u(`span`,{className:`block truncate text-[10px] ${e.testResult.ok?`text-success`:`text-danger`}`,children:e.testResult.text})]})]})}},{key:`kind`,header:e.t(`ai.colKind`,`Kind`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByName.get(t.kind)?.label??t.kind})},{key:`model`,header:e.t(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.model})},{key:`vision`,header:e.t(`ai.colVision`,`Vision`),align:`center`,nowrap:!0,render:t=>t.supportsVision?u(V,{variant:`info`,style:`outline`,children:e.t(`ai.vision`,`vision`)}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})},{key:`node`,header:e.t(`ai.colNode`,`Node`),nowrap:!0,render:e=>e.runtime===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(V,{variant:`default`,children:e.runtime.nodeId})},{key:`enabled`,header:e.t(`ai.colOn`,`On`),align:`center`,nowrap:!0,render:t=>u(W,{checked:t.enabled,onCheckedChange:()=>e.onToggle(t),"aria-label":q.t(`system.aiProfilesTab.toggle`,`toggle {{name}}`,{name:t.name})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>a(`span`,{className:`flex items-center justify-end gap-1`,children:[u(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest(t),title:e.t(`ai.test`,`Test`),children:e.testingId===t.id?u(T,{className:`h-3.5 w-3.5 animate-spin`}):u(M,{className:`h-3.5 w-3.5`})}),u(P,{size:`sm`,variant:`ghost`,type:`button`,disabled:!e.kindByName.has(t.kind),onClick:()=>e.onEdit(t),title:e.t(`common.edit`,`Edit`),children:u(b,{className:`h-3.5 w-3.5`})}),u(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:e.t(`common.delete`,`Delete`),children:u(h,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function Fe(){let{t:e}=J(),s=O(),{state:c,openNew:d,openEdit:f,close:p}=te(),[m,h]=r(null),[g,_]=r(null),[v,b]=r(null),x=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),S=o({queryKey:se,queryFn:async()=>(await s.trpcClient.llm.listProfileKinds.query({})).map(e=>({...e,configSchema:e.configSchema}))}),w=()=>{x.refetch()},E=i(()=>{h(null),b(null),p()},[p]);t(()=>{c.mode===`closed`&&h(null)},[c.mode]);let D=l({mutationFn:e=>s.trpcClient.llm.upsertProfile.mutate({profile:e}),onSuccess:()=>{E(),w()},onError:t=>b(t instanceof Error?t.message:e(`ai.saveFailed`,`Save failed`))}),ee=l({mutationFn:e=>s.trpcClient.llm.deleteProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:w}),k=l({mutationFn:e=>s.trpcClient.llm.testProfile.mutate({addonId:e.addonId,profileId:e.id}),onSuccess:(e,t)=>_({id:t.id,ok:e.ok,text:e.ok?q.t(`system.aiProfilesTab.testOk`,{text:e.text,tokens:e.usage.outputTokens,ms:e.latencyMs}):`${e.code}: ${e.message}`})}),A=x.data??[],j=n(()=>S.data??[],[S.data]),M=n(()=>{let e=new Map;for(let t of j)e.set(t.kind,t);return e},[j]),N=c.mode===`edit`?A.find(e=>e.id===c.id)??null:null,F=N===null?null:M.get(N.kind)??null,I=c.mode===`new`&&m===null,L=c.mode===`new`?m:F,B=c.mode===`edit`?N:null,V=L!==null&&(c.mode===`new`||B!==null);return a(ae,{embedded:!0,icon:C,title:e(`ai.profilesTitle`,`AI profiles`),subtitle:e(`ai.profilesSubtitle`,`One row = one usable model endpoint. The defaults below decide who answers when a feature names no profile.`),children:[u(`div`,{className:`flex justify-end`,children:a(P,{size:`sm`,type:`button`,onClick:()=>{b(null),h(null),d()},children:[u(y,{className:`h-3.5 w-3.5`}),e(`ai.addProfile`,`Add profile`)]})}),x.isError&&u(ne,{title:e(`ai.loadFailed`,`Failed to load profiles`),message:x.error instanceof Error?x.error.message:e(`common.error`,`Error`),onRetry:()=>void x.refetch()}),u(Ie,{profiles:A}),x.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(T,{className:`h-6 w-6 animate-spin text-primary`})}),!x.isLoading&&A.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noProfiles`,`No AI profiles yet. Click "Add profile" to configure one.`)}),A.length>0&&u(z,{headingId:`ai-profiles-list`,title:e(`ai.profilesList`,`Profiles`),children:u(R,{columns:Pe({kindByName:M,testResult:g,testingId:k.isPending?k.variables?.id??null:null,t:e,onToggle:e=>D.mutate({...e,enabled:!e.enabled,apiKey:`__redacted__`}),onTest:e=>k.mutate(e),onEdit:e=>{M.has(e.kind)&&(b(null),h(null),f(e.id))},onDelete:e=>ee.mutate(e)}),rows:A,rowKey:e=>e.id,minWidthPx:760,bordered:!1,maxBodyHeight:`max-h-[60vh]`})}),I&&u(Me,{kinds:j,onCancel:E,onPick:e=>{b(null),h(e)}}),V&&L!==null&&u(Ne,{kind:L,existing:B,saving:D.isPending,error:v,onSave:e=>D.mutate(e),onCancel:E})]})}function Ie({profiles:e}){let{t}=J(),n=O(),r=o({queryKey:ce,queryFn:()=>n.trpcClient.llm.getDefaults.query({})}),i=l({mutationFn:e=>n.trpcClient.llm.setDefault.mutate({selector:{purpose:e.purpose},profileId:e.profileId}),onSuccess:()=>{r.refetch()}}),s=e=>(r.data??[]).find(t=>`purpose`in t.selector&&t.selector.purpose===e)?.profileId??``,c=e=>e===`vision`?t(`ai.defaultVision`,`Default vision profile`):t(`ai.defaultText`,`Default text profile`);return u(z,{headingId:`ai-profiles-defaults`,title:t(`ai.defaultsTitle`,`Defaults`),children:u(`div`,{className:`${d} grid gap-4 sm:grid-cols-2`,children:de.map(({purpose:n,visionOnly:r})=>{let o=r?e.filter(e=>e.supportsVision):e,l=s(n),d=e.find(e=>e.id===l);return a(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,htmlFor:`llm-default-${n}`,children:c(n)}),u(G,{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 q.t(`system.aiRuntimes.sizeGb`,{value:(e/1e9).toFixed(1)})}function ze(){let{t:e}=J(),t=O(),r=o({queryKey:Y,refetchInterval:Le,queryFn:()=>t.trpcClient.llm.listRuntimeNodes.query({})}),i=n(()=>[{key:`node`,header:e(`ai.colNode`,`Node`),render:e=>u(`span`,{className:`text-sm font-medium text-foreground`,children:e.nodeId})},{key:`state`,header:e(`ai.colState`,`State`),nowrap:!0,render:t=>a(`span`,{className:`flex items-center gap-1.5`,children:[u(V,{variant:t.reachable?`success`:`danger`,children:t.reachable?t.status?.state??e(`ai.ready`,`ready`):e(`ai.unreachable`,`unreachable`)}),t.status?.downloadProgress!==void 0&&u(V,{variant:`info`,children:`${String(Math.round(t.status.downloadProgress*100))}%`})]})},{key:`model`,header:e(`ai.colModel`,`Model`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.status?.modelId??`—`})},{key:`disk`,header:e(`ai.colDisk`,`On disk`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.disk===void 0?`—`:Re(e.disk.modelsBytes)})},{key:`apple`,header:e(`ai.colApple`,`Apple on-device`),render:t=>{let n=Ee(t);return a(`span`,{className:`flex flex-col items-start gap-0.5`,children:[u(V,{variant:n.tone,children:e(n.labelKey,n.labelDefault)}),n.detail!==null&&u(`span`,{className:`text-[10px] text-foreground-subtle`,children:n.detail})]})}},{key:`error`,header:e(`ai.colError`,`Error`),render:e=>e.error===void 0?u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):u(`span`,{className:`text-[11px] text-danger`,children:e.error})}],[e]),s=r.data??[];return a(ae,{embedded:!0,icon:k,title:e(`ai.runtimesTitle`,`Managed runtimes`),subtitle:e(`ai.runtimesSubtitle`,`Nodes advertising the llm-runtime capability: what each has loaded, what it is downloading, and how much model data sits on its disk.`),children:[r.isError&&u(ne,{title:e(`ai.runtimesFailed`,`Failed to read runtime nodes`),message:r.error instanceof Error?r.error.message:e(`common.error`,`Error`),onRetry:()=>void r.refetch()}),s.length===0?u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noRuntimes`,`No node advertises the llm-runtime capability.`)}):u(z,{headingId:`ai-runtimes-list`,title:e(`ai.runtimesList`,`Nodes`),children:u(R,{columns:i,rows:s,rowKey:e=>e.nodeId,minWidthPx:760,bordered:!1,maxBodyHeight:B})})]})}var Be=x(`/addon/ai/test-chat`),Ve=x(`/addon/ai/test-chat/chats`),He=6e5;function Ue(e){let t=e.firstTokenTimeoutMs;if(!(typeof t!=`number`||!Number.isFinite(t)||t<=0))return Math.min(Math.round(t),He)}function We(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ge(e){if(!We(e))return null;let t=e.kind;return t!==`snapshot`&&t!==`track`||typeof e.mimeType!=`string`||typeof e.sizeBytes!=`number`?null:{kind:t,mimeType:e.mimeType,sizeBytes:e.sizeBytes,...typeof e.mediaKind==`string`?{mediaKind:e.mediaKind}:{},...typeof e.capturedAt==`number`?{capturedAt:e.capturedAt}:{},...typeof e.thumbnailBase64==`string`?{thumbnailBase64:e.thumbnailBase64}:{}}}var Ke=[`resolving-image`,`connecting`,`first-token-wait`,`streaming`];function qe(e){let t;try{t=JSON.parse(e)}catch{return null}if(!We(t))return null;switch(t.kind){case`status`:{let e=Ke.find(e=>e===t.phase);return e===void 0?null:{kind:`status`,phase:e}}case`meta`:return typeof t.profileName!=`string`||typeof t.model!=`string`?null:{kind:`meta`,profileName:t.profileName,model:t.model,mediaSent:Ge(t.mediaSent),streamed:t.streamed===!0,firstTokenTimeoutMs:typeof t.firstTokenTimeoutMs==`number`?t.firstTokenTimeoutMs:0};case`token`:return typeof t.text==`string`?{kind:`token`,text:t.text}:null;case`done`:return{kind:`done`,inputTokens:typeof t.inputTokens==`number`?t.inputTokens:0,outputTokens:typeof t.outputTokens==`number`?t.outputTokens:0,latencyMs:typeof t.latencyMs==`number`?t.latencyMs:0,truncated:t.truncated===!0,...typeof t.conversationId==`string`?{conversationId:t.conversationId}:{}};case`error`:return{kind:`error`,code:typeof t.code==`string`?t.code:`adapter-error`,message:typeof t.message==`string`?t.message:q.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 q.t(`helpers.aiTestChat.phaseImage`);case`connecting`:return q.t(`helpers.aiTestChat.phaseConnecting`);case`first-token-wait`:return t>0?q.t(`helpers.aiTestChat.phaseWaitUpTo`,{seconds:Math.round(t/1e3)}):q.t(`helpers.aiTestChat.phaseWait`);case`streaming`:return q.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}=J(),s=O(),[l,d]=r(``),[f,p]=r(``),[m,g]=r(``),[y,b]=r([]),[x,S]=r(null),[C,w]=r(`none`),[T,E]=r(`throwaway`),[k,N]=r(null),[te,L]=r([]),[R,z]=r(null),[B,V]=r(null),H=c(null);t(()=>()=>H.current?.abort(),[]);let U=i(async()=>{let e=await fetch(Ve,{credentials:`same-origin`});e.ok&&L((await e.json()).chats??[])},[]);t(()=>{T===`persistent`&&U()},[T,U]);let W=o({queryKey:oe,queryFn:()=>s.trpcClient.llm.listProfiles.query({})}),K=n(()=>(W.data??[]).filter(e=>e.enabled),[W.data]),q=K.find(e=>e.id===l)??null,re=B!==null,ie=i(async(t,n)=>{let r=new AbortController;H.current=r,z(null);let i=Ue(q??{});V({...it,firstTokenTimeoutMs:i??0});let a=``,o=null,s,c=null,u=null,d;try{let e=await fetch(Be,{method:`POST`,headers:{"content-type":`application/json`},credentials:`same-origin`,signal:r.signal,body:JSON.stringify({profileId:l,messages:t,...f.trim()===``?{}:{system:f.trim()},...n===void 0?{}:{attachment:n},...i===void 0?{}:{firstTokenTimeoutMs:i},...T===`persistent`?{persist:!0,...k===null?{}:{conversationId:k}}:{}})});if(!e.ok||e.body===null){let t=await e.text().catch(()=>``);throw Error(t.length>0?t:`HTTP ${String(e.status)}`)}for await(let t of Je(e.body))switch(t.kind){case`status`:V(e=>({...e??it,phase:t.phase}));break;case`meta`:o=t.mediaSent,s=t.model,V(e=>({...e??it,firstTokenTimeoutMs:t.firstTokenTimeoutMs,mediaSent:t.mediaSent}));break;case`token`:a+=t.text,V(e=>({...e??it,text:a}));break;case`done`:u={outputTokens:t.outputTokens,latencyMs:t.latencyMs},d=t.conversationId;break;case`error`:c=`${t.code}: ${t.message}`;break}}catch(t){r.signal.aborted||z(t instanceof Error?t.message:e(`common.error`,`Error`))}finally{H.current=null,V(null)}d!==void 0&&(N(d),U());let p=r.signal.aborted&&a.length>0;c===null&&a.length===0&&!p||b(e=>[...e,{id:`a-${String(Date.now())}`,role:`assistant`,content:c??a,...c===null?{}:{failed:!0},...o===null?{}:{attachment:o},...s!==void 0&&c===null?{model:s}:{},...u===null?{}:u}])},[T,k,q,l,U,f,e]),se=i(()=>{let e=m.trim();if(e===``||l===``||re)return;let t={id:`u-${String(Date.now())}`,role:`user`,content:e,...x===null?{}:{attachmentLabel:x.label,attachmentKind:x.ref.kind}},n=[...y,t];b(n),g(``);let r=x?.ref;S(null),w(`none`),ie(T===`persistent`&&k!==null?[{role:`user`,content:e}]:Ye(n),r)},[T,k,m,x,l,ie,re,y]),ce=()=>H.current?.abort(),Y=()=>{H.current?.abort(),b([]),S(null),g(``),z(null),V(null),N(null)},le=async e=>{H.current?.abort();let t=await fetch(`${Ve}/${e}`,{credentials:`same-origin`});if(!t.ok)return;let n=await t.json();N(e),b(Ze(n)),V(null),z(null)};return a(ae,{embedded:!0,icon:ee,title:e(`ai.testTitle`,`Test chat`),subtitle:e(T===`persistent`?`ai.testSubtitlePersistent`:`ai.testSubtitle`,T===`persistent`?`Conversations are saved for you and can be reopened. Throwaway mode is still available.`:`A throwaway conversation with one profile. Attach a live camera snapshot or a recent track to check the model can actually read a picture. Nothing is saved — only the usage row.`),children:[u(`div`,{className:`flex justify-end`,children:a(P,{size:`sm`,variant:`secondary`,type:`button`,disabled:y.length===0&&x===null,onClick:Y,children:[u(h,{className:`h-3.5 w-3.5`}),e(`ai.clearChat`,`Clear`)]})}),a(F,{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(G,{id:`ai-test-profile`,value:l,onChange:e=>d(e.target.value),options:[{value:``,label:e(`ai.selectProfile`,`Select a profile…`)},...K.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.supportsVision?` · vision`:``}`}))]}),K.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(I,{id:`ai-test-system`,value:f,onChange:e=>p(e.target.value),placeholder:e(`ai.systemPlaceholder`,`Answer in one short sentence.`)})]})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(P,{size:`sm`,variant:T===`throwaway`?`primary`:`outline`,type:`button`,onClick:()=>{E(`throwaway`),N(null)},children:e(`ai.throwawayMode`,`Throwaway`)}),u(P,{size:`sm`,variant:T===`persistent`?`primary`:`outline`,type:`button`,onClick:()=>E(`persistent`),children:e(`ai.saveConversation`,`Save conversation`)})]}),T===`persistent`&&a(`div`,{className:`space-y-2`,children:[u(`div`,{className:`flex items-center gap-2`,children:a(P,{size:`sm`,variant:`secondary`,type:`button`,onClick:Y,children:[u(j,{className:`h-3.5 w-3.5`}),e(`ai.newChat`,`New chat`)]})}),te.length>0&&u(`div`,{className:`max-h-36 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:te.map(e=>u(`button`,{type:`button`,onClick:()=>void le(e.id),className:`flex w-full px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover ${e.id===k?`bg-primary/10`:``}`,children:u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.title})},e.id))})]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e(`ai.streamNote`,`The answer streams as the model produces it. A cold model can take a while to load — the status line says which phase it is in.`)}),q!==null&&!q.supportsVision&&u(`p`,{className:`text-[10px] text-warning`,children:e(`ai.notVision`,`This profile is not vision-capable — an attached image will be refused before anything is read.`)})]}),R!==null&&u(ne,{title:e(`ai.chatFailed`,`The test call failed`),message:R}),u(ot,{turns:y,live:B}),a(F,{className:`space-y-2 p-3`,children:[x!==null&&a(`div`,{className:`flex items-center gap-2 rounded-md border border-border bg-surface px-2.5 py-1.5`,children:[x.ref.kind===`snapshot`?u(A,{className:`h-3.5 w-3.5 text-foreground-subtle`}):u(v,{className:`h-3.5 w-3.5 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-[11px] text-foreground`,children:x.label}),u(P,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>S(null),children:u(D,{className:`h-3.5 w-3.5`})})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(P,{size:`sm`,variant:C===`snapshot`?`primary`:`outline`,type:`button`,onClick:()=>w(C===`snapshot`?`none`:`snapshot`),children:[u(A,{className:`h-3.5 w-3.5`}),e(`ai.attachSnapshot`,`Camera snapshot`)]}),a(P,{size:`sm`,variant:C===`track`?`primary`:`outline`,type:`button`,onClick:()=>w(C===`track`?`none`:`track`),children:[u(v,{className:`h-3.5 w-3.5`}),e(`ai.attachTrack`,`Recent track`)]})]}),C===`snapshot`&&u(lt,{onPick:t=>{S({ref:{kind:`snapshot`,deviceId:t.id},label:e(`ai.snapshotOf`,`Snapshot of {{name}}`,{name:t.name})}),w(`none`)}}),C===`track`&&u(dt,{onPick:(t,n)=>{S({ref:{kind:`track`,trackId:t.trackId,deviceId:t.deviceId},label:e(`ai.trackOf`,`{{class}} on {{name}}`,{class:t.label??t.className,name:n})}),w(`none`)}}),a(`div`,{className:`flex items-center gap-2`,children:[u(I,{value:m,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),se())},placeholder:e(`ai.messagePlaceholder`,`Ask the model something…`),"aria-label":e(`ai.message`,`Message`)}),re?a(P,{size:`sm`,variant:`secondary`,type:`button`,onClick:ce,children:[u(_,{className:`h-3.5 w-3.5`}),e(`ai.stop`,`Stop`)]}):a(P,{size:`sm`,type:`button`,disabled:m.trim()===``||l===``,onClick:se,children:[u(M,{className:`h-3.5 w-3.5`}),e(`ai.send`,`Send`)]})]})]})]})}function ot({turns:e,live:t}){let{t:n}=J();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(F,{children:a(`div`,{className:`max-h-[50vh] space-y-2 overflow-y-auto p-3`,children:[e.map(e=>u(st,{turn:e},e.id)),t!==null&&a(`div`,{className:`space-y-1`,children:[t.mediaSent!==null&&u(ct,{attachment:t.mediaSent}),t.text.length>0&&u(st,{turn:{id:`live`,role:`assistant`,content:t.text},streaming:!0}),a(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(T,{className:`h-3.5 w-3.5 animate-spin`}),$e(t.phase,t.firstTokenTimeoutMs)]})]})]})})}function st({turn:e,streaming:t=!1}){let{t:n}=J(),r=e.role===`user`,i=e.failed===!0?`border-danger/40 bg-danger/10`:`border-border bg-surface`;return u(`div`,{className:`flex ${r?`justify-end`:`justify-start`}`,children:a(`div`,{className:`max-w-[85%] rounded-lg border px-3 py-2 ${r?`border-primary/40 bg-primary/10`:i}`,children:[a(`p`,{className:`whitespace-pre-wrap break-words text-xs text-foreground`,children:[e.content,t&&u(`span`,{className:`ml-0.5 animate-pulse text-primary`,children:`▌`})]}),e.attachment!==void 0&&u(ct,{attachment:e.attachment}),e.attachmentLabel!==void 0&&a(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachmentKind===`track`?u(v,{className:`h-3 w-3`}):u(A,{className:`h-3 w-3`}),e.attachmentLabel]}),e.attachment!==void 0&&a(`p`,{className:`mt-1 flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[e.attachment.kind===`snapshot`?u(A,{className:`h-3 w-3`}):u(v,{className:`h-3 w-3`}),Qe(e.attachment)]}),e.model!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:n(`system.aiTestChat.tokMs`,`{{model}} · {{value2}} tok · {{value3}} ms`,{model:e.model,value2:String(e.outputTokens??0),value3:String(e.latencyMs??0)})})]})})}function ct({attachment:e}){let{t}=J(),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}=J(),n=U({isCamera:!0,projection:`slim`}),r=(n.data??[]).filter(e=>!e.disabled);return n.isLoading?u(T,{className:`h-4 w-4 animate-spin text-foreground-subtle`}):r.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noCameras`,`No camera found.`)}):u(`div`,{className:`grid max-h-56 grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-4`,children:r.map(t=>u(ut,{device:t,onPick:e},t.id))})}function ut({device:e,onPick:t}){let{t:n}=J(),{src:r}=p(e.id,{width:rt});return a(`button`,{type:`button`,onClick:()=>t(e),className:`overflow-hidden rounded-md border border-border bg-surface text-left transition-colors hover:border-primary/50`,children:[u(`span`,{className:`block aspect-video w-full bg-background-elevated`,children:r!==null&&u(`img`,{src:r,alt:``,className:`h-full w-full object-cover`,loading:`lazy`})}),a(`span`,{className:`flex items-center gap-1 px-2 py-1`,children:[!e.online&&u(V,{variant:`warning`,children:n(`common.off`)}),u(`span`,{className:`truncate text-[10px] text-foreground`,children:e.name})]})]})}function dt({onPick:e}){let{t}=J(),r=O(),i=U({isCamera:!0,projection:`slim`}),s=n(()=>(i.data??[]).map(e=>e.id),[i.data]),c=n(()=>{let e=new Map;for(let t of i.data??[])e.set(t.id,t.name);return e},[i.data]),l=o({queryKey:[...et,s.length],enabled:s.length>0,queryFn:()=>r.trpcClient.pipelineAnalytics.listRecentTracks.query({deviceIds:[...s],since:Date.now()-tt,limit:nt,projection:`slim`})});if(i.isLoading||l.isLoading)return u(T,{className:`h-4 w-4 animate-spin text-foreground-subtle`});let d=l.data?.tracks??[];return d.length===0?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`ai.noTracks`,`No track in the last 6 hours.`)}):u(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,children:d.map(t=>a(`button`,{type:`button`,onClick:()=>e(t,c.get(t.deviceId)??String(t.deviceId)),className:`flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-[11px] hover:bg-surface-hover`,children:[u(v,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className}),u(`span`,{className:`shrink-0 text-foreground-subtle`,children:c.get(t.deviceId)??t.deviceId}),u(`span`,{className:`shrink-0 text-foreground-subtle`,children:new Date(t.lastSeen).toLocaleTimeString()})]},t.trackId))})}e();var ft=1440*60*1e3,pt=[1,7,30,90];function mt(){let{t:e}=J(),t=O(),[i,s]=r(7),c=n(()=>{let e=new Date;return e.setHours(0,0,0,0),e.getTime()-(i-1)*ft},[i]),l=o({queryKey:oe,queryFn:()=>t.trpcClient.llm.listProfiles.query({})}),d=o({queryKey:[...ue,i],queryFn:()=>t.trpcClient.llm.getUsage.query({since:c})}),f=n(()=>{let e=new Map;for(let t of l.data??[])e.set(t.id,t.name);return e},[l.data]),p=n(()=>[{key:`day`,header:e(`ai.colDay`,`Day`),nowrap:!0,render:e=>e.day},{key:`consumer`,header:e(`ai.colConsumer`,`Consumer`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:e.consumer})},{key:`profile`,header:e(`ai.colProfile`,`Profile`),render:e=>u(`span`,{className:`text-[11px] text-foreground`,children:f.get(e.profileId)??e.profileId})},{key:`calls`,header:e(`ai.colCalls`,`Calls`),align:`right`,nowrap:!0,render:e=>String(e.calls)},{key:`okErr`,header:e(`ai.colOkErr`,`OK / err`),align:`right`,nowrap:!0,render:e=>u(`span`,{className:e.errorCalls>0?`text-danger`:void 0,children:`${String(e.okCalls)} / ${String(e.errorCalls)}`})},{key:`tokens`,header:e(`ai.colTokens`,`In / out tok`),align:`right`,nowrap:!0,render:e=>`${String(e.inputTokens)} / ${String(e.outputTokens)}`},{key:`latency`,header:e(`ai.colAvgMs`,`Avg ms`),align:`right`,nowrap:!0,render:e=>String(Math.round(e.avgLatencyMs))}],[f,e]),m=d.data??[];return a(ae,{embedded:!0,icon:S,title:e(`ai.usageTitle`,`Usage`),subtitle:e(`ai.usageSubtitle`,`Server-side rollup per day, consumer and profile — never raw call rows. Errors are counted, so a profile that always fails is visible here before a feature reports it.`),actions:u(`div`,{className:`w-40`,children:u(G,{"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(ne,{title:e(`ai.usageFailed`,`Failed to read usage`),message:d.error instanceof Error?d.error.message:e(`common.error`,`Error`),onRetry:()=>void d.refetch()}),m.length===0?u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`ai.noUsage`,`No AI calls in this window.`)}):u(z,{headingId:`ai-usage-list`,title:e(`ai.usageList`,`Rollup`),children:u(R,{columns:p,rows:m,rowKey:e=>`${e.day}|${e.consumer}|${e.profileId}`,minWidthPx:720,bordered:!1,maxBodyHeight:B})})]})}function ht(){let{t:e}=J(),t=re(`/system/ai`,{t:e,isAdmin:!0})??{icon:C,title:e(`system.ai`,`AI`)};return u(ie,{icon:t.icon,title:t.title,defaultSection:`profiles`,sectionsLabel:`${t.title} sections`,sections:[{id:`profiles`,label:e(`ai.tabProfiles`,`Profiles`),content:u(Fe,{})},{id:`runtimes`,label:e(`ai.tabRuntimes`,`Runtimes`),content:u(ze,{})},{id:`usage`,label:e(`ai.tabUsage`,`Usage`),content:u(mt,{})},{id:`test`,label:e(`ai.tabTest`,`Test`),content:u(at,{})}]})}export{ht as AiProfilesPage,ht as default};