@camstack/addon-provider-velux 0.2.59 → 0.2.61

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 (3) hide show
  1. package/dist/addon.js +428 -25
  2. package/dist/addon.mjs +428 -25
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -12756,7 +12756,26 @@ var DiscoveryCandidateSchema = object({
12756
12756
  * identity ahead of adoption. Rendering metadata (unit, precision)
12757
12757
  * flows live through the cap STATUS SLICE after adoption.
12758
12758
  */
12759
- sourceInfo: SourceInfoSchema.optional()
12759
+ sourceInfo: SourceInfoSchema.optional(),
12760
+ /**
12761
+ * Set when this candidate is a device the provider ALREADY owns.
12762
+ *
12763
+ * A scan cannot generally produce the identity a device was onboarded under
12764
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
12765
+ * comparison never matches and an owned device looks addable. Re-adopting one
12766
+ * overwrites its config with scan-derived values — that is how a Home Hub's
12767
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
12768
+ * three child cameras offline for four hours.
12769
+ *
12770
+ * A provider that can recognise its own devices says so here. Absent means
12771
+ * "not recognised", which is not the same as "known to be new" — a provider
12772
+ * that cannot tell simply never sets it.
12773
+ */
12774
+ alreadyOnboarded: boolean().optional(),
12775
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
12776
+ onboardedDeviceId: number().optional(),
12777
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
12778
+ onboardedName: string().optional()
12760
12779
  });
12761
12780
  /**
12762
12781
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -12812,6 +12831,35 @@ var deviceProviderCapability = {
12812
12831
  name: string(),
12813
12832
  type: string()
12814
12833
  }))),
12834
+ /**
12835
+ * Tear down and reconstruct ONE device in place from its persisted rows —
12836
+ * touching no other device this provider owns.
12837
+ *
12838
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
12839
+ * migrated numbers: after `swapIds` the runner's live instance still
12840
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
12841
+ * registrations and its log tags), and a live object cannot be renumbered.
12842
+ * Before this method the only flush was restarting the whole owning addon
12843
+ * — which took every camera the provider owns down with it (28 devices
12844
+ * for one migrated camera, measured 2026-09-04, and the morning of the
12845
+ * same day ~27 devices' native caps did not come back on their own).
12846
+ *
12847
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
12848
+ * that changes. The reply carries the id the device answers on NOW.
12849
+ * Implemented once in `BaseDeviceProvider` — decommission the live
12850
+ * instance (if any), then re-create from the persisted row: the same
12851
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
12852
+ * An RPC, never an event: a dropped event would leave the runner writing
12853
+ * against the wrong camera (D8).
12854
+ *
12855
+ * Construction can dial hardware, and the migrated source is
12856
+ * characteristically dead — the timeout covers a full activate window
12857
+ * rather than the 60 s default.
12858
+ */
12859
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
12860
+ kind: "mutation",
12861
+ timeoutMs: 3 * 6e4
12862
+ }),
12815
12863
  supportsDiscovery: method(object({}), boolean()),
