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