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

36.5 KB
Raw Blame
import { StrictMode, useLayoutEffect } from 'react';
import { createMemoryRouter, RouterProvider } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor, fireEvent, within, act } from '@testing-library/react';
import { awaitPageLoaded } from '../test/pageLoadBarrier';
import { BedAudio } from '../components/media/VideoTimelineLanes';

// The editor's pure rules live in lib/videoTimelineModel.js and its blocks in
// components/media/VideoTimelineLanes.jsx, both tested there. What only exists
// here is the page's own wiring: which lanes render, what counts as a missing
// source, and the lane caps.

vi.mock('@dnd-kit/sortable', async () => {
  const actual = await vi.importActual('@dnd-kit/sortable');
  return {
    ...actual,
    useSortable: () => ({
      attributes: {}, listeners: {}, setNodeRef: () => {}, transform: null, transition: null, isDragging: false,
    }),
  };
});

const toastError = vi.hoisted(() => vi.fn());
vi.mock('../components/ui/Toast', () => ({
  default: Object.assign(vi.fn(), { error: toastError, success: vi.fn() }),
}));

vi.mock('../hooks/useSseProgress', () => ({
  useSseProgress: () => ({ latest: null, closed: false }),
  isTerminalSseFrame: () => false,
}));

const api = vi.hoisted(() => ({
  project: null,
  getTimelineProject: vi.fn(),
  getGalleryImages: vi.fn(),
  history: [],
  gallery: [],
  music: { tracks: [] },
  galleryThrows: false,
  updateTimelineProject: vi.fn(async () => ({ updatedAt: 'u2' })),
  listHistory: vi.fn(),
  listMusic: vi.fn(),
}));

vi.mock('../services/api', () => ({
  getTimelineProject: (...args) => api.getTimelineProject(...args),
  listVideoHistory: (...args) => api.listHistory(...args),
  getGalleryImages: (...args) => api.getGalleryImages(...args),
  listMusicLibrary: (...args) => api.listMusic(...args),
  updateTimelineProject: (...args) => api.updateTimelineProject(...args),
  renderTimelineProject: async () => ({ jobId: 'j1' }),
}));

vi.mock('../services/apiImageVideo', () => ({
  listImageGalleryPage: async ({ limit, offset }) => ({ items: api.gallery.slice(offset, offset + limit), total: api.gallery.length, offset, limit }),
}));

const VideoTimelineEditor = (await import('./VideoTimelineEditor')).default;

const CLIP_A = '11111111-1111-4111-8111-111111111111';

const project = (over = {}) => ({
  id: 'p1', name: 'Example Project', updatedAt: 'u1', schemaVersion: 2,
  segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [], ...over,
});

const clipSegment = { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 1 };
const stillSegment = { type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3, fadeInSec: 0, fadeOutSec: 0 };
const overlayEntry = { type: 'image', assetKind: 'images', assetFile: 'logo.png', startSec: 0, durationSec: 2, x: 0, y: 0, width: 0.25, opacity: 1, fadeInSec: 0, fadeOutSec: 0 };
const bedEntry = { assetKind: 'music', assetFile: 'bed.mp3', startSec: 0, offsetSec: 0, durationSec: 4, volume: 1, fadeInSec: 0, fadeOutSec: 0 };

beforeEach(() => {
  Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1024 });
  window.matchMedia = vi.fn((query) => ({
    matches: query === '(min-width: 64rem)' && window.innerWidth >= 1024,
    media: query,
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
  }));
  toastError.mockClear();
  api.project = project();
  api.history = [{ id: CLIP_A, prompt: 'A dramatic sunrise', filename: 'a.mp4', thumbnail: 'a.jpg', width: 1920, height: 1080, fps: 24, numFrames: 96 }];
  api.gallery = [{ filename: 'plate.png' }, { filename: 'logo.png' }];
  api.music = { tracks: [{ filename: 'bed.mp3', label: 'Bed' }] };
  api.galleryThrows = false;
  api.listHistory.mockReset().mockImplementation(async () => api.history);
  api.listMusic.mockReset().mockImplementation(async () => api.music);
  api.getTimelineProject.mockReset().mockImplementation(async () => api.project);
  api.getGalleryImages.mockReset().mockImplementation(async (filenames) => {
    if (api.galleryThrows) throw new Error('network');
    return api.gallery.filter(row => filenames.includes(row.filename));
  });
  api.updateTimelineProject.mockReset().mockResolvedValue({ updatedAt: 'u2' });
});

