Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

41.1 KB
Raw Blame
/** Keep builders dependency-free and derive fixtures from indices and a fixed epoch for repeatable baselines. */

export const MOCK_BACKEND_PROFILE_NAMES = Object.freeze(['empty', 'representative']);

export const MOCK_BACKEND_PROFILE_COUNTS = Object.freeze({
  empty: Object.freeze({
    images: 0,
    layers: 0,
    models: 0,
    nodes: 0,
    projects: 0,
    queueItems: 0,
    workflowNodes: 0,
  }),
  representative: Object.freeze({
    images: 1_000,
    layers: 64,
    models: 100,
    nodes: 100,
    projects: 40,
    queueItems: 500,
    workflowNodes: 100,
  }),
});

export const MOCK_BACKEND_FIXED_EPOCH = '2026-01-15T12:00:00.000Z';
export const MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME = 'fixture-video-001.mp4';

const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);
const range = (length, build) => Array.from({ length }, (_, index) => build(index));
const ordinal = (index, width = 3) => String(index + 1).padStart(width, '0');

/** The single user every fixture belongs to; matches `MOCK_USER_ID` in the mock backend. */
const FIXTURE_USER_ID = 'fixture-user';
const timestampAt = (index) => new Date(FIXED_EPOCH_MS - index * 60_000).toISOString();

export const isMockBackendProfileName = (value) => MOCK_BACKEND_PROFILE_NAMES.includes(value);

export const assertMockBackendProfileName = (value) => {
  if (!isMockBackendProfileName(value)) {
    throw new TypeError(
      `Unknown mock-backend profile ${JSON.stringify(value)}. Expected one of ${MOCK_BACKEND_PROFILE_NAMES.join(', ')}.`
    );
  }

  return value;
};

/** Reassigns existing images without changing the pinned image count. */
export const PROJECT_FILE_BOARD = Object.freeze({
  /** Generated, on the board, and drawn by the canvas: the overlap case. */
  referencedImage: 'fixture-image-0002.png',
  unreferencedImage: 'fixture-image-0005.png',
  userAsset: 'fixture-image-0006.png',
  maskAsset: 'fixture-image-0007.png',
  starredImage: 'fixture-image-0012.png',
  /** The canvas's private category. On the board, and it must never travel as board membership. */
  canvasOwnedImage: 'fixture-image-0008.png',
  intermediateImage: 'fixture-image-0009.png',
  video: 'fixture-video-project.mp4',
  /** Drawn by the canvas but owned by no project: reused on import, never copied. */
  externalImages: Object.freeze(['fixture-image-0001.png', 'fixture-image-0003.png', 'fixture-image-0004.png']),
  memberImages: Object.freeze(['fixture-image-0013.png', 'fixture-image-0014.png']),
});

export const PROJECT_FILE_MEMBER_BOARD = Object.freeze({ id: 'fixture-member-board-02', name: 'Site plan refs' });

const PROJECT_BOARD_IMAGES = new Map([
  [PROJECT_FILE_BOARD.referencedImage, { image_category: 'general' }],
  [PROJECT_FILE_BOARD.unreferencedImage, { image_category: 'general' }],
  [PROJECT_FILE_BOARD.starredImage, { image_category: 'general', starred: true }],
  [PROJECT_FILE_BOARD.userAsset, { image_category: 'user' }],
  [PROJECT_FILE_BOARD.maskAsset, { image_category: 'mask' }],
  [PROJECT_FILE_BOARD.canvasOwnedImage, { image_category: 'other' }],
  [PROJECT_FILE_BOARD.intermediateImage, { image_category: 'general', is_intermediate: true }],
]);
const MEMBER_BOARD_IMAGES = new Set(PROJECT_FILE_BOARD.memberImages);

const createImages = (count) =>
  range(count, (index) => {
    const id = ordinal(index, 4);
    const imageName = `fixture-image-${id}.png`;
    const boardIndex = index % 10;
    const imageCategory = index % 10 === 0 ? 'control' : 'general';
    const projectBoardMembership = PROJECT_BOARD_IMAGES.get(imageName);

    return {
      board_id: index % 8 === 0 ? null : `fixture-board-${ordinal(boardIndex, 2)}`,
      created_at: timestampAt(index),
      height: 512 + (index % 3) * 64,
      image_category: imageCategory,
      image_name: imageName,
      image_url: `/api/v1/images/i/${imageName}/full`,
      is_intermediate: false,
      starred: index % 11 === 0,
      thumbnail_url: `/api/v1/images/i/${imageName}/thumbnail`,
      width: 512 + (index % 4) * 64,
      ...(projectBoardMembership === undefined
        ? {}
        : { board_id: PROJECT_FILE_BOARD_ID, starred: false, ...projectBoardMembership }),
      ...(MEMBER_BOARD_IMAGES.has(imageName)
        ? { board_id: PROJECT_FILE_MEMBER_BOARD.id, image_category: 'general', starred: false }
        : {}),
    };
  });

/** The mock catalog serves no Wan main, so recall reports the model as not installed. */
const wanT2vMetadata = (positivePrompt, seed) => ({
  cfg_scale: 5,
  fps: 16,
  generation_mode: 'wan_t2v',
  height: 480,
  model: {
    base: 'wan',
    hash: 'blake3:fixture-wan-2-2-t2v-a14b',
    key: 'fixture-wan-t2v-a14b',
    name: 'Wan 2.2 T2V A14B',
    type: 'main',
  },
  negative_prompt: 'blurry, low quality, static frame',
  num_frames: 81,
  positive_prompt: positivePrompt,
  seed,
  steps: 30,
  width: 832,
});

