@camstack/addon-provider-dreo 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
@@ -12809,7 +12809,26 @@ var DiscoveryCandidateSchema = object({
12809
12809
  * identity ahead of adoption. Rendering metadata (unit, precision)
12810
12810
  * flows live through the cap STATUS SLICE after adoption.
12811
12811
  */
12812
- sourceInfo: SourceInfoSchema.optional()
12812
+ sourceInfo: SourceInfoSchema.optional(),
12813
+ /**
12814
+ * Set when this candidate is a device the provider ALREADY owns.
12815
+ *
12816
+ * A scan cannot generally produce the identity a device was onboarded under
12817
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
12818
+ * comparison never matches and an owned device looks addable. Re-adopting one
12819
+ * overwrites its config with scan-derived values — that is how a Home Hub's
12820
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
12821
+ * three child cameras offline for four hours.
12822
+ *
12823
+ * A provider that can recognise its own devices says so here. Absent means
12824
+ * "not recognised", which is not the same as "known to be new" — a provider
12825
+ * that cannot tell simply never sets it.
12826
+ */
12827
+ alreadyOnboarded: boolean().optional(),
12828
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
12829
+ onboardedDeviceId: number().optional(),
12830
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
12831
+ onboardedName: string().optional()
12813
12832
  });
12814
12833
  /**
12815
12834
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -12865,6 +12884,35 @@ var deviceProviderCapability = {
12865
12884
  name: string(),
12866
12885
  type: string()
12867
12886
  }))),
12887
+ /**
12888
+ * Tear down and reconstruct ONE device in place from its persisted rows —
12889
+ * touching no other device this provider owns.
12890
+ *
12891
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
12892
+ * migrated numbers: after `swapIds` the runner's live instance still
12893
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
12894
+ * registrations and its log tags), and a live object cannot be renumbered.
12895
+ * Before this method the only flush was restarting the whole owning addon
12896
+ * — which took every camera the provider owns down with it (28 devices
12897
+ * for one migrated camera, measured 2026-09-04, and the morning of the
12898
+ * same day ~27 devices' native caps did not come back on their own).
12899
+ *
12900
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
12901
+ * that changes. The reply carries the id the device answers on NOW.
12902
+ * Implemented once in `BaseDeviceProvider` — decommission the live
12903
+ * instance (if any), then re-create from the persisted row: the same
12904
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
12905
+ * An RPC, never an event: a dropped event would leave the runner writing
12906
+ * against the wrong camera (D8).
12907
+ *
12908
+ * Construction can dial hardware, and the migrated source is
12909
+ * characteristically dead — the timeout covers a full activate window
12910
+ * rather than the 60 s default.
12911
+ */
12912
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
12913
+ kind: "mutation",
12914
+ timeoutMs: 3 * 6e4
12915
+ }),
12868
12916
  supportsDiscovery: method(object({}), boolean()),
12869
12917
  /**
12870
12918
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13192,7 +13240,8 @@ method(object({
13192
13240
  targetId: number()
13193
13241
  }), MigrateDeviceResultSchema, {
13194
13242
  kind: "mutation",
13195
- auth: "admin"
13243
+ auth: "admin",
13244
+ timeoutMs: 12 * 6e4
13196
13245
  }), 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({
13197
13246
  deviceId: number(),
13198
13247
  name: string()
@@ -32556,6 +32605,147 @@ var BaseDevice$1 = class {
32556
32605
  }
32557
32606
  };
32558
32607
  /**
32608
+ * Delays before retry rounds 1..N — the round count IS the bound.
32609
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32610
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32611
+ * per attempt) covers a device-manager lock held for minutes — the
32612
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32613
+ */
32614
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32615
+ 1e4,
32616
+ 3e4,
32617
+ 9e4
32618
+ ];
32619
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32620
+ function sleep$1(ms, signal) {
32621
+ return new Promise((resolve) => {
32622
+ if (signal.aborted) {
32623
+ resolve();
32624
+ return;
32625
+ }
32626
+ const onAbort = () => {
32627
+ clearTimeout(timer);
32628
+ resolve();
32629
+ };
32630
+ const timer = setTimeout(() => {
32631
+ signal.removeEventListener("abort", onAbort);
32632
+ resolve();
32633
+ }, ms);
32634
+ timer.unref?.();
32635
+ signal.addEventListener("abort", onAbort, { once: true });
32636
+ });
32637
+ }
32638
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32639
+ * not reject (callers wrap their own try/catch). */
32640
+ async function runWithConcurrency(items, width, fn) {
32641
+ const queue = [...items];
32642
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32643
+ const lane = async () => {
32644
+ for (;;) {
32645
+ const item = queue.shift();
32646
+ if (item === void 0) return;
32647
+ await fn(item);
32648
+ }
32649
+ };
32650
+ await Promise.all(Array.from({ length: laneCount }, lane));
32651
+ }
32652
+ var DeviceRestoreRetryScheduler = class {
32653
+ #logger;
32654
+ #attempt;
32655
+ #onPermanentFailure;
32656
+ #delaysMs;
32657
+ #concurrency;
32658
+ #now;
32659
+ #abort = new AbortController();
32660
+ constructor(options) {
32661
+ this.#logger = options.logger;
32662
+ this.#attempt = options.attempt;
32663
+ this.#onPermanentFailure = options.onPermanentFailure;
32664
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32665
+ this.#concurrency = options.concurrency ?? 4;
32666
+ this.#now = options.now ?? Date.now;
32667
+ }
32668
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32669
+ * permanently failed — the next boot restores them from disk. */
32670
+ cancel() {
32671
+ this.#abort.abort();
32672
+ }
32673
+ /**
32674
+ * Run the bounded retry rounds. Resolves when every entry has either
32675
+ * restored, been marked permanently failed, or the scheduler was
32676
+ * cancelled. Never rejects.
32677
+ */
32678
+ async run(initialFailures) {
32679
+ let pending = initialFailures.map((failure) => ({
32680
+ saved: failure.saved,
32681
+ lastError: failure.error,
32682
+ attempts: 1
32683
+ }));
32684
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32685
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32686
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32687
+ if (this.#abort.signal.aborted) break;
32688
+ pending = await this.#runRound(pending, round);
32689
+ }
32690
+ if (this.#abort.signal.aborted) return [];
32691
+ const terminal = pending.map((entry) => ({
32692
+ deviceId: entry.saved.id,
32693
+ stableId: entry.saved.stableId,
32694
+ type: String(entry.saved.type),
32695
+ attempts: entry.attempts,
32696
+ lastError: entry.lastError,
32697
+ failedAt: this.#now()
32698
+ }));
32699
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32700
+ return terminal;
32701
+ }
32702
+ /** One retry round: parents first (phase 0), then hub-adopted
32703
+ * children (phase 1) — a child's attempt depends on its parent
32704
+ * having landed, exactly like the initial two-pass restore. */
32705
+ async #runRound(pending, round) {
32706
+ const next = [];
32707
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32708
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32709
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32710
+ if (this.#abort.signal.aborted) {
32711
+ next.push(entry);
32712
+ return;
32713
+ }
32714
+ const attemptNo = entry.attempts + 1;
32715
+ try {
32716
+ await this.#attempt(entry.saved);
32717
+ this.#logger.info("Device restored on retry", {
32718
+ tags: {
32719
+ deviceId: entry.saved.id,
32720
+ stableId: entry.saved.stableId
32721
+ },
32722
+ meta: { attempt: attemptNo }
32723
+ });
32724
+ } catch (err) {
32725
+ const lastError = err instanceof Error ? err.message : String(err);
32726
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32727
+ this.#logger.warn("Device restore retry failed", {
32728
+ tags: {
32729
+ deviceId: entry.saved.id,
32730
+ stableId: entry.saved.stableId
32731
+ },
32732
+ meta: {
32733
+ attempt: attemptNo,
32734
+ remainingRetries,
32735
+ error: lastError
32736
+ }
32737
+ });
32738
+ next.push({
32739
+ saved: entry.saved,
32740
+ lastError,
32741
+ attempts: attemptNo
32742
+ });
32743
+ }
32744
+ });
32745
+ return next;
32746
+ }
32747
+ };
32748
+ /**
32559
32749
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32560
32750
  * device-provider cap router. Shared across all providers.
32561
32751
  */
