All files / session smartCubeSession.ts

89.92% Statements 232/258
84.84% Branches 112/132
87.09% Functions 54/62
92.47% Lines 209/226

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                                                                                                                                                                                                                                                                                            4x                 28x 28x             48x 48x 48x 48x     48x 48x 2x             48x           48x     48x 98x 48x 48x               48x 48x 48x 48x     48x 48x         48x 45x         48x 48x 48x 48x 48x     37x       111x 99x 25x 25x       52x 52x 52x       76x       76x       1x 1x 1x 1x             18x     18x 18x               24x 24x 24x       1x       29x         29x 29x       52x 52x 52x 52x     373x 48x 373x 373x   48x 5x           50x 50x 45x       45x 45x 45x 45x     48x 112x 112x 58x               58x 58x         112x 9x 9x       9x 9x     111x     112x 112x   112x   112x       112x         112x   112x 112x 111x 111x 5x               111x 1x 1x               1x   111x 111x 12x 12x               111x 4x 4x             111x 2x 2x                 111x     48x 92x 92x 92x 1x 1x   92x     48x     59x 20x 20x 20x   39x 39x 38x     38x     48x 113x 59x 59x       54x 54x     48x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x       46x 46x 46x 46x 46x 46x 46x 46x 1x 1x   45x               45x       45x 45x         1x 1x   46x     45x 44x                                 30x 30x     30x 30x 30x 30x 30x 30x 30x 30x 30x       2x 2x 1x         2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x       2x 2x 2x               2x 2x 2x       1x   1x     48x 49x   15x 15x       40x 40x             16x 16x             7x 33x                     7x       7x              
import type { Subscription } from 'rxjs';
import type {
  SmartCubeCommand,
  SmartCubeDiagnosticEvent,
  SmartCubeEvent,
  SmartCubeTransportConnection,
  SmartCubeVendorCommand,
} from '@wstein/regrip-core/bindings/smartCubeTransport';
 
import * as GyroPipeline from '@wstein/regrip-core/domain/GyroPipeline';
import * as AbsoluteRegripDetector from '@wstein/regrip-core/domain/AbsoluteRegripDetector';
import * as MoveBackTrigger from '@wstein/regrip-core/domain/MoveBackTrigger';
import * as MoveTracker from '@wstein/regrip-core/domain/MoveTracker';
import * as SnapshotDeduper from '@wstein/regrip-core/domain/SnapshotDeduper';
import * as ShakeTrigger from '@wstein/regrip-core/domain/ShakeTrigger';
import type { regripToken as RegripToken } from '@wstein/regrip-core/domain/CubeNotation';
import {
  disconnectConnection,
  requestInitialState,
} from '@wstein/regrip-core/session/connectionLifecycle';
import {
  resolveSessionFeatures,
  mergeSessionFeatures,
  stabilizerConfig,
  type SessionFeatures,
  type SessionFeaturesPatch,
} 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 { parseSensorToBodyAxisMap } from '@wstein/regrip-core/session/profile/axisMap';
import * as SensorToBody from '@wstein/regrip-core/domain/SensorToBody';
import type { ProfileOverrides, ResolvedProfile } from '@wstein/regrip-core/session/profile/types';
import { structuralEqual } from '../internal/structuralEqual.js';
import { deepMergeRecord } from '../internal/deepMergeRecord.js';
 
/** A whole-cube rotation inferred from calibrated gyro orientation. */
export type VirtualRegripEvent = {
  type: 'REGRIP';
  timestamp: number;
  /** Clockwise Singmaster x/y/z notation. */
  notationToken: RegripToken;
  /** The corresponding positive/negative calibrated sensor axis. */
  sensorFrameToken: RegripToken;
};
 
/** A configured move-based gesture recognized by the session. */
export type CustomTriggerEvent = {
  type: 'CUSTOM_TRIGGER';
  timestamp: number;
  /** The initiating quarter-turn, e.g. `R` for `R R'`. */
  move: string;
};
 
/** A shake gesture recognized from the calibrated gyro stream. */
export type ShakeTriggerEvent = {
  type: 'SHAKE';
  /** Time of the final reversal-bearing gyro sample; emission lags by the guard. */
  timestamp: number;
  steps: number;
  reversals: number;
  spanMs: number;
};
 
/** A protocol move serial skipped one or more turns; await FACELETS recovery. */
export type MoveGapEvent = {
  type: 'MOVE_GAP';
  timestamp: number;
  previousSerial: number;
  serial: number;
  missing: number;
};
 
