@onekeyfe/hd-transport-react-native 1.2.0-alpha.18 → 1.2.0-alpha.180

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.
@@ -2,11 +2,17 @@ import { EventEmitter } from 'events';
2
2
  import transportPackage, {
3
3
  PROTOCOL_V2_CHANNEL_BLE_UART,
4
4
  ProtocolV2,
5
- bytesToHex,
5
+ TRANSPORT_EVENT,
6
6
  } from '@onekeyfe/hd-transport';
7
- import { HardwareErrorCode } from '@onekeyfe/hd-shared';
7
+ import { HardwareErrorCode, createDeferred } from '@onekeyfe/hd-shared';
8
8
 
9
- import ReactNativeBleTransport from '../index';
9
+ import ReactNativeBleTransport, {
10
+ BLE_NATIVE_TEARDOWN_TIMEOUT_MS,
11
+ BLE_WRITE_PACKET_TIMEOUT_MS,
12
+ configureProtocolV2BleTuning,
13
+ getFirmwareUploadWriteRetryType,
14
+ resetProtocolV2BleTuning,
15
+ } from '../index';
10
16
 
11
17
  jest.mock(
12
18
  'react-native',
@@ -28,6 +34,7 @@ jest.mock('react-native-ble-plx', () => ({
28
34
  CharacteristicNotFound: 404,
29
35
  },
30
36
  BleManager: jest.fn(),
37
+ ConnectionPriority: { Balanced: 0, High: 1, LowPower: 2 },
31
38
  ScanMode: { LowLatency: 2 },
32
39
  }));
33
40
 
@@ -41,11 +48,17 @@ jest.mock('../subscribeBleOn', () => ({
41
48
  subscribeBleOn: jest.fn(() => Promise.resolve()),
42
49
  }));
43
50
 
51
+ const setPlatformOS = (os: 'ios' | 'android') => {
52
+ const reactNative: { Platform: { OS: string } } = jest.requireMock('react-native');
53
+ reactNative.Platform.OS = os;
54
+ };
55
+
44
56
  const { parseConfigure } = transportPackage;
45
57
 
