Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
73.7 KB
Raw Blame
/* Machine-level settings.
 *
 * The video engine and its weights are a property of THIS computer, not of a
 * project: a project folder copied from another machine carries paths that do
 * not exist here. They therefore live in localStorage rather than in
 * slopus.json, and are merged into `providerSettings.slopfab` only
 * on the way into a Tauri command — never on the way into a saved config.
 * Keep it that way: writing them into a project file would put one machine's
 * disk layout into a file the user is invited to move, copy, and share.
 *
 * The option names below are the contract with `Configuration::from_settings`
 * in src-tauri/core/src/slopfab/config.rs. Renaming one here without renaming it there
 * silently drops that path.
 */
import { isSigmaShift, isSampler, isScheduler, type SigmaShifts, type SamplingChoices, type Sampler, type Scheduler } from "./sampling";
import { initialH3Components, isSharedH3Field, normalizeH3Library, resolveH3Components, type H3Components } from "./h3Components";
import { generatorModel } from "./generatorModels";
import { YUE2_DEFAULT_STEPS } from "./music";
export { generatorModel, GENERATOR_MODELS } from "./generatorModels";
import { latentUpscalerPath, otherWeightPaths, TAEH3_URL } from "./upscalers";
import { loadGenerationPreviewsEnabled } from "./generationPreviewSettings";
import { DEFAULT_GENERATION_STEPS, MAX_GENERATION_STEPS, type ProjectConfig, type ProviderSetting } from "./project";
// Type-only: erased at build time, so this does not close a cycle with runtime.ts.
import type { ProviderId } from "./runtime";
import { effectiveLoras, selectionConflict, downloadableTemplateLoras, loadLoras, loraStepOverride, loraSigmaShiftOverrides, isLoraStepOverride, normalizeTemplateLoras, resolveTemplateLoras, subscribeLoras, TURBO_LORA, VIGGLE_ANIMATE_LORA, type TemplateLora } from "./loras";
import { remoteWorkerSelected, selectedWorker, WORKERS_EVENT } from "./workers";

/* Light/dark appearance is machine-level for the same reason and lives in
 * ./theme.ts, which is separate only because index.html has to read the same
 * value from a classic script before the bundle exists. */

export type EnginePathId = "transformer" | "textEncoder" | "tokenizer" | "videoVae" | "audioVae";

export interface EnginePathField {
  id: EnginePathId;
  label: string;
  /** What this file is, in the user's terms — not in the model's. */
  hint: string;
  /** A directory picker rather than a file picker. */
  directory: boolean;
  /** File extensions offered by the picker; empty means "any file". */
  extensions: string[];
  /** Generation cannot run without it. */
  required: boolean;
}

/* No entry for the engine library itself: it ships beside Slopus.exe and is
   loaded from there, so there was never a path worth asking anyone for — only
   one that could be set wrong. Weights are different: they are large, they are
   downloaded separately, and they live wherever the user put them. */
export const ENGINE_PATH_FIELDS: EnginePathField[] = [
  { id: "transformer", label: "Transformer weights", hint: "The main model that turns your description into moving pictures.", directory: false, extensions: ["safetensors", "gguf", "bin"], required: true },
  { id: "textEncoder", label: "Text encoder weights", hint: "Reads your prompt so the transformer can act on it.", directory: false, extensions: ["safetensors", "gguf", "bin"], required: true },
  { id: "videoVae", label: "Video VAE weights", hint: "Turns the model's internal picture into real video frames.", directory: false, extensions: ["safetensors", "gguf", "bin"], required: true },
  { id: "audioVae", label: "Audio VAE weights", hint: "Turns the model's internal sound into real audio.", directory: false, extensions: ["safetensors", "gguf", "bin"], required: true },
  { id: "tokenizer", label: "Tokenizer", hint: "Splits your prompt into pieces the text encoder understands. Usually a folder.", directory: true, extensions: [], required: false },
];

export type EngineSettings = Record<EnginePathId, string>;

export const EMPTY_ENGINE_SETTINGS: EngineSettings = {
  transformer: "", textEncoder: "", tokenizer: "", videoVae: "", audioVae: "",
};

const ENGINE_KEY = "slopus.engine-paths.v1";
const GENERATOR_TEMPLATES_KEY = "slopus.generator-templates.v1";
const LEGACY_ENGINE_KEY = "polstudio.engine-paths.v1";
const LEGACY_GENERATOR_TEMPLATES_KEY = "polstudio.generator-templates.v1";

function migratedStorageItem(key: string, legacyKey: string): string | null {
  const current = localStorage.getItem(key);
  if (current !== null) return current;
  const legacy = localStorage.getItem(legacyKey);
  if (legacy !== null) localStorage.setItem(key, legacy);
  return legacy;
}

export const MINIMAX_H3_MODEL_TYPE = "minimax-h3";
export const H3_IMAGE_MODEL_TYPE = "h3_image";
export const MOSS_MODEL_TYPE = "moss";
export const FIBO_MODEL_TYPE = "fibo2";
export const KREA_MODEL_TYPE = "krea2";
export const templateSupportsMusic = (template: Pick<GeneratorTemplate, "modelType">): boolean => generatorModel(template.modelType).musicGeneration;
export const templateSupportsVideo = (template: Pick<GeneratorTemplate, "modelType">): boolean => generatorModel(template.modelType).videoGeneration;
export const templateSupportsImages = (template: Pick<GeneratorTemplate, "modelType" | "mode">): boolean => generatorModel(template.modelType).imageGeneration && template.mode !== "animate";

export const templateSupportsEditing = (template: Pick<GeneratorTemplate, "modelType" | "editingModel" | "mode">): boolean =>
  templateSupportsImages(template) && generatorModel(template.modelType).imageEditing && template.editingModel !== false;
export const templateSupportsOutpainting = (template: Pick<GeneratorTemplate, "modelType" | "editingModel" | "mode">): boolean =>
  templateSupportsEditing(template) && generatorModel(template.modelType).imageOutpainting;

export interface GeneratorTemplate extends SigmaShifts, SamplingChoices {
  id: string;
  name: string;
  /** Stable model-family identifier, independent of template name and mode.
   * Open to new identifiers as other model families are added. */
  modelType: string;
  /** Whether these weights support editing; omitted legacy values use the model capability. */
  editingModel?: boolean;
  kreaVariant?: "turbo" | "raw";
  defaultSteps: number;
  attention: AttentionMode;
  motionCache?: boolean;
  mode?: "prompt" | "animate";
  paths: EngineSettings;
  videoVaeId?: string;
  audioVaeId?: string;
  /** Marks migration of the former image-only encoder into the H3 library. */
  sharedTextEncoder?: boolean;
  sources?: Partial<Record<EnginePathId, WeightSource[]>>;
  loras?: TemplateLora[];
  additionalSafetensors?: AdditionalSafetensor[];
}

export interface AdditionalSafetensor {
  id: string;
  name: string;
  url: string;
  role?: "promptEmbedding";
  downloadedPath?: string;
}

export const ANIMATE_CONDITIONING_URL = "https://huggingface.co/drbaph/Viggle-Animate-ComfyUI/resolve/main/text_cond/fixed_embed_fwd_anyframe.safetensors";

export interface WeightSource {
  url: string;
  gpuModel: string;
  minVramGb: number;
  downloadedPath?: string;
}

export function templateSamplingOptions(template: Partial<GeneratorTemplate>, overrides: TemplateLora[] = []) {
  const model = generatorModel(template.modelType);
  const library = loadLoras();
  const active = new Set(effectiveLoras(template.loras, overrides, template.modelType, library)
    .filter((entry) => entry.enabled && entry.strength !== 0).map((entry) => entry.loraId));
  const adapters = library.filter((entry) => active.has(entry.id));
  const preset = adapters.some((entry) => entry.samplingPreset);
  const omni = template.modelType === MINIMAX_H3_MODEL_TYPE && [template.paths?.transformer ?? "", ...(template.sources?.transformer ?? []).map((source) => source.url)]
    .some((path) => path.includes("fasth3_omniref_8step_pruned_int8_convrot.safetensors"));
  const samplers: Sampler[] = ["default", ...(preset ? [] : omni || template.mode === "animate" ? ["euler"] : model.samplers) as Sampler[]];
  const schedulers: Scheduler[] = ["default", ...(!omni && !preset ? model.schedulers : []) as Scheduler[]];
  const reason = preset ? "The active LoRA recipe controls the sampler and scheduler."
    : omni ? "FastH3 Omni requires Euler and its trained schedule."
    : template.mode === "animate" ? "Animate requires Euler. Adapters may also require a fixed schedule."
    : template.modelType === "yue2" ? "Choose the flow sampler in the song's Advanced settings."
    : model.musicGeneration ? "This music model uses its built-in solver and schedule." : undefined;
  return { samplers, schedulers, reason };
}

export function effectiveTemplateSampling(template: Partial<GeneratorTemplate>, overrides: TemplateLora[] = []): Required<SamplingChoices> {
  const allowed = templateSamplingOptions(template, overrides);
  return { sampler: template.sampler && allowed.samplers.includes(template.sampler) ? template.sampler : "default",
    scheduler: template.scheduler && allowed.schedulers.includes(template.scheduler) ? template.scheduler : "default" };
}

