Skip to content

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

31.6 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
  BINARY_MAGIC_0,
  BINARY_MAGIC_1,
  CODE_BRUSH_ASSET_DATA,
  CODE_CAMERA_SYNC,
  multiplayerService,
  sanitizeIncomingJsonMessage,
} from '../../services/multiplayerService';
import { WebRtcHostHub } from '../../services/webrtcHostHub';
import {
  ChunkReassembler,
  encodeTransportFrames,
} from '../../services/collabTransport';
import {
  computeBrushAssetHash,
  hydrateBrushSettingsForLocalUse,
  registerRemoteBrushAsset,
  resetBrushAssetCache,
} from '../brushAssetSync';
import {
  buildCameraSyncSnapshot,
  buildSaveableCspBrush,
  buildTryBrushSettings,
  computeFollowedCameraTransform,
  hasSignificantCameraDelta,
  resolveBrushDisplayName,
  stepInterpolatedFollowCamera,
} from '../collabFeatures';
import { toolStoreActions, useToolStore } from '../../stores';
import { CollabRoomOverlay } from '../../components/CollabRoomOverlay';
import { HostModal } from '../../components/HostModal';
import type { BrushSettings, CanvasDimensions } from '../../types/editor';
import type {
  CollabChatMessage,
  CollabPeer,
  CollabPeerCamera,
} from '../../types/multiplayer';
import type { ISignalingClient } from '../../services/webrtcSignaling';

const TINY_PNG_B64 =
  'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
const TINY_PNG_DATA_URL = `data:image/png;base64,${TINY_PNG_B64}`;

// Distinct valid 1x1 PNG (red pixel) for dual-tip / paper texture testing
const TINY_RED_PNG_B64 =
  'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==';
const TINY_RED_PNG_DATA_URL = `data:image/png;base64,${TINY_RED_PNG_B64}`;

function toArrayBuffer(u8: Uint8Array): ArrayBuffer {
  return u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer;
}

// --- Minimal DOM shim for React component tests (matching hostModal.test.tsx) ---

class TestTextNode {
  public nodeType = 3;
  public nodeName = '#text';
  public parentNode: TestElement | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: TestDocument
  ) {}
}

class TestElement extends EventTarget {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI = 'http://www.w3.org/1999/xhtml';
  public parentNode: TestElement | null = null;
  public childNodes: Array<TestElement | TestTextNode> = [];
  public style: Record<string, string> = {};
  public attributes = new Map<string, string>();
  public value = '';
  public disabled = false;
  public type = '';
  public placeholder = '';
  public className = '';
  public blurred = false;

  constructor(
    tag: string,
    public ownerDocument: TestDocument
  ) {
    super();
    this.nodeName = tag.toUpperCase();
    this.tagName = this.nodeName;
  }

  blur() {
    this.blurred = true;
  }

  scrollIntoView() {}

  appendChild<T extends TestElement | TestTextNode>(child: T): T {
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }

  removeChild<T extends TestElement | TestTextNode>(child: T): T {
    const idx = this.childNodes.indexOf(child);
    if (idx >= 0) this.childNodes.splice(idx, 1);
    child.parentNode = null;
    return child;
  }

  insertBefore<T extends TestElement | TestTextNode>(
    child: T,
    ref: TestElement | TestTextNode | null
  ): T {
    child.parentNode = this;
    const idx = ref ? this.childNodes.indexOf(ref) : -1;
    if (idx >= 0) this.childNodes.splice(idx, 0, child);
    else this.childNodes.push(child);
    return child;
  }

  setAttribute(name: string, val: string) {
    this.attributes.set(name, String(val));
    if (name === 'placeholder') this.placeholder = String(val);
    if (name === 'type') this.type = String(val);
    if (name === 'value') this.value = String(val);
  }

  removeAttribute(name: string) {
    this.attributes.delete(name);
  }

  getAttribute(name: string): string | null {
    return this.attributes.has(name) ? this.attributes.get(name)! : null;
  }

  get textContent(): string {
    return this.childNodes
      .map((c) => (c instanceof TestTextNode ? c.nodeValue : c.textContent))
      .join('');
  }

  set textContent(v: string) {
    this.childNodes = [];
    if (v) this.appendChild(new TestTextNode(v, this.ownerDocument));
  }

