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.

28.6 KB
Raw Blame
import { galleryItems } from '@features/gallery';
import { configureLogging, getLoggingConfig, getLogSnapshot, resetLogging } from '@platform/logging/logger';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';

const mocks = vi.hoisted(() => ({
  apiFetchJson: vi.fn(),
  apiFetchRaw: vi.fn(),
  sleep: vi.fn(),
}));

vi.mock('@platform/transport/http', async (importOriginal) => ({
  ...(await importOriginal<Record<string, unknown>>()),
  absolutizeApiUrl: (url: string) => `https://api.test${url}`,
  apiFetch: vi.fn(),
  apiFetchJson: mocks.apiFetchJson,
  apiFetchRaw: mocks.apiFetchRaw,
  sleep: mocks.sleep,
}));

import { ApiError } from '@platform/transport/http';

import {
  addImagesToGalleryBoard,
  createGalleryBoard,
  galleryBoardExists,
  deleteGalleryBoard,
  deleteGalleryImages,
  downloadGalleryArchive,
  getGalleryImageByName,
  getGalleryImagesByNames,
  getGalleryItemLocation,
  listGalleryDateBoardItemNames,
  listGalleryItemNames,
  imageMakeCanvasAssetChanges,
  listGalleryBoards,
  listGalleryItems,
  listPaletteImages,
  removeImagesFromGalleryBoard,
  updateGalleryBoard,
  uploadGalleryImage,
  uploadGalleryVideo,
} from './backend';

describe('deleteGalleryBoard outcomes', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('maps confirmed and failed media when deleting a board with its contents', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      board_id: 'board-1',
      deleted_board_images: [],
      deleted_board_videos: [],
      deleted_images: ['gone.png'],
      deleted_videos: ['gone.mp4'],
      failed_images: ['locked.png'],
      failed_videos: ['locked.mp4'],
    });

    await expect(deleteGalleryBoard('board-1', true)).resolves.toEqual({
      boardId: 'board-1',
      deletedBoardImageNames: [],
      deletedBoardVideoNames: [],
      deletedImageNames: ['gone.png'],
      deletedVideoNames: ['gone.mp4'],
      failedImageNames: ['locked.png'],
      failedVideoNames: ['locked.mp4'],
    });
  });

  it('maps removed board relationships when retaining the board contents', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      board_id: 'board-1',
      deleted_board_images: ['moved.png'],
      deleted_board_videos: ['moved.mp4'],
      deleted_images: [],
      deleted_videos: [],
      failed_images: [],
      failed_videos: [],
    });

    await expect(deleteGalleryBoard('board-1', false)).resolves.toEqual({
      boardId: 'board-1',
      deletedBoardImageNames: ['moved.png'],
      deletedBoardVideoNames: ['moved.mp4'],
      deletedImageNames: [],
      deletedVideoNames: [],
      failedImageNames: [],
      failedVideoNames: [],
    });
    expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/boards/board-1?include_images=false', {
      method: 'DELETE',
      signal: undefined,
    });
  });
});

describe('image mutation outcomes', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('returns only images confirmed added to or removed from a board', async () => {
    mocks.apiFetchJson
      .mockResolvedValueOnce({ added_images: ['moved.png'], affected_boards: ['board-1', 'none'] })
      .mockResolvedValueOnce({ affected_boards: ['board-1', 'none'], removed_images: ['removed.png'] });

    await expect(addImagesToGalleryBoard('board-1', ['moved.png', 'locked.png'])).resolves.toEqual(['moved.png']);
    await expect(removeImagesFromGalleryBoard(['removed.png', 'locked.png'])).resolves.toEqual(['removed.png']);
  });
});

