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.

36.3 KB
Raw Blame
/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop */
import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey } from '@features/gallery';
import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
import type { ModelsSnapshot } from '@features/models/data/modelsStore';

/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import { ChakraProvider } from '@chakra-ui/react';
import { galleryKeys } from '@features/gallery/queries';
import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';
import { captureAccountScope } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { act, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';

import type * as ModelOnlyUpscaleModule from './modelOnlyUpscale';
import type { ImageActions } from './useImageActions';

import { ImageContextMenu, type ImageContextMenuTarget, type ImageContextMenuVariant } from './ImageContextMenu';
import { EMPTY_IMAGE_RECALL_CAPABILITIES } from './imageRecall';

const NO_BOARDS: [] = [];
const LOAD_WORKFLOW = 'widgets.gallery.itemActions.loadWorkflow.label';
const GENERATE_PBR_MAPS = 'widgets.gallery.itemActions.pbrMaps.label';

const findGalleryItem = vi.fn();

vi.mock('@workbench/image-actions/useFindGalleryItem', () => ({ useFindGalleryItem: () => findGalleryItem }));
vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));
vi.mock('@workbench/projects/library', () => ({
  useProjectLibrarySelector: (selector: (snapshot: { summaries: [] }) => unknown) => selector({ summaries: [] }),
}));
const commandsMock = vi.hoisted(() => ({
  gallery: { setCompareItem: vi.fn() },
  generation: { setSource: vi.fn(), submitModelOnlyUpscale: vi.fn() },
  notifications: { add: vi.fn() },
  widgets: { patchValues: vi.fn() },
}));
const galleryMock = vi.hoisted(() => ({
  metadata: vi.fn((): Promise<Record<string, unknown> | null> => Promise.resolve(null)),
  resolve: vi.fn((imageName: string) => Promise.resolve({ hasWorkflow: imageName === 'made-by-workflow.png' })),
  resolveItem: vi.fn((ref: { kind: string; name: string }, _signal?: AbortSignal) =>
    Promise.resolve({ hasWorkflow: ref.name === 'made-by-workflow.mp4', kind: ref.kind })
  ),
  videoMetadata: vi.fn((_videoName: string, _signal?: AbortSignal): Promise<Record<string, unknown> | null> =>
    Promise.resolve(null)
  ),
}));
// The transport, under both the gallery's shared metadata queries and its public media ports.
vi.mock('@features/gallery/data/backend', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  getGalleryImageByName: galleryMock.resolve,
  getGalleryImageMetadata: galleryMock.metadata,
  getGalleryItemByRef: galleryMock.resolveItem,
  getGalleryVideoMetadata: galleryMock.videoMetadata,
}));
// The Upscale submenu asks for the model library on mount; tests seed the snapshot instead of fetching it.
const ensureModelsLoaded = vi.hoisted(() => vi.fn(() => Promise.resolve()));
vi.mock('@features/models', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  ensureModelsLoaded,
}));
vi.mock('@features/gallery/queries', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  ensureGalleryBoardDestinations: () => null,
}));
// The upscale command's chunk loads on pick; `fail` stands in for that load failing.
const modelOnlyLoad = vi.hoisted(() => ({ fail: false }));
vi.mock('./modelOnlyUpscale', async (importOriginal) => {
  const original = await importOriginal<typeof ModelOnlyUpscaleModule>();

  return {
    ...original,
    queueModelOnlyUpscale: (...args: Parameters<typeof original.queueModelOnlyUpscale>) =>
      modelOnlyLoad.fail
        ? Promise.reject(new Error('Failed to fetch dynamically imported module'))
        : original.queueModelOnlyUpscale(...args),
  };
});
// The open project's Gallery values, which the compare entry reads its state from.
const galleryValuesMock = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));
vi.mock('@workbench/WorkbenchContext', () => ({
  useActiveProjectId: () => 'project-1',
  useActiveProjectName: () => 'Project',
  useWidgetValuesSelector: (_widgetId: string, selector: (values: Record<string, unknown>) => unknown) =>
    selector(galleryValuesMock.current),
  useWorkbenchCommands: () => commandsMock,
}));
// Keys stand in for copy; the one interpolated value a test reads, an upscale factor, is shown as the locale does.
vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, options?: { key?: string; scale?: number }) =>
      // The hint renders beside its label as written, short; a key there would widen the menu past the viewport.
      key === 'widgets.gallery.itemMenu.compareShortcut'
        ? `${String(options?.key)}+click`
        : options?.scale === undefined
          ? key
          : `${options.scale}×${key.endsWith('.factorNative') ? ' (native)' : ''}`,
  }),
}));

