Skip to content

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

79.3 KB
Raw Blame
import { CollabIceCandidateType, CollabRole } from '../types/multiplayer';
import { composeSubRectOntoTilePacket } from '../utils/collabTileCodec';
import {
  ChunkReassembler,
  CollabSendOptions,
  DataChannelSendQueue,
  ICollabTransport,
  encodeTransportFrames,
  isEphemeralWireBinary,
  queryPeerConnectionIceCandidateType,
  toUint8Array,
} from './collabTransport';
import {
  createSignalingClient,
  ISignalingClient,
  SignalingEnvelope,
} from './webrtcSignaling';

export const WEBRTC_DATACHANNEL_LABEL = 'inkstudio-collab';
export const WEBRTC_EPHEMERAL_DATACHANNEL_LABEL = 'inkstudio-collab-ephemeral';
export const MAX_WEBRTC_PEERS = 8;

/** Bounded Host-Hub op_log limits (mirrors stateful Rust server for incremental reconnects). */
export const WEBRTC_OP_LOG_MAX_ENTRIES = 2048;
export const WEBRTC_OP_LOG_MAX_BYTES = 32 * 1024 * 1024; // 32 MB
const OP_LOG_COMPACT_STALE_THRESHOLD = 32;

/** Bounded LRU cache for content-addressed BRUSH_ASSET_DATA packets on the Host Hub. */
export const WEBRTC_BRUSH_ASSET_CACHE_MAX_ENTRIES = 64;
export const WEBRTC_BRUSH_ASSET_CACHE_MAX_BYTES = 16 * 1024 * 1024; // 16 MB

/** Bounded LRU cache for content-addressed BRUSH_PROFILE_DATA packets on the Host Hub. */
export const WEBRTC_BRUSH_PROFILE_CACHE_MAX_ENTRIES = 128;
export const WEBRTC_BRUSH_PROFILE_CACHE_MAX_BYTES = 4 * 1024 * 1024; // 4 MB

/** Bounded self-contained base tile store for safe sub-rect composition on the Host Hub. */
const WEBRTC_TILE_BASE_CACHE_MAX_BYTES = 32 * 1024 * 1024; // 32 MB

export const DEFAULT_WEBRTC_ICE_SERVERS: RTCIceServer[] = [
  { urls: 'stun:stun.l.google.com:19302' },
  { urls: 'stun:stun1.l.google.com:19302' },
  { urls: 'stun:stun.cloudflare.com:3478' },
];

export interface WebRtcTurnConfig {
  turnUrl?: string;
  turnUsername?: string;
  turnCredential?: string;
}

export function buildIceServers(turn?: WebRtcTurnConfig): RTCIceServer[] {
  const servers: RTCIceServer[] = DEFAULT_WEBRTC_ICE_SERVERS.map((s) => ({ ...s }));
  const url = (turn?.turnUrl || '').trim();
  if (url && /^(turns?:)/i.test(url)) {
    const entry: RTCIceServer = { urls: url };
    if (turn?.turnUsername?.trim()) entry.username = turn.turnUsername.trim();
    if (turn?.turnCredential?.trim()) entry.credential = turn.turnCredential.trim();
    servers.push(entry);
  }
  return servers;
}

const BINARY_MAGIC_0 = 0x49; // 'I'
const BINARY_MAGIC_1 = 0x4e; // 'N'
const CODE_STROKE_START = 0x01;
const CODE_STROKE_CHUNK = 0x02;
const CODE_STROKE_FINISH = 0x03;
const CODE_TILE_DELTA = 0x04;
const CODE_CURSOR_MOVE = 0x05;
const CODE_SELECTIVE_UNDO = 0x06;
const CODE_BRUSH_ASSET_DATA = 0x07;
const CODE_BRUSH_ASSET_REQUEST = 0x08;
const CODE_LAYER_MASK_DATA = 0x09;
const CODE_CAMERA_SYNC = 0x0a;
const CODE_BRUSH_PROFILE_DATA = 0x0b;
const CODE_BRUSH_PROFILE_REQUEST = 0x0c;
const CODE_STROKE_CHUNK_V2 = 0x0d;
const CODE_PING = 0x0e;
const CODE_PONG = 0x0f;

const KNOWN_BINARY_OPCODES = new Set<number>([
  CODE_STROKE_START,
  CODE_STROKE_CHUNK,
  CODE_STROKE_FINISH,
  CODE_TILE_DELTA,
  CODE_CURSOR_MOVE,
  CODE_SELECTIVE_UNDO,
  CODE_BRUSH_ASSET_DATA,
  CODE_BRUSH_ASSET_REQUEST,
  CODE_LAYER_MASK_DATA,
  CODE_CAMERA_SYNC,
  CODE_BRUSH_PROFILE_DATA,
  CODE_BRUSH_PROFILE_REQUEST,
  CODE_STROKE_CHUNK_V2,
  CODE_PING,
  CODE_PONG,
]);

const STROKE_START_BINARY_VERSION = 0x02;
const PING_PAYLOAD_BYTES = 12;
const TILE_CODEC_EMPTY = 0;
const TILE_CODEC_RAW = 1;
const TILE_CODEC_LZ4 = 2;
const TILE_CODEC_SOLID = 3;
const TILE_CODEC_SUBRECT_LZ4 = 4;
const HEX32_RE = /^[0-9a-f]{32}$/;

const DISCONNECTED_GRACE_MS = 5_000;
const sharedTextEncoder = new TextEncoder();
const sharedTextDecoder = new TextDecoder();

interface LayerLockMeta {
  ownerPeerId?: string;
  reservedByPeerId?: string;
}

interface OpLogEntry {
  seq: number;
  senderPeerId?: string;
  tileKey?: string;
  kind: 'text' | 'binary';
  payload: string | Uint8Array;
  byteLength: number;
}

type SignalingIceCandidate = NonNullable<SignalingEnvelope['candidate']>;

const VIEWER_ALLOWED_JSON_TYPES = new Set<string>([
  'JOIN_REQUEST',
  'DOC_SYNC_REQUEST',
  'TILE_RESYNC_REQUEST',
  'CURSOR_MOVE',
  'CAMERA_SYNC_REQUEST',
  'CHAT_MESSAGE',
  'CANVAS_PING',
  'BRUSH_ASSET_REQUEST',
  'BRUSH_REQUEST',
  'BRUSH_SHARE',
  'PEER_LEFT',
]);

const HOST_ONLY_MODERATION_TYPES = new Set<string>([
  'PEER_ROLE_UPDATE',
  'PEER_KICK',
  'PEER_BAN',
  'PEER_UNBAN',
]);

const HOST_ONLY_CONSUME_TYPES = new Set<string>([
  'JOIN_REQUEST',
  'DOC_SYNC_REQUEST',
  'TILE_RESYNC_REQUEST',
]);

const UNICAST_FROM_HOST_TYPES = new Set<string>([
  'JOIN_ACCEPTED',
  'DOC_SYNC_RESPONSE',
  'ACCESS_DENIED',
  'BRUSH_ASSET_REQUEST',
  'CAMERA_SYNC_REQUEST',
  'BRUSH_REQUEST',
  'BRUSH_SHARE',
]);

const OP_LOG_TEXT_TYPES = new Set<string>([
  'LAYER_ADD',
  'LAYER_DELETE',
  'LAYER_CLEAR',
  'LAYER_RENAME',
  'LAYER_VISIBILITY',
  'LAYER_OPACITY',
  'LAYER_UPDATE',
  'LAYER_TREE_SYNC',
  'PERSPECTIVE_RULER_SYNC',
  'STRAIGHT_RULER_SYNC',
  'ANIMATION_SYNC',
  'CANVAS_RESIZE',
  'CHAT_MESSAGE',
  'PEER_JOINED',
  'PEER_LEFT',
  'PEER_DISCONNECTED',
  'PEER_ROLE_UPDATE',
  'PEER_KICK',
  'PEER_BAN',
]);

const EPHEMERAL_TEXT_TYPES = new Set<string>(['CURSOR_MOVE', 'CANVAS_PING']);

/**
 * Injects `"seq":<n>` directly into an already-validated JSON object string that does not
 * contain a `"seq"` key, avoiding `{ ...parsed }` spread allocations and full `JSON.stringify`.
 */
function injectSeqIntoJsonObject(rawText: string, seq: number): string | null {
  const trimmed = rawText.trimEnd();
  if (!trimmed.endsWith('}')) return null;
  let i = trimmed.length - 2;
  while (i >= 0 && trimmed.charCodeAt(i) <= 32) {
    i--;
  }
  if (i < 0) return null;
  const prefix = trimmed.slice(0, -1);
  return trimmed.charCodeAt(i) === 123 /* '{' */
    ? `${prefix}"seq":${seq}}`
    : `${prefix},"seq":${seq}}`;
}

/**
 * Extracts a stable session fingerprint from an SDP offer (`a=ice-ufrag:` / `o=`) so
 * trickle-ICE offer retries are distinguished from a fresh RTCPeerConnection reconnect offer.
 */
function extractSdpSessionFingerprint(sdp: string): string {
  const ufragMatch = sdp.match(/a=ice-ufrag:([^\r\n]+)/);
  if (ufragMatch) return `ufrag:${ufragMatch[1].trim()}`;
  const originMatch = sdp.match(/^o=([^\r\n]+)/m);
  if (originMatch) return `o:${originMatch[1].trim()}`;
  return sdp;
}

interface BinaryTileMeta {
  key: string;
  layerId: string;
  layerIdBytes: Uint8Array;
  tilePacketOffset: number;
  payloadEnd: number;
  codec: number;
}

function extractBinaryTileMeta(bytes: Uint8Array): BinaryTileMeta | null {
  if (bytes.byteLength < 11 || bytes[2] !== CODE_TILE_DELTA) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  const payloadEnd = 11 + payloadLen;
  if (payloadEnd > bytes.byteLength || payloadLen < 10) return null;
  const layerIdLen = view.getUint16(11, true);
  const tilePacketOffset = 13 + layerIdLen;
  if (layerIdLen === 0 || layerIdLen > 256 || tilePacketOffset + 8 > payloadEnd) {
    return null;
  }
  const layerIdBytes = bytes.subarray(13, tilePacketOffset);
  const layerId = sharedTextDecoder.decode(layerIdBytes);
  const tileX = view.getInt32(tilePacketOffset, true);
  const tileY = view.getInt32(tilePacketOffset + 4, true);
  const codec = tilePacketOffset + 14 <= payloadEnd ? bytes[tilePacketOffset + 13] : -1;
  return {
    key: `${layerId}:${tileX}:${tileY}`,
    layerId,
    layerIdBytes,
    tilePacketOffset,
    payloadEnd,
    codec,
  };
}

function buildWireTileDeltaPacket(
  layerIdBytes: Uint8Array,
  tilePacket: Uint8Array,
  seq: number
): Uint8Array {
  const payloadLen = 2 + layerIdBytes.byteLength + tilePacket.byteLength;
  const out = new Uint8Array(11 + payloadLen);
  const view = new DataView(out.buffer);
  out[0] = BINARY_MAGIC_0;
  out[1] = BINARY_MAGIC_1;
  out[2] = CODE_TILE_DELTA;
  view.setUint32(3, seq >>> 0, true);
  view.setUint32(7, payloadLen, true);
  view.setUint16(11, layerIdBytes.byteLength, true);
  out.set(layerIdBytes, 13);
  out.set(tilePacket, 13 + layerIdBytes.byteLength);
  return out;
}