/** Raw gyro data enriched with the session's calibrated orientation. */
export type SessionGyroEvent = Extract<SmartCubeEvent, { type: 'GYRO' }> & {
  /** One session-owned, basis-normalized pose for every gyro consumer. */
  relative: { x: number; y: number; z: number; w: number };
  /** Drift-compensated pose before magnetic detent; equals `relative` when disabled. */
  driftCorrected: { x: number; y: number; z: number; w: number };
  /** Drift-compensated pose after magnetic detent; equals `relative` when disabled. */
  stabilized: { x: number; y: number; z: number; w: number };
  velocityMagnitude: number;
  dtSeconds: number;
};
 
/** Union of raw cube events and session-derived events. */
export type SmartCubeSessionEvent =
  | Exclude<SmartCubeEvent, { type: 'GYRO' }>
  | SessionGyroEvent
  | VirtualRegripEvent
  | CustomTriggerEvent
  | ShakeTriggerEvent
  | MoveGapEvent;
 
type FaceletsEvent = Extract<SmartCubeEvent, { type: 'FACELETS' }>;
 
type SessionEventType = SmartCubeSessionEvent['type'];
type SessionEventOf<T extends SessionEventType> = Extract<SmartCubeSessionEvent, { type: T }>;
 
/** Observable state owned by a smart-cube session. */
export type SmartCubeSessionState = {
  status: 'disconnected' | 'connecting' | 'connected' | 'error';
  connection: SmartCubeTransportConnection | null;
  lastEvent: SmartCubeSessionEvent | null;
  profile: ResolvedProfile;
  /** Fully resolved feature configuration for the selected device profile. */
  features: SessionFeatures;
  error: string | null;
};
 
/** Dependencies and optional host overrides for a smart-cube session. */
export type SmartCubeSessionOptions = {
  connect: () => Promise<SmartCubeTransportConnection>;
  /**
   * Schedules the latest contiguous gyro packet at display cadence. Supplying
   * this is primarily useful for deterministic hosts and tests.
   */
  gyroFrameScheduler?: GyroFrameScheduler;
  /**
   * @deprecated Use `features.regrip.enabled`. This compatibility option will
   * be removed after downstream callers migrate to the profile feature model.
   */
  virtualRegrips?: boolean;
  /** App-layer feature overrides, applied after the selected device profile. */
  features?: SessionFeaturesPatch;
};
 
/** Host scheduler used to coalesce gyro updates at display cadence. */
export type GyroFrameScheduler = {
  schedule: (flush: () => void) => unknown;
  cancel: (handle: unknown) => void;
};
 
/** Public controller returned by {@link createSmartCubeSession}. */
export type SmartCubeSession = ReturnType<typeof createSmartCubeSession>;
 
/**
 * Raw protocol evidence kept outside `SmartCubeSessionEvent`: it must never
 * affect cube state, gyro processing, or feature detectors.
 */
export type SmartCubeSessionDiagnostic = SmartCubeDiagnosticEvent;
 
const browserGyroFrameScheduler: GyroFrameScheduler =
  typeof requestAnimationFrame === 'function'
    ? {
        schedule: (flush) => requestAnimationFrame(flush),
        cancel: (handle) => cancelAnimationFrame(handle as number),
      }
    : {
        // Keep headless replay synchronous. Browsers use requestAnimationFrame
        // and therefore receive the real 60 Hz coalescing behavior.
        schedule: (flush) => {
          flush();
          return undefined;
        },
        cancel: () => {},
      };
 