export function generatorPathFields(template: Pick<GeneratorTemplate, "mode"> & { modelType?: string }): EnginePathField[] {
  if (template.modelType === "yue2" || template.modelType === "minimax_music3") return ENGINE_PATH_FIELDS.filter(({ id }) =>
    id === "transformer" || template.modelType === "minimax_music3" && (id === "textEncoder" || id === "audioVae")).map((field) =>
    field.id === "transformer" ? { ...field, hint: "The main model that generates music from your style and lyrics." } : field);
  if ([MOSS_MODEL_TYPE, FIBO_MODEL_TYPE, KREA_MODEL_TYPE, H3_IMAGE_MODEL_TYPE].includes(template.modelType ?? "")) return ENGINE_PATH_FIELDS.filter(({ id }) => id !== "audioVae").map((field) => {
    if (field.id === "transformer") return { ...field, hint: "The main model that turns your description into an image." };
    if (field.id === "videoVae") return { ...field, label: "Image VAE weights", hint: "Decodes the model's internal picture into an image." };
    if (field.id === "tokenizer" && template.modelType === MOSS_MODEL_TYPE) return { ...field, required: true, directory: false, extensions: ["json"], hint: "The Qwen3.5 tokenizer JSON used by MOSS." };
    return field;
  });
  return template.mode === "animate"
    ? ENGINE_PATH_FIELDS.filter(({ id }) => id !== "textEncoder" && id !== "tokenizer")
    : ENGINE_PATH_FIELDS;
}

export const isDownloadUrl = (value: string): boolean => /^https?:\/\//i.test(value.trim());

export interface WeightGpu { name: string; memoryBytes: number }

export function chooseWeightSource(sources: WeightSource[], devices: WeightGpu[]): WeightSource | null {
  // Prefer an explicit GPU match, then the highest memory tier that fits.
  // Equal-ranked alternatives keep the author's order. Unknown hardware only
  // qualifies for universal variants with no minimum memory requirement.
  const matches = sources.filter((source) => !source.gpuModel.trim() && source.minVramGb === 0
    || devices.some((gpu) => gpu.name.toLowerCase().includes(source.gpuModel.trim().toLowerCase())
      // Drivers reserve part of VRAM (a 32 GB card may report 31.4 GiB).
      && Math.ceil(gpu.memoryBytes / 1024 ** 3) >= source.minVramGb));
  return matches.sort((a, b) => Number(Boolean(b.gpuModel.trim())) - Number(Boolean(a.gpuModel.trim())) || b.minVramGb - a.minVramGb)[0] ?? null;
}

/** Whether a generator can run where generation currently happens. A LAN
 *  worker downloads URL weights itself, so a template only needs a source or
 *  a local file for each model; this computer needs everything downloaded. */
export function templateUsable(template: GeneratorTemplate): boolean {
  if (selectionConflict(effectiveLoras(template.loras, [], template.modelType))) return false;
  if (!remoteWorkerSelected()) {
    try { resolveTemplateLoras(effectiveLoras(template.loras, [], template.modelType)); return !templateNeedsDownload(template); }
    catch { return false; }
  }
  if (!generatorPathFields(template).every(({ id, required }) => !required || template.paths[id].trim() || (template.sources?.[id]?.length ?? 0) > 0)) return false;
  try {
    resolveTemplateLoras(effectiveLoras(template.loras, [], template.modelType), true);
    return true;
  } catch {
    return false;
  }
}

export function templateWithSceneLoras(template: GeneratorTemplate, job?: { loraOverrides?: TemplateLora[] | null }): GeneratorTemplate {
  return { ...template, loras: effectiveLoras(template.loras, job?.loraOverrides ?? [], template.modelType) };
}

/** Downloaded client weights do not pin a worker to the client's GPU variant.
 * Explicit local files without a matching download entry remain uploads. */
