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

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

const socketHarness = vi.hoisted(() => ({ handlers: new Map(), emit: vi.fn() }));

vi.mock('../services/socket', () => ({ default: {
  connected: true,
  emit: (event, payload) => {
    socketHarness.emit(event, payload);
    if (event !== 'generated-preview:open') return;
    const opened = {
      requestId: payload.requestId,
      sessionId: '11111111-1111-4111-8111-111111111111',
      durationSec: 20, fps: 30, width: 1280, height: 720,
      audio: payload.withAudio ? 'ready' : 'none',
      revision: payload.revision,
    };
    for (const handler of socketHarness.handlers.get('generated-preview:opened') || []) handler(opened);
    for (const handler of socketHarness.handlers.get('generated-preview:frame') || []) {
      handler({ ...opened, generation: 0, mime: 'image/jpeg', data: btoa('frame') });
    }
  },
  on: vi.fn((event, handler) => {
    const handlers = socketHarness.handlers.get(event) || new Set();
    handlers.add(handler);
    socketHarness.handlers.set(event, handlers);
  }),
  off: vi.fn((event, handler) => socketHarness.handlers.get(event)?.delete(handler)),
} }));

vi.mock('../services/api', () => ({
  buildCodeAnimationPrompt: vi.fn(),
  generateCodeAnimationBrief: vi.fn(),
  getCodeAnimationJob: vi.fn(),
  getCodeAnimationOptions: vi.fn(),
  generateCodeAnimationSoundtrack: vi.fn(),
  listMusicEngines: vi.fn().mockResolvedValue({ engines: [] }),
  previewMusicPrompt: vi.fn(),
  getFilmStyle: vi.fn(),
  listFilmStyles: vi.fn(),
  listCodeAnimationJobPage: vi.fn().mockResolvedValue({ items: [], total: 0, counts: { running: 0, completed: 0 }, nextCursor: null }),
  codeAnimationPosterUrl: (id, version) => `/posters/${id}.jpg?v=${version}`,
  requestCodeAnimationPoster: vi.fn(),
  listMoodBoardNames: vi.fn(),
  listTracks: vi.fn().mockResolvedValue([]),
  listUniverseNames: vi.fn(),
  listUniverseStyles: vi.fn(),
  startCodeAnimationGeneration: vi.fn(),
  uploadFile: vi.fn(),
  uploadGalleryVideo: vi.fn(),
}));
vi.mock('../components/videoGen/GalleryVideoPicker', () => ({
  default: ({ open, onSelect, onClose }) => (open ? (
    <button type="button" onClick={() => { onSelect({ filename: 'take.mp4', prompt: '(no prompt)', previewUrl: '/data/video-thumbnails/take.jpg' }); onClose(); }}>Choose example video</button>
  ) : null),
}));
vi.mock('../hooks/useProviderModels', () => ({
  default: () => ({
    providers: [{ id: 'api-1', name: 'Example API', type: 'api', enabled: true }],
    selectedProviderId: 'api-1',
    selectedModel: '',
    availableModels: [],
    setSelectedProviderId: vi.fn(),
    setSelectedModel: vi.fn(),
    loading: false,
  }),
}));

import CodeAnimation from './CodeAnimation';
import {
  buildCodeAnimationPrompt,
  generateCodeAnimationBrief,
  getCodeAnimationJob,
  listCodeAnimationJobPage,
  requestCodeAnimationPoster,
  getCodeAnimationOptions,
  getFilmStyle,
  listFilmStyles,
  listMoodBoardNames,
  listTracks,
  listUniverseNames,
  listUniverseStyles,
  startCodeAnimationGeneration,
} from '../services/api';

const OPTIONS = {
  aspectRatios: ['16:9', '9:16'],
  resolutions: ['720p', '1080p'],
  renderers: ['auto', 'canvas2d'],
  limits: { durationMin: 3, durationMax: 180, fpsOptions: [24, 30, 60], referenceImagesMax: 8, seedIdeaMax: 2000 },
  messages: { ready: 'r', record: 'rec', recorded: 'done', progress: 'p', error: 'e' },
  audioGlobal: 'ANIMATION_AUDIO_URL',
  audioExtensions: ['mp3', 'wav'],
};