function extractBrushAssetDataHash(bytes: Uint8Array): string | null {
  if (bytes.byteLength < 15 || bytes[2] !== CODE_BRUSH_ASSET_DATA) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  if (11 + payloadLen > bytes.byteLength || payloadLen < 4) return null;
  const hashLen = bytes[11];
  if (hashLen === 0 || hashLen > 64 || 12 + hashLen + 1 > 11 + payloadLen) return null;
  return sharedTextDecoder.decode(bytes.subarray(12, 12 + hashLen));
}

function extractBrushAssetRequestHash(bytes: Uint8Array): string | null {
  if (bytes.byteLength < 13 || bytes[2] !== CODE_BRUSH_ASSET_REQUEST) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  if (11 + payloadLen > bytes.byteLength || payloadLen === 0) return null;
  try {
    const jsonStr = sharedTextDecoder.decode(bytes.subarray(11, 11 + payloadLen));
    const parsed = JSON.parse(jsonStr) as { hash?: unknown };
    return typeof parsed?.hash === 'string' && parsed.hash.length > 0 && parsed.hash.length <= 64
      ? parsed.hash
      : null;
  } catch {
    return null;
  }
}

function extractBrushProfileDataHash(bytes: Uint8Array): string | null {
  if (bytes.byteLength < 46 || bytes[2] !== CODE_BRUSH_PROFILE_DATA) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  if (11 + payloadLen > bytes.byteLength || payloadLen < 35) return null;
  if (bytes[11] !== 32) return null;
  const hash = sharedTextDecoder.decode(bytes.subarray(12, 44));
  return HEX32_RE.test(hash) ? hash : null;
}

function extractBrushProfileRequestHash(bytes: Uint8Array): string | null {
  if (bytes.byteLength < 13 || bytes[2] !== CODE_BRUSH_PROFILE_REQUEST) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  if (11 + payloadLen > bytes.byteLength || payloadLen === 0) return null;
  try {
    const jsonStr = sharedTextDecoder.decode(bytes.subarray(11, 11 + payloadLen));
    const parsed = JSON.parse(jsonStr) as { hash?: unknown };
    return typeof parsed?.hash === 'string' && HEX32_RE.test(parsed.hash) ? parsed.hash : null;
  } catch {
    return null;
  }
}

function extractBrushProfilePacketFromStrokeStart(
  bytes: Uint8Array,
  seq: number
): { hash: string; packet: Uint8Array } | null {
  if (bytes.byteLength < 13 || bytes[2] !== CODE_STROKE_START) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  if (payloadLen === 0 || 11 + payloadLen > bytes.byteLength) return null;
  // Skip slim binary v2 STROKE_START packets (payload[0] === 0x02 != '{')
  if (bytes[11] !== 0x7b) return null;
  try {
    const jsonStr = sharedTextDecoder.decode(bytes.subarray(11, 11 + payloadLen));
    const parsed = JSON.parse(jsonStr) as {
      brushProfileHash?: unknown;
      brushSettings?: unknown;
      brushAssetRefs?: unknown;
    };
    if (
      typeof parsed?.brushProfileHash !== 'string' ||
      !HEX32_RE.test(parsed.brushProfileHash) ||
      !parsed.brushSettings ||
      typeof parsed.brushSettings !== 'object'
    ) {
      return null;
    }
    const profileObj: Record<string, unknown> = { settings: parsed.brushSettings };
    if (parsed.brushAssetRefs && typeof parsed.brushAssetRefs === 'object') {
      profileObj.assetRefs = parsed.brushAssetRefs;
    }
    const jsonBytes = sharedTextEncoder.encode(JSON.stringify(profileObj));
    if (jsonBytes.byteLength === 0 || jsonBytes.byteLength > 256 * 1024) return null;
    const hashBytes = sharedTextEncoder.encode(parsed.brushProfileHash);
    if (hashBytes.byteLength !== 32) return null;

    const profilePayloadLen = 1 + 32 + 1 + jsonBytes.byteLength;
    const packet = new Uint8Array(11 + profilePayloadLen);
    const pktView = new DataView(packet.buffer);
    packet[0] = BINARY_MAGIC_0;
    packet[1] = BINARY_MAGIC_1;
    packet[2] = CODE_BRUSH_PROFILE_DATA;
    pktView.setUint32(3, seq >>> 0, true);
    pktView.setUint32(7, profilePayloadLen, true);
    packet[11] = 32;
    packet.set(hashBytes, 12);
    packet[44] = 0; // uncompressed JSON
    packet.set(jsonBytes, 45);
    return { hash: parsed.brushProfileHash, packet };
  } catch {
    return null;
  }
}

function buildPongPacketFromPing(bytes: Uint8Array): Uint8Array | null {
  if (bytes.byteLength < 11 + PING_PAYLOAD_BYTES || bytes[2] !== CODE_PING) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const payloadLen = view.getUint32(7, true);
  if (payloadLen !== PING_PAYLOAD_BYTES || 11 + payloadLen > bytes.byteLength) return null;
  const out = new Uint8Array(11 + PING_PAYLOAD_BYTES);
  const outView = new DataView(out.buffer);
  out[0] = BINARY_MAGIC_0;
  out[1] = BINARY_MAGIC_1;
  out[2] = CODE_PONG;
  outView.setUint32(3, 0, true);
  outView.setUint32(7, PING_PAYLOAD_BYTES, true);
  out.set(bytes.subarray(11, 11 + PING_PAYLOAD_BYTES), 11);
  return out;
}

function isOpLogEligibleBinaryOpcode(opcode: number): boolean {
  return (
    opcode === CODE_TILE_DELTA ||
    opcode === CODE_LAYER_MASK_DATA ||
    opcode === CODE_STROKE_START ||
    opcode === CODE_STROKE_FINISH ||
    opcode === CODE_SELECTIVE_UNDO
  );
}

interface GuestConnection {
  signalingPeerId: string;
  appPeerId: string | null;
  joined: boolean;
  role: Exclude<CollabRole, 'host'>;
  pc: RTCPeerConnection;
  dc: RTCDataChannel | null;
  ephemeralDc: RTCDataChannel | null;
  sender: DataChannelSendQueue;
  reassembler: ChunkReassembler;
  ephemeralReassembler: ChunkReassembler;
  /** False while an initial snapshot or incremental catch-up replay is in flight. */
  live: boolean;
  syncing: boolean;
  snapshotSeq: number;
  pendingReconnectSinceSeq: number | null;
  lastIncrementalReplayedFromSeq: number | null;
  remoteDescSet: boolean;
  pendingIce: RTCIceCandidateInit[];
  localIceCandidates: SignalingIceCandidate[];
  lastAnswerSdp: string | null;
  lastOfferFingerprint: string | null;
  disconnectTimer: ReturnType<typeof setTimeout> | null;
  closed: boolean;
}

export interface WebRtcHostHubOptions {
  roomHash: string;
  hostPeerId: string;
  turnConfig?: WebRtcTurnConfig;
  customSignalingUrl?: string;
  signalingClient?: ISignalingClient;
  maxPeers?: number;
  opLogMaxEntries?: number;
  opLogMaxBytes?: number;
  brushAssetCacheMaxEntries?: number;
  brushAssetCacheMaxBytes?: number;
  brushProfileCacheMaxEntries?: number;
  brushProfileCacheMaxBytes?: number;
  bufferedAmountLowThreshold?: number;
  ephemeralSoftLimit?: number;
  reliableHighWaterMark?: number;
  reliableQueueHardLimit?: number;
}

/**
 * Authoritative Star-Topology WebRTC Host Hub.
 *
 * The Host tablet/browser accepts up to 8 concurrent guest connections over dual
 * RTCDataChannels (ordered reliable + optional unordered ephemeral for cursors/cameras),
 * enforces Host / Editor / Viewer roles & layer locks, applies per-guest backpressure
 * queues, single-encode fanout, Host-side compacted `op_log` for incremental reconnects,
 * snapshot isolation, and a bounded `BRUSH_ASSET_DATA` unicast cache.
 */
export class WebRtcHostHub implements ICollabTransport {
  public readonly kind = 'webrtc-host' as const;

  public readonly roomHash: string;
  private readonly hostPeerId: string;
  private readonly iceServers: RTCIceServer[];
  private readonly maxPeers: number;
  private readonly signaling: ISignalingClient;
  private readonly opLogMaxEntries: number;
  private readonly opLogMaxBytes: number;
  private readonly brushAssetCacheMaxEntries: number;
  private readonly brushAssetCacheMaxBytes: number;
  private readonly brushProfileCacheMaxEntries: number;
  private readonly brushProfileCacheMaxBytes: number;
  private readonly tileBaseCacheMaxBytes: number;
  private readonly queueConfig: {
    bufferedAmountLowThreshold?: number;
    ephemeralSoftLimit?: number;
    reliableHighWaterMark?: number;
    reliableQueueHardLimit?: number;
  };

  private guests = new Map<string, GuestConnection>();
  private peerRoles = new Map<string, Exclude<CollabRole, 'host'>>();
  private layerLocks = new Map<string, LayerLockMeta>();
  private textHandlers = new Set<(text: string) => void>();
  private binaryHandlers = new Set<(data: ArrayBuffer) => void>();
  private closeHandlers = new Set<(reason?: string) => void>();
  private errorHandlers = new Set<(err: Error | Event) => void>();

  // Bounded ring op_log with tile compaction by (layerId, tileX, tileY)
  private opLog: OpLogEntry[] = [];
  private opLogHead = 0;
  private opLogBytes = 0;
  private opLogFloor = 0;
  private tileLatestSeq = new Map<string, number>();
  private staleOpLogEntries = 0;

  // Bounded self-contained full tile packet store for safe SUBRECT_LZ4 composition
  private tileBasePackets = new Map<string, Uint8Array>();
  private tileBasePacketsBytes = 0;

  // Bounded LRU brush asset packet cache
  private brushAssetCache = new Map<string, Uint8Array>();
  private brushAssetCacheBytes = 0;

  // Bounded LRU brush profile packet cache
  private brushProfileCache = new Map<string, Uint8Array>();
  private brushProfileCacheBytes = 0;

  private retiredDroppedEphemeralCount = 0;

  private unsubSignaling: (() => void) | null = null;
  private nextMsgId = 1;
  private seq = 0;
  private open = false;
  private closed = false;

