@onekeyfe/hd-transport-web-device 1.2.11-alpha.16 → 1.2.11-alpha.18

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.
@@ -1534,7 +1534,8 @@ describe('ElectronBleTransport protocol detection', () => {
1534
1534
  'Initialize',
1535
1535
  {},
1536
1536
  { timeoutMs: 3000 },
1537
- { oneShot: true }
1537
+ { oneShot: true },
1538
+ true
1538
1539
  );
1539
1540
  });
1540
1541
 
@@ -1644,4 +1645,165 @@ describe('ElectronBleTransport protocol detection', () => {
1644
1645
  });
1645
1646
  expect(callProtocolV1).not.toHaveBeenCalled();
1646
1647
  });
1648
+
1649
+ test('does not send Initialize wake when GetFeatures fails from an ordinary GATT write error', async () => {
1650
+ const device = { id: 'gatt-write-err-classic-id', name: 'K8141' };
1651
+ const nobleBle = createNobleBle(device);
1652
+ const bleTransport = configureTransport(nobleBle);
1653
+ const probes = bleTransport as any;
1654
+ const wakeSpy = jest.spyOn(probes, 'wakeSilentProtocolV1Device');
1655
+ jest.spyOn(probes, 'probeProtocolV2').mockResolvedValue(false);
1656
+ nobleBle.write.mockRejectedValueOnce(new Error('GATT write error'));
1657
+
1658
+ await expect(bleTransport.acquire({ uuid: device.id })).rejects.toMatchObject({
1659
+ errorCode: HardwareErrorCode.TransportProtocolProbeFailed,
1660
+ });
1661
+ expect(wakeSpy).not.toHaveBeenCalled();
1662
+ });
1663
+
1664
+ test('prevents a canceled acquire whose getDevice settles late from disconnecting a replacement acquire', async () => {
1665
+ const device = { id: 'superseded-acquire-id', name: 'K8141' };
1666
+ const nobleBle = createNobleBle(device);
1667
+ let resolveFirstGetDevice: ((d: typeof device) => void) | undefined;
1668
+ nobleBle.getDevice
1669
+ .mockImplementationOnce(
1670
+ () =>
1671
+ new Promise(resolve => {
1672
+ resolveFirstGetDevice = resolve;
1673
+ })
1674
+ )
1675
+ .mockResolvedValue(device);
1676
+ const bleTransport = configureTransport(nobleBle);
1677
+ const abortA = new AbortController();
1678
+
1679
+ const acquireA = bleTransport.acquire({
1680
+ uuid: device.id,
1681
+ expectedProtocol: 'V1',
1682
+ abortSignal: abortA.signal,
1683
+ });
1684
+ abortA.abort();
1685
+
1686
+ // Acquire B succeeds while acquire A is still waiting on getDevice.
1687
+ await expect(
1688
+ bleTransport.acquire({ uuid: device.id, expectedProtocol: 'V1' })
1689
+ ).resolves.toMatchObject({ uuid: device.id, protocolType: 'V1' });
1690
+ nobleBle.disconnect.mockClear();
1691
+ nobleBle.unsubscribe.mockClear();
1692
+
1693
+ // Acquire A resumes when its delayed lookup settles; it must not tear down B's link.
1694
+ resolveFirstGetDevice?.(device);
1695
+ await expect(acquireA).rejects.toMatchObject({
1696
+ errorCode: HardwareErrorCode.DeviceInterruptedFromUser,
1697
+ });
1698
+ expect(nobleBle.unsubscribe).not.toHaveBeenCalled();
1699
+ expect(nobleBle.disconnect).not.toHaveBeenCalled();
1700
+ expect(bleTransport.getProtocolType(device.id)).toBe('V1');
1701
+ });
1702
+
1703
+ test('restores wake eligibility when Windows rejects the Initialize wake write with writeRejected', async () => {
1704
+ const device = { id: 'win-wake-reject-id', name: 'K8141' };
1705
+ const nobleBle = createNobleBle(device);
1706
+ const bleTransport = configureTransport(nobleBle);
1707
+ const probes = bleTransport as any;
1708
+ jest.spyOn(probes, 'probeProtocolV1').mockResolvedValue(false);
1709
+ jest.spyOn(probes, 'probeProtocolV2').mockResolvedValue(false);
1710
+
1711
+ nobleBle.write.mockRejectedValueOnce(
1712
+ ERRORS.TypedError(
1713
+ HardwareErrorCode.BleConnectedError,
1714
+ 'Write failed with abortable error for device win-wake-reject-id: status: 3',
1715
+ { writeRejected: true }
1716
+ )
1717
+ );
1718
+ await expect(bleTransport.acquire({ uuid: device.id })).rejects.toMatchObject({
1719
+ errorCode: HardwareErrorCode.BleConnectedError,
1720
+ });
1721
+
1722
+ // After pairing succeeds on the next acquire, Initialize wake must still run.
1723
+ const callProtocolV1 = jest.spyOn(probes, 'callProtocolV1').mockResolvedValueOnce({
1724
+ type: 'Features',
1725
+ message: {},
1726
+ });
1727
+ await expect(bleTransport.acquire({ uuid: device.id })).resolves.toMatchObject({
1728
+ uuid: device.id,
1729
+ protocolType: 'V1',
1730
+ });
1731
+ expect(callProtocolV1).toHaveBeenCalledTimes(1);
1732
+ expect(callProtocolV1.mock.calls[0]?.[1]).toBe('Initialize');
1733
+ });
1734
+
1735
+ test('disconnects an ordinary 3000ms Initialize call on timeout instead of treating it as a probe', async () => {
1736
+ const device = { id: 'ordinary-init-3s-id', name: 'OneKey Classic' };
1737
+ const nobleBle = createNobleBle(device);
1738
+ nobleBle.onNotification.mockImplementation(() => jest.fn());
1739
+ nobleBle.write.mockImplementation(() => Promise.resolve());
1740
+ const bleTransport = configureTransport(nobleBle);
1741
+
1742
+ await bleTransport.acquire({ uuid: device.id, expectedProtocol: 'V1' });
1743
+ jest.useFakeTimers({ doNotFake: ['performance'] });
1744
+ try {
1745
+ const pending = bleTransport.call(device.id, 'Initialize', {}, { timeoutMs: 3000 });
1746
+ const expectation = expect(pending).rejects.toMatchObject({
1747
+ errorCode: HardwareErrorCode.BleTimeoutError,
1748
+ });
1749
+ await Promise.resolve();
1750
+ await Promise.resolve();
1751
+ jest.advanceTimersByTime(3000);
1752
+ await expectation;
1753
+ } finally {
1754
+ jest.useRealTimers();
1755
+ }
1756
+
1757
+ expect(nobleBle.disconnect).toHaveBeenCalledWith(device.id);
1758
+ expect(bleTransport.getProtocolType(device.id)).toBeUndefined();
1759
+ });
1760
+
1761
+ test('uses the post-connect device name for Electron legacy V1 wake when initial lookup has a placeholder name', async () => {
1762
+ const placeholder = { id: 'cold-classic-id', name: 'OneKey Device' };
1763
+ const connected = { id: 'cold-classic-id', name: 'K8141', mtu: 247 };
1764
+ const nobleBle = createNobleBle(placeholder);
1765
+ nobleBle.getDevice.mockResolvedValueOnce(placeholder).mockResolvedValueOnce(connected);
1766
+ const bleTransport = configureTransport(nobleBle);
1767
+ const probes = bleTransport as any;
1768
+ jest.spyOn(probes, 'probeProtocolV1').mockResolvedValue(false);
1769
+ const probeProtocolV2 = jest.spyOn(probes, 'probeProtocolV2').mockResolvedValue(false);
1770
+ const callProtocolV1 = jest.spyOn(probes, 'callProtocolV1').mockResolvedValue({
1771
+ type: 'Features',
1772
+ message: {},
1773
+ });
1774
+
1775
+ await expect(bleTransport.acquire({ uuid: placeholder.id })).resolves.toMatchObject({
1776
+ uuid: placeholder.id,
1777
+ name: 'K8141',
1778
+ protocolType: 'V1',
1779
+ });
1780
+ expect(callProtocolV1).toHaveBeenCalledTimes(1);
1781
+ expect(callProtocolV1.mock.calls[0]?.[1]).toBe('Initialize');
1782
+ expect(probeProtocolV2).not.toHaveBeenCalled();
1783
+ });
1784
+
1785
+ test('rejects an already-aborted acquire without releasing an existing Electron BLE link', async () => {
1786
+ const device = { id: 'existing-link-id', name: 'OneKey Classic' };
1787
+ const nobleBle = createNobleBle(device);
1788
+ const bleTransport = configureTransport(nobleBle);
1789
+ await bleTransport.acquire({ uuid: device.id, expectedProtocol: 'V1' });
1790
+
1791
+ const aborted = new AbortController();
1792
+ aborted.abort();
1793
+ const releaseSpy = jest.spyOn(bleTransport, 'release');
1794
+ nobleBle.disconnect.mockClear();
1795
+
1796
+ await expect(
1797
+ bleTransport.acquire({
1798
+ uuid: device.id,
1799
+ expectedProtocol: 'V1',
1800
+ abortSignal: aborted.signal,
1801
+ })
1802
+ ).rejects.toMatchObject({
1803
+ errorCode: HardwareErrorCode.DeviceInterruptedFromUser,
1804
+ });
1805
+ expect(releaseSpy).not.toHaveBeenCalled();
1806
+ expect(nobleBle.disconnect).not.toHaveBeenCalled();
1807
+ expect(bleTransport.getProtocolType(device.id)).toBe('V1');
1808
+ });
1647
1809
  });