const image = (imageName: string): GalleryImage => ({
  boardId: 'none',
  height: 512,
  imageCategory: 'general',
  imageName,
  imageUrl: `/${imageName}`,
  queuedAt: '2026-06-15T00:00:00Z',
  sourceQueueItemId: 'queue-item',
  starred: false,
  thumbnailUrl: `/thumb-${imageName}`,
  width: 512,
});

const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions => ({
  canUseAsConditioningClip: { audio: false, video: false },
  canUseAsReferenceImage: false,
  canUseAsReferenceVideo: false,
  copyImage: vi.fn(() => Promise.resolve()),
  createCanvasFromImages: vi.fn(() => Promise.resolve()),
  deleteItems,
  deleteImages: vi.fn(() => Promise.resolve()),
  deriveImageRecallCapabilities: vi.fn(() => EMPTY_IMAGE_RECALL_CAPABILITIES),
  downloadItem: vi.fn(() => Promise.resolve()),
  downloadItems: vi.fn(() => Promise.resolve()),
  downloadImage: vi.fn(() => Promise.resolve()),
  downloadImages: vi.fn(() => Promise.resolve()),
  generatePbrMaps: vi.fn(() => Promise.resolve()),
  loadImageWorkflow: vi.fn(() => Promise.resolve()),
  moveItemsToBoard: vi.fn(() => Promise.resolve()),
  moveImagesToBoard: vi.fn(() => Promise.resolve()),
  openItemInNewTab: vi.fn(),
  openItemInPreview: vi.fn(),
  openImageInPreview: vi.fn(),
  recallImageData: vi.fn(() => Promise.resolve()),
  loadVideoWorkflow: vi.fn(() => Promise.resolve()),
  recallVideoData: vi.fn(() => Promise.resolve()),
  selectForCompare: vi.fn(),
  sendToCanvas: vi.fn(() => Promise.resolve()),
  sendImageAsControl: vi.fn(() => Promise.resolve()),
  setItemsStarred: vi.fn(() => Promise.resolve()),
  setImagesStarred: vi.fn(() => Promise.resolve()),
  savePromptAsTemplate: vi.fn(),
  sendToInitialVideo: vi.fn(),
  useAsReferenceImage: vi.fn(),
  useAsConditioningClip: vi.fn(),
  useAsReferenceVideo: vi.fn(),
});

let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

const interact = (action: () => void): Promise<void> =>
  act(async () => {
    action();
    await new Promise<void>((resolve) => {
      globalThis.setTimeout(resolve, 50);
    });
  });

/** Polls inside `act` until the condition holds, so a wait tracks state rather than a fixed delay. */
const settleUntil = async (isSettled: () => boolean, description: string, timeoutMs = 2000): Promise<void> => {
  const deadline = Date.now() + timeoutMs;

  while (!isSettled()) {
    if (Date.now() > deadline) {
      throw new Error(`Timed out after ${String(timeoutMs)}ms waiting for ${description}`);
    }
    await act(async () => {
      await new Promise<void>((resolve) => {
        globalThis.setTimeout(resolve, 10);
      });
    });
  }
};

/**
 * Hovers an item the way zag recognises. zag only treats a move as a real hover when the pointer position changes, so
 * approach the item's center from one pixel away instead of dispatching a static point, which reads as no move at all
 * whenever zag's last recorded position is already there.
 */
const hoverItem = async (target: HTMLElement): Promise<void> => {
  const rect = target.getBoundingClientRect();
  const clientX = rect.left + rect.width / 2;
  const clientY = rect.top + rect.height / 2;
  await interact(() => {
    for (const x of [clientX - 1, clientX]) {
      target.dispatchEvent(
        new PointerEvent('pointermove', { bubbles: true, clientX: x, clientY, pointerType: 'mouse' })
      );
    }
  });
};

/** Quick icon items select through zag, which needs the item highlighted by a hover before the click. */
const pickQuickItem = async (label: string): Promise<void> => {
  const target = document.querySelector<HTMLElement>(`[aria-label="${label}"]`);
  expect(target).not.toBeNull();
  await hoverItem(target!);
  // Wait for Zag's asynchronous highlight before clicking; unhighlighted items ignore clicks.
  await settleUntil(() => target!.hasAttribute('data-highlighted'), `"${label}" to be highlighted`);
  await interact(() => target!.click());
};

/** An item's label: its first line, so a hint under it does not count. */
const itemLabel = (candidate: HTMLElement): string | undefined =>
  (candidate.querySelector('p') ?? candidate).textContent?.trim() || undefined;

const getMenuItem = (label: string): HTMLElement => {
  const item = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find(
    (candidate) => itemLabel(candidate) === label || candidate.textContent?.trim() === label
  );

  if (!item) {
    throw new Error(`Could not find menu item: ${label}`);
  }

  return item;
};