  constructor(options: WebRtcHostHubOptions) {
    this.roomHash = options.roomHash;
    this.hostPeerId = options.hostPeerId;
    this.iceServers = buildIceServers(options.turnConfig);
    this.maxPeers = Math.max(1, Math.min(MAX_WEBRTC_PEERS, options.maxPeers ?? MAX_WEBRTC_PEERS));
    this.opLogMaxEntries = Math.max(1, options.opLogMaxEntries ?? WEBRTC_OP_LOG_MAX_ENTRIES);
    this.opLogMaxBytes = Math.max(1024, options.opLogMaxBytes ?? WEBRTC_OP_LOG_MAX_BYTES);
    this.brushAssetCacheMaxEntries = Math.max(
      0,
      options.brushAssetCacheMaxEntries ?? WEBRTC_BRUSH_ASSET_CACHE_MAX_ENTRIES
    );
    this.brushAssetCacheMaxBytes = Math.max(
      0,
      options.brushAssetCacheMaxBytes ?? WEBRTC_BRUSH_ASSET_CACHE_MAX_BYTES
    );
    this.brushProfileCacheMaxEntries = Math.max(
      0,
      options.brushProfileCacheMaxEntries ?? WEBRTC_BRUSH_PROFILE_CACHE_MAX_ENTRIES
    );
    this.brushProfileCacheMaxBytes = Math.max(
      0,
      options.brushProfileCacheMaxBytes ?? WEBRTC_BRUSH_PROFILE_CACHE_MAX_BYTES
    );
    this.tileBaseCacheMaxBytes = Math.max(this.opLogMaxBytes, WEBRTC_TILE_BASE_CACHE_MAX_BYTES);
    this.queueConfig = {
      bufferedAmountLowThreshold: options.bufferedAmountLowThreshold,
      ephemeralSoftLimit: options.ephemeralSoftLimit,
      reliableHighWaterMark: options.reliableHighWaterMark,
      reliableQueueHardLimit: options.reliableQueueHardLimit,
    };
    this.signaling =
      options.signalingClient ??
      createSignalingClient({
        roomHash: options.roomHash,
        peerId: options.hostPeerId,
        customSignalingUrl: options.customSignalingUrl,
      });
  }

  public async start(): Promise<void> {
    if (this.closed) {
      throw new Error('WebRTC Host Hub has already been closed');
    }
    if (typeof RTCPeerConnection === 'undefined') {
      throw new Error('WebRTC is not supported in this browser/WebView');
    }

    this.unsubSignaling = this.signaling.onMessage((env) => {
      void this.handleSignalingEnvelope(env);
    });

    await this.signaling.connect();
    this.open = true;
  }

  public isOpen(): boolean {
    return this.open && !this.closed;
  }

  public getConnectedGuestCount(): number {
    let count = 0;
    for (const g of this.guests.values()) {
      if (!g.closed && g.dc?.readyState === 'open') count += 1;
    }
    return count;
  }

  public getBufferedAmount(): number {
    let maxBuffered = 0;
    for (const g of this.guests.values()) {
      if (!g.closed && g.dc && g.dc.readyState === 'open') {
        const buffered = g.sender ? g.sender.getTotalBufferedAmount() : g.dc.bufferedAmount || 0;
        maxBuffered = Math.max(maxBuffered, buffered);
      }
    }
    return maxBuffered;
  }

  public getCurrentSeq(): number {
    return this.seq;
  }

  public getOpLogFloor(): number {
    return this.opLogFloor;
  }

  public getOpLogSize(): number {
    return Math.max(0, this.opLog.length - this.opLogHead);
  }

  public getBrushAssetCacheSize(): number {
    return this.brushAssetCache.size;
  }

  public getBrushProfileCacheSize(): number {
    return this.brushProfileCache.size;
  }

  public getDroppedEphemeralCount(): number {
    let total = this.retiredDroppedEphemeralCount;
    for (const guest of this.guests.values()) {
      if (!guest.closed && guest.sender) {
        total += guest.sender.getDroppedEphemeralCount();
      }
    }
    return total;
  }

  public async getActiveIceCandidateType(): Promise<CollabIceCandidateType | null> {
    if (this.closed) return null;
    const rank: Record<CollabIceCandidateType, number> = {
      relay: 4,
      srflx: 3,
      prflx: 2,
      host: 1,
      unknown: 0,
    };
    let best: CollabIceCandidateType | null = null;
    for (const guest of this.guests.values()) {
      if (guest.closed || !guest.dc || guest.dc.readyState !== 'open') continue;
      const candType = await queryPeerConnectionIceCandidateType(guest.pc);
      if (candType && (!best || rank[candType] > rank[best])) {
        best = candType;
      }
    }
    return best;
  }

  public canIncrementalCatchUp(sinceSeq: number): boolean {
    return (
      Number.isSafeInteger(sinceSeq) &&
      sinceSeq > 0 &&
      sinceSeq >= this.opLogFloor &&
      sinceSeq <= this.seq
    );
  }

  /**
   * Begins snapshot isolation for a joining guest: holds live room broadcasts out of the
   * guest's channel while `DOC_SYNC_RESPONSE`, tiles, and masks stream at `snapshotSeq`.
   */
  public beginPeerSnapshot(targetPeerId: string | number): number {
    const guest = this.findGuestByAppOrSignalingId(targetPeerId);
    const snapshotSeq = ++this.seq;
    if (guest && !guest.closed) {
      guest.live = false;
      guest.syncing = true;
      guest.snapshotSeq = snapshotSeq;
      guest.pendingReconnectSinceSeq = null;
      guest.lastIncrementalReplayedFromSeq = null;
    }
    return snapshotSeq;
  }

  /**
   * Completes snapshot isolation for a guest: drains all compacted `op_log` entries
   * with `seq > snapshotSeq` into the guest's FIFO reliable queue and flips `live = true` atomically.
   */
  public finishPeerSnapshot(targetPeerId: string | number, snapshotSeqOverride?: number): void {
    const guest = this.findGuestByAppOrSignalingId(targetPeerId);
    if (!guest || guest.closed) return;
    const baseSeq =
      typeof snapshotSeqOverride === 'number' &&
      Number.isSafeInteger(snapshotSeqOverride) &&
      snapshotSeqOverride >= 0
        ? snapshotSeqOverride
        : guest.snapshotSeq;

    this.replayOpLogEntriesToGuest(guest, baseSeq);
    if (guest.closed) return;

    guest.syncing = false;
    guest.snapshotSeq = 0;
    guest.pendingReconnectSinceSeq = null;
    guest.live = true;
  }

  /**
   * Replays missed compacted `op_log` entries strictly greater than `sinceSeq` to a
   * reconnecting guest and flips `guest.live = true` atomically.
   */
  public replayIncrementalToPeer(targetPeerId: string | number, sinceSeq: number): boolean {
    const guest = this.findGuestByAppOrSignalingId(targetPeerId);
    if (!guest || guest.closed) return false;

    // Avoid duplicate replay if `JOIN_ACCEPTED` already replayed this exact reconnect cursor
    if (guest.lastIncrementalReplayedFromSeq === sinceSeq) {
      guest.lastIncrementalReplayedFromSeq = null;
      return true;
    }

    if (!this.canIncrementalCatchUp(sinceSeq)) {
      return false;
    }

    guest.live = false;
    guest.syncing = true;
    this.replayOpLogEntriesToGuest(guest, sinceSeq);
    if (guest.closed) return false;

    guest.pendingReconnectSinceSeq = null;
    guest.lastIncrementalReplayedFromSeq = null;
    guest.syncing = false;
    guest.live = true;
    return true;
  }

  private allocMessageId = (): number => {
    this.nextMsgId = (this.nextMsgId + 1) >>> 0;
    if (this.nextMsgId === 0) this.nextMsgId = 1;
    return this.nextMsgId;
  };

  private isOpEntryStale(entry: OpLogEntry): boolean {
    if (!entry.tileKey) return false;
    const latest = this.tileLatestSeq.get(entry.tileKey);
    return latest !== undefined && entry.seq < latest;
  }

  private compactOpLog(): void {
    const activeLen = this.opLog.length - this.opLogHead;
    if (activeLen <= 0) {
      this.opLog.length = 0;
      this.opLogHead = 0;
      this.opLogBytes = 0;
      this.staleOpLogEntries = 0;
      return;
    }

    const next: OpLogEntry[] = [];
    let nextBytes = 0;
    for (let i = this.opLogHead; i < this.opLog.length; i++) {
      const entry = this.opLog[i];
      if (!entry || this.isOpEntryStale(entry)) {
        continue;
      }
      next.push(entry);
      nextBytes += entry.byteLength;
    }
    this.opLog = next;
    this.opLogHead = 0;
    this.opLogBytes = nextBytes;
    this.staleOpLogEntries = 0;
  }

  private pushOpLog(
    seq: number,
    kind: 'text' | 'binary',
    payload: string | Uint8Array,
    senderPeerId?: string,
    tileKey?: string
  ): void {
    const byteLength =
      kind === 'binary' ? (payload as Uint8Array).byteLength : (payload as string).length * 2;

    if (tileKey) {
      const prevSeq = this.tileLatestSeq.get(tileKey);
      this.tileLatestSeq.set(tileKey, seq);
      if (prevSeq !== undefined && prevSeq > this.opLogFloor) {
        this.staleOpLogEntries += 1;
      }
    }

    if (byteLength > this.opLogMaxBytes) {
      this.opLog.length = 0;
      this.opLogHead = 0;
      this.opLogBytes = 0;
      this.staleOpLogEntries = 0;
      this.opLogFloor = Math.max(this.opLogFloor, seq);
      return;
    }

    const activeLen = this.opLog.length - this.opLogHead;
    const needsRoom =
      activeLen >= this.opLogMaxEntries || this.opLogBytes + byteLength > this.opLogMaxBytes;
    if (
      this.staleOpLogEntries > 0 &&
      (needsRoom ||
        this.staleOpLogEntries >= OP_LOG_COMPACT_STALE_THRESHOLD ||
        activeLen <= 256)
    ) {
      this.compactOpLog();
    }

    while (
      this.opLog.length - this.opLogHead > 0 &&
      (this.opLog.length - this.opLogHead >= this.opLogMaxEntries ||
        this.opLogBytes + byteLength > this.opLogMaxBytes)
    ) {
      const evicted = this.opLog[this.opLogHead];
      this.opLog[this.opLogHead] = undefined as unknown as OpLogEntry;
      this.opLogHead += 1;
      if (evicted) {
        this.opLogBytes = Math.max(0, this.opLogBytes - evicted.byteLength);
        this.opLogFloor = Math.max(this.opLogFloor, evicted.seq);
        if (evicted.tileKey && this.tileLatestSeq.get(evicted.tileKey) === evicted.seq) {
          this.tileLatestSeq.delete(evicted.tileKey);
        }
      }
    }

    if (this.opLogHead >= 64 && this.opLogHead * 2 >= this.opLog.length) {
      this.opLog = this.opLog.slice(this.opLogHead);
      this.opLogHead = 0;
    }

    this.opLog.push({
      seq,
      senderPeerId,
      tileKey,
      kind,
      payload,
      byteLength,
    });
    this.opLogBytes += byteLength;
  }

  private replayOpLogEntriesToGuest(guest: GuestConnection, sinceSeq: number): number {
    const guestPeerId = guest.appPeerId || guest.signalingPeerId;
    let sentCount = 0;
    for (let i = this.opLogHead; i < this.opLog.length; i++) {
      if (guest.closed) break;
      const entry = this.opLog[i];
      if (!entry || entry.seq <= sinceSeq) continue;
      if (this.isOpEntryStale(entry)) continue;
      if (entry.senderPeerId && entry.senderPeerId === guestPeerId) continue;

      if (entry.kind === 'text') {
        this.sendTextToGuest(guest, entry.payload as string, false);
      } else {
        this.sendBinaryToGuest(guest, entry.payload as Uint8Array, false);
      }
      sentCount += 1;
    }
    return sentCount;
  }

