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.

141 KB
Raw Blame
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { resolve } from 'node:path';

import {
  assertMockBackendFixture,
  assertMockBackendProfileName,
  CATALOG_MANAGED_EXTERNAL_SOURCE,
  collectCanvasLeaves,
  createMockBackendFixture,
  createLargeWorkflowLibraryFixture,
  getFixtureProjectWorkflowDocument,
  getMockBackendFixtureCounts,
  MOCK_BACKEND_FIXED_EPOCH,
  MODEL_SEED_SETS,
} from './mock-backend-fixtures.mjs';
import { fixturePng, mediaDimensions } from './mock-media.mjs';
import { createWorkingMemoryMock, WORKING_MEMORY_SCENARIOS } from './mock-working-memory.mjs';

/** The canvas schema every mock project declares; the real server keeps the same floor per record. */
const DEFAULT_CANVAS_SCHEMA_VERSION = 3;

const schemaUnsupported = (minimum, maximum) => [
  412,
  {
    detail: {
      code: 'canvas_schema_unsupported',
      max_canvas_schema_version: maximum,
      message: `Project requires canvas schema ${minimum}; client supports up to ${maximum}.`,
      minimum_canvas_schema_version: minimum,
    },
  },
];

const clientMaximum = (value) => (Number.isInteger(value) && value >= 1 ? value : DEFAULT_CANVAS_SCHEMA_VERSION);

/** A project saved whole; from 4 the record holds its content and each member's workspace apart. */
const DEFAULT_DOCUMENT_SCHEMA_VERSION = 3;
const SPLIT_DOCUMENT_SCHEMA_VERSION = 4;

const documentSchemaUnsupported = (minimum, maximum) => [
  412,
  {
    detail: {
      code: 'document_schema_unsupported',
      max_document_schema_version: maximum,
      message: `Project requires document schema ${minimum}; client supports up to ${maximum}.`,
      minimum_document_schema_version: minimum,
    },
  },
];

const documentMaximum = (value) => (Number.isInteger(value) && value >= 1 ? value : DEFAULT_DOCUMENT_SCHEMA_VERSION);

/** A write's answer: the content; the caller's workspace goes beside it only where the write stored one. */
const writtenRecordOf = ({ workspace, ...project }) => ({
  ...project,
  workspace_updated_at: workspace?.updated_at ?? null,
});

/** In-memory test backend; no Socket.IO. POST /__reset restores the startup profile unless ?profile= overrides it. */

const FIXED_EPOCH_MS = Date.parse(MOCK_BACKEND_FIXED_EPOCH);
const FIXTURE_VIDEO = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.mp4'));
const FIXTURE_VIDEO_POSTER = readFileSync(resolve(import.meta.dirname, 'mock-assets/fixture-video.webp'));
const ARCHITECTURE_CAPABILITIES = JSON.parse(
  readFileSync(
    resolve(import.meta.dirname, '../src/features/models/core/__fixtures__/architectureCapabilities.json'),
    'utf8'
  )
);

/**
 * POST /__faults overrides until POST /__reset: capabilities, `intermediatesCaller` (user/multiuser-admin enable auth),
 * `sharedBoards`, `imageMoves` (idle/needs-recovery/failed/instant) and calibration (mock-working-memory.mjs).
 */
const CAPABILITY_FAULTS = new Set(['ok', 'error', 'empty']);
const INTERMEDIATES_CALLERS = new Set(['admin', 'user', 'multiuser-admin']);
const IMAGE_MOVE_FAULTS = new Set(['idle', 'needs-recovery', 'failed', 'instant']);
const IMAGE_MOVE_MAINTENANCE_DETAIL = 'Image storage maintenance is active';
/** The job states the real service counts as finished; any other journaled job still needs recovery. */
const FINISHED_IMAGE_MOVE_JOB_STATES = new Set(['committed', 'error']);
const IMAGE_STORAGE_LAYOUTS = new Set(['flat', 'date', 'type', 'hash']);
const IMAGE_MOVE_TICKS = 2;

const createFaults = () => ({
  capabilities: 'ok',
  imageMoves: 'idle',
  intermediatesCaller: 'admin',
  workingMemory: 'ok',
});

/** Fixture images are stored flat, so a move counts the whole library whenever the layout differs. */
const createImageStorage = () => ({
  layout: 'flat',
  storedLayout: 'flat',
  job: null,
  lastError: null,
  nextJobId: 1,
  running: null,
});

const imageMoveStatus = (state) => {
  const storage = state.imageStorage;

  return {
    active_job_id:
      storage.job !== null && !FINISHED_IMAGE_MOVE_JOB_STATES.has(storage.job.state) ? storage.job.id : null,
    is_running: storage.running !== null,
    last_error: storage.lastError,
    latest_job: storage.job === null ? null : { ...storage.job },
    needs_move_count: storage.layout === storage.storedLayout ? 0 : state.images.size,
    operation: storage.running?.operation ?? null,
  };
};

const seedInterruptedImageMove = (state) => {
  const storage = state.imageStorage;

  storage.job = { error_message: null, id: storage.nextJobId, state: 'moving' };
  storage.nextJobId += 1;
  storage.lastError = 'Server stopped during an image move';
};

const seedFailedImageMove = (state) => {
  const storage = state.imageStorage;

  storage.job = { error_message: 'Disk full while moving images', id: storage.nextJobId, state: 'error' };
  storage.nextJobId += 1;
  storage.lastError = 'Disk full while moving images';
};

const commitImageMove = (state) => {
  const storage = state.imageStorage;

  if (storage.running.operation === 'move_all') {
    storage.storedLayout = storage.layout;
  }
  if (storage.job !== null) {
    storage.job = { ...storage.job, state: 'committed' };
  }
  storage.running = null;
};

/** An `instant` move commits before the POST answers, as a tiny library does on the real server. */
const startImageMoveOperation = (state, operation, { instant = false } = {}) => {
  const storage = state.imageStorage;

  if (operation === 'move_all') {
    storage.job = { error_message: null, id: storage.nextJobId, state: 'moving' };
    storage.nextJobId += 1;
  }
  storage.lastError = null;
  storage.running = { operation, ticks: IMAGE_MOVE_TICKS };
  if (instant) {
    commitImageMove(state);
  }
};

const tickImageMove = (state) => {
  const storage = state.imageStorage;

  if (storage.running === null) {
    return;
  }
  storage.running.ticks -= 1;
  if (storage.running.ticks === 0) {
    commitImageMove(state);
  }
};

/** Mirrors `is_maintenance_active`: a running operation, or a journaled job that has not finished. */
const isImageMoveMaintenanceActive = (state) =>
  state.imageStorage.running !== null || imageMoveStatus(state).active_job_id !== null;

/** Mirrors `has_active_queue_work`, which gates Start Move: any queue item pending or in progress. */
const hasActiveQueueWork = (state) =>
  [...state.queueItems.values()].some((item) => item.status === 'pending' || item.status === 'in_progress');

/** Mirrors the real maintenance guard: media mutations and files refuse; listings and DTO reads stay open. */
const isImageMoveMaintenanceRoute = (method, path, url) => {
  if (path.startsWith('/api/v1/board_images')) {
    return true;
  }
  if (path.startsWith('/api/v1/images')) {
    return method !== 'GET' || /^\/api\/v1\/images\/i\/[^/]+\/(full|thumbnail|workflow)$/.test(path);
  }
  return method === 'DELETE' && path.startsWith('/api/v1/boards/') && url.searchParams.get('include_images') === 'true';
};

const isAdminCaller = (faults) => faults.intermediatesCaller !== 'user';
const isMultiuserCaller = (faults) => faults.intermediatesCaller !== 'admin';

/** Mirrors `board_access_common.py`: the least role each board action needs. */
const BOARD_ROLE_RANK = { contributor: 2, editor: 3, owner: 4, viewer: 1 };
const BOARD_ACTION_MINIMUM_ROLE = {
  read: 'viewer',
  add_media: 'contributor',
  manage_items: 'editor',
  rename: 'editor',
  set_cover: 'editor',
  archive: 'editor',
  set_general_access: 'owner',
  move: 'owner',
  delete: 'owner',
};
/** A project's inbox is managed through its project, by everyone, admins included. */
const INBOX_MANAGED_ACTIONS = new Set(['rename', 'archive', 'set_general_access', 'move', 'delete']);

const OTHER_USER_NAMES = { 'user-ana': 'Ana', 'user-ben': 'Ben', 'user-cleo': 'Cleo', 'user-dee': 'Dee' };

const SHARED_BOARD_FIXTURES = [
  {
    board_id: 'shared-editor',
    board_name: 'Brand kit',
    general_access: 'restricted',
    member_role: 'editor',
    user_id: 'user-ana',
  },
  { board_id: 'shared-contributor', board_name: 'Team moodboard', general_access: 'contributor', user_id: 'user-ben' },
  { board_id: 'shared-viewer', board_name: 'Client references', general_access: 'viewer', user_id: 'user-cleo' },
  { board_id: 'others-private', board_name: 'Private sketches', general_access: 'restricted', user_id: 'user-dee' },
];

const seedSharedBoards = (state) => {
  for (const fixture of SHARED_BOARD_FIXTURES) {
    const { member_role: memberRole, ...board } = fixture;
    state.boards.set(board.board_id, {
      ...board,
      archived: false,
      created_at: '2026-01-02T00:00:00.000Z',
      deleted_at: null,
      project_id: null,
      updated_at: '2026-01-02T00:00:00.000Z',
    });
    if (memberRole) {
      state.boardMembers.set(board.board_id, new Map([[MOCK_USER_ID, memberRole]]));
    }
  }
};

const boardAccessFor = (state, faults, board, { ignoreInbox = false } = {}) => {
  const ownerId = board.user_id ?? MOCK_USER_ID;
  const isAdmin = isAdminCaller(faults);
  const candidates = [
    ...(ownerId === MOCK_USER_ID ? ['owner'] : []),
    ...[state.boardMembers.get(board.board_id)?.get(MOCK_USER_ID)].filter(Boolean),
    ...((board.general_access ?? 'restricted') === 'restricted' ? [] : [board.general_access]),
  ];
  const role = candidates.sort((left, right) => BOARD_ROLE_RANK[right] - BOARD_ROLE_RANK[left])[0] ?? null;
  const isInbox = !ignoreInbox && inboxProjectIdForBoard(state, board.board_id) !== null;
  const allows = (action) =>
    !(isInbox && INBOX_MANAGED_ACTIONS.has(action)) &&
    (isAdmin || (role !== null && BOARD_ROLE_RANK[role] >= BOARD_ROLE_RANK[BOARD_ACTION_MINIMUM_ROLE[action]]));
  return {
    actions: Object.keys(BOARD_ACTION_MINIMUM_ROLE).filter(allows),
    adminOverride: isAdmin && role !== 'owner',
    allows,
    readable: isAdmin || role !== null,
    role,
  };
};

/** The server's answer for a board that exists but the caller may not read; only a missing board answers 404. */
const BOARD_UNREADABLE = [
  403,
  { detail: { code: 'board_unreadable', message: 'Not authorized to access this board' } },
];

const BOARD_ACTION_FORBIDDEN = [
  403,
  { detail: { code: 'board_action_denied', message: 'Not authorized to change this board' } },
];

const boardRefusal = (state, faults, board, action) => {
  const access = boardAccessFor(state, faults, board);
  if (!access.readable) {
    return BOARD_UNREADABLE;
  }
  return access.allows(action) ? null : BOARD_ACTION_FORBIDDEN;
};

/** Mirrors the server's claim rule: the staging board is the caller's own, unshared, projectless, nobody's inbox. */
const boardClaimRefusal = (state, board) =>
  (board.user_id ?? MOCK_USER_ID) !== MOCK_USER_ID ||
  (board.general_access ?? 'restricted') !== 'restricted' ||
  (state.boardMembers.get(board.board_id)?.size ?? 0) > 0 ||
  inboxProjectIdForBoard(state, board.board_id) !== null ||
  (board.project_id ?? null) !== null
    ? [409, { detail: 'Board is not available to be claimed by a project' }]
    : null;

const MOCK_USER_ID = 'fixture-user';

const matchingIntermediates = (rows, { isAdmin, ownerFilter, projectId, search }) => {
  const needle = (search ?? '').toLowerCase();
  return rows
    .filter((row) => ownerFilter === null || row.user_id === ownerFilter)
    .filter((row) => projectId === null || row.project_id === projectId)
    .filter(
      (row) =>
        !needle ||
        [row.project_name, ...(isAdmin ? [row.user_display_name, row.user_email] : [])].some((value) =>
          (value ?? '').toLowerCase().includes(needle)
        )
    );
};
const MOCK_USER_TOKEN = 'mock-user-token';

const mockNonAdminUser = () => ({
  created_at: '2026-01-01T00:00:00Z',
  display_name: 'Fixture User',
  email: '[email protected]',
  is_active: true,
  is_admin: false,
  last_login_at: null,
  updated_at: '2026-01-01T00:00:00Z',
  user_id: MOCK_USER_ID,
});

const clone = (value) => structuredClone(value);

const STARTER_MODEL = {
  base: 'sd-1',
  description: 'Fixture starter model',
  format: 'diffusers',
  is_installed: false,
  name: 'Fixture Starter',
  source: 'https://example.invalid/fixture-starter.safetensors',
  source_urls: ['https://example.invalid/models/fixture-starter'],
  type: 'main',
};

const EXTERNAL_STARTER_MODEL = {
  base: 'external',
  description: 'Fixture hosted starter model',
  format: 'external_api',
  is_installed: false,
  name: 'Fixture Gemini Flash (Catalog)',
  source: CATALOG_MANAGED_EXTERNAL_SOURCE,
  type: 'external_image_generator',
};

const MOCK_APP_VERSION = 'fixture';

const STARTER_MODELS_RESPONSE = {
  starter_bundles: {
    'sd-1': { models: [STARTER_MODEL], name: 'Stable Diffusion 1.5' },
    sdxl: {
      models: [
        {
          ...STARTER_MODEL,
          base: 'sdxl',
          name: 'Fixture Starter XL',
          source_urls: [
            'https://example.invalid/models/fixture-starter-xl',
            'https://example.invalid/models/fixture-starter-xl-quantized',
          ],
        },
      ],
      name: 'SDXL',
    },
  },
  starter_models: [STARTER_MODEL, EXTERNAL_STARTER_MODEL],
};

/** Starters read as installed when a library record carries their source, as the backend reports them. */
const getStarterModelsResponse = (state) => {
  const installedSources = new Set([...state.models.values()].map((model) => model.source));
  const withInstalled = (starter) => ({ ...starter, is_installed: installedSources.has(starter.source) });

  return {
    starter_bundles: Object.fromEntries(
      Object.entries(STARTER_MODELS_RESPONSE.starter_bundles).map(([base, bundle]) => [
        base,
        { ...bundle, models: bundle.models.map(withInstalled) },
      ])
    ),
    starter_models: STARTER_MODELS_RESPONSE.starter_models.map(withInstalled),
  };
};

/** The backend's `EXTERNAL_PROVIDER_FIELDS`, in its order: the config route lists each, configured or not. */
const EXTERNAL_PROVIDER_IDS = ['alibabacloud', 'atlascloud', 'gemini', 'openai', 'seedream'];

/** The backend removes a provider's records with its key, so providers the hosted records route to have one. */
const createExternalProviderConfigs = (models) => {
  const routed = new Set(
    models.filter((model) => model.type === 'external_image_generator').map((model) => model.provider_id)
  );

  return new Map(
    EXTERNAL_PROVIDER_IDS.map((providerId) => [
      providerId,
      { api_key_configured: routed.has(providerId), base_url: null, provider_id: providerId },
    ])
  );
};

const removeExternalModelsForProvider = (state, providerId) => {
  for (const [key, model] of state.models) {
    if (model.type === 'external_image_generator' && model.provider_id === providerId) {
      state.models.delete(key);
    }
  }
};

const DELIVERY_CLAIM_TTL_MS = 120_000;

const SEEDED_WILDCARD_NAMES = ['animals', 'colors', 'styles/painting'];

/** Most ids one `POST /api/v1/wildcards/delete` takes, as `MAX_WILDCARD_BATCH_SIZE` on the server. */
const MAX_WILDCARD_BATCH_SIZE = 1000;

const createWildcards = (count) =>
  new Map(
    Array.from({ length: count }, (_, index) => {
      const name = SEEDED_WILDCARD_NAMES[index] ?? `wildcard-${String(index + 1).padStart(4, '0')}`;
      const id = `wildcard-id-${String(index + 1).padStart(4, '0')}`;

      return [id, { id, name, user_id: MOCK_USER_ID, values: [`${name} one`, `${name} two`] }];
    })
  );