/** Items that select through zag (`onSelect`) need the item highlighted by a hover before the click. */
const pickItem = async (label: string): Promise<void> => {
  const target = getMenuItem(label);
  await hoverItem(target);
  await settleUntil(() => target.hasAttribute('data-highlighted'), `"${label}" to be highlighted`);
  await interact(() => target.click());
};

const getOpenAlertDialog = (): HTMLElement | null =>
  document.querySelector<HTMLElement>('[role="alertdialog"][data-state="open"]');

const Harness = ({ actions, images }: { actions: ImageActions; images: GalleryImage[] }) => {
  const [target, setTarget] = useState<ImageContextMenuTarget | null>({ images, x: 20, y: 20 });

  return <ImageContextMenu actions={actions} boards={NO_BOARDS} target={target} onClose={() => setTarget(null)} />;
};

const renderMenu = async (actions: ImageActions, images: GalleryImage[]) => {
  host = document.createElement('div');
  document.body.append(host);
  root = createRoot(host);

  await interact(() => {
    root?.render(
      <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
        <ChakraProvider value={system}>
          <Harness actions={actions} images={images} />
        </ChakraProvider>
      </QueryClientProvider>
    );
  });
};

const item = (kind: GalleryItem['kind'], name: string): GalleryItem => {
  const base = {
    boardId: 'none',
    category: 'general' as const,
    createdAt: '2026-06-15T00:00:00Z',
    fullUrl: `/full/${name}`,
    height: 512,
    isIntermediate: false,
    name,
    starred: false,
    thumbnailUrl: `/thumb-${name}`,
    width: 512,
  };

  return kind === 'video' ? { ...base, durationSeconds: 12, kind } : { ...base, kind };
};

const renderItemMenu = async (
  actions: ImageActions,
  target: GalleryItemContextMenuTarget,
  previewVideoActions?: {
    isCopyCurrentFrameAvailable: boolean;
    itemKey: GalleryItemKey;
    onCopyCurrentFrame: () => void;
    onOpenDetails: () => void;
  },
  queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }),
  variant?: ImageContextMenuVariant
) => {
  host = document.createElement('div');
  document.body.append(host);
  root = createRoot(host);

  await interact(() => {
    root?.render(
      <QueryClientProvider client={queryClient}>
        <ChakraProvider value={system}>
          <ImageContextMenu
            actions={actions}
            boards={NO_BOARDS}
            previewVideoActions={previewVideoActions}
            target={target as unknown as ImageContextMenuTarget}
            variant={variant}
            onClose={vi.fn()}
          />
        </ChakraProvider>
      </QueryClientProvider>
    );
  });
};

afterEach(async () => {
  await interact(() => root?.unmount());
  host?.remove();
  host = null;
  root = null;
  galleryValuesMock.current = {};
});

describe('ImageContextMenu deletion delegation', () => {
  it('delegates deletion to the shared image actions adapter', async () => {
    const deleteItems = vi.fn(() => Promise.resolve());
    await renderMenu(createActions(deleteItems), [image('single.png')]);

    await interact(() => getMenuItem('widgets.gallery.itemMenu.deleteImage').click());

    expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: 'single.png' }], {
      returnFocus: undefined,
    });
    expect(getOpenAlertDialog()).toBeNull();
  });
});

describe('ImageContextMenu find in gallery', () => {
  it('reveals a single image or video by its gallery reference', async () => {
    findGalleryItem.mockClear();
    await renderMenu(createActions(vi.fn()), [image('still.png')]);
    await interact(() => getMenuItem('widgets.gallery.findInGallery').click());
    expect(findGalleryItem).toHaveBeenCalledExactlyOnceWith({ kind: 'image', name: 'still.png' });

    await interact(() => root?.unmount());
    const video = item('video', 'clip.mp4');
    await renderItemMenu(createActions(vi.fn()), {
      itemRefs: [{ kind: 'video', name: video.name }],
      items: [video],
      x: 20,
      y: 20,
    });
    await interact(() => getMenuItem('widgets.gallery.findInGallery').click());
    expect(findGalleryItem).toHaveBeenLastCalledWith({ kind: 'video', name: 'clip.mp4' });
  });
});

describe('ImageContextMenu load workflow', () => {
  it('enables Load Workflow once the image is known to embed one and hands the image to the action', async () => {
    const actions = createActions(vi.fn());
    actions.deriveImageRecallCapabilities = vi.fn((recallImage: GalleryImage) => ({
      ...EMPTY_IMAGE_RECALL_CAPABILITIES,
      workflow: recallImage.hasWorkflow === true,
    }));
    await renderMenu(actions, [image('made-by-workflow.png')]);

    await vi.waitFor(() => expect(getMenuItem(LOAD_WORKFLOW).getAttribute('aria-disabled')).not.toBe('true'));
    await interact(() => getMenuItem(LOAD_WORKFLOW).click());

    expect(actions.loadImageWorkflow).toHaveBeenCalledExactlyOnceWith(
      expect.objectContaining({ imageName: 'made-by-workflow.png' })
    );
  });
});

