Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
31.3 KB
Raw Blame
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { SettingsView } from "./SettingsView";
import { loadGeneratorTemplateSettings, minimaxSingularityTemplate } from "../lib/settings";
import { getWeightDownloadState } from "../lib/weightDownloads";
import { WorkQueuePanel } from "./WorkQueuePanel";
import { WorkQueue } from "../lib/workQueue";
import { DMAD_LORA, PIKA_FL2VA_LORA, PIKA_REF2VA_LORA, loadLoras, saveLoras, TAOMATE_LORA, TURBO_LORA } from "../lib/loras";

vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
const files = new Set<string>();
const pick = (name: string, option: string) => {
  fireEvent.click(screen.getByRole("combobox", { name }));
  fireEvent.click(screen.getByRole("option", { name: option }));
};
const card = (openLabel: string) => screen.getByRole("button", { name: openLabel }).closest(".settings-open-card") as HTMLElement;

it.each([PIKA_FL2VA_LORA, PIKA_REF2VA_LORA])("offers $name, preserves its recipe, and downloads it with a generator", async (lora) => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  expect(screen.getByRole("button", { name: `Download LoRA ${lora.name}` })).toBeEnabled();
  fireEvent.click(screen.getByRole("button", { name: `Edit ${lora.name} LoRA` }));
  expect(screen.getByRole("combobox", { name: "LoRA sampling recipe" })).toHaveTextContent("Pika H3 Flex 6-Step");
  expect(screen.getByText(/video\/audio shifts of 12\/3/)).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Save" }));
  await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
  const generator = lora.id === PIKA_FL2VA_LORA.id ? "First/Last Frame" : "References";
  fireEvent.click(screen.getByRole("button", { name: `Edit ${generator} generator` }));
  pick("Add LoRA to generator", lora.name);
  expect(screen.getByText(/Pika H3 Flex fixes generation to six/)).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Download weights" }));
  await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 5, error: null }));
  expect(invoke).toHaveBeenCalledWith("download_weight", expect.objectContaining({ url: lora.url }));
  expect(loadLoras().find(({ id }) => id === lora.id)).toMatchObject({ samplingPreset: "pika-6step", path: expect.stringContaining("pika_h3_flex") });
});

it("downloads DMAD, preserves its sampling recipe when edited, and explains its fixed grid", async () => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit DMAD 4-Step LoRA" }));
  expect(screen.getByRole("combobox", { name: "LoRA sampling recipe" })).toHaveTextContent("DMAD 4-Step");
  expect(screen.queryByLabelText("Override step count")).not.toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Save" }));
  await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
  expect(loadLoras().find(({ id }) => id === DMAD_LORA.id)?.samplingPreset).toBe("dmad-4step");
  fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
  pick("Add LoRA to generator", DMAD_LORA.name);
  expect(screen.getByText(/DMAD fixes generation to four/)).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Download weights" }));
  await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ active: false, completed: 4, error: null }));
  expect(invoke).toHaveBeenCalledWith("download_weight", expect.objectContaining({ url: DMAD_LORA.url }));
  expect(loadLoras().find(({ id }) => id === DMAD_LORA.id)).toMatchObject({ samplingPreset: "dmad-4step", path: expect.stringContaining("dmad_minimax_h3") });
});

it("keeps a failed local import editable and supports local-only preparation", async () => {
  const normal = vi.mocked(invoke).getMockImplementation()!;
  vi.mocked(invoke).mockImplementation(async (command, args) => {
    if (command === "prepare_lora") throw new Error("Local companion grid missing");
    return normal(command, args);
  });
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Add LoRA" }));
  fireEvent.change(screen.getByLabelText("LoRA name"), { target: { value: "Offline style" } });
  fireEvent.change(screen.getByLabelText("LoRA path"), { target: { value: "D:/style.safetensors" } });
  fireEvent.click(screen.getByLabelText("Download missing timestep grid"));
  fireEvent.click(screen.getByRole("button", { name: "Add" }));
  expect(await screen.findByRole("alert")).toHaveTextContent("Local companion grid missing");
  expect(loadLoras().find(({ name }) => name === "Offline style")).toBeUndefined();
  expect(invoke).toHaveBeenCalledWith("prepare_lora", { path: "D:/style.safetensors", allowDownload: false });
  expect(screen.getByLabelText("LoRA name")).toHaveValue("Offline style");
  vi.mocked(invoke).mockImplementation(normal);
  fireEvent.click(screen.getByRole("button", { name: "Add" }));
  await screen.findByRole("button", { name: "Prepare LoRA Offline style" });
  expect(loadLoras().find(({ name }) => name === "Offline style")?.path).toBe("D:/style.safetensors");
});