const renderEditorRoute = ({ strict = false } = {}) => {
  const router = createMemoryRouter([
    { path: '/media/timeline/:projectId', element: <VideoTimelineEditor /> },
    { path: '/media/timeline', element: <div>Project index</div> },
  ], { initialEntries: ['/media/timeline/p1'] });
  const provider = <RouterProvider router={router} />;
  return { ...render(strict ? <StrictMode>{provider}</StrictMode> : provider), router };
};

const renderEditor = async () => {
  renderEditorRoute();
  await awaitPageLoaded('Loading timeline project');
};

const deferred = () => {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
  return { promise, resolve, reject };
};

describe('route and refresh ownership', () => {
  it('keeps B lanes and its save token after a late A read completes', async () => {
    const oldRead = deferred();
    api.getTimelineProject.mockImplementation((id) => id === 'p1' ? oldRead.promise : Promise.resolve(project({
      id: 'p2', name: 'Example B', updatedAt: 'b1', segments: [{ ...stillSegment, assetFile: 'logo.png' }],
    })));
    const view = renderEditorRoute();

    await act(async () => { await view.router.navigate('/media/timeline/p2'); });
    expect(await screen.findByRole('textbox', { name: 'Project name' })).toHaveValue('Example B');
    await act(async () => { oldRead.resolve(project({ name: 'Example A', segments: [stillSegment] })); });

    expect(api.getTimelineProject).toHaveBeenCalledWith('p1', { silent: true });
    expect(api.getTimelineProject).toHaveBeenCalledWith('p2', { silent: true });
    expect(view.router.state.location.pathname).toBe('/media/timeline/p2');
    expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Example B');
    expect(screen.getByRole('button', { name: 'Remove logo.png from timeline' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Remove plate.png from timeline' })).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    view.unmount();
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledOnce());
    expect(api.updateTimelineProject).toHaveBeenCalledWith('p2', expect.objectContaining({
      expectedUpdatedAt: 'b1',
      segments: [expect.objectContaining({ assetFile: 'logo.png' }), expect.objectContaining({ clipId: CLIP_A })],
    }), { silent: true });
  });

  it('holds navigation until all A edits save through their tail, then gives B its own token', async () => {
    const firstSave = deferred();
    api.getTimelineProject.mockImplementation(async (id) => project({
      id, name: id === 'p1' ? 'Example A' : 'Example B', updatedAt: id === 'p1' ? 'a1' : 'b1',
    }));
    api.updateTimelineProject.mockImplementationOnce(() => firstSave.promise).mockResolvedValue({ updatedAt: 'a3' });
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledOnce(), { timeout: 1500 });
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    await act(async () => { await view.router.navigate('/media/timeline/p2'); });
    expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Example A');
    await act(async () => { firstSave.resolve({ updatedAt: 'a2' }); });
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(2));
    await waitFor(() => expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Example B'));
    expect(screen.getByText(/Add clips, stills, overlays and audio/)).toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    expect(api.updateTimelineProject.mock.calls[1]).toEqual(['p1', expect.objectContaining({
      expectedUpdatedAt: 'a2', segments: [expect.objectContaining({ clipId: CLIP_A }), expect.objectContaining({ clipId: CLIP_A })],
    }), { silent: true }]);
    expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Example B');
    const pendingUnload = new Event('beforeunload', { cancelable: true });
    window.dispatchEvent(pendingUnload);
    expect(pendingUnload.defaultPrevented).toBe(true);

    view.unmount();
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(3));
    expect(api.updateTimelineProject.mock.calls[2]).toEqual(['p2', expect.objectContaining({
      expectedUpdatedAt: 'b1', segments: [expect.objectContaining({ clipId: CLIP_A })],
    }), { silent: true }]);
  });

  it('keeps the current StrictMode load pending when the disposed setup completes', async () => {
    const disposedRead = deferred();
    const currentRead = deferred();
    api.getTimelineProject.mockImplementationOnce(() => disposedRead.promise).mockImplementationOnce(() => currentRead.promise);
    const view = renderEditorRoute({ strict: true });
    expect(api.getTimelineProject).toHaveBeenCalledTimes(2);

    await act(async () => { disposedRead.resolve(project({ name: 'Obsolete project', updatedAt: 'old' })); });
    expect(screen.getByLabelText('Loading timeline project')).toBeInTheDocument();
    await act(async () => { currentRead.resolve(project({ name: 'Current project', updatedAt: 'current' })); });
    expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Current project');
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    view.unmount();
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledOnce());
    expect(api.updateTimelineProject.mock.calls[0][1].expectedUpdatedAt).toBe('current');
  });

  it('drops a superseded refresh that was already waiting for its image catalogue', async () => {
    const oldGallery = deferred();
    const secondSave = deferred();
    api.getTimelineProject.mockResolvedValueOnce(project({ segments: [clipSegment] }))
      .mockResolvedValueOnce(project({ name: 'Obsolete project', updatedAt: 'old', segments: [stillSegment] }))
      .mockResolvedValueOnce(project({ name: 'Current project', updatedAt: 'current', segments: [{ ...stillSegment, assetFile: 'logo.png' }] }));
    api.getGalleryImages.mockResolvedValueOnce([])
      .mockImplementationOnce(() => oldGallery.promise)
      .mockResolvedValueOnce([{ filename: 'logo.png' }]);
    const conflict = Object.assign(new Error('conflict'), { code: 'CONFLICT' });
    api.updateTimelineProject.mockRejectedValueOnce(conflict).mockImplementationOnce(() => secondSave.promise);
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    fireEvent.click(screen.getByRole('button', { name: 'Render' }));
    fireEvent.click(screen.getByRole('button', { name: 'Render' }));
    await waitFor(() => expect(api.getGalleryImages).toHaveBeenCalledTimes(2));
    await act(async () => { secondSave.reject(conflict); });
    expect(await screen.findByRole('textbox', { name: 'Project name' })).toHaveValue('Current project');
    await act(async () => { oldGallery.resolve([]); });

    expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Current project');
    expect(screen.getByRole('button', { name: 'Remove logo.png from timeline' })).toBeInTheDocument();
    expect(screen.queryByText('(missing)')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    view.unmount();
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(3));
    expect(api.updateTimelineProject.mock.calls[2][1].expectedUpdatedAt).toBe('current');
  });

  it('ignores an obsolete same-project reload error after a newer conflict reload succeeds', async () => {
    const oldReload = deferred();
    const currentReload = deferred();
    api.getTimelineProject.mockResolvedValueOnce(project({ segments: [clipSegment] }))
      .mockImplementationOnce(() => oldReload.promise)
      .mockImplementationOnce(() => currentReload.promise);
    const conflict = Object.assign(new Error('conflict'), { code: 'CONFLICT' });
    api.updateTimelineProject.mockRejectedValueOnce(conflict).mockRejectedValueOnce(conflict);
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    // Both render attempts flush a save and start a conflict refresh.
    fireEvent.click(screen.getByRole('button', { name: 'Render' }));
    fireEvent.click(screen.getByRole('button', { name: 'Render' }));
    await waitFor(() => expect(api.getTimelineProject).toHaveBeenCalledTimes(3));
    await act(async () => { currentReload.resolve(project({ name: 'Current project', updatedAt: 'current' })); });
    await act(async () => { oldReload.reject(new Error('Obsolete failure')); });

    expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Current project');
    expect(screen.queryByText('Obsolete failure')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    view.unmount();
    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(3));
    expect(api.updateTimelineProject.mock.calls[2][1].expectedUpdatedAt).toBe('current');
  });
});

