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

15.5 KB
Raw Blame
import { beforeEach, describe, expect, it } from 'vitest';
import { act, cleanup, fireEvent, screen, waitFor } from '@testing-library/react';

import {
  loadVideoGenPage,
  renderVideoGenPage,
  resetVideoGenMockState,
  state,
  videoGenModel,
  videoGenModelContext,
  videoGenStatus,
} from '../test/videoGenPageMocks.jsx';

/**
 * Cross-page Remix restores exactly what in-page Remix restores (#6290).
 *
 * Media History used to hand /media/video a field-by-field URL bundle built by
 * `useMediaPreviewActions`, a second restore implementation that fell behind the
 * page's own `applyRemix`: the conditioner, speed profile, draft decode and the
 * LoRA arrays were all missing from it, so the same saved clip came back with
 * stock/Quality/Full/no-LoRA settings from History and with its real settings
 * from the gallery — a different render at a different compute cost. The handoff
 * is now the RECORD ID, resolved here against the page's own history load and
 * replayed through the one restore implementation.
 */
const MODEL = videoGenModel('example-ltx', {
  name: 'Example LTX',
  runtime: 'ltx2',
  supportedModes: ['text', 'image'],
  defaultFrames: 121,
  frameOptions: [121, 241],
  fpsOptions: [24],
  samplerLocked: false,
  supportsNegativePrompt: true,
  supportsTiling: true,
  supportsDisableAudio: true,
  textEncoderOptions: [
    { id: 'stock', label: 'Stock conditioner', builtIn: true },
    { id: 'example-substitute', label: 'Example substitute' },
  ],
  speedProfiles: [{ id: 'turbo', label: 'Turbo', steps: 4, guidance: 1 }],
  draftDecodeOptions: [{ id: 'example-draft', label: 'Example draft decoder' }],
});

const LORA = { filename: 'lora-example.safetensors', name: 'Example LoRA', loraCompatKey: 'ltx-video' };

/**
 * A saved render carrying every field the old URL bundle dropped. `hidden` is
 * deliberate: History can open a hidden record, so the lookup has to run against
 * the unfiltered load rather than the gallery's visible slice.
 */
const RECORD = {
  id: 'vid-example-1',
  filename: 'example.mp4',
  prompt: 'a paper boat on a canal',
  negativePrompt: 'blurry',
  modelId: MODEL.id,
  width: 768,
  height: 512,
  numFrames: 121,
  fps: 24,
  seed: 42,
  steps: 12,
  guidanceScale: 3,
  tiling: 'none',
  disableAudio: true,
  textEncoderId: 'example-substitute',
  speedProfileId: 'turbo',
  draftDecode: 'example-draft',
  loraFilenames: [LORA.filename],
  loraScales: [0.7],
  chainedFrom: ['vid-example-a', 'vid-example-b'],
  chunkPrompts: ['the boat launches', 'the boat sinks'],
  hidden: true,
};

/** A record from before the optional render fields existed. */
const LEGACY_RECORD = {
  id: 'vid-legacy-1',
  filename: 'legacy.mp4',
  prompt: 'a kite over a field',
  modelId: MODEL.id,
  width: 768,
  height: 512,
  numFrames: 121,
  fps: 24,
};

await loadVideoGenPage();

/**
 * Everything the restore is responsible for, read off the live form: the
 * controls the page renders itself, plus the sampler/LoRA props it hands the
 * panels. One reading, so the two entry paths are compared on identical terms.
 */
const readRestoredForm = () => ({
  prompt: screen.getByLabelText('Prompt').value,
  negativePrompt: screen.getByLabelText('Negative Prompt').value,
  modelId: screen.getByLabelText('Model').value,
  textEncoderId: screen.getByLabelText('Text encoder').value,
  loras: (state.loraPicker?.selected || []).map((l) => `${l.filename}@${l.scale}`),
  numFrames: state.advancedParams?.numFrames,
  fps: state.advancedParams?.fps,
  seed: state.advancedParams?.seed,
  steps: state.advancedParams?.steps,
  guidanceScale: state.advancedParams?.guidanceScale,
  speedProfileId: state.advancedParams?.speedProfileId,
  draftDecode: state.advancedParams?.draftDecode,
  tiling: state.advancedParams?.tiling,
  disableAudio: state.advancedParams?.disableAudio,
  chunks: state.advancedParams?.chunks,
  chunkPrompts: state.advancedParams?.chunkPrompts,
});