  override dispatchEvent(event: Event): boolean {
    const path: EventTarget[] = [];
    let cur: TestElement | null = this;
    while (cur) {
      path.push(cur);
      cur = cur.parentNode;
    }
    path.push(this.ownerDocument);
    if (this.ownerDocument.defaultView && this.ownerDocument.defaultView instanceof EventTarget) {
      path.push(this.ownerDocument.defaultView);
    }

    Object.defineProperty(event, 'target', { value: this, configurable: true });
    for (const node of path) {
      Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });
      EventTarget.prototype.dispatchEvent.call(node, event);
      if (event.cancelBubble) break;
    }
    return !event.defaultPrevented;
  }
}

class TestDocument extends EventTarget {
  public nodeType = 9;
  public activeElement: TestElement | null = null;
  public defaultView: unknown = null;
  public documentElement: TestElement;
  public body: TestElement;

  constructor() {
    super();
    this.documentElement = new TestElement('html', this);
    this.body = new TestElement('body', this);
    this.documentElement.appendChild(this.body);
  }

  createElement(tag: string): TestElement {
    return new TestElement(tag, this);
  }

  createElementNS(_ns: string, tag: string): TestElement {
    return new TestElement(tag, this);
  }

  createTextNode(text: string): TestTextNode {
    return new TestTextNode(text, this);
  }

  createComment(): TestTextNode {
    return new TestTextNode('', this);
  }
}

function findAll(root: TestElement, pred: (el: TestElement) => boolean): TestElement[] {
  const out: TestElement[] = [];
  const walk = (node: TestElement | TestTextNode) => {
    if (node instanceof TestElement) {
      if (pred(node)) out.push(node);
      for (const child of node.childNodes) walk(child);
    }
  };
  walk(root);
  return out;
}

function findByTestId(root: TestElement, testId: string): TestElement | undefined {
  return findAll(root, (el) => el.getAttribute('data-testid') === testId)[0];
}

function clickElement(el: TestElement) {
  el.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
}

// =========================================================================
// 1. FOLLOW CAMERA MATH & BINARY PROTOCOL TESTS
// =========================================================================