function workerWeight(value: string, sources: WeightSource[] | undefined): string {
  const pathKey = (path: string) => { const normalized = path.replaceAll("\\", "/").replace(/^\/\/\?\//, ""); return /^[a-z]:\//i.test(normalized) ? normalized.toLowerCase() : normalized; };
  const downloaded = sources?.some((source) => source.downloadedPath && pathKey(source.downloadedPath) === pathKey(value));
  if (value && !isDownloadUrl(value) && !downloaded) return value;
  // The native job builder makes the authoritative choice from the connected
  // worker's info; its GPU may differ from this UI's last discovery snapshot.
  return chooseWeightSource(sources ?? [], selectedWorker()?.gpus ?? [])?.url ?? sources?.[0]?.url ?? value;
}

export function templateNeedsDownload(template: GeneratorTemplate): boolean {
  return generatorPathFields(template).some(({ id }) => isDownloadUrl(template.paths[id])
    || (template.modelType === H3_IMAGE_MODEL_TYPE && id === "textEncoder" && !template.paths[id].trim())
    || (template.modelType === MINIMAX_H3_MODEL_TYPE && (id === "videoVae" && template.videoVaeId !== undefined || id === "audioVae" && template.audioVaeId !== undefined || id === "textEncoder" && template.videoVaeId !== undefined) && !template.paths[id].trim())
    || (!template.paths[id].trim() && (template.sources?.[id]?.length ?? 0) > 0))
    || downloadableTemplateLoras(effectiveLoras(template.loras, [], template.modelType)).length > 0
    || (template.additionalSafetensors ?? []).some((file) => !file.downloadedPath || isDownloadUrl(file.downloadedPath));
}

const GENERATOR_TEMPLATES_EVENT = "slopus:generator-templates-changed";
export function subscribeGeneratorTemplates(listener: () => void) {
  const unsubscribeLoras = subscribeLoras(listener);
  const storage = (event: StorageEvent) => { if (event.key === GENERATOR_TEMPLATES_KEY || event.key === null) listener(); };
  window.addEventListener(GENERATOR_TEMPLATES_EVENT, listener);
  // Choosing a LAN worker changes which templates are usable.
  window.addEventListener(WORKERS_EVENT, listener);
  window.addEventListener("storage", storage);
  return () => {
    unsubscribeLoras();
    window.removeEventListener(GENERATOR_TEMPLATES_EVENT, listener);
    window.removeEventListener(WORKERS_EVENT, listener);
    window.removeEventListener("storage", storage);
  };
}

export type AttentionMode = "exact" | "flash2" | "sage2" | "sol";
export type InferenceBackend = "cuda" | "vulkan";
const INFERENCE_BACKEND_KEY = "slopus.inference-backend.v1";

export function loadInferenceBackend(): InferenceBackend {
  try {
    return localStorage.getItem(INFERENCE_BACKEND_KEY) === "vulkan" ? "vulkan" : "cuda";
  } catch {
    return "cuda";
  }
}

export function saveInferenceBackend(backend: InferenceBackend): void {
  try {
    localStorage.setItem(INFERENCE_BACKEND_KEY, backend);
  } catch {
    /* Keep the current settings screen usable if storage is unavailable. */
  }
}

export interface GeneratorTemplateSettings {
  templates: GeneratorTemplate[];
  defaultTemplateId: string;
  catalogVersion?: number;
  h3Components?: H3Components;
}

const copyPaths = (paths: EngineSettings): EngineSettings => ({ ...paths });

const pathsFrom = (value: unknown): EngineSettings => {
  const result = copyPaths(EMPTY_ENGINE_SETTINGS);
  if (!value || typeof value !== "object") return result;
  const record = value as Partial<Record<EnginePathId, unknown>>;
  for (const field of ENGINE_PATH_FIELDS) {
    const path = record[field.id];
    if (typeof path === "string") result[field.id] = path;
  }
  return result;
};

export function createGeneratorTemplate(name = "New template", modelType = MINIMAX_H3_MODEL_TYPE): GeneratorTemplate {
  return {
    id: `generator-template-${crypto.randomUUID()}`,
    name,
    modelType,
    editingModel: generatorModel(modelType).imageEditing,
    defaultSteps: modelType === H3_IMAGE_MODEL_TYPE ? 6 : modelType === KREA_MODEL_TYPE ? 8 : modelType === "yue2" ? YUE2_DEFAULT_STEPS : modelType === "minimax_music3" ? 30 : modelType === MOSS_MODEL_TYPE ? 50 : modelType === FIBO_MODEL_TYPE ? 4 : DEFAULT_GENERATION_STEPS,
    attention: modelType === H3_IMAGE_MODEL_TYPE || modelType === KREA_MODEL_TYPE || generatorModel(modelType).cudaOnly || generatorModel(modelType).musicGeneration ? "flash2" : "sage2",
    paths: copyPaths(EMPTY_ENGINE_SETTINGS),
  };
}

export function musicTemplates(): GeneratorTemplate[] {
  const root = "https://huggingface.co/Comfy-Org/MiniMax-Music-3/resolve/main/";
  return (["yue2", "minimax_music3"] as const).map((modelType) => {
    const paths = { ...EMPTY_ENGINE_SETTINGS, ...(modelType === "yue2" ? {
      transformer: "https://huggingface.co/Comfy-Org/YuE2/resolve/main/checkpoints/yue2_3b_int8_convrot.safetensors",
    } : { transformer: root + "diffusion_models/minimax_music3_dit_int8_convrot.safetensors",
      textEncoder: root + "text_encoders/minimax_music3_text_encoder_pruned_int8_convrot.safetensors",
      audioVae: root + "vae/minimax_music3_dav.safetensors" }) };
    return { ...createGeneratorTemplate(generatorModel(modelType).label, modelType), id: modelType, paths,
      sources: Object.fromEntries(Object.entries(paths).filter(([, url]) => url).map(([id, url]) => [id, [
        // Selection rounds detected GiB up: a minimum tier of 9 means strictly
        // more than 8 GiB, keeping 8 GiB cards on the INT8 fallback.
        ...(modelType === "yue2" && id === "transformer" ? [{ url: "https://huggingface.co/Comfy-Org/YuE2/resolve/main/checkpoints/yue2_3b_bf16.safetensors", gpuModel: "", minVramGb: 9 }] : []),
        ...(modelType === "minimax_music3" && id === "transformer" ? [
          { url: root + "diffusion_models/minimax_music3_dit_fp32.safetensors", gpuModel: "", minVramGb: 10 },
          { url: root + "diffusion_models/minimax_music3_dit_fp16.safetensors", gpuModel: "", minVramGb: 5 },
        ] : []),
        { url, gpuModel: "", minVramGb: modelType === "minimax_music3" ? id === "transformer" ? 3 : id === "textEncoder" ? 9 : 1 : 0 },
      ]])) };
  });
}

export function kreaImageTemplates(): GeneratorTemplate[] {
  const root = "https://huggingface.co/Comfy-Org/Krea-2/resolve/main/";
  return (["turbo", "raw"] as const).map((variant) => {
    const paths = { ...EMPTY_ENGINE_SETTINGS,
      transformer: `${root}diffusion_models/krea2_${variant}_int8_convrot.safetensors`,
      textEncoder: `${root}text_encoders/qwen3vl_4b_int8_convrot.safetensors`,
      videoVae: `${root}vae/qwen_image_vae.safetensors`,
    };
    return { ...createGeneratorTemplate(`Krea 2 ${variant === "raw" ? "Raw" : "Turbo"}`, KREA_MODEL_TYPE),
      id: `krea2-${variant}`, kreaVariant: variant, defaultSteps: variant === "raw" ? 52 : 8, paths,
      sources: Object.fromEntries(Object.entries(paths).filter(([, url]) => url).map(([id, url]) =>
        [id, [{ url, gpuModel: "", minVramGb: id === "transformer" ? 14 : id === "textEncoder" ? 5 : 0 }]])),
    };
  });
}

export function minimaxImageTemplate(): GeneratorTemplate {
  const root = "https://huggingface.co/Comfy-Org/MiniMax-H3-Image/resolve/main/";
  const paths = { ...EMPTY_ENGINE_SETTINGS,
    transformer: `${root}diffusion_models/minimax_h3_image_pruned_int8_convrot.safetensors`,
    textEncoder: `${root}text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors`,
    videoVae: `${root}vae/minimax_h3_image_vae_fp16.safetensors`,
  };
  return { ...createGeneratorTemplate("MiniMax H3 Image", H3_IMAGE_MODEL_TYPE), id: "minimax-h3-image", paths,
    sources: {
      transformer: [
        { url: `${root}diffusion_models/minimax_h3_image_pruned_bf16.safetensors`, gpuModel: "", minVramGb: 48 },
        { url: paths.transformer, gpuModel: "", minVramGb: 24 },
        { url: `${root}diffusion_models/minimax_h3_image_pruned_w4a8.safetensors`, gpuModel: "", minVramGb: 13 },
      ],
      textEncoder: [
        { url: `${root}text_encoders/qwen3vl_32b_minimax_h3_int8_convrot.safetensors`, gpuModel: "", minVramGb: 32 },
        { url: paths.textEncoder, gpuModel: "", minVramGb: 18 },
      ],
      videoVae: [{ url: paths.videoVae, gpuModel: "", minVramGb: 0 }],
    },
  };
}

export function mossImageTemplate(): GeneratorTemplate {
  const root = "https://huggingface.co/Comfy-Org/MOSS-Image/resolve/main/";
  const paths: EngineSettings = {
    transformer: `${root}diffusion_models/moss_image_sft_int8_convrot.safetensors`,
    textEncoder: `${root}text_encoders/qwen3.5_9b_int8_convrot.safetensors`,
    videoVae: `${root}vae/flux2-vae_small.safetensors`,
    tokenizer: "https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT/resolve/main/tokenizer/tokenizer.json",
    audioVae: "",
  };
  const sources = Object.fromEntries(Object.entries(paths).filter(([, url]) => url).map(([id, url]) => [id, [{ url, gpuModel: "", minVramGb: 0 }]]));
  return { id: "moss-image", name: "MOSS Image", modelType: MOSS_MODEL_TYPE, editingModel: false, defaultSteps: 50, attention: "flash2", paths, sources };
}

export function fiboImageTemplate(): GeneratorTemplate {
  const root = "https://huggingface.co/Comfy-Org/Fibo-2.0/resolve/main/";
  const paths: EngineSettings = {
    transformer: `${root}diffusion_models/fibo2_edit_turbo_int8_convrot.safetensors`,
    textEncoder: `${root}text_encoders/qwen3vl_4b_int8_convrot.safetensors`,
    videoVae: `${root}vae/flux2-vae.safetensors`, tokenizer: "", audioVae: "",
  };
  const sources = Object.fromEntries(Object.entries(paths).filter(([, url]) => url).map(([id, url]) => [id, [{ url, gpuModel: "", minVramGb: 0 }]]));
  return { id: "fibo2-edit-turbo", name: "Fibo 2.0 Edit Turbo", modelType: FIBO_MODEL_TYPE, editingModel: true, defaultSteps: 4, attention: "flash2", paths, sources };
}

export function fiboBaseTemplate(): GeneratorTemplate {
  const template = fiboImageTemplate();
  const transformer = "https://huggingface.co/Comfy-Org/Fibo-2.0/resolve/main/diffusion_models/fibo2_dev_int8_convrot.safetensors";
  return { ...template, id: "fibo2-base", name: "Fibo 2.0 Base", editingModel: false,
    paths: { ...template.paths, transformer },
    sources: { ...template.sources, transformer: [{ url: transformer, gpuModel: "", minVramGb: 0 }] } };
}

const MINIMAX_REF2VA_W4A8_URL = "https://huggingface.co/koongrizzly/MiniMax_H3_int4_W4A8_ConvRot_Pruned/resolve/main/diffusion_models/minimax_h3_ref2va_hybrid_b20-49_pruned_w4a8_mixed.safetensors";
const MINIMAX_FL2VA_W4A8_URL = "https://huggingface.co/Winnougan/MiniMax-H3-INT4_Convrot_ComfyUI/resolve/main/minimax_h3_fl2va_pruned-w4a8_convrot_pruned.safetensors";

export function minimaxOriginalTemplate(): GeneratorTemplate {
  const root = "https://huggingface.co/Comfy-Org/MiniMax-H3/blob/main/";
  const paths = {
    transformer: `${root}diffusion_models/minimax_h3_fl2va_pruned_int8_convrot.safetensors`,
    textEncoder: `${root}text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors`,
    videoVae: `${root}vae/minimax_h3_video_vae_fp16.safetensors`,
    audioVae: `${root}vae/minimax_h3_audio_vae_fp32.safetensors`, tokenizer: "",
  };
  const sources: GeneratorTemplate["sources"] = Object.fromEntries(ENGINE_PATH_FIELDS.filter(({ id }) => paths[id]).map(({ id }) => [id, [{ url: paths[id], gpuModel: "", minVramGb: id === "textEncoder" ? 16 : id === "videoVae" ? 6 : id === "audioVae" ? 1 : 0 }]]));
  sources.transformer = [
    { url: paths.transformer, gpuModel: "", minVramGb: 21 },
    { url: MINIMAX_FL2VA_W4A8_URL, gpuModel: "", minVramGb: 13 },
    { url: "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/diffusion_models/minimax_h3_fl2va_pruned_w6a8.safetensors", gpuModel: "", minVramGb: 16 },
  ];
  return { id: "minimax-h3-original", name: "First/Last Frame", modelType: MINIMAX_H3_MODEL_TYPE, defaultSteps: 20, attention: "sage2", paths, sources };
}

function minimaxVariantTemplate(id: string, name: string, transformer: string, defaultSteps = 20): GeneratorTemplate {
  const template = minimaxOriginalTemplate();
  return { ...template, id, name, defaultSteps,
    paths: { ...template.paths, transformer },
    sources: { ...template.sources, transformer: template.sources!.transformer!.map((source) =>
      source.url === template.paths.transformer ? { ...source, url: transformer } : source) },
  };
}

export function minimaxReferencesTemplate(): GeneratorTemplate {
  const template = minimaxVariantTemplate("minimax-h3-references", "References",
    "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors");
  return { ...template, sources: { ...template.sources, transformer: [
    { url: template.paths.transformer, gpuModel: "", minVramGb: 21 },
    { url: MINIMAX_REF2VA_W4A8_URL, gpuModel: "", minVramGb: 13 },
    { url: "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/diffusion_models/minimax_h3_ref2va_pruned_w6a8.safetensors", gpuModel: "", minVramGb: 16 },
  ] } };
}

export function minimaxFastTemplate(): GeneratorTemplate {
  const template = minimaxVariantTemplate("minimax-h3-fast", "FastH3 Omni",
    "https://huggingface.co/FastVideo/FastH3-Omni-Comfy/resolve/main/diffusion_models/fasth3_omniref_8step_pruned_int8_convrot.safetensors", 8);
  const videoVae = "https://huggingface.co/Comfy-Org/MiniMax-H3/blob/main/vae/minimax_h3_video_vae_int8_convrot.safetensors";
  return { ...template,
    paths: { ...template.paths, videoVae },
    sources: { ...template.sources,
      transformer: [{ url: template.paths.transformer, gpuModel: "", minVramGb: 22 },
        { url: "https://huggingface.co/berryber09/FastH3-OmniRef-8step-pruned-w4a8/resolve/main/fasth3_omniref_8step_pruned_w4a8.safetensors", gpuModel: "", minVramGb: 17 }],
      videoVae: [{ url: videoVae, gpuModel: "", minVramGb: 3 }] },
  };
}

export function minimaxSingularityTemplate(): GeneratorTemplate {
  const template = minimaxOriginalTemplate();
  const transformer = "https://huggingface.co/WarmBloodAban/Minimax-h3_Singularity/blob/main/Minimax-h3_Singularity_ref2va_Pruned_v1.3_int8.safetensors";
  return { ...template, id: "minimax-h3-singularity", name: "Singularity", defaultSteps: 4,
    loras: [{ loraId: TURBO_LORA.id, enabled: true, strength: 1 }],
    paths: { ...template.paths, transformer },
    sources: { ...template.sources, transformer: [{ url: transformer, gpuModel: "", minVramGb: 21 },
      { url: "https://huggingface.co/WarmBloodAban/Minimax-h3_Singularity/resolve/main/Minimax-h3_Singularity_ref2va_v1.3_Pruned_w4a8.safetensors", gpuModel: "", minVramGb: 12 }] },
  };
}

export function minimaxSingularityV2Template(): GeneratorTemplate {
  const template = minimaxSingularityTemplate();
  const root = "https://huggingface.co/WAS/Minimax-h3_Singularity_v2_pruned/resolve/main/";
  const transformer = root + "Minimax-h3_Singularity_ref2va_v2_pruned_int8_convrot_r2.safetensors";
  return { ...template, id: "minimax-h3-singularity-v2", name: "Singularity v2",
    paths: { ...template.paths, transformer },
    sources: { ...template.sources, transformer: [
      { url: transformer, gpuModel: "", minVramGb: 21 },
      { url: root + "Minimax-h3_Singularity_ref2va_v2_pruned_w6a8_r2.safetensors", gpuModel: "", minVramGb: 16 },
      { url: root + "Minimax-h3_Singularity_ref2va_v2_pruned_w4a8.safetensors", gpuModel: "", minVramGb: 12 },
    ] },
  };
}

export function viggleAnimateTemplate(): GeneratorTemplate {
  const template = minimaxOriginalTemplate();
  const transformer = "https://huggingface.co/DeepBeepMeep/MiniMax-H3/resolve/main/Viggle-Animate-pruned_rank8_int8_convrot.safetensors";
  return { ...template, id: "viggle-animate", name: "Animate", mode: "animate", defaultSteps: 4,
    additionalSafetensors: [{ id: "animate-conditioning", name: "Animate conditioning", url: ANIMATE_CONDITIONING_URL, role: "promptEmbedding" }],
    loras: [{ loraId: VIGGLE_ANIMATE_LORA.id, enabled: true, strength: 1 }],
    paths: { ...template.paths, transformer },
    sources: { ...template.sources, transformer: [{ url: transformer, gpuModel: "", minVramGb: 21 }] },
  };
}

const initialTemplateSettings = (paths = EMPTY_ENGINE_SETTINGS): GeneratorTemplateSettings => normalizeTemplateSettings({
  templates: [{ id: "default", name: "Default", modelType: MINIMAX_H3_MODEL_TYPE, defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(paths) }, minimaxOriginalTemplate(), minimaxReferencesTemplate(), minimaxFastTemplate(), minimaxSingularityTemplate(), viggleAnimateTemplate(), mossImageTemplate(), fiboImageTemplate(), fiboBaseTemplate(), ...musicTemplates(), ...kreaImageTemplates(), minimaxSingularityV2Template(), minimaxImageTemplate()],
  defaultTemplateId: "default",
  catalogVersion: 23,
})!;

const normalizeTemplateSettings = (value: unknown, shareComponents = true): GeneratorTemplateSettings | null => {
  if (!value || typeof value !== "object") return null;
  const record = value as { templates?: unknown; defaultTemplateId?: unknown; catalogVersion?: unknown; h3Components?: unknown };
  if (!Array.isArray(record.templates)) return null;
  const ids = new Set<string>();
  const templates = record.templates.flatMap((item): GeneratorTemplate[] => {
    if (!item || typeof item !== "object") return [];
    const candidate = item as Partial<Record<keyof GeneratorTemplate, unknown>>;
    const id = typeof candidate.id === "string" ? candidate.id.trim() : "";
    if (!id || ids.has(id)) return [];
    ids.add(id);
    const name = typeof candidate.name === "string" && candidate.name.trim() ? candidate.name.trim() : "Untitled template";
    const modelType = typeof candidate.modelType === "string" && candidate.modelType.trim() ? candidate.modelType.trim() : MINIMAX_H3_MODEL_TYPE;
    const defaultSteps = modelType === H3_IMAGE_MODEL_TYPE ? 6 : typeof candidate.defaultSteps === "number"
      && Number.isInteger(candidate.defaultSteps)
      && candidate.defaultSteps >= 2
      && candidate.defaultSteps <= MAX_GENERATION_STEPS
      ? candidate.defaultSteps
      : modelType === KREA_MODEL_TYPE ? candidate.kreaVariant === "raw" ? 52 : 8 : modelType === "yue2" ? YUE2_DEFAULT_STEPS : modelType === "minimax_music3" ? 30 : modelType === FIBO_MODEL_TYPE ? 4 : DEFAULT_GENERATION_STEPS;
    const attention = modelType === H3_IMAGE_MODEL_TYPE ? "flash2" : candidate.attention === "exact" || candidate.attention === "flash2" || candidate.attention === "sol" ? candidate.attention : "sage2";
    const paths = pathsFrom(candidate.paths);
    const sources: GeneratorTemplate["sources"] = {};
    for (const field of ENGINE_PATH_FIELDS) {
      const raw = (candidate.sources as Record<string, unknown> | undefined)?.[field.id];
      const entries: WeightSource[] = Array.isArray(raw) ? raw.flatMap((source) => {
        if (!source || typeof source.url !== "string" || !isDownloadUrl(source.url)) return [];
        return [{ url: source.url.trim(), gpuModel: typeof source.gpuModel === "string" ? source.gpuModel : "",
          minVramGb: typeof source.minVramGb === "number" && Number.isFinite(source.minVramGb) ? Math.max(0, source.minVramGb) : 0,
          ...(typeof source.downloadedPath === "string" ? { downloadedPath: source.downloadedPath } : {}) }];
      }) : [];
      if (isDownloadUrl(paths[field.id]) && !entries.some((source) => source.url === paths[field.id].trim())) {
        entries.unshift({ url: paths[field.id].trim(), gpuModel: "", minVramGb: 0 });
      }
      if (entries.length) sources[field.id] = entries;
    }
    const additionalIds = new Set<string>();
    const additionalSafetensors: AdditionalSafetensor[] = Array.isArray(candidate.additionalSafetensors)
      ? candidate.additionalSafetensors.flatMap((file) => {
        if (!file || typeof file.id !== "string" || !file.id.trim() || additionalIds.has(file.id)
          || typeof file.url !== "string" || !isDownloadUrl(file.url)) return [];
        additionalIds.add(file.id);
        return [{ id: file.id, name: typeof file.name === "string" && file.name.trim() ? file.name.trim() : "Additional safetensor",
          url: file.url.trim(), ...(file.role === "promptEmbedding" ? { role: "promptEmbedding" as const } : {}),
          ...(typeof file.downloadedPath === "string" && file.downloadedPath.trim() && !isDownloadUrl(file.downloadedPath) ? { downloadedPath: file.downloadedPath } : {}) }];
      }) : [];
    return [{ id, name, modelType, defaultSteps, attention, paths, sources,
      ...(candidate.sharedTextEncoder === true ? { sharedTextEncoder: true } : {}),
      ...(typeof candidate.videoVaeId === "string" ? { videoVaeId: candidate.videoVaeId } : {}),
      ...(typeof candidate.audioVaeId === "string" ? { audioVaeId: candidate.audioVaeId } : {}),
      ...(typeof candidate.editingModel === "boolean" ? { editingModel: candidate.editingModel } : {}),
      ...(candidate.kreaVariant === "raw" || candidate.kreaVariant === "turbo" ? { kreaVariant: candidate.kreaVariant } : {}),
      ...(isSampler(candidate.sampler) ? { sampler: candidate.sampler } : {}),
      ...(isScheduler(candidate.scheduler) ? { scheduler: candidate.scheduler } : {}),
      ...(isSigmaShift(candidate.videoSigmaShift) ? { videoSigmaShift: candidate.videoSigmaShift } : {}),
      ...(isSigmaShift(candidate.audioSigmaShift) ? { audioSigmaShift: candidate.audioSigmaShift } : {}),
      ...(typeof candidate.motionCache === "boolean" ? { motionCache: candidate.motionCache } : {}),
      ...(candidate.additionalSafetensors !== undefined ? { additionalSafetensors } : {}),
      ...(candidate.mode === "animate" || candidate.mode === "prompt" ? { mode: candidate.mode } : {}),
      ...(candidate.loras !== undefined ? { loras: normalizeTemplateLoras(candidate.loras) } : {}) }];
  });
  if (templates.length === 0) return null;
  const requestedDefault = typeof record.defaultTemplateId === "string" ? record.defaultTemplateId : "";
  const shared = shareComponents ? normalizeH3Library(templates, record.h3Components, requestedDefault)
    : { templates, ...(record.h3Components ? { h3Components: record.h3Components as H3Components } : {}) };
  return {
    ...shared,
    defaultTemplateId: !shareComponents ? requestedDefault : shared.templates.find((template) => template.id === requestedDefault && templateUsable(template))?.id
      ?? shared.templates.find(templateUsable)?.id ?? "",
    catalogVersion: typeof record.catalogVersion === "number" && [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23].includes(record.catalogVersion) ? record.catalogVersion : 0,
  };
};

/** Generator templates are machine-local because every path names this
 * computer. A pre-template installation is migrated in memory into its one
 * Default template; the next edit persists the new format. */
export function loadGeneratorTemplateSettings(): GeneratorTemplateSettings {
  try {
    const stored = migratedStorageItem(GENERATOR_TEMPLATES_KEY, LEGACY_GENERATOR_TEMPLATES_KEY);
    if (stored) {
      let normalized = normalizeTemplateSettings(JSON.parse(stored), false);
      if (normalized) {
        if ((normalized.catalogVersion ?? 0) < 2) {
          const bundled = minimaxOriginalTemplate();
          const existing = normalized.templates.find((template) => template.id === bundled.id);
          if (!normalized.catalogVersion && !existing) normalized.templates.push(bundled);
          // Upgrade the original catalog entry without replacing custom variants or local paths.
          for (const field of ["transformer"] as const) {
            const variants = existing?.sources?.[field];
            const defaults = bundled.sources![field]!;
            if (variants?.length === 1 && variants[0].url === bundled.paths[field]
              && !variants[0].gpuModel.trim() && variants[0].minVramGb === 0) {
              existing!.sources![field] = [{ ...variants[0], minVramGb: defaults[0].minVramGb }, { ...defaults[1] }];
            }
          }
          normalized.catalogVersion = 2;
        }
        if ((normalized.catalogVersion ?? 0) < 3) {
          const bundled = minimaxOriginalTemplate();
          const existing = normalized.templates.find((template) => template.id === bundled.id);
          const removedUrl = "https://huggingface.co/Merserk/qwen3vl-4b-int4-convrot/resolve/main/qwen3vl_4b_int4_convrot.safetensors";
          const encoders = existing?.sources?.textEncoder;
          if (existing && encoders) {
            const removed = encoders.filter((source) => source.url === removedUrl);
            const retained = encoders.filter((source) => source.url !== removedUrl).map((source) =>
              source.url === bundled.paths.textEncoder && !source.gpuModel.trim() && source.minVramGb === 13
                ? { ...source, minVramGb: 0 } : source);
            if (removed.length && !retained.some((source) => source.url === bundled.paths.textEncoder)) {
              retained.push({ ...bundled.sources!.textEncoder![0] });
            }
            if (existing.paths.textEncoder.trim() === removedUrl
              || removed.some((source) => source.downloadedPath && source.downloadedPath === existing.paths.textEncoder)) {
              const original = retained.find((source) => source.url === bundled.paths.textEncoder)!;
              existing.paths.textEncoder = original.downloadedPath || original.url;
            }
            existing.sources!.textEncoder = retained;
          }
          // A replaced local encoder may now need downloading and cannot remain the default.
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 3 }, false)!;
        }
        if ((normalized.catalogVersion ?? 0) < 4) {
          const original = normalized.templates.find((template) => template.id === "minimax-h3-original");
          if (original?.name === "Minimax H3 Original") original.name = "First/Last Frame";
          for (const template of [minimaxReferencesTemplate(), minimaxFastTemplate()]) {
            if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          }
          normalized.catalogVersion = 4;
        }
        if ((normalized.catalogVersion ?? 0) < 5) {
          const template = minimaxSingularityTemplate();
          if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized.catalogVersion = 5;
        }
        if ((normalized.catalogVersion ?? 0) < 6) {
          const singularity = normalized.templates.find(({ id }) => id === "minimax-h3-singularity");
          if (singularity && !singularity.loras?.some(({ loraId }) => loraId === TURBO_LORA.id)) {
            singularity.loras = [...(singularity.loras ?? []), { loraId: TURBO_LORA.id, enabled: true, strength: 1 }];
          }
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 6 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 7) {
          const template = viggleAnimateTemplate();
          if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 7 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 8) {
          const animate = normalized.templates.find(({ id }) => id === "viggle-animate");
          if (animate && !animate.additionalSafetensors?.some((file) => file.role === "promptEmbedding")) {
            animate.additionalSafetensors = [...(animate.additionalSafetensors ?? []), ...viggleAnimateTemplate().additionalSafetensors!];
          }
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 8 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 9) {
          const fast = normalized.templates.find(({ id }) => id === "minimax-h3-fast");
          if (fast) {
            const bundled = minimaxFastTemplate();
            const oldUrls = {
              transformer: "https://huggingface.co/datasets/jacokon/fasth3-live/resolve/main/minimax_h3_fl2va_fasth3_dense_pruned_int8_convrot.safetensors",
              videoVae: minimaxOriginalTemplate().paths.videoVae,
            };
            for (const field of ["transformer", "videoVae"] as const) {
              const matchesOldUrl = (url: string) => url.replace("/blob/", "/resolve/") === oldUrls[field].replace("/blob/", "/resolve/");
              const sources = fast.sources?.[field];
              if (matchesOldUrl(fast.paths[field]) || sources?.some((source) => matchesOldUrl(source.url)
                && source.downloadedPath === fast.paths[field])) {
                fast.paths[field] = bundled.paths[field];
              }
              if (sources) {
                fast.sources![field] = sources.map((source) => {
                  if (!matchesOldUrl(source.url)) return source;
                  const { downloadedPath: _downloadedPath, ...updated } = source;
                  return { ...updated, url: bundled.paths[field] };
                });
              }
            }
            if (fast.defaultSteps === 6) fast.defaultSteps = bundled.defaultSteps;
          }
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 9 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 10) {
          const template = mossImageTemplate();
          if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 10 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 11) {
          const fast = normalized.templates.find(({ id }) => id === "minimax-h3-fast");
          if (fast) {
            const bundled = minimaxFastTemplate();
            if (fast.name === "First/Last Frame Fast") fast.name = bundled.name;
            const oldUrl = "https://huggingface.co/FastVideo/FastVideo-FastH3-Comfy/resolve/main/diffusion_models/fastvideo_fasth3_8step_v2_pruned_int8_convrot.safetensors";
            const matchesOldUrl = (url: string) => url.replace("/blob/", "/resolve/") === oldUrl;
            const sources = fast.sources?.transformer;
            if (matchesOldUrl(fast.paths.transformer) || sources?.some((source) => matchesOldUrl(source.url) && source.downloadedPath === fast.paths.transformer)) {
              fast.paths.transformer = bundled.paths.transformer;
            }
            if (sources) fast.sources!.transformer = sources.map((source) => {
              if (!matchesOldUrl(source.url)) return source;
              const { downloadedPath: _downloadedPath, ...updated } = source;
              return { ...updated, url: bundled.paths.transformer };
            });
          }
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 11 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 12) {
          const fast = normalized.templates.find(({ id }) => id === "minimax-h3-fast");
          if (fast) {
            const bundled = minimaxFastTemplate();
            const fallbackUrl = MINIMAX_REF2VA_W4A8_URL;
            const canonical = (url: string) => url.trim().replace("/blob/", "/resolve/");
            const sources = fast.sources?.transformer ?? [];
            const removed = sources.filter((source) => canonical(source.url) === fallbackUrl);
            const retained = sources.filter((source) => canonical(source.url) !== fallbackUrl).map((source) =>
              canonical(source.url) === bundled.paths.transformer && !source.gpuModel.trim() && source.minVramGb === 21
                ? { ...source, minVramGb: 0 } : source);
            const usedFallback = canonical(fast.paths.transformer) === fallbackUrl
              || removed.some((source) => source.downloadedPath && source.downloadedPath === fast.paths.transformer);
            if ((removed.length || usedFallback) && !retained.some((source) => canonical(source.url) === bundled.paths.transformer)) {
              retained.push({ ...bundled.sources!.transformer![0] });
            }
            if (usedFallback) {
              const omni = retained.find((source) => canonical(source.url) === bundled.paths.transformer)!;
              fast.paths.transformer = omni.downloadedPath || omni.url;
            }
            if (sources.length || retained.length) fast.sources = { ...fast.sources, transformer: retained };
          }
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 12 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 13) {
          const original = normalized.templates.find(({ id }) => id === "minimax-h3-original");
          if (original) {
            const isOldFallback = (url: string) => url.trim().replace("/blob/", "/resolve/") === MINIMAX_REF2VA_W4A8_URL;
            const sources = original.sources?.transformer;
            if (isOldFallback(original.paths.transformer) || sources?.some((source) => isOldFallback(source.url) && source.downloadedPath === original.paths.transformer)) {
              original.paths.transformer = sources?.find((source) => source.url === MINIMAX_FL2VA_W4A8_URL)?.downloadedPath || MINIMAX_FL2VA_W4A8_URL;
            }
            if (sources) original.sources!.transformer = sources.map((source) => {
              if (!isOldFallback(source.url)) return source;
              const { downloadedPath: _downloadedPath, ...updated } = source;
              return { ...updated, url: MINIMAX_FL2VA_W4A8_URL };
            });
          }
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 13 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 14) {
          const template = fiboImageTemplate();
          if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 14 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 15) {
          const template = fiboBaseTemplate();
          if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 15 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 16) {
          for (const template of musicTemplates()) if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 16 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 17) {
          const yue = musicTemplates()[0];
          const bf16 = yue.sources!.transformer![0];
          normalized.templates = normalized.templates.map((template) => {
            const sources = template.sources?.transformer ?? [];
            if (template.id !== yue.id || template.modelType !== yue.modelType
              || !sources.some((source) => source.url === yue.paths.transformer)
              || sources.some((source) => source.url === bf16.url)) return template;
            return { ...template, sources: { ...template.sources, transformer: [bf16, ...sources] } };
          });
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 17 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 18) {
          const canonical = (url: string) => url.trim().replace("/blob/", "/resolve/");
          const bundled = [minimaxOriginalTemplate(), minimaxReferencesTemplate(), minimaxFastTemplate(), minimaxSingularityTemplate(), viggleAnimateTemplate(), ...musicTemplates()];
          const limits = new Map([
            ...bundled.flatMap((template) => Object.values(template.sources ?? {}).flat()),
            ...initialH3Components().templates.flatMap((entry) => entry.sources),
          ].map((source) => [canonical(source.url), source.minVramGb]));
          // Only replace the old unrestricted defaults; retain user limits, GPU
          // rules, custom URLs and downloaded paths, including shared components.
          const upgrade = (source: WeightSource): WeightSource => {
            const minimum = limits.get(canonical(source.url));
            return minimum && source.minVramGb === 0 && !source.gpuModel.trim()
              ? { ...source, minVramGb: minimum } : source;
          };
          normalized.templates = normalized.templates.map((template) => ({ ...template,
            sources: Object.fromEntries(Object.entries(template.sources ?? {}).map(([field, sources]) => [field, sources!.map(upgrade)])),
          }));
          if (normalized.h3Components) normalized.h3Components = { ...normalized.h3Components,
            templates: normalized.h3Components.templates.map((entry) => ({ ...entry, sources: entry.sources.map(upgrade) })),
          };
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 18 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 19) {
          const music = musicTemplates()[1];
          const canonical = (url: string) => url.trim().replace("/blob/", "/resolve/");
          normalized.templates = normalized.templates.map((template) => {
            const sources = template.sources?.transformer ?? [];
            if (template.id !== music.id || template.modelType !== music.modelType
              || !sources.some((source) => canonical(source.url) === music.paths.transformer)) return template;
            const missing = music.sources!.transformer!.filter((source) =>
              !sources.some((existing) => canonical(existing.url) === source.url));
            return { ...template, sources: { ...template.sources, transformer: [...missing, ...sources] } };
          });
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 19 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 20) {
          for (const template of kreaImageTemplates()) if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 20 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 21) {
          const canonical = (url: string) => url.trim().replace("/blob/", "/resolve/");
          const bundled = [minimaxOriginalTemplate(), minimaxReferencesTemplate(), minimaxFastTemplate(), minimaxSingularityTemplate()];
          normalized.templates = normalized.templates.map((template) => {
            const catalog = bundled.find(({ id, modelType }) => id === template.id && modelType === template.modelType);
            const defaults = catalog?.sources?.transformer;
            const sources = template.sources?.transformer ?? [];
            if (!defaults || !sources.some((source) => defaults.some((entry) => canonical(entry.url) === canonical(source.url)))) return template;
            const retained = sources.map((source) =>
              [MINIMAX_FL2VA_W4A8_URL, MINIMAX_REF2VA_W4A8_URL].includes(canonical(source.url))
                && source.minVramGb === 12 && !source.gpuModel.trim() ? { ...source, minVramGb: 13 } : source);
            // Add only the new variants; retain removals of older catalog sources.
            const previousUrls = [canonical(catalog!.paths.transformer), MINIMAX_FL2VA_W4A8_URL, MINIMAX_REF2VA_W4A8_URL];
            const missing = defaults.filter((source) => !previousUrls.includes(canonical(source.url))
              && !sources.some((entry) => canonical(entry.url) === canonical(source.url)));
            return { ...template, sources: { ...template.sources, transformer: [...retained, ...missing] } };
          });
          const singularity = minimaxSingularityV2Template();
          if (!normalized.templates.some(({ id }) => id === singularity.id)) normalized.templates.push(singularity);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 21 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 22) {
          normalized.templates = normalized.templates.map(template => template.modelType === "yue2" && template.defaultSteps === 32
            ? { ...template, defaultSteps: YUE2_DEFAULT_STEPS } : template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 22 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        if ((normalized.catalogVersion ?? 0) < 23) {
          const template = minimaxImageTemplate();
          if (!normalized.templates.some(({ id }) => id === template.id)) normalized.templates.push(template);
          normalized = normalizeTemplateSettings({ ...normalized, catalogVersion: 23 }, false)!;
          localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
        }
        const shared = normalizeTemplateSettings(normalized)!;
        if (normalized.templates.some((template) => template.modelType === H3_IMAGE_MODEL_TYPE && !template.sharedTextEncoder)
          || JSON.stringify(normalized.h3Components) !== JSON.stringify(shared.h3Components)) localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(shared));
        return shared;
      }
    }
    const legacy = migratedStorageItem(ENGINE_KEY, LEGACY_ENGINE_KEY);
    return initialTemplateSettings(legacy ? pathsFrom(JSON.parse(legacy)) : EMPTY_ENGINE_SETTINGS);
  } catch {
    return initialTemplateSettings();
  }
}

export function saveGeneratorTemplateSettings(settings: GeneratorTemplateSettings, options: { strict?: boolean } = {}): void {
  // Older API clients replace generators only; keep the independently edited library.
  if (!settings.h3Components && (settings.catalogVersion ?? 17) >= 17) {
    try {
      const stored = localStorage.getItem(GENERATOR_TEMPLATES_KEY);
      const library = stored ? JSON.parse(stored).h3Components : undefined;
      if (library) settings = { ...settings, h3Components: library };
    } catch { /* Normalization below handles a missing or damaged store. */ }
  }
  const normalized = normalizeTemplateSettings(settings, (settings.catalogVersion ?? 17) >= 17) ?? initialTemplateSettings();
  try {
    localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));
  } catch (error) {
    if (options.strict) throw error;
    /* The current React state remains usable for this session. */
  }
  queueMicrotask(() => window.dispatchEvent(new Event(GENERATOR_TEMPLATES_EVENT)));
}