describe('downloadGalleryArchive', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
    mocks.apiFetchRaw.mockReset();
    mocks.sleep.mockReset();
  });

  it('aborts polling before another account can request the prior account archive', async () => {
    let resumeSleep: (() => void) | undefined;
    mocks.apiFetchJson.mockResolvedValue({ bulk_download_item_name: 'user-a.zip' });
    mocks.apiFetchRaw.mockResolvedValue(new Response(null, { status: 404 }));
    mocks.sleep.mockImplementationOnce(
      () =>
        new Promise<void>((resolve) => {
          resumeSleep = resolve;
        })
    );

    const download = downloadGalleryArchive({ imageNames: ['user-a.png'] });

    await vi.waitFor(() => {
      expect(mocks.sleep).toHaveBeenCalledOnce();
    });
    const postSignal = (mocks.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
    const pollSignal = (mocks.apiFetchRaw.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;
    const sleepSignal = mocks.sleep.mock.calls[0]?.[1] as AbortSignal;

    accountLifecycle.invalidate();
    accountLifecycle.activate('user-b');
    resumeSleep?.();

    await expect(download).rejects.toThrow('no longer active');
    expect(postSignal?.aborted).toBe(true);
    expect(pollSignal?.aborted).toBe(true);
    expect(sleepSignal.aborted).toBe(true);
    expect(mocks.apiFetchRaw).toHaveBeenCalledTimes(1);
  });
});

describe('getGalleryItemLocation', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('sends the exact ordinary-page filters and maps the zero-based rank', async () => {
    mocks.apiFetchJson.mockResolvedValue({ index: 123, kind: 'video', name: 'clip.mp4', total: 250 });
    const signal = new AbortController().signal;

    await expect(
      getGalleryItemLocation({
        boardId: 'board-1',
        createdFrom: '2026-07-01',
        createdTo: '2026-07-31',
        galleryView: 'assets',
        kind: 'video',
        name: 'clip.mp4',
        orderDir: 'ASC',
        searchTerm: ' portrait ',
        signal,
        starred: false,
      })
    ).resolves.toEqual({ index: 123, kind: 'video', name: 'clip.mp4', total: 250 });

    expect(mocks.apiFetchJson).toHaveBeenCalledWith(
      '/api/v1/gallery/items/location?board_id=board-1&categories=control&categories=mask&categories=user&created_from=2026-07-01&created_to=2026-07-31&is_intermediate=false&kind=video&order_dir=ASC&name=clip.mp4&search_term=portrait&starred=false&starred_first=false',
      { signal }
    );
  });
});

describe('media kind restriction', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
    mocks.apiFetchJson.mockResolvedValue({
      index: 0,
      items: [],
      kind: 'video',
      name: 'clip.mp4',
      total: 0,
      total_count: 0,
    });
  });

  const requestedMediaKinds = () =>
    mocks.apiFetchJson.mock.calls.map(([url]) => new URLSearchParams(String(url).split('?')[1]).getAll('media_kind'));
  const base = { boardId: 'board-1', galleryView: 'images', searchTerm: '' } as const;

  it('sends media_kind to every ordinary listing endpoint when one kind is chosen', async () => {
    await listGalleryItems({ ...base, mediaKind: 'video' });
    await listGalleryItemNames({ ...base, mediaKind: 'video', orderDir: 'DESC' });
    await getGalleryItemLocation({ ...base, kind: 'video', mediaKind: 'video', name: 'clip.mp4', orderDir: 'DESC' });
    await listGalleryDateBoardItemNames({
      ...base,
      boardId: 'by_date:2026-08-02',
      mediaKind: 'image',
      orderDir: 'DESC',
    });

    expect(requestedMediaKinds()).toEqual([['video'], ['video'], ['video'], ['image']]);
  });
});

describe('getGalleryImageByName', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
  });

  it('encodes the image name, forwards the abort signal, and maps the backend image', async () => {
    const controller = new AbortController();
    mocks.apiFetchJson.mockResolvedValue({
      board_id: 'board-1',
      created_at: '2026-07-09T12:00:00.000Z',
      has_workflow: true,
      height: 360,
      image_category: 'general',
      image_name: 'folder/workflow result.png',
      image_url: '/images/workflow-result.png',
      is_intermediate: false,
      starred: true,
      thumbnail_url: '/thumbnails/workflow-result.webp',
      width: 640,
    });

    await expect(getGalleryImageByName('folder/workflow result.png', controller.signal)).resolves.toEqual({
      boardId: 'board-1',
      createdAt: '2026-07-09T12:00:00.000Z',
      hasWorkflow: true,
      height: 360,
      imageCategory: 'general',
      imageName: 'folder/workflow result.png',
      imageUrl: 'https://api.test/images/workflow-result.png',
      queuedAt: '2026-07-09T12:00:00.000Z',
      sourceQueueItemId: 'backend-gallery',
      starred: true,
      thumbnailUrl: 'https://api.test/thumbnails/workflow-result.webp',
      width: 640,
    });
    expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/images/i/folder%2Fworkflow%20result.png', {
      signal: controller.signal,
    });
  });
});