@@ -32604,6 +32794,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32604
32794
  }];
32605
32795
  }
32606
32796
  async onShutdown() {
32797
+ this.cancelRestoreRetries();
32607
32798
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32608
32799
  for (const device of devices) try {
32609
32800
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32621,9 +32812,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32621
32812
  async start() {}
32622
32813
  async stop() {}
32623
32814
  async getStatus() {
32815
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32816
+ const summary = this.restoreFailureSummary();
32817
+ if (summary === null) return {
32818
+ connected: true,
32819
+ deviceCount: all.length
32820
+ };
32624
32821
  return {
32625
32822
  connected: true,
32626
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
32823
+ deviceCount: all.length,
32824
+ error: summary
32627
32825
  };
32628
32826
  }
32629
32827
  async getDevices() {
@@ -32713,8 +32911,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32713
32911
  };
32714
32912
  }
32715
32913
  async restoreDevices(savedDevices) {
32716
- await this.onRestoreDevices(savedDevices);
32717
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
32914
+ const report = await this.onRestoreDevices(savedDevices);
32915
+ if (savedDevices.length === 0) return;
32916
+ if (report && report.failedCount > 0) {
32917
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
32918
+ return;
32919
+ }
32920
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
32921
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
32922
+ }
32923
+ /** Retry schedule. Overridable (tests use millisecond delays). */
32924
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
32925
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
32926
+ * never re-stampede full-width while the initial pass does (D167). */
32927
+ restoreRetryConcurrency = 4;
32928
+ _restoreRetryScheduler = null;
32929
+ _restoreRetryCompletion = null;
32930
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
32931
+ /** Settles when the background retry rounds finish (or `null` when
32932
+ * nothing failed). Exposed for tests and subclass diagnostics —
32933
+ * boot NEVER awaits this: the runner's post-init handshake goes out
32934
+ * with the devices that restored, and a late success is announced
32935
+ * through the `native-cap-change` → `updateCaps` path. */
32936
+ get restoreRetryCompletion() {
32937
+ return this._restoreRetryCompletion;
32938
+ }
32939
+ /** Devices that exhausted the retry bound this process lifetime. */
32940
+ get permanentRestoreFailures() {
32941
+ return [...this._permanentRestoreFailures.values()];
32942
+ }
32943
+ /** One-line operator-facing summary for `getStatus().error`, or
32944
+ * `null` when every device restored. */
32945
+ restoreFailureSummary() {
32946
+ if (this._permanentRestoreFailures.size === 0) return null;
32947
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
32948
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
32949
+ }
32950
+ cancelRestoreRetries() {
32951
+ this._restoreRetryScheduler?.cancel();
32952
+ this._restoreRetryScheduler = null;
32953
+ }
32954
+ recordPermanentRestoreFailure(failure) {
32955
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
32956
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
32957
+ tags: {
32958
+ deviceId: failure.deviceId,
32959
+ stableId: failure.stableId
32960
+ },
32961
+ meta: {
32962
+ type: failure.type,
32963
+ attempts: failure.attempts,
32964
+ error: failure.lastError
32965
+ }
32966
+ });
32967
+ }
32968
+ scheduleRestoreRetries(failures, attempt) {
32969
+ const scheduler = new DeviceRestoreRetryScheduler({
32970
+ logger: this.ctx.logger,
32971
+ delaysMs: this.restoreRetryDelaysMs,
32972
+ concurrency: this.restoreRetryConcurrency,
32973
+ attempt,
32974
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
32975
+ });
32976
+ this._restoreRetryScheduler = scheduler;
32977
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
32978
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
32979
+ });
32980
+ }
32981
+ /**
32982
+ * Tear down and reconstruct ONE device from its persisted rows — the
32983
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
32984
+ * and no other device this provider owns is disturbed.
32985
+ *
32986
+ * Keyed by `stableId` because the caller's whole reason to be here is that
32987
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
32988
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
32989
+ * whatever number the row carries NOW. The teardown is `decommission` —
32990
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
32991
+ * unregisters native caps, drops the registry entry) — and the rebuild is
32992
+ * the boot restore's own `create()` path, including its pass 2: first-class
32993
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
32994
+ * parent by the cascade and must be re-created explicitly, because only
32995
+ * accessory children come back through `getAccessoryChildren()`.
32996
+ *
32997
+ * Reloading an accessory child directly is refused (no device class) —
32998
+ * reload its parent instead.
32999
+ */
33000
+ async reloadDevice(input) {
33001
+ const { stableId } = input;
33002
+ const devices = this.ctx.kernel.devices;
33003
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33004
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33005
+ if (live) await devices.decommission(live.id);
33006
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33007
+ addonId: this.addonId,
33008
+ stableId
33009
+ });
33010
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33011
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33012
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33013
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33014
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33015
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33016
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33017
+ for (const row of rows) {
33018
+ if (row.parentDeviceId !== id) continue;
33019
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33020
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33021
+ if (!ChildClass) continue;
33022
+ try {
33023
+ await devices.create(row.stableId, ChildClass, {}, id);
33024
+ } catch (err) {
33025
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33026
+ tags: {
33027
+ deviceId: row.id,
33028
+ stableId: row.stableId
33029
+ },
33030
+ meta: {
33031
+ parentDeviceId: id,
33032
+ error: err instanceof Error ? err.message : String(err)
33033
+ }
33034
+ });
33035
+ }
33036
+ }
33037
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33038
+ tags: { deviceId: id },
33039
+ meta: {
33040
+ stableId,
33041
+ type: meta.type
33042
+ }
33043
+ });
33044
+ return { deviceId: id };
32718
33045
  }