export type GeneratorMedium = "video" | "image" | "music";
const ACTIVE_GENERATOR_EVENT = "slopus:active-generator-changed";
const activeGeneratorKey = (medium: GeneratorMedium) => `slopus.${medium}-generator-template.v1`;
const activeGeneratorFallback: Partial<Record<GeneratorMedium, string>> = {};

export function loadActiveGeneratorId(medium: GeneratorMedium): string {
  if (activeGeneratorFallback[medium] !== undefined) return activeGeneratorFallback[medium]!;
  try { return localStorage.getItem(activeGeneratorKey(medium)) ?? ""; } catch { return ""; }
}

export function saveActiveGeneratorId(medium: GeneratorMedium, id: string) {
  try { localStorage.setItem(activeGeneratorKey(medium), id); delete activeGeneratorFallback[medium]; }
  catch { activeGeneratorFallback[medium] = id; }
  window.dispatchEvent(new Event(ACTIVE_GENERATOR_EVENT));
}

export function subscribeActiveGenerators(listener: () => void) {
  const storage = (event: StorageEvent) => {
    if (event.key === null || (["video", "image", "music"] as const).some((medium) => event.key === activeGeneratorKey(medium))) listener();
  };
  window.addEventListener(ACTIVE_GENERATOR_EVENT, listener);
  window.addEventListener("storage", storage);
  return () => { window.removeEventListener(ACTIVE_GENERATOR_EVENT, listener); window.removeEventListener("storage", storage); };
}

