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.

7.9 KB
Raw Blame
import type { GalleryUiAdapter } from '@features/gallery/react';
import type { Project } from '@workbench/projectContracts';
import type { WorkbenchSnapshot } from '@workbench/workbenchStore';
import type { ReactNode } from 'react';

import { accountLifecycle } from '@platform/state/accountLifecycle';
import { shallowEqual, useExternalStoreSelector } from '@platform/state/selectors';
import { reportProjectSync } from '@workbench/projects/syncStore';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { createWorkbenchStore } from '@workbench/workbenchStore';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { GalleryUiAdapterProvider } from './GalleryUiAdapter';

let store: ReturnType<typeof createWorkbenchStore>;
let adapter: GalleryUiAdapter;
let renderCount: number;
let host: HTMLDivElement;
let root: Root;
const noop = () => undefined;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

vi.mock('@features/gallery/react', () => ({
  GalleryUiProvider: ({ adapter: next, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => {
    adapter = next;
    renderCount += 1;
    return children;
  },
}));
vi.mock('@workbench/widgets/preview/livePreviewFollow', () => ({
  useLivePreviewFollow: () => ({
    sessions: [],
    gallerySessions: [],
    pinnedSessionId: null,
    followedSessionId: null,
    follow: vi.fn(),
    pin: vi.fn(),
    showAll: vi.fn(),
  }),
}));
const session = vi.hoisted(() => ({ multiuserEnabled: false }));
const usage = vi.hoisted(() => ({ check: vi.fn(), readProject: vi.fn() }));
// The server is doubled; the resolver runs for real over the store's projects.
vi.mock('@features/gallery/mediaUsage', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  checkGalleryMediaUsage: (...args: unknown[]) => usage.check(...args),
}));
// Reading the server's copy of a project fails: a report that needed it would list the project unchecked.
vi.mock('@workbench/projects/api', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  getProjectWithinSize: (...args: unknown[]) => usage.readProject(...args),
}));
vi.mock('@features/identity', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  useAuthSession: () => session,
}));
vi.mock('@workbench/projects/useProjectFileActions', () => ({ useExportLibraryProject: () => noop }));
vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => noop }));
vi.mock('./GalleryImageActionsBridge', () => ({
  GalleryItemActionsAdapter: () => null,
  GalleryImageContextMenu: () => null,
}));
vi.mock('@workbench/WorkbenchContext', () => ({
  useActiveProjectSelector: (selector: (project: Project) => unknown) =>
    useExternalStoreSelector(
      store.subscribe,
      store.getSnapshot,
      (snapshot) => selector(snapshot.activeProject),
      shallowEqual
    ),
  useOptionalWorkbenchCommands: () => store.commands,
  useWorkbenchCommands: () => store.commands,
  useWorkbenchInternalStore: () => store,
  useWorkbenchPersistenceService: () => ({ ensureProjectOnServer: () => Promise.resolve() }),
  useWorkbenchQueries: () => store.queries,
  useWorkbenchSelector: (selector: (snapshot: WorkbenchSnapshot) => unknown) =>
    useExternalStoreSelector(store.subscribe, store.getSnapshot, selector, shallowEqual),
}));

const renderAdapter = async (absent: string[] = []) => {
  const state = createInitialWorkbenchState();
  const project = state.projects[0]!;
  project.widgetInstances = Object.fromEntries(
    Object.entries(project.widgetInstances).filter(([, instance]) => !absent.includes(instance.typeId))
  );
  store = createWorkbenchStore(state);
  await act(() => root.render(<GalleryUiAdapterProvider>{null}</GalleryUiAdapterProvider>));
};

beforeEach(() => {
  accountLifecycle.activate('gallery-subscription-test');
  renderCount = 0;
  host = document.createElement('div');
  document.body.append(host);
  root = createRoot(host);
});
afterEach(async () => {
  await act(() => root.unmount());
  host.remove();
  accountLifecycle.invalidate();
});

