Skip to content

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

26.4 KB
Raw Blame
import React, { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LayerItem } from '../../types/editor';
import {
  globalTimelapseManager,
  packTimelapseFrameBatch,
  TimelapseRecorderManager,
} from '../timelapseEngine';
import {
  useDocumentLifecycle,
  UseDocumentLifecycleParams,
} from '../../components/DocumentLifecycleManager';
import { uiStoreActions, useDocumentStore } from '../../stores';

// Mock @tauri-apps/api/core so we can test Tauri persistent local disk storage across restarts
const mockTauriInvoke = vi.fn();
vi.mock('@tauri-apps/api/core', () => ({
  invoke: (...args: unknown[]) => mockTauriInvoke(...args),
}));

const mockOpenFile = vi.fn();
vi.mock('../imageLoader', () => ({
  openFile: (...args: unknown[]) => mockOpenFile(...args),
}));

const mockNativeTl = vi.hoisted(() => ({
  active: true,
  captureNativeTimelapseFrame: vi.fn(),
  flattenNativeDocument: vi.fn(),
}));

vi.mock('../nativeEngineBridge', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
  return {
    ...actual,
    isNativeCanvasActive: () => mockNativeTl.active,
    captureNativeTimelapseFrame: (...args: unknown[]) =>
      mockNativeTl.captureNativeTimelapseFrame(...args),
    flattenNativeDocument: (...args: unknown[]) =>
      mockNativeTl.flattenNativeDocument(...args),
  };
});

vi.mock('../recentDocumentsManager', () => ({
  saveRecentDocument: vi.fn().mockResolvedValue(undefined),
}));

function makeBaseLayer(): LayerItem {
  return {
    id: 'layer-1',
    name: 'Artwork',
    type: 'raster',
    visible: true,
    opacity: 1,
    blendMode: 'normal',
    locked: false,
    parentId: null,
  };
}

function makeFakeWebpBytes(tag: number, len = 32): Uint8Array {
  const bytes = new Uint8Array(len);
  bytes[0] = 0x52;
  bytes[1] = 0x49;
  bytes[2] = 0x46;
  bytes[3] = 0x46;
  bytes[8] = 0x57;
  bytes[9] = 0x45;
  bytes[10] = 0x42;
  bytes[11] = 0x50;
  for (let i = 12; i < len; i++) {
    bytes[i] = (tag * 31 + i) & 0xff;
  }
  return bytes;
}

function stubCanvasForCapture(payloadQueue: Uint8Array[]) {
  let callIndex = 0;
  vi.stubGlobal('ImageData', class FakeImageData {
    constructor(
      public data: Uint8ClampedArray,
      public width: number,
      public height: number
    ) {}
  });
  vi.stubGlobal('document', {
    createElement: (tag: string) => {
      if (tag !== 'canvas') return {};
      return {
        width: 0,
        height: 0,
        getContext: () => ({
          save: () => {},
          restore: () => {},
          setTransform: () => {},
          scale: () => {},
          translate: () => {},
          rotate: () => {},
          fillStyle: '',
          fillRect: () => {},
          drawImage: () => {},
          putImageData: () => {},
          globalAlpha: 1,
          globalCompositeOperation: 'source-over',
        }),
        toBlob: (cb: (b: Blob | null) => void, mime?: string) => {
          if (mime === 'image/png') {
            cb(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }));
            return;
          }
          const next = payloadQueue[callIndex++] ?? makeFakeWebpBytes(callIndex);
          cb(new Blob([next as BlobPart], { type: mime || 'image/webp' }));
        },
      };
    },
  });
}

interface MockPersistedFrame {
  index: number;
  ext: string;
  timestamp: number;
  width: number;
  height: number;
  mimeType: 'image/webp' | 'image/jpeg' | 'image/png';
  bytes: Uint8Array;
  captureArea?: string;
}