describe('getGalleryImagesByNames', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
  });

  it('restores the requested order when the bulk endpoint responds out of order', async () => {
    const dto = (imageName: string) => ({
      board_id: 'none',
      created_at: '2026-07-09T12:00:00.000Z',
      height: 512,
      image_category: 'general',
      image_name: imageName,
      image_url: `/images/${imageName}`,
      is_intermediate: false,
      thumbnail_url: `/thumbnails/${imageName}`,
      width: 512,
    });
    mocks.apiFetchJson.mockResolvedValue([dto('third.png'), dto('first.png'), dto('second.png')]);

    const images = await getGalleryImagesByNames(['first.png', 'second.png', 'third.png']);

    expect(images.map((image) => image.imageName)).toEqual(['first.png', 'second.png', 'third.png']);
  });
});

describe('listPaletteImages created-at range', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
    mocks.apiFetchJson.mockResolvedValue({ items: [], limit: 20, offset: 0, total: 0 });
  });

  it('sends created_from/created_to as query params', async () => {
    await listPaletteImages({
      boardId: 'board-1',
      createdFrom: '2026-07-01',
      createdTo: '2026-07-15',
      galleryView: 'images',
      searchTerm: '',
    });

    const url = mocks.apiFetchJson.mock.calls[0]?.[0] as string;
    const params = new URLSearchParams(url.split('?')[1]);
    expect(params.get('created_from')).toBe('2026-07-01');
    expect(params.get('created_to')).toBe('2026-07-15');
  });

  it('short-circuits a date board that falls outside the range without a request', async () => {
    await expect(
      listPaletteImages({
        boardId: 'by_date:2026-07-18',
        createdFrom: '2026-07-01',
        createdTo: '2026-07-15',
        galleryView: 'images',
        searchTerm: '',
      })
    ).resolves.toEqual({ images: [], total: 0 });
    expect(mocks.apiFetchJson).not.toHaveBeenCalled();
  });
});