12816
12864
  /**
12817
12865
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13139,7 +13187,8 @@ method(object({
13139
13187
  targetId: number()
13140
13188
  }), MigrateDeviceResultSchema, {
13141
13189
  kind: "mutation",
13142
- auth: "admin"
13190
+ auth: "admin",
13191
+ timeoutMs: 12 * 6e4
13143
13192
  }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
13144
13193
  deviceId: number(),
13145
13194
  name: string()
@@ -32495,6 +32544,147 @@ var BaseDevice = class {
32495
32544
  }
32496
32545
  };
32497
32546
  /**
32547
+ * Delays before retry rounds 1..N — the round count IS the bound.
32548
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32549
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32550
+ * per attempt) covers a device-manager lock held for minutes — the
32551
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32552
+ */
32553
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32554
+ 1e4,
32555
+ 3e4,
32556
+ 9e4
32557
+ ];
32558
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32559
+ function sleep$1(ms, signal) {
32560
+ return new Promise((resolve) => {
32561
+ if (signal.aborted) {
32562
+ resolve();
32563
+ return;
32564
+ }
32565
+ const onAbort = () => {
32566
+ clearTimeout(timer);
32567
+ resolve();
32568
+ };
32569
+ const timer = setTimeout(() => {
32570
+ signal.removeEventListener("abort", onAbort);
32571
+ resolve();
32572
+ }, ms);
32573
+ timer.unref?.();
32574
+ signal.addEventListener("abort", onAbort, { once: true });
32575
+ });
32576
+ }
32577
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32578
+ * not reject (callers wrap their own try/catch). */
32579
+ async function runWithConcurrency(items, width, fn) {
32580
+ const queue = [...items];
32581
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32582
+ const lane = async () => {
32583
+ for (;;) {
32584
+ const item = queue.shift();
32585
+ if (item === void 0) return;
32586
+ await fn(item);
32587
+ }
32588
+ };
32589
+ await Promise.all(Array.from({ length: laneCount }, lane));
32590
+ }
32591
+ var DeviceRestoreRetryScheduler = class {
32592
+ #logger;
32593
+ #attempt;
32594
+ #onPermanentFailure;
32595
+ #delaysMs;
32596
+ #concurrency;
32597
+ #now;
32598
+ #abort = new AbortController();
32599
+ constructor(options) {
32600
+ this.#logger = options.logger;
32601
+ this.#attempt = options.attempt;
32602
+ this.#onPermanentFailure = options.onPermanentFailure;
32603
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32604
+ this.#concurrency = options.concurrency ?? 4;
32605
+ this.#now = options.now ?? Date.now;
32606
+ }
32607
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32608
+ * permanently failed — the next boot restores them from disk. */
32609
+ cancel() {
32610
+ this.#abort.abort();
32611
+ }
32612
+ /**
32613
+ * Run the bounded retry rounds. Resolves when every entry has either
32614
+ * restored, been marked permanently failed, or the scheduler was
32615
+ * cancelled. Never rejects.
32616
+ */
32617
+ async run(initialFailures) {
32618
+ let pending = initialFailures.map((failure) => ({
32619
+ saved: failure.saved,
32620
+ lastError: failure.error,
32621
+ attempts: 1
32622
+ }));
32623
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32624
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32625
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32626
+ if (this.#abort.signal.aborted) break;
32627
+ pending = await this.#runRound(pending, round);
32628
+ }
32629
+ if (this.#abort.signal.aborted) return [];
32630
+ const terminal = pending.map((entry) => ({
32631
+ deviceId: entry.saved.id,
32632
+ stableId: entry.saved.stableId,
32633
+ type: String(entry.saved.type),
32634
+ attempts: entry.attempts,
32635
+ lastError: entry.lastError,
32636
+ failedAt: this.#now()
32637
+ }));
32638
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32639
+ return terminal;
32640
+ }
32641
+ /** One retry round: parents first (phase 0), then hub-adopted
32642
+ * children (phase 1) — a child's attempt depends on its parent
32643
+ * having landed, exactly like the initial two-pass restore. */
32644
+ async #runRound(pending, round) {
32645
+ const next = [];
32646
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32647
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32648
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32649
+ if (this.#abort.signal.aborted) {
32650
+ next.push(entry);
32651
+ return;
32652
+ }
32653
+ const attemptNo = entry.attempts + 1;
32654
+ try {
32655
+ await this.#attempt(entry.saved);
32656
+ this.#logger.info("Device restored on retry", {
32657
+ tags: {
32658
+ deviceId: entry.saved.id,
32659
+ stableId: entry.saved.stableId
32660
+ },
32661
+ meta: { attempt: attemptNo }
32662
+ });
32663
+ } catch (err) {
32664
+ const lastError = err instanceof Error ? err.message : String(err);
32665
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32666
+ this.#logger.warn("Device restore retry failed", {
32667
+ tags: {
32668
+ deviceId: entry.saved.id,
32669
+ stableId: entry.saved.stableId
32670
+ },
32671
+ meta: {
32672
+ attempt: attemptNo,
32673
+ remainingRetries,
32674
+ error: lastError
32675
+ }
32676
+ });
32677
+ next.push({
32678
+ saved: entry.saved,
32679
+ lastError,
32680
+ attempts: attemptNo
32681
+ });
32682
+ }
32683
+ });
32684
+ return next;
32685
+ }
32686
+ };
32687
+ /**
32498
32688
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32499
32689
  * device-provider cap router. Shared across all providers.
32500
32690
  */
@@ -32543,6 +32733,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32543
32733
  }];
32544
32734
  }