32719
33046
  /**
32720
33047
  * Restore devices from persisted state. Two-pass:
@@ -32740,55 +33067,125 @@ var BaseDeviceProvider = class extends BaseAddon {
32740
33067
  * accessory-spawn flow handles via the parent's
32741
33068
  * `getAccessoryChildren()`. Override only when the default doesn't
32742
33069
  * fit.
33070
+ *
33071
+ * A row that fails either pass is NOT terminal (D347): it is handed
33072
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33073
+ * Only after the bound is exhausted is the device marked permanently
33074
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33075
+ * `getStatus().error`.
32743
33076
  */
33077
+ /**
33078
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33079
+ * Default: no-op — most providers have nothing to heal.
33080
+ *
33081
+ * This exists because a restored device self-hydrates from the DB: `create()`
33082
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33083
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33084
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33085
+ * been emptied failed all four bounded attempts against fields
33086
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33087
+ *
33088
+ * Implementations get every saved row, so a child can read its parent's blob.
33089
+ * A heal that throws is treated like any other restore failure: retried under
33090
+ * the bound, then reported — never swallowed.
33091
+ */
33092
+ async healSavedConfig(_saved, _allSaved) {}
32744
33093
  async onRestoreDevices(savedDevices) {
32745
33094
  const restored = /* @__PURE__ */ new Set();
33095
+ const failures = [];
33096
+ const attemptRestore = async (saved) => {
33097
+ if (restored.has(saved.id)) return;
33098
+ const Class = this.deviceClasses[saved.type];
33099
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33100
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33101
+ await this.healSavedConfig(saved, savedDevices);
33102
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33103
+ restored.add(saved.id);
33104
+ };
32746
33105
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32747
33106
  const restoreOne = async (saved) => {
32748
- const Class = this.deviceClasses[saved.type];
32749
- if (!Class) {
33107
+ if (!this.deviceClasses[saved.type]) {
32750
33108
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32751
- tags: { stableId: saved.stableId },
33109
+ tags: {
33110
+ deviceId: saved.id,
33111
+ stableId: saved.stableId
33112
+ },
32752
33113
  meta: { type: saved.type }
32753
33114
  });
32754
33115
  return;
32755
33116
  }
32756
33117
  try {
32757
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32758
- restored.add(saved.id);
33118
+ await attemptRestore(saved);
32759
33119
  } catch (err) {
32760
- this.ctx.logger.warn("Failed to restore device", {
32761
- tags: { stableId: saved.stableId },
33120
+ const error = err instanceof Error ? err.message : String(err);
33121
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33122
+ tags: {
33123
+ deviceId: saved.id,
33124
+ stableId: saved.stableId
33125
+ },
32762
33126
  meta: {
32763
33127
  type: saved.type,
32764
- error: err instanceof Error ? err.message : String(err)
33128
+ attempt: 1,
33129
+ error
32765
33130
  }
32766
33131
  });
33132
+ failures.push({
33133
+ saved,
33134
+ error
33135
+ });
32767
33136
  }
32768
33137
  };