describe('ImageContextMenu PBR maps', () => {
  it('hands a single image to the PBR maps action', async () => {
    const actions = createActions(vi.fn());
    await renderMenu(actions, [image('texture.png')]);

    await interact(() => getMenuItem(GENERATE_PBR_MAPS).click());

    expect(actions.generatePbrMaps).toHaveBeenCalledExactlyOnceWith(
      expect.objectContaining({ imageName: 'texture.png' })
    );
  });
});

describe('ImageContextMenu canvas destinations', () => {
  const menuItemLabels = () =>
    Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).map(
      (candidate) => itemLabel(candidate) || candidate.getAttribute('aria-label')
    );

  /** Top-level menu entries in order, with separators as `—`, so a position within its group is observable. */
  const menuSequence = () =>
    Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"], [role="separator"]')).map((candidate) =>
      candidate.getAttribute('role') === 'separator'
        ? '—'
        : itemLabel(candidate) || candidate.getAttribute('aria-label')
    );
  const ADD = 'widgets.gallery.itemMenu.addToCanvasAs';
  const NEW_PROJECT = 'widgets.canvas.import.newProjectFromImage';

  it('selects another image for compare while one waits, comparing the two', async () => {
    const waiting = image('waiting.png');
    galleryValuesMock.current = {
      compareImage: waiting,
      selectedImage: waiting,
      selectedImageName: 'image:waiting.png',
    };
    const actions = createActions(vi.fn());
    const other = image('other.png');
    await renderMenu(actions, [other]);

    await pickItem('widgets.preview.selectForCompare');

    expect(actions.selectForCompare).toHaveBeenCalledExactlyOnceWith(
      expect.objectContaining({ imageName: 'other.png' })
    );
  });

  it('edits the image on the current canvas as a raster layer in one step', async () => {
    const actions = createActions(vi.fn());
    await renderMenu(actions, [image('image-0.png')]);

    await pickItem('widgets.preview.editOnCanvas');

    expect(
      vi.mocked(actions.sendToCanvas).mock.calls.map(([images, destination]) => [images.length, destination])
    ).toEqual([[1, 'raster']]);
  });

  it('reuses the settings from a submenu, Remix first, each gated by what the image records', async () => {
    const actions = createActions(vi.fn());
    actions.deriveImageRecallCapabilities = vi.fn(() => ({
      ...EMPTY_IMAGE_RECALL_CAPABILITIES,
      remix: true,
      seed: true,
    }));
    await renderMenu(actions, [image('image-0.png')]);
    await hoverItem(getMenuItem('widgets.gallery.itemMenu.reuseFromImage'));
    await settleUntil(
      () => menuItemLabels().includes('widgets.gallery.itemMenu.allSettings'),
      'the reuse submenu to open',
      5000
    );
    const submenu = getMenuItem('widgets.gallery.itemMenu.allSettings').closest('[role="menu"]')!;
    await vi.waitFor(() =>
      expect(
        Array.from(submenu.querySelectorAll<HTMLElement>('[role="menuitem"]')).map(
          (entry) => `${itemLabel(entry)}${entry.getAttribute('aria-disabled') === 'true' ? ' (disabled)' : ''}`
        )
      ).toEqual([
        'widgets.gallery.itemActions.recall.verbs.remix',
        'widgets.gallery.itemMenu.allSettings (disabled)',
        'widgets.gallery.itemActions.recall.verbs.prompts (disabled)',
        'widgets.gallery.itemActions.recall.verbs.seed',
        'widgets.gallery.itemActions.recall.verbs.dimensions (disabled)',
        'widgets.gallery.itemActions.recall.verbs.clipSkip (disabled)',
      ])
    );

    await pickItem('widgets.gallery.itemActions.recall.verbs.seed');
    expect(vi.mocked(actions.recallImageData).mock.calls.map(([entry, kind]) => [entry.imageName, kind])).toEqual([
      ['image-0.png', 'seed'],
    ]);
  });

  it('opens the multi-image menu, below its header, with the two canvas destinations in a group of their own', async () => {
    await renderMenu(
      createActions(vi.fn()),
      Array.from({ length: 3 }, (_, index) => image(`image-${index}.png`))
    );

    // The single-image hand-offs (Edit on Canvas, Use as Control, PBR maps, Find in Gallery) take one image; the canvas
    // items take the whole selection.
    expect(menuSequence()).toEqual([
      '—',
      ADD,
      NEW_PROJECT,
      '—',
      'widgets.gallery.starSelection',
      'widgets.gallery.downloadSelection',
      'widgets.gallery.changeBoard',
      '—',
      'widgets.gallery.deleteSelection',
    ]);
  });

  it.each([1, 3])('adds the %s targeted image(s) to the current canvas as the chosen layer', async (count) => {
    const actions = createActions(vi.fn());
    const images = Array.from({ length: count }, (_, index) => image(`image-${index}.png`));
    await renderMenu(actions, images);

    // A nested menu opens on a real hover of its trigger after zag's open delay: the open is awaited, not slept.
    await hoverItem(getMenuItem('widgets.gallery.itemMenu.addToCanvasAs'));
    await settleUntil(
      () => menuItemLabels().includes('widgets.canvas.import.inpaintMask'),
      'the add-to-current-canvas submenu to open',
      5000
    );
    // Raster leads, as the drop zones order them; each destination shows its layer kind's glyph, and resized control a
    // resize glyph so it reads apart from control.
    const destinations = Array.from(
      getMenuItem('widgets.canvas.import.raster')
        .closest('[role="menu"]')!
        .querySelectorAll<HTMLElement>('[role="menuitem"]')
    ).map((item) => [
      item.textContent?.trim(),
      Array.from(item.querySelector('svg')?.classList ?? []).find((name) => name.startsWith('lucide-')),
    ]);
    expect(destinations).toEqual([
      ['widgets.canvas.import.raster', 'lucide-brush'],
      ['widgets.canvas.import.control', 'lucide-sliders-horizontal'],
      ['widgets.canvas.import.inpaintMask', 'lucide-square-dashed-bottom'],
      ['widgets.canvas.import.regionalGuidance', 'lucide-map-pin'],
      ['widgets.canvas.import.regionalReference', 'lucide-image-plus'],
      ['widgets.canvas.import.resizedControl', 'lucide-scaling'],
    ]);
    // Destinations select through zag, which needs the item highlighted by a hover before the click.
    const inpaintMask = getMenuItem('widgets.canvas.import.inpaintMask');
    await hoverItem(inpaintMask);
    await settleUntil(() => inpaintMask.hasAttribute('data-highlighted'), 'the inpaint mask destination highlight');
    await interact(() => inpaintMask.click());

    const calls = vi.mocked(actions.sendToCanvas).mock.calls;
    expect(calls).toHaveLength(1);
    expect(calls[0]?.[0].map((entry) => entry.imageName)).toEqual(images.map((entry) => entry.imageName));
    expect(calls[0]?.[1]).toBe('inpaint-mask');
    expect(actions.createCanvasFromImages).not.toHaveBeenCalled();
  });
});