32545
32735
  async onShutdown() {
32736
+ this.cancelRestoreRetries();
32546
32737
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32547
32738
  for (const device of devices) try {
32548
32739
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32560,9 +32751,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32560
32751
  async start() {}
32561
32752
  async stop() {}
32562
32753
  async getStatus() {
32754
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32755
+ const summary = this.restoreFailureSummary();
32756
+ if (summary === null) return {
32757
+ connected: true,
32758
+ deviceCount: all.length
32759
+ };
32563
32760
  return {
32564
32761
  connected: true,
32565
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
32762
+ deviceCount: all.length,
32763
+ error: summary
32566
32764
  };
32567
32765
  }
32568
32766
  async getDevices() {
@@ -32652,8 +32850,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32652
32850
  };
32653
32851
  }
32654
32852
  async restoreDevices(savedDevices) {
32655
- await this.onRestoreDevices(savedDevices);
32656
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
32853
+ const report = await this.onRestoreDevices(savedDevices);
32854
+ if (savedDevices.length === 0) return;
32855
+ if (report && report.failedCount > 0) {
32856
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
32857
+ return;
32858
+ }
32859
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
32860
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
32861
+ }
32862
+ /** Retry schedule. Overridable (tests use millisecond delays). */
32863
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
32864
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
32865
+ * never re-stampede full-width while the initial pass does (D167). */
32866
+ restoreRetryConcurrency = 4;
32867
+ _restoreRetryScheduler = null;
32868
+ _restoreRetryCompletion = null;
32869
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
32870
+ /** Settles when the background retry rounds finish (or `null` when
32871
+ * nothing failed). Exposed for tests and subclass diagnostics —
32872
+ * boot NEVER awaits this: the runner's post-init handshake goes out
32873
+ * with the devices that restored, and a late success is announced
32874
+ * through the `native-cap-change` → `updateCaps` path. */
32875
+ get restoreRetryCompletion() {
32876
+ return this._restoreRetryCompletion;
32877
+ }
32878
+ /** Devices that exhausted the retry bound this process lifetime. */
32879
+ get permanentRestoreFailures() {
32880
+ return [...this._permanentRestoreFailures.values()];
32881
+ }
32882
+ /** One-line operator-facing summary for `getStatus().error`, or
32883
+ * `null` when every device restored. */
32884
+ restoreFailureSummary() {
32885
+ if (this._permanentRestoreFailures.size === 0) return null;
32886
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
32887
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
32888
+ }
32889
+ cancelRestoreRetries() {
32890
+ this._restoreRetryScheduler?.cancel();
32891
+ this._restoreRetryScheduler = null;
32892
+ }
32893
+ recordPermanentRestoreFailure(failure) {
32894
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
32895
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
32896
+ tags: {
32897
+ deviceId: failure.deviceId,
32898
+ stableId: failure.stableId
32899
+ },
32900
+ meta: {
32901
+ type: failure.type,
32902
+ attempts: failure.attempts,
32903
+ error: failure.lastError
32904
+ }
32905
+ });
32906
+ }
32907
+ scheduleRestoreRetries(failures, attempt) {
32908
+ const scheduler = new DeviceRestoreRetryScheduler({
32909
+ logger: this.ctx.logger,
32910
+ delaysMs: this.restoreRetryDelaysMs,
32911
+ concurrency: this.restoreRetryConcurrency,
32912
+ attempt,
32913
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
32914
+ });
32915
+ this._restoreRetryScheduler = scheduler;
32916
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
32917
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
32918
+ });
32919
+ }
32920
+ /**
32921
+ * Tear down and reconstruct ONE device from its persisted rows — the
32922
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
32923
+ * and no other device this provider owns is disturbed.
32924
+ *
32925
+ * Keyed by `stableId` because the caller's whole reason to be here is that
32926
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
32927
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
32928
+ * whatever number the row carries NOW. The teardown is `decommission` —
32929
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
32930
+ * unregisters native caps, drops the registry entry) — and the rebuild is
32931
+ * the boot restore's own `create()` path, including its pass 2: first-class
32932
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
32933
+ * parent by the cascade and must be re-created explicitly, because only
32934
+ * accessory children come back through `getAccessoryChildren()`.
32935
+ *
32936
+ * Reloading an accessory child directly is refused (no device class) —
32937
+ * reload its parent instead.
32938
+ */
32939
+ async reloadDevice(input) {
32940
+ const { stableId } = input;
32941
+ const devices = this.ctx.kernel.devices;
32942
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
32943
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
32944
+ if (live) await devices.decommission(live.id);
32945
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
32946
+ addonId: this.addonId,
32947
+ stableId
32948
+ });
32949
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
32950
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
32951
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
32952
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
32953
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
32954
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
32955
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
32956
+ for (const row of rows) {
32957
+ if (row.parentDeviceId !== id) continue;
32958
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
32959
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
32960
+ if (!ChildClass) continue;
32961
+ try {
32962
+ await devices.create(row.stableId, ChildClass, {}, id);
32963
+ } catch (err) {
32964
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
32965
+ tags: {
32966
+ deviceId: row.id,
32967
+ stableId: row.stableId
32968
+ },
32969
+ meta: {
32970
+ parentDeviceId: id,
32971
+ error: err instanceof Error ? err.message : String(err)
32972
+ }
32973
+ });
32974
+ }
32975
+ }
32976
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
32977
+ tags: { deviceId: id },
32978
+ meta: {
32979
+ stableId,
32980
+ type: meta.type
32981
+ }
32982
+ });
32983
+ return { deviceId: id };
32657
32984
  }
32658
32985
  /**
32659
32986
  * Restore devices from persisted state. Two-pass:
@@ -32679,55 +33006,125 @@ var BaseDeviceProvider = class extends BaseAddon {
32679
33006
  * accessory-spawn flow handles via the parent's
32680
33007
  * `getAccessoryChildren()`. Override only when the default doesn't
32681
33008
  * fit.
33009
+ *
33010
+ * A row that fails either pass is NOT terminal (D347): it is handed
33011
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33012
+ * Only after the bound is exhausted is the device marked permanently
33013
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33014
+ * `getStatus().error`.
33015
+ */
33016
+ /**
33017
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33018
+ * Default: no-op — most providers have nothing to heal.
33019
+ *
33020
+ * This exists because a restored device self-hydrates from the DB: `create()`
33021
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33022
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33023
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33024
+ * been emptied failed all four bounded attempts against fields
33025
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33026
+ *
33027
+ * Implementations get every saved row, so a child can read its parent's blob.
33028
+ * A heal that throws is treated like any other restore failure: retried under
33029
+ * the bound, then reported — never swallowed.
32682
33030
  */
