Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

73.9 KB
Raw Blame
import { describe, it, expect, vi, afterEach } from 'vitest';
import {
  CHUNK_HEADER_BYTES,
  ChunkReassembler,
  DC_BUFFERED_AMOUNT_LOW_THRESHOLD,
  DC_EPHEMERAL_SOFT_LIMIT,
  DC_RELIABLE_HIGH_WATER_MARK,
  DEFAULT_CHUNK_PAYLOAD_BYTES,
  ICollabTransport,
  encodeTransportFrames,
} from '../../services/collabTransport';
import {
  computeRoomTopicHash,
  decodeMqttPackets,
  encodeMqttConnect,
  encodeMqttPublish,
  encodeMqttSubscribe,
  generateP2pRoomCredentials,
  sha256HexSync,
  validateSignalingMessage,
  ISignalingClient,
  SignalingEnvelope,
} from '../../services/webrtcSignaling';
import {
  BINARY_MAGIC_0,
  BINARY_MAGIC_1,
  CODE_BRUSH_ASSET_DATA,
  CODE_BRUSH_ASSET_REQUEST,
  CODE_CAMERA_SYNC,
  CODE_CURSOR_MOVE,
  CODE_TILE_DELTA,
  buildP2pShareUrl,
  multiplayerService,
  parseCollabTarget,
  parseInviteUrl,
} from '../../services/multiplayerService';
import {
  DEFAULT_WEBRTC_ICE_SERVERS,
  WEBRTC_DATACHANNEL_LABEL,
  WEBRTC_EPHEMERAL_DATACHANNEL_LABEL,
  WebRtcHostHub,
  buildIceServers,
} from '../../services/webrtcHostHub';
import { WebRtcGuestClient } from '../../services/webrtcGuestClient';
import type { CollabPeer, MultiplayerMessage } from '../../types/multiplayer';
import type { WireTilePayload } from '../collabTileCodec';

describe('WebRTC Framing & Chunking (collabTransport.ts)', () => {
  it('round-trips small text and binary messages in a single frame', () => {
    const reassembler = new ChunkReassembler();

    const text = JSON.stringify({ type: 'CURSOR_MOVE', peerId: 'p1', x: 120, y: 240 });
    const textFrames = encodeTransportFrames('text', text, 1);
    expect(textFrames).toHaveLength(1);
    expect(textFrames[0].byteLength).toBeGreaterThan(CHUNK_HEADER_BYTES);

    const decodedText = reassembler.pushFrame(textFrames[0]);
    expect(decodedText).toEqual({ kind: 'text', text });

    // Binary Ink Studio packet ('I', 'N', ...)
    const binPayload = new Uint8Array([BINARY_MAGIC_0, BINARY_MAGIC_1, 0x01, 0x02, 0x03, 0xfe, 0xff]);
    const binFrames = encodeTransportFrames('binary', binPayload, 2);
    expect(binFrames).toHaveLength(1);

    const decodedBin = reassembler.pushFrame(binFrames[0]);
    expect(decodedBin?.kind).toBe('binary');
    if (decodedBin?.kind === 'binary') {
      expect(Array.from(new Uint8Array(decodedBin.data))).toEqual(Array.from(binPayload));
    }
  });

  it('splits large multi-MB binary snapshots into 48 KB chunks and reassembles cleanly', () => {
    const size = 1_250_000; // ~1.25 MB LZ4 canvas snapshot
    const payload = new Uint8Array(size);
    payload[0] = BINARY_MAGIC_0; // 'I'
    payload[1] = BINARY_MAGIC_1; // 'N'
    for (let i = 2; i < size; i++) {
      payload[i] = (i * 31 + 7) & 0xff;
    }

    const frames = encodeTransportFrames('binary', payload, 42);
    const expectedChunks = Math.ceil(size / DEFAULT_CHUNK_PAYLOAD_BYTES);
    expect(frames).toHaveLength(expectedChunks);
    expect(expectedChunks).toBeGreaterThan(20);

    for (const f of frames) {
      expect(f.byteLength).toBeLessThanOrEqual(CHUNK_HEADER_BYTES + DEFAULT_CHUNK_PAYLOAD_BYTES);
    }

    const reassembler = new ChunkReassembler();
    let result = null;
    for (let i = 0; i < frames.length; i++) {
      result = reassembler.pushFrame(frames[i]);
      if (i < frames.length - 1) {
        expect(result).toBeNull();
      }
    }

    expect(result?.kind).toBe('binary');
    if (result?.kind === 'binary') {
      const out = new Uint8Array(result.data);
      expect(out.byteLength).toBe(size);
      expect(out[0]).toBe(BINARY_MAGIC_0);
      expect(out[1]).toBe(BINARY_MAGIC_1);
      expect(out[123456]).toBe(payload[123456]);
      expect(out[size - 1]).toBe(payload[size - 1]);
    }
    expect(reassembler.getPendingCount()).toBe(0);
  });

  it('handles out-of-order, interleaved messageIds, duplicate chunks, and UTF-8 JSON', () => {
    const bigJson = JSON.stringify({
      type: 'DOC_SYNC_RESPONSE',
      name: 'Ink Studio — 世界',
      blob: 'あいうえお-'.repeat(4000),
    });
    const framesA = encodeTransportFrames('text', bigJson, 100, 1024);
    const framesB = encodeTransportFrames('text', 'hello-'.repeat(500), 200, 1024);
    expect(framesA.length).toBeGreaterThan(3);
    expect(framesB.length).toBeGreaterThan(2);

    const reassembler = new ChunkReassembler();
    expect(reassembler.pushFrame(framesA[2])).toBeNull();
    expect(reassembler.pushFrame(framesB[1])).toBeNull();
    expect(reassembler.pushFrame(framesA[2])).toBeNull(); // duplicate
    expect(reassembler.pushFrame(framesA[0])).toBeNull();

    let completedB: ReturnType<ChunkReassembler['pushFrame']> = null;
    for (let i = 0; i < framesB.length; i++) {
      if (i === 1) continue;
      completedB = reassembler.pushFrame(framesB[i]);
    }
    expect(completedB).toEqual({ kind: 'text', text: 'hello-'.repeat(500) });

    let completedA: ReturnType<ChunkReassembler['pushFrame']> = null;
    for (let i = 1; i < framesA.length; i++) {
      if (i === 2) continue;
      completedA = reassembler.pushFrame(framesA[i]);
    }
    expect(completedA).toEqual({ kind: 'text', text: bigJson });
    expect(reassembler.getPendingCount()).toBe(0);
  });

  it('rejects malformed headers and prunes expired partial messages', () => {
    const reassembler = new ChunkReassembler();

    expect(reassembler.pushFrame(new Uint8Array([0x49, 0x43]))).toBeNull();
    const badMagic = new Uint8Array(CHUNK_HEADER_BYTES + 4);
    badMagic[0] = 0x00;
    badMagic[1] = 0x00;
    expect(reassembler.pushFrame(badMagic)).toBeNull();

    const partialFrames = encodeTransportFrames('text', 'x'.repeat(2500), 99, 1024);
    expect(partialFrames.length).toBe(3);
    expect(reassembler.pushFrame(partialFrames[0], 1000)).toBeNull();
    expect(reassembler.getPendingCount()).toBe(1);

    reassembler.pruneExpired(10_000);
    expect(reassembler.getPendingCount()).toBe(1);

    reassembler.pruneExpired(40_000);
    expect(reassembler.getPendingCount()).toBe(0);
  });
});

describe('WebRTC Signaling Crypto, Validation & MQTT Codec (webrtcSignaling.ts)', () => {
  it('computes RFC-compliant SHA-256 hex digests and deterministic room topic hashes', () => {
    expect(sha256HexSync('')).toBe(
      'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
    );
    expect(sha256HexSync('abc')).toBe(
      'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
    );

    const h1 = computeRoomTopicHash('INK-7429', 'K8P2M9');
    const h2 = computeRoomTopicHash(' ink-7429 ', 'k8p2m9');
    const hDiffSecret = computeRoomTopicHash('INK-7429', 'XXXXXX');
    const hDiffCode = computeRoomTopicHash('INK-7430', 'K8P2M9');

    expect(h1).toHaveLength(64);
    expect(h1).toBe(h2);
    expect(h1).not.toBe(hDiffSecret);
    expect(h1).not.toBe(hDiffCode);
  });

  it('generates human-friendly INK-XXXX credentials and join codes', () => {
    const creds = generateP2pRoomCredentials();
    expect(creds.roomCode).toMatch(/^INK-\d{4}$/);
    expect(creds.roomSecret).toMatch(/^[A-Z2-9]{6}$/);
    expect(creds.joinCode).toBe(`${creds.roomCode}-${creds.roomSecret}`);
    expect(creds.roomHash).toBe(computeRoomTopicHash(creds.roomCode, creds.roomSecret));
  });

  it('validates signaling envelopes strictly against roomHash and schema constraints', () => {
    const roomHash = computeRoomTopicHash('INK-7429', 'K8P2M9');
    const wrongHash = computeRoomTopicHash('INK-7429', 'WRONG1');

    const validOffer = {
      v: 1,
      roomHash,
      mid: 'msg-1',
      type: 'offer',
      fromPeerId: 'guest-1',
      sdp: 'v=0\r\no=- 123 2 IN IP4 127.0.0.1\r\n',
      ts: Date.now(),
    };
    expect(validateSignalingMessage(validOffer, roomHash)).toMatchObject({
      v: 1,
      type: 'offer',
      roomHash,
      fromPeerId: 'guest-1',
      sdpType: 'offer',
    });

    // Cross-room hijack attempt
    expect(
      validateSignalingMessage(
        {
          v: 1,
          roomHash: wrongHash,
          mid: 'msg-2',
          type: 'offer',
          fromPeerId: 'attacker',
          sdp: 'v=0\r\n',
          ts: Date.now(),
        },
        roomHash
      )
    ).toBeNull();

    // Oversized SDP rejected
    expect(
      validateSignalingMessage(
        { v: 1, roomHash, mid: 'm6', type: 'offer', fromPeerId: 'g1', sdp: 'a'.repeat(70_000), ts: 1 },
        roomHash
      )
    ).toBeNull();

    // Unknown message type rejected
    expect(
      validateSignalingMessage(
        { v: 1, roomHash, mid: 'm5', type: 'eval', fromPeerId: 'g1', ts: 1 },
        roomHash
      )
    ).toBeNull();
  });

  it('encodes and decodes MQTT v3.1.1 CONNECT, SUBSCRIBE, and PUBLISH packets cleanly', () => {
    const connectPkt = encodeMqttConnect('ink-desktop-client');
    expect(connectPkt[0]).toBe(0x10);

    const subPkt = encodeMqttSubscribe(1, 'inkstudio/sig/v1/abcdef');
    expect(subPkt[0]).toBe(0x82);

    const topic = 'inkstudio/sig/v1/0123456789abcdef';
    const largePayload = JSON.stringify({ sdp: 'v=0\r\n' + 'a=candidate:'.repeat(40) });
    const pubPkt = encodeMqttPublish(topic, largePayload);
    const pubPkt2 = encodeMqttPublish(topic, '{"type":"bye"}');

    const combined = new Uint8Array(pubPkt.length + pubPkt2.length);
    combined.set(pubPkt, 0);
    combined.set(pubPkt2, pubPkt.length);

    const packets = decodeMqttPackets(combined);
    expect(packets).toHaveLength(2);
    expect(packets[0]).toEqual({ packetType: 3, topic, payload: largePayload });
    expect(packets[1]).toEqual({ packetType: 3, topic, payload: '{"type":"bye"}' });
    expect(decodeMqttPackets(pubPkt.slice(0, 10))).toEqual([]);
  });
});

