@camstack/server 1.2.890 → 1.2.892

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/api/trpc/generated-cap-mounts.js +2 -1
  3. package/dist/api/trpc/generated-cap-routers.js +212 -39
  4. package/dist/core/addon/addon-registry.service.js +47 -0
  5. package/dist/core/addon/retire-undeclared-fixed-integrations.js +57 -0
  6. package/package.json +31 -19
  7. package/system/dist/addon-runner.js +25 -9
  8. package/system/dist/addon-runner.mjs +25 -9
  9. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  14. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  15. package/system/dist/builtins/autotrack/index.js +1 -1
  16. package/system/dist/builtins/autotrack/index.mjs +1 -1
  17. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  18. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  19. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  20. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  21. package/system/dist/builtins/camera-grid/addon.d.ts +65 -41
  22. package/system/dist/builtins/camera-grid/grid-blocks.d.ts +51 -0
  23. package/system/dist/builtins/camera-grid/grid-camera-device.d.ts +4 -3
  24. package/system/dist/builtins/camera-grid/grid-layout-native-provider.d.ts +3 -1
  25. package/system/dist/builtins/camera-grid/grid-plan.d.ts +3 -3
  26. package/system/dist/builtins/camera-grid/index.d.ts +2 -6
  27. package/system/dist/builtins/camera-grid/index.js +431 -727
  28. package/system/dist/builtins/camera-grid/index.mjs +428 -719
  29. package/system/dist/builtins/composer/composed-device.d.ts +12 -2
  30. package/system/dist/builtins/composer/composer.addon.js +28 -10
  31. package/system/dist/builtins/composer/composer.addon.mjs +28 -10
  32. package/system/dist/builtins/composer/composition-declarations.d.ts +3 -1
  33. package/system/dist/builtins/console-logging/index.js +1 -1
  34. package/system/dist/builtins/console-logging/index.mjs +1 -1
  35. package/system/dist/builtins/core-blocks/core-blocks.addon.js +283 -51
  36. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +284 -52
  37. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +19 -1
  38. package/system/dist/builtins/core-blocks/power-source-devices.d.ts +9 -0
  39. package/system/dist/builtins/core-blocks/power-source-service.d.ts +39 -2
  40. package/system/dist/builtins/core-blocks/tags-service.d.ts +20 -3
  41. package/system/dist/builtins/core-blocks/tags-wiring.d.ts +15 -2
  42. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  43. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  44. package/system/dist/builtins/device-manager/device-identifiers-action.d.ts +9 -0
  45. package/system/dist/builtins/device-manager/device-manager.addon.js +172 -5
  46. package/system/dist/builtins/device-manager/device-manager.addon.mjs +172 -5
  47. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  48. package/system/dist/builtins/device-manager/device-row-store.d.ts +3 -2
  49. package/system/dist/builtins/device-manager/device-state-mirror.d.ts +7 -0
  50. package/system/dist/builtins/device-manager/workload-transition.d.ts +23 -0
  51. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  52. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  53. package/system/dist/builtins/keychain/index.js +4 -4
  54. package/system/dist/builtins/keychain/index.mjs +4 -4
  55. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  56. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  57. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  58. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  59. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  60. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  61. package/system/dist/builtins/loki-logging/index.js +1 -1
  62. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  63. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  64. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  65. package/system/dist/builtins/platform-probe/index.js +1 -1
  66. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  67. package/system/dist/builtins/record-entries/index.js +1 -1
  68. package/system/dist/builtins/record-entries/index.mjs +1 -1
  69. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  70. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  71. package/system/dist/builtins/snapshot/index.js +1 -1
  72. package/system/dist/builtins/snapshot/index.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  74. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  75. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  76. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  77. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  78. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  79. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  80. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  81. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  82. package/system/dist/builtins/system-config/system-config.addon.mjs +284 -284
  83. package/system/dist/builtins/winston-logging/index.js +1 -1
  84. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  85. package/system/dist/{capture-engine-C1vdBL88.js → capture-engine-DHmlkW_d.js} +1 -1
  86. package/system/dist/{capture-engine-B1bMuzVX.mjs → capture-engine-sl6e9f9S.mjs} +1 -1
  87. package/system/dist/{composition-sources-Dj6qn5PP.mjs → composition-sources-CznD85Ri.mjs} +1 -1
  88. package/system/dist/{composition-sources-BfLlyKRe.js → composition-sources-PqcZfe3j.js} +1 -1
  89. package/system/dist/{constants-Ba51ywI4.mjs → constants-CHwj_mIM.mjs} +1 -1
  90. package/system/dist/{constants-DuB_xXYx.js → constants-_2SOk0By.js} +1 -1
  91. package/system/dist/{device-ca-CkXjf3ms.mjs → device-ca-D2H1EMUY.mjs} +1 -1
  92. package/system/dist/{device-ca-CVjaotgX.js → device-ca-WIEO5ZcE.js} +1 -1
  93. package/system/dist/{dist-BKojK6Wf.mjs → dist-DbAhCrHy.mjs} +2468 -454
  94. package/system/dist/{dist-BjhII4Uq.js → dist-yx2KHo3b.js} +2575 -453
  95. package/system/dist/file-host-worker.js +1 -1
  96. package/system/dist/file-host-worker.mjs +1 -1
  97. package/system/dist/{hub-identity-C0qf888i.mjs → hub-identity-BcvZqT0L.mjs} +1 -1
  98. package/system/dist/{hub-identity-C0ehkt78.js → hub-identity-Buegac-w.js} +1 -1
  99. package/system/dist/{hub-mdns-ciao-BYe34S2Q.mjs → hub-mdns-ciao-B6K_dO2s.mjs} +2 -2
  100. package/system/dist/{hub-mdns-ciao-DJHjyjvT.js → hub-mdns-ciao-DcNPj7WJ.js} +2 -2
  101. package/system/dist/index.js +33 -19
  102. package/system/dist/index.mjs +33 -19
  103. package/system/dist/kernel/moleculer/child-cap-dispatch.d.ts +3 -6
  104. package/system/dist/kernel/moleculer/switch-toggle.d.ts +7 -2
  105. package/system/dist/{legacy-integration-rows-door-G6EceE_J.js → legacy-integration-rows-door-BsZyVNiR.js} +1 -1
  106. package/system/dist/{legacy-integration-rows-door-BEYgXSXr.mjs → legacy-integration-rows-door-DHOJeDPG.mjs} +1 -1
  107. package/system/dist/{rename-composition-block-D1mO51F9.js → rename-composition-block-BXMor7MR.js} +1 -1
  108. package/system/dist/{rename-composition-block-D6bq3Twf.mjs → rename-composition-block-DcVS1LuC.mjs} +1 -1
  109. package/system/dist/{restore-archive-FXsCWq_f.mjs → restore-archive-BG8VJ8Ar.mjs} +82 -82
  110. package/system/dist/{restore-archive-CJvMq13C.js → restore-archive-BURufVQd.js} +1 -1
  111. package/system/dist/{wal-maintenance-Ci9Dl-lB.mjs → wal-maintenance-B4wGD6QR.mjs} +0 -0
  112. package/system/dist/{wal-maintenance-COJ_JxrD.js → wal-maintenance-CeaJyKNT.js} +0 -0
  113. package/system/package.json +2 -5
  114. package/system/dist/builtins/camera-grid/grid-camera-declarations.d.ts +0 -59
  115. package/system/dist/builtins/camera-grid/grid-instances.d.ts +0 -40
  116. package/system/dist/builtins/camera-grid/grid-record-kinds.d.ts +0 -31
  117. package/system/dist/builtins/camera-grid/migrations/__fixtures__/seed.d.ts +0 -13
  118. package/system/dist/builtins/camera-grid/migrations/camera-grids-to-records.d.ts +0 -26
  119. package/system/dist/builtins/camera-grid/migrations/index.d.ts +0 -6
@@ -1,77 +1,10 @@
1
- import { Cr as declarationOwnerNodeId, Do as snapshotCapability, Fo as streamCatalogCapability, Gl as DeviceType, Jl as EventCategory, Jn as cameraGridLayoutCapability, Kl as errMsg, Ks as BaseAddon, Ln as bareAddonId, Pt as MOTION_CLOSE_AFTER_MS, Qi as memoizePinnedFfmpeg, Uc as createEvent, Ul as DeviceFeature, V as DERIVED_CAMERA_SILENCED_CAP_NAMES, _s as buildFfmpegArgs, cl as isInstanceEnabled, gc as RecordIntegrationInstances, gi as integrationInstancesCapability, ia as motionCapability, qc as defineEntryKind, rl as hydrateSchema, tt as DeclaredDevices, v as BaseDevice } from "../../dist-BKojK6Wf.mjs";
1
+ import { Ar as declarationOwnerNodeId, It as MOTION_CLOSE_AFTER_MS, Mo as selectEngineHostedBlocks, Ps as buildFfmpegArgs, Qo as sweepLegacyEngineRows, Si as hostEngineDevice, Ts as COMPOSER_ADDON_ID, Tt as HostedWithdrawalGate, Un as bareAddonId, V as DERIVED_CAMERA_SILENCED_CAP_NAMES, Vo as snapshotCapability, Yi as legacySweepDone, Yo as streamCatalogCapability, er as cameraGridLayoutCapability, fu as EventCategory, ga as motionCapability, la as memoizePinnedFfmpeg, pr as compileHelper, sl as createEvent, su as DeviceFeature, uc as BaseAddon, uu as errMsg, v as BaseDevice, xl as hydrateSchema } from "../../dist-DbAhCrHy.mjs";
2
2
  import { z } from "zod";
3
- import { createHash } from "node:crypto";
4
3
  import { FfmpegProcess } from "@camstack/types/node";
5
4
  import { promises } from "node:fs";
6
5
  import { join } from "node:path";
7
6
  import { spawn } from "node:child_process";
8
7
  import { createServer } from "node:http";