46
58
  const protocolV1Schema = {
47
59
  nested: {
48
60
  Initialize: { fields: {} },
61
+ GetFeatures: { fields: {} },
49
62
  Success: {
50
63
  fields: {
51
64
  message: { type: 'string', id: 1 },
@@ -55,6 +68,7 @@ const protocolV1Schema = {
55
68
  values: {
56
69
  MessageType_Initialize: 1,
57
70
  MessageType_Success: 2,
71
+ MessageType_GetFeatures: 55,
58
72
  },
59
73
  },
60
74
  },
@@ -62,11 +76,13 @@ const protocolV1Schema = {
62
76
 
63
77
  const protocolV2Schema = {
64
78
  nested: {
79
+ ProtocolInfoRequest: { fields: {} },
65
80
  Ping: {
66
81
  fields: {
67
82
  message: { type: 'string', id: 1 },
68
83
  },
69
84
  },
85
+ DeviceInfoGet: { fields: {} },
70
86
  FileWrite: { fields: {} },
71
87
  Success: {
72
88
  fields: {
@@ -75,8 +91,10 @@ const protocolV2Schema = {
75
91
  },
76
92
  MessageType: {
77
93
  values: {
94
+ MessageType_ProtocolInfoRequest: 60200,
78
95
  MessageType_Ping: 60206,
79
96
  MessageType_Success: 60207,
97
+ MessageType_DeviceInfoGet: 60600,
80
98
  MessageType_FileWrite: 60805,
81
99
  },
82
100
  },
@@ -88,9 +106,16 @@ const schemas = {
88
106
  protocolV2: parseConfigure(protocolV2Schema),
89
107
  };
90
108
 
91
- const createHarness = () => {
109
+ const createHarness = ({
110
+ deviceName = 'OneKey Pro 2',
111
+ isWritableWithResponse = true,
112
+ }: {
113
+ deviceName?: string;
114
+ isWritableWithResponse?: boolean;
115
+ } = {}) => {
92
116
  const uuid = 'rn-pro2-id';
93
117
  const sentSeqs: number[] = [];
118
+ let responseSeq = 0;
94
119
  let shouldRespond = true;
95
120
  let notifyCallback:
96
121
  | ((
@@ -98,6 +123,7 @@ const createHarness = () => {
98
123
  characteristic: { value: string } | null
99
124
  ) => void)
100
125
  | undefined;
126
+ let disconnectCallback: (() => void) | undefined;
101
127
  const notifyCharacteristic = {
102
128
  uuid: '0003',
103
129
  deviceID: uuid,
@@ -111,11 +137,12 @@ const createHarness = () => {
111
137
  const frame = Buffer.from(base64, 'base64');
112
138
  sentSeqs.push(frame[6]);
113
139
  if (shouldRespond) {
140
+ responseSeq += 1;
114
141
  const response = ProtocolV2.encodeFrame(
115
142
  schemas,
116
143
  'Success',
117
144
  { message: 'ok' },
118
- { router: PROTOCOL_V2_CHANNEL_BLE_UART }
145
+ { router: PROTOCOL_V2_CHANNEL_BLE_UART, seq: responseSeq }
119
146
  );
120
147
  notifyCallback?.(null, { value: Buffer.from(response).toString('base64') });
121
148
  }
@@ -124,36 +151,51 @@ const createHarness = () => {
124
151
  const writeCharacteristic = {
125
152
  uuid: '0002',
126
153
  deviceID: uuid,
127
- isWritableWithResponse: true,
154
+ isWritableWithResponse,
128
155
  isWritableWithoutResponse: true,
129
156
  writeWithResponse: jest.fn(handleWrite),
130
157
  writeWithoutResponse: jest.fn(handleWrite),
131
158
  };
132
159
  const device = {
133
160
  id: uuid,
134
- name: 'OneKey Pro 2',
135
- localName: 'OneKey Pro 2',
136
- serviceUUIDs: ['fffd'],
161
+ name: deviceName,
162
+ localName: deviceName,
163
+ mtu: 247,
164
+ serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
137
165
  isConnected: jest.fn(() => Promise.resolve(true)),
138
- onDisconnected: jest.fn(() => ({ remove: jest.fn() })),
139
- };
166
+ cancelConnection: jest.fn(() => Promise.resolve()),
167
+ onDisconnected: jest.fn(callback => {
168
+ disconnectCallback = callback;
169
+ return { remove: jest.fn() };
170
+ }),
171
+ } as any;
172
+ device.requestMTU = jest.fn(() => Promise.resolve(device));
173
+ device.requestConnectionPriority = jest.fn(() => Promise.resolve(device));
140
174
  const bleManager = {
141
175
  devices: jest.fn(() => Promise.resolve([device])),
142
176
  connectedDevices: jest.fn(() => Promise.resolve([])),
143
177
  cancelTransaction: jest.fn(() => Promise.resolve()),
178
+ cancelDeviceConnection: jest.fn(() => Promise.resolve()),
179
+ destroy: jest.fn(),
144
180
  };
145
181
  const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
182
+ const emitter = new EventEmitter();
183
+ const logger = { debug: jest.fn(), error: jest.fn() };
146
184
  transport.blePlxManager = bleManager;
147
185
  transport.resolveCharacteristics = jest.fn(() =>
148
186
  Promise.resolve({ writeCharacteristic, notifyCharacteristic })
149
187
  );
150
- transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
188
+ transport.init(logger, emitter);
151
189
  transport.configure(protocolV1Schema);
152
190
  transport.configureProtocolV2(protocolV2Schema);
153
191
 
154
192
  return {
155
193
  transport,
194
+ emitter,
195
+ logger,
156
196
  uuid,
197
+ device,
198
+ bleManager,
157
199
  sentSeqs,
158
200
  writeCharacteristic,
159
201
  setShouldRespond(value: boolean) {
@@ -162,30 +204,646 @@ const createHarness = () => {
162
204
  emitMonitorError(error: Error & { reason?: string }) {
163
205
  notifyCallback?.(error, null);
164
206
  },
207
+ emitDisconnect() {
208
+ disconnectCallback?.();
209
+ },
210
+ };
211
+ };
212
+
213
+ const createV1Harness = ({
214
+ respondOnWriteCount = 1,
215
+ isWritableWithResponse = true,
216
+ }: {
217
+ respondOnWriteCount?: number | number[];
218
+ isWritableWithResponse?: boolean;
219
+ } = {}) => {
220
+ const uuid = 'rn-classic-id';
221
+ const notifySubscriptionRemovers: jest.Mock[] = [];
222
+ const disconnectSubscriptionRemovers: jest.Mock[] = [];
223
+ let notifyCallback:
224
+ | ((error: Error | null, characteristic: { value: string } | null) => void)
225
+ | undefined;
226
+ const notifyCharacteristic = {
227
+ uuid: '0003',
228
+ deviceID: uuid,
229
+ isNotifiable: true,
230
+ monitor: jest.fn(callback => {
231
+ notifyCallback = callback;
232
+ const remove = jest.fn();
233
+ notifySubscriptionRemovers.push(remove);
234
+ return { remove };
235
+ }),
236
+ };
237
+ let writeCount = 0;
238
+ const responseWriteCounts = new Set(
239
+ Array.isArray(respondOnWriteCount) ? respondOnWriteCount : [respondOnWriteCount]
240
+ );
241
+ const handleWrite = () => {
242
+ writeCount += 1;
243
+ if (responseWriteCounts.has(writeCount)) {
244
+ notifyCallback?.(null, {
245
+ value: Buffer.from('3f23230002000000040a026f6b', 'hex').toString('base64'),
246
+ });
247
+ }
248
+ return Promise.resolve();
249
+ };
250
+ const writeCharacteristic = {
251
+ uuid: '0002',
252
+ deviceID: uuid,
253
+ isWritableWithResponse,
254
+ isWritableWithoutResponse: true,
255
+ writeWithResponse: jest.fn(handleWrite),
256
+ writeWithoutResponse: jest.fn(handleWrite),
257
+ };
258
+ const device = {
259
+ id: uuid,
260
+ name: 'OneKey Classic',
261
+ localName: 'OneKey Classic',
262
+ mtu: 247,
263
+ serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
264
+ isConnected: jest.fn(() => Promise.resolve(true)),
265
+ cancelConnection: jest.fn(() => Promise.resolve()),
266
+ onDisconnected: jest.fn(() => {
267
+ const remove = jest.fn();
268
+ disconnectSubscriptionRemovers.push(remove);
269
+ return { remove };
270
+ }),
271
+ } as any;
272
+ device.requestMTU = jest.fn(() => Promise.resolve(device));
273
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 });
274
+ const bleManager = {
275
+ devices: jest.fn(() => Promise.resolve([device])),
276
+ connectedDevices: jest.fn(() => Promise.resolve([])),
277
+ cancelTransaction: jest.fn(() => Promise.resolve()),
278
+ };
279
+ transport.blePlxManager = bleManager as any;
280
+ transport.resolveCharacteristics = jest.fn(() =>
281
+ Promise.resolve({ writeCharacteristic, notifyCharacteristic })
282
+ );
283
+ transport.init({ debug: jest.fn(), error: jest.fn() }, new EventEmitter());
284
+ transport.configure(protocolV1Schema);
285
+ transport.configureProtocolV2(protocolV2Schema);
286
+ return {
287
+ transport,
288
+ uuid,
289
+ device,
290
+ bleManager,
291
+ writeCharacteristic,
292
+ notifySubscriptionRemovers,
293
+ disconnectSubscriptionRemovers,
165
294
  };
166
295
  };
167
296
 
168
297
  describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
169
- test('keeps the Protocol V2 sequence across probe and the next call', async () => {
298
+ test('does not classify disconnects as retryable firmware writes', () => {
299
+ expect(
300
+ getFirmwareUploadWriteRetryType({
301
+ errorCode: 205,
302
+ message: 'Device disconnected after write',
303
+ })
304
+ ).toBeNull();
305
+ });
306
+
307
+ test.each(['status 143', 'status:143', 'status = 143', 'GATT_CONGESTED'])(
308
+ 'classifies %s as transient GATT congestion',
309
+ message => {
310
+ expect(getFirmwareUploadWriteRetryType({ message })).toBe('congested');
311
+ }
312
+ );
313
+
314
+ test('handles long uncontrolled status messages without a backtracking regular expression', () => {
315
+ const message = `status${' '.repeat(100_000)}142`;
316
+
317
+ expect(getFirmwareUploadWriteRetryType({ message })).toBeNull();
318
+ });
319
+
320
+ test('keeps another device reader when releasing a device with an active V1 call', async () => {
321
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
322
+ const activeV1Call = createDeferred<string>();
323
+ const otherDeviceReader = createDeferred<Uint8Array>();
324
+ activeV1Call.promise.catch(() => undefined);
325
+ otherDeviceReader.promise.catch(() => undefined);
326
+ transport.runPromise = activeV1Call;
327
+ transport.runPromiseDeviceId = 'device-a';
328
+ transport.protocolV2FramePromises.set('device-b', otherDeviceReader);
329
+
330
+ await transport.releaseNative('device-a', true);
331
+
332
+ expect(transport.protocolV2FramePromises.get('device-b')).toBe(otherDeviceReader);
333
+ });
334
+
335
+ test('rejects a pending reader when its device frame state resets', async () => {
336
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
337
+ const reader = createDeferred<Uint8Array>();
338
+ transport.protocolV2FramePromises.set('device-a', reader);
339
+ const result = Promise.race([
340
+ reader.promise.then(
341
+ () => 'resolved',
342
+ () => 'rejected'
343
+ ),
344
+ new Promise(resolve => {
345
+ setTimeout(() => resolve('pending'), 20);
346
+ }),
347
+ ]);
348
+
349
+ transport.resetProtocolV2Frames('device-a');
350
+
351
+ await expect(result).resolves.toBe('rejected');
352
+ });
353
+
354
+ test('keeps the legacy default BLE scan timeout', () => {
355
+ expect(new ReactNativeBleTransport({}).scanTimeout).toBe(3000);
356
+ });
357
+
358
+ test('uses withResponse for consecutive iOS Protocol V1 control commands without releasing', async () => {
359
+ const { transport, uuid, writeCharacteristic } = createV1Harness({
360
+ respondOnWriteCount: [1, 2],
361
+ });
362
+
363
+ await expect(transport.acquire({ uuid, expectedProtocol: 'V1' })).resolves.toEqual({
364
+ uuid,
365
+ protocolType: 'V1',
366
+ });
367
+ const releaseNative = jest.spyOn(transport as any, 'releaseNative');
368
+ expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
369
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
370
+
371
+ await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 50 })).resolves.toBeDefined();
372
+ await expect(transport.call(uuid, 'GetFeatures', {}, { timeoutMs: 50 })).resolves.toBeDefined();
373
+
374
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(2);
375
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
376
+ expect(releaseNative).not.toHaveBeenCalled();
377
+ await transport.release(uuid, true);
378
+ });
379
+
380
+ test('falls back to withoutResponse for an iOS Protocol V1 control command when required', async () => {
381
+ const { transport, uuid, writeCharacteristic } = createV1Harness({
382
+ isWritableWithResponse: false,
383
+ });
384
+
385
+ await transport.acquire({ uuid, expectedProtocol: 'V1' });
386
+ await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 50 })).resolves.toBeDefined();
387
+
388
+ expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
389
+ expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(1);
390
+ await transport.release(uuid, true);
391
+ });
392
+
393
+ test('does not resend a failed iOS Protocol V1 control write without response', async () => {
394
+ const { transport, uuid, writeCharacteristic } = createV1Harness();
395
+ const writeError = new Error('write with response failed');
396
+
397
+ await transport.acquire({ uuid, expectedProtocol: 'V1' });
398
+ writeCharacteristic.writeWithResponse.mockRejectedValueOnce(writeError);
399
+
400
+ await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 50 })).rejects.toMatchObject({
401
+ errorCode: HardwareErrorCode.BleWriteCharacteristicError,
402
+ });
403
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(1);
404
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
405
+ await transport.release(uuid, true);
406
+ });
407
+
408
+ test('detects Protocol V2 on iOS without using the BLE name as a protocol hint', async () => {
409
+ const { transport, uuid, device, sentSeqs, writeCharacteristic } = createHarness({
410
+ deviceName: 'Pro2 6E9E',
411
+ });
412
+
413
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
414
+ uuid,
415
+ protocolType: 'V2',
416
+ });
417
+ expect(device.requestMTU).toHaveBeenCalledWith(247);
418
+ expect(writeCharacteristic.writeWithResponse.mock.calls.length).toBeGreaterThan(1);
419
+
420
+ await expect(
421
+ transport.call(uuid, 'Ping', { message: 'first-core-command' })
422
+ ).resolves.toBeDefined();
423
+ expect(sentSeqs.filter(seq => seq > 0)).toEqual([1, 2]);
424
+ await transport.release(uuid, true);
425
+ });
426
+
427
+ test('physically refreshes an uncached Protocol V2 firmware install link without Ping', async () => {
428
+ const { transport, uuid, device, bleManager, writeCharacteristic } = createHarness();
429
+ const probeProtocolV2 = jest.spyOn(transport as any, 'probeProtocolV2');
430
+ (transport as any).sessionProtocols.set(uuid, 'V2');
431
+ device.connect = jest.fn().mockResolvedValue(device);
432
+ device.isConnected.mockResolvedValueOnce(false);
433
+
434
+ await expect(
435
+ transport.acquire({ uuid, expectedProtocol: 'V2', skipProtocolProbe: true })
436
+ ).resolves.toEqual({
437
+ uuid,
438
+ protocolType: 'V2',
439
+ });
440
+
441
+ expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(uuid);
442
+ expect(device.cancelConnection).not.toHaveBeenCalled();
443
+ expect(device.connect).toHaveBeenCalled();
444
+ expect(probeProtocolV2).not.toHaveBeenCalled();
445
+ expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
446
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
447
+ expect(transport.getProtocolType(uuid)).toBe('V2');
448
+ await transport.release(uuid, true);
449
+ });
450
+
451
+ test('refreshes a cached firmware install connection instead of trusting GATT state', async () => {
452
+ const { transport, uuid, device, bleManager, writeCharacteristic } = createHarness();
453
+ const probeProtocolV2 = jest.spyOn(transport as any, 'probeProtocolV2');
454
+
455
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
456
+ device.connect = jest.fn().mockResolvedValue(device);
457
+ device.isConnected.mockResolvedValueOnce(false);
458
+ writeCharacteristic.writeWithResponse.mockClear();
459
+ writeCharacteristic.writeWithoutResponse.mockClear();
460
+
461
+ await expect(
462
+ transport.acquire({ uuid, expectedProtocol: 'V2', skipProtocolProbe: true })
463
+ ).resolves.toEqual({
464
+ uuid,
465
+ protocolType: 'V2',
466
+ });
467
+
468
+ expect(bleManager.cancelDeviceConnection).toHaveBeenCalledWith(uuid);
469
+ expect(device.cancelConnection).toHaveBeenCalled();
470
+ expect(device.connect).toHaveBeenCalled();
471
+ expect(probeProtocolV2).toHaveBeenCalledTimes(1);
472
+ expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
473
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
474
+ await transport.release(uuid, true);
475
+ });
476
+
477
+ test('rejects no-probe acquire before the BLE endpoint has confirmed a protocol', async () => {
478
+ const { transport, uuid } = createHarness();
479
+
480
+ await expect(
481
+ transport.acquire({ uuid, expectedProtocol: 'V2', skipProtocolProbe: true })
482
+ ).rejects.toThrow('previously confirmed protocol');
483
+
484
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
485
+ });
486
+
487
+ test.each(['ios', 'android'] as const)(
488
+ 'keeps a first expected Protocol V2 probe miss retryable on %s',
489
+ async platform => {
490
+ setPlatformOS(platform);
491
+ const { transport, uuid, device } = createHarness();
492
+ jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(false);
493
+
494
+ await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
495
+ errorCode: HardwareErrorCode.RuntimeError,
496
+ });
497
+
498
+ expect(device.cancelConnection).not.toHaveBeenCalled();
499
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
500
+ }
501
+ );
502
+
503
+ test.each(['ios', 'android'] as const)(
504
+ 'keeps a second expected Protocol V2 probe miss retryable on %s',
505
+ async platform => {
506
+ setPlatformOS(platform);
507
+ const { transport, uuid, device } = createHarness();
508
+ jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(false);
509
+
510
+ await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
511
+ errorCode: HardwareErrorCode.RuntimeError,
512
+ });
513
+ await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
514
+ errorCode: HardwareErrorCode.RuntimeError,
515
+ });
516
+
517
+ expect(device.cancelConnection).not.toHaveBeenCalled();
518
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
519
+ }
520
+ );
521
+
522
+ test.each(['ios', 'android'] as const)(
523
+ 'reports a stale bond on %s when a previously confirmed Protocol V2 device stops responding',
524
+ async platform => {
525
+ setPlatformOS(platform);
526
+ const { transport, uuid, device } = createHarness();
527
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
528
+ await transport.release(uuid, true);
529
+ jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(false);
530
+
531
+ await expect(transport.acquire({ uuid, expectedProtocol: 'V2' })).rejects.toMatchObject({
532
+ errorCode: HardwareErrorCode.BleDeviceBondError,
533
+ });
534
+
535
+ expect(device.cancelConnection).toHaveBeenCalled();
536
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
537
+ }
538
+ );
539
+
540
+ test('waits for an in-flight release before reacquiring the same device', async () => {
541
+ const { transport, uuid } = createHarness();
542
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
543
+ const releaseGate = createDeferred<void>();
544
+ const releaseStarted = createDeferred<void>();
545
+ const { protocolV2Links } = transport as any;
546
+ const invalidateLink = protocolV2Links.invalidateLink.bind(protocolV2Links);
547
+ jest
548
+ .spyOn(protocolV2Links, 'invalidateLink')
549
+ .mockImplementationOnce(async (...args: unknown[]) => {
550
+ releaseStarted.resolve();
551
+ await releaseGate.promise;
552
+ return invalidateLink(...args);
553
+ });
554
+
555
+ const release = transport.release(uuid, true);
556
+ await releaseStarted.promise;
557
+ let reacquired = false;
558
+ const acquire = transport.acquire({ uuid, expectedProtocol: 'V2' }).then(result => {
559
+ reacquired = true;
560
+ return result;
561
+ });
562
+
563
+ await Promise.resolve();
564
+ expect(reacquired).toBe(false);
565
+
566
+ releaseGate.resolve();
567
+ await release;
568
+ await expect(acquire).resolves.toEqual({ uuid, protocolType: 'V2' });
569
+ await expect(transport.call(uuid, 'Ping', { message: 'after-release' })).resolves.toMatchObject(
570
+ {
571
+ type: 'Success',
572
+ message: { message: 'ok' },
573
+ }
574
+ );
575
+ });
576
+
577
+ test(
578
+ 'releases the lifecycle queue when native teardown never settles',
579
+ async () => {
580
+ const { transport, uuid, device, bleManager } = createHarness();
581
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
582
+ const otherUuid = 'rn-pro2-other-id';
583
+ const otherDevice = {
584
+ ...device,
585
+ id: otherUuid,
586
+ name: 'OneKey Pro 2 Other',
587
+ localName: 'OneKey Pro 2 Other',
588
+ };
589
+ await (transport as any).installTransportForAcquire(otherUuid, otherDevice);
590
+ (transport as any).deviceProtocol.set(otherUuid, 'V2');
591
+ const disconnectEvents: Array<{ connectId: string }> = [];
592
+ transport.emitter?.on(TRANSPORT_EVENT.DEVICE_DISCONNECT, event => {
593
+ disconnectEvents.push(event);
594
+ });
595
+ const stalledNativeCleanup = createDeferred<void>();
596
+ bleManager.cancelTransaction
597
+ .mockImplementationOnce(() => stalledNativeCleanup.promise)
598
+ .mockResolvedValue(undefined);
599
+ const resetPlxManager = jest.spyOn(transport as any, 'resetPlxManager');
600
+ const nextLifecycleOperation = jest.fn().mockResolvedValue('next-operation');
601
+
602
+ const release = transport.release(uuid, true);
603
+ const nextOperation = (transport as any).runLifecycleOperation(uuid, nextLifecycleOperation);
604
+
605
+ await expect(release).resolves.toBe(true);
606
+ await expect(nextOperation).resolves.toBe('next-operation');
607
+ expect(resetPlxManager).toHaveBeenCalledTimes(1);
608
+ expect(nextLifecycleOperation).toHaveBeenCalledTimes(1);
609
+ expect(disconnectEvents).toContainEqual(expect.objectContaining({ connectId: otherUuid }));
610
+ expect(() => (transport as any).getCachedTransport(otherUuid)).toThrow();
611
+
612
+ await (transport as any).installTransportForAcquire(uuid, device);
613
+ (transport as any).deviceProtocol.set(uuid, 'V2');
614
+
615
+ stalledNativeCleanup.resolve();
616
+ await Promise.resolve();
617
+ await expect(
618
+ transport.call(uuid, 'Ping', { message: 'after-stale-cleanup' })
619
+ ).resolves.toMatchObject({
620
+ type: 'Success',
621
+ message: { message: 'ok' },
622
+ });
623
+ },
624
+ BLE_NATIVE_TEARDOWN_TIMEOUT_MS + 5_000
625
+ );
626
+
627
+ test('falls back to the other active probe on iOS when protocol metadata is absent', async () => {
628
+ const { transport, uuid } = createHarness({ deviceName: 'OneKey' });
629
+ const probeProtocolV1 = jest
630
+ .spyOn(transport as any, 'probeProtocolV1')
631
+ .mockResolvedValue(false);
632
+ const probeProtocolV2 = jest.spyOn(transport as any, 'probeProtocolV2').mockResolvedValue(true);
633
+
634
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
635
+ uuid,
636
+ protocolType: 'V2',
637
+ });
638
+
639
+ expect(probeProtocolV1).toHaveBeenCalledTimes(1);
640
+ expect(probeProtocolV2).toHaveBeenCalledTimes(1);
641
+ expect(probeProtocolV1.mock.invocationCallOrder[0]).toBeLessThan(
642
+ probeProtocolV2.mock.invocationCallOrder[0]
643
+ );
644
+ await transport.release(uuid, true);
645
+ });
646
+
647
+ test('continues with the current MTU when the connected snapshot refresh fails', async () => {
648
+ const { transport, uuid, device } = createHarness();
649
+ const mtuError = new Error('MTU refresh failed');
650
+ device.requestMTU.mockRejectedValueOnce(mtuError);
651
+
652
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
653
+ uuid,
654
+ protocolType: 'V2',
655
+ });
656
+ expect(device.requestMTU).toHaveBeenCalledTimes(1);
657
+ expect((transport as any).getCachedTransport(uuid).mtuSize).toBe(247);
658
+ await transport.release(uuid, true);
659
+ });
660
+
661
+ test('refreshes a transient bootloader MTU after notifications are ready', async () => {
662
+ const { transport, uuid, device } = createHarness();
663
+ device.mtu = 23;
664
+ device.requestMTU
665
+ .mockResolvedValueOnce(device)
666
+ .mockResolvedValueOnce(device)
667
+ .mockImplementationOnce(() => {
668
+ device.mtu = 247;
669
+ return Promise.resolve(device);
670
+ });
671
+
672
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
673
+ uuid,
674
+ protocolType: 'V2',
675
+ });
676
+ expect(device.requestMTU).toHaveBeenCalledTimes(3);
677
+ expect((transport as any).getCachedTransport(uuid).mtuSize).toBe(247);
678
+ await transport.release(uuid, true);
679
+ });
680
+
681
+ test('continues with a low bootloader MTU when the bounded retry fails', async () => {
682
+ const { transport, uuid, device } = createHarness();
683
+ device.mtu = 23;
684
+ device.requestMTU
685
+ .mockResolvedValueOnce(device)
686
+ .mockResolvedValueOnce(device)
687
+ .mockRejectedValueOnce(new Error('bootloader MTU retry failed'));
688
+
689
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
690
+ uuid,
691
+ protocolType: 'V2',
692
+ });
693
+ expect(device.requestMTU).toHaveBeenCalledTimes(3);
694
+ expect((transport as any).getCachedTransport(uuid).mtuSize).toBe(23);
695
+ await transport.release(uuid, true);
696
+ });
697
+
698
+ test('accepts a stable low MTU without the delayed refresh loop', async () => {
699
+ const { transport, uuid, device } = createHarness();
700
+ device.mtu = 185;
701
+
702
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
703
+ uuid,
704
+ protocolType: 'V2',
705
+ });
706
+ expect(device.requestMTU).toHaveBeenCalledTimes(1);
707
+ expect((transport as any).getCachedTransport(uuid).mtuSize).toBe(185);
708
+ await transport.release(uuid, true);
709
+ });
710
+
711
+ test('continues Protocol V2 probing with a conservative packet size when MTU is unavailable', async () => {
712
+ const { transport, uuid, device, writeCharacteristic } = createHarness();
713
+ device.mtu = undefined;
714
+
715
+ await expect(transport.acquire({ uuid })).resolves.toEqual({
716
+ uuid,
717
+ protocolType: 'V2',
718
+ });
719
+ expect(device.requestMTU).toHaveBeenCalledTimes(3);
720
+ expect((transport as any).getCachedTransport(uuid).mtuSize).toBeUndefined();
721
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalled();
722
+ await transport.release(uuid, true);
723
+ });
724
+
725
+ test('refreshes an unavailable MTU before a Protocol V2 high-volume write', async () => {
726
+ const { transport, uuid, device, writeCharacteristic } = createHarness();
727
+ device.mtu = undefined;
728
+
729
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
730
+ device.requestMTU.mockImplementationOnce(() => {
731
+ device.mtu = 247;
732
+ return Promise.resolve(device);
733
+ });
734
+
735
+ await expect(transport.call(uuid, 'FileWrite', {})).resolves.toBeDefined();
736
+ expect(device.requestMTU).toHaveBeenCalledTimes(4);
737
+ expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(1);
738
+ await transport.release(uuid, true);
739
+ });
740
+
741
+ test('rejects a Protocol V2 high-volume write when MTU remains unavailable', async () => {
742
+ const { transport, uuid, device, writeCharacteristic } = createHarness();
743
+ device.mtu = undefined;
744
+
745
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
746
+
747
+ await expect(transport.call(uuid, 'FileWrite', {})).rejects.toMatchObject({
748
+ errorCode: HardwareErrorCode.BleConnectedError,
749
+ });
750
+ expect(device.requestMTU).toHaveBeenCalledTimes(4);
751
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
752
+ await transport.release(uuid, true);
753
+ });
754
+
755
+ test('reconnects before falling back to Protocol V1 after a fatal V2 probe failure', async () => {
756
+ setPlatformOS('android');
757
+ const { transport, uuid, device, notifySubscriptionRemovers, disconnectSubscriptionRemovers } =
758
+ createV1Harness();
759
+ const probeProtocolV2 = jest
760
+ .spyOn(transport as any, 'probeProtocolV2')
761
+ .mockImplementation(async () => {
762
+ await (transport as any).releaseNative(uuid, true);
763
+ return false;
764
+ });
765
+ const resolveCharacteristics = jest.spyOn(transport as any, 'resolveCharacteristics');
766
+
767
+ await expect(transport.acquire({ uuid, protocolHint: 'V2' })).resolves.toEqual({
768
+ uuid,
769
+ protocolType: 'V1',
770
+ });
771
+
772
+ expect(probeProtocolV2).toHaveBeenCalledTimes(1);
773
+ expect(resolveCharacteristics).toHaveBeenCalledTimes(2);
774
+ expect(transport.getProtocolType(uuid)).toBe('V1');
775
+ expect(device.onDisconnected).toHaveBeenCalledTimes(1);
776
+ expect(notifySubscriptionRemovers).toHaveLength(2);
777
+ expect(notifySubscriptionRemovers[0]).toHaveBeenCalledTimes(1);
778
+
779
+ await transport.release(uuid, true);
780
+
781
+ expect(notifySubscriptionRemovers[1]).toHaveBeenCalledTimes(1);
782
+ expect(disconnectSubscriptionRemovers).toHaveLength(1);
783
+ expect(disconnectSubscriptionRemovers[0]).toHaveBeenCalledTimes(1);
784
+ });
785
+
786
+ test('cleans the rebuilt transport when Protocol V1 fallback also fails', async () => {
787
+ setPlatformOS('android');
788
+ const { transport, uuid, device, bleManager, notifySubscriptionRemovers } = createV1Harness();
789
+ jest.spyOn(transport as any, 'probeProtocolV2').mockImplementation(async () => {
790
+ await (transport as any).releaseNative(uuid, true);
791
+ return false;
792
+ });
793
+ jest.spyOn(transport as any, 'probeProtocolV1').mockResolvedValue(false);
794
+
795
+ await expect(transport.acquire({ uuid, protocolHint: 'V2' })).rejects.toMatchObject({
796
+ errorCode: HardwareErrorCode.BleTimeoutError,
797
+ });
798
+
799
+ expect(device.onDisconnected).not.toHaveBeenCalled();
800
+ expect(notifySubscriptionRemovers).toHaveLength(2);
801
+ expect(notifySubscriptionRemovers[0]).toHaveBeenCalledTimes(1);
802
+ expect(notifySubscriptionRemovers[1]).toHaveBeenCalledTimes(1);
803
+ expect(bleManager.cancelTransaction).toHaveBeenCalled();
804
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
805
+ });
806
+
807
+ test('disconnects and invalidates a Protocol V1 link after a response timeout', async () => {
808
+ const { transport, uuid, device } = createV1Harness({
809
+ respondOnWriteCount: Number.POSITIVE_INFINITY,
810
+ });
811
+
812
+ await transport.acquire({ uuid, expectedProtocol: 'V1' });
813
+ await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 5 })).rejects.toMatchObject({
814
+ errorCode: HardwareErrorCode.BleTimeoutError,
815
+ });
816
+
817
+ expect(device.cancelConnection).toHaveBeenCalled();
818
+ expect(transport.getProtocolType(uuid)).toBeUndefined();
819
+ });
820
+
821
+ afterEach(() => {
822
+ setPlatformOS('ios');
823
+ resetProtocolV2BleTuning();
824
+ });
825
+
826
+ test('uses the first Protocol V2 sequence for the first Core call when protocol is known', async () => {
170
827
  const { transport, uuid, sentSeqs } = createHarness();
171
828
 
172
- await transport.acquire({ uuid });
173
- await transport.call(uuid, 'Ping', { message: 'after-probe' });
829
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
830
+ await transport.call(uuid, 'Ping', { message: 'first-core-command' });
174
831
 
175
832
  expect(sentSeqs).toEqual([1, 2]);
176
- expect(bytesToHex(new Uint8Array([sentSeqs[0], sentSeqs[1]]))).toBe('0102');
177
833
  await transport.release(uuid, true);
178
834
  });