describe('pending lane saves', () => {
  it('flushes the latest edit exactly once when unmounted before the debounce', async () => {
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');

    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    view.unmount();

    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(1));
    expect(api.updateTimelineProject.mock.calls[0][1].segments).toHaveLength(1);
    expect(api.updateTimelineProject.mock.calls[0][1].segments[0].clipId).toBe(CLIP_A);
  });

  it('does not save on unmount when no lane edit is pending', async () => {
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');

    view.unmount();

    expect(api.updateTimelineProject).not.toHaveBeenCalled();
  });

  it('prevents unload only while a debounced save is pending', async () => {
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));

    const pendingUnload = new Event('beforeunload', { cancelable: true });
    window.dispatchEvent(pendingUnload);
    expect(pendingUnload.defaultPrevented).toBe(true);

    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(1), { timeout: 1500 });
    const savedUnload = new Event('beforeunload', { cancelable: true });
    window.dispatchEvent(savedUnload);
    expect(savedUnload.defaultPrevented).toBe(false);
    view.unmount();
  });

  it('keeps the leave warning after a save fails', async () => {
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    api.updateTimelineProject.mockRejectedValueOnce(new Error('offline'));
    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));

    await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledOnce(), { timeout: 1500 });
    const failedSaveUnload = new Event('beforeunload', { cancelable: true });
    window.dispatchEvent(failedSaveUnload);
    expect(failedSaveUnload.defaultPrevented).toBe(true);
    expect(toastError).toHaveBeenCalledWith('Save failed: offline');
    view.unmount();
  });
});