describe('VideoGen cross-page Remix handoff', () => {
  beforeEach(() => {
    localStorage.clear();
    sessionStorage.clear();
    resetVideoGenMockState();
    state.getVideoGenStatus.mockResolvedValue(videoGenStatus([MODEL]));
    state.getVideoGenModelContext.mockResolvedValue(videoGenModelContext([MODEL]));
    state.availableLoras = [LORA];
    state.listVideoHistory.mockResolvedValue([RECORD, LEGACY_RECORD]);
    // Every weight cached — a ready install. Without this the Generate button
    // is disabled by the weights gate no matter what, which would let the
    // "held while the handoff is pending" assertion pass for the wrong reason.
    state.getModelStatus = () => ({ cached: true });
    state.modelDownloadExtra = { textEncoder: { cached: true } };
  });

  it('restores the same settings from a History handoff as from the in-page gallery', async () => {
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    const fromHistory = readRestoredForm();

    // The exact fields the old URL bundle dropped. Asserted by name as well as
    // by the equality below, so a regression that broke BOTH paths together
    // still fails this test rather than comparing two blank forms.
    expect(fromHistory.textEncoderId).toBe('example-substitute');
    expect(fromHistory.speedProfileId).toBe('turbo');
    expect(fromHistory.draftDecode).toBe('example-draft');
    expect(fromHistory.loras).toEqual(['[email protected]']);
    expect(fromHistory.chunks).toBe(2);
    expect(fromHistory.chunkPrompts).toEqual(RECORD.chunkPrompts);

    cleanup();
    await renderVideoGenPage();
    await act(async () => { state.galleryProps.onRemix(RECORD); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));

    expect(readRestoredForm()).toEqual(fromHistory);
  });

  it('clears the optional controls when a legacy record follows a configured one', async () => {
    // The configured record first, so every control under test holds a
    // NON-default value. Asserting the sentinels on a freshly mounted form
    // would pass even if the restore stopped clearing them at all.
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    expect(readRestoredForm().speedProfileId).toBe('turbo');

    // A second handoff arriving in place, with the page already mounted.
    await act(async () => { state.navigate(`/media/video?remix=${LEGACY_RECORD.id}`); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(LEGACY_RECORD.prompt));

    const restored = readRestoredForm();
    expect(restored.textEncoderId).toBe('stock');
    expect(restored.speedProfileId).toBe('quality');
    expect(restored.draftDecode).toBe('full');
    expect(restored.loras).toEqual([]);
    expect(restored.negativePrompt).toBe('');
    expect(restored.steps).toBe('');
    expect(restored.guidanceScale).toBe('');
    expect(restored.chunks).toBe(1);
    expect(restored.chunkPrompts).toEqual([]);
  });

  it('labels a restored LoRA even when the library lands after the record does', async () => {
    // The page fetches history and the LoRA library as independent mount
    // effects. A cross-page Remix restores as soon as HISTORY settles, so on
    // this ordering the names have nothing to resolve against yet — and a
    // one-shot resolve would leave the picker showing the raw filename.
    let settleLoras;
    state.listLorasFull.mockReturnValue(new Promise((resolve) => { settleLoras = resolve; }));
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));

    await act(async () => { settleLoras([LORA]); });

    await waitFor(() => expect(state.loraPicker?.selected).toEqual([
      { filename: LORA.filename, name: LORA.name, scale: 0.7 },
    ]));
  });

  it('restores a record older than the history page by hydrating it by id', async () => {
    state.listVideoHistory.mockResolvedValue([]);
    state.getVideoHistoryItem.mockResolvedValue(RECORD);
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    expect(state.getVideoHistoryItem).toHaveBeenCalledTimes(1);
    expect(screen.queryByText(/no longer in your history/)).toBeNull();
  });

  it('reports a missing record when the by-id lookup answers 404', async () => {
    state.listVideoHistory.mockResolvedValue([]);
    state.getVideoHistoryItem.mockRejectedValue(Object.assign(new Error('Not found'), { status: 404 }));
    await renderVideoGenPage('/media/video?remix=vid-gone');
    await screen.findByText(/no longer in your history/);
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();
  });

  it('offers Retry after a non-404 by-id failure and restores once it succeeds', async () => {
    state.listVideoHistory.mockResolvedValue([]);
    state.getVideoHistoryItem
      .mockRejectedValueOnce(Object.assign(new Error('Server error'), { status: 500 }))
      .mockResolvedValue(RECORD);
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await act(async () => { fireEvent.click(await screen.findByRole('button', { name: 'Retry' })); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
  });

  it('says nothing about a missing record while the history fetch is still in flight', async () => {
    let settleHistory;
    state.listVideoHistory.mockReturnValue(new Promise((resolve) => { settleHistory = resolve; }));
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);

    // The pending fetch is not evidence of anything — claiming the record is
    // gone here would fire on every load that beats the round trip.
    expect(screen.queryByText(/no longer in your history/)).toBeNull();
    expect(screen.queryByText(/Couldn't load your render history/)).toBeNull();

    // It IS announced, and Generate is held: the form still shows the page
    // defaults and is about to be replaced wholesale, so a render started here
    // would spend GPU time on the wrong settings under the clip's name.
    screen.getByText(/Restoring this render's settings/);
    fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'anything at all' } });
    expect(screen.getByRole('button', { name: /Generate/ })).toBeDisabled();

    await act(async () => { settleHistory([RECORD]); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    expect(screen.queryByText(/no longer in your history/)).toBeNull();
    expect(screen.queryByText(/Restoring this render's settings/)).toBeNull();
    expect(screen.getByRole('button', { name: /Generate/ })).toBeEnabled();
  });

  it('keeps waiting when a background refresh fails beside the fetch it is waiting on', async () => {
    // The mount fetch and the completion refresh write one shared load
    // sentinel. A blip on the background one must not strand the handoff and
    // leave "couldn't load your history" sitting over a gallery that loaded.
    let settleMount;
    state.listVideoHistory.mockReturnValueOnce(new Promise((resolve) => { settleMount = resolve; }));
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);

    state.listVideoHistory.mockRejectedValueOnce(new Error('transient'));
    await act(async () => { await state.completionRefresh.onVideoCompleted(); });
    expect(screen.queryByText(/Couldn't load your render history/)).toBeNull();

    await act(async () => { settleMount([RECORD]); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    expect(screen.queryByText(/Couldn't load your render history/)).toBeNull();
  });

  it('offers a retry when the history fetch fails, and restores once it succeeds', async () => {
    state.listVideoHistory.mockRejectedValueOnce(new Error('offline'));
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);

    // A failed fetch is not a missing record — the settings may be perfectly
    // intact on disk, so the notice has to be the retryable one.
    await screen.findByText(/Couldn't load your render history/);
    expect(screen.queryByText(/no longer in your history/)).toBeNull();

    state.listVideoHistory.mockResolvedValue([RECORD]);
    await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })); });

    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    expect(screen.queryByText(/Couldn't load your render history/)).toBeNull();
  });

  it('waits for Retry rather than restoring from a background refresh after a failure', async () => {
    state.listVideoHistory.mockRejectedValueOnce(new Error('offline'));
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await screen.findByText(/Couldn't load your render history/);

    // The banner can sit for as long as the user leaves it there, and the form
    // is live the whole time. A render finishing in the background re-fetches
    // history — the stranded handoff must not ride in on it and wipe the form.
    fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a half-typed idea' } });
    state.listVideoHistory.mockResolvedValue([RECORD, LEGACY_RECORD]);
    await act(async () => { await state.completionRefresh.onVideoCompleted(); });

    expect(screen.getByLabelText('Prompt')).toHaveValue('a half-typed idea');
    expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();

    // The wait belongs to THAT handoff, not to the page: a different record
    // arriving afterwards must resolve against the history that has since
    // loaded rather than inherit the stranded one's block.
    await act(async () => { state.navigate(`/media/video?remix=${LEGACY_RECORD.id}`); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(LEGACY_RECORD.prompt));
    expect(screen.queryByText(/Couldn't load your render history/)).toBeNull();

    // And the block is spent, not permanent: the record whose fetch failed is
    // restorable once it is handed over again against a history that loaded.
    await act(async () => { state.navigate(`/media/video?remix=${RECORD.id}`); });
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));
    expect(screen.queryByText(/Couldn't load your render history/)).toBeNull();
  });

  it('reports an actionable missing-record state when the load holds no such record', async () => {
    state.listVideoHistory.mockResolvedValue([LEGACY_RECORD]);
    await renderVideoGenPage('/media/video?remix=vid-deleted');

    await screen.findByText(/no longer in your history/);
    expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();

    await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Dismiss' })); });
    expect(screen.queryByText(/no longer in your history/)).toBeNull();
  });

  it('does not replay the consumed handoff over the edits that follow it', async () => {
    await renderVideoGenPage(`/media/video?remix=${RECORD.id}`);
    await waitFor(() => expect(screen.getByLabelText('Prompt')).toHaveValue(RECORD.prompt));

    fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'a paper boat at dusk' } });
    // The completion refresh re-fetches history — the handoff must not ride
    // along with it and overwrite what the user has typed since.
    await act(async () => { await state.completionRefresh.onVideoCompleted(); });

    expect(screen.getByLabelText('Prompt')).toHaveValue('a paper boat at dusk');
  });
});