describe('ImageContextMenu video placement', () => {
  const renderVideoMenu = (actions: ImageActions, video: GalleryItem) =>
    renderItemMenu(actions, { itemRefs: [{ kind: 'video', name: video.name }], items: [video], x: 20, y: 20 });

  it('hands the video to the Initial Video and reference actions', async () => {
    const video = item('video', 'clip.mp4');
    const actions = { ...createActions(vi.fn()), canUseAsReferenceVideo: true };
    await renderVideoMenu(actions, video);

    await pickItem('widgets.gallery.itemMenu.extendInVideo');
    expect(actions.sendToInitialVideo).toHaveBeenCalledExactlyOnceWith(video);

    await pickItem('widgets.gallery.itemMenu.useAsReferenceVideo');
    expect(actions.useAsReferenceVideo).toHaveBeenCalledExactlyOnceWith(video);
  });

  it('aborts the video reads when the menu closes before they answer', async () => {
    const pending = () => new Promise<never>(() => {});
    galleryMock.videoMetadata.mockImplementationOnce(pending);
    galleryMock.resolveItem.mockImplementationOnce(pending);
    await renderVideoMenu(createActions(vi.fn()), item('video', 'slow.mp4'));
    await vi.waitFor(() => expect(galleryMock.resolveItem).toHaveBeenCalled());

    await interact(() => root?.unmount());

    const signals = [galleryMock.videoMetadata.mock.lastCall?.[1], galleryMock.resolveItem.mock.lastCall?.[1]];
    expect(signals.map((signal) => signal?.aborted)).toEqual([true, true]);
  });

  const openReuseSubmenu = async (): Promise<void> => {
    await hoverItem(getMenuItem('widgets.gallery.itemMenu.reuseFromVideo'));
    await settleUntil(
      () =>
        Array.from(document.querySelectorAll('[role="menuitem"]')).some(
          (candidate) => candidate.textContent?.trim() === 'widgets.gallery.itemMenu.allSettings'
        ),
      'the reuse submenu to open',
      5000
    );
  };

  const isDisabled = (label: string) => getMenuItem(label).getAttribute('aria-disabled') === 'true';

  it("reads a video's metadata once across opens, and reads a failed one again on the next open", async () => {
    const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
    const open = (video: GalleryItem) =>
      renderItemMenu(
        createActions(vi.fn()),
        { itemRefs: [{ kind: 'video', name: video.name }], items: [video], x: 20, y: 20 },
        undefined,
        queryClient
      );
    const close = async () => {
      await interact(() => root?.unmount());
      host?.remove();
    };
    const recorded = { generation_mode: 'wan_t2v', positive_prompt: 'a fox', seed: 7 };

    galleryMock.videoMetadata.mockClear();
    galleryMock.videoMetadata.mockResolvedValueOnce(recorded);
    await open(item('video', 'twice.mp4'));
    await openReuseSubmenu();
    await vi.waitFor(() => expect(isDisabled('widgets.gallery.itemActions.recall.verbs.prompts')).toBe(false));
    await close();
    await open(item('video', 'twice.mp4'));
    await openReuseSubmenu();

    expect(isDisabled('widgets.gallery.itemActions.recall.verbs.prompts')).toBe(false);
    expect(galleryMock.videoMetadata).toHaveBeenCalledOnce();
    await close();

    galleryMock.videoMetadata.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(recorded);
    await open(item('video', 'flaky.mp4'));
    await openReuseSubmenu();
    await vi.waitFor(() => expect(galleryMock.videoMetadata).toHaveBeenCalledTimes(2));
    // A failed read offers no recall rather than an answer of "nothing recorded" that would stick.
    await vi.waitFor(() =>
      expect(queryClient.getQueryState(galleryKeys.videoMetadata(captureAccountScope(), 'flaky.mp4'))?.status).toBe(
        'error'
      )
    );
    expect(isDisabled('widgets.gallery.itemActions.recall.verbs.prompts')).toBe(true);
    await close();
    await open(item('video', 'flaky.mp4'));
    await openReuseSubmenu();

    await vi.waitFor(() => expect(isDisabled('widgets.gallery.itemActions.recall.verbs.prompts')).toBe(false));
    expect(galleryMock.videoMetadata).toHaveBeenCalledTimes(3);
  });

  const openConditioningSubmenu = async (): Promise<void> => {
    await hoverItem(getMenuItem('widgets.gallery.itemMenu.useAsConditioningClip'));
    await settleUntil(
      () =>
        Array.from(document.querySelectorAll('[role="menuitem"]')).some(
          (candidate) => candidate.textContent?.trim() === 'widgets.video.conditioningRoleAudio'
        ),
      'the conditioning clip submenu to open',
      5000
    );
  };

  it('hands the video to the conditioning clip action in the chosen role', async () => {
    const video = item('video', 'clip.mp4');
    const actions = { ...createActions(vi.fn()), canUseAsConditioningClip: { audio: true, video: true } };
    await renderVideoMenu(actions, video);
    await openConditioningSubmenu();

    await pickItem('widgets.video.conditioningRoleAudio');

    expect(actions.useAsConditioningClip).toHaveBeenCalledExactlyOnceWith(video, 'audio');
  });
});