const createVideos = () => [
  {
    board_id: null,
    created_at: timestampAt(2),
    duration: 1,
    fps: 10,
    graph: '{"nodes":[{"id":"fixture-video-output","type":"wan_l2v"}]}',
    height: 64,
    is_intermediate: false,
    metadata: wanT2vMetadata('wan fixture', 1234567),
    owner_user_id: 'fixture-user',
    starred: true,
    thumbnail_url: `/api/v1/videos/i/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}/thumbnail`,
    video_category: 'general',
    video_name: MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,
    video_origin: 'external',
    video_url: `/api/v1/videos/i/${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}/full`,
    width: 64,
    workflow: '{"name":"Fixture video workflow","nodes":[]}',
  },
  {
    board_id: 'fixture-board-02',
    created_at: timestampAt(0),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: false,
    metadata: wanT2vMetadata('board cover fixture', 2345678),
    owner_user_id: 'fixture-user',
    starred: true,
    thumbnail_url: '/api/v1/videos/i/fixture-video-board.mp4/thumbnail',
    video_category: 'control',
    video_name: 'fixture-video-board.mp4',
    video_origin: 'internal',
    video_url: '/api/v1/videos/i/fixture-video-board.mp4/full',
    width: 64,
    workflow: null,
  },
  {
    board_id: null,
    created_at: timestampAt(11),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: false,
    metadata: { prompt: 'same-name collision fixture' },
    owner_user_id: 'fixture-user',
    starred: true,
    thumbnail_url: '/api/v1/videos/i/fixture-image-0012.png/thumbnail',
    video_category: 'general',
    video_name: 'fixture-image-0012.png',
    video_origin: 'internal',
    video_url: '/api/v1/videos/i/fixture-image-0012.png/full',
    width: 64,
    workflow: null,
  },
  {
    board_id: 'fixture-board-03',
    created_at: timestampAt(2),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: false,
    metadata: { prompt: 'asset category fixture' },
    owner_user_id: 'fixture-user',
    starred: false,
    thumbnail_url: '/api/v1/videos/i/fixture-video-asset.mp4/thumbnail',
    video_category: 'control',
    video_name: 'fixture-video-asset.mp4',
    video_origin: 'internal',
    video_url: '/api/v1/videos/i/fixture-video-asset.mp4/full',
    width: 64,
    workflow: null,
  },
  {
    board_id: null,
    created_at: timestampAt(3),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: true,
    metadata: { prompt: 'intermediate fixture' },
    owner_user_id: 'fixture-user',
    starred: false,
    thumbnail_url: '/api/v1/videos/i/fixture-video-intermediate.mp4/thumbnail',
    video_category: 'general',
    video_name: 'fixture-video-intermediate.mp4',
    video_origin: 'internal',
    video_url: '/api/v1/videos/i/fixture-video-intermediate.mp4/full',
    width: 64,
    workflow: null,
  },
  {
    board_id: 'fixture-project-board-02',
    created_at: timestampAt(5),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: false,
    metadata: wanT2vMetadata('project board fixture', 3456789),
    owner_user_id: 'fixture-user',
    starred: false,
    thumbnail_url: '/api/v1/videos/i/fixture-video-project.mp4/thumbnail',
    video_category: 'general',
    video_name: 'fixture-video-project.mp4',
    video_origin: 'internal',
    video_url: '/api/v1/videos/i/fixture-video-project.mp4/full',
    width: 64,
    workflow: null,
  },
  {
    board_id: null,
    created_at: timestampAt(4),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: false,
    metadata: { prompt: 'foreign fixture' },
    owner_user_id: 'other-user',
    starred: false,
    thumbnail_url: '/api/v1/videos/i/fixture-video-foreign.mp4/thumbnail',
    video_category: 'general',
    video_name: 'fixture-video-foreign.mp4',
    video_origin: 'external',
    video_url: '/api/v1/videos/i/fixture-video-foreign.mp4/full',
    width: 64,
    workflow: null,
  },
  {
    board_id: null,
    created_at: timestampAt(800),
    duration: 1,
    fps: 10,
    graph: null,
    height: 64,
    is_intermediate: false,
    metadata: wanT2vMetadata('previous-day fixture', 4567890),
    owner_user_id: 'fixture-user',
    starred: false,
    thumbnail_url: '/api/v1/videos/i/fixture-video-old.mp4/thumbnail',
    video_category: 'general',
    video_name: 'fixture-video-old.mp4',
    video_origin: 'internal',
    video_url: '/api/v1/videos/i/fixture-video-old.mp4/full',
    width: 64,
    workflow: null,
  },
];

/** Only project APIs may rename/delete a project-owned board. */
export const projectBoardId = (index) => `fixture-project-board-${ordinal(index, 2)}`;

export const PROJECT_FILE_BOARD_ID = projectBoardId(1);

const buildBoard = (boardId, boardName, images, videos, createdAt, projectId = null) => {
  const boardImages = images.filter((image) => image.board_id === boardId);
  const boardVideos = videos.filter((video) => video.board_id === boardId);
  const cover = [
    ...boardImages.map((image) => ({
      createdAt: image.created_at,
      kind: 'image',
      name: image.image_name,
      starred: image.starred,
    })),
    ...boardVideos.map((video) => ({
      createdAt: video.created_at,
      kind: 'video',
      name: video.video_name,
      starred: video.starred,
    })),
  ].sort(
    (left, right) =>
      Number(right.starred) - Number(left.starred) ||
      right.createdAt.localeCompare(left.createdAt) ||
      right.kind.localeCompare(left.kind) ||
      right.name.localeCompare(left.name)
  )[0];

  return {
    archived: false,
    asset_count: boardImages.filter((image) => image.image_category !== 'general').length,
    board_id: boardId,
    board_name: boardName,
    general_access: 'restricted',
    cover_image_name: cover?.kind === 'image' ? cover.name : null,
    cover_video_name: cover?.kind === 'video' ? cover.name : null,
    created_at: createdAt,
    image_count: boardImages.filter((image) => image.image_category === 'general').length,
    owner_username: null,
    project_id: projectId,
    user_id: FIXTURE_USER_ID,
    video_count: boardVideos.length,
  };
};

