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

26.8 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router';

// Spy on navigation so the "Remix into…" handoff can assert the target route +
// the generic `remix.ingredientIds` state payload. MemoryRouter still supplies
// the real Link/router context.
const navigateMock = vi.hoisted(() => vi.fn());
vi.mock('react-router', async (importOriginal) => {
  const actual = await importOriginal();
  return { ...actual, useNavigate: () => navigateMock };
});

vi.mock('../services/apiCatalog', () => ({
  listCatalogIngredients: vi.fn(),
  createCatalogIngredient: vi.fn(),
  deleteCatalogIngredient: vi.fn(),
  linkCatalogIngredient: vi.fn(),
  getCatalogStats: vi.fn(),
  getCatalogFacets: vi.fn(),
  rerunCatalogMigration: vi.fn(),
}));

// Bulk "Add to universe/series" sources its menu from the FULL live lists (so
// empty universes/series are valid destinations), not the facet arrays.
vi.mock('../services/apiUniverseBuilder', () => ({
  listUniverseNames: vi.fn(),
}));
vi.mock('../services/apiPipeline', () => ({
  listPipelineSeriesNames: vi.fn(),
}));

vi.mock('../components/ui/Toast', () => ({
  default: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
}));

// useCatalogTypes (via Catalog) fetches the type registry — mock the API so a
// user-defined type surfaces as a filter chip + dropdown option.
vi.mock('../services/apiCatalogTypes', () => ({
  listCatalogTypes: vi.fn(),
  createCatalogType: vi.fn(),
  updateCatalogType: vi.fn(),
  deleteCatalogType: vi.fn(),
}));

// MediaImage pulls in the socket service; stub it to a plain <img> so the card
// thumbnail's src/alt are assertable without the socket wiring.
vi.mock('../components/MediaImage', () => ({
  default: ({ src, alt, ...rest }) => <img src={src} alt={alt} {...rest} />,
}));

import Catalog from './Catalog';
import {
  listCatalogIngredients,
  createCatalogIngredient,
  deleteCatalogIngredient,
  linkCatalogIngredient,
  getCatalogStats,
  getCatalogFacets,
  rerunCatalogMigration,
} from '../services/apiCatalog';
import { listCatalogTypes } from '../services/apiCatalogTypes';
import { listUniverseNames } from '../services/apiUniverseBuilder';
import { listPipelineSeriesNames } from '../services/apiPipeline';
import toast from '../components/ui/Toast';

const sample = [
  { id: 'i-1', name: 'Echo Saint', type: 'character', payload: { physicalDescription: 'A wiry figure in a long coat.' }, tags: ['noir'] },
  { id: 'i-2', name: 'Old Harbor', type: 'place', payload: { description: 'Brine and rust.' }, tags: [] },
];

function LocationProbe() {
  const { pathname, search } = useLocation();
  return <div data-testid="catalog-location">{`${pathname}${search}`}</div>;
}

const renderCatalog = (initialEntry = '/catalog') => render(
  <MemoryRouter initialEntries={[initialEntry]}>
    <Catalog />
    <LocationProbe />
  </MemoryRouter>,
);

const sampleFacets = {
  types: [{ type: 'character', count: 1 }, { type: 'place', count: 1 }],
  universes: [{ refId: 'u-1', name: 'Echo Saints', count: 1 }],
  series: [{ refId: 's-1', name: 'Season 1', universeId: 'u-1', count: 1 }],
  tags: [{ tag: 'noir', count: 1 }],
  unlinkedCount: 1,
  orphanedCount: 0,
  total: 2,
};

beforeEach(() => {
  vi.clearAllMocks();
  listCatalogIngredients.mockResolvedValue({ items: sample, nextOffset: sample.length });
  linkCatalogIngredient.mockResolvedValue({ success: true });
  getCatalogStats.mockResolvedValue({ total: 2, byType: { character: 1, place: 1 } });
  getCatalogFacets.mockResolvedValue(sampleFacets);
  listUniverseNames.mockResolvedValue([{ id: 'u-1', name: 'Echo Saints' }]);
  listPipelineSeriesNames.mockResolvedValue([{ id: 's-1', name: 'Season 1', universeId: 'u-1' }]);
  rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 0 } });
  // Default: system registry only (the hook merges with the static fallback).
  listCatalogTypes.mockResolvedValue({ types: [] });
});