describe('listGalleryItems', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
  });

  it('maps a mixed page by kind and normalizes transport-only fields', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      items: [
        {
          board_id: null,
          category: 'general',
          created_at: '2026-07-20T10:00:00.000Z',
          duration: 8.5,
          full_url: '/images/still.png',
          height: 512,
          is_intermediate: false,
          kind: 'image',
          name: 'still.png',
          starred: true,
          thumbnail_url: '/thumbnails/still.webp',
          width: 768,
        },
        {
          board_id: 'board-1',
          category: 'general',
          created_at: '2026-07-20T09:00:00.000Z',
          duration: 3.25,
          fps: null,
          full_url: '/videos/clip.mp4',
          height: 720,
          is_intermediate: true,
          kind: 'video',
          name: 'clip.mp4',
          starred: false,
          thumbnail_url: '/thumbnails/clip.webp',
          width: 1280,
        },
      ],
      limit: 20,
      offset: 0,
      total: 2,
    });

    await expect(listGalleryItems({ boardId: 'board-1', galleryView: 'images', searchTerm: '' })).resolves.toEqual({
      items: [
        {
          boardId: 'none',
          category: 'general',
          createdAt: '2026-07-20T10:00:00.000Z',
          fullUrl: 'https://api.test/images/still.png',
          height: 512,
          isIntermediate: false,
          kind: 'image',
          name: 'still.png',
          starred: true,
          thumbnailUrl: 'https://api.test/thumbnails/still.webp',
          width: 768,
        },
        {
          boardId: 'board-1',
          category: 'general',
          createdAt: '2026-07-20T09:00:00.000Z',
          durationSeconds: 3.25,
          fullUrl: 'https://api.test/videos/clip.mp4',
          height: 720,
          isIntermediate: true,
          kind: 'video',
          name: 'clip.mp4',
          starred: false,
          thumbnailUrl: 'https://api.test/thumbnails/clip.webp',
          width: 1280,
        },
      ],
      total: 2,
    });
  });

  it('forwards gallery filters and pagination to the polymorphic endpoint', async () => {
    const controller = new AbortController();
    mocks.apiFetchJson.mockResolvedValue({ items: [], limit: 17, offset: 34, total: 0 });

    await listGalleryItems({
      boardId: 'board-1',
      createdFrom: '2026-07-01',
      createdTo: '2026-07-15',
      galleryView: 'images',
      isIntermediate: true,
      limit: 17,
      offset: 34,
      orderDir: 'ASC',
      searchTerm: '  summer clip  ',
      signal: controller.signal,
      starred: true,
    });

    const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
    const params = new URLSearchParams(url.split('?')[1]);

    expect(url.split('?')[0]).toBe('/api/v1/gallery/items/');
    expect(params.get('board_id')).toBe('board-1');
    expect(params.getAll('categories')).toEqual(['general']);
    expect(params.get('created_from')).toBe('2026-07-01');
    expect(params.get('created_to')).toBe('2026-07-15');
    expect(params.get('is_intermediate')).toBe('true');
    expect(params.get('limit')).toBe('17');
    expect(params.get('offset')).toBe('34');
    expect(params.get('order_dir')).toBe('ASC');
    expect(params.get('starred')).toBe('true');
    // The backend defaults to starred-first; the grid must pin it off.
    expect(params.get('starred_first')).toBe('false');
    expect(params.get('search_term')).toBe('summer clip');
    expect(init.signal).toBe(controller.signal);
  });
});

describe('mixed gallery item details', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
  });

  it('resolves a video ref and omits absent fps', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      board_id: null,
      created_at: '2026-07-20T10:00:00.000Z',
      duration: 4.5,
      fps: null,
      height: 720,
      is_intermediate: false,
      starred: true,
      thumbnail_url: '/thumbnails/clip.webp',
      video_category: 'general',
      video_name: 'folder/clip.mp4',
      video_url: '/videos/clip.mp4',
      width: 1280,
    });

    const item = await galleryItems.resolve({ kind: 'video', name: 'folder/clip.mp4' });

    expect(item).toEqual({
      boardId: 'none',
      category: 'general',
      createdAt: '2026-07-20T10:00:00.000Z',
      durationSeconds: 4.5,
      fullUrl: 'https://api.test/videos/clip.mp4',
      height: 720,
      isIntermediate: false,
      kind: 'video',
      name: 'folder/clip.mp4',
      starred: true,
      thumbnailUrl: 'https://api.test/thumbnails/clip.webp',
      width: 1280,
    });
    expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/videos/i/folder%2Fclip.mp4', { signal: undefined });
  });

  it('carries the media-origin marker so a reference needs no follow-up metadata fetch', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      board_id: null,
      created_at: '2026-07-20T10:00:00.000Z',
      duration: 4.5,
      fps: 24,
      height: 360,
      is_intermediate: false,
      media_origin: 'audio_upload',
      starred: false,
      thumbnail_url: '/thumbnails/song.webp',
      video_category: 'user',
      video_name: 'song.mp4',
      video_url: '/videos/song.mp4',
      width: 640,
    });

    const item = await galleryItems.resolve({ kind: 'video', name: 'song.mp4' });

    expect(item).toMatchObject({ kind: 'video', mediaOrigin: 'audio_upload' });
  });
});

describe('imageMakeCanvasAssetChanges', () => {
  it('makes the image durable AND moves it out of the gallery images view', () => {
    // Durability alone leaves node outputs in `general`, publishing preprocess results to Images.
    expect(imageMakeCanvasAssetChanges()).toEqual({ image_category: 'other', is_intermediate: false });
  });
});