describe('Room-Code & Invite-Link Routing (parseCollabTarget & parseInviteUrl)', () => {
  it('routes short P2P room codes and tablet P2P invite links to WebRTC P2P', () => {
    // Combined code (case-insensitive)
    expect(parseCollabTarget('ink-7429-k8p2m9')).toMatchObject({
      kind: 'p2p',
      roomCode: 'INK-7429',
      roomSecret: 'K8P2M9',
      joinCode: 'INK-7429-K8P2M9',
      roomName: 'INK-7429',
    });

    // Bare code (separate passcode)
    expect(parseCollabTarget('INK-7429')).toMatchObject({
      kind: 'p2p',
      roomCode: 'INK-7429',
      roomSecret: '',
      joinCode: 'INK-7429',
      roomName: 'INK-7429',
    });

    // Tablet deep-link P2P invite
    expect(
      parseCollabTarget('inkstudio://p2p?code=INK-5511&secret=ABC234&room=Tablet%20Canvas')
    ).toMatchObject({
      kind: 'p2p',
      roomCode: 'INK-5511',
      roomSecret: 'ABC234',
      joinCode: 'INK-5511-ABC234',
      roomName: 'Tablet Canvas',
    });

    // HTTPS web P2P invite with custom signaling URL
    expect(
      parseCollabTarget(
        'https://inkstudio.app/?p2p=INK-4400&secret=Q7R8S9&room=Collab&sig=wss%3A%2F%2Fsig.example.workers.dev%2Fsignal'
      )
    ).toMatchObject({
      kind: 'p2p',
      roomCode: 'INK-4400',
      roomSecret: 'Q7R8S9',
      joinCode: 'INK-4400-Q7R8S9',
      roomName: 'Collab',
      signalingUrl: 'wss://sig.example.workers.dev/signal',
    });

    // buildP2pShareUrl round-trip
    const shareUrl = buildP2pShareUrl(
      'INK-8123',
      'M4N5P6',
      'PC Studio',
      'wss://sig.example.workers.dev/signal'
    );
    expect(parseCollabTarget(shareUrl)).toMatchObject({
      kind: 'p2p',
      roomCode: 'INK-8123',
      roomSecret: 'M4N5P6',
      joinCode: 'INK-8123-M4N5P6',
      roomName: 'PC Studio',
      signalingUrl: 'wss://sig.example.workers.dev/signal',
    });
  });

  it('continues routing ws://, wss://, trycloudflare.com, and LAN HTTP links to WebSocket', () => {
    const cfHttp = parseCollabTarget(
      'https://warm-ink-1234.trycloudflare.com/?room=Studio&token=tok1'
    );
    expect(cfHttp).toMatchObject({
      kind: 'ws',
      host: 'warm-ink-1234.trycloudflare.com',
      port: 443,
      roomName: 'Studio',
      token: 'tok1',
      isSecure: true,
    });

    // Bare trycloudflare.com URL without ?room=
    const cfBare = parseCollabTarget('https://quick-room.trycloudflare.com/');
    expect(cfBare).toMatchObject({
      kind: 'ws',
      host: 'quick-room.trycloudflare.com',
      port: 443,
      isSecure: true,
    });

    // Direct wss:// URL with custom path
    const directWss = parseCollabTarget('wss://relay.example.com:8443/custom/ws?room=Art&token=abc');
    expect(directWss).toMatchObject({
      kind: 'ws',
      host: 'relay.example.com',
      port: 8443,
      roomName: 'Art',
      token: 'abc',
      isSecure: true,
      wsPath: '/custom/ws',
    });

    // Local LAN ws:// and http:// URLs
    const lanWs = parseCollabTarget('ws://192.168.1.40:30303/ws?token=lan1');
    expect(lanWs).toMatchObject({
      kind: 'ws',
      host: '192.168.1.40',
      port: 30303,
      token: 'lan1',
      isSecure: false,
    });

    const lanHttp = parseInviteUrl('http://192.168.1.40:30303/?room=LAN&token=lan2');
    expect(lanHttp).toMatchObject({
      host: '192.168.1.40',
      port: 30303,
      roomName: 'LAN',
      token: 'lan2',
      isSecure: false,
    });

    // Invalid inputs
    expect(parseCollabTarget('not a room code')).toBeNull();
    expect(parseCollabTarget('')).toBeNull();
  });
});