@@ -35,6 +35,10 @@ export default class ElectronBleTransport {
35
35
  private deviceProtocol;
36
36
  private deviceProtocolHints;
37
37
  private silentDetections;
38
+ private probeResponseTimeoutErrors;
39
+ private lastV1ProbeFailedWithoutTimeout;
40
+ private acquireGenerations;
41
+ private nextAcquireGeneration;
38
42
  private deviceMtus;
39
43
  private devicePacketCapacities;
40
44
  private v1Buffers;
@@ -1 +1 @@
1
- {"version":3,"file":"electron-ble-transport.d.ts","sourceRoot":"","sources":["../src/electron-ble-transport.ts"],"names":[],"mappings":";AA0BA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EACV,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAEV,gBAAgB,EAChB,YAAY,EAEZ,oBAAoB,EACrB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,YAAY,MAAM,QAAQ,CAAC;AAIvC,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,UAAU,CAAC,EAAE,UAAU,CAAC;KACzB;CACF;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,gBAAgB,CAAC,EAAE,YAAY,CAAC;IAChC,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B,CAAC;AAoFF,MAAM,CAAC,OAAO,OAAO,oBAAoB;IACvC,OAAO,CAAC,SAAS,CAAmE;IAEpF,OAAO,CAAC,WAAW,CAAmE;IAEtF,OAAO,CAAC,6BAA6B,CAAqB;IAE1D,IAAI,SAA0B;IAE9B,UAAU,UAAS;IAEnB,UAAU,EAAE,QAAQ,CAAC,UAAU,GAAG,MAAM,CAAC,GAAG,IAAI,CAAQ;IAExD,OAAO,CAAC,kBAAkB,CAAuB;IAEjD,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV,OAAO,CAAC,EAAE,YAAY,CAAC;IAEvB,OAAO,CAAC,gBAAgB,CAA0B;IAElD,OAAO,CAAC,eAAe,CAA0B;IAEjD,OAAO,CAAC,oBAAoB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AiC;YAwBjC,eAAe;YAkCf,eAAe;YAyBf,SAAS;YAeT,wBAAwB;IAOtC,OAAO,CAAC,uBAAuB;IAc/B,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,oBAAoB;IAqB5B,OAAO,CAAC,kBAAkB;IA+B1B,OAAO,CAAC,iCAAiC;IAazC,OAAO,CAAC,4BAA4B;IAkBpC,OAAO,CAAC,uBAAuB;IAS/B,OAAO,CAAC,sBAAsB;IAU9B,OAAO,CAAC,qBAAqB;IAI7B,OAAO,CAAC,sBAAsB;YAShB,mBAAmB;IAiBjC,OAAO,CAAC,4BAA4B;IAqB9B,IAAI,CACR,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,oBAAoB;IAuB1B,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;YAatD,cAAc;YA+Fd,cAAc;IA+B5B,OAAO,CAAC,uBAAuB;IAyC/B,OAAO,CAAC,6BAA6B;IA4CrC,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;CAGxD"}
package/dist/index.d.ts CHANGED
@@ -272,6 +272,10 @@ declare class ElectronBleTransport {
272
272
  private deviceProtocol;
273
273
  private deviceProtocolHints;
274
274
  private silentDetections;
275
+ private probeResponseTimeoutErrors;
276
+ private lastV1ProbeFailedWithoutTimeout;
277
+ private acquireGenerations;
278
+ private nextAcquireGeneration;
275
279
  private deviceMtus;
276
280
  private devicePacketCapacities;
277
281
  private v1Buffers;
package/dist/index.js CHANGED
@@ -1543,8 +1543,11 @@ const shouldRethrowElectronProtocolProbeError = (error) => {
1543
1543
  code === hdShared.HardwareErrorCode.BleLocationError);
1544
1544
  };
1545
1545
  const isUnstartedElectronWakeError = (error) => {
1546
- const code = error === null || error === void 0 ? void 0 : error.errorCode;
1547
- return (code === hdShared.HardwareErrorCode.BleCharacteristicNotFound ||
1546
+ var _a;
1547
+ const candidate = error;
1548
+ const code = candidate === null || candidate === void 0 ? void 0 : candidate.errorCode;
1549
+ return (((_a = candidate === null || candidate === void 0 ? void 0 : candidate.params) === null || _a === void 0 ? void 0 : _a.writeRejected) === true ||
1550
+ code === hdShared.HardwareErrorCode.BleCharacteristicNotFound ||
1548
1551
  code === hdShared.HardwareErrorCode.BlePoweredOff ||
1549
1552
  code === hdShared.HardwareErrorCode.BleUnsupported ||
1550
1553
  code === hdShared.HardwareErrorCode.BleLocationError);
@@ -1563,6 +1566,10 @@ class ElectronBleTransport {
1563
1566
  this.deviceProtocol = new Map();
1564
1567
  this.deviceProtocolHints = new Map();
1565
1568
  this.silentDetections = new Map();
1569
+ this.probeResponseTimeoutErrors = new WeakSet();
1570
+ this.lastV1ProbeFailedWithoutTimeout = new Set();
1571
+ this.acquireGenerations = new Map();
1572
+ this.nextAcquireGeneration = 1;
1566
1573
  this.deviceMtus = new Map();
1567
1574
  this.devicePacketCapacities = new Map();
1568
1575
  this.v1Buffers = new Map();
@@ -1645,6 +1652,7 @@ class ElectronBleTransport {
1645
1652
  this.devicePacketCapacities.delete(deviceId);
1646
1653
  this.v1Buffers.delete(deviceId);
1647
1654
  this.v2Assemblers.delete(deviceId);
1655
+ this.lastV1ProbeFailedWithoutTimeout.delete(deviceId);
1648
1656
  this.resetProtocolV2Frames(deviceId);
1649
1657
  this.notificationTokens.delete(deviceId);
1650
1658
  if (this.runPromise && this.runPromiseDeviceId === deviceId) {
@@ -1704,6 +1712,8 @@ class ElectronBleTransport {
1704
1712
  ]);
1705
1713
  yield Promise.all(Array.from(trackedDeviceIds, deviceId => this.releaseNative(deviceId)));
1706
1714
  this.acquiringDevices.clear();
1715
+ this.acquireGenerations.clear();
1716
+ this.lastV1ProbeFailedWithoutTimeout.clear();
1707
1717
  this.protocolV2CallCounts.clear();
1708
1718
  this.silentDetections.clear();
1709
1719
  yield this.protocolV2Links
@@ -1772,12 +1782,26 @@ class ElectronBleTransport {
1772
1782
  });
1773
1783
  }
1774
1784
  acquire(input) {
1775
- var _a, _b, _c, _d, _e, _f, _g;
1785
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1776
1786
  return __awaiter(this, void 0, void 0, function* () {
1777
1787
  const { uuid, forceCleanRunPromise, expectedProtocol, forceProtocolDetection } = input;
1778
1788
  if (!uuid) {
1779
1789
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleRequiredUUID);
1780
1790
  }
1791
+ if ((_a = input.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
1792
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
1793
+ }
1794
+ const acquireGeneration = this.nextAcquireGeneration;
1795
+ this.nextAcquireGeneration += 1;
1796
+ this.acquireGenerations.set(uuid, acquireGeneration);
1797
+ const isCurrentAcquire = () => this.acquireGenerations.get(uuid) === acquireGeneration;
1798
+ const assertAcquireActive = () => {
1799
+ var _a;
1800
+ this.assertRunning();
1801
+ if (((_a = input.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) || !isCurrentAcquire()) {
1802
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceInterruptedFromUser);
1803
+ }
1804
+ };
1781
1805
  const retainedToken = this.retainedDevices.has(uuid) &&
1782
1806
  !forceProtocolDetection &&
1783
1807
  (!expectedProtocol || expectedProtocol === 'V2') &&
@@ -1788,21 +1812,21 @@ class ElectronBleTransport {
1788
1812
  if (this.connectedDevices.has(uuid) && retainedToken === undefined) {
1789
1813
  yield this.release(uuid);
1790
1814
  }
1815
+ assertAcquireActive();
1791
1816
  if (forceCleanRunPromise && this.runPromise) {
1792
1817
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleForceCleanRunPromise);
1793
1818
  this.runPromise.reject(error);
1794
1819
  this.runPromise = null;
1795
1820
  this.runPromiseDeviceId = null;
1796
1821
  }
1797
- this.assertRunning();
1798
1822
  this.acquiringDevices.add(uuid);
1799
1823
  let connectAttempted = false;
1800
1824
  try {
1801
- if (!((_a = window.desktopApi) === null || _a === void 0 ? void 0 : _a.nobleBle)) {
1825
+ if (!((_b = window.desktopApi) === null || _b === void 0 ? void 0 : _b.nobleBle)) {
1802
1826
  throw new Error('Noble BLE API not available');
1803
1827
  }
1804
1828
  const device = yield invokeNobleBle(window.desktopApi.nobleBle.getDevice(uuid));
1805
- this.assertRunning();
1829
+ assertAcquireActive();
1806
1830
  if (!device) {
1807
1831
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Device ${uuid} not found`);
1808
1832
  }
@@ -1814,19 +1838,20 @@ class ElectronBleTransport {
1814
1838
  }
1815
1839
  const protocolHint = expectedProtocol
1816
1840
  ? undefined
1817
- : (_b = input.protocolHint) !== null && _b !== void 0 ? _b : this.deviceProtocolHints.get(uuid);
1841
+ : (_c = input.protocolHint) !== null && _c !== void 0 ? _c : this.deviceProtocolHints.get(uuid);
1818
1842
  if (protocolHint) {
1819
1843
  this.deviceProtocolHints.set(uuid, protocolHint);
1820
1844
  }
1821
1845
  try {
1822
1846
  connectAttempted = true;
1823
1847
  yield invokeNobleBle(window.desktopApi.nobleBle.connect(uuid));
1848
+ assertAcquireActive();
1824
1849
  this.connectedDevices.add(uuid);
1825
1850
  }
1826
1851
  catch (error) {
1827
1852
  this.handleBluetoothError(error);
1828
1853
  }
1829
- this.assertRunning();
1854
+ assertAcquireActive();
1830
1855
  const mtuCleanup = this.createMtuSubscription(uuid);
1831
1856
  if (mtuCleanup) {
1832
1857
  this.mtuCleanups.set(uuid, mtuCleanup);
@@ -1839,47 +1864,53 @@ class ElectronBleTransport {
1839
1864
  catch (error) {
1840
1865
  this.handleBluetoothError(error);
1841
1866
  }
1842
- yield this.refreshBlePacketCapacity(uuid);
1843
- this.assertRunning();
1867
+ assertAcquireActive();
1868
+ const connectedDevice = yield this.refreshBlePacketCapacity(uuid);
1869
+ assertAcquireActive();
1870
+ const resolvedDeviceName = (connectedDevice === null || connectedDevice === void 0 ? void 0 : connectedDevice.name) || device.name;
1844
1871
  const cleanup = this.createNotificationSubscription(uuid);
1845
1872
  this.notificationCleanups.set(uuid, cleanup);
1846
1873
  const protocolType = yield this.detectProtocol(uuid, expectedProtocol, protocolHint, {
1847
- isKnownLegacyV1Device: hdShared.isLegacyProtocolV1BleName(device.name),
1874
+ isKnownLegacyV1Device: hdShared.isLegacyProtocolV1BleName(resolvedDeviceName),
1848
1875
  onlyConnectBleDevice: input.onlyConnectBleDevice,
1849
1876
  abortSignal: input.abortSignal,
1850
1877
  });
1851
- this.assertRunning();
1878
+ assertAcquireActive();
1852
1879
  if (protocolType === 'V2') {
1853
- (_c = this.Log) === null || _c === void 0 ? void 0 : _c.debug('[Electron BLE] Protocol V2 write configured', {
1880
+ (_d = this.Log) === null || _d === void 0 ? void 0 : _d.debug('[Electron BLE] Protocol V2 write configured', {
1854
1881
  writeMode: 'withoutResponse',
1855
1882
  negotiatedMtu: this.deviceMtus.get(uuid),
1856
- packetCapacity: (_d = this.devicePacketCapacities.get(uuid)) !== null && _d !== void 0 ? _d : BLE_PACKET_SIZE_FALLBACK,
1883
+ packetCapacity: (_e = this.devicePacketCapacities.get(uuid)) !== null && _e !== void 0 ? _e : BLE_PACKET_SIZE_FALLBACK,
1857
1884
  });
1858
1885
  }
1859
- return Object.assign(Object.assign({}, toBleDescriptor({ id: device.id, name: device.name }, protocolType)), { uuid });
1886
+ return Object.assign(Object.assign({}, toBleDescriptor({ id: device.id, name: resolvedDeviceName }, protocolType)), { uuid });
1860
1887
  }
1861
1888
  catch (error) {
1862
- (_e = this.Log) === null || _e === void 0 ? void 0 : _e.error('[Electron BLE] acquire failed:', error);
1863
- try {
1864
- const nobleBle = (_f = window.desktopApi) === null || _f === void 0 ? void 0 : _f.nobleBle;
1865
- if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
1866
- if (this.connectedDevices.has(uuid)) {
1867
- yield invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
1868
- var _a;
1869
- (_a = this.Log) === null || _a === void 0 ? void 0 : _a.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
1870
- });
1889
+ (_f = this.Log) === null || _f === void 0 ? void 0 : _f.error('[Electron BLE] acquire failed:', error);
1890
+ if (isCurrentAcquire()) {
1891
+ try {
1892
+ const nobleBle = (_g = window.desktopApi) === null || _g === void 0 ? void 0 : _g.nobleBle;
1893
+ if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
1894
+ if (this.connectedDevices.has(uuid)) {
1895
+ yield invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
1896
+ var _a;
1897
+ (_a = this.Log) === null || _a === void 0 ? void 0 : _a.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
1898
+ });
1899
+ }
1900
+ yield invokeNobleBle(nobleBle.disconnect(uuid));
1871
1901
  }
1872
- yield invokeNobleBle(nobleBle.disconnect(uuid));
1873
1902
  }
1903
+ catch (cleanupError) {
1904
+ (_h = this.Log) === null || _h === void 0 ? void 0 : _h.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
1905
+ }
1906
+ this.cleanupDeviceState(uuid);
1874
1907
  }
1875
- catch (cleanupError) {
1876
- (_g = this.Log) === null || _g === void 0 ? void 0 : _g.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
1877
- }
1878
- this.cleanupDeviceState(uuid);
1879
- this.handleBluetoothError(error);
1908
+ throw this.normalizeBluetoothError(error);
1880
1909
  }
1881
1910
  finally {
1882
- this.acquiringDevices.delete(uuid);
1911
+ if (isCurrentAcquire()) {
1912
+ this.acquiringDevices.delete(uuid);
1913
+ }
1883
1914
  }
1884
1915
  });
1885
1916
  }
@@ -2001,8 +2032,9 @@ class ElectronBleTransport {
2001
2032
  yield this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
2002
2033
  this.assertRunning();
2003
2034
  }
2035
+ this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
2004
2036
  let detected = protocol === 'V1' ? yield this.probeProtocolV1(uuid) : yield this.probeProtocolV2(uuid);
2005
- if (!detected && protocol === 'V1') {
2037
+ if (!detected && protocol === 'V1' && !this.lastV1ProbeFailedWithoutTimeout.has(uuid)) {
2006
2038
  detected = yield this.wakeSilentProtocolV1Device(uuid, probeOrder, options);
2007
2039
  }
2008
2040
  this.assertRunning();
@@ -2047,7 +2079,7 @@ class ElectronBleTransport {
2047
2079
  let answeredV1 = false;
2048
2080
  try {
2049
2081
  this.deviceProtocol.set(uuid, 'V1');
2050
- const response = yield this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS }, { oneShot: true });
2082
+ const response = yield this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS }, { oneShot: true }, true);
2051
2083
  answeredV1 = typeof (response === null || response === void 0 ? void 0 : response.type) === 'string';
2052
2084
  }
2053
2085
  catch (error) {
@@ -2118,7 +2150,8 @@ class ElectronBleTransport {
2118
2150
  }
2119
2151
  try {
2120
2152
  this.deviceProtocol.set(uuid, 'V1');
2121
- yield this.callProtocolV1(uuid, 'GetFeatures', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS }, { oneShot: true });
2153
+ this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
2154
+ yield this.callProtocolV1(uuid, 'GetFeatures', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS }, { oneShot: true }, true);
2122
2155
  return true;
2123
2156
  }
2124
2157
  catch (error) {
@@ -2127,6 +2160,9 @@ class ElectronBleTransport {
2127
2160
  if (shouldRethrowElectronProtocolProbeError(error)) {
2128
2161
  throw error;
2129
2162
  }
2163
+ if (!(error instanceof Error && this.probeResponseTimeoutErrors.has(error))) {
2164
+ this.lastV1ProbeFailedWithoutTimeout.add(uuid);
2165
+ }
2130
2166
  return false;
2131
2167
  }
2132
2168
  });
@@ -2180,6 +2216,7 @@ class ElectronBleTransport {
2180
2216
  const nobleBle = (_a = window.desktopApi) === null || _a === void 0 ? void 0 : _a.nobleBle;
2181
2217
  const device = nobleBle ? yield invokeNobleBle(nobleBle.getDevice(uuid)) : undefined;
2182
2218
  this.updateBlePacketCapacity(uuid, device === null || device === void 0 ? void 0 : device.mtu);
2219
+ return device;
2183
2220
  });
2184
2221
  }
2185
2222
  updateBlePacketCapacity(uuid, mtu) {
@@ -2371,7 +2408,7 @@ class ElectronBleTransport {
2371
2408
  yield this.callProtocolV1(uuid, name, data);
2372
2409
  });
2373
2410
  }
2374
- callProtocolV1(uuid, name, data, options, writeOptions) {
2411
+ callProtocolV1(uuid, name, data, options, writeOptions, isProtocolProbe = false) {
2375
2412
  var _a, _b;
2376
2413
  return __awaiter(this, void 0, void 0, function* () {
2377
2414
  if (!this._messages) {
@@ -2388,6 +2425,7 @@ class ElectronBleTransport {
2388
2425
  const messages = this._messages;
2389
2426
  const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
2390
2427
  let timeout;
2428
+ let responseTimedOut = false;
2391
2429
  try {
2392
2430
  if (!((_a = window.desktopApi) === null || _a === void 0 ? void 0 : _a.nobleBle)) {
2393
2431
  throw new Error('Noble BLE write API not available');
@@ -2410,6 +2448,7 @@ class ElectronBleTransport {
2410
2448
  new Promise((_, reject) => {
2411
2449
  if (options === null || options === void 0 ? void 0 : options.timeoutMs) {
2412
2450
  timeout = setTimeout(() => {
2451
+ responseTimedOut = true;
2413
2452
  const error = hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `BLE response timeout after ${options.timeoutMs}ms for ${name}`);
2414
2453
  runPromise.reject(error);
2415
2454
  reject(error);
@@ -2425,19 +2464,21 @@ class ElectronBleTransport {
2425
2464
  }
2426
2465
  catch (e) {
2427
2466
  (_b = this.Log) === null || _b === void 0 ? void 0 : _b.error('[Electron BLE] Protocol V1 call error:', e);
2428
- const isProbeTimeout = (name === 'GetFeatures' || name === 'Initialize') &&
2429
- (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS;
2430
2467
  if ((e === null || e === void 0 ? void 0 : e.errorCode) === hdShared.HardwareErrorCode.BleTimeoutError) {
2431
2468
  this.v1Buffers.set(uuid, { buffer: [], bufferLength: 0 });
2432
2469
  const notifyCleanup = this.notificationCleanups.get(uuid);
2433
2470
  notifyCleanup === null || notifyCleanup === void 0 ? void 0 : notifyCleanup();
2434
2471
  this.notificationCleanups.delete(uuid);
2435
2472
  this.notificationTokens.delete(uuid);
2436
- if (!isProbeTimeout) {
2473
+ if (!isProtocolProbe) {
2437
2474
  yield this.releaseNative(uuid, { forceNative: true });
2438
2475
  }
2439
2476
  }
2440
- throw this.normalizeBluetoothError(e);
2477
+ const normalized = this.normalizeBluetoothError(e);
2478
+ if (isProtocolProbe && responseTimedOut && normalized instanceof Error) {
2479
+ this.probeResponseTimeoutErrors.add(normalized);
2480
+ }
2481
+ throw normalized;
2441
2482
  }
2442
2483
  finally {
2443
2484
  if (timeout)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-web-device",
3
- "version": "1.2.11-alpha.16",
3
+ "version": "1.2.11-alpha.18",
4
4
  "author": "OneKey",
5
5
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
6
6
  "license": "MIT",
@@ -21,14 +21,14 @@
21
21
  "lint:fix": "eslint . --fix"
22
22
  },
23
23
  "dependencies": {
24
- "@onekeyfe/hd-shared": "1.2.11-alpha.16",
25
- "@onekeyfe/hd-transport": "1.2.11-alpha.16",
24
+ "@onekeyfe/hd-shared": "1.2.11-alpha.18",
25
+ "@onekeyfe/hd-transport": "1.2.11-alpha.18",
26
26
  "bytebuffer": "^5.0.1"
27
27
  },
28
28
  "devDependencies": {
29
- "@onekeyfe/hd-transport-electron": "1.2.11-alpha.16",
29
+ "@onekeyfe/hd-transport-electron": "1.2.11-alpha.18",
30
30
  "@types/w3c-web-usb": "^1.0.6",
31
31
  "@types/web-bluetooth": "^0.0.17"
32
32
  },
33
- "gitHead": "14d1790c00dee0883571769faec6c7065b395b39"
33
+ "gitHead": "561cf549c4ca51bda4b2303638dcd3a035f21f48"
34
34
  }
@@ -122,9 +122,12 @@ const shouldRethrowElectronProtocolProbeError = (error: unknown): boolean => {
122
122
  };
123
123
 
124
124
  const isUnstartedElectronWakeError = (error: unknown): boolean => {
125
- const code = (error as { errorCode?: unknown })?.errorCode;
126
- // Errors returned before a GATT write is submitted to the peripheral.
125
+ const candidate = error as { errorCode?: unknown; params?: { writeRejected?: unknown } };
126
+ const code = candidate?.errorCode;
127
+ // Errors returned before a GATT write is submitted or explicitly rejected by the host
128
+ // (e.g. Windows pairing rejection with status: 3) leave the peripheral untouched.
127
129
  return (
130
+ candidate?.params?.writeRejected === true ||
128
131
  code === HardwareErrorCode.BleCharacteristicNotFound ||
129
132
  code === HardwareErrorCode.BlePoweredOff ||
130
133
  code === HardwareErrorCode.BleUnsupported ||
@@ -182,6 +185,14 @@ export default class ElectronBleTransport {
182
185
 
183
186
  private silentDetections = new Map<string, 'silent' | 'woken'>();
184
187
 
188
+ private probeResponseTimeoutErrors = new WeakSet<Error>();
189
+
190
+ private lastV1ProbeFailedWithoutTimeout: Set<string> = new Set();
191
+
192
+ private acquireGenerations: Map<string, number> = new Map();
193
+
194
+ private nextAcquireGeneration = 1;
195
+
185
196
  private deviceMtus: Map<string, number> = new Map();
186
197
 
187
198
  private devicePacketCapacities: Map<string, number> = new Map();
@@ -294,6 +305,7 @@ export default class ElectronBleTransport {
294
305
  // and doesn't depend on connection state. Preserving it avoids redundant V1 probe on reconnect.
295
306
  this.v1Buffers.delete(deviceId);
296
307
  this.v2Assemblers.delete(deviceId);
308
+ this.lastV1ProbeFailedWithoutTimeout.delete(deviceId);
297
309
  this.resetProtocolV2Frames(deviceId);
298
310
  this.notificationTokens.delete(deviceId);
299
311
  if (this.runPromise && this.runPromiseDeviceId === deviceId) {
@@ -364,6 +376,8 @@ export default class ElectronBleTransport {
364
376
 
365
377
  await Promise.all(Array.from(trackedDeviceIds, deviceId => this.releaseNative(deviceId)));
366
378
  this.acquiringDevices.clear();
379
+ this.acquireGenerations.clear();
380
+ this.lastV1ProbeFailedWithoutTimeout.clear();
367
381
  this.protocolV2CallCounts.clear();
368
382
  this.silentDetections.clear();
369
383
  await this.protocolV2Links
@@ -457,6 +471,20 @@ export default class ElectronBleTransport {
457
471
  if (!uuid) {
458
472
  throw ERRORS.TypedError(HardwareErrorCode.BleRequiredUUID);
459
473
  }
474
+ if (input.abortSignal?.aborted) {
475
+ throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
476
+ }
477
+
478
+ const acquireGeneration = this.nextAcquireGeneration;
479
+ this.nextAcquireGeneration += 1;
480
+ this.acquireGenerations.set(uuid, acquireGeneration);
481
+ const isCurrentAcquire = () => this.acquireGenerations.get(uuid) === acquireGeneration;
482
+ const assertAcquireActive = () => {
483
+ this.assertRunning();
484
+ if (input.abortSignal?.aborted || !isCurrentAcquire()) {
485
+ throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
486
+ }
487
+ };
460
488
 
461
489
  const retainedToken =
462
490
  this.retainedDevices.has(uuid) &&
@@ -470,6 +498,8 @@ export default class ElectronBleTransport {
470
498
  await this.release(uuid);
471
499
  }
472
500
 
501
+ assertAcquireActive();
502
+
473
503
  if (forceCleanRunPromise && this.runPromise) {
474
504
  const error = ERRORS.TypedError(HardwareErrorCode.BleForceCleanRunPromise);
475
505
  this.runPromise.reject(error);
@@ -477,7 +507,6 @@ export default class ElectronBleTransport {
477
507
  this.runPromiseDeviceId = null;
478
508
  }
479
509
 
480
- this.assertRunning();
481
510
  this.acquiringDevices.add(uuid);
482
511
  let connectAttempted = false;
483
512
  try {
@@ -486,7 +515,7 @@ export default class ElectronBleTransport {
486
515
  }
487
516
 
488
517
  const device = await invokeNobleBle(window.desktopApi.nobleBle.getDevice(uuid));
489
- this.assertRunning();
518
+ assertAcquireActive();
490
519
  if (!device) {
491
520
  throw ERRORS.TypedError(HardwareErrorCode.DeviceNotFound, `Device ${uuid} not found`);
492
521
  }
@@ -512,11 +541,12 @@ export default class ElectronBleTransport {
512
541
  try {
513
542
  connectAttempted = true;
514
543
  await invokeNobleBle(window.desktopApi.nobleBle.connect(uuid));
544
+ assertAcquireActive();
515
545
  this.connectedDevices.add(uuid);
516
546
  } catch (error) {
517
547
  this.handleBluetoothError(error);
518
548
  }
519
- this.assertRunning();
549
+ assertAcquireActive();
520
550
 
521
551
  const mtuCleanup = this.createMtuSubscription(uuid);
522
552
  if (mtuCleanup) {
@@ -531,18 +561,20 @@ export default class ElectronBleTransport {
531
561
  } catch (error) {
532
562
  this.handleBluetoothError(error);
533
563
  }
534
- await this.refreshBlePacketCapacity(uuid);
535
- this.assertRunning();
564
+ assertAcquireActive();
565
+ const connectedDevice = await this.refreshBlePacketCapacity(uuid);
566
+ assertAcquireActive();
567
+ const resolvedDeviceName = connectedDevice?.name || device.name;
536
568
 
537
569
  const cleanup = this.createNotificationSubscription(uuid);
538
570
  this.notificationCleanups.set(uuid, cleanup);
539
571
 
540
572
  const protocolType = await this.detectProtocol(uuid, expectedProtocol, protocolHint, {
541
- isKnownLegacyV1Device: isLegacyProtocolV1BleName(device.name),
573
+ isKnownLegacyV1Device: isLegacyProtocolV1BleName(resolvedDeviceName),
542
574
  onlyConnectBleDevice: input.onlyConnectBleDevice,
543
575
  abortSignal: input.abortSignal,
544
576
  });
545
- this.assertRunning();
577
+ assertAcquireActive();
546
578
  if (protocolType === 'V2') {
547
579
  this.Log?.debug('[Electron BLE] Protocol V2 write configured', {
548
580
  writeMode: 'withoutResponse',
@@ -552,28 +584,32 @@ export default class ElectronBleTransport {
552
584
  }
553
585
 
554
586
  return {
555
- ...toBleDescriptor({ id: device.id, name: device.name }, protocolType),
587
+ ...toBleDescriptor({ id: device.id, name: resolvedDeviceName }, protocolType),
556
588
  uuid,
557
589
  };
558
590
  } catch (error) {
559
591
  this.Log?.error('[Electron BLE] acquire failed:', error);
560
- try {
561
- const nobleBle = window.desktopApi?.nobleBle;
562
- if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
563
- if (this.connectedDevices.has(uuid)) {
564
- await invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
565
- this.Log?.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
566
- });
592
+ if (isCurrentAcquire()) {
593
+ try {
594
+ const nobleBle = window.desktopApi?.nobleBle;
595
+ if (nobleBle && !this.stopped && (connectAttempted || this.connectedDevices.has(uuid))) {
596
+ if (this.connectedDevices.has(uuid)) {
597
+ await invokeNobleBle(nobleBle.unsubscribe(uuid)).catch(cleanupError => {
598
+ this.Log?.debug('[Electron BLE] acquire unsubscribe failed:', cleanupError);
599
+ });
600
+ }
601
+ await invokeNobleBle(nobleBle.disconnect(uuid));
567
602
  }
568
- await invokeNobleBle(nobleBle.disconnect(uuid));
603
+ } catch (cleanupError) {
604
+ this.Log?.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
569
605
  }
570
- } catch (cleanupError) {
571
- this.Log?.debug('[Electron BLE] acquire cleanup failed:', cleanupError);
606
+ this.cleanupDeviceState(uuid);
572
607
  }
573
- this.cleanupDeviceState(uuid);
574
- this.handleBluetoothError(error);
608
+ throw this.normalizeBluetoothError(error);
575
609
  } finally {
576
- this.acquiringDevices.delete(uuid);
610
+ if (isCurrentAcquire()) {
611
+ this.acquiringDevices.delete(uuid);
612
+ }
577
613
  }
578
614
  }
579
615
 
@@ -731,9 +767,10 @@ export default class ElectronBleTransport {
731
767
  await this.resetProbeStateAfterProtocolProbe(uuid, probeOrder[i - 1]);
732
768
  this.assertRunning();
733
769
  }
770
+ this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
734
771
  let detected =
735
772
  protocol === 'V1' ? await this.probeProtocolV1(uuid) : await this.probeProtocolV2(uuid);
736
- if (!detected && protocol === 'V1') {
773
+ if (!detected && protocol === 'V1' && !this.lastV1ProbeFailedWithoutTimeout.has(uuid)) {
737
774
  detected = await this.wakeSilentProtocolV1Device(uuid, probeOrder, options);
738
775
  }
739
776
  this.assertRunning();
@@ -797,7 +834,8 @@ export default class ElectronBleTransport {
797
834
  'Initialize',
798
835
  {},
799
836
  { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS },
800
- { oneShot: true }
837
+ { oneShot: true },
838
+ true
801
839
  );
802
840
  answeredV1 = typeof response?.type === 'string';
803
841
  } catch (error) {
@@ -878,12 +916,14 @@ export default class ElectronBleTransport {
878
916
  // session before Core has a chance to restore a hidden wallet. Use a one-shot
879
917
  // native write so a fresh Windows link does not stall 28s in the 15-attempt
880
918
  // pairing retry loop when a sleeping Classic silently ignores GetFeatures.
919
+ this.lastV1ProbeFailedWithoutTimeout.delete(uuid);
881
920
  await this.callProtocolV1(
882
921
  uuid,
883
922
  'GetFeatures',
884
923
  {},
885
924
  { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS },
886
- { oneShot: true }
925
+ { oneShot: true },
926
+ true
887
927
  );
888
928
  return true;
889
929
  } catch (error) {
@@ -892,6 +932,9 @@ export default class ElectronBleTransport {
892
932
  if (shouldRethrowElectronProtocolProbeError(error)) {
893
933
  throw error;
894
934
  }
935
+ if (!(error instanceof Error && this.probeResponseTimeoutErrors.has(error))) {
936
+ this.lastV1ProbeFailedWithoutTimeout.add(uuid);
937
+ }
895
938
  return false;
896
939
  }
897
940
  }
@@ -936,10 +979,11 @@ export default class ElectronBleTransport {
936
979
  }
937
980
  }
938
981
 
939
- private async refreshBlePacketCapacity(uuid: string): Promise<void> {
982
+ private async refreshBlePacketCapacity(uuid: string) {
940
983
  const nobleBle = window.desktopApi?.nobleBle;
941
984
  const device = nobleBle ? await invokeNobleBle(nobleBle.getDevice(uuid)) : undefined;
942
985
  this.updateBlePacketCapacity(uuid, device?.mtu);
986
+ return device;
943
987
  }
944
988
 
945
989
  private updateBlePacketCapacity(uuid: string, mtu?: number): void {
@@ -1164,7 +1208,8 @@ export default class ElectronBleTransport {
1164
1208
  name: string,
1165
1209
  data: Record<string, unknown>,
1166
1210
  options?: TransportCallOptions,
1167
- writeOptions?: NobleBleWriteOptions
1211
+ writeOptions?: NobleBleWriteOptions,
1212
+ isProtocolProbe = false
1168
1213
  ) {
1169
1214
  if (!this._messages) {
1170
1215
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
@@ -1182,6 +1227,7 @@ export default class ElectronBleTransport {
1182
1227
  const messages = this._messages;
1183
1228
  const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
1184
1229
  let timeout: ReturnType<typeof setTimeout> | undefined;
1230
+ let responseTimedOut = false;
1185
1231
 
1186
1232
  try {
1187
1233
  if (!window.desktopApi?.nobleBle) {
@@ -1209,6 +1255,7 @@ export default class ElectronBleTransport {
1209
1255
  new Promise<never>((_, reject) => {
1210
1256
  if (options?.timeoutMs) {
1211
1257
  timeout = setTimeout(() => {
1258
+ responseTimedOut = true;
1212
1259
  const error = ERRORS.TypedError(
1213
1260
  HardwareErrorCode.BleTimeoutError,
1214
1261
  `BLE response timeout after ${options.timeoutMs}ms for ${name}`
@@ -1227,20 +1274,21 @@ export default class ElectronBleTransport {
1227
1274
  return check.call(jsonData);
1228
1275
  } catch (e) {
1229
1276
  this.Log?.error('[Electron BLE] Protocol V1 call error:', e);
1230
- const isProbeTimeout =
1231
- (name === 'GetFeatures' || name === 'Initialize') &&
1232
- options?.timeoutMs === PROTOCOL_PROBE_TIMEOUT_MS;
1233
1277
  if ((e as { errorCode?: unknown })?.errorCode === HardwareErrorCode.BleTimeoutError) {
1234
1278
  this.v1Buffers.set(uuid, { buffer: [], bufferLength: 0 });
1235
1279
  const notifyCleanup = this.notificationCleanups.get(uuid);
1236
1280
  notifyCleanup?.();
1237
1281
  this.notificationCleanups.delete(uuid);
1238
1282
  this.notificationTokens.delete(uuid);
1239
- if (!isProbeTimeout) {
1283
+ if (!isProtocolProbe) {
1240
1284
  await this.releaseNative(uuid, { forceNative: true });
1241
1285
  }
1242
1286
  }
1243
- throw this.normalizeBluetoothError(e);
1287
+ const normalized = this.normalizeBluetoothError(e);
1288
+ if (isProtocolProbe && responseTimedOut && normalized instanceof Error) {
1289
+ this.probeResponseTimeoutErrors.add(normalized);
1290
+ }
1291
+ throw normalized;
1244
1292
  } finally {
1245
1293
  if (timeout) clearTimeout(timeout);
1246
1294
  if (this.runPromise === runPromise) {