describe('gallery category queries', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
    mocks.apiFetchJson.mockResolvedValue({ items: [], limit: 20, offset: 0, total: 0 });
  });

  const categoriesFor = async (galleryView: 'images' | 'assets'): Promise<string[]> => {
    await listPaletteImages({ boardId: 'board-1', galleryView, searchTerm: '' });
    const url = mocks.apiFetchJson.mock.calls[0]?.[0] as string;

    return new URLSearchParams(url.split('?')[1]).getAll('categories');
  };

  it('lists only user-facing categories in the assets view', async () => {
    expect(await categoriesFor('assets')).toEqual(['control', 'mask', 'user']);
  });
});

describe('board media counts and covers', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('maps video counts and resolves a video cover to its thumbnail', async () => {
    mocks.apiFetchJson.mockImplementation((path: string) => {
      if (path.startsWith('/api/v1/boards/')) {
        return Promise.resolve([
          {
            archived: false,
            asset_count: 1,
            board_id: 'board-1',
            board_name: 'Clips',
            cover_image_name: null,
            cover_video_name: 'clip.mp4',
            image_count: 2,
            video_count: 3,
          },
        ]);
      }

      // Uncategorized image / asset / video totals.
      return Promise.resolve({ total: 0 });
    });

    const boards = await listGalleryBoards();

    expect(boards[1]).toMatchObject({
      coverThumbnailUrl: 'https://api.test/api/v1/videos/i/clip.mp4/thumbnail',
      coverVideoName: 'clip.mp4',
      id: 'board-1',
      imageCount: 2,
      videoCount: 3,
    });
  });
});

describe('deleteGalleryImages partial failures', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('separates deleted names from ones the backend refused', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      affected_boards: ['board-1'],
      deleted_images: ['gone.png'],
      failed_images: ['locked.png'],
    });

    await expect(deleteGalleryImages(['gone.png', 'locked.png'])).resolves.toEqual({
      deletedImageNames: ['gone.png'],
      failedImageNames: ['locked.png'],
    });
  });

  it('treats names the server confirms absent as deleted when the delete response is lost', async () => {
    mocks.apiFetchJson.mockImplementation((url: string) =>
      url === '/api/v1/images/gone'
        ? Promise.resolve(['committed.png'])
        : Promise.reject(new TypeError('Failed to fetch'))
    );

    await expect(deleteGalleryImages(['committed.png', 'kept.png'])).resolves.toEqual({
      deletedImageNames: ['committed.png'],
      failedImageNames: ['kept.png'],
    });
  });

  it('keeps the lost response’s error when the server cannot confirm any absence', async () => {
    const lost = new TypeError('Failed to fetch');
    mocks.apiFetchJson.mockImplementation((url: string) =>
      url === '/api/v1/images/gone' ? Promise.resolve([]) : Promise.reject(lost)
    );

    await expect(deleteGalleryImages(['a.png'])).rejects.toBe(lost);

    mocks.apiFetchJson.mockRejectedValue(lost);

    await expect(deleteGalleryImages(['a.png'])).rejects.toBe(lost);
  });

  it('reports a whole-batch refusal as is, without asking what is gone', async () => {
    const refused = new ApiError('{"detail":"Image maintenance is running"}', 409);
    mocks.apiFetchJson.mockRejectedValue(refused);

    await expect(deleteGalleryImages(['a.png'])).rejects.toBe(refused);
    expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
  });

  it('counts names the route skipped as deleted once the server confirms them absent', async () => {
    mocks.apiFetchJson.mockImplementation((url: string, init: { body: string }) => {
      if (url === '/api/v1/images/gone') {
        expect(JSON.parse(init.body)).toEqual({ image_names: ['already-gone.png', 'foreign.png'] });
        return Promise.resolve(['already-gone.png']);
      }
      return Promise.resolve({ affected_boards: [], deleted_images: ['live.png'], failed_images: [] });
    });

    await expect(deleteGalleryImages(['live.png', 'already-gone.png', 'foreign.png'])).resolves.toEqual({
      deletedImageNames: ['live.png', 'already-gone.png'],
      failedImageNames: [],
    });
  });
});