describe('Follow Camera Math & CODE_CAMERA_SYNC Binary Protocol', () => {
  const dims: CanvasDimensions = { width: 2000, height: 1500 };

  it('round-trips viewport camera -> document center -> follower camera across pan, zoom, rotation, and view flips', () => {
    const senderCam = {
      pan: { x: 412, y: 278 },
      zoom: 1.75,
      rotation: -33.5,
      flipX: true,
      flipY: false,
    };
    const snap = buildCameraSyncSnapshot(senderCam, 1280, 720, dims);
    const followed = computeFollowedCameraTransform(snap, 1280, 720, dims);

    expect(followed.zoom).toBeCloseTo(senderCam.zoom, 5);
    expect(followed.rotation).toBeCloseTo(senderCam.rotation, 5);
    expect(followed.flipX).toBe(true);
    expect(followed.flipY).toBe(false);
    expect(followed.pan.x).toBeCloseTo(senderCam.pan.x, 3);
    expect(followed.pan.y).toBeCloseTo(senderCam.pan.y, 3);
  });

  it('adapts zoom proportionally for smaller browser/tablet viewports while centering on the exact same document point', () => {
    const teacherSnap: CollabPeerCamera = {
      centerX: 1350,
      centerY: 620,
      zoom: 2.0,
      rotation: 15,
      flipX: false,
      flipY: false,
      viewportWidth: 1600,
      viewportHeight: 900,
      updatedAt: Date.now(),
    };

    // Student has half-size viewport (800x450) -> zoom adapts to 1.0x so nothing is clipped
    const studentCam = computeFollowedCameraTransform(teacherSnap, 800, 450, dims);
    expect(studentCam.zoom).toBeCloseTo(1.0, 4);
    expect(studentCam.rotation).toBeCloseTo(15, 4);

    // Re-project student viewport center back to document space -> exact match!
    const reprojected = buildCameraSyncSnapshot(studentCam, 800, 450, dims);
    expect(reprojected.centerX).toBeCloseTo(1350, 2);
    expect(reprojected.centerY).toBeCloseTo(620, 2);
  });

  it('smoothly interpolates Follow Camera with shortest-angle rotation wrap', () => {
    const current = {
      pan: { x: 640, y: 360 },
      zoom: 1.0,
      rotation: 175,
      flipX: false,
      flipY: false,
    };
    const target: CollabPeerCamera = {
      centerX: 1100,
      centerY: 800,
      zoom: 2.0,
      rotation: -175, // 10 degrees clockwise past 175, NOT -350 degrees!
      flipX: false,
      flipY: false,
      viewportWidth: 1280,
      viewportHeight: 720,
      updatedAt: Date.now(),
    };

    const { next, settled } = stepInterpolatedFollowCamera(
      current,
      target,
      1280,
      720,
      dims,
      0.016
    );
    expect(settled).toBe(false);
    // Rotation must advance smoothly across the +180/-180 wrap, not swing backwards toward 0
    expect(next.rotation).toBeGreaterThan(175);
    expect(next.zoom).toBeGreaterThan(1.0);
    expect(next.zoom).toBeLessThan(2.0);
  });

  it('detects significant camera deltas and suppresses no-op camera churn', () => {
    const base = {
      centerX: 1000,
      centerY: 750,
      zoom: 1.0,
      rotation: 0,
      flipX: false,
      flipY: false,
      viewportWidth: 1280,
      viewportHeight: 720,
    };
    expect(hasSignificantCameraDelta(null, base)).toBe(true);
    expect(hasSignificantCameraDelta(base, { ...base })).toBe(false);
    expect(hasSignificantCameraDelta(base, { ...base, centerX: 1000.05 })).toBe(false);
    expect(hasSignificantCameraDelta(base, { ...base, centerX: 1002 })).toBe(true);
    expect(hasSignificantCameraDelta(base, { ...base, flipX: true })).toBe(true);
  });

  it('encodes and decodes compact binary CODE_CAMERA_SYNC packets losslessly', () => {
    const sentPackets: Uint8Array[] = [];
    const sendSpy = vi
      .spyOn(multiplayerService, 'sendBinary')
      .mockImplementation((buf) => {
        sentPackets.push(buf instanceof Uint8Array ? buf : new Uint8Array(buf));
      });
    const connSpy = vi.spyOn(multiplayerService, 'isConnected').mockReturnValue(true);
    (multiplayerService as unknown as { currentPeer: unknown }).currentPeer = {
      id: 'teacher-1',
      name: 'Sensei',
      color: '#3b82f6',
    };

    multiplayerService.sendCameraSync(
      {
        centerX: 842.5,
        centerY: 519.25,
        zoom: 2.5,
        rotation: -22.5,
        flipX: true,
        flipY: false,
        viewportWidth: 1440,
        viewportHeight: 900,
      },
      true
    );

    expect(sentPackets).toHaveLength(1);
    expect(sentPackets[0][0]).toBe(BINARY_MAGIC_0);
    expect(sentPackets[0][1]).toBe(BINARY_MAGIC_1);
    expect(sentPackets[0][2]).toBe(CODE_CAMERA_SYNC);

    const decoded = multiplayerService.decodeBinaryPacket(toArrayBuffer(sentPackets[0]));
    expect(decoded).toMatchObject({
      type: 'CAMERA_SYNC',
      peerId: 'teacher-1',
      centerX: 842.5,
      centerY: 519.25,
      zoom: 2.5,
      rotation: -22.5,
      flipX: true,
      flipY: false,
      viewportWidth: 1440,
      viewportHeight: 900,
    });

    sendSpy.mockRestore();
    connSpy.mockRestore();
    (multiplayerService as unknown as { currentPeer: unknown }).currentPeer = null;
  });
});

// =========================================================================
// 2. ROOM TEXT CHAT & GRAB AN ARTIST'S BRUSH PROTOCOL TESTS
// =========================================================================