it("prepares an existing adapter with a busy state and no unsupported cancel action", async () => {
  const lora = { id: "local", name: "Existing style", path: "D:/style.safetensors" };
  saveLoras([lora]);
  const normal = vi.mocked(invoke).getMockImplementation()!;
  let finish!: () => void;
  vi.mocked(invoke).mockImplementation(async (command, args) => command === "prepare_lora"
    ? new Promise<void>((resolve) => { finish = resolve; }) : normal(command, args));
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Prepare LoRA Existing style" }));
  expect(screen.getByRole("button", { name: "Prepare LoRA Existing style" })).toBeDisabled();
  expect(screen.getByRole("button", { name: "Remove LoRA Existing style" })).toBeDisabled();
  expect(screen.queryByRole("button", { name: "Cancel download" })).not.toBeInTheDocument();
  expect(screen.getByRole("status")).toHaveTextContent(/Preparing LoRA/);
  await act(async () => finish());
  expect(screen.getByRole("status")).toHaveTextContent("LoRA prepared");
  expect(loadLoras().find(({ id }) => id === lora.id)?.needsPreparation).toBeUndefined();
});

beforeEach(() => {
  localStorage.clear(); files.clear(); vi.clearAllMocks();
  Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
  vi.mocked(invoke).mockImplementation(async (command, args) => {
    if (command === "weight_download_hardware") return [{ name: "RTX 5090", memoryBytes: 32 * 1024 ** 3 }];
    if (command === "find_downloaded_weights") return {};
    if (command === "check_weight_files") return Object.fromEntries((args as { paths: string[] }).paths.map((path) => [path, files.has(path)]));
    if (command === "remove_downloaded_weights") { for (const path of (args as { paths: string[] }).paths) files.delete(path); return; }
    if (command === "download_weight") {
      const path = `C:/Slopus/weights/${(args as { url: string }).url.split('/').at(-1)}`;
      files.add(path); return path;
    }
    return { state: "modelsMissing", dllPath: "slopfab.dll", version: "1.4.0", platform: "Vulkan", detail: "Missing models", models: [] };
  });
});
afterEach(() => { cleanup(); delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; });

it("adds and downloads an additional safetensor from a generator's settings", async () => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
  fireEvent.change(screen.getByLabelText("Add additional safetensor URL"), { target: { value: "https://example.com/extra.safetensors" } });
  fireEvent.click(screen.getByRole("button", { name: "Add file" }));
  expect(screen.getByLabelText("Additional safetensor 1 URL")).toHaveValue("https://example.com/extra.safetensors");
  fireEvent.click(screen.getByRole("button", { name: "Download weights" }));
  await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ templateId: "default", active: false, completed: 4, error: null }));
  expect(loadGeneratorTemplateSettings().templates[0].additionalSafetensors![0].downloadedPath).toBe("C:/Slopus/weights/extra.safetensors");
  pick("Generator mode", "Animate (reference video)");
  pick("Additional safetensor 1 use", "Animate conditioning");
  await waitFor(() => expect(invoke).toHaveBeenCalledWith("slopfab_status", expect.objectContaining({ settings: {
    slopfab: expect.objectContaining({ options: expect.objectContaining({ generationMode: "animate", promptEmbedding: "C:/Slopus/weights/extra.safetensors" }) }),
  } })));
});