function installTauriPersistentDiskMock() {
  const diskFrames = new Map<string, Map<number, MockPersistedFrame>>();
  const diskMeta = new Map<string, Record<string, unknown>>();

  const unpackBatchJs = (raw: Uint8Array) => {
    const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
    const count = view.getUint32(0, true);
    let offset = 4;
    const out: Array<{ index: number; ext: string; bytes: Uint8Array }> = [];
    for (let i = 0; i < count; i++) {
      const index = view.getUint32(offset, true);
      const extCode = raw[offset + 4];
      const ext = extCode === 1 ? 'jpg' : 'webp';
      const len = view.getUint32(offset + 5, true);
      offset += 9;
      out.push({ index, ext, bytes: raw.slice(offset, offset + len) });
      offset += len;
    }
    return out;
  };

  mockTauriInvoke.mockImplementation(
    async (cmd: string, bodyOrArgs: unknown, opts?: { headers?: Record<string, string> }) => {
      if (cmd === 'timelapse_save_meta') {
        const { sessionId, metaJson } = bodyOrArgs as { sessionId: string; metaJson: string };
        diskMeta.set(sessionId, JSON.parse(metaJson));
        return undefined;
      }
      if (cmd === 'timelapse_write_frame') {
        const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');
        const idx = Number(opts?.headers?.['x-frame-index'] || '0');
        const ext = opts?.headers?.['x-ext'] || 'webp';
        const timestamp = Number(opts?.headers?.['x-timestamp'] || '0');
        const width = Number(opts?.headers?.['x-width'] || '512');
        const height = Number(opts?.headers?.['x-height'] || '512');
        const captureArea = opts?.headers?.['x-capture-area']
          ? decodeURIComponent(opts.headers['x-capture-area'])
          : undefined;
        if (!diskFrames.has(sid)) diskFrames.set(sid, new Map());
        const bytes =
          bodyOrArgs instanceof ArrayBuffer
            ? new Uint8Array(bodyOrArgs.slice(0))
            : new Uint8Array(bodyOrArgs as Uint8Array);
        diskFrames.get(sid)!.set(idx, {
          index: idx,
          ext,
          timestamp,
          width,
          height,
          mimeType: ext === 'jpg' ? 'image/jpeg' : 'image/webp',
          bytes,
          captureArea,
        });
        return undefined;
      }
      if (cmd === 'timelapse_write_frames_batch') {
        const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');
        if (!diskFrames.has(sid)) diskFrames.set(sid, new Map());
        const entries = unpackBatchJs(bodyOrArgs as Uint8Array);
        for (const e of entries) {
          diskFrames.get(sid)!.set(e.index, {
            index: e.index,
            ext: e.ext,
            timestamp: 0,
            width: 512,
            height: 512,
            mimeType: e.ext === 'jpg' ? 'image/jpeg' : 'image/webp',
            bytes: e.bytes,
          });
        }
        return entries.length;
      }
      if (cmd === 'timelapse_read_frame') {
        const sid = decodeURIComponent(opts?.headers?.['x-session-id'] || '');
        const idx = Number(opts?.headers?.['x-frame-index'] || '0');
        const entry = diskFrames.get(sid)?.get(idx);
        if (!entry) throw new Error('Frame not found');
        return entry.bytes.slice().buffer;
      }
      if (cmd === 'timelapse_load_session') {
        const sid = (bodyOrArgs as { sessionId: string }).sessionId;
        const meta = diskMeta.get(sid) ?? null;
        const map = diskFrames.get(sid);
        const sorted = map
          ? Array.from(map.values()).sort((a, b) => a.index - b.index)
          : [];
        let totalBytes = 0;
        const frames = sorted.map((f) => {
          totalBytes += f.bytes.byteLength;
          return {
            index: f.index,
            timestamp: f.timestamp,
            width: f.width,
            height: f.height,
            mimeType: f.mimeType,
            bytes: f.bytes.byteLength,
            ...(f.captureArea ? { captureArea: f.captureArea } : {}),
          };
        });
        return { meta, frames, totalBytes };
      }
      if (cmd === 'timelapse_list_sessions') {
        const ids = new Set<string>([...diskMeta.keys(), ...diskFrames.keys()]);
        return Array.from(ids).map((id) => {
          const m = diskMeta.get(id) as Record<string, unknown> | undefined;
          const map = diskFrames.get(id);
          const list = map ? Array.from(map.values()) : [];
          const totalBytes = list.reduce((acc, f) => acc + f.bytes.byteLength, 0);
          return {
            recordingId: id,
            documentName: String(m?.documentName || 'Untitled'),
            enabled: Boolean(m?.enabled),
            captureArea: String(m?.captureArea || 'artwork'),
            captureResolution: String(m?.captureResolution || '1080p'),
            frameCount: list.length,
            totalBytes,
            createdAt: Number(m?.createdAt || 0),
            updatedAt: Number(m?.updatedAt || 0),
          };
        });
      }
      if (cmd === 'timelapse_list_frames') {
        const sid = (bodyOrArgs as { sessionId: string }).sessionId;
        const map = diskFrames.get(sid);
        if (!map) return [];
        return Array.from(map.values())
          .sort((a, b) => a.index - b.index)
          .map((f): [number, string] => [f.index, f.ext]);
      }
      if (cmd === 'timelapse_clear') {
        const sid = (bodyOrArgs as { sessionId: string }).sessionId;
        diskFrames.delete(sid);
        diskMeta.delete(sid);
        return undefined;
      }
      return undefined;
    }
  );

  return { diskFrames, diskMeta };
}