describe('ImageContextMenu mixed-media action visibility', () => {
  it('shows common actions for a single video and hides every image-only action', async () => {
    const video = item('video', 'clip.mp4');
    await renderItemMenu(createActions(vi.fn()), {
      itemRefs: [{ kind: 'video', name: video.name }],
      items: [video],
      x: 20,
      y: 20,
    });

    expect(document.querySelector('[aria-label="widgets.gallery.itemMenu.openInNewTab"]')).not.toBeNull();
    expect(document.querySelector('[aria-label="widgets.gallery.itemMenu.downloadVideo"]')).not.toBeNull();
    expect(document.querySelector('[aria-label="widgets.gallery.itemMenu.openInPreview"]')).not.toBeNull();
    expect(document.querySelector('[aria-label="widgets.preview.starVideo"]')).not.toBeNull();
    expect(document.body.textContent).toContain('widgets.gallery.changeBoard');
    expect(document.body.textContent).toContain('widgets.gallery.itemMenu.deleteVideo');
    expect(document.body.textContent).not.toContain('widgets.gallery.itemMenu.copyToClipboard');
    expect(document.body.textContent).not.toContain('widgets.preview.copyCurrentFrame');
    // Videos carry their own Recall Metadata submenu (parameter recall).
    expect(document.body.textContent).toContain('widgets.gallery.itemMenu.reuseFromVideo');
    expect(document.body.textContent).not.toContain('widgets.gallery.itemActions.upscale.label');
    expect(document.body.textContent).not.toContain('widgets.preview.selectForCompare');
    expect(document.body.textContent).not.toContain('widgets.gallery.itemMenu.addToCanvasAs');
    expect(document.body.textContent).not.toContain('widgets.canvas.import.newProjectFromImage');
  });

  it('keeps complete mixed refs for common bulk actions and hides image-only bulk actions when a ref is unresolved', async () => {
    const loadedImage = item('image', 'still.png');
    const actions = createActions(vi.fn());
    const refs = [
      { kind: 'image' as const, name: loadedImage.name },
      { kind: 'video' as const, name: 'unloaded.mp4' },
    ];
    await renderItemMenu(actions, {
      itemRefs: refs,
      items: [loadedImage],
      x: 20,
      y: 20,
    });

    expect(document.body.textContent).toContain('widgets.gallery.itemMenu.itemsSelected');
    expect(document.body.textContent).toContain('widgets.gallery.starSelection');
    expect(document.body.textContent).toContain('widgets.gallery.downloadSelection');
    expect(document.body.textContent).toContain('widgets.gallery.changeBoard');
    expect(document.body.textContent).toContain('widgets.gallery.deleteSelection');
    expect(document.body.textContent).not.toContain('widgets.gallery.itemMenu.addToCanvasAs');
    expect(document.body.textContent).not.toContain('widgets.canvas.import.newProjectFromImage');
    await pickQuickItem('widgets.gallery.itemMenu.openInNewTab');
    await interact(() => root?.unmount());
    host?.remove();
    await renderItemMenu(actions, { itemRefs: refs, items: [loadedImage], x: 20, y: 20 });
    await pickQuickItem('widgets.gallery.itemMenu.openInPreview');
    expect(actions.openItemInNewTab).toHaveBeenCalledWith(loadedImage);
    expect(actions.openItemInPreview).toHaveBeenCalledWith(loadedImage);

    await interact(() => getMenuItem('widgets.gallery.starSelection').click());
    expect(actions.setItemsStarred).toHaveBeenCalledWith(refs, true);
  });
});