describe('Room Text Chat & Grab Artist Brush Protocol', () => {
  beforeEach(() => {
    resetBrushAssetCache();
  });

  it('sanitizes incoming CHAT_MESSAGE, CAMERA_SYNC_REQUEST, BRUSH_REQUEST, and BRUSH_SHARE strictly', () => {
    // Reject empty/whitespace chat
    expect(sanitizeIncomingJsonMessage({ type: 'CHAT_MESSAGE', text: '   \n  ' })).toBeNull();

    // Clamp overly long chat text & sanitize bad color
    const chat = sanitizeIncomingJsonMessage({
      type: 'CHAT_MESSAGE',
      senderId: 'peer-2',
      id: 'msg-1',
      senderName: 'Mika',
      senderColor: 'javascript:alert(1)',
      text: `  Hello\r\nworld! ${'a'.repeat(1500)}`,
      timestamp: 1700000000000,
    });
    expect(chat?.type).toBe('CHAT_MESSAGE');
    if (chat?.type === 'CHAT_MESSAGE') {
      expect(chat.text.length).toBe(1000);
      expect(chat.text.startsWith('Hello\nworld!')).toBe(true);
      expect(chat.senderColor).toBe('#38bdf8');
    }

    // CAMERA_SYNC_REQUEST & BRUSH_REQUEST
    expect(
      sanitizeIncomingJsonMessage({ type: 'CAMERA_SYNC_REQUEST', targetPeerId: 'host-1' })
    ).toMatchObject({ type: 'CAMERA_SYNC_REQUEST', targetPeerId: 'host-1' });
    expect(
      sanitizeIncomingJsonMessage({ type: 'CAMERA_SYNC_REQUEST', targetPeerId: '' })
    ).toBeNull();

    expect(
      sanitizeIncomingJsonMessage({ type: 'BRUSH_REQUEST', targetPeerId: 'artist-9' })
    ).toMatchObject({ type: 'BRUSH_REQUEST', targetPeerId: 'artist-9' });

    // BRUSH_SHARE strips inline base64 data URLs and keeps sanitized asset refs
    const validHash = 'a'.repeat(32);
    const share = sanitizeIncomingJsonMessage({
      type: 'BRUSH_SHARE',
      peerId: 'artist-9',
      peerName: 'Aoi',
      brushName: 'Ink Nib',
      tool: 'brush',
      brushSettings: {
        size: 18,
        minSizeFactor: 0.1,
        color: '#000',
        opacity: 0.9,
        flow: 0.85,
        spacing: 0.06,
        usePressure: true,
        smoothing: true,
        stabilization: 12,
        hardness: 0.95,
        customTipDataUrl: TINY_PNG_DATA_URL,
      },
      brushAssetRefs: { tipHash: validHash },
      explicit: true,
    });
    expect(share?.type).toBe('BRUSH_SHARE');
    if (share?.type === 'BRUSH_SHARE') {
      expect(share.brushSettings.customTipDataUrl).toBeUndefined();
      expect(share.brushAssetRefs?.tipHash).toBe(validHash);
      expect(share.explicit).toBe(true);
    }
  });

  it('transmits brush tips, dual tips, and paper textures via BRUSH_ASSET_DATA and hydrates full local BrushSettings', () => {
    const sentBinaries: Uint8Array[] = [];
    const sentJsons: unknown[] = [];
    const binSpy = vi
      .spyOn(multiplayerService, 'sendBinary')
      .mockImplementation((buf) => {
        sentBinaries.push(buf instanceof Uint8Array ? buf : new Uint8Array(buf));
      });
    const msgSpy = vi
      .spyOn(multiplayerService, 'sendMessage')
      .mockImplementation((msg) => {
        sentJsons.push(msg);
      });
    const connSpy = vi.spyOn(multiplayerService, 'isConnected').mockReturnValue(true);
    (multiplayerService as unknown as { currentPeer: unknown }).currentPeer = {
      id: 'artist-a',
      name: 'Haru',
      color: '#10b981',
    };

    const sourceBrush: BrushSettings = {
      preset: 'csp-custom-99',
      brushName: 'Haru Charcoal',
      size: 28,
      minSizeFactor: 0.08,
      color: '#ff0000',
      opacity: 0.88,
      flow: 0.75,
      spacing: 0.09,
      usePressure: true,
      smoothing: true,
      stabilization: 16,
      hardness: 0.6,
      customTipDataUrl: TINY_PNG_DATA_URL,
      paperTexture: TINY_RED_PNG_DATA_URL,
      dualBrush: true,
      dualBrushConfig: {
        enabled: true,
        compositeMode: 'multiply',
        tipDataUrl: TINY_RED_PNG_DATA_URL,
      },
    };

    const shareMsg = multiplayerService.sendBrushShare(sourceBrush, 'brush', 'Haru Charcoal', {
      targetPeerId: 'guest-b',
      explicit: false,
      forceAssets: true,
    });

    expect(shareMsg).not.toBeNull();
    // 2 unique PNG assets sent via binary BRUSH_ASSET_DATA (TINY_PNG + TINY_RED_PNG deduplicated)
    expect(sentBinaries).toHaveLength(2);
    expect(sentBinaries[0][2]).toBe(CODE_BRUSH_ASSET_DATA);
    expect(sentBinaries[1][2]).toBe(CODE_BRUSH_ASSET_DATA);
    expect(sentJsons).toHaveLength(1);
    expect(shareMsg!.brushSettings.customTipDataUrl).toBeUndefined();
    expect(shareMsg!.brushSettings.paperTexture).toBeUndefined();
    expect(shareMsg!.brushSettings.dualBrushConfig?.tipDataUrl).toBeUndefined();

    // Simulate clean receiving peer: wipe cache, ingest binary BRUSH_ASSET_DATA packets, hydrate for local use
    resetBrushAssetCache();
    for (const pkt of sentBinaries) {
      const decoded = multiplayerService.decodeBinaryPacket(toArrayBuffer(pkt));
      expect(decoded?.type).toBe('BRUSH_ASSET_DATA');
      if (decoded?.type === 'BRUSH_ASSET_DATA') {
        expect(registerRemoteBrushAsset(decoded.hash, decoded.mime, decoded.data)).toBe(true);
        expect(computeBrushAssetHash(decoded.data)).toBe(decoded.hash);
      }
    }

    const { hydrated, missingHashes } = hydrateBrushSettingsForLocalUse(
      shareMsg!.brushSettings,
      shareMsg!.brushAssetRefs
    );
    expect(missingHashes).toEqual([]);
    expect(hydrated.customTipDataUrl).toBe(TINY_PNG_DATA_URL);
    expect(hydrated.paperTexture).toBe(TINY_RED_PNG_DATA_URL);
    expect(hydrated.dualTipDataUrl).toBe(TINY_RED_PNG_DATA_URL);
    expect(hydrated.dualBrushConfig?.tipDataUrl).toBe(TINY_RED_PNG_DATA_URL);

    // Equip non-destructively via buildTryBrushSettings + toolStoreActions.applySharedBrush
    const prevPrimary = useToolStore.getState().primaryColor;
    toolStoreActions.setPrimaryColor('#123456', false, 'color');
    const trySettings = buildTryBrushSettings({
      hydratedSettings: hydrated,
      brushAssetRefs: shareMsg!.brushAssetRefs,
      peerId: 'artist-a',
      peerName: 'Haru',
      brushName: 'Haru Charcoal',
      localPrimaryColor: '#123456',
      localSecondaryColor: '#ffffff',
      localIsTransparentInk: false,
    });
    expect(trySettings.preset).toMatch(/^collab-shared-/);
    expect(trySettings.brushName).toBe('Haru Charcoal (Haru)');
    expect(trySettings.color).toBe('#123456'); // Keeps local artist's active color!
    expect(trySettings.customTipDataUrl).toBe(TINY_PNG_DATA_URL);

    toolStoreActions.applySharedBrush(trySettings, 'brush');
    expect(useToolStore.getState().tool).toBe('brush');
    expect(useToolStore.getState().brushSettings.preset).toBe(trySettings.preset);
    expect(useToolStore.getState().brushSettings.customTipDataUrl).toBe(TINY_PNG_DATA_URL);

    // Convert to persistent CspBrush cleanly
    const cspBrush = buildSaveableCspBrush(trySettings, trySettings.brushName!);
    expect(cspBrush.tipDataUrl).toBe(TINY_PNG_DATA_URL);
    expect(cspBrush.paperTexture).toBe(TINY_RED_PNG_DATA_URL);
    expect(cspBrush.secondaryTipDataUrl).toBe(TINY_RED_PNG_DATA_URL);
    expect(resolveBrushDisplayName({ preset: 'g-pen' })).toBe('G-Pen');

    toolStoreActions.setPrimaryColor(prevPrimary, false, 'color');
    binSpy.mockRestore();
    msgSpy.mockRestore();
    connSpy.mockRestore();
    (multiplayerService as unknown as { currentPeer: unknown }).currentPeer = null;
  });

  it('allows Viewers over WebRTC Host Hub to chat, sync/request camera, and grab/share brush assets while still blocking strokes', () => {
    const fakeSignaling: ISignalingClient = {
      connect: vi.fn().mockResolvedValue(undefined),
      send: vi.fn(),
      onMessage: () => () => {},
      onError: () => () => {},
      close: vi.fn(),
    };

    const hub = new WebRtcHostHub({
      roomHash: 'a'.repeat(64),
      hostPeerId: 'host-1',
      signalingClient: fakeSignaling,
    });

    const hostReceivedTexts: string[] = [];
    const hostReceivedBins: ArrayBuffer[] = [];
    hub.onTextMessage((t) => hostReceivedTexts.push(t));
    hub.onBinaryMessage((b) => hostReceivedBins.push(b));

    const guestSentFrames: ArrayBuffer[] = [];
    const mockDc = {
      readyState: 'open',
      bufferedAmount: 0,
      send: (buf: ArrayBuffer) => guestSentFrames.push(buf),
      close: vi.fn(),
    } as unknown as RTCDataChannel;

    const mockGuest = {
      signalingPeerId: 'sig-viewer',
      appPeerId: 'viewer-1',
      joined: true,
      role: 'viewer' as const,
      pc: { close: vi.fn() } as unknown as RTCPeerConnection,
      dc: mockDc,
      reassembler: new ChunkReassembler(),
      remoteDescSet: true,
      pendingIce: [],
      localIceCandidates: [],
      lastAnswerSdp: null,
      disconnectTimer: null,
      closed: false,
    };
    (hub as unknown as { guests: Map<string, unknown> }).guests.set('sig-viewer', mockGuest);

    const handleText = (hub as unknown as {
      handleGuestTextMessage: (g: unknown, t: string) => void;
    }).handleGuestTextMessage.bind(hub);
    const handleBin = (hub as unknown as {
      handleGuestBinaryMessage: (g: unknown, b: ArrayBuffer) => void;
    }).handleGuestBinaryMessage.bind(hub);

    // 1. Viewer sends CHAT_MESSAGE -> allowed & delivered to host
    handleText(
      mockGuest,
      JSON.stringify({
        type: 'CHAT_MESSAGE',
        id: 'c-1',
        senderName: 'Student',
        senderColor: '#10b981',
        text: 'Can you zoom in on the eyes?',
        timestamp: Date.now(),
      })
    );
    expect(hostReceivedTexts.some((t) => JSON.parse(t).type === 'CHAT_MESSAGE')).toBe(true);

    // 2. Viewer sends CAMERA_SYNC_REQUEST & BRUSH_REQUEST -> allowed
    handleText(mockGuest, JSON.stringify({ type: 'CAMERA_SYNC_REQUEST', targetPeerId: 'host-1' }));
    handleText(mockGuest, JSON.stringify({ type: 'BRUSH_REQUEST', targetPeerId: 'host-1' }));
    expect(hostReceivedTexts.some((t) => JSON.parse(t).type === 'CAMERA_SYNC_REQUEST')).toBe(true);
    expect(hostReceivedTexts.some((t) => JSON.parse(t).type === 'BRUSH_REQUEST')).toBe(true);

    // 3. Viewer sends binary CODE_CAMERA_SYNC -> allowed
    const camPkt = new Uint8Array(11 + 25);
    camPkt[0] = BINARY_MAGIC_0;
    camPkt[1] = BINARY_MAGIC_1;
    camPkt[2] = CODE_CAMERA_SYNC;
    new DataView(camPkt.buffer).setUint32(7, 25, true);
    handleBin(mockGuest, camPkt.buffer);
    expect(hostReceivedBins).toHaveLength(1);

    // 4. Viewer sends binary STROKE_START -> still strictly blocked with VIEWER_READONLY!
    const strokePkt = new Uint8Array(11 + 4);
    strokePkt[0] = BINARY_MAGIC_0;
    strokePkt[1] = BINARY_MAGIC_1;
    strokePkt[2] = 0x01; // CODE_STROKE_START
    new DataView(strokePkt.buffer).setUint32(7, 4, true);
    handleBin(mockGuest, strokePkt.buffer);
    expect(hostReceivedBins).toHaveLength(1); // Not relayed

    // Verify ACCESS_DENIED (VIEWER_READONLY) was sent back to viewer
    const guestReassembler = new ChunkReassembler();
    let deniedMsg: Record<string, unknown> | null = null;
    for (const frame of guestSentFrames) {
      const assembled = guestReassembler.pushFrame(frame);
      if (assembled?.kind === 'text') {
        const parsed = JSON.parse(assembled.text);
        if (parsed.type === 'ACCESS_DENIED') deniedMsg = parsed;
      }
    }
    expect(deniedMsg?.code).toBe('VIEWER_READONLY');
    // Keep unused import check satisfied
    expect(encodeTransportFrames('text', 'ok', 1).length).toBe(1);
    hub.close();
  });
});