// Minimal DOM shim for mounting useDocumentLifecycle hook
class MiniNode {
  public parentNode: MiniEl | null = null;
  constructor(
    public nodeType: number,
    public nodeName: string,
    public ownerDocument: MiniDoc
  ) {}
}

class MiniEl extends EventTarget {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI = 'http://www.w3.org/1999/xhtml';
  public parentNode: MiniEl | null = null;
  public childNodes: Array<MiniEl | MiniNode> = [];
  public style: Record<string, string> = {};
  constructor(tag: string, public ownerDocument: MiniDoc) {
    super();
    this.nodeName = tag.toUpperCase();
    this.tagName = tag.toUpperCase();
  }
  appendChild<T extends MiniEl | MiniNode>(child: T): T {
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }
  removeChild<T extends MiniEl | MiniNode>(child: T): T {
    const idx = this.childNodes.indexOf(child);
    if (idx >= 0) this.childNodes.splice(idx, 1);
    child.parentNode = null;
    return child;
  }
}

class MiniDoc extends EventTarget {
  public nodeType = 9;
  public defaultView: unknown = globalThis;
  public documentElement: MiniEl;
  public body: MiniEl;
  constructor() {
    super();
    this.documentElement = new MiniEl('html', this);
    this.body = new MiniEl('body', this);
    this.documentElement.appendChild(this.body);
  }
  createElement(tag: string): MiniEl {
    return new MiniEl(tag, this);
  }
  createTextNode(): MiniNode {
    return new MiniNode(3, '#text', this);
  }
  createComment(): MiniNode {
    return new MiniNode(8, '#comment', this);
  }
}