33031
+ async healSavedConfig(_saved, _allSaved) {}
32683
33032
  async onRestoreDevices(savedDevices) {
32684
33033
  const restored = /* @__PURE__ */ new Set();
33034
+ const failures = [];
33035
+ const attemptRestore = async (saved) => {
33036
+ if (restored.has(saved.id)) return;
33037
+ const Class = this.deviceClasses[saved.type];
33038
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33039
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33040
+ await this.healSavedConfig(saved, savedDevices);
33041
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33042
+ restored.add(saved.id);
33043
+ };
32685
33044
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32686
33045
  const restoreOne = async (saved) => {
32687
- const Class = this.deviceClasses[saved.type];
32688
- if (!Class) {
33046
+ if (!this.deviceClasses[saved.type]) {
32689
33047
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32690
- tags: { stableId: saved.stableId },
33048
+ tags: {
33049
+ deviceId: saved.id,
33050
+ stableId: saved.stableId
33051
+ },
32691
33052
  meta: { type: saved.type }
32692
33053
  });
32693
33054
  return;
32694
33055
  }
32695
33056
  try {
32696
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32697
- restored.add(saved.id);
33057
+ await attemptRestore(saved);
32698
33058
  } catch (err) {
32699
- this.ctx.logger.warn("Failed to restore device", {
32700
- tags: { stableId: saved.stableId },
33059
+ const error = err instanceof Error ? err.message : String(err);
33060
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33061
+ tags: {
33062
+ deviceId: saved.id,
33063
+ stableId: saved.stableId
33064
+ },
32701
33065
  meta: {
32702
33066
  type: saved.type,
32703
- error: err instanceof Error ? err.message : String(err)
33067
+ attempt: 1,
33068
+ error
32704
33069
  }
32705
33070
  });
33071
+ failures.push({
33072
+ saved,
33073
+ error
33074
+ });
32706
33075
  }
32707
33076
  };
32708
33077
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33078
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32709
33079
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32710
33080
  for (const saved of childRows) {
32711
- const Class = this.deviceClasses[saved.type];
32712
- if (!Class) continue;
33081
+ if (!this.deviceClasses[saved.type]) continue;
32713
33082
  if (saved.parentDeviceId === null) continue;
32714
- if (!restored.has(saved.parentDeviceId)) continue;
32715
- try {
32716
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32717
- restored.add(saved.id);
32718
- } catch (err) {
32719
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33083
+ if (restored.has(saved.parentDeviceId)) {
33084
+ try {
33085
+ await attemptRestore(saved);
33086
+ } catch (err) {
33087
+ const error = err instanceof Error ? err.message : String(err);
33088
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33089
+ tags: {
33090
+ deviceId: saved.id,
33091
+ stableId: saved.stableId,
33092
+ parentDeviceId: saved.parentDeviceId
33093
+ },
33094
+ meta: {
33095
+ type: saved.type,
33096
+ attempt: 1,
33097
+ error
33098
+ }
33099
+ });
33100
+ failures.push({
33101
+ saved,
33102
+ error
33103
+ });
33104
+ }
33105
+ continue;
33106
+ }
33107
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33108
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32720
33109
  tags: {
33110
+ deviceId: saved.id,
32721
33111
  stableId: saved.stableId,
32722
33112
  parentDeviceId: saved.parentDeviceId
32723
33113
  },
32724
- meta: {
32725
- type: saved.type,
32726
- error: err instanceof Error ? err.message : String(err)
32727
- }
33114
+ meta: { type: saved.type }
32728
33115
  });
33116
+ failures.push({
33117
+ saved,
33118
+ error: `parent device ${saved.parentDeviceId} not restored`
33119
+ });
33120
+ continue;
32729
33121
  }
32730
33122
  }
33123
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33124
+ return {
33125
+ restoredCount: restored.size,
33126
+ failedCount: failures.length
33127
+ };
32731
33128
  }