const supportsMedium = (template: GeneratorTemplate, medium?: GeneratorMedium) =>
  medium === "video" ? templateSupportsVideo(template) : medium === "image" ? templateSupportsImages(template) : medium === "music" ? templateSupportsMusic(template) : true;

export function defaultGeneratorTemplate(settings = loadGeneratorTemplateSettings(), medium?: GeneratorMedium): GeneratorTemplate {
  const eligible = settings.templates.filter((template) => supportsMedium(template, medium));
  return eligible.find((template) => template.id === settings.defaultTemplateId && templateUsable(template))
    ?? eligible.find(templateUsable)
    ?? { id: "", name: "No downloaded generators", modelType: MINIMAX_H3_MODEL_TYPE, defaultSteps: DEFAULT_GENERATION_STEPS, attention: "sage2", paths: copyPaths(EMPTY_ENGINE_SETTINGS) };
}

/** Match the image page's remembered selection when initializing new images. */
export function selectedImageGeneratorTemplate(settings = loadGeneratorTemplateSettings()): GeneratorTemplate {
  return selectedGeneratorTemplate("image", settings);
}

export function selectedGeneratorTemplate(medium: GeneratorMedium, settings = loadGeneratorTemplateSettings(), id = loadActiveGeneratorId(medium)): GeneratorTemplate {
  return settings.templates.find((template) => template.id === id && supportsMedium(template, medium))
    ?? defaultGeneratorTemplate(settings, medium);
}