export const fixtureProjectId = (index) => `fixture-project-${ordinal(index, 3)}`;

const createBoards = (images, videos, projectCount) => [
  ...range(10, (index) =>
    buildBoard(
      `fixture-board-${ordinal(index, 2)}`,
      `Fixture Board ${ordinal(index, 2)}`,
      images,
      videos,
      timestampAt(index * 10)
    )
  ),
  ...range(projectCount, (index) =>
    buildBoard(
      projectBoardId(index),
      `Fixture Project ${ordinal(index, 3)}`,
      images,
      videos,
      timestampAt(index),
      fixtureProjectId(index)
    )
  ),
  ...range(Math.min(projectCount, 2), (index) =>
    buildBoard(
      `fixture-member-board-${ordinal(index, 2)}`,
      index === 0 ? 'Façade variants' : 'Site plan refs',
      images,
      videos,
      timestampAt(index + 100),
      fixtureProjectId(index)
    )
  ),
];

const QUEUE_STATUSES = ['pending', 'waiting', 'in_progress', 'completed', 'failed', 'canceled'];

const createQueueItems = (count) =>
  range(count, (index) => {
    const itemId = index + 1;
    const status = QUEUE_STATUSES[index % QUEUE_STATUSES.length];
    const createdAt = timestampAt(index);
    const isSettled = status === 'completed' || status === 'failed' || status === 'canceled';

    return {
      batch_id: `fixture-batch-${ordinal(Math.floor(index / 4), 3)}`,
      completed_at: isSettled ? createdAt : null,
      created_at: createdAt,
      destination: index % 2 === 0 ? 'gallery' : 'canvas',
      error_message: status === 'failed' ? 'Synthetic fixture failure' : null,
      error_traceback: null,
      error_type: status === 'failed' ? 'FixtureError' : null,
      field_values: [
        {
          field_name: 'prompt',
          node_path: 'fixture_prompt',
          value: `Representative prompt ${itemId}`,
        },
      ],
      item_id: itemId,
      origin: `webv2:fixture-project-${ordinal(index % 40, 3)}:generate`,
      retried_from_item_id: null,
      session: { prepared_source_mapping: {}, results: {} },
      session_id: `fixture-session-${ordinal(index, 4)}`,
      started_at: status === 'pending' || status === 'waiting' ? null : createdAt,
      status,
      updated_at: createdAt,
      user_display_name: 'Fixture User',
      user_email: '[email protected]',
      user_id: 'fixture-user',
    };
  });

const MODEL_BASES = ['sd-1', 'sdxl', 'flux', 'flux2', 'qwen-image'];
const MODEL_TYPES = ['main', 'lora', 'controlnet', 'vae', 'embedding'];
const MAIN_MODEL_BASES = ['sd-1', 'sdxl', 'sdxl-refiner'];

/** The source of the hosted record the mock starter catalog also lists, so the Model Manager shows it read-only. */
export const CATALOG_MANAGED_EXTERNAL_SOURCE = 'external://gemini/gemini-2.5-flash-image';