describe('lane visibility', () => {
  it('shows the empty-timeline hint only when EVERY lane is empty', async () => {
    await renderEditor();
    expect(screen.getByText(/Add clips, stills, overlays and audio/)).toBeInTheDocument();
  });

  it('renders the free lanes for a project whose video lane is empty', async () => {
    // Overlays and beds added to an empty project would otherwise be
    // unselectable and unremovable on reload.
    api.project = project({ overlays: [overlayEntry], audio: { clipVolume: 1, tracks: [bedEntry] } });
    await renderEditor();

    expect(screen.queryByText(/Add clips, stills, overlays and audio/)).not.toBeInTheDocument();
    expect(screen.getByText('Add a clip or a still from the library')).toBeInTheDocument();
    expect(await screen.findByRole('button', { name: 'Remove logo.png from timeline' })).toBeInTheDocument();
    expect(await screen.findByRole('button', { name: 'Remove bed.mp3 from timeline' })).toBeInTheDocument();
  });

  it('summarises every lane in the header, not just the video lane', async () => {
    api.project = project({ segments: [clipSegment, stillSegment], overlays: [overlayEntry], audio: { clipVolume: 1, tracks: [bedEntry] } });
    await renderEditor();
    expect(screen.getByText(/2 segments · 1 overlays · 1 beds/)).toBeInTheDocument();
  });
});

describe('missing-source detection', () => {
  it('flags a still whose gallery file is gone', async () => {
    api.gallery = [{ filename: 'logo.png' }];
    api.project = project({ segments: [stillSegment] });
    await renderEditor();
    expect(screen.getByText('(missing)')).toBeInTheDocument();
  });

  it('says nothing when the gallery fetch FAILED — an unloaded catalogue is not evidence of absence', async () => {
    // Collapsing a failed fetch into "empty" would mark every still and
    // overlay missing even though the server can still render them.
    api.galleryThrows = true;
    api.project = project({ segments: [stillSegment], overlays: [overlayEntry] });
    await renderEditor();
    expect(screen.queryByText('(missing)')).not.toBeInTheDocument();
  });

  it('does not flag an asset kind it has no catalogue for', async () => {
    api.project = project({ audio: { clipVolume: 1, tracks: [{ ...bedEntry, assetKind: 'audio', assetFile: 'vo.wav' }] } });
    await renderEditor();
    expect(screen.queryByText('(missing)')).not.toBeInTheDocument();
  });
});

describe('header layout — mobile overflow regression (#5425)', () => {
  it('header container carries flex-wrap so it can reflow on narrow viewports', async () => {
    await renderEditor();
    // The header must be able to reflow the right-side buttons at narrow widths
    // without allowing the project-name input to preserve its min-content width.
    const titleInput = screen.getByRole('textbox', { name: 'Project name' });
    const titleRow = titleInput.parentElement;
    const headerDiv = titleRow?.parentElement;
    expect(headerDiv).toHaveClass('flex', 'flex-wrap');
    expect(headerDiv).toContainElement(screen.getByRole('button', { name: 'Hide library' }));
    expect(headerDiv).toContainElement(screen.getByRole('button', { name: 'Render' }));
    expect(titleRow).toHaveClass('flex-1', 'min-w-[120px]');
    expect(titleInput).toHaveClass('flex-1', 'min-w-0');
  });

  it('summary span is hidden on small screens (carries hidden sm:inline)', async () => {
    api.project = project({ segments: [clipSegment], overlays: [overlayEntry], audio: { clipVolume: 1, tracks: [bedEntry] } });
    await renderEditor();
    const summarySpan = screen.getByText(/1 segments · 1 overlays · 1 beds/);
    expect(summarySpan).toHaveClass('hidden', 'sm:inline');
  });
});