export function loadDefaultGenerationSteps(): number {
  return defaultGeneratorTemplate().defaultSteps;
}

/** Reads what is stored, ignoring anything that is not a string: a hand-edited
 *  or half-written entry must not take the whole settings screen down. */
export function loadEngineSettings(): EngineSettings {
  return copyPaths(defaultGeneratorTemplate().paths);
}

export function saveEngineSettings(settings: EngineSettings): void {
  const current = loadGeneratorTemplateSettings();
  saveGeneratorTemplateSettings({
    ...current,
    templates: current.templates.map((template) => template.id === current.defaultTemplateId
      ? { ...template, paths: copyPaths(settings) }
      : template),
  });
}

/** The `slopfab` provider setting these paths describe, with blanks dropped so
 *  an unset field falls through to whatever the project (or the Rust default)
 *  already had rather than overwriting it with "". */
export function engineProviderSetting(settings: EngineSettings, base?: ProviderSetting, attention = defaultGeneratorTemplate().attention, selection = defaultGeneratorTemplate().loras, mode = defaultGeneratorTemplate().mode, additionalSafetensors = defaultGeneratorTemplate().additionalSafetensors, motionCache = defaultGeneratorTemplate().motionCache ?? false, sources = defaultGeneratorTemplate().sources, shifts: SigmaShifts & SamplingChoices & { modelType?: string; editingModel?: boolean; kreaVariant?: "raw" | "turbo" } = defaultGeneratorTemplate(), sceneLoras: TemplateLora[] = []): ProviderSetting {
  // Resolve again at submission: a queued generator may predate a default encoder change.
  if (isSharedH3Field(shifts.modelType, "textEncoder")) {
    const library = loadGeneratorTemplateSettings().h3Components!;
    const resolved = resolveH3Components({ id: "", name: "", defaultSteps: 20, attention, ...shifts,
      modelType: shifts.modelType!, mode, paths: settings, sources } as GeneratorTemplate, library);
    // Legacy callers may supply only paths; named VAE links are resolved by the settings loader.
    settings = { ...settings, textEncoder: resolved.paths.textEncoder, tokenizer: resolved.paths.tokenizer,
      ...("videoVaeId" in shifts ? { videoVae: resolved.paths.videoVae } : {}),
      ...("audioVaeId" in shifts ? { audioVae: resolved.paths.audioVae } : {}) };
    sources = { ...sources, textEncoder: resolved.sources?.textEncoder, tokenizer: resolved.sources?.tokenizer,
      ...("videoVaeId" in shifts ? { videoVae: resolved.sources?.videoVae } : {}),
      ...("audioVaeId" in shifts ? { audioVae: resolved.sources?.audioVae } : {}) };
  }
  // A LAN worker receives URLs for weights it should download itself.
  const remote = remoteWorkerSelected();
  const options: ProviderSetting["options"] = { ...(base?.options ?? {}), attention, inferenceBackend: loadInferenceBackend() };
  const pathFields = generatorPathFields({ modelType: shifts.modelType, mode });
  options.modelType = shifts.modelType ?? MINIMAX_H3_MODEL_TYPE;
  options.editingModel = templateSupportsEditing({ modelType: options.modelType, editingModel: shifts.editingModel, mode });
  // Always replace project-carried adapter paths with this machine's selection.
  delete options.kreaVariant;
  if (shifts.modelType === KREA_MODEL_TYPE) options.kreaVariant = shifts.kreaVariant ?? "turbo";
  delete options.loras;
  delete options.schedule;
  delete options.sampler;
  delete options.scheduler;
  delete options.stepOverride;
  delete options.samplingPreset;
  for (const key of ["videoSigmaShift", "audioSigmaShift"] as const) {
    delete options[key];
    delete options[`${key}Override`];
    if (isSigmaShift(shifts[key])) options[key] = shifts[key];
  }
  delete options.generationMode;
  delete options.promptEmbedding;
  delete options.motionCache;
  delete options.workerWeightSources;
  delete options.latentUpscaler;
  delete options.previewVae;
  const previewVae = otherWeightPaths()[TAEH3_URL];
  if (loadGenerationPreviewsEnabled() && (shifts.modelType ?? "minimax-h3") === "minimax-h3" && previewVae) options.previewVae = previewVae;
  const latentUpscaler = latentUpscalerPath();
  if (latentUpscaler && !generatorModel(shifts.modelType).musicGeneration) options.latentUpscaler = latentUpscaler;
  if (remote && sources) {
    options.workerWeightSources = JSON.stringify(Object.fromEntries(Object.entries(sources)
      .filter(([role, entries]) => entries?.length && pathFields.some(({ id }) => id === role))
      .map(([role, entries]) => [role, entries!.map(({ url, gpuModel, minVramGb }) => ({ url, gpuModel, minVramGb }))])));
  }
  if (motionCache && mode !== "animate") options.motionCache = true;
  if (mode === "animate") options.generationMode = "animate";
  if (mode === "animate") {
    const file = additionalSafetensors?.find((entry) => entry.role === "promptEmbedding");
    const path = file?.downloadedPath && !isDownloadUrl(file.downloadedPath) ? file.downloadedPath : remote ? file?.url : undefined;
    if (path) options.promptEmbedding = path;
  }
  const loras = resolveTemplateLoras(effectiveLoras(selection, sceneLoras, shifts.modelType), remote);
  if (loras.length) options.loras = JSON.stringify(loras.map(({ path, strength }) => ({ path, strength })));
  const shiftOverrides = loraSigmaShiftOverrides(loras);
  if (shiftOverrides.videoSigmaShift !== undefined) options.videoSigmaShiftOverride = shiftOverrides.videoSigmaShift;
  if (shiftOverrides.audioSigmaShift !== undefined) options.audioSigmaShiftOverride = shiftOverrides.audioSigmaShift;
  const stepOverride = loraStepOverride(loras);
  if (stepOverride !== undefined) options.stepOverride = stepOverride;
  const presets = new Set(loras.flatMap((lora) => lora.samplingPreset ? [lora.samplingPreset] : []));
  if (presets.size > 1) throw new Error("Active LoRAs require different sampling recipes. Choose either DMAD or Pika H3 Flex.");
  if (presets.size) {
    options.samplingPreset = [...presets][0];
    // Fixed re-noising schedules forbid approximate caches.
    delete options.motionCache;
  }
  const sampling = effectiveTemplateSampling({ ...shifts, paths: settings, sources, mode, loras: selection }, sceneLoras);
  if (sampling.sampler !== "default") options.sampler = sampling.sampler;
  if (sampling.scheduler !== "default") options.scheduler = sampling.scheduler;
  if (sampling.sampler !== "default" && sampling.sampler !== "euler") delete options.motionCache;
  for (const field of ENGINE_PATH_FIELDS) {
    if (!pathFields.some(({ id }) => id === field.id)) {
      delete options[field.id];
      continue;
    }
    const value = remote ? workerWeight(settings[field.id].trim(), sources?.[field.id]) : settings[field.id].trim();
    if (value && (remote || !isDownloadUrl(value))) options[field.id] = value;
    else if (isDownloadUrl(value) || [FIBO_MODEL_TYPE, KREA_MODEL_TYPE, H3_IMAGE_MODEL_TYPE].includes(shifts.modelType ?? "") && field.id === "tokenizer"
      || isSharedH3Field(shifts.modelType, field.id)) delete options[field.id];
  }
  return { enabled: base?.enabled ?? true, model: base?.model ?? null, options };
}

