Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

14.5 KB
Raw Blame
const jobsApi = vi.hoisted(() => ({ getMediaJob: vi.fn() }));
vi.mock('../services/apiMediaJobs', () => jobsApi);
const batchApi = vi.hoisted(() => ({ importGalleryFile: vi.fn(), assignImportedMedia: vi.fn() }));
vi.mock('../services/apiMedia', () => batchApi);
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router';

const { fetchPage, deleteImage, saveAnnotation, getGalleryImages, getVideoHistoryItem, listImageVariants, stitchVideos, toast, socketHandlers } = vi.hoisted(() => ({ stitchVideos: vi.fn(), toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }), socketHandlers: new Map(), fetchPage: vi.fn(), deleteImage: vi.fn(), saveAnnotation: vi.fn(), getGalleryImages: vi.fn(), getVideoHistoryItem: vi.fn(), listImageVariants: vi.fn() }));
vi.mock('../services/apiImageVideo', () => ({ listMediaGalleryPage: fetchPage, getGalleryImages, getVideoHistoryItem, listImageVariants }));
vi.mock('../services/api', () => ({ listMediaGalleryPage: fetchPage, deleteImage, deleteVideoHistoryItem: vi.fn(), stitchVideos }));
vi.mock('../services/socket', () => ({ default: { on: (event, fn) => socketHandlers.set(event, fn), off: (event) => socketHandlers.delete(event) } }));
vi.mock('../components/ui/Toast', () => ({ default: toast }));
vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: () => {} }));
vi.mock('../hooks/useMediaAnnotations', () => ({ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: saveAnnotation, getCardProps: () => ({}) }) }));
vi.mock('../hooks/useMediaPreviewActions', () => ({ default: () => ({}) }));
vi.mock('../components/media/VideoUpscaleDrawer', () => ({ default: () => null }));
vi.mock('../components/media/MediaPreview', () => ({ default: ({ preview }) => preview ? <div role="dialog">{preview.prompt}{preview.detailError && ' [details unavailable]'}</div> : null }));
vi.mock('../components/media/MediaCard', () => ({ default: ({ item, onDelete, onToggleStar, onPreview, onClick }) => <div>{onClick && <button type="button" onClick={() => onClick(item)}>Pick {item.filename}</button>}<button type="button" onClick={() => onPreview(item)}>{item.prompt}</button><button type="button" onClick={() => onToggleStar(item)}>Favorite {item.filename}</button><button type="button" onClick={() => onDelete(item)}>Delete {item.filename}</button></div> }));
vi.mock('../components/media/MediaHistoryGrid', () => ({ default: ({ items, children }) => <div>{items.map(children)}</div> }));
import MediaHistory from './MediaHistory';

let rows;
beforeEach(() => {
  vi.resetAllMocks();
  jobsApi.getMediaJob.mockResolvedValue({ status: 'queued' });
  saveAnnotation.mockResolvedValue({ ok: true });
  rows = Array.from({ length: 61 }, (_, n) => ({ kind: 'image', data: { filename: `${n}.png`, prompt: `Picture ${n}`, createdAt: '2026-01-01' } }));
  fetchPage.mockImplementation(async ({ limit = 60, offset = 0, q = '', filename }) => {
    const matches = rows.filter(row => (!filename || row.data.filename === filename) && row.data.prompt.includes(q));
    return { items: matches.slice(offset, offset + limit), total: matches.length, offset, limit, counts: { all: matches.length, image: matches.length, video: 0 } };
  });
  getGalleryImages.mockImplementation(async filenames => rows.filter(row => filenames.includes(row.data.filename)).map(row => row.data));
  // Hydration tries the variants group first (mediaDetail.js's
  // `fetchImageVariantGroup`, #8341); resolving "not indexed" by default
  // falls back to `getGalleryImages` so the existing hydration tests below
  // exercise that fallback exactly as before.
  listImageVariants.mockImplementation(async () => ({ items: [] }));
  deleteImage.mockImplementation(async filename => { rows = rows.filter(row => row.data.filename !== filename); return { ok: true }; });
});
const open = (url = '/media/history') => render(<MemoryRouter initialEntries={[url]}><MediaHistory /></MemoryRouter>);

