@onekeyfe/hd-transport-react-native 1.2.0-alpha.53 → 1.2.0-alpha.54

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.
@@ -3,6 +3,7 @@ import transportPackage, {
3
3
  PROTOCOL_V2_CHANNEL_BLE_UART,
4
4
  ProtocolV2,
5
5
  TRANSPORT_EVENT,
6
+ bytesToHex,
6
7
  } from '@onekeyfe/hd-transport';
7
8
  import { HardwareErrorCode, createDeferred } from '@onekeyfe/hd-shared';
8
9
 
@@ -45,11 +46,6 @@ jest.mock('../subscribeBleOn', () => ({
45
46
  subscribeBleOn: jest.fn(() => Promise.resolve()),
46
47
  }));
47
48
 
48
- const setPlatformOS = (os: 'ios' | 'android') => {
49
- const reactNative: { Platform: { OS: string } } = jest.requireMock('react-native');
50
- reactNative.Platform.OS = os;
51
- };
52
-
53
49
  const { parseConfigure } = transportPackage;
54
50
 
55
51
  const protocolV1Schema = {
@@ -73,13 +69,11 @@ const protocolV1Schema = {
73
69
 
74
70
  const protocolV2Schema = {
75
71
  nested: {
76
- ProtocolInfoRequest: { fields: {} },
77
72
  Ping: {
78
73
  fields: {
79
74
  message: { type: 'string', id: 1 },
80
75
  },
81
76
  },
82
- DeviceInfoGet: { fields: {} },
83
77
  FileWrite: { fields: {} },
84
78
  Success: {
85
79
  fields: {
@@ -88,10 +82,8 @@ const protocolV2Schema = {
88
82
  },
89
83
  MessageType: {
90
84
  values: {
91
- MessageType_ProtocolInfoRequest: 60200,
92
85
  MessageType_Ping: 60206,
93
86
  MessageType_Success: 60207,
94
- MessageType_DeviceInfoGet: 60600,
95
87
  MessageType_FileWrite: 60805,
96
88
  },
97
89
  },
@@ -103,13 +95,7 @@ const schemas = {
103
95
  protocolV2: parseConfigure(protocolV2Schema),
104
96
  };
105
97
 
106
- const createHarness = ({
107
- deviceName = 'OneKey Pro 2',
108
- isWritableWithResponse = true,
109
- }: {
110
- deviceName?: string;
111
- isWritableWithResponse?: boolean;
112
- } = {}) => {
98
+ const createHarness = () => {
113
99
  const uuid = 'rn-pro2-id';
114
100
  const sentSeqs: number[] = [];
115
101
  let responseSeq = 0;
@@ -148,15 +134,15 @@ const createHarness = ({
148
134
  const writeCharacteristic = {
149
135
  uuid: '0002',
150
136
  deviceID: uuid,
151
- isWritableWithResponse,
137
+ isWritableWithResponse: true,
152
138
  isWritableWithoutResponse: true,
153
139
  writeWithResponse: jest.fn(handleWrite),
154
140
  writeWithoutResponse: jest.fn(handleWrite),
155
141
  };
156
142
  const device = {
157
143
  id: uuid,
158
- name: deviceName,
159
- localName: deviceName,
144
+ name: 'OneKey Pro 2',
145
+ localName: 'OneKey Pro 2',
160
146
  serviceUUIDs: ['00000001-0000-1000-8000-00805f9b34fb'],
161
147
  isConnected: jest.fn(() => Promise.resolve(true)),
162
148
  cancelConnection: jest.fn(() => Promise.resolve()),
@@ -198,13 +184,7 @@ const createHarness = ({
198
184
  };
199
185
  };
200
186
 
201
- const createV1Harness = ({
202
- respondOnWriteCount = 1,
203
- isWritableWithResponse = true,
204
- }: {
205
- respondOnWriteCount?: number | number[];
206
- isWritableWithResponse?: boolean;
207
- } = {}) => {
187
+ const createV1Harness = () => {
208
188
  const uuid = 'rn-classic-id';
209
189
  const notifySubscriptionRemovers: jest.Mock[] = [];
210
190
  const disconnectSubscriptionRemovers: jest.Mock[] = [];
@@ -223,25 +203,20 @@ const createV1Harness = ({
223
203
  }),
224
204
  };
225
205
  let writeCount = 0;
226
- const responseWriteCounts = new Set(
227
- Array.isArray(respondOnWriteCount) ? respondOnWriteCount : [respondOnWriteCount]
228
- );
229
- const handleWrite = () => {
230
- writeCount += 1;
231
- if (responseWriteCounts.has(writeCount)) {
232
- notifyCallback?.(null, {
233
- value: Buffer.from('3f23230002000000040a026f6b', 'hex').toString('base64'),
234
- });
235
- }
236
- return Promise.resolve();
237
- };
238
206
  const writeCharacteristic = {
239
207
  uuid: '0002',
240
208
  deviceID: uuid,
241
- isWritableWithResponse,
209
+ isWritableWithResponse: true,
242
210
  isWritableWithoutResponse: true,
243
- writeWithResponse: jest.fn(handleWrite),
244
- writeWithoutResponse: jest.fn(handleWrite),
211
+ writeWithoutResponse: jest.fn(() => {
212
+ writeCount += 1;
213
+ if (writeCount === 1) {
214
+ notifyCallback?.(null, {
215
+ value: Buffer.from('3f23230002000000040a026f6b', 'hex').toString('base64'),
216
+ });
217
+ }
218
+ return Promise.resolve();
219
+ }),
245
220
  };
246
221
  const device = {
247
222
  id: uuid,
@@ -274,7 +249,6 @@ const createV1Harness = ({
274
249
  uuid,
275
250
  device,
276
251
  bleManager,
277
- writeCharacteristic,
278
252
  notifySubscriptionRemovers,
279
253
  disconnectSubscriptionRemovers,
280
254
  };
@@ -328,81 +302,12 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
328
302
  expect(new ReactNativeBleTransport({}).scanTimeout).toBe(3000);
329
303
  });
330
304
 
331
- test('uses withResponse for consecutive iOS Protocol V1 control commands without releasing', async () => {
332
- const { transport, uuid, writeCharacteristic } = createV1Harness({
333
- respondOnWriteCount: [1, 2],
334
- });
335
-
336
- await expect(transport.acquire({ uuid })).resolves.toEqual({
337
- uuid,
338
- protocolType: 'V1',
339
- });
340
- const releaseNative = jest.spyOn(transport as any, 'releaseNative');
341
- expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
342
- expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
343
-
344
- await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 50 })).resolves.toBeDefined();
345
- await expect(transport.call(uuid, 'GetFeatures', {}, { timeoutMs: 50 })).resolves.toBeDefined();
346
-
347
- expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(2);
348
- expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
349
- expect(releaseNative).not.toHaveBeenCalled();
350
- await transport.release(uuid, true);
351
- });
352
-
353
- test('falls back to withoutResponse for an iOS Protocol V1 control command when required', async () => {
354
- const { transport, uuid, writeCharacteristic } = createV1Harness({
355
- isWritableWithResponse: false,
356
- });
357
-
358
- await transport.acquire({ uuid });
359
- await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 50 })).resolves.toBeDefined();
360
-
361
- expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
362
- expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(1);
363
- await transport.release(uuid, true);
364
- });
365
-
366
- test('does not resend a failed iOS Protocol V1 control write without response', async () => {
367
- const { transport, uuid, writeCharacteristic } = createV1Harness();
368
- const writeError = new Error('write with response failed');
369
-
370
- await transport.acquire({ uuid });
371
- writeCharacteristic.writeWithResponse.mockRejectedValueOnce(writeError);
372
-
373
- await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 50 })).rejects.toMatchObject({
374
- errorCode: HardwareErrorCode.BleWriteCharacteristicError,
375
- });
376
- expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(1);
377
- expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
378
- await transport.release(uuid, true);
379
- });
380
-
381
- test('keeps the first Core command as the first iOS BLE request for a Protocol V2 device', async () => {
382
- const { transport, uuid, sentSeqs, writeCharacteristic } = createHarness({
383
- deviceName: 'Pro2 6E9E',
384
- });
385
-
386
- await expect(transport.acquire({ uuid })).resolves.toEqual({
387
- uuid,
388
- protocolType: 'V2',
389
- });
390
- expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
391
-
392
- await expect(
393
- transport.call(uuid, 'Ping', { message: 'first-core-command' })
394
- ).resolves.toBeDefined();
395
- expect(sentSeqs).toEqual([1]);
396
- await transport.release(uuid, true);
397
- });
398
-
399
305
  test('reconnects before falling back to Protocol V1 after a fatal V2 probe failure', async () => {
400
- setPlatformOS('android');
401
306
  const { transport, uuid, device, notifySubscriptionRemovers, disconnectSubscriptionRemovers } =
402
307
  createV1Harness();
403
308
  const probeProtocolV2 = jest
404
309
  .spyOn(transport as any, 'probeProtocolV2')
405
- .mockImplementation(async () => {
310
+ .mockImplementationOnce(async () => {
406
311
  await (transport as any).releaseNative(uuid, true);
407
312
  return false;
408
313
  });
@@ -428,9 +333,8 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
428
333
  });
429
334
 
430
335
  test('cleans the rebuilt transport when Protocol V1 fallback also fails', async () => {
431
- setPlatformOS('android');
432
336
  const { transport, uuid, device, bleManager, notifySubscriptionRemovers } = createV1Harness();
433
- jest.spyOn(transport as any, 'probeProtocolV2').mockImplementation(async () => {
337
+ jest.spyOn(transport as any, 'probeProtocolV2').mockImplementationOnce(async () => {
434
338
  await (transport as any).releaseNative(uuid, true);
435
339
  return false;
436
340
  });
@@ -449,9 +353,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
449
353
  });
450
354
 
451
355
  test('disconnects and invalidates a Protocol V1 link after a response timeout', async () => {
452
- const { transport, uuid, device } = createV1Harness({
453
- respondOnWriteCount: Number.POSITIVE_INFINITY,
454
- });
356
+ const { transport, uuid, device } = createV1Harness();
455
357
 
456
358
  await transport.acquire({ uuid, expectedProtocol: 'V1' });
457
359
  await expect(transport.call(uuid, 'Initialize', {}, { timeoutMs: 5 })).rejects.toMatchObject({
@@ -463,17 +365,17 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
463
365
  });
464
366
 
465
367
  afterEach(() => {
466
- setPlatformOS('ios');
467
368
  resetProtocolV2BleTuning();
468
369
  });
469
370
 
470
- test('starts the Protocol V2 sequence with the first Core call on iOS', async () => {
371
+ test('keeps the Protocol V2 sequence across probe and the next call', async () => {
471
372
  const { transport, uuid, sentSeqs } = createHarness();
472
373
 
473
374
  await transport.acquire({ uuid });
474
- await transport.call(uuid, 'Ping', { message: 'first-core-command' });
375
+ await transport.call(uuid, 'Ping', { message: 'after-probe' });
475
376
 
476
- expect(sentSeqs).toEqual([1]);
377
+ expect(sentSeqs).toEqual([1, 2]);
378
+ expect(bytesToHex(new Uint8Array([sentSeqs[0], sentSeqs[1]]))).toBe('0102');
477
379
  await transport.release(uuid, true);
478
380
  });
479
381
 
@@ -484,10 +386,8 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
484
386
  harness.setShouldRespond(false);
485
387
 
486
388
  const call = transport.call(uuid, 'Ping', { message: 'wait-for-monitor' }, { timeoutMs: 50 });
487
- while (sentSeqs.length < 1) {
488
- await new Promise(resolve => {
489
- setTimeout(resolve, 0);
490
- });
389
+ while (sentSeqs.length < 2) {
390
+ await Promise.resolve();
491
391
  }
492
392
  await new Promise(resolve => {
493
393
  setTimeout(resolve, 0);
@@ -503,124 +403,30 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
503
403
  const { transport, uuid, sentSeqs } = createHarness();
504
404
 
505
405
  await transport.acquire({ uuid });
506
- await transport.call(uuid, 'Ping', { message: 'first-generation' });
507
406
  await transport.release(uuid, true);
508
407
  await transport.acquire({ uuid });
509
- await transport.call(uuid, 'Ping', { message: 'second-generation' });
510
408
 
511
409
  expect(sentSeqs).toEqual([1, 2]);
512
410
  await transport.release(uuid, true);
513
411
  });
514
412
 
515
- test('uses withResponse for consecutive iOS Protocol V2 control calls without releasing', async () => {
516
- const { transport, uuid, writeCharacteristic } = createHarness();
517
-
518
- await transport.acquire({ uuid });
519
- const releaseNative = jest.spyOn(transport as any, 'releaseNative');
520
- expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
521
- expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
522
-
523
- await transport.call(uuid, 'DeviceInfoGet', {});
524
- await transport.call(uuid, 'ProtocolInfoRequest', {});
525
-
526
- expect(writeCharacteristic.writeWithResponse).toHaveBeenCalledTimes(2);
527
- expect(writeCharacteristic.writeWithoutResponse).not.toHaveBeenCalled();
528
- expect(releaseNative).not.toHaveBeenCalled();
529
-
530
- await transport.release(uuid, true);
531
- });
532
-
533
- test('keeps iOS Protocol V2 high-volume calls on withoutResponse', async () => {
413
+ test('uses withoutResponse for normal and high-volume calls', async () => {
534
414
  const { transport, uuid, writeCharacteristic } = createHarness();
535
415
 
536
416
  await transport.acquire({ uuid });
537
-
538
- await transport.call(uuid, 'FileWrite', {});
539
417
  expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(1);
540
418
  expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
541
- await transport.release(uuid, true);
542
- });
543
419
 
544
- test('falls back to withoutResponse for an iOS Protocol V2 control call when required', async () => {
545
- const { transport, uuid, writeCharacteristic } = createHarness({
546
- isWritableWithResponse: false,
547
- });
548
-
549
- await transport.acquire({ uuid });
550
- await transport.call(uuid, 'ProtocolInfoRequest', {});
420
+ await transport.call(uuid, 'Ping', { message: 'normal' });
421
+ expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(2);
422
+ expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
551
423
 
424
+ await transport.call(uuid, 'FileWrite', {});
425
+ expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(3);
552
426
  expect(writeCharacteristic.writeWithResponse).not.toHaveBeenCalled();
553
- expect(writeCharacteristic.writeWithoutResponse).toHaveBeenCalledTimes(1);
554
427
  await transport.release(uuid, true);
555
428
  });
556
429
 
557
- test('does not resend a failed iOS Protocol V2 control write without response', async () => {
558
- const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
559
- const writeError = new Error('write with response failed');
560
- const writeWithResponse = jest.fn().mockRejectedValue(writeError);
561
- const writeWithoutResponse = jest.fn().mockResolvedValue(undefined);
562
- const context = {
563
- messageName: 'ProtocolInfoRequest',
564
- timeoutMs: 1000,
565
- highVolume: false,
566
- generation: 1,
567
- signal: new AbortController().signal,
568
- };
569
-
570
- await expect(
571
- transport.writeProtocolV2Packet(
572
- {
573
- writeCharacteristic: {
574
- isWritableWithResponse: true,
575
- writeWithResponse,
576
- writeWithoutResponse,
577
- },
578
- },
579
- Buffer.from('control').toString('base64'),
580
- context,
581
- jest.fn()
582
- )
583
- ).rejects.toBe(writeError);
584
- expect(writeWithResponse).toHaveBeenCalledTimes(1);
585
- expect(writeWithoutResponse).not.toHaveBeenCalled();
586
- });
587
-
588
- test('paces a one-packet Protocol V2 control write on iOS', async () => {
589
- const transport = new ReactNativeBleTransport({ scanTimeout: 1 }) as any;
590
- const writeWithoutResponse = jest.fn().mockResolvedValue(undefined);
591
- const bleTransport = {
592
- mtuSize: 23,
593
- writeCharacteristic: { writeWithoutResponse },
594
- };
595
- const context = {
596
- messageName: 'ProtocolInfoRequest',
597
- timeoutMs: 1000,
598
- highVolume: false,
599
- generation: 1,
600
- signal: new AbortController().signal,
601
- };
602
- configureProtocolV2BleTuning({ iosPacketLength: 20 });
603
- const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
604
-
605
- try {
606
- const call = transport.writeProtocolV2Frame(
607
- bleTransport,
608
- new Uint8Array(10),
609
- context,
610
- jest.fn()
611
- );
612
-
613
- await Promise.resolve();
614
- expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 5);
615
- expect(writeWithoutResponse).not.toHaveBeenCalled();
616
-
617
- await call;
618
- expect(writeWithoutResponse).toHaveBeenCalledTimes(1);
619
- } finally {
620
- setTimeoutSpy.mockRestore();
621
- }
622
- });
623
-
624
430
  test('rejects an active Protocol V2 reader when disconnect resets the link', async () => {
625
431
  const harness = createHarness();
626
432
  const { transport, uuid, sentSeqs } = harness;
@@ -628,10 +434,8 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
628
434
  harness.setShouldRespond(false);
629
435
 
630
436
  const call = transport.call(uuid, 'Ping', { message: 'disconnect' }, { timeoutMs: 50 });
631
- while (sentSeqs.length < 1) {
632
- await new Promise(resolve => {
633
- setTimeout(resolve, 0);
634
- });
437
+ while (sentSeqs.length < 2) {
438
+ await Promise.resolve();
635
439
  }
636
440
 
637
441
  const rejection = expect(call).rejects.toThrow('React Native BLE transport disconnected');
@@ -678,6 +482,7 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
678
482
  configureProtocolV2BleTuning({ iosPacketLength: 20 });
679
483
 
680
484
  await transport.writeProtocolV2Frame(
485
+ 'device-uuid',
681
486
  bleTransport,
682
487
  new Uint8Array(30),
683
488
  context,
@@ -709,7 +514,13 @@ describe('ReactNativeBleTransport Protocol V2 link lifecycle', () => {
709
514
  configureProtocolV2BleTuning({ iosPacketLength: 20 });
710
515
 
711
516
  await expect(
712
- transport.writeProtocolV2Frame(bleTransport, new Uint8Array(30), context, jest.fn())
517
+ transport.writeProtocolV2Frame(
518
+ 'device-uuid',
519
+ bleTransport,
520
+ new Uint8Array(30),
521
+ context,
522
+ jest.fn()
523
+ )
713
524
  ).rejects.toMatchObject({ errorCode: 205 });
714
525
  expect(writeWithoutResponse).toHaveBeenCalledTimes(1);
715
526
  });
@@ -0,0 +1,211 @@
1
+ import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
+
3
+ import ReactNativeBleTransport from '../index';
4
+
5
+ import messages from '@onekeyfe/hd-transport/messages.json';
6
+
7
+ jest.mock(
8
+ 'react-native',
9
+ () => ({
10
+ Platform: { OS: 'ios', select: (spec: Record<string, unknown>) => spec.ios },
11
+ PermissionsAndroid: {
12
+ PERMISSIONS: {},
13
+ RESULTS: {},
14
+ request: jest.fn(),
15
+ requestMultiple: jest.fn(),
16
+ },
17
+ }),
18
+ { virtual: true }
19
+ );
20
+
21
+ jest.mock('react-native-ble-plx', () => ({
22
+ BleATTErrorCode: { InvalidHandle: 1 },
23
+ BleError: Error,
24
+ BleErrorCode: { DeviceDisconnected: 201, OperationStartFailed: 601 },
25
+ BleManager: jest.fn(),
26
+ ScanMode: { LowLatency: 2 },
27
+ }));
28
+
29
+ jest.mock('@onekeyfe/react-native-ble-utils', () => ({
30
+ __esModule: true,
31
+ default: {
32
+ getConnectedPeripherals: jest.fn(() => Promise.resolve([])),
33
+ getBondedPeripherals: jest.fn(() => Promise.resolve([])),
34
+ pairDevice: jest.fn(() => Promise.resolve()),
35
+ },
36
+ }));
37
+
38
+ const UUID = 'stale-timeout-device';
39
+
40
+ const flush = () =>
41
+ new Promise(resolve => {
42
+ setImmediate(resolve);
43
+ });
44
+
45
+ function createHarness() {
46
+ const t = new ReactNativeBleTransport({});
47
+ t.configure(messages);
48
+ (t as any).deviceProtocol.set(UUID, 'V1');
49
+ const writeWithoutResponse = jest.fn(() => Promise.resolve());
50
+ const fakeBleTransport = {
51
+ writeCharacteristic: { writeWithoutResponse },
52
+ writeWithRetry: jest.fn(() => Promise.resolve()),
53
+ };
54
+ (t as any).getCachedTransport = () => fakeBleTransport;
55
+ const disconnectSpy = jest.spyOn(t, 'disconnect').mockResolvedValue(undefined);
56
+ return { t, disconnectSpy, writeWithoutResponse };
57
+ }
58
+
59
+ describe('Protocol V1 stale call timeout', () => {
60
+ beforeAll(() => {
61
+ jest.useFakeTimers({ doNotFake: ['setImmediate', 'performance'] });
62
+ });
63
+
64
+ afterAll(() => {
65
+ jest.useRealTimers();
66
+ });
67
+
68
+ afterEach(() => {
69
+ jest.clearAllTimers();
70
+ jest.restoreAllMocks();
71
+ });
72
+
73
+ test('superseded Initialize timeout does not tear down the shared transport', async () => {
74
+ const { t, disconnectSpy } = createHarness();
75
+
76
+ // Initialize #1: written while the device reboots, never answered.
77
+ const firstErrors: unknown[] = [];
78
+ const first = t.call(UUID, 'Initialize', {}, { timeoutMs: 25000 });
79
+ first.catch(e => firstErrors.push(e));
80
+ await flush();
81
+
82
+ // Initialize #2 (forceRun) supersedes #1 three seconds later.
83
+ jest.advanceTimersByTime(3000);
84
+ const secondErrors: unknown[] = [];
85
+ const second = t.call(UUID, 'Initialize', {}, { timeoutMs: 25000 });
86
+ second.catch(e => secondErrors.push(e));
87
+ await flush();
88
+
89
+ // The device answers Initialize #2 (settle its deferred at the transport seam).
90
+ expect(t.runPromise).not.toBeNull();
91
+ t.runPromise?.reject(new Error('settled by device response'));
92
+ await flush();
93
+
94
+ // FirmwareUpload is now the active call on the same transport, awaiting its response.
95
+ const uploadErrors: unknown[] = [];
96
+ const upload = t.call(UUID, 'FirmwareUpload', { payload: Buffer.alloc(300) });
97
+ upload.catch(e => uploadErrors.push(e));
98
+ await flush();
99
+ jest.advanceTimersByTime(100); // firmware upload flush delay
100
+ await flush();
101
+
102
+ // Initialize #1's 25s response timer elapses while the upload is in flight.
103
+ jest.advanceTimersByTime(25000);
104
+ await flush();
105
+
106
+ expect(disconnectSpy).not.toHaveBeenCalled();
107
+ expect(firstErrors).toHaveLength(1);
108
+ expect(uploadErrors).toHaveLength(0);
109
+ });
110
+
111
+ test('forceRun supersede settles the previous pending call immediately', async () => {
112
+ const { t } = createHarness();
113
+
114
+ const firstErrors: Array<{ errorCode?: unknown }> = [];
115
+ const first = t.call(UUID, 'Initialize', {}, { timeoutMs: 25000 });
116
+ first.catch(e => firstErrors.push(e));
117
+ await flush();
118
+
119
+ const second = t.call(UUID, 'Initialize', {}, { timeoutMs: 25000 });
120
+ second.catch(() => undefined);
121
+ await flush();
122
+
123
+ expect(firstErrors).toHaveLength(1);
124
+ expect(firstErrors[0]?.errorCode).toBe(HardwareErrorCode.BleForceCleanRunPromise);
125
+
126
+ t.runPromise?.reject(new Error('settle second call'));
127
+ await flush();
128
+ });
129
+
130
+ test('late write failure of a superseded call keeps the successor as owner', async () => {
131
+ const { t, disconnectSpy } = createHarness();
132
+
133
+ // First call's write hangs; its promise is controlled by the test.
134
+ let rejectFirstWrite: ((e: Error) => void) | undefined;
135
+ const fakeBleTransport = {
136
+ writeCharacteristic: {
137
+ writeWithoutResponse: jest
138
+ .fn()
139
+ .mockImplementationOnce(
140
+ () =>
141
+ new Promise((_resolve, reject) => {
142
+ rejectFirstWrite = reject;
143
+ })
144
+ )
145
+ .mockImplementation(() => Promise.resolve()),
146
+ },
147
+ writeWithRetry: jest.fn(() => Promise.resolve()),
148
+ };
149
+ (t as any).getCachedTransport = () => fakeBleTransport;
150
+
151
+ const firstErrors: unknown[] = [];
152
+ const first = t.call(UUID, 'Initialize', {}, { timeoutMs: 25000 });
153
+ first.catch(e => firstErrors.push(e));
154
+ await flush();
155
+
156
+ // forceRun successor takes ownership while the first call is stuck writing.
157
+ const secondErrors: unknown[] = [];
158
+ const second = t.call(UUID, 'Initialize', {}, { timeoutMs: 5000 });
159
+ second.catch(e => secondErrors.push(e));
160
+ await flush();
161
+
162
+ // The first call's write now fails late; it must not clear the successor's slot.
163
+ rejectFirstWrite?.(new Error('late write failure'));
164
+ await flush();
165
+
166
+ expect(t.runPromise).not.toBeNull();
167
+
168
+ // The successor's genuine timeout must still tear the connection down.
169
+ jest.advanceTimersByTime(5000);
170
+ await flush();
171
+
172
+ expect(disconnectSpy).toHaveBeenCalledTimes(1);
173
+ expect(secondErrors).toHaveLength(1);
174
+ });
175
+
176
+ test('orphan timer left behind by cancel() must not disconnect the transport', async () => {
177
+ const { t, disconnectSpy } = createHarness();
178
+
179
+ // cancel() nulls the ownership slot without settling the deferred, so the
180
+ // call's response timer stays armed (reachable via DeviceCommands.dispose).
181
+ const errors: Array<{ errorCode?: unknown }> = [];
182
+ const p = t.call(UUID, 'GetFeatures', {}, { timeoutMs: 5000 });
183
+ p.catch(e => errors.push(e));
184
+ await flush();
185
+
186
+ t.cancel();
187
+
188
+ jest.advanceTimersByTime(5000);
189
+ await flush();
190
+
191
+ expect(disconnectSpy).not.toHaveBeenCalled();
192
+ expect(errors).toHaveLength(1);
193
+ expect(errors[0]?.errorCode).toBe(HardwareErrorCode.BleTimeoutError);
194
+ });
195
+
196
+ test('timeout on the active call still disconnects the transport', async () => {
197
+ const { t, disconnectSpy } = createHarness();
198
+
199
+ const errors: Array<{ errorCode?: unknown }> = [];
200
+ const p = t.call(UUID, 'GetFeatures', {}, { timeoutMs: 5000 });
201
+ p.catch(e => errors.push(e));
202
+ await flush();
203
+
204
+ jest.advanceTimersByTime(5000);
205
+ await flush();
206
+
207
+ expect(disconnectSpy).toHaveBeenCalledTimes(1);
208
+ expect(errors).toHaveLength(1);
209
+ expect(errors[0]?.errorCode).toBe(HardwareErrorCode.BleTimeoutError);
210
+ });
211
+ });