/** The effective count shown for the selected generator before submission. */
export function generationStepsForTemplate(steps: number, template?: Pick<GeneratorTemplate, "loras" | "modelType">, overrides: TemplateLora[] = []): number {
  if (template?.modelType === H3_IMAGE_MODEL_TYPE) return 6;
  // Display metadata without resolving weight paths: a template awaiting a
  // download can still show its step count without throwing during render.
  const activeIds = new Set(effectiveLoras(template?.loras, overrides, template?.modelType).filter((entry) => entry.enabled && entry.strength !== 0).map((entry) => entry.loraId));
  return loraStepOverride(loadLoras().filter((lora) => activeIds.has(lora.id))) ?? steps;
}

export function sigmaShiftOverridesForTemplate(template?: Pick<GeneratorTemplate, "loras" | "modelType">, overrides: TemplateLora[] = []): SigmaShifts {
  const active = new Set(effectiveLoras(template?.loras, overrides, template?.modelType).filter((entry) => entry.enabled && entry.strength !== 0).map((entry) => entry.loraId));
  return loraSigmaShiftOverrides(loadLoras().filter((lora) => active.has(lora.id)));
}

export function generationSigmaShifts(shifts: { videoSigmaShift?: number | null; audioSigmaShift?: number | null; loraOverrides?: TemplateLora[] | null }, template?: GeneratorTemplate): SigmaShifts {
  const overrides = sigmaShiftOverridesForTemplate(template, shifts.loraOverrides ?? []);
  return { videoSigmaShift: overrides.videoSigmaShift ?? shifts.videoSigmaShift ?? template?.videoSigmaShift,
    audioSigmaShift: overrides.audioSigmaShift ?? shifts.audioSigmaShift ?? template?.audioSigmaShift };
}

