@onekeyfe/hd-transport-react-native 1.2.8-alpha.115 → 1.2.8-alpha.116

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/index.ts CHANGED
@@ -190,6 +190,11 @@ const ANDROID_NOTIFY_READY_DELAY_MS = 300;
190
190
  export type ProtocolV2BleTuning = {
191
191
  iosPacketLength?: number;
192
192
  androidPacketLength?: number;
193
+ /**
194
+ * Write each multi-packet high-throughput frame with one native call when the native
195
+ * BLE module supports it. Defaults to true; false keeps the per-packet JS write loop.
196
+ */
197
+ nativeFrameWrite?: boolean;
193
198
  };
194
199
 
195
200
  type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
@@ -197,6 +202,7 @@ type ResolvedProtocolV2BleTuning = Required<ProtocolV2BleTuning>;
197
202
  const DEFAULT_PROTOCOL_V2_BLE_TUNING: ResolvedProtocolV2BleTuning = {
198
203
  iosPacketLength: IOS_PROTOCOL_V2_PACKET_LENGTH,
199
204
  androidPacketLength: ANDROID_PROTOCOL_V2_PACKET_LENGTH,
205
+ nativeFrameWrite: true,
200
206
  };
201
207
 
202
208
  let protocolV2BleTuning: ResolvedProtocolV2BleTuning = { ...DEFAULT_PROTOCOL_V2_BLE_TUNING };
@@ -217,6 +223,10 @@ export function configureProtocolV2BleTuning(tuning: ProtocolV2BleTuning = {}) {
217
223
  tuning.androidPacketLength,
218
224
  protocolV2BleTuning.androidPacketLength
219
225
  ),
226
+ nativeFrameWrite:
227
+ typeof tuning.nativeFrameWrite === 'boolean'
228
+ ? tuning.nativeFrameWrite
229
+ : protocolV2BleTuning.nativeFrameWrite,
220
230
  };
221
231
  Log?.debug('[ReactNativeBleTransport] BLE tuning configured', protocolV2BleTuning);
222
232
  }
@@ -230,6 +240,138 @@ export function getProtocolV2BleTuning() {
230
240
  return { ...protocolV2BleTuning };
231
241
  }
232
242
 