32769
33138
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33139
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32770
33140
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32771
33141
  for (const saved of childRows) {
32772
- const Class = this.deviceClasses[saved.type];
32773
- if (!Class) continue;
33142
+ if (!this.deviceClasses[saved.type]) continue;
32774
33143
  if (saved.parentDeviceId === null) continue;
32775
- if (!restored.has(saved.parentDeviceId)) continue;
32776
- try {
32777
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32778
- restored.add(saved.id);
32779
- } catch (err) {
32780
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33144
+ if (restored.has(saved.parentDeviceId)) {
33145
+ try {
33146
+ await attemptRestore(saved);
33147
+ } catch (err) {
33148
+ const error = err instanceof Error ? err.message : String(err);
33149
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33150
+ tags: {
33151
+ deviceId: saved.id,
33152
+ stableId: saved.stableId,
33153
+ parentDeviceId: saved.parentDeviceId
33154
+ },
33155
+ meta: {
33156
+ type: saved.type,
33157
+ attempt: 1,
33158
+ error
33159
+ }
33160
+ });
33161
+ failures.push({
33162
+ saved,
33163
+ error
33164
+ });
33165
+ }
33166
+ continue;
33167
+ }
33168
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33169
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32781
33170
  tags: {
33171
+ deviceId: saved.id,
32782
33172
  stableId: saved.stableId,
32783
33173
  parentDeviceId: saved.parentDeviceId
32784
33174
  },
32785
- meta: {
32786
- type: saved.type,
32787
- error: err instanceof Error ? err.message : String(err)
32788
- }
33175
+ meta: { type: saved.type }
32789
33176
  });
33177
+ failures.push({
33178
+ saved,
33179
+ error: `parent device ${saved.parentDeviceId} not restored`
33180
+ });
33181
+ continue;
32790
33182
  }
32791
33183
  }
33184
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33185
+ return {
33186
+ restoredCount: restored.size,
33187
+ failedCount: failures.length
33188
+ };
32792
33189
  }