/** Create a connection-safe smart-cube session and derived-event pipeline. */
export function createSmartCubeSession(options: SmartCubeSessionOptions) {
  let subscription: Subscription | null = null;
  let diagnosticSubscription: Subscription | null = null;
  let connectionGeneration = 0;
  const gyroFrameScheduler = options.gyroFrameScheduler ?? browserGyroFrameScheduler;
  let pendingGyro: Extract<SmartCubeEvent, { type: 'GYRO' }> | undefined;
  let pendingGyroFrame: unknown;
  let hasCalibratedGyro = false;
  if (options.virtualRegrips !== undefined) {
    console.warn(
      'virtualRegrips is deprecated; use features: { regrip: { enabled: ... } } instead.',
    );
  }
  // Preserve the former explicit option while keeping the resulting value in
  // the normal app profile layer. An explicit new feature value takes priority.
  const featurePatch: SessionFeaturesPatch | undefined =
    options.features?.regrip?.enabled === undefined && options.virtualRegrips !== undefined
      ? {
          ...options.features,
          regrip: { ...options.features?.regrip, enabled: options.virtualRegrips },
        }
      : options.features;
  const profileOverrides: ProfileOverrides = featurePatch
    ? { app: { features: featurePatch } }
    : {};
  const resolveSessionProfile = (context: Parameters<typeof resolveProfile>[0]): ResolvedProfile =>
    resolveProfile(context, bundledProfiles, profileOverrides);
  const initialProfile = resolveSessionProfile({});
  let state: SmartCubeSessionState = {
    status: 'disconnected',
    connection: null,
    lastEvent: null,
    error: null,
    profile: initialProfile,
    features: resolveSessionFeatures(initialProfile.value.features),
  };
  const listeners = new Set<(next: SmartCubeSessionState) => void>();
  const eventListeners = new Set<(event: SmartCubeSessionEvent) => void>();
  const diagnosticListeners = new Set<(event: SmartCubeSessionDiagnostic) => void>();
  const pendingFaceletSyncs = new Set<(error: Error) => void>();
  // The session owns calibration once; both regrip detection and display
  // stabilization consume the resulting calibrated pose.
  let gyroConfig = GyroPipeline.makeConfig(stabilizerConfig(state.features));
  let gyroState = GyroPipeline.initial;
  // A patch, not a resolved snapshot: it must keep applying on top of
  // whatever the currently-selected profile resolves to, not replace that
  // profile's own feature configuration wholesale on the next reprofile.
  let runtimeFeaturePatch: SessionFeaturesPatch | undefined;
  const applyProfileAxisMap = (profile: ResolvedProfile): void => {
    gyroConfig = GyroPipeline.withSensorToBody(
      gyroConfig,
      parseSensorToBodyAxisMap(profile.value.gyro?.axisMap) ?? SensorToBody.default,
    );
  };
  let regripState = AbsoluteRegripDetector.initial;
  let moveBackState = MoveBackTrigger.initial;
  let shakeState = ShakeTrigger.initial;
  let moveTrackerState = MoveTracker.initial;
  let snapshotDeduperState = SnapshotDeduper.initial;
 
  function moveBackWindow(features: SessionFeatures): number | undefined {
    return features.customTrigger.triggers.find((trigger) => trigger.kind === 'moveBack')?.windowMs;
  }
 
  function shakeConfig(features: SessionFeatures): ShakeTrigger.config | undefined {
    const spec = features.customTrigger.triggers.find((trigger) => trigger.kind === 'shake');
    if (!spec) return undefined;
    const { kind: _kind, ...overrides } = spec;
    return { ...ShakeTrigger.defaults, ...overrides };
  }
 
  function resetFeatureDetectors(): void {
    regripState = AbsoluteRegripDetector.initial;
    moveBackState = MoveBackTrigger.initial;
    shakeState = ShakeTrigger.initial;
  }
 
  function resetMoveTracker(): void {
    moveTrackerState = MoveTracker.initial;
  }
 
  function resetSnapshotDeduper(): void {
    snapshotDeduperState = SnapshotDeduper.initial;
  }
 
  function requestFaceletsAfterMoveGap(): void {
    const connection = state.connection;
    Iif (!connection?.capabilities.facelets) return;
    snapshotDeduperState = SnapshotDeduper.request(snapshotDeduperState);
    void connection.sendCommand({ type: 'REQUEST_FACELETS' }).catch((error: unknown) => {
      snapshotDeduperState = SnapshotDeduper.cancel(snapshotDeduperState);
      console.warn('Could not request facelets after a move serial gap.', error);
    });
  }
 
  function observeMoveBack(move: string, timestamp: number): string | undefined {
    const [nextState, trigger] = MoveBackTrigger.step(moveBackState, move, timestamp, {
      windowMs: moveBackWindow(state.features) ?? 300,
    });
    moveBackState = nextState;
    return trigger;
  }
 
  function observeShake(
    orientation: { x: number; y: number; z: number; w: number },
    timestamp: number,
    config: ShakeTrigger.config,
  ): ShakeTrigger.detection | undefined {
    const [nextState, detection] = ShakeTrigger.observe(shakeState, timestamp, orientation, config);
    shakeState = nextState;
    return detection;
  }
 
  function observeShakeMove(timestamp: number, config: ShakeTrigger.config): void {
    shakeState = ShakeTrigger.observeMove(shakeState, timestamp, config);
  }
 
  function observeRegrip(orientation: { x: number; y: number; z: number; w: number }) {
    const [nextState, observation] = AbsoluteRegripDetector.step(
      regripState,
      orientation,
      undefined,
    );
    regripState = nextState;
    return observation;
  }
 
  function applyFeatures(features: SessionFeatures): void {
    gyroConfig = GyroPipeline.withStabilizerConfig(gyroConfig, stabilizerConfig(features));
    gyroState = GyroPipeline.resetStabilizer(gyroState);
    resetFeatureDetectors();
    setState({ features });
  }
 
  const publish = (): void => listeners.forEach((listener) => listener(state));
  const setState = (next: Partial<SmartCubeSessionState>): void => {
    state = { ...state, ...next };
    publish();
  };
  const sameProfile = (left: ResolvedProfile, right: ResolvedProfile): boolean =>
    left.id === right.id && structuralEqual(left.value, right.value);
 
  function reprofile(
    context: Parameters<typeof resolveSessionProfile>[0],
    force = false,
  ): ResolvedProfile {
    const profile = resolveSessionProfile(context);
    if (!force && sameProfile(state.profile, profile)) return state.profile;
    const features = mergeSessionFeatures(
      resolveSessionFeatures(profile.value.features),
      runtimeFeaturePatch,
    );
    applyProfileAxisMap(profile);
    setState({ profile });
    applyFeatures(features);
    return profile;
  }
 
  const processEvent = (event: SmartCubeEvent): void => {
    const sessionEvent: SmartCubeSessionEvent = (() => {
      if (event.type !== 'GYRO') return event;
      const [nextGyroState, sample] = GyroPipeline.step(
        gyroState,
        event.quaternion,
        event.timestamp,
        event.velocity,
        gyroConfig,
        state.features.stabilizer.enabled,
      );
      gyroState = nextGyroState;
      return { ...event, ...sample };
    })();
    // Gyro packets are already coalesced to display cadence by `scheduleGyro`.
    // Do not filter them again: sub-degree drift corrections are intentional
    // visual motion, while MagneticDetent handles resting sensor noise.
    if (event.type === 'FACELETS') {
      moveTrackerState = MoveTracker.observeSnapshot(moveTrackerState, event.serial);
      const [nextSnapshotDeduperState, shouldPublish] = SnapshotDeduper.observe(
        snapshotDeduperState,
        { serial: event.serial, facelets: event.facelets },
      );
      snapshotDeduperState = nextSnapshotDeduperState;
      if (!shouldPublish) return;
    }
    const [nextMoveTrackerState, moveGap] =
      event.type === 'MOVE'
        ? MoveTracker.observeMove(moveTrackerState, event.serial)
        : [moveTrackerState, undefined];
    moveTrackerState = nextMoveTrackerState;
    const calibrated = sessionEvent.type === 'GYRO' ? sessionEvent.relative : undefined;
    const regripOrientation =
      sessionEvent.type === 'GYRO' ? sessionEvent.driftCorrected : undefined;
    const regrip =
      regripOrientation && state.features.regrip.enabled
        ? observeRegrip(regripOrientation)
        : undefined;
    const customTrigger =
      event.type === 'MOVE' &&
      state.features.customTrigger.enabled &&
      moveBackWindow(state.features) !== undefined
        ? observeMoveBack(event.move, event.timestamp)
        : undefined;
    const shakeCfg = state.features.customTrigger.enabled ? shakeConfig(state.features) : undefined;
    const shake =
      shakeCfg && calibrated ? observeShake(calibrated, event.timestamp, shakeCfg) : undefined;
    if (shakeCfg && event.type === 'MOVE') observeShakeMove(event.timestamp, shakeCfg);
    setState({ lastEvent: sessionEvent });
    if (event.type === 'HARDWARE' && state.connection) {
      reprofile({
        protocol: state.connection.protocol.id,
        deviceName: state.connection.deviceName,
        deviceMAC: state.connection.deviceMAC,
        hardwareName: event.hardwareName,
        goCubeType: event.goCubeType?.name,
      });
    }
    if (moveGap) {
      eventListeners.forEach((listener) =>
        listener({
          type: 'MOVE_GAP',
          timestamp: event.timestamp,
          previousSerial: moveGap.previousSerial,
          serial: moveGap.serial,
          missing: moveGap.missing,
        }),
      );
      requestFaceletsAfterMoveGap();
    }
    eventListeners.forEach((listener) => listener(sessionEvent));
    if (regrip) {
      eventListeners.forEach((listener) =>
        listener({
          type: 'REGRIP',
          timestamp: event.timestamp,
          notationToken: regrip.notationToken,
          sensorFrameToken: regrip.sensorFrameToken,
        }),
      );
    }
    if (customTrigger) {
      eventListeners.forEach((listener) =>
        listener({
          type: 'CUSTOM_TRIGGER',
          timestamp: event.timestamp,
          move: customTrigger,
        }),
      );
    }
    if (shake) {
      eventListeners.forEach((listener) =>
        listener({
          type: 'SHAKE',
          timestamp: shake.at,
          steps: shake.steps,
          reversals: shake.reversals,
          spanMs: shake.spanMs,
        }),
      );
    }
    if (event.type === 'DISCONNECT') void disconnect();
  };
 
  const flushPendingGyro = (): void => {
    const event = pendingGyro;
    pendingGyro = undefined;
    if (pendingGyroFrame !== undefined) {
      gyroFrameScheduler.cancel(pendingGyroFrame);
      pendingGyroFrame = undefined;
    }
    if (event) processEvent(event);
  };
 
  const scheduleGyro = (event: Extract<SmartCubeEvent, { type: 'GYRO' }>): void => {
    // The calibration sample establishes an exact identity-relative pose for
    // both the regrip ratchet and render pipeline. Do not drop it in a burst.
    if (!hasCalibratedGyro) {
      hasCalibratedGyro = true;
      processEvent(event);
      return;
    }
    pendingGyro = event;
    if (pendingGyroFrame !== undefined) return;
    const handle = gyroFrameScheduler.schedule(flushPendingGyro);
    // The headless scheduler may flush synchronously. Only retain a handle
    // when a gyro packet is still pending after schedule() returns.
    if (pendingGyro !== undefined && pendingGyroFrame === undefined) pendingGyroFrame = handle;
  };
 
  const onEvent = (event: SmartCubeEvent): void => {
    if (event.type === 'GYRO') {
      scheduleGyro(event);
      return;
    }
    // Do not let a following MOVE/FACELETS/DISCONNECT overtake the final gyro
    // sample in the preceding BLE packet burst.
    flushPendingGyro();
    processEvent(event);
  };
 
  const resetGyro = (): void => {
    pendingGyro = undefined;
    Iif (pendingGyroFrame !== undefined) gyroFrameScheduler.cancel(pendingGyroFrame);
    pendingGyroFrame = undefined;
    hasCalibratedGyro = false;
    gyroState = GyroPipeline.reset(gyroState);
    regripState = AbsoluteRegripDetector.initial;
    moveBackState = MoveBackTrigger.initial;
    shakeState = ShakeTrigger.initial;
    resetMoveTracker();
    resetSnapshotDeduper();
  };
 
  async function connect(): Promise<void> {
    Iif (state.status === 'connecting' || state.connection) return;
    const generation = ++connectionGeneration;
    setState({ status: 'connecting', error: null });
    resetGyro();
    let connection: SmartCubeTransportConnection | null = null;
    try {
      connection = await options.connect();
      if (generation !== connectionGeneration) {
        await disconnectConnection(connection);
        return;
      }
      const profile = reprofile(
        {
          protocol: connection.protocol.id,
          deviceName: connection.deviceName,
          deviceMAC: connection.deviceMAC,
        },
        true,
      );
      setState({
        connection,
        profile,
      });
      subscription = connection.events$.subscribe(onEvent);
      diagnosticSubscription =
        connection.diagnostics$?.subscribe((diagnostic) => {
          // Diagnostics have a deliberately separate channel. Keeping this
          // guard here also prevents late emissions from a replaced transport
          // from reaching a newly connected session.
          Iif (generation !== connectionGeneration || state.connection !== connection) return;
          diagnosticListeners.forEach((listener) => listener(diagnostic));
        }) ?? null;
      await requestInitialState(connection);
      // A device can send DISCONNECT while initial commands are in flight.
      // Never let that earlier attempt restore a dead connection afterwards.
      if (generation !== connectionGeneration || state.connection !== connection) return;
      setState({ status: 'connected', connection });
    } catch (error) {
      if (generation !== connectionGeneration) return;
      subscription?.unsubscribe();
      subscription = null;
      diagnosticSubscription?.unsubscribe();
      diagnosticSubscription = null;
      await disconnectConnection(connection);
      setState({
        status: 'error',
        connection: null,
        error: error instanceof Error ? error.message : String(error),
      });
    }
  }
 
  async function disconnect(): Promise<void> {
    connectionGeneration += 1;
    pendingFaceletSyncs.forEach((reject) =>
      reject(new Error('Cube disconnected before state sync')),
    );
    pendingFaceletSyncs.clear();
    subscription?.unsubscribe();
    subscription = null;
    diagnosticSubscription?.unsubscribe();
    diagnosticSubscription = null;
    const connection = state.connection;
    resetGyro();
    setState({ status: 'disconnected', connection: null });
    await disconnectConnection(connection);
  }
 
  async function sendCommand(command: SmartCubeCommand): Promise<void> {
    const connection = state.connection;
    if (!connection) throw new Error('Cube is not connected');
    await connection.sendCommand(command);
  }
 
  /** Request an authoritative snapshot and resolve only when it arrives. */
  function syncFacelets(): Promise<FaceletsEvent> {
    const connection = state.connection;
    Iif (!connection) return Promise.reject(new Error('Cube is not connected'));
    Iif (!connection.capabilities.facelets)
      return Promise.reject(new Error('Cube does not support facelet snapshots'));
 
    snapshotDeduperState = SnapshotDeduper.request(snapshotDeduperState);
    return new Promise<FaceletsEvent>((resolve, reject) => {
      let unsubscribe = (): void => {};
      const finish = (result: FaceletsEvent | Error): void => {
        unsubscribe();
        pendingFaceletSyncs.delete(rejectSync);
        Iif (result instanceof Error) reject(result);
        else resolve(result);
      };
      const rejectSync = (error: Error): void => finish(error);
      pendingFaceletSyncs.add(rejectSync);
      const listener = (event: SmartCubeSessionEvent): void => {
        if (event.type === 'FACELETS') finish(event);
        else Eif (event.type === 'DISCONNECT')
          finish(new Error('Cube disconnected before state sync'));
      };
      eventListeners.add(listener);
      unsubscribe = () => eventListeners.delete(listener);
      void connection.sendCommand({ type: 'REQUEST_FACELETS' }).catch((error: unknown) => {
        snapshotDeduperState = SnapshotDeduper.cancel(snapshotDeduperState);
        finish(error instanceof Error ? error : new Error(String(error)));
      });
    });
  }
 
  async function sendVendorCommand(command: SmartCubeVendorCommand): Promise<void> {
    const connection = state.connection;
    Iif (!connection) throw new Error('Cube is not connected');
    if (
      !connection.sendVendorCommand ||
      !connection.capabilities.vendorCommands?.includes(command.type)
    ) {
      throw new Error(`Unsupported cube command: ${command.type}`);
    }
    await connection.sendVendorCommand(command);
  }
 
  return {
    getState: (): SmartCubeSessionState => state,
    subscribe(listener: (next: SmartCubeSessionState) => void): () => void {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    /** Events remain owned by the session; consumers only observe them here. */
    subscribeEvents(listener: (event: SmartCubeSessionEvent) => void): () => void {
      eventListeners.add(listener);
      return () => eventListeners.delete(listener);
    },
    /**
     * Observe raw transport diagnostics without admitting them to the typed
     * cube-state stream. A transport may omit this capability entirely.
     */
    subscribeDiagnostics(listener: (event: SmartCubeSessionDiagnostic) => void): () => void {
      diagnosticListeners.add(listener);
      return () => diagnosticListeners.delete(listener);
    },
    /** Observe one event type without creating a parallel event channel. */
    on<T extends SessionEventType>(
      type: T,
      listener: (event: SessionEventOf<T>) => void,
    ): () => void {
      return this.subscribeEvents((event) => {
        if (event.type === type) listener(event as SessionEventOf<T>);
      });
    },
    connect,
    disconnect,
    resetGyro,
    /** Apply a runtime feature patch and reset any detector state it affects.
     * Accumulates across calls and keeps applying on top of whichever
     * profile is current, including one resolved later (e.g. after a
     * `HARDWARE` event or a reconnect to a different device). */
    configureFeatures(patch: SessionFeaturesPatch): void {
      runtimeFeaturePatch = deepMergeRecord(
        runtimeFeaturePatch ?? {},
        patch,
      ) as SessionFeaturesPatch;
      applyFeatures(mergeSessionFeatures(state.features, patch));
    },
    sendCommand,
    syncFacelets,
    sendVendorCommand,
  };
}