describe('Binary & JSON Wire Compatibility over ICollabTransport & WebRTC Hub/Guest', () => {
  const origRTCPeerConnection = globalThis.RTCPeerConnection;

  afterEach(() => {
    multiplayerService.disconnect();
    if (origRTCPeerConnection === undefined) {
      delete (globalThis as Record<string, unknown>).RTCPeerConnection;
    } else {
      globalThis.RTCPeerConnection = origRTCPeerConnection;
    }
  });

  it('includes public Google + Cloudflare STUN servers and optional TURN config', () => {
    const defaultIce = buildIceServers();
    expect(defaultIce).toEqual(DEFAULT_WEBRTC_ICE_SERVERS);

    const withTurn = buildIceServers({
      turnUrl: 'turns:turn.example.com:5349',
      turnUsername: 'ink',
      turnCredential: 'secret',
    });
    expect(withTurn).toHaveLength(DEFAULT_WEBRTC_ICE_SERVERS.length + 1);
    expect(withTurn[withTurn.length - 1]).toEqual({
      urls: 'turns:turn.example.com:5349',
      username: 'ink',
      credential: 'secret',
    });
  });

  it('round-trips JSON and binary (LZ4 tile delta + stroke + cursor) packets via multiplayerService.attachTransport', () => {
    const sentTexts: string[] = [];
    const sentBinaries: Uint8Array[] = [];
    const textListeners = new Set<(text: string) => void>();
    const binaryListeners = new Set<(data: ArrayBuffer) => void>();
    const closeListeners = new Set<(reason?: string) => void>();
    let open = true;

    const loopbackTransport: ICollabTransport = {
      kind: 'webrtc-guest',
      isOpen: () => open,
      getBufferedAmount: () => 0,
      sendText: (text: string) => {
        sentTexts.push(text);
        // Loop back through ChunkReassembler to simulate real WebRTC DataChannel framing
        const frames = encodeTransportFrames('text', text, sentTexts.length);
        const reassembler = new ChunkReassembler();
        for (const frame of frames) {
          const out = reassembler.pushFrame(frame);
          if (out?.kind === 'text') {
            textListeners.forEach((h) => h(out.text));
          }
        }
      },
      sendBinary: (data: ArrayBuffer | Uint8Array) => {
        const bytes = data instanceof Uint8Array ? new Uint8Array(data) : new Uint8Array(data);
        sentBinaries.push(bytes);
        const frames = encodeTransportFrames('binary', bytes, 1000 + sentBinaries.length);
        const reassembler = new ChunkReassembler();
        for (const frame of frames) {
          const out = reassembler.pushFrame(frame);
          if (out?.kind === 'binary') {
            binaryListeners.forEach((h) => h(out.data));
          }
        }
      },
      close: () => {
        if (!open) return;
        open = false;
        closeListeners.forEach((h) => h('closed'));
      },
      onTextMessage: (h) => {
        textListeners.add(h);
        return () => textListeners.delete(h);
      },
      onBinaryMessage: (h) => {
        binaryListeners.add(h);
        return () => binaryListeners.delete(h);
      },
      onClose: (h) => {
        closeListeners.add(h);
        return () => closeListeners.delete(h);
      },
      onError: () => () => {},
    };

    const received: MultiplayerMessage[] = [];
    const unsub = multiplayerService.onMessage((msg) => received.push(msg));

    const peer: CollabPeer = {
      id: 'desktop-peer-1',
      name: 'DesktopArtist',
      color: '#3b82f6',
      role: 'editor',
    };

    multiplayerService.attachTransport(loopbackTransport, peer, { sendJoinRequest: true });
    expect(multiplayerService.isConnected()).toBe(true);
    expect(multiplayerService.getTransportKind()).toBe('webrtc-guest');

    // Verify automatic JOIN_REQUEST over WebRTC text frame
    expect(received.some((m) => m.type === 'JOIN_REQUEST')).toBe(true);

    // Send JSON layer rename
    multiplayerService.sendLayerRename('layer-1', 'Lineart');
    const renameMsg = received.find((m) => m.type === 'LAYER_RENAME');
    expect(renameMsg).toMatchObject({
      type: 'LAYER_RENAME',
      layerId: 'layer-1',
      newName: 'Lineart',
    });

    // Send binary stroke chunk ('I','N', CODE_STROKE_CHUNK)
    multiplayerService.sendStrokeChunk('stroke-abc', [
      { x: 10, y: 20, pressure: 0.75, width: 12, timestamp: 1000 },
      { x: 25.5, y: 40.25, pressure: 0.9, width: 14, timestamp: 1016 },
    ]);
    const chunkMsg = received.find((m) => m.type === 'STROKE_CHUNK');
    expect(chunkMsg).toBeDefined();
    if (chunkMsg?.type === 'STROKE_CHUNK') {
      expect(chunkMsg.strokeId).toBe('stroke-abc');
      expect(chunkMsg.points).toHaveLength(2);
      expect(chunkMsg.points[0].x).toBeCloseTo(10, 3);
      expect(chunkMsg.points[1].pressure).toBeCloseTo(0.9, 3);
    }

    // Send binary LZ4 tile delta ('I','N', CODE_TILE_DELTA) — full 256x256 RGBA tile (262,144 bytes)
    const tileBytes = new Uint8Array(256 * 256 * 4);
    for (let i = 0; i < tileBytes.length; i += 4) {
      tileBytes[i] = 255;
      tileBytes[i + 1] = 128;
      tileBytes[i + 2] = 64;
      tileBytes[i + 3] = 255;
    }
    const tile: WireTilePayload = {
      layerId: 'layer-1',
      tileX: 2,
      tileY: 3,
      format: 'color-32bit',
      version: 5,
      data: tileBytes,
    };
    multiplayerService.sendTileDelta('layer-1', tile);
    const tileMsg = received.find((m) => m.type === 'BINARY_TILE');
    expect(tileMsg).toBeDefined();
    if (tileMsg?.type === 'BINARY_TILE') {
      expect(tileMsg.layerId).toBe('layer-1');
      expect(tileMsg.tileX).toBe(2);
      expect(tileMsg.tileY).toBe(3);
      expect(tileMsg.version).toBe(5);
      expect(tileMsg.data?.byteLength).toBe(tileBytes.byteLength);
      expect(tileMsg.data?.[0]).toBe(255);
      expect(tileMsg.data?.[1]).toBe(128);
    }

    unsub();
  });

  it('connects WebRtcHostHub and WebRtcGuestClient end-to-end and enforces roles on binary & JSON traffic', async () => {
    const roomHash = computeRoomTopicHash('INK-9001', 'XYZ234');

    // In-memory signaling bus linking Host Hub and Guest Client
    const signalingBus = new Set<{ peerId: string; cb: (env: SignalingEnvelope) => void }>();
    const createMockSignaling = (peerId: string): ISignalingClient => ({
      connect: vi.fn().mockResolvedValue(undefined),
      send: (env) => {
        const full: SignalingEnvelope = {
          ...env,
          v: 1,
          roomHash,
          mid: `m-${Math.random().toString(36).slice(2)}`,
          ts: Date.now(),
        };
        queueMicrotask(() => {
          for (const sub of signalingBus) {
            if (sub.peerId === full.fromPeerId) continue;
            if (full.toPeerId && full.toPeerId !== sub.peerId) continue;
            sub.cb(full);
          }
        });
      },
      onMessage: (cb) => {
        const entry = { peerId, cb };
        signalingBus.add(entry);
        return () => signalingBus.delete(entry);
      },
      onError: () => () => {},
      close: vi.fn(),
    });

    // Paired FakeDataChannel / FakeRTCPeerConnection wiring Guest <-> Host
    class PairedDataChannel {
      readyState: RTCDataChannelState = 'connecting';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      peerChannel: PairedDataChannel | null = null;
      onopen: (() => void) | null = null;
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;

      open() {
        this.readyState = 'open';
        this.onopen?.();
      }
      send(data: ArrayBuffer | Uint8Array) {
        if (this.readyState !== 'open' || !this.peerChannel || this.peerChannel.readyState !== 'open') {
          return;
        }
        const copy =
          data instanceof Uint8Array
            ? new Uint8Array(data)
            : new Uint8Array(data.slice(0));
        this.peerChannel.onmessage?.({ data: copy.buffer });
      }
      close() {
        this.readyState = 'closed';
        this.onclose?.();
      }
    }

    let guestPcRef: FakePeerConnection | null = null;
    class FakePeerConnection {
      connectionState: RTCPeerConnectionState = 'new';
      localDescription: RTCSessionDescriptionInit | null = null;
      onicecandidate: ((ev: { candidate: null }) => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: PairedDataChannel }) => void) | null = null;
      dc: PairedDataChannel | null = null;

      createDataChannel() {
        const dc = new PairedDataChannel();
        this.dc = dc;
        guestPcRef = this;
        return dc;
      }
      async createOffer() {
        return { type: 'offer' as const, sdp: 'v=0\r\noffer\r\n' };
      }
      async setLocalDescription(desc: RTCSessionDescriptionInit) {
        this.localDescription = desc;
      }
      async setRemoteDescription(desc: RTCSessionDescriptionInit) {
        if (desc.type === 'answer' && this.dc) {
          this.connectionState = 'connected';
          this.dc.open();
        }
      }
      async createAnswer() {
        // Pair host DC with guest DC
        const hostDc = new PairedDataChannel();
        if (guestPcRef?.dc) {
          hostDc.peerChannel = guestPcRef.dc;
          guestPcRef.dc.peerChannel = hostDc;
        }
        hostDc.readyState = 'open';
        this.connectionState = 'connected';
        this.ondatachannel?.({ channel: hostDc });
        return { type: 'answer' as const, sdp: 'v=0\r\nanswer\r\n' };
      }
      async addIceCandidate() {}
      close() {
        this.connectionState = 'closed';
      }
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'android-host',
      signalingClient: createMockSignaling('android-host'),
    });
    const hostReceivedTexts: string[] = [];
    const hostReceivedBinaries: ArrayBuffer[] = [];
    hub.onTextMessage((t) => hostReceivedTexts.push(t));
    hub.onBinaryMessage((b) => hostReceivedBinaries.push(b));
    await hub.start();

    const guest = new WebRtcGuestClient({
      roomHash,
      peerId: 'desktop-guest',
      signalingClient: createMockSignaling('desktop-guest'),
    });
    const guestReceivedTexts: string[] = [];
    guest.onTextMessage((t) => guestReceivedTexts.push(t));
    await guest.connect();

    expect(guest.isOpen()).toBe(true);
    expect(hub.getConnectedGuestCount()).toBe(1);

    // Guest sends JOIN_REQUEST -> received by Host with authoritative seq
    guest.sendText(
      JSON.stringify({
        type: 'JOIN_REQUEST',
        senderId: 'desktop-guest',
        peer: { id: 'desktop-guest', name: 'DesktopGuest', color: '#10b981' },
      })
    );
    expect(hostReceivedTexts).toHaveLength(1);
    expect(JSON.parse(hostReceivedTexts[0])).toMatchObject({
      type: 'JOIN_REQUEST',
      senderId: 'desktop-guest',
      seq: 1,
    });

    // Guest sends binary packet (CODE_STROKE_START) -> accepted while editor
    const strokeBin = new Uint8Array([BINARY_MAGIC_0, BINARY_MAGIC_1, 0x01, 0, 0, 0, 0, 0, 0, 0, 0]);
    guest.sendBinary(strokeBin);
    expect(hostReceivedBinaries).toHaveLength(1);

    // Host demotes guest to viewer
    hub.sendText(
      JSON.stringify({
        type: 'PEER_ROLE_UPDATE',
        senderId: 'android-host',
        targetPeerId: 'desktop-guest',
        role: 'viewer',
      })
    );

    // Viewer tries to send binary stroke -> blocked with ACCESS_DENIED (VIEWER_READONLY)
    hostReceivedBinaries.length = 0;
    guestReceivedTexts.length = 0;
    guest.sendBinary(strokeBin);
    expect(hostReceivedBinaries).toHaveLength(0);
    expect(guestReceivedTexts).toHaveLength(1);
    expect(JSON.parse(guestReceivedTexts[0])).toMatchObject({
      type: 'ACCESS_DENIED',
      code: 'VIEWER_READONLY',
    });

    guest.close();
    hub.close();
  });

  it('stamps authoritative monotonic seq on binary packets, unicasts via sendBinaryTo, and enforces layer locks', async () => {
    const roomHash = computeRoomTopicHash('INK-9002', 'ABC345');
    const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
    const mockSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: vi.fn(),
      onMessage: (cb) => {
        signalingListeners.add(cb);
        return () => signalingListeners.delete(cb);
      },
      onError: () => () => {},
      close: vi.fn(),
    };

    class FakeDataChannel {
      readyState: RTCDataChannelState = 'open';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      sent: ArrayBuffer[] = [];
      onopen: (() => void) | null = null;
      onmessage: ((ev: { data: unknown }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      send(data: ArrayBuffer) {
        this.sent.push(data);
      }
      close() {
        this.readyState = 'closed';
      }
    }

    const createdPcs: Array<{
      dc: FakeDataChannel;
      ondatachannel: ((ev: { channel: FakeDataChannel }) => void) | null;
    }> = [];
    class FakePeerConnection {
      connectionState: RTCPeerConnectionState = 'connected';
      onicecandidate: ((ev: { candidate: null }) => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: FakeDataChannel }) => void) | null = null;
      dc = new FakeDataChannel();
      constructor() {
        createdPcs.push(this);
      }
      async setRemoteDescription() {}
      async createAnswer() {
        return { type: 'answer', sdp: 'v=0\r\nanswer\r\n' };
      }
      async setLocalDescription() {}
      async addIceCandidate() {}
      close() {
        this.connectionState = 'closed';
      }
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'host-1',
      signalingClient: mockSignaling,
    });
    const hostBinaries: ArrayBuffer[] = [];
    hub.onBinaryMessage((b) => hostBinaries.push(b));
    await hub.start();

    for (const gid of ['guest-a', 'guest-b']) {
      for (const listener of signalingListeners) {
        listener({
          v: 1,
          mid: `offer-${gid}`,
          roomHash,
          type: 'offer',
          fromPeerId: gid,
          sdp: 'v=0\r\noffer\r\n',
          ts: Date.now(),
        });
      }
    }
    await new Promise((r) => setTimeout(r, 0));

    const dcA = createdPcs[0].dc;
    const dcB = createdPcs[1].dc;
    createdPcs[0].ondatachannel?.({ channel: dcA });
    createdPcs[1].ondatachannel?.({ channel: dcB });

    const sendText = (dc: FakeDataChannel, id: number, payload: object) => {
      for (const f of encodeTransportFrames('text', JSON.stringify(payload), id)) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    };
    const sendBin = (dc: FakeDataChannel, id: number, bytes: Uint8Array) => {
      for (const f of encodeTransportFrames('binary', bytes, id)) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    };
    const makeTileBin = (layerId: string, clientLamport: number): Uint8Array => {
      const lid = new TextEncoder().encode(layerId);
      const payloadLen = 2 + lid.length + 4;
      const pkt = new Uint8Array(11 + payloadLen);
      const v = new DataView(pkt.buffer);
      pkt[0] = 0x49;
      pkt[1] = 0x4e;
      pkt[2] = 0x04; // CODE_TILE_DELTA
      v.setUint32(3, clientLamport, true);
      v.setUint32(7, payloadLen, true);
      v.setUint16(11, lid.length, true);
      pkt.set(lid, 13);
      return pkt;
    };

    // 1. Pre-join binary tile is rejected before JOIN_REQUEST
    sendBin(dcA, 1, makeTileBin('layer-1', 50));
    expect(hostBinaries).toHaveLength(0);

    // Join both guests
    sendText(dcA, 2, { type: 'JOIN_REQUEST', peer: { id: 'guest-a', name: 'A', color: '#111' } });
    sendText(dcB, 3, { type: 'JOIN_REQUEST', peer: { id: 'guest-b', name: 'B', color: '#222' } });
    dcA.sent.length = 0;
    dcB.sent.length = 0;

    // 2. Host unicasts binary tile to guest-b only -> guest-a receives nothing, guest-b gets stamped seq
    hub.sendBinaryTo('guest-b', makeTileBin('layer-1', 999));
    expect(dcA.sent).toHaveLength(0);
    expect(dcB.sent).toHaveLength(1);
    const reB = new ChunkReassembler();
    const msgB = reB.pushFrame(dcB.sent[0]);
    expect(msgB?.kind).toBe('binary');
    const hostUnicastSeq =
      msgB?.kind === 'binary' ? new DataView(msgB.data).getUint32(3, true) : 0;
    expect(hostUnicastSeq).toBeGreaterThan(0);
    expect(hostUnicastSeq).not.toBe(999);

    // 3. Guest A sends binary tile with low Lamport (1) -> Hub stamps monotonic seq > hostUnicastSeq
    dcB.sent.length = 0;
    sendBin(dcA, 4, makeTileBin('layer-1', 1));
    expect(hostBinaries).toHaveLength(1);
    const stampedSeq = new DataView(hostBinaries[0]).getUint32(3, true);
    expect(stampedSeq).toBeGreaterThan(hostUnicastSeq);

    // 4. Host locks layer-1 to guest-a -> guest-b binary tile on layer-1 is rejected with LAYER_LOCKED
    hub.sendText(
      JSON.stringify({
        type: 'LAYER_UPDATE',
        layerId: 'layer-1',
        patch: { reservedByPeerId: 'guest-a' },
      })
    );
    hostBinaries.length = 0;
    dcB.sent.length = 0;
    sendBin(dcB, 5, makeTileBin('layer-1', 100));
    expect(hostBinaries).toHaveLength(0);
    expect(dcB.sent.length).toBeGreaterThan(0);
    const denied = new ChunkReassembler().pushFrame(dcB.sent[0]);
    expect(denied?.kind).toBe('text');
    if (denied?.kind === 'text') {
      expect(JSON.parse(denied.text).code).toBe('LAYER_LOCKED');
    }

    hub.close();
  });
});