it("discovers Singularity's existing weights on opening Settings and downloads only missing Turbo", async () => {
  const normal = vi.mocked(invoke).getMockImplementation()!;
  const cached = Object.fromEntries(Object.values(minimaxSingularityTemplate().paths).filter(Boolean)
    .map((url) => [url, `D:/Projects/weights/${url.split('/').at(-1)}`]));
  Object.values(cached).forEach((path) => files.add(path));
  vi.mocked(invoke).mockImplementation(async (command, args) => command === "find_downloaded_weights"
    ? Object.fromEntries((args as { urls: string[] }).urls.filter((url) => cached[url]).map((url) => [url, cached[url]])) : normal(command, args));
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  await waitFor(() => expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "minimax-h3-singularity")?.paths.transformer).toMatch(/^D:\/Projects\/weights\//));
  expect(screen.getByRole("button", { name: "Download generator Singularity" })).toBeEnabled();
  expect(card("Edit Singularity generator")).toHaveTextContent("Needs Turbo LoRA");
  expect(invoke).not.toHaveBeenCalledWith("download_weight", expect.anything());
  fireEvent.click(screen.getByRole("button", { name: "Download generator Singularity" }));
  expect(await screen.findByRole("button", { name: "Set Singularity as default" })).toBeEnabled();
  expect(vi.mocked(invoke).mock.calls.filter(([command]) => command === "download_weight")).toEqual([
    ["download_weight", { requestId: expect.any(String), url: TURBO_LORA.url }],
  ]);
});

it("shows discovered model files as Found even when an active LoRA is missing", async () => {
  const normal = vi.mocked(invoke).getMockImplementation()!;
  const cached = Object.fromEntries(Object.values(minimaxSingularityTemplate().paths).filter(Boolean)
    .map((url) => [url, `D:/Projects/weights/${url.split('/').at(-1)}`]));
  vi.mocked(invoke).mockImplementation(async (command, args) => {
    if (command === "find_downloaded_weights") return Object.fromEntries((args as { urls: string[] }).urls.filter((url) => cached[url]).map((url) => [url, cached[url]]));
    if (command === "slopfab_status") {
      const options = (args as { settings: { slopfab: { options: Record<string, string> } } }).settings.slopfab.options;
      const models = ["transformer", "textEncoder", "videoVae", "audioVae"].map((id) => ({ id, path: options[id], configured: Boolean(options[id]), available: Object.values(cached).includes(options[id]) }));
      return { state: models.every(({ available }) => available) ? "ready" : "modelsMissing", dllPath: "slopfab.dll", version: "1.8.0", platform: "CUDA 13", detail: "Runtime loaded.", models };
    }
    return normal(command, args);
  });
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit Singularity generator" }));
  await waitFor(() => expect(screen.getAllByText("Found")).toHaveLength(1));
  expect(screen.queryByText("Checking this computer…")).not.toBeInTheDocument();
  expect(screen.queryByText("Engine ready")).not.toBeInTheDocument();
  expect(screen.getByText(/Download or locate LoRA Turbo/)).toBeInTheDocument();
  expect(screen.getByRole("button", { name: "Download weights" })).toBeEnabled();
});

it("selects an undownloaded LoRA in a generator and downloads it from that generator", async () => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
  fireEvent.click(screen.getByRole("combobox", { name: "Add LoRA to generator" }));
  expect(screen.getByRole("option", { name: "Turbo" })).toBeInTheDocument();
  fireEvent.click(screen.getByRole("option", { name: "Turbo" }));
  expect(screen.getByLabelText("Enable Turbo")).toBeChecked();
  expect(screen.getByText(/step count to 4/)).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Download weights" }));
  await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ templateId: "default", active: false, completed: 4, error: null }));
  expect(loadLoras().find(({ id }) => id === TURBO_LORA.id)?.path).not.toBe("");
  expect(screen.queryByRole("button", { name: "Download weights" })).not.toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  expect(within(screen.getByRole("list", { name: "Generators" })).getByText("Default")).toBeInTheDocument();
  expect(card("Edit Default generator")).toHaveTextContent("Used by default");
  fireEvent.click(screen.getByRole("button", { name: "Remove LoRA Turbo" }));
  expect(await screen.findByRole("button", { name: "Download generator Default" })).toBeEnabled();
  expect(within(screen.getByRole("list", { name: "Available to download" })).getByText("Default")).toBeInTheDocument();
  expect(card("Edit Default generator")).not.toHaveTextContent("Used by default");
});