32732
33129
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32733
33130
  toSummary(device) {
@@ -34490,6 +34887,12 @@ Object.freeze({
34490
34887
  addonId: null,
34491
34888
  access: "view"
34492
34889
  },
34890
+ "deviceProvider.reloadDevice": {
34891
+ capName: "device-provider",
34892
+ capScope: "system",
34893
+ addonId: null,
34894
+ access: "create"
34895
+ },
34493
34896
  "deviceProvider.start": {
34494
34897
  capName: "device-provider",
34495
34898
  capScope: "system",
package/dist/addon.mjs CHANGED
@@ -12755,7 +12755,26 @@ var DiscoveryCandidateSchema = object({
12755
12755
  * identity ahead of adoption. Rendering metadata (unit, precision)
12756
12756
  * flows live through the cap STATUS SLICE after adoption.
12757
12757
  */
12758
- sourceInfo: SourceInfoSchema.optional()
12758
+ sourceInfo: SourceInfoSchema.optional(),
12759
+ /**
12760
+ * Set when this candidate is a device the provider ALREADY owns.
12761
+ *
12762
+ * A scan cannot generally produce the identity a device was onboarded under
12763
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
12764
+ * comparison never matches and an owned device looks addable. Re-adopting one
12765
+ * overwrites its config with scan-derived values — that is how a Home Hub's
12766
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
12767
+ * three child cameras offline for four hours.
12768
+ *
12769
+ * A provider that can recognise its own devices says so here. Absent means
12770
+ * "not recognised", which is not the same as "known to be new" — a provider
12771
+ * that cannot tell simply never sets it.
12772
+ */
12773
+ alreadyOnboarded: boolean().optional(),
12774
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
12775
+ onboardedDeviceId: number().optional(),
12776
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
12777
+ onboardedName: string().optional()
12759
12778
  });
12760
12779
  /**
12761
12780
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -12811,6 +12830,35 @@ var deviceProviderCapability = {
12811
12830
  name: string(),
12812
12831
  type: string()
12813
12832
  }))),
12833
+ /**
12834
+ * Tear down and reconstruct ONE device in place from its persisted rows —
12835
+ * touching no other device this provider owns.
12836
+ *
12837
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
12838
+ * migrated numbers: after `swapIds` the runner's live instance still
12839
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
12840
+ * registrations and its log tags), and a live object cannot be renumbered.
12841
+ * Before this method the only flush was restarting the whole owning addon
12842
+ * — which took every camera the provider owns down with it (28 devices
12843
+ * for one migrated camera, measured 2026-09-04, and the morning of the
12844
+ * same day ~27 devices' native caps did not come back on their own).
12845
+ *
12846
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
12847
+ * that changes. The reply carries the id the device answers on NOW.
12848
+ * Implemented once in `BaseDeviceProvider` — decommission the live
12849
+ * instance (if any), then re-create from the persisted row: the same
12850
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
12851
+ * An RPC, never an event: a dropped event would leave the runner writing
12852
+ * against the wrong camera (D8).
12853
+ *
12854
+ * Construction can dial hardware, and the migrated source is
12855
+ * characteristically dead — the timeout covers a full activate window
12856
+ * rather than the 60 s default.
12857
+ */
12858
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
12859
+ kind: "mutation",
12860
+ timeoutMs: 3 * 6e4
12861
+ }),
12814
12862
  supportsDiscovery: method(object({}), boolean()),
12815
12863
  /**
12816
12864
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13138,7 +13186,8 @@ method(object({
13138
13186
  targetId: number()
13139
13187
  }), MigrateDeviceResultSchema, {
13140
13188
  kind: "mutation",
13141
- auth: "admin"
13189
+ auth: "admin",
13190
+ timeoutMs: 12 * 6e4
13142
13191
  }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
13143
13192
  deviceId: number(),
13144
13193
  name: string()
@@ -32494,6 +32543,147 @@ var BaseDevice = class {
32494
32543
  }
32495
32544
  };
32496
32545
  /**
32546
+ * Delays before retry rounds 1..N — the round count IS the bound.
32547
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32548
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32549
+ * per attempt) covers a device-manager lock held for minutes — the
32550
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32551
+ */
32552
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32553
+ 1e4,
32554
+ 3e4,
32555
+ 9e4
32556
+ ];
32557
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32558
+ function sleep$1(ms, signal) {
32559
+ return new Promise((resolve) => {
32560
+ if (signal.aborted) {
32561
+ resolve();
32562
+ return;
32563
+ }
32564
+ const onAbort = () => {
32565
+ clearTimeout(timer);
32566
+ resolve();
32567
+ };
32568
+ const timer = setTimeout(() => {
32569
+ signal.removeEventListener("abort", onAbort);
32570
+ resolve();
32571
+ }, ms);
32572
+ timer.unref?.();
32573
+ signal.addEventListener("abort", onAbort, { once: true });
32574
+ });
32575
+ }
32576
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32577
+ * not reject (callers wrap their own try/catch). */
32578
+ async function runWithConcurrency(items, width, fn) {
32579
+ const queue = [...items];
32580
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32581
+ const lane = async () => {
32582
+ for (;;) {
32583
+ const item = queue.shift();
32584
+ if (item === void 0) return;
32585
+ await fn(item);
32586
+ }
32587
+ };
32588
+ await Promise.all(Array.from({ length: laneCount }, lane));
32589
+ }
32590
+ var DeviceRestoreRetryScheduler = class {
32591
+ #logger;
32592
+ #attempt;
32593
+ #onPermanentFailure;
32594
+ #delaysMs;
32595
+ #concurrency;
32596
+ #now;
32597
+ #abort = new AbortController();
32598
+ constructor(options) {
32599
+ this.#logger = options.logger;
32600
+ this.#attempt = options.attempt;
32601
+ this.#onPermanentFailure = options.onPermanentFailure;
32602
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32603
+ this.#concurrency = options.concurrency ?? 4;
32604
+ this.#now = options.now ?? Date.now;
32605
+ }
32606
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32607
+ * permanently failed — the next boot restores them from disk. */
32608
+ cancel() {
32609
+ this.#abort.abort();
32610
+ }
32611
+ /**
32612
+ * Run the bounded retry rounds. Resolves when every entry has either
32613
+ * restored, been marked permanently failed, or the scheduler was
32614
+ * cancelled. Never rejects.
32615
+ */
32616
+ async run(initialFailures) {
32617
+ let pending = initialFailures.map((failure) => ({
32618
+ saved: failure.saved,
32619
+ lastError: failure.error,
32620
+ attempts: 1
32621
+ }));
32622
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32623
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32624
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32625
+ if (this.#abort.signal.aborted) break;
32626
+ pending = await this.#runRound(pending, round);
32627
+ }
32628
+ if (this.#abort.signal.aborted) return [];
32629
+ const terminal = pending.map((entry) => ({
32630
+ deviceId: entry.saved.id,
32631
+ stableId: entry.saved.stableId,
32632
+ type: String(entry.saved.type),
32633
+ attempts: entry.attempts,
32634
+ lastError: entry.lastError,
32635
+ failedAt: this.#now()
32636
+ }));
32637
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32638
+ return terminal;
32639
+ }
32640
+ /** One retry round: parents first (phase 0), then hub-adopted
32641
+ * children (phase 1) — a child's attempt depends on its parent
32642
+ * having landed, exactly like the initial two-pass restore. */
32643
+ async #runRound(pending, round) {
32644
+ const next = [];
32645
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32646
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32647
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32648
+ if (this.#abort.signal.aborted) {
32649
+ next.push(entry);
32650
+ return;
32651
+ }
32652
+ const attemptNo = entry.attempts + 1;
32653
+ try {
32654
+ await this.#attempt(entry.saved);
32655
+ this.#logger.info("Device restored on retry", {
32656
+ tags: {
32657
+ deviceId: entry.saved.id,
32658
+ stableId: entry.saved.stableId
32659
+ },
32660
+ meta: { attempt: attemptNo }
32661
+ });
32662
+ } catch (err) {
32663
+ const lastError = err instanceof Error ? err.message : String(err);
32664
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32665
+ this.#logger.warn("Device restore retry failed", {
32666
+ tags: {
32667
+ deviceId: entry.saved.id,
32668
+ stableId: entry.saved.stableId
32669
+ },
32670
+ meta: {
32671
+ attempt: attemptNo,
32672
+ remainingRetries,
32673
+ error: lastError
32674
+ }
32675
+ });
32676
+ next.push({
32677
+ saved: entry.saved,
32678
+ lastError,
32679
+ attempts: attemptNo
32680
+ });
32681
+ }
32682
+ });
32683
+ return next;
32684
+ }
32685
+ };
32686
+ /**
32497
32687
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32498
32688
  * device-provider cap router. Shared across all providers.
32499
32689
  */