export function generationSigmaShiftsWithLoras(shifts: SigmaShifts, config: ProjectConfig): SigmaShifts {
  const options = config.providerSettings.slopfab?.options;
  const resolve = (key: keyof SigmaShifts) => {
    const override = options?.[`${key}Override`];
    const fallback = options?.[key];
    return isSigmaShift(override) ? override : shifts[key] ?? (isSigmaShift(fallback) ? fallback : undefined);
  };
  return { videoSigmaShift: resolve("videoSigmaShift"), audioSigmaShift: resolve("audioSigmaShift") };
}

export function generationStepsWithLoras(steps: number, config: ProjectConfig): number {
  if (config.providerSettings.slopfab?.options.modelType === H3_IMAGE_MODEL_TYPE) return 6;
  const override = config.providerSettings.slopfab?.options.stepOverride;
  return isLoraStepOverride(override) ? override : steps;
}

/** A copy of `config` carrying this machine's engine paths. For passing to a
 *  Tauri command only — never store or save the result. */
export function withEngineSettings(config: ProjectConfig): ProjectConfig {
  return {
    ...config,
    providerSettings: {
      ...config.providerSettings,
      slopfab: engineProviderSetting(loadEngineSettings(), config.providerSettings.slopfab),
    },
  };
}

export type EndpointProviderId = "openrouter" | "local";

export interface EndpointProviderSettings {
  endpoint: string;
  apiKey: string;
  model: string;
}

export type AgentEndpointSettings = Record<EndpointProviderId, EndpointProviderSettings>;

export const EMPTY_AGENT_ENDPOINT_SETTINGS: AgentEndpointSettings = {
  openrouter: { endpoint: "https://openrouter.ai/api/v1", apiKey: "", model: "" },
  local: { endpoint: "", apiKey: "", model: "" },
};

const AGENT_ENDPOINTS_KEY = "slopus.agent-endpoints.v1";
const LEGACY_AGENT_ENDPOINTS_KEY = "polstudio.agent-endpoints.v1";

export function loadAgentEndpointSettings(): AgentEndpointSettings {
  const fallback = {
    openrouter: { ...EMPTY_AGENT_ENDPOINT_SETTINGS.openrouter },
    local: { ...EMPTY_AGENT_ENDPOINT_SETTINGS.local },
  };
  try {
    const raw = migratedStorageItem(AGENT_ENDPOINTS_KEY, LEGACY_AGENT_ENDPOINTS_KEY);
    if (!raw) return fallback;
    const parsed = JSON.parse(raw) as Partial<Record<EndpointProviderId, Partial<Record<keyof EndpointProviderSettings, unknown>>>>;
    for (const id of ["openrouter", "local"] as const) {
      for (const field of ["endpoint", "apiKey", "model"] as const) {
        const value = parsed?.[id]?.[field];
        if (typeof value === "string") fallback[id][field] = value;
      }
    }
    return fallback;
  } catch {
    return fallback;
  }
}

export function saveAgentEndpointSettings(settings: AgentEndpointSettings): void {
  try {
    localStorage.setItem(AGENT_ENDPOINTS_KEY, JSON.stringify(settings));
  } catch {
    /* Never fall back to putting machine credentials in a project file. */
  }
}

export function endpointProviderSetting(settings: EndpointProviderSettings): ProviderSetting {
  const options: ProviderSetting["options"] = { endpoint: settings.endpoint.trim() };
  if (settings.apiKey.trim()) options.apiKey = settings.apiKey.trim();
  return { enabled: true, model: settings.model.trim() || null, options };
}

export function isEndpointProviderConfigured(id: EndpointProviderId, settings: EndpointProviderSettings): boolean {
  return Boolean(settings.endpoint.trim() && settings.model.trim() && (id === "local" || settings.apiKey.trim()));
}

/** These settings exist only on an IPC request. Rust removes them before
 * validating, prompting with, or saving the project. */
export function agentEndpointProviderSettings(): Partial<Record<EndpointProviderId, ProviderSetting>> {
  const settings = loadAgentEndpointSettings();
  return Object.fromEntries(
    (["openrouter", "local"] as const)
      .filter((id) => isEndpointProviderConfigured(id, settings[id]))
      .map((id) => [id, endpointProviderSetting(settings[id])]),
  );
}

export function withAgentEndpointSettings(config: ProjectConfig): ProjectConfig {
  return {
    ...config,
    providerSettings: { ...config.providerSettings, ...agentEndpointProviderSettings() },
  };
}

/* --- Agent provider -------------------------------------------------------- */

/* Which coding agent drives Slop is a property of the computer — it depends on
 * what is installed and signed in here — so it is remembered across restarts
 * next to the engine paths, not inside a project file. Projects written before
 * this existed still carry their own choice; that is read as a seed the first
 * time and then this preference takes over. */
const AGENT_PROVIDER_KEY = "slopus.agent-provider.v1";
const LEGACY_AGENT_PROVIDER_KEY = "polstudio.agent-provider.v1";

export function loadAgentProvider(): ProviderId | null {
  try {
    const value = migratedStorageItem(AGENT_PROVIDER_KEY, LEGACY_AGENT_PROVIDER_KEY);
    return value === "claude" || value === "codex" || value === "openrouter" || value === "local" ? value : null;
  } catch {
    return null;
  }
}

export function saveAgentProvider(provider: ProviderId): void {
  try {
    localStorage.setItem(AGENT_PROVIDER_KEY, provider);
  } catch {
    /* Losing the preference costs a dropdown click next launch, nothing more. */
  }
}

/* --- Debug options --------------------------------------------------------- */

const DEBUG_OPTIONS_KEY = "slopus.debug-options.v1";
const DEBUG_OPTIONS_EVENT = "slopus:debug-options-changed";

export function loadDebugOptionsEnabled(): boolean {
  try {
    return localStorage.getItem(DEBUG_OPTIONS_KEY) === "true";
  } catch {
    return false;
  }
}

export function saveDebugOptionsEnabled(enabled: boolean): void {
  try {
    localStorage.setItem(DEBUG_OPTIONS_KEY, String(enabled));
  } catch {
    return;
  }
  window.dispatchEvent(new Event(DEBUG_OPTIONS_EVENT));
}

export function subscribeDebugOptions(listener: () => void): () => void {
  const onStorage = (event: StorageEvent) => {
    if (event.key === DEBUG_OPTIONS_KEY || event.key === null) listener();
  };
  window.addEventListener(DEBUG_OPTIONS_EVENT, listener);
  window.addEventListener("storage", onStorage);
  return () => {
    window.removeEventListener(DEBUG_OPTIONS_EVENT, listener);
    window.removeEventListener("storage", onStorage);
  };
}

/* --- Panel layout ----------------------------------------------------------
   How the media panel lays its footage out. A working habit, not a property of
   any one project, so it lives beside the engine paths rather than in
   slopus.json — a project file the user may copy to another machine should not
   carry one editor's panel preference with it. */

export type MediaLayout = "grid" | "list";

const MEDIA_LAYOUT_KEY = "slopus.media-layout.v1";
const LEGACY_MEDIA_LAYOUT_KEY = "polstudio.media-layout.v1";

export function loadMediaLayout(): MediaLayout {
  try {
    return migratedStorageItem(MEDIA_LAYOUT_KEY, LEGACY_MEDIA_LAYOUT_KEY) === "list" ? "list" : "grid";
  } catch {
    return "grid";
  }
}

export function saveMediaLayout(layout: MediaLayout): void {
  try {
    localStorage.setItem(MEDIA_LAYOUT_KEY, layout);
  } catch {
    /* A full or disabled localStorage costs the preference, not the session:
       the panel still shows whatever was just chosen. */
  }
}