const sortedWildcards = (state) =>
  [...state.wildcards.values()].sort((left, right) => left.name.localeCompare(right.name)).map(clone);

const wildcardNameTaken = (state, name, exceptId = null) =>
  [...state.wildcards.values()].some((wildcard) => wildcard.name === name && wildcard.id !== exceptId);

const createState = (profile, clock) => {
  const fixture = assertMockBackendFixture(createMockBackendFixture(profile));
  const models = new Map(fixture.models.map((model) => [model.key, clone(model)]));

  return {
    boardMembers: new Map(),
    boards: new Map(fixture.boards.map((board) => [board.board_id, clone(board)])),
    // Dismiss the beta notice and What's New notes so journeys start on the requested page.
    clientState: new Map([
      [
        'webv2:workbench-settings',
        JSON.stringify({ betaNoticeAcknowledged: true, whatsNewSeenVersion: MOCK_APP_VERSION }),
      ],
    ]),
    externalProviders: createExternalProviderConfigs(fixture.models),
    images: new Map(fixture.images.map((image) => [image.image_name, clone(image)])),
    imageStorage: createImageStorage(),
    models,
    modelProbes: new Map(),
    mutationClock: 0,
    nextBoardNumber: fixture.boards.length + 1,
    nextImageNumber: fixture.images.length + 1,
    nextProjectNumber: fixture.projects.length + 1,
    nextVideoNumber: fixture.videos.length + 1,
    nodeCatalog: clone(fixture.nodeCatalog),
    openApiDocument: clone(fixture.openApiDocument),
    profile,
    projects: new Map(fixture.projects.map((project) => [project.project_id, clone(project)])),
    intermediates: fixture.intermediates.map(clone),
    intermediatesOperations: new Map(),
    intermediatesPreviews: new Map(),
    queueItems: new Map(fixture.queueItems.map((item) => [item.item_id, clone(item)])),
    deliveryClaims: new Map(),
    runtimeConfig: { generation_devices: 'auto', max_queue_history: null },
    invocationCache: { enabled: true, hits: 0, max_size: 1000, misses: 0, size: 0 },
    videos: new Map(fixture.videos.map((video) => [video.video_name, clone(video)])),
    wildcards: createWildcards(profile === 'empty' ? 0 : SEEDED_WILDCARD_NAMES.length),
    workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),
    workingMemory: createWorkingMemoryMock(fixture.models, { clock, currentModel: (key) => models.get(key) }),
    nextWorkflowNumber: fixture.workflows.length + 1,
    /** Custom workflow thumbnails by workflow id; the version stands in for the server's cache-busting query. */
    workflowThumbnails: new Map(),
    nextWorkflowThumbnailVersion: 1,
    workflowRequests: [],
    libraryScenario: null,
    hasLibraryPageFailed: false,
  };
};

/** Seed unboarded name collisions to verify imports copy board media instead of adopting existing items. */
const seedCollisionMedia = (state, names) => {
  const source = createMockBackendFixture('representative');
  const requested = new Set(names);

  for (const image of source.images) {
    if (requested.has(image.image_name)) {
      state.images.set(image.image_name, { ...clone(image), board_id: null, is_intermediate: false });
    }
  }

  for (const video of source.videos) {
    if (requested.has(video.video_name)) {
      state.videos.set(video.video_name, { ...clone(video), board_id: null, is_intermediate: false });
    }
  }
};

const timestamp = (state) => {
  const value = new Date(FIXED_EPOCH_MS + state.mutationClock * 1_000).toISOString();

  state.mutationClock += 1;

  return value;
};

/** Keep both map endpoints on one fixed projection timestamp; timestamp(state) advances on every call. */
const IMAGE_MAP_UPDATED_AT = '2026-01-01 00:00:00.000';

const getRequestedMediaKind = (url) => {
  const mediaKind = url.searchParams.get('media_kind');

  return mediaKind === 'image' || mediaKind === 'video' ? mediaKind : null;
};

/** Image-map kinds, as the backend serves them: `media_kind` alone decides when set, else `include_videos`. */
const getImageMapServedKinds = (url) => {
  const mediaKind = getRequestedMediaKind(url);

  if (mediaKind) {
    return [mediaKind];
  }

  return url.searchParams.get('include_videos') === 'true' ? ['image', 'video'] : ['image'];
};

/** Use deterministic coordinates and round-robin cluster IDs; this fixture does not run clustering. */
const imageMapPoints = (state, kinds) => {
  const items = [
    ...(kinds.includes('image') ? [...state.images.keys()].map((name) => ({ kind: 'image', name })) : []),
    ...(kinds.includes('video') ? [...state.videos.keys()].map((name) => ({ kind: 'video', name })) : []),
  ];

  return items.map((item, index) => {
    const angle = index * 2.399;
    const cluster = index % 3 === 2 ? -1 : index % 2;

    return {
      cluster,
      image_name: item.name,
      kind: item.kind,
      x: Math.cos(angle) * (2 + cluster) + cluster * 6,
      y: Math.sin(angle) * (2 + cluster),
    };
  });
};

const summaryOf = (project) => ({
  board_id: project.board_id,
  created_at: project.created_at,
  minimum_canvas_schema_version: project.minimum_canvas_schema_version ?? DEFAULT_CANVAS_SCHEMA_VERSION,
  minimum_document_schema_version: project.minimum_document_schema_version ?? DEFAULT_DOCUMENT_SCHEMA_VERSION,
  name: project.name,
  project_id: project.project_id,
  revision: project.revision,
  updated_at: project.updated_at,
  workspace_updated_at: project.workspace?.updated_at ?? null,
});

const readBody = (request) =>
  new Promise((resolve, reject) => {
    const chunks = [];

    request.on('data', (chunk) => chunks.push(chunk));
    request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
    request.on('error', reject);
  });

const readRawBody = (request) =>
  new Promise((resolve, reject) => {
    const chunks = [];

    request.on('data', (chunk) => chunks.push(chunk));
    request.on('end', () => resolve(Buffer.concat(chunks)));
    request.on('error', reject);
  });

const readMultipartFile = async (request, fieldName) => {
  const boundary = /boundary=(?:"([^"]+)"|([^;]+))/.exec(request.headers['content-type'] ?? '');

  if (!boundary) {
    return null;
  }

  const body = await readRawBody(request);
  const delimiter = Buffer.from(`--${boundary[1] ?? boundary[2]}`);
  let start = body.indexOf(delimiter);

  while (start !== -1) {
    const next = body.indexOf(delimiter, start + delimiter.length);
    const headerEnd = body.indexOf('\r\n\r\n', start);

    if (next === -1 || headerEnd === -1 || headerEnd > next) {
      return null;
    }

    const headers = body.subarray(start + delimiter.length, headerEnd).toString('utf8');

    if (new RegExp(`;\\s*name="${fieldName.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&')}"`).test(headers)) {
      return {
        contentType: /content-type:\s*([^\r\n]+)/i.exec(headers)?.[1]?.trim() ?? '',
        // The part's data ends at the CRLF that precedes the next delimiter.
        data: body.subarray(headerEnd + 4, next - 2),
      };
    }

    start = next;
  }

  return null;
};

const readJsonBody = async (request, fallback = {}) => {
  const body = await readBody(request);

  return body ? JSON.parse(body) : fallback;
};

const MEDIA_IMAGE_NAME_KEYS = new Set(['imageName', 'image_name']);
const MEDIA_VIDEO_NAME_KEYS = new Set(['videoName', 'video_name', 'source_video_name']);
const MEDIA_USAGE_NAME_CAP = 1000;
const MEDIA_USAGE_DOCUMENT_CAP = 100;
const ACTIVE_QUEUE_STATUSES = new Set(['pending', 'in_progress', 'waiting']);

/** Every name under the server's media keys, at any depth, as its `media_references` extractor reads documents. */
const collectReferencedMedia = (roots) => {
  const images = new Set();
  const videos = new Set();
  const pending = [...roots];

  while (pending.length > 0) {
    const node = pending.pop();

    if (Array.isArray(node)) {
      pending.push(...node);
    } else if (node && typeof node === 'object') {
      for (const [key, value] of Object.entries(node)) {
        if (typeof value === 'string') {
          if (MEDIA_IMAGE_NAME_KEYS.has(key)) {
            images.add(value);
          } else if (MEDIA_VIDEO_NAME_KEYS.has(key)) {
            videos.add(value);
          }
        } else if (value && typeof value === 'object') {
          pending.push(value);
        }
      }
    }
  }

  return { images, videos };
};

const usedNamesOf = (referenced, checked) => {
  const imageNames = [...checked.images].filter((name) => referenced.images.has(name)).sort();
  const videoNames = [...checked.videos].filter((name) => referenced.videos.has(name)).sort();

  return {
    image_count: imageNames.length,
    image_names: imageNames.slice(0, MEDIA_USAGE_NAME_CAP),
    video_count: videoNames.length,
    video_names: videoNames.slice(0, MEDIA_USAGE_NAME_CAP),
  };
};

const parseClientStateValue = (value) => {
  try {
    return JSON.parse(value);
  } catch {
    return null;
  }
};

/** Mirrors `POST /api/v1/gallery/usage` over the fixtures; the mock has one account, so other accounts use nothing. */
const galleryMediaUsage = (state, faults, body) => {
  const imageNames = Array.isArray(body.image_names) ? body.image_names : [];
  const videoNames = Array.isArray(body.video_names) ? body.video_names : [];
  const boardId = typeof body.board_id === 'string' ? body.board_id : null;

  if (boardId !== null && imageNames.length + videoNames.length > 0) {
    return [422, { detail: 'board_id cannot be combined with image_names or video_names' }];
  }

  // As the server: only media the caller may delete is checked; fixture images carry no owner.
  const isCallers = (item) => (item.owner_user_id ?? MOCK_USER_ID) === MOCK_USER_ID;
  let checked;

  if (boardId !== null) {
    const board = state.boards.get(boardId);

    if (!board) {
      return [404, { detail: 'Board not found' }];
    }
    if (!boardAccessFor(state, faults, board, { ignoreInbox: true }).allows('delete')) {
      return BOARD_ACTION_FORBIDDEN;
    }
    const onBoard = (items) => [...items].filter((item) => item.board_id === boardId && isCallers(item));
    checked = {
      images: new Set(onBoard(state.images.values()).map((image) => image.image_name)),
      videos: new Set(onBoard(state.videos.values()).map((video) => video.video_name)),
    };
  } else {
    const deletable = (store, names) => names.filter((name) => store.has(name) && isCallers(store.get(name)));
    checked = {
      images: new Set(deletable(state.images, imageNames)),
      videos: new Set(deletable(state.videos, videoNames)),
    };
  }

  const documents = [];
  // As the server: a project reports the content and workspace revisions its names were read at; other kinds none.
  const addDocument = (kind, id, name, roots, revisions = { revision: null, workspace_revision: null }) => {
    const used = usedNamesOf(collectReferencedMedia(roots), checked);

    if (used.image_count + used.video_count > 0) {
      documents.push({ id, kind, name, ...used, ...revisions });
    }
  };

  for (const project of state.projects.values()) {
    addDocument('project', project.project_id, project.name, [project.data, project.workspace?.data], {
      revision: project.revision,
      workspace_revision: project.workspace?.revision ?? null,
    });
  }
  for (const workflow of state.workflows.values()) {
    if (workflow.category !== 'default') {
      addDocument('workflow', workflow.workflow_id, workflow.name, [workflow.workflow]);
    }
  }
  addDocument(
    'legacy_editor',
    'legacy_editor',
    null,
    [...state.clientState].filter(([key]) => !key.startsWith('webv2:')).map(([, value]) => parseClientStateValue(value))
  );

  const kindOrder = ['legacy_editor', 'project', 'quarantined_project', 'workflow'];
  documents.sort(
    (left, right) =>
      kindOrder.indexOf(left.kind) - kindOrder.indexOf(right.kind) ||
      (left.name ?? '').localeCompare(right.name ?? '') ||
      left.id.localeCompare(right.id)
  );

  const activeItems = [...state.queueItems.values()].filter((item) => ACTIVE_QUEUE_STATUSES.has(item.status));
  const queueItemsUsing = activeItems.filter((item) => {
    const used = usedNamesOf(collectReferencedMedia([item.session, item.field_values]), checked);

    return used.image_count + used.video_count > 0;
  });
  const queueUsed = usedNamesOf(
    collectReferencedMedia(queueItemsUsing.flatMap((item) => [item.session, item.field_values])),
    checked
  );
  // The fixture lists stay far below the name cap, so their union is every name in use.
  const inUseImages = new Set([...documents.flatMap((document) => document.image_names), ...queueUsed.image_names]);
  const inUseVideos = new Set([...documents.flatMap((document) => document.video_names), ...queueUsed.video_names]);

  return [
    200,
    {
      checked_image_count: checked.images.size,
      checked_video_count: checked.videos.size,
      documents: documents.slice(0, MEDIA_USAGE_DOCUMENT_CAP),
      documents_total: documents.length,
      in_use_image_count: inUseImages.size,
      in_use_video_count: inUseVideos.size,
      other_accounts: { document_count: 0, image_count: 0, queue_item_count: 0, video_count: 0 },
      queue: { item_count: queueItemsUsing.length, ...queueUsed },
    },
  ];
};

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

const getStateCounts = (state) => ({
  images: state.images.size,
  layers: collectCanvasLeaves(state.projects.values().next().value?.data?.canvas?.document).length,
  models: state.models.size,
  nodes: invocationNodeCount(state),
  projects: state.projects.size,
  queueItems: state.queueItems.size,
  workflowNodes: getFixtureProjectWorkflowDocument(state.projects.values().next().value?.data)?.nodes?.length ?? 0,
});

const getProfileInfo = (state) => ({
  counts: getStateCounts(state),
  profile: state.profile,
});

const queueItemsForScope = (state, url) => {
  const originPrefix = url.searchParams.get('origin_prefix');
  const items = [...state.queueItems.values()];

  return originPrefix ? items.filter((item) => item.origin?.startsWith(originPrefix)) : items;
};

const queueStatus = (items) => {
  const count = (status) => items.filter((item) => item.status === status).length;

  return {
    canceled: count('canceled'),
    completed: count('completed'),
    failed: count('failed'),
    in_progress: count('in_progress'),
    pending: count('pending'),
    queue_id: 'default',
    total: items.length,
    waiting: count('waiting'),
  };
};

const getRequestedCategories = (url) => {
  const values = url.searchParams.getAll('categories');

  return values.flatMap((value) => value.split(',')).filter(Boolean);
};

const getOptionalBoolean = (url, name) => {
  const value = url.searchParams.get(name);

  return value === null ? undefined : value === 'true';
};

// Only media_origin belongs in the DTO; other metadata is served by /metadata.
const toVideoDto = (video) => ({
  board_id: video.board_id,
  created_at: video.created_at,
  duration: video.duration,
  fps: video.fps,
  height: video.height,
  is_intermediate: video.is_intermediate,
  media_origin: video.metadata?.media_origin ?? null,
  starred: video.starred,
  thumbnail_url: video.thumbnail_url,
  video_category: video.video_category,
  video_name: video.video_name,
  video_url: video.video_url,
  width: video.width,
});

const toGalleryItem = (kind, value) =>
  kind === 'image'
    ? {
        board_id: value.board_id,
        category: value.image_category,
        created_at: value.created_at,
        full_url: value.image_url,
        height: value.height,
        is_intermediate: value.is_intermediate,
        kind,
        name: value.image_name,
        starred: value.starred ?? false,
        thumbnail_url: value.thumbnail_url,
        width: value.width,
      }
    : {
        board_id: value.board_id,
        category: value.video_category,
        created_at: value.created_at,
        duration: value.duration,
        fps: value.fps,
        full_url: value.video_url,
        height: value.height,
        is_intermediate: value.is_intermediate,
        kind,
        media_origin: value.metadata?.media_origin ?? null,
        name: value.video_name,
        starred: value.starred,
        thumbnail_url: value.thumbnail_url,
        width: value.width,
      };

const getGalleryCandidates = (state) => [
  ...[...state.images.values()].map((image) => ({
    item: toGalleryItem('image', image),
    origin: image.image_origin ?? 'internal',
    searchable: image.metadata,
  })),
  ...[...state.videos.values()]
    .filter((video) => video.owner_user_id === MOCK_USER_ID)
    .map((video) => ({
      item: toGalleryItem('video', video),
      origin: video.video_origin ?? 'internal',
      searchable: video.metadata,
    })),
];

