All files / session/replay replaySession.ts

92.65% Statements 265/286
78.94% Branches 165/209
95.19% Functions 99/104
95.31% Lines 244/256

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689                                                                      1x                                               1x   1x   9x           116x 116x   233x     38x 38x               4x           11x                     73x       29x 22x 22x               22x       16x                 162x           19x 19x 19x 19x 19x 19x 19x 19x 19x 19x                                 14x   5x 10x 10x 5x   5x 5x                 5x   35x         5x       35x         5x 5x                                             13x 13x 13x 13x                       4x 4x 4x 4x 4x 4x 4x 4x             1x   3x 3x                                 3x 3x 3x 3x           1x   2x                       2x 2x                 2x 2x 2x 2x 2x                 1x 1x 1x 1x 1x                     4x 4x                 13x   17x       14x 13x 13x         1x   4x       4x 4x     3x 3x     2x 2x     2x 2x     1x 1x     4x 4x         19x     19x 19x 71x   19x 19x           47x 47x 47x   47x     47x       47x 47x   19x 72x 72x   19x                 7x               7x               7x 7x 7x 7x 28x 28x   7x 11x 11x     7x 7x   7x 8x   7x       7x               6x 6x     1x         1x     1x     1x 1x           4x     7x                     19x 19x 19x 47x 19x             19x 19x 19x 19x 19x 19x 19x   23x 19x 19x 24x 24x 24x     24x 24x     24x   70x 19x 22x 22x 22x 22x 22x 22x   19x 22x 22x 22x 15x 15x 15x         7x 7x   22x   19x   19x 40x 40x 40x 40x 15x 15x     19x 23x   19x 23x 23x 23x 23x 23x     19x 6x   2x     12x     1x     2x 8x     3x 1x 1x   1x 1x 1x 1x     19x     1x     1x     3x     1x     10x     2x     1x     1x       1x     1x 1x 1x 1x 1x       12x 12x 12x 12x 12x       11x 11x 10x 10x     10x 7x   6x   7x 7x 7x   3x 3x 3x 3x       5x 3x     1x        
import type {
  SmartCubeCommand,
  SmartCubeEvent,
  SmartCubeTransportConnection,
  SmartCubeVendorCommand,
} from '../../bindings/smartCubeTransport.js';
 
import * as ReplayCursor from '@wstein/regrip-core/domain/ReplayCursor';
import type { regripToken as RegripToken } from '@wstein/regrip-core/domain/CubeNotation';
import { resolveSessionFeatures, type SessionFeatures } from '@wstein/regrip-core/session/features';
import { bundledProfiles } from '@wstein/regrip-core/session/profile/bundled';
import { resolveProfile } from '@wstein/regrip-core/session/profile/resolveProfile';
import {
  createSmartCubeSession,
  type CustomTriggerEvent,
  type MoveGapEvent,
  type SessionGyroEvent,
  type ShakeTriggerEvent,
  type SmartCubeSession,
  type SmartCubeSessionDiagnostic,
  type SmartCubeSessionEvent,
  type SmartCubeSessionState,
  type VirtualRegripEvent,
} from '../smartCubeSession.js';
import {
  createJsonlReplay,
  createJsonlMockConnection,
  isSmartCubeEvent,
  type JsonlMockIdentity,
  type JsonlReplay,
} from './jsonlMock.js';
 
/** Choose raw transport replay or recorded session-output replay. */
export type ReplayFeed = 'connection' | 'session';
/** Browser-local storage used only by the dev replay harness. */
export const REPLAY_STORAGE_KEY = 'regrip.replay.jsonl';
 
export type ReplayItem = {
  timestamp: number;
  event?: SmartCubeEvent | SmartCubeSessionEvent;
  status?: SmartCubeSessionState['status'];
};
type ReplayItemPayload = Omit<ReplayItem, 'timestamp'>;
type BuiltReplayItem = { payload: ReplayItemPayload; sourceTimestamp?: number };
type ReplayItemBuilder = (
  data: Record<string, unknown>,
  fallbackTimestamp: number,
) => BuiltReplayItem | undefined;
 
