Skip to content

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

30.7 KB
Raw Blame
import { act, useRef } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BrushSettings, CanvasDimensions, DocumentTab, LayerItem } from '../../types/editor';
import type { CanvasAreaProps } from '../../components/canvasArea/types';
import {
  documentStoreActions,
  resetNativeDiagnosticsStore,
  uiStoreActions,
  useDocumentStore,
  useToolStore,
  useUpdaterStore,
  useWorkspaceStore,
} from '../../stores';
import { recoveryService } from '../../services/recoveryService';
import { globalTimelapseManager } from '../timelapseEngine';

const mockBridge = vi.hoisted(() => ({
  nativeActive: true,
  setNativeViewport: vi.fn(async () => {}),
  setNativeOccludedRects: vi.fn(async () => {}),
  setNativePolicy: vi.fn(async () => {}),
  setNativeCamera: vi.fn(async () => {}),
  setNativeDocument: vi.fn(async () => {}),
  setNativeAppearance: vi.fn(async () => {}),
  setNativeCursor: vi.fn(async () => {}),
  setNativeMaskMode: vi.fn(async () => {}),
  setNativeRulers: vi.fn(async () => {}),
  setNativePressureCurve: vi.fn(async () => {}),
  syncNativeFullBrushConfig: vi.fn(async () => {}),
  requestNativeThumbnails: vi.fn(async () => {}),
  renderNativeNavigatorPreview: vi.fn(async () => ({
    width: 64,
    height: 64,
    rgba: new Uint8ClampedArray(64 * 64 * 4),
  })),
  diagnosticsListeners: new Set<(diag: any) => void>(),
  pointerStatListeners: new Set<(stat: any) => void>(),
  strokeCommittedListeners: new Set<(ev: any) => void>(),
  historyListeners: new Set<(ev: any) => void>(),
  thumbnailsListeners: new Set<(ev: any) => void>(),
}));

vi.mock('../nativeEngineBridge', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
  return {
    ...actual,
    isNativeCanvasActive: () => mockBridge.nativeActive,
    initNativeEngineBridge: async () => mockBridge.nativeActive,
    getNativeDiagnostics: async () => null,
    canNativeEngineHandleBrush: () => true,
    setNativeViewport: (...args: any[]) => (mockBridge.setNativeViewport as any)(...args),
    setNativeOccludedRects: (...args: any[]) => (mockBridge.setNativeOccludedRects as any)(...args),
    setNativePolicy: (...args: any[]) => (mockBridge.setNativePolicy as any)(...args),
    setNativeCamera: (...args: any[]) => (mockBridge.setNativeCamera as any)(...args),
    setNativeDocument: (...args: any[]) => (mockBridge.setNativeDocument as any)(...args),
    setNativeAppearance: (...args: any[]) => (mockBridge.setNativeAppearance as any)(...args),
    setNativeCursor: (...args: any[]) => (mockBridge.setNativeCursor as any)(...args),
    setNativeMaskMode: (...args: any[]) => (mockBridge.setNativeMaskMode as any)(...args),
    setNativeRulers: (...args: any[]) => (mockBridge.setNativeRulers as any)(...args),
    setNativePressureCurve: (...args: any[]) => (mockBridge.setNativePressureCurve as any)(...args),
    syncNativeFullBrushConfig: (...args: any[]) =>
      (mockBridge.syncNativeFullBrushConfig as any)(...args),
    requestNativeThumbnails: (...args: any[]) =>
      (mockBridge.requestNativeThumbnails as any)(...args),
    renderNativeNavigatorPreview: (...args: any[]) =>
      (mockBridge.renderNativeNavigatorPreview as any)(...args),
    nativeGetHistory: async () => null,
    subscribeNativeCanvasActive: () => () => {},
    subscribeNativeCamera: () => () => {},
    subscribeNativeViewportInvalidated: () => () => {},
    subscribeNativeDiagnostics: (cb: (diag: any) => void) => {
      mockBridge.diagnosticsListeners.add(cb);
      return () => mockBridge.diagnosticsListeners.delete(cb);
    },
    subscribeNativePointerStat: (cb: (stat: any) => void) => {
      mockBridge.pointerStatListeners.add(cb);
      return () => mockBridge.pointerStatListeners.delete(cb);
    },
    subscribeNativeStrokeCommitted: (cb: (ev: any) => void) => {
      mockBridge.strokeCommittedListeners.add(cb);
      return () => mockBridge.strokeCommittedListeners.delete(cb);
    },
    subscribeNativeHistory: (cb: (ev: any) => void) => {
      mockBridge.historyListeners.add(cb);
      return () => mockBridge.historyListeners.delete(cb);
    },
    subscribeNativeThumbnails: (cb: (ev: any) => void) => {
      mockBridge.thumbnailsListeners.add(cb);
      return () => mockBridge.thumbnailsListeners.delete(cb);
    },
  };
});