/** No shipped provider accepts a mask, so none advertises inpaint. */
const EXTERNAL_MODEL_FIXTURES = [
  {
    base: 'external',
    capabilities: {
      allowed_aspect_ratios: ['1:1', '16:9', '9:16'],
      max_image_size: { height: 4096, width: 4096 },
      max_images_per_request: 1,
      max_reference_images: 14,
      modes: ['txt2img'],
      resolution_presets: ['1K', '2K'].flatMap((imageSize) =>
        [
          ['1:1', 1, 1],
          ['16:9', 16, 9],
          ['9:16', 9, 16],
        ].map(([ratio, w, h]) => {
          const base = imageSize === '1K' ? 1024 : 2048;
          const width = w >= h ? base : Math.round((base * w) / h);
          const height = w >= h ? Math.round((base * h) / w) : base;
          return {
            aspect_ratio: ratio,
            height,
            image_size: imageSize,
            label: `${ratio} (${imageSize}) — ${width}×${height}`,
            width,
          };
        })
      ),
      supports_reference_images: true,
      supports_seed: true,
    },
    cover_image: null,
    default_settings: { height: 1024, num_images: 1, width: 1024 },
    description: 'Fixture hosted model with named resolution presets and sampling options.',
    file_size: 0,
    format: 'external_api',
    hash: 'external:gemini:fixture-gemini-image',
    key: 'fixture-external-gemini',
    name: 'Fixture Gemini Image',
    path: 'external://gemini/fixture-gemini-image',
    provider_id: 'gemini',
    provider_model_id: 'fixture-gemini-image',
    source: 'external://gemini/fixture-gemini-image',
    source_type: 'external',
    source_url: null,
    type: 'external_image_generator',
  },
  {
    base: 'external',
    capabilities: {
      allowed_aspect_ratios: ['1:1', '3:2', '2:3'],
      aspect_ratio_sizes: {
        '1:1': { height: 1024, width: 1024 },
        '3:2': { height: 1024, width: 1536 },
        '2:3': { height: 1536, width: 1024 },
      },
      max_images_per_request: 10,
      modes: ['txt2img', 'img2img'],
      supports_reference_images: true,
    },
    cover_image: null,
    default_settings: { height: 1024, num_images: 1, width: 1024 },
    description: 'Fixture hosted model with fixed ratio sizes and canvas image-to-image.',
    file_size: 0,
    format: 'external_api',
    hash: 'external:openai:fixture-gpt-image',
    key: 'fixture-external-openai',
    name: 'Fixture GPT Image',
    path: 'external://openai/fixture-gpt-image',
    provider_id: 'openai',
    // A GPT Image id, so Generate offers OpenAI's quality, background and input-fidelity options.
    provider_model_id: 'gpt-image-1',
    source: 'external://openai/fixture-gpt-image',
    source_type: 'external',
    source_url: null,
    type: 'external_image_generator',
  },
  {
    base: 'external',
    capabilities: {
      allowed_aspect_ratios: ['1:1', '16:9'],
      aspect_ratio_sizes: { '1:1': { height: 2048, width: 2048 }, '16:9': { height: 1600, width: 2848 } },
      max_images_per_request: 15,
      max_reference_images: 14,
      modes: ['txt2img', 'img2img'],
      supports_reference_images: true,
    },
    cover_image: null,
    default_settings: { height: 2048, num_images: 1, width: 2048 },
    description: 'Fixture hosted model with provider toggles.',
    file_size: 0,
    format: 'external_api',
    hash: 'external:seedream:fixture-seedream',
    key: 'fixture-external-seedream',
    name: 'Fixture Seedream',
    path: 'external://seedream/fixture-seedream',
    provider_id: 'seedream',
    provider_model_id: 'fixture-seedream',
    source: 'external://seedream/fixture-seedream',
    source_type: 'external',
    source_url: null,
    type: 'external_image_generator',
  },
  {
    base: 'external',
    capabilities: {
      allowed_aspect_ratios: ['1:1', '16:9', '9:16'],
      max_images_per_request: 1,
      max_reference_images: 3,
      modes: ['txt2img'],
      supports_reference_images: true,
    },
    cover_image: null,
    default_settings: { height: 1024, num_images: 1, width: 1024 },
    description: 'Fixture hosted model whose capabilities the starter catalog manages.',
    file_size: 0,
    format: 'external_api',
    hash: 'external:gemini:gemini-2.5-flash-image',
    key: 'fixture-external-gemini-catalog',
    name: 'Fixture Gemini Flash (Catalog)',
    path: CATALOG_MANAGED_EXTERNAL_SOURCE,
    provider_id: 'gemini',
    provider_model_id: 'gemini-2.5-flash-image',
    source: CATALOG_MANAGED_EXTERNAL_SOURCE,
    source_type: 'external',
    source_url: null,
    type: 'external_image_generator',
  },
];

/** The last slots of the model library hold the hosted-provider records so the profile counts stay as declared. */
const createModels = (count) => [
  ...createLocalModels(Math.max(0, count - EXTERNAL_MODEL_FIXTURES.length)),
  ...EXTERNAL_MODEL_FIXTURES.slice(0, count).map((model) => ({ roles: [], ...structuredClone(model) })),
];

const createLocalModels = (count) =>
  range(count, (index) => {
    const id = ordinal(index);
    const type = MODEL_TYPES[index % MODEL_TYPES.length];
    const base =
      type === 'main'
        ? MAIN_MODEL_BASES[Math.floor(index / MODEL_TYPES.length) % MAIN_MODEL_BASES.length]
        : MODEL_BASES[index % MODEL_BASES.length];

    // Like the backend, a config serializes only the fields it stores.
    return {
      base,
      cover_image: null,
      ...(type === 'vae' ? { cpu_only: null } : {}),
      default_settings: type === 'main' ? { cfg_scale: 7, height: 1024, steps: 30, width: 1024 } : null,
      description: `Deterministic representative ${type} model ${id}.`,
      file_size: 512_000_000 + index * 1_024,
      format: type === 'embedding' ? 'embedding_file' : 'checkpoint',
      hash: `fixture-hash-${id}`,
      key: `fixture-model-${id}`,
      name: `Fixture Model ${id}`,
      path: `fixtures/models/fixture-model-${id}.safetensors`,
      roles: [],
      source: `fixtures/models/fixture-model-${id}.safetensors`,
      source_type: 'path',
      source_url: null,
      source_urls:
        index === 0
          ? ['https://example.invalid/models/fixture-model', 'https://example.invalid/models/fixture-model-quantized']
          : [],
      ...(type === 'lora' ? { trigger_phrases: [`fixture-style-${id}`] } : {}),
      ...(type === 'main' ? { trigger_phrases: null } : {}),
      type,
    };
  });

/** Main, LoRA and Control LoRA seeds add `trigger_phrases`, which only those configs store. */
const seedModel = ({ key, name, ...fields }) => ({
  base: 'any',
  cover_image: null,
  default_settings: null,
  description: null,
  file_size: 32_000_000,
  format: 'checkpoint',
  hash: `seed-hash-${key}`,
  key,
  name,
  path: `seeds/${key}.safetensors`,
  roles: [],
  source: `seeds/${key}.safetensors`,
  source_type: 'path',
  source_url: null,
  variant: null,
  ...fields,
});

const controlSeed = (name, base, preprocessor, fields = {}) => ({
  record: seedModel({
    base,
    default_settings: preprocessor === null ? null : { preprocessor },
    key: `seed-${name}`,
    name,
    type: 'controlnet',
    ...fields,
  }),
});