32793
33190
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32794
33191
  toSummary(device) {
@@ -34551,6 +34948,12 @@ Object.freeze({
34551
34948
  addonId: null,
34552
34949
  access: "view"
34553
34950
  },
34951
+ "deviceProvider.reloadDevice": {
34952
+ capName: "device-provider",
34953
+ capScope: "system",
34954
+ addonId: null,
34955
+ access: "create"
34956
+ },
34554
34957
  "deviceProvider.start": {
34555
34958
  capName: "device-provider",
34556
34959
  capScope: "system",
package/dist/addon.mjs CHANGED
@@ -12810,7 +12810,26 @@ var DiscoveryCandidateSchema = object({
12810
12810
  * identity ahead of adoption. Rendering metadata (unit, precision)
12811
12811
  * flows live through the cap STATUS SLICE after adoption.
12812
12812
  */
12813
- sourceInfo: SourceInfoSchema.optional()
12813
+ sourceInfo: SourceInfoSchema.optional(),
12814
+ /**
12815
+ * Set when this candidate is a device the provider ALREADY owns.
12816
+ *
12817
+ * A scan cannot generally produce the identity a device was onboarded under
12818
+ * (Reolink keys on `mac-<mac>`, learned at adopt time), so a stableId
12819
+ * comparison never matches and an owned device looks addable. Re-adopting one
12820
+ * overwrites its config with scan-derived values — that is how a Home Hub's
12821
+ * Baichuan port was overwritten with its ONVIF port, taking the hub and its
12822
+ * three child cameras offline for four hours.
12823
+ *
12824
+ * A provider that can recognise its own devices says so here. Absent means
12825
+ * "not recognised", which is not the same as "known to be new" — a provider
12826
+ * that cannot tell simply never sets it.
12827
+ */
12828
+ alreadyOnboarded: boolean().optional(),
12829
+ /** Numeric id of the device this candidate was matched to. Set with `alreadyOnboarded`. */
12830
+ onboardedDeviceId: number().optional(),
12831
+ /** Operator-facing name of the matched device, so the UI can say WHICH one it is. */
12832
+ onboardedName: string().optional()
12814
12833
  });
12815
12834
  /**
12816
12835
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -12866,6 +12885,35 @@ var deviceProviderCapability = {
12866
12885
  name: string(),
12867
12886
  type: string()
12868
12887
  }))),
12888
+ /**
12889
+ * Tear down and reconstruct ONE device in place from its persisted rows —
12890
+ * touching no other device this provider owns.
12891
+ *
12892
+ * The primitive `deviceManager.migrateDevice` uses to flush the two
12893
+ * migrated numbers: after `swapIds` the runner's live instance still
12894
+ * carries the PRE-swap numeric id (baked into the object, its native-cap
12895
+ * registrations and its log tags), and a live object cannot be renumbered.
12896
+ * Before this method the only flush was restarting the whole owning addon
12897
+ * — which took every camera the provider owns down with it (28 devices
12898
+ * for one migrated camera, measured 2026-09-04, and the morning of the
12899
+ * same day ~27 devices' native caps did not come back on their own).
12900
+ *
12901
+ * Keyed by `stableId`, deliberately: the numeric id is exactly the thing
12902
+ * that changes. The reply carries the id the device answers on NOW.
12903
+ * Implemented once in `BaseDeviceProvider` — decommission the live
12904
+ * instance (if any), then re-create from the persisted row: the same
12905
+ * teardown/rehydrate pair every graceful shutdown + boot already uses.
12906
+ * An RPC, never an event: a dropped event would leave the runner writing
12907
+ * against the wrong camera (D8).
12908
+ *
12909
+ * Construction can dial hardware, and the migrated source is
12910
+ * characteristically dead — the timeout covers a full activate window
12911
+ * rather than the 60 s default.
12912
+ */
12913
+ reloadDevice: method(object({ stableId: string() }), object({ deviceId: number() }), {
12914
+ kind: "mutation",
12915
+ timeoutMs: 3 * 6e4
12916
+ }),
12869
12917
  supportsDiscovery: method(object({}), boolean()),
12870
12918
  /**
12871
12919
  * Run a network scan. `params` carries optional provider-specific scan
@@ -13193,7 +13241,8 @@ method(object({
13193
13241
  targetId: number()
13194
13242
  }), MigrateDeviceResultSchema, {
13195
13243
  kind: "mutation",
13196
- auth: "admin"
13244
+ auth: "admin",
13245
+ timeoutMs: 12 * 6e4
13197
13246
  }), 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({
13198
13247
  deviceId: number(),
13199
13248
  name: string()
@@ -32557,6 +32606,147 @@ var BaseDevice$1 = class {
32557
32606
  }
32558
32607
  };
32559
32608
  /**
32609
+ * Delays before retry rounds 1..N — the round count IS the bound.
32610
+ * 10 s catches "the hub was busy for a moment"; the full schedule
32611
+ * (10 + 30 + 90 s of waiting, plus up to one 60 s transport timeout
32612
+ * per attempt) covers a device-manager lock held for minutes — the
32613
+ * 2026-09-04 outage's migration hold was ~3.5 min.
32614
+ */
32615
+ var DEVICE_RESTORE_RETRY_DELAYS_MS = [
32616
+ 1e4,
32617
+ 3e4,
32618
+ 9e4
32619
+ ];
32620
+ /** Abortable sleep — resolves early (never rejects) on abort. */
32621
+ function sleep$1(ms, signal) {
32622
+ return new Promise((resolve) => {
32623
+ if (signal.aborted) {
32624
+ resolve();
32625
+ return;
32626
+ }
32627
+ const onAbort = () => {
32628
+ clearTimeout(timer);
32629
+ resolve();
32630
+ };
32631
+ const timer = setTimeout(() => {
32632
+ signal.removeEventListener("abort", onAbort);
32633
+ resolve();
32634
+ }, ms);
32635
+ timer.unref?.();
32636
+ signal.addEventListener("abort", onAbort, { once: true });
32637
+ });
32638
+ }
32639
+ /** Drain `items` through at most `width` concurrent lanes. `fn` must
32640
+ * not reject (callers wrap their own try/catch). */
32641
+ async function runWithConcurrency(items, width, fn) {
32642
+ const queue = [...items];
32643
+ const laneCount = Math.max(1, Math.min(width, queue.length));
32644
+ const lane = async () => {
32645
+ for (;;) {
32646
+ const item = queue.shift();
32647
+ if (item === void 0) return;
32648
+ await fn(item);
32649
+ }
32650
+ };
32651
+ await Promise.all(Array.from({ length: laneCount }, lane));
32652
+ }
32653
+ var DeviceRestoreRetryScheduler = class {
32654
+ #logger;
32655
+ #attempt;
32656
+ #onPermanentFailure;
32657
+ #delaysMs;
32658
+ #concurrency;
32659
+ #now;
32660
+ #abort = new AbortController();
32661
+ constructor(options) {
32662
+ this.#logger = options.logger;
32663
+ this.#attempt = options.attempt;
32664
+ this.#onPermanentFailure = options.onPermanentFailure;
32665
+ this.#delaysMs = options.delaysMs ?? DEVICE_RESTORE_RETRY_DELAYS_MS;
32666
+ this.#concurrency = options.concurrency ?? 4;
32667
+ this.#now = options.now ?? Date.now;
32668
+ }
32669
+ /** Stop retrying (shutdown). Pending entries are NOT marked
32670
+ * permanently failed — the next boot restores them from disk. */
32671
+ cancel() {
32672
+ this.#abort.abort();
32673
+ }
32674
+ /**
32675
+ * Run the bounded retry rounds. Resolves when every entry has either
32676
+ * restored, been marked permanently failed, or the scheduler was
32677
+ * cancelled. Never rejects.
32678
+ */
32679
+ async run(initialFailures) {
32680
+ let pending = initialFailures.map((failure) => ({
32681
+ saved: failure.saved,
32682
+ lastError: failure.error,
32683
+ attempts: 1
32684
+ }));
32685
+ for (let round = 0; round < this.#delaysMs.length; round += 1) {
32686
+ if (pending.length === 0 || this.#abort.signal.aborted) break;
32687
+ await sleep$1(this.#delaysMs[round] ?? 0, this.#abort.signal);
32688
+ if (this.#abort.signal.aborted) break;
32689
+ pending = await this.#runRound(pending, round);
32690
+ }
32691
+ if (this.#abort.signal.aborted) return [];
32692
+ const terminal = pending.map((entry) => ({
32693
+ deviceId: entry.saved.id,
32694
+ stableId: entry.saved.stableId,
32695
+ type: String(entry.saved.type),
32696
+ attempts: entry.attempts,
32697
+ lastError: entry.lastError,
32698
+ failedAt: this.#now()
32699
+ }));
32700
+ for (const failure of terminal) this.#onPermanentFailure(failure);
32701
+ return terminal;
32702
+ }
32703
+ /** One retry round: parents first (phase 0), then hub-adopted
32704
+ * children (phase 1) — a child's attempt depends on its parent
32705
+ * having landed, exactly like the initial two-pass restore. */
32706
+ async #runRound(pending, round) {
32707
+ const next = [];
32708
+ const parents = pending.filter((entry) => entry.saved.parentDeviceId === null);
32709
+ const children = pending.filter((entry) => entry.saved.parentDeviceId !== null);
32710
+ for (const phase of [parents, children]) await runWithConcurrency(phase, this.#concurrency, async (entry) => {
32711
+ if (this.#abort.signal.aborted) {
32712
+ next.push(entry);
32713
+ return;
32714
+ }
32715
+ const attemptNo = entry.attempts + 1;
32716
+ try {
32717
+ await this.#attempt(entry.saved);
32718
+ this.#logger.info("Device restored on retry", {
32719
+ tags: {
32720
+ deviceId: entry.saved.id,
32721
+ stableId: entry.saved.stableId
32722
+ },
32723
+ meta: { attempt: attemptNo }
32724
+ });
32725
+ } catch (err) {
32726
+ const lastError = err instanceof Error ? err.message : String(err);
32727
+ const remainingRetries = this.#delaysMs.length - (round + 1);
32728
+ this.#logger.warn("Device restore retry failed", {
32729
+ tags: {
32730
+ deviceId: entry.saved.id,
32731
+ stableId: entry.saved.stableId
32732
+ },
32733
+ meta: {
32734
+ attempt: attemptNo,
32735
+ remainingRetries,
32736
+ error: lastError
32737
+ }
32738
+ });
32739
+ next.push({
32740
+ saved: entry.saved,
32741
+ lastError,
32742
+ attempts: attemptNo
32743
+ });
32744
+ }
32745
+ });
32746
+ return next;
32747
+ }
32748
+ };
32749
+ /**
32560
32750
  * Convert an IDevice to the flat DeviceSummary shape expected by the
32561
32751
  * device-provider cap router. Shared across all providers.
32562
32752
  */
@@ -32605,6 +32795,7 @@ var BaseDeviceProvider = class extends BaseAddon {
32605
32795
  }];