it("downloads TaoMate and persists manual adapters, activation, strength and order per template", async () => {
  const settings = render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Download LoRA TaoMate 3-Step" }));
  await waitFor(() => expect(loadLoras()[0].path).not.toBe(""));
  fireEvent.click(screen.getByRole("button", { name: "Add LoRA" }));
  expect(screen.queryByRole("button", { name: "New generator" })).not.toBeInTheDocument();
  expect(screen.getByRole("heading", { name: "Add LoRA" })).toBeInTheDocument();
  expect(screen.getByRole("dialog", { name: "Add LoRA" })).toBeInTheDocument();
  fireEvent.change(screen.getByLabelText("LoRA name"), { target: { value: "My style" } });
  fireEvent.change(screen.getByLabelText("LoRA path"), { target: { value: "D:/models/style.safetensors" } });
  expect(screen.queryByLabelText("LoRA multiplier")).not.toBeInTheDocument();
  fireEvent.click(screen.getByLabelText("Override step count"));
  fireEvent.change(screen.getByLabelText("LoRA step override"), { target: { value: "8" } });
  fireEvent.click(screen.getByRole("button", { name: "Add" }));
  await waitFor(() => expect(loadLoras().find(({ name }) => name === "My style")).toBeDefined());
  expect(invoke).toHaveBeenCalledWith("prepare_lora", { path: "D:/models/style.safetensors", allowDownload: true });
  const manual = loadLoras().find(({ name }) => name === "My style")!;
  expect(manual.stepOverride).toBe(8);
  expect(manual).not.toHaveProperty("multiplier");
  expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Edit My style LoRA" }));
  expect(screen.getByLabelText("LoRA step override")).toHaveValue(8);
  expect(screen.getByRole("dialog", { name: "Edit LoRA" })).toBeInTheDocument();
  expect(screen.queryByLabelText("LoRA multiplier")).not.toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
  pick("Add LoRA to generator", TAOMATE_LORA.name);
  pick("Add LoRA to generator", manual.name);
  fireEvent.change(screen.getByLabelText("My style strength"), { target: { value: "-0.5" } });
  fireEvent.click(screen.getByRole("button", { name: "Move My style up" }));
  fireEvent.click(screen.getByLabelText("Enable TaoMate 3-Step"));
  expect(screen.getByText("1 active")).toBeInTheDocument();
  expect(screen.getByText(/step count to 8/)).toBeInTheDocument();
  const expected = [{ loraId: manual.id, enabled: true, strength: -0.5 }, { loraId: TAOMATE_LORA.id, enabled: false, strength: 1 }];
  expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "default")!.loras).toEqual(expected);
  settings.unmount();
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
  expect(screen.getByLabelText("My style strength")).toHaveValue(-0.5);
  expect(screen.getByLabelText("Enable TaoMate 3-Step")).not.toBeChecked();
  expect(screen.getByRole("button", { name: "Move My style up" })).toBeDisabled();
});

it("keeps a LoRA download alive outside Settings, shows progress and cancels through Work Queue", async () => {
  let progress: (event: { payload: { requestId: string; downloaded: number; total: number | null } }) => void = () => undefined;
  vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);
  const normal = vi.mocked(invoke).getMockImplementation()!;
  let requestId = "";
  let rejectDownload: (reason: Error) => void = () => undefined;
  vi.mocked(invoke).mockImplementation(async (command, args) => {
    if (command === "download_weight") {
      requestId = (args as { requestId: string }).requestId;
      return new Promise((_resolve, reject) => { rejectDownload = reject; });
    }
    if (command === "cancel_weight_download") { rejectDownload(new Error("Download cancelled.")); return; }
    return normal(command, args);
  });
  const settings = render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Download LoRA TaoMate 3-Step" }));
  await waitFor(() => expect(requestId).not.toBe(""));
  expect(screen.getByRole("button", { name: "Download generator First/Last Frame" })).toBeEnabled();
  settings.unmount();
  render(<WorkQueuePanel queue={new WorkQueue()} items={[]} onClose={() => undefined} />);
  act(() => progress({ payload: { requestId, downloaded: 50, total: 100 } }));
  expect(screen.getByRole("progressbar", { name: "TaoMate 3-Step download progress" })).toHaveAttribute("aria-valuenow", "50");
  fireEvent.click(screen.getByRole("button", { name: "Cancel TaoMate 3-Step download" }));
  await waitFor(() => expect(getWeightDownloadState()).toMatchObject({ active: false, error: "Download cancelled." }));
  expect(loadLoras()[0].path).toBe("");
  expect(screen.getByRole("button", { name: "Retry download" })).toBeInTheDocument();
});