type ReplayListener = () => void;
type RawGyroEvent = Extract<SmartCubeEvent, { type: 'GYRO' }>;
type Quaternion = RawGyroEvent['quaternion'];
type Vector3 = NonNullable<RawGyroEvent['velocity']>;
type ReplayOutputSession = SmartCubeSession & {
  /** Replay-only injection seam; never exposed from a production session. */
  emit(event: SmartCubeSessionEvent): void;
  setReplayStatus(status: SmartCubeSessionState['status']): void;
};
 
const regripTokens = new Set<RegripToken>(['x', "x'", 'x2', 'y', "y'", 'y2', 'z', "z'", 'z2']);
 
const synchronousGyroScheduler = {
  schedule(flush: () => void): void {
    flush();
  },
  cancel(): void {},
};
 
function createFanout<T>() {
  const listeners = new Set<(value: T) => void>();
  return {
    emit(value: T): void {
      listeners.forEach((listener) => listener(value));
    },
    subscribe(listener: (value: T) => void): () => void {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
  };
}
 
function isRawSessionEvent(
  value: unknown,
): value is Exclude<SmartCubeSessionEvent, { type: 'GYRO' }> {
  return isSmartCubeEvent(value) && value.type !== 'GYRO';
}
 
function isSmartCubeSessionEvent(
  value: SmartCubeEvent | SmartCubeSessionEvent,
): value is SmartCubeSessionEvent {
  return (
    value.type !== 'GYRO' ||
    ('relative' in value &&
      'driftCorrected' in value &&
      'stabilized' in value &&
      'velocityMagnitude' in value &&
      'dtSeconds' in value)
  );
}
 
function number(value: unknown): number | undefined {
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}
 
function quaternion(value: unknown): Quaternion | undefined {
  if (!value || typeof value !== 'object') return undefined;
  const candidate = value as Record<string, unknown>;
  Iif (
    typeof candidate.x !== 'number' ||
    typeof candidate.y !== 'number' ||
    typeof candidate.z !== 'number' ||
    typeof candidate.w !== 'number'
  ) {
    return undefined;
  }
  return { x: candidate.x, y: candidate.y, z: candidate.z, w: candidate.w };
}
 
function vector3(value: unknown): Vector3 | undefined {
  Eif (!value || typeof value !== 'object') return undefined;
  const candidate = value as Record<string, unknown>;
  const x = number(candidate.x);
  const y = number(candidate.y);
  const z = number(candidate.z);
  return x === undefined || y === undefined || z === undefined ? undefined : { x, y, z };
}
 
function record(value: unknown): Record<string, unknown> | undefined {
  return value !== null && typeof value === 'object' && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : undefined;
}
 
function capturedFeatures(entries: JsonlReplay['entries']): SessionFeatures | undefined {
  const session = record(entries[0]?.data.session);
  const profileValue = record(session?.profileValue);
  const features = record(profileValue?.features);
  const stabilizer = record(features?.stabilizer);
  const hysteresis = record(stabilizer?.hysteresis);
  const drift = record(stabilizer?.drift);
  const regrip = record(features?.regrip);
  const customTrigger = record(features?.customTrigger);
  const triggers = customTrigger?.triggers;
  if (
    typeof stabilizer?.enabled !== 'boolean' ||
    number(stabilizer.radiusDeg) === undefined ||
    number(stabilizer.snapDeg) === undefined ||
    number(stabilizer.velocityMax) === undefined ||
    typeof hysteresis?.enabled !== 'boolean' ||
    number(hysteresis.marginDeg) === undefined ||
    typeof drift?.enabled !== 'boolean' ||
    number(drift.degPerSec) === undefined ||
    typeof regrip?.enabled !== 'boolean' ||
    (regrip.detector !== undefined &&
      regrip.detector !== 'threshold' &&
      regrip.detector !== 'absolute') ||
    (regrip.thresholdDeg !== undefined && number(regrip.thresholdDeg) === undefined) ||
    typeof customTrigger?.enabled !== 'boolean' ||
    !Array.isArray(triggers)
  ) {
    return undefined;
  }
  const parsedTriggers = triggers.flatMap((value) => {
    const trigger = record(value);
    if (trigger?.kind === 'moveBack' && number(trigger.windowMs) !== undefined) {
      return [{ kind: 'moveBack' as const, windowMs: trigger.windowMs as number }];
    }
    Iif (trigger?.kind !== 'shake') return [];
    const optionalNumbers = [
      'minStepAngleDeg',
      'minSteps',
      'minReversals',
      'maxSampleGapMs',
      'burstWindowMs',
      'faceGuardMs',
      'cooldownMs',
    ] as const;
    Iif (
      optionalNumbers.some(
        (key) => trigger[key] !== undefined && number(trigger[key]) === undefined,
      )
    ) {
      return [];
    }
    return [
      Object.fromEntries([
        ['kind', 'shake'],
        ...optionalNumbers.flatMap((key) =>
          trigger[key] === undefined ? [] : ([[key, trigger[key]]] as const),
        ),
      ] as const) as SessionFeatures['customTrigger']['triggers'][number],
    ];
  });
  Iif (parsedTriggers.length !== triggers.length) return undefined;
  return {
    stabilizer: {
      enabled: stabilizer.enabled,
      radiusDeg: stabilizer.radiusDeg as number,
      snapDeg: stabilizer.snapDeg as number,
      velocityMax: stabilizer.velocityMax as number,
      hysteresis: { enabled: hysteresis.enabled, marginDeg: hysteresis.marginDeg as number },
      drift: { enabled: drift.enabled, degPerSec: drift.degPerSec as number },
    },
    // Detector-specific fields from older captures are intentionally ignored.
    regrip: { enabled: regrip.enabled },
    customTrigger: { enabled: customTrigger.enabled, triggers: parsedTriggers },
  };
}
 
/**
 * Older app exports only persisted derived gyro samples. They still contain
 * the raw quaternion needed to reconstruct the connection/session pipeline.
 */
function gyroFromStabilizer(
  data: Record<string, unknown>,
  fallbackTimestamp: number,
): RawGyroEvent | undefined {
  const quaternionValue = quaternion(data.quaternion);
  Iif (!quaternionValue) return undefined;
  const validVelocity = vector3(data.velocity);
  return {
    type: 'GYRO',
    timestamp: number(data.timestamp) ?? fallbackTimestamp,
    quaternion: quaternionValue,
    ...(validVelocity ? { velocity: validVelocity } : {}),
  };
}
 
function sessionGyroFromRecord(
  data: Record<string, unknown>,
  fallbackTimestamp: number,
): SessionGyroEvent | undefined {
  const timestamp = number(data.timestamp) ?? fallbackTimestamp;
  const quaternionValue = quaternion(data.quaternion);
  const relative = quaternion(data.relative);
  const recordedDriftCorrected = quaternion(data.driftCorrected);
  const stabilized = quaternion(data.stabilized);
  const velocityMagnitude = number(data.velocityMagnitude);
  const dtSeconds = number(data.dtSeconds);
  if (
    !quaternionValue ||
    !relative ||
    !stabilized ||
    velocityMagnitude === undefined ||
    dtSeconds === undefined
  ) {
    return undefined;
  }
  const velocity = vector3(data.velocity);
  return {
    type: 'GYRO',
    timestamp,
    quaternion: quaternionValue,
    ...(velocity ? { velocity } : {}),
    relative,
    driftCorrected: recordedDriftCorrected ?? relative,
    stabilized,
    velocityMagnitude,
    dtSeconds,
  };
}
 
function regripFromRecord(
  data: Record<string, unknown>,
  fallbackTimestamp: number,
): VirtualRegripEvent | undefined {
  const timestamp = number(data.timestamp) ?? fallbackTimestamp;
  const notationToken = data.notationToken;
  const sensorFrameToken = data.sensorFrameToken;
  if (
    typeof notationToken !== 'string' ||
    !regripTokens.has(notationToken as RegripToken) ||
    typeof sensorFrameToken !== 'string' ||
    !regripTokens.has(sensorFrameToken as RegripToken)
  ) {
    return undefined;
  }
  return {
    type: 'REGRIP',
    timestamp,
    notationToken: notationToken as RegripToken,
    sensorFrameToken: sensorFrameToken as RegripToken,
  };
}
 
function customTriggerFromRecord(
  data: Record<string, unknown>,
  fallbackTimestamp: number,
): CustomTriggerEvent | undefined {
  const timestamp = number(data.timestamp) ?? fallbackTimestamp;
  return typeof data.move === 'string' && data.move.length > 0
    ? { type: 'CUSTOM_TRIGGER', timestamp, move: data.move }
    : undefined;
}
 
function shakeFromRecord(
  data: Record<string, unknown>,
  fallbackTimestamp: number,
): ShakeTriggerEvent | undefined {
  const timestamp = number(data.timestamp) ?? fallbackTimestamp;
  const steps = number(data.steps);
  const reversals = number(data.reversals);
  const spanMs = number(data.spanMs);
  return steps === undefined || reversals === undefined || spanMs === undefined
    ? undefined
    : { type: 'SHAKE', timestamp, steps, reversals, spanMs };
}
 
function moveGapFromRecord(
  data: Record<string, unknown>,
  fallbackTimestamp: number,
): MoveGapEvent | undefined {
  const timestamp = number(data.timestamp) ?? fallbackTimestamp;
  const previousSerial = number(data.previousSerial);
  const serial = number(data.serial);
  const missing = number(data.missing);
  return previousSerial === undefined ||
    serial === undefined ||
    missing === undefined ||
    missing < 1
    ? undefined
    : { type: 'MOVE_GAP', timestamp, previousSerial, serial, missing };
}
 
function statusFromRecord(
  data: Record<string, unknown>,
): SmartCubeSessionState['status'] | undefined {
  const status = data.status;
  return status === 'disconnected' ||
    status === 'connecting' ||
    status === 'connected' ||
    status === 'error'
    ? status
    : undefined;
}
 
function connectionBuilders(hasRawGyro: boolean): Record<string, ReplayItemBuilder> {
  return {
    cube_event: (data) =>
      isSmartCubeEvent(data)
        ? { payload: { event: data }, sourceTimestamp: data.timestamp }
        : undefined,
    gyro_stabilizer: (data, fallbackTimestamp) => {
      if (hasRawGyro) return undefined;
      const event = gyroFromStabilizer(data, fallbackTimestamp);
      return event ? { payload: { event }, sourceTimestamp: event.timestamp } : undefined;
    },
  };
}
 
const sessionBuilders: Record<string, ReplayItemBuilder> = {
  cube_event: (data) =>
    isRawSessionEvent(data)
      ? { payload: { event: data }, sourceTimestamp: data.timestamp }
      : undefined,
  gyro_stabilizer: (data, fallbackTimestamp) => {
    const event = sessionGyroFromRecord(data, fallbackTimestamp);
    return event ? { payload: { event }, sourceTimestamp: event.timestamp } : undefined;
  },
  virtual_regrip: (data, fallbackTimestamp) => {
    const event = regripFromRecord(data, fallbackTimestamp);
    return event ? { payload: { event }, sourceTimestamp: event.timestamp } : undefined;
  },
  custom_trigger: (data, fallbackTimestamp) => {
    const event = customTriggerFromRecord(data, fallbackTimestamp);
    return event ? { payload: { event }, sourceTimestamp: event.timestamp } : undefined;
  },
  shake_trigger: (data, fallbackTimestamp) => {
    const event = shakeFromRecord(data, fallbackTimestamp);
    return event ? { payload: { event }, sourceTimestamp: event.timestamp } : undefined;
  },
  move_gap: (data, fallbackTimestamp) => {
    const event = moveGapFromRecord(data, fallbackTimestamp);
    return event ? { payload: { event }, sourceTimestamp: event.timestamp } : undefined;
  },
  session_status: (data) => {
    const status = statusFromRecord(data);
    return status ? { payload: { status } } : undefined;
  },
};
 
function parseReplayItems(entries: JsonlReplay['entries'], feed: ReplayFeed): ReplayItem[] {
  const items: ReplayItem[] = [];
  let firstRecordedAt: number | undefined;
  let firstTimelineTimestamp: number | undefined;
  let previousTimelineTimestamp = 0;
  const hasRawGyro = entries.some(
    (entry) => entry.type === 'cube_event' && entry.data.type === 'GYRO',
  );
  const builders = feed === 'connection' ? connectionBuilders(hasRawGyro) : sessionBuilders;
  const add = (
    entry: (typeof entries)[number],
    index: number,
    value: ReplayItemPayload,
    sourceTimestamp?: number,
  ): void => {
    const recordedAt = Date.parse(entry.recordedAt);
    if (firstRecordedAt === undefined && Number.isFinite(recordedAt)) firstRecordedAt = recordedAt;
    if (firstTimelineTimestamp === undefined) firstTimelineTimestamp = sourceTimestamp ?? index;
    const elapsed =
      firstRecordedAt === undefined || !Number.isFinite(recordedAt)
        ? index
        : recordedAt - firstRecordedAt;
    const timestamp = Math.max(
      previousTimelineTimestamp,
      firstTimelineTimestamp + Math.max(0, elapsed),
    );
    previousTimelineTimestamp = timestamp;
    items.push({ ...value, timestamp });
  };
  entries.forEach((entry, index) => {
    const built = builders[entry.type]?.(entry.data, index);
    if (built) add(entry, index, built.payload, built.sourceTimestamp);
  });
  return items;
}
 
function createOutputSession(
  connection: SmartCubeTransportConnection,
  replayFeatures?: SessionFeatures,
): ReplayOutputSession {
  // A2 bypasses the production connection lifecycle, but must still present
  // the same profile selected by the capture identity to the UI.
  const profile = resolveProfile(
    {
      protocol: connection.protocol.id,
      deviceName: connection.deviceName,
      deviceMAC: connection.deviceMAC,
    },
    bundledProfiles,
  );
  let state: SmartCubeSessionState = {
    status: 'disconnected',
    connection: null,
    lastEvent: null,
    profile,
    features: replayFeatures ?? resolveSessionFeatures(profile.value.features),
    error: null,
  };
  const states = createFanout<SmartCubeSessionState>();
  const events = createFanout<SmartCubeSessionEvent>();
  const diagnostics = createFanout<SmartCubeSessionDiagnostic>();
  const setState = (patch: Partial<SmartCubeSessionState>): void => {
    state = { ...state, ...patch };
    states.emit(state);
  };
  const emit = (event: SmartCubeSessionEvent): void => {
    setState({ lastEvent: event });
    events.emit(event);
  };
 
  const subscribeEvents: SmartCubeSession['subscribeEvents'] = (listener) => {
    return events.subscribe(listener);
  };
  const output: ReplayOutputSession = {
    getState: () => state,
    subscribe(listener) {
      return states.subscribe(listener);
    },
    subscribeEvents,
    subscribeDiagnostics(listener) {
      return diagnostics.subscribe(listener);
    },
    on(type, listener) {
      return subscribeEvents((event) => {
        if (event.type === type) listener(event as never);
      });
    },
    async connect() {
      setState({ status: 'connecting', error: null });
      setState({ status: 'connected', connection });
    },
    async disconnect() {
      setState({ status: 'disconnected', connection: null });
    },
    resetGyro() {},
    configureFeatures() {},
    async sendCommand(command: SmartCubeCommand) {
      await connection.sendCommand(command);
    },
    async syncFacelets() {
      throw new Error('State sync is unavailable for session-feed replay');
    },
    async sendVendorCommand(command: SmartCubeVendorCommand) {
      Eif (!connection.sendVendorCommand)
        throw new Error(`Unsupported cube command: ${command.type}`);
      await connection.sendVendorCommand(command);
    },
    // Testing-only seam used by the replay facade; production sessions never expose it.
    emit,
    setReplayStatus(status: SmartCubeSessionState['status']) {
      setState({ status, connection: status === 'connected' ? connection : null });
    },
  };
  return output;
}
 
/**
 * Deterministic JSONL transport. Connection feed exercises the full session;
 * session feed pins recorded derived events for UI/adapters-only inspection.
 */
export type ReplaySessionController = ReturnType<typeof createReplaySession>;
 
/** Create a deterministic session facade driven by a JSONL capture. */
export function createReplaySession(contents: string, feed: ReplayFeed = 'connection') {
  const replayData = createJsonlReplay(contents);
  const replayFeatures = capturedFeatures(replayData.entries);
  const items = parseReplayItems(replayData.entries, feed);
  const timestamps = items.map((item) => item.timestamp);
  let cursor = ReplayCursor.seekTo(timestamps, 0);
  let mock!: ReturnType<typeof createJsonlMockConnection>;
  let current!: SmartCubeSession;
  let output: ReplayOutputSession | undefined;
  let unsubscribeState: (() => void) | undefined;
  let unsubscribeEvents: (() => void) | undefined;
  let unsubscribeDiagnostics: (() => void) | undefined;
  let transportGeneration = 0;
  let transport = Promise.resolve();
  const states = createFanout<SmartCubeSessionState>();
  const events = createFanout<SmartCubeSessionEvent>();
  const diagnostics = createFanout<SmartCubeSessionDiagnostic>();
  const cursors = createFanout<void>();
  const rebuilds = createFanout<void>();
 
  const notifyCursor = (): void => cursors.emit();
  const notifyRebuild = (): void => rebuilds.emit();
  const enqueue = <T>(operation: (generation: number) => Promise<T>): Promise<T> => {
    const generation = ++transportGeneration;
    const task = transport.then(
      () => operation(generation),
      () => operation(generation),
    );
    transport = task.then(
      () => undefined,
      () => undefined,
    );
    return task;
  };
  const isCurrent = (generation: number): boolean => generation === transportGeneration;
  const bind = (): void => {
    unsubscribeState?.();
    unsubscribeEvents?.();
    unsubscribeDiagnostics?.();
    unsubscribeState = current.subscribe(states.emit);
    unsubscribeEvents = current.subscribeEvents(events.emit);
    unsubscribeDiagnostics = current.subscribeDiagnostics(diagnostics.emit);
  };
  const rebuild = (notify = false): void => {
    if (notify) notifyRebuild();
    mock = createJsonlMockConnection(replayData);
    if (feed === 'connection') {
      output = undefined;
      current = createSmartCubeSession({
        connect: async () => mock.connection,
        features: replayFeatures,
        gyroFrameScheduler: synchronousGyroScheduler,
      });
    } else {
      output = createOutputSession(mock.connection, replayFeatures);
      current = output;
    }
    bind();
  };
  rebuild();
 
  const emit = (index: number): void => {
    const item = items[index];
    Iif (!item) return;
    if (feed === 'connection' && item.event && isSmartCubeEvent(item.event)) mock.emit(item.event);
    if (feed === 'session') {
      if (item.event && isSmartCubeSessionEvent(item.event)) output?.emit(item.event);
      if (item.status) output?.setReplayStatus(item.status);
    }
  };
  const ensureConnected = async (): Promise<void> => {
    if (!current.getState().connection) await current.connect();
  };
  const run = async (indices: readonly number[], generation: number): Promise<void> => {
    Iif (!isCurrent(generation)) return;
    await ensureConnected();
    Iif (!isCurrent(generation)) return;
    indices.forEach(emit);
    notifyCursor();
  };
 
  const session: SmartCubeSession = {
    getState: () => current.getState(),
    subscribe(listener: (state: SmartCubeSessionState) => void) {
      return states.subscribe(listener);
    },
    subscribeEvents(listener: (event: SmartCubeSessionEvent) => void) {
      return events.subscribe(listener);
    },
    subscribeDiagnostics(listener: (event: SmartCubeSessionDiagnostic) => void) {
      return diagnostics.subscribe(listener);
    },
    on(type, listener) {
      return this.subscribeEvents((event) => {
        if (event.type === type) listener(event as never);
      });
    },
    connect: () => current.connect(),
    disconnect: () => current.disconnect(),
    resetGyro: () => current.resetGyro(),
    configureFeatures: (patch: Parameters<SmartCubeSession['configureFeatures']>[0]) =>
      current.configureFeatures(patch),
    sendCommand: (command: SmartCubeCommand) => current.sendCommand(command),
    syncFacelets: () => current.syncFacelets(),
    sendVendorCommand: (command: SmartCubeVendorCommand) => current.sendVendorCommand(command),
  };
 
  return {
    session,
    get feed(): ReplayFeed {
      return feed;
    },
    get identity(): JsonlMockIdentity {
      return replayData.identity;
    },
    get length(): number {
      return items.length;
    },
    get items(): ReadonlyArray<ReplayItem> {
      return items;
    },
    get position(): number {
      return ReplayCursor.position(cursor);
    },
    get virtualNowMs(): number {
      return ReplayCursor.virtualNowMs(cursor);
    },
    get done(): boolean {
      return ReplayCursor.done(cursor, timestamps);
    },
    subscribeCursor(listener: ReplayListener): () => void {
      return cursors.subscribe(listener);
    },
    /** Fires immediately before a backward seek reconstructs the session. */
    subscribeRebuild(listener: ReplayListener): () => void {
      return rebuilds.subscribe(listener);
    },
    async stepOne(): Promise<void> {
      return enqueue(async (generation) => {
        Iif (!isCurrent(generation)) return;
        const [next, index] = ReplayCursor.stepOne(cursor, timestamps);
        cursor = next;
        await run(index === undefined ? [] : [index], generation);
      });
    },
    async advanceTo(targetMs: number): Promise<void> {
      return enqueue(async (generation) => {
        Iif (!isCurrent(generation)) return;
        const [next, indices] = ReplayCursor.advanceTo(cursor, timestamps, targetMs);
        cursor = next;
        await run(indices, generation);
      });
    },
    async seekTo(index: number): Promise<void> {
      return enqueue(async (generation) => {
        if (!isCurrent(generation)) return;
        const target = Math.max(0, Math.min(index, items.length));
        const currentPosition = ReplayCursor.position(cursor);
        // Forward seeks can continue the current deterministic session. Only
        // backward seeks need a clean connection/session plus prefix replay.
        if (target >= currentPosition) {
          const forward = Array.from(
            { length: target - currentPosition },
            (_, offset) => currentPosition + offset,
          );
          cursor = ReplayCursor.seekTo(timestamps, target);
          await run(forward, generation);
          return;
        }
        rebuild(true);
        const prefix = Array.from({ length: target }, (_, itemIndex) => itemIndex);
        cursor = ReplayCursor.seekTo(timestamps, target);
        await run(prefix, generation);
      });
    },
    async seekToTimestamp(timestamp: number): Promise<void> {
      const index = timestamps.findIndex((candidate) => candidate > timestamp);
      await this.seekTo(index === -1 ? items.length : index);
    },
    async reset(): Promise<void> {
      await this.seekTo(0);
    },
  };
}