const FILM_STYLES = [
  { id: 'blueprint-draft', label: 'Blueprint draft', category: 'drawing', summary: 'White lines on a deep blue sheet.', nativeMoves: [{ name: 'Exploded assembly' }] },
];
const BLUEPRINT = {
  ...FILM_STYLES[0],
  nativeMoves: [{ name: 'Exploded assembly', how: 'Pull apart.', fitsContentLike: ['product anatomy', 'teardowns'] }],
};

function CurrentRoute() {
  return <output data-testid="route">{useLocation().pathname}</output>;
}

const renderPage = async (initialEntry = '/code-animation', navLinks = []) => {
  const result = render(
    <MemoryRouter initialEntries={[initialEntry]}>
      <CurrentRoute />
      {navLinks.map((to) => <Link key={to} to={to}>Open {to}</Link>)}
      <Routes>
        <Route path="/code-animation" element={<CodeAnimation />} />
        <Route path="/code-animation/gallery" element={<CodeAnimation />} />
        <Route path="/code-animation/drafts/:draftId" element={<CodeAnimation />} />
        <Route path="/code-animation/:jobId" element={<CodeAnimation />} />
      </Routes>
    </MemoryRouter>,
  );
  await act(async () => {});
  return result;
};

const emitSocket = async (event, payload) => {
  await act(async () => {
    for (const handler of socketHarness.handlers.get(event) || []) handler(payload);
  });
};

const changeVisibility = async (value) => {
  await act(async () => {
    Object.defineProperty(document, 'visibilityState', { configurable: true, value });
    document.dispatchEvent(new Event('visibilitychange'));
  });
};

const runningJob = {
  id: 'job-1', status: 'running', title: 'Example animation',
  input: { title: 'Example animation', concept: 'A lantern rises' },
  prompt: 'Example prompt', createdAt: '2026-01-01T00:00:00.000Z',
};
const completedJob = {
  ...runningJob, status: 'completed', html: '<html><body>Finished animation</body></html>',
  audioUrl: '/api/uploads/example-audio.mp3',
  frame: { width: 1280, height: 720, durationSeconds: 20, fps: 30 },
};