it("keeps downloading with Settings closed and restores progress in the template row and Work Queue", async () => {
  let progress: (event: { payload: { requestId: string; downloaded: number; total: number | null } }) => void = () => undefined;
  vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);
  const original = vi.mocked(invoke).getMockImplementation()!;
  const pending: { requestId: string; finish: () => void }[] = [];
  vi.mocked(invoke).mockImplementation(async (command, args) => {
    if (command !== "download_weight") return original(command, args);
    const request = args as { requestId: string; url: string };
    return new Promise<string>((resolve) => pending.push({ requestId: request.requestId, finish: () => {
      const path = `C:/Slopus/weights/${request.url.split('/').at(-1)}`;
      files.add(path); resolve(path);
    } }));
  });
  const settings = render(<SettingsView onClose={() => settings.unmount()} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Download generator First/Last Frame" }));
  await waitFor(() => expect(pending).toHaveLength(1));
  act(() => progress({ payload: { requestId: pending[0].requestId, downloaded: 50, total: 100 } }));
  const fill = screen.getByRole("progressbar", { name: "Downloading First/Last Frame weights" });
  expect(fill.closest(".settings-open-card")).toHaveTextContent("Downloading · 12%");
  expect(within(screen.getByRole("list", { name: "Available to download" })).getByRole("progressbar")).toBe(fill);
  expect(within(screen.getByRole("list", { name: "Generators" })).queryByText("First/Last Frame")).toBeNull();
  expect(fill).toHaveAttribute("aria-valuenow", "13");
  expect(fill.querySelector(".ui-progress__fill")).toHaveStyle({ width: "12.5%" });
  fireEvent.click(screen.getByRole("button", { name: "Back" }));
  fireEvent.click(screen.getByRole("button", { name: "Back" }));
  await act(async () => pending[0].finish());
  await waitFor(() => expect(pending).toHaveLength(2));
  act(() => progress({ payload: { requestId: pending[1].requestId, downloaded: 50, total: 100 } }));
  const queue = new WorkQueue(async (record) => record);
  const panel = render(<WorkQueuePanel queue={queue} items={[]} onClose={() => panel.unmount()} />);
  expect(screen.getByRole("region", { name: "Weight downloads" })).toHaveTextContent("First/Last Frame");
  expect(screen.getByRole("progressbar", { name: "First/Last Frame download progress" })).toHaveAttribute("aria-valuenow", "38");
  expect(screen.queryByText("No work yet")).toBeNull();
  panel.unmount();
  const reopened = render(<SettingsView onClose={() => reopened.unmount()} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  expect(screen.getByRole("progressbar", { name: "Downloading First/Last Frame weights" }).querySelector(".ui-progress__fill")).toHaveStyle({ width: "37.5%" });
  reopened.unmount();
  for (let index = 1; index < 4; index++) {
    await waitFor(() => expect(pending.length).toBe(index + 1));
    await act(async () => pending[index].finish());
  }
  await waitFor(() => expect(getWeightDownloadState()?.active).toBe(false));
  expect(getWeightDownloadState()).toMatchObject({ completed: 4, error: null });
  expect(vi.mocked(invoke).mock.calls.some(([command]) => command === "cancel_weight_download")).toBe(false);
  render(<WorkQueuePanel queue={queue} items={[]} onClose={() => undefined} />);
  expect(screen.getByRole("region", { name: "Weight downloads" })).toHaveTextContent("Download complete");
});

it("queues Other weights from Settings and follows their progress after Settings closes", async () => {
  let progress: (event: { payload: { requestId: string; downloaded: number; total: number | null } }) => void = () => undefined;
  vi.mocked(listen).mockImplementation((async (_name, callback) => { progress = callback as typeof progress; return () => undefined; }) as typeof listen);
  const original = vi.mocked(invoke).getMockImplementation()!;
  const pending: { requestId: string; finish: () => void }[] = [];
  vi.mocked(invoke).mockImplementation(async (command, args) => {
    if (command !== "download_weight") return original(command, args);
    const request = args as { requestId: string; url: string };
    return new Promise<string>((resolve) => pending.push({ requestId: request.requestId, finish: () => resolve(`C:/weights/${request.url.split('/').at(-1)}`) }));
  });
  const settings = render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "Other" }));
  const otherCard = (name: string) => within(screen.getByText(name).closest(".ui-settings-card") as HTMLElement);
  fireEvent.click(otherCard("Real-ESRGAN").getByRole("button", { name: "Download" }));
  await waitFor(() => expect(pending).toHaveLength(1));
  fireEvent.click(otherCard("SeedVR2").getByRole("button", { name: "Download" }));
  expect(otherCard("SeedVR2").getByText("Queued for download")).toBeInTheDocument();
  fireEvent.click(otherCard("SeedVR2").getByRole("button", { name: "Cancel" }));
  fireEvent.click(otherCard("SeedVR2").getByRole("button", { name: "Download" }));
  settings.unmount();
  const navigate = vi.fn();
  render(<WorkQueuePanel queue={new WorkQueue()} items={[]} onClose={() => undefined} onNavigate={navigate} />);
  expect(within(screen.getByRole("region", { name: "Upcoming work" })).getByText("SeedVR2")).toBeInTheDocument();
  act(() => progress({ payload: { requestId: pending[0].requestId, downloaded: 50, total: 100 } }));
  expect(screen.getByRole("progressbar", { name: "Real-ESRGAN download progress" })).toHaveAttribute("aria-valuenow", "50");
  await act(async () => pending[0].finish());
  await waitFor(() => expect(pending).toHaveLength(2));
  expect(screen.queryByRole("region", { name: "Upcoming work" })).toBeNull();
  act(() => progress({ payload: { requestId: pending[1].requestId, downloaded: 50, total: 100 } }));
  expect(screen.getByRole("progressbar", { name: "SeedVR2 download progress" })).toHaveAttribute("aria-valuenow", "25");
  await act(async () => pending[1].finish());
  await waitFor(() => expect(pending).toHaveLength(3));
  act(() => progress({ payload: { requestId: pending[2].requestId, downloaded: 50, total: 100 } }));
  expect(screen.getByRole("progressbar", { name: "SeedVR2 download progress" })).toHaveAttribute("aria-valuenow", "75");
  await act(async () => pending[2].finish());
  await waitFor(() => expect(screen.getByText(/Download complete/)).toBeInTheDocument());
  fireEvent.click(screen.getByRole("button", { name: "Open SeedVR2 download" }));
  expect(navigate).toHaveBeenCalledWith({ kind: "download", download: expect.objectContaining({ otherWeightId: "seedvr2", completed: 2, active: false }) });
});