import {
  classifyOccluderMutations,
  useNativeEngineViewport,
} from '../../hooks/useNativeEngineViewport';
import { useDrawingHistory, UseDrawingHistoryResult } from '../../hooks/drawing/useDrawingHistory';
import { CanvasViewportHud } from '../../components/canvasArea/CanvasViewportHud';
import { NavigatorPanel } from '../../components/NavigatorPanel';
import type { CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';

// Minimal DOM harness matching repo Vitest node environment
interface MiniNode {
  nodeType: number;
  nodeName: string;
  parentNode: MiniElement | null;
  ownerDocument: MiniDocument;
}

class MiniTextNode implements MiniNode {
  public nodeType = 3;
  public nodeName = '#text';
  public parentNode: MiniElement | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: MiniDocument
  ) {}
}

class MiniCommentNode implements MiniNode {
  public nodeType = 8;
  public nodeName = '#comment';
  public parentNode: MiniElement | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: MiniDocument
  ) {}
}

function createMock2DCtx() {
  return {
    save: vi.fn(),
    restore: vi.fn(),
    setTransform: vi.fn(),
    clearRect: vi.fn(),
    fillRect: vi.fn(),
    strokeRect: vi.fn(),
    beginPath: vi.fn(),
    moveTo: vi.fn(),
    lineTo: vi.fn(),
    closePath: vi.fn(),
    fill: vi.fn(),
    stroke: vi.fn(),
    translate: vi.fn(),
    rotate: vi.fn(),
    scale: vi.fn(),
    drawImage: vi.fn(),
    createImageData: (w: number, h: number) => ({
      data: new Uint8ClampedArray(w * h * 4),
      width: w,
      height: h,
    }),
    putImageData: vi.fn(),
    imageSmoothingEnabled: true,
    fillStyle: '',
    strokeStyle: '',
    lineWidth: 1,
    globalAlpha: 1,
  };
}

class MiniElement extends EventTarget implements MiniNode {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI = 'http://www.w3.org/1999/xhtml';
  public parentNode: MiniElement | null = null;
  public childNodes: MiniNode[] = [];
  public style: Record<string, string> = {};
  public className = '';
  public isContentEditable = false;
  public width = 200;
  public height = 120;
  public clientWidth = 200;
  public clientHeight = 120;
  public rect = { left: 240, top: 64, right: 1200, bottom: 784, width: 960, height: 720 };
  private attrs = new Map<string, string>();
  private mockCtx: ReturnType<typeof createMock2DCtx> | null = null;

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

  get firstChild(): MiniNode | null {
    return this.childNodes[0] ?? null;
  }

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