describe('bounded media history', () => {
  it('loads the next server page, retries it without losing existing cards, and searches on the server', async () => {
    open();
    await screen.findByText('Picture 0');
    expect(screen.queryByText('Picture 60')).toBeNull();
    expect(fetchPage).toHaveBeenCalledWith(expect.objectContaining({ limit: 60, offset: 0, summary: true, hidden: false, compact: true }), { silent: true });
    fetchPage.mockRejectedValueOnce(new Error('Page unavailable'));
    fireEvent.click(screen.getByRole('button', { name: /Show more/ }));
    await screen.findByRole('alert');
    expect(screen.getByText('Picture 0')).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Retry loading' }));
    await screen.findByText('Picture 60');
    expect(fetchPage).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 60 }), { silent: true });
    fireEvent.change(screen.getByLabelText('Search media history'), { target: { value: 'Picture 60' } });
    await waitFor(() => expect(fetchPage).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 0, q: 'Picture 60' }), { silent: true }));
    await waitFor(() => expect(screen.queryByText('Picture 0')).toBeNull());
    expect(await screen.findByText('Picture 60')).toBeInTheDocument();
  });

  it('stars the card item by media key', async () => {
    open();
    await screen.findByText('Picture 0');
    fireEvent.click(screen.getByRole('button', { name: 'Favorite 0.png' }));
    await waitFor(() => expect(saveAnnotation).toHaveBeenCalledWith('image:0.png', { starred: true }));
  });

  it('keeps the previously unseen last item reachable after deletion shifts offsets', async () => {
    open();
    await screen.findByText('Picture 0');
    fireEvent.click(screen.getByRole('button', { name: 'Delete 0.png' }));
    await screen.findByText('Picture 60');
    expect(screen.queryByText('Picture 0')).toBeNull();
    expect(screen.queryByRole('button', { name: /Show more/ })).toBeNull();
  });

  it('opens a compact card by hydrating only that record, and never shows the preview as its prompt', async () => {
    const full = 'Picture 0 ' + 'with a long stored prompt '.repeat(30);
    rows[0].data.prompt = full;
    fetchPage.mockImplementation(async ({ offset = 0 }) => ({
      items: rows.slice(offset, offset + 60).map(row => ({ kind: row.kind, data: { ...row.data, compact: true, prompt: row.data.prompt.slice(0, 12) + '…' } })),
      total: rows.length, offset, limit: 60, counts: { all: rows.length, image: rows.length, video: 0 },
    }));
    open();
    fireEvent.click(await screen.findByRole('button', { name: 'Picture 0 wi…' }));
    expect(await screen.findByRole('dialog')).toHaveTextContent(full.trim());
    expect(getGalleryImages).toHaveBeenCalledTimes(1);
    expect(getGalleryImages).toHaveBeenCalledWith(['0.png'], { silent: true });
  });

  // #8341: opening an image used to cost two full-record reads (this
  // hydration's `gallery/lookup` PLUS the lightbox's own `variants` read for
  // the original-vs-cleaned toggle). The variants group always carries the
  // opened filename's own record, so hydration takes it from there and never
  // falls back to `getGalleryImages`.
  it('hydrates an opened image from the variants group without a separate gallery lookup', async () => {
    const full = 'Picture 0 ' + 'with a long stored prompt '.repeat(30);
    rows[0].data.prompt = full;
    fetchPage.mockImplementation(async ({ offset = 0 }) => ({
      items: rows.slice(offset, offset + 60).map(row => ({ kind: row.kind, data: { ...row.data, compact: true, prompt: row.data.prompt.slice(0, 12) + '…' } })),
      total: rows.length, offset, limit: 60, counts: { all: rows.length, image: rows.length, video: 0 },
    }));
    listImageVariants.mockImplementation(async filename => ({
      items: filename === '0.png' ? [rows[0].data] : [],
    }));
    open();
    fireEvent.click(await screen.findByRole('button', { name: 'Picture 0 wi…' }));
    expect(await screen.findByRole('dialog')).toHaveTextContent(full.trim());
    expect(listImageVariants).toHaveBeenCalledWith('0.png');
    expect(getGalleryImages).not.toHaveBeenCalled();
  });

  it('marks a compact record whose detail read fails instead of passing its preview off as complete', async () => {
    fetchPage.mockImplementation(async ({ offset = 0 }) => ({
      items: rows.slice(offset, offset + 60).map(row => ({ kind: row.kind, data: { ...row.data, compact: true } })),
      total: rows.length, offset, limit: 60, counts: { all: rows.length, image: rows.length, video: 0 },
    }));
    getGalleryImages.mockRejectedValue(new Error('offline'));
    open();
    fireEvent.click(await screen.findByRole('button', { name: 'Picture 3' }));
    await waitFor(() => expect(screen.getByRole('dialog')).toHaveTextContent('Picture 3 [details unavailable]'));
  });

  it('resolves an older deep-linked preview with a one-item request outside the loaded page', async () => {
    open('/media/history?preview=image:60.png');
    expect(await screen.findByRole('dialog')).toHaveTextContent('Picture 60');
    expect(fetchPage).toHaveBeenCalledWith({ limit: 1, kind: 'image', filename: '60.png' }, { silent: true });
  });
});