  private cacheBrushAsset(hash: string, packet: Uint8Array): void {
    if (
      this.brushAssetCacheMaxEntries === 0 ||
      this.brushAssetCacheMaxBytes === 0 ||
      packet.byteLength > this.brushAssetCacheMaxBytes
    ) {
      return;
    }

    const existing = this.brushAssetCache.get(hash);
    if (existing) {
      this.brushAssetCacheBytes = Math.max(0, this.brushAssetCacheBytes - existing.byteLength);
      this.brushAssetCache.delete(hash);
    }

    while (
      this.brushAssetCache.size > 0 &&
      (this.brushAssetCache.size >= this.brushAssetCacheMaxEntries ||
        this.brushAssetCacheBytes + packet.byteLength > this.brushAssetCacheMaxBytes)
    ) {
      const oldestKey = this.brushAssetCache.keys().next().value;
      if (oldestKey === undefined) break;
      const oldest = this.brushAssetCache.get(oldestKey);
      this.brushAssetCache.delete(oldestKey);
      if (oldest) {
        this.brushAssetCacheBytes = Math.max(0, this.brushAssetCacheBytes - oldest.byteLength);
      }
    }

    this.brushAssetCache.set(hash, packet);
    this.brushAssetCacheBytes += packet.byteLength;
  }

  private getCachedBrushAsset(hash: string): Uint8Array | null {
    const cached = this.brushAssetCache.get(hash);
    if (!cached) return null;
    // Refresh LRU recency
    this.brushAssetCache.delete(hash);
    this.brushAssetCache.set(hash, cached);
    return cached;
  }

  private cacheBrushProfile(hash: string, packet: Uint8Array): void {
    if (
      this.brushProfileCacheMaxEntries === 0 ||
      this.brushProfileCacheMaxBytes === 0 ||
      packet.byteLength > this.brushProfileCacheMaxBytes
    ) {
      return;
    }

    const existing = this.brushProfileCache.get(hash);
    if (existing) {
      this.brushProfileCacheBytes = Math.max(0, this.brushProfileCacheBytes - existing.byteLength);
      this.brushProfileCache.delete(hash);
    }

    while (
      this.brushProfileCache.size > 0 &&
      (this.brushProfileCache.size >= this.brushProfileCacheMaxEntries ||
        this.brushProfileCacheBytes + packet.byteLength > this.brushProfileCacheMaxBytes)
    ) {
      const oldestKey = this.brushProfileCache.keys().next().value;
      if (oldestKey === undefined) break;
      const oldest = this.brushProfileCache.get(oldestKey);
      this.brushProfileCache.delete(oldestKey);
      if (oldest) {
        this.brushProfileCacheBytes = Math.max(0, this.brushProfileCacheBytes - oldest.byteLength);
      }
    }

    this.brushProfileCache.set(hash, packet);
    this.brushProfileCacheBytes += packet.byteLength;
  }

  private getCachedBrushProfile(hash: string): Uint8Array | null {
    const cached = this.brushProfileCache.get(hash);
    if (!cached) return null;
    this.brushProfileCache.delete(hash);
    this.brushProfileCache.set(hash, cached);
    return cached;
  }

  private recordTileBasePacket(tileKey: string, fullWirePacket: Uint8Array): void {
    if (fullWirePacket.byteLength > this.tileBaseCacheMaxBytes) return;
    const existing = this.tileBasePackets.get(tileKey);
    if (existing) {
      this.tileBasePacketsBytes = Math.max(0, this.tileBasePacketsBytes - existing.byteLength);
      this.tileBasePackets.delete(tileKey);
    }
    while (
      this.tileBasePackets.size > 0 &&
      this.tileBasePacketsBytes + fullWirePacket.byteLength > this.tileBaseCacheMaxBytes
    ) {
      const oldestKey = this.tileBasePackets.keys().next().value;
      if (oldestKey === undefined) break;
      const oldest = this.tileBasePackets.get(oldestKey);
      this.tileBasePackets.delete(oldestKey);
      if (oldest) {
        this.tileBasePacketsBytes = Math.max(0, this.tileBasePacketsBytes - oldest.byteLength);
      }
    }
    this.tileBasePackets.set(tileKey, fullWirePacket);
    this.tileBasePacketsBytes += fullWirePacket.byteLength;
  }

  private deleteTileBasePacket(tileKey: string): void {
    const existing = this.tileBasePackets.get(tileKey);
    if (existing) {
      this.tileBasePacketsBytes = Math.max(0, this.tileBasePacketsBytes - existing.byteLength);
      this.tileBasePackets.delete(tileKey);
    }
  }

  private pruneTileBasePacketsForLayer(layerId: string): void {
    const prefix = `${layerId}:`;
    for (const key of Array.from(this.tileBasePackets.keys())) {
      if (key.startsWith(prefix)) {
        this.deleteTileBasePacket(key);
      }
    }
  }

  private clearTileBasePackets(): void {
    this.tileBasePackets.clear();
    this.tileBasePacketsBytes = 0;
  }

  private findGuestByAppOrSignalingId(peerId: string | number | undefined): GuestConnection | null {
    if (peerId === undefined || peerId === null) return null;
    const target = String(peerId);
    for (const guest of this.guests.values()) {
      if (guest.appPeerId === target || guest.signalingPeerId === target) {
        return guest;
      }
    }
    return null;
  }

  private sendEncodedFramesToGuest(
    guest: GuestConnection,
    frames: readonly Uint8Array[],
    ephemeral: boolean
  ): void {
    if (guest.closed) return;
    if (guest.sender) {
      guest.sender.sendFrames(frames, ephemeral);
      return;
    }
    if (guest.dc && guest.dc.readyState === 'open') {
      for (let i = 0; i < frames.length; i++) {
        guest.dc.send(frames[i] as unknown as ArrayBuffer);
      }
    }
  }

  private sendTextToGuest(
    guest: GuestConnection,
    text: string,
    ephemeral: boolean = false
  ): void {
    if (guest.closed || !guest.dc || guest.dc.readyState !== 'open') return;
    try {
      const frames = encodeTransportFrames('text', text, this.allocMessageId());
      this.sendEncodedFramesToGuest(guest, frames, ephemeral);
    } catch {
      // ignore encode failure on oversized/closing payload
    }
  }

  private sendBinaryToGuest(
    guest: GuestConnection,
    data: ArrayBuffer | Uint8Array,
    ephemeral: boolean = false
  ): void {
    if (guest.closed) return;
    const hasOpenChannel =
      (guest.dc && guest.dc.readyState === 'open') ||
      (ephemeral && guest.ephemeralDc && guest.ephemeralDc.readyState === 'open');
    if (!hasOpenChannel) return;
    try {
      const frames = encodeTransportFrames('binary', data, this.allocMessageId());
      this.sendEncodedFramesToGuest(guest, frames, ephemeral);
    } catch {
      // ignore encode failure on oversized/closing payload
    }
  }

  private sendAccessDeniedToGuest(
    guest: GuestConnection,
    code: 'VIEWER_READONLY' | 'FORBIDDEN' | 'LAYER_LOCKED' | 'NOT_OWNER',
    reason: string
  ): void {
    const payload = JSON.stringify({
      type: 'ACCESS_DENIED',
      senderId: this.hostPeerId,
      targetPeerId: guest.appPeerId || guest.signalingPeerId,
      code,
      reason,
    });
    this.sendTextToGuest(guest, payload, false);
  }

  private stampBinarySeqCopy(
    data: ArrayBuffer | Uint8Array,
    fixedSeq?: number
  ): { bytes: Uint8Array; seq: number } {
    const src = toUint8Array(data);
    const out = new Uint8Array(src.byteLength);
    out.set(src);
    let seq = fixedSeq ?? 0;
    if (out.byteLength >= 11 && out[0] === BINARY_MAGIC_0 && out[1] === BINARY_MAGIC_1) {
      seq = fixedSeq !== undefined ? fixedSeq : ++this.seq;
      const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
      view.setUint32(3, seq, true);
    }
    return { bytes: out, seq };
  }

  private syncLayerLocksFromWireList(layersRaw: unknown): void {
    if (!Array.isArray(layersRaw)) return;
    const next = new Map<string, LayerLockMeta>();
    for (const item of layersRaw) {
      if (!item || typeof item !== 'object') continue;
      const obj = item as Record<string, unknown>;
      if (typeof obj.id !== 'string' || !obj.id) continue;
      const ownerPeerId =
        obj.ownerPeerId !== undefined && obj.ownerPeerId !== null && obj.ownerPeerId !== ''
          ? String(obj.ownerPeerId)
          : undefined;
      const reservedByPeerId =
        obj.reservedByPeerId !== undefined &&
        obj.reservedByPeerId !== null &&
        obj.reservedByPeerId !== ''
          ? String(obj.reservedByPeerId)
          : undefined;
      next.set(obj.id, { ownerPeerId, reservedByPeerId });
    }
    this.layerLocks = next;
  }

  private applyLayerLockMutation(parsed: Record<string, unknown>): void {
    const type = typeof parsed.type === 'string' ? parsed.type : '';
    if (type === 'DOC_SYNC_RESPONSE' || type === 'LAYER_TREE_SYNC') {
      this.syncLayerLocksFromWireList(parsed.layers);
      return;
    }
    if (type === 'LAYER_ADD' && parsed.layerItem && typeof parsed.layerItem === 'object') {
      const item = parsed.layerItem as Record<string, unknown>;
      if (typeof item.id === 'string' && item.id) {
        this.layerLocks.set(item.id, {
          ownerPeerId:
            item.ownerPeerId !== undefined && item.ownerPeerId !== null && item.ownerPeerId !== ''
              ? String(item.ownerPeerId)
              : undefined,
          reservedByPeerId:
            item.reservedByPeerId !== undefined &&
            item.reservedByPeerId !== null &&
            item.reservedByPeerId !== ''
              ? String(item.reservedByPeerId)
              : undefined,
        });
      }
      return;
    }
    if (type === 'LAYER_DELETE' && typeof parsed.layerId === 'string') {
      this.layerLocks.delete(parsed.layerId);
      this.pruneTileBasePacketsForLayer(parsed.layerId);
      return;
    }
    if (type === 'LAYER_CLEAR' && typeof parsed.layerId === 'string') {
      this.pruneTileBasePacketsForLayer(parsed.layerId);
      return;
    }
    if (type === 'CANVAS_RESIZE') {
      this.clearTileBasePackets();
      return;
    }
    if (type === 'LAYER_UPDATE' && typeof parsed.layerId === 'string') {
      const existing = this.layerLocks.get(parsed.layerId) || {};
      const next: LayerLockMeta = { ...existing };
      const patch =
        parsed.patch && typeof parsed.patch === 'object'
          ? (parsed.patch as Record<string, unknown>)
          : null;
      const cleared = Array.isArray(parsed.clearedFields) ? parsed.clearedFields : [];
      if (patch) {
        if (patch.ownerPeerId !== undefined && patch.ownerPeerId !== null && patch.ownerPeerId !== '') {
          next.ownerPeerId = String(patch.ownerPeerId);
        }
        if (
          patch.reservedByPeerId !== undefined &&
          patch.reservedByPeerId !== null &&
          patch.reservedByPeerId !== ''
        ) {
          next.reservedByPeerId = String(patch.reservedByPeerId);
        }
      }
      if (cleared.includes('ownerPeerId')) delete next.ownerPeerId;
      if (cleared.includes('reservedByPeerId')) delete next.reservedByPeerId;
      this.layerLocks.set(parsed.layerId, next);
      return;
    }
    if (type === 'PEER_BAN' && parsed.targetPeerId !== undefined && parsed.targetPeerId !== null) {
      const bannedId = String(parsed.targetPeerId);
      for (const meta of this.layerLocks.values()) {
        if (meta.reservedByPeerId === bannedId) {
          delete meta.reservedByPeerId;
        }
      }
    }
  }