  set textContent(val: string) {
    this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];
  }

  appendChild<T extends MiniNode>(child: T): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }

  removeChild<T extends MiniNode>(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 MiniNode>(newNode: T, refNode: MiniNode | null): T {
    if (newNode.parentNode) newNode.parentNode.removeChild(newNode);
    newNode.parentNode = this;
    if (!refNode) {
      this.childNodes.push(newNode);
      return newNode;
    }
    const idx = this.childNodes.indexOf(refNode);
    if (idx < 0) this.childNodes.push(newNode);
    else this.childNodes.splice(idx, 0, newNode);
    return newNode;
  }

  setAttribute(k: string, v: string) {
    this.attrs.set(k, String(v));
  }
  getAttribute(k: string): string | null {
    return this.attrs.get(k) ?? null;
  }
  removeAttribute(k: string) {
    this.attrs.delete(k);
  }
  hasAttribute(k: string): boolean {
    return this.attrs.has(k);
  }
  getBoundingClientRect() {
    return { ...this.rect, x: this.rect.left, y: this.rect.top };
  }
  getContext(type: string) {
    if (type === '2d') {
      if (!this.mockCtx) this.mockCtx = createMock2DCtx();
      return this.mockCtx;
    }
    return null;
  }
  findByAttr(attr: string, val: string): MiniElement | null {
    if (this.getAttribute(attr) === val) return this;
    for (const c of this.childNodes) {
      if (c instanceof MiniElement) {
        const hit = c.findByAttr(attr, val);
        if (hit) return hit;
      }
    }
    return null;
  }
}

class MiniDocument extends EventTarget {
  public nodeType = 9;
  public nodeName = '#document';
  public defaultView: any;
  public body: MiniElement;
  public documentElement: MiniElement;
  public activeElement: MiniElement | null = null;
  public hidden = false;
  public occluders: MiniElement[] = [];

  constructor(win: any) {
    super();
    this.defaultView = win;
    this.documentElement = new MiniElement('html', this);
    this.body = new MiniElement('body', this);
    this.documentElement.appendChild(this.body);
  }

  createElement(tag: string) {
    return new MiniElement(tag, this);
  }
  createElementNS(_ns: string, tag: string) {
    return new MiniElement(tag, this);
  }
  createTextNode(text: string) {
    return new MiniTextNode(text, this);
  }
  createComment(text: string) {
    return new MiniCommentNode(text, this);
  }
  querySelectorAll(_selector: string) {
    return this.occluders;
  }
}

class RecordingMutationObserver {
  public static instances: RecordingMutationObserver[] = [];
  public observedTarget: Node | null = null;
  public observedOptions: MutationObserverInit | null = null;
  private cb: MutationCallback;
  constructor(cb: MutationCallback) {
    this.cb = cb;
    RecordingMutationObserver.instances.push(this);
  }
  observe(target: Node, options?: MutationObserverInit) {
    this.observedTarget = target;
    this.observedOptions = options ?? null;
  }
  disconnect() {}
  takeRecords(): MutationRecord[] {
    return [];
  }
  emit(records: Partial<MutationRecord>[]) {
    this.cb(records as MutationRecord[], this as unknown as MutationObserver);
  }
}

function makeDoc(id: string): DocumentTab {
  return {
    id,
    name: 'PerfTest',
    isDirty: false,
    dimensions: { width: 1024, height: 1024, dpi: 300 },
    colorMode: 'color',
    layers: [
      {
        id: 'layer-1',
        name: 'Layer 1',
        type: 'raster',
        visible: true,
        opacity: 100,
        blendMode: 'normal',
        locked: false,
        alphaLocked: false,
        clipped: false,
        parentId: null,
      },
    ],
    activeLayerId: 'layer-1',
  };
}

function createMockNavHandle(): CanvasNavigationHandle {
  const panRef = { current: { x: 400, y: 300 } };
  const zoomRef = { current: 1 };
  const rotationRef = { current: 0 };
  const flipXRef = { current: false };
  const flipYRef = { current: false };
  return {
    panRef,
    zoomRef,
    rotationRef,
    flipXRef,
    flipYRef,
    getCameraState: () => ({
      pan: { ...panRef.current },
      zoom: zoomRef.current,
      rotation: rotationRef.current,
      flipX: flipXRef.current,
      flipY: flipYRef.current,
    }),
    subscribeCamera: () => () => {},
    setPanLive: vi.fn(),
    setZoomLive: vi.fn(),
    rotateBy: vi.fn(),
    commitCameraState: vi.fn(),
  };
}