/** Sets for `POST /__models`; `probe` is what reidentify fills in for a record installed before it recorded them. */
export const MODEL_SEED_SETS = Object.freeze({
  'anima-lllite': [
    {
      record: seedModel({
        base: 'anima',
        key: 'seed-anima-main',
        name: 'Anima Preview',
        trigger_phrases: null,
        type: 'main',
      }),
    },
    {
      record: seedModel({
        base: 'anima',
        cond_in_channels: 3,
        key: 'seed-lllite-sketch',
        name: 'Anima LLLite Sketch',
        type: 'controlnet',
      }),
    },
    {
      probe: { cond_in_channels: 3 },
      record: seedModel({
        base: 'anima',
        cond_in_channels: null,
        key: 'seed-lllite-lineart',
        name: 'Anima LLLite Lineart (old install)',
        type: 'controlnet',
      }),
    },
    {
      probe: { cond_in_channels: 4 },
      record: seedModel({
        base: 'anima',
        cond_in_channels: null,
        key: 'seed-lllite-inpaint',
        name: 'Anima LLLite Inpainting (old install)',
        type: 'controlnet',
      }),
    },
  ],
  spandrel: [
    {
      record: seedModel({ key: 'seed-spandrel-4x', name: '4x-UltraSharp', scale: 4, type: 'spandrel_image_to_image' }),
    },
    {
      record: seedModel({ key: 'seed-spandrel-2x', name: '2x-AnimeSharp', scale: 2, type: 'spandrel_image_to_image' }),
    },
    { record: seedModel({ key: 'seed-spandrel-1x', name: '1x-Denoise', scale: 1, type: 'spandrel_image_to_image' }) },
    {
      probe: { scale: 4 },
      record: seedModel({
        key: 'seed-spandrel-legacy',
        name: 'RealESRGAN x4 (old install)',
        scale: null,
        type: 'spandrel_image_to_image',
      }),
    },
  ],
  'control-sdxl': [
    controlSeed('controlnet-depth-sdxl-1.0', 'sdxl', 'depth_anything_image_processor'),
    controlSeed('controlnet-zoe-depth-sdxl', 'sdxl', 'depth_anything_depth_estimation'),
    controlSeed('thibaud-openpose-sdxl', 'sdxl', 'dw_openpose_image_processor'),
    controlSeed('xinsir-controlnet-union-sdxl-promax', 'sdxl', null),
    controlSeed('my-sdxl-control', 'sdxl', null),
    controlSeed('t2i-adapter-canny-sdxl-1.0', 'sdxl', 'canny_image_processor', {
      format: 'diffusers',
      type: 't2i_adapter',
    }),
  ],
  'control-flux': [
    {
      record: seedModel({
        base: 'flux',
        key: 'seed-flux-dev',
        name: 'FLUX.1 dev',
        trigger_phrases: null,
        type: 'main',
        variant: 'dev',
      }),
    },
    controlSeed('flux-depth-control-lora', 'flux', 'depth_anything_image_processor', {
      format: 'lycoris',
      trigger_phrases: null,
      type: 'control_lora',
    }),
    controlSeed('flux-controlnet-union-pro', 'flux', null),
  ],
  // A Krea-2 Turbo main with a depth Control LoRA, Krea-2's only control kind.
  'control-krea2': [
    {
      record: seedModel({
        base: 'krea-2',
        format: 'diffusers',
        key: 'seed-krea2-turbo',
        name: 'Krea-2 Turbo',
        trigger_phrases: null,
        type: 'main',
        variant: 'krea2_turbo',
      }),
    },
    controlSeed('krea2-depth-control-lora', 'krea-2', 'depth_anything_image_processor', {
      format: 'lycoris',
      trigger_phrases: null,
      type: 'control_lora',
    }),
  ],
  // Models whose files also serve as another type: single-file MOSS-Image and Z-Image mains with their VAEs, a Text
  // LLM that is also the Qwen3.5 9B encoder, a Qwen3.5 encoder that is also a Text LLM, and a Qwen3 4B causal-LM
  // folder that is also the Qwen3 encoder.
  'model-roles': [
    {
      record: seedModel({
        base: 'moss-image',
        key: 'seed-moss-image-main',
        name: 'MOSS-Image (single file)',
        trigger_phrases: null,
        type: 'main',
      }),
    },
    {
      record: seedModel({ base: 'flux2', cpu_only: null, key: 'seed-flux2-vae', name: 'FLUX.2 VAE', type: 'vae' }),
    },
    {
      record: seedModel({
        cpu_only: null,
        key: 'seed-text-llm-qwen35-9b',
        name: 'Qwen3.5 9B VLM (int8)',
        roles: [{ format: null, type: 'qwen3_5_encoder', variant: 'qwen3_5_9b' }],
        supports_images: true,
        type: 'text_llm',
        variant: undefined,
      }),
    },
    {
      record: seedModel({
        cpu_only: null,
        key: 'seed-qwen35-encoder-9b',
        name: 'Qwen3.5 9B Encoder (int8)',
        roles: [{ format: null, type: 'text_llm', variant: null }],
        type: 'qwen3_5_encoder',
        variant: 'qwen3_5_9b',
      }),
    },
    {
      record: seedModel({
        base: 'z-image',
        key: 'seed-z-image-main',
        name: 'Z-Image (single file)',
        trigger_phrases: null,
        type: 'main',
      }),
    },
    { record: seedModel({ base: 'flux', cpu_only: null, key: 'seed-flux-vae', name: 'FLUX VAE', type: 'vae' }) },
    {
      record: seedModel({
        cpu_only: null,
        format: 'diffusers',
        key: 'seed-qwen3-4b-llm',
        name: 'Qwen3 4B',
        roles: [{ format: 'qwen3_encoder', type: 'qwen3_encoder', variant: 'qwen3_4b' }],
        type: 'text_llm',
        variant: undefined,
      }),
    },
  ],
});