describe('Catalog page', () => {
  it('opens catalog type settings in a deep-linkable feature drawer', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    expect(screen.queryByRole('dialog', { name: 'Catalog settings' })).toBeNull();

    fireEvent.click(screen.getByRole('button', { name: 'Catalog settings' }));

    expect(await screen.findByRole('dialog', { name: 'Catalog settings' })).toBeTruthy();
    expect(screen.getByText(/Define custom ingredient types for the Catalog/i)).toBeTruthy();
    expect(screen.getByTestId('catalog-location').textContent).toBe('/catalog?settings=1');

    fireEvent.click(screen.getByRole('button', { name: 'Close settings' }));
    await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Catalog settings' })).toBeNull());
    expect(screen.getByTestId('catalog-location').textContent).toBe('/catalog');
  });

  it('opens catalog type settings from the compatibility deep link', async () => {
    renderCatalog('/catalog?settings=1');
    expect(await screen.findByRole('dialog', { name: 'Catalog settings' })).toBeTruthy();
  });

  it('renders the fetched ingredient cards with snippet + count', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    expect(screen.getByText('Old Harbor')).toBeTruthy();
    expect(screen.getByText(/wiry figure in a long coat/i)).toBeTruthy();
    // Total count comes from stats.
    expect(screen.getByText(/2 ingredients/i)).toBeTruthy();
  });

  it('filters by type when a type chip is clicked', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByRole('button', { name: /^Character/i }));
    await waitFor(() => {
      expect(listCatalogIngredients).toHaveBeenLastCalledWith(
        expect.objectContaining({ type: 'character' }),
      );
    });
  });

  it('debounces search input into the list fetch', async () => {
    vi.useFakeTimers();
    renderCatalog();
    // Drain the initial mount fetch.
    await act(async () => { await vi.runOnlyPendingTimersAsync(); });

    fireEvent.change(screen.getByLabelText(/Search catalog/i), { target: { value: 'harbor' } });
    // Before the debounce window elapses, q hasn't been pushed yet.
    expect(listCatalogIngredients).not.toHaveBeenCalledWith(
      expect.objectContaining({ q: 'harbor' }),
    );
    await act(async () => { await vi.advanceTimersByTimeAsync(350); });
    expect(listCatalogIngredients).toHaveBeenLastCalledWith(
      expect.objectContaining({ q: 'harbor' }),
    );
    vi.useRealTimers();
  });

  it('creates an ingredient and optimistically prepends it', async () => {
    createCatalogIngredient.mockResolvedValue({
      id: 'i-3', name: 'New Idea', type: 'idea', payload: { summary: 'spark' }, tags: [],
    });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByRole('button', { name: /^New$/i }));
    fireEvent.change(screen.getByLabelText(/^Name$/i), { target: { value: 'New Idea' } });

    await act(async () => {
      fireEvent.submit(screen.getByLabelText(/^Name$/i).closest('form'));
    });

    expect(createCatalogIngredient).toHaveBeenCalledWith(
      expect.objectContaining({ name: 'New Idea' }),
      { silent: true },
    );
    await waitFor(() => expect(screen.getByText('New Idea')).toBeTruthy());
    // Assert the PREPEND contract (not just existence): the new card must
    // render before the pre-existing "Echo Saint" card in document order.
    const newEl = screen.getByText('New Idea');
    const echoEl = screen.getByText('Echo Saint');
    expect(newEl.compareDocumentPosition(echoEl) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(toast.success).toHaveBeenCalled();
  });

  it('two-click-arms then deletes a card, removing it locally', async () => {
    deleteCatalogIngredient.mockResolvedValue({ success: true });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    // Arm: the per-card Delete button reveals the Yes/No confirm.
    fireEvent.click(screen.getByLabelText(/Delete Echo Saint/i));
    const yesBtn = await screen.findByRole('button', { name: /^Yes$/i });

    await act(async () => { fireEvent.click(yesBtn); });

    await waitFor(() => expect(screen.queryByText('Echo Saint')).toBeNull());
    expect(screen.getByText('Old Harbor')).toBeTruthy();
    expect(deleteCatalogIngredient).toHaveBeenCalledWith('i-1', { silent: true });
  });

  it('restores the row when delete fails', async () => {
    deleteCatalogIngredient.mockRejectedValue(new Error('nope'));
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByLabelText(/Delete Echo Saint/i));
    const yesBtn = await screen.findByRole('button', { name: /^Yes$/i });
    await act(async () => { fireEvent.click(yesBtn); });

    await waitFor(() => expect(toast.error).toHaveBeenCalled());
    // Optimistic removal is rolled back.
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
  });

  it('shows the empty state when the catalog has no ingredients', async () => {
    listCatalogIngredients.mockResolvedValue({ items: [] });
    getCatalogStats.mockResolvedValue({ total: 0, byType: {} });
    renderCatalog();
    await waitFor(() => expect(screen.getByText(/Your catalog is empty/i)).toBeTruthy());
  });

  it('surfaces a toast when the list fetch fails', async () => {
    listCatalogIngredients.mockRejectedValue(new Error('load failed'));
    renderCatalog();
    await waitFor(() => expect(toast.error).toHaveBeenCalledWith('load failed'));
  });

  it('syncs from universes and reloads the list when items were promoted', async () => {
    rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 3 } });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    const callsBefore = listCatalogIngredients.mock.calls.length;

    await act(async () => {
      fireEvent.click(screen.getByRole('button', { name: /Sync from Universes/i }));
    });

    expect(rerunCatalogMigration).toHaveBeenCalledWith(
      expect.objectContaining({ force: true, silent: true }),
    );
    // A non-zero promote count reloads the list + stats so new items appear.
    await waitFor(() => expect(listCatalogIngredients.mock.calls.length).toBeGreaterThan(callsBefore));
    expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Synced 3 canon items/i));
  });

  it('reports an up-to-date catalog without reloading when nothing was promoted', async () => {
    rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 0 } });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    const callsBefore = listCatalogIngredients.mock.calls.length;

    await act(async () => {
      fireEvent.click(screen.getByRole('button', { name: /Sync from Universes/i }));
    });

    expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/already up to date/i));
    expect(listCatalogIngredients.mock.calls.length).toBe(callsBefore);
  });

  it('surfaces an error toast (not a success) when the sync reports errors', async () => {
    rerunCatalogMigration.mockResolvedValue({ stats: { promoted: 0, errors: 2 } });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    await act(async () => {
      fireEvent.click(screen.getByRole('button', { name: /Sync from Universes/i }));
    });

    expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/Sync hit 2 errors/i));
    expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/up to date/i));
  });

  it('renders a card thumbnail when the ingredient has a thumbnail key', async () => {
    listCatalogIngredients.mockResolvedValue({
      items: [{ ...sample[0], thumbnailKey: 'hero.png' }],
    });
    renderCatalog();
    const img = await screen.findByAltText('Echo Saint');
    expect(img.getAttribute('src')).toBe('/data/image-thumbnails/hero.webp');
  });

  it('multi-selects ingredients and remixes them into Story Builder with a generic state payload', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    // No action bar until something is selected.
    expect(screen.queryByText(/selected$/i)).toBeNull();

    fireEvent.click(screen.getByLabelText('Select Echo Saint'));
    fireEvent.click(screen.getByLabelText('Select Old Harbor'));
    await waitFor(() => expect(screen.getByText('2 selected')).toBeTruthy());

    // Open the Remix menu and choose Story Builder.
    fireEvent.click(screen.getByRole('button', { name: /Remix into/i }));
    fireEvent.click(await screen.findByRole('button', { name: 'Story Builder' }));

    expect(navigateMock).toHaveBeenCalledWith('/story-builder', {
      state: { remix: { ingredientIds: ['i-1', 'i-2'] } },
    });
  });

  it('toggling a selection checkbox does not navigate to the card detail', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    fireEvent.click(screen.getByLabelText('Select Echo Saint'));
    // Selection is a distinct gesture from opening the card — no navigation.
    expect(navigateMock).not.toHaveBeenCalled();
    expect(screen.getByText('1 selected')).toBeTruthy();
  });

  it('drops a deleted ingredient from the selection so the count stays honest', async () => {
    deleteCatalogIngredient.mockResolvedValue({ success: true });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByLabelText('Select Echo Saint'));
    fireEvent.click(screen.getByLabelText('Select Old Harbor'));
    expect(screen.getByText('2 selected')).toBeTruthy();

    fireEvent.click(screen.getByLabelText(/Delete Echo Saint/i));
    const yesBtn = await screen.findByRole('button', { name: /^Yes$/i });
    await act(async () => { fireEvent.click(yesBtn); });

    await waitFor(() => expect(screen.getByText('1 selected')).toBeTruthy());
  });

  it('renders a user-defined type as a filter chip from the merged registry', async () => {
    listCatalogTypes.mockResolvedValue({
      types: [{ id: 'faction', label: 'Faction', system: false, badgeColor: 'bg-gray-500/20 text-gray-300 border-gray-500/40', primaryContentKey: 'creed', primaryContentLabel: 'Creed', snippetFallbackKeys: ['creed'], fields: [] }],
    });
    renderCatalog();
    // The built-in chips render synchronously; the user chip appears after the
    // type-registry fetch resolves.
    await waitFor(() => expect(screen.getByRole('button', { name: /^Faction/i })).toBeTruthy());
  });

  it('filters by universe via the dropdown, passing a ref filter to the list fetch', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.change(screen.getByLabelText(/^Universe$/i), { target: { value: 'u-1' } });
    await waitFor(() => {
      expect(listCatalogIngredients).toHaveBeenLastCalledWith(
        expect.objectContaining({ refKind: 'universe', refId: 'u-1' }),
      );
    });
  });

  it('filters to a source scrap via `?scrap=`, shows the filter banner, and clears it on demand (#7617)', async () => {
    renderCatalog('/catalog?scrap=cat-scrap-1');
    await waitFor(() => {
      expect(listCatalogIngredients).toHaveBeenLastCalledWith(
        expect.objectContaining({ scrapId: 'cat-scrap-1' }),
      );
    });
    expect(screen.getByText(/Filtered by source/)).toBeTruthy();

    fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
    await waitFor(() => expect(screen.getByTestId('catalog-location').textContent).toBe('/catalog'));
    expect(screen.queryByText(/Filtered by source/)).toBeNull();
  });

  it('shows the source scrap title in the filter banner when it arrives via router state', async () => {
    render(
      <MemoryRouter initialEntries={[{ pathname: '/catalog', search: '?scrap=cat-scrap-1', state: { scrapTitle: 'Notebook Page Three' } }]}>
        <Catalog />
      </MemoryRouter>,
    );
    await waitFor(() => expect(screen.getByText('Notebook Page Three')).toBeTruthy());
  });

  it('paginates with "Load more", appending the next page at the right offset', async () => {
    const firstPage = Array.from({ length: 60 }, (_, i) => ({
      id: `p-${i}`, name: `Item ${i}`, type: 'idea', payload: {}, tags: [],
    }));
    listCatalogIngredients
      .mockResolvedValueOnce({ items: firstPage, nextOffset: 60 })
      .mockResolvedValueOnce({ items: [{ id: 'p-60', name: 'Item 60', type: 'idea', payload: {}, tags: [] }], nextOffset: 61 });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Item 0')).toBeTruthy());

    const loadMore = screen.getByRole('button', { name: /Load more/i });
    await act(async () => { fireEvent.click(loadMore); });

    expect(listCatalogIngredients).toHaveBeenLastCalledWith(
      expect.objectContaining({ offset: 60 }),
    );
    await waitFor(() => expect(screen.getByText('Item 60')).toBeTruthy());
  });

  it('drops a stale Load more page when filters change mid-flight', async () => {
    const firstPage = Array.from({ length: 60 }, (_, i) => ({
      id: `pg-${i}`, name: `Page ${i}`, type: 'idea', payload: {}, tags: [],
    }));
    let resolveStale;
    const stalePromise = new Promise((r) => { resolveStale = r; });
    listCatalogIngredients.mockImplementation((params = {}) => {
      if (params.offset === 60 && !params.type) return stalePromise;          // the in-flight loadMore
      if (params.type === 'character') {
        return Promise.resolve({ items: [{ id: 'flt', name: 'Filtered Only', type: 'character', payload: {}, tags: [] }], nextOffset: 1 });
      }
      return Promise.resolve({ items: firstPage, nextOffset: 60 });           // initial full page
    });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Page 0')).toBeTruthy());

    fireEvent.click(screen.getByRole('button', { name: /Load more/i }));      // offset 60 → pending
    fireEvent.click(screen.getByRole('button', { name: /^Character/i }));     // filter changes mid-flight
    await waitFor(() => expect(screen.getByText('Filtered Only')).toBeTruthy());

    await act(async () => {
      resolveStale({ items: [{ id: 'stale', name: 'Stale Page Item', type: 'idea', payload: {}, tags: [] }], nextOffset: 61 });
    });
    // The stale page must NOT leak into the now-character-filtered grid.
    expect(screen.queryByText('Stale Page Item')).toBeNull();
    expect(screen.getByText('Filtered Only')).toBeTruthy();
  });

  it('switches to the Albums view and lazy-loads the Raw album', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByRole('button', { name: /^Albums$/i }));
    // Raw album is pinned + default-expanded → it fetches the unlinked set, and
    // the live universe album header shows from /facets.
    await waitFor(() => expect(screen.getByText('Unsorted / Raw')).toBeTruthy());
    expect(screen.getByText('Echo Saints')).toBeTruthy();
    await waitFor(() => {
      expect(listCatalogIngredients).toHaveBeenCalledWith(
        expect.objectContaining({ unlinked: true }),
      );
    });
  });

  it('paginates an album past one page with its own Load more', async () => {
    const rawPage = Array.from({ length: 60 }, (_, i) => ({
      id: `raw-${i}`, name: `Raw ${i}`, type: 'idea', payload: {}, tags: [],
    }));
    // Grid loads return the default sample; the Raw album (unlinked) gets a full
    // first page then a short second page.
    listCatalogIngredients.mockImplementation((params = {}) => {
      if (params.unlinked && params.offset === 0) return Promise.resolve({ items: rawPage, nextOffset: 60 });
      if (params.unlinked && params.offset === 60) return Promise.resolve({ items: [{ id: 'raw-60', name: 'Raw 60', type: 'idea', payload: {}, tags: [] }], nextOffset: 61 });
      return Promise.resolve({ items: sample, nextOffset: sample.length });
    });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByRole('button', { name: /^Albums$/i }));
    await waitFor(() => expect(screen.getByText('Raw 0')).toBeTruthy());

    const loadMore = await screen.findByRole('button', { name: /Load more/i });
    await act(async () => { fireEvent.click(loadMore); });

    expect(listCatalogIngredients).toHaveBeenCalledWith(
      expect.objectContaining({ unlinked: true, offset: 60 }),
    );
    await waitFor(() => expect(screen.getByText('Raw 60')).toBeTruthy());
  });

  it('bulk-places the selection into a universe with type-derived roles', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());

    fireEvent.click(screen.getByLabelText('Select Echo Saint'));
    fireEvent.click(screen.getByLabelText('Select Old Harbor'));
    expect(screen.getByText('2 selected')).toBeTruthy();

    fireEvent.click(screen.getByRole('button', { name: /Add to universe\/series/i }));
    // The menu lazy-loads the full universe/series lists; wait for it to populate.
    const item = await screen.findByRole('button', { name: 'Echo Saints' });
    await act(async () => { fireEvent.click(item); });

    // character → cast-character, place → cast-place.
    expect(linkCatalogIngredient).toHaveBeenCalledWith(
      'i-1', { refKind: 'universe', refId: 'u-1', role: 'cast-character' }, { silent: true },
    );
    expect(linkCatalogIngredient).toHaveBeenCalledWith(
      'i-2', { refKind: 'universe', refId: 'u-1', role: 'cast-place' }, { silent: true },
    );
    expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Added 2 ingredients to Echo Saints/i));
  });

  it('shows and retries universe and series target read errors in the add menu', async () => {
    listUniverseNames.mockRejectedValueOnce(new Error('universe offline')).mockResolvedValueOnce([]);
    listPipelineSeriesNames.mockRejectedValueOnce(new Error('series offline')).mockResolvedValueOnce([]);
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    fireEvent.click(screen.getByLabelText('Select Echo Saint'));
    fireEvent.click(screen.getByRole('button', { name: /Add to universe\/series/i }));

    await waitFor(() => expect(screen.getAllByRole('alert')).toHaveLength(2));
    expect(screen.queryByText('No universes or series yet.')).toBeNull();
    fireEvent.click(within(screen.getByText(/Could not load universes/).closest('[role="alert"]')).getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.queryByText(/Could not load universes/)).toBeNull());
    fireEvent.click(within(screen.getByText(/Could not load series/).closest('[role="alert"]')).getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
    expect(await screen.findByText('No universes or series yet.')).toBeInTheDocument();
  });

  it('scopes the Albums view to a single album when a universe is selected', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    fireEvent.click(screen.getByRole('button', { name: /^Albums$/i }));
    await waitFor(() => expect(screen.getByText('Unsorted / Raw')).toBeTruthy());

    fireEvent.change(screen.getByLabelText(/^Universe$/i), { target: { value: 'u-1' } });
    // Raw/Orphaned/other albums collapse to just the selected universe's album.
    await waitFor(() => expect(screen.queryByText('Unsorted / Raw')).toBeNull());
    expect(screen.getByText('Echo Saints')).toBeTruthy();
  });

  it('shows an inline error + Retry (no retry loop) when an album load fails', async () => {
    listCatalogIngredients.mockImplementation((params = {}) => {
      if (params.unlinked) return Promise.reject(new Error('boom'));
      return Promise.resolve({ items: sample, nextOffset: sample.length });
    });
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    fireEvent.click(screen.getByRole('button', { name: /^Albums$/i }));

    // The default-expanded Raw album fails → inline error + Retry, not a loop.
    expect(await screen.findByRole('button', { name: /^Retry$/i })).toBeTruthy();
    const unlinkedCalls = () => listCatalogIngredients.mock.calls.filter(([p]) => p?.unlinked).length;
    const before = unlinkedCalls();
    await act(async () => { await new Promise((r) => setTimeout(r, 50)); });
    expect(unlinkedCalls()).toBe(before); // bounded — no tight retry loop
  });

  it('lists empty (link-less) universes in the Add-to menu so they can be seeded', async () => {
    // A brand-new universe with zero catalog links is absent from /facets but
    // must still be a valid placement target.
    listUniverseNames.mockResolvedValue([
      { id: 'u-1', name: 'Echo Saints' },
      { id: 'u-empty', name: 'Fresh Empty Universe' },
    ]);
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    fireEvent.click(screen.getByLabelText('Select Echo Saint'));
    fireEvent.click(screen.getByRole('button', { name: /Add to universe\/series/i }));

    expect(await screen.findByRole('button', { name: 'Fresh Empty Universe' })).toBeTruthy();
  });

  // These buttons hide the tail of their label on a narrow viewport, so the full
  // wording has to live in aria-label or the accessible name silently shortens
  // with the screen. jsdom applies no CSS, so the existing name-based queries
  // elsewhere in this file would still pass with the aria-label deleted — only
  // an explicit attribute assertion catches that. The paired textContent check
  // holds the visible text to a prefix of the name (WCAG 2.5.3 label-in-name).
  it('keeps the full accessible name on buttons whose visible label shortens on a narrow viewport', async () => {
    renderCatalog();
    await waitFor(() => expect(screen.getByText('Echo Saint')).toBeTruthy());
    fireEvent.click(screen.getByLabelText('Select Echo Saint'));

    for (const [visiblePrefix, fullName] of [
      ['Sync', 'Sync from Universes'],
      ['Remix', 'Remix into…'],
      ['Add', 'Add to universe/series…'],
    ]) {
      const btn = screen.getByRole('button', { name: fullName });
      expect(btn.getAttribute('aria-label')).toBe(fullName);
      expect(btn.textContent.startsWith(visiblePrefix)).toBe(true);
    }
  });

  it('renders section navigation tabs linking to Catalog, Casting, Environments, and Objects', async () => {
    renderCatalog();
    await act(async () => {});
    expect(screen.getByRole('tab', { name: 'Catalog' })).toHaveAttribute('aria-selected', 'true');
    expect(screen.getByRole('tab', { name: 'Casting' })).toHaveAttribute('aria-selected', 'false');
    expect(screen.getByRole('tab', { name: 'Environments' })).toHaveAttribute('aria-selected', 'false');
    expect(screen.getByRole('tab', { name: 'Objects' })).toHaveAttribute('aria-selected', 'false');
  });
});