@onekeyfe/hd-transport-web-device 1.2.0-alpha.14 → 1.2.0-alpha.141

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.
package/src/webusb.ts CHANGED
@@ -6,8 +6,8 @@ import transport, {
6
6
  PROTOCOL_V1_USB_PACKET_SIZE,
7
7
  PROTOCOL_V2_CHANNEL_USB,
8
8
  PROTOCOL_V2_FRAME_MAX_BYTES,
9
- ProtocolV2FrameAssembler,
10
- ProtocolV2Session,
9
+ ProtocolV2LinkError,
10
+ ProtocolV2UsbTransportBase,
11
11
  probeProtocolV2 as probeProtocolV2Helper,
12
12
  } from '@onekeyfe/hd-transport';
13
13
  import {
@@ -19,12 +19,12 @@ import {
19
19
  } from '@onekeyfe/hd-shared';
20
20
  import ByteBuffer from 'bytebuffer';
21
21
 
22
- import { createTransportCallLog, shouldSuppressHighVolumeCallLog } from './transportLog';
23
-
24
22
  import type {
25
23
  AcquireInput,
26
24
  OneKeyDeviceInfoBase,
27
25
  ProtocolType,
26
+ ProtocolV2CallContext,
27
+ ProtocolV2Schemas,
28
28
  TransportCallOptions,
29
29
  } from '@onekeyfe/hd-transport';
30
30
 
@@ -39,7 +39,12 @@ const REPORT_ID = PROTOCOL_V1_REPORT_ID;
39
39
  const HEADER_LENGTH = PROTOCOL_V1_MESSAGE_HEADER_SIZE;
40
40
  const PACKET_IO_MAX_RETRIES = 3;
41
41
  const PACKET_IO_RETRY_DELAY = 300;
42
- const PROTOCOL_PROBE_TIMEOUT = 1000;
42
+ // Legacy devices can take longer to answer Initialize after a WebUSB reset.
43
+ // Keep this aligned with Node USB so a slow Protocol V1 response is not
44
+ // misreported as a protocol mismatch during acquire.
45
+ const PROTOCOL_V1_PROBE_TIMEOUT = 5000;
46
+ const PROTOCOL_V2_PROBE_TIMEOUT = 1000;
47
+ const EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS = 2;
43
48
  function inferProtocolHintFromDeviceName(name?: string | null): ProtocolType | undefined {
44
49
  return /\bpro\s*2\b/i.test(name ?? '') ? 'V2' : undefined;
45
50
  }
@@ -64,37 +69,60 @@ interface TransferCancelToken {
64
69
  cancelled: boolean;
65
70
  }
66
71
 
67
- export default class WebUsbTransport {
72
+ /**
73
+ * The navigator.usb disconnect listener is module-scoped and attached at most
74
+ * once: listeners on navigator.usb are global and never garbage collected, so a
75
+ * per-instance listener would retain every transport instance created across
76
+ * SDK re-initializations. Events are routed to the most recently initialized
77
+ * transport instance instead.
78
+ */
79
+ let activeWebUsbTransport: WebUsbTransport | undefined;
80
+ let usbDisconnectListenerAttached = false;
81
+
82
+ function registerActiveWebUsbTransport(instance: WebUsbTransport, usb: USB) {
83
+ activeWebUsbTransport = instance;
84
+ if (usbDisconnectListenerAttached) return;
85
+ usbDisconnectListenerAttached = true;
86
+ usb.addEventListener('disconnect', event => {
87
+ const serial = event.device?.serialNumber;
88
+ if (typeof serial !== 'string' || serial.length === 0) return;
89
+ activeWebUsbTransport?.markProtocolStale(serial);
90
+ });
91
+ }
92
+
93
+ export default class WebUsbTransport extends ProtocolV2UsbTransportBase<string> {
68
94
  messages: ReturnType<typeof transport.parseConfigure> | undefined;
69
95
 
70
96
  /** Protobuf schema for Protocol V2 transports. */
71
97
  messagesV2: ReturnType<typeof transport.parseConfigure> | undefined;
72
98
 
99
+ private protocolV2SchemaSource: string | undefined;
100
+
73
101
  /** Per-path protocol type detected by active wire-level probe. */
74
102
  private deviceProtocol: Map<string, ProtocolType> = new Map();
75
103
 
76
104
  private deviceProtocolHints: Map<string, ProtocolType> = new Map();
77
105
 
78
- /** 按设备缓存 Protocol V2 frame assembler,保留同一次读取里多出来的后续 frame。 */
79
- private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
80
-
81
- /** 按设备缓存 Protocol V2 session,保持 seq 与设备会话一致递增。 */
82
- private protocolV2Sessions: Map<string, ProtocolV2Session> = new Map();
83
-
84
- /** 当前 Protocol V2 调用的读取超时,由缓存 session 的 readFrame 闭包读取。 */
85
- private protocolV2ReadTimeouts: Map<string, number | undefined> = new Map();
106
+ /**
107
+ * Paths whose cached protocol must be re-probed on the next acquire (a USB
108
+ * disconnect was seen, or a transfer-level reconnect happened mid-call).
109
+ */
110
+ private staleProtocolPaths: Set<string> = new Set();
86
111
 
87
- /** Per-path USB endpoint / interface numbers (discovered from USB descriptors) */
88
- private deviceEndpoints: Map<string, DeviceEndpoints> = new Map();
112
+ /** Paths currently acquired (between a successful acquire() and its release()). */
113
+ private acquiredPaths: Set<string> = new Set();
89
114
 
90
115
  /**
91
- * 早期 Pro2 工程板 USB descriptor 没有烧录 serial number。
92
- * 为这类设备生成会话内稳定的 mock path(同一 USBDevice 实例复用同一 path),
93
- * 避免设备因为空 serial 被发现流程整体丢弃。重新插拔后实例变化,path 会重新生成。
116
+ * The exact USBDevice object each cached protocol was probed against. The
117
+ * browser returns the same object identity for a device as long as it stays
118
+ * connected, and a replug/reboot always yields a new object — so an identity
119
+ * mismatch proves the device was re-enumerated since the probe, even when the
120
+ * disconnect event itself was delayed or missed.
94
121
  */
95
- private mockSerialPaths: WeakMap<USBDevice, string> = new WeakMap();
122
+ private probedDeviceObjects: Map<string, USBDevice> = new Map();
96
123
 
97
- private mockSerialCounter = 0;
124
+ /** Per-path USB endpoint / interface numbers (discovered from USB descriptors) */
125
+ private deviceEndpoints: Map<string, DeviceEndpoints> = new Map();
98
126
 
99
127
  name = 'WebUsbTransport';
100
128
 
@@ -118,6 +146,14 @@ export default class WebUsbTransport {
118
146
 
119
147
  interfaceId = INTERFACE_ID;
120
148
 
149
+ constructor() {
150
+ super({
151
+ router: PROTOCOL_V2_CHANNEL_USB,
152
+ maxFrameBytes: PROTOCOL_V2_FRAME_MAX_BYTES,
153
+ logPrefix: 'ProtocolV2 WebUSB',
154
+ });
155
+ }
156
+
121
157
  /**
122
158
  * Initialize WebUSB transport
123
159
  */
@@ -132,6 +168,22 @@ export default class WebUsbTransport {
132
168
  );
133
169
  }
134
170
  this.usb = usb;
171
+ registerActiveWebUsbTransport(this, usb);
172
+ }
173
+
174
+ /**
175
+ * Protocol type is a property of the physical device keyed by USB serial number.
176
+ * It can only change across a device reboot (e.g. normal ↔ bootloader mode), and
177
+ * a reboot always surfaces as a USB disconnect. Disconnects (and transfer-level
178
+ * reconnects, which cover a missed disconnect event) only MARK the cached probe
179
+ * result stale instead of deleting it: an in-flight session keeps using the old
180
+ * value so the transfer-level reconnect retries can absorb a transient
181
+ * re-enumeration exactly as they did before the cache existed, while the next
182
+ * acquire re-probes from scratch.
183
+ */
184
+ markProtocolStale(path: string) {
185
+ this.staleProtocolPaths.add(path);
186
+ this.probedDeviceObjects.delete(path);
135
187
  }
136
188
 
137
189
  /**
@@ -147,9 +199,20 @@ export default class WebUsbTransport {
147
199
  * Cache the Protocol V2 protobuf schema.
148
200
  */
149
201
  configureProtocolV2(signedData: any) {
202
+ const schemaSource =
203
+ typeof signedData === 'string'
204
+ ? signedData
205
+ : JSON.stringify(signedData) ?? String(signedData);
206
+ if (schemaSource === this.protocolV2SchemaSource) return;
207
+
208
+ const hadProtocolV2Schema = this.protocolV2SchemaSource !== undefined;
150
209
  this.messagesV2 = parseConfigure(signedData);
151
- this.protocolV2Sessions.clear();
152
- this.protocolV2ReadTimeouts.clear();
210
+ this.protocolV2SchemaSource = schemaSource;
211
+ if (!hadProtocolV2Schema) return;
212
+
213
+ this.invalidateAllProtocolV2UsbLinks('Protocol V2 schema reconfigured').catch(error =>
214
+ this.Log?.debug('[WebUsbTransport] schema link cleanup failed:', error)
215
+ );
153
216
  }
154
217
 
155
218
  /**
@@ -181,26 +244,6 @@ export default class WebUsbTransport {
181
244
  return this.deviceList;
182
245
  }
183
246
 
184
- /**
185
- * 设备 path:正常设备直接用 USB serial number;
186
- * 空 serial(早期工程板)回退到会话内稳定的 mock path。
187
- */
188
- private getDevicePath(device: USBDevice): string {
189
- if (typeof device.serialNumber === 'string' && device.serialNumber.length > 0) {
190
- return device.serialNumber;
191
- }
192
- let path = this.mockSerialPaths.get(device);
193
- if (!path) {
194
- this.mockSerialCounter += 1;
195
- path = `mock-serial:${device.vendorId.toString(16)}:${device.productId.toString(16)}:${
196
- this.mockSerialCounter
197
- }`;
198
- this.mockSerialPaths.set(device, path);
199
- this.Log?.debug(`[WebUSB] device has no serial number, using mock path: ${path}`);
200
- }
201
- return path;
202
- }
203
-
204
247
  /**
205
248
  * Get list of connected devices
206
249
  */
@@ -213,11 +256,12 @@ export default class WebUsbTransport {
213
256
  (desc: { vendorId: number; productId: number }) =>
214
257
  dev.vendorId === desc.vendorId && dev.productId === desc.productId
215
258
  );
216
- return isOneKey && !isKnownTrezorWebUsbDevice(dev);
259
+ const hasSerialNumber = typeof dev.serialNumber === 'string' && dev.serialNumber.length > 0;
260
+ return isOneKey && hasSerialNumber && !isKnownTrezorWebUsbDevice(dev);
217
261
  });