  private isLayerLockedForGuest(layerId: string, guestPeerId: string): boolean {
    const meta = this.layerLocks.get(layerId);
    return Boolean(meta?.reservedByPeerId && meta.reservedByPeerId !== guestPeerId);
  }

  private extractBinaryLayerId(bytes: Uint8Array, opcode: number): string | null {
    if (bytes.byteLength < 11) return null;
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const payloadLen = view.getUint32(7, true);
    if (11 + payloadLen > bytes.byteLength) return null;

    if (opcode === CODE_TILE_DELTA || opcode === CODE_LAYER_MASK_DATA) {
      if (payloadLen < 2) return null;
      const layerIdLen = view.getUint16(11, true);
      if (layerIdLen === 0 || layerIdLen > 256 || 13 + layerIdLen > 11 + payloadLen) return null;
      return sharedTextDecoder.decode(bytes.subarray(13, 13 + layerIdLen));
    }

    if (opcode === CODE_STROKE_START) {
      // Fast O(1) layerId extraction for slim binary STROKE_START v2 (layerIdLen at payload[19])
      if (payloadLen >= 21 && bytes[11] === STROKE_START_BINARY_VERSION) {
        const layerIdLen = bytes[30];
        if (layerIdLen === 0 || 31 + layerIdLen > 11 + payloadLen) return null;
        return sharedTextDecoder.decode(bytes.subarray(31, 31 + layerIdLen));
      }
      try {
        const jsonStr = sharedTextDecoder.decode(bytes.subarray(11, 11 + payloadLen));
        const parsed = JSON.parse(jsonStr) as { layerId?: unknown };
        return typeof parsed?.layerId === 'string' ? parsed.layerId : null;
      } catch {
        return null;
      }
    }

    if (opcode === CODE_STROKE_FINISH) {
      try {
        const jsonStr = sharedTextDecoder.decode(bytes.subarray(11, 11 + payloadLen));
        const parsed = JSON.parse(jsonStr) as { layerId?: unknown };
        return typeof parsed?.layerId === 'string' ? parsed.layerId : null;
      } catch {
        return null;
      }
    }

    return null;
  }

  /**
   * Single-encode text fanout across all eligible live guests.
   * Frames are encoded at most once and shared across all recipient queues.
   */
  private broadcastText(
    text: string,
    excludeSignalingId?: string,
    options?: { ephemeral?: boolean; includeSyncing?: boolean; excludeAppPeerId?: string }
  ): void {
    const ephemeral = Boolean(options?.ephemeral);
    const includeSyncing = Boolean(options?.includeSyncing);
    const excludeAppPeerId = options?.excludeAppPeerId;
    let frames: Uint8Array[] | null = null;

    for (const guest of this.guests.values()) {
      if (guest.closed) continue;
      if (excludeSignalingId && guest.signalingPeerId === excludeSignalingId) continue;
      if (excludeAppPeerId && guest.appPeerId === excludeAppPeerId) continue;
      if (!includeSyncing && (!guest.joined || guest.live === false)) continue;
      if (!guest.dc || guest.dc.readyState !== 'open') continue;

      if (frames === null) {
        try {
          frames = encodeTransportFrames('text', text, this.allocMessageId());
        } catch {
          return;
        }
      }
      this.sendEncodedFramesToGuest(guest, frames, ephemeral);
    }
  }

  /**
   * Single-encode binary fanout across all eligible live guests.
   * Transport chunks are encoded once per broadcast and shared across all recipient queues.
   */
  private broadcastBinary(
    data: ArrayBuffer | Uint8Array,
    excludeSignalingId?: string,
    options?: { ephemeral?: boolean; includeSyncing?: boolean }
  ): void {
    const ephemeral = Boolean(options?.ephemeral);
    const includeSyncing = Boolean(options?.includeSyncing);
    let frames: Uint8Array[] | null = null;

    for (const guest of this.guests.values()) {
      if (guest.closed) continue;
      if (excludeSignalingId && guest.signalingPeerId === excludeSignalingId) continue;
      if (!includeSyncing && (!guest.joined || guest.live === false)) continue;
      const hasOpenChannel =
        (guest.dc && guest.dc.readyState === 'open') ||
        (ephemeral && guest.ephemeralDc && guest.ephemeralDc.readyState === 'open');
      if (!hasOpenChannel) continue;

      if (frames === null) {
        try {
          frames = encodeTransportFrames('binary', data, this.allocMessageId());
        } catch {
          return;
        }
      }
      this.sendEncodedFramesToGuest(guest, frames, ephemeral);
    }
  }

  private stampOutgoingJsonSeq(
    rawText: string,
    parsed: Record<string, unknown>,
    forcedSeq?: number
  ): { text: string; seq: number } {
    if (
      forcedSeq === undefined &&
      typeof parsed.seq === 'number' &&
      Number.isSafeInteger(parsed.seq) &&
      parsed.seq > 0
    ) {
      if (parsed.seq > this.seq) {
        this.seq = parsed.seq;
      }
      return { text: rawText, seq: parsed.seq };
    }

    const seq = forcedSeq !== undefined ? forcedSeq : ++this.seq;
    if (!('seq' in parsed)) {
      const injected = injectSeqIntoJsonObject(rawText, seq);
      if (injected !== null) {
        return { text: injected, seq };
      }
    }
    parsed.seq = seq;
    return { text: JSON.stringify(parsed), seq };
  }

  public sendText(text: string, options?: CollabSendOptions): void {
    if (!this.isOpen()) return;

    let parsed: Record<string, unknown> | null = null;
    try {
      const raw = JSON.parse(text) as unknown;
      if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
        parsed = raw as Record<string, unknown>;
      }
    } catch {
      // send raw
    }

    if (parsed) {
      const type = typeof parsed.type === 'string' ? parsed.type : '';
      const targetPeerId =
        typeof parsed.targetPeerId === 'string' || typeof parsed.targetPeerId === 'number'
          ? String(parsed.targetPeerId)
          : undefined;

      // Stateful Rust server seed is unnecessary in P2P host hub (Host is already live)
      if (targetPeerId === '__server__') {
        return;
      }

      if (type === 'PEER_ROLE_UPDATE' && targetPeerId) {
        const nextRole: Exclude<CollabRole, 'host'> =
          parsed.role === 'viewer' ? 'viewer' : 'editor';
        this.peerRoles.set(targetPeerId, nextRole);
        const guest = this.findGuestByAppOrSignalingId(targetPeerId);
        if (guest) {
          guest.role = nextRole;
        }
      } else if (type === 'JOIN_ACCEPTED' && targetPeerId) {
        const assignedRole: Exclude<CollabRole, 'host'> | null =
          parsed.assignedRole === 'viewer'
            ? 'viewer'
            : parsed.assignedRole === 'editor'
              ? 'editor'
              : null;
        if (assignedRole) {
          this.peerRoles.set(targetPeerId, assignedRole);
        }
        const guest = this.findGuestByAppOrSignalingId(targetPeerId);
        if (guest && assignedRole) {
          guest.role = assignedRole;
        }

        // Incremental reconnect handshake: deliver JOIN_ACCEPTED, replay missed op_log > sinceSeq, flip live
        if (guest && guest.pendingReconnectSinceSeq !== null) {
          const sinceSeq = guest.pendingReconnectSinceSeq;
          const stamped = this.stampOutgoingJsonSeq(text, parsed, sinceSeq);
          this.sendTextToGuest(guest, stamped.text, false);
          this.replayOpLogEntriesToGuest(guest, sinceSeq);
          if (!guest.closed) {
            guest.pendingReconnectSinceSeq = null;
            guest.lastIncrementalReplayedFromSeq = sinceSeq;
            guest.syncing = false;
            guest.live = true;
          }
          return;
        }

        // Full snapshot handshake: pin JOIN_ACCEPTED to snapshotSeq so it matches DOC_SYNC_RESPONSE
        if (guest && guest.syncing && guest.snapshotSeq > 0) {
          const stamped = this.stampOutgoingJsonSeq(text, parsed, guest.snapshotSeq);
          this.sendTextToGuest(guest, stamped.text, false);
          return;
        }
      }

      this.applyLayerLockMutation(parsed);

      if (type === 'DOC_SYNC_RESPONSE' && targetPeerId) {
        const targetGuest = this.findGuestByAppOrSignalingId(targetPeerId);
        if (targetGuest) {
          const forcedSeq =
            targetGuest.syncing && targetGuest.snapshotSeq > 0
              ? targetGuest.snapshotSeq
              : undefined;
          const stamped = this.stampOutgoingJsonSeq(text, parsed, forcedSeq);
          this.sendTextToGuest(targetGuest, stamped.text, false);
        }
        return;
      }

      const { text: sequenced, seq } = this.stampOutgoingJsonSeq(text, parsed);

      if (
        type === 'PEER_KICK' ||
        type === 'PEER_BAN' ||
        (type === 'ACCESS_DENIED' && (parsed.code === 'BANNED' || parsed.code === 'KICKED'))
      ) {
        const guest = this.findGuestByAppOrSignalingId(targetPeerId);
        if (type === 'ACCESS_DENIED') {
          if (guest) this.sendTextToGuest(guest, sequenced, false);
        } else {
          this.pushOpLog(seq, 'text', sequenced, this.hostPeerId);
          this.broadcastText(sequenced, undefined, { includeSyncing: true });
        }
        if (guest) {
          setTimeout(() => this.removeGuest(guest.signalingPeerId, false), 80);
        }
        return;
      }

      if (targetPeerId && UNICAST_FROM_HOST_TYPES.has(type)) {
        const targetGuest = this.findGuestByAppOrSignalingId(targetPeerId);
        if (targetGuest) {
          this.sendTextToGuest(targetGuest, sequenced, false);
        }
        return;
      }

      if (OP_LOG_TEXT_TYPES.has(type)) {
        const opSenderPeerId =
          type === 'PEER_JOINED' &&
          parsed.peer &&
          typeof parsed.peer === 'object' &&
          (typeof (parsed.peer as Record<string, unknown>).id === 'string' ||
            typeof (parsed.peer as Record<string, unknown>).id === 'number')
            ? String((parsed.peer as Record<string, unknown>).id)
            : this.hostPeerId;
        this.pushOpLog(seq, 'text', sequenced, opSenderPeerId);
      }

      const ephemeral = options?.ephemeral ?? EPHEMERAL_TEXT_TYPES.has(type);
      const excludeAppPeerId =
        type === 'PEER_JOINED' &&
        parsed.peer &&
        typeof parsed.peer === 'object' &&
        (typeof (parsed.peer as Record<string, unknown>).id === 'string' ||
          typeof (parsed.peer as Record<string, unknown>).id === 'number')
          ? String((parsed.peer as Record<string, unknown>).id)
          : undefined;
      this.broadcastText(sequenced, undefined, { ephemeral, excludeAppPeerId });
      return;
    }