243
+ /**
244
+ * Optional frame-write extension of the App's patched react-native-ble-plx. The SDK depends on
245
+ * the unpatched release, so the shape is declared here and probed at runtime.
246
+ */
247
+ type ProtocolV2NativeFrameWriteExtension = {
248
+ isWriteCharacteristicWithoutResponseFrameSupported?: () => boolean;
249
+ writeCharacteristicWithoutResponseFrame?: (
250
+ characteristicIdentifier: number,
251
+ base64Frame: string,
252
+ packetSize: number,
253
+ transactionId: string
254
+ ) => Promise<void>;
255
+ };
256
+
257
+ type ProtocolV2NativeFrameWriter = BlePlxManager & Required<ProtocolV2NativeFrameWriteExtension>;
258
+
259
+ type ActiveProtocolV2FrameWrite = {
260
+ transactionId: string;
261
+ generation: number;
262
+ cancel: (error: Error) => void;
263
+ };
264
+
265
+ /**
266
+ * A newer JS bundle can run on an older native binary that ships the JS wrapper without the
267
+ * native method, so support comes from the wrapper's native check, never from its presence.
268
+ */
269
+ const getProtocolV2NativeFrameWriter = (
270
+ manager: BlePlxManager | undefined
271
+ ): ProtocolV2NativeFrameWriter | undefined => {
272
+ const candidate = manager as (BlePlxManager & ProtocolV2NativeFrameWriteExtension) | undefined;
273
+ if (!candidate || typeof candidate.writeCharacteristicWithoutResponseFrame !== 'function') {
274
+ return undefined;
275
+ }
276
+ try {
277
+ return candidate.isWriteCharacteristicWithoutResponseFrameSupported?.() === true
278
+ ? (candidate as ProtocolV2NativeFrameWriter)
279
+ : undefined;
280
+ } catch {
281
+ return undefined;
282
+ }
283
+ };
284
+
285
+ const getNativeBleErrorReason = (error: unknown): string | undefined => {
286
+ const { reason, message } = (error ?? {}) as { reason?: unknown; message?: unknown };
287
+ if (typeof reason === 'string' && reason) return reason;
288
+ return typeof message === 'string' && message ? message : undefined;
289
+ };
290
+
291
+ type ProtocolV2FrameWriteMode = 'native-frame' | 'per-packet';
292
+
293
+ const nowMs = () =>
294
+ typeof performance !== 'undefined' && typeof performance.now === 'function'
295
+ ? performance.now()
296
+ : Date.now();
297
+
298
+ const roundMs = (ms: number) => Math.round(ms * 10) / 10;
299
+
300
+ /** Upper bounds of the per-packet write histogram buckets; the last bucket is open. */
301
+ const FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS = [1, 2, 3, 5, 8];
302
+
303
+ const createDurationStats = () => {
304
+ let total = 0;
305
+ let count = 0;
306
+ let max = 0;
307
+ return {
308
+ add(ms: number) {
309
+ total += ms;
310
+ count += 1;
311
+ max = Math.max(max, ms);
312
+ },
313
+ summarize: () => ({
314
+ total: roundMs(total),
315
+ avg: count ? roundMs(total / count) : 0,
316
+ max: roundMs(max),
317
+ }),
318
+ };
319
+ };
320
+
321
+ /** Scalar-only timing of one pipelined FilesystemFileWrite call. */
322
+ const createProtocolV2FileWritePerf = () => {
323
+ const startedAt = nowMs();
324
+ let nativeFrames = 0;
325
+ let frames = 0;
326
+ let packets = 0;
327
+ let frameBytes = 0;
328
+ const write = createDurationStats();
329
+ const readWait = createDurationStats();
330
+ const packet = createDurationStats();
331
+ const packetHistogram = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.map(() => 0).concat(0);
332
+
333
+ return {
334
+ /** Called before each frame write so a frame that fails still reports its mode. */
335
+ startFrame(mode: ProtocolV2FrameWriteMode) {
336
+ if (mode === 'native-frame') nativeFrames += 1;
337
+ },
338
+ recordFrame(bytes: number, framePackets: number, elapsedMs: number) {
339
+ frames += 1;
340
+ packets += framePackets;
341
+ frameBytes += bytes;
342
+ write.add(elapsedMs);
343
+ },
344
+ recordPacket(elapsedMs: number) {
345
+ packet.add(elapsedMs);
346
+ const bucket = FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.findIndex(bound => elapsedMs < bound);
347
+ packetHistogram[bucket < 0 ? FILE_WRITE_PACKET_HISTOGRAM_BOUNDS_MS.length : bucket] += 1;
348
+ },
349
+ recordReadWait(elapsedMs: number) {
350
+ readWait.add(elapsedMs);
351
+ },
352
+ summarize(ok: boolean) {
353
+ const mode: ProtocolV2FrameWriteMode = nativeFrames > 0 ? 'native-frame' : 'per-packet';
354
+ const packetStats = packet.summarize();
355
+ return {
356
+ platform: Platform.OS,
357
+ mode,
358
+ ok,
359
+ frames,
360
+ packets,
361
+ frameBytes,
362
+ elapsedMs: roundMs(nowMs() - startedAt),
363
+ writeMs: write.summarize(),
364
+ readWaitMs: readWait.summarize(),
365
+ ...(mode === 'per-packet'
366
+ ? { packetMs: { avg: packetStats.avg, max: packetStats.max, hist: [...packetHistogram] } }
367
+ : {}),
368
+ };
369
+ },
370
+ };
371
+ };
372
+
373
+ type ProtocolV2FileWritePerf = ReturnType<typeof createProtocolV2FileWritePerf>;
374
+
233
375
  function getDeviceDisplayName(device?: Device | null) {
234
376
  return device?.name || device?.localName || null;
235
377
  }