it("downloads the sample, enables its default choice, and removes only weights to restore the download action", async () => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  const makeDefault = () => screen.getByRole("button", { name: "Set First/Last Frame as default" });
  expect(within(screen.getByRole("list", { name: "Available to download" })).getByText("Default")).toBeInTheDocument();
  expect(within(screen.getByRole("list", { name: "Available to download" })).getByText("First/Last Frame")).toBeInTheDocument();
  expect(within(screen.getByRole("list", { name: "Available to download" })).queryByRole("button", { name: /as default/ })).toBeNull();
  expect(screen.queryByRole("button", { name: "Remove generator First/Last Frame" })).toBeNull();
  fireEvent.click(screen.getByRole("button", { name: "Download generator First/Last Frame" }));
  const remove = await screen.findByRole("button", { name: "Remove downloaded weights for First/Last Frame" }, { timeout: 5000 });
  expect(within(screen.getByRole("list", { name: "Generators" })).getByText("First/Last Frame")).toBeInTheDocument();
  expect(within(screen.getByRole("list", { name: "Available to download" })).queryByText("First/Last Frame")).toBeNull();
  expect(within(screen.getByRole("list", { name: "Available to download" })).getByText("References")).toBeInTheDocument();
  expect(makeDefault()).toBeEnabled();
  fireEvent.click(makeDefault());
  await waitFor(() => expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe("minimax-h3-original"));
  fireEvent.click(remove);
  expect(await screen.findByRole("button", { name: "Download generator First/Last Frame" })).toBeEnabled();
  expect(within(screen.getByRole("list", { name: "Available to download" })).getByText("First/Last Frame")).toBeInTheDocument();
  expect(within(screen.getByRole("list", { name: "Generators" })).queryByText("First/Last Frame")).toBeNull();
  expect(within(screen.getByRole("list", { name: "Available to download" })).queryByRole("button", { name: /as default/ })).toBeNull();
  expect(files.size).toBe(3); // Shared encoder and VAEs stay installed.
  expect(loadGeneratorTemplateSettings().templates.find((template) => template.id === "minimax-h3-original")?.paths.transformer).toMatch(/^https:/);
});