@@ -32542,6 +32732,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32542
32732
  }];
32543
32733
  }
32544
32734
  async onShutdown() {
32735
+ this.cancelRestoreRetries();
32545
32736
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32546
32737
  for (const device of devices) try {
32547
32738
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32559,9 +32750,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32559
32750
  async start() {}
32560
32751
  async stop() {}
32561
32752
  async getStatus() {
32753
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32754
+ const summary = this.restoreFailureSummary();
32755
+ if (summary === null) return {
32756
+ connected: true,
32757
+ deviceCount: all.length
32758
+ };
32562
32759
  return {
32563
32760
  connected: true,
32564
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
32761
+ deviceCount: all.length,
32762
+ error: summary
32565
32763
  };
32566
32764
  }
32567
32765
  async getDevices() {
@@ -32651,8 +32849,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32651
32849
  };
32652
32850
  }
32653
32851
  async restoreDevices(savedDevices) {
32654
- await this.onRestoreDevices(savedDevices);
32655
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
32852
+ const report = await this.onRestoreDevices(savedDevices);
32853
+ if (savedDevices.length === 0) return;
32854
+ if (report && report.failedCount > 0) {
32855
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
32856
+ return;
32857
+ }
32858
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
32859
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
32860
+ }
32861
+ /** Retry schedule. Overridable (tests use millisecond delays). */
32862
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
32863
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
32864
+ * never re-stampede full-width while the initial pass does (D167). */
32865
+ restoreRetryConcurrency = 4;
32866
+ _restoreRetryScheduler = null;
32867
+ _restoreRetryCompletion = null;
32868
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
32869
+ /** Settles when the background retry rounds finish (or `null` when
32870
+ * nothing failed). Exposed for tests and subclass diagnostics —
32871
+ * boot NEVER awaits this: the runner's post-init handshake goes out
32872
+ * with the devices that restored, and a late success is announced
32873
+ * through the `native-cap-change` → `updateCaps` path. */
32874
+ get restoreRetryCompletion() {
32875
+ return this._restoreRetryCompletion;
32876
+ }
32877
+ /** Devices that exhausted the retry bound this process lifetime. */
32878
+ get permanentRestoreFailures() {
32879
+ return [...this._permanentRestoreFailures.values()];
32880
+ }
32881
+ /** One-line operator-facing summary for `getStatus().error`, or
32882
+ * `null` when every device restored. */
32883
+ restoreFailureSummary() {
32884
+ if (this._permanentRestoreFailures.size === 0) return null;
32885
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
32886
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
32887
+ }
32888
+ cancelRestoreRetries() {
32889
+ this._restoreRetryScheduler?.cancel();
32890
+ this._restoreRetryScheduler = null;
32891
+ }
32892
+ recordPermanentRestoreFailure(failure) {
32893
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
32894
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
32895
+ tags: {
32896
+ deviceId: failure.deviceId,
32897
+ stableId: failure.stableId
32898
+ },
32899
+ meta: {
32900
+ type: failure.type,
32901
+ attempts: failure.attempts,
32902
+ error: failure.lastError
32903
+ }
32904
+ });
32905
+ }
32906
+ scheduleRestoreRetries(failures, attempt) {
32907
+ const scheduler = new DeviceRestoreRetryScheduler({
32908
+ logger: this.ctx.logger,
32909
+ delaysMs: this.restoreRetryDelaysMs,
32910
+ concurrency: this.restoreRetryConcurrency,
32911
+ attempt,
32912
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
32913
+ });
32914
+ this._restoreRetryScheduler = scheduler;
32915
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
32916
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
32917
+ });
32918
+ }
32919
+ /**
32920
+ * Tear down and reconstruct ONE device from its persisted rows — the
32921
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
32922
+ * and no other device this provider owns is disturbed.
32923
+ *
32924
+ * Keyed by `stableId` because the caller's whole reason to be here is that
32925
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
32926
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
32927
+ * whatever number the row carries NOW. The teardown is `decommission` —
32928
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
32929
+ * unregisters native caps, drops the registry entry) — and the rebuild is
32930
+ * the boot restore's own `create()` path, including its pass 2: first-class
32931
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
32932
+ * parent by the cascade and must be re-created explicitly, because only
32933
+ * accessory children come back through `getAccessoryChildren()`.
32934
+ *
32935
+ * Reloading an accessory child directly is refused (no device class) —
32936
+ * reload its parent instead.
32937
+ */
32938
+ async reloadDevice(input) {
32939
+ const { stableId } = input;
32940
+ const devices = this.ctx.kernel.devices;
32941
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
32942
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
32943
+ if (live) await devices.decommission(live.id);
32944
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
32945
+ addonId: this.addonId,
32946
+ stableId
32947
+ });
32948
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
32949
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
32950
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
32951
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
32952
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
32953
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
32954
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
32955
+ for (const row of rows) {
32956
+ if (row.parentDeviceId !== id) continue;
32957
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
32958
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
32959
+ if (!ChildClass) continue;
32960
+ try {
32961
+ await devices.create(row.stableId, ChildClass, {}, id);
32962
+ } catch (err) {
32963
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
32964
+ tags: {
32965
+ deviceId: row.id,
32966
+ stableId: row.stableId
32967
+ },
32968
+ meta: {
32969
+ parentDeviceId: id,
32970
+ error: err instanceof Error ? err.message : String(err)
32971
+ }
32972
+ });
32973
+ }
32974
+ }
32975
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
32976
+ tags: { deviceId: id },
32977
+ meta: {
32978
+ stableId,
32979
+ type: meta.type
32980
+ }
32981
+ });
32982
+ return { deviceId: id };
32656
32983
  }