const createNodePacks = (nodeCount) =>
  range(Math.ceil(nodeCount / 5), (packIndex) => {
    const firstNodeIndex = packIndex * 5;
    const nodeTypes = range(Math.min(5, nodeCount - firstNodeIndex), (nodeOffset) => {
      const nodeIndex = firstNodeIndex + nodeOffset;

      return `mock_node_${ordinal(nodeIndex)}`;
    });

    return {
      name: `fixture-pack-${ordinal(packIndex, 2)}`,
      node_count: nodeTypes.length,
      node_types: nodeTypes,
      path: `/opt/invokeai/nodes/fixture-pack-${ordinal(packIndex, 2)}`,
    };
  });

const createOpenApiDocument = (nodeCount) => {
  const outputSchema = {
    class: 'output',
    properties: {
      type: { const: 'fixture_output', default: 'fixture_output' },
      value: { field_kind: 'output', title: 'Value', type: 'string' },
    },
    type: 'object',
  };
  const invocationSchemas = Object.fromEntries(
    range(nodeCount, (index) => {
      const id = ordinal(index);
      const type = `mock_node_${id}`;

      return [
        `FixtureNode${id}Invocation`,
        {
          category: `fixture-${(index % 5) + 1}`,
          class: 'invocation',
          classification: 'stable',
          description: `Synthetic invocation template ${id}.`,
          node_pack: `fixture-pack-${ordinal(Math.floor(index / 5), 2)}`,
          output: { $ref: '#/components/schemas/FixtureOutput' },
          properties: {
            prompt: {
              default: '',
              field_kind: 'input',
              input: 'direct',
              orig_required: false,
              title: 'Prompt',
              type: 'string',
              ui_hidden: false,
            },
            type: { const: type, default: type, title: 'type' },
            use_cache: { default: true, field_kind: 'internal', type: 'boolean' },
          },
          tags: ['fixture'],
          title: `Fixture Node ${id}`,
          type: 'object',
          version: '1.0.0',
        },
      ];
    })
  );

  return {
    components: { schemas: { FixtureOutput: outputSchema, ...invocationSchemas } },
    info: { title: 'InvokeAI deterministic mock', version: '1.0.0' },
    openapi: '3.1.0',
    paths: {},
  };
};

const createWorkflowNodes = (count) =>
  range(count, (index) => {
    const id = ordinal(index);

    return {
      data: {
        inputs: { prompt: { label: '', name: 'prompt', value: `Fixture node ${id}` } },
        isIntermediate: true,
        isOpen: true,
        label: `Fixture Node ${id}`,
        nodePack: `fixture-pack-${ordinal(Math.floor(index / 5), 2)}`,
        notes: '',
        type: `mock_node_${id}`,
        useCache: true,
        version: '1.0.0',
      },
      id: `fixture-workflow-node-${id}`,
      position: { x: (index % 10) * 320, y: Math.floor(index / 10) * 240 },
      type: 'invocation',
    };
  });

const createCanvasLayers = (count) =>
  range(count, (index) => {
    const id = ordinal(index);
    const imageName = `fixture-image-${ordinal(index, 4)}.png`;

    return {
      blendMode: 'normal',
      id: `fixture-layer-${id}`,
      isEnabled: true,
      isLocked: false,
      name: `Fixture Layer ${id}`,
      opacity: 1,
      source: {
        image: { height: 512, imageName, width: 512 },
        type: 'image',
      },
      transform: {
        rotation: 0,
        scaleX: 1,
        scaleY: 1,
        x: (index % 8) * 32,
        y: Math.floor(index / 8) * 32,
      },
      type: 'raster',
    };
  });

const createProjectFileWorkflowNodes = () => {
  const [node] = createWorkflowNodes(1);

  return [
    {
      ...node,
      data: {
        ...node.data,
        inputs: {
          ...node.data.inputs,
          video: {
            label: '',
            name: 'video',
            value: { video_name: MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME },
          },
        },
      },
    },
  ];
};

/** Match LAYER_STACK_ORDER and preorder within each forest; plain JS cannot import the TypeScript constant. */
export const collectCanvasLeaves = (document) => {
  const leaves = [];
  const visit = (nodes) => {
    for (const node of nodes ?? []) {
      if (node.type === 'group') {
        visit(node.children);
      } else {
        leaves.push(node);
      }
    }
  };
  for (const stack of ['raster', 'control', 'regional_guidance', 'inpaint_mask']) {
    visit(document?.stacks?.[stack]);
  }
  return leaves;
};

const createRasterForest = (layers) => {
  if (layers.length < 32) {
    return layers;
  }
  const group = (id, name, children, overrides = {}) => ({
    children,
    id,
    isEnabled: true,
    isLocked: false,
    name,
    type: 'group',
    ...overrides,
  });
  return [
    ...layers.slice(0, 8),
    group('fixture-group-001', 'Fixture Group 001', [
      ...layers.slice(8, 12),
      group('fixture-group-002', 'Fixture Group 002', layers.slice(12, 16), { isEnabled: false }),
      ...layers.slice(16, 20),
    ]),
    ...layers.slice(20, 28),
    group('fixture-group-003', 'Fixture Group 003', layers.slice(28, 32), { isLocked: true }),
    ...layers.slice(32),
  ];
};