describe('Native Engine Bridge Performance Regressions', () => {
  let prevGlobals: Record<string, unknown>;
  let miniWin: any;
  let miniDoc: MiniDocument;
  let hostEl: MiniElement;
  let root: Root | null = null;
  let pendingRafs: Map<number, FrameRequestCallback>;
  let nextRafId: number;

  const flushRaf = () => {
    const callbacks = Array.from(pendingRafs.values());
    pendingRafs.clear();
    for (const cb of callbacks) cb(0);
  };

  beforeEach(() => {
    vi.clearAllMocks();
    resetNativeDiagnosticsStore();
    recoveryService.setDrawingActive(false);
    mockBridge.nativeActive = true;
    mockBridge.diagnosticsListeners.clear();
    mockBridge.pointerStatListeners.clear();
    mockBridge.strokeCommittedListeners.clear();
    mockBridge.historyListeners.clear();
    mockBridge.thumbnailsListeners.clear();
    RecordingMutationObserver.instances = [];
    pendingRafs = new Map();
    nextRafId = 1;

    const g = globalThis as Record<string, unknown>;
    prevGlobals = {
      window: g.window,
      document: g.document,
      HTMLElement: g.HTMLElement,
      HTMLIFrameElement: g.HTMLIFrameElement,
      Element: g.Element,
      Node: g.Node,
      getComputedStyle: g.getComputedStyle,
      MutationObserver: g.MutationObserver,
      requestAnimationFrame: g.requestAnimationFrame,
      cancelAnimationFrame: g.cancelAnimationFrame,
      IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,
    };

    const fakeGetComputedStyle = (el: MiniElement) => ({
      display: el.style?.display ?? 'block',
      visibility: el.style?.visibility ?? 'visible',
      pointerEvents: el.style?.pointerEvents ?? 'auto',
      opacity: el.style?.opacity ?? '1',
      getPropertyValue: () => '#18181b',
    });

    const FakeIFrame = class HTMLIFrameElement {};
    miniWin = Object.assign(new EventTarget(), {
      devicePixelRatio: 1,
      HTMLElement: MiniElement,
      HTMLIFrameElement: FakeIFrame,
      Element: MiniElement,
      Node: MiniElement,
      matchMedia: () => ({
        matches: true,
        addEventListener: () => {},
        removeEventListener: () => {},
      }),
      getComputedStyle: fakeGetComputedStyle,
    });
    miniDoc = new MiniDocument(miniWin);
    miniWin.document = miniDoc;
    hostEl = miniDoc.createElement('div');
    miniDoc.body.appendChild(hostEl);

    g.window = miniWin;
    g.document = miniDoc;
    g.HTMLElement = MiniElement;
    g.HTMLIFrameElement = FakeIFrame;
    g.Element = MiniElement;
    g.Node = MiniElement;
    g.getComputedStyle = fakeGetComputedStyle;
    g.MutationObserver = RecordingMutationObserver;
    g.requestAnimationFrame = (cb: FrameRequestCallback) => {
      const id = nextRafId++;
      pendingRafs.set(id, cb);
      return id;
    };
    g.cancelAnimationFrame = (id: number) => {
      pendingRafs.delete(id);
    };
    g.IS_REACT_ACT_ENVIRONMENT = true;

    uiStoreActions.setAppView('workspace');
    uiStoreActions.setBrushStudioModalOpen(false);
    useUpdaterStore.setState({ isModalOpen: false });
    useWorkspaceStore.setState({ palettesHidden: false });
    const doc = makeDoc('doc-perf-1');
    documentStoreActions.setDocuments([doc]);
    documentStoreActions.setActiveDocumentId(doc.id);
  });

  afterEach(async () => {
    vi.useRealTimers();
    recoveryService.setDrawingActive(false);
    resetNativeDiagnosticsStore();
    if (root) {
      await act(async () => {
        root?.unmount();
      });
      root = null;
    }
    const g = globalThis as Record<string, unknown>;
    for (const [k, v] of Object.entries(prevGlobals)) {
      if (v === undefined) delete g[k];
      else g[k] = v;
    }
  });

  it('1. emitting 10 native-engine://diagnostics events causes 0 re-renders of CanvasArea subtree while updating NativeGpuPerfHud leaf without data-native-occluder', () => {
    const viewportEl = miniDoc.createElement('div');
    const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
    const layer = useDocumentStore.getState().documents[0].layers[0];
    let canvasAreaRenderCount = 0;

    function SimulatedCanvasArea() {
      canvasAreaRenderCount += 1;
      const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
      const cursorRingRef = useRef<HTMLDivElement | null>(null);
      const pointerStatRef = useRef<HTMLDivElement | null>(null);
      const { nativeActive, onClearNativeCanvas } = useNativeEngineViewport({
        viewportRef: vpRef,
        dimensions: { width: 1024, height: 1024, dpi: 300 },
        showCheckerboard: true,
        hasOpenDocument: true,
        tool: 'brush',
        brushSettings,
        primaryColor: '#111111',
        activeLayer: layer,
        isMaskMode: false,
        isSquare: false,
        thicknessRatio: 1,
        thicknessVertical: false,
        tipAngleDeg: 0,
        isResizingBrush: false,
        isSpaceDown: false,
        isPanning: false,
        isRotating: false,
        isZoomDragging: false,
        isRotateModifier: false,
        pan: { x: 0, y: 0 },
        zoom: 1,
        rotation: 0,
        flipX: false,
        flipY: false,
      });

      return (
        <CanvasViewportHud
          canvasProps={
            {
              viewportRef: vpRef,
              dimensions: { width: 1024, height: 1024, dpi: 300 },
              brushSettings,
              onUpdateBrushSettings: () => {},
              zoom: 1,
              pan: { x: 0, y: 0 },
              rotation: 0,
              isSpaceDown: false,
              isShiftDown: false,
              isRotateModifier: false,
              isPanning: false,
              isRotating: false,
              isHovering: false,
              cursorPos: null,
              onStartPan: () => {},
              onStartRotate: () => {},
              onPointerDown: () => {},
              onPointerMove: () => {},
              onPointerUp: () => {},
              onPointerEnter: () => {},
              onPointerLeave: () => {},
              layers: [layer],
              activeLayerId: layer.id,
            } as unknown as CanvasAreaProps
          }
          cursorRingRef={cursorRingRef}
          pointerStatRef={pointerStatRef}
          livePan={{ x: 0, y: 0 }}
          liveZoom={1}
          liveRotation={0}
          liveFlipX={false}
          liveFlipY={false}
          cursorWidth={20}
          cursorHeight={20}
          totalAngleDeg={0}
          isCustomTip={false}
          isSquare={false}
          tipOutline={null}
          isResizingBrush={false}
          resizePreviewX={0}
          resizePreviewY={0}
          quickPalettePos={null}
          setQuickPalettePos={() => {}}
          nativeCanvasActive={nativeActive}
          onClearNativeCanvas={onClearNativeCanvas}
        />
      );
    }

    root = createRoot(hostEl as any);
    act(() => {
      root!.render(<SimulatedCanvasArea />);
    });

    const rendersAfterMount = canvasAreaRenderCount;
    expect(mockBridge.diagnosticsListeners.size).toBe(1);

    const hudEl = hostEl.findByAttr('data-testid', 'native-gpu-perf-hud');
    expect(hudEl).not.toBeNull();
    // Perf HUD must NOT have data-native-occluder="true" so digit changes never trigger occlusion IPC
    expect(hudEl!.getAttribute('data-native-occluder')).toBeNull();

    // Emit 10 rapid 4 Hz diagnostics updates
    act(() => {
      for (let i = 1; i <= 10; i++) {
        const diag = {
          ready: true,
          adapterName: 'RTX 4090',
          backend: 'DX12',
          presentMode: 'Immediate',
          fps: 120 + i,
          frameTimeMs: 4.2,
          inputToPresentMs: 2.1 + i * 0.1,
          swapchainWidth: 1920,
          swapchainHeight: 1080,
          docWidth: 1024,
          docHeight: 1024,
          activeStrokeDabs: i * 10,
          totalFramesRendered: i * 30,
          deviceLostRecoveries: 0,
          maxFrameLatency: 1,
          compositionMode: 'DirectComposition',
          isIdle: false,
        };
        for (const cb of mockBridge.diagnosticsListeners) cb(diag);
      }
    });

    // Zero CanvasArea re-renders across all 10 diagnostics events!
    expect(canvasAreaRenderCount).toBe(rendersAfterMount);
    // Leaf HUD reflects the latest 10th diagnostics snapshot directly
    expect(hudEl!.textContent).toContain('130 FPS');
    expect(hudEl!.textContent).toContain('I2P 3.10ms');
  });

  it('2. mutating StatusBar pressure bar style.width does NOT trigger setNativeOccludedRects', () => {
    const viewportEl = miniDoc.createElement('div');
    const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
    const layer = useDocumentStore.getState().documents[0].layers[0];

    function ViewportHarness() {
      const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
      useNativeEngineViewport({
        viewportRef: vpRef,
        dimensions: { width: 1024, height: 1024, dpi: 300 },
        showCheckerboard: true,
        hasOpenDocument: true,
        tool: 'brush',
        brushSettings,
        primaryColor: '#111111',
        activeLayer: layer,
        isMaskMode: false,
        isSquare: false,
        thicknessRatio: 1,
        thicknessVertical: false,
        tipAngleDeg: 0,
        isResizingBrush: false,
        isSpaceDown: false,
        isPanning: false,
        isRotating: false,
        isZoomDragging: false,
        isRotateModifier: false,
        pan: { x: 0, y: 0 },
        zoom: 1,
        rotation: 0,
        flipX: false,
        flipY: false,
      });
      return null;
    }

    root = createRoot(hostEl as any);
    act(() => {
      root!.render(<ViewportHarness />);
    });

    // Find the body MutationObserver registered by useNativeEngineViewport
    const bodyObserver = RecordingMutationObserver.instances.find(
      (inst) => inst.observedTarget === (miniDoc.body as unknown as Node)
    );
    expect(bodyObserver).toBeDefined();
    // `style` MUST NOT be observed across document.body
    expect(bodyObserver!.observedOptions?.attributeFilter).not.toContain('style');

    const statusBar = miniDoc.createElement('footer');
    statusBar.setAttribute('data-testid', 'status-bar');
    statusBar.setAttribute('data-chrome-bar', 'status');
    const pressureBar = miniDoc.createElement('div');
    statusBar.appendChild(pressureBar);
    miniDoc.body.appendChild(statusBar);

    const floatingPill = miniDoc.createElement('div');
    floatingPill.setAttribute('data-testid', 'floating-brush-pill');
    floatingPill.setAttribute('data-native-occluder', 'true');
    floatingPill.rect = { left: 300, top: 300, right: 420, bottom: 360, width: 120, height: 60 };
    miniDoc.occluders = [floatingPill];
    mockBridge.setNativeOccludedRects.mockClear();

    // Simulate 30 Hz StatusBar pressure bar style.width + class mutations
    act(() => {
      for (let i = 0; i < 30; i++) {
        pressureBar.style.width = `${i * 3}%`;
        bodyObserver!.emit([
          {
            type: 'attributes',
            attributeName: 'style',
            target: pressureBar as unknown as Node,
          },
          {
            type: 'attributes',
            attributeName: 'class',
            target: pressureBar as unknown as Node,
          },
        ]);
      }
      flushRaf();
    });

    expect(mockBridge.setNativeOccludedRects).not.toHaveBeenCalled();

    // Direct classifier verification for StatusBar vs modal opening
    expect(
      classifyOccluderMutations([
        {
          type: 'attributes',
          attributeName: 'style',
          target: pressureBar as unknown as Node,
        } as MutationRecord,
      ])
    ).toEqual({ shouldScan: false, isModalEvent: false });

    const modalEl = miniDoc.createElement('div');
    modalEl.setAttribute('role', 'dialog');
    modalEl.setAttribute('aria-modal', 'true');
    modalEl.rect = { left: 400, top: 200, right: 800, bottom: 600, width: 400, height: 400 };
    miniDoc.occluders = [floatingPill, modalEl];

    // Even during an active stroke, opening a modal MUST trigger an immediate occluder rescan
    recoveryService.setDrawingActive(true);
    act(() => {
      bodyObserver!.emit([
        {
          type: 'childList',
          target: miniDoc.body as unknown as Node,
          addedNodes: [modalEl] as unknown as NodeList,
          removedNodes: [] as unknown as NodeList,
        },
      ]);
      flushRaf();
    });

    expect(mockBridge.setNativeOccludedRects).toHaveBeenCalledTimes(1);
    expect(mockBridge.setNativeOccludedRects).toHaveBeenLastCalledWith([
      { x: 300, y: 300, width: 120, height: 60 },
      { x: 400, y: 200, width: 400, height: 400 },
    ]);
  });

  it('3. rapid StrokeCommitted + HistoryChanged + ThumbnailsUpdated trigger at most 1 debounced Navigator preview and 1 history state update', () => {
    vi.useFakeTimers();
    const activeDoc = useDocumentStore.getState().documents[0];
    const dims: CanvasDimensions = activeDoc.dimensions;
    const nav = createMockNavHandle();
    const vpRef = { current: { clientWidth: 800, clientHeight: 600 } as HTMLDivElement };

    let historyRenderCount = 0;
    let latestHistory: UseDrawingHistoryResult | null = null;

    function CombinedHarness({ layers }: { layers: LayerItem[] }) {
      historyRenderCount += 1;
      const dimsRef = useRef(dims);
      const layerIdRef = useRef('layer-1');
      const colorModeRef = useRef(activeDoc.colorMode);
      const layersRef = useRef<LayerItem[] | undefined>(layers);
      const isDrawingRef = useRef(false);
      const lastStrokeEndRef = useRef(null);
      const abortRef = useRef(() => {});
      const maskThumbRef = useRef<((id: string) => void) | undefined>(undefined);

      latestHistory = useDrawingHistory({
        activeSessionId: activeDoc.id,
        activeLayerId: 'layer-1',
        activeLayerLocked: false,
        dimensions: dims,
        dimensionsRef: dimsRef,
        activeLayerIdRef: layerIdRef,
        colorModeRef,
        layersRef,
        onUpdateLayerThumbnail: () => {},
        onUpdateMaskThumbnailRef: maskThumbRef,
        isDrawingRef,
        lastStrokeEndRef,
        abortActiveStrokeRef: abortRef,
      });

      return (
        <NavigatorPanel
          viewportRef={vpRef}
          navigation={nav}
          dimensions={dims}
          layers={layers}
          showCheckerboard={false}
          zoom={1}
          rotation={0}
          flipX={false}
          flipY={false}
          onZoomIn={() => {}}
          onZoomOut={() => {}}
          onFitToScreen={() => {}}
          onZoomActualSize={() => {}}
          onRotateLeft={() => {}}
          onRotateRight={() => {}}
          onResetRotation={() => {}}
          onToggleFlipHorizontal={() => {}}
          onToggleFlipVertical={() => {}}
          throttleMs={200}
        />
      );
    }

    root = createRoot(hostEl as any);
    act(() => {
      root!.render(<CombinedHarness layers={activeDoc.layers} />);
    });

    // Initial mount rendered Navigator preview once
    expect(mockBridge.renderNativeNavigatorPreview).toHaveBeenCalledTimes(1);
    mockBridge.renderNativeNavigatorPreview.mockClear();
    const rendersBeforeStroke = historyRenderCount;

    const historySnap = {
      entries: [
        {
          id: 'stroke-42',
          type: 'stroke',
          label: 'Brush Stroke',
          timestamp: 1000,
          timeFormatted: '00:01',
          thumbnailUrl: '',
        },
      ],
      index: 0,
      canUndo: true,
      canRedo: false,
    };

    // Emit StrokeCommitted + duplicate HistoryChanged + ThumbnailsUpdated in rapid succession
    act(() => {
      for (const cb of mockBridge.strokeCommittedListeners) {
        cb({
          docId: activeDoc.id,
          layerId: 'layer-1',
          entryId: 'stroke-42',
          dirtyRect: { x: 0, y: 0, width: 64, height: 64 },
          history: historySnap,
          points: [],
        });
      }
      for (const cb of mockBridge.historyListeners) {
        cb({ docId: activeDoc.id, history: historySnap });
      }
      for (const cb of mockBridge.thumbnailsListeners) {
        cb({ docId: activeDoc.id, updates: [{ layerId: 'layer-1', thumbnailUrl: 'data:image/png;base64,AA==' }] });
      }
    });

    // History state updated EXACTLY ONCE despite receiving both StrokeCommitted and HistoryChanged!
    expect(historyRenderCount - rendersBeforeStroke).toBe(1);
    expect(latestHistory!.historyList).toHaveLength(1);
    expect(latestHistory!.canUndo).toBe(true);

    // Updating layer thumbnailUrl prop must NOT trigger another Navigator GPU readback
    act(() => {
      root!.render(
        <CombinedHarness
          layers={[{ ...activeDoc.layers[0], thumbnailUrl: 'data:image/png;base64,BBBB' }]}
        />
      );
    });

    // During the 1500ms native stroke grace window, Navigator GPU readback is deferred
    expect(recoveryService.getIsDrawingActive()).toBe(true);
    expect(mockBridge.renderNativeNavigatorPreview).toHaveBeenCalledTimes(0);

    // Advance past the 1500ms grace window + 200ms trailing debounce -> AT MOST 1 Navigator readback!
    act(() => {
      vi.advanceTimersByTime(1800);
    });
    expect(mockBridge.renderNativeNavigatorPreview).toHaveBeenCalledTimes(1);
  });

  it('4. native stroke activity sets recoveryService.getIsDrawingActive() === true and suppresses checkpoints & timelapse until idle', async () => {
    vi.useFakeTimers();
    (miniWin as any).__TAURI_INTERNALS__ = {};
    const triggerCheckpointSpy = vi
      .spyOn(recoveryService as any, 'triggerCheckpoint')
      .mockResolvedValue(undefined);

    const docId = 'doc-perf-guard';
    await recoveryService.initSession(docId, () => null);
    globalTimelapseManager.setRecording(docId, true, 'GuardTest');

    const captureContext = {
      isDrawingActive: () => recoveryService.getIsDrawingActive(),
      documentName: 'GuardTest',
    };

    // Simulate rapid hatching burst of 30 native strokes (exceeding CHECKPOINT_STROKE_THRESHOLD=25),
    // each 200ms apart (well within the 1500ms idle grace window).
    for (let i = 0; i < 30; i++) {
      recoveryService.notifyNativeStrokeStart();
      expect(recoveryService.getIsDrawingActive()).toBe(true);

      // Timelapse capture mid-stroke MUST be deferred (returns false)
      const captured = await globalTimelapseManager.captureKeyframe(
        docId,
        useDocumentStore.getState().documents[0].layers,
        { width: 1024, height: 1024, dpi: 300 },
        false,
        captureContext
      );
      expect(captured).toBe(false);

      recoveryService.notifyNativeStrokeCommitted(docId);
      expect(recoveryService.getIsDrawingActive()).toBe(true);
      vi.advanceTimersByTime(200);
    }

    // Even after 30 strokes, ZERO recovery checkpoints fired mid-sketching!
    expect(recoveryService.getIsDrawingActive()).toBe(true);
    expect(triggerCheckpointSpy).not.toHaveBeenCalled();

    // Wait 1400ms (still inside 1500ms grace window from last stroke: 200ms already passed -> 1300ms left)
    vi.advanceTimersByTime(1200);
    expect(recoveryService.getIsDrawingActive()).toBe(true);
    expect(triggerCheckpointSpy).not.toHaveBeenCalled();

    // Pass the 1500ms idle grace window -> drawing becomes idle & deferred checkpoint flushes!
    vi.advanceTimersByTime(200);
    expect(recoveryService.getIsDrawingActive()).toBe(false);
    expect(triggerCheckpointSpy).toHaveBeenCalledTimes(1);

    await globalTimelapseManager.removeSession(docId);
    triggerCheckpointSpy.mockRestore();
  });
});