describe('WebRTC Production Parity: Dual Channels, Backpressure, Single-Encode, op_log & Snapshot Isolation', () => {
  const origRTCPeerConnection = globalThis.RTCPeerConnection;

  afterEach(() => {
    multiplayerService.disconnect();
    vi.useRealTimers();
    if (origRTCPeerConnection === undefined) {
      delete (globalThis as Record<string, unknown>).RTCPeerConnection;
    } else {
      globalThis.RTCPeerConnection = origRTCPeerConnection;
    }
  });

  const makeCursorBin = (peerId: string, x = 12, y = 34): Uint8Array => {
    const pid = new TextEncoder().encode(peerId);
    const payloadSize = 2 + pid.length + 10;
    const pkt = new Uint8Array(11 + payloadSize);
    const v = new DataView(pkt.buffer);
    pkt[0] = BINARY_MAGIC_0;
    pkt[1] = BINARY_MAGIC_1;
    pkt[2] = CODE_CURSOR_MOVE;
    v.setUint32(3, 1, true);
    v.setUint32(7, payloadSize, true);
    v.setUint16(11, pid.length, true);
    pkt.set(pid, 13);
    v.setFloat32(13 + pid.length, x, true);
    v.setFloat32(13 + pid.length + 4, y, true);
    return pkt;
  };

  const makeCameraBin = (peerId: string, zoom = 1.5): Uint8Array => {
    const pid = new TextEncoder().encode(peerId);
    const payloadSize = 2 + pid.length + 21;
    const pkt = new Uint8Array(11 + payloadSize);
    const v = new DataView(pkt.buffer);
    pkt[0] = BINARY_MAGIC_0;
    pkt[1] = BINARY_MAGIC_1;
    pkt[2] = CODE_CAMERA_SYNC;
    v.setUint32(3, 1, true);
    v.setUint32(7, payloadSize, true);
    v.setUint16(11, pid.length, true);
    pkt.set(pid, 13);
    const off = 13 + pid.length;
    v.setFloat32(off, 500, true);
    v.setFloat32(off + 4, 400, true);
    v.setFloat32(off + 8, zoom, true);
    v.setFloat32(off + 12, 0, true);
    v.setUint16(off + 16, 1280, true);
    v.setUint16(off + 18, 720, true);
    pkt[off + 20] = 0;
    return pkt;
  };

  const makeFullTileBin = (
    layerId: string,
    tileX: number,
    tileY: number,
    tagByte: number,
    extraBodyBytes = 16
  ): Uint8Array => {
    const lid = new TextEncoder().encode(layerId);
    const tileBodyLen = 14 + extraBodyBytes;
    const payloadLen = 2 + lid.length + tileBodyLen;
    const pkt = new Uint8Array(11 + payloadLen);
    const v = new DataView(pkt.buffer);
    pkt[0] = BINARY_MAGIC_0;
    pkt[1] = BINARY_MAGIC_1;
    pkt[2] = CODE_TILE_DELTA;
    v.setUint32(3, 1, true);
    v.setUint32(7, payloadLen, true);
    v.setUint16(11, lid.length, true);
    pkt.set(lid, 13);
    const tOff = 13 + lid.length;
    v.setInt32(tOff, tileX, true);
    v.setInt32(tOff + 4, tileY, true);
    pkt[tOff + 8] = 4; // color-32bit
    v.setUint32(tOff + 9, tagByte, true); // tile version / tag
    pkt[tOff + 13] = 1; // raw codec
    pkt.fill(tagByte & 0xff, tOff + 14);
    return pkt;
  };

  const makeBrushAssetDataBin = (hash: string, mime: string, body: Uint8Array): Uint8Array => {
    const hBytes = new TextEncoder().encode(hash);
    const mBytes = new TextEncoder().encode(mime);
    const payloadSize = 1 + hBytes.length + 1 + mBytes.length + body.byteLength;
    const pkt = new Uint8Array(11 + payloadSize);
    const v = new DataView(pkt.buffer);
    pkt[0] = BINARY_MAGIC_0;
    pkt[1] = BINARY_MAGIC_1;
    pkt[2] = CODE_BRUSH_ASSET_DATA;
    v.setUint32(3, 1, true);
    v.setUint32(7, payloadSize, true);
    let off = 11;
    pkt[off++] = hBytes.length;
    pkt.set(hBytes, off);
    off += hBytes.length;
    pkt[off++] = mBytes.length;
    pkt.set(mBytes, off);
    off += mBytes.length;
    pkt.set(body, off);
    return pkt;
  };

  const makeBrushAssetReqBin = (hash: string, senderId: string): Uint8Array => {
    const json = new TextEncoder().encode(JSON.stringify({ hash, senderId }));
    const pkt = new Uint8Array(11 + json.length);
    const v = new DataView(pkt.buffer);
    pkt[0] = BINARY_MAGIC_0;
    pkt[1] = BINARY_MAGIC_1;
    pkt[2] = CODE_BRUSH_ASSET_REQUEST;
    v.setUint32(3, 1, true);
    v.setUint32(7, json.length, true);
    pkt.set(json, 11);
    return pkt;
  };

  const decodeAllFrames = (frames: Array<Uint8Array | ArrayBuffer>) => {
    const reassembler = new ChunkReassembler();
    const out: Array<{ kind: 'text'; text: string } | { kind: 'binary'; data: ArrayBuffer }> = [];
    for (const f of frames) {
      const msg = reassembler.pushFrame(f);
      if (msg) out.push(msg);
    }
    return out;
  };

  it('routes CURSOR_MOVE and CAMERA_SYNC over the unordered ephemeral channel while reliable tiles/layers stay ordered, with seamless fallback', async () => {
    const roomHash = computeRoomTopicHash('INK-9101', 'DUAL12');
    const signalingBus = new Set<{ peerId: string; cb: (env: SignalingEnvelope) => void }>();
    const createMockSignaling = (peerId: string): ISignalingClient => ({
      connect: vi.fn().mockResolvedValue(undefined),
      send: (env) => {
        const full: SignalingEnvelope = {
          ...env,
          v: 1,
          roomHash,
          mid: `m-${Math.random().toString(36).slice(2)}`,
          ts: Date.now(),
        };
        queueMicrotask(() => {
          for (const sub of signalingBus) {
            if (sub.peerId === full.fromPeerId) continue;
            if (full.toPeerId && full.toPeerId !== sub.peerId) continue;
            sub.cb(full);
          }
        });
      },
      onMessage: (cb) => {
        const entry = { peerId, cb };
        signalingBus.add(entry);
        return () => signalingBus.delete(entry);
      },
      onError: () => () => {},
      close: vi.fn(),
    });

    class DualPairedDataChannel {
      label: string;
      ordered: boolean;
      maxRetransmits?: number;
      readyState: RTCDataChannelState = 'connecting';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      bufferedAmountLowThreshold = 0;
      sent: Uint8Array[] = [];
      peerChannel: DualPairedDataChannel | null = null;
      onopen: (() => void) | null = null;
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      onbufferedamountlow: (() => void) | null = null;

      constructor(label: string, init?: RTCDataChannelInit) {
        this.label = label;
        this.ordered = init?.ordered ?? true;
        this.maxRetransmits = init?.maxRetransmits;
      }

      open() {
        this.readyState = 'open';
        this.onopen?.();
      }

      send(data: ArrayBuffer | Uint8Array) {
        if (this.readyState !== 'open') return;
        const view = data instanceof Uint8Array ? data : new Uint8Array(data);
        this.sent.push(view);
        if (this.peerChannel && this.peerChannel.readyState === 'open') {
          const copy = new Uint8Array(view.byteLength);
          copy.set(view);
          this.peerChannel.onmessage?.({ data: copy.buffer });
        }
      }

      close() {
        if (this.readyState === 'closed') return;
        this.readyState = 'closed';
        this.onclose?.();
        if (this.peerChannel && this.peerChannel.readyState !== 'closed') {
          this.peerChannel.readyState = 'closed';
          this.peerChannel.onclose?.();
        }
      }
    }

    let guestPcRef: DualPeerConnection | null = null;
    let hostPcRef: DualPeerConnection | null = null;

    class DualPeerConnection {
      connectionState: RTCPeerConnectionState = 'new';
      localDescription: RTCSessionDescriptionInit | null = null;
      onicecandidate: ((ev: { candidate: null }) => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: DualPairedDataChannel }) => void) | null = null;
      channels = new Map<string, DualPairedDataChannel>();

      createDataChannel(label: string, init?: RTCDataChannelInit) {
        const dc = new DualPairedDataChannel(label, init);
        this.channels.set(label, dc);
        guestPcRef = this;
        return dc;
      }

      async createOffer() {
        return { type: 'offer' as const, sdp: 'v=0\r\na=ice-ufrag:guest1\r\n' };
      }
      async setLocalDescription(desc: RTCSessionDescriptionInit) {
        this.localDescription = desc;
      }
      async setRemoteDescription(desc: RTCSessionDescriptionInit) {
        if (desc.type === 'answer') {
          this.connectionState = 'connected';
          for (const dc of this.channels.values()) {
            dc.open();
          }
        }
      }
      async createAnswer() {
        hostPcRef = this;
        this.connectionState = 'connected';
        if (guestPcRef) {
          for (const [label, guestDc] of guestPcRef.channels.entries()) {
            const hostDc = new DualPairedDataChannel(label, {
              ordered: guestDc.ordered,
              maxRetransmits: guestDc.maxRetransmits,
            });
            hostDc.peerChannel = guestDc;
            guestDc.peerChannel = hostDc;
            hostDc.readyState = 'open';
            this.channels.set(label, hostDc);
            this.ondatachannel?.({ channel: hostDc });
          }
        }
        return { type: 'answer' as const, sdp: 'v=0\r\na=ice-ufrag:host1\r\n' };
      }
      async addIceCandidate() {}
      close() {
        this.connectionState = 'closed';
      }
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = DualPeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'host-1',
      signalingClient: createMockSignaling('host-1'),
    });
    const hostBinaries: ArrayBuffer[] = [];
    const hostTexts: string[] = [];
    hub.onBinaryMessage((b) => hostBinaries.push(b));
    hub.onTextMessage((t) => hostTexts.push(t));
    await hub.start();

    const guest = new WebRtcGuestClient({
      roomHash,
      peerId: 'guest-1',
      signalingClient: createMockSignaling('guest-1'),
    });
    const guestBinaries: ArrayBuffer[] = [];
    const guestTexts: string[] = [];
    guest.onBinaryMessage((b) => guestBinaries.push(b));
    guest.onTextMessage((t) => guestTexts.push(t));
    await guest.connect();

    const guestRel = guestPcRef!.channels.get(WEBRTC_DATACHANNEL_LABEL)!;
    const guestEph = guestPcRef!.channels.get(WEBRTC_EPHEMERAL_DATACHANNEL_LABEL)!;
    const hostRel = hostPcRef!.channels.get(WEBRTC_DATACHANNEL_LABEL)!;
    const hostEph = hostPcRef!.channels.get(WEBRTC_EPHEMERAL_DATACHANNEL_LABEL)!;

    expect(guestRel.ordered).toBe(true);
    expect(guestEph.ordered).toBe(false);
    expect(guestEph.maxRetransmits).toBe(0);
    expect(guestRel.bufferedAmountLowThreshold).toBe(DC_BUFFERED_AMOUNT_LOW_THRESHOLD);
    expect(hostRel.bufferedAmountLowThreshold).toBe(DC_BUFFERED_AMOUNT_LOW_THRESHOLD);
    expect(guest.hasOpenEphemeralChannel()).toBe(true);

    // Join guest via multiplayerService so priority routing hook is exercised end-to-end
    const guestPeer: CollabPeer = { id: 'guest-1', name: 'G1', color: '#3b82f6', role: 'editor' };
    multiplayerService.attachTransport(guest, guestPeer, { sendJoinRequest: true });
    expect(hostTexts).toHaveLength(1);

    guestRel.sent.length = 0;
    guestEph.sent.length = 0;
    hostRel.sent.length = 0;
    hostEph.sent.length = 0;
    hostBinaries.length = 0;
    guestBinaries.length = 0;

    // 1. Guest sends CURSOR_MOVE & CAMERA_SYNC via multiplayerService -> must use ephemeral channel ONLY
    multiplayerService.sendCursor(120, 240, false, 'brush', true);
    multiplayerService.sendCameraSync(
      {
        centerX: 500,
        centerY: 300,
        zoom: 2,
        rotation: 0,
        flipX: false,
        flipY: false,
        viewportWidth: 1280,
        viewportHeight: 720,
      },
      true
    );
    expect(guestEph.sent).toHaveLength(2);
    expect(guestRel.sent).toHaveLength(0);
    expect(hostBinaries).toHaveLength(2);
    expect(new Uint8Array(hostBinaries[0])[2]).toBe(CODE_CURSOR_MOVE);
    expect(new Uint8Array(hostBinaries[1])[2]).toBe(CODE_CAMERA_SYNC);

    // 2. Guest sends BINARY_TILE & LAYER_UPDATE -> must use reliable ordered channel ONLY
    guestRel.sent.length = 0;
    guestEph.sent.length = 0;
    guest.sendBinary(makeFullTileBin('layer-1', 0, 0, 7));
    multiplayerService.sendLayerUpdate('layer-1', { blendMode: 'multiply' }, undefined, {
      immediate: true,
    });
    expect(guestRel.sent).toHaveLength(2);
    expect(guestEph.sent).toHaveLength(0);

    // 3. Host broadcasts CURSOR_MOVE & CAMERA_SYNC -> must use Host ephemeral channel ONLY
    //    even when Host reliable channel is heavily backed up (zero HoL blocking!)
    hostRel.bufferedAmount = DC_RELIABLE_HIGH_WATER_MARK + 100_000;
    hub.sendBinary(makeCursorBin('host-1', 99, 88));
    hub.sendBinary(makeCameraBin('host-1', 2.5));
    expect(hostEph.sent).toHaveLength(2);
    expect(hostRel.sent).toHaveLength(0);
    expect(guestBinaries).toHaveLength(2);

    // Host broadcasts BINARY_TILE & LAYER_UPDATE -> must stay on reliable channel (queued until drain)
    hostRel.bufferedAmount = 0;
    hub.sendBinary(makeFullTileBin('layer-1', 1, 2, 9));
    hub.sendText(JSON.stringify({ type: 'LAYER_UPDATE', layerId: 'layer-1', patch: { opacity: 0.5 } }));
    expect(hostRel.sent).toHaveLength(2);
    expect(hostEph.sent).toHaveLength(2); // unchanged

    // 4. Ephemeral channel closes/fails -> connection stays alive and seamlessly falls back to reliable!
    guestEph.close();
    expect(guest.isOpen()).toBe(true);
    expect(guest.hasOpenEphemeralChannel()).toBe(false);
    expect(hub.getConnectedGuestCount()).toBe(1);

    guestRel.sent.length = 0;
    hostRel.sent.length = 0;
    hostBinaries.length = 0;
    guestBinaries.length = 0;

    guest.sendBinary(makeCursorBin('guest-1', 50, 60));
    expect(guestRel.sent).toHaveLength(1);
    expect(hostBinaries).toHaveLength(1);

    hub.sendBinary(makeCameraBin('host-1', 1.25));
    expect(hostRel.sent).toHaveLength(1);
    expect(guestBinaries).toHaveLength(1);

    guest.close();
    hub.close();
  });

  it('drops ephemeral packets under backpressure while queuing reliable tiles in strict FIFO order until bufferedamountlow fires', async () => {
    const roomHash = computeRoomTopicHash('INK-9102', 'BACK99');
    const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
    const mockSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: vi.fn(),
      onMessage: (cb) => {
        signalingListeners.add(cb);
        return () => signalingListeners.delete(cb);
      },
      onError: () => () => {},
      close: vi.fn(),
    };

    class BackpressureDataChannel {
      label = WEBRTC_DATACHANNEL_LABEL;
      readyState: RTCDataChannelState = 'open';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      bufferedAmountLowThreshold = 0;
      sent: Uint8Array[] = [];
      onopen: (() => void) | null = null;
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      onbufferedamountlow: (() => void) | null = null;

      send(data: ArrayBuffer | Uint8Array) {
        const view = data instanceof Uint8Array ? data : new Uint8Array(data);
        this.sent.push(view);
      }
      close() {
        this.readyState = 'closed';
        this.onclose?.();
      }
    }

    const createdPcs: Array<{
      dc: BackpressureDataChannel;
      ondatachannel: ((ev: { channel: BackpressureDataChannel }) => void) | null;
    }> = [];
    class FakePeerConnection {
      connectionState: RTCPeerConnectionState = 'connected';
      onicecandidate: (() => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: BackpressureDataChannel }) => void) | null = null;
      dc = new BackpressureDataChannel();
      constructor() {
        createdPcs.push(this);
      }
      async setRemoteDescription() {}
      async createAnswer() {
        return { type: 'answer', sdp: 'v=0\r\nanswer\r\n' };
      }
      async setLocalDescription() {}
      async addIceCandidate() {}
      close() {
        this.connectionState = 'closed';
      }
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'host-bp',
      signalingClient: mockSignaling,
      reliableQueueHardLimit: 4096, // small hard cap to also test wedged-guest eviction cleanly
    });
    await hub.start();

    for (const gid of ['slow-guest', 'fast-guest']) {
      for (const cb of signalingListeners) {
        cb({
          v: 1,
          mid: `offer-${gid}`,
          roomHash,
          type: 'offer',
          fromPeerId: gid,
          sdp: `v=0\r\na=ice-ufrag:${gid}\r\n`,
          ts: Date.now(),
        });
      }
    }
    await new Promise((r) => setTimeout(r, 0));

    const slowDc = createdPcs[0].dc;
    const fastDc = createdPcs[1].dc;
    createdPcs[0].ondatachannel?.({ channel: slowDc });
    createdPcs[1].ondatachannel?.({ channel: fastDc });

    expect(slowDc.bufferedAmountLowThreshold).toBe(DC_BUFFERED_AMOUNT_LOW_THRESHOLD);

    // Join both guests
    for (const [dc, id] of [
      [slowDc, 'slow-guest'],
      [fastDc, 'fast-guest'],
    ] as const) {
      for (const f of encodeTransportFrames(
        'text',
        JSON.stringify({ type: 'JOIN_REQUEST', peer: { id, name: id, color: '#111' } }),
        1
      )) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    }
    slowDc.sent.length = 0;
    fastDc.sent.length = 0;

    // Simulate slow LTE guest whose SCTP bufferedAmount exceeds 1 MB high-water mark
    slowDc.bufferedAmount = DC_RELIABLE_HIGH_WATER_MARK + 200_000;

    // 1. Ephemeral cursor & camera packets drop immediately on slow-guest while reaching fast-guest
    hub.sendBinary(makeCursorBin('host-bp', 10, 20));
    hub.sendBinary(makeCameraBin('host-bp', 1.8));
    expect(slowDc.sent).toHaveLength(0);
    expect(fastDc.sent).toHaveLength(2);

    // 2. Reliable tiles & layer update queue in FIFO order on slow-guest (zero drops!) while reaching fast-guest immediately
    fastDc.sent.length = 0;
    hub.sendBinary(makeFullTileBin('layer-1', 0, 0, 11));
    hub.sendBinary(makeFullTileBin('layer-1', 1, 0, 22));
    hub.sendText(JSON.stringify({ type: 'LAYER_RENAME', layerId: 'layer-1', newName: 'Inked' }));
    hub.sendBinary(makeFullTileBin('layer-1', 2, 0, 33));

    // Nothing sent yet to slow-guest while congested; fast-guest already got all 4
    expect(slowDc.sent).toHaveLength(0);
    expect(fastDc.sent).toHaveLength(4);
    expect(hub.getBufferedAmount()).toBeGreaterThan(slowDc.bufferedAmount);

    // Ephemeral packet sent while reliable queue is non-empty also drops immediately even if bufferedAmount dips below soft limit
    slowDc.bufferedAmount = DC_EPHEMERAL_SOFT_LIMIT - 1024;
    // Wait — queue is still non-empty before flush, so ephemeral drops instead of jumping ahead of queued frames
    hub.sendBinary(makeCursorBin('host-bp', 50, 60));
    expect(slowDc.sent).toHaveLength(0);

    // 3. bufferedamountlow fires on slow-guest -> all 4 reliable frames flush in exact FIFO order (zero ephemeral mixed in)
    slowDc.bufferedAmount = 0;
    slowDc.onbufferedamountlow?.();

    const flushed = decodeAllFrames(slowDc.sent);
    expect(flushed).toHaveLength(4);
    expect(flushed[0].kind).toBe('binary');
    expect(flushed[1].kind).toBe('binary');
    expect(flushed[2].kind).toBe('text');
    expect(flushed[3].kind).toBe('binary');

    const seq0 = flushed[0].kind === 'binary' ? new DataView(flushed[0].data).getUint32(3, true) : 0;
    const seq1 = flushed[1].kind === 'binary' ? new DataView(flushed[1].data).getUint32(3, true) : 0;
    const seq2 = flushed[2].kind === 'text' ? JSON.parse(flushed[2].text).seq : 0;
    const seq3 = flushed[3].kind === 'binary' ? new DataView(flushed[3].data).getUint32(3, true) : 0;
    expect(seq0).toBeLessThan(seq1);
    expect(seq1).toBeLessThan(seq2);
    expect(seq2).toBeLessThan(seq3);
    if (flushed[2].kind === 'text') {
      expect(JSON.parse(flushed[2].text).newName).toBe('Inked');
    }

    // 4. Hard queue safety ceiling disconnects a truly wedged guest without harming healthy guests
    slowDc.bufferedAmount = DC_RELIABLE_HIGH_WATER_MARK + 1;
    hub.sendBinary(makeFullTileBin('layer-1', 0, 0, 99, 5000)); // > 4096 byte test ceiling
    expect(slowDc.readyState).toBe('closed');
    expect(hub.getConnectedGuestCount()).toBe(1);
    expect(fastDc.readyState).toBe('open');

    hub.close();
  });

  it('encodes broadcast frames once and shares identical chunk buffers across multiple guests', async () => {
    const roomHash = computeRoomTopicHash('INK-9103', 'FAN333');
    const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
    const mockSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: vi.fn(),
      onMessage: (cb) => {
        signalingListeners.add(cb);
        return () => signalingListeners.delete(cb);
      },
      onError: () => () => {},
      close: vi.fn(),
    };

    class CaptureDataChannel {
      label = WEBRTC_DATACHANNEL_LABEL;
      readyState: RTCDataChannelState = 'open';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      sent: Uint8Array[] = [];
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      send(data: Uint8Array) {
        this.sent.push(data);
      }
      close() {
        this.readyState = 'closed';
      }
    }

    const pcs: Array<{
      dc: CaptureDataChannel;
      ondatachannel: ((ev: { channel: CaptureDataChannel }) => void) | null;
    }> = [];
    class FakePeerConnection {
      connectionState: RTCPeerConnectionState = 'connected';
      onicecandidate: (() => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: CaptureDataChannel }) => void) | null = null;
      dc = new CaptureDataChannel();
      constructor() {
        pcs.push(this);
      }
      async setRemoteDescription() {}
      async createAnswer() {
        return { type: 'answer', sdp: 'v=0\r\nanswer\r\n' };
      }
      async setLocalDescription() {}
      async addIceCandidate() {}
      close() {}
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'host-fan',
      signalingClient: mockSignaling,
    });
    await hub.start();

    for (const gid of ['g1', 'g2', 'g3']) {
      for (const cb of signalingListeners) {
        cb({
          v: 1,
          mid: `offer-${gid}`,
          roomHash,
          type: 'offer',
          fromPeerId: gid,
          sdp: `v=0\r\na=ice-ufrag:${gid}\r\n`,
          ts: Date.now(),
        });
      }
    }
    await new Promise((r) => setTimeout(r, 0));

    pcs.forEach((p, idx) => {
      p.ondatachannel?.({ channel: p.dc });
      for (const f of encodeTransportFrames(
        'text',
        JSON.stringify({ type: 'JOIN_REQUEST', peer: { id: `g${idx + 1}`, name: `G${idx + 1}`, color: '#fff' } }),
        1
      )) {
        p.dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
      p.dc.sent.length = 0;
    });

    // Multi-chunk (~120 KB) binary tile broadcast across 3 guests -> encoded ONCE and shared by reference
    const largeTile = makeFullTileBin('layer-1', 0, 0, 5, 120_000);
    hub.sendBinary(largeTile);

    const [dc1, dc2, dc3] = pcs.map((p) => p.dc);
    expect(dc1.sent.length).toBeGreaterThan(2);
    expect(dc2.sent.length).toBe(dc1.sent.length);
    expect(dc3.sent.length).toBe(dc1.sent.length);
    for (let i = 0; i < dc1.sent.length; i++) {
      // Exact same Uint8Array instance (proves single encodeTransportFrames call across all 3 guests)
      expect(dc2.sent[i]).toBe(dc1.sent[i]);
      expect(dc3.sent[i]).toBe(dc1.sent[i]);
    }

    // Text broadcast across 3 guests -> also encoded ONCE and shared by reference
    dc1.sent.length = 0;
    dc2.sent.length = 0;
    dc3.sent.length = 0;
    hub.sendText(JSON.stringify({ type: 'LAYER_RENAME', layerId: 'layer-1', newName: 'Shared' }));
    expect(dc1.sent).toHaveLength(1);
    expect(dc2.sent[0]).toBe(dc1.sent[0]);
    expect(dc3.sent[0]).toBe(dc1.sent[0]);

    hub.close();
  });

  it('replays only missed compacted op_log entries on incremental reconnect (isReconnect + sinceSeq) and serves cached BRUSH_ASSET_DATA unicast', async () => {
    const roomHash = computeRoomTopicHash('INK-9104', 'OPLOG7');
    const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
    const mockSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: vi.fn(),
      onMessage: (cb) => {
        signalingListeners.add(cb);
        return () => signalingListeners.delete(cb);
      },
      onError: () => () => {},
      close: vi.fn(),
    };

    class CaptureDataChannel {
      label = WEBRTC_DATACHANNEL_LABEL;
      readyState: RTCDataChannelState = 'open';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      sent: Uint8Array[] = [];
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      send(data: Uint8Array) {
        this.sent.push(data);
      }
      close() {
        this.readyState = 'closed';
      }
    }

    const pcs: Array<{
      dc: CaptureDataChannel;
      ondatachannel: ((ev: { channel: CaptureDataChannel }) => void) | null;
    }> = [];
    class FakePeerConnection {
      connectionState: RTCPeerConnectionState = 'connected';
      onicecandidate: (() => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: CaptureDataChannel }) => void) | null = null;
      dc = new CaptureDataChannel();
      constructor() {
        pcs.push(this);
      }
      async setRemoteDescription() {}
      async createAnswer() {
        return { type: 'answer', sdp: 'v=0\r\nanswer\r\n' };
      }
      async setLocalDescription() {}
      async addIceCandidate() {}
      close() {
        this.connectionState = 'closed';
      }
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'host-op',
      signalingClient: mockSignaling,
      opLogMaxEntries: 16,
    });
    const hostTexts: string[] = [];
    const hostBinaries: ArrayBuffer[] = [];
    hub.onTextMessage((t) => hostTexts.push(t));
    hub.onBinaryMessage((b) => hostBinaries.push(b));
    await hub.start();

    const connectGuest = async (gid: string, ufrag: string) => {
      const idx = pcs.length;
      for (const cb of signalingListeners) {
        cb({
          v: 1,
          mid: `offer-${gid}-${ufrag}`,
          roomHash,
          type: 'offer',
          fromPeerId: gid,
          sdp: `v=0\r\na=ice-ufrag:${ufrag}\r\n`,
          ts: Date.now(),
        });
      }
      await new Promise((r) => setTimeout(r, 0));
      const dc = pcs[idx].dc;
      pcs[idx].ondatachannel?.({ channel: dc });
      return dc;
    };

    const sendJsonFromGuest = (dc: CaptureDataChannel, id: number, obj: object) => {
      for (const f of encodeTransportFrames('text', JSON.stringify(obj), id)) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    };
    const sendBinFromGuest = (dc: CaptureDataChannel, id: number, bin: Uint8Array) => {
      for (const f of encodeTransportFrames('binary', bin, id)) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    };

    const dcA = await connectGuest('guest-a', 'u1');
    const dcB1 = await connectGuest('guest-b', 'u2');
    sendJsonFromGuest(dcA, 1, { type: 'JOIN_REQUEST', peer: { id: 'guest-a', name: 'A', color: '#111' } });
    sendJsonFromGuest(dcB1, 2, { type: 'JOIN_REQUEST', peer: { id: 'guest-b', name: 'B', color: '#222' } });

    // Baseline op received by Guest B before Wi-Fi drop
    hub.sendText(JSON.stringify({ type: 'LAYER_RENAME', layerId: 'layer-1', newName: 'BeforeDrop' }));
    const dropSeq = hub.getCurrentSeq();
    expect(dropSeq).toBeGreaterThan(0);

    // Guest A caches a brush asset while Guest B is connected/away
    const brushHash = '0123456789abcdef0123456789abcdef';
    const assetBytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3, 4]);
    sendBinFromGuest(dcA, 3, makeBrushAssetDataBin(brushHash, 'image/png', assetBytes));
    expect(hub.getBrushAssetCacheSize()).toBe(1);

    // Simulate Guest B dropping Wi-Fi for 2 seconds; while away, Host & Guest A perform edits:
    //  - 1 LAYER_RENAME
    //  - 3 overwrites to the SAME tile (layer-1, 2, 3) -> op_log compacts first two away!
    //  - 1 write to tile (layer-1, 4, 5)
    dcB1.close();
    hub.sendText(JSON.stringify({ type: 'LAYER_RENAME', layerId: 'layer-1', newName: 'AfterDrop' }));
    sendBinFromGuest(dcA, 4, makeFullTileBin('layer-1', 2, 3, 10));
    sendBinFromGuest(dcA, 5, makeFullTileBin('layer-1', 2, 3, 20));
    sendBinFromGuest(dcA, 6, makeFullTileBin('layer-1', 2, 3, 30)); // supersedes 10 & 20
    const latestTile23Seq = hub.getCurrentSeq();
    hub.sendBinary(makeFullTileBin('layer-1', 4, 5, 40));
    const tile45Seq = hub.getCurrentSeq();

    // Guest B reconnects with fresh SDP ufrag + JOIN_REQUEST { isReconnect: true, sinceSeq: dropSeq }
    const dcB2 = await connectGuest('guest-b', 'u3-reconnect');
    expect(hub.canIncrementalCatchUp(dropSeq)).toBe(true);
    sendJsonFromGuest(dcB2, 7, {
      type: 'JOIN_REQUEST',
      peer: { id: 'guest-b', name: 'B', color: '#222' },
      isReconnect: true,
      sinceSeq: dropSeq,
    });

    // Host sends JOIN_ACCEPTED ONLY (no DOC_SYNC_RESPONSE!) -> Hub replays missed compacted ops automatically
    dcB2.sent.length = 0;
    hub.sendText(
      JSON.stringify({
        type: 'JOIN_ACCEPTED',
        targetPeerId: 'guest-b',
        roomName: 'Studio',
        peers: [],
        hostId: 'host-op',
        docDimensions: { width: 1024, height: 1024 },
        colorMode: 'color',
        assignedRole: 'editor',
        isReconnect: true,
      })
    );

    const replayed = decodeAllFrames(dcB2.sent);
    // Expected exact sequence: JOIN_ACCEPTED, LAYER_RENAME('AfterDrop'), tile (2,3) tag=30 ONLY, tile (4,5) tag=40
    // (BRUSH_ASSET_DATA is NOT in op_log; PEER_DISCONNECTED for guest-b or stale tiles 10 & 20 are excluded)
    const texts = replayed
      .filter((m): m is { kind: 'text'; text: string } => m.kind === 'text')
      .map((m) => JSON.parse(m.text));
    const binaries = replayed
      .filter((m): m is { kind: 'binary'; data: ArrayBuffer } => m.kind === 'binary')
      .map((m) => m.data);

    expect(texts[0].type).toBe('JOIN_ACCEPTED');
    expect(texts.some((t) => t.type === 'DOC_SYNC_RESPONSE')).toBe(false);
    expect(texts.some((t) => t.type === 'LAYER_RENAME' && t.newName === 'AfterDrop')).toBe(true);

    // Only 2 compacted tiles replayed (stale versions 10 & 20 were compacted out!)
    expect(binaries).toHaveLength(2);
    expect(new DataView(binaries[0]).getUint32(3, true)).toBe(latestTile23Seq);
    expect(new DataView(binaries[1]).getUint32(3, true)).toBe(tile45Seq);

    // Verify BRUSH_ASSET_REQUEST from Guest B is answered unicast directly from Host Hub cache
    // without forwarding the request to Host or Guest A
    dcA.sent.length = 0;
    dcB2.sent.length = 0;
    hostBinaries.length = 0;
    sendBinFromGuest(dcB2, 8, makeBrushAssetReqBin(brushHash, 'guest-b'));
    expect(hostBinaries).toHaveLength(0);
    expect(dcA.sent).toHaveLength(0);
    const cacheResp = decodeAllFrames(dcB2.sent);
    expect(cacheResp).toHaveLength(1);
    expect(cacheResp[0].kind).toBe('binary');
    if (cacheResp[0].kind === 'binary') {
      expect(new Uint8Array(cacheResp[0].data)[2]).toBe(CODE_BRUSH_ASSET_DATA);
    }

    // Verify op_log eviction advances opLogFloor so stale sinceSeq falls back to full sync
    for (let i = 0; i < 20; i++) {
      hub.sendText(JSON.stringify({ type: 'LAYER_RENAME', layerId: 'layer-1', newName: `N${i}` }));
    }
    expect(hub.getOpLogFloor()).toBeGreaterThan(dropSeq);
    expect(hub.canIncrementalCatchUp(dropSeq)).toBe(false);

    hub.close();
  });

  it('isolates joining guests from live peer edits during initial snapshot streaming and drains op_log > snapshotSeq atomically', async () => {
    const roomHash = computeRoomTopicHash('INK-9105', 'SNAP88');
    const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
    const mockSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: vi.fn(),
      onMessage: (cb) => {
        signalingListeners.add(cb);
        return () => signalingListeners.delete(cb);
      },
      onError: () => () => {},
      close: vi.fn(),
    };

    class CaptureDataChannel {
      label = WEBRTC_DATACHANNEL_LABEL;
      readyState: RTCDataChannelState = 'open';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      sent: Uint8Array[] = [];
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      send(data: Uint8Array) {
        this.sent.push(data);
      }
      close() {
        this.readyState = 'closed';
      }
    }

    const pcs: Array<{
      dc: CaptureDataChannel;
      ondatachannel: ((ev: { channel: CaptureDataChannel }) => void) | null;
    }> = [];
    class FakePeerConnection {
      connectionState: RTCPeerConnectionState = 'connected';
      onicecandidate: (() => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      ondatachannel: ((ev: { channel: CaptureDataChannel }) => void) | null = null;
      dc = new CaptureDataChannel();
      constructor() {
        pcs.push(this);
      }
      async setRemoteDescription() {}
      async createAnswer() {
        return { type: 'answer', sdp: 'v=0\r\nanswer\r\n' };
      }
      async setLocalDescription() {}
      async addIceCandidate() {}
      close() {}
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = FakePeerConnection;

    const hub = new WebRtcHostHub({
      roomHash,
      hostPeerId: 'host-snap',
      signalingClient: mockSignaling,
    });
    await hub.start();

    for (const gid of ['guest-live', 'guest-joining']) {
      for (const cb of signalingListeners) {
        cb({
          v: 1,
          mid: `offer-${gid}`,
          roomHash,
          type: 'offer',
          fromPeerId: gid,
          sdp: `v=0\r\na=ice-ufrag:${gid}\r\n`,
          ts: Date.now(),
        });
      }
    }
    await new Promise((r) => setTimeout(r, 0));

    const dcLive = pcs[0].dc;
    const dcJoining = pcs[1].dc;
    pcs[0].ondatachannel?.({ channel: dcLive });
    pcs[1].ondatachannel?.({ channel: dcJoining });

    const sendJson = (dc: CaptureDataChannel, id: number, obj: object) => {
      for (const f of encodeTransportFrames('text', JSON.stringify(obj), id)) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    };
    const sendBin = (dc: CaptureDataChannel, id: number, bin: Uint8Array) => {
      for (const f of encodeTransportFrames('binary', bin, id)) {
        dc.onmessage?.({
          data: f.buffer.slice(f.byteOffset, f.byteOffset + f.byteLength) as ArrayBuffer,
        });
      }
    };

    sendJson(dcLive, 1, { type: 'JOIN_REQUEST', peer: { id: 'guest-live', name: 'Live', color: '#111' } });
    sendJson(dcJoining, 2, { type: 'JOIN_REQUEST', peer: { id: 'guest-joining', name: 'New', color: '#222' } });
    dcJoining.sent.length = 0;

    // 1. Host begins snapshot isolation for guest-joining
    const snapSeq = hub.beginPeerSnapshot('guest-joining');
    hub.sendText(
      JSON.stringify({
        type: 'JOIN_ACCEPTED',
        targetPeerId: 'guest-joining',
        roomName: 'Studio',
        peers: [],
        hostId: 'host-snap',
        docDimensions: { width: 1024, height: 1024 },
        colorMode: 'color',
      })
    );
    hub.sendText(
      JSON.stringify({
        type: 'DOC_SYNC_RESPONSE',
        targetPeerId: 'guest-joining',
        dimensions: { width: 1024, height: 1024 },
        colorMode: 'color',
        layers: [],
      })
    );
    // Stream first snapshot tile
    hub.sendBinaryTo('guest-joining', makeFullTileBin('layer-1', 0, 0, 1));
    expect(dcJoining.sent).toHaveLength(3);

    // 2. While snapshot is still streaming, guest-live broadcasts live edits (must NOT interleave!)
    sendJson(dcLive, 3, {
      type: 'LAYER_RENAME',
      senderId: 'guest-live',
      layerId: 'layer-1',
      newName: 'LiveEditDuringSnapshot',
    });
    sendBin(dcLive, 4, makeFullTileBin('layer-1', 0, 0, 2));

    // guest-joining MUST still only have the 3 snapshot frames (zero live edits interleaved)
    expect(dcJoining.sent).toHaveLength(3);

    // 3. Host finishes streaming second snapshot tile and flips guest-joining to live atomically
    hub.sendBinaryTo('guest-joining', makeFullTileBin('layer-1', 1, 0, 1));
    expect(dcJoining.sent).toHaveLength(4);

    hub.finishPeerSnapshot('guest-joining');

    // Verify exact order on guest-joining:
    //   [0] JOIN_ACCEPTED (seq == snapSeq)
    //   [1] DOC_SYNC_RESPONSE (seq == snapSeq)
    //   [2] snapshot tile (0,0) (seq == snapSeq)
    //   [3] snapshot tile (1,0) (seq == snapSeq)
    //   [4] drained op_log: LAYER_RENAME ('LiveEditDuringSnapshot', seq > snapSeq)
    //   [5] drained op_log: live tile (0,0) (seq > snapSeq — cleanly outranks snapshot tile!)
    const allMsgs = decodeAllFrames(dcJoining.sent);
    expect(allMsgs).toHaveLength(6);

    expect(allMsgs[0].kind).toBe('text');
    expect(allMsgs[1].kind).toBe('text');
    expect(allMsgs[2].kind).toBe('binary');
    expect(allMsgs[3].kind).toBe('binary');
    expect(allMsgs[4].kind).toBe('text');
    expect(allMsgs[5].kind).toBe('binary');

    if (allMsgs[0].kind === 'text' && allMsgs[1].kind === 'text' && allMsgs[4].kind === 'text') {
      const m0 = JSON.parse(allMsgs[0].text);
      const m1 = JSON.parse(allMsgs[1].text);
      const m4 = JSON.parse(allMsgs[4].text);
      expect(m0.type).toBe('JOIN_ACCEPTED');
      expect(m0.seq).toBe(snapSeq);
      expect(m1.type).toBe('DOC_SYNC_RESPONSE');
      expect(m1.seq).toBe(snapSeq);
      expect(m4.type).toBe('LAYER_RENAME');
      expect(m4.newName).toBe('LiveEditDuringSnapshot');
      expect(m4.seq).toBeGreaterThan(snapSeq);
    }

    if (allMsgs[2].kind === 'binary' && allMsgs[3].kind === 'binary' && allMsgs[5].kind === 'binary') {
      const snapTile1Seq = new DataView(allMsgs[2].data).getUint32(3, true);
      const snapTile2Seq = new DataView(allMsgs[3].data).getUint32(3, true);
      const liveTileSeq = new DataView(allMsgs[5].data).getUint32(3, true);
      expect(snapTile1Seq).toBe(snapSeq);
      expect(snapTile2Seq).toBe(snapSeq);
      expect(liveTileSeq).toBeGreaterThan(snapSeq);
    }

    // 4. Subsequent live edits now flow directly to guest-joining immediately
    dcJoining.sent.length = 0;
    sendJson(dcLive, 5, {
      type: 'LAYER_RENAME',
      senderId: 'guest-live',
      layerId: 'layer-1',
      newName: 'AfterLiveFlip',
    });
    const postLive = decodeAllFrames(dcJoining.sent);
    expect(postLive).toHaveLength(1);
    if (postLive[0].kind === 'text') {
      expect(JSON.parse(postLive[0].text).newName).toBe('AfterLiveFlip');
    }

    hub.close();
  });

  it('handles WebRtcGuestClient single-channel fallback and outbound backpressure queuing with timer-fallback drain', async () => {
    vi.useFakeTimers();
    const roomHash = computeRoomTopicHash('INK-9106', 'GUE555');
    const signalingListeners = new Set<(env: SignalingEnvelope) => void>();
    const mockSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: (env) => {
        if (env.type === 'offer') {
          queueMicrotask(() => {
            for (const cb of signalingListeners) {
              cb({
                v: 1,
                mid: 'ans-1',
                roomHash,
                type: 'answer',
                fromPeerId: 'legacy-host',
                toPeerId: env.fromPeerId,
                sdp: 'v=0\r\nanswer\r\n',
                sdpType: 'answer',
                ts: Date.now(),
              });
            }
          });
        }
      },
      onMessage: (cb) => {
        signalingListeners.add(cb);
        return () => signalingListeners.delete(cb);
      },
      onError: () => () => {},
      close: vi.fn(),
    };

    class SingleChannelGuestDC {
      label: string;
      readyState: RTCDataChannelState = 'connecting';
      binaryType: BinaryType = 'arraybuffer';
      bufferedAmount = 0;
      bufferedAmountLowThreshold = 0;
      sent: Uint8Array[] = [];
      onopen: (() => void) | null = null;
      onmessage: ((ev: { data: ArrayBuffer }) => void) | null = null;
      onclose: (() => void) | null = null;
      onerror: ((ev: Event) => void) | null = null;
      onbufferedamountlow: (() => void) | null = null;
      constructor(label: string) {
        this.label = label;
      }
      send(data: Uint8Array) {
        this.sent.push(data);
      }
      close() {
        this.readyState = 'closed';
      }
    }

    let reliableDcRef: SingleChannelGuestDC | null = null;
    class LegacySingleChannelPC {
      connectionState: RTCPeerConnectionState = 'new';
      localDescription: RTCSessionDescriptionInit | null = null;
      onicecandidate: (() => void) | null = null;
      onconnectionstatechange: (() => void) | null = null;
      createDataChannel(label: string) {
        // Simulate a legacy remote peer / restricted WebView where ephemeral channel fails to open
        if (label === WEBRTC_EPHEMERAL_DATACHANNEL_LABEL) {
          throw new Error('Unordered channel unsupported');
        }
        const dc = new SingleChannelGuestDC(label);
        reliableDcRef = dc;
        return dc;
      }
      async createOffer() {
        return { type: 'offer' as const, sdp: 'v=0\r\noffer\r\n' };
      }
      async setLocalDescription(d: RTCSessionDescriptionInit) {
        this.localDescription = d;
      }
      async setRemoteDescription() {
        this.connectionState = 'connected';
        if (reliableDcRef) {
          reliableDcRef.readyState = 'open';
          reliableDcRef.onopen?.();
        }
      }
      async addIceCandidate() {}
      close() {}
    }

    (globalThis as Record<string, unknown>).RTCPeerConnection = LegacySingleChannelPC;

    const guest = new WebRtcGuestClient({
      roomHash,
      peerId: 'guest-bp',
      signalingClient: mockSignaling,
    });
    await guest.connect();

    expect(guest.isOpen()).toBe(true);
    expect(guest.hasOpenEphemeralChannel()).toBe(false);
    expect(reliableDcRef!.bufferedAmountLowThreshold).toBe(DC_BUFFERED_AMOUNT_LOW_THRESHOLD);

    // 1. Single-channel fallback: CURSOR_MOVE routes over reliable channel when uncongested
    guest.sendBinary(makeCursorBin('guest-bp', 1, 2));
    expect(reliableDcRef!.sent).toHaveLength(1);
    reliableDcRef!.sent.length = 0;

    // 2. Backpressure: bufferedAmount > high-water mark drops ephemeral, queues reliable tiles
    reliableDcRef!.bufferedAmount = DC_RELIABLE_HIGH_WATER_MARK + 10_000;
    guest.sendBinary(makeCursorBin('guest-bp', 3, 4));
    guest.sendBinary(makeCameraBin('guest-bp', 2.0));
    guest.sendBinary(makeFullTileBin('layer-1', 0, 0, 1));
    guest.sendBinary(makeFullTileBin('layer-1', 1, 0, 2));
    expect(reliableDcRef!.sent).toHaveLength(0);
    expect(guest.getBufferedAmount()).toBeGreaterThan(reliableDcRef!.bufferedAmount);

    // 3. Lower bufferedAmount WITHOUT firing onbufferedamountlow -> timer fallback drains in exact FIFO order!
    reliableDcRef!.bufferedAmount = 0;
    await vi.advanceTimersByTimeAsync(50);

    const drained = decodeAllFrames(reliableDcRef!.sent);
    expect(drained).toHaveLength(2);
    expect(drained[0].kind).toBe('binary');
    expect(drained[1].kind).toBe('binary');
    if (drained[0].kind === 'binary' && drained[1].kind === 'binary') {
      expect(new Uint8Array(drained[0].data)[2]).toBe(CODE_TILE_DELTA);
      expect(new Uint8Array(drained[1].data)[2]).toBe(CODE_TILE_DELTA);
    }

    guest.close();
  });
});