it("restores a deleted downloaded file when Settings regains focus", async () => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Download generator First/Last Frame" }));
  await screen.findByRole("button", { name: "Remove downloaded weights for First/Last Frame" }, { timeout: 5000 });
  files.clear();
  fireEvent.focus(window);
  expect(await screen.findByRole("button", { name: "Download generator First/Last Frame" })).toBeEnabled();
});

it("stores multiple variants and their GPU and VRAM criteria in the editor", async () => {
  render(<SettingsView onClose={() => undefined} />);
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit First/Last Frame generator" }));
  const advanced = screen.getByRole("switch", { name: "Show advanced options" });
  expect(advanced).not.toBeChecked();
  expect(screen.queryByText(/Download variants/)).toBeNull();
  const groups = document.querySelectorAll(".settings-page > .ui-settings-group");
  expect(groups[groups.length - 1]).toBe(advanced.closest(".ui-settings-group"));
  fireEvent.click(advanced);
  const weight = screen.getByRole("group", { name: "Transformer weights" }).closest(".settings-path") as HTMLElement;
  const variants = within(weight).getByRole("button", { name: /^Download variants \(3\)/ });
  fireEvent.click(variants);
  expect(variants).toHaveAttribute("aria-expanded", "true");
  fireEvent.change(screen.getByLabelText("Add Transformer weights download URL"), { target: { value: "https://example.com/larger.safetensors" } });
  fireEvent.click(within(weight as HTMLElement).getByRole("button", { name: "Add URL" }));
  const gpu = screen.getByLabelText("Transformer weights variant 4 GPU model");
  fireEvent.change(gpu, { target: { value: "RTX 5090" } });
  fireEvent.blur(gpu);
  fireEvent.change(screen.getByLabelText("Transformer weights variant 4 minimum VRAM"), { target: { value: "32" } });
  await waitFor(() => expect(loadGeneratorTemplateSettings().templates.find((template) => template.id === "minimax-h3-original")?.sources?.transformer?.[3]).toMatchObject({ url: "https://example.com/larger.safetensors", gpuModel: "RTX 5090", minVramGb: 32 }));
  fireEvent.click(advanced);
  expect(screen.queryByText(/Download variants/)).toBeNull();
  fireEvent.click(advanced);
  expect(screen.getByLabelText("Transformer weights variant 4 GPU model")).toHaveValue("RTX 5090");
  fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
  fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
  expect(screen.getByRole("switch", { name: "Show advanced options" })).not.toBeChecked();
  expect(screen.queryByText(/Download variants/)).toBeNull();
});