9
- //#region src/builtins/camera-grid/grid-camera-declarations.ts
10
- /**
11
- * Turning persisted grid rows into the camera declarations `DeclaredDevices`
12
- * reconciles.
13
- *
14
- * Modelled on `terminal-camera-declarations.ts`, and for the same reasons: the
15
- * declaration set is the ONLY thing standing between a transient RPC failure
16
- * and a sweep that deletes every camera this addon owns.
17
- */
18
- /** The prefix every stable id this addon has ever minted starts with. */
19
- var GRID_CAMERA_STABLE_ID_PREFIX = "camera-grid-";
20
- /**
21
- * The stable id is `camera-grid-<instance uuid>` and NOTHING else.
22
- *
23
- * A stable id is permanent the instant it is minted: bindings, grid layouts in
24
- * other addons, recording rows, the timeline and this addon's own tombstones
25
- * all reference it, and a device whose stable id changes is a NEW camera with
26
- * an empty history. So it may only be derived from something that itself never
27
- * changes.
28
- *
29
- * The instance uuid is the only such thing here. Deriving it from the NAME
30
- * would rename-break every reference; deriving it from the CELLS would mint a
31
- * new camera every time the operator drags a rectangle — which is the entire
32
- * activity this addon exists for. Terminal learned the same lesson from the
33
- * other end: its original one-camera-per-node id is permanent, and its profile
34
- * migration had to ENRICH that row rather than mint a replacement.
35
- */
36
- function newGridCameraStableId(instanceId) {
37
- return `${GRID_CAMERA_STABLE_ID_PREFIX}${instanceId}`;
38
- }
39
- /**
40
- * Explicit persisted instances only. A grid camera exists because an operator
41
- * created a grid, never because some source camera happens to exist.
42
- *
43
- * A grid with NO cells is declared like any other: creation is name-only and
44
- * the layout is authored afterwards in the camera's own device details, so
45
- * "no cells yet" is the normal first state, not an invalid row.
46
- */
47
- function buildGridCameraDeclarations(instances) {
48
- return instances.filter((instance) => instance.enabled).map((instance) => ({
49
- stableId: instance.cameraStableId,
50
- name: instance.name,
51
- config: { instanceId: instance.id }
52
- }));
53
- }
54
- /**
55
- * The rows `DeclaredDevices` is allowed to consider — every live declaration
56
- * plus ONE bounded batch of orphans.
57
- *
58
- * Two guards, both copied from Terminal because both were paid for there:
59
- *
60
- * 1. **An unknown integration id yields an EMPTY index.** `null`/`undefined`
61
- * means "the integration lookup has not answered", which is not the same
62
- * fact as "this addon owns no rows" — and only the second one may drive a
63
- * withdrawal.
64
- * 2. **The orphan batch is bounded and deterministically ordered.** The generic
65
- * sweep refuses an over-limit set outright; selecting a batch here drains a
66
- * large historical orphan set across passes without weakening that guard.
67
- */
68
- function gridCameraReconciliationIndex(rows, integrationId, declarations, managedStableIds = /* @__PURE__ */ new Set()) {
69
- if (!integrationId) return [];
70
- const declared = new Set(declarations.map((camera) => camera.stableId));
71
- const owned = rows.filter((row) => row.integrationId === integrationId && (declared.has(row.stableId) || managedStableIds.has(row.stableId) || row.stableId.startsWith(GRID_CAMERA_STABLE_ID_PREFIX)));
72
- return [...owned.filter((row) => declared.has(row.stableId)), ...owned.filter((row) => !declared.has(row.stableId)).sort((left, right) => left.id - right.id).slice(0, 32)];
73
- }
74
- //#endregion
75
8
  //#region src/builtins/camera-grid/grid-device-settings.ts
76
9
  /** The widget id, registered in `ui-library`'s `HOST_WIDGETS`. */
77
10
  var GRID_LAYOUT_WIDGET_ID = "host/camera-grid-layout";
@@ -132,7 +65,7 @@ function buildGridLayoutNativeProvider(source) {
132
65
  getLayout: async ({ deviceId }) => source.getLayout(deviceId),
133
66
  saveLayout: async (patch) => source.saveLayout(patch),
134
67
  getDeviceSettingsContribution: async ({ deviceId }) => {
135
- const schema = buildGridDeviceSchema(source.getLayout(deviceId) !== null);
68
+ const schema = buildGridDeviceSchema(source.isGrid(deviceId));
136
69
  return schema === null ? null : hydrateSchema(schema, {});
137
70
  },
138
71
  getDeviceLiveContribution: async () => null,
@@ -168,8 +101,8 @@ function buildGridLayoutNativeProvider(source) {
168
101
  * (`grid-snapshot.ts`).
169
102
  */
170
103
  var gridCameraSchema = z.object({
171
- /** The persisted grid row this camera was declared from. */
172
- instanceId: z.string().min(1) });
104
+ /** The grid block (planning#580) whose camera this is. Handed in, never persisted. */
105
+ blockId: z.string().min(1) });
173
106
  var runtime = null;
174
107
  function installGridCameraRuntime(next) {
175
108
  runtime = next;
@@ -188,6 +121,7 @@ var GridCameraDevice = class extends BaseDevice {
188
121
  } });
189
122
  const layoutProvider = buildGridLayoutNativeProvider({
190
123
  getLayout: (deviceId) => activeRuntime().getLayout(deviceId),
124
+ isGrid: (deviceId) => activeRuntime().isGrid(deviceId),
191
125
  saveLayout: (patch) => activeRuntime().saveLayout(patch)
192
126
  });
193
127
  this.ctx.registerNativeCap(cameraGridLayoutCapability, layoutProvider);
@@ -202,8 +136,8 @@ var GridCameraDevice = class extends BaseDevice {
202
136
  this.markOnline(true);
203
137
  }
204
138
  catalog() {
205
- const descriptors = activeRuntime().descriptorsFor(this.config.get("instanceId"));
206
- if (descriptors === null) throw new Error(`camera-grid: cannot describe the streams of instance ${this.config.get("instanceId")}`);
139
+ const descriptors = activeRuntime().descriptorsFor(this.config.get("blockId"));
140
+ if (descriptors === null) throw new Error(`camera-grid: cannot describe the streams of grid block ${this.config.get("blockId")}`);
207
141
  return descriptors;
208
142
  }
209
143
  setAddonOnline(online) {
@@ -224,96 +158,68 @@ async function acquireWithRetry(attempt, deps) {
224
158
  }
225
159
  }
226
160
  //#endregion
227
- //#region src/builtins/camera-grid/grid-instances.ts
161
+ //#region src/builtins/camera-grid/grid-blocks.ts
228
162
  /**
229
- * The operator-written grid rows.
230
- *
231
- * Shape follows `readTerminalInstances`: a grid is a persisted row that
232
- * DECLARES a camera, and the declaration reconcile turns rows into devices.
233
- *
234
- * Config is operator-writable, so a malformed or duplicate row is IGNORED
235
- * rather than allowed to make the reconcile destructive. One bad row must never
236
- * delete every camera this addon declares — that failure mode is why the
237
- * Terminal addon reads its rows the same way.
163
+ * A grid is a core block (planning#580): its configuration is the block's
164
+ * `GridHelperSpec`, its camera is the composer's row `composed-<blockId>`, and
165
+ * this engine serves the camera caps on it. The spec names its sources by
166
+ * `(addonId, stableId)`; the compositor addresses them by device id, so a pass
167
+ * resolves one into the other here, and a layout save resolves back.
238
168
  */