32657
32984
  /**
32658
32985
  * Restore devices from persisted state. Two-pass:
@@ -32678,55 +33005,125 @@ var BaseDeviceProvider = class extends BaseAddon {
32678
33005
  * accessory-spawn flow handles via the parent's
32679
33006
  * `getAccessoryChildren()`. Override only when the default doesn't
32680
33007
  * fit.
33008
+ *
33009
+ * A row that fails either pass is NOT terminal (D347): it is handed
33010
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33011
+ * Only after the bound is exhausted is the device marked permanently
33012
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33013
+ * `getStatus().error`.
33014
+ */
33015
+ /**
33016
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33017
+ * Default: no-op — most providers have nothing to heal.
33018
+ *
33019
+ * This exists because a restored device self-hydrates from the DB: `create()`
33020
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33021
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33022
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33023
+ * been emptied failed all four bounded attempts against fields
33024
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33025
+ *
33026
+ * Implementations get every saved row, so a child can read its parent's blob.
33027
+ * A heal that throws is treated like any other restore failure: retried under
33028
+ * the bound, then reported — never swallowed.
32681
33029
  */
33030
+ async healSavedConfig(_saved, _allSaved) {}
32682
33031
  async onRestoreDevices(savedDevices) {
32683
33032
  const restored = /* @__PURE__ */ new Set();
33033
+ const failures = [];
33034
+ const attemptRestore = async (saved) => {
33035
+ if (restored.has(saved.id)) return;
33036
+ const Class = this.deviceClasses[saved.type];
33037
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33038
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33039
+ await this.healSavedConfig(saved, savedDevices);
33040
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33041
+ restored.add(saved.id);
33042
+ };
32684
33043
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32685
33044
  const restoreOne = async (saved) => {
32686
- const Class = this.deviceClasses[saved.type];
32687
- if (!Class) {
33045
+ if (!this.deviceClasses[saved.type]) {
32688
33046
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32689
- tags: { stableId: saved.stableId },
33047
+ tags: {
33048
+ deviceId: saved.id,
33049
+ stableId: saved.stableId
33050
+ },
32690
33051
  meta: { type: saved.type }
32691
33052
  });
32692
33053
  return;
32693
33054
  }
32694
33055
  try {
32695
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32696
- restored.add(saved.id);
33056
+ await attemptRestore(saved);
32697
33057
  } catch (err) {
32698
- this.ctx.logger.warn("Failed to restore device", {
32699
- tags: { stableId: saved.stableId },
33058
+ const error = err instanceof Error ? err.message : String(err);
33059
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33060
+ tags: {
33061
+ deviceId: saved.id,
33062
+ stableId: saved.stableId
33063
+ },
32700
33064
  meta: {
32701
33065
  type: saved.type,
32702
- error: err instanceof Error ? err.message : String(err)
33066
+ attempt: 1,
33067
+ error
32703
33068
  }
32704
33069
  });
33070
+ failures.push({
33071
+ saved,
33072
+ error
33073
+ });
32705
33074
  }
32706
33075
  };