// =========================================================================
// 3. ROOM OVERLAY & HOST MODAL UI INTERACTION TESTS
// =========================================================================

describe('CollabRoomOverlay & HostModal UI (Chat, Follow Camera, Grab Brush)', () => {
  const origWindow = (globalThis as any).window;
  const origDocument = (globalThis as any).document;
  const origHTMLElement = (globalThis as any).HTMLElement;
  const origElement = (globalThis as any).Element;
  const origNode = (globalThis as any).Node;
  const origActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT;

  let doc: TestDocument;
  let container: TestElement;
  let root: Root;

  const myPeer: CollabPeer = {
    id: 'peer-me',
    name: 'Sora',
    color: '#3b82f6',
    isHost: true,
    role: 'host',
  };
  const remotePeer: CollabPeer = {
    id: 'peer-alice',
    name: 'Alice',
    color: '#f43f5e',
    role: 'editor',
    activeBrushName: 'Real G-Pen',
  };

  beforeEach(() => {
    doc = new TestDocument();
    const win: any = new EventTarget();
    win.document = doc;
    doc.defaultView = win;
    class HTMLIFrameElementShim extends TestElement {}
    win.HTMLElement = TestElement;
    win.HTMLIFrameElement = HTMLIFrameElementShim;
    win.Element = TestElement;
    win.Node = TestElement;
    win.navigator = {};
    (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
    (globalThis as any).window = win;
    (globalThis as any).document = doc;
    (globalThis as any).HTMLElement = TestElement;
    (globalThis as any).HTMLIFrameElement = HTMLIFrameElementShim;
    (globalThis as any).Element = TestElement;
    (globalThis as any).Node = TestElement;

    container = doc.createElement('div');
    doc.body.appendChild(container);
    root = createRoot(container as unknown as HTMLElement);
  });

  afterEach(async () => {
    await act(async () => {
      root.unmount();
    });
    (globalThis as any).window = origWindow;
    (globalThis as any).document = origDocument;
    (globalThis as any).HTMLElement = origHTMLElement;
    (globalThis as any).Element = origElement;
    (globalThis as any).Node = origNode;
    (globalThis as any).IS_REACT_ACT_ENVIRONMENT = origActEnv;
  });

  it('supports Follow Camera click, 1-click Try Brush, Share Brush, and Built-in Text Chat in CollabRoomOverlay', async () => {
    const onSendChatMessage = vi.fn().mockReturnValue(true);
    const onChatVisibilityChange = vi.fn();
    const onToggleFollowPeer = vi.fn();
    const onStopFollowing = vi.fn();
    const onGrabPeerBrush = vi.fn();
    const onTrySharedBrush = vi.fn();
    const onShareMyBrush = vi.fn();
    const onSaveGrabbedBrush = vi.fn();

    const chatMessages: CollabChatMessage[] = [
      {
        id: 'm1',
        senderId: 'peer-alice',
        senderName: 'Alice',
        senderColor: '#f43f5e',
        text: 'Watch this lineart pass!',
        timestamp: 1700000000000,
      },
      {
        id: 'm2',
        senderId: 'peer-alice',
        senderName: 'Alice',
        senderColor: '#f43f5e',
        text: 'Shared brush "Ink Wash"',
        timestamp: 1700000005000,
        sharedBrush: {
          peerId: 'peer-alice',
          peerName: 'Alice',
          brushName: 'Ink Wash',
          tool: 'brush',
          brushSettings: {
            size: 20,
            minSizeFactor: 0.1,
            color: '#000',
            opacity: 1,
            flow: 1,
            spacing: 0.08,
            usePressure: true,
            smoothing: true,
            stabilization: 10,
            hardness: 0.9,
          },
        },
      },
    ];

    await act(async () => {
      root.render(
        <CollabRoomOverlay
          isConnected={true}
          myRole="host"
          hostInfo={{
            isRunning: true,
            port: 30303,
            localIp: '127.0.0.1',
            roomName: 'Manga Study',
            inviteUrl: 'https://example.com/?room=Manga',
            peerCount: 2,
          }}
          myPeer={myPeer}
          peers={[remotePeer]}
          chatMessages={chatMessages}
          unreadChatCount={2}
          onSendChatMessage={onSendChatMessage}
          onChatVisibilityChange={onChatVisibilityChange}
          followingPeerId="peer-alice"
          onToggleFollowPeer={onToggleFollowPeer}
          onStopFollowing={onStopFollowing}
          grabbingPeerId={null}
          onGrabPeerBrush={onGrabPeerBrush}
          onTrySharedBrush={onTrySharedBrush}
          onShareMyBrush={onShareMyBrush}
          activeGrabbedBrush={{
            peerId: 'peer-alice',
            peerName: 'Alice',
            brushName: 'Real G-Pen',
            settings: {
              size: 12,
              minSizeFactor: 0.05,
              color: '#000',
              opacity: 1,
              flow: 1,
              spacing: 0.06,
              usePressure: true,
              smoothing: true,
              stabilization: 8,
              hardness: 1,
            },
          }}
          onSaveGrabbedBrush={onSaveGrabbedBrush}
          onDismissGrabbedBrush={vi.fn()}
          onOpenHostModal={vi.fn()}
        />
      );
    });

    // Follow banner + Stop button visible
    expect(findByTestId(container, 'collab-follow-banner')?.textContent).toContain('Alice');
    const stopFollowBtn = findByTestId(container, 'collab-stop-follow-btn')!;
    await act(async () => {
      clickElement(stopFollowBtn);
    });
    expect(onStopFollowing).toHaveBeenCalledTimes(1);

    // Active grabbed brush banner with Save button
    const saveGrabbedBtn = findByTestId(container, 'collab-save-grabbed-brush-btn')!;
    await act(async () => {
      clickElement(saveGrabbedBtn);
    });
    expect(onSaveGrabbedBrush).toHaveBeenCalledTimes(1);

    // Unread chat badge visible while on Participants tab
    expect(findByTestId(container, 'collab-unread-badge')?.textContent).toBe('2');

    // Click participant to toggle Follow Camera
    const followAliceBtn = findByTestId(container, 'collab-follow-peer-peer-alice')!;
    await act(async () => {
      clickElement(followAliceBtn);
    });
    expect(onToggleFollowPeer).toHaveBeenCalledWith('peer-alice');

    // Click "Try Brush" button on Alice
    const grabAliceBtn = findByTestId(container, 'collab-grab-brush-peer-alice')!;
    await act(async () => {
      clickElement(grabAliceBtn);
    });
    expect(onGrabPeerBrush).toHaveBeenCalledWith('peer-alice');

    // Click "Share Brush" button
    const shareBtn = findByTestId(container, 'collab-share-my-brush-btn')!;
    await act(async () => {
      clickElement(shareBtn);
    });
    expect(onShareMyBrush).toHaveBeenCalledTimes(1);

    // Switch to Chat tab -> notifies visibility and shows chat messages + interactive brush card
    const chatTab = findByTestId(container, 'collab-tab-chat')!;
    await act(async () => {
      clickElement(chatTab);
    });
    expect(onChatVisibilityChange).toHaveBeenCalledWith(true);

    const messagesBox = findByTestId(container, 'collab-chat-messages')!;
    expect(messagesBox.textContent).toContain('Watch this lineart pass!');
    expect(messagesBox.textContent).toContain('Ink Wash');

    const tryFromChatBtn = findByTestId(container, 'collab-chat-try-brush-m2')!;
    await act(async () => {
      clickElement(tryFromChatBtn);
    });
    expect(onTrySharedBrush).toHaveBeenCalledWith(chatMessages[1].sharedBrush);
  });

  it('exposes Follow Camera and Try This Users Brush buttons in HostModal participants list', async () => {
    const onToggleFollowPeer = vi.fn();
    const onGrabPeerBrush = vi.fn();
    const onClose = vi.fn();

    await act(async () => {
      root.render(
        <HostModal
          isOpen={true}
          onClose={onClose}
          isHost={true}
          isConnected={true}
          hostInfo={{
            isRunning: true,
            port: 30303,
            localIp: '192.168.1.5',
            roomName: 'Studio',
            inviteUrl: 'http://192.168.1.5:30303/?room=Studio',
            peerCount: 2,
          }}
          peers={[remotePeer]}
          myPeer={myPeer}
          onUpdateMyName={vi.fn()}
          onStartHosting={vi.fn().mockResolvedValue({})}
          onStopHosting={vi.fn()}
          onJoinByInviteUrl={vi.fn().mockResolvedValue(true)}
          onLeaveRoom={vi.fn()}
          onToggleFollowPeer={onToggleFollowPeer}
          onGrabPeerBrush={onGrabPeerBrush}
          showToast={vi.fn()}
        />
      );
    });

    const grabBtn = findByTestId(container, 'host-modal-grab-brush-peer-alice')!;
    expect(grabBtn).toBeDefined();
    await act(async () => {
      clickElement(grabBtn);
    });
    expect(onGrabPeerBrush).toHaveBeenCalledWith('peer-alice');

    const followBtn = findByTestId(container, 'host-modal-follow-peer-peer-alice')!;
    expect(followBtn).toBeDefined();
    await act(async () => {
      clickElement(followBtn);
    });
    expect(onToggleFollowPeer).toHaveBeenCalledWith('peer-alice');
    expect(onClose).toHaveBeenCalledTimes(1);
  });
});