const createWorkflowDocument = ({ description, graphId, index, name, workflowNodes }) => {
  const formRootId = `${graphId}-form-root`;

  return {
    author: 'InvokeAI',
    contact: '',
    description,
    edges: [],
    form: {
      elements: {
        [formRootId]: {
          data: { children: [], layout: 'column' },
          id: formRootId,
          type: 'container',
        },
      },
      rootElementId: formRootId,
    },
    id: graphId,
    name,
    nodes: workflowNodes,
    notes: '',
    tags: 'fixture',
    updatedAt: timestampAt(index),
    version: 2,
    workflowVersion: '1.0.0',
  };
};

/** Project 0 is schema 3 with two workflows; project 1 stays schema 2 for the project-file journey's migration. */
const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {
  const id = fixtureProjectId(index);
  const graphId = `${id}-graph`;
  const primaryWorkflow = createWorkflowDocument({
    description: index === 0 ? 'Representative 100-node workflow.' : '',
    graphId,
    index,
    name: index === 0 ? 'Representative Workflow' : 'Empty Workflow',
    workflowNodes,
  });
  const workflows =
    index === 1
      ? null
      : {
          activeWorkflowId: graphId,
          entries: [
            { document: primaryWorkflow },
            ...(index === 0
              ? [
                  {
                    document: createWorkflowDocument({
                      description: 'A second, blank workflow beside the representative graph.',
                      graphId: `${id}-graph-2`,
                      index,
                      name: 'Second Workflow',
                      workflowNodes: [],
                    }),
                  },
                ]
              : []),
          ],
        };

  return {
    canvas: {
      document: {
        background: 'transparent',
        bbox: { height: 1024, width: 1024, x: 0, y: 0 },
        height: 1024,
        selectedLayerId: layers[0]?.id ?? null,
        stacks: { control: [], inpaint_mask: [], raster: createRasterForest(layers), regional_guidance: [] },
        version: 3,
        width: 1024,
      },
      documentRevision: 0,
      snapshots: [],
      stagingArea: {
        areThumbnailsVisible: true,
        autoSwitchMode: 'off',
        isVisible: false,
        pendingImageIds: [],
        pendingImages: [],
        selectedImageIndex: 0,
      },
      version: 3,
    },
    id,
    invocation: {
      destination: 'gallery',
      destinationLocked: false,
      sourceId: workflowNodes.length > 0 ? 'workflow' : 'generate',
      sourceLocked: false,
    },
    ...(workflows ? { documentSchemaVersion: 3 } : { documentSchemaVersion: 2 }),
    layout: {
      centerViewId: 'preview',
      panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },
      presetId: 'canvas-default',
    },
    name: `Fixture Project ${ordinal(index, 3)}`,
    promptHistory: [],
    ...(workflows ? { workflows } : { projectGraph: primaryWorkflow }),
    queue: { items: [] },
    settings: {},
    widgetGraphs: {},
  };
};

export const getFixtureProjectWorkflowDocument = (data) =>
  data?.workflows?.entries?.[0]?.document ?? data?.projectGraph ?? null;

const createProjects = (count, workflowNodeCount, layerCount) =>
  range(count, (index) => {
    const data = createProjectDocument({
      index,
      layers: index === 0 ? createCanvasLayers(layerCount) : index === 1 ? createCanvasLayers(4) : [],
      workflowNodes:
        index === 0 ? createWorkflowNodes(workflowNodeCount) : index === 1 ? createProjectFileWorkflowNodes() : [],
    });
    const timestamp = timestampAt(index);

    return {
      // Every project owns exactly one private board; the server is authoritative for which.
      board_id: projectBoardId(index),
      created_at: timestamp,
      data,
      minimum_canvas_schema_version: 3,
      name: data.name,
      project_id: data.id,
      revision: 1,
      updated_at: timestamp,
    };
  });

const createWorkflows = (count) =>
  range(count, (index) => {
    const id = ordinal(index);

    return {
      category: index % 4 === 0 ? 'default' : 'user',
      created_at: timestampAt(index),
      description: `Synthetic workflow library entry ${id}.`,
      name: `Fixture Workflow ${id}`,
      opened_at: index % 3 === 0 ? timestampAt(index) : null,
      revision: 1,
      tags: 'fixture,representative',
      thumbnail_url: null,
      updated_at: timestampAt(index),
      workflow: {
        author: 'InvokeAI',
        contact: '',
        description: `Synthetic workflow library entry ${id}.`,
        edges: [],
        exposedFields: [],
        form: { elements: {}, rootElementId: '' },
        meta: { category: 'user', version: '3.0.0' },
        name: `Fixture Workflow ${id}`,
        nodes: [],
        notes: '',
        tags: 'fixture',
        version: '3.0.0',
        workflowVersion: '1.0.0',
      },
      // Bundled ids carry the server's `default_` prefix; the client treats those templates as read-only.
      workflow_id: index % 4 === 0 ? `default_fixture-workflow-${id}` : `fixture-workflow-${id}`,
    };
  });

export const createLargeWorkflowLibraryFixture = () =>
  createWorkflows(1000).map((record, index) => ({
    ...record,
    category: 'user',
    workflow_id: `large-workflow-${String(index).padStart(4, '0')}`,
    workflow: {
      ...record.workflow,
      nodes: range(40, (node) => ({
        id: `node-${node}`,
        type: 'invocation',
        position: { x: node * 100, y: 0 },
        data: { type: 'integer', inputs: { value: { name: 'value', value: node, label: '' } } },
      })),
    },
  }));