describe('ImageContextMenu change-board destinations', () => {
  const board = (id: string, access: NonNullable<GalleryBoard['access']>): GalleryBoard => ({
    access,
    archived: false,
    assetCount: 0,
    assetVideoCount: 0,
    id,
    imageCount: 1,
    isInbox: false,
    kind: 'board',
    name: id,
    ownerName: access.role === 'owner' ? 'Me' : 'Dee',
    projectId: null,
    videoCount: 0,
  });
  const renderWithBoards = async (boards: GalleryBoard[], listedValue = 'board-theirs', target = image('one.png')) => {
    host = document.createElement('div');
    document.body.append(host);
    root = createRoot(host);

    await interact(() => {
      root?.render(
        <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
          <ChakraProvider value={system}>
            <ImageContextMenu
              actions={createActions(vi.fn())}
              boards={boards}
              target={{ images: [target], x: 20, y: 20 }}
              onClose={vi.fn()}
            />
          </ChakraProvider>
        </QueryClientProvider>
      );
    });
    const trigger = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).find((candidate) =>
      candidate.textContent?.includes('widgets.gallery.changeBoard')
    );
    expect(trigger).not.toBeUndefined();
    await hoverItem(trigger!);
    await settleUntil(
      () => document.querySelector(`[data-value="${listedValue}"]`) !== null,
      'the change-board submenu to list its boards'
    );

    return Array.from(
      document
        .querySelector(`[data-value="${listedValue}"]`)!
        .closest('[role="menu"]')!
        .querySelectorAll<HTMLElement>('[data-scope="menu"][data-part="item-group-label"]')
    ).map((label) => label.textContent?.trim());
  };

  it("groups the boards as the host lists them: another user's board apart, the caller's own under Library", async () => {
    expect(
      await renderWithBoards([
        board('mine', {
          actions: ['read', 'add_media'],
          adminOverride: false,
          generalAccess: 'restricted',
          role: 'owner',
        }),
        // An admin's view of someone else's board; a host without board sharing folds it before handing it over.
        board('theirs', {
          actions: ['read', 'add_media'],
          adminOverride: true,
          generalAccess: 'restricted',
          role: null,
        }),
      ])
    ).toEqual(['widgets.gallery.boardGroups.library', 'widgets.gallery.boardGroups.otherUsers']);
    expect(document.querySelector('[data-value="board-mine"]')).not.toBeNull();
  });

  it("offers what the selection bar offers: no archived board, not the item's own, and Uncategorized as a move", async () => {
    const owned = {
      actions: ['read', 'add_media'],
      adminOverride: false,
      generalAccess: 'restricted',
      role: 'owner',
    } as const;
    await renderWithBoards(
      [board('here', owned), { ...board('old', owned), archived: true }, board('there', owned)],
      'board-there',
      { ...image('one.png'), boardId: 'here' }
    );

    expect(document.querySelector('[data-value="board-here"]')).toBeNull();
    expect(document.querySelector('[data-value="board-old"]')).toBeNull();
    expect(document.querySelector('[data-value="remove-from-board"]')).not.toBeNull();
  });
});