32707
33076
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33077
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32708
33078
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32709
33079
  for (const saved of childRows) {
32710
- const Class = this.deviceClasses[saved.type];
32711
- if (!Class) continue;
33080
+ if (!this.deviceClasses[saved.type]) continue;
32712
33081
  if (saved.parentDeviceId === null) continue;
32713
- if (!restored.has(saved.parentDeviceId)) continue;
32714
- try {
32715
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32716
- restored.add(saved.id);
32717
- } catch (err) {
32718
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33082
+ if (restored.has(saved.parentDeviceId)) {
33083
+ try {
33084
+ await attemptRestore(saved);
33085
+ } catch (err) {
33086
+ const error = err instanceof Error ? err.message : String(err);
33087
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33088
+ tags: {
33089
+ deviceId: saved.id,
33090
+ stableId: saved.stableId,
33091
+ parentDeviceId: saved.parentDeviceId
33092
+ },
33093
+ meta: {
33094
+ type: saved.type,
33095
+ attempt: 1,
33096
+ error
33097
+ }
33098
+ });
33099
+ failures.push({
33100
+ saved,
33101
+ error
33102
+ });
33103
+ }
33104
+ continue;
33105
+ }
33106
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33107
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32719
33108
  tags: {
33109
+ deviceId: saved.id,
32720
33110
  stableId: saved.stableId,
32721
33111
  parentDeviceId: saved.parentDeviceId
32722
33112
  },
32723
- meta: {
32724
- type: saved.type,
32725
- error: err instanceof Error ? err.message : String(err)
32726
- }
33113
+ meta: { type: saved.type }
32727
33114
  });
33115
+ failures.push({
33116
+ saved,
33117
+ error: `parent device ${saved.parentDeviceId} not restored`
33118
+ });
33119
+ continue;
32728
33120
  }
32729
33121
  }
33122
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33123
+ return {
33124
+ restoredCount: restored.size,
33125
+ failedCount: failures.length
33126
+ };
32730
33127
  }
32731
33128
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32732
33129
  toSummary(device) {
@@ -34489,6 +34886,12 @@ Object.freeze({
34489
34886
  addonId: null,
34490
34887
  access: "view"
34491
34888
  },
34889
+ "deviceProvider.reloadDevice": {
34890
+ capName: "device-provider",
34891
+ capScope: "system",
34892
+ addonId: null,
34893
+ access: "create"
34894
+ },
34492
34895
  "deviceProvider.start": {
34493
34896
  capName: "device-provider",
34494
34897
  capScope: "system",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-velux",
3
- "version": "0.2.59",
3
+ "version": "0.2.61",
4
4
  "description": "Velux KLF-200 device-provider addon for CamStack — local-gateway window + shutter covers (positional, no tilt)",
5
5
  "keywords": [
6
6
  "camstack",