const createIntermediates = () => [
  {
    user_id: 'fixture-user',
    user_display_name: 'Fixture User',
    user_email: '[email protected]',
    project_id: 'fixture-project-001',
    project_name: 'Fixture Project 001',
    cover_image_name: 'fixture-image-0002.png',
    images: { safe: 128, referenced: 6, active: 2, recent: 4 },
    videos: { safe: 3, referenced: 1, active: 0, recent: 0 },
    reclaimable_bytes: 2_580_000_000,
    referenced_bytes: 120_000_000,
    unknown_size_count: 0,
  },
  {
    user_id: 'fixture-user',
    user_display_name: 'Fixture User',
    user_email: '[email protected]',
    project_id: 'fixture-project-002',
    project_name: 'Fixture Project 002',
    cover_image_name: null,
    images: { safe: 12, referenced: 0, active: 0, recent: 1 },
    videos: { safe: 0, referenced: 0, active: 0, recent: 0 },
    reclaimable_bytes: 96_000_000,
    referenced_bytes: 0,
    unknown_size_count: 3,
  },
  {
    user_id: 'fixture-user',
    user_display_name: 'Fixture User',
    user_email: '[email protected]',
    project_id: null,
    project_name: null,
    cover_image_name: null,
    images: { safe: 40, referenced: 0, active: 0, recent: 0 },
    videos: { safe: 1, referenced: 0, active: 0, recent: 0 },
    reclaimable_bytes: 410_000_000,
    referenced_bytes: 0,
    unknown_size_count: 0,
  },
];

const createEmptyFixture = () => ({
  boards: [],
  images: [],
  intermediates: [],
  models: [],
  nodeCatalog: { custom_nodes_path: '/opt/invokeai/nodes', node_packs: [] },
  openApiDocument: createOpenApiDocument(0),
  profile: 'empty',
  projects: [],
  queueItems: [],
  videos: [],
  workflows: [],
});

const createRepresentativeFixture = () => {
  const counts = MOCK_BACKEND_PROFILE_COUNTS.representative;
  const images = createImages(counts.images);
  const videos = createVideos();

  return {
    boards: createBoards(images, videos, counts.projects),
    images,
    intermediates: createIntermediates(),
    models: createModels(counts.models),
    nodeCatalog: {
      custom_nodes_path: '/opt/invokeai/nodes',
      node_packs: createNodePacks(counts.nodes),
    },
    openApiDocument: createOpenApiDocument(counts.nodes),
    profile: 'representative',
    projects: createProjects(counts.projects, counts.workflowNodes, counts.layers),
    queueItems: createQueueItems(counts.queueItems),
    videos,
    workflows: createWorkflows(100),
  };
};

export const createMockBackendFixture = (profile = 'empty') => {
  assertMockBackendProfileName(profile);

  return profile === 'representative' ? createRepresentativeFixture() : createEmptyFixture();
};

const countInvocationSchemas = (fixture) =>
  Object.values(fixture.openApiDocument?.components?.schemas ?? {}).filter((schema) => schema?.class === 'invocation')
    .length;

export const getMockBackendFixtureCounts = (fixture) => ({
  images: fixture.images.length,
  layers: collectCanvasLeaves(fixture.projects[0]?.data?.canvas?.document).length,
  models: fixture.models.length,
  nodes: countInvocationSchemas(fixture),
  projects: fixture.projects.length,
  queueItems: fixture.queueItems.length,
  workflowNodes: getFixtureProjectWorkflowDocument(fixture.projects[0]?.data)?.nodes?.length ?? 0,
});

const findDuplicates = (values) => {
  const seen = new Set();
  const duplicates = new Set();

  for (const value of values) {
    if (seen.has(value)) {
      duplicates.add(value);
    }
    seen.add(value);
  }

  return [...duplicates];
};

export const validateMockBackendFixture = (fixture) => {
  const failures = [];

  if (!isMockBackendProfileName(fixture?.profile)) {
    failures.push(`fixture.profile must be one of ${MOCK_BACKEND_PROFILE_NAMES.join(', ')}`);
    return failures;
  }

  const expected = MOCK_BACKEND_PROFILE_COUNTS[fixture.profile];
  const received = getMockBackendFixtureCounts(fixture);

  for (const [name, expectedCount] of Object.entries(expected)) {
    if (received[name] !== expectedCount) {
      failures.push(`${fixture.profile}.${name}: expected ${expectedCount}, received ${received[name]}`);
    }
  }

  const identities = [
    ['image names', fixture.images.map((image) => image.image_name)],
    ['model keys', fixture.models.map((model) => model.key)],
    ['project ids', fixture.projects.map((project) => project.project_id)],
    ['queue item ids', fixture.queueItems.map((item) => item.item_id)],
    ['video names', fixture.videos.map((video) => video.video_name)],
  ];

  for (const [label, values] of identities) {
    const duplicates = findDuplicates(values);

    if (duplicates.length > 0) {
      failures.push(`${label} must be unique; duplicated ${duplicates.join(', ')}`);
    }
  }

  const nodeTypes = fixture.nodeCatalog.node_packs.flatMap((pack) => pack.node_types);
  const invocationTypes = Object.values(fixture.openApiDocument.components.schemas)
    .filter((schema) => schema?.class === 'invocation')
    .map((schema) => schema.properties?.type?.const);

  if (JSON.stringify(nodeTypes) !== JSON.stringify(invocationTypes)) {
    failures.push('custom-node catalog types and OpenAPI invocation types must match in deterministic order');
  }

  return failures;
};

export const assertMockBackendFixture = (fixture) => {
  const failures = validateMockBackendFixture(fixture);

  if (failures.length > 0) {
    throw new Error(`Invalid mock-backend fixture:\n- ${failures.join('\n- ')}`);
  }

  return fixture;
};