218
262
 
219
263
  this.deviceList = onekeyDevices.map(device => {
220
- const path = this.getDevicePath(device);
264
+ const path = device.serialNumber as string;
221
265
  const protocolHint = inferProtocolHintFromDeviceName(device.productName);
222
266
  if (protocolHint) {
223
267
  this.deviceProtocolHints.set(path, protocolHint);
@@ -239,20 +283,61 @@ export default class WebUsbTransport {
239
283
  async acquire(input: AcquireInput) {
240
284
  if (!input.path) return;
241
285
  try {
286
+ await this.rotateProtocolV2UsbGeneration(input.path, 'WebUSB transport acquired');
242
287
  await this.closeOpenDevice(input.path);
243
288
  await this.connect(input.path ?? '', true);
244
- const deviceName = this.deviceList.find(device => device.path === input.path)?.device
245
- .productName;
246
- const protocolHint = input.expectedProtocol
247
- ? undefined
248
- : this.deviceProtocolHints.get(input.path) ?? inferProtocolHintFromDeviceName(deviceName);
249
- if (protocolHint) {
250
- this.deviceProtocolHints.set(input.path, protocolHint);
289
+ if (input.forceProtocolDetection) {
290
+ // Explicit recovery/discovery (e.g. detectDeviceConnectProtocol) must
291
+ // probe on the wire regardless of any cached result — the cached
292
+ // binding may be exactly what the caller is trying to recover from.
293
+ this.staleProtocolPaths.delete(input.path);
294
+ this.deviceProtocol.delete(input.path);
295
+ this.deviceProtocolHints.delete(input.path);
296
+ }
297
+ if (this.staleProtocolPaths.has(input.path)) {
298
+ // The device disconnected (possibly rebooting into another mode) since
299
+ // the protocol was probed — drop the cache so it is re-probed below.
300
+ this.staleProtocolPaths.delete(input.path);
301
+ this.deviceProtocol.delete(input.path);
302
+ }
303
+ if (this.deviceProtocol.has(input.path)) {
304
+ const currentDevice = this.deviceList.find(d => d.path === input.path)?.device;
305
+ if (!currentDevice || currentDevice !== this.probedDeviceObjects.get(input.path)) {
306
+ // The OS re-enumerated the device since the probe (a replug/reboot we
307
+ // may not have seen a disconnect event for) — the cached protocol can
308
+ // no longer be trusted; re-probe on the wire below.
309
+ this.deviceProtocol.delete(input.path);
310
+ }
311
+ }
312
+ const cachedProtocol = this.deviceProtocol.get(input.path);
313
+ if (cachedProtocol && input.expectedProtocol && cachedProtocol !== input.expectedProtocol) {
314
+ // The caller expects a different protocol than the cached probe result;
315
+ // the cache is stale — drop it and re-probe on the wire below.
316
+ this.deviceProtocol.delete(input.path);
251
317
  }
252
- await this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
318
+ if (!this.deviceProtocol.has(input.path)) {
319
+ const deviceName = this.deviceList.find(device => device.path === input.path)?.device
320
+ .productName;
321
+ const protocolHint = input.expectedProtocol
322
+ ? undefined
323
+ : input.protocolHint ??
324
+ this.deviceProtocolHints.get(input.path) ??
325
+ inferProtocolHintFromDeviceName(deviceName);
326
+ if (protocolHint) {
327
+ this.deviceProtocolHints.set(input.path, protocolHint);
328
+ }
329
+ await this.detectProtocol(input.path, input.expectedProtocol, protocolHint);
330
+ const probedDevice = this.deviceList.find(d => d.path === input.path)?.device;
331
+ if (probedDevice) {
332
+ this.probedDeviceObjects.set(input.path, probedDevice);
333
+ }
334
+ }
335
+ this.acquiredPaths.add(input.path);
253
336
  return await Promise.resolve(input.path);
254
337
  } catch (e) {
255
338
  this.Log.debug('acquire error: ', e instanceof Error ? `${e.name}: ${e.message}` : String(e));
339
+ this.acquiredPaths.delete(input.path);
340
+ await this.closeOpenDevice(input.path);
256
341
  throw e;
257
342
  }
258
343
  }
@@ -269,13 +354,17 @@ export default class WebUsbTransport {
269
354
  );
270
355
  }
271
356
 
272
- private createProtocolDetectionError() {
357
+ private createProtocolProbeTimeoutError(expected: ProtocolType, attempts: number) {
273
358
  return ERRORS.TypedError(
274
- HardwareErrorCode.RuntimeError,
275
- 'Unable to detect USB protocol: device did not respond to Protocol V1 Initialize or Protocol V2 Ping'
359
+ HardwareErrorCode.DeviceInitializeFailed,
360
+ `Protocol ${expected} probe timeout after ${attempts} attempts`
276
361
  );
277
362
  }
278
363
 
364
+ private createProtocolDetectionError() {
365
+ return ERRORS.TypedError(HardwareErrorCode.DeviceNotFound);
366
+ }
367
+
279
368
  private async detectProtocol(
280
369
  path: string,
281
370
  expectedProtocol?: ProtocolType,
@@ -286,29 +375,54 @@ export default class WebUsbTransport {
286
375
  this.deviceProtocol.set(path, 'V1');
287
376
  return 'V1';
288
377
  }
378
+ await this.closeConnectionAfterProbe(path);
289
379
  throw this.createProtocolMismatchError(expectedProtocol);
290
380
  }
291
381
 
292
382
  if (expectedProtocol === 'V2') {
293
- // 免探测路径:调用方显式承诺该设备是 V2(例如固件升级重启后的重连场景,
294
- // 上层已经探测过协议并通过 expectedProtocol 传回),这里不再重复探测。
295
- this.deviceProtocol.set(path, 'V2');
296
- return 'V2';
383
+ for (let attempt = 1; attempt <= EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS; attempt += 1) {
384
+ if (await this.probeProtocolV2(path)) {
385
+ this.deviceProtocol.set(path, 'V2');
386
+ return 'V2';
387
+ }
388
+ if (attempt < EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS) {
389
+ await this.resetConnectionAfterProbe(path);
390
+ this.Log?.debug(
391
+ `[WebUsbTransport] Protocol V2 probe timed out, retrying ${
392
+ attempt + 1
393
+ }/${EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS}`
394
+ );
395
+ } else {
396
+ await this.closeConnectionAfterProbe(path);
397
+ }
398
+ }
399
+ this.deviceProtocol.delete(path);
400
+ throw this.createProtocolProbeTimeoutError(
401
+ expectedProtocol,
402
+ EXPECTED_PROTOCOL_V2_PROBE_ATTEMPTS
403
+ );
297
404
  }
298
405
 
299
- // 项目约束:协议判断必须在连接后主动探测,不能依赖设备名/PID/descriptor。
300
- // 设备名 hint(如 "Pro 2")只用于调整探测顺序:hint=V2 时先探 V2、失败回落 V1,
301
- // 不能作为最终结论。
406
+ // Protocol must be actively probed after connection. Name, PID, and descriptors only
407
+ // influence probe order; a V2 hint probes V2 first and falls back to V1.
302
408
  const probeOrder: ProtocolType[] =
303
409
  protocolHint === 'V2' || this.deviceProtocol.get(path) === 'V2' ? ['V2', 'V1'] : ['V1', 'V2'];
304
410
 
305
- for (const protocol of probeOrder) {
411
+ for (const [index, protocol] of probeOrder.entries()) {
306
412
  const detected =
307
413
  protocol === 'V1' ? await this.probeProtocolV1(path) : await this.probeProtocolV2(path);
308
414
  if (detected) {
309
415
  this.deviceProtocol.set(path, protocol);
310
416
  return protocol;
311
417
  }
418
+ if (index < probeOrder.length - 1) {
419
+ // A timed-out WebUSB transferIn cannot be cancelled in place. Closing and
420
+ // reopening the device guarantees the next protocol probe cannot consume a
421
+ // late response from the previous protocol generation.
422
+ await this.resetConnectionAfterProbe(path);
423
+ } else {
424
+ await this.closeConnectionAfterProbe(path);
425
+ }
312
426
  }
313
427
 
314
428
  this.deviceProtocol.delete(path);
@@ -420,16 +534,12 @@ export default class WebUsbTransport {
420
534
  // Discover endpoints from USB descriptors; descriptors are not used for protocol selection.
421
535
  const endpoints = this.discoverEndpoints(device);
422
536
  this.deviceEndpoints.set(path, endpoints);
423
- this.protocolV2Assemblers.get(path)?.reset();
424
- this.protocolV2Assemblers.set(path, new ProtocolV2FrameAssembler(PROTOCOL_V2_FRAME_MAX_BYTES));
425
-
426
537
  await device.claimInterface(endpoints.interfaceNumber);
427
538
  await this.clearEndpointHalt(device, 'in', endpoints.endpointIn);
428
539
  await this.clearEndpointHalt(device, 'out', endpoints.endpointOut);
429
540
  }
430
541
 
431
542
  private async closeOpenDevice(path: string) {
432
- this.protocolV2Assemblers.get(path)?.reset();
433
543
  const current = this.deviceList.find(device => device.path === path)?.device;
434
544
  if (!current?.opened) return;
435
545
 
@@ -462,7 +572,25 @@ export default class WebUsbTransport {
462
572
  }
463
573
  }
464
574
 
575
+ /**
576
+ * With the protocol cache surviving release(), deviceProtocol presence no
577
+ * longer implies an active session. Guard call()/post() explicitly so a
578
+ * post-release straggler fails fast instead of silently reopening the device
579
+ * and driving it outside any session (pre-cache behavior: the deleted
580
+ * protocol entry produced the same fail-fast).
581
+ */
582
+ private assertAcquired(path: string) {
583
+ if (!this.acquiredPaths.has(path)) {
584
+ throw ERRORS.TypedError(HardwareErrorCode.RuntimeError, `Device is not acquired for ${path}`);
585
+ }
586
+ }
587
+
465
588
  async post(session: string, name: string, data: Record<string, unknown>) {
589
+ this.assertAcquired(session);
590
+ if (this.deviceProtocol.get(session) === 'V2') {
591
+ await this.sendProtocolV2UsbFlowControl(session, name, data);
592
+ return;
593
+ }
466
594
  await this.call(session, name, data);
467
595
  }
468
596
 
@@ -500,6 +628,11 @@ export default class WebUsbTransport {
500
628
  error
501
629
  )}`
502
630
  );
631
+ // The device dropped off the bus mid-call and may have rebooted into a
632
+ // different mode. The in-flight retry keeps the known protocol, but the
633
+ // next acquire must re-probe — this also self-heals a stale cache when the
634
+ // USB disconnect event itself was missed.
635
+ this.staleProtocolPaths.add(path);
503
636
  await wait(attempt * PACKET_IO_RETRY_DELAY);
504
637
 
505
638
  try {
@@ -624,33 +757,30 @@ export default class WebUsbTransport {
624
757
  throw lastError;
625
758
  }
626
759
 
627
- private async resetConnectionAfterProbe(path: string) {
628
- this.protocolV2Assemblers.get(path)?.reset();
629
- this.protocolV2Sessions.delete(path);
630
- this.protocolV2ReadTimeouts.delete(path);
631
-
632
- try {
633
- const device = await this.findDevice(path);
634
- if (device.opened) {
635
- const endpoints = this.deviceEndpoints.get(path);
636
- const ifaceNum = endpoints?.interfaceNumber ?? this.interfaceId;
637
- try {
638
- await device.releaseInterface(ifaceNum);
639
- } catch (error) {
640
- this.Log.debug('[WebUsbTransport] releaseInterface after protocol probe error:', error);
641
- }
642
- await device.close();
643
- }
644
- } catch (error) {
645
- this.Log.debug('[WebUsbTransport] close after protocol probe error:', error);
760
+ private async transferInOnce(path: string, length: number): Promise<DataView> {
761
+ const device = await this.findDevice(path);
762
+ if (!device.opened) {
763
+ throw new Error('USBDevice is not open for transferIn');
646
764
  }
765
+ const endpoints = this.deviceEndpoints.get(path);
766
+ const endpointIn = endpoints?.endpointIn ?? this.endpointId;
767
+ const result = await device.transferIn(endpointIn, length);
768
+ return this.getTransferInData(result);
769
+ }
770
+
771
+ private async closeConnectionAfterProbe(path: string) {
772
+ await this.rotateProtocolV2UsbGeneration(path, 'WebUSB protocol probe reset');
773
+ await this.closeOpenDevice(path);
774
+ }
647
775
 
776
+ private async resetConnectionAfterProbe(path: string) {
777
+ await this.closeConnectionAfterProbe(path);
648
778
  await this.getConnectedDevices();
649
779
  await this.connect(path, false);
650
780
  }
651
781
 
652
782
  private async withProtocolReadTimeout<T>(
653
- _path: string,
783
+ path: string,
654
784
  promise: Promise<T>,
655
785
  timeoutMs: number,
656
786
  protocol: ProtocolType,
@@ -672,9 +802,16 @@ export default class WebUsbTransport {
672
802
  return await Promise.race([
673
803
  guardedPromise,
674
804
  new Promise<never>((_, reject) => {
675
- timer = setTimeout(() => {
805
+ timer = setTimeout(async () => {
676
806
  timedOut = true;
677
807
  onTimeout?.();
808
+ if (protocol === 'V1') {
809
+ try {
810
+ await this.resetConnectionAfterProbe(path);
811
+ } catch (error) {
812
+ this.Log.debug('[WebUsbTransport] reset after Protocol V1 timeout failed:', error);
813
+ }
814
+ }
678
815
  reject(new Error(`Protocol ${protocol} read timeout after ${timeoutMs}ms`));
679
816
  }, timeoutMs);
680
817
  }),
@@ -690,7 +827,14 @@ export default class WebUsbTransport {
690
827
  }
691
828
 
692
829
  try {
693
- await this.callProtocolV1(path, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT });
830
+ await this.callProtocolV1(
831
+ path,
832
+ 'Initialize',
833
+ {},
834
+ {
835
+ timeoutMs: PROTOCOL_V1_PROBE_TIMEOUT,
836
+ }
837
+ );
694
838
  return true;
695
839
  } catch (_error) {
696
840
  return false;
@@ -704,10 +848,9 @@ export default class WebUsbTransport {
704
848
 
705
849
  return probeProtocolV2Helper({
706
850
  call: (name, data, options) => this.callProtocolV2(path, name, data, options),
707
- timeoutMs: PROTOCOL_PROBE_TIMEOUT,
851
+ timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT,
708
852
  logger: this.Log,
709
853
  logPrefix: 'ProtocolV2 WebUSB',
710
- onProbeFailed: () => this.resetConnectionAfterProbe(path),
711
854
  });
712
855
  }
713
856
 
@@ -723,6 +866,7 @@ export default class WebUsbTransport {
723
866
  if (this.messages == null) {
724
867
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
725
868
  }
869
+ this.assertAcquired(path);
726
870
 
727
871
  const device = await this.findDevice(path);
728
872
  if (!device) {
@@ -737,10 +881,6 @@ export default class WebUsbTransport {
737
881
  );
738
882
  }
739
883
 
740
- if (!shouldSuppressHighVolumeCallLog(name)) {
741
- this.Log.debug('transport call', createTransportCallLog(name, protocol));
742
- }
743
-
744
884
  if (protocol === 'V2') {
745
885
  return this.callProtocolV2(path, name, data, options);
746
886
  }
@@ -788,94 +928,7 @@ export default class WebUsbTransport {
788
928
  data: Record<string, unknown>,
789
929
  options?: TransportCallOptions
790
930
  ) {
791
- const protocolV1Messages = this.messages;
792
- if (!this.messagesV2) {
793
- throw ERRORS.TypedError(
794
- HardwareErrorCode.TransportNotConfigured,
795
- 'Protocol V2 schema not configured'
796
- );
797
- }
798
- if (!protocolV1Messages) {
799
- throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
800
- }
801
-
802
- let session = this.protocolV2Sessions.get(path);
803
- if (!session) {
804
- session = new ProtocolV2Session({
805
- schemas: {
806
- protocolV1: protocolV1Messages,
807
- protocolV2: this.messagesV2,
808
- },
809
- router: PROTOCOL_V2_CHANNEL_USB,
810
- writeFrame: (frame: Uint8Array) => this.transferOutOnce(path, frame),
811
- readFrame: () => this.receiveProtocolV2Frame(path, this.protocolV2ReadTimeouts.get(path)),
812
- logger: this.Log,
813
- logPrefix: 'ProtocolV2 WebUSB',
814
- createTimeoutError: (messageName: string, timeoutMs: number) =>
815
- new Error(`Protocol V2 response timeout after ${timeoutMs}ms for ${messageName}`),
816
- });
817
- this.protocolV2Sessions.set(path, session);
818
- }
819
-
820
- this.protocolV2ReadTimeouts.set(path, options?.timeoutMs);
821
- this.protocolV2Assemblers.get(path)?.reset();
822
- try {
823
- return await session.call(name, data, options);
824
- } catch (error) {
825
- const message =
826
- error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
827
- if (message.includes('protocol v2 read timeout') || message.includes('response timeout')) {
828
- try {
829
- await this.resetConnectionAfterProbe(path);
830
- } catch (resetError) {
831
- this.Log.debug('[WebUsbTransport] Protocol V2 timeout reset failed:', resetError);
832
- }
833
- }
834
- throw error;
835
- } finally {
836
- this.protocolV2ReadTimeouts.delete(path);
837
- }
838
- }
839
-
840
- private async receiveProtocolV2Frame(path: string, timeoutMs?: number): Promise<Uint8Array> {
841
- let assembler = this.protocolV2Assemblers.get(path);
842
- if (!assembler) {
843
- assembler = new ProtocolV2FrameAssembler(PROTOCOL_V2_FRAME_MAX_BYTES);
844
- this.protocolV2Assemblers.set(path, assembler);
845
- }
846
-
847
- let frame: Uint8Array | undefined = assembler.push(new Uint8Array(0));
848
- const deadline = timeoutMs ? Date.now() + timeoutMs : undefined;
849
-
850
- while (!frame) {
851
- const cancelToken = { cancelled: false };
852
- const transferIn = this.transferInWithRetry(path, PROTOCOL_V2_FRAME_MAX_BYTES, cancelToken);
853
- const dataView = deadline
854
- ? await this.withProtocolReadTimeout(
855
- path,
856
- transferIn,
857
- Math.max(deadline - Date.now(), 1),
858
- 'V2',
859
- () => {
860
- cancelToken.cancelled = true;
861
- }
862
- )
863
- : await transferIn;
864
- const bytes = new Uint8Array(
865
- this.toArrayBuffer(
866
- dataView.buffer.slice(dataView.byteOffset, dataView.byteOffset + dataView.byteLength)
867
- )
868
- );
869
- try {
870
- frame = assembler.push(bytes);
871
- } catch (error) {
872
- throw ERRORS.TypedError(
873
- HardwareErrorCode.NetworkError,
874
- error instanceof Error ? error.message : String(error)
875
- );
876
- }
877
- }
878
- return frame;
931
+ return this.callProtocolV2Usb(path, name, data, options);
879
932
  }
880
933
 
881
934
  /**
@@ -930,20 +983,67 @@ export default class WebUsbTransport {
930
983
  * Release device
931
984
  */
932
985
  async release(path: string) {
933
- const device: USBDevice = await this.findDevice(path);
934
- const endpoints = this.deviceEndpoints.get(path);
935
- const ifaceNum = endpoints?.interfaceNumber ?? this.interfaceId;
936
- await device.releaseInterface(ifaceNum);
937
- await device.close();
938
- this.deviceProtocol.delete(path);
939
- this.deviceProtocolHints.delete(path);
940
- this.protocolV2Assemblers.get(path)?.reset();
941
- this.protocolV2Assemblers.delete(path);
942
- this.protocolV2Sessions.delete(path);
943
- this.protocolV2ReadTimeouts.delete(path);
986
+ this.acquiredPaths.delete(path);
987
+ await this.invalidateProtocolV2UsbLink(path, 'WebUSB transport released');
988
+ await this.closeOpenDevice(path);
989
+ // Keep deviceProtocol/deviceProtocolHints across release: the probe result is a
990
+ // physical-device property, so the next acquire can skip the wire-level probe.
991
+ // V2 entries are still dropped by onProtocolV2UsbLinkInvalidated via the link
992
+ // invalidation above, and any entry is re-probed after a USB disconnect or a
993
+ // transfer-level reconnect (see markProtocolStale).
944
994
  this.deviceEndpoints.delete(path);
945
995
  }
946
996
 
997
+ protected getProtocolV2UsbSchemas(): ProtocolV2Schemas {
998
+ if (!this.messages || !this.messagesV2) {
999
+ throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
1000
+ }
1001
+ return {
1002
+ protocolV1: this.messages,
1003
+ protocolV2: this.messagesV2,
1004
+ };
1005
+ }
1006
+
1007
+ protected getProtocolV2UsbLogger() {
1008
+ return this.Log;
1009
+ }
1010
+
1011
+ protected async writeProtocolV2UsbPacket(
1012
+ path: string,
1013
+ frame: Uint8Array,
1014
+ _context: ProtocolV2CallContext
1015
+ ): Promise<void> {
1016
+ await this.transferOutOnce(path, frame);
1017
+ }
1018
+
1019
+ protected async readProtocolV2UsbPacket(
1020
+ path: string,
1021
+ _context: ProtocolV2CallContext
1022
+ ): Promise<Uint8Array> {
1023
+ const dataView = await this.transferInOnce(path, PROTOCOL_V2_FRAME_MAX_BYTES);
1024
+ return new Uint8Array(
1025
+ this.toArrayBuffer(
1026
+ dataView.buffer.slice(dataView.byteOffset, dataView.byteOffset + dataView.byteLength)
1027
+ )
1028
+ );
1029
+ }
1030
+
1031
+ protected async resetProtocolV2UsbNativeLink(path: string, _reason: string): Promise<void> {
1032
+ await this.closeOpenDevice(path);
1033
+ }
1034
+
1035
+ protected onProtocolV2UsbLinkInvalidated(path: string, reason: string) {
1036
+ this.deviceProtocol.delete(path);
1037
+ this.Log?.debug(`[WebUsbTransport] Protocol V2 link invalidated: ${path}`, reason);
1038
+ }
1039
+
1040
+ protected createProtocolV2UsbTimeoutError(name: string, timeoutMs: number): Error {
1041
+ return new ProtocolV2LinkError(
1042
+ 'response-timeout',
1043
+ `Protocol V2 response timeout after ${timeoutMs}ms for ${name}`
1044
+ );
1045
+ }
1046
+
947
1047
  /**
948
1048
  * Expose the detected protocol type for a given device path.
949
1049
  * Used by upper layers (e.g. TransportManager) to select the correct schema.