179
835
 
180
836
  test('rejects the active Protocol V2 reader when the current monitor errors', async () => {
181
837
  const harness = createHarness();
182
838
  const { transport, uuid, sentSeqs } = harness;
183
- await transport.acquire({ uuid });
839
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
184
840
  harness.setShouldRespond(false);
185
841
 
186
842
  const call = transport.call(uuid, 'Ping', { message: 'wait-for-monitor' }, { timeoutMs: 50 });
187
- while (sentSeqs.length < 2) {
188
- await Promise.resolve();
843
+ while (sentSeqs.length < 1) {
844
+ await new Promise(resolve => {
845
+ setTimeout(resolve, 0);
846
+ });
189
847
  }
190
848
  await new Promise(resolve => {
191
849
  setTimeout(resolve, 0);
@@ -200,44 +858,296 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
200
858
  test('retains the sequence cursor when a new monitor generation is acquired', async () => {
201
859
  const { transport, uuid, sentSeqs } = createHarness();
202
860
 
203
- await transport.acquire({ uuid });
861
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
862
+ await transport.call(uuid, 'Ping', { message: 'first-generation' });
204
863
  await transport.release(uuid, true);
205
- await transport.acquire({ uuid });
864
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
865
+ await transport.call(uuid, 'Ping', { message: 'second-generation' });
206
866
 
207
- expect(sentSeqs).toEqual([1, 2]);
867
+ expect(sentSeqs).toEqual([1, 2, 3, 4]);
208
868
  await transport.release(uuid, true);
209
869
  });
210
870
 
211
- test('uses withoutResponse for normal and high-volume calls', async () => {
871
+ test('uses withResponse for consecutive iOS Protocol V2 control calls without releasing', async () => {
212
872
  const { transport, uuid, writeCharacteristic } = createHarness();
213
873
 
214
- await transport.acquire({ uuid });
215
- expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(1);
216
- expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
874
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
875
+ const releaseNative = jest.spyOn(transport as any, 'releaseNative');
876
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
877
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(1);
878
+
879
+ await transport.call(uuid, 'DeviceInfoGet', {});
880
+ await transport.call(uuid, 'ProtocolInfoRequest', {});
881
+
882
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(3);
883
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
884
+ expect(releaseNative).not.toHaveBeenCalled();
217
885
 
218
- await transport.call(uuid, 'Ping', { message: 'normal' });
886
+ await transport.release(uuid, true);
887
+ });
888
+
889
+ test('keeps iOS Protocol V2 high-volume calls on withoutResponse', async () => {
890
+ const { transport, uuid, logger, writeCharacteristic } = createHarness();
891
+
892
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
893
+
894
+ await transport.call(uuid, 'FileWrite', {});
895
+ await transport.call(uuid, 'FileWrite', {});
219
896
  expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(2);
220
- expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
897
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(1);
898
+ expect(
899
+ logger.debug.mock.calls.filter(
900
+ ([message]) =>
901
+ message === '[ReactNativeBleTransport] Protocol V2 high-volume write configured'
902
+ )
903
+ ).toHaveLength(1);
904
+ await transport.release(uuid, true);
905
+ });
906
+
907
+ test('uses Android 517 MTU and high connection priority during Protocol V2 high-volume calls', async () => {
908
+ setPlatformOS('android');
909
+ const { transport, uuid, device } = createHarness();
221
910
 
911
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
912
+ expect(device.requestMTU).toHaveBeenCalledWith(517);
913
+
914
+ await transport.call(uuid, 'FileWrite', {});
222
915
  await transport.call(uuid, 'FileWrite', {});
223
- expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(3);
916
+
917
+ expect(device.requestConnectionPriority).toHaveBeenCalledTimes(1);
918
+ expect(device.requestConnectionPriority).toHaveBeenCalledWith(1);
919
+
920
+ await transport.release(uuid, true);
921
+ expect(device.requestConnectionPriority).toHaveBeenLastCalledWith(0);
922
+ });
923
+
924
+ test('uses withResponse for an iOS Protocol V2 firmware file write when requested', async () => {
925
+ const { transport, uuid, writeCharacteristic } = createHarness();
926
+
927
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
928
+
929
+ await transport.call(uuid, 'FileWrite', {}, { writeWithResponse: true });
930
+ expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(2);
931
+ expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
932
+ await transport.release(uuid, true);
933
+ });
934
+
935
+ test('falls back to withoutResponse for an iOS Protocol V2 control call when required', async () => {
936
+ const { transport, uuid, writeCharacteristic } = createHarness({
937
+ isWritableWithResponse: false,
938
+ });
939
+
940
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
941
+ await transport.call(uuid, 'ProtocolInfoRequest', {});
942
+
224
943
  expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
944
+ expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(2);
225
945
  await transport.release(uuid, true);
226
946
  });
227
947
 
948
+ test('does not resend a failed iOS Protocol V2 control write without response', async () => {
949
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
950
+ const writeError = new Error('write with response failed');
951
+ const writeWithResponse = jest.fn().mockRejectedValue(writeError);
952
+ const writeWithoutResponse = jest.fn().mockResolvedValue(undefined);
953
+ const context = {
954
+ messageName: 'ProtocolInfoRequest',
955
+ timeoutMs: 1000,
956
+ highThroughput: false,
957
+ generation: 1,
958
+ signal: new AbortController().signal,
959
+ };
960
+
961
+ await expect(
962
+ transport.writeProtocolV2Packet(
963
+ 'test-device',
964
+ {
965
+ writeCharacteristic: {
966
+ isWritableWithResponse: true,
967
+ writeWithResponse,
968
+ writeWithoutResponse,
969
+ },
970
+ },
971
+ Buffer.from('control').toString('base64'),
972
+ context,
973
+ jest.fn()
974
+ )
975
+ ).rejects.toBe(writeError);
976
+ expect(writeWithResponse).toHaveBeenCalledTimes(1);
977
+ expect(writeWithoutResponse).not.toHaveBeenCalled();
978
+ });
979
+
980
+ test('does not pace a one-packet Protocol V2 control write on iOS', async () => {
981
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
982
+ const writeWithoutResponse = jest.fn().mockResolvedValue(undefined);
983
+ const bleTransport = {
984
+ mtuSize: 23,
985
+ writeCharacteristic: { writeWithoutResponse },
986
+ };
987
+ const context = {
988
+ messageName: 'ProtocolInfoRequest',
989
+ timeoutMs: 1000,
990
+ highThroughput: false,
991
+ generation: 1,
992
+ signal: new AbortController().signal,
993
+ };
994
+ configureProtocolV2BleTuning({ iosPacketLength: 20 });
995
+ const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
996
+
997
+ try {
998
+ const call = transport.writeProtocolV2Frame(
999
+ 'test-device',
1000
+ bleTransport,
1001
+ new Uint8Array(10),
1002
+ context,
1003
+ jest.fn()
1004
+ );
1005
+
1006
+ await call;
1007
+ // The only scheduled timer is the per-packet BLE write watchdog: no pacing delay.
1008
+ expect(setTimeoutSpy.mock.calls.map(([, timeout]) => timeout)).toEqual([
1009
+ BLE_WRITE_PACKET_TIMEOUT_MS,
1010
+ ]);
1011
+ expect(writeWithoutResponse).toHaveBeenCalledTimes(1);
1012
+ } finally {
1013
+ setTimeoutSpy.mockRestore();
1014
+ }
1015
+ });
1016
+
228
1017
  test('rejects an active Protocol V2 reader when disconnect resets the link', async () => {
229
1018
  const harness = createHarness();
230
1019
  const { transport, uuid, sentSeqs } = harness;
231
- await transport.acquire({ uuid });
1020
+ await transport.acquire({ uuid, expectedProtocol: 'V2' });
232
1021
  harness.setShouldRespond(false);
233
1022
 
234
1023
  const call = transport.call(uuid, 'Ping', { message: 'disconnect' }, { timeoutMs: 50 });
235
- while (sentSeqs.length < 2) {
236
- await Promise.resolve();
1024
+ while (sentSeqs.length < 1) {
1025
+ await new Promise(resolve => {
1026
+ setTimeout(resolve, 0);
1027
+ });
237
1028
  }
238
1029
 
239
1030
  const rejection = expect(call).rejects.toThrow('React Native BLE transport disconnected');
240
1031
  await transport.disconnect(uuid);
241
1032
  await rejection;
242
1033
  });
1034
+
1035
+ test('emits one disconnect event when the physical callback races manual cleanup', async () => {
1036
+ const harness = createHarness();
1037
+ const disconnectListener = jest.fn();
1038
+ harness.emitter.on(TRANSPORT_EVENT.DEVICE_DISCONNECT, disconnectListener);
1039
+
1040
+ await harness.transport.acquire({ uuid: harness.uuid, expectedProtocol: 'V2' });
1041
+ harness.emitDisconnect();
1042
+ await harness.transport.disconnect(harness.uuid);
1043
+
1044
+ expect(disconnectListener).toHaveBeenCalledTimes(1);
1045
+ expect(disconnectListener).toHaveBeenCalledWith({
1046
+ name: 'OneKey Pro 2',
1047
+ id: harness.uuid,
1048
+ connectId: harness.uuid,
1049
+ });
1050
+ });
1051
+
1052
+ test('chunks large frames and retries only transient GATT congestion', async () => {
1053
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
1054
+ const congested = { status: 143, message: 'GATT_CONGESTED' };
1055
+ const writeWithoutResponse = jest
1056
+ .fn()
1057
+ .mockRejectedValueOnce(congested)
1058
+ .mockResolvedValue(undefined);
1059
+ const bleTransport = {
1060
+ mtuSize: 23,
1061
+ writeCharacteristic: { writeWithoutResponse },
1062
+ };
1063
+ const context = {
1064
+ messageName: 'Ping',
1065
+ timeoutMs: 1000,
1066
+ highThroughput: false,
1067
+ generation: 1,
1068
+ signal: new AbortController().signal,
1069
+ };
1070
+ const assertCurrentGeneration = jest.fn();
1071
+ configureProtocolV2BleTuning({ iosPacketLength: 20 });
1072
+
1073
+ await transport.writeProtocolV2Frame(
1074
+ 'device-uuid',
1075
+ bleTransport,
1076
+ new Uint8Array(30),
1077
+ context,
1078
+ assertCurrentGeneration
1079
+ );
1080
+
1081
+ expect(writeWithoutResponse).toHaveBeenCalledTimes(3);
1082
+ expect(writeWithoutResponse.mock.calls[0][0]).toBe(writeWithoutResponse.mock.calls[1][0]);
1083
+ expect(Buffer.from(writeWithoutResponse.mock.calls[2][0], 'base64')).toHaveLength(10);
1084
+ expect(assertCurrentGeneration).toHaveBeenCalled();
1085
+ });
1086
+
1087
+ test('does not retry a disconnected Protocol V2 write inside a partial frame', async () => {
1088
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
1089
+ const writeWithoutResponse = jest
1090
+ .fn()
1091
+ .mockRejectedValue({ errorCode: 205, message: 'Device disconnected' });
1092
+ const bleTransport = {
1093
+ mtuSize: 23,
1094
+ writeCharacteristic: { writeWithoutResponse },
1095
+ };
1096
+ const context = {
1097
+ messageName: 'FileWrite',
1098
+ timeoutMs: 1000,
1099
+ highThroughput: true,
1100
+ generation: 1,
1101
+ signal: new AbortController().signal,
1102
+ };
1103
+ configureProtocolV2BleTuning({ iosPacketLength: 20 });
1104
+
1105
+ await expect(
1106
+ transport.writeProtocolV2Frame(
1107
+ 'device-uuid',
1108
+ bleTransport,
1109
+ new Uint8Array(30),
1110
+ context,
1111
+ jest.fn()
1112
+ )
1113
+ ).rejects.toMatchObject({ errorCode: 205 });
1114
+ expect(writeWithoutResponse).toHaveBeenCalledTimes(1);
1115
+ });
1116
+
1117
+ test('does not apply fixed burst or flush pauses to high-volume Protocol V2 writes', async () => {
1118
+ const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
1119
+ const writeWithoutResponse = jest.fn().mockResolvedValue(undefined);
1120
+ const bleTransport = {
1121
+ mtuSize: 247,
1122
+ writeCharacteristic: { writeWithoutResponse },
1123
+ };
1124
+ const context = {
1125
+ messageName: 'FileWrite',
1126
+ timeoutMs: 1000,
1127
+ highThroughput: true,
1128
+ generation: 1,
1129
+ signal: new AbortController().signal,
1130
+ };
1131
+ const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
1132
+
1133
+ try {
1134
+ await transport.writeProtocolV2Frame(
1135
+ 'test-device',
1136
+ bleTransport,
1137
+ new Uint8Array(600),
1138
+ context,
1139
+ jest.fn()
1140
+ );
1141
+
1142
+ expect(writeWithoutResponse).toHaveBeenCalledTimes(3);
1143
+ // One BLE write watchdog per packet and nothing else: no burst or flush pauses.
1144
+ expect(setTimeoutSpy.mock.calls.map(([, timeout]) => timeout)).toEqual([
1145
+ BLE_WRITE_PACKET_TIMEOUT_MS,
1146
+ BLE_WRITE_PACKET_TIMEOUT_MS,
1147
+ BLE_WRITE_PACKET_TIMEOUT_MS,
1148
+ ]);
1149
+ } finally {
1150
+ setTimeoutSpy.mockRestore();
1151
+ }
1152
+ });
243
1153
  });