@@ -560,6 +702,13 @@ export default class ReactNativeBleTransport {
560
702
 
561
703
  private androidPriorityResetTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
562
704
 
705
+ /** In-flight native frame write per device; Protocol V2 writes are serialized per device. */
706
+ private protocolV2FrameWrites: Map<string, ActiveProtocolV2FrameWrite> = new Map();
707
+
708
+ private protocolV2FrameWriteCounter = 0;
709
+
710
+ private protocolV2FileWritePerfs: Map<string, ProtocolV2FileWritePerf> = new Map();
711
+
563
712
  private nextMonitorToken = 1;
564
713
 
565
714
  /** Serializes transport lifecycle changes for the same physical device. */
@@ -1529,11 +1678,13 @@ export default class ReactNativeBleTransport {
1529
1678
  }
1530
1679
 
1531
1680
  private async releaseUnlocked(uuid: string, onclose = false) {
1681
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1532
1682
  await this.protocolV2Links.invalidateLink(uuid, 'React Native BLE transport released');
1533
1683
  return this.releaseNative(uuid, onclose);
1534
1684
  }
1535
1685
 
1536
1686
  private async releaseNative(uuid: string, onclose = false) {
1687
+ this.cancelProtocolV2FrameWrite(uuid, new Error('React Native BLE transport released'));
1537
1688
  const transport = transportCache[uuid];
1538
1689
  const manager = this.blePlxManager;
1539
1690
  if (this.runPromise && this.runPromiseDeviceId === uuid) {
@@ -1954,6 +2105,7 @@ export default class ReactNativeBleTransport {
1954
2105
  }
1955
2106
 
1956
2107
  private async disconnectUnlocked(session: string) {
2108
+ this.cancelProtocolV2FrameWrite(session, new Error('React Native BLE transport disconnected'));
1957
2109
  await this.protocolV2Links.invalidateLink(session, 'React Native BLE transport disconnected');
1958
2110
  const transport = transportCache[session];
1959
2111
  const manager = this.blePlxManager;
@@ -2431,6 +2583,13 @@ export default class ReactNativeBleTransport {
2431
2583
  consecutiveWriteTimeouts: timeouts,
2432
2584
  });
2433
2585
 
2586
+ this.cancelProtocolV2FrameWrite(
2587
+ uuid,
2588
+ ERRORS.TypedError(
2589
+ HardwareErrorCode.BleWriteCharacteristicError,
2590
+ `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
2591
+ )
2592
+ );
2434
2593
  const wedged = transportCache[uuid];
2435
2594
  this.disconnect(uuid).catch(error => {
2436
2595
  Log?.debug('[ReactNativeBleTransport] wedged link teardown failed (ignored):', error);
@@ -2458,6 +2617,10 @@ export default class ReactNativeBleTransport {
2458
2617
  const manager = this.blePlxManager;
2459
2618
  this.blePlxManager = undefined;
2460
2619
  const reason = 'React Native BLE manager reset';
2620
+ // Cancel through the manager that started each frame before destroy() drops its queue.
2621
+ Array.from(this.protocolV2FrameWrites.keys()).forEach(uuid =>
2622
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason))
2623
+ );
2461
2624
  // Destroying the shared manager invalidates every peripheral it owns. Notify
2462
2625
  // each cached session before clearing generations so Core cannot retain a
2463
2626
  // silently stale connection for an unrelated device.
@@ -2929,22 +3092,208 @@ export default class ReactNativeBleTransport {
2929
3092
  androidPacketLength: tuning.androidPacketLength,
2930
3093
  mtu: transport.mtuSize,
2931
3094
  });
2932
- await writeProtocolV2BleFrame({
2933
- frame,
2934
- packetCapacity,
2935
- assertActive: assertCurrentGeneration,
2936
- signal: context.signal,
2937
- abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
2938
- wait: delay,
2939
- writePacket: packet =>
2940
- this.writeProtocolV2Packet(
2941
- uuid,
2942
- transport,
2943
- Buffer.from(packet).toString('base64'),
2944
- context,
2945
- assertCurrentGeneration
2946
- ),
3095
+ const perf =
3096
+ context.messageName === 'FilesystemFileWrite'
3097
+ ? this.protocolV2FileWritePerfs.get(uuid)
3098
+ : undefined;
3099
+ const startedAt = perf ? nowMs() : 0;
3100
+ const nativeFrameWriter =
3101
+ frame.length > packetCapacity
3102
+ ? this.resolveProtocolV2NativeFrameWriter(transport, context, tuning.nativeFrameWrite)
3103
+ : undefined;
3104
+ perf?.startFrame(nativeFrameWriter ? 'native-frame' : 'per-packet');
3105
+ if (nativeFrameWriter) {
3106
+ await this.writeProtocolV2NativeFrame(
3107
+ uuid,
3108
+ transport,
3109
+ nativeFrameWriter,
3110
+ frame,
3111
+ packetCapacity,
3112
+ context,
3113
+ assertCurrentGeneration
3114
+ );
3115
+ } else {
3116
+ await writeProtocolV2BleFrame({
3117
+ frame,
3118
+ packetCapacity,
3119
+ assertActive: assertCurrentGeneration,
3120
+ signal: context.signal,
3121
+ abortMessage: `Protocol V2 BLE write aborted for ${context.messageName}`,
3122
+ wait: delay,
3123
+ writePacket: async packet => {
3124
+ const packetStartedAt = perf ? nowMs() : 0;
3125
+ await this.writeProtocolV2Packet(
3126
+ uuid,
3127
+ transport,
3128
+ Buffer.from(packet).toString('base64'),
3129
+ context,
3130
+ assertCurrentGeneration
3131
+ );
3132
+ perf?.recordPacket(nowMs() - packetStartedAt);
3133
+ },
3134
+ });
3135
+ }
3136
+ perf?.recordFrame(frame.length, Math.ceil(frame.length / packetCapacity), nowMs() - startedAt);
3137
+ }
3138
+
3139
+ /**
3140
+ * The native frame write only replaces the per-packet loop where its JS<->native round trips
3141
+ * dominate: multi-packet (checked by the caller) high-throughput frames written without response.
3142
+ */
3143
+ private resolveProtocolV2NativeFrameWriter(
3144
+ transport: BleTransport,
3145
+ context: Pick<ProtocolV2CallContext, 'highThroughput' | 'writeWithResponse'>,
3146
+ nativeFrameWrite: boolean
3147
+ ): ProtocolV2NativeFrameWriter | undefined {
3148
+ if (!context.highThroughput || nativeFrameWrite === false) return undefined;
3149
+ if (
3150
+ shouldWriteProtocolV2WithResponse({
3151
+ platform: Platform.OS,
3152
+ highThroughput: context.highThroughput,
3153
+ requestedWithResponse: context.writeWithResponse,
3154
+ characteristic: transport.writeCharacteristic,
3155
+ })
3156
+ ) {
3157
+ return undefined;
3158
+ }
3159
+ if (typeof transport.writeCharacteristic.id !== 'number') return undefined;
3160
+ return getProtocolV2NativeFrameWriter(this.blePlxManager);
3161
+ }
3162
+
3163
+ /**
3164
+ * Writes one frame with a single native call that sends its packets in order without response.
3165
+ * Nothing here retries it: a resend could duplicate bytes the device already received. The
3166
+ * native transaction is cancelled on abort, watchdog expiry, generation change and link
3167
+ * teardown so the native side stops writing a frame nobody waits for any more.
3168
+ */
3169
+ private async writeProtocolV2NativeFrame(
3170
+ uuid: string,
3171
+ transport: BleTransport,
3172
+ manager: ProtocolV2NativeFrameWriter,
3173
+ frame: Uint8Array,
3174
+ packetCapacity: number,
3175
+ context: ProtocolV2CallContext,
3176
+ assertCurrentGeneration: () => void
3177
+ ) {
3178
+ const abortMessage = `Protocol V2 BLE write aborted for ${context.messageName}`;
3179
+ assertCurrentGeneration();
3180
+ if (context.signal.aborted) {
3181
+ throw new Error(abortMessage);
3182
+ }
3183
+
3184
+ this.protocolV2FrameWriteCounter += 1;
3185
+ const transactionId = `${uuid}:v2frame:${context.generation}:${this.protocolV2FrameWriteCounter}`;
3186
+ let cancelError: Error | undefined;
3187
+ let rejectCancelled: (error: Error) => void = () => undefined;
3188
+ const cancelled = new Promise<never>((_, reject) => {
3189
+ rejectCancelled = reject;
2947
3190
  });
3191
+ const active: ActiveProtocolV2FrameWrite = {
3192
+ transactionId,
3193
+ generation: context.generation,
3194
+ cancel: error => {
3195
+ if (cancelError) return;
3196
+ cancelError = error;
3197
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3198
+ this.protocolV2FrameWrites.delete(uuid);
3199
+ }
3200
+ rejectCancelled(error);
3201
+ this.cancelNativeTransaction(manager, transactionId);
3202
+ },
3203
+ };
3204
+ // Same rule as writeBlePacket: a superseded generation must not tear down the current link.
3205
+ const isCurrentOwner = () => {
3206
+ try {
3207
+ assertCurrentGeneration();
3208
+ return !context.signal.aborted;
3209
+ } catch {
3210
+ return false;
3211
+ }
3212
+ };
3213
+ const onAbort = () => active.cancel(new Error(abortMessage));
3214
+ let timer: ReturnType<typeof setTimeout> | undefined;
3215
+ let completed = false;
3216
+ let nativeError: unknown;
3217
+ try {
3218
+ const nativeWrite = Promise.resolve(
3219
+ manager.writeCharacteristicWithoutResponseFrame(
3220
+ transport.writeCharacteristic.id,
3221
+ Buffer.from(frame).toString('base64'),
3222
+ packetCapacity,
3223
+ transactionId
3224
+ )
3225
+ );
3226
+ // A cancelled or timed-out frame still settles natively later; that outcome is ignored.
3227
+ nativeWrite.catch(() => undefined);
3228
+ this.protocolV2FrameWrites.set(uuid, active);
3229
+ context.signal.addEventListener('abort', onAbort);
3230
+ await Promise.race([
3231
+ nativeWrite,
3232
+ cancelled,
3233
+ new Promise<never>((_, reject) => {
3234
+ timer = setTimeout(() => {
3235
+ const owner = isCurrentOwner();
3236
+ const error = ERRORS.TypedError(
3237
+ HardwareErrorCode.BleWriteCharacteristicError,
3238
+ `BLE write timeout after ${BLE_WRITE_PACKET_TIMEOUT_MS}ms`
3239
+ );
3240
+ active.cancel(error);
3241
+ reject(error);
3242
+ if (owner) {
3243
+ this.tearDownWedgedLink(uuid);
3244
+ } else {
3245
+ Log?.debug('[ReactNativeBleTransport] stale BLE frame write timed out, link kept');
3246
+ }
3247
+ }, BLE_WRITE_PACKET_TIMEOUT_MS);
3248
+ }),
3249
+ ]);
3250
+ completed = true;
3251
+ } catch (error) {
3252
+ nativeError = error;
3253
+ } finally {
3254
+ if (timer) clearTimeout(timer);
3255
+ context.signal.removeEventListener('abort', onAbort);
3256
+ }
3257
+
3258
+ if (completed) {
3259
+ this.writeTimeoutCounts.delete(uuid);
3260
+ try {
3261
+ assertCurrentGeneration();
3262
+ } catch (error) {
3263
+ active.cancel(error instanceof Error ? error : new Error(String(error)));
3264
+ }
3265
+ }
3266
+ if (this.protocolV2FrameWrites.get(uuid) === active) {
3267
+ this.protocolV2FrameWrites.delete(uuid);
3268
+ }
3269
+ if (cancelError) throw cancelError;
3270
+ if (completed) return;
3271
+ if (isNativeBleDisconnectError(nativeError)) {
3272
+ throw toBleDisconnectHardwareError(nativeError);
3273
+ }
3274
+ throw ERRORS.TypedError(
3275
+ HardwareErrorCode.BleWriteCharacteristicError,
3276
+ getNativeBleErrorReason(nativeError)
3277
+ );
3278
+ }
3279
+
3280
+ /** Stops the native frame write in flight on `uuid`, optionally only one of `generation`. */
3281
+ private cancelProtocolV2FrameWrite(uuid: string, error: Error, generation?: number) {
3282
+ const active = this.protocolV2FrameWrites.get(uuid);
3283
+ if (!active || (generation !== undefined && active.generation !== generation)) return;
3284
+ active.cancel(error);
3285
+ }
3286
+
3287
+ private cancelNativeTransaction(manager: BlePlxManager, transactionId: string) {
3288
+ const logFailure = (error: unknown) =>
3289
+ Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write cancellation failed', {
3290
+ error: error instanceof Error ? error.message : String(error),
3291
+ });
3292
+ try {
3293
+ Promise.resolve(manager.cancelTransaction(transactionId)).catch(logFailure);
3294
+ } catch (error) {
3295
+ logFailure(error);
3296
+ }
2948
3297
  }
2949
3298
 
2950
3299
  private async callProtocolV2(
@@ -2993,20 +3342,50 @@ export default class ReactNativeBleTransport {
2993
3342
  packetCapacity,
2994
3343
  });
2995
3344
  }
3345
+ const frameWriteMode: ProtocolV2FrameWriteMode = this.resolveProtocolV2NativeFrameWriter(
3346
+ currentTransport,
3347
+ { highThroughput: true, writeWithResponse: options?.writeWithResponse },
3348
+ tuning.nativeFrameWrite
3349
+ )
3350
+ ? 'native-frame'
3351
+ : 'per-packet';
3352
+ const frameWriteModeSignature = `frameWriteMode:${frameWriteMode}`;
3353
+ if (!loggedSignatures.has(frameWriteModeSignature)) {
3354
+ loggedSignatures.add(frameWriteModeSignature);
3355
+ this.protocolV2HighVolumeLogSignatures.set(uuid, loggedSignatures);
3356
+ Log?.debug('[ReactNativeBleTransport] Protocol V2 frame write mode', {
3357
+ platform: Platform.OS,
3358
+ mode: frameWriteMode,
3359
+ nativeFrameWrite: tuning.nativeFrameWrite,
3360
+ nativeFrameWriteSupported: !!getProtocolV2NativeFrameWriter(this.blePlxManager),
3361
+ packetCapacity,
3362
+ });
3363
+ }
2996
3364
  }
2997
3365
 
2998
3366
  if (highThroughputWrite) {
2999
3367
  await this.enableAndroidHighConnectionPriority(uuid);
3000
3368
  }
3001
3369
 
3370
+ const fileWritePerf =
3371
+ name === 'FilesystemFileWrite' && options?.fileWritePipeline
3372
+ ? createProtocolV2FileWritePerf()
3373
+ : undefined;
3374
+ if (fileWritePerf) {
3375
+ this.protocolV2FileWritePerfs.set(uuid, fileWritePerf);
3376
+ }
3377
+ let fileWriteOk = false;
3378
+
3002
3379
  try {
3003
- return await this.protocolV2Links.call(
3380
+ const response = await this.protocolV2Links.call(
3004
3381
  uuid,
3005
3382
  () => this.createProtocolV2Adapter(uuid),
3006
3383
  name,
3007
3384
  data,
3008
3385
  callOptions
3009
3386
  );
3387
+ fileWriteOk = response.type !== 'Failure';
3388
+ return response;
3010
3389
  } catch (e) {
3011
3390
  Log?.error('[ReactNativeBleTransport] Protocol V2 call error:', e);
3012
3391
  if (
@@ -3027,6 +3406,15 @@ export default class ReactNativeBleTransport {
3027
3406
  if (highThroughputWrite) {
3028
3407
  this.scheduleAndroidBalancedConnectionPriority(uuid);
3029
3408
  }
3409
+ if (fileWritePerf) {
3410
+ if (this.protocolV2FileWritePerfs.get(uuid) === fileWritePerf) {
3411
+ this.protocolV2FileWritePerfs.delete(uuid);
3412
+ }
3413
+ Log?.debug(
3414
+ '[ReactNativeBleTransport] FileWrite perf',
3415
+ fileWritePerf.summarize(fileWriteOk)
3416
+ );
3417
+ }
3030
3418
  }
3031
3419
  }
3032
3420
 
@@ -3143,15 +3531,23 @@ export default class ReactNativeBleTransport {
3143
3531
  assertCurrentGeneration
3144
3532
  );
3145
3533
  },
3146
- readFrame: async () => {
3534
+ readFrame: async (context?: ProtocolV2CallContext) => {
3147
3535
  assertCurrentGeneration();
3536
+ const perf =
3537
+ context?.messageName === 'FilesystemFileWrite'
3538
+ ? this.protocolV2FileWritePerfs.get(uuid)
3539
+ : undefined;
3540
+ const startedAt = perf ? nowMs() : 0;
3148
3541
  const rxFrame = await this.readProtocolV2Frame(uuid);
3542
+ perf?.recordReadWait(nowMs() - startedAt);
3149
3543
  if (!(rxFrame instanceof Uint8Array)) {
3150
3544
  throw new Error('Protocol V2 response is not Uint8Array');
3151
3545
  }
3152
3546
  return rxFrame;
3153
3547
  },
3154
3548
  reset: (reason: string) => {
3549
+ // The frame belongs to this link even after a newer monitor generation took over.
3550
+ this.cancelProtocolV2FrameWrite(uuid, new Error(reason), generation);
3155
3551
  if (this.monitorTokens.get(uuid) !== generation) return;
3156
3552
  this.protocolV2Assemblers.get(uuid)?.reset();
3157
3553
  this.rejectProtocolV2Frames(uuid, new Error(reason));