const compareGalleryItems = (left, right, orderDir, starredFirst) => {
  if (starredFirst && left.starred !== right.starred) {
    return left.starred ? -1 : 1;
  }

  const direction = orderDir === 'ASC' ? 1 : -1;

  return (
    direction * left.created_at.localeCompare(right.created_at) ||
    direction * left.kind.localeCompare(right.kind) ||
    direction * left.name.localeCompare(right.name)
  );
};

/** As the server's `board_id=all` listing: an active board the caller may read. */
const isListedBoard = (state, faults, boardId) => {
  const board = state.boards.get(boardId);

  return board !== undefined && !board.archived && boardAccessFor(state, faults, board).readable;
};

const filterGalleryItems = (state, url, faults, { createdDate, starredFirst } = {}) => {
  const boardId = url.searchParams.get('board_id');
  const categories = getRequestedCategories(url);
  const createdFrom = url.searchParams.get('created_from');
  const createdTo = url.searchParams.get('created_to');
  const intermediate = getOptionalBoolean(url, 'is_intermediate');
  const mediaKind = getRequestedMediaKind(url);
  const origin = url.searchParams.get('origin');
  const starred = getOptionalBoolean(url, 'starred');
  const searchTerm = url.searchParams.get('search_term')?.trim().toLocaleLowerCase() ?? '';

  return getGalleryCandidates(state)
    .filter(({ item, origin: itemOrigin, searchable }) => {
      if (mediaKind && item.kind !== mediaKind) {
        return false;
      }
      if (boardId === 'all') {
        if (item.board_id !== null && !isListedBoard(state, faults, item.board_id)) {
          return false;
        }
      } else if (boardId && (boardId === 'none' ? item.board_id !== null : item.board_id !== boardId)) {
        return false;
      }
      if (origin && itemOrigin !== origin) {
        return false;
      }
      if (categories.length > 0 && !categories.includes(item.category)) {
        return false;
      }
      if (intermediate !== undefined && item.is_intermediate !== intermediate) {
        return false;
      }
      if (starred !== undefined && Boolean(item.starred) !== starred) {
        return false;
      }
      if (createdDate && item.created_at.slice(0, 10) !== createdDate) {
        return false;
      }
      if (createdFrom && item.created_at < createdFrom) {
        return false;
      }
      if (createdTo && item.created_at >= `${createdTo}T24:00:00`) {
        return false;
      }
      if (searchTerm) {
        const document = `${JSON.stringify(searchable ?? {})} ${item.created_at}`.toLocaleLowerCase();

        if (!document.includes(searchTerm)) {
          return false;
        }
      }

      return true;
    })
    .map(({ item }) => item)
    .sort((left, right) =>
      compareGalleryItems(
        left,
        right,
        url.searchParams.get('order_dir')?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC',
        starredFirst ?? url.searchParams.get('starred_first') !== 'false'
      )
    );
};

const getGalleryItemLocation = (state, url, faults) => {
  const kind = url.searchParams.get('kind');
  const name = url.searchParams.get('name');
  const items = filterGalleryItems(state, url, faults, { starredFirst: false });
  const index = items.findIndex((item) => item.kind === kind && item.name === name);

  return index === -1 ? null : { kind, name, index, total: items.length };
};

const listGalleryItems = (state, url, faults) => {
  const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0) || 0);
  const limit = Math.max(0, Number(url.searchParams.get('limit') ?? 10) || 0);
  const filtered = filterGalleryItems(state, url, faults);

  return {
    items: limit === 0 ? [] : filtered.slice(offset, offset + limit),
    limit,
    offset,
    total: filtered.length,
  };
};

const listGalleryItemNames = (state, url, faults, options) => {
  const items = filterGalleryItems(state, url, faults, options);

  return {
    items: items.map(({ kind, name }) => ({ kind, name })),
    starred_count: url.searchParams.get('starred_first') !== 'false' ? items.filter((item) => item.starred).length : 0,
    total_count: items.length,
  };
};

const listVideos = (state, url) => {
  const boardId = url.searchParams.get('board_id');
  const categories = getRequestedCategories(url);
  const intermediate = getOptionalBoolean(url, 'is_intermediate');
  const searchTerm = url.searchParams.get('search_term')?.trim().toLocaleLowerCase() ?? '';
  const orderDir = url.searchParams.get('order_dir')?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
  const starredFirst = url.searchParams.get('starred_first') !== 'false';
  const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0) || 0);
  const limit = Math.max(0, Number(url.searchParams.get('limit') ?? 10) || 0);
  const filtered = [...state.videos.values()]
    .filter((video) => {
      if (video.owner_user_id !== MOCK_USER_ID) {
        return false;
      }
      if (boardId && (boardId === 'none' ? video.board_id !== null : video.board_id !== boardId)) {
        return false;
      }
      if (categories.length > 0 && !categories.includes(video.video_category)) {
        return false;
      }
      if (intermediate !== undefined && video.is_intermediate !== intermediate) {
        return false;
      }

      return (
        !searchTerm ||
        `${JSON.stringify(video.metadata ?? {})} ${video.created_at}`.toLocaleLowerCase().includes(searchTerm)
      );
    })
    .map(toVideoDto)
    .sort((left, right) =>
      compareGalleryItems(
        {
          created_at: left.created_at,
          kind: 'video',
          name: left.video_name,
          starred: left.starred,
        },
        {
          created_at: right.created_at,
          kind: 'video',
          name: right.video_name,
          starred: right.starred,
        },
        orderDir,
        starredFirst
      )
    );

  return {
    items: limit === 0 ? [] : filtered.slice(offset, offset + limit),
    limit,
    offset,
    total: filtered.length,
  };
};

/** Derived from `projects.board_id`, as the backend derives it. */
const inboxProjectIdForBoard = (state, boardId) =>
  [...state.projects.values()].find((project) => project.board_id === boardId)?.project_id ?? null;

/** Match /board-snapshot visibility and ordering: exclude intermediate/other items, sort by kind then name. */
const boardSnapshotItems = (state, boardId) => {
  const visible = (category) => ['general', 'control', 'mask', 'user'].includes(category);
  const items = [
    ...[...state.images.values()]
      .filter((image) => image.board_id === boardId && !image.is_intermediate && visible(image.image_category))
      .map((image) => ({
        category: image.image_category,
        kind: 'image',
        name: image.image_name,
        starred: Boolean(image.starred),
      })),
    ...[...state.videos.values()]
      .filter(
        (video) =>
          video.board_id === boardId &&
          video.owner_user_id === MOCK_USER_ID &&
          !video.is_intermediate &&
          visible(video.video_category)
      )
      .map((video) => ({
        category: video.video_category,
        kind: 'video',
        name: video.video_name,
        starred: Boolean(video.starred),
      })),
  ];

  return items.sort((left, right) => left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name));
};

const boardDto = (state, board, faults) => {
  const images = [...state.images.values()].filter((image) => image.board_id === board.board_id);
  const videos = [...state.videos.values()].filter(
    (video) => video.board_id === board.board_id && video.owner_user_id === MOCK_USER_ID
  );
  const cover = [
    ...images.map((image) => ({
      createdAt: image.created_at,
      kind: 'image',
      name: image.image_name,
      starred: image.starred,
    })),
    ...videos.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];

  const projectId = board.project_id ?? null;
  const access = boardAccessFor(state, faults, board);
  const ownerId = board.user_id ?? MOCK_USER_ID;
  const generalAccess = board.general_access ?? 'restricted';

  return {
    ...board,
    admin_override: access.adminOverride,
    allowed_actions: access.actions,
    board_visibility: { contributor: 'public', restricted: 'private', viewer: 'shared' }[generalAccess],
    general_access: generalAccess,
    my_role: access.role,
    owner_username: ownerId === MOCK_USER_ID ? 'Fixture User' : (OTHER_USER_NAMES[ownerId] ?? 'Unknown user'),
    user_id: ownerId,
    asset_count: images.filter((image) => image.image_category !== 'general').length,
    cover_image_name: cover?.kind === 'image' ? cover.name : null,
    cover_video_name: cover?.kind === 'video' ? cover.name : null,
    image_count: images.filter((image) => image.image_category === 'general').length,
    is_inbox: inboxProjectIdForBoard(state, board.board_id) !== null,
    // The backend sends null for a Library board, and to anyone but the owner and admins.
    project_id: access.role === 'owner' || isAdminCaller(faults) ? projectId : null,
    video_count: videos.length,
  };
};

const listImages = (state, url) => {
  const boardId = url.searchParams.get('board_id');
  const categories = getRequestedCategories(url);
  const createdFrom = url.searchParams.get('created_from');
  const createdTo = url.searchParams.get('created_to');
  const orderDir = url.searchParams.get('order_dir')?.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
  const searchTerm = url.searchParams.get('search_term')?.trim().toLocaleLowerCase() ?? '';
  const starredFirst = url.searchParams.get('starred_first') === 'true';
  const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0) || 0);
  const limit = Math.max(0, Number(url.searchParams.get('limit') ?? 100) || 0);
  let items = [...state.images.values()].filter((image) => {
    if (image.is_intermediate) {
      return false;
    }
    if (boardId && boardId !== 'all') {
      if (boardId === 'none' ? image.board_id !== null : image.board_id !== boardId) {
        return false;
      }
    }
    if (categories.length > 0 && !categories.includes(image.image_category)) {
      return false;
    }
    if (createdFrom && image.created_at.slice(0, 10) < createdFrom) {
      return false;
    }
    if (createdTo && image.created_at.slice(0, 10) > createdTo) {
      return false;
    }

    return !searchTerm || image.image_name.toLocaleLowerCase().includes(searchTerm);
  });

  items.sort((left, right) => {
    if (starredFirst && Boolean(left.starred) !== Boolean(right.starred)) {
      return left.starred ? -1 : 1;
    }

    return orderDir === 'ASC'
      ? left.created_at.localeCompare(right.created_at)
      : right.created_at.localeCompare(left.created_at);
  });

  const total = items.length;
  items = limit === 0 ? [] : items.slice(offset, offset + limit);

  return { items, limit, offset, total };
};

const listVirtualDateBoards = (state) => {
  const groups = new Map();

  for (const item of getGalleryCandidates(state).map(({ item }) => item)) {
    if (item.is_intermediate) {
      continue;
    }
    const date = item.created_at.slice(0, 10);
    const group = groups.get(date) ?? [];

    group.push(item);
    groups.set(date, group);
  }

  return [...groups.entries()]
    .sort(([left], [right]) => right.localeCompare(left))
    .map(([date, items]) => {
      const ordered = [...items].sort((left, right) => compareGalleryItems(left, right, 'DESC', false));
      const cover = ordered[0];

      return {
        asset_count: items.filter((item) => item.kind === 'image' && item.category !== 'general').length,
        board_name: date,
        cover_image_name: cover?.kind === 'image' ? cover.name : null,
        cover_video_name: cover?.kind === 'video' ? cover.name : null,
        date,
        image_count: items.filter((item) => item.kind === 'image' && item.category === 'general').length,
        video_count: items.filter((item) => item.kind === 'video').length,
        virtual_board_id: `by_date:${date}`,
      };
    });
};

const writeJson = (response, status, value) => {
  const body = JSON.stringify(value ?? null);

  response.writeHead(status, {
    'cache-control': 'no-store',
    'content-length': Buffer.byteLength(body),
    'content-type': 'application/json',
  });
  response.end(body);
};

const writePng = (response, image, thumbnail) => {
  const { width, height } = mediaDimensions(image, thumbnail);
  const bytes = fixturePng(width, height);
  response.writeHead(200, {
    'cache-control': 'public, max-age=3600',
    'content-length': bytes.length,
    'content-type': 'image/png',
  });
  response.end(bytes);
};

const writeBinary = (response, status, body, headers) => {
  response.writeHead(status, {
    'cache-control': 'public, max-age=3600',
    'content-length': body.length,
    ...headers,
  });
  response.end(body);
};

const parseByteRange = (value, size) => {
  const match = /^bytes=(\d*)-(\d*)$/.exec(value.trim());

  if (!match || size <= 0 || (!match[1] && !match[2])) {
    return null;
  }
  if (!match[1]) {
    const suffixLength = Number(match[2]);

    return suffixLength > 0 ? [Math.max(size - suffixLength, 0), size - 1] : null;
  }

  const start = Number(match[1]);
  const end = match[2] ? Number(match[2]) : size - 1;

  return Number.isSafeInteger(start) && Number.isSafeInteger(end) && start <= end && start < size
    ? [start, Math.min(end, size - 1)]
    : null;
};