32606
32796
  }
32607
32797
  async onShutdown() {
32798
+ this.cancelRestoreRetries();
32608
32799
  const devices = await this.ctx.kernel.devices?.getAll() ?? [];
32609
32800
  for (const device of devices) try {
32610
32801
  await this.ctx.kernel.devices?.decommission(device.id);
@@ -32622,9 +32813,16 @@ var BaseDeviceProvider = class extends BaseAddon {
32622
32813
  async start() {}
32623
32814
  async stop() {}
32624
32815
  async getStatus() {
32816
+ const all = await this.ctx.kernel.devices?.getAll() ?? [];
32817
+ const summary = this.restoreFailureSummary();
32818
+ if (summary === null) return {
32819
+ connected: true,
32820
+ deviceCount: all.length
32821
+ };
32625
32822
  return {
32626
32823
  connected: true,
32627
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
32824
+ deviceCount: all.length,
32825
+ error: summary
32628
32826
  };
32629
32827
  }
32630
32828
  async getDevices() {
@@ -32714,8 +32912,137 @@ var BaseDeviceProvider = class extends BaseAddon {
32714
32912
  };
32715
32913
  }
32716
32914
  async restoreDevices(savedDevices) {
32717
- await this.onRestoreDevices(savedDevices);
32718
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
32915
+ const report = await this.onRestoreDevices(savedDevices);
32916
+ if (savedDevices.length === 0) return;
32917
+ if (report && report.failedCount > 0) {
32918
+ this.ctx.logger.warn(`Restored ${report.restoredCount}/${savedDevices.length} ${this.providerName} device(s) — ${report.failedCount} failed, bounded retry scheduled`);
32919
+ return;
32920
+ }
32921
+ const restoredCount = report ? report.restoredCount : savedDevices.length;
32922
+ this.ctx.logger.info(`Restored ${restoredCount} ${this.providerName} device(s)`);
32923
+ }
32924
+ /** Retry schedule. Overridable (tests use millisecond delays). */
32925
+ restoreRetryDelaysMs = DEVICE_RESTORE_RETRY_DELAYS_MS;
32926
+ /** Retry lane width. See `device-restore-retry.ts` for why retries
32927
+ * never re-stampede full-width while the initial pass does (D167). */
32928
+ restoreRetryConcurrency = 4;
32929
+ _restoreRetryScheduler = null;
32930
+ _restoreRetryCompletion = null;
32931
+ _permanentRestoreFailures = /* @__PURE__ */ new Map();
32932
+ /** Settles when the background retry rounds finish (or `null` when
32933
+ * nothing failed). Exposed for tests and subclass diagnostics —
32934
+ * boot NEVER awaits this: the runner's post-init handshake goes out
32935
+ * with the devices that restored, and a late success is announced
32936
+ * through the `native-cap-change` → `updateCaps` path. */
32937
+ get restoreRetryCompletion() {
32938
+ return this._restoreRetryCompletion;
32939
+ }
32940
+ /** Devices that exhausted the retry bound this process lifetime. */
32941
+ get permanentRestoreFailures() {
32942
+ return [...this._permanentRestoreFailures.values()];
32943
+ }
32944
+ /** One-line operator-facing summary for `getStatus().error`, or
32945
+ * `null` when every device restored. */
32946
+ restoreFailureSummary() {
32947
+ if (this._permanentRestoreFailures.size === 0) return null;
32948
+ const ids = [...this._permanentRestoreFailures.keys()].join(", ");
32949
+ return `${this._permanentRestoreFailures.size} device(s) permanently failed restore (deviceIds: ${ids}) — restart the ${this.providerName} provider to retry`;
32950
+ }
32951
+ cancelRestoreRetries() {
32952
+ this._restoreRetryScheduler?.cancel();
32953
+ this._restoreRetryScheduler = null;
32954
+ }
32955
+ recordPermanentRestoreFailure(failure) {
32956
+ this._permanentRestoreFailures.set(failure.deviceId, failure);
32957
+ this.ctx.logger.error("Device restore permanently failed — its capabilities will not register until the provider restarts", {
32958
+ tags: {
32959
+ deviceId: failure.deviceId,
32960
+ stableId: failure.stableId
32961
+ },
32962
+ meta: {
32963
+ type: failure.type,
32964
+ attempts: failure.attempts,
32965
+ error: failure.lastError
32966
+ }
32967
+ });
32968
+ }
32969
+ scheduleRestoreRetries(failures, attempt) {
32970
+ const scheduler = new DeviceRestoreRetryScheduler({
32971
+ logger: this.ctx.logger,
32972
+ delaysMs: this.restoreRetryDelaysMs,
32973
+ concurrency: this.restoreRetryConcurrency,
32974
+ attempt,
32975
+ onPermanentFailure: (failure) => this.recordPermanentRestoreFailure(failure)
32976
+ });
32977
+ this._restoreRetryScheduler = scheduler;
32978
+ this._restoreRetryCompletion = scheduler.run(failures).then(() => void 0).catch((err) => {
32979
+ this.ctx.logger.error("Restore retry scheduler crashed", { meta: { error: err instanceof Error ? err.message : String(err) } });
32980
+ });
32981
+ }
32982
+ /**
32983
+ * Tear down and reconstruct ONE device from its persisted rows — the
32984
+ * `deviceProvider.reloadDevice` cap method. Persistence is never touched,
32985
+ * and no other device this provider owns is disturbed.
32986
+ *
32987
+ * Keyed by `stableId` because the caller's whole reason to be here is that
32988
+ * the NUMERIC id changed (`deviceManager.migrateDevice` swapped it): the
32989
+ * fresh instance resolves its id through `allocateDeviceId`, which returns
32990
+ * whatever number the row carries NOW. The teardown is `decommission` —
32991
+ * exactly what a graceful shutdown runs per device (fires `removeDevice()`,
32992
+ * unregisters native caps, drops the registry entry) — and the rebuild is
32993
+ * the boot restore's own `create()` path, including its pass 2: first-class
32994
+ * children (hub-adopted cameras under an NVR) are decommissioned with the
32995
+ * parent by the cascade and must be re-created explicitly, because only
32996
+ * accessory children come back through `getAccessoryChildren()`.
32997
+ *
32998
+ * Reloading an accessory child directly is refused (no device class) —
32999
+ * reload its parent instead.
33000
+ */
33001
+ async reloadDevice(input) {
33002
+ const { stableId } = input;
33003
+ const devices = this.ctx.kernel.devices;
33004
+ if (!devices) throw new Error(`${this.providerName}: kernel.devices unavailable — cannot reload`);
33005
+ const live = (await devices.getAll()).find((d) => d.stableId === stableId);
33006
+ if (live) await devices.decommission(live.id);
33007
+ const { id } = await this.ctx.api.deviceManager.allocateDeviceId.mutate({
33008
+ addonId: this.addonId,
33009
+ stableId
33010
+ });
33011
+ const meta = await this.ctx.api.deviceManager.loadMeta.query({ deviceId: id });
33012
+ if (meta === null) throw new Error(`${this.providerName}: no persisted meta for "${stableId}" (id ${id}) — cannot reload`);
33013
+ const deviceType = Object.values(DeviceType).find((t) => t === meta.type);
33014
+ const Class = deviceType !== void 0 ? this.deviceClasses[deviceType] : void 0;
33015
+ if (!Class) throw new Error(`${this.providerName}: no device class for type "${meta.type}" — "${stableId}" is an accessory child; reload its parent instead`);
33016
+ await devices.create(stableId, Class, {}, meta.parentDeviceId ?? null);
33017
+ const rows = await this.ctx.api.deviceManager.listPersistedByAddon.query({ addonId: this.addonId });
33018
+ for (const row of rows) {
33019
+ if (row.parentDeviceId !== id) continue;
33020
+ const childType = Object.values(DeviceType).find((t) => t === row.type);
33021
+ const ChildClass = childType !== void 0 ? this.deviceClasses[childType] : void 0;
33022
+ if (!ChildClass) continue;
33023
+ try {
33024
+ await devices.create(row.stableId, ChildClass, {}, id);
33025
+ } catch (err) {
33026
+ this.ctx.logger.warn("reloadDevice: failed to re-create first-class child", {
33027
+ tags: {
33028
+ deviceId: row.id,
33029
+ stableId: row.stableId
33030
+ },
33031
+ meta: {
33032
+ parentDeviceId: id,
33033
+ error: err instanceof Error ? err.message : String(err)
33034
+ }
33035
+ });
33036
+ }
33037
+ }
33038
+ this.ctx.logger.info("device reloaded in place from persisted rows", {
33039
+ tags: { deviceId: id },
33040
+ meta: {
33041
+ stableId,
33042
+ type: meta.type
33043
+ }
33044
+ });
33045
+ return { deviceId: id };
32719
33046
  }
32720
33047
  /**
32721
33048
  * Restore devices from persisted state. Two-pass:
@@ -32741,55 +33068,125 @@ var BaseDeviceProvider = class extends BaseAddon {
32741
33068
  * accessory-spawn flow handles via the parent's
32742
33069
  * `getAccessoryChildren()`. Override only when the default doesn't
32743
33070
  * fit.
33071
+ *
33072
+ * A row that fails either pass is NOT terminal (D347): it is handed
33073
+ * to a bounded background retry (`DeviceRestoreRetryScheduler`).
33074
+ * Only after the bound is exhausted is the device marked permanently
33075
+ * failed — logged at ERROR with `tags.deviceId` and surfaced via
33076
+ * `getStatus().error`.
32744
33077
  */
33078
+ /**
33079
+ * Repair a row's PERSISTED config blob immediately before it is restored.
33080
+ * Default: no-op — most providers have nothing to heal.
33081
+ *
33082
+ * This exists because a restored device self-hydrates from the DB: `create()`
33083
+ * passes `{}` and `BaseDevice` parses the stored blob against the device
33084
+ * schema. A blob that lost a REQUIRED field therefore fails restore forever,
33085
+ * and no later pass revisits it — a hub-adopted Reolink camera whose blob had
33086
+ * been emptied failed all four bounded attempts against fields
33087
+ * (`host`, `password`) it inherits from its parent and never dials itself.
33088
+ *
33089
+ * Implementations get every saved row, so a child can read its parent's blob.
33090
+ * A heal that throws is treated like any other restore failure: retried under
33091
+ * the bound, then reported — never swallowed.
33092
+ */
33093
+ async healSavedConfig(_saved, _allSaved) {}
32745
33094
  async onRestoreDevices(savedDevices) {
32746
33095
  const restored = /* @__PURE__ */ new Set();
33096
+ const failures = [];
33097
+ const attemptRestore = async (saved) => {
33098
+ if (restored.has(saved.id)) return;
33099
+ const Class = this.deviceClasses[saved.type];
33100
+ if (!Class) throw new Error(`no device class registered for type "${saved.type}"`);
33101
+ if (saved.parentDeviceId !== null && !restored.has(saved.parentDeviceId)) throw new Error(`parent device ${saved.parentDeviceId} not restored`);
33102
+ await this.healSavedConfig(saved, savedDevices);
33103
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
33104
+ restored.add(saved.id);
33105
+ };
32747
33106
  const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
32748
33107
  const restoreOne = async (saved) => {
32749
- const Class = this.deviceClasses[saved.type];
32750
- if (!Class) {
33108
+ if (!this.deviceClasses[saved.type]) {
32751
33109
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
32752
- tags: { stableId: saved.stableId },
33110
+ tags: {
33111
+ deviceId: saved.id,
33112
+ stableId: saved.stableId
33113
+ },
32753
33114
  meta: { type: saved.type }
32754
33115
  });
32755
33116
  return;
32756
33117
  }
32757
33118
  try {
32758
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
32759
- restored.add(saved.id);
33119
+ await attemptRestore(saved);
32760
33120
  } catch (err) {
32761
- this.ctx.logger.warn("Failed to restore device", {
32762
- tags: { stableId: saved.stableId },
33121
+ const error = err instanceof Error ? err.message : String(err);
33122
+ this.ctx.logger.warn("Failed to restore device — bounded retry scheduled", {
33123
+ tags: {
33124
+ deviceId: saved.id,
33125
+ stableId: saved.stableId
33126
+ },
32763
33127
  meta: {
32764
33128
  type: saved.type,
32765
- error: err instanceof Error ? err.message : String(err)
33129
+ attempt: 1,
33130
+ error
32766
33131
  }
32767
33132
  });
33133
+ failures.push({
33134
+ saved,
33135
+ error
33136
+ });
32768
33137
  }
32769
33138
  };
32770
33139
  await Promise.all(topLevel.map((saved) => restoreOne(saved)));
33140
+ const failedTopLevelIds = new Set(failures.map((failure) => failure.saved.id));
32771
33141
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
32772
33142
  for (const saved of childRows) {
32773
- const Class = this.deviceClasses[saved.type];
32774
- if (!Class) continue;
33143
+ if (!this.deviceClasses[saved.type]) continue;
32775
33144
  if (saved.parentDeviceId === null) continue;
32776
- if (!restored.has(saved.parentDeviceId)) continue;
32777
- try {
32778
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
32779
- restored.add(saved.id);
32780
- } catch (err) {
32781
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
33145
+ if (restored.has(saved.parentDeviceId)) {
33146
+ try {
33147
+ await attemptRestore(saved);
33148
+ } catch (err) {
33149
+ const error = err instanceof Error ? err.message : String(err);
33150
+ this.ctx.logger.warn("Failed to restore hub-adopted child — bounded retry scheduled", {
33151
+ tags: {
33152
+ deviceId: saved.id,
33153
+ stableId: saved.stableId,
33154
+ parentDeviceId: saved.parentDeviceId
33155
+ },
33156
+ meta: {
33157
+ type: saved.type,
33158
+ attempt: 1,
33159
+ error
33160
+ }
33161
+ });
33162
+ failures.push({
33163
+ saved,
33164
+ error
33165
+ });
33166
+ }
33167
+ continue;
33168
+ }
33169
+ if (failedTopLevelIds.has(saved.parentDeviceId)) {
33170
+ this.ctx.logger.warn("Hub-adopted child deferred — parent failed initial restore", {
32782
33171
  tags: {
33172
+ deviceId: saved.id,
32783
33173
  stableId: saved.stableId,
32784
33174
  parentDeviceId: saved.parentDeviceId
32785
33175
  },
32786
- meta: {
32787
- type: saved.type,
32788
- error: err instanceof Error ? err.message : String(err)
32789
- }
33176
+ meta: { type: saved.type }
32790
33177
  });
33178
+ failures.push({
33179
+ saved,
33180
+ error: `parent device ${saved.parentDeviceId} not restored`
33181
+ });
33182
+ continue;
32791
33183
  }
32792
33184
  }
33185
+ if (failures.length > 0) this.scheduleRestoreRetries(failures, attemptRestore);
33186
+ return {
33187
+ restoredCount: restored.size,
33188
+ failedCount: failures.length
33189
+ };
32793
33190
  }
32794
33191
  /** Convert an IDevice to the flat DeviceSummary for the cap router. */
32795
33192
  toSummary(device) {
@@ -34552,6 +34949,12 @@ Object.freeze({
34552
34949
  addonId: null,
34553
34950
  access: "view"
34554
34951
  },
34952
+ "deviceProvider.reloadDevice": {
34953
+ capName: "device-provider",
34954
+ capScope: "system",
34955
+ addonId: null,
34956
+ access: "create"
34957
+ },
34555
34958
  "deviceProvider.start": {
34556
34959
  capName: "device-provider",
34557
34960
  capScope: "system",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-dreo",
3
- "version": "0.2.59",
3
+ "version": "0.2.61",
4
4
  "description": "Dreo smart-device (fan / air-circulator / purifier / heater / humidifier) device-provider addon for CamStack — wraps the @apocaliss92/nodedreo Dreo cloud client (REST + WebSocket)",
5
5
  "keywords": [
6
6
  "camstack",