describe('name lists past the server’s per-request cap', () => {
  const names = (count: number) => Array.from({ length: count }, (_, index) => `image-${index}.png`);
  const sentNames = () =>
    mocks.apiFetchJson.mock.calls.map(
      ([, init]) => (JSON.parse(String(init.body)) as { image_names: string[] }).image_names
    );
  // Deletes what it is sent, except that it reports every name ending in 7 as failed.
  const deleteServer = (_url: string, init: { body: string }) => {
    const sent = (JSON.parse(init.body) as { image_names: string[] }).image_names;

    if (sent.length > 1000) {
      return Promise.reject(new ApiError('List should have at most 1000 items', 422));
    }

    return Promise.resolve({
      affected_boards: [`board-${sent[0]}`],
      deleted_images: sent.filter((name) => !name.endsWith('7.png')),
      failed_images: sent.filter((name) => name.endsWith('7.png')),
    });
  };

  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('sends 2,500 names as 1,000, 1,000 and 500, in order, and merges the answers', async () => {
    mocks.apiFetchJson.mockImplementation(deleteServer);
    const requested = names(2500);

    const result = await deleteGalleryImages(requested);

    expect(sentNames()).toEqual([requested.slice(0, 1000), requested.slice(1000, 2000), requested.slice(2000)]);
    expect(result).toEqual({
      deletedImageNames: requested.filter((name) => !name.endsWith('7.png')),
      failedImageNames: requested.filter((name) => name.endsWith('7.png')),
    });
  });

  it('reports the earlier batches’ successes when a later batch fails, and the rest as failed', async () => {
    configureLogging({ ...getLoggingConfig(), level: 'debug' });
    onTestFinished(resetLogging);
    mocks.apiFetchJson
      .mockImplementationOnce(deleteServer)
      .mockRejectedValueOnce(new ApiError('{"detail":"Server error"}', 500));
    const requested = names(2500);

    const result = await deleteGalleryImages(requested);

    // The third batch is never sent, and the cause is kept in the log.
    expect(mocks.apiFetchJson.mock.calls.filter(([url]) => url === '/api/v1/images/delete')).toHaveLength(2);
    expect(getLogSnapshot().entries).toContainEqual(
      expect.objectContaining({ level: 'debug', name: 'gallery.batch-request-failed' })
    );
    expect(result).toEqual({
      deletedImageNames: requested.slice(0, 1000).filter((name) => !name.endsWith('7.png')),
      failedImageNames: [
        ...requested.slice(0, 1000).filter((name) => name.endsWith('7.png')),
        ...requested.slice(1000),
      ],
    });
  });

  it('reports what earlier batches did when the caller aborts later, and sends nothing after', async () => {
    const controller = new AbortController();
    const requested = names(2500);
    mocks.apiFetchJson.mockImplementation((url: string, init: { body: string }) => {
      if (mocks.apiFetchJson.mock.calls.length === 2) {
        controller.abort();
      }
      return deleteServer(url, init);
    });

    const result = await deleteGalleryImages(requested, controller.signal);

    expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
    // The aborted batch's answer is never read, so its names are unconfirmed.
    expect(result).toEqual({
      deletedImageNames: requested.slice(0, 1000).filter((name) => !name.endsWith('7.png')),
      failedImageNames: [
        ...requested.slice(0, 1000).filter((name) => name.endsWith('7.png')),
        ...requested.slice(1000),
      ],
    });
  });

  it('sends no further batch once the account changes', async () => {
    mocks.apiFetchJson.mockImplementationOnce(() => {
      accountLifecycle.invalidate();
      accountLifecycle.activate('user-b');
      return Promise.resolve({ affected_boards: [], removed_images: names(1000) });
    });

    await expect(removeImagesFromGalleryBoard(names(2500))).rejects.toThrow('no longer active');
    expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);
  });
});