239
- /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
240
- var NormalizedRectSchema = z.object({
241
- x: z.number().min(0).max(1),
242
- y: z.number().min(0).max(1),
243
- width: z.number().gt(0).max(1),
244
- height: z.number().gt(0).max(1)
245
- });
169
+ function sourceRefKey(ref) {
170
+ return `${ref.addonId}\u0000${ref.stableId}`;
171
+ }
246
172
  /**
247
- * One source camera, the part of its picture taken, and where that part lands
248
- * on the composite's canvas. Both rectangles are NORMALIZED so a source that
249
- * changes resolution does not silently start cutting the wrong region.
250
- */
251
- var GridCellSchema = z.object({
252
- deviceId: z.number().int().positive(),
253
- source: NormalizedRectSchema,
254
- cell: NormalizedRectSchema
255
- });
256
- var GridInstanceSchema = z.object({
257
- id: z.string().uuid(),
258
- cameraStableId: z.string().min(1).max(256),
259
- name: z.string().min(1).max(160),
260
- enabled: z.boolean(),
261
- /**
262
- * NO canvas size. It is DERIVED, per profile, from the cells and the sources'
263
- * own dimensions (`grid-canvas-derivation.ts`) — the two numbers that used to
264
- * live here were typed into the editor and silently decided both how much the
265
- * composite cost and how sharp it was.
266
- *
267
- * Rows written before that change still carry `width`/`height`; zod drops
268
- * unknown keys, so they are ignored rather than migrated. Nothing reads them,
269
- * and a migration that rewrote every row to delete two fields would be a
270
- * write with no reader.
271
- */
272
- fps: z.number().int().min(1).max(60),
273
- /**
274
- * Which profiles this grid PUBLISHES, of the ones it could serve.
275
- *
276
- * Default `mid` + `low`, and the default is the finding: a grid's `high` is
277
- * composed of its sources' `high`, so on this fleet it is a 4K canvas built
278
- * from 4K decodes — a thing to opt into, not to be handed by a viewer's
279
- * adaptive climbing to the top rung it can see.
280
- *
281
- * Absent on rows written before this, which is why the default lives in the
282
- * schema rather than at the call site: an old grid starts publishing the two
283
- * cheap rungs without anyone touching it.
284
- */
285
- publishedProfiles: z.array(z.enum([
286
- "high",
287
- "mid",
288
- "low"
289
- ])).max(3).default(["mid", "low"]),
290
- /**
291
- * Empty is the NORMAL freshly-created state: a grid is created from the
292
- * integration page with a name only, and laid out afterwards in the camera's
293
- * own settings. A grid with no cells declares its camera and emits nothing.
294
- */
295
- cells: z.array(GridCellSchema).max(16).default([])
296
- });
297
- function readGridInstances(raw, onInvalid) {
298
- const ids = /* @__PURE__ */ new Set();
299
- const stableIds = /* @__PURE__ */ new Set();
300
- const instances = [];
301
- for (const value of raw) {
302
- const parsed = GridInstanceSchema.safeParse(value);
303
- if (!parsed.success) {
304
- onInvalid?.("Ignoring malformed camera-grid configuration");
305
- continue;
306
- }
307
- const instance = parsed.data;
308
- if (ids.has(instance.id) || stableIds.has(instance.cameraStableId)) {
309
- onInvalid?.(`Ignoring duplicate camera-grid instance ${instance.id}`);
173
+ * Resolve every cell's source to its device id. A source with no row is left
174
+ * out of the composition and NAMED: a deleted camera must not keep the grid
175
+ * from composing the cells that remain.
176
+ */
177
+ function resolveGridCells(spec, deviceIdOf) {
178
+ const cells = [];
179
+ const unresolved = [];
180
+ for (const cell of spec.cells) {
181
+ const deviceId = deviceIdOf(cell.source);
182
+ if (deviceId === null) {
183
+ unresolved.push(cell.source);
310
184
  continue;
311
185
  }
312
- ids.add(instance.id);
313
- stableIds.add(instance.cameraStableId);
314
- instances.push(instance);
186
+ cells.push({
187
+ deviceId,
188
+ source: cell.region,
189
+ cell: cell.cell
190
+ });
315
191
  }
316
- return instances;
192
+ return {
193
+ cells,
194
+ unresolved
195
+ };
196
+ }
197
+ /**
198
+ * The spec a layout save stores. A cell whose device has no identity is
199
+ * refused by id: a saved spec must never carry a numeric device id.
200
+ */
201
+ function gridSpecFromPatch(current, patch, refOf) {
202
+ const cells = patch.cells.map((cell) => {
203
+ const source = refOf(cell.deviceId);
204
+ if (source === null) throw new Error(`camera-grid: source device ${String(cell.deviceId)} does not exist`);
205
+ return {
206
+ source,
207
+ region: cell.source,
208
+ cell: cell.cell
209
+ };
210
+ });
211
+ return {
212
+ kind: "grid",
213
+ fps: patch.fps ?? current.fps,
214
+ publishedProfiles: patch.publishedProfiles ?? current.publishedProfiles,
215
+ cells
216
+ };
217
+ }
218
+ /** The composition a grid spec compiles to — the shape a block of this kind stores. */
219
+ function gridComposition(spec) {
220
+ const compiled = compileHelper(spec);
221
+ if (!compiled.ok) throw new Error(`camera-grid: the grid spec does not compile — ${compiled.problems.map((p) => p.message).join("; ")}`);
222
+ return compiled.composition;
317
223
  }
318
224
  //#endregion
319
225
  //#region src/builtins/camera-grid/grid-plan.ts
@@ -363,283 +269,6 @@ function gridPlanFor(instance, encode) {
363
269
  };
364
270
  }
365
271
  //#endregion
366
- //#region src/builtins/camera-grid/grid-record-kinds.ts
367
- /**
368
- * A camera grid as a record (D1013): one `camera-grid` row per grid, owned by the `camera-grid`
369
- * builtin, listed and edited through `integration-instances` on the Camera grids page. The layout
370
- * (cells, frame rate, published profiles) is authored in the camera's own device details and
371
- * saved onto the same record.
372
- *
373
- * The record id IS the grid id the old settings list carried (a uuid), so the camera
374
- * `camera-grid-<id>` and everything that names it keeps its stable identity. `cameraStableId` is
375
- * stored only where it is not derivable from the id.
376
- */
377
- /** Checked against the interface by its annotation: a drifted field fails the typecheck. */
378
- var GridBodySchema = z.object({
379
- name: z.string().min(1).max(160),
380
- cameraStableId: z.string().min(1).max(256).optional(),
381
- fps: z.number().int().min(1).max(60),
382
- publishedProfiles: z.array(z.enum([
383
- "high",
384
- "mid",
385
- "low"
386
- ])).max(3),
387
- cells: z.array(GridCellSchema).max(16),
388
- enabled: z.boolean().optional()
389
- });
390
- var CAMERA_GRID_KIND_NAME = "camera-grid";
391
- var cameraGridKind = defineEntryKind(CAMERA_GRID_KIND_NAME, {
392
- title: "Camera grids",
393
- nameField: "name",
394
- schema: GridBodySchema,
395
- writeTrigger: "an operator adds, switches or deletes a grid, or saves its layout in the camera details"
396
- });
397
- /** Canvas cadence and published rungs a new grid starts with, until the layout editor changes them. */
398
- var DEFAULT_FPS = 10;
399
- var DEFAULT_PUBLISHED = ["mid", "low"];
400
- /** The body a new grid starts with: a name only, no cells, so it declares a camera and emits nothing. */
401
- function initialGridBody(name) {
402
- return {
403
- name,
404
- fps: DEFAULT_FPS,
405
- publishedProfiles: DEFAULT_PUBLISHED,
406
- cells: []
407
- };
408
- }
409
- /** The row `readGridInstances` parses, from a record. */
410
- function rawGridOfRecord(id, body) {
411
- return {
412
- id,
413
- cameraStableId: body.cameraStableId ?? newGridCameraStableId(id),
414
- name: body.name,
415
- enabled: isInstanceEnabled(body),
416
- fps: body.fps,
417
- publishedProfiles: body.publishedProfiles,
418
- cells: body.cells
419
- };
420
- }
421
- //#endregion
422
- //#region src/builtins/camera-grid/migrations/camera-grids-to-records.ts
423
- /**
424
- * The grids a pre-record install kept in the addon settings (`cameraGrids`) become `camera-grid`
425
- * records (planning#440 step 7, D1013). The record id IS the old row id, so the camera
426
- * `camera-grid-<id>` and every binding, layout and recording that names it keeps its identity.
427
- *
428
- * Rows are first normalised the way the old boot-time normaliser did (a missing or non-uuid id is
429
- * minted, a missing stable id is derived). The id is minted DETERMINISTICALLY from the row, so an
430
- * interrupted run converts the same row to the same record. Every good row is written, read back
431
- * equal, and an existing record is never overwritten.
432
- *
433
- * A row that still cannot be converted (nameless, malformed, a duplicate id or camera) never
434
- * blocks the others: the old reader skipped it and ran the rest. The legacy key is rewritten to
435
- * hold ONLY those raw rows (nothing reads it any more; kept for forensics), one warn per row, and
436
- * the migration lands as done. With no bad row the key is deleted.
437
- */
438
- var LEGACY_GRIDS_KEY = "cameraGrids";
439
- /**
440
- * The shape the settings list stored, frozen here: the migration owns what it reads. `width` and
441
- * `height` of rows written long ago are dropped (nothing reads them: the canvas is derived).
442
- */
443
- var LegacyRowSchema = z.object({
444
- id: z.string().uuid(),
445
- cameraStableId: z.string().min(1).max(256).optional(),
446
- name: z.string().min(1).max(160),
447
- enabled: z.boolean().default(true),
448
- fps: z.number().int().min(1).max(60).default(10),
449
- publishedProfiles: z.array(z.enum([
450
- "high",
451
- "mid",
452
- "low"
453
- ])).max(3).default(["mid", "low"]),
454
- cells: z.array(GridCellSchema).max(16).default([])
455
- });
456
- var UUID = z.string().uuid();
457
- /** A uuid derived from the row itself, so a rerun mints the same id for the same row. */
458
- function mintedId(raw) {
459
- const hex = createHash("sha1").update(JSON.stringify(raw)).digest("hex");
460
- const variant = (Number.parseInt(hex.charAt(16), 16) & 3 | 8).toString(16);
461
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
462
- }
463
- function verdictOf(raw) {
464
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return {
465
- kind: "skip",
466
- reason: "the row is not an object"
467
- };
468
- const name = Reflect.get(raw, "name");
469
- if (typeof name !== "string" || name.trim().length === 0) return {
470
- kind: "skip",
471
- reason: "the row has no name"
472
- };
473
- const rawId = Reflect.get(raw, "id");
474
- const id = UUID.safeParse(rawId).success && typeof rawId === "string" ? rawId : mintedId(raw);
475
- const parsed = LegacyRowSchema.safeParse({
476
- ...raw,
477
- id,
478
- name: name.trim()
479
- });
480
- if (!parsed.success) return {
481
- kind: "skip",
482
- reason: "the row does not match the legacy shape"
483
- };
484
- const row = parsed.data;
485
- const derived = row.cameraStableId === void 0 || row.cameraStableId === newGridCameraStableId(row.id);
486
- return {
487
- kind: "draft",
488
- draft: {
489
- id: row.id,
490
- body: {
491
- name: row.name,
492
- ...derived ? {} : { cameraStableId: row.cameraStableId },
493
- fps: row.fps,
494
- publishedProfiles: row.publishedProfiles,
495
- cells: row.cells,
496
- ...row.enabled ? {} : { enabled: false }
497
- }
498
- }
499
- };
500
- }
501
- function canonical(value) {
502
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
503
- if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).toSorted(([a], [b]) => a < b ? -1 : 1).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
504
- return JSON.stringify(value);
505
- }
506
- /** Absent `enabled` means on, so the two spellings of "on" read back as equal. */
507
- function sameBody(a, b) {
508
- const norm = (body) => canonical({
509
- ...body,
510
- enabled: isInstanceEnabled(body)
511
- });
512
- return norm(a) === norm(b);
513
- }
514
- function rowName(raw) {
515
- if (raw === null || typeof raw !== "object") return "(not an object)";
516
- const id = Reflect.get(raw, "id");
517
- return typeof id === "string" && id.length > 0 ? `'${id}'` : "(no id)";
518
- }
519
- async function copyGridsToRecords(ports) {
520
- const legacy = await ports.readLegacy();
521
- if (legacy.kind === "absent" || !Array.isArray(legacy.value)) return {
522
- outcome: "already-done",
523
- summary: { reason: "no-legacy-data" }
524
- };
525
- const rows = legacy.value;
526
- const drafts = [];
527
- const skipped = [];
528
- const ids = /* @__PURE__ */ new Set();
529
- const cameras = /* @__PURE__ */ new Set();
530
- for (const raw of rows) {
531
- const verdict = verdictOf(raw);
532
- if (verdict.kind === "skip") {
533
- skipped.push({
534
- raw,
535
- reason: verdict.reason
536
- });
537
- continue;
538
- }
539
- const camera = verdict.draft.body.cameraStableId ?? newGridCameraStableId(verdict.draft.id);
540
- if (ids.has(verdict.draft.id) || cameras.has(camera)) {
541
- skipped.push({
542
- raw,
543
- reason: "a duplicate grid or camera"
544
- });
545
- continue;
546
- }
547
- ids.add(verdict.draft.id);
548
- cameras.add(camera);
549
- drafts.push(verdict.draft);
550
- }
551
- if (drafts.length === 0 && skipped.length > 0) {
552
- ports.warn(`camera-grid: ${skipped.length} legacy row(s) are kept unconverted in the old list and ignored`);
553
- return {
554
- outcome: "already-done",
555
- summary: { skipped: skipped.length }
556
- };
557
- }
558
- const have = await ports.listIds();
559
- let created = 0;
560
- let kept = 0;
561
- for (const { id, body } of drafts) {
562
- if (have.has(id)) {
563
- kept += 1;
564
- continue;
565
- }
566
- await ports.putRecord(id, body);
567
- const back = await ports.readRecord(id);
568
- if (back === null || !sameBody(back, body)) throw new Error(`camera-grid: grid '${id}' did not read back as written; the legacy list is kept`);
569
- created += 1;
570
- }
571
- for (const { raw, reason } of skipped) ports.warn(`camera-grid: row ${rowName(raw)} was not copied into records (${reason}) and is ignored`);
572
- if (skipped.length === 0) await ports.dropLegacyKey();
573
- else await ports.keepLegacyRows(skipped.map((entry) => entry.raw));
574
- return {
575
- outcome: "done",
576
- summary: {
577
- created,
578
- kept,
579
- skipped: skipped.length
580
- }
581
- };
582
- }
583
- function gridPortsOver(api) {
584
- const records = api.records.kind(cameraGridKind);
585
- return {
586
- readLegacy: async () => {
587
- const { store } = await api.settings.read({});
588
- return Object.prototype.hasOwnProperty.call(store, "cameraGrids") ? {
589
- kind: "present",
590
- value: store[LEGACY_GRIDS_KEY]
591
- } : { kind: "absent" };
592
- },
593
- listIds: async () => {
594
- const out = /* @__PURE__ */ new Set();
595
- let cursor;
596
- do {
597
- const page = await records.query({
598
- limit: 500,
599
- ...cursor === void 0 ? {} : { cursor }
600
- });
601
- for (const row of page.records) out.add(row.id);
602
- cursor = page.nextCursor ?? void 0;
603
- } while (cursor !== void 0);
604
- return out;
605
- },
606
- putRecord: async (id, body) => {
607
- await records.put({
608
- id,
609
- data: body,
610
- ifRev: 0
611
- });
612
- },
613
- readRecord: async (id) => (await records.get({ id }))?.data ?? null,
614
- dropLegacyKey: async () => {
615
- await api.settings.deleteKeys({ keys: [LEGACY_GRIDS_KEY] });
616
- },
617
- keepLegacyRows: async (kept) => {
618
- await api.settings.write({ patch: { [LEGACY_GRIDS_KEY]: [...kept] } });
619
- },
620
- warn: (message) => {
621
- api.log.warn({ message });
622
- }
623
- };
624
- }
625
- /** The `camera-grid` catalogue (D987): offered to the engine when the addon initialises. */
626
- var ADDON_MIGRATIONS = [{
627
- meta: {
628
- id: "camera-grid/2026-11-07-grids-to-records",
629
- owner: "camera-grid",
630
- level: "addon-state",
631
- seq: 1,
632
- dependsOn: [],
633
- store: "settings",
634
- scope: "cluster",
635
- onFailure: "tolerate",
636
- bodyKind: "procedure",
637
- description: "Copy the addon-level grid list (cameraGrids) into camera-grid records under the same ids, each read back; the legacy key is deleted only once every row has its record",
638
- fixtureMark: "cells[0].source.x of a grid row, read back from its record"
639
- },
640
- procedure: copyGridsToRecords
641
- }];
642
- //#endregion
643
272
  //#region src/builtins/camera-grid/grid-activity-mirror.ts
644
273
  /**
645
274
  * What a grid says about ITSELF, kept from what its sources said.
@@ -3148,8 +2777,11 @@ async function startGridCompositorChild(ctx, plan, sources, onEnded) {
3148
2777
  }
3149
2778
  //#endregion
3150
2779
  //#region src/builtins/camera-grid/addon.ts
3151
- var INTEGRATION_NAME = "Camera Grids";
2780
+ /** The integration the pre-block grid cameras were declared under; only its leftovers are swept. */
2781
+ var LEGACY_INTEGRATION_NAME = "Camera Grids";
3152
2782
  var RECONCILE_MS = 6e4;
2783
+ /** The per-device flag that analysis was silenced once (`ctx.settings` device store, D865). */
2784
+ var ANALYSIS_SILENCED_KEY = "analysisSilenced";
3153
2785
  /**
3154
2786
  * How long a source acquire may keep asking while a provider is still coming up.
3155
2787
  * Long enough to cover the republish window after a hub restart, short enough
@@ -3159,8 +2791,8 @@ var SOURCE_ACQUIRE_BUDGET_MS = 8e3;
3159
2791
  var SOURCE_ACQUIRE_PAUSE_MS = 700;
3160
2792
  var DEFAULTS = {};
3161
2793
  /** One composition per (grid, profile) — a grid composes each separately. */
3162
- function sessionKey(instanceId, profile) {
3163
- return `${instanceId}::${profile}`;
2794
+ function sessionKey(blockId, profile) {
2795
+ return `${blockId}::${profile}`;
3164
2796
  }
3165
2797
  /**
3166
2798
  * One grid's composition of one profile.
@@ -3172,11 +2804,11 @@ function sessionKey(instanceId, profile) {
3172
2804
  * adaptive can stand on costs what it is worth.
3173
2805
  */
3174
2806
  var GridSessionEntry = class {
3175
- instanceId;
2807
+ blockId;
3176
2808
  profile;
3177
2809
  session;
3178
- constructor(instanceId, profile, session) {
3179
- this.instanceId = instanceId;
2810
+ constructor(blockId, profile, session) {
2811
+ this.blockId = blockId;
3180
2812
  this.profile = profile;
3181
2813
  this.session = session;
3182
2814
  }
@@ -3187,18 +2819,15 @@ var GridSessionEntry = class {
3187
2819
  var CameraGridAddon = class extends BaseAddon {
3188
2820
  relay = null;
3189
2821
  reconcileTimer = null;
3190
- /** Keyed by instance id — ONE composition per grid. */
2822
+ /** Keyed by session key — ONE composition per (grid, profile). */
3191
2823
  sessions = /* @__PURE__ */ new Map();
3192
- deviceIdByInstanceId = /* @__PURE__ */ new Map();
3193
- instances = null;
3194
- /** The grids, as the last read of the records saw them. */
3195
- instanceRows = [];
3196
- /**
3197
- * False until the records are readable and the grids migration landed: a camera is never
3198
- * withdrawn on a list that may be incomplete (D49).
3199
- */
3200
- instancesTrusted = false;
3201
- migrationLanded = false;
2824
+ /** The grids this engine hosts, by block id. */
2825
+ grids = /* @__PURE__ */ new Map();
2826
+ withdrawalGate = new HostedWithdrawalGate();
2827
+ /** One pass at a time: a save and the timer must not host the same block twice. */
2828
+ passChain = Promise.resolve();
2829
+ /** True once a pass found no legacy `camera-grid` row left to remove. */
2830
+ legacySwept = false;
3202
2831
  /**
3203
2832
  * What each grid can honestly publish, per profile.
3204
2833
  *
@@ -3209,7 +2838,7 @@ var CameraGridAddon = class extends BaseAddon {
3209
2838
  * (D224), and 60 s is the window for a fact — "does 101 have a low assigned"
3210
2839
  * — that only changes when an operator changes it.
3211
2840
  */
3212
- plansByInstanceId = /* @__PURE__ */ new Map();
2841
+ plansByBlockId = /* @__PURE__ */ new Map();
3213
2842
  activity = null;
3214
2843
  snapshots = null;
3215
2844
  frameSampler = null;
@@ -3220,13 +2849,11 @@ var CameraGridAddon = class extends BaseAddon {
3220
2849
  pinnedFfmpeg = memoizePinnedFfmpeg(() => this.ctx.deps.ensureFfmpeg());
3221
2850
  /** A resolution in flight, so a reconcile pass never starts a second. */
3222
2851
  ffmpegResolving = null;
3223
- integrationId;
3224
2852
  constructor() {
3225
2853
  super({ ...DEFAULTS });
3226
2854
  }
3227
2855
  async onInitialize() {
3228
2856
  if (declarationOwnerNodeId(this.ctx.kernel.localNodeId) === "hub") {
3229
- await this.initInstanceRecords();
3230
2857
  await this.resolveFfmpeg();
3231
2858
  const relay = new GridStreamRelay({
3232
2859
  logger: this.ctx.logger.child("relay"),
@@ -3252,8 +2879,9 @@ var CameraGridAddon = class extends BaseAddon {
3252
2879
  });
3253
2880
  this.subscribeSourceActivity();
3254
2881
  installGridCameraRuntime({
3255
- descriptorsFor: (instanceId) => this.descriptorsFor(instanceId),
2882
+ descriptorsFor: (blockId) => this.descriptorsFor(blockId),
3256
2883
  getLayout: (deviceId) => this.gridViewFor(deviceId),
2884
+ isGrid: (deviceId) => this.gridForDevice(deviceId) !== null,
3257
2885
  saveLayout: async (patch) => this.saveGridLayout(patch),
3258
2886
  getSnapshot: async (deviceId) => this.getSnapshot(deviceId),
3259
2887
  motionStatus: (deviceId) => {
@@ -3277,18 +2905,14 @@ var CameraGridAddon = class extends BaseAddon {
3277
2905
  }, RECONCILE_MS);
3278
2906
  this.reconcileTimer.unref?.();
3279
2907
  }
3280
- const providers = [{
2908
+ return { providers: [{
3281
2909
  capability: cameraGridLayoutCapability,
3282
2910
  provider: buildGridLayoutNativeProvider({
3283
2911
  getLayout: (deviceId) => this.gridViewFor(deviceId),
2912
+ isGrid: (deviceId) => this.gridForDevice(deviceId) !== null,
3284
2913
  saveLayout: (patch) => this.saveGridLayout(patch)
3285
2914
  })
3286
- }];
3287
- if (this.instances !== null) providers.push({
3288
- capability: integrationInstancesCapability,
3289
- provider: this.instances.toProvider()
3290
- });
3291
- return { providers };
2915
+ }] };
3292
2916
  }
3293
2917
  async onShutdown() {
3294
2918
  if (this.reconcileTimer) clearInterval(this.reconcileTimer);
@@ -3298,171 +2922,209 @@ var CameraGridAddon = class extends BaseAddon {
3298
2922
  this.relay = null;
3299
2923
  for (const entry of this.sessions.values()) await entry.session.dispose();
3300
2924
  this.sessions.clear();
2925
+ for (const grid of this.grids.values()) await grid.hosted.withdraw().catch(() => void 0);
2926
+ this.grids = /* @__PURE__ */ new Map();
3301
2927
  this.snapshots = null;
3302
2928
  this.frameSampler = null;
3303
2929
  }
3304
- instanceList() {
3305
- return this.instanceRows;
2930
+ gridById(blockId) {
2931
+ return this.grids.get(blockId) ?? null;
3306
2932
  }
3307
- instanceById(instanceId) {
3308
- return this.instanceRows.find((instance) => instance.id === instanceId);
2933
+ gridForDevice(deviceId) {
2934
+ for (const grid of this.grids.values()) if (grid.block.deviceId === deviceId) return grid;
2935
+ return null;
3309
2936
  }
3310
- /**
3311
- * Hub only: declare the `camera-grid` kind, serve it through `integration-instances`, move the
3312
- * old settings list into records (D987), then read the rows. A migration that did not land
3313
- * leaves the declared cameras exactly as they are (`instancesTrusted` stays false).
3314
- */
3315
- async initInstanceRecords() {
3316
- const records = this.ctx.records;
3317
- if (records === void 0) throw new Error("camera-grid: ctx.records is not available on the hub");
3318
- await records.declare({ [CAMERA_GRID_KIND_NAME]: cameraGridKind });
3319
- this.instances = new RecordIntegrationInstances(records, cameraGridKind, {
3320
- description: {
3321
- role: "services",
3322
- instanceMode: "multiple",
3323
- kind: CAMERA_GRID_KIND_NAME,
3324
- canTest: false,
3325
- kinds: [{
3326
- id: CAMERA_GRID_KIND_NAME,
3327
- label: "Camera grid",
3328
- functionCap: "camera-grid-layout",
3329
- canTest: false
3330
- }]
3331
- },
3332
- kindOf: () => CAMERA_GRID_KIND_NAME,
3333
- formSchema: () => this.instanceForm(),
3334
- initialBody: (name) => initialGridBody(name),
3335
- mintId: () => crypto.randomUUID(),
3336
- configured: () => true,
3337
- onChanged: (id, change) => this.onInstanceChanged(id, change)
2937
+ /** One pass at a time, in order: a save waits for a running pass and the reverse. */
2938
+ serialized(work) {
2939
+ const run = this.passChain.then(work, work);
2940
+ this.passChain = run.then(() => void 0, () => void 0);
2941
+ return run;
2942
+ }
2943
+ reconcile() {
2944
+ return this.serialized(async () => {
2945
+ if (!this.relay) return;
2946
+ await this.sweepLegacyCameras();
2947
+ await this.hostGridBlocks();
3338
2948
  });
3339
- const report = await this.runMigrations(ADDON_MIGRATIONS, gridPortsOver);
3340
- this.migrationLanded = report.declared && !report.failed.includes("camera-grid/2026-11-07-grids-to-records") && !report.blocked.includes("camera-grid/2026-11-07-grids-to-records");
3341
- if (!this.migrationLanded) this.ctx.logger.error("camera grid: the grids migration has not landed - the declared cameras are left as they are until it does", { meta: {
3342
- declared: report.declared,
3343
- failed: report.failed,
3344
- blocked: report.blocked
3345
- } });
3346
- await this.refreshInstanceRows();
3347
2949
  }
3348
- /** Re-read every grid record. A failed read changes nothing (D49). */
3349
- async refreshInstanceRows() {
3350
- const handle = this.ctx.records?.kind(cameraGridKind);
3351
- if (handle === void 0 || !this.migrationLanded) {
3352
- this.instancesTrusted = false;
2950
+ /** Read the grid blocks and host what they name. A read that cannot be trusted changes nothing (D49). */
2951
+ async hostGridBlocks() {
2952
+ let compositions;
2953
+ let composerRows;
2954
+ try {
2955
+ compositions = await this.ctx.api.coreBlocks.listCompositions.query({});
2956
+ composerRows = await this.ctx.api.deviceManager.listAll.query({
2957
+ addonId: COMPOSER_ADDON_ID,
2958
+ projection: "slim"
2959
+ });
2960
+ } catch (error) {
2961
+ this.ctx.logger.warn("camera grid: the grid blocks could not be read - nothing changes", { meta: { error: errMsg(error) } });
2962
+ return;
2963
+ }
2964
+ const read = selectEngineHostedBlocks("grid", compositions, composerRows);
2965
+ if (read.kind === "untrusted") {
2966
+ this.ctx.logger.info("camera grid: the blocks are not loaded yet - nothing changes", { meta: { reason: read.reason } });
3353
2967
  return;
3354
2968
  }
2969
+ const wanted = read.blocks.filter((block) => block.enabled);
2970
+ const { withdraw } = this.withdrawalGate.judge(this.grids.keys(), new Set(wanted.map((block) => block.blockId)));
2971
+ for (const blockId of withdraw) await this.unhost(blockId, "its block is gone or switched off");
2972
+ const sources = await this.readSources(wanted);
2973
+ const next = new Map(this.grids);
2974
+ for (const block of wanted) {
2975
+ const hosted = await this.hostOne(block, sources);
2976
+ if (hosted !== null) next.set(block.blockId, hosted);
2977
+ }
2978
+ this.grids = next;
2979
+ await this.refreshSourcePlans();
2980
+ for (const grid of this.grids.values()) this.ensureSessions(grid.block.blockId, grid.block.deviceId);
2981
+ }
2982
+ /** Build (or refresh) one grid. A failure is logged per device and leaves the previous state. */
2983
+ async hostOne(block, sources) {
2984
+ const previous = this.gridById(block.blockId);
2985
+ const layout = this.layoutOf(block, sources, previous);
2986
+ if (previous !== null) {
2987
+ if (previous.block.deviceId === block.deviceId) {
2988
+ if (JSON.stringify(previous.layout) !== JSON.stringify(layout)) await this.applyLayoutChanges(block.blockId);
2989
+ return {
2990
+ block,
2991
+ layout,
2992
+ hosted: previous.hosted
2993
+ };
2994
+ }
2995
+ await this.unhost(block.blockId, "its row changed");
2996
+ }
2997
+ let hosted;
3355
2998
  try {
3356
- const raw = [];
3357
- let cursor;
3358
- do {
3359
- const page = await handle.query({
3360
- limit: 500,
3361
- ...cursor === void 0 ? {} : { cursor }
3362
- });
3363
- for (const row of page.records) raw.push(rawGridOfRecord(row.id, row.data));
3364
- cursor = page.nextCursor ?? void 0;
3365
- } while (cursor !== void 0);
3366
- this.instanceRows = readGridInstances(raw, (message) => {
3367
- this.ctx.logger.warn(message);
3368
- });
3369
- this.instancesTrusted = true;
2999
+ hosted = await hostEngineDevice(this.ctx.kernel.devices, {
3000
+ id: block.deviceId,
3001
+ stableId: block.stableId
3002
+ }, { blockId: block.blockId }, GridCameraDevice);
3370
3003
  } catch (error) {
3371
- this.instancesTrusted = false;
3372
- this.ctx.logger.warn("camera grid: the grid records could not be read - keeping the last list", { meta: { error: errMsg(error) } });
3004
+ this.ctx.logger.error("camera grid: a grid block could not be hosted", {
3005
+ tags: { deviceId: block.deviceId },
3006
+ meta: {
3007
+ blockId: block.blockId,
3008
+ error: errMsg(error)
3009
+ }
3010
+ });
3011
+ return null;
3373
3012
  }
3013
+ this.ctx.logger.info("camera grid: hosting a grid block on its camera row", {
3014
+ tags: { deviceId: block.deviceId },
3015
+ meta: {
3016
+ blockId: block.blockId,
3017
+ cells: layout.cells.length
3018
+ }
3019
+ });
3020
+ await this.silenceOnce(block.deviceId);
3021
+ return {
3022
+ block,
3023
+ layout,
3024
+ hosted
3025
+ };
3374
3026
  }
3375
3027
  /**
3376
- * A grid is created with a name only; its layout is authored afterwards in the camera's own
3377
- * device details (a generated form for the geometry would render "cell 1 source = 592" and be
3378
- * unusable), so the form carries no field of its own.
3028
+ * The grid's cells resolved to device ids. A source whose addon could not be
3029
+ * read keeps the previous resolution; a source that has no row is left out
3030
+ * and named.
3379
3031
  */
3380
- instanceForm() {
3381
- return { sections: [{
3382
- id: "camera-grid",
3383
- title: "Camera grid",
3384
- description: "A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other camera. Create one with a name; open its camera to lay it out. Object detection is switched OFF on a new grid - the cameras it is composed from are already analysed.",
3385
- fields: []
3386
- }] };
3387
- }
3388
- /** Runs after every create / edit / switch / delete of a grid record, on the hub. */
3389
- async onInstanceChanged(_id, _change) {
3390
- await this.refreshInstanceRows();
3391
- if (this.relay === null) return;
3392
- await this.applyLayoutChanges();
3393
- await this.reconcile().catch((error) => {
3394
- this.ctx.logger.warn("camera grid: reconciliation after an instance change failed", { meta: { error: errMsg(error) } });
3032
+ layoutOf(block, sources, previous) {
3033
+ if (block.spec.cells.some((cell) => sources.unreadAddons.has(cell.source.addonId)) && previous !== null) return {
3034
+ ...previous.layout,
3035
+ fps: block.spec.fps
3036
+ };
3037
+ const { cells, unresolved } = resolveGridCells(block.spec, (ref) => sources.ids.get(sourceRefKey(ref)) ?? null);
3038
+ if (unresolved.length > 0) this.ctx.logger.warn("camera grid: a cell names a source with no device - it is left out", {
3039
+ tags: { deviceId: block.deviceId },
3040
+ meta: {
3041
+ blockId: block.blockId,
3042
+ missing: unresolved.map(sourceRefKey)
3043
+ }
3395
3044
  });
3045
+ return {
3046
+ fps: block.spec.fps,
3047
+ publishedProfiles: block.spec.publishedProfiles,
3048
+ cells
3049
+ };
3396
3050
  }
3397
- async reconcile() {
3398
- if (!this.relay) return;
3399
- await this.refreshInstanceRows();
3400
- if (!this.instancesTrusted) return;
3401
- const instances = this.instanceList();
3402
- const declarations = buildGridCameraDeclarations(instances);
3403
- await this.refreshSourcePlans(instances);
3404
- await this.retireWithdrawnSessions(instances);
3405
- const result = await new DeclaredDevices({
3406
- logger: this.ctx.logger.child("declaration"),
3407
- addonId: bareAddonId(this.ctx.id),
3408
- devices: this.ctx.kernel.devices,
3409
- localNodeId: this.ctx.kernel.localNodeId,
3410
- getIntegration: async (addonId) => {
3411
- const integration = await this.ctx.api.integrations.getByAddonId.query({ addonId });
3412
- this.integrationId = integration?.id ?? null;
3413
- return integration;
3414
- },
3415
- createIntegration: async (input) => {
3416
- const created = await this.ctx.api.integrationInstances.createInstance.mutate({
3417
- addonId: input.addonId,
3418
- name: input.name,
3419
- seed: { info: input.info }
3420
- });
3421
- this.integrationId = created.id;
3422
- return { id: created.id };
3423
- },
3424
- updateIntegration: async ({ id, info }) => {
3425
- await this.ctx.api.integrations.update.mutate({
3426
- id,
3427
- info,
3428
- skipRestart: true
3429
- });
3430
- },
3431
- listOwnDevices: async () => {
3432
- return gridCameraReconciliationIndex(await this.ctx.api.deviceManager.listAll.query({ addonId: bareAddonId(this.ctx.id) }), this.integrationId, declarations);
3051
+ /** One indexed read per source addon (`listAll({ addonId })`), never the fleet. */
3052
+ async readSources(blocks) {
3053
+ const addonIds = new Set(blocks.flatMap((b) => b.spec.cells.map((c) => c.source.addonId)));
3054
+ const ids = /* @__PURE__ */ new Map();
3055
+ const unreadAddons = /* @__PURE__ */ new Set();
3056
+ for (const addonId of addonIds) try {
3057
+ const rows = await this.ctx.api.deviceManager.listAll.query({
3058
+ addonId,
3059
+ projection: "slim"
3060
+ });
3061
+ for (const row of rows) ids.set(sourceRefKey({
3062
+ addonId,
3063
+ stableId: row.stableId
3064
+ }), row.id);
3065
+ } catch (error) {
3066
+ unreadAddons.add(addonId);
3067
+ this.ctx.logger.warn("camera grid: the sources of one addon could not be read", { meta: {
3068
+ addonId,
3069
+ error: errMsg(error)
3070
+ } });
3071
+ }
3072
+ return {
3073
+ ids,
3074
+ unreadAddons
3075
+ };
3076
+ }
3077
+ async unhost(blockId, reason) {
3078
+ const grid = this.gridById(blockId);
3079
+ if (grid === null) return;
3080
+ const deviceId = grid.block.deviceId;
3081
+ this.ctx.logger.info("camera grid: no longer hosting a grid block", {
3082
+ tags: { deviceId },
3083
+ meta: {
3084
+ blockId,
3085
+ reason
3433
3086
  }
3434
- }).reconcile({
3435
- integrationName: INTEGRATION_NAME,
3436
- placement: "hub",
3437
- devices: declarations.map((camera) => ({
3438
- stableId: camera.stableId,
3439
- name: camera.name,
3440
- type: DeviceType.Camera,
3441
- DeviceClass: GridCameraDevice,
3442
- config: camera.config,
3443
- role: "camera-grid"
3444
- }))
3445
3087
  });
3446
- const declaredByStableId = new Map(declarations.map((camera) => [camera.stableId, camera]));
3447
- for (const outcome of result.devices) {
3448
- if (!(outcome.device instanceof GridCameraDevice)) continue;
3449
- const declaration = declaredByStableId.get(outcome.stableId);
3450
- if (!declaration) continue;
3451
- const config = outcome.device.config;
3452
- if (config.get("instanceId") !== declaration.config.instanceId) await config.setAll(declaration.config);
3453
- const instanceId = declaration.config.instanceId;
3454
- this.deviceIdByInstanceId.set(instanceId, outcome.device.id);
3455
- this.ensureSessions(instanceId, outcome.device.id);
3456
- if (outcome.created) await this.silenceAnalysis(outcome.device.id);
3457
- outcome.device.setAddonOnline(true);
3088
+ for (const [key, entry] of [...this.sessions]) {
3089
+ if (entry.blockId !== blockId) continue;
3090
+ this.sessions.delete(key);
3091
+ await entry.session.dispose();
3458
3092
  }
3093
+ this.activity?.forget(deviceId);
3094
+ this.plansByBlockId.delete(blockId);
3095
+ grid.hosted.device.setAddonOnline(false);
3096
+ try {
3097
+ await grid.hosted.withdraw();
3098
+ } catch (error) {
3099
+ this.ctx.logger.warn("camera grid: withdrawing a grid device failed", {
3100
+ tags: { deviceId },
3101
+ meta: {
3102
+ blockId,
3103
+ error: errMsg(error)
3104
+ }
3105
+ });
3106
+ }
3107
+ this.grids = new Map([...this.grids].filter(([id]) => id !== blockId));
3459
3108
  }
3460
- async silenceAnalysis(deviceId) {
3109
+ /**
3110
+ * Analysis is silenced the FIRST time this engine hosts the device, and the
3111
+ * fact is kept per device (`ctx.settings` device store, cleared with the
3112
+ * device, D865). An operator who turns detection back on must win: it is
3113
+ * never re-asserted.
3114
+ */
3115
+ async silenceOnce(deviceId) {
3116
+ const settings = this.ctx.settings;
3117
+ if (!settings) {
3118
+ this.ctx.logger.warn("camera grid: no settings store - analysis is not silenced", { tags: { deviceId } });
3119
+ return;
3120
+ }
3461
3121
  try {
3122
+ if ((await settings.readDeviceStore(deviceId))[ANALYSIS_SILENCED_KEY] === true) return;
3462
3123
  await silenceAnalysisFor({
3463
3124
  api: this.ctx.api,
3464
3125
  logger: this.ctx.logger
3465
3126
  }, deviceId);
3127
+ await settings.writeDeviceStore(deviceId, { [ANALYSIS_SILENCED_KEY]: true });
3466
3128
  } catch (error) {
3467
3129
  this.ctx.logger.error("camera grid: a new grid could not be silenced", {
3468
3130
  tags: { deviceId },
@@ -3471,6 +3133,31 @@ var CameraGridAddon = class extends BaseAddon {
3471
3133
  }
3472
3134
  }
3473
3135
  /**
3136
+ * The grid cameras declared before grids were blocks are not carried over
3137
+ * (planning#580: the operator recreates them as blocks). Every row this addon
3138
+ * still owns under its old integration is removed through the declared sweep
3139
+ * (`removeDevice` → tombstone, D865). No integration means nothing was ever
3140
+ * declared, and nothing is minted to find out.
3141
+ */
3142
+ async sweepLegacyCameras() {
3143
+ if (this.legacySwept) return;
3144
+ const addonId = bareAddonId(this.ctx.id);
3145
+ try {
3146
+ const sweep = await sweepLegacyEngineRows({
3147
+ logger: this.ctx.logger.child("legacy-sweep"),
3148
+ addonId,
3149
+ devices: this.ctx.kernel.devices,
3150
+ localNodeId: this.ctx.kernel.localNodeId,
3151
+ getIntegration: (owner) => this.ctx.api.integrations.getByAddonId.query({ addonId: owner }),
3152
+ listAddonRows: (owner) => this.ctx.api.deviceManager.listAll.query({ addonId: owner })
3153
+ }, LEGACY_INTEGRATION_NAME);
3154
+ if (sweep.kind === "swept" && sweep.removed.length > 0) this.ctx.logger.info("camera grid: legacy grid cameras removed - recreate them as blocks", { meta: { removed: [...sweep.removed] } });
3155
+ if (legacySweepDone(sweep)) this.legacySwept = true;
3156
+ } catch (error) {
3157
+ this.ctx.logger.warn("camera grid: the legacy grid cameras could not be swept - retried", { meta: { error: errMsg(error) } });
3158
+ }
3159
+ }
3160
+ /**
3474
3161
  * Listen to the SOURCES, so the grid can say the same things about itself.
3475
3162
  *
3476
3163
  * Filtered by source id inside the handler rather than by subscribing per
@@ -3508,22 +3195,22 @@ var CameraGridAddon = class extends BaseAddon {
3508
3195
  */
3509
3196
  gridsForSource(sourceDeviceId) {
3510
3197
  const targets = [];
3511
- for (const [instanceId, deviceId] of this.deviceIdByInstanceId) {
3512
- const instance = this.instanceById(instanceId);
3513
- if (!instance || !instance.enabled) continue;
3198
+ for (const grid of this.grids.values()) {
3199
+ const deviceId = grid.block.deviceId;
3200
+ const layout = grid.layout;
3514
3201
  if (sourceDeviceId === deviceId) continue;
3515
- if (instance.cells.filter((cell) => cell.deviceId === sourceDeviceId).length === 0) continue;
3202
+ if (layout.cells.filter((cell) => cell.deviceId === sourceDeviceId).length === 0) continue;
3516
3203
  targets.push({
3517
3204
  deviceId,
3518
- canvas: this.canvasFor(instanceId) ?? {
3205
+ canvas: this.canvasFor(grid.block.blockId) ?? {
3519
3206
  width: 0,
3520
3207
  height: 0
3521
3208
  },
3522
- cellsForSource: (id) => instance.cells.filter((cell) => cell.deviceId === id).map((cell) => ({
3209
+ cellsForSource: (id) => layout.cells.filter((cell) => cell.deviceId === id).map((cell) => ({
3523
3210
  source: cell.source,
3524
3211
  cell: cell.cell
3525
3212
  })),
3526
- sourceDeviceIds: [...new Set(instance.cells.map((cell) => cell.deviceId))]
3213
+ sourceDeviceIds: [...new Set(layout.cells.map((cell) => cell.deviceId))]
3527
3214
  });
3528
3215
  }
3529
3216
  return targets;
@@ -3537,14 +3224,15 @@ var CameraGridAddon = class extends BaseAddon {
3537
3224
  * empty catalog, and turning it into one would retract the streams of every
3538
3225
  * grid on the hub.
3539
3226
  */
3540
- async refreshSourcePlans(instances) {
3227
+ async refreshSourcePlans() {
3228
+ const grids = [...this.grids.values()];
3541
3229
  let slots;
3542
3230
  try {
3543
3231
  slots = await this.ctx.api.streamBroker.listAllProfileSlots.query();
3544
3232
  } catch (error) {
3545
3233
  this.ctx.logger.warn("camera grid: could not read the broker profile slots - keeping the last answer", { meta: {
3546
3234
  error: errMsg(error),
3547
- grids: instances.length
3235
+ grids: grids.length
3548
3236
  } });
3549
3237
  return;
3550
3238
  }
@@ -3559,19 +3247,19 @@ var CameraGridAddon = class extends BaseAddon {
3559
3247
  });
3560
3248
  servedBy.set(slot.deviceId, profiles);
3561
3249
  }
3562
- for (const instance of instances) {
3250
+ for (const grid of grids) {
3563
3251
  const plans = gridProfilePlans({
3564
- publishedProfiles: instance.publishedProfiles,
3565
- cells: instance.cells.map((cell) => ({
3252
+ publishedProfiles: grid.layout.publishedProfiles,
3253
+ cells: grid.layout.cells.map((cell) => ({
3566
3254
  deviceId: cell.deviceId,
3567
3255
  source: cell.source,
3568
3256
  cell: cell.cell
3569
3257
  })),
3570
3258
  profilesServedBy: (deviceId) => servedBy.get(deviceId) ?? null
3571
3259
  });
3572
- const previous = this.plansByInstanceId.get(instance.id);
3573
- this.plansByInstanceId.set(instance.id, plans);
3574
- this.logSourcePlan(instance, plans, previous);
3260
+ const previous = this.plansByBlockId.get(grid.block.blockId);
3261
+ this.plansByBlockId.set(grid.block.blockId, plans);
3262
+ this.logSourcePlan(grid, plans, previous);
3575
3263
  }
3576
3264
  }
3577
3265
  /**
@@ -3587,16 +3275,16 @@ var CameraGridAddon = class extends BaseAddon {
3587
3275
  * Logged on the EDGE: a grid that cannot be composed would otherwise write a
3588
3276
  * line a minute for ever.
3589
3277
  */
3590
- logSourcePlan(instance, plans, previous) {
3278
+ logSourcePlan(grid, plans, previous) {
3591
3279
  const shape = (value) => JSON.stringify(value);
3592
3280
  if (previous !== void 0 && shape(previous) === shape(plans)) return;
3593
- const deviceId = this.deviceIdByInstanceId.get(instance.id) ?? 0;
3281
+ const deviceId = grid.block.deviceId;
3594
3282
  for (const row of plans) {
3595
3283
  if (row.offered || row.missingSources.length === 0) continue;
3596
3284
  this.ctx.logger.info("camera grid: a profile is NOT on offer", {
3597
3285
  tags: { deviceId },
3598
3286
  meta: {
3599
- instanceId: instance.id,
3287
+ blockId: grid.block.blockId,
3600
3288
  profile: row.profile,
3601
3289
  missingSources: [...row.missingSources]
3602
3290
  }
@@ -3605,16 +3293,16 @@ var CameraGridAddon = class extends BaseAddon {
3605
3293
  this.ctx.logger.info("camera grid: published profiles", {
3606
3294
  tags: { deviceId },
3607
3295
  meta: {
3608
- instanceId: instance.id,
3296
+ blockId: grid.block.blockId,
3609
3297
  offered: Object.fromEntries(plans.filter((row) => row.offered && row.published).map((row) => [row.profile, row.offered ? `${String(row.canvas.width)}x${String(row.canvas.height)}` : ""]))
3610
3298
  }
3611
3299
  });
3612
3300
  }
3613
- plansFor(instanceId) {
3614
- return this.plansByInstanceId.get(instanceId) ?? null;
3301
+ plansFor(blockId) {
3302
+ return this.plansByBlockId.get(blockId) ?? null;
3615
3303
  }
3616
- planFor(instanceId, profile) {
3617
- return this.plansFor(instanceId)?.find((row) => row.profile === profile) ?? null;
3304
+ planFor(blockId, profile) {
3305
+ return this.plansFor(blockId)?.find((row) => row.profile === profile) ?? null;
3618
3306
  }
3619
3307
  /**
3620
3308
  * The canvas of the BEST profile this grid offers.
@@ -3625,14 +3313,14 @@ var CameraGridAddon = class extends BaseAddon {
3625
3313
  * offered one is the honest default; a grid offering nothing has no geometry
3626
3314
  * and says so.
3627
3315
  */
3628
- canvasFor(instanceId) {
3629
- for (const row of this.plansFor(instanceId) ?? []) if (row.offered) return row.canvas;
3316
+ canvasFor(blockId) {
3317
+ for (const row of this.plansFor(blockId) ?? []) if (row.offered) return row.canvas;
3630
3318
  return null;
3631
3319
  }
3632
- ensureSessions(instanceId, deviceId) {
3320
+ ensureSessions(blockId, deviceId) {
3633
3321
  for (const profile of GRID_PROFILES) {
3634
- const key = sessionKey(instanceId, profile);
3635
- const plan = this.planFor(instanceId, profile);
3322
+ const key = sessionKey(blockId, profile);
3323
+ const plan = this.planFor(blockId, profile);
3636
3324
  if (plan === null || !plan.offered || !plan.published) {
3637
3325
  const stale = this.sessions.get(key);
3638
3326
  if (stale) {
@@ -3647,14 +3335,14 @@ var CameraGridAddon = class extends BaseAddon {
3647
3335
  this.ctx.logger.error("camera-grid: composition refused — no pinned ffmpeg on this node (D540)", {
3648
3336
  tags: { deviceId },
3649
3337
  meta: {
3650
- instanceId,
3338
+ blockId,
3651
3339
  profile
3652
3340
  }
3653
3341
  });
3654
3342
  this.resolveFfmpeg();
3655
3343
  continue;
3656
3344
  }
3657
- this.sessions.set(key, new GridSessionEntry(instanceId, profile, this.makeSession(instanceId, deviceId, profile, binaryPath)));
3345
+ this.sessions.set(key, new GridSessionEntry(blockId, profile, this.makeSession(blockId, deviceId, profile, binaryPath)));
3658
3346
  }
3659
3347
  }
3660
3348
  /**
@@ -3684,7 +3372,7 @@ var CameraGridAddon = class extends BaseAddon {
3684
3372
  }
3685
3373
  return names;
3686
3374
  }
3687
- makeSession(instanceId, deviceId, profile, binaryPath) {
3375
+ makeSession(blockId, deviceId, profile, binaryPath) {
3688
3376
  const childContext = {
3689
3377
  binaryPath,
3690
3378
  logger: this.ctx.logger,
@@ -3710,7 +3398,7 @@ var CameraGridAddon = class extends BaseAddon {
3710
3398
  this.ctx.logger.info("camera grid: a source has not republished yet — asking again", {
3711
3399
  tags: { deviceId },
3712
3400
  meta: {
3713
- instanceId,
3401
+ blockId,
3714
3402
  profile,
3715
3403
  sourceDeviceId,
3716
3404
  waitedMs
@@ -3721,7 +3409,7 @@ var CameraGridAddon = class extends BaseAddon {
3721
3409
  this.ctx.logger.info("camera grid: source acquired", {
3722
3410
  tags: { deviceId },
3723
3411
  meta: {
3724
- instanceId,
3412
+ blockId,
3725
3413
  profile,
3726
3414
  sourceDeviceId,
3727
3415
  mode: dial.mode,
@@ -3741,10 +3429,10 @@ var CameraGridAddon = class extends BaseAddon {
3741
3429
  })
3742
3430
  },
3743
3431
  resolvePlan: () => {
3744
- const instance = this.instanceById(instanceId);
3745
- const plan = this.planFor(instanceId, profile);
3746
- if (!instance || plan === null || !plan.offered || !plan.published) return null;
3747
- return gridPlanFor(instance, {
3432
+ const grid = this.gridById(blockId);
3433
+ const plan = this.planFor(blockId, profile);
3434
+ if (grid === null || plan === null || !plan.offered || !plan.published) return null;
3435
+ return gridPlanFor(grid.layout, {
3748
3436
  encoder: "libx264",
3749
3437
  decodeHwAccel: null,
3750
3438
  canvas: plan.canvas
@@ -3753,51 +3441,36 @@ var CameraGridAddon = class extends BaseAddon {
3753
3441
  });
3754
3442
  return session;
3755
3443
  }
3756
- /** The session a dial is asking for, or `null` - which the relay answers 404 to. */
3444
+ /** The session a dial is asking for, or `null` - which the relay answers 404 to. The relay's `instanceId` is the block id. */
3757
3445
  sessionFor(request) {
3758
3446
  return this.sessions.get(sessionKey(request.instanceId, request.profile))?.session ?? null;
3759
3447
  }
3760
3448
  /** This grid's sessions, in DESCENDING quality — the snapshot takes the first running one. */
3761
3449
  sessionsForDevice(deviceId) {
3762
- const instanceId = this.instanceIdForDevice(deviceId);
3763
- if (instanceId === null) return [];
3450
+ const grid = this.gridForDevice(deviceId);
3451
+ if (grid === null) return [];
3764
3452
  const entries = [];
3765
3453
  for (const profile of GRID_PROFILES) {
3766
- const entry = this.sessions.get(sessionKey(instanceId, profile));
3454
+ const entry = this.sessions.get(sessionKey(grid.block.blockId, profile));
3767
3455
  if (entry) entries.push(entry);
3768
3456
  }
3769
3457
  return entries;
3770
3458
  }
3771
- /** A grid that is gone stops immediately - it must not keep N sources dialled. */
3772
- async retireWithdrawnSessions(instances) {
3773
- const live = new Set(instances.filter((instance) => instance.enabled).map((i) => i.id));
3774
- for (const [key, entry] of [...this.sessions]) {
3775
- if (live.has(entry.instanceId)) continue;
3776
- this.ctx.logger.info("camera grid: retiring a withdrawn grid", {
3777
- tags: { deviceId: this.deviceIdByInstanceId.get(entry.instanceId) ?? 0 },
3778
- meta: { instanceId: entry.instanceId }
3779
- });
3780
- this.sessions.delete(key);
3781
- await entry.session.dispose();
3782
- }
3783
- for (const instanceId of [...this.deviceIdByInstanceId.keys()]) {
3784
- if (live.has(instanceId)) continue;
3785
- this.activity?.forget(this.deviceIdByInstanceId.get(instanceId) ?? 0);
3786
- this.deviceIdByInstanceId.delete(instanceId);
3787
- this.plansByInstanceId.delete(instanceId);
3788
- }
3789
- }
3790
3459
  /**
3791
3460
  * A geometry change is a NEW composition. The running child is composing the
3792
3461
  * old one, and ffmpeg has no way to be told otherwise, so it is stopped: the
3793
3462
  * consumer's next read re-dials and gets the new picture.
3794
3463
  */
3795
- async applyLayoutChanges() {
3464
+ async applyLayoutChanges(blockId) {
3465
+ const deviceId = this.gridById(blockId)?.block.deviceId ?? 0;
3796
3466
  for (const entry of this.sessions.values()) {
3797
- if (!entry.session.isRunning()) continue;
3467
+ if (entry.blockId !== blockId || !entry.session.isRunning()) continue;
3798
3468
  this.ctx.logger.info("camera grid: the layout changed - restarting the composition", {
3799
- tags: { deviceId: this.deviceIdByInstanceId.get(entry.instanceId) ?? 0 },
3800
- meta: { instanceId: entry.instanceId }
3469
+ tags: { deviceId },
3470
+ meta: {
3471
+ blockId,
3472
+ profile: entry.profile
3473
+ }
3801
3474
  });
3802
3475
  entry.session.onChildEnded("layout-changed");
3803
3476
  }
@@ -3829,44 +3502,48 @@ var CameraGridAddon = class extends BaseAddon {
3829
3502
  * empty array would be the broker reading "this camera offers nothing" and
3830
3503
  * sweeping every stream it holds for the grid.
3831
3504
  */
3832
- descriptorsFor(instanceId) {
3833
- const instance = this.instanceById(instanceId);
3505
+ descriptorsFor(blockId) {
3506
+ const grid = this.gridById(blockId);
3834
3507
  const relay = this.relay;
3835
- const plans = this.plansFor(instanceId);
3836
- if (!instance || !relay || plans === null) return null;
3508
+ const plans = this.plansFor(blockId);
3509
+ if (grid === null || !relay || plans === null) return null;
3837
3510
  return plans.filter((row) => row.offered && row.published).map((row) => gridStreamDescriptor({
3838
3511
  profile: row.profile,
3839
3512
  width: row.offered ? row.canvas.width : 0,
3840
3513
  height: row.offered ? row.canvas.height : 0,
3841
- fps: instance.fps,
3514
+ fps: grid.layout.fps,
3842
3515
  url: relay.streamUrl({
3843
- instanceId,
3516
+ instanceId: blockId,
3844
3517
  profile: row.profile
3845
3518
  })
3846
3519
  }));
3847
3520
  }
3848
- instanceIdForDevice(deviceId) {
3849
- for (const [instanceId, id] of this.deviceIdByInstanceId) if (id === deviceId) return instanceId;
3850
- return null;
3851
- }
3852
- instanceForDevice(deviceId) {
3853
- const instanceId = this.instanceIdForDevice(deviceId);
3854
- return instanceId === null ? null : this.instanceById(instanceId) ?? null;
3855
- }
3856
- gridViewFor(deviceId) {
3857
- const instance = this.instanceForDevice(deviceId);
3858
- if (!instance) return null;
3521
+ /**
3522
+ * The grid's name is its DEVICE row's: the composer owns the row and keeps
3523
+ * it in step with the block, and an operator rename lands there. Asked at
3524
+ * the moment the editor reads, never kept here (D224).
3525
+ */
3526
+ async gridViewFor(deviceId) {
3527
+ const grid = this.gridForDevice(deviceId);
3528
+ if (grid === null) return null;
3529
+ const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId }).catch((error) => {
3530
+ this.ctx.logger.warn("camera grid: the grid row could not be read for its name", {
3531
+ tags: { deviceId },
3532
+ meta: { error: errMsg(error) }
3533
+ });
3534
+ return null;
3535
+ });
3859
3536
  return {
3860
- instanceId: instance.id,
3537
+ blockId: grid.block.blockId,
3861
3538
  deviceId,
3862
- name: instance.name,
3863
- fps: instance.fps,
3864
- cells: instance.cells.map((cell) => ({
3539
+ name: device?.name ?? grid.block.name,
3540
+ fps: grid.layout.fps,
3541
+ cells: grid.layout.cells.map((cell) => ({
3865
3542
  deviceId: cell.deviceId,
3866
3543
  source: cell.source,
3867
3544
  cell: cell.cell
3868
3545
  })),
3869
- profiles: (this.plansByInstanceId.get(instance.id) ?? []).map((row) => ({
3546
+ profiles: (this.plansByBlockId.get(grid.block.blockId) ?? []).map((row) => ({
3870
3547
  profile: row.profile,
3871
3548
  offered: row.offered,
3872
3549
  published: row.offered && row.published,
@@ -3875,39 +3552,71 @@ var CameraGridAddon = class extends BaseAddon {
3875
3552
  }))
3876
3553
  };
3877
3554
  }
3878
- async saveGridLayout(input) {
3879
- const instance = this.instanceForDevice(input.deviceId);
3880
- if (!instance) throw new Error(`camera-grid: device ${String(input.deviceId)} is not a grid camera`);
3881
- const updated = {
3882
- ...instance,
3883
- ...input.name !== void 0 ? { name: input.name.trim() } : {},
3884
- ...input.fps !== void 0 ? { fps: input.fps } : {},
3885
- ...input.publishedProfiles !== void 0 ? { publishedProfiles: [...input.publishedProfiles] } : {},
3886
- cells: input.cells.map((cell) => ({ ...cell }))
3887
- };
3888
- this.ctx.logger.info("camera grid: layout saved", {
3889
- tags: { deviceId: input.deviceId },
3890
- meta: {
3891
- cells: updated.cells.length,
3892
- sources: [...new Set(updated.cells.map((cell) => cell.deviceId))],
3893
- fps: updated.fps
3894
- }
3555
+ /** The identity `(addonId, stableId)` of each source device, by one targeted read. */
3556
+ async sourceRefs(deviceIds) {
3557
+ const unique = [...new Set(deviceIds)];
3558
+ if (unique.length === 0) return /* @__PURE__ */ new Map();
3559
+ const rows = await this.ctx.api.deviceManager.listAll.query({
3560
+ deviceIds: unique,
3561
+ projection: "slim"
3895
3562
  });
3896
- const handle = this.ctx.records?.kind(cameraGridKind);
3897
- if (handle === void 0) throw new Error("camera-grid: the grid records are not available");
3898
- await handle.patch(instance.id, {
3899
- name: updated.name,
3900
- fps: updated.fps,
3901
- publishedProfiles: updated.publishedProfiles,
3902
- cells: updated.cells
3563
+ return new Map(rows.map((row) => [row.id, {
3564
+ addonId: row.addonId,
3565
+ stableId: row.stableId
3566
+ }]));
3567
+ }
3568
+ /**
3569
+ * A layout save writes the BLOCK: its spec, sources by identity, with the
3570
+ * block's `updatedAt` as the optimistic guard. The name is not the editor's
3571
+ * to write (it is the block's, renamed through the block).
3572
+ */
3573
+ saveGridLayout(input) {
3574
+ return this.serialized(async () => {
3575
+ const grid = this.gridForDevice(input.deviceId);
3576
+ if (grid === null) throw new Error(`camera-grid: device ${String(input.deviceId)} is not a grid camera`);
3577
+ const refs = await this.sourceRefs(input.cells.map((cell) => cell.deviceId));
3578
+ const spec = gridSpecFromPatch(grid.block.spec, input, (id) => refs.get(id) ?? null);
3579
+ const composition = gridComposition(spec);
3580
+ const result = await this.ctx.api.coreBlocks.updateComposition.mutate({
3581
+ blockId: grid.block.blockId,
3582
+ expectedUpdatedAt: grid.block.updatedAt,
3583
+ block: { composition }
3584
+ });
3585
+ this.ctx.logger.info("camera grid: layout saved", {
3586
+ tags: { deviceId: input.deviceId },
3587
+ meta: {
3588
+ blockId: grid.block.blockId,
3589
+ cells: spec.cells.length,
3590
+ sources: [...new Set(input.cells.map((cell) => cell.deviceId))],
3591
+ fps: spec.fps
3592
+ }
3593
+ });
3594
+ const saved = {
3595
+ hosted: grid.hosted,
3596
+ block: {
3597
+ ...grid.block,
3598
+ updatedAt: result.block.updatedAt,
3599
+ composition,
3600
+ spec
3601
+ },
3602
+ layout: {
3603
+ fps: spec.fps,
3604
+ publishedProfiles: spec.publishedProfiles,
3605
+ cells: input.cells.map((cell) => ({
3606
+ deviceId: cell.deviceId,
3607
+ source: cell.source,
3608
+ cell: cell.cell
3609
+ }))
3610
+ }
3611
+ };
3612
+ this.grids = new Map([...this.grids, [grid.block.blockId, saved]]);
3613
+ await this.applyLayoutChanges(grid.block.blockId);
3614
+ await this.refreshSourcePlans();
3615
+ this.ensureSessions(grid.block.blockId, input.deviceId);
3616
+ const view = await this.gridViewFor(input.deviceId);
3617
+ if (view === null) throw new Error("camera-grid: the grid vanished while it was being saved");
3618
+ return view;
3903
3619
  });
3904
- await this.refreshInstanceRows();
3905
- await this.applyLayoutChanges();
3906
- await this.refreshSourcePlans(this.instanceList());
3907
- this.ensureSessions(instance.id, input.deviceId);
3908
- const view = this.gridViewFor(input.deviceId);
3909
- if (!view) throw new Error("camera-grid: the grid vanished while it was being saved");
3910
- return view;
3911
3620
  }
3912
3621
  /**
3913
3622
  * Resolve the pinned build, single-flighted, and hand it to the frame sampler.
@@ -4198,4 +3907,4 @@ async function startGridChild(ctx, plan, sources, onEnded) {
4198
3907
  };
4199
3908
  }
4200
3909
  //#endregion
4201
- export { CAMERA_GRID_KIND_NAME, CameraGridAddon, CameraGridAddon as default, GRID_CAM_STREAM_ID, GRID_PROFILES, GRID_SILENCED_CAP_NAMES, GridBodySchema, GridCameraDevice, GridFrameSampler, GridLastFrameFileStore, GridSnapshotSource, GridStreamRelay, GridStreamSession, buildGridCameraDeclarations, buildGridFilterGraph, cameraGridKind, deriveGridCanvas, gridCamStreamId, gridCameraReconciliationIndex, gridPlanFor, gridProfilePlans, gridSnapshotAnswerFor, gridSourceDial, gridStreamDescriptor, gridStreamInvocation, initialGridBody, installGridCameraRuntime, newGridCameraStableId, parseGridStreamPath, rawGridOfRecord, readGridInstances, silenceAnalysisFor, startGridChild };
3910
+ export { CameraGridAddon, CameraGridAddon as default, GRID_CAM_STREAM_ID, GRID_PROFILES, GRID_SILENCED_CAP_NAMES, GridCameraDevice, GridFrameSampler, GridLastFrameFileStore, GridSnapshotSource, GridStreamRelay, GridStreamSession, buildGridFilterGraph, deriveGridCanvas, gridCamStreamId, gridComposition, gridPlanFor, gridProfilePlans, gridSnapshotAnswerFor, gridSourceDial, gridSpecFromPatch, gridStreamDescriptor, gridStreamInvocation, installGridCameraRuntime, parseGridStreamPath, resolveGridCells, silenceAnalysisFor, sourceRefKey, startGridChild };