it('imports a mixed batch from History and inserts both returned records', async () => {
  batchApi.importGalleryFile.mockImplementation(async file => {
    const row = file.name.endsWith('.png')
      ? { kind: 'image', ref: 'new.png', data: { filename: 'new.png', prompt: 'Imported image prompt' } }
      : { kind: 'video', ref: 'new-video', data: { id: 'new-video', filename: 'new.mp4', prompt: 'Imported video prompt' } };
    rows.unshift(row);
    return row;
  });
  open();
  await screen.findByText('Picture 0');
  const input = screen.getByLabelText('Upload / import');
  expect(input.multiple).toBe(true);
  fireEvent.change(input, { target: { files: [new File(['png'], 'new.png'), new File(['mp4'], 'new.mp4')] } });
  expect(await screen.findByText('2 of 2 imported')).toHaveClass('sr-only');
  expect(screen.queryByRole('list', { name: 'Import queue' })).not.toBeInTheDocument();
  expect(await screen.findByText('Imported image prompt')).toBeInTheDocument();
  expect(await screen.findByText('Imported video prompt')).toBeInTheDocument();
  expect(batchApi.assignImportedMedia).not.toHaveBeenCalled();
});

describe('stitch job', () => {
  it('recovers a terminal result that arrived before enqueue acknowledgement and settles only once', async () => {
    rows = ['a', 'b'].map(id => ({ kind: 'video', data: { id, filename: `${id}.mp4`, prompt: `Clip ${id}`, createdAt: '2026-01-01' } }));
    let acknowledge;
    stitchVideos.mockImplementationOnce(() => new Promise(resolve => { acknowledge = resolve; }));
    jobsApi.getMediaJob.mockResolvedValueOnce({ status: 'completed' });
    open();
    await screen.findByText('Clip a');
    fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));
    fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));
    await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'fast-job' }));
    expect(toast.success).not.toHaveBeenCalled();
    await act(async () => { acknowledge({ job: { jobId: 'fast-job', status: 'queued' } }); });
    await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
    await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'fast-job' }));
    expect(toast.success).toHaveBeenCalledTimes(1);

    stitchVideos.mockResolvedValueOnce({ job: { jobId: 'unknown-job', status: 'queued' } });
    jobsApi.getMediaJob.mockRejectedValueOnce(new Error('Status unavailable'));
    fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));
    fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));
    await waitFor(() => expect(toast).toHaveBeenCalledWith('Stitch status unknown — check media history'));
    await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'unknown-job' }));
    expect(toast.success).toHaveBeenCalledTimes(2);
    await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'unknown-job' }));
    expect(toast.success).toHaveBeenCalledTimes(2);
  });

  it('toasts success only when the job settles, and surfaces an enqueue failure', async () => {
    rows = ['a', 'b'].map(id => ({ kind: 'video', data: { id, filename: `${id}.mp4`, prompt: `Clip ${id}`, createdAt: '2026-01-01' } }));
    stitchVideos.mockResolvedValueOnce({ ok: true, job: { jobId: 'job-1', status: 'queued' } });
    jobsApi.getMediaJob.mockRejectedValueOnce(new Error('Status unavailable'));
    open();
    await screen.findByText('Clip a');
    fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));
    fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));
    await waitFor(() => expect(stitchVideos).toHaveBeenCalledWith(['a', 'b'], { silent: true }));
    await waitFor(() => expect(toast).toHaveBeenCalled());
    expect(toast).toHaveBeenCalledWith('Stitch status unknown — check media history');
    expect(toast.success).not.toHaveBeenCalled();
    await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'unrelated-job' }));
    expect(toast.success).not.toHaveBeenCalled();
    await act(async () => socketHandlers.get('video-gen:failed')(undefined));
    expect(toast.error).not.toHaveBeenCalled();
    jobsApi.getMediaJob.mockResolvedValueOnce({ status: 'completed' });
    await act(async () => socketHandlers.get('connect')());
    await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
    await act(async () => socketHandlers.get('video-gen:completed')({ generationId: 'job-1' }));
    await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));

    stitchVideos.mockRejectedValueOnce(new Error('Queue full'));
    fireEvent.click(screen.getByRole('button', { name: 'Stitch' }));
    fireEvent.click(await screen.findByRole('button', { name: 'Pick a.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Pick b.mp4' }));
    fireEvent.click(screen.getByRole('button', { name: 'Stitch 2' }));
    await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Queue full'));
    expect(toast.success).toHaveBeenCalledTimes(1);
  });
});