@camstack/addon-provider-gree 0.2.58 → 0.2.60

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