describe('workspace layout — mobile library regression (#5424)', () => {
  it('starts with the library hidden and keeps the workspace before it when opened', async () => {
    Object.defineProperty(window, 'innerWidth', { configurable: true, value: 375 });
    await renderEditor();

    const showLibrary = screen.getByRole('button', { name: 'Show library' });
    const workspace = screen.getByRole('button', { name: 'Play' }).parentElement?.parentElement;
    const inspector = screen.getByText('Inspector').parentElement;
    expect(screen.queryByRole('tablist', { name: 'Clip library' })).not.toBeInTheDocument();
    expect(showLibrary).toHaveAttribute('aria-expanded', 'false');
    expect(showLibrary).toHaveAttribute('aria-controls', 'timeline-library');
    expect(workspace?.parentElement).toHaveClass('lg:grid-cols-[1fr_240px]');
    expect(workspace).toHaveClass('order-1', 'lg:order-2');
    expect(workspace?.compareDocumentPosition(inspector) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();

    fireEvent.click(showLibrary);

    // The scroll bar sits between the tablist and the panel the page sizes.
    const library = screen.getByRole('tablist', { name: 'Clip library' }).closest('#timeline-library');
    expect(screen.getByRole('button', { name: 'Hide library' })).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Hide library' })).toHaveAttribute('aria-expanded', 'true');
    expect(workspace?.parentElement).toHaveClass('lg:grid-cols-[260px_1fr_240px]');
    expect(library).toHaveAttribute('id', 'timeline-library');
    expect(library).toHaveClass('order-2', 'lg:order-1');
    expect(workspace?.compareDocumentPosition(library) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();

    fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
    await waitFor(() => expect(
      screen.getByRole('button', { name: 'Remove A dramatic sunrise from timeline' }),
    ).toBeInTheDocument());

    const mountedLibrary = library;
    Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1024 });
    fireEvent(window, new Event('resize'));
    expect(screen.getByRole('tablist', { name: 'Clip library' }).closest('#timeline-library')).toBe(mountedLibrary);
  });

  it('keeps the desktop library visible in the original left-rail grid position', async () => {
    await renderEditor();

    const library = screen.getByRole('tablist', { name: 'Clip library' }).closest('#timeline-library');
    const workspace = screen.getByRole('button', { name: 'Play' }).parentElement?.parentElement;
    expect(screen.getByRole('button', { name: 'Hide library' })).toBeInTheDocument();
    expect(workspace?.parentElement).toHaveClass('lg:grid-cols-[260px_1fr_240px]');
    expect(workspace).toHaveClass('order-1', 'lg:order-2');
    expect(library).toHaveClass('order-2', 'lg:order-1');
    expect(workspace?.compareDocumentPosition(library) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();

    fireEvent.click(screen.getByRole('button', { name: 'Hide library' }));
    expect(workspace?.parentElement).toHaveClass('lg:grid-cols-[1fr_240px]');
  });

  it('keeps one tab stop on the Clip library bar and switches it with arrow keys (#7244)', async () => {
    await renderEditor();

    const tablist = screen.getByRole('tablist', { name: 'Clip library' });
    const [clips, stills, audio] = within(tablist).getAllByRole('tab');
    expect(clips).toHaveAttribute('tabindex', '0');
    expect(stills).toHaveAttribute('tabindex', '-1');
    expect(audio).toHaveAttribute('tabindex', '-1');

    clips.focus();
    fireEvent.keyDown(clips, { key: 'ArrowRight' });
    // The arrow key moves the tab stop and switches the library pane together.
    expect(stills).toHaveAttribute('aria-selected', 'true');
    expect(stills).toHaveAttribute('tabindex', '0');
    expect(document.activeElement).toBe(stills);
    expect(screen.getByPlaceholderText('Search images…')).toBeInTheDocument();
    // The stills pane fires its gallery fetch on selection — settle it so the
    // update doesn't land outside act.
    await act(async () => {});
  });
});

// The Stills tab arrives with the GALLERY, which `renderEditor` does not wait
// for — it only waits out the "Loading project…" text. A synchronous getByRole
// therefore races the gallery render, and the heavier the fixture the likelier
// it loses: the cap test below mounts 51 gallery entries and flaked on CI's
// shared runners while passing locally every time. findByRole waits.
describe('lane caps', () => {
  it('refuses an add past the overlay cap with a message naming the lane', async () => {
    // One entry over the cap 400s every later debounced save, with nothing
    // telling the user which lane to trim.
    api.project = project({
      segments: [clipSegment],
      overlays: Array.from({ length: 50 }, (_, i) => ({ ...overlayEntry, assetFile: `logo${i}.png` })),
    });
    api.gallery = [{ filename: 'plate.png' }, ...Array.from({ length: 50 }, (_, i) => ({ filename: `logo${i}.png` }))];
    await renderEditor();

    fireEvent.click(await screen.findByRole('tab', { name: /Stills/ }));
    fireEvent.click((await screen.findAllByRole('button', { name: 'Overlay' }))[0]);

    expect(toastError).toHaveBeenCalledWith(expect.stringContaining('Overlay lane limit reached (50)'));
  });

  it('allows the add when the lane is under the cap', async () => {
    api.project = project({ segments: [clipSegment] });
    await renderEditor();

    fireEvent.click(await screen.findByRole('tab', { name: /Stills/ }));
    fireEvent.click((await screen.findAllByRole('button', { name: 'Overlay' }))[0]);

    expect(toastError).not.toHaveBeenCalled();
    await waitFor(() => expect(screen.getByRole('button', { name: 'Remove plate.png from timeline' })).toBeInTheDocument());
  });
});

// The saved lanes hold what the author ASKED for; the export resolves them
// against the real sources (a shortened history clip, a short music file). The
// preview must play that resolved timeline, or its cuts, fades and overlays run
// on a different clock than the render (#10866).
describe('source-aware playback', () => {
  const seekTo = (seconds) => fireEvent.change(screen.getByRole('slider', { name: 'Playhead position' }), { target: { value: String(seconds) } });

  it('advances past a clip whose source is shorter than its authored trim, matching the export', async () => {
    // Authored 0-8s with 3s+3s fades, but the history entry is 1s long: the
    // export renders 1s with the fades refit to 0.5s+0.5s.
    api.history = [{ ...api.history[0], numFrames: 24, fps: 24 }];
    api.project = project({
      segments: [{ ...clipSegment, outSec: 8, fadeInSec: 3, fadeOutSec: 3 }, stillSegment],
      overlays: [{ ...overlayEntry, startSec: 0, durationSec: 10, fadeOutSec: 2 }],
    });
    await renderEditor();

    // Total is 1s clip + 3s still, not 8 + 3.
    expect(screen.getByRole('slider', { name: 'Playhead position' })).toHaveAttribute('max', '4');

    // Half a second in, the refit fade is already at full level: no scrim.
    seekTo(0.5);
    expect(screen.queryByTestId('fade-scrim')).not.toBeInTheDocument();

    // The next cut lands at 1s, so the still is up at 1.5s.
    const previewStill = () => document.querySelector('img.object-contain[src="/data/images/plate.png"]');
    expect(previewStill()).toBeNull();
    seekTo(1.5);
    expect(previewStill()).not.toBeNull();

    // The overlay's 10s window is clamped to the 4s timeline, so its fade-out
    // starts at 2s and is half spent at 3s.
    seekTo(3);
    expect(Number(screen.getByTestId('overlay-preview').style.opacity)).toBeCloseTo(0.5);
  });

  it('keeps the authored spans when the history clip has no frame metadata', async () => {
    api.history = [{ ...api.history[0], numFrames: undefined }];
    api.project = project({ segments: [{ ...clipSegment, outSec: 8, fadeInSec: 3 }] });
    await renderEditor();
    expect(screen.getByRole('slider', { name: 'Playhead position' })).toHaveAttribute('max', '8');
  });

  describe('bed audio', () => {
    const shortBed = { ...bedEntry, durationSec: 10, fadeInSec: 4, fadeOutSec: 4 };
    // The lane block is the one carrying an inline width; a selected bed's
    // inspector repeats the filename.
    const bedBlock = () => screen.getAllByText('bed.mp3').map((node) => node.parentElement).find((node) => node.style.width);
    const reportBedLength = (el, seconds) => {
      Object.defineProperty(el, 'duration', { configurable: true, value: seconds });
      // No act here: the early-metadata fixture calls this inside render's act; test-side callers use reportBedLengthInAct.
      // Real loadedmetadata leaves HAVE_METADATA available to a late listener.
      Object.defineProperty(el, 'readyState', { configurable: true, value: 1 });
      el.dispatchEvent(new Event('loadedmetadata'));
    };
    const reportBedLengthInAct = (el, seconds) => { act(() => reportBedLength(el, seconds)); };

    it('recovers metadata reported before the bed listener is installed', async () => {
      const onDuration = vi.fn();
      const registry = new Map();
      function EarlyMetadata() {
        useLayoutEffect(() => {
          reportBedLength(document.querySelector('audio'), 2);
        }, []);
        return <BedAudio trackKey="bed-1" assetId="music/bed.mp3" src="/data/music/bed.mp3" registry={registry} onDuration={onDuration} />;
      }
      await act(async () => { render(<EarlyMetadata />); });
      expect(onDuration).toHaveBeenCalledWith('music/bed.mp3', 2);
    });

    it('plays a short file on the fade envelope the export builds once its length loads', async () => {
      api.project = project({ segments: [clipSegment], audio: { clipVolume: 1, tracks: [shortBed] } });
      const { container } = renderEditorRoute();
      await awaitPageLoaded('Loading timeline project');
      const el = container.querySelector('audio');

      // Until the length is known the authored placement stands.
      expect(bedBlock().style.width).toBe('600px');

      reportBedLengthInAct(el, 2);
      // Metadata updates React state; wait for the measured span to render.
      await waitFor(() => expect(bedBlock().style.width).toBe('120px'));

      // 2s file, 4s+4s authored fades refit to 1s+1s: gain is 0.5 at 0.5s.
      seekTo(0.5);
      await waitFor(() => expect(el.volume).toBeCloseTo(0.5));

      // Past the end of the file the bed is inactive.
      seekTo(3);
      await waitFor(() => expect(el.volume).toBe(0));
    });

    it('ignores a length that is not finite and never persists a measured one', async () => {
      api.project = project({ segments: [clipSegment], audio: { clipVolume: 1, tracks: [shortBed] } });
      const { container, unmount } = renderEditorRoute();
      await awaitPageLoaded('Loading timeline project');
      const el = container.querySelector('audio');

      reportBedLengthInAct(el, Infinity);
      expect(bedBlock().style.width).toBe('600px');

      reportBedLengthInAct(el, 2);
      unmount();
      // Nothing was edited, so nothing is saved; the measured span is a view.
      expect(api.updateTimelineProject).not.toHaveBeenCalled();
    });

    it('forgets a removed bed so a later placement of the file starts from its own span', async () => {
      api.project = project({ segments: [clipSegment], audio: { clipVolume: 1, tracks: [shortBed] } });
      const { container } = renderEditorRoute();
      await awaitPageLoaded('Loading timeline project');
      reportBedLengthInAct(container.querySelector('audio'), 2);
      // Metadata updates React state; wait for the measured span to render.
      await waitFor(() => expect(bedBlock().style.width).toBe('120px'));

      fireEvent.click(screen.getByRole('button', { name: 'Remove bed.mp3 from timeline' }));
      expect(container.querySelector('audio')).toBeNull();

      fireEvent.click(screen.getByRole('tab', { name: /Audio/ }));
      fireEvent.click(screen.getByRole('button', { name: 'Add' }));
      // The fresh placement is the 4s default (the timeline is 4s) until ITS
      // element reports a length — the earlier measurement must not leak in.
      expect(bedBlock().style.width).toBe('240px');
    });
  });
});


describe('timeline navigation after save failure', () => {
  it('retains failed edits, guards internal navigation, and retries the latest snapshot before proceeding', async () => {
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    vi.useFakeTimers();
    try {
      api.updateTimelineProject.mockRejectedValueOnce(new Error('offline'));
      fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
      await act(async () => { await vi.advanceTimersByTimeAsync(400); });
      expect(screen.getByRole('status', { name: 'Timeline save status' })).toHaveTextContent('Save failed: offline');
      fireEvent.click(screen.getByRole('button', { name: 'Back to projects' }));
      expect(screen.getByRole('button', { name: 'Keep editing' })).toBeInTheDocument();
      expect(view.router.state.location.pathname).toBe('/media/timeline/p1');
      fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));
      fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
      fireEvent.click(screen.getByRole('button', { name: 'Back to projects' }));
      const retry = deferred();
      api.updateTimelineProject.mockReturnValueOnce(retry.promise);
      await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry save' })); });
      expect(api.updateTimelineProject.mock.calls[1][1]).toMatchObject({ expectedUpdatedAt: 'u1', segments: [expect.any(Object), expect.any(Object)] });
      const unload = new Event('beforeunload', { cancelable: true });
      window.dispatchEvent(unload);
      expect(unload.defaultPrevented).toBe(true);
      expect(view.router.state.location.pathname).toBe('/media/timeline/p1');
      await act(async () => { retry.resolve({ updatedAt: 'u2' }); });
      expect(screen.getByText('Project index')).toBeInTheDocument();
      expect(api.updateTimelineProject).toHaveBeenCalledTimes(2);
    } finally { vi.useRealTimers(); }
  });

  it('keeps conflicting edits and requires explicit discard to leave without another write', async () => {
    const view = renderEditorRoute();
    await awaitPageLoaded('Loading timeline project');
    vi.useFakeTimers();
    try {
      api.updateTimelineProject.mockRejectedValueOnce(Object.assign(new Error('conflict'), { code: 'CONFLICT' }));
      fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
      await act(async () => { await vi.advanceTimersByTimeAsync(400); });
      expect(screen.getByRole('status', { name: 'Timeline save status' })).toHaveTextContent('Your edits are retained');
      expect(api.getTimelineProject).toHaveBeenCalledOnce();
      await act(async () => { await view.router.navigate('/media/timeline'); });
      expect(view.router.state.location.pathname).toBe('/media/timeline/p1');
      await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Discard' })); });
      expect(screen.getByText('Project index')).toBeInTheDocument();
      await act(async () => { await vi.advanceTimersByTimeAsync(400); });
      expect(api.updateTimelineProject).toHaveBeenCalledOnce();
    } finally { vi.useRealTimers(); }
  });
});

