Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
38.8 KB
Raw Blame
// @vitest-environment jsdom
import { installH3TestDependencies } from "../lib/h3TestUtils";

import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { invoke } from "@tauri-apps/api/core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { middleEllipsis, SettingsView } from "./SettingsView";
import { createGeneratorTemplate, mossImageTemplate, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings } from "../lib/settings";
import { loadAlbumCoverGeneratorId, loadReferenceIconGeneratorId } from "../lib/referenceIconSettings";
import { loadGenerationPreviewsEnabled } from "../lib/generationPreviewSettings";
import { loadLoras, saveLoras } from "../lib/loras";

vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));

beforeEach(() => {
  localStorage.clear(); installH3TestDependencies();
  vi.clearAllMocks();
  delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
});
afterEach(() => {
  cleanup();
  delete (window as Window & { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
});

const open = (model: string | null = "MiniMax H3") => {
  const view = render(<SettingsView onClose={() => undefined} />);
  if (model) fireEvent.click(screen.getByRole("button", { name: model }));
  return view;
};
const tab = (name: string) => within(screen.getByRole("navigation", { name: "Settings sections" })).getByRole("button", { name: new RegExp(`^${name}`) });
const editDefaultGenerator = () => fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
const combo = (name: string) => screen.getByRole("combobox", { name });
const pick = (name: string, option: string) => { fireEvent.click(combo(name)); fireEvent.click(screen.getByRole("option", { name: option })); };
const optionsOf = (name: string) => {
  fireEvent.click(combo(name));
  const labels = screen.getAllByRole("option").map((option) => option.textContent);
  fireEvent.keyDown(combo(name), { key: "Escape" });
  return labels;
};
const toggle = (name: string) => screen.getByRole("switch", { name });
const enterPath = (label: string, value: string) => {
  fireEvent.click(screen.getByRole("button", { name: `More options for ${label}` }));
  fireEvent.click(screen.getByRole("menuitem", { name: "Enter path or URL…" }));
  const input = screen.getByRole("textbox", { name: label });
  fireEvent.change(input, { target: { value } });
  fireEvent.blur(input);
};

describe("the settings page", () => {
  it("persists the generation previews switch across settings visits", () => {
    const view = open(null);
    expect(toggle("Enable generation previews").getAttribute("aria-checked")).toBe("true");
    fireEvent.click(toggle("Enable generation previews"));
    expect(loadGenerationPreviewsEnabled()).toBe(false);
    view.unmount();
    open(null);
    expect(toggle("Enable generation previews").getAttribute("aria-checked")).toBe("false");
    fireEvent.click(toggle("Enable generation previews"));
    expect(loadGenerationPreviewsEnabled()).toBe(true);
  });

  it("opens a focused page with a navigation pane and a Back action", () => {
    const onClose = vi.fn();
    render(<SettingsView onClose={onClose} />);
    expect(document.activeElement).toBe(screen.getByRole("main", { name: "Settings" }));
    expect(screen.queryByRole("dialog")).toBeNull();
    expect(screen.getByRole("heading", { level: 1, name: "Generators" })).toBeTruthy();
    expect(tab("Generators").getAttribute("aria-current")).toBe("page");
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    expect(onClose).toHaveBeenCalledOnce();
  });

  it("closes on Escape from the top level", () => {
    const onClose = vi.fn();
    render(<SettingsView onClose={onClose} />);
    fireEvent.keyDown(screen.getByRole("main", { name: "Settings" }), { key: "Escape" });
    expect(onClose).toHaveBeenCalledOnce();
  });

  it("middle-ellipsises long paths and keeps the file name", () => {
    expect(middleEllipsis("C:\\short.safetensors")).toBe("C:\\short.safetensors");
    const long = `D:\\${"folder\\".repeat(20)}model.safetensors`;
    const shown = middleEllipsis(long);
    expect(shown.length).toBe(64);
    expect(shown).toMatch(/^D:\\folder.*….*model\.safetensors$/);
  });
});

describe("the settings screen", () => {
  it("opens model-specific generators and LoRAs, and keeps Other weights on their own page", () => {
    saveLoras([{ id: "future-adapter", name: "MOSS adapter", modelType: "moss", path: "D:/moss-adapter.safetensors" }]);
    open(null);
    const models = screen.getByRole("list", { name: "Generator models" });
    expect(within(models).getAllByRole("button").map((button) => button.getAttribute("aria-label"))).toEqual(["MiniMax H3", "Fibo 2.0", "Krea 2", "MiniMax H3 Image", "MOSS", "MiniMax Music3", "YuE2", "Other"]);
    expect(screen.queryByRole("button", { name: "Edit Default generator" })).toBeNull();
    fireEvent.click(within(models).getByRole("button", { name: "MiniMax H3" }));
    expect(screen.getByRole("button", { name: "Edit Default generator" })).toBeTruthy();
    expect(screen.getByRole("button", { name: "Edit TaoMate 3-Step LoRA" })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "Edit MOSS adapter LoRA" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Edit MOSS Image generator" })).toBeNull();
    expect(screen.queryByRole("list", { name: "Other weights" })).toBeNull();
    editDefaultGenerator();
    fireEvent.click(combo("Add LoRA to generator"));
    expect(screen.queryByRole("option", { name: "MOSS adapter" })).toBeNull();
    fireEvent.keyDown(combo("Add LoRA to generator"), { key: "Escape" });
    fireEvent.click(screen.getByRole("button", { name: "Generators" }));
    expect(document.activeElement).toBe(screen.getByRole("button", { name: "MiniMax H3" }));
    fireEvent.click(screen.getByRole("button", { name: "MOSS" }));
    expect(screen.getByRole("button", { name: "Edit MOSS Image generator" })).toBeTruthy();
    expect(screen.getByRole("button", { name: "Edit MOSS adapter LoRA" })).toBeTruthy();
    expect(screen.getByText("This model does not support LoRAs.")).toBeTruthy();
    expect(screen.queryByRole("button", { name: "Add LoRA" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Edit TaoMate 3-Step LoRA" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Edit Default generator" })).toBeNull();
    fireEvent.click(screen.getByRole("button", { name: "Generators" }));
    expect(document.activeElement).toBe(screen.getByRole("button", { name: "MOSS" }));
    fireEvent.click(screen.getByRole("button", { name: "Other" }));
    expect(screen.getByRole("list", { name: "Other weights" })).toBeTruthy();
    for (const name of ["Real-ESRGAN", "SeedVR2"]) expect(screen.getByText(name)).toBeTruthy();
    expect(screen.queryByRole("list", { name: "Generators" })).toBeNull();
    expect(screen.queryByRole("list", { name: "LoRAs" })).toBeNull();
  });

  it("selects the same text encoder for H3 Image and video while keeping the image VAE", () => {
    const settings = loadGeneratorTemplateSettings();
    settings.h3Components!.templates.push({ id: "shared-test", name: "Shared test encoder", type: "textEncoder", path: "D:/shared-text", tokenizer: "D:/tokenizer", sources: [] });
    saveGeneratorTemplateSettings(settings);
    const imageVae = settings.templates.find(({ id }) => id === "minimax-h3-image")!.paths.videoVae;
    open("MiniMax H3 Image");
    fireEvent.click(screen.getByRole("button", { name: "Edit MiniMax H3 Image generator" }));
    expect(screen.getByText("Image VAE weights")).toBeTruthy();
    expect(screen.queryByText("Text encoder weights")).toBeNull();
    fireEvent.click(combo("Shared H3 text encoder"));
    fireEvent.click(screen.getByRole("option", { name: "Shared test encoder" }));
    const updated = loadGeneratorTemplateSettings();
    expect(updated.h3Components!.defaultTextEncoderId).toBe("shared-test");
    for (const id of ["minimax-h3-image", "minimax-h3-original"]) {
      expect(updated.templates.find((template) => template.id === id)!.paths).toMatchObject({ textEncoder: "D:/shared-text", tokenizer: "D:/tokenizer" });
    }
    expect(updated.templates.find(({ id }) => id === "minimax-h3-image")!.paths.videoVae).toBe(imageVae);
  });

  it("creates a generator for the selected model and follows model changes when returning", () => {
    open("MOSS");
    const defaultId = loadGeneratorTemplateSettings().defaultTemplateId;
    fireEvent.click(screen.getByRole("button", { name: "New generator" }));
    const name = (screen.getByLabelText("Generator name") as HTMLInputElement).value;
    expect(loadGeneratorTemplateSettings().templates.find((template) => template.name === name)).toMatchObject({ modelType: "moss", attention: "flash2", defaultSteps: 50 });
    expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe(defaultId);
    fireEvent.click(combo("Generator model"));
    fireEvent.click(screen.getByRole("option", { name: /^MiniMax H3 Image and video generation$/ }));
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    expect(screen.getByRole("heading", { level: 1, name: "MiniMax H3" })).toBeTruthy();
    expect(screen.getByRole("button", { name: `Edit ${name} generator` })).toBeTruthy();
  });

  it("opens the model page when navigating from generator, LoRA and Other downloads", () => {
    const props = { onClose: vi.fn() };
    const view = render(<SettingsView {...props} navigation={{ templateId: "moss-image" }} />);
    expect(combo("Generator model").getAttribute("data-value")).toBe("moss");
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    expect(screen.getByRole("heading", { level: 1, name: "MOSS" })).toBeTruthy();
    view.rerender(<SettingsView {...props} navigation={{ templateId: "lora:taomate-3step", loraId: "taomate-3step" }} />);
    expect(screen.getByRole("dialog", { name: "Edit LoRA" })).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
    expect(screen.getByRole("heading", { level: 1, name: "MiniMax H3" })).toBeTruthy();
    view.rerender(<SettingsView {...props} navigation={{ templateId: "other:seedvr2", otherWeightId: "seedvr2" }} />);
    expect(screen.getByRole("heading", { level: 1, name: "Other" })).toBeTruthy();
    expect(screen.getByRole("list", { name: "Other weights" })).toBeTruthy();
  });

  it("persists the editing switch for Fibo Base", () => {
    open("Fibo 2.0");
    fireEvent.click(screen.getByRole("button", { name: "Edit Fibo 2.0 Base generator" }));
    const toggle = screen.getByRole("switch", { name: "Editing model" });
    expect(toggle.getAttribute("aria-checked")).toBe("false");
    fireEvent.click(toggle);
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "fibo2-base")!.editingModel).toBe(true);
    fireEvent.click(toggle);
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "fibo2-base")!.editingModel).toBe(false);
  });

  it("offers Fibo settings with embedded tokenizer and no H3-only controls", () => {
    open("Fibo 2.0");
    fireEvent.click(screen.getByRole("button", { name: "Edit Fibo 2.0 Edit Turbo generator" }));
    expect(combo("Generator model").getAttribute("data-value")).toBe("fibo2");
    expect(combo("Generator attention").getAttribute("data-value")).toBe("flash2");
    expect(screen.getByRole("button", { name: "More options for Image VAE weights" })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "More options for Audio VAE weights" })).toBeNull();
    expect(screen.queryByRole("combobox", { name: "Generator mode" })).toBeNull();
    expect(screen.queryByRole("switch", { name: "Enable MotionCache" })).toBeNull();
  });

  it("groups MOSS under its model and edits its image-only weight setup", () => {
    open("MOSS");
    expect(screen.getByRole("heading", { level: 1, name: "MOSS" })).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "Edit MOSS Image generator" }));
    expect(combo("Generator model").getAttribute("data-value")).toBe("moss");
    expect(screen.queryByRole("combobox", { name: "Generator mode" })).toBeNull();
    expect(screen.getByRole("button", { name: "More options for Image VAE weights" })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "More options for Audio VAE weights" })).toBeNull();
    expect(combo("Generator attention").getAttribute("data-value")).toBe("flash2");
    expect(screen.queryByRole("switch", { name: "Enable MotionCache" })).toBeNull();
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "moss-image")).toEqual(mossImageTemplate());
    fireEvent.click(combo("Generator model"));
    fireEvent.click(screen.getByRole("option", { name: /^MiniMax H3 Image and video generation$/ }));
    expect(screen.getByRole("combobox", { name: "Generator mode" })).toBeTruthy();
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "moss-image")?.modelType).toBe("minimax-h3");
  });
  it("offers Krea image-only templates and their sampling recipes", () => {
    open("Krea 2");
    fireEvent.click(screen.getByRole("button", { name: "Edit Krea 2 Raw generator" }));
    expect(combo("Generator model").getAttribute("data-value")).toBe("krea2");
    expect(combo("Krea sampling defaults").getAttribute("data-value")).toBe("raw");
    expect((screen.getByRole("spinbutton", { name: "Generator default steps" }) as HTMLInputElement).value).toBe("52");
    expect((screen.getByRole("switch", { name: "Editing model" }) as HTMLButtonElement).disabled).toBe(true);
    expect(screen.queryByRole("combobox", { name: "Generator mode" })).toBeNull();
    expect(screen.queryByRole("button", { name: "More options for Audio VAE weights" })).toBeNull();
    expect(screen.getByRole("spinbutton", { name: "Generator image sigma shift" }).getAttribute("placeholder")).toBe("Auto");
    fireEvent.click(combo("Krea sampling defaults"));
    fireEvent.click(screen.getByRole("option", { name: "Turbo" }));
    expect((screen.getByRole("spinbutton", { name: "Generator default steps" }) as HTMLInputElement).value).toBe("8");
  });
  it("persists supported sampling choices and resets them when the model changes", () => {
    const view = open("MOSS");
    fireEvent.click(screen.getByRole("button", { name: "Edit MOSS Image generator" }));
    expect(combo("Generator sampler").getAttribute("data-value")).toBe("default");
    expect(optionsOf("Generator sampler")).toEqual(["Model default", "Euler", "ER-SDE"]);
    expect(optionsOf("Generator scheduler")).toEqual(["Model default", "Beta"]);
    pick("Generator sampler", "ER-SDE");
    pick("Generator scheduler", "Beta");
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "moss-image")).toMatchObject({ sampler: "er_sde", scheduler: "beta" });
    view.unmount();
    open("MOSS");
    fireEvent.click(screen.getByRole("button", { name: "Edit MOSS Image generator" }));
    expect(combo("Generator sampler").getAttribute("data-value")).toBe("er_sde");
    fireEvent.click(combo("Generator model"));
    fireEvent.click(screen.getByRole("option", { name: /^MiniMax Music3/ }));
    expect(combo("Generator sampler").getAttribute("data-value")).toBe("default");
    expect(combo("Generator scheduler").getAttribute("data-value")).toBe("default");
  });
  it("remembers MotionCache per generator and disables it in Animate mode", () => {
    const view = open();
    editDefaultGenerator();
    const motion = () => toggle("Enable MotionCache");
    expect(motion().getAttribute("aria-checked")).toBe("false");
    fireEvent.click(motion());
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "default")?.motionCache).toBe(true);
    pick("Generator mode", "Animate (reference video)");
    expect(motion().getAttribute("aria-checked")).toBe("false");
    expect((motion() as HTMLButtonElement).disabled).toBe(true);
    pick("Generator mode", "Text prompt");
    expect(motion().getAttribute("aria-checked")).toBe("true");
    fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
    fireEvent.click(screen.getByRole("button", { name: "New generator" }));
    expect(motion().getAttribute("aria-checked")).toBe("false");
    view.unmount();
    open();
    editDefaultGenerator();
    expect(motion().getAttribute("aria-checked")).toBe("true");
    fireEvent.click(motion());
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "default")?.motionCache).toBe(false);
  });

  it("defaults to Sage and remembers each generator's attention", () => {
    const view = open();
    editDefaultGenerator();
    expect(combo("Generator attention").getAttribute("data-value")).toBe("sage2");
    expect(optionsOf("Generator attention")).toEqual(["Exact attention", "Flash attention", "Sage attention", "Sol attention"]);
    pick("Generator attention", "Sol attention");
    expect(screen.getByText("Sol attention requires a CUDA GPU on the machine running generation.")).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
    fireEvent.click(screen.getByRole("button", { name: "New generator" }));
    expect(combo("Generator attention").getAttribute("data-value")).toBe("sage2");
    view.unmount();
    open();
    editDefaultGenerator();
    expect(combo("Generator attention").getAttribute("data-value")).toBe("sol");
  });

  it("switches NVIDIA between CUDA and Vulkan and keeps both choices after switching", async () => {
    Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
    vi.mocked(invoke).mockImplementation(async (command, args) => command === "slopfab_status" ? {
      state: "ready", dllPath: "slopfab.dll", version: "1.4.0", cudaAvailable: true,
      platform: (args as { settings: { slopfab: { options: { inferenceBackend: string } } } }).settings.slopfab.options.inferenceBackend === "vulkan" ? "Vulkan" : "CUDA 13",
      detail: "Ready.", models: [],
    } : null);
    const view = open();
    fireEvent.click(tab("Diagnostics"));
    const backend = () => combo("GPU backend") as HTMLButtonElement;
    await waitFor(() => expect(backend().disabled).toBe(false));
    expect(backend().getAttribute("data-value")).toBe("cuda");
    expect(optionsOf("GPU backend")).toEqual(["CUDA", "Vulkan"]);
    pick("GPU backend", "Vulkan");
    await waitFor(() => expect(backend().disabled).toBe(false));
    expect(backend().getAttribute("data-value")).toBe("vulkan");
    view.unmount();
    open();
    fireEvent.click(tab("Diagnostics"));
    await waitFor(() => expect(backend().disabled).toBe(false));
    expect(backend().getAttribute("data-value")).toBe("vulkan");
    pick("GPU backend", "CUDA");
    await waitFor(() => expect(backend().getAttribute("data-value")).toBe("cuda"));
    expect(localStorage.getItem("slopus.inference-backend.v1")).toBe("cuda");
  });

  it("locks machines without CUDA hardware to Vulkan despite a saved CUDA preference", async () => {
    Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
    localStorage.setItem("slopus.inference-backend.v1", "cuda");
    vi.mocked(invoke).mockResolvedValue({ state: "ready", dllPath: "slopfab.dll", version: "1.4.0", platform: "Vulkan", cudaAvailable: false, detail: "Ready.", models: [] });
    open();
    fireEvent.click(tab("Diagnostics"));
    await waitFor(() => expect(invoke).toHaveBeenCalledWith("slopfab_status", expect.anything()));
    const backend = combo("GPU backend") as HTMLButtonElement;
    expect(backend.disabled).toBe(true);
    expect(backend.getAttribute("data-value")).toBe("vulkan");
    expect(backend.textContent).toBe("Vulkan");
  });

  it("keeps the popup's saved icon choice without exposing confirmation in settings", () => {
    localStorage.setItem("slopus.reference-icon-automation.v1", "enabled");
    const view = open(null);
    const automatic = () => toggle("Automatic reference icon generation");
    expect(automatic().getAttribute("aria-checked")).toBe("true");
    expect(screen.queryByRole("switch", { name: "Ask before automatic icon generation" })).toBeNull();
    view.unmount();
    open(null);
    expect(automatic().getAttribute("aria-checked")).toBe("true");
    expect(localStorage.getItem("slopus.reference-icon-automation.v1")).toBe("enabled");
    fireEvent.click(automatic());
    expect(automatic().getAttribute("aria-checked")).toBe("false");
    expect(localStorage.getItem("slopus.reference-icon-automation.v1")).toBe("disabled");
    fireEvent.click(automatic());
    expect(automatic().getAttribute("aria-checked")).toBe("true");
    expect(localStorage.getItem("slopus.reference-icon-automation.v1")).toBe("ask");
  });

  it("keeps debug options off by default and remembers the Diagnostics choice", () => {
    const view = open();
    fireEvent.click(tab("Diagnostics"));
    expect(toggle("Enable debug options").getAttribute("aria-checked")).toBe("false");
    fireEvent.click(toggle("Enable debug options"));
    view.unmount();
    open();
    fireEvent.click(tab("Diagnostics"));
    expect(toggle("Enable debug options").getAttribute("aria-checked")).toBe("true");
    fireEvent.click(toggle("Enable debug options"));
    expect(toggle("Enable debug options").getAttribute("aria-checked")).toBe("false");
  });

  it("picks the app theme from one combo box and saves it", () => {
    open();
    fireEvent.click(tab("Appearance"));
    expect(screen.getByRole("heading", { level: 1, name: "Appearance" })).toBeTruthy();
    expect(combo("App theme").textContent).toBe("Use system setting");
    expect(optionsOf("App theme")).toEqual(["Use system setting", "Light", "Dark"]);
    pick("App theme", "Light");
    expect(localStorage.getItem("slopus.theme.v1")).toBe("light");
    expect(combo("App theme").textContent).toBe("Light");
  });

  it("opens on the engine, because that is what has to be set before anything renders", async () => {
    open();
    expect(tab("Generators").getAttribute("aria-current")).toBe("page");
    expect(screen.getByRole("heading", { name: "Generators" })).toBeTruthy();
    expect(screen.queryByRole("group", { name: "Transformer weights" })).toBeNull();
    editDefaultGenerator();
    expect(screen.getByRole("group", { name: "Transformer weights" })).toBeTruthy();
    // The other sections are not merely hidden, they are not rendered.
    expect(screen.queryByRole("combobox", { name: "App theme" })).toBeNull();
    await waitFor(() => expect(screen.getByRole("status").textContent).toContain("Browser preview"));
  });

  it("shows the compute platform selected by the desktop engine probe", async () => {
    Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
    vi.mocked(invoke).mockResolvedValue({
      state: "ready",
      dllPath: "C:\\Slopus\\slopfab.dll",
      version: "1.4.0",
      platform: "CUDA 13",
      detail: "Ready.",
      models: [],
    });
    open();
    editDefaultGenerator();
    await waitFor(() => expect(screen.getByText("CUDA 13")).toBeTruthy());
    expect(screen.getByText("Platform")).toBeTruthy();
  });

  it("swaps sections from the navigation pane, and follows the arrow keys", () => {
    open();
    const items = within(screen.getByRole("navigation", { name: "Settings sections" })).getAllByRole("button").filter((item) => item.id.startsWith("settings-tab-"));
    expect(items.map((item) => item.textContent?.replace(/\d+$/, ""))).toEqual([
      "Generators", "Workers", "Agents", "Appearance", "Diagnostics", "Updates",
    ]);
    fireEvent.click(tab("Appearance"));
    expect(combo("App theme")).toBeTruthy();
    expect(screen.queryByRole("group", { name: "Transformer weights" })).toBeNull();
    expect(screen.getByRole("heading", { level: 1 }).textContent).toBe("Appearance");

    fireEvent.keyDown(tab("Appearance"), { key: "ArrowDown" });
    expect(tab("Diagnostics").getAttribute("aria-current")).toBe("page");
    fireEvent.keyDown(tab("Diagnostics"), { key: "ArrowUp" });
    expect(tab("Appearance").getAttribute("aria-current")).toBe("page");
    fireEvent.keyDown(tab("Appearance"), { key: "Home" });
    expect(document.activeElement).toBe(tab("Generators"));
    fireEvent.keyDown(tab("Generators"), { key: "End" });
    expect(document.activeElement).toBe(tab("Updates"));
  });

  it("counts the paths still to set on the Generator item, from any section", () => {
    open();
    // Four of the five fields are required and none is set yet.
    expect(within(tab("Generators")).getByText("4")).toBeTruthy();
    expect(tab("Generators").getAttribute("aria-label")).toBe("Generators, 4 model paths to set");
    fireEvent.click(tab("Appearance"));
    expect(within(tab("Generators")).getByText("4")).toBeTruthy();
  });

  it("keeps the settings copy short", () => {
    const { container } = open();
    for (const gone of ["belongs to this computer", "stays behind when", "needs the model files", "ships with the app", "Match this computer", "whatever this computer"]) {
      expect(container.textContent, gone).not.toContain(gone);
    }
    expect(screen.queryByText("This computer")).toBeNull();
    editDefaultGenerator();
    expect(screen.queryByText("Reads your prompt so the transformer can act on it.")).toBeNull();
    expect(screen.queryByText("Set its name, generation steps, attention, and model locations on this computer.")).toBeNull();
  });

  it("keeps the tokenizer with the shared text encoder", () => {
    open();
    editDefaultGenerator();
    expect(screen.queryByRole("button", { name: "More options for Tokenizer" })).toBeNull();
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    fireEvent.click(screen.getByRole("button", { name: "Advanced Options" }));
    fireEvent.click(screen.getByRole("button", { name: "Edit Qwen3 VL 32B MiniMax H3 text encoder" }));
    expect(screen.getByLabelText("Text encoder tokenizer")).toBeTruthy();
  });

  it("shows paths in cards and edits them through the More menu", () => {
    open();
    editDefaultGenerator();
    const card = screen.getByRole("group", { name: "Transformer weights" });
    expect(card.textContent).toContain("Not set");
    expect(within(card).getByRole("button", { name: "Browse for Transformer weights" })).toBeTruthy();
    const long = "D:\\Models\\a-very-long-folder-name\\another-nested-folder\\wan2.2\\transformer-weights.safetensors";
    enterPath("Transformer weights", long);
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "default")?.paths.transformer).toBe(long);
    const shown = card.querySelector(".settings-path__value")!;
    expect(shown.textContent).toContain("…");
    expect(shown.textContent).toMatch(/transformer-weights\.safetensors$/);
    expect(shown.getAttribute("data-tooltip")).toBe(long);
    fireEvent.click(screen.getByRole("button", { name: "More options for Transformer weights" }));
    fireEvent.click(screen.getByRole("menuitem", { name: "Clear" }));
    expect(loadGeneratorTemplateSettings().templates.find(({ id }) => id === "default")?.paths.transformer).toBe("");
  });

  it("offers Clear generator paths only on the generator sub-page", () => {
    open();
    expect(screen.queryByRole("button", { name: /Clear generator paths/ })).toBeNull();
    editDefaultGenerator();
    expect(screen.getByRole("button", { name: /Clear generator paths/ })).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
    expect(screen.queryByRole("button", { name: /Clear generator paths/ })).toBeNull();
    fireEvent.click(tab("Appearance"));
    expect(screen.queryByRole("button", { name: /Clear generator paths/ })).toBeNull();
  });

  it("edits generators on a sub-page with a breadcrumb and returns on Escape or Back", async () => {
    const onClose = vi.fn();
    render(<SettingsView onClose={onClose} />);
    fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
    const opener = screen.getByRole("button", { name: "Edit Default generator" });
    opener.focus(); fireEvent.click(opener);
    expect(screen.queryByRole("dialog")).toBeNull();
    const breadcrumb = screen.getByRole("navigation", { name: "Breadcrumb" });
    expect(breadcrumb.textContent).toBe("GeneratorsMiniMax H3Default");
    expect(document.activeElement).toBe(screen.getByRole("heading", { level: 1, name: "Default" }));
    // The navigation pane stays usable while a sub-page is open.
    expect(tab("Appearance")).toBeTruthy();
    for (const group of ["General", "Performance", "Model files", /^Additional safetensors/, /^LoRAs/]) {
      expect(screen.getByRole("heading", { name: group })).toBeTruthy();
    }

    fireEvent.keyDown(screen.getByLabelText("Generator name"), { key: "Escape" });
    expect(screen.getByRole("navigation", { name: "Breadcrumb" }).textContent).toBe("GeneratorsMiniMax H3");
    expect(onClose).not.toHaveBeenCalled();
    await waitFor(() => expect(document.activeElement).toBe(screen.getByRole("button", { name: "Edit Default generator" })));

    fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    expect(screen.queryByLabelText("Generator name")).toBeNull();
    expect(onClose).not.toHaveBeenCalled();
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    expect(onClose).not.toHaveBeenCalled();
    expect(screen.getByRole("button", { name: "MiniMax H3" })).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "Back" }));
    expect(onClose).toHaveBeenCalledOnce();
  });

  it("edits LoRAs in a content dialog and discards unsaved changes on Cancel or Escape", async () => {
    const onClose = vi.fn();
    render(<SettingsView onClose={onClose} />);
    fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
    const opener = screen.getByRole("button", { name: "Edit TaoMate 3-Step LoRA" });
    opener.focus(); fireEvent.click(opener);
    const dialog = screen.getByRole("dialog", { name: "Edit LoRA" });
    const name = within(dialog).getByLabelText("LoRA name");
    expect(document.activeElement).toBe(name);
    // The page behind is hidden from assistive technology while it is open.
    expect(screen.queryByRole("main", { name: "Settings" })).toBeNull();
    expect(within(dialog).queryByLabelText("LoRA multiplier")).toBeNull();
    expect(within(dialog).getByRole("button", { name: "Save" })).toBeTruthy();
    fireEvent.change(name, { target: { value: "Unsaved name" } });
    fireEvent.keyDown(name, { key: "Escape" });
    expect(screen.queryByRole("dialog")).toBeNull();
    expect(onClose).not.toHaveBeenCalled();
    expect(loadLoras()[0].name).toBe("TaoMate 3-Step");
    await waitFor(() => expect(document.activeElement).toBe(opener));
    fireEvent.click(opener);
    fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
    expect(screen.queryByRole("dialog")).toBeNull();
  });

  it("saves and clears independent LoRA sigma shift overrides", async () => {
    open();
    fireEvent.click(screen.getByRole("button", { name: "Edit TaoMate 3-Step LoRA" }));
    fireEvent.change(screen.getByLabelText("LoRA video sigma shift override"), { target: { value: "8.5" } });
    fireEvent.change(screen.getByLabelText("LoRA audio sigma shift override"), { target: { value: "2.5" } });
    fireEvent.click(screen.getByRole("button", { name: "Save" }));
    await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
    expect(loadLoras()[0]).toMatchObject({ videoSigmaShiftOverride: 8.5, audioSigmaShiftOverride: 2.5 });
    fireEvent.click(screen.getByRole("button", { name: "Edit TaoMate 3-Step LoRA" }));
    expect((screen.getByLabelText("LoRA video sigma shift override") as HTMLInputElement).value).toBe("8.5");
    fireEvent.change(screen.getByLabelText("LoRA video sigma shift override"), { target: { value: "0" } });
    expect((screen.getByRole("button", { name: "Save" }) as HTMLButtonElement).disabled).toBe(true);
    fireEvent.change(screen.getByLabelText("LoRA video sigma shift override"), { target: { value: "" } });
    fireEvent.click(screen.getByRole("button", { name: "Save" }));
    await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
    expect(loadLoras()[0].videoSigmaShiftOverride).toBeUndefined();
    expect(loadLoras()[0].audioSigmaShiftOverride).toBe(2.5);
  });

  it("defaults icon generation to the sole available generator and remembers a separate selection", () => {
    const first = createGeneratorTemplate("Video"), second = createGeneratorTemplate("Icons");
    const templates = { templates: [first], defaultTemplateId: first.id, catalogVersion: 17 };
    saveGeneratorTemplateSettings(templates);
    const view = open(null);
    expect(combo("Reference icon generator").getAttribute("data-value")).toBe(first.id);
    view.unmount();
    saveGeneratorTemplateSettings({ ...templates, templates: [first, second] });
    const reopened = open(null);
    pick("Reference icon generator", "Icons");
    expect(loadReferenceIconGeneratorId()).toBe(second.id);
    expect(loadGeneratorTemplateSettings().defaultTemplateId).toBe(first.id);
    reopened.unmount();
    open(null);
    expect(combo("Reference icon generator").getAttribute("data-value")).toBe(second.id);
  });

  it("remembers a separate album cover generator under Icons", () => {
    const first = createGeneratorTemplate("Reference art"), second = createGeneratorTemplate("Cover art", "krea2");
    saveGeneratorTemplateSettings({ templates: [first, second], defaultTemplateId: first.id });
    const view = open(null);
    expect(screen.getByText("Icons", { selector: "h3" })).toBeTruthy();
    expect(combo("Album cover generator").getAttribute("data-value")).toBe(first.id);
    pick("Album cover generator", "Cover art");
    expect(loadAlbumCoverGeneratorId()).toBe(second.id);
    expect(combo("Reference icon generator").getAttribute("data-value")).toBe(first.id);
    view.unmount();
    open(null);
    expect(combo("Album cover generator").getAttribute("data-value")).toBe(second.id);
  });

  it("creates a generator with 20 steps, edits it on its own page, and can make it the default", () => {
    open();
    expect(screen.queryByRole("group", { name: "Transformer weights" })).toBeNull();
    const nextGeneratorName = `Generator ${loadGeneratorTemplateSettings().templates.length + 1}`;
    fireEvent.click(screen.getByRole("button", { name: "New generator" }));
    expect((screen.getByLabelText("Generator name") as HTMLInputElement).value).toBe(nextGeneratorName);
    expect(document.activeElement).toBe(screen.getByLabelText("Generator name"));
    expect((screen.getByLabelText("Generator default steps") as HTMLInputElement).value).toBe("20");

    fireEvent.change(screen.getByLabelText("Generator name"), { target: { value: "Fast draft" } });
    fireEvent.change(screen.getByLabelText("Generator default steps"), { target: { value: "12" } });
    fireEvent.change(screen.getByLabelText("Generator video sigma shift"), { target: { value: "8.5" } });
    fireEvent.change(screen.getByLabelText("Generator audio sigma shift"), { target: { value: "2.5" } });
    expect(loadGeneratorTemplateSettings().templates.find((template) => template.name === "Fast draft")).toMatchObject({ videoSigmaShift: 8.5, audioSigmaShift: 2.5 });
    expect(screen.getByRole("heading", { level: 1, name: "Fast draft" })).toBeTruthy();
    enterPath("Transformer weights", "D:\\Models\\draft.safetensors");
    fireEvent.click(screen.getByRole("button", { name: "MiniMax H3" }));
    expect(screen.queryByRole("group", { name: "Transformer weights" })).toBeNull();
    fireEvent.click(screen.getByRole("button", { name: "Set Fast draft as default" }));

    const stored = JSON.parse(localStorage.getItem("slopus.generator-templates.v1") ?? "null");
    const selected = stored.templates.find((template: { id: string }) => template.id === stored.defaultTemplateId);
    expect(selected).toMatchObject({ name: "Fast draft", defaultSteps: 12, paths: { transformer: "D:\\Models\\draft.safetensors" } });
    expect(screen.queryByRole("button", { name: "Set Fast draft as default" })).toBeNull();
    expect(screen.getByRole("button", { name: "Set Default as default" })).toBeTruthy();
  });

  it("marks the default generator in its card description instead of a radio", () => {
    open();
    expect(screen.queryByRole("radio")).toBeNull();
    const card = screen.getByRole("button", { name: "Edit Default generator" }).closest(".settings-open-card") as HTMLElement;
    expect(card.textContent).toContain("Used by default");
    expect(within(card).queryByRole("button", { name: /as default/ })).toBeNull();
  });

  it("offers only a row to reveal the log without fetching log details", async () => {
    Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });
    const info = {
      path: "C:\\Users\\Editor\\AppData\\Local\\Slopus\\logs\\slopus.log",
      previousPath: null,
      sessionId: "42-1",
      maxFileBytes: 5_242_880,
    };
    vi.mocked(invoke).mockImplementation(async (command) => command === "diagnostic_log_info" || command === "reveal_diagnostic_log"
      ? info
      : { state: "ready", dllPath: "C:\\Slopus\\slopfab.dll", version: "1.4.0", platform: "CUDA 13", detail: "Ready.", models: [] });

    open();
    fireEvent.click(tab("Diagnostics"));
    expect(screen.queryByText(info.path)).toBeNull();
    expect(screen.queryByRole("heading", { name: "Application log" })).toBeNull();
    expect(screen.queryByText(/Prompt text and credentials are not recorded/)).toBeNull();
    expect(vi.mocked(invoke).mock.calls.map(([command]) => command)).not.toContain("diagnostic_log_info");
    fireEvent.click(screen.getByRole("button", { name: "Show log file" }));
    await waitFor(() => expect(vi.mocked(invoke).mock.calls.map(([command]) => command)).toContain("reveal_diagnostic_log"));
  });

  it("configures OpenRouter and local OpenAI-compatible models without requiring a local API key", () => {
    open();
    fireEvent.click(tab("Agents"));
    const provider = (name: string) => screen.getByRole("button", { name }).closest(".ui-settings-expander") as HTMLElement;

    const openrouter = provider("OpenRouter");
    fireEvent.click(screen.getByRole("button", { name: "OpenRouter" }));
    expect(screen.getByRole("button", { name: "OpenRouter" }).getAttribute("aria-expanded")).toBe("true");
    expect((within(openrouter).getByLabelText("OpenRouter endpoint") as HTMLInputElement).value).toBe("https://openrouter.ai/api/v1");
    fireEvent.change(within(openrouter).getByLabelText("OpenRouter API key"), { target: { value: "sk-or-test" } });
    fireEvent.change(within(openrouter).getByLabelText("OpenRouter model"), { target: { value: "openai/gpt-test" } });
    expect(openrouter.textContent).toContain("Configured");

    const local = provider("Local OpenAI-compatible");
    fireEvent.change(within(local).getByLabelText("Local OpenAI-compatible endpoint"), { target: { value: "http://localhost:1234/v1" } });
    fireEvent.change(within(local).getByLabelText("Local OpenAI-compatible model"), { target: { value: "local-model" } });
    expect(local.textContent).toContain("Configured");

    const stored = JSON.parse(localStorage.getItem("slopus.agent-endpoints.v1") ?? "null");
    expect(stored.openrouter).toMatchObject({ apiKey: "sk-or-test", model: "openai/gpt-test" });
    expect(stored.local).toMatchObject({ endpoint: "http://localhost:1234/v1", model: "local-model", apiKey: "" });
  });
});