describe('Gallery adapter subscriptions', () => {
  it.each([['gallery'], ['generate'], ['gallery', 'generate']])(
    'retains the adapter during unrelated layout updates with absent widgets %j',
    async (...absent) => {
      await renderAdapter(absent);
      const previousAdapter = adapter;
      const previousRenderCount = renderCount;
      const previousSnapshot = store.getSnapshot();
      const nextWidth = previousSnapshot.activeProject.widgetRegions.left.sizePx + 20;

      await act(() => store.commands.layout.setRegionSize('left', nextWidth));

      expect(store.getSnapshot()).not.toBe(previousSnapshot);
      expect(store.getSnapshot().activeProject.widgetRegions.left.sizePx).toBe(nextWidth);
      expect(adapter).toBe(previousAdapter);
      expect(renderCount).toBe(previousRenderCount);
    }
  );

  it('publishes relevant Gallery and Generate value changes through the subscribed adapter', async () => {
    await renderAdapter();
    const previousAdapter = adapter;

    await act(() => store.commands.gallery.updateSettings({ imageDensityPercent: 24 }));

    expect(adapter).not.toBe(previousAdapter);
    expect(adapter.galleryValues.imageDensityPercent).toBe(24);
    const galleryAdapter = adapter;

    await act(() => store.commands.widgets.patchValues('generate', { positivePrompt: 'Updated prompt' }));

    expect(adapter).not.toBe(galleryAdapter);
    expect(adapter.generateValues.positivePrompt).toBe('Updated prompt');
    expect(adapter.galleryValues).toBe(galleryAdapter.galleryValues);
  });
});

describe('board sharing', () => {
  it.each([true, false])(
    'tells the gallery boards can be shared exactly when the server has accounts (%s)',
    async (multiuser) => {
      session.multiuserEnabled = multiuser;

      await renderAdapter();

      expect(adapter.boardSharing).toBe(multiuser);
    }
  );
});

describe('board media usage', () => {
  it("narrows a board's report by the open project's own state when the server holds what it builds on", async () => {
    await renderAdapter();
    const projectId = store.getSnapshot().activeProject.id;
    usage.readProject.mockRejectedValue(new Error('Not read'));
    // Saved at revisions 7 and 3 with both; the project now uses only a.png.
    await act(() =>
      store.commands.widgets.patchValues('generate', {
        referenceImages: [{ config: { image: { image_name: 'a.png' } } }],
      })
    );
    reportProjectSync({
      hasPendingChanges: true,
      localDraftStatus: 'ok',
      projects: { [projectId]: { isPendingPush: true, revision: 7, workspaceRevision: 3 } },
      recoverableDrafts: [],
    });
    usage.check.mockResolvedValue({
      checkedImageCount: 3,
      checkedVideoCount: 0,
      documents: [
        {
          id: projectId,
          imageCount: 2,
          imageNames: ['a.png', 'b.png'],
          kind: 'project',
          name: 'Open',
          revision: 7,
          videoCount: 0,
          videoNames: [],
          workspaceRevision: 3,
        },
      ],
      documentsTotal: 1,
      inUseImageCount: 2,
      inUseVideoCount: 0,
      otherAccounts: { documentCount: 0, imageCount: 0, queueItemCount: 0, videoCount: 0 },
      queue: { imageCount: 0, imageNames: [], itemCount: 0, videoCount: 0, videoNames: [] },
    });

    const report = await adapter.getBoardMediaUsage('board-1', new AbortController().signal);

    expect(usage.check).toHaveBeenCalledWith({ boardId: 'board-1', kind: 'board' }, expect.any(AbortSignal));
    expect(usage.readProject).not.toHaveBeenCalled();
    expect(report).toMatchObject({
      checkedCount: 3,
      groups: [{ count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'generateReferenceImages' }] }],
      inUseCount: 1,
      scope: 'board',
    });
  });
});