    this.broadcastText(text, undefined, { ephemeral: options?.ephemeral });
  }

  public sendBinary(data: ArrayBuffer | Uint8Array, options?: CollabSendOptions): void {
    if (!this.isOpen()) return;
    const raw = toUint8Array(data);
    const rawOpcode =
      raw.byteLength >= 11 && raw[0] === BINARY_MAGIC_0 && raw[1] === BINARY_MAGIC_1 ? raw[2] : -1;

    // Lightweight RTT PING/PONG never bump authoritative seq or enter op_log
    if (rawOpcode === CODE_PING) {
      const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
      const payloadLen = view.getUint32(7, true);
      if (payloadLen === PING_PAYLOAD_BYTES && 11 + payloadLen <= raw.byteLength) {
        this.broadcastBinary(raw, undefined, { ephemeral: true });
      }
      return;
    }
    if (rawOpcode === CODE_PONG) {
      return;
    }

    // Sub-rect tile patches must compose cleanly onto a known full base tile so op_log
    // and late-joiner/reconnecting replays NEVER receive an orphaned sub-rect patch.
    if (rawOpcode === CODE_TILE_DELTA) {
      const tileMeta = extractBinaryTileMeta(raw);
      if (tileMeta && tileMeta.codec === TILE_CODEC_SUBRECT_LZ4) {
        const baseWire = this.tileBasePackets.get(tileMeta.key);
        if (!baseWire) return;
        const baseMeta = extractBinaryTileMeta(baseWire);
        if (!baseMeta) return;
        const composedTilePacket = composeSubRectOntoTilePacket(
          tileMeta.layerId,
          baseWire.subarray(baseMeta.tilePacketOffset, baseMeta.payloadEnd),
          raw.subarray(tileMeta.tilePacketOffset, tileMeta.payloadEnd)
        );
        if (!composedTilePacket) return;

        const { bytes: stampedLive, seq } = this.stampBinarySeqCopy(raw);
        const storedFull = buildWireTileDeltaPacket(
          tileMeta.layerIdBytes,
          composedTilePacket,
          seq
        );
        this.recordTileBasePacket(tileMeta.key, storedFull);
        this.pushOpLog(seq, 'binary', storedFull, this.hostPeerId, tileMeta.key);
        this.broadcastBinary(stampedLive, undefined, { ephemeral: false });
        return;
      }

      const { bytes: stamped, seq } = this.stampBinarySeqCopy(raw);
      if (tileMeta) {
        if (tileMeta.codec === TILE_CODEC_EMPTY) {
          this.deleteTileBasePacket(tileMeta.key);
        } else if (
          tileMeta.codec === TILE_CODEC_RAW ||
          tileMeta.codec === TILE_CODEC_LZ4 ||
          tileMeta.codec === TILE_CODEC_SOLID
        ) {
          this.recordTileBasePacket(tileMeta.key, stamped);
        }
        if (seq > 0) {
          this.pushOpLog(seq, 'binary', stamped, this.hostPeerId, tileMeta.key);
        }
      } else if (seq > 0) {
        this.pushOpLog(seq, 'binary', stamped, this.hostPeerId);
      }
      this.broadcastBinary(stamped, undefined, { ephemeral: options?.ephemeral ?? false });
      return;
    }

    const { bytes: stamped, seq } = this.stampBinarySeqCopy(raw);
    const opcode = rawOpcode;

    if (opcode === CODE_BRUSH_ASSET_DATA) {
      const hash = extractBrushAssetDataHash(stamped);
      if (hash) {
        this.cacheBrushAsset(hash, stamped);
      }
    } else if (opcode === CODE_BRUSH_PROFILE_DATA) {
      const hash = extractBrushProfileDataHash(stamped);
      if (hash) {
        this.cacheBrushProfile(hash, stamped);
      }
    } else if (seq > 0 && isOpLogEligibleBinaryOpcode(opcode)) {
      if (opcode === CODE_STROKE_START) {
        const extractedProfile = extractBrushProfilePacketFromStrokeStart(stamped, seq);
        if (extractedProfile) {
          this.cacheBrushProfile(extractedProfile.hash, extractedProfile.packet);
        }
      }
      this.pushOpLog(seq, 'binary', stamped, this.hostPeerId);
    }

    const ephemeral = options?.ephemeral ?? isEphemeralWireBinary(stamped);
    this.broadcastBinary(stamped, undefined, { ephemeral });
  }

  public sendBinaryTo(
    targetPeerId: string | number,
    data: ArrayBuffer | Uint8Array,
    options?: CollabSendOptions
  ): void {
    if (!this.isOpen()) return;
    const guest = this.findGuestByAppOrSignalingId(targetPeerId);
    if (!guest) return;

    // During snapshot streaming, pin unicast snapshot tiles/masks to snapshotSeq so
    // subsequent op_log entries (> snapshotSeq) strictly outrank snapshot frames on the guest.
    const fixedSeq = guest.syncing && guest.snapshotSeq > 0 ? guest.snapshotSeq : undefined;
    const { bytes: stamped } = this.stampBinarySeqCopy(data, fixedSeq);

    if (
      stamped.byteLength >= 11 &&
      stamped[0] === BINARY_MAGIC_0 &&
      stamped[1] === BINARY_MAGIC_1
    ) {
      const opcode = stamped[2];
      if (opcode === CODE_BRUSH_ASSET_DATA) {
        const hash = extractBrushAssetDataHash(stamped);
        if (hash) {
          this.cacheBrushAsset(hash, stamped);
        }
      } else if (opcode === CODE_BRUSH_PROFILE_DATA) {
        const hash = extractBrushProfileDataHash(stamped);
        if (hash) {
          this.cacheBrushProfile(hash, stamped);
        }
      } else if (opcode === CODE_TILE_DELTA) {
        const tileMeta = extractBinaryTileMeta(stamped);
        if (tileMeta) {
          // Never send an orphaned sub-rect patch over unicast snapshot/resync
          if (tileMeta.codec === TILE_CODEC_SUBRECT_LZ4) {
            return;
          }
          if (
            (tileMeta.codec === TILE_CODEC_RAW ||
              tileMeta.codec === TILE_CODEC_LZ4 ||
              tileMeta.codec === TILE_CODEC_SOLID) &&
            !this.tileBasePackets.has(tileMeta.key)
          ) {
            this.recordTileBasePacket(tileMeta.key, stamped);
          }
        }
      }
    }

    const ephemeral = options?.ephemeral ?? isEphemeralWireBinary(stamped);
    this.sendBinaryToGuest(guest, stamped, ephemeral);
  }

  private async handleSignalingEnvelope(env: SignalingEnvelope): Promise<void> {
    if (this.closed) return;

    if (env.type === 'offer' && env.sdp) {
      const incomingFingerprint = extractSdpSessionFingerprint(env.sdp);
      const existing = this.guests.get(env.fromPeerId);
      if (existing) {
        if (!existing.closed && existing.lastOfferFingerprint === incomingFingerprint) {
          if (existing.pc.connectionState === 'connected' || existing.dc?.readyState === 'open') {
            return;
          }
          // Resend answer + gathered host ICE candidates on duplicate offer retries while connecting/new
          if (
            existing.lastAnswerSdp &&
            (existing.pc.connectionState === 'connecting' || existing.pc.connectionState === 'new')
          ) {
            const latestAnswerSdp = existing.pc.localDescription?.sdp || existing.lastAnswerSdp;
            this.signaling.send({
              type: 'answer',
              fromPeerId: this.hostPeerId,
              toPeerId: existing.signalingPeerId,
              sdp: latestAnswerSdp,
              sdpType: 'answer',
            });
            for (const cand of existing.localIceCandidates) {
              this.signaling.send({
                type: 'ice',
                fromPeerId: this.hostPeerId,
                toPeerId: existing.signalingPeerId,
                candidate: cand,
              });
            }
            return;
          }
        }
        // Replace stale/zombie or closed peer connection cleanly on fresh reconnect offer
        this.removeGuest(env.fromPeerId, false);
      }

      if (this.guests.size >= this.maxPeers) {
        this.signaling.send({
          type: 'room-full',
          fromPeerId: this.hostPeerId,
          toPeerId: env.fromPeerId,
          reason: `Room is full (maximum ${this.maxPeers} guests)`,
        });
        return;
      }

      const pc = new RTCPeerConnection({ iceServers: this.iceServers });
      const guest: GuestConnection = {
        signalingPeerId: env.fromPeerId,
        appPeerId: null,
        joined: false,
        role: this.peerRoles.get(env.fromPeerId) ?? 'editor',
        pc,
        dc: null,
        ephemeralDc: null,
        sender: new DataChannelSendQueue({
          ...this.queueConfig,
          onOverflow: () => {
            this.removeGuest(env.fromPeerId, true);
          },
        }),
        reassembler: new ChunkReassembler(),
        ephemeralReassembler: new ChunkReassembler({ maxInflight: 16, timeoutMs: 5_000 }),
        live: true,
        syncing: false,
        snapshotSeq: 0,
        pendingReconnectSinceSeq: null,
        lastIncrementalReplayedFromSeq: null,
        remoteDescSet: false,
        pendingIce: [],
        localIceCandidates: [],
        lastAnswerSdp: null,
        lastOfferFingerprint: incomingFingerprint,
        disconnectTimer: null,
        closed: false,
      };
      this.guests.set(env.fromPeerId, guest);

      pc.onicecandidate = (ev) => {
        if (guest.closed || !ev.candidate) return;
        const json = ev.candidate.toJSON ? ev.candidate.toJSON() : undefined;
        const candidateStr = json?.candidate ?? ev.candidate.candidate ?? '';
        if (!candidateStr) return;
        const candidateInit: SignalingIceCandidate = {
          candidate: candidateStr,
          sdpMid: json?.sdpMid ?? ev.candidate.sdpMid ?? null,
          sdpMLineIndex: json?.sdpMLineIndex ?? ev.candidate.sdpMLineIndex ?? null,
          ...(json?.usernameFragment != null ? { usernameFragment: json.usernameFragment } : {}),
        };
        if (guest.localIceCandidates.length < 64) {
          guest.localIceCandidates.push(candidateInit);
        }
        this.signaling.send({
          type: 'ice',
          fromPeerId: this.hostPeerId,
          toPeerId: guest.signalingPeerId,
          candidate: candidateInit,
        });
      };

      pc.onconnectionstatechange = () => {
        if (guest.closed) return;
        if (pc.connectionState === 'connected') {
          if (guest.disconnectTimer !== null) {
            clearTimeout(guest.disconnectTimer);
            guest.disconnectTimer = null;
          }
          return;
        }
        if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
          this.removeGuest(guest.signalingPeerId, true);
        } else if (pc.connectionState === 'disconnected') {
          if (guest.disconnectTimer === null) {
            guest.disconnectTimer = setTimeout(() => {
              guest.disconnectTimer = null;
              if (!guest.closed && pc.connectionState === 'disconnected') {
                this.removeGuest(guest.signalingPeerId, true);
              }
            }, DISCONNECTED_GRACE_MS);
          }
        }
      };

      pc.ondatachannel = (ev) => {
        if (guest.closed) return;
        const dc = ev.channel;
        dc.binaryType = 'arraybuffer';

        const isEphemeralChannel = dc.label === WEBRTC_EPHEMERAL_DATACHANNEL_LABEL;

        const wireOnMessage = (reassembler: ChunkReassembler) => async (msgEv: MessageEvent) => {
          if (guest.closed) return;
          try {
            const rawBuf =
              msgEv.data instanceof ArrayBuffer
                ? msgEv.data
                : msgEv.data instanceof Blob
                  ? await msgEv.data.arrayBuffer()
                  : null;
            if (!rawBuf) return;

            const assembled = reassembler.pushFrame(rawBuf);
            if (!assembled) return;

            if (assembled.kind === 'text') {
              this.handleGuestTextMessage(guest, assembled.text);
            } else {
              this.handleGuestBinaryMessage(guest, assembled.data);
            }
          } catch {
            // drop malformed frame
          }
        };

        if (isEphemeralChannel) {
          guest.ephemeralDc = dc;
          guest.sender.attachEphemeralChannel(dc);
          dc.onmessage = wireOnMessage(guest.ephemeralReassembler);

          // Ephemeral channel close/error NEVER disconnects the guest — fall back seamlessly to reliable
          const detachEphemeral = () => {
            if (guest.ephemeralDc === dc) {
              guest.ephemeralDc = null;
              guest.sender.detachEphemeralChannel();
              guest.ephemeralReassembler.clear();
            }
          };
          dc.onclose = detachEphemeral;
          dc.onerror = detachEphemeral;
          return;
        }

        // Reliable ordered primary channel (WEBRTC_DATACHANNEL_LABEL or unlabeled mock channel)
        guest.dc = dc;
        guest.sender.attachReliableChannel(dc);
        dc.onmessage = wireOnMessage(guest.reassembler);

        dc.onclose = () => {
          if (guest.dc === dc) {
            this.removeGuest(guest.signalingPeerId, true);
          }
        };

        dc.onerror = () => {
          if (guest.dc === dc) {
            this.removeGuest(guest.signalingPeerId, true);
          }
        };
      };

      try {
        await pc.setRemoteDescription({ type: 'offer', sdp: env.sdp });
        guest.remoteDescSet = true;
        for (const cand of guest.pendingIce.splice(0)) {
          try {
            await pc.addIceCandidate(cand);
          } catch {
            // ignore stale candidate
          }
        }
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);
        const answerSdp = pc.localDescription?.sdp || answer.sdp;
        if (answerSdp) {
          guest.lastAnswerSdp = answerSdp;
          this.signaling.send({
            type: 'answer',
            fromPeerId: this.hostPeerId,
            toPeerId: guest.signalingPeerId,
            sdp: answerSdp,
            sdpType: 'answer',
          });
        }
      } catch (err) {
        this.errorHandlers.forEach((h) =>
          h(err instanceof Error ? err : new Error('Failed to answer WebRTC peer'))
        );
        this.removeGuest(guest.signalingPeerId, false);
      }
      return;
    }

    if (env.type === 'ice' && env.candidate) {
      const guest = this.guests.get(env.fromPeerId);
      if (!guest || guest.closed) return;
      if (!guest.remoteDescSet) {
        if (guest.pendingIce.length < 64) {
          guest.pendingIce.push(env.candidate);
        }
        return;
      }
      try {
        await guest.pc.addIceCandidate(env.candidate);
      } catch {
        // ignore invalid candidate
      }
      return;
    }

    if (env.type === 'bye') {
      this.removeGuest(env.fromPeerId, true);
    }
  }

  private handleGuestTextMessage(guest: GuestConnection, rawText: string): void {
    let parsed: Record<string, unknown>;
    try {
      const raw = JSON.parse(rawText) as unknown;
      if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
      parsed = raw as Record<string, unknown>;
    } catch {
      return;
    }

    const type = typeof parsed.type === 'string' ? parsed.type : '';
    if (!type) return;

    if (type === 'JOIN_REQUEST' && parsed.peer && typeof parsed.peer === 'object') {
      const peerObj = parsed.peer as Record<string, unknown>;
      if (typeof peerObj.id === 'string' || typeof peerObj.id === 'number') {
        guest.appPeerId = String(peerObj.id);
        const persistedRole = this.peerRoles.get(guest.appPeerId);
        if (persistedRole) {
          guest.role = persistedRole;
        }
      }
      guest.joined = true;
      guest.lastIncrementalReplayedFromSeq = null;

      const isReconnect = parsed.isReconnect === true;
      const sinceSeq =
        typeof parsed.sinceSeq === 'number' && Number.isSafeInteger(parsed.sinceSeq)
          ? parsed.sinceSeq
          : undefined;
      if (isReconnect && sinceSeq !== undefined && this.canIncrementalCatchUp(sinceSeq)) {
        guest.pendingReconnectSinceSeq = sinceSeq;
        guest.syncing = true;
        guest.live = false;
      } else {
        guest.pendingReconnectSinceSeq = null;
      }
    }

    // Strict pre-join & role enforcement on the authoritative Host Hub
    if (!guest.joined && type !== 'JOIN_REQUEST' && type !== 'PEER_LEFT') {
      this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Must join room before sending actions');
      return;
    }

    if (HOST_ONLY_MODERATION_TYPES.has(type)) {
      this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Only the Host can moderate participants');
      return;
    }

    if (type === 'STATE_CHECKSUM_AUDIT') {
      // Only the Host may emit authoritative state integrity checksums
      return;
    }

    if (guest.role === 'viewer' && !VIEWER_ALLOWED_JSON_TYPES.has(type)) {
      this.sendAccessDeniedToGuest(guest, 'VIEWER_READONLY', 'Viewers have read-only access');
      return;
    }

    // Serve BRUSH_ASSET_REQUEST directly from Host Hub cache on cache hit
    if (type === 'BRUSH_ASSET_REQUEST' && typeof parsed.hash === 'string') {
      const cached = this.getCachedBrushAsset(parsed.hash);
      if (cached) {
        this.sendBinaryToGuest(guest, cached, false);
        return;
      }
    }

    // Serve incremental DOC_SYNC_REQUEST directly from Host Hub op_log when within window
    if (
      type === 'DOC_SYNC_REQUEST' &&
      typeof parsed.sinceSeq === 'number' &&
      this.canIncrementalCatchUp(parsed.sinceSeq)
    ) {
      guest.live = false;
      guest.syncing = true;
      this.replayOpLogEntriesToGuest(guest, parsed.sinceSeq);
      if (!guest.closed) {
        guest.syncing = false;
        guest.live = true;
      }
      return;
    }

    const guestPeerId = guest.appPeerId || guest.signalingPeerId;

    // Layer ownership & lock enforcement matching stateful Rust server
    if (type === 'LAYER_DELETE' && typeof parsed.layerId === 'string') {
      const meta = this.layerLocks.get(parsed.layerId);
      if (meta?.reservedByPeerId && meta.reservedByPeerId !== guestPeerId) {
        this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Layer is locked by its owner');
        return;
      }
      if (meta?.ownerPeerId && meta.ownerPeerId !== guestPeerId) {
        this.sendAccessDeniedToGuest(
          guest,
          'NOT_OWNER',
          'Only the layer owner or Host can delete this layer'
        );
        return;
      }
    } else if (
      (type === 'LAYER_CLEAR' ||
        type === 'LAYER_RENAME' ||
        type === 'LAYER_VISIBILITY' ||
        type === 'LAYER_OPACITY' ||
        type === 'LAYER_UPDATE') &&
      typeof parsed.layerId === 'string'
    ) {
      if (this.isLayerLockedForGuest(parsed.layerId, guestPeerId)) {
        this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Layer is locked by its owner');
        return;
      }
      if (type === 'LAYER_UPDATE') {
        const meta = this.layerLocks.get(parsed.layerId);
        const patch =
          parsed.patch && typeof parsed.patch === 'object'
            ? (parsed.patch as Record<string, unknown>)
            : null;
        if (
          patch?.reservedByPeerId !== undefined &&
          patch.reservedByPeerId !== null &&
          patch.reservedByPeerId !== '' &&
          String(patch.reservedByPeerId) !== guestPeerId
        ) {
          this.sendAccessDeniedToGuest(
            guest,
            'FORBIDDEN',
            'Cannot lock layer under another peer ID'
          );
          return;
        }
        if (
          meta?.ownerPeerId &&
          meta.ownerPeerId !== guestPeerId &&
          (patch?.ownerPeerId !== undefined ||
            (Array.isArray(parsed.clearedFields) && parsed.clearedFields.includes('ownerPeerId')))
        ) {
          this.sendAccessDeniedToGuest(guest, 'NOT_OWNER', 'Cannot reassign layer ownership');
          return;
        }
      }
    } else if (type === 'LAYER_TREE_SYNC' && Array.isArray(parsed.layers)) {
      const incomingById = new Map<string, Record<string, unknown>>();
      for (const rawItem of parsed.layers) {
        if (rawItem && typeof rawItem === 'object') {
          const item = rawItem as Record<string, unknown>;
          if (typeof item.id === 'string') incomingById.set(item.id, item);
        }
      }
      for (const [layerId, meta] of this.layerLocks.entries()) {
        const nextItem = incomingById.get(layerId);
        if (!nextItem) {
          if (meta.reservedByPeerId && meta.reservedByPeerId !== guestPeerId) {
            this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Cannot delete a locked layer');
            return;
          }
          if (meta.ownerPeerId && meta.ownerPeerId !== guestPeerId) {
            this.sendAccessDeniedToGuest(guest, 'NOT_OWNER', 'Cannot delete another user layer');
            return;
          }
        } else if (meta.reservedByPeerId && meta.reservedByPeerId !== guestPeerId) {
          const nextReserved =
            nextItem.reservedByPeerId !== undefined &&
            nextItem.reservedByPeerId !== null &&
            nextItem.reservedByPeerId !== ''
              ? String(nextItem.reservedByPeerId)
              : undefined;
          if (nextReserved !== meta.reservedByPeerId) {
            this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Cannot unlock another user layer');
            return;
          }
        }
      }
    }

    this.applyLayerLockMutation(parsed);

    const authoritativeSenderId =
      guest.appPeerId ||
      (typeof parsed.senderId === 'string' || typeof parsed.senderId === 'number'
        ? String(parsed.senderId)
        : guest.signalingPeerId);
    const seq = ++this.seq;
    const senderMatches =
      parsed.senderId !== undefined &&
      parsed.senderId !== null &&
      String(parsed.senderId) === authoritativeSenderId;

    let sequenced: string;
    if (senderMatches && !('seq' in parsed)) {
      const injected = injectSeqIntoJsonObject(rawText, seq);
      sequenced =
        injected !== null
          ? injected
          : ((parsed.senderId = authoritativeSenderId), (parsed.seq = seq), JSON.stringify(parsed));
    } else {
      parsed.senderId = authoritativeSenderId;
      parsed.seq = seq;
      sequenced = JSON.stringify(parsed);
    }

    if (!HOST_ONLY_CONSUME_TYPES.has(type) && OP_LOG_TEXT_TYPES.has(type)) {
      this.pushOpLog(seq, 'text', sequenced, authoritativeSenderId);
    }

    // Deliver locally to the Host's multiplayerService
    this.textHandlers.forEach((h) => h(sequenced));

    // Relay to all other live guests unless this is a Host-consumed handshake message
    if (!HOST_ONLY_CONSUME_TYPES.has(type)) {
      const ephemeral = EPHEMERAL_TEXT_TYPES.has(type);
      this.broadcastText(sequenced, guest.signalingPeerId, { ephemeral });
    }
  }

  private handleGuestBinaryMessage(guest: GuestConnection, buf: ArrayBuffer): void {
    const bytes = new Uint8Array(buf);
    if (bytes.byteLength < 11 || bytes[0] !== BINARY_MAGIC_0 || bytes[1] !== BINARY_MAGIC_1) {
      return;
    }

    const opcode = bytes[2];
    if (!KNOWN_BINARY_OPCODES.has(opcode)) {
      return;
    }
    const isPreJoinAllowedBinary =
      opcode === CODE_CURSOR_MOVE ||
      opcode === CODE_BRUSH_ASSET_REQUEST ||
      opcode === CODE_BRUSH_PROFILE_REQUEST ||
      opcode === CODE_PING ||
      opcode === CODE_PONG;
    const isViewerAllowedBinary =
      isPreJoinAllowedBinary ||
      opcode === CODE_CAMERA_SYNC ||
      opcode === CODE_BRUSH_ASSET_DATA ||
      opcode === CODE_BRUSH_PROFILE_DATA;

    if (!guest.joined && !isPreJoinAllowedBinary) {
      this.sendAccessDeniedToGuest(guest, 'FORBIDDEN', 'Must join room before drawing');
      return;
    }

    if (guest.role === 'viewer' && !isViewerAllowedBinary) {
      this.sendAccessDeniedToGuest(guest, 'VIEWER_READONLY', 'Viewers have read-only access');
      return;
    }

    // Immediate RTT PING -> PONG echo without seq bump, op_log, or room broadcast
    if (opcode === CODE_PING) {
      const pong = buildPongPacketFromPing(bytes);
      if (pong) {
        this.sendBinaryToGuest(guest, pong, true);
      }
      return;
    }
    if (opcode === CODE_PONG) {
      const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      const payloadLen = view.getUint32(7, true);
      if (payloadLen === PING_PAYLOAD_BYTES && 11 + payloadLen <= bytes.byteLength) {
        this.binaryHandlers.forEach((h) => h(buf));
      }
      return;
    }

    const guestPeerId = guest.appPeerId || guest.signalingPeerId;

    if (
      opcode === CODE_STROKE_START ||
      opcode === CODE_STROKE_FINISH ||
      opcode === CODE_TILE_DELTA ||
      opcode === CODE_LAYER_MASK_DATA
    ) {
      const layerId = this.extractBinaryLayerId(bytes, opcode);
      if (layerId && this.isLayerLockedForGuest(layerId, guestPeerId)) {
        this.sendAccessDeniedToGuest(guest, 'LAYER_LOCKED', 'Layer is locked by its owner');
        return;
      }
    }

    // Serve BRUSH_ASSET_REQUEST unicast directly from Host Hub cache on hit
    if (opcode === CODE_BRUSH_ASSET_REQUEST) {
      const hash = extractBrushAssetRequestHash(bytes);
      if (hash) {
        const cached = this.getCachedBrushAsset(hash);
        if (cached) {
          this.sendBinaryToGuest(guest, cached, false);
          return;
        }
      }
    }

    // Serve BRUSH_PROFILE_REQUEST unicast directly from Host Hub cache on hit
    if (opcode === CODE_BRUSH_PROFILE_REQUEST) {
      const hash = extractBrushProfileRequestHash(bytes);
      if (hash) {
        const cached = this.getCachedBrushProfile(hash);
        if (cached) {
          this.sendBinaryToGuest(guest, cached, false);
          return;
        }
      }
    }

    // Validate and compose SUBRECT_LZ4 tile deltas BEFORE advancing authoritative seq
    let tileMeta: BinaryTileMeta | null = null;
    let composedTilePacket: Uint8Array | null = null;
    if (opcode === CODE_TILE_DELTA) {
      tileMeta = extractBinaryTileMeta(bytes);
      if (tileMeta && tileMeta.codec === TILE_CODEC_SUBRECT_LZ4) {
        const baseWire = this.tileBasePackets.get(tileMeta.key);
        if (!baseWire) return;
        const baseMeta = extractBinaryTileMeta(baseWire);
        if (!baseMeta) return;
        composedTilePacket = composeSubRectOntoTilePacket(
          tileMeta.layerId,
          baseWire.subarray(baseMeta.tilePacketOffset, baseMeta.payloadEnd),
          bytes.subarray(tileMeta.tilePacketOffset, tileMeta.payloadEnd)
        );
        if (!composedTilePacket) return;
      }
    }

    // Stamp authoritative monotonic seq directly in place on the reassembler-owned buffer (0 extra copies)
    const seq = ++this.seq;
    new DataView(buf).setUint32(3, seq, true);

    if (opcode === CODE_BRUSH_ASSET_DATA) {
      const hash = extractBrushAssetDataHash(bytes);
      if (hash) {
        this.cacheBrushAsset(hash, bytes);
      }
    } else if (opcode === CODE_BRUSH_PROFILE_DATA) {
      const hash = extractBrushProfileDataHash(bytes);
      if (hash) {
        this.cacheBrushProfile(hash, bytes);
      }
    } else if (opcode === CODE_TILE_DELTA) {
      if (tileMeta && composedTilePacket) {
        const storedFull = buildWireTileDeltaPacket(
          tileMeta.layerIdBytes,
          composedTilePacket,
          seq
        );
        this.recordTileBasePacket(tileMeta.key, storedFull);
        this.pushOpLog(seq, 'binary', storedFull, guestPeerId, tileMeta.key);
      } else {
        if (tileMeta) {
          if (tileMeta.codec === TILE_CODEC_EMPTY) {
            this.deleteTileBasePacket(tileMeta.key);
          } else if (
            tileMeta.codec === TILE_CODEC_RAW ||
            tileMeta.codec === TILE_CODEC_LZ4 ||
            tileMeta.codec === TILE_CODEC_SOLID
          ) {
            this.recordTileBasePacket(tileMeta.key, bytes);
          }
        }
        this.pushOpLog(seq, 'binary', bytes, guestPeerId, tileMeta?.key);
      }
    } else if (isOpLogEligibleBinaryOpcode(opcode)) {
      if (opcode === CODE_STROKE_START) {
        const extractedProfile = extractBrushProfilePacketFromStrokeStart(bytes, seq);
        if (extractedProfile) {
          this.cacheBrushProfile(extractedProfile.hash, extractedProfile.packet);
        }
      }
      this.pushOpLog(seq, 'binary', bytes, guestPeerId);
    }

    // Deliver locally to the Host's multiplayerService
    this.binaryHandlers.forEach((h) => h(buf));

    // Relay once-encoded frames to all other live guests (star topology)
    const ephemeral =
      opcode === CODE_CURSOR_MOVE ||
      opcode === CODE_CAMERA_SYNC ||
      opcode === CODE_PING ||
      opcode === CODE_PONG;
    this.broadcastBinary(bytes, guest.signalingPeerId, { ephemeral });
  }

  private removeGuest(signalingPeerId: string, notifyDisconnect: boolean): void {
    const guest = this.guests.get(signalingPeerId);
    if (!guest || guest.closed) return;
    guest.closed = true;
    guest.live = false;
    guest.syncing = false;
    if (guest.disconnectTimer !== null) {
      clearTimeout(guest.disconnectTimer);
      guest.disconnectTimer = null;
    }
    this.guests.delete(signalingPeerId);
    if (guest.sender) {
      this.retiredDroppedEphemeralCount += guest.sender.getDroppedEphemeralCount();
      guest.sender.dispose();
    }
    guest.reassembler?.clear();
    guest.ephemeralReassembler?.clear();

    try {
      if (guest.dc) {
        guest.dc.onmessage = null;
        guest.dc.onclose = null;
        guest.dc.onerror = null;
        guest.dc.close();
      }
    } catch {
      // ignore
    }
    guest.dc = null;

    try {
      if (guest.ephemeralDc) {
        guest.ephemeralDc.onmessage = null;
        guest.ephemeralDc.onclose = null;
        guest.ephemeralDc.onerror = null;
        guest.ephemeralDc.close();
      }
    } catch {
      // ignore
    }
    guest.ephemeralDc = null;

    try {
      guest.pc.onicecandidate = null;
      guest.pc.ondatachannel = null;
      guest.pc.onconnectionstatechange = null;
      guest.pc.close();
    } catch {
      // ignore
    }

    if (notifyDisconnect && guest.appPeerId && !this.closed) {
      const seq = ++this.seq;
      const discJson = JSON.stringify({
        type: 'PEER_DISCONNECTED',
        peerId: guest.appPeerId,
        seq,
      });
      this.pushOpLog(seq, 'text', discJson);
      this.textHandlers.forEach((h) => h(discJson));
      this.broadcastText(discJson);
    }
  }

  public onTextMessage(handler: (text: string) => void): () => void {
    this.textHandlers.add(handler);
    return () => this.textHandlers.delete(handler);
  }

  public onBinaryMessage(handler: (data: ArrayBuffer) => void): () => void {
    this.binaryHandlers.add(handler);
    return () => this.binaryHandlers.delete(handler);
  }

  public onClose(handler: (reason?: string) => void): () => void {
    this.closeHandlers.add(handler);
    return () => this.closeHandlers.delete(handler);
  }

  public onError(handler: (err: Error | Event) => void): () => void {
    this.errorHandlers.add(handler);
    return () => this.errorHandlers.delete(handler);
  }

  public close(): void {
    if (this.closed) return;
    this.closed = true;
    this.open = false;

    try {
      this.signaling.send({
        type: 'bye',
        fromPeerId: this.hostPeerId,
        reason: 'Host closed the room',
      });
    } catch {
      // ignore
    }

    for (const id of Array.from(this.guests.keys())) {
      this.removeGuest(id, false);
    }

    this.opLog.length = 0;
    this.opLogHead = 0;
    this.opLogBytes = 0;
    this.tileLatestSeq.clear();
    this.clearTileBasePackets();
    this.brushAssetCache.clear();
    this.brushAssetCacheBytes = 0;
    this.brushProfileCache.clear();
    this.brushProfileCacheBytes = 0;
    this.retiredDroppedEphemeralCount = 0;

    this.unsubSignaling?.();
    this.unsubSignaling = null;
    this.signaling.close();
    this.closeHandlers.forEach((h) => h('Host closed the P2P room'));
  }
}