describe('gallery uploads', () => {
  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
  });

  it('uploads images as user assets and never sends a synthetic board id', async () => {
    mocks.apiFetchJson.mockResolvedValue({
      board_id: null,
      created_at: '2026-07-30T12:00:00.000Z',
      height: 64,
      image_category: 'user',
      image_name: 'photo.png',
      image_url: '/images/photo.png',
      is_intermediate: false,
      starred: false,
      thumbnail_url: '/thumbnails/photo.webp',
      width: 64,
    });

    await uploadGalleryImage(new File(['image'], 'photo.png', { type: 'image/png' }), 'all');

    const [url, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];
    const query = new URLSearchParams(url.split('?')[1]);
    expect(url.split('?')[0]).toBe('/api/v1/images/upload');
    expect(query.get('image_category')).toBe('user');
    expect(query.get('is_intermediate')).toBe('false');
    expect(query.has('board_id')).toBe(false);
    expect(init.method).toBe('POST');
    expect(init.body).toBeInstanceOf(FormData);
  });

  it.each(['none', 'all', 'by_date:2026-07-30'])('omits synthetic board %s from video uploads', async (boardId) => {
    mocks.apiFetchJson.mockResolvedValue({
      board_id: null,
      created_at: '2026-07-30T12:00:00.000Z',
      duration: 4,
      height: 360,
      is_intermediate: false,
      starred: false,
      thumbnail_url: '/videos/clip.webp',
      video_category: 'general',
      video_name: 'clip.mp4',
      video_url: '/videos/clip.mp4',
      width: 640,
    });

    await uploadGalleryVideo(new File(['video'], 'clip.mp4', { type: 'video/mp4' }), boardId);

    const url = mocks.apiFetchJson.mock.calls[0]?.[0] as string;
    expect(new URLSearchParams(url.split('?')[1]).has('board_id')).toBe(false);
  });
});

describe('board membership transport', () => {
  const dto = { archived: false, asset_count: 0, board_id: 'b1', board_name: 'B', image_count: 0, is_inbox: false };

  beforeEach(() => {
    accountLifecycle.activate('user-a');
    mocks.apiFetchJson.mockReset();
    mocks.apiFetchJson.mockResolvedValue(dto);
  });

  it('sends an explicit null to move a board to the Library, and no key to leave it alone', async () => {
    await updateGalleryBoard('b1', { projectId: null });
    await updateGalleryBoard('b1', { projectId: 'p2' });
    await updateGalleryBoard('b1', { name: 'Renamed' });

    const bodies = mocks.apiFetchJson.mock.calls.map(([, init]) => JSON.parse((init as { body: string }).body));
    expect(bodies[0]).toEqual({ project_id: null });
    expect(bodies[1]).toEqual({ project_id: 'p2' });
    expect(bodies[2]).toEqual({ board_name: 'Renamed' });
  });

  it('reads the caller’s access, and reports none for a server that sends no actions', async () => {
    mocks.apiFetchJson.mockResolvedValueOnce({
      ...dto,
      admin_override: false,
      allowed_actions: ['read', 'add_media'],
      general_access: 'contributor',
      my_role: 'contributor',
      owner_username: 'Ana',
    });

    const shared = await createGalleryBoard('B');
    const unreported = await createGalleryBoard('B');

    expect(shared).toMatchObject({
      access: {
        actions: ['read', 'add_media'],
        adminOverride: false,
        generalAccess: 'contributor',
        role: 'contributor',
      },
      ownerName: 'Ana',
    });
    expect(unreported.access).toBeUndefined();
  });
});

describe('galleryBoardExists', () => {
  beforeEach(() => {
    mocks.apiFetchJson.mockReset();
  });

  it('answers true for a board the server returns, and for one it refuses to show (403): it exists either way', async () => {
    mocks.apiFetchJson.mockResolvedValueOnce({ board_id: 'b1' });
    mocks.apiFetchJson.mockRejectedValueOnce(
      new ApiError('{"detail":{"code":"board_unreadable","message":"Not authorized to access this board"}}', 403)
    );

    await expect(galleryBoardExists('b1')).resolves.toBe(true);
    await expect(galleryBoardExists('restricted')).resolves.toBe(true);
    expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);
  });
});