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

10.3 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router';

// The page pulls in network-y siblings (sync integrity hook, share/sync peer
// buttons) that fetch on mount. Stub them so the test only exercises the
// duplicate-detection banner + merge flow added here.
vi.mock('../services/api', () => ({
  listUniverseSummaries: vi.fn(),
  deleteUniverse: vi.fn(),
  listPipelineSeriesSummaries: vi.fn(),
  listMediaCollections: vi.fn(),
  listUniverseDuplicates: vi.fn(),
  previewUniverseMerge: vi.fn(),
  mergeUniverses: vi.fn(),
  previewSeriesMerge: vi.fn(),
  mergeSeries: vi.fn(),
  updateUniverse: vi.fn(),
  updatePipelineSeries: vi.fn(),
}));
vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../components/ui/Modal', () => ({ default: ({ open, children }) => (open ? <div role="dialog">{children}</div> : null) }));
vi.mock('../components/ui/InlineDiff', () => ({ default: ({ oldText, newText }) => <div data-testid="diff">{oldText}|{newText}</div> }));
vi.mock('../hooks/useSyncIntegrity', () => ({ useSyncIntegrity: () => ({}), syncBadgeStatus: () => 'unknown' }));
vi.mock('../components/sharing/ShareToButton', () => ({ default: () => null }));
vi.mock('../components/sharing/SyncToPeerButton', () => ({ default: () => null }));
vi.mock('../components/sync/SyncBadge', () => ({ default: () => null }));

import * as api from '../services/api';
import Universes from './Universes';

const dupGroup = {
  normalizedName: 'clandestiny',
  records: [
    { id: 'u-new', name: 'Clandestiny', updatedAt: '2026-05-22T00:00:00Z', counts: { characters: 5, places: 2, objects: 1, categories: 4 }, linkedSeriesCount: 1, linkedCollectionItemCount: 3 },
    { id: 'u-old', name: 'Clandestiny', updatedAt: '2026-05-11T00:00:00Z', counts: { characters: 1, places: 0, objects: 0, categories: 4 }, linkedSeriesCount: 0, linkedCollectionItemCount: 0 },
  ],
};

const renderPage = async () => {
  const result = render(<MemoryRouter><Universes /></MemoryRouter>);
  await act(async () => {});
  return result;
};