describe('Code Animation page', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
    socketHarness.handlers.clear();
    listCodeAnimationJobPage.mockResolvedValue({ items: [], total: 0, counts: { running: 0, completed: 0 }, nextCursor: null });
    localStorage.clear();
    getCodeAnimationOptions.mockResolvedValue(OPTIONS);
    listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
    listUniverseStyles.mockResolvedValue([{ id: 'u1', name: 'Example Universe', influences: { embrace: ['ink wash'], avoid: ['photorealism'] } }]);
    listMoodBoardNames.mockResolvedValue([{ id: 'b1', name: 'Dusk' }]);
    listTracks.mockResolvedValue([]);
    listFilmStyles.mockResolvedValue(FILM_STYLES);
    getFilmStyle.mockResolvedValue(BLUEPRINT);
    buildCodeAnimationPrompt.mockResolvedValue({
      prompt: 'You are an award-winning creative coder…',
      attachments: [{ label: 'Night markets', origin: 'universe', url: '/data/image-refs/style-ref.png' }],
      frame: { width: 1920, height: 1080, fps: 30, durationSeconds: 20 },
      audioUrl: null,
      moodBoardId: 'b1',
    });
  });

  afterEach(() => vi.useRealTimers());

  it('creates distinct UUID draft routes and restores each brief independently', async () => {
    const user = userEvent.setup();
    const firstRender = await renderPage();
    const firstRoute = screen.getByTestId('route').textContent;
    expect(firstRoute).toMatch(/^\/code-animation\/drafts\/[0-9a-f-]{36}$/);
    await user.type(screen.getByLabelText(/what happens/i), 'First project');
    firstRender.unmount();

    const secondRender = await renderPage();
    expect(screen.getByTestId('route').textContent).not.toBe(firstRoute);
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('');
    await user.type(screen.getByLabelText(/what happens/i), 'Second project');
    secondRender.unmount();

    await renderPage(firstRoute, ['/code-animation/drafts/11111111-1111-4111-8111-111111111111', firstRoute]);
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('First project');
    await user.click(screen.getByRole('link', { name: 'Open /code-animation/drafts/11111111-1111-4111-8111-111111111111' }));
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('');
    await user.click(screen.getByRole('link', { name: `Open ${firstRoute}` }));
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('First project');
    expect(getCodeAnimationJob).not.toHaveBeenCalled();
    expect(startCodeAnimationGeneration).not.toHaveBeenCalled();
  });

  it('restores a routed job, updates its preview on its event, and never polls', async () => {
    getCodeAnimationJob.mockResolvedValue(runningJob);
    await renderPage('/code-animation/job-1');
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
    expect(screen.getByLabelText(/^title/i)).toHaveValue('Example animation');
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('A lantern rises');
    expect(screen.getByLabelText('Generated prompt')).toHaveValue('Example prompt');
    vi.useFakeTimers();
    await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
    vi.useRealTimers();

    await emitSocket('code-animation:changed', { id: 'unrelated-job' });
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
    await emitSocket('code-animation:changed', { id: 'job-1', kind: 'poster' });
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
    getCodeAnimationJob.mockResolvedValue(completedJob);
    await emitSocket('code-animation:changed', { id: 'job-1' });
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
    expect(await screen.findByRole('button', { name: 'Run with audio' })).toBeInTheDocument();
    await userEvent.setup().click(screen.getByRole('button', { name: 'Preview without audio' }));
    const frame = await screen.findByTitle('Code animation preview');
    expect(frame.tagName).toBe('IMG');
    expect(document.querySelector('iframe')).toBeNull();
    const open = socketHarness.emit.mock.calls.filter(([event]) => event === 'generated-preview:open').at(-1)[1];
    expect(open).toEqual(expect.objectContaining({ kind: 'code-animation', jobId: 'job-1', withAudio: false }));
    expect(open.html).toBeUndefined();

    // Terminal records still reconcile: a missing output can be discovered later.
    getCodeAnimationJob.mockResolvedValue({ ...completedJob, status: 'failed', error: 'Output missing', html: null });
    await emitSocket('code-animation:changed', { id: 'job-1' });
    expect(screen.getByText('Generation failed: Output missing')).toBeInTheDocument();
    expect(screen.queryByTitle('Code animation preview')).not.toBeInTheDocument();
  });

  it('reconciles once per reconnect and tab re-show, including transient errors and missing jobs', async () => {
    getCodeAnimationJob.mockRejectedValueOnce(new Error('Temporary outage')).mockResolvedValue(runningJob);
    await renderPage('/code-animation/job-1');
    expect(screen.queryByText('That generation is no longer available.')).not.toBeInTheDocument();
    await emitSocket('connect');
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
    expect(screen.getByLabelText(/^title/i)).toHaveValue('Example animation');
    await changeVisibility('hidden');
    await emitSocket('code-animation:changed', { id: 'job-1' });
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
    getCodeAnimationJob.mockRejectedValueOnce({ status: 404, message: 'Missing' });
    await changeVisibility('visible');
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(3);
    expect(screen.getByText('That generation is no longer available.')).toBeInTheDocument();
    await changeVisibility('visible');
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(3);
  });

  it('offers recovery when the final event read fails without discarding the displayed job', async () => {
    getCodeAnimationJob.mockResolvedValue(runningJob);
    await renderPage('/code-animation/job-1');
    getCodeAnimationJob.mockRejectedValueOnce(new Error('Temporary outage'));
    await emitSocket('code-animation:changed', { id: 'job-1' });
    expect(screen.getByText(/displayed status may be out of date/)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Generating…' })).toBeDisabled();
    getCodeAnimationJob.mockResolvedValue(completedJob);
    await userEvent.setup().click(screen.getByRole('button', { name: 'Retry job status' }));
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(3);
    expect(await screen.findByRole('button', { name: 'Run with audio' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: 'Retry job status' })).not.toBeInTheDocument();
  });

  it('drops a pending response after selecting another job and releases listeners on unmount', async () => {
    let resolveFirst;
    getCodeAnimationJob.mockImplementationOnce(() => new Promise(resolve => { resolveFirst = resolve; }))
      .mockResolvedValue({ ...runningJob, id: 'job-2', title: 'Second animation',
        input: { title: 'Second animation', concept: 'Another scene' } });
    const view = await renderPage('/code-animation/job-1', ['/code-animation/job-2']);
    await userEvent.setup().click(screen.getByRole('link', { name: 'Open /code-animation/job-2' }));
    await waitFor(() => expect(screen.getByLabelText(/^title/i)).toHaveValue('Second animation'));
    await act(async () => resolveFirst(completedJob));
    expect(screen.getByLabelText(/^title/i)).toHaveValue('Second animation');
    expect(screen.queryByRole('button', { name: 'Run with audio' })).not.toBeInTheDocument();
    await emitSocket('code-animation:changed', { id: 'job-1' });
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
    view.unmount();
    await emitSocket('code-animation:changed', { id: 'job-2' });
    await emitSocket('connect');
    expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
  });

  it('recovers from a parseable but malformed saved draft', async () => {
    localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({
      title: { text: 'not a string' },
      audio: { filename: 42 },
      format: null,
      referenceImages: null,
    }));

    await renderPage();

    expect(screen.getByLabelText(/^title/i)).toHaveValue('');
    expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();
  });

  it('keeps the job list off Fast HTML and opens it as the Gallery tab', async () => {
    await renderPage();
    expect(listCodeAnimationJobPage).not.toHaveBeenCalled();
    await userEvent.setup().click(screen.getByRole('tab', { name: /Gallery/ }));
    expect(await screen.findByText('Animations you generate in Fast HTML appear here.')).toBeInTheDocument();
    expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(1);
  });

  it('shows saved posters, draws missing ones once each and one at a time, and labels unfinished jobs', async () => {
    listCodeAnimationJobPage.mockResolvedValue({ items: [
      { id: 'job-a', status: 'completed', title: 'With poster', posterVersion: 11, createdAt: '2026-01-03T00:00:00.000Z' },
      { id: 'job-b', status: 'completed', title: 'Needs poster', createdAt: '2026-01-02T00:00:00.000Z' },
      { id: 'job-d', status: 'completed', title: 'Also needs poster', createdAt: '2026-01-02T00:00:00.000Z' },
      { id: 'job-c', status: 'running', title: 'Still going', createdAt: '2026-01-01T00:00:00.000Z' },
    ], total: 4, counts: { running: 1, completed: 3 }, nextCursor: null });
    const draws = [];
    requestCodeAnimationPoster.mockImplementation(() => new Promise((resolve) => { draws.push(resolve); }));
    const { container } = await renderPage('/code-animation/gallery');
    await waitFor(() => expect(screen.getByRole('link', { name: /With poster/ })).toHaveAttribute('href', '/code-animation/job-a'));
    expect(container.querySelector('img[src="/posters/job-a.jpg?v=11"]')).not.toBeNull();
    expect(screen.getAllByText('Drawing thumbnail…')).toHaveLength(2);
    expect(screen.getAllByText('In progress').length).toBeGreaterThan(0);
    await waitFor(() => expect(requestCodeAnimationPoster).toHaveBeenCalledTimes(1));
    expect(requestCodeAnimationPoster).toHaveBeenCalledWith('job-b', { silent: true });
    await act(async () => draws[0]({ posterVersion: 22 }));
    expect(container.querySelector('img[src="/posters/job-b.jpg?v=22"]')).not.toBeNull();
    await waitFor(() => expect(requestCodeAnimationPoster).toHaveBeenCalledTimes(2));
    expect(requestCodeAnimationPoster).toHaveBeenLastCalledWith('job-d', { silent: true });
    await act(async () => draws[1]({ posterVersion: null }));
    expect(screen.queryByText('Drawing thumbnail…')).not.toBeInTheDocument();
    await emitSocket('code-animation:changed', { id: 'job-c' });
    expect(requestCodeAnimationPoster).toHaveBeenCalledTimes(2);
  });

  it('loads one compact page, stays idle, and refreshes on durable changes and reconnect', async () => {
    const jobs = Array.from({ length: 50 }, (_, n) => ({
      id: `job-${n}`, status: 'completed', title: `Animation ${n}`, createdAt: '2026-01-01T00:00:00.000Z',
    }));
    listCodeAnimationJobPage.mockResolvedValue({ items: jobs, total: 1000,
      counts: { running: 0, completed: 1000 }, nextCursor: 'next-page' });
    requestCodeAnimationPoster.mockResolvedValue({ posterVersion: null });
    await renderPage('/code-animation/gallery');
    await waitFor(() => expect(screen.getAllByRole('link', { name: /Animation \d+/ })).toHaveLength(50));
    expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(1);
    expect(screen.getByText('1,000 completed · 0 in progress')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Load older animations' })).toBeInTheDocument();
    vi.useFakeTimers();
    await act(async () => { vi.advanceTimersByTime(60_000); });
    vi.useRealTimers();
    expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(1);
    await act(async () => { for (const handler of socketHarness.handlers.get('code-animation:changed') || []) handler({ id: 'job-0' }); });
    await waitFor(() => expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(2));
    await act(async () => { for (const handler of socketHarness.handlers.get('connect') || []) handler(); });
    await waitFor(() => expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(3));
  });

  it('builds a universe-styled prompt that follows the universe mood board by default', async () => {
    const user = userEvent.setup();
    await renderPage();
    const build = screen.getByRole('button', { name: /build prompt/i });
    expect(build).toBeDisabled();

    await user.selectOptions(screen.getByLabelText(/universe \(sets the art style\)/i), 'u1');
    expect(screen.getByText('ink wash')).toBeInTheDocument();
    await user.type(screen.getByLabelText(/what happens/i), 'A lantern drifts over a harbor');
    await user.click(build);

    await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalledTimes(1));
    const brief = buildCodeAnimationPrompt.mock.calls[0][0];
    expect(brief).toMatchObject({ universeId: 'u1', concept: 'A lantern drifts over a harbor' });
    expect('moodBoardId' in brief).toBe(false);
    expect(await screen.findByLabelText('Generated prompt')).toHaveValue('You are an award-winning creative coder…');
    expect(screen.getByText(/Using the universe's mood board: Dusk/)).toBeInTheDocument();
    expect(screen.getByAltText('Night markets')).toHaveAttribute('src', '/data/image-refs/style-ref.png');

    // Editing the brief marks the built prompt stale until it is rebuilt.
    await user.type(screen.getByLabelText(/style refinements/i), 'more fog');
    expect(screen.getByText(/brief changed since this prompt was built/i)).toBeInTheDocument();
  });

  it('sends a picked Media History reference video with its note and reserves its image slots', async () => {
    const user = userEvent.setup();
    await renderPage();
    expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();
    await user.click(screen.getByRole('button', { name: /pick or upload a video/i }));
    await user.click(screen.getByRole('button', { name: 'Choose example video' }));
    expect(screen.getByText('Reference images (0/5)')).toBeInTheDocument();
    await user.type(screen.getByLabelText('Note for take.mp4'), 'cut rhythm');
    await user.type(screen.getByLabelText(/what happens/i), 'A lantern drifts over a harbor');
    await user.click(screen.getByRole('button', { name: /build prompt/i }));
    await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalledTimes(1));
    expect(buildCodeAnimationPrompt.mock.calls[0][0].referenceVideo).toEqual({ filename: 'take.mp4', label: 'take.mp4', note: 'cut rhythm' });
    await user.click(screen.getByRole('button', { name: 'Remove reference video' }));
    expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();
  });

  it('writes the brief from the universe and drops it into the form', async () => {
    const user = userEvent.setup();
    generateCodeAnimationBrief.mockResolvedValue({
      brief: {
        title: 'The Brass Wick',
        concept: 'Mira climbs the flooded arcade as the lamps go out.',
        cast: 'Mira — tall, oil-stained coat',
        onScreenText: '0:02 "One light remains"',
        styleNotes: 'colder blues at the climax',
      },
      moodBoardId: 'b1',
      llm: { provider: 'api-1', model: null, runId: 'run-b' },
    });
    await renderPage();
    const write = screen.getByRole('button', { name: /write brief/i });
    // Nothing to be faithful to yet — no universe, no spark, no words.
    expect(write).toBeDisabled();

    await user.selectOptions(screen.getByLabelText(/universe \(sets the art style\)/i), 'u1');
    await user.type(screen.getByLabelText(/starting idea/i), 'a chase that ends in silence');
    await user.click(write);

    await waitFor(() => expect(generateCodeAnimationBrief).toHaveBeenCalledTimes(1));
    expect(generateCodeAnimationBrief.mock.calls[0][0]).toMatchObject({
      universeId: 'u1',
      seedIdea: 'a chase that ends in silence',
      providerId: 'api-1',
      current: { title: '', concept: '' },
    });
    expect(await screen.findByLabelText(/what happens/i)).toHaveValue('Mira climbs the flooded arcade as the lamps go out.');
    expect(screen.getByLabelText(/^title/i)).toHaveValue('The Brass Wick');
    expect(screen.getByLabelText(/^characters/i)).toHaveValue('Mira — tall, oil-stained coat');
    expect(screen.getByLabelText(/on-screen text/i)).toHaveValue('0:02 "One light remains"');
    expect(screen.getByLabelText(/style refinements/i)).toHaveValue('colder blues at the climax');
  });

  it('keeps the artist\'s own style refinements and characters when the writer adds none', async () => {
    const user = userEvent.setup();
    generateCodeAnimationBrief.mockResolvedValue({
      brief: { title: '', concept: 'Fireflies gather over the water.', cast: '', onScreenText: '', styleNotes: '' },
      moodBoardId: null,
      llm: { provider: 'api-1', model: null, runId: null },
    });
    await renderPage();
    await user.type(screen.getByLabelText(/style refinements/i), 'more fog');
    await user.type(screen.getByLabelText(/^characters/i), 'Wick, a paper lantern');
    await user.type(screen.getByLabelText(/starting idea/i), 'fireflies');
    await user.click(screen.getByRole('button', { name: /write brief/i }));
    await waitFor(() => expect(generateCodeAnimationBrief).toHaveBeenCalled());
    expect(await screen.findByLabelText(/what happens/i)).toHaveValue('Fireflies gather over the water.');
    expect(screen.getByLabelText(/style refinements/i)).toHaveValue('more fog');
    expect(screen.getByLabelText(/^characters/i)).toHaveValue('Wick, a paper lantern');
  });

  it('preserves brief fields edited while Write Brief is in flight', async () => {
    const user = userEvent.setup();
    let resolveBrief;
    generateCodeAnimationBrief.mockImplementationOnce(() => new Promise((resolve) => { resolveBrief = resolve; }));
    await renderPage();
    await user.type(screen.getByLabelText(/starting idea/i), 'A quiet departure');
    await user.click(screen.getByRole('button', { name: /write brief/i }));

    await user.type(screen.getByLabelText(/^title/i), 'My title');
    await user.type(screen.getByLabelText(/what happens/i), 'My concept');
    await user.type(screen.getByLabelText(/on-screen text/i), 'My text');
    await user.type(screen.getByLabelText(/style refinements/i), 'My style');

    await act(async () => resolveBrief({
      brief: { title: 'Generated title', concept: 'Generated concept', onScreenText: 'Generated text', styleNotes: 'Generated style' },
    }));

    expect(screen.getByLabelText(/^title/i)).toHaveValue('My title');
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('My concept');
    expect(screen.getByLabelText(/on-screen text/i)).toHaveValue('My text');
    expect(screen.getByLabelText(/style refinements/i)).toHaveValue('My style');
  });

  it('keeps edits made after starting a generation when an invalidation returns its input snapshot', async () => {
    const user = userEvent.setup();
    startCodeAnimationGeneration.mockResolvedValueOnce({
      id: 'job-1', status: 'running', prompt: 'Built prompt', input: { title: '', concept: 'Original concept' },
    });
    getCodeAnimationJob.mockResolvedValue({
      id: 'job-1', status: 'running', prompt: 'Built prompt', input: { title: '', concept: 'Original concept' },
    });
    await renderPage();
    await user.type(screen.getByLabelText(/what happens/i), 'Original concept');
    await user.click(screen.getByRole('button', { name: /build prompt/i }));
    await screen.findByLabelText('Generated prompt');
    await user.click(screen.getByRole('button', { name: /generate animation/i }));
    await waitFor(() => expect(startCodeAnimationGeneration).toHaveBeenCalledOnce());
    await user.type(screen.getByLabelText(/^title/i), 'Edited after submit');

    await emitSocket('code-animation:changed', { id: 'job-1' });

    expect(screen.getByLabelText(/^title/i)).toHaveValue('Edited after submit');
  });

  it('forks a finished animation into a new, longer one that sends the original as its base', async () => {
    const user = userEvent.setup();
    getCodeAnimationJob.mockResolvedValue({ ...completedJob, audioUrl: null, input: { ...completedJob.input, format: { durationSeconds: 20 } } });
    startCodeAnimationGeneration.mockResolvedValueOnce({ id: 'job-2', status: 'running', prompt: 'Extended prompt', input: {} });
    await renderPage('/code-animation/job-1', ['/code-animation/job-2']);
    await user.click(await screen.findByRole('button', { name: /fork & extend/i }));
    expect(await screen.findByText(/Extending/)).toHaveTextContent('Extending Example animation (20s)');
    expect(screen.getByText(/not longer than the original yet/)).toBeInTheDocument();
    expect(screen.getByLabelText(/what happens/i)).toHaveValue('A lantern rises');
    const duration = screen.getByLabelText(/duration/i);
    await user.clear(duration);
    await user.type(duration, '120');
    expect(screen.queryByText(/not longer than the original yet/)).not.toBeInTheDocument();
    await user.click(screen.getByRole('button', { name: /generate animation/i }));
    await waitFor(() => expect(startCodeAnimationGeneration).toHaveBeenCalledOnce());
    expect(startCodeAnimationGeneration.mock.calls[0][0]).toMatchObject({ baseJobId: 'job-1', format: { durationSeconds: 120 } });

    // Stop extending sends a fresh animation again.
    await user.click(screen.getByRole('button', { name: 'Stop extending' }));
    expect(screen.queryByText(/Extending/)).not.toBeInTheDocument();
  });

  it('picks a film style, shows its moves, and sends the id with the brief and the prompt request', async () => {
    const user = userEvent.setup();
    await renderPage();
    const select = screen.getByLabelText(/^film style/i);
    expect(select).toHaveValue('');
    expect(screen.getByRole('option', { name: /^None \(derive from universe/ })).toBeInTheDocument();
    await user.selectOptions(select, 'blueprint-draft');
    expect(screen.getByText('White lines on a deep blue sheet.')).toBeInTheDocument();
    expect(await screen.findByText(/fits content like product anatomy, teardowns/)).toBeInTheDocument();
    await user.type(screen.getByLabelText(/what happens/i), 'A lantern');
    await user.click(screen.getByRole('button', { name: /build prompt/i }));
    await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
    expect(buildCodeAnimationPrompt.mock.calls[0][0].styleGrammarId).toBe('blueprint-draft');
    expect(listFilmStyles).toHaveBeenCalledTimes(1);
  });

  it('restores the film style from a saved job', async () => {
    getCodeAnimationJob.mockResolvedValue({ ...runningJob, input: { ...runningJob.input, styleGrammarId: 'blueprint-draft' } });
    await renderPage('/code-animation/job-1');
    expect(screen.getByLabelText(/^film style/i)).toHaveValue('blueprint-draft');
  });

  it('drops a stored film style the catalog no longer has before it reaches the server', async () => {
    localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({ concept: 'x', styleGrammarId: 'retired-style' }));
    const user = userEvent.setup();
    await renderPage();
    await user.click(screen.getByRole('button', { name: /build prompt/i }));
    await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
    expect(buildCodeAnimationPrompt.mock.calls[0][0].styleGrammarId).toBeNull();
  });

  it('shows an inline error and keeps the form usable when the catalog fails to load', async () => {
    listFilmStyles.mockRejectedValue(new Error('offline'));
    const user = userEvent.setup();
    await renderPage();
    expect(await screen.findByRole('alert')).toHaveTextContent(/film styles unavailable: offline/i);
    expect(screen.getByLabelText(/^film style/i)).toHaveValue('');
    await user.type(screen.getByLabelText(/what happens/i), 'A lantern');
    expect(screen.getByRole('button', { name: /build prompt/i })).toBeEnabled();
  });

  it('sends an explicit empty board when the user opts out of a mood board', async () => {
    const user = userEvent.setup();
    await renderPage();
    await user.type(screen.getByLabelText(/what happens/i), 'Fireflies');
    await user.selectOptions(screen.getByLabelText('Mood board'), 'none');
    await user.click(screen.getByRole('button', { name: /build prompt/i }));
    await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
    expect(buildCodeAnimationPrompt.mock.calls[0][0].moodBoardId).toBe('');
  });

  it('picks a track from the music library, shows library badge, and sends track audio in brief', async () => {
    const user = userEvent.setup();
    listTracks.mockResolvedValue([
      { id: 'track-1', title: 'Neon Rain', audioFilename: 'neon-rain.mp3', durationSec: 42.5 },
    ]);
    await renderPage();

    expect(screen.getByRole('button', { name: /pick from music library/i })).toBeInTheDocument();
    await user.click(screen.getByRole('button', { name: /pick from music library/i }));

    expect(screen.getByText('Pick soundtrack track')).toBeInTheDocument();
    expect(screen.getByText('Neon Rain')).toBeInTheDocument();

    await user.click(screen.getByRole('radio', { name: /select neon rain/i }));
    await user.click(screen.getByRole('button', { name: /select track/i }));

    expect(screen.getByText('Neon Rain')).toBeInTheDocument();
    expect(screen.getByText('42.5s')).toBeInTheDocument();
    expect(screen.getByText('Library track')).toBeInTheDocument();

    await user.type(screen.getByLabelText(/what happens/i), 'Robots dancing');
    await user.click(screen.getByRole('button', { name: /build prompt/i }));
    await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
    expect(buildCodeAnimationPrompt.mock.calls[0][0].audio).toEqual({
      source: 'track',
      trackId: 'track-1',
      label: 'Neon Rain',
      durationSeconds: 42.5,
      notes: '',
    });

    await user.click(screen.getByRole('button', { name: /remove audio track/i }));
    expect(screen.getByRole('button', { name: /pick from music library/i })).toBeInTheDocument();
  });

  it('restores draft with library track audio from localStorage', async () => {
    localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({
      audio: {
        source: 'track',
        trackId: 'track-stored',
        label: 'Ambient Drone',
        durationSeconds: 60,
      },
    }));

    await renderPage();

    expect(screen.getByText('Ambient Drone')).toBeInTheDocument();
    expect(screen.getByText('60.0s')).toBeInTheDocument();
    expect(screen.getByText('Library track')).toBeInTheDocument();
  });
});