describe('ImageContextMenu Upscale submenu', () => {
  const upscaler = (key: string, name: string, scale: number | null) => ({
    base: 'any' as const,
    file_size: 1,
    format: 'checkpoint' as const,
    hash: `${key}-hash`,
    key,
    name,
    path: key,
    scale,
    source: key,
    source_type: 'path' as const,
    type: 'spandrel_image_to_image' as const,
  });
  const SEND_TO = 'widgets.gallery.itemActions.upscale.sendTo';
  const MODEL_ONLY = 'widgets.gallery.itemActions.upscale.modelOnlyGroup';

  const openUpscaleSubMenu = async (
    models: ReturnType<typeof upscaler>[],
    status: ModelsSnapshot['status'] = 'loaded'
  ) => {
    setModelsSnapshotForTests({ models, status });
    await renderMenu(createActions(vi.fn()), [image('source.png')]);
    await hoverItem(getMenuItem('widgets.gallery.itemActions.upscale.label'));
    await settleUntil(() => document.querySelector('[data-value="send-to-upscale"]') !== null, 'the Upscale submenu');

    return document
      .querySelector<HTMLElement>('[data-value="send-to-upscale"]')!
      .closest<HTMLElement>('[role="menu"]')!;
  };
  /** Opens one upscaler's factor submenu; `scaleSuffix` is the native scale its trigger shows. */
  const openFactorSubMenu = async (model: ReturnType<typeof upscaler>, scaleSuffix: string) => {
    await openUpscaleSubMenu([model]);
    await hoverItem(getMenuItem(`${model.name}${scaleSuffix}`));
    await settleUntil(
      () => document.querySelector(`[data-value^="upscale-model-only-${model.key}-"]`) !== null,
      `the factors of ${model.name}`
    );

    return document
      .querySelector<HTMLElement>(`[data-value^="upscale-model-only-${model.key}-"]`)!
      .closest<HTMLElement>('[role="menu"]')!;
  };
  const entries = (menu: HTMLElement) =>
    Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitem"], [data-part="item-group-label"]')).map(
      (entry) => `${entry.textContent?.trim()}${entry.getAttribute('aria-disabled') === 'true' ? ' (disabled)' : ''}`
    );

  afterEach(() => {
    setModelsSnapshotForTests({ models: [], status: 'idle' });
    ensureModelsLoaded.mockClear();
    commandsMock.generation.submitModelOnlyUpscale.mockReset();
    commandsMock.notifications.add.mockReset();
    galleryMock.metadata.mockReset();
  });

  it('lists every installed upscaler by name, with its native scale where it is recorded', async () => {
    const menu = await openUpscaleSubMenu([
      upscaler('ultra', '4x-UltraSharp', 4),
      upscaler('anime', '2x-AnimeSharp', 2),
      upscaler('legacy', 'Legacy restorer', null),
    ]);

    expect(entries(menu)).toEqual([SEND_TO, MODEL_ONLY, '2x-AnimeSharp2×', '4x-UltraSharp4×', 'Legacy restorer']);
  });

  it.each([
    ['its native scale', '4× (native)', 'native'],
    ['another factor', '1.5×', 1.5],
  ])("queues the chosen upscaler at %s on the image with the image's metadata", async (_case, label, scale) => {
    const ultra = upscaler('ultra', '4x-UltraSharp', 4);
    galleryMock.metadata.mockResolvedValue({ positive_prompt: 'a lighthouse' });
    await openFactorSubMenu(ultra, '4×');

    await interact(() => getMenuItem(label).click());
    await settleUntil(
      () => commandsMock.generation.submitModelOnlyUpscale.mock.calls.length > 0,
      'the upscale to queue'
    );

    expect(galleryMock.metadata).toHaveBeenCalledWith('source.png', expect.any(AbortSignal));
    expect(commandsMock.generation.submitModelOnlyUpscale).toHaveBeenCalledWith({
      backendSupportsCancellation: true,
      image: { height: 512, image_name: 'source.png', width: 512 },
      projectId: 'project-1',
      scale,
      sourceMetadata: { positive_prompt: 'a lighthouse' },
      upscaleModel: ultra,
    });
  });
});