@onekeyfe/hd-transport-electron 1.2.2-alpha.100 → 1.2.2-alpha.2

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.
@@ -32,7 +32,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
32
32
 
33
33
  function initNobleBleSupport(webContents) {
34
34
  return __awaiter(this, void 0, void 0, function* () {
35
- const { setupNobleBleHandlers } = yield Promise.resolve().then(function () { return require('./noble-ble-handler-e8b87173.js'); });
35
+ const { setupNobleBleHandlers } = yield Promise.resolve().then(function () { return require('./noble-ble-handler-56d2eab3.js'); });
36
36
  setupNobleBleHandlers(webContents);
37
37
  });
38
38
  }
package/dist/index.d.ts CHANGED
@@ -25,6 +25,7 @@ interface NobleModule {
25
25
  interface Logger {
26
26
  info(message: string, ...args: any[]): void;
27
27
  debug(message: string, ...args: any[]): void;
28
+ warn(message: string, ...args: any[]): void;
28
29
  error(message: string, ...args: any[]): void;
29
30
  }
30
31
 
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var index = require('./index-b37d926c.js');
5
+ var index = require('./index-a518d449.js');
6
6
 
7
7
 
8
8
 
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var index = require('./index-b37d926c.js');
3
+ var index = require('./index-a518d449.js');
4
4
  var hdShared = require('@onekeyfe/hd-shared');
5
5
  var pRetry = require('p-retry');
6
6
 
@@ -116,7 +116,8 @@ const DEVICE_SCAN_TIMEOUT = 5000;
116
116
  const DEVICE_CHECK_INTERVAL = 500;
117
117
  const SERVICE_DISCOVERY_TIMEOUT = 10000;
118
118
  const BLE_CLEANUP_TIMEOUT = 250;
119
- const BLE_IDLE_DISCONNECT_MS = 3 * 60000;
119
+ const BLE_DISCONNECT_CONFIRM_TIMEOUT_MS = 3000;
120
+ const BLE_IDLE_DISCONNECT_MS = 20000;
120
121
  const BLE_BUSY_BACKSTOP_MS = 10 * 60000;
121
122
  const BLE_PACKET_SIZE_FALLBACK = 192;
122
123
  const BLE_PACKET_SIZE_MAXIMUM = 244;
@@ -242,6 +243,7 @@ function initializeNoble() {
242
243
  try {
243
244
  noble = require('@stoprocent/noble');
244
245
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Noble library loaded');
246
+ setupPersistentStateListener();
245
247
  yield new Promise((resolve, reject) => {
246
248
  if (!noble) {
247
249
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Noble not initialized'));
@@ -251,7 +253,6 @@ function initializeNoble() {
251
253
  resolve();
252
254
  return;
253
255
  }
254
- setupPersistentStateListener();
255
256
  const timeout = setTimeout(() => {
256
257
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Bluetooth initialization timeout'));
257
258
  }, BLUETOOTH_INIT_TIMEOUT);
@@ -336,7 +337,14 @@ function armIdleDisconnect(deviceId, ms = BLE_IDLE_DISCONNECT_MS, reason = 'idle
336
337
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Keep-alive timeout, disconnecting device', { deviceId, reason });
337
338
  const peripheral = connectedDevices.get(deviceId);
338
339
  const deviceName = ((_a = peripheral === null || peripheral === void 0 ? void 0 : peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName) || 'Unknown Device';
339
- const pending = disconnectDevice(deviceId)
340
+ const pending = unsubscribeNotifications(deviceId)
341
+ .catch(error => {
342
+ logger === null || logger === void 0 ? void 0 : logger.warn('[NobleBLE] Keep-alive unsubscribe failed, disconnecting anyway', {
343
+ deviceId,
344
+ error: error instanceof Error ? error.message : String(error),
345
+ });
346
+ })
347
+ .then(() => disconnectDevice(deviceId))
340
348
  .then(() => {
341
349
  broadcastToAllWebContents(hdShared.EOneKeyBleMessageKeys.BLE_DEVICE_DISCONNECTED, {
342
350
  id: deviceId,
@@ -409,6 +417,7 @@ function handleDeviceDisconnect(deviceId, webContents) {
409
417
  });
410
418
  cleanupDevice(deviceId, webContents, {
411
419
  cleanupConnection: true,
420
+ cleanupDiscoveredCache: true,
412
421
  sendDisconnectEvent: true,
413
422
  cancelOperations: true,
414
423
  reason: 'auto-disconnect',
@@ -590,18 +599,37 @@ function transmitHexDataToDevice(deviceId, hexData, options) {
590
599
  }
591
600
  });
592
601
  }
602
+ const BLE_COLD_CONNECT_SCAN_TIMEOUT_MS = 1500;
603
+ const SERVICE_DISCOVERY_MAX_ATTEMPTS = 2;
604
+ const bleNamesById = new Map();
605
+ function rememberBleName(deviceId, name) {
606
+ const trimmed = name === null || name === void 0 ? void 0 : name.trim();
607
+ if (trimmed) {
608
+ bleNamesById.set(deviceId, trimmed);
609
+ }
610
+ }
611
+ function resolveBleName(deviceId) {
612
+ var _a, _b, _c, _d, _e, _f;
613
+ const live = ((_c = (_b = (_a = connectedDevices.get(deviceId)) === null || _a === void 0 ? void 0 : _a.advertisement) === null || _b === void 0 ? void 0 : _b.localName) === null || _c === void 0 ? void 0 : _c.trim()) ||
614
+ ((_f = (_e = (_d = discoveredDevices.get(deviceId)) === null || _d === void 0 ? void 0 : _d.advertisement) === null || _e === void 0 ? void 0 : _e.localName) === null || _f === void 0 ? void 0 : _f.trim());
615
+ return live || bleNamesById.get(deviceId);
616
+ }
617
+ function shouldConnectByIdFirst(deviceId) {
618
+ return hdShared.isPro2FamilyBleName(resolveBleName(deviceId));
619
+ }
593
620
  function handleDeviceDiscovered(peripheral) {
594
- var _a, _b;
621
+ var _a, _b, _c;
595
622
  if (!isOneKeyPeripheral(peripheral)) {
596
623
  return;
597
624
  }
598
625
  const isNewDevice = !discoveredDevices.has(peripheral.id);
599
626
  discoveredDevices.set(peripheral.id, peripheral);
627
+ rememberBleName(peripheral.id, (_a = peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName);
600
628
  if (isNewDevice) {
601
629
  logger === null || logger === void 0 ? void 0 : logger.debug('[NobleBLE] OneKey BLE device discovered', {
602
630
  deviceId: peripheral.id,
603
- name: ((_a = peripheral.advertisement) === null || _a === void 0 ? void 0 : _a.localName) || 'Unknown Device',
604
- serviceUUIDs: ((_b = peripheral.advertisement) === null || _b === void 0 ? void 0 : _b.serviceUuids) || [],
631
+ name: ((_b = peripheral.advertisement) === null || _b === void 0 ? void 0 : _b.localName) || 'Unknown Device',
632
+ serviceUUIDs: ((_c = peripheral.advertisement) === null || _c === void 0 ? void 0 : _c.serviceUuids) || [],
605
633
  });
606
634
  }
607
635
  }
@@ -627,7 +655,7 @@ function waitForNobleScanStop(nobleInstance) {
627
655
  });
628
656
  });
629
657
  }
630
- function performTargetedScan(targetDeviceId) {
658
+ function performTargetedScan(targetDeviceId, timeoutMs = NOBLE_BLE_TARGETED_SCAN_TIMEOUT_MS) {
631
659
  return index.__awaiter(this, void 0, void 0, function* () {
632
660
  if (!noble) {
633
661
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Noble not available');
@@ -667,7 +695,7 @@ function performTargetedScan(targetDeviceId) {
667
695
  const timeoutId = setTimeout(() => {
668
696
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Targeted scan timeout for device:', targetDeviceId);
669
697
  finish(null).catch(reject);
670
- }, NOBLE_BLE_TARGETED_SCAN_TIMEOUT_MS);
698
+ }, timeoutMs);
671
699
  nobleInstance.on('discover', onDiscover);
672
700
  nobleInstance.startScanning([], true, (error) => {
673
701
  if (error) {
@@ -802,7 +830,7 @@ function discoverServicesAndCharacteristics(peripheral) {
802
830
  });
803
831
  const discoveryPromise = (() => index.__awaiter(this, void 0, void 0, function* () {
804
832
  const services = yield new Promise((resolve, reject) => {
805
- peripheral.discoverServices([], (error, svc) => {
833
+ peripheral.discoverServices(ONEKEY_SERVICE_UUIDS, (error, svc) => {
806
834
  if (error) {
807
835
  logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed:', error);
808
836
  reject(hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, error.message));
@@ -813,7 +841,7 @@ function discoverServicesAndCharacteristics(peripheral) {
813
841
  });
814
842
  });
815
843
  if (!services || services.length === 0) {
816
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, 'No services found');
844
+ throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleServiceNotFound, 'No OneKey services found');
817
845
  }
818
846
  logger === null || logger === void 0 ? void 0 : logger.debug('[NobleBLE] services discovered', {
819
847
  deviceId: peripheral.id,
@@ -930,11 +958,11 @@ function discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId) {
930
958
  deviceId,
931
959
  peripheralState: peripheral.state,
932
960
  attempt: attemptNumber,
933
- maxRetries: 5,
961
+ maxRetries: SERVICE_DISCOVERY_MAX_ATTEMPTS,
934
962
  targetUUIDs: ONEKEY_SERVICE_UUIDS,
935
963
  });
936
964
  if (attemptNumber > 1) {
937
- logger === null || logger === void 0 ? void 0 : logger.info(`[NobleBLE] Service discovery retry attempt ${attemptNumber}/5`);
965
+ logger === null || logger === void 0 ? void 0 : logger.info(`[NobleBLE] Service discovery retry attempt ${attemptNumber}/${SERVICE_DISCOVERY_MAX_ATTEMPTS}`);
938
966
  }
939
967
  if (peripheral.state !== 'connected') {
940
968
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleConnectedError, `Device not connected: ${peripheral.state}`);
@@ -943,16 +971,16 @@ function discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId) {
943
971
  return yield discoverServicesAndCharacteristics(peripheral);
944
972
  }
945
973
  catch (error) {
946
- logger === null || logger === void 0 ? void 0 : logger.error(`[NobleBLE] No services found (attempt ${attemptNumber}/5)`);
947
- if (attemptNumber < 5) {
948
- logger === null || logger === void 0 ? void 0 : logger.error(`[NobleBLE] Will retry service discovery (attempt ${attemptNumber + 1}/5)`);
974
+ logger === null || logger === void 0 ? void 0 : logger.error(`[NobleBLE] No services found (attempt ${attemptNumber}/${SERVICE_DISCOVERY_MAX_ATTEMPTS})`);
975
+ if (attemptNumber < SERVICE_DISCOVERY_MAX_ATTEMPTS) {
976
+ logger === null || logger === void 0 ? void 0 : logger.error(`[NobleBLE] Will retry service discovery (attempt ${attemptNumber + 1}/${SERVICE_DISCOVERY_MAX_ATTEMPTS})`);
949
977
  }
950
978
  throw error;
951
979
  }
952
980
  }), {
953
- retries: 4,
981
+ retries: SERVICE_DISCOVERY_MAX_ATTEMPTS - 1,
954
982
  factor: 1.5,
955
- minTimeout: 1000,
983
+ minTimeout: 500,
956
984
  maxTimeout: 3000,
957
985
  onFailedAttempt: error => {
958
986
  logger === null || logger === void 0 ? void 0 : logger.error(`[NobleBLE] Service discovery attempt ${error.attemptNumber} failed:`, {
@@ -966,23 +994,24 @@ function discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId) {
966
994
  }
967
995
  function setupConnectionAndDiscoverServices(peripheral, deviceId, webContents) {
968
996
  return index.__awaiter(this, void 0, void 0, function* () {
969
- setupDisconnectListener(peripheral, deviceId, webContents);
970
997
  try {
971
- return yield discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId);
998
+ yield forceReconnectPeripheral(peripheral, deviceId);
972
999
  }
973
- catch (initialError) {
974
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Direct service discovery failed, retrying after reconnect', {
975
- deviceId,
976
- error: initialError,
977
- });
1000
+ catch (resetError) {
1001
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Connection reset before discovery failed, continuing', resetError);
978
1002
  }
979
- yield forceReconnectPeripheral(peripheral, deviceId);
980
1003
  setupDisconnectListener(peripheral, deviceId, webContents);
981
1004
  try {
982
1005
  return yield discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId);
983
1006
  }
984
- catch (reconnectError) {
985
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed after reconnect, attempting fresh scan...', reconnectError);
1007
+ catch (discoveryError) {
1008
+ if (peripheral.state === 'connected') {
1009
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed on a live link, dropping it before the fresh scan', discoveryError);
1010
+ yield disconnectDevice(deviceId).catch(() => undefined);
1011
+ }
1012
+ else {
1013
+ logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Service discovery failed, attempting fresh scan...', discoveryError);
1014
+ }
986
1015
  return freshScanAndDiscover(deviceId, webContents);
987
1016
  }
988
1017
  });
@@ -1042,7 +1071,7 @@ function tryDirectConnectById(deviceId) {
1042
1071
  });
1043
1072
  }
1044
1073
  function connectDevice(deviceId, webContents) {
1045
- var _a;
1074
+ var _a, _b, _c;
1046
1075
  return index.__awaiter(this, void 0, void 0, function* () {
1047
1076
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Connect device request:', {
1048
1077
  deviceId,
@@ -1054,34 +1083,47 @@ function connectDevice(deviceId, webContents) {
1054
1083
  });
1055
1084
  let peripheral = (_a = discoveredDevices.get(deviceId)) !== null && _a !== void 0 ? _a : connectedDevices.get(deviceId);
1056
1085
  if (!peripheral) {
1057
- logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Device not discovered, attempting targeted scan for:', deviceId);
1058
1086
  if (!noble) {
1059
1087
  yield initializeNoble();
1060
1088
  }
1061
1089
  if (!noble) {
1062
1090
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, 'Noble not available');
1063
1091
  }
1064
- peripheral = yield tryDirectConnectById(deviceId);
1065
- if (peripheral) {
1066
- discoveredDevices.set(deviceId, peripheral);
1067
- }
1068
- }
1069
- if (!peripheral) {
1070
- try {
1071
- const foundPeripheral = yield performTargetedScan(deviceId);
1072
- if (!foundPeripheral) {
1073
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Device ${deviceId} not found even after targeted scan`);
1092
+ const byIdFirst = shouldConnectByIdFirst(deviceId);
1093
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Resolving device for cold connect', {
1094
+ deviceId,
1095
+ name: (_b = resolveBleName(deviceId)) !== null && _b !== void 0 ? _b : 'unknown',
1096
+ strategy: byIdFirst ? 'connect-by-id-first' : 'scan-first',
1097
+ });
1098
+ const scanForPeripheral = () => index.__awaiter(this, void 0, void 0, function* () {
1099
+ var _d;
1100
+ try {
1101
+ return (_d = (yield performTargetedScan(deviceId, BLE_COLD_CONNECT_SCAN_TIMEOUT_MS))) !== null && _d !== void 0 ? _d : undefined;
1074
1102
  }
1075
- peripheral = foundPeripheral;
1076
- }
1077
- catch (error) {
1078
- logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Targeted scan failed:', error);
1079
- throw error;
1103
+ catch (scanError) {
1104
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Targeted scan failed', {
1105
+ deviceId,
1106
+ error: scanError instanceof Error ? scanError.message : String(scanError),
1107
+ });
1108
+ return undefined;
1109
+ }
1110
+ });
1111
+ const connectById = () => index.__awaiter(this, void 0, void 0, function* () {
1112
+ const found = yield tryDirectConnectById(deviceId);
1113
+ if (found) {
1114
+ discoveredDevices.set(deviceId, found);
1115
+ }
1116
+ return found;
1117
+ });
1118
+ peripheral = byIdFirst ? yield connectById() : yield scanForPeripheral();
1119
+ if (!peripheral) {
1120
+ peripheral = byIdFirst ? yield scanForPeripheral() : yield connectById();
1080
1121
  }
1081
1122
  }
1082
1123
  if (!peripheral) {
1083
1124
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.DeviceNotFound, `Device ${deviceId} not found`);
1084
1125
  }
1126
+ rememberBleName(deviceId, (_c = peripheral.advertisement) === null || _c === void 0 ? void 0 : _c.localName);
1085
1127
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Connecting to device:', deviceId);
1086
1128
  if (peripheral.state === 'connected') {
1087
1129
  logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Device already connected, skipping connection step');
@@ -1156,9 +1198,9 @@ function connectDevice(deviceId, webContents) {
1156
1198
  }
1157
1199
  catch (setupError) {
1158
1200
  logger === null || logger === void 0 ? void 0 : logger.error('[NobleBLE] Connection setup failed:', setupError);
1159
- connectedPeripheral.disconnect(() => {
1160
- reject(setupError);
1161
- });
1201
+ disconnectDevice(deviceId)
1202
+ .catch(() => undefined)
1203
+ .then(() => reject(setupError));
1162
1204
  }
1163
1205
  }));
1164
1206
  });
@@ -1176,11 +1218,15 @@ function disconnectDevice(deviceId) {
1176
1218
  deviceDisconnectListeners.delete(deviceId);
1177
1219
  }
1178
1220
  yield runBleCallbackOperation(callback => peripheral.disconnect(() => callback()), {
1179
- timeoutMs: BLE_CLEANUP_TIMEOUT,
1221
+ timeoutMs: BLE_DISCONNECT_CONFIRM_TIMEOUT_MS,
1180
1222
  timeoutBehavior: 'resolve',
1181
1223
  });
1224
+ if (peripheral.state === 'connected') {
1225
+ logger === null || logger === void 0 ? void 0 : logger.warn('[NobleBLE] Physical disconnect did not confirm in time', { deviceId });
1226
+ }
1182
1227
  cleanupDevice(deviceId, undefined, {
1183
1228
  cleanupConnection: true,
1229
+ cleanupDiscoveredCache: true,
1184
1230
  sendDisconnectEvent: false,
1185
1231
  cancelOperations: true,
1186
1232
  reason: 'manual-disconnect',
@@ -1271,9 +1317,14 @@ function subscribeNotifications(deviceId, callback) {
1271
1317
  });
1272
1318
  });
1273
1319
  }
1320
+ const subscribeStartedAt = Date.now();
1274
1321
  try {
1275
1322
  yield rebuildAppSubscription(deviceId, notifyCharacteristic);
1276
1323
  subscribedDevices.set(deviceId, true);
1324
+ logger === null || logger === void 0 ? void 0 : logger.info('[NobleBLE] Notification subscription active', {
1325
+ deviceId,
1326
+ ms: Date.now() - subscribeStartedAt,
1327
+ });
1277
1328
  }
1278
1329
  finally {
1279
1330
  subscriptionOperations.set(deviceId, 'idle');
@@ -1391,10 +1442,6 @@ function setupNobleBleHandlers(webContents) {
1391
1442
  yield disconnectDevice(deviceId).catch(() => undefined);
1392
1443
  }
1393
1444
  yield stopScanning().catch(() => undefined);
1394
- if (noble && persistentStateListener) {
1395
- noble.removeListener('stateChange', persistentStateListener);
1396
- persistentStateListener = null;
1397
- }
1398
1445
  cleanupNobleListeners();
1399
1446
  discoveredDevices.clear();
1400
1447
  safeLog(logger, 'info', 'Noble BLE cleanup completed');
@@ -1 +1 @@
1
- {"version":3,"file":"noble-ble-handler.d.ts","sourceRoot":"","sources":["../src/noble-ble-handler.ts"],"names":[],"mappings":"AA+BA,OAAO,KAAK,EAA+B,WAAW,EAAE,MAAM,UAAU,CAAC;AAEzE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AA0EhE,wBAAgB,+BAA+B,CAAC,OAAO,CAAC,EAAE,oBAAoB,UAI7E;AA2mDD,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,IAAI,CAgMpE"}
1
+ {"version":3,"file":"noble-ble-handler.d.ts","sourceRoot":"","sources":["../src/noble-ble-handler.ts"],"names":[],"mappings":"AAgCA,OAAO,KAAK,EAA+B,WAAW,EAAE,MAAM,UAAU,CAAC;AAEzE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAoFhE,wBAAgB,+BAA+B,CAAC,OAAO,CAAC,EAAE,oBAAoB,UAI7E;AAsvDD,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,WAAW,GAAG,IAAI,CAkMpE"}
@@ -22,6 +22,7 @@ export interface NobleModule {
22
22
  export interface Logger {
23
23
  info(message: string, ...args: any[]): void;
24
24
  debug(message: string, ...args: any[]): void;
25
+ warn(message: string, ...args: any[]): void;
25
26
  error(message: string, ...args: any[]): void;
26
27
  }
27
28
  export declare function safeLog(logger: Logger | null, level: 'info' | 'debug' | 'error', message: string, ...args: any[]): void;
@@ -1 +1 @@
1
- {"version":3,"file":"noble-extended.d.ts","sourceRoot":"","sources":["../../src/types/noble-extended.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAGnE,MAAM,WAAW,UAAW,SAAQ,oBAAoB;IACtD,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAGD,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,cAAc,CAAC;IACtB,MAAM,EAAE,cAAc,CAAC;CACxB;AAGD,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,CACX,YAAY,EAAE,MAAM,EAAE,EACtB,eAAe,EAAE,OAAO,EACxB,QAAQ,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,GACjC,IAAI,CAAC;IACR,YAAY,CAAC,QAAQ,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC1C,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;IAClE,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,UAAU,EAAE,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IACxE,cAAc,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;IAC9E,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,UAAU,EAAE,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;CACrF;AAGD,MAAM,WAAW,MAAM;IACrB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC5C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC7C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;CAC9C;AAGD,wBAAgB,OAAO,CACrB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,EACjC,OAAO,EAAE,MAAM,EACf,GAAG,IAAI,EAAE,GAAG,EAAE,GACb,IAAI,CAMN"}
1
+ {"version":3,"file":"noble-extended.d.ts","sourceRoot":"","sources":["../../src/types/noble-extended.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAGnE,MAAM,WAAW,UAAW,SAAQ,oBAAoB;IACtD,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAGD,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,cAAc,CAAC;IACtB,MAAM,EAAE,cAAc,CAAC;CACxB;AAGD,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,CACX,YAAY,EAAE,MAAM,EAAE,EACtB,eAAe,EAAE,OAAO,EACxB,QAAQ,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,KAAK,IAAI,GACjC,IAAI,CAAC;IACR,YAAY,CAAC,QAAQ,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;IAC1C,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;IAClE,EAAE,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,UAAU,EAAE,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;IACxE,cAAc,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;IAC9E,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,UAAU,EAAE,UAAU,KAAK,IAAI,GAAG,IAAI,CAAC;CACrF;AAGD,MAAM,WAAW,MAAM;IACrB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC5C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC7C,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAC5C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;CAC9C;AAGD,wBAAgB,OAAO,CACrB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,EACjC,OAAO,EAAE,MAAM,EACf,GAAG,IAAI,EAAE,GAAG,EAAE,GACb,IAAI,CAMN"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-electron",
3
- "version": "1.2.2-alpha.100",
3
+ "version": "1.2.2-alpha.2",
4
4
  "author": "OneKey",
5
5
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
6
6
  "license": "MIT",
@@ -25,9 +25,9 @@
25
25
  "electron-log": ">=4.0.0"
26
26
  },
27
27
  "dependencies": {
28
- "@onekeyfe/hd-core": "1.2.2-alpha.100",
29
- "@onekeyfe/hd-shared": "1.2.2-alpha.100",
30
- "@onekeyfe/hd-transport": "1.2.2-alpha.100",
28
+ "@onekeyfe/hd-core": "1.2.2-alpha.2",
29
+ "@onekeyfe/hd-shared": "1.2.2-alpha.2",
30
+ "@onekeyfe/hd-transport": "1.2.2-alpha.2",
31
31
  "@stoprocent/noble": "2.3.16",
32
32
  "p-retry": "^4.6.2"
33
33
  },
@@ -36,5 +36,5 @@
36
36
  "electron": "^25.0.0",
37
37
  "typescript": "^5.3.3"
38
38
  },
39
- "gitHead": "c40dad085297b0e3cc2020bd218c146dff6ed3e1"
39
+ "gitHead": "fc914d0361028f1012ca764e53f996b9893b40f9"
40
40
  }
@@ -16,6 +16,7 @@ import {
16
16
  createKnownBleUuidAliases,
17
17
  hasOnekeyCommunicationService,
18
18
  isOnekeyBluetoothDevice,
19
+ isPro2FamilyBleName,
19
20
  matchesKnownBleUuid,
20
21
  wait,
21
22
  } from '@onekeyfe/hd-shared';
@@ -90,8 +91,18 @@ const DEVICE_SCAN_TIMEOUT = 5000; // 5 seconds for device scanning
90
91
  const DEVICE_CHECK_INTERVAL = 500; // 500ms interval for periodic device checks
91
92
  const SERVICE_DISCOVERY_TIMEOUT = 10000; // 10 seconds for service discovery
92
93
  const BLE_CLEANUP_TIMEOUT = 250;
94
+ // A physical teardown must actually reach the OS before the device can return
95
+ // to a clean state; 250ms routinely declared success while CoreBluetooth was
96
+ // still disconnecting, leaving no trace when the teardown never completed.
97
+ const BLE_DISCONNECT_CONFIRM_TIMEOUT_MS = 3000;
93
98
  // Renderer release is logical only; this timer physically frees the device.
94
- const BLE_IDLE_DISCONNECT_MS = 3 * 60_000;
99
+ // Keep it SHORT: the Classic 1S goes protocol-deaf when a link is dropped
100
+ // after sitting idle for minutes (field logs 2026-08-19: every deaf window
101
+ // followed a 3-minute-idle disconnect, while disconnects right after traffic
102
+ // have never produced one across 6.5.0's per-call teardown history). A hot
103
+ // disconnect ~20s after the last operation stays inside the proven-safe
104
+ // pattern and also shrinks the window in which phones cannot see the device.
105
+ const BLE_IDLE_DISCONNECT_MS = 20_000;
95
106
  // Ceiling while a call is in flight: no outstanding write, but not forever.
96
107
  const BLE_BUSY_BACKSTOP_MS = 10 * 60_000;
97
108
 
@@ -257,6 +268,11 @@ async function initializeNoble(): Promise<void> {
257
268
  noble = require('@stoprocent/noble') as NobleModule;
258
269
  logger?.info('[NobleBLE] Noble library loaded');
259
270
 
271
+ // Register the process-lifetime state listener before any early return:
272
+ // the poweredOn fast path below would otherwise skip it for the whole
273
+ // session, leaving poweredOff cache/state reconciliation dead.
274
+ setupPersistentStateListener();
275
+
260
276
  // Wait for Bluetooth to be ready
261
277
  await new Promise<void>((resolve, reject) => {
262
278
  if (!noble) {
@@ -269,9 +285,6 @@ async function initializeNoble(): Promise<void> {
269
285
  return;
270
286
  }
271
287
 
272
- // Setup persistent state listener before initialization
273
- setupPersistentStateListener();
274
-
275
288
  const timeout = setTimeout(() => {
276
289
  reject(
277
290
  ERRORS.TypedError(HardwareErrorCode.RuntimeError, 'Bluetooth initialization timeout')
@@ -398,7 +411,21 @@ function armIdleDisconnect(
398
411
  logger?.info('[NobleBLE] Keep-alive timeout, disconnecting device', { deviceId, reason });
399
412
  const peripheral = connectedDevices.get(deviceId);
400
413
  const deviceName = peripheral?.advertisement?.localName || 'Unknown Device';
401
- const pending = disconnectDevice(deviceId)
414
+ // Unsubscribe CCCD before dropping the link, matching every other
415
+ // teardown path: the 1S leaves its notify session half-open when the
416
+ // link drops without an unsubscribe and then ignores application
417
+ // protocol traffic on NEW links for tens of minutes (field log
418
+ // 2026-08-19: the lone unsubscribe-skipping idle teardown caused a
419
+ // 6-attempt reconnect loop; unsubscribe-first teardowns reconnected
420
+ // instantly).
421
+ const pending = unsubscribeNotifications(deviceId)
422
+ .catch(error => {
423
+ logger?.warn('[NobleBLE] Keep-alive unsubscribe failed, disconnecting anyway', {
424
+ deviceId,
425
+ error: error instanceof Error ? error.message : String(error),
426
+ });
427
+ })
428
+ .then(() => disconnectDevice(deviceId))
402
429
  .then(() => {
403
430
  // A call is still in flight here; it must reject, not hang.
404
431
  // Both 'idle' and 'busy-backstop' report IdleKeepAlive on purpose:
@@ -508,6 +535,9 @@ function handleDeviceDisconnect(deviceId: string, webContents: WebContents): voi
508
535
 
509
536
  cleanupDevice(deviceId, webContents, {
510
537
  cleanupConnection: true,
538
+ // Same stale-object hazard as manual disconnect: an externally dropped
539
+ // link invalidates the cached peripheral for the next reconnect.
540
+ cleanupDiscoveredCache: true,
511
541
  sendDisconnectEvent: true,
512
542
  cancelOperations: true,
513
543
  reason: 'auto-disconnect',
@@ -761,6 +791,44 @@ async function transmitHexDataToDevice(
761
791
  }
762
792
 
763
793
  // Handle discovered device (for general enumeration only)
794
+ // A scan that finds nothing costs this much before the direct-connect
795
+ // fallback runs. Every advertisement in the 6.5.0 control logs arrived within
796
+ // 631ms, so this leaves ~2x headroom while keeping a miss cheap.
797
+ const BLE_COLD_CONNECT_SCAN_TIMEOUT_MS = 1500;
798
+
799
+ // Attempts before a link is written off as unable to serve the OneKey service.
800
+ const SERVICE_DISCOVERY_MAX_ATTEMPTS = 2;
801
+
802
+ // Advertised names, kept for the life of the process: device caches are purged
803
+ // on every disconnect, but the family a device belongs to never changes and
804
+ // decides which connection strategy is safe for it.
805
+ const bleNamesById = new Map<string, string>();
806
+
807
+ function rememberBleName(deviceId: string, name?: string | null): void {
808
+ const trimmed = name?.trim();
809
+ if (trimmed) {
810
+ bleNamesById.set(deviceId, trimmed);
811
+ }
812
+ }
813
+
814
+ function resolveBleName(deviceId: string): string | undefined {
815
+ const live =
816
+ connectedDevices.get(deviceId)?.advertisement?.localName?.trim() ||
817
+ discoveredDevices.get(deviceId)?.advertisement?.localName?.trim();
818
+ return live || bleNamesById.get(deviceId);
819
+ }
820
+
821
+ /**
822
+ * Pro2/Neo connect by id first: they are unaffected by the stale-session
823
+ * problem and advertise under Find My names a OneKey-filtered scan cannot
824
+ * match. Everything else — Classic family, and any device whose name is not
825
+ * known yet — scans first, because connecting by id can resolve a session the
826
+ * device no longer serves (see setupConnectionAndDiscoverServices).
827
+ */
828
+ function shouldConnectByIdFirst(deviceId: string): boolean {
829
+ return isPro2FamilyBleName(resolveBleName(deviceId));
830
+ }
831
+
764
832
  function handleDeviceDiscovered(peripheral: Peripheral): void {
765
833
  // Only process OneKey candidates for general discovery. Avoid logging every
766
834
  // ambient BLE peripheral; it makes Pro2 debugging hard to read.
@@ -770,6 +838,7 @@ function handleDeviceDiscovered(peripheral: Peripheral): void {
770
838
 
771
839
  const isNewDevice = !discoveredDevices.has(peripheral.id);
772
840
  discoveredDevices.set(peripheral.id, peripheral);
841
+ rememberBleName(peripheral.id, peripheral.advertisement?.localName);
773
842
  if (isNewDevice) {
774
843
  logger?.debug('[NobleBLE] OneKey BLE device discovered', {
775
844
  deviceId: peripheral.id,
@@ -804,7 +873,10 @@ async function waitForNobleScanStop(nobleInstance: NobleModule): Promise<void> {
804
873
 
805
874
  // Perform targeted scan for a specific device ID
806
875
  // Uses self-contained local listener pattern - no global state needed
807
- async function performTargetedScan(targetDeviceId: string): Promise<Peripheral | null> {
876
+ async function performTargetedScan(
877
+ targetDeviceId: string,
878
+ timeoutMs: number = NOBLE_BLE_TARGETED_SCAN_TIMEOUT_MS
879
+ ): Promise<Peripheral | null> {
808
880
  if (!noble) {
809
881
  throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, 'Noble not available');
810
882
  }
@@ -849,7 +921,7 @@ async function performTargetedScan(targetDeviceId: string): Promise<Peripheral |
849
921
  const timeoutId = setTimeout(() => {
850
922
  logger?.info('[NobleBLE] Targeted scan timeout for device:', targetDeviceId);
851
923
  finish(null).catch(reject);
852
- }, NOBLE_BLE_TARGETED_SCAN_TIMEOUT_MS);
924
+ }, timeoutMs);
853
925
 
854
926
  // Add local listener for this scan
855
927
  nobleInstance.on('discover', onDiscover);
@@ -1051,9 +1123,17 @@ async function discoverServicesAndCharacteristics(
1051
1123
 
1052
1124
  // Main discovery logic as async function
1053
1125
  const discoveryPromise = (async (): Promise<CharacteristicPair> => {
1054
- // Step 1: Discover ALL services (no filter Pro2 may use different service UUID)
1126
+ // Step 1: Discover the OneKey service by UUID. Filtering is not just a
1127
+ // narrowing: an unfiltered discovery is answered from the OS GATT cache, so
1128
+ // a device whose stack still advertises and accepts links but no longer
1129
+ // serves its application layer still looks healthy — the link comes up, the
1130
+ // cached services resolve, the protocol frame goes out and nothing ever
1131
+ // answers. A targeted query returns nothing in that state, which is what
1132
+ // 6.5.0 relied on to trip the recovery path below (retry, reset, fresh
1133
+ // scan) — the sequence that brings such a device back. Pro2/Neo expose the
1134
+ // same service UUID, and the selection below only ever accepts that one.
1055
1135
  const services = await new Promise<Service[]>((resolve, reject) => {
1056
- peripheral.discoverServices([], (error, svc) => {
1136
+ peripheral.discoverServices(ONEKEY_SERVICE_UUIDS, (error, svc) => {
1057
1137
  if (error) {
1058
1138
  logger?.error('[NobleBLE] Service discovery failed:', error);
1059
1139
  reject(ERRORS.TypedError(HardwareErrorCode.BleServiceNotFound, error.message));
@@ -1064,7 +1144,7 @@ async function discoverServicesAndCharacteristics(
1064
1144
  });
1065
1145
 
1066
1146
  if (!services || services.length === 0) {
1067
- throw ERRORS.TypedError(HardwareErrorCode.BleServiceNotFound, 'No services found');
1147
+ throw ERRORS.TypedError(HardwareErrorCode.BleServiceNotFound, 'No OneKey services found');
1068
1148
  }
1069
1149
 
1070
1150
  logger?.debug('[NobleBLE] services discovered', {
@@ -1248,12 +1328,14 @@ async function discoverServicesAndCharacteristicsWithRetry(
1248
1328
  deviceId,
1249
1329
  peripheralState: peripheral.state,
1250
1330
  attempt: attemptNumber,
1251
- maxRetries: 5,
1331
+ maxRetries: SERVICE_DISCOVERY_MAX_ATTEMPTS,
1252
1332
  targetUUIDs: ONEKEY_SERVICE_UUIDS,
1253
1333
  });
1254
1334
 
1255
1335
  if (attemptNumber > 1) {
1256
- logger?.info(`[NobleBLE] Service discovery retry attempt ${attemptNumber}/5`);
1336
+ logger?.info(
1337
+ `[NobleBLE] Service discovery retry attempt ${attemptNumber}/${SERVICE_DISCOVERY_MAX_ATTEMPTS}`
1338
+ );
1257
1339
  }
1258
1340
 
1259
1341
  // Verify connection state before attempting service discovery
@@ -1267,20 +1349,32 @@ async function discoverServicesAndCharacteristicsWithRetry(
1267
1349
  try {
1268
1350
  return await discoverServicesAndCharacteristics(peripheral);
1269
1351
  } catch (error) {
1270
- logger?.error(`[NobleBLE] No services found (attempt ${attemptNumber}/5)`);
1352
+ logger?.error(
1353
+ `[NobleBLE] No services found (attempt ${attemptNumber}/${SERVICE_DISCOVERY_MAX_ATTEMPTS})`
1354
+ );
1271
1355
 
1272
- if (attemptNumber < 5) {
1273
- logger?.error(`[NobleBLE] Will retry service discovery (attempt ${attemptNumber + 1}/5)`);
1356
+ if (attemptNumber < SERVICE_DISCOVERY_MAX_ATTEMPTS) {
1357
+ logger?.error(
1358
+ `[NobleBLE] Will retry service discovery (attempt ${
1359
+ attemptNumber + 1
1360
+ }/${SERVICE_DISCOVERY_MAX_ATTEMPTS})`
1361
+ );
1274
1362
  }
1275
1363
 
1276
1364
  throw error; // p-retry will handle the retry logic
1277
1365
  }
1278
1366
  },
1279
1367
  {
1280
- retries: 4, // Total 5 attempts (initial + 4 retries)
1281
- factor: 1.5, // Exponential backoff: 1000ms 1500ms 2250ms 3000ms
1282
- minTimeout: 1000, // Start with 1 second delay
1283
- maxTimeout: 3000, // Maximum 3 seconds delay
1368
+ // One retry, not four. An empty result here is the signature of a device
1369
+ // whose stack no longer serves its application layer, and retrying the
1370
+ // same link has never recovered it — every observed run failed all the
1371
+ // way through. The recovery is the teardown and cold reconnect the caller
1372
+ // performs afterwards, so reaching it sooner is what shortens the wait.
1373
+ // The single retry stays for a genuinely transient miss.
1374
+ retries: SERVICE_DISCOVERY_MAX_ATTEMPTS - 1,
1375
+ factor: 1.5,
1376
+ minTimeout: 500,
1377
+ maxTimeout: 3000,
1284
1378
  onFailedAttempt: error => {
1285
1379
  // This runs after each failed attempt
1286
1380
  logger?.error(`[NobleBLE] Service discovery attempt ${error.attemptNumber} failed:`, {
@@ -1305,26 +1399,45 @@ async function setupConnectionAndDiscoverServices(
1305
1399
  deviceId: string,
1306
1400
  webContents: WebContents
1307
1401
  ): Promise<CharacteristicPair> {
1308
- setupDisconnectListener(peripheral, deviceId, webContents);
1309
-
1402
+ // Reset the link before any protocol traffic reaches the device. 6.5.0 did
1403
+ // this on every cold setup and never produced a protocol-deaf Classic 1S
1404
+ // (control log 2026-08-20: 16/16 links answered within ~1s, including after
1405
+ // a 15-minute idle). Demoting it to a discovery-failure fallback removed the
1406
+ // reset entirely for this device, because discovery always succeeds: the link
1407
+ // comes up, GATT resolves from cache, and the device then answers nothing on
1408
+ // a session it no longer serves. Costs ~1.3s per cold setup; a kept-alive
1409
+ // link with an intact subscription returns before reaching here, so reuse
1410
+ // inside a workflow is unaffected.
1310
1411
  try {
1311
- return await discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId);
1312
- } catch (initialError) {
1313
- logger?.info('[NobleBLE] Direct service discovery failed, retrying after reconnect', {
1314
- deviceId,
1315
- error: initialError,
1316
- });
1412
+ await forceReconnectPeripheral(peripheral, deviceId);
1413
+ } catch (resetError) {
1414
+ // A failed reset must not abort the attempt: discovery on the existing
1415
+ // link, then the fresh-scan fallback, still have a chance to recover.
1416
+ logger?.error('[NobleBLE] Connection reset before discovery failed, continuing', resetError);
1317
1417
  }
1318
-
1319
- await forceReconnectPeripheral(peripheral, deviceId);
1320
1418
  setupDisconnectListener(peripheral, deviceId, webContents);
1419
+
1321
1420
  try {
1322
1421
  return await discoverServicesAndCharacteristicsWithRetry(peripheral, deviceId);
1323
- } catch (reconnectError) {
1324
- logger?.error(
1325
- '[NobleBLE] Service discovery failed after reconnect, attempting fresh scan...',
1326
- reconnectError
1327
- );
1422
+ } catch (discoveryError) {
1423
+ // A connected peripheral does not advertise, so the fresh scan below would
1424
+ // only run out its timeout. Drop the link first, then rescan: the cold
1425
+ // reconnect is what recovers a device whose stack stopped serving its
1426
+ // application layer. Recover here rather than throwing to the caller —
1427
+ // one acquire pays ~2s for the rescan, while a thrown error costs the
1428
+ // renderer a full retry round trip.
1429
+ if (peripheral.state === 'connected') {
1430
+ logger?.error(
1431
+ '[NobleBLE] Service discovery failed on a live link, dropping it before the fresh scan',
1432
+ discoveryError
1433
+ );
1434
+ await disconnectDevice(deviceId).catch(() => undefined);
1435
+ } else {
1436
+ logger?.error(
1437
+ '[NobleBLE] Service discovery failed, attempting fresh scan...',
1438
+ discoveryError
1439
+ );
1440
+ }
1328
1441
  return freshScanAndDiscover(deviceId, webContents);
1329
1442
  }
1330
1443
  }
@@ -1413,10 +1526,7 @@ async function connectDevice(deviceId: string, webContents: WebContents): Promis
1413
1526
  // enumerate clears the discovery map; a kept-alive link outlives it.
1414
1527
  let peripheral = discoveredDevices.get(deviceId) ?? connectedDevices.get(deviceId);
1415
1528
 
1416
- // If device not discovered, try a targeted scan for this specific device
1417
1529
  if (!peripheral) {
1418
- logger?.info('[NobleBLE] Device not discovered, attempting targeted scan for:', deviceId);
1419
-
1420
1530
  // Initialize Noble if not already done
1421
1531
  if (!noble) {
1422
1532
  await initializeNoble();
@@ -1426,27 +1536,46 @@ async function connectDevice(deviceId: string, webContents: WebContents): Promis
1426
1536
  throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, 'Noble not available');
1427
1537
  }
1428
1538
 
1429
- // Reaches a bonded device that is not advertising; else falls to the scan.
1430
- peripheral = await tryDirectConnectById(deviceId);
1431
- if (peripheral) {
1432
- discoveredDevices.set(deviceId, peripheral);
1433
- }
1434
- }
1539
+ // A live advertisement proves the device holds no link and will open a
1540
+ // fresh session; connecting by id resolves through the OS cache instead
1541
+ // and can hand back a session the device no longer serves (see
1542
+ // setupConnectionAndDiscoverServices). Scanning is also the faster of the
1543
+ // two when the device does advertise: ~96ms median against ~784ms for
1544
+ // connect-by-id across the field logs. Pro2/Neo keep connect-by-id first
1545
+ // because they are unaffected and may advertise under an unmatchable Find
1546
+ // My name.
1547
+ const byIdFirst = shouldConnectByIdFirst(deviceId);
1548
+ logger?.info('[NobleBLE] Resolving device for cold connect', {
1549
+ deviceId,
1550
+ name: resolveBleName(deviceId) ?? 'unknown',
1551
+ strategy: byIdFirst ? 'connect-by-id-first' : 'scan-first',
1552
+ });
1435
1553
 
1436
- if (!peripheral) {
1437
- // Perform a targeted scan to find the specific device
1438
- try {
1439
- const foundPeripheral = await performTargetedScan(deviceId);
1440
- if (!foundPeripheral) {
1441
- throw ERRORS.TypedError(
1442
- HardwareErrorCode.DeviceNotFound,
1443
- `Device ${deviceId} not found even after targeted scan`
1444
- );
1554
+ const scanForPeripheral = async () => {
1555
+ try {
1556
+ return (await performTargetedScan(deviceId, BLE_COLD_CONNECT_SCAN_TIMEOUT_MS)) ?? undefined;
1557
+ } catch (scanError) {
1558
+ logger?.info('[NobleBLE] Targeted scan failed', {
1559
+ deviceId,
1560
+ error: scanError instanceof Error ? scanError.message : String(scanError),
1561
+ });
1562
+ return undefined;
1563
+ }
1564
+ };
1565
+
1566
+ const connectById = async () => {
1567
+ const found = await tryDirectConnectById(deviceId);
1568
+ if (found) {
1569
+ discoveredDevices.set(deviceId, found);
1445
1570
  }
1446
- peripheral = foundPeripheral;
1447
- } catch (error) {
1448
- logger?.error('[NobleBLE] Targeted scan failed:', error);
1449
- throw error;
1571
+ return found;
1572
+ };
1573
+
1574
+ peripheral = byIdFirst ? await connectById() : await scanForPeripheral();
1575
+ if (!peripheral) {
1576
+ // The preferred route came up empty: not advertising (held elsewhere, or
1577
+ // silent), or not reachable by id. Try the other one before giving up.
1578
+ peripheral = byIdFirst ? await scanForPeripheral() : await connectById();
1450
1579
  }
1451
1580
  }
1452
1581
 
@@ -1455,6 +1584,10 @@ async function connectDevice(deviceId: string, webContents: WebContents): Promis
1455
1584
  throw ERRORS.TypedError(HardwareErrorCode.DeviceNotFound, `Device ${deviceId} not found`);
1456
1585
  }
1457
1586
 
1587
+ // Also covers the connect-by-id route, whose simulated discovery carries no
1588
+ // service UUIDs and therefore never reaches handleDeviceDiscovered.
1589
+ rememberBleName(deviceId, peripheral.advertisement?.localName);
1590
+
1458
1591
  logger?.info('[NobleBLE] Connecting to device:', deviceId);
1459
1592
 
1460
1593
  // Check if device is already connected
@@ -1575,9 +1708,14 @@ async function connectDevice(deviceId: string, webContents: WebContents): Promis
1575
1708
  resolve();
1576
1709
  } catch (setupError) {
1577
1710
  logger?.error('[NobleBLE] Connection setup failed:', setupError);
1578
- connectedPeripheral.disconnect(() => {
1579
- reject(setupError);
1580
- });
1711
+ // Never reject from inside a raw disconnect callback: noble only fires
1712
+ // it on a real 'disconnect' event, so a peripheral that is already
1713
+ // down leaves this promise — and the renderer acquire awaiting it —
1714
+ // pending forever. disconnectDevice always settles (it no-ops on an
1715
+ // unknown peripheral and caps the confirm wait).
1716
+ disconnectDevice(deviceId)
1717
+ .catch(() => undefined)
1718
+ .then(() => reject(setupError));
1581
1719
  }
1582
1720
  });
1583
1721
  });
@@ -1597,11 +1735,18 @@ async function disconnectDevice(deviceId: string): Promise<void> {
1597
1735
  }
1598
1736
 
1599
1737
  await runBleCallbackOperation(callback => peripheral.disconnect(() => callback()), {
1600
- timeoutMs: BLE_CLEANUP_TIMEOUT,
1738
+ timeoutMs: BLE_DISCONNECT_CONFIRM_TIMEOUT_MS,
1601
1739
  timeoutBehavior: 'resolve',
1602
1740
  });
1741
+ if (peripheral.state === 'connected') {
1742
+ logger?.warn('[NobleBLE] Physical disconnect did not confirm in time', { deviceId });
1743
+ }
1603
1744
  cleanupDevice(deviceId, undefined, {
1604
1745
  cleanupConnection: true,
1746
+ // macOS returns zero GATT services when a previously-disconnected
1747
+ // peripheral object is reconnected; drop the discovery cache so the next
1748
+ // connect resolves a fresh peripheral (direct connect by id, or scan).
1749
+ cleanupDiscoveredCache: true,
1605
1750
  sendDisconnectEvent: false,
1606
1751
  cancelOperations: true,
1607
1752
  reason: 'manual-disconnect',
@@ -1742,9 +1887,14 @@ async function subscribeNotifications(
1742
1887
  });
1743
1888
  }
1744
1889
 
1890
+ const subscribeStartedAt = Date.now();
1745
1891
  try {
1746
1892
  await rebuildAppSubscription(deviceId, notifyCharacteristic);
1747
1893
  subscribedDevices.set(deviceId, true);
1894
+ logger?.info('[NobleBLE] Notification subscription active', {
1895
+ deviceId,
1896
+ ms: Date.now() - subscribeStartedAt,
1897
+ });
1748
1898
  } finally {
1749
1899
  // 🔒 CRITICAL: Always clear operation state (even on error)
1750
1900
  subscriptionOperations.set(deviceId, 'idle');
@@ -1927,10 +2077,12 @@ export function setupNobleBleHandlers(webContents: WebContents): void {
1927
2077
  }
1928
2078
 
1929
2079
  await stopScanning().catch(() => undefined);
1930
- if (noble && persistentStateListener) {
1931
- noble.removeListener('stateChange', persistentStateListener);
1932
- persistentStateListener = null;
1933
- }
2080
+ // persistentStateListener is process-lifetime, NOT per-window: this
2081
+ // destroy handler also fires on a renderer soft restart, and removing
2082
+ // the listener here permanently killed poweredOff/poweredOn
2083
+ // reconciliation for the rest of the process (nothing re-registers it:
2084
+ // initializeNoble early-returns once noble is loaded). The null-guard
2085
+ // in setupPersistentStateListener keeps it deduped to one instance.
1934
2086
  cleanupNobleListeners();
1935
2087
  discoveredDevices.clear();
1936
2088
  safeLog(logger, 'info', 'Noble BLE cleanup completed');
@@ -39,6 +39,7 @@ export interface NobleModule {
39
39
  export interface Logger {
40
40
  info(message: string, ...args: any[]): void;
41
41
  debug(message: string, ...args: any[]): void;
42
+ warn(message: string, ...args: any[]): void;
42
43
  error(message: string, ...args: any[]): void;
43
44
  }
44
45