beforeEach(() => {
  vi.clearAllMocks();
  api.listUniverseSummaries.mockResolvedValue([
    { id: 'u-new', name: 'Clandestiny', createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z' },
    { id: 'u-old', name: 'Clandestiny', createdAt: '2026-05-11T00:00:00Z', updatedAt: '2026-05-11T00:00:00Z' },
  ]);
  api.listPipelineSeriesSummaries.mockResolvedValue([]);
  api.listMediaCollections.mockResolvedValue([]);
  api.listUniverseDuplicates.mockResolvedValue({ groups: [dupGroup] });
});

describe('Universes page — duplicate detection', () => {
  it('shows the universe list error and retries without rendering the empty copy', async () => {
    api.listUniverseSummaries.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce([]);
    const user = userEvent.setup();
    await renderPage();
    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load universes');
    expect(screen.queryByText(/No universes yet/)).not.toBeInTheDocument();
    await user.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText(/No universes yet/)).toBeInTheDocument();
  });

  it('shows and retries a failed series-count read independently', async () => {
    api.listPipelineSeriesSummaries.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce([]);
    const user = userEvent.setup();
    await renderPage();
    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load series counts');
    expect(screen.getAllByText('—').length).toBeGreaterThan(0);
    await user.click(screen.getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
  });

  it('shows and retries a failed thumbnail collection read without blocking universes', async () => {
    api.listMediaCollections.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce([]);
    const user = userEvent.setup();
    await renderPage();
    expect(await screen.findByRole('alert')).toHaveTextContent('Could not load universe thumbnails');
    expect(screen.getAllByText('Clandestiny').length).toBeGreaterThan(0);
    await user.click(screen.getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
  });

  it('shows a banner when duplicate-named universes are detected', async () => {
    await renderPage();
    await waitFor(() => expect(screen.getByText(/1 duplicate-named universe detected/)).toBeInTheDocument());
    expect(screen.getByText(/2 copies/)).toBeInTheDocument();
  });

  it('hides the banner when no duplicates exist', async () => {
    api.listUniverseDuplicates.mockResolvedValue({ groups: [] });
    await renderPage();
    await waitFor(() => expect(screen.getByText('Universes')).toBeInTheDocument());
    expect(screen.queryByText(/duplicate-named/)).not.toBeInTheDocument();
  });

  it('opens the merge modal, previews, executes with field choices, and re-scans', async () => {
    api.previewUniverseMerge.mockResolvedValue({
      conflicts: [{ field: 'starterPrompt', survivorValue: 'A', loserValue: 'B' }],
      cascade: { seriesToRepoint: [{ id: 's1' }], loserCollectionItemCount: 3 },
    });
    api.mergeUniverses.mockResolvedValue({ merged: true });
    // After the merge tombstones the loser, the re-scan returns no duplicates.
    api.listUniverseDuplicates
      .mockResolvedValueOnce({ groups: [dupGroup] })
      .mockResolvedValue({ groups: [] });

    const user = userEvent.setup();
    await renderPage();
    await waitFor(() => expect(screen.getByText(/2 copies/)).toBeInTheDocument());

    await user.click(screen.getByRole('button', { name: /Merge…/ }));
    await waitFor(() => expect(api.previewUniverseMerge).toHaveBeenCalledWith({ survivorId: 'u-new', loserId: 'u-old' }, expect.anything()));
    await waitFor(() => expect(screen.getByText('starterPrompt')).toBeInTheDocument());
    expect(screen.getByText(/child series re-pointed/)).toBeInTheDocument();

    await user.click(screen.getByRole('button', { name: /^Merge$/ }));
    await waitFor(() => expect(api.mergeUniverses).toHaveBeenCalledWith(
      { survivorId: 'u-new', loserId: 'u-old', fieldChoices: { starterPrompt: 'survivor' } },
      expect.anything(),
    ));
    // Banner clears after the re-scan finds nothing.
    await waitFor(() => expect(screen.queryByText(/duplicate-named/)).not.toBeInTheDocument());
  });

  it('dismisses a group via "Keep both" for the session', async () => {
    const user = userEvent.setup();
    await renderPage();
    await waitFor(() => expect(screen.getByText(/duplicate-named/)).toBeInTheDocument());

    await user.click(screen.getByRole('button', { name: /Keep both/ }));
    await waitFor(() => expect(screen.queryByText(/duplicate-named/)).not.toBeInTheDocument());
  });
});

describe('Universes page — row thumbnail', () => {
  beforeEach(() => {
    api.listUniverseDuplicates.mockResolvedValue({ groups: [] });
  });

  it('shows the projected canon count and base style image, matching the detail page', async () => {
    api.listUniverseSummaries.mockResolvedValue([
      { id: 'u1', name: 'Neon Expanse', styleImageRef: 'base-style.png', canonCount: 7, updatedAt: '2026-06-01T00:00:00Z' },
    ]);
    // A media-collection image exists too, but the base style image wins.
    api.listMediaCollections.mockResolvedValue([
      { universeId: 'u1', items: [{ kind: 'image', ref: 'contact-sheet.png', addedAt: '2026-06-10T00:00:00Z' }] },
    ]);
    const { container } = await renderPage();
    await waitFor(() => expect(screen.getAllByText('Neon Expanse').length).toBeGreaterThan(0));
    const img = container.querySelector('img');
    expect(img).toBeTruthy();
    expect(screen.getAllByText('7').length).toBeGreaterThan(0);
    expect(img.getAttribute('src')).toContain('base-style.png');
    expect(img.getAttribute('src')).not.toContain('contact-sheet.png');
  });

  it('falls back to the media image when the summary has no style image', async () => {
    api.listUniverseSummaries.mockResolvedValue([
      { id: 'u3', name: 'Void', styleImageRef: null, updatedAt: '2026-06-01T00:00:00Z' },
    ]);
    api.listMediaCollections.mockResolvedValue([
      { universeId: 'u3', items: [{ kind: 'image', ref: 'media.png', addedAt: '2026-06-10T00:00:00Z' }] },
    ]);
    const { container } = await renderPage();
    await waitFor(() => expect(screen.getAllByText('Void').length).toBeGreaterThan(0));
    expect(container.querySelector('img').getAttribute('src')).toContain('media.png');
  });

  it('falls back to the latest media-collection image when no base style image exists', async () => {
    api.listUniverseSummaries.mockResolvedValue([
      { id: 'u2', name: 'Reality', updatedAt: '2026-06-01T00:00:00Z' },
    ]);
    api.listMediaCollections.mockResolvedValue([
      { universeId: 'u2', items: [{ kind: 'image', ref: 'fallback.png', addedAt: '2026-06-10T00:00:00Z' }] },
    ]);
    const { container } = await renderPage();
    await waitFor(() => expect(screen.getAllByText('Reality').length).toBeGreaterThan(0));
    const img = container.querySelector('img');
    expect(img.getAttribute('src')).toContain('fallback.png');
  });
});

describe('Universes page — factual badge (#7616)', () => {
  beforeEach(() => {
    api.listUniverseDuplicates.mockResolvedValue({ groups: [] });
    api.listMediaCollections.mockResolvedValue([]);
  });

  it('badges only the universes whose factual flag is set', async () => {
    api.listUniverseSummaries.mockResolvedValue([
      { id: 'universe-reality', name: 'Reality', factual: true, updatedAt: '2026-06-02T00:00:00Z', createdAt: '2026-06-02T00:00:00Z' },
      { id: 'u-fiction', name: 'Example Universe', factual: false, updatedAt: '2026-06-01T00:00:00Z', createdAt: '2026-06-01T00:00:00Z' },
    ]);
    await renderPage();
    await waitFor(() => expect(screen.getAllByText('Example Universe').length).toBeGreaterThan(0));
    // One badge per layout (desktop table + mobile cards), and none for the
    // fiction world — the regression is a badge keyed on truthiness of a field
    // the summary projection omits, which would mark every universe real.
    expect(screen.getAllByText('Real')).toHaveLength(2);
  });
});