describe('clip and audio library load failures', () => {
  it('shows a failed clip load with Retry instead of the empty copy, and recovers on retry', async () => {
    // Two rejections: the initial load and the first Retry both fail, so the
    // error must stay visible and actionable until a retry actually succeeds.
    const failure = new Error('network');
    api.listHistory.mockRejectedValueOnce(failure).mockRejectedValueOnce(failure);
    await renderEditor();

    const notice = await screen.findByRole('status');
    expect(notice).toHaveTextContent("Couldn't load your clips.");
    expect(screen.queryByText(/No clips/)).not.toBeInTheDocument();

    fireEvent.click(within(notice).getByRole('button', { name: 'Retry' }));
    await waitFor(() => expect(screen.getByRole('button', { name: 'Retry' })).toBeEnabled());
    expect(screen.getByRole('status')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
    expect(await screen.findByRole('button', { name: 'Add to timeline' })).toBeInTheDocument();
    expect(screen.queryByRole('status')).not.toBeInTheDocument();
  });

  it('tells a successful empty audio library apart from a failed one', async () => {
    api.music = { tracks: [] };
    await renderEditor();
    fireEvent.click(within(screen.getByRole('tablist', { name: 'Clip library' })).getAllByRole('tab')[2]);
    expect(screen.getByText('No audio in the shared music library.')).toBeInTheDocument();
    expect(screen.queryByRole('status')).not.toBeInTheDocument();
  });

  it('shows a failed audio load with Retry, then lists the tracks once the retry succeeds', async () => {
    api.listMusic.mockRejectedValueOnce(new Error('network'));
    await renderEditor();
    fireEvent.click(within(screen.getByRole('tablist', { name: 'Clip library' })).getAllByRole('tab')[2]);

    const notice = await screen.findByRole('status');
    expect(notice).toHaveTextContent("Couldn't load the shared music library.");
    expect(screen.queryByText('No audio in the shared music library.')).not.toBeInTheDocument();

    fireEvent.click(within(notice).getByRole('button', { name: 'Retry' }));
    expect(await screen.findByText('Bed')).toBeInTheDocument();
    expect(screen.queryByRole('status')).not.toBeInTheDocument();
  });
});