describe('External Persistent Time-lapse Storage & Restart Resume (Zero .ink Bloat)', () => {
  afterEach(async () => {
    await new Promise((r) => setTimeout(r, 0));
    vi.restoreAllMocks();
    vi.unstubAllGlobals();
    mockTauriInvoke.mockReset();
    mockOpenFile.mockReset();
    mockNativeTl.captureNativeTimelapseFrame.mockReset();
    mockNativeTl.flattenNativeDocument.mockReset();
    if (typeof window !== 'undefined') {
      delete (window as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
    }
  });

  it('persists native Rust timelapse frames externally and resumes recording across app restarts', async () => {
    const f0 = makeFakeWebpBytes(1, 40);
    const f1 = makeFakeWebpBytes(2, 48);
    const f2 = makeFakeWebpBytes(3, 52);
    const f3 = makeFakeWebpBytes(4, 60);
    const f4 = makeFakeWebpBytes(5, 64);
    const payloads = [f0, f1, f2, f3, f4];
    let captureIdx = 0;

    stubCanvasForCapture(payloads);

    (globalThis as unknown as Record<string, unknown>).window = {
      __TAURI_INTERNALS__: {
        invoke: (...args: unknown[]) => mockTauriInvoke(...args),
      },
    };
    const { diskFrames } = installTauriPersistentDiskMock();

    mockNativeTl.captureNativeTimelapseFrame.mockImplementation(
      async (params: { sessionId: string; frameIndex: number }) => {
        const bytes = payloads[captureIdx++] ?? makeFakeWebpBytes(captureIdx);
        if (!diskFrames.has(params.sessionId)) diskFrames.set(params.sessionId, new Map());
        diskFrames.get(params.sessionId)!.set(params.frameIndex, {
          index: params.frameIndex,
          ext: 'webp',
          timestamp: Date.now(),
          width: 512,
          height: 512,
          mimeType: 'image/webp',
          bytes,
          captureArea: 'artwork',
        });
        return { width: 512, height: 512, bytes: bytes.byteLength };
      }
    );

    const layers = [makeBaseLayer()];
    const dims = { width: 512, height: 512, dpi: 300 };

    // --- Session 1: enable recording, capture 3 frames, inspect slim external metadata, detach ---
    const mgr1 = new TimelapseRecorderManager({ minIntervalMs: 0 });
    mgr1.setRecording('doc-session-1', true, 'Illustration');
    mgr1.setCaptureArea('doc-session-1', 'artwork');
    mgr1.setCaptureResolution('doc-session-1', '4k');

    expect(await mgr1.captureKeyframe('doc-session-1', layers, dims, true)).toBe(true);
    expect(await mgr1.captureKeyframe('doc-session-1', layers, dims, true)).toBe(true);
    expect(await mgr1.captureKeyframe('doc-session-1', layers, dims, true)).toBe(true);

    const recId = mgr1.getRecordingId('doc-session-1');
    expect(recId).toBeTruthy();
    expect(mgr1.getStats('doc-session-1')).toMatchObject({
      recordingId: recId,
      enabled: true,
      frameCount: 3,
      diskFrames: 3,
      memoryBytes: 0,
      captureArea: 'artwork',
      captureResolution: '4k',
    });

    const recoveryMeta1 = mgr1.getRecoveryMetadata('doc-session-1');
    expect(recoveryMeta1).toMatchObject({
      recordingId: recId,
      storageMode: 'external',
      enabled: true,
      frameCount: 3,
      captureArea: 'artwork',
      captureResolution: '4k',
    });
    expect(recoveryMeta1?.frames).toBeUndefined();

    // App exit detaches session from RAM WITHOUT deleting external persistent frames
    await mgr1.detachSession('doc-session-1');
    expect(mgr1.getStats('doc-session-1').frameCount).toBe(0);
    expect(diskFrames.get(recId!)?.size).toBe(3);

    // --- Session 2: brand new manager after app restart reattaches via external metadata ---
    const mgr2 = new TimelapseRecorderManager({ minIntervalMs: 0 });
    const restored1 = await mgr2.attachOrRestoreSession('doc-session-2', {
      documentName: 'Illustration',
      metadata: recoveryMeta1,
      fallbackDims: dims,
    });
    expect(restored1).toEqual({ enabled: true, frameCount: 3 });
    expect(mgr2.getStats('doc-session-2')).toMatchObject({
      recordingId: recId,
      enabled: true,
      frameCount: 3,
      diskFrames: 3,
      memoryBytes: 0,
      captureArea: 'artwork',
      captureResolution: '4k',
    });

    // Byte-for-byte fidelity of all 3 externally persisted frames
    const frames2 = mgr2.getFrames('doc-session-2');
    expect(Array.from((await mgr2.loadFrameBytes('doc-session-2', frames2[0]))!)).toEqual(
      Array.from(f0)
    );
    expect(Array.from((await mgr2.loadFrameBytes('doc-session-2', frames2[2]))!)).toEqual(
      Array.from(f2)
    );

    // Continue drawing in Session 2 -> seamlessly appends frames 3 & 4
    expect(await mgr2.captureKeyframe('doc-session-2', layers, dims, true)).toBe(true);
    expect(await mgr2.captureKeyframe('doc-session-2', layers, dims, true)).toBe(true);
    expect(mgr2.getFrames('doc-session-2').map((f) => f.index)).toEqual([0, 1, 2, 3, 4]);

    const recoveryMeta2 = mgr2.getRecoveryMetadata('doc-session-2');

    // Detach again, launch Session 3 -> all 5 frames survive intact!
    await mgr2.detachSession('doc-session-2');
    const mgr3 = new TimelapseRecorderManager({ minIntervalMs: 0 });
    const restored2 = await mgr3.attachOrRestoreSession('doc-session-3', {
      documentName: 'Illustration',
      metadata: recoveryMeta2,
      fallbackDims: dims,
    });
    expect(restored2).toEqual({ enabled: true, frameCount: 5 });

    const frames3 = mgr3.getFrames('doc-session-3');
    for (let i = 0; i < payloads.length; i++) {
      const bytes = await mgr3.loadFrameBytes('doc-session-3', frames3[i]);
      expect(Array.from(bytes!)).toEqual(Array.from(payloads[i]));
    }

    // Explicit clearSession deletes persisted frames from disk
    await mgr3.clearSession('doc-session-3');
    expect(mgr3.getStats('doc-session-3').frameCount).toBe(0);
    expect(diskFrames.has(recId!)).toBe(false);
  });

  it('migrates legacy embedded frames into external storage and emits slim external metadata', async () => {
    const f0 = makeFakeWebpBytes(10, 36);
    const f1 = makeFakeWebpBytes(11, 36);
    stubCanvasForCapture([]);

    (globalThis as unknown as Record<string, unknown>).window = {
      __TAURI_INTERNALS__: {
        invoke: (...args: unknown[]) => mockTauriInvoke(...args),
      },
    };
    const { diskFrames } = installTauriPersistentDiskMock();

    const mgr = new TimelapseRecorderManager();
    const restored = await mgr.attachOrRestoreSession('doc-legacy', {
      documentName: 'LegacyArt',
      metadata: { enabled: false, frameCount: 2 },
      legacyFrames: [
        { index: 0, timestamp: 1000, width: 256, height: 256, mimeType: 'image/webp', bytes: f0 },
        { index: 1, timestamp: 2000, width: 256, height: 256, mimeType: 'image/webp', bytes: f1 },
      ],
    });
    expect(restored).toEqual({ enabled: false, frameCount: 2 });
    expect(mgr.isRecording('doc-legacy')).toBe(false);
    const migratedRecId = mgr.getRecordingId('doc-legacy')!;
    expect(diskFrames.get(migratedRecId)?.size).toBe(2);

    const slimMeta = mgr.getRecoveryMetadata('doc-legacy');
    expect(slimMeta?.storageMode).toBe('external');
    expect(slimMeta?.recordingId).toBe(migratedRecId);
    expect(slimMeta?.frames).toBeUndefined();
  });

  it('recovers persisted frames after a crash and supports listing stored recordings', async () => {
    const f0 = makeFakeWebpBytes(21, 44);
    const f1 = makeFakeWebpBytes(22, 46);
    const payloads = [f0, f1];
    let idx = 0;
    stubCanvasForCapture(payloads);

    (globalThis as unknown as Record<string, unknown>).window = {
      __TAURI_INTERNALS__: {
        invoke: (...args: unknown[]) => mockTauriInvoke(...args),
      },
    };
    const { diskFrames } = installTauriPersistentDiskMock();

    mockNativeTl.captureNativeTimelapseFrame.mockImplementation(
      async (params: { sessionId: string; frameIndex: number }) => {
        const bytes = payloads[idx++] ?? makeFakeWebpBytes(idx);
        if (!diskFrames.has(params.sessionId)) diskFrames.set(params.sessionId, new Map());
        diskFrames.get(params.sessionId)!.set(params.frameIndex, {
          index: params.frameIndex,
          ext: 'webp',
          timestamp: Date.now(),
          width: 512,
          height: 512,
          mimeType: 'image/webp',
          bytes,
          captureArea: 'artwork',
        });
        return { width: 512, height: 512, bytes: bytes.byteLength };
      }
    );

    const layers = [makeBaseLayer()];
    const dims = { width: 512, height: 512, dpi: 300 };

    const mgr1 = new TimelapseRecorderManager({ minIntervalMs: 0 });
    mgr1.setRecording('crash-doc', true, 'ComicPage01');
    await mgr1.captureKeyframe('crash-doc', layers, dims, true);
    await mgr1.captureKeyframe('crash-doc', layers, dims, true);
    await mgr1.waitForPendingCapture('crash-doc');

    const recoveryMeta = mgr1.getRecoveryMetadata('crash-doc');
    expect(recoveryMeta?.recordingId).toBeTruthy();

    // Simulate sudden crash (no detach called, new manager boots up)
    const crashMgr = new TimelapseRecorderManager({ minIntervalMs: 0 });
    const recovered = await crashMgr.restoreFromScratchDisk('crash-doc', recoveryMeta, dims);
    expect(recovered).toEqual({ enabled: true, frameCount: 2 });

    const library = await crashMgr.listStoredRecordings();
    expect(library).toHaveLength(1);
    expect(library[0].documentName).toBe('ComicPage01');
    expect(library[0].frameCount).toBe(2);
  });

  it('handles metadata-only timelapse sessions and packs binary batches accurately', async () => {
    const mgr = new TimelapseRecorderManager();
    const res = await mgr.restoreSession(
      'legacy-doc',
      { enabled: true, frameCount: 42 },
      undefined
    );
    expect(res).toEqual({ enabled: true, frameCount: 0 });
    expect(mgr.isRecording('legacy-doc')).toBe(true);

    // Binary batch packer format check
    const packed = packTimelapseFrameBatch([
      { index: 7, ext: 'webp', bytes: new Uint8Array([1, 2, 3]) },
      { index: 8, ext: 'jpg', bytes: new Uint8Array([9, 8]) },
    ]);
    const dv = new DataView(packed.buffer);
    expect(dv.getUint32(0, true)).toBe(2);
    expect(dv.getUint32(4, true)).toBe(7);
    expect(packed[8]).toBe(0);
    expect(dv.getUint32(9, true)).toBe(3);
    expect(Array.from(packed.subarray(13, 16))).toEqual([1, 2, 3]);
    expect(dv.getUint32(16, true)).toBe(8);
    expect(packed[20]).toBe(1);
    expect(dv.getUint32(21, true)).toBe(2);
    expect(Array.from(packed.subarray(25, 27))).toEqual([9, 8]);
  });
});

describe('DocumentLifecycleManager External Time-lapse Reconnect & Preserve on Close', () => {
  let root: Root | null = null;
  let container: MiniEl | null = null;
  let hookApi: ReturnType<typeof useDocumentLifecycle> | null = null;
  let prevDoc: unknown;
  let prevWin: unknown;
  let prevAct: unknown;

  beforeEach(() => {
    mockNativeTl.active = false;
    prevDoc = (globalThis as Record<string, unknown>).document;
    prevWin = (globalThis as Record<string, unknown>).window;
    prevAct = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;

    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
    const miniDoc = new MiniDoc();
    (globalThis as Record<string, unknown>).document = miniDoc;
    (globalThis as Record<string, unknown>).window = globalThis;
    (globalThis as Record<string, unknown>).HTMLElement = MiniEl;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = class HTMLIFrameElement {};
    (globalThis as Record<string, unknown>).Element = MiniEl;
    (globalThis as Record<string, unknown>).Node = MiniNode;

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

    useDocumentStore.reset();
    uiStoreActions.setAppView('home');
    hookApi = null;
  });

  afterEach(async () => {
    const activeId = useDocumentStore.getState().activeDocumentId;
    if (activeId) {
      await globalTimelapseManager.removeSession(activeId);
    }
    if (root) {
      act(() => {
        root?.unmount();
      });
    }
    root = null;
    container = null;
    await new Promise((r) => setTimeout(r, 0));
    delete (globalThis as unknown as Record<string, unknown>).__TAURI_INTERNALS__;
    mockTauriInvoke.mockReset();
    mockOpenFile.mockReset();
    (globalThis as Record<string, unknown>).document = prevDoc;
    (globalThis as Record<string, unknown>).window = prevWin;
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevAct;
    mockNativeTl.active = true;
  });

  it('migrates legacy .ink on open, preserves frames on tab close, and reconnects on reopen', async () => {
    (globalThis as unknown as Record<string, unknown>).__TAURI_INTERNALS__ = {
      invoke: (...args: unknown[]) => mockTauriInvoke(...args),
    };
    const { diskFrames } = installTauriPersistentDiskMock();

    const baseLayer = makeBaseLayer();
    const f0 = makeFakeWebpBytes(51, 32);
    const f1 = makeFakeWebpBytes(52, 32);

    mockOpenFile.mockResolvedValueOnce({
      name: 'AttachedTL',
      dimensions: { width: 256, height: 256, dpi: 300 },
      colorMode: 'color',
      layers: [baseLayer],
      timelapse: { recordingId: 'rec-lifecycle-1', enabled: true, frameCount: 2 },
      timelapseFrames: [
        { index: 0, timestamp: 1000, width: 256, height: 256, mimeType: 'image/webp', bytes: f0 },
        { index: 1, timestamp: 2000, width: 256, height: 256, mimeType: 'image/webp', bytes: f1 },
      ],
    });

    const showToast = vi.fn();
    const params: UseDocumentLifecycleParams = {
      layers: [baseLayer],
      activeLayer: baseLayer,
      activeLayerId: 'layer-1',
      getEffectiveOpacity: () => 1,
      isLayerEffectivelyVisible: () => true,
      setActiveLayerId: vi.fn(),
      resetToNewCanvas: vi.fn(() => ({ layers: [baseLayer], activeLayerId: 'layer-1' })),
      setDefaultToneFrequency: vi.fn(),
      clearDocument: vi.fn(),
      loadDocument: vi.fn(),
      switchDocumentSession: vi.fn(),
      resizeCanvas: vi.fn(),
      copyLayer: vi.fn(() => null),
      pasteLayer: vi.fn(async () => ({ success: false })),
      deleteLayer: vi.fn(),
      pasteLayerFromFile: vi.fn(async () => 'Pasted'),
      resetZoomAndCenter: vi.fn(),
      resetHistory: vi.fn(),
      pushHistoryStep: vi.fn(),
      showToast,
    };

    function Harness() {
      hookApi = useDocumentLifecycle(params);
      return null;
    }
    act(() => {
      root!.render(React.createElement(Harness));
    });

    const inkFile = new File([new Uint8Array([1, 2, 3])], 'AttachedTL.ink', {
      type: 'application/octet-stream',
    });

    await act(async () => {
      await hookApi!.handleProcessFile(inkFile);
    });

    const openedId = useDocumentStore.getState().activeDocumentId!;
    expect(openedId).toBeTruthy();
    expect(globalTimelapseManager.isRecording(openedId)).toBe(true);
    expect(globalTimelapseManager.getStats(openedId).frameCount).toBe(2);
    expect(showToast).toHaveBeenCalledWith(
      'Opened AttachedTL.ink — time-lapse resumed (2 frames)'
    );

    // Closing the tab detaches from RAM while PRESERVING frames in external disk storage!
    await act(async () => {
      hookApi!.handleCloseDocument(openedId);
    });
    expect(globalTimelapseManager.getStats(openedId).frameCount).toBe(0);
    expect(diskFrames.get('rec-lifecycle-1')?.size).toBe(2);

    // Reopening a slim external-pointer .ink reconnects straight to the 2 preserved frames!
    mockOpenFile.mockResolvedValueOnce({
      name: 'AttachedTL',
      dimensions: { width: 256, height: 256, dpi: 300 },
      colorMode: 'color',
      layers: [baseLayer],
      timelapse: {
        recordingId: 'rec-lifecycle-1',
        storageMode: 'external',
        enabled: true,
        frameCount: 2,
      },
    });

    await act(async () => {
      await hookApi!.handleProcessFile(
        new File([new Uint8Array([4, 5, 6])], 'AttachedTL.ink', {
          type: 'application/octet-stream',
        })
      );
    });

    const reopenedId = useDocumentStore.getState().activeDocumentId!;
    expect(globalTimelapseManager.isRecording(reopenedId)).toBe(true);
    expect(globalTimelapseManager.getStats(reopenedId).frameCount).toBe(2);
  });
});