export const startMockBackend = async (port, { clock = Date.now, profile = 'empty' } = {}) => {
  const initialProfile = assertMockBackendProfileName(profile);
  let state = createState(initialProfile, clock);
  let faults = createFaults();

  const server = createServer(async (request, response) => {
    const url = new URL(request.url, `http://127.0.0.1:${String(port)}`);
    const path = url.pathname;
    const method = request.method ?? 'GET';
    const json = (status, value) => writeJson(response, status, value);

    try {
      if (method === 'GET' && (path === '/__health' || path === '/__profile')) {
        return json(200, { ok: true, ...getProfileInfo(state) });
      }

      if (method === 'POST' && path === '/__reset') {
        const body = await readJsonBody(request);
        const requestedProfile = url.searchParams.get('profile') ?? body.profile ?? initialProfile;

        try {
          state = createState(assertMockBackendProfileName(requestedProfile), clock);
        } catch (error) {
          return json(400, { detail: error instanceof Error ? error.message : String(error) });
        }

        faults = createFaults();

        const wildcardCount = url.searchParams.get('wildcards') ?? body.wildcards;
        if (wildcardCount !== undefined && wildcardCount !== null) {
          const count = Number(wildcardCount);
          if (!Number.isInteger(count) || count < 0) {
            return json(400, { detail: `Invalid wildcard count: ${String(wildcardCount)}` });
          }
          state.wildcards = createWildcards(count);
        }

        const collisions = [...url.searchParams.getAll('collide'), ...(body.collide ?? [])]
          .flatMap((value) => String(value).split(','))
          .map((value) => value.trim())
          .filter(Boolean);

        if (collisions.length > 0) {
          seedCollisionMedia(state, collisions);
        }

        return json(200, { ok: true, ...getProfileInfo(state) });
      }

      if (method === 'POST' && path === '/__queue_items') {
        // Test seam: workflow-call chains only arise from execution, which the mock does not run.
        const body = await readJsonBody(request);
        for (const item of Array.isArray(body.items) ? body.items : []) {
          state.queueItems.set(item.item_id, clone(item));
        }
        return json(200, { ok: true });
      }

      if (method === 'POST' && path === '/__models') {
        const body = await readJsonBody(request);
        if (body.set !== undefined && !Object.hasOwn(MODEL_SEED_SETS, body.set)) {
          return json(400, { detail: `Unknown model seed set: ${String(body.set)}` });
        }
        const entries = [
          ...(body.set === undefined ? [] : MODEL_SEED_SETS[body.set]),
          ...(Array.isArray(body.models) ? body.models.map((record) => ({ record })) : []),
        ];
        for (const { probe, record } of entries) {
          state.models.set(record.key, clone(record));
          if (probe) {
            state.modelProbes.set(record.key, clone(probe));
          }
        }
        return json(200, { keys: entries.map(({ record }) => record.key), ok: true });
      }

      if (path === '/__faults') {
        if (method === 'POST') {
          const body = await readJsonBody(request);
          const requested = url.searchParams.get('capabilities') ?? body.capabilities;
          const caller = url.searchParams.get('intermediatesCaller') ?? body.intermediatesCaller;
          const workingMemory = url.searchParams.get('workingMemory') ?? body.workingMemory;
          const imageMoves = url.searchParams.get('imageMoves') ?? body.imageMoves;

          if (body.sharedBoards === true && !state.boards.has(SHARED_BOARD_FIXTURES[0].board_id)) {
            seedSharedBoards(state);
          }

          if (requested !== undefined && requested !== null) {
            if (!CAPABILITY_FAULTS.has(requested)) {
              return json(400, { detail: `Unknown capabilities fault: ${String(requested)}` });
            }

            faults.capabilities = requested;
          }

          if (caller !== undefined && caller !== null) {
            if (!INTERMEDIATES_CALLERS.has(caller)) {
              return json(400, { detail: `Unknown intermediates caller: ${String(caller)}` });
            }

            faults.intermediatesCaller = caller;
          }

          if (workingMemory !== undefined && workingMemory !== null) {
            if (!WORKING_MEMORY_SCENARIOS.has(workingMemory)) {
              return json(400, { detail: `Unknown working-memory scenario: ${String(workingMemory)}` });
            }

            faults.workingMemory = workingMemory;
          }

          if (
            body.modelChangedCalibration !== undefined &&
            !state.workingMemory.seedModelChanged(body.modelChangedCalibration)
          ) {
            return json(400, {
              detail: `No main model to seed a changed-model calibration on: ${String(body.modelChangedCalibration)}`,
            });
          }

          if (body.runningCalibration !== undefined && !state.workingMemory.seedRunning(body.runningCalibration)) {
            return json(400, {
              detail: `No main model to seed a running calibration on: ${String(body.runningCalibration)}`,
            });
          }

          if (body.stoppedCalibration !== undefined && !state.workingMemory.seedStopped(body.stoppedCalibration)) {
            return json(400, {
              detail: `No main model to seed a stopped calibration on: ${String(body.stoppedCalibration)}`,
            });
          }

          if (imageMoves !== undefined && imageMoves !== null) {
            if (!IMAGE_MOVE_FAULTS.has(imageMoves)) {
              return json(400, { detail: `Unknown image moves fault: ${String(imageMoves)}` });
            }

            faults.imageMoves = imageMoves;
            state.imageStorage = createImageStorage();
            if (imageMoves === 'needs-recovery') {
              seedInterruptedImageMove(state);
            }
            if (imageMoves === 'failed') {
              seedFailedImageMove(state);
            }
          }
        }

        return json(200, { ok: true, faults: { ...faults } });
      }

      if (method === 'POST' && path === '/__board-access') {
        const body = await readJsonBody(request);
        const board = state.boards.get(body.board_id);
        if (!board) {
          return json(404, { detail: 'Board not found' });
        }
        if (body.general_access !== undefined) {
          board.general_access = body.general_access;
        }
        if (body.member_role !== undefined) {
          const members = state.boardMembers.get(board.board_id) ?? new Map();
          if (body.member_role === null) {
            members.delete(MOCK_USER_ID);
          } else {
            members.set(MOCK_USER_ID, body.member_role);
          }
          state.boardMembers.set(board.board_id, members);
        }
        return json(200, { ok: true });
      }

      if (method === 'GET' && path === '/openapi.json') {
        return json(200, state.openApiDocument);
      }

      if (method === 'GET' && path === '/api/v1/auth/status') {
        return json(200, {
          admin_email: null,
          has_single_user_work: false,
          multiuser_enabled: isMultiuserCaller(faults),
          setup_required: false,
          strict_password_checking: false,
        });
      }

      if (isMultiuserCaller(faults) && path.startsWith('/api/v1/auth/')) {
        const sessionUser = { ...mockNonAdminUser(), is_admin: isAdminCaller(faults) };
        if (method === 'POST' && path === '/api/v1/auth/login') {
          return json(200, { expires_in: 86_400, token: MOCK_USER_TOKEN, user: sessionUser });
        }
        if (method === 'GET' && path === '/api/v1/auth/me') {
          return request.headers.authorization === `Bearer ${MOCK_USER_TOKEN}`
            ? json(200, sessionUser)
            : json(401, { detail: 'Not authenticated' });
        }
        if (method === 'POST' && (path === '/api/v1/auth/media-cookie' || path === '/api/v1/auth/logout')) {
          return json(200, { success: true });
        }
      }

      if (method === 'GET' && path === '/api/v1/image_map/points') {
        const kinds = getImageMapServedKinds(url);
        const points = imageMapPoints(state, kinds);

        return json(200, {
          cluster_eps: 0.5,
          point_count: points.length,
          points,
          stale: false,
          state: points.length > 0 ? 'ready' : 'empty',
          updated_at: IMAGE_MAP_UPDATED_AT,
          visible_hash: `visible-${kinds.join('+')}`,
        });
      }

      if (method === 'GET' && path === '/api/v1/image_map/cluster_labels') {
        return json(200, {
          labels: { 0: { alternates: ['sunset', 'coastline'], label: 'beaches' } },
          // Labels must match /points on both projection timestamp and visible set.
          updated_at: IMAGE_MAP_UPDATED_AT,
          visible_hash: `visible-${getImageMapServedKinds(url).join('+')}`,
        });
      }

      if (method === 'GET' && path === '/api/v1/image_map/image_labels') {
        const name = url.searchParams.get('image_name') ?? '';
        const isVideo = url.searchParams.get('kind') === 'video';
        const exists = isVideo ? state.videos.has(name) : state.images.has(name);

        // Match the real route's 404 so tests can exercise definitive label-cache misses.
        if (!exists) {
          return json(404, { detail: 'This item has no stored embedding to label' });
        }

        return json(200, { alternates: ['surf', 'shoreline'], label: isVideo ? 'clip' : 'photo' });
      }

      if (method === 'GET' && path === '/api/v1/image_map/status') {
        const total = state.images.size + state.videos.size;
        const pointCount = imageMapPoints(state, getImageMapServedKinds(url)).length;

        return json(200, {
          enabled: true,
          index: { embedded: total, failed: 0, total },
          projection: {
            point_count: pointCount,
            stale: false,
            state: pointCount > 0 ? 'ready' : 'empty',
            updated_at: IMAGE_MAP_UPDATED_AT,
          },
        });
      }

      if (method === 'GET' && path === '/api/v1/image_map/vocab') {
        return json(200, {
          terms: ['architectural study', 'watercolor'],
          state: 'ready',
          error: null,
          max_terms: 500,
          max_term_length: 64,
        });
      }

      if (method === 'POST' && path === '/api/v1/image_map/refresh') {
        return json(200, { enqueued: true });
      }

      if (method === 'GET' && path === '/api/v1/app/version') {
        return json(200, { version: MOCK_APP_VERSION });
      }

      if (method === 'GET' && path === '/api/v1/app/app_deps') {
        return json(200, { CUDA: 'N/A', invokeai: MOCK_APP_VERSION });
      }

      if (method === 'GET' && path === '/api/v1/app/frontend_config') {
        return json(200, { show_donation_link: true });
      }

      if (method === 'GET' && path === '/api/v1/app/generation_device_options') {
        return json(200, [{ device: 'cpu', name: 'CPU' }]);
      }

      if (path === '/api/v1/app/runtime_config') {
        const runtimeConfig = () => ({
          config: { ...state.runtimeConfig, image_subfolder_strategy: state.imageStorage.layout },
          set_fields: state.imageStorage.layout === 'flat' ? [] : ['image_subfolder_strategy'],
        });

        if (method === 'GET') {
          return json(200, runtimeConfig());
        }
        if (method === 'PATCH') {
          if (!isAdminCaller(faults)) {
            return json(403, { detail: 'Admin privileges required' });
          }

          const body = await readJsonBody(request);

          if ('max_queue_history' in body) {
            const value = body.max_queue_history;

            if (value !== null && !(Number.isInteger(value) && value >= 0)) {
              return json(422, { detail: 'max_queue_history must be a non-negative integer or null' });
            }
          }
          if ('image_subfolder_strategy' in body) {
            if (!IMAGE_STORAGE_LAYOUTS.has(body.image_subfolder_strategy)) {
              return json(422, { detail: 'image_subfolder_strategy must be one of flat, date, type, hash' });
            }

            state.imageStorage.layout = body.image_subfolder_strategy;
          }
          if ('generation_devices' in body) {
            state.runtimeConfig.generation_devices = body.generation_devices;
          }
          if ('max_queue_history' in body) {
            state.runtimeConfig.max_queue_history = body.max_queue_history;
          }

          return json(200, runtimeConfig());
        }
      }

      if (path.startsWith('/api/v1/image_moves/')) {
        if (!isAdminCaller(faults)) {
          return json(403, { detail: 'Admin privileges required' });
        }

        const storage = state.imageStorage;

        if (method === 'GET' && path === '/api/v1/image_moves/status') {
          tickImageMove(state);
          return json(200, imageMoveStatus(state));
        }
        if (method === 'POST' && path === '/api/v1/image_moves/start') {
          if (storage.running !== null) {
            return json(409, { detail: 'An image move job is already running' });
          }
          if (imageMoveStatus(state).active_job_id !== null) {
            return json(409, { detail: 'An image move job is already active' });
          }
          if (hasActiveQueueWork(state)) {
            return json(409, { detail: 'Cannot start image move while queue work is active' });
          }

          startImageMoveOperation(state, 'move_all', { instant: faults.imageMoves === 'instant' });
          return json(202, imageMoveStatus(state));
        }
        if (method === 'POST' && path === '/api/v1/image_moves/recover') {
          if (storage.running !== null) {
            return json(409, { detail: 'An image move job is already running' });
          }

          startImageMoveOperation(state, 'recovery', { instant: faults.imageMoves === 'instant' });
          return json(202, imageMoveStatus(state));
        }
      }

      if (isImageMoveMaintenanceActive(state) && isImageMoveMaintenanceRoute(method, path, url)) {
        return json(409, { detail: IMAGE_MOVE_MAINTENANCE_DETAIL });
      }

      if (path.startsWith('/api/v1/app/invocation_cache')) {
        const cache = state.invocationCache;

        if (path === '/api/v1/app/invocation_cache/status' && method === 'GET') {
          return json(200, { ...cache });
        }
        if (path === '/api/v1/app/invocation_cache' && method === 'DELETE') {
          cache.size = 0;
          return json(200, null);
        }
        if (path === '/api/v1/app/invocation_cache/enable' && method === 'PUT') {
          cache.enabled = true;
          return json(200, null);
        }
        if (path === '/api/v1/app/invocation_cache/disable' && method === 'PUT') {
          cache.enabled = false;
          return json(200, null);
        }
      }

      if (method === 'GET' && path === '/api/v1/app/external_providers/config') {
        return json(200, [...state.externalProviders.values()].map(clone));
      }

      const externalProviderMatch = /^\/api\/v1\/app\/external_providers\/config\/([^/]+)$/.exec(path);
      if (externalProviderMatch && (method === 'POST' || method === 'DELETE')) {
        const providerId = decodeURIComponent(externalProviderMatch[1]);
        const config = state.externalProviders.get(providerId);

        if (!config) {
          return json(404, { detail: `Unknown external provider '${providerId}'` });
        }
        if (method === 'DELETE') {
          Object.assign(config, { api_key_configured: false, base_url: null });
          removeExternalModelsForProvider(state, providerId);
          return json(200, clone(config));
        }

        const update = await readJsonBody(request);
        const apiKey = typeof update.api_key === 'string' ? update.api_key.trim() : null;
        const baseUrl = typeof update.base_url === 'string' ? update.base_url.trim() : null;

        if (apiKey === null && baseUrl === null) {
          return json(400, { detail: 'No external provider config fields provided' });
        }
        if (baseUrl !== null) {
          config.base_url = baseUrl || null;
        }
        if (apiKey !== null) {
          config.api_key_configured = apiKey !== '';
          if (apiKey === '') {
            removeExternalModelsForProvider(state, providerId);
          }
        }

        return json(200, clone(config));
      }

      if (path === '/api/v1/projects/' || path === '/api/v1/projects') {
        if (method === 'GET') {
          return json(200, [...state.projects.values()].map(summaryOf));
        }
        if (method === 'POST') {
          const requested = await readJsonBody(request);

          if (requested.project_id && state.projects.has(requested.project_id)) {
            return json(409, { detail: 'Project already exists' });
          }

          const now = timestamp(state);
          const projectNumber = state.nextProjectNumber;
          const name = requested.name ?? `Project Name #${projectNumber}`;
          const projectId = requested.project_id ?? `mock-project-${projectNumber}`;

          // Refusals come before any write: a refused create claims no board.
          const minimum = requested.minimum_canvas_schema_version ?? DEFAULT_CANVAS_SCHEMA_VERSION;
          const maximum = clientMaximum(requested.max_canvas_schema_version);
          if (minimum > maximum) {
            return json(...schemaUnsupported(minimum, maximum));
          }
          const documentFloor = requested.minimum_document_schema_version ?? DEFAULT_DOCUMENT_SCHEMA_VERSION;
          if (documentFloor > documentMaximum(requested.max_document_schema_version)) {
            return json(
              ...documentSchemaUnsupported(documentFloor, documentMaximum(requested.max_document_schema_version))
            );
          }
          const workspaceData = requested.workspace ?? null;
          if (workspaceData !== null && documentFloor < SPLIT_DOCUMENT_SCHEMA_VERSION) {
            return json(400, {
              detail: {
                code: 'workspace_needs_split_document',
                message: 'A workspace is saved only with content at document schema 4 or newer.',
                minimum_document_schema_version: documentFloor,
              },
            });
          }

          // Adopting a prepopulated board makes project creation the import commit point.
          let boardId = requested.board_id ?? null;
          if (boardId === null) {
            boardId = `mock-project-board-${projectNumber}`;
            state.boards.set(boardId, {
              archived: false,
              board_id: boardId,
              board_name: name,
              general_access: 'restricted',
              created_at: now,
              deleted_at: null,
              owner_username: null,
              project_id: projectId,
              updated_at: now,
              user_id: MOCK_USER_ID,
            });
          } else {
            const board = state.boards.get(boardId);
            if (!board) {
              return json(404, { detail: 'Board not found' });
            }
            const claimRefusal = boardClaimRefusal(state, board);
            if (claimRefusal) {
              return json(...claimRefusal);
            }
            board.board_name = name;
            board.project_id = projectId;
            board.updated_at = now;
          }

          const project = {
            board_id: boardId,
            created_at: now,
            data: requested.data ?? {},
            minimum_canvas_schema_version: minimum,
            minimum_document_schema_version: documentFloor,
            name,
            project_id: projectId,
            revision: 1,
            updated_at: now,
            workspace: workspaceData === null ? null : { data: workspaceData, revision: 1, updated_at: now },
          };

          state.nextProjectNumber += 1;
          state.projects.set(project.project_id, project);

          return json(200, { ...writtenRecordOf(project), workspace: project.workspace });
        }
      }

      const projectMatch = /^\/api\/v1\/projects\/([^/]+)$/.exec(path);
      if (projectMatch) {
        const projectId = decodeURIComponent(projectMatch[1]);
        const project = state.projects.get(projectId);

        if (method === 'GET') {
          if (!project) {
            return json(404, { detail: 'Project not found' });
          }
          const maximum = clientMaximum(
            Number(url.searchParams.get('max_canvas_schema_version') ?? DEFAULT_CANVAS_SCHEMA_VERSION)
          );
          const documentFloor = project.minimum_document_schema_version ?? DEFAULT_DOCUMENT_SCHEMA_VERSION;
          const documentClient = documentMaximum(Number(url.searchParams.get('max_document_schema_version')));
          if (project.minimum_canvas_schema_version > maximum) {
            return json(...schemaUnsupported(project.minimum_canvas_schema_version, maximum));
          }
          return documentFloor > documentClient
            ? json(...documentSchemaUnsupported(documentFloor, documentClient))
            : json(200, { ...writtenRecordOf(project), workspace: project.workspace ?? null });
        }
        if (method === 'PUT') {
          if (!project) {
            return json(404, { detail: 'Project not found' });
          }

          const requested = await readJsonBody(request);

          if (requested.expected_revision !== undefined && requested.expected_revision !== project.revision) {
            return json(409, { detail: { current_revision: project.revision, message: 'Revision conflict' } });
          }
          // The caller's workspace, saved in the same write as the content: a revision mismatch refuses both.
          const workspaceRequest = requested.workspace ?? null;
          const currentWorkspaceRevision = project.workspace?.revision ?? null;
          if (workspaceRequest && currentWorkspaceRevision !== (workspaceRequest.expected_revision ?? null)) {
            return json(409, {
              detail: { current_revision: currentWorkspaceRevision, message: 'Workspace revision conflict' },
            });
          }
          const maximum = clientMaximum(requested.max_canvas_schema_version);
          if (project.minimum_canvas_schema_version > maximum) {
            return json(...schemaUnsupported(project.minimum_canvas_schema_version, maximum));
          }
          const documentClient = documentMaximum(requested.max_document_schema_version);
          const currentDocumentFloor = project.minimum_document_schema_version ?? DEFAULT_DOCUMENT_SCHEMA_VERSION;
          if (currentDocumentFloor > documentClient) {
            return json(...documentSchemaUnsupported(currentDocumentFloor, documentClient));
          }
          const requestedDocumentFloor = requested.minimum_document_schema_version ?? currentDocumentFloor;
          if (requestedDocumentFloor < currentDocumentFloor) {
            return json(400, {
              detail: {
                code: 'document_schema_downgrade',
                current_minimum_document_schema_version: currentDocumentFloor,
                message: 'A project never lowers its document schema floor.',
                requested_minimum_document_schema_version: requestedDocumentFloor,
              },
            });
          }
          if (requestedDocumentFloor > documentClient) {
            return json(...documentSchemaUnsupported(requestedDocumentFloor, documentClient));
          }
          const documentFloor = requestedDocumentFloor;
          // As the server: a workspace is stored only beside split content, and the split never lands without one.
          if (workspaceRequest && documentFloor < SPLIT_DOCUMENT_SCHEMA_VERSION) {
            return json(400, {
              detail: {
                code: 'workspace_needs_split_document',
                message: 'A workspace is saved only with content at document schema 4 or newer.',
                minimum_document_schema_version: documentFloor,
              },
            });
          }
          if (
            !workspaceRequest &&
            currentDocumentFloor < SPLIT_DOCUMENT_SCHEMA_VERSION &&
            documentFloor >= SPLIT_DOCUMENT_SCHEMA_VERSION
          ) {
            return json(400, {
              detail: {
                code: 'split_needs_workspace',
                message: 'The save that splits a whole project must carry the caller’s workspace.',
                minimum_document_schema_version: currentDocumentFloor,
              },
            });
          }
          const requestedMinimum = requested.minimum_canvas_schema_version;
          if (requestedMinimum !== undefined && requestedMinimum < project.minimum_canvas_schema_version) {
            return json(400, {
              detail: {
                code: 'canvas_schema_downgrade',
                current_minimum_canvas_schema_version: project.minimum_canvas_schema_version,
                message: 'A project never lowers its canvas schema floor.',
                requested_minimum_canvas_schema_version: requestedMinimum,
              },
            });
          }
          if (requestedMinimum !== undefined && requestedMinimum > maximum) {
            return json(...schemaUnsupported(requestedMinimum, maximum));
          }

          project.data = requested.data ?? project.data;
          project.name = requested.name ?? project.name;
          project.minimum_canvas_schema_version = requestedMinimum ?? project.minimum_canvas_schema_version;
          project.minimum_document_schema_version = documentFloor;
          project.revision += 1;
          project.updated_at = timestamp(state);
          if (workspaceRequest) {
            project.workspace = {
              data: workspaceRequest.data ?? {},
              revision: (currentWorkspaceRevision ?? 0) + 1,
              updated_at: project.updated_at,
            };
          }

          const board = state.boards.get(project.board_id);
          if (board) {
            board.board_name = project.name;
            board.updated_at = project.updated_at;
          }

          return json(200, { ...writtenRecordOf(project), workspace: workspaceRequest ? project.workspace : null });
        }
        if (method === 'DELETE') {
          if (project) {
            const boardsMode = url.searchParams.get('boards') ?? 'release';
            if (boardsMode !== 'release' && boardsMode !== 'delete') {
              return json(422, { detail: 'boards must be release or delete' });
            }
            state.projects.delete(projectId);
            // The inbox goes with the project; other boards are released or deleted; media survives uncategorized.
            const removedBoardIds = new Set([project.board_id]);
            for (const board of state.boards.values()) {
              if ((board.project_id ?? null) === projectId && board.board_id !== project.board_id) {
                if (boardsMode === 'delete') {
                  removedBoardIds.add(board.board_id);
                } else {
                  board.project_id = null;
                }
              }
            }
            for (const boardId of removedBoardIds) {
              state.boards.delete(boardId);
            }
            for (const image of state.images.values()) {
              if (removedBoardIds.has(image.board_id)) {
                image.board_id = null;
              }
            }
            for (const video of state.videos.values()) {
              if (removedBoardIds.has(video.board_id)) {
                video.board_id = null;
              }
            }
          }
          return json(200, { ok: true });
        }
      }

      const workspaceMatch = /^\/api\/v1\/projects\/([^/]+)\/workspace$/.exec(path);
      if (method === 'PUT' && workspaceMatch) {
        const project = state.projects.get(decodeURIComponent(workspaceMatch[1]));
        if (!project) {
          return json(404, { detail: 'Project not found' });
        }
        const requested = await readJsonBody(request);
        // The workspace holds canvas state, so it answers the canvas floor as the content routes do.
        const canvasMaximum = clientMaximum(requested.max_canvas_schema_version);
        if (project.minimum_canvas_schema_version > canvasMaximum) {
          return json(...schemaUnsupported(project.minimum_canvas_schema_version, canvasMaximum));
        }
        const documentFloor = project.minimum_document_schema_version ?? DEFAULT_DOCUMENT_SCHEMA_VERSION;
        if (documentFloor > documentMaximum(requested.max_document_schema_version)) {
          return json(
            ...documentSchemaUnsupported(documentFloor, documentMaximum(requested.max_document_schema_version))
          );
        }
        const current = project.workspace?.revision ?? null;
        if (current !== (requested.expected_revision ?? null)) {
          return json(409, { detail: { current_revision: current, message: 'Workspace revision conflict' } });
        }
        project.workspace = {
          data: requested.data ?? {},
          revision: (current ?? 0) + 1,
          updated_at: timestamp(state),
        };
        return json(200, project.workspace);
      }

      const boardSnapshotMatch = /^\/api\/v1\/projects\/([^/]+)\/board-snapshot$/.exec(path);
      if (method === 'GET' && boardSnapshotMatch) {
        const project = state.projects.get(decodeURIComponent(boardSnapshotMatch[1]));

        if (!project) {
          return json(404, { detail: 'Project not found' });
        }

        // The inbox first, then the project's other boards in creation order — as the backend lists them.
        const members = [...state.boards.values()]
          .filter((board) => (board.project_id ?? null) === project.project_id && board.board_id !== project.board_id)
          .sort(
            (left, right) =>
              left.created_at.localeCompare(right.created_at) || left.board_id.localeCompare(right.board_id)
          );
        const boards = [state.boards.get(project.board_id), ...members]
          .filter((board) => board !== undefined)
          .map((board) => ({
            archived: board.archived,
            board_id: board.board_id,
            is_inbox: board.board_id === project.board_id,
            items: boardSnapshotItems(state, board.board_id),
            name: board.board_name,
          }));

        return json(200, { boards });
      }

      if (path.startsWith('/api/v1/client_state/')) {
        const key = url.searchParams.get('key') ?? '';

        if (path.endsWith('/get_by_key')) {
          return json(200, state.clientState.get(key) ?? null);
        }
        if (path.endsWith('/set_by_key')) {
          const value = await readJsonBody(request, null);

          state.clientState.set(key, value);
          return json(200, value);
        }
        if (path.endsWith('/delete_by_key')) {
          state.clientState.delete(key);
          return json(200, { ok: true });
        }
      }

      const queueItemMatch = /^\/api\/v1\/queue\/[^/]+\/i\/(\d+)$/.exec(path);
      if (queueItemMatch) {
        const itemId = Number(queueItemMatch[1]);
        const item = state.queueItems.get(itemId);

        if (method === 'GET') {
          return item ? json(200, item) : json(404, { detail: 'Queue item not found' });
        }
        if (method === 'DELETE') {
          state.queueItems.delete(itemId);
          return json(200, { ok: true });
        }
      }

      const queueItemDeliveryMatch = /^\/api\/v1\/queue\/[^/]+\/i\/(\d+)\/delivery$/.exec(path);
      if (queueItemDeliveryMatch && method === 'POST') {
        // Like the backend: one claimant stages an item until it confirms, releases or expires.
        const itemId = Number(queueItemDeliveryMatch[1]);
        if (!state.queueItems.has(itemId)) {
          return json(404, { detail: 'Queue item not found' });
        }
        const { action, claimant } = await readJsonBody(request);
        const claim = state.deliveryClaims.get(itemId);
        const now = Date.now();
        if (action === 'confirm') {
          state.deliveryClaims.set(itemId, { claimant, claimedAt: now, isDelivered: true });
          return json(200, { status: 'delivered' });
        }
        if (action === 'release') {
          if (claim?.claimant === claimant && !claim.isDelivered) {
            state.deliveryClaims.delete(itemId);
          }
          return json(200, { status: 'released' });
        }
        if (claim?.isDelivered) {
          return json(200, { status: 'delivered' });
        }
        if (claim && claim.claimant !== claimant && now - claim.claimedAt < DELIVERY_CLAIM_TTL_MS) {
          return json(200, { retry_after_ms: DELIVERY_CLAIM_TTL_MS - (now - claim.claimedAt), status: 'held' });
        }
        state.deliveryClaims.set(itemId, { claimant, claimedAt: now, isDelivered: false });
        return json(200, { status: 'claimed' });
      }

      const queueItemCancelMatch = /^\/api\/v1\/queue\/[^/]+\/i\/(\d+)\/cancel$/.exec(path);
      if (queueItemCancelMatch && method === 'PUT') {
        const item = state.queueItems.get(Number(queueItemCancelMatch[1]));

        if (!item) {
          return json(404, { detail: 'Queue item not found' });
        }
        // Like the backend, canceling any item of a workflow-call chain cancels the whole chain.
        const rootId = item.root_item_id ?? item.item_id;
        for (const chainItem of state.queueItems.values()) {
          if (
            (chainItem.root_item_id ?? chainItem.item_id) === rootId &&
            ['pending', 'waiting', 'in_progress'].includes(chainItem.status)
          ) {
            chainItem.status = 'canceled';
            chainItem.completed_at = timestamp(state);
            chainItem.updated_at = chainItem.completed_at;
          }
        }
        return json(200, item);
      }

      const queueMatch = /^\/api\/v1\/queue\/[^/]+\/(.+)$/.exec(path);
      if (queueMatch) {
        const action = queueMatch[1];

        if (action === 'enqueue_batch' && method === 'POST') {
          if (isImageMoveMaintenanceActive(state)) {
            return json(409, { detail: IMAGE_MOVE_MAINTENANCE_DETAIL });
          }

          const { batch = {} } = await readJsonBody(request);
          const runs = Number.isInteger(batch.runs) && batch.runs > 0 ? batch.runs : 1;
          const now = timestamp(state);
          const batchId = `mock-batch-${String(state.mutationClock)}`;
          const itemIds = [];

          // Items stay pending: the mock has no processor and no socket, so nothing ever completes them.
          for (let run = 0; run < runs; run += 1) {
            const itemId = Math.max(0, ...state.queueItems.keys()) + 1;

            itemIds.push(itemId);
            state.queueItems.set(itemId, {
              batch_id: batchId,
              completed_at: null,
              created_at: now,
              destination: batch.destination ?? null,
              error_message: null,
              error_traceback: null,
              error_type: null,
              field_values: null,
              item_id: itemId,
              origin: batch.origin ?? null,
              retried_from_item_id: null,
              session: { prepared_source_mapping: {}, results: {} },
              session_id: `mock-session-${String(itemId)}`,
              started_at: null,
              status: 'pending',
              updated_at: now,
              user_display_name: 'Fixture User',
              user_email: '[email protected]',
              user_id: MOCK_USER_ID,
            });
          }

          return json(201, {
            batch: { ...batch, batch_id: batchId },
            enqueued: itemIds.length,
            item_ids: itemIds,
            priority: 0,
            queue_id: 'default',
          });
        }

        const scopedItems = queueItemsForScope(state, url);

        if (action === 'status') {
          return json(200, {
            processor: { is_processing: scopedItems.some((item) => item.status === 'in_progress'), is_started: true },
            queue: queueStatus(scopedItems),
          });
        }
        if (action === 'current') {
          return json(200, scopedItems.find((item) => item.status === 'in_progress') ?? null);
        }
        if (action === 'next') {
          return json(200, scopedItems.find((item) => item.status === 'pending' || item.status === 'waiting') ?? null);
        }
        if (action === 'list_all') {
          return json(200, scopedItems);
        }
        if (action === 'items_by_ids') {
          const body = await readJsonBody(request);
          const ids = Array.isArray(body.item_ids) ? new Set(body.item_ids) : new Set();

          return json(
            200,
            scopedItems.filter((item) => ids.has(item.item_id))
          );
        }
        if (action === 'item_summaries_by_ids') {
          const body = await readJsonBody(request);
          const ids = Array.isArray(body.item_ids) ? body.item_ids : [];
          const itemsById = new Map(scopedItems.map((item) => [item.item_id, item]));

          return json(
            200,
            ids
              .map((itemId) => itemsById.get(itemId))
              .filter((item) => item !== undefined)
              .map((item) =>
                Object.fromEntries(
                  [
                    'item_id',
                    'created_at',
                    'status',
                    'device',
                    'started_at',
                    'completed_at',
                    'origin',
                    'destination',
                    'batch_id',
                    'user_id',
                    'user_display_name',
                    'user_email',
                    'field_values',
                    'parent_item_id',
                  ].map((key) => [key, item[key] ?? null])
                )
              )
          );
        }
        if (action === 'item_ids' || action === 'list') {
          const descending = url.searchParams.get('order_dir')?.toUpperCase() !== 'ASC';
          const itemIds = scopedItems.map((item) => item.item_id).sort((left, right) => left - right);
          // Like the backend: a limit returns the head of the order, and total_count is then the number returned.
          const limit = action === 'item_ids' ? url.searchParams.get('limit') : null;

          if (limit !== null && !(/^\d+$/.test(limit) && Number(limit) >= 1 && Number(limit) <= 1000)) {
            return json(422, { detail: 'limit must be an integer from 1 to 1000' });
          }
          if (descending) {
            itemIds.reverse();
          }

          const returned = limit === null ? itemIds : itemIds.slice(0, Number(limit));

          return json(200, { item_ids: returned, total_count: returned.length });
        }
        if (action === 'cancel_all' && method === 'PUT') {
          const originPrefix = url.searchParams.get('origin_prefix');

          if (originPrefix !== null && state.workingMemory.isCalibrationPrefix(originPrefix)) {
            return json(200, { canceled: state.workingMemory.cancelByOrigin(originPrefix) });
          }

          let canceled = 0;
          for (const item of scopedItems) {
            if (item.status === 'pending' || item.status === 'in_progress') {
              item.status = 'canceled';
              canceled += 1;
            }
          }
          return json(200, { canceled });
        }
        if (action === 'clear' && method === 'PUT') {
          state.queueItems.clear();
          return json(200, { deleted: true });
        }
        if (action === 'prune' && method === 'PUT') {
          // Like the backend: a finished child stays while its root is still active.
          const isTerminal = (item) => ['completed', 'failed', 'canceled'].includes(item?.status);
          const prunable = [...state.queueItems.values()].filter(
            (item) =>
              isTerminal(item) &&
              (item.root_item_id === null ||
                item.root_item_id === undefined ||
                !state.queueItems.has(item.root_item_id) ||
                isTerminal(state.queueItems.get(item.root_item_id)))
          );

          for (const item of prunable) {
            state.queueItems.delete(item.item_id);
          }
          return json(200, { deleted: prunable.length });
        }
        if (action === 'cancel_by_batch_ids' && method === 'PUT') {
          const body = await readJsonBody(request);
          const batchIds = new Set(Array.isArray(body.batch_ids) ? body.batch_ids : []);
          let canceled = 0;

          for (const item of state.queueItems.values()) {
            if (batchIds.has(item.batch_id) && ['pending', 'waiting', 'in_progress'].includes(item.status)) {
              item.status = 'canceled';
              item.completed_at = timestamp(state);
              item.updated_at = item.completed_at;
              canceled += 1;
            }
          }
          return json(200, { canceled });
        }
        if (action === 'retry_items_by_id' && method === 'PUT') {
          // Like the backend: each failed or canceled root retries once as a new pending item paired with its rerun.
          const itemIds = await readJsonBody(request, []);
          const retriedItems = [];
          const seenRoots = new Set();
          const isRetryable = (item) => ['failed', 'canceled'].includes(item?.status);

          for (const itemId of Array.isArray(itemIds) ? itemIds : []) {
            const item = state.queueItems.get(itemId);
            const root = state.queueItems.get(item?.root_item_id ?? item?.item_id);

            if (!isRetryable(item) || !isRetryable(root) || seenRoots.has(root.item_id)) {
              continue;
            }
            seenRoots.add(root.item_id);

            const nextId = Math.max(0, ...state.queueItems.keys()) + 1;
            const now = timestamp(state);

            state.queueItems.set(nextId, {
              ...clone(root),
              completed_at: null,
              created_at: now,
              error_message: null,
              error_traceback: null,
              error_type: null,
              item_id: nextId,
              retried_from_item_id: root.retried_from_item_id ?? root.item_id,
              session: { prepared_source_mapping: {}, results: {} },
              session_id: `${root.session_id}-retry-${nextId}`,
              started_at: null,
              status: 'pending',
              updated_at: now,
            });
            retriedItems.push({ item_id: nextId, source_item_id: root.item_id });
          }
          return json(200, {
            queue_id: 'default',
            retried_item_ids: retriedItems.map((item) => item.source_item_id),
            retried_items: retriedItems,
          });
        }

        return json(200, null);
      }

      if (path.startsWith('/api/v2/models/') && path.includes('working_memory')) {
        const body = method === 'POST' ? await readJsonBody(request) : null;
        const answer = state.workingMemory.handle({ body, method, path, scenario: faults.workingMemory });

        if (answer) {
          return json(answer.status, answer.body);
        }
      }

      if (method === 'GET' && path === '/api/v2/models/stats') {
        return json(200, null);
      }
      if (method === 'GET' && path === '/api/v2/models/missing') {
        return json(200, { models: [] });
      }
      if (method === 'GET' && path === '/api/v2/models/models_dir') {
        return json(200, '/opt/invokeai/models');
      }
      if (method === 'GET' && path === '/api/v2/models/install') {
        return json(200, []);
      }
      if (method === 'GET' && path === '/api/v2/models/capabilities') {
        if (faults.capabilities === 'error') {
          return json(500, { detail: 'Fixture capability outage.' });
        }

        return json(200, faults.capabilities === 'empty' ? [] : ARCHITECTURE_CAPABILITIES);
      }
      if (method === 'GET' && path === '/api/v2/models/starter_models') {
        return json(200, getStarterModelsResponse(state));
      }
      if (method === 'GET' && path === '/api/v2/models/hf_login') {
        return json(200, 'unknown');
      }
      if (method === 'GET' && path === '/api/v2/models/sync/orphaned') {
        return json(200, []);
      }

      const reidentifyMatch = /^\/api\/v2\/models\/i\/([^/]+)\/reidentify$/.exec(path);
      if (method === 'POST' && reidentifyMatch) {
        // Like the backend's re-probe: fields recorded since the model was installed are filled in.
        const key = decodeURIComponent(reidentifyMatch[1]);
        const model = state.models.get(key);
        if (!model) {
          return json(404, { detail: 'Model not found' });
        }
        const identified = { ...model, ...state.modelProbes.get(key) };
        state.models.set(key, identified);
        return json(200, clone(identified));
      }

      const modelMatch = /^\/api\/v2\/models\/i\/([^/]+)$/.exec(path);
      if (modelMatch) {
        const key = decodeURIComponent(modelMatch[1]);
        const model = state.models.get(key);
        if (!model) {
          return json(404, { detail: 'Model not found' });
        }
        if (method === 'PATCH') {
          // Fields replace stored ones wholesale, as in update_model, but without the backend's validation or 409s.
          const updated = { ...model, ...(await readJsonBody(request)), key };
          state.models.set(key, updated);
          return json(200, clone(updated));
        }
        return json(200, model);
      }

      if (method === 'GET' && (path === '/api/v2/models' || path === '/api/v2/models/')) {
        return json(200, { models: [...state.models.values()] });
      }

      if (path.startsWith('/api/v1/model_relationships')) {
        return json(200, []);
      }

      if (method === 'GET' && (path === '/api/v1/wildcards' || path === '/api/v1/wildcards/')) {
        return json(200, sortedWildcards(state));
      }

      if (method === 'POST' && (path === '/api/v1/wildcards' || path === '/api/v1/wildcards/')) {
        const body = await readJsonBody(request);
        const name = typeof body.name === 'string' ? body.name.trim() : '';
        if (!name || !Array.isArray(body.values)) {
          return json(422, { detail: 'A wildcard needs a name and values' });
        }
        if (wildcardNameTaken(state, name)) {
          return json(409, { detail: `A wildcard named '${name}' already exists` });
        }
        const id = `wildcard-id-${randomUUID()}`;
        const wildcard = { id, name, user_id: MOCK_USER_ID, values: body.values.map(String) };
        state.wildcards.set(id, wildcard);
        return json(201, clone(wildcard));
      }

      if (method === 'POST' && path === '/api/v1/wildcards/delete') {
        // Mirrors the server: 1 to 1000 ids, duplicates once, unknown ids skipped and left out of the result.
        const body = await readJsonBody(request);
        const ids = body.wildcard_ids;
        if (!Array.isArray(ids) || ids.length === 0 || ids.length > MAX_WILDCARD_BATCH_SIZE) {
          return json(422, { detail: `wildcard_ids takes 1 to ${String(MAX_WILDCARD_BATCH_SIZE)} ids` });
        }
        const deletedIds = [...new Set(ids)].filter((id) => state.wildcards.delete(id));
        return json(200, { deleted_ids: deletedIds });
      }

      const wildcardMatch = /^\/api\/v1\/wildcards\/([^/]+)$/.exec(path);
      if (wildcardMatch && (method === 'PATCH' || method === 'DELETE')) {
        const id = decodeURIComponent(wildcardMatch[1]);
        const wildcard = state.wildcards.get(id);
        if (!wildcard) {
          return json(404, { detail: 'Wildcard not found' });
        }
        if (method === 'DELETE') {
          state.wildcards.delete(id);
          response.writeHead(204);
          return response.end();
        }
        const body = await readJsonBody(request);
        const name = typeof body.name === 'string' ? body.name.trim() : wildcard.name;
        if (wildcardNameTaken(state, name, id)) {
          return json(409, { detail: `A wildcard named '${name}' already exists` });
        }
        const updated = {
          ...wildcard,
          name,
          values: Array.isArray(body.values) ? body.values.map(String) : wildcard.values,
        };
        state.wildcards.set(id, updated);
        return json(200, clone(updated));
      }

      if ((method === 'PUT' || method === 'DELETE') && /^\/api\/v1\/intermediates\/holds\/[^/]+$/.test(path)) {
        response.writeHead(204);
        return response.end();
      }

      if (method === 'GET' && path === '/api/v1/intermediates/summary') {
        // Mirrors IntermediatesService.get_summary: non-admins see only their rows and may not name another owner.
        const isAdmin = isAdminCaller(faults);
        const ownerId = url.searchParams.get('owner_id');
        if (!isAdmin && ownerId !== null && ownerId !== MOCK_USER_ID) {
          return json(403, { detail: 'Only administrators can inspect other accounts' });
        }
        const ownerFilter = isAdmin ? ownerId : MOCK_USER_ID;
        const sort = url.searchParams.get('sort') ?? 'reclaimable_bytes';
        const descending = (url.searchParams.get('order') ?? 'desc') === 'desc';
        const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
        const limit = Math.max(1, Number(url.searchParams.get('limit') ?? 50));
        const rows = matchingIntermediates(state.intermediates, {
          isAdmin,
          ownerFilter,
          projectId: url.searchParams.get('project_id'),
          search: url.searchParams.get('search'),
        }).sort((left, right) =>
          (left.project_name ?? '').toLowerCase().localeCompare((right.project_name ?? '').toLowerCase())
        );
        if (sort === 'reclaimable_bytes') {
          rows.sort((left, right) => (right.reclaimable_bytes - left.reclaimable_bytes) * (descending ? 1 : -1));
        } else if (descending) {
          rows.reverse();
        }
        const totals = rows.reduce(
          (acc, row) => ({
            rows: acc.rows + 1,
            safe_images: acc.safe_images + row.images.safe,
            safe_videos: acc.safe_videos + row.videos.safe,
            in_use_images: acc.in_use_images + row.images.referenced + row.images.active + row.images.recent,
            in_use_videos: acc.in_use_videos + row.videos.referenced + row.videos.active + row.videos.recent,
            reclaimable_bytes: acc.reclaimable_bytes + row.reclaimable_bytes,
            unknown_size_count: acc.unknown_size_count + row.unknown_size_count,
          }),
          {
            rows: 0,
            safe_images: 0,
            safe_videos: 0,
            in_use_images: 0,
            in_use_videos: 0,
            reclaimable_bytes: 0,
            unknown_size_count: 0,
          }
        );
        return json(200, {
          items: rows.slice(offset, offset + limit),
          total: rows.length,
          offset,
          limit,
          totals,
          recent_grace_seconds: 1800,
          measuring: false,
          can_manage_everyone: isAdmin,
        });
      }

      if (method === 'POST' && path === '/api/v1/intermediates/previews') {
        const requested = await readJsonBody(request);
        // Mirrors IntermediatesService._authorize_scope.
        const isAdmin = isAdminCaller(faults);
        const scope = requested?.scope ?? {};
        if (scope.kind === 'everyone' && !isAdmin) {
          return json(403, { detail: "Only administrators can clear everyone's intermediates" });
        }
        if (scope.kind === 'owner' && !scope.user_id) {
          return json(422, { detail: 'An owner scope names the account to clear' });
        }
        if (scope.kind === 'owner' && scope.user_id !== MOCK_USER_ID && !isAdmin) {
          return json(403, { detail: "Only administrators can clear another account's intermediates" });
        }
        if (scope.kind === 'selection' && !(scope.targets?.length > 0)) {
          return json(422, { detail: 'A selection scope names at least one row' });
        }
        if (scope.kind === 'selection' && !isAdmin && scope.targets.some((target) => target.user_id !== MOCK_USER_ID)) {
          return json(403, { detail: "Only administrators can clear another account's intermediates" });
        }
        if (scope.kind === 'matching' && !isAdmin && scope.user_id && scope.user_id !== MOCK_USER_ID) {
          return json(403, { detail: "Only administrators can delete another account's intermediates" });
        }
        if (scope.kind === 'matching' && (scope.excluded?.length ?? 0) > 1000) {
          return json(422, { detail: 'Too many excluded rows' });
        }
        const previewId = `preview-${state.intermediatesPreviews.size + 1}`;
        const targets =
          scope.kind === 'selection'
            ? state.intermediates.filter((row) =>
                scope.targets.some(
                  (target) => target.user_id === row.user_id && (target.project_id ?? null) === row.project_id
                )
              )
            : scope.kind === 'owner'
              ? state.intermediates.filter((row) => row.user_id === scope.user_id)
              : scope.kind === 'matching'
                ? // Mirrors IntermediatesService._resolve_scope: the summary's filters minus the excluded rows.
                  matchingIntermediates(state.intermediates, {
                    isAdmin,
                    ownerFilter: isAdmin ? (scope.user_id ?? null) : MOCK_USER_ID,
                    projectId: scope.project_id ?? null,
                    search: scope.search ?? null,
                  }).filter(
                    (row) =>
                      !(scope.excluded ?? []).some(
                        (target) => target.user_id === row.user_id && (target.project_id ?? null) === row.project_id
                      )
                  )
                : state.intermediates;
        if (scope.kind === 'matching' && targets.length === 0) {
          return json(422, { detail: 'No rows match the filter' });
        }
        const force = requested?.mode === 'force';
        const affectedDocuments = force
          ? targets
              .filter((row) => row.images.referenced + row.videos.referenced > 0)
              .map((row) => ({
                kind: 'project',
                user_id: row.user_id,
                user_display_name: row.user_display_name,
                user_email: row.user_email,
                owner_id: row.project_id ?? 'unassigned',
                name: row.project_name,
                references: row.images.referenced + row.videos.referenced,
              }))
          : [];
        const impact = targets.reduce(
          (acc, row) => ({
            delete_images: acc.delete_images + row.images.safe + (force ? row.images.referenced : 0),
            delete_videos: acc.delete_videos + row.videos.safe + (force ? row.videos.referenced : 0),
            keep_referenced_images: acc.keep_referenced_images + (force ? 0 : row.images.referenced),
            keep_referenced_videos: acc.keep_referenced_videos + (force ? 0 : row.videos.referenced),
            keep_active_images: acc.keep_active_images + row.images.active,
            keep_active_videos: acc.keep_active_videos + row.videos.active,
            keep_recent_images: acc.keep_recent_images + row.images.recent,
            keep_recent_videos: acc.keep_recent_videos + row.videos.recent,
            reclaimable_bytes: acc.reclaimable_bytes + row.reclaimable_bytes + (force ? row.referenced_bytes : 0),
            unknown_size_count: acc.unknown_size_count + row.unknown_size_count,
          }),
          {
            delete_images: 0,
            delete_videos: 0,
            keep_referenced_images: 0,
            keep_referenced_videos: 0,
            keep_active_images: 0,
            keep_active_videos: 0,
            keep_recent_images: 0,
            keep_recent_videos: 0,
            reclaimable_bytes: 0,
            unknown_size_count: 0,
          }
        );
        if (force && affectedDocuments.length > 10_000) {
          return json(422, { detail: 'This force delete would break more than 10000 documents; narrow the scope' });
        }
        const preview = {
          preview_id: previewId,
          mode: requested?.mode ?? 'safe',
          scope: {
            kind: scope.kind ?? 'owner',
            targets: scope.targets ?? [],
            user_id: scope.user_id ?? null,
            project_id: scope.project_id ?? null,
            search: scope.search ?? null,
            excluded: scope.excluded ?? [],
          },
          created_at: new Date().toISOString(),
          expires_at: new Date(Date.now() + 600_000).toISOString(),
          target_rows: targets.length,
          impact,
          affected_documents: affectedDocuments.slice(0, 200),
          affected_documents_total: affectedDocuments.length,
        };
        state.intermediatesPreviews.set(previewId, { preview, targets });
        return json(201, preview);
      }

      if (method === 'GET' && path === '/api/v1/intermediates/operations') {
        // Newest first; the real server retains a handful of settled operations per account.
        return json(200, { items: [...state.intermediatesOperations.values()].reverse().slice(0, 5) });
      }

      if (method === 'POST' && path === '/api/v1/intermediates/operations') {
        const requested = await readJsonBody(request);
        // Mirrors IntermediatesService.start_operation: a preview is confirmed once.
        const frozen = state.intermediatesPreviews.get(requested?.preview_id);
        if (!frozen) {
          return json(404, { detail: 'Preview expired or unknown; request a new one' });
        }
        state.intermediatesPreviews.delete(requested.preview_id);
        const operationId = `operation-${state.intermediatesOperations.size + 1}`;
        const { impact } = frozen.preview;
        const operation = {
          operation_id: operationId,
          user_id: MOCK_USER_ID,
          mode: frozen.preview.mode,
          scope: frozen.preview.scope,
          status: 'completed',
          created_at: new Date().toISOString(),
          started_at: new Date().toISOString(),
          completed_at: new Date().toISOString(),
          error: null,
          target_images: impact.delete_images,
          target_videos: impact.delete_videos,
          progress: {
            processed_images: impact.delete_images,
            processed_videos: impact.delete_videos,
            deleted_images: impact.delete_images,
            deleted_videos: impact.delete_videos,
            retained_images: 0,
            retained_videos: 0,
            failed_images: 0,
            failed_videos: 0,
            reclaimed_bytes: impact.reclaimable_bytes,
            unknown_size_count: impact.unknown_size_count,
            pending_disk_cleanup: 0,
          },
        };
        for (const row of frozen.targets) {
          row.images = {
            ...row.images,
            safe: 0,
            referenced: frozen.preview.mode === 'force' ? 0 : row.images.referenced,
          };
          row.videos = {
            ...row.videos,
            safe: 0,
            referenced: frozen.preview.mode === 'force' ? 0 : row.videos.referenced,
          };
          row.reclaimable_bytes = 0;
          row.unknown_size_count = 0;
        }
        state.intermediatesOperations.set(operationId, operation);
        return json(202, operation);
      }

      {
        const operationMatch = /^\/api\/v1\/intermediates\/operations\/([^/]+)$/.exec(path);
        if (method === 'GET' && operationMatch) {
          const operation = state.intermediatesOperations.get(decodeURIComponent(operationMatch[1]));
          return operation ? json(200, operation) : json(404, { detail: 'Not found' });
        }
      }

      if (method === 'GET' && path === '/api/v1/fonts') {
        return json(200, {
          items: [],
          total: 0,
          offset: Math.max(0, Number(url.searchParams.get('offset') ?? 0)),
          limit: Number(url.searchParams.get('limit') ?? 100),
        });
      }

      // Implements only the {a|b} subset needed by journeys.
      if (method === 'POST' && path === '/api/v1/utilities/dynamicprompts') {
        const requested = await readJsonBody(request);
        const prompt = typeof requested?.prompt === 'string' ? requested.prompt : '';
        const maxPrompts = typeof requested?.max_prompts === 'number' ? requested.max_prompts : 100;
        const match = /\{([^{}]*)\}/.exec(prompt);
        const prompts = match ? match[1].split('|').map((value) => prompt.replace(match[0], value.trim())) : [prompt];

        return json(200, { error: null, prompts: prompts.slice(0, Math.max(1, maxPrompts)) });
      }

      if (method === 'GET' && (path === '/api/v2/custom_nodes' || path === '/api/v2/custom_nodes/')) {
        return json(200, state.nodeCatalog);
      }

      if (path === '/api/v1/boards' || path === '/api/v1/boards/') {
        if (method === 'GET') {
          return json(
            200,
            [...state.boards.values()]
              .filter((board) => boardAccessFor(state, faults, board).readable)
              .map((board) => boardDto(state, board, faults))
          );
        }
        if (method === 'POST') {
          const now = timestamp(state);
          const boardId = `mock-board-${state.nextBoardNumber}`;
          const projectId = url.searchParams.get('project_id');
          if (projectId !== null && !state.projects.has(projectId)) {
            return json(404, { detail: 'Project not found' });
          }
          const board = {
            archived: false,
            board_id: boardId,
            board_name: url.searchParams.get('board_name') ?? `Board ${state.nextBoardNumber}`,
            general_access: 'restricted',
            created_at: now,
            deleted_at: null,
            owner_username: null,
            project_id: projectId,
            updated_at: now,
            user_id: MOCK_USER_ID,
          };

          state.nextBoardNumber += 1;
          state.boards.set(boardId, board);

          return json(201, boardDto(state, board, faults));
        }
      }

      const boardMatch = /^\/api\/v1\/boards\/([^/]+)$/.exec(path);
      if (boardMatch) {
        const boardId = decodeURIComponent(boardMatch[1]);
        const board = state.boards.get(boardId);

        if (!board) {
          return json(404, { detail: 'Board not found' });
        }
        if (!boardAccessFor(state, faults, board).readable) {
          return json(...BOARD_UNREADABLE);
        }
        if (method === 'GET') {
          return json(200, boardDto(state, board, faults));
        }
        if (method === 'PATCH') {
          const changes = await readJsonBody(request);
          const moves = Object.hasOwn(changes, 'project_id');
          const requiredActions = [
            ...(changes.board_name !== undefined ? ['rename'] : []),
            ...(changes.archived !== undefined ? ['archive'] : []),
            ...(changes.cover_image_name !== undefined ? ['set_cover'] : []),
            ...(changes.general_access !== undefined ? ['set_general_access'] : []),
            ...(moves ? ['move'] : []),
          ];
          // As the router: the caller's role first, then the inbox refuses what its project owns.
          for (const action of requiredActions) {
            if (!boardAccessFor(state, faults, board, { ignoreInbox: true }).allows(action)) {
              return json(...BOARD_ACTION_FORBIDDEN);
            }
          }
          if (
            inboxProjectIdForBoard(state, boardId) !== null &&
            (changes.board_name !== undefined ||
              changes.archived !== undefined ||
              changes.general_access !== undefined ||
              moves)
          ) {
            return json(409, { detail: "This board is the project's inbox" });
          }
          const nextProjectId = moves ? changes.project_id : (board.project_id ?? null);
          if (nextProjectId !== null && !state.projects.has(nextProjectId)) {
            return json(404, { detail: 'Project not found' });
          }

          for (const key of ['archived', 'board_name', 'cover_image_name', 'general_access']) {
            if (changes[key] !== undefined) {
              board[key] = changes[key];
            }
          }
          if (moves) {
            board.project_id = nextProjectId;
          }
          board.updated_at = timestamp(state);

          return json(201, boardDto(state, board, faults));
        }
        if (method === 'DELETE') {
          if (!boardAccessFor(state, faults, board, { ignoreInbox: true }).allows('delete')) {
            return json(...BOARD_ACTION_FORBIDDEN);
          }
          if (inboxProjectIdForBoard(state, boardId) !== null) {
            // Refused before any media is touched — the whole point of the ordering.
            return json(409, { detail: "This board is the project's inbox" });
          }

          const includeImages = url.searchParams.get('include_images') === 'true';
          const boardImages = [...state.images.values()].filter((image) => image.board_id === boardId);
          const boardVideos = [...state.videos.values()].filter(
            (video) => video.board_id === boardId && video.owner_user_id === MOCK_USER_ID
          );
          const imageNames = boardImages.map((image) => image.image_name);
          const videoNames = boardVideos.map((video) => video.video_name);

          state.boards.delete(boardId);
          if (includeImages) {
            for (const imageName of imageNames) {
              state.images.delete(imageName);
            }
            for (const videoName of videoNames) {
              state.videos.delete(videoName);
            }

            return json(200, {
              board_id: boardId,
              deleted_board_images: [],
              deleted_board_videos: [],
              deleted_images: imageNames,
              deleted_videos: videoNames,
              failed_images: [],
              failed_videos: [],
            });
          }

          for (const image of boardImages) {
            image.board_id = null;
          }
          for (const video of boardVideos) {
            video.board_id = null;
          }

          return json(200, {
            board_id: boardId,
            deleted_board_images: imageNames,
            deleted_board_videos: videoNames,
            deleted_images: [],
            deleted_videos: [],
            failed_images: [],
            failed_videos: [],
          });
        }
      }

      if (method === 'GET' && path === '/api/v1/virtual_boards/by_date') {
        return json(200, listVirtualDateBoards(state));
      }

      const virtualBoardItemNamesMatch = /^\/api\/v1\/virtual_boards\/by_date\/([^/]+)\/item_names$/.exec(path);
      if (method === 'GET' && virtualBoardItemNamesMatch) {
        const date = decodeURIComponent(virtualBoardItemNamesMatch[1]);

        return json(200, listGalleryItemNames(state, url, faults, { createdDate: date }));
      }

      const virtualBoardNamesMatch = /^\/api\/v1\/virtual_boards\/by_date\/([^/]+)\/image_names$/.exec(path);
      if (method === 'GET' && virtualBoardNamesMatch) {
        const date = decodeURIComponent(virtualBoardNamesMatch[1]);
        const imageNames = [...state.images.values()]
          .filter((image) => image.created_at.startsWith(date))
          .map((image) => image.image_name);

        return json(200, { image_names: imageNames, total_count: imageNames.length });
      }

      if (method === 'POST' && path === '/api/v1/images/images_by_names') {
        const body = await readJsonBody(request);
        const names = Array.isArray(body.image_names) ? body.image_names : [];

        return json(
          200,
          names.flatMap((name) => (state.images.has(name) ? [state.images.get(name)] : []))
        );
      }

      if (method === 'POST' && path === '/api/v1/images/upload') {
        const multipartBody = await readBody(request);
        const requestedName = /filename="([^"]+)"/.exec(multipartBody)?.[1] ?? 'uploaded-fixture';
        const suffix = String(state.nextImageNumber).padStart(3, '0');
        const imageName = `fixture-upload-${suffix}-${requestedName.replaceAll(/[^a-zA-Z0-9._-]/g, '-')}.png`;
        const boardId = url.searchParams.get('board_id');
        const uploadBoard = boardId ? state.boards.get(boardId) : undefined;
        const uploadRefusal = uploadBoard ? boardRefusal(state, faults, uploadBoard, 'add_media') : null;
        if (uploadRefusal) {
          return json(...uploadRefusal);
        }
        const now = timestamp(state);
        const image = {
          board_id: boardId && state.boards.has(boardId) ? boardId : null,
          created_at: now,
          deleted_at: null,
          has_workflow: false,
          height: 1,
          image_category: url.searchParams.get('image_category') ?? 'general',
          image_name: imageName,
          image_origin: 'external',
          image_subfolder: '',
          image_url: `/api/v1/images/i/${imageName}/full`,
          is_intermediate: url.searchParams.get('is_intermediate') === 'true',
          node_id: null,
          session_id: null,
          starred: false,
          thumbnail_url: `/api/v1/images/i/${imageName}/thumbnail`,
          updated_at: now,
          width: 1,
        };

        state.nextImageNumber += 1;
        state.images.set(imageName, image);
        response.setHeader('location', image.image_url);
        return json(201, image);
      }

      if (method === 'POST' && (path === '/api/v1/images/star' || path === '/api/v1/images/unstar')) {
        const body = await readJsonBody(request);
        const names = Array.isArray(body.image_names) ? [...new Set(body.image_names)] : [];
        const succeeded = [];
        const affectedBoards = [];
        const starred = path.endsWith('/star');

        for (const name of names) {
          const image = state.images.get(name);

          if (!image) {
            continue;
          }
          image.starred = starred;
          succeeded.push(name);
          affectedBoards.push(image.board_id ?? 'none');
        }

        return json(200, {
          affected_boards: [...new Set(affectedBoards)],
          ...(starred ? { starred_images: succeeded } : { unstarred_images: succeeded }),
        });
      }

      if (method === 'POST' && path === '/api/v1/images/copy') {
        const body = await readJsonBody(request);
        const names = Array.isArray(body.image_names) ? body.image_names : [];
        const boardId = body.board_id ?? null;

        if (boardId !== null && !state.boards.has(boardId)) {
          return json(404, { detail: 'Board not found' });
        }
        const copyRefusal =
          boardId === null ? null : boardRefusal(state, faults, state.boards.get(boardId), 'add_media');
        if (copyRefusal) {
          return json(...copyRefusal);
        }

        const copied = [];
        const failed = [];

        for (const name of names) {
          const source = state.images.get(name);

          if (!source) {
            failed.push(name);
            continue;
          }

          const suffix = String(state.nextImageNumber).padStart(3, '0');
          const imageName = `fixture-copy-${suffix}.png`;
          const now = timestamp(state);

          state.nextImageNumber += 1;
          // Copies need a new board_images key; retain category/provenance, but set starring separately.
          state.images.set(imageName, {
            ...clone(source),
            board_id: boardId,
            created_at: now,
            image_name: imageName,
            image_url: `/api/v1/images/i/${imageName}/full`,
            is_intermediate: false,
            starred: false,
            thumbnail_url: `/api/v1/images/i/${imageName}/thumbnail`,
            updated_at: now,
          });
          copied.push({ image_name: imageName, source_image_name: name });
        }

        return json(200, { copied, failed });
      }

      if (method === 'POST' && path === '/api/v1/videos/copy') {
        const body = await readJsonBody(request);
        const names = Array.isArray(body.video_names) ? body.video_names : [];
        const boardId = body.board_id ?? null;

        if (boardId !== null && !state.boards.has(boardId)) {
          return json(404, { detail: 'Board not found' });
        }
        const copyRefusal =
          boardId === null ? null : boardRefusal(state, faults, state.boards.get(boardId), 'add_media');
        if (copyRefusal) {
          return json(...copyRefusal);
        }

        const copied = [];
        const failed = [];

        for (const name of names) {
          const source = state.videos.get(name);

          if (!source || source.owner_user_id !== MOCK_USER_ID) {
            failed.push(name);
            continue;
          }

          const suffix = String(state.nextVideoNumber).padStart(3, '0');
          const videoName = `fixture-copy-${suffix}.mp4`;
          const now = timestamp(state);

          state.nextVideoNumber += 1;
          state.videos.set(videoName, {
            ...clone(source),
            board_id: boardId,
            created_at: now,
            is_intermediate: false,
            starred: false,
            updated_at: now,
            video_name: videoName,
          });
          copied.push({ source_video_name: name, video_name: videoName });
        }

        return json(200, { copied, failed });
      }

      if (method === 'GET' && (path === '/api/v1/images' || path === '/api/v1/images/')) {
        return json(200, listImages(state, url));
      }

      if (method === 'GET' && path === '/api/v1/gallery/items/') {
        return json(200, listGalleryItems(state, url, faults));
      }

      if (method === 'GET' && path === '/api/v1/gallery/items/location') {
        const location = getGalleryItemLocation(state, url, faults);

        return location ? json(200, location) : json(404, { detail: 'Gallery item not found' });
      }

      if (method === 'GET' && path === '/api/v1/gallery/items/names') {
        return json(200, listGalleryItemNames(state, url, faults));
      }

      if (method === 'POST' && path === '/api/v1/gallery/usage') {
        return json(...galleryMediaUsage(state, faults, await readJsonBody(request)));
      }

      const imageAssetMatch = /^\/api\/v1\/images\/i\/([^/]+)\/(full|thumbnail)$/.exec(path);
      if (method === 'GET' && imageAssetMatch) {
        const imageName = decodeURIComponent(imageAssetMatch[1]);

        const image = state.images.get(imageName);
        return image
          ? writePng(response, image, imageAssetMatch[2] === 'thumbnail')
          : json(404, { detail: 'Image not found' });
      }

      const imageWorkflowMatch = /^\/api\/v1\/images\/i\/([^/]+)\/workflow$/.exec(path);
      if (method === 'GET' && imageWorkflowMatch) {
        const image = state.images.get(decodeURIComponent(imageWorkflowMatch[1]));

        return image
          ? json(200, { graph: image.graph ?? null, workflow: image.workflow ?? null })
          : json(404, { detail: 'Image not found' });
      }

      const imageMetadataMatch = /^\/api\/v1\/images\/i\/([^/]+)\/metadata$/.exec(path);
      if (method === 'GET' && imageMetadataMatch) {
        return json(200, {});
      }

      const imageMatch = /^\/api\/v1\/images\/i\/([^/]+)$/.exec(path);
      if ((method === 'GET' || method === 'PATCH') && imageMatch) {
        const imageName = decodeURIComponent(imageMatch[1]);
        const image = state.images.get(imageName);
        if (!image) {
          return json(404, { detail: 'Image not found' });
        }
        if (method === 'PATCH') {
          const changes = await readJsonBody(request);
          if (
            ('is_intermediate' in changes && typeof changes.is_intermediate !== 'boolean') ||
            ('image_category' in changes &&
              !['general', 'control', 'mask', 'user', 'other'].includes(changes.image_category))
          ) {
            return json(422, { detail: 'Invalid image changes' });
          }
          if ('is_intermediate' in changes) {
            image.is_intermediate = changes.is_intermediate;
          }
          if ('image_category' in changes) {
            image.image_category = changes.image_category;
          }
        }
        return json(200, image);
      }

      if (method === 'POST' && path === '/api/v1/videos/upload') {
        const multipartBody = await readBody(request);
        const requestedName = /filename="([^"]+)"/.exec(multipartBody)?.[1] ?? 'uploaded-fixture.mp4';
        const suffix = String(state.nextVideoNumber).padStart(3, '0');
        const videoName = `fixture-upload-${suffix}-${requestedName.replaceAll(/[^a-zA-Z0-9._-]/g, '-')}`;
        const boardId = url.searchParams.get('board_id');
        const uploadBoard = boardId ? state.boards.get(boardId) : undefined;
        const uploadRefusal = uploadBoard ? boardRefusal(state, faults, uploadBoard, 'add_media') : null;
        if (uploadRefusal) {
          return json(...uploadRefusal);
        }
        const video = {
          board_id: boardId && state.boards.has(boardId) ? boardId : null,
          created_at: timestamp(state),
          duration: 1,
          fps: 10,
          graph: null,
          height: 64,
          is_intermediate: url.searchParams.get('is_intermediate') === 'true',
          metadata: null,
          owner_user_id: MOCK_USER_ID,
          starred: false,
          thumbnail_url: `/api/v1/videos/i/${videoName}/thumbnail`,
          video_category: url.searchParams.get('video_category') ?? 'general',
          video_name: videoName,
          video_origin: 'external',
          video_url: `/api/v1/videos/i/${videoName}/full`,
          width: 64,
          workflow: null,
        };

        state.nextVideoNumber += 1;
        state.videos.set(videoName, video);
        response.setHeader('location', video.video_url);
        return json(201, toVideoDto(video));
      }

      if (method === 'GET' && (path === '/api/v1/videos' || path === '/api/v1/videos/')) {
        return json(200, listVideos(state, url));
      }

      if (method === 'POST' && (path === '/api/v1/videos/star' || path === '/api/v1/videos/unstar')) {
        const body = await readJsonBody(request);
        const names = Array.isArray(body.video_names) ? [...new Set(body.video_names)] : [];
        const succeeded = [];
        const affectedBoards = [];
        const starred = path.endsWith('/star');

        for (const name of names) {
          const video = state.videos.get(name);

          if (!video || video.owner_user_id !== MOCK_USER_ID) {
            continue;
          }
          video.starred = starred;
          succeeded.push(name);
          affectedBoards.push(video.board_id ?? 'none');
        }

        return json(200, {
          affected_boards: [...new Set(affectedBoards)],
          failed_videos: [],
          [starred ? 'starred_videos' : 'unstarred_videos']: succeeded,
        });
      }

      if (method === 'POST' && path === '/api/v1/videos/delete') {
        const body = await readJsonBody(request);
        const names = Array.isArray(body.video_names) ? [...new Set(body.video_names)] : [];
        const deletedVideos = [];
        const affectedBoards = [];

        for (const name of names) {
          const video = state.videos.get(name);

          if (!video || video.owner_user_id !== MOCK_USER_ID) {
            continue;
          }
          state.videos.delete(name);
          deletedVideos.push(name);
          affectedBoards.push(video.board_id ?? 'none');
        }

        return json(200, {
          affected_boards: [...new Set(affectedBoards)],
          deleted_videos: deletedVideos,
          failed_videos: [],
        });
      }

      if (path === '/api/v1/videos/board' && (method === 'POST' || method === 'DELETE')) {
        const body = await readJsonBody(request);
        const video = state.videos.get(body.video_name);

        if (!video || video.owner_user_id !== MOCK_USER_ID) {
          return json(404, { detail: 'Video not found' });
        }

        const oldBoardId = video.board_id ?? 'none';

        if (method === 'POST') {
          if (!body.board_id || !state.boards.has(body.board_id)) {
            return json(404, { detail: 'Board not found' });
          }
          const attachRefusal = boardRefusal(state, faults, state.boards.get(body.board_id), 'add_media');
          if (attachRefusal) {
            return json(...attachRefusal);
          }
          video.board_id = body.board_id;
          return json(200, {
            added_videos: [video.video_name],
            affected_boards: [...new Set([oldBoardId, body.board_id])],
          });
        }

        video.board_id = null;
        return json(200, {
          affected_boards: [...new Set([oldBoardId, 'none'])],
          removed_videos: [video.video_name],
        });
      }

      const videoMetadataMatch = /^\/api\/v1\/videos\/i\/([^/]+)\/metadata$/.exec(path);
      if (method === 'GET' && videoMetadataMatch) {
        const video = state.videos.get(decodeURIComponent(videoMetadataMatch[1]));

        return video && video.owner_user_id === MOCK_USER_ID
          ? json(200, video.metadata)
          : json(404, { detail: 'Video not found' });
      }

      const videoWorkflowMatch = /^\/api\/v1\/videos\/i\/([^/]+)\/workflow$/.exec(path);
      if (method === 'GET' && videoWorkflowMatch) {
        const video = state.videos.get(decodeURIComponent(videoWorkflowMatch[1]));

        return video && video.owner_user_id === MOCK_USER_ID
          ? json(200, { graph: video.graph, workflow: video.workflow })
          : json(404, { detail: 'Video not found' });
      }

      const videoThumbnailMatch = /^\/api\/v1\/videos\/i\/([^/]+)\/thumbnail$/.exec(path);
      if (method === 'GET' && videoThumbnailMatch) {
        const video = state.videos.get(decodeURIComponent(videoThumbnailMatch[1]));

        return video && video.owner_user_id === MOCK_USER_ID
          ? writeBinary(response, 200, FIXTURE_VIDEO_POSTER, { 'content-type': 'image/webp' })
          : json(404, { detail: 'Video not found' });
      }

      const videoFullMatch = /^\/api\/v1\/videos\/i\/([^/]+)\/full$/.exec(path);
      if ((method === 'GET' || method === 'HEAD') && videoFullMatch) {
        const video = state.videos.get(decodeURIComponent(videoFullMatch[1]));

        if (!video || video.owner_user_id !== MOCK_USER_ID) {
          return json(404, { detail: 'Video not found' });
        }

        const commonHeaders = {
          'accept-ranges': 'bytes',
          'content-type': 'video/mp4',
        };

        if (method === 'HEAD') {
          response.writeHead(200, { ...commonHeaders, 'content-length': FIXTURE_VIDEO.length });
          return response.end();
        }

        const rangeHeader = request.headers.range;

        if (!rangeHeader) {
          return writeBinary(response, 200, FIXTURE_VIDEO, commonHeaders);
        }

        const range = parseByteRange(rangeHeader, FIXTURE_VIDEO.length);

        if (!range) {
          response.writeHead(416, {
            ...commonHeaders,
            'content-length': 0,
            'content-range': `bytes */${String(FIXTURE_VIDEO.length)}`,
          });
          return response.end();
        }

        const [start, end] = range;
        const body = FIXTURE_VIDEO.subarray(start, end + 1);

        return writeBinary(response, 206, body, {
          ...commonHeaders,
          'content-range': `bytes ${String(start)}-${String(end)}/${String(FIXTURE_VIDEO.length)}`,
        });
      }

      const videoMatch = /^\/api\/v1\/videos\/i\/([^/]+)$/.exec(path);
      if (method === 'GET' && videoMatch) {
        const video = state.videos.get(decodeURIComponent(videoMatch[1]));

        return video && video.owner_user_id === MOCK_USER_ID
          ? json(200, toVideoDto(video))
          : json(404, { detail: 'Video not found' });
      }

      if (method === 'POST' && path === '/__workflow-library') {
        const { scenario = 'large' } = await readJsonBody(request);
        if (!['large', 'empty', 'failed-page', 'slow-detail', 'changed-revision'].includes(scenario)) {
          return json(400, { detail: 'Unknown workflow library scenario' });
        }
        const workflows = scenario === 'empty' ? [] : createLargeWorkflowLibraryFixture();
        state.workflows = new Map(workflows.map((workflow) => [workflow.workflow_id, workflow]));
        state.libraryScenario = scenario;
        state.hasLibraryPageFailed = false;
        state.workflowRequests = [];
        return json(200, { count: workflows.length, nodesPerDocument: 40, scenario });
      }

      if (path.startsWith('/api/v1/workflows')) {
        state.workflowRequests.push({ method, path });
      }

      if (method === 'GET' && path === '/__workflow-requests') {
        return json(200, { requests: state.workflowRequests });
      }

      const workflowRecord = (workflow) => {
        const thumbnail = state.workflowThumbnails.get(workflow.workflow_id);

        return {
          ...workflow,
          thumbnail_url: thumbnail
            ? `/api/v1/workflows/i/${encodeURIComponent(workflow.workflow_id)}/thumbnail?v=${String(thumbnail.version)}`
            : (workflow.thumbnail_url ?? null),
        };
      };
      const workflowListItem = ({ workflow: _workflow, ...item }) => workflowRecord(item);
      const hasBeenOpened = url.searchParams.get('has_been_opened');
      const matchesOpened = (workflow) =>
        hasBeenOpened === null || (hasBeenOpened === 'true') === Boolean(workflow.opened_at);
      const workflowTags = (workflow) =>
        String(workflow.tags ?? '')
          .split(',')
          .map((tag) => tag.trim())
          .filter(Boolean);
      const workflowTagsForVisibility = (value, isPublic) => {
        const tags = String(value ?? '')
          .split(',')
          .map((tag) => tag.trim())
          .filter((tag) => tag && tag !== 'shared');

        if (isPublic) {
          tags.push('shared');
        }

        return tags.join(',');
      };

      if (path === '/api/v1/workflows/tags') {
        const categories = url.searchParams.getAll('categories');
        const tags = new Set();

        for (const workflow of state.workflows.values()) {
          if (categories.length === 0 || categories.includes(workflow.category)) {
            workflowTags(workflow).forEach((tag) => tags.add(tag));
          }
        }

        return json(200, [...tags].sort());
      }

      if (path === '/api/v1/workflows/counts_by_tag') {
        const categories = url.searchParams.getAll('categories');
        const counts = {};

        for (const tag of url.searchParams.getAll('tags')) {
          counts[tag] = [...state.workflows.values()].filter(
            (workflow) =>
              (categories.length === 0 || categories.includes(workflow.category)) &&
              matchesOpened(workflow) &&
              workflowTags(workflow).includes(tag)
          ).length;
        }

        return json(200, counts);
      }

      const visibilityMatch = /^\/api\/v1\/workflows\/i\/([^/]+)\/is_public$/.exec(path);
      if (visibilityMatch) {
        if (method !== 'PATCH') {
          return json(405, { detail: `No mock for ${method} ${path}` });
        }

        const workflowId = decodeURIComponent(visibilityMatch[1]);
        const workflow = state.workflows.get(workflowId);

        if (!workflow) {
          return json(404, { detail: 'Workflow not found' });
        }
        if (workflow.category === 'default') {
          return json(403, { detail: 'Bundled workflows cannot be modified' });
        }

        const body = await readJsonBody(request);
        if (typeof body.is_public !== 'boolean') {
          return json(422, { detail: 'is_public must be a boolean' });
        }

        workflow.is_public = body.is_public;
        workflow.tags = workflowTagsForVisibility(workflow.tags, body.is_public);
        workflow.workflow = {
          ...workflow.workflow,
          tags: workflowTagsForVisibility(workflow.workflow?.tags, body.is_public),
        };

        return json(200, workflowRecord(workflow));
      }

      const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(\/opened_at|\/last_run_at|\/thumbnail)?$/.exec(path);
      if (workflowMatch) {
        const workflowId = decodeURIComponent(workflowMatch[1]);
        const suffix = workflowMatch[2] ?? '';
        const workflow = state.workflows.get(workflowId);

        if (!workflow) {
          return json(404, { detail: 'Workflow not found' });
        }

        if ((suffix === '/opened_at' || suffix === '/last_run_at') && method === 'PUT') {
          workflow[suffix.slice(1)] = timestamp(state);
          return json(200, null);
        }

        if (suffix === '/thumbnail') {
          const thumbnail = state.workflowThumbnails.get(workflowId);

          if (method === 'GET') {
            return thumbnail
              ? writeBinary(response, 200, thumbnail.data, { 'content-type': thumbnail.contentType })
              : json(404, { detail: 'Workflow thumbnail not found' });
          }
          if (workflow.category === 'default') {
            return json(403, { detail: 'Bundled workflows cannot be modified' });
          }
          if (method === 'PUT') {
            const file = await readMultipartFile(request, 'image');

            if (!file?.contentType.startsWith('image') || file.data.length === 0) {
              return json(415, { detail: 'Not an image' });
            }

            state.workflowThumbnails.set(workflowId, {
              contentType: file.contentType,
              data: file.data,
              version: state.nextWorkflowThumbnailVersion++,
            });
            return json(200, null);
          }
          if (method === 'DELETE') {
            // Fixture workflows can carry a seeded thumbnail URL without stored bytes; removing clears either.
            const removedUpload = state.workflowThumbnails.delete(workflowId);
            const removedFixture = Boolean(workflow.thumbnail_url);

            workflow.thumbnail_url = null;
            return removedUpload || removedFixture
              ? json(200, null)
              : json(404, { detail: 'Workflow thumbnail not found' });
          }

          return json(405, { detail: `No mock for ${method} ${path}` });
        }

        if (method === 'GET') {
          if (state.libraryScenario === 'slow-detail') {
            await new Promise((resolve) => {
              setTimeout(resolve, 300);
            });
          }
          if (state.libraryScenario === 'changed-revision' && workflow.revision === 1) {
            workflow.revision = 2;
          }
          return json(200, workflowRecord(workflow));
        }

        if (method === 'DELETE') {
          if (workflow.category === 'default') {
            return json(403, { detail: 'Bundled workflows cannot be deleted' });
          }
          state.workflows.delete(workflowId);
          state.workflowThumbnails.delete(workflowId);
          return json(200, null);
        }

        if (method === 'PATCH') {
          const body = await readJsonBody(request);
          const submitted = body.workflow ?? {};

          if (submitted.id !== workflowId) {
            return json(400, { detail: 'The workflow id in the body does not match the URL' });
          }
          if (workflow.category === 'default') {
            return json(403, { detail: 'Bundled workflows cannot be modified' });
          }
          if (body.expected_revision !== undefined && body.expected_revision !== workflow.revision) {
            return json(409, {
              detail: {
                current_revision: workflow.revision,
                expected_revision: body.expected_revision,
                message: `Workflow ${workflowId} is at revision ${String(workflow.revision)}`,
                reason: 'revision-conflict',
              },
            });
          }

          const { id: _id, ...content } = submitted;

          workflow.workflow = { ...content, meta: { ...content.meta, category: 'user' } };
          workflow.name = content.name ?? workflow.name;
          workflow.description = content.description ?? workflow.description;
          workflow.tags = content.tags ?? workflow.tags;
          workflow.revision += 1;
          workflow.updated_at = timestamp(state);

          return json(200, workflowRecord(workflow));
        }
      }

      if (method === 'POST' && (path === '/api/v1/workflows' || path === '/api/v1/workflows/')) {
        const body = await readJsonBody(request);
        const { id: _id, ...content } = body.workflow ?? {};
        const reservedId = typeof body.workflow_id === 'string' ? body.workflow_id : null;

        if (reservedId !== null && !/^[0-9a-f-]{36}$/i.test(reservedId)) {
          return json(400, { detail: 'A reserved workflow id must be a UUID' });
        }

        const existing = reservedId === null ? null : state.workflows.get(reservedId);

        if (existing) {
          // A retried creation is accepted only for the same content; anything else under the id is a conflict.
          return JSON.stringify(existing.workflow) ===
            JSON.stringify({ ...content, meta: { ...content.meta, category: 'user' } })
            ? json(200, workflowRecord(existing))
            : json(409, { detail: { message: 'The workflow id is already in use', reason: 'id-conflict' } });
        }

        const workflowId = reservedId ?? `mock-workflow-${String(state.nextWorkflowNumber++).padStart(4, '0')}`;
        const created = {
          category: 'user',
          created_at: timestamp(state),
          description: content.description ?? '',
          is_public: !isMultiuserCaller(faults),
          name: content.name ?? '',
          last_run_at: null,
          opened_at: null,
          revision: 1,
          tags: content.tags ?? '',
          thumbnail_url: null,
          updated_at: null,
          user_id: MOCK_USER_ID,
          workflow: { ...content, meta: { ...content.meta, category: 'user' } },
          workflow_id: workflowId,
        };

        created.updated_at = created.created_at;
        state.workflows.set(workflowId, created);

        return json(200, workflowRecord(created));
      }

      if (method === 'GET' && (path === '/api/v1/workflows' || path === '/api/v1/workflows/')) {
        const categories = url.searchParams.getAll('categories');
        const query = url.searchParams.get('query')?.trim().toLocaleLowerCase() ?? '';
        const tags = url.searchParams.getAll('tags');
        const isPublic = url.searchParams.get('is_public');
        const page = Math.max(0, Number(url.searchParams.get('page') ?? 0) || 0);
        const perPage = Math.max(1, Number(url.searchParams.get('per_page') ?? 20) || 20);
        if (state.libraryScenario === 'failed-page' && page === 2 && !state.hasLibraryPageFailed) {
          state.hasLibraryPageFailed = true;
          return json(503, { detail: 'Synthetic page failure; retry succeeds' });
        }
        const orderBy = url.searchParams.get('order_by') ?? 'updated_at';
        const sign = url.searchParams.get('direction') === 'ASC' ? 1 : -1;
        // As the server: NOCASE names, NULLs last in both directions, the id breaking ties.
        const sortKey = (workflow) =>
          orderBy === 'name'
            ? workflow.name.replace(/[A-Z]/g, (letter) => letter.toLowerCase())
            : (workflow[orderBy] ?? null);
        const compare = (left, right) => (left === right ? 0 : left < right ? -1 : 1);
        const compareKeys = (left, right) =>
          left === right ? 0 : left === null ? 1 : right === null ? -1 : sign * compare(left, right);
        const items = [...state.workflows.values()]
          .filter(
            (workflow) =>
              (categories.length === 0 || categories.includes(workflow.category)) &&
              (!query || `${workflow.name} ${workflow.description}`.toLocaleLowerCase().includes(query)) &&
              (tags.length === 0 || tags.some((tag) => workflowTags(workflow).includes(tag))) &&
              (isPublic === null || String(workflow.is_public) === isPublic) &&
              matchesOpened(workflow)
          )
          .sort(
            (left, right) =>
              compareKeys(sortKey(left), sortKey(right)) || sign * compare(left.workflow_id, right.workflow_id)
          );
        const pages = Math.max(1, Math.ceil(items.length / perPage));
        const pageItems = items.slice(page * perPage, (page + 1) * perPage).map(workflowListItem);

        return json(200, { items: pageItems, page, pages, total: items.length });
      }

      return json(404, { detail: `No mock for ${method} ${path}` });
    } catch (error) {
      return json(500, { detail: error instanceof Error ? error.message : String(error) });
    }
  });

  await new Promise((resolve, reject) => {
    server.once('error', reject);
    server.listen(port, '127.0.0.1', resolve);
  });

  const address = server.address();
  const actualPort = typeof address === 'object' && address ? address.port : port;

  return {
    close: () =>
      new Promise((resolve) => {
        server.close(resolve);
        server.closeAllConnections?.();
      }),
    counts: () => getStateCounts(state),
    origin: `http://127.0.0.1:${String(actualPort)}`,
    port: actualPort,
    profile: () => state.profile,
  };
};

export { getMockBackendFixtureCounts };