Skip to content

AI media harness for planning, generating, and editing locally

TypeScript
45.9 KB
Raw Blame
import type { GenerationPreview } from "../../lib/generationPreview";
import { generatorOptions } from "../generatorOptions";
import { sceneUpscaleSubmission, selectedUpscaleTake } from "../../lib/sceneUpscale";
import { Flyout } from "../ui";
import { ChevronDown14 } from "../ui/icons";
import { duplicateScene, makeSceneGenerationPrimary, removeSceneDraft, removeSceneGeneration, saveSceneDrafts, selectSceneGeneration, sceneUsedSeed } from "../../lib/sceneHistory";
import { sceneLoraBlocker, sceneGenerationRequest, sendBlocker, templateSceneBlocker } from "../../lib/sceneGeneration";
import { longShotBlocker, longShotDependencies, longShotPosition } from "../../lib/longShot";
export { templateSceneBlocker } from "../../lib/sceneGeneration";
import type { GenerationSubmission } from "../../lib/workQueue";
import { loadLoras, subscribeLoras } from "../../lib/loras";
import { refreshDownloadedLoras } from "../../lib/weightDownloads";
import { continuationBlocker, continuationSceneId, isVideoTransition, sceneGenerationPending, sceneGenerationSteps, sceneTypeFor } from "../../lib/project";
import { Add16, Delete16, GridView16, GridView16Filled, ListView16, ListView16Filled, Scene16, Scene32, Sparkle16, Stop14, Wand16 } from "../ui/icons";
import { invoke } from "@tauri-apps/api/core";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { useShortcut } from "../../lib/commands";
import { askNative } from "../../lib/nativeShell";
import { ProjectStatus } from "./ProjectStatus";
import { GeneratorSelector } from "./GeneratorSelector";
import { CommandBar, CommandBarButton, CommandBarSeparator, ComboBox, EmptyState, ItemHeader, Splitter, tooltipProps, usePaneSize } from "../ui";
import { sceneSiblings, shotReferenceIds, compileGenerationJobSegments, createDraftGenerationJob, GENERATION_FRAME_RATE, RANDOM_GENERATION_SEED, sceneDurationSeconds, sceneFrameInputs, sceneGenerationReferences, sceneGenerationSeed, sceneGenerationSnapshot, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, type GenerationJob, type ProjectConfig, type ProjectReference, type SceneShot } from "../../lib/project";
import { isTauri } from "../../lib/persistence";
import { getEngineStatus, type SlopfabGenerationRequest, type SlopfabStatus } from "../../lib/runtime";
import { selectedWorker } from "../../lib/workers";
import { SceneBoard, type BoardDensity, type GeneratorSelection } from "./SceneBoard";
import { SceneInspector, ShotInspector, STEP_SECONDS, writeShots } from "./SceneEditor";
import { STATUS_BADGE, type SceneIndicatorStatus } from "./sceneStatus";
import { forgetShotPosters } from "./ShotThumbnail";
import { purgeTimelineThumbnails } from "../../lib/timelineThumbnails";
import { templateWithSceneLoras, selectedGeneratorTemplate, loadActiveGeneratorId, saveActiveGeneratorId, subscribeActiveGenerators, generationStepsForTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, subscribeDebugOptions, subscribeGeneratorTemplates, templateSupportsVideo, templateUsable } from "../../lib/settings";
import { refreshDownloadedWeights } from "../../lib/weightDownloads";
import { DebugPromptDialog } from "./DebugPromptDialog";
import { sceneVideoSettings, videoGuidedScene } from "../../lib/videoLibrary";
import { generationDimensions } from "../../lib/export";
import { sceneVideoReference } from "../../lib/sceneReference";

interface GeneratorViewProps {
  toolbarStart?: ReactNode;
  sceneIds?: readonly string[];
  config: ProjectConfig;
  folderPath: string;
  runtime?: SlopfabStatus | null;
  generationPreviews?: Readonly<Record<string, GenerationPreview>>;
  generationCompletionTimes?: Readonly<Record<string, number>>;
  /** `key` groups rapid edits of one thing into one undo step (the workspace's session.edit). */
  onChange: (next: ProjectConfig, key?: string) => void;
  onGenerate?: (submissions: GenerationSubmission[]) => void;
  onCancelGeneration?: (sceneIds: string[]) => Promise<void>;
  cancellingJobIds?: ReadonlySet<string>;
  onOpenTimeline: () => void;
  selectedJobId?: string;
  /** The scene open here, whenever it changes — the Timeline marks it in its
   *  sources, and the Generator reopens on it. */
  onSelectedJobChange?: (jobId: string) => void;
  onRuntimeChange?: (runtime: SlopfabStatus) => void;
}

const DENSITY_KEY = "slopus.generator.density";
const readDensity = (): BoardDensity => {
  try { return localStorage.getItem(DENSITY_KEY) === "list" ? "list" : "tiles"; } catch { return "tiles"; }
};

/* The Generator is a BOARD and a PANEL.
 *
 * The board is every scene in the project, each one a row of shot cards reading
 * left to right in the order they play, separated by the line that carries the
 * scene's own name, state and settings. A card is the summary of a shot: its
 * picture once the scene has been rendered, the line written for it, and the
 * settings hung off it.
 *
 * The panel is whatever is open — one shot, or the scene itself. Nothing is
 * edited on the board, and nothing is duplicated in the panel: there is exactly
 * one place to change any given thing. */
export function GeneratorView({ config, sceneIds, toolbarStart, folderPath, runtime = null, generationPreviews = {}, generationCompletionTimes = {}, onChange, selectedJobId, onSelectedJobChange, onRuntimeChange, onGenerate, onCancelGeneration, cancellingJobIds = new Set() }: GeneratorViewProps) {
  const jobs = sceneIds ? sceneIds.flatMap((id) => { const job = config.generationJobs.find((job) => job.id === id); return job ? [job] : []; }) : config.generationJobs;
  const [selection, setSelection] = useState<GeneratorSelection>(() => ({ jobId: selectedJobId ?? jobs.find((job) => job.status === "generating")?.id ?? jobs[0]?.id ?? "", shotId: null }));
  const [templateSettings, setTemplateSettings] = useState(loadGeneratorTemplateSettings);
  const activeGeneratorId = useSyncExternalStore(subscribeActiveGenerators, () => loadActiveGeneratorId("video"));
  const selectedTemplate = selectedGeneratorTemplate("video", templateSettings, activeGeneratorId);
  const defaultGenerationSteps = selectedTemplate.defaultSteps;
  const [generatorRuntime, setGeneratorRuntime] = useState<SlopfabStatus | null>(runtime);
  const [runtimeError, setRuntimeError] = useState<string | null>(null);
  const runtimeProbe = useRef(0);
  const [loraLibrary, setLoraLibrary] = useState(loadLoras);
  useEffect(() => subscribeLoras(() => setLoraLibrary(loadLoras())), []);
  const templateKey = JSON.stringify([selectedTemplate.id, selectedTemplate.modelType, selectedTemplate.mode, selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.motionCache, selectedTemplate.loras, selectedTemplate.additionalSafetensors, loraLibrary, selectedWorker()?.id ?? null]);
  const probedTemplate = useRef(templateKey);
  const configRef = useRef(config);
  configRef.current = config;
  /* A scene is always what is named; the shot inside it is what a card opens.
     Opening the Generator, or arriving from a clip in the timeline, opens the
     SCENE — the thing that has a state, a prompt and a Generate button. */
  const [density, setDensity] = useState<BoardDensity>(readDensity);
  const chooseDensity = (next: BoardDensity) => {
    setDensity(next);
    try { localStorage.setItem(DENSITY_KEY, next); } catch { /* storage unavailable */ }
  };
  const inspectorPane = usePaneSize("generator.inspector", 340, { min: 280, max: 560 });
  const root = useRef<HTMLDivElement>(null);
  const titleInput = useRef<HTMLInputElement>(null);
  const [showDebugPrompt, setShowDebugPrompt] = useState(false);
  const [generationActionsOpen, setGenerationActionsOpen] = useState(false);
  const generationActionsButton = useRef<HTMLButtonElement>(null);
  useEffect(() => setGenerationActionsOpen(false), [selection.jobId, selection.shotId]);
  const debugEnabled = useSyncExternalStore(subscribeDebugOptions, loadDebugOptionsEnabled);
  const [startFrameError, setStartFrameError] = useState<string | null>(null);

  useEffect(() => {
    if (!debugEnabled) setShowDebugPrompt(false);
  }, [debugEnabled]);

  useEffect(() => {
    setTemplateSettings(loadGeneratorTemplateSettings());
    setGeneratorRuntime(runtime);
    setRuntimeError(null);
  }, [runtime]);

  useEffect(() => () => { runtimeProbe.current += 1; }, []);
  useEffect(() => subscribeGeneratorTemplates(() => setTemplateSettings(loadGeneratorTemplateSettings())), []);
  useEffect(() => {
    const refresh = () => { void Promise.all([refreshDownloadedWeights(), refreshDownloadedLoras()]).catch((reason) => setRuntimeError(String(reason))); };
    refresh();
    window.addEventListener("focus", refresh);
    const timer = window.setInterval(refresh, 5000);
    return () => { window.removeEventListener("focus", refresh); window.clearInterval(timer); };
  }, []);

  const chooseGeneratorTemplate = (templateId: string) => {
    const template = templateSettings.templates.find((candidate) => candidate.id === templateId);
    if (!template || !(templateSupportsVideo(template) && templateUsable(template))) return;
    saveActiveGeneratorId("video", template.id);
  };

  useEffect(() => {
    if (probedTemplate.current === templateKey) return;
    probedTemplate.current = templateKey;
    setGeneratorRuntime(null);
    setRuntimeError(null);
    const probe = ++runtimeProbe.current;
    if (!selectedTemplate.id) return;
    void getEngineStatus(selectedTemplate.paths, selectedTemplate.attention, selectedTemplate.loras ?? [], selectedTemplate.mode ?? "prompt", selectedTemplate.additionalSafetensors ?? [], selectedTemplate.motionCache ?? false, selectedTemplate.sources, selectedTemplate.modelType).then((status) => {
      if (probe !== runtimeProbe.current) return;
      setGeneratorRuntime(status);
      onRuntimeChange?.(status);
    }).catch((reason: unknown) => {
      if (probe !== runtimeProbe.current) return;
      setRuntimeError(reason instanceof Error ? reason.message : String(reason));
    });
  }, [templateKey]);

  /* The workspace hears which scene is open, and may send one back (Open in
     Generator). Its echo of this panel's own choice must not close the shot. */
  useEffect(() => {
    if (selectedJobId) setSelection((current) => current.jobId === selectedJobId ? current : { jobId: selectedJobId, shotId: null });
  }, [selectedJobId]);
  const reportSelection = useRef(onSelectedJobChange);
  reportSelection.current = onSelectedJobChange;
  useEffect(() => { if (selection.jobId) reportSelection.current?.(selection.jobId); }, [selection.jobId]);

  /* A scene can be deleted, and a shot can be removed, from under the panel.
     Falling back to the first scene beats a panel pointing at nothing. */
  const selected = jobs.find((job) => job.id === selection.jobId) ?? jobs[0];
  const selectedTake = selected && selectedUpscaleTake(selected, config);
  const usedGenerator = selectedTake && templateSettings.templates.find((candidate) => candidate.id === selectedTake.scene.generatorTemplateId && templateSupportsVideo(candidate));
  const inheritedSettings = selected ? sceneVideoSettings(selected, config) : config.settings;
  const parentVideo = selected && config.videos?.find((video) => video.sceneIds.includes(selected.id));
  const animate = selected ? sceneTypeFor(selected) === "animate" : false;
  const selectedShots = useMemo(() => (selected ? sceneShots(selected) : []), [selected]);
  const shotIndex = selectedShots.findIndex((shot) => shot.id === selection.shotId);
  const openShot = !animate && shotIndex >= 0 ? selectedShots[shotIndex] : null;
  const shotEndsAt = selected && openShot
    ? shotIndex + 1 < selectedShots.length ? selectedShots[shotIndex + 1].startSeconds : sceneDurationSeconds(selected)
    : 0;

  const active = jobs.filter((job) => job.status === "generating" || job.status === "ready");
  const queued = jobs.filter((job) => job.status === "queued");
  const cancellable = jobs.filter((job) => job.status === "queued" || job.status === "generating");
  const frameInputs = useMemo(() => { if (!selected) return null; const guided = videoGuidedScene(selected, config); return sceneFrameInputs(guided.job, guided.config); }, [config, selected]);
  const boundRefs = frameInputs?.references ?? [];
  const runtimeReady = Boolean(selectedTemplate.id) && generatorRuntime?.state === "ready";

  const updateJob = (id: string, updates: Partial<GenerationJob>) => {
    const current = configRef.current;
    // Typing in one scene's fields (or dragging its length) is one undo step.
    onChange(saveSceneDrafts({ ...current, generationJobs: current.generationJobs.map((job) => job.id === id ? { ...job, ...updates } : job) }, current), `scene:${id}`);
  };

  // Keep saved bindings in sync with all shots, including chip replacement,
  // shot removal and moves between scenes. Animate has separate input pickers.
  const mergeSceneUpdates = (job: GenerationJob, updates: Partial<GenerationJob>): GenerationJob => {
    const next: Partial<GenerationJob> = { ...updates, updatedAt: new Date().toISOString() };
    if (updates.shots && (updates.sceneType ?? job.sceneType) !== "animate") {
      const referenceIds: string[] = [];
      for (const shot of updates.shots) {
        for (const id of shotReferenceIds(shot)) {
          if (!referenceIds.includes(id) && config.references.some((reference) => reference.id === id)) referenceIds.push(id);
        }
      }
      next.referenceIds = referenceIds;
    }
    return { ...job, ...next };
  };

  const updateScene = (job: GenerationJob, updates: Partial<GenerationJob>) =>
    updateJob(job.id, mergeSceneUpdates(job, updates));

  const changeSceneSettings = (job: GenerationJob, updates: Partial<GenerationJob>) => {
    updateScene(job, updates);
  };

  const addFrame = async (job: GenerationJob, edge: "start" | "end") => {
    if (!isTauri()) return;
    setStartFrameError(null);
    try {
      const imported = await invoke<{ name: string; relativePath: string } | null>("choose_reference_image", { folderPath });
      if (!imported) return;
      const current = configRef.current;
      const id = `ref-${Date.now()}`;
      const reference: ProjectReference = {
        id,
        kind: "text",
        name: imported.name,
        description: "",
        images: [{ id: `${id}-image`, name: imported.name, relativePath: imported.relativePath }],
        intendedUse: [],
        createdAt: new Date().toISOString(),
      };
      onChange({
        ...current,
        references: [reference, ...current.references],
        generationJobs: current.generationJobs.map((candidate) => candidate.id === job.id
          ? { ...candidate, ...(edge === "start" ? { startFrameReferenceId: id, usePreviousSceneLastFrame: undefined } : { endFrameReferenceId: id }), updatedAt: new Date().toISOString() }
          : candidate),
      });
    } catch (reason) {
      setStartFrameError(reason instanceof Error ? reason.message : String(reason));
    }
  };

  /* --- The shots of a scene ------------------------------------------------
     Every one of these goes through writeShots, so the mirrored `prompt` and
     `creativeBrief` can never fall behind the lines they mirror. */

  const setShots = (job: GenerationJob, next: SceneShot[], extra: Partial<GenerationJob> = {}) =>
    updateScene(job, writeShots(job, next, extra));

  const patchShot = (job: GenerationJob, shotId: string, updates: Partial<SceneShot>) =>
    setShots(job, sceneShots(job).map((shot) => shot.id === shotId ? { ...shot, ...updates } : shot));

  const addShot = (job: GenerationJob) => {
    if (job.sceneType === "single-shot") return;
    const shots = sceneShots(job);
    const duration = sceneDurationSeconds(job);
    const last = shots[shots.length - 1];
    const halfway = Math.round(((last.startSeconds + duration) / 2) / STEP_SECONDS) * STEP_SECONDS;
    const start = Math.min(duration, Math.max(last.startSeconds + STEP_SECONDS, halfway));
    const shot: SceneShot = { id: `shot-${crypto.randomUUID()}`, startSeconds: start, action: "" };
    setShots(job, [...shots, shot]);
    // The new card is blank, so open it: there is nowhere else to write it.
    setSelection({ jobId: job.id, shotId: shot.id });
  };

  const removeShot = (job: GenerationJob, shotId: string) => {
    const shots = sceneShots(job);
    // A scene is at least one shot: with none there is nowhere to write, and
    // the compiler would have nothing to make a [Shot 1] out of.
    if (shots.length <= 1) return;
    setShots(job, shots.filter((shot) => shot.id !== shotId));
    setSelection({ jobId: job.id, shotId: null });
  };

  const setDuration = (job: GenerationJob, value: number) => {
    const next = Math.min(SCENE_MAX_SECONDS, Math.max(SCENE_MIN_SECONDS, Math.round(value / STEP_SECONDS) * STEP_SECONDS));
    // A shot cannot start after the scene ends, so shortening the scene pulls
    // the later cuts back with it rather than leaving them past the end.
    setShots(job, sceneShots(job).map((shot) => ({ ...shot, startSeconds: Math.min(shot.startSeconds, next) })), { durationSeconds: next });
  };

  const moveScene = (jobId: string, beforeJobId: string | null) => {
    const current = configRef.current;
    const moving = current.generationJobs.find((job) => job.id === jobId);
    if (!moving || beforeJobId === jobId) return;
    const without = current.generationJobs.filter((job) => job.id !== jobId);
    const index = beforeJobId === null ? without.length : without.findIndex((job) => job.id === beforeJobId);
    if (index < 0) return;
    const generationJobs = [...without.slice(0, index), moving, ...without.slice(index)];
    onChange({ ...current, generationJobs });
  };

  /** Reordering keeps the existing cut slots. A cross-scene move inserts a new
   * cut between its neighbours (or at the end), so array order and playback
   * order remain the same even though scene shots are normalized by time. */
  const moveShot = (sourceJobId: string, shotId: string, targetJobId: string, beforeShotId: string | null) => {
    const current = configRef.current;
    const source = current.generationJobs.find((job) => job.id === sourceJobId);
    const target = current.generationJobs.find((job) => job.id === targetJobId);
    if (!source || !target) return;
    const sourceShots = sceneShots(source);
    const moving = sourceShots.find((shot) => shot.id === shotId);
    if (!moving) return;

    if (source.id === target.id) {
      const without = sourceShots.filter((shot) => shot.id !== shotId);
      const index = beforeShotId === null ? without.length : without.findIndex((shot) => shot.id === beforeShotId);
      if (index < 0) return;
      const ordered = [...without.slice(0, index), moving, ...without.slice(index)];
      const starts = sourceShots.map((shot) => shot.startSeconds);
      const retimed = ordered.map((shot, at) => ({ ...shot, startSeconds: starts[at] }));
      const updated = mergeSceneUpdates(source, writeShots(source, retimed));
      onChange({ ...current, generationJobs: current.generationJobs.map((job) => job.id === source.id ? updated : job) });
      setSelection({ jobId: source.id, shotId });
      return;
    }

    // A scene with no shots cannot be represented or edited.
    if (sourceShots.length <= 1) return;
    const targetShots = sceneShots(target);
    const insertAt = beforeShotId === null ? targetShots.length : targetShots.findIndex((shot) => shot.id === beforeShotId);
    if (insertAt < 0) return;
    const inserted = { ...moving, startSeconds: 0 };
    const orderedTargetShots = [...targetShots.slice(0, insertAt), inserted, ...targetShots.slice(insertAt)];
    const targetDuration = sceneDurationSeconds(target);
    // A destination gains a cut, so divide its available time again. This
    // avoids a zero-length shot when one is dropped at either edge.
    const nextTargetShots = orderedTargetShots.map((shot, at) => ({
      ...shot,
      startSeconds: at === 0 ? 0 : Math.min(targetDuration, Math.round((targetDuration * at / orderedTargetShots.length) / STEP_SECONDS) * STEP_SECONDS),
    }));
    const nextSourceShots = sourceShots.filter((shot) => shot.id !== shotId);
    const updatedSource = mergeSceneUpdates(source, writeShots(source, nextSourceShots));
    const updatedTarget = mergeSceneUpdates(target, writeShots(target, nextTargetShots));
    onChange({
      ...current,
      generationJobs: current.generationJobs.map((job) => job.id === source.id ? updatedSource : job.id === target.id ? updatedTarget : job),
    });
    setSelection({ jobId: target.id, shotId });
  };

  const requestFor = (job: GenerationJob): SlopfabGenerationRequest =>
    sceneGenerationRequest(job, configRef.current, folderPath, selectedTemplate.defaultSteps, selectedTemplate);

  const snapshotFor = (job: GenerationJob, request = requestFor(job)): string =>
    sceneGenerationSnapshot(job, request);

  const purgeSceneThumbnails = async (job: GenerationJob) => {
    if (job.outputRelativePath) forgetShotPosters(folderPath, job.outputRelativePath);
    await purgeTimelineThumbnails(folderPath, job.id).catch(() => undefined);
  };

  const submit = (scenes: GenerationJob[]) => {
    if (!runtimeReady) return;
    const submissions = scenes.map((job) => {
      const request = requestFor(job);
      return { job, request, snapshot: snapshotFor(job, request), template: selectedTemplate };
    });
    try { onGenerate?.(submissions); }
    catch (reason) { setRuntimeError(reason instanceof Error ? reason.message : String(reason)); }
  };

  /* A scene now starts EMPTY. There is no box that turns a sentence into a
     scene any more: the + button adds a scene holding one blank shot, and the
     shots are written in the panel beside the board. Slopus still writes no
     line for anyone, so the scene arrives with no words and carries
     UNTITLED_SCENE as its name rather than a phrase this app made up.

     A scene built FROM a prompt is Slop’s job: the bar along the bottom of the
     window hands the request to Claude Code or Codex, which returns a compact
     command batch that Slopus applies. Nothing is auto-bound either way — which
     references steer a scene is decided by writing them into a line or by the
     references already named by its shots. */
  const newScene = () => {
    const job = createDraftGenerationJob("", { steps: defaultGenerationSteps,
      sceneType: selectedTemplate.mode === "animate" ? "animate" : selected?.sceneType === "single-shot" ? "single-shot" : "prompt" });
    onChange({ ...config, generationJobs: [...config.generationJobs, job] });
    setSelection({ jobId: job.id, shotId: null });
  };

  const removeScene = (job: GenerationJob) => {
    const current = configRef.current;
    const at = current.generationJobs.findIndex((item) => item.id === job.id);
    if (at < 0) return;
    void purgeSceneThumbnails(job);
    if (job.status === "generating" || job.status === "queued") void onCancelGeneration?.([job.id]);
    const generationJobs = current.generationJobs.filter((item) => item.id !== job.id);
    onChange({ ...current, generationJobs });
    if (selection.jobId === job.id) {
      const remaining = sceneIds ? generationJobs.filter((item) => sceneIds.includes(item.id)) : generationJobs;
      const fallback = remaining[Math.min(jobs.findIndex((item) => item.id === job.id), remaining.length - 1)];
      setSelection({ jobId: fallback?.id ?? "", shotId: null });
    }
  };

  /* Deleting asks first, in a native Windows message box. */
  const confirmRemoveScene = async (job: GenerationJob) => {
    const confirmed = await askNative({ title: "Delete scene", message: `Delete “${job.title}” and all of its shots?`, kind: "warning", okLabel: "Delete", cancelLabel: "Cancel" });
    if (confirmed) removeScene(job);
  };
  const confirmRemoveShot = async (job: GenerationJob, shotId: string) => {
    const shots = sceneShots(job);
    const index = shots.findIndex((shot) => shot.id === shotId);
    if (index < 0 || shots.length <= 1) return;
    const name = shots[index].name ?? `Shot ${index + 1}`;
    const confirmed = await askNative({ title: "Delete shot", message: `Delete “${name}” from “${job.title}”?`, kind: "warning", okLabel: "Delete", cancelLabel: "Cancel" });
    if (!confirmed) return;
    const current = configRef.current.generationJobs.find((candidate) => candidate.id === job.id);
    if (current) removeShot(current, shotId);
  };

  const cancelScenes = (scenes: GenerationJob[]) => onCancelGeneration?.(scenes.map((job) => job.id));
  const generateScene = (job: GenerationJob) => {
    if (job.status === "queued" || job.status === "generating") void cancelScenes([job]);
    else submit([job]);
  };

  /** Generate All is an idempotent update for fixed seeds, but a deliberate
   * reroll for random ones. A completed fixed-seed scene is current only when
   * both its output and the exact renderer-input snapshot still exist. */
  const batchScenesReady: GenerationJob[] = [];
  const visited = new Set<string>();
  const visiting = new Set<string>();
  const visitForBatch = (job: GenerationJob): boolean => {
    if (!templateUsable(templateWithSceneLoras(selectedTemplate, job))) return false;
    if (sceneLoraBlocker(job, selectedTemplate) || continuationBlocker(job, config.generationJobs) || longShotBlocker(job, config, false) || templateSceneBlocker(sceneTypeFor(job), selectedTemplate) || sendBlocker(job, config.references, config)) return false;
    if (visited.has(job.id)) return true;
    if (visiting.has(job.id)) return false;
    if (["queued", "generating", "ready"].includes(job.status)) { visited.add(job.id); return true; }
    const previous = config.generationJobs.find((candidate) => candidate.id === continuationSceneId(job, config.generationJobs));
    const context = job.sceneType === "single-shot" && config.generationJobs.find((candidate) => candidate.id === job.contextSceneId);
    const dependencies = [...(previous ? [previous] : []), ...(context ? [context] : []), ...longShotDependencies(job, sceneSiblings(job, config))];
    visiting.add(job.id);
    if (dependencies.some((source) => !visitForBatch(source))) { visiting.delete(job.id); return false; }
    visiting.delete(job.id);
    visited.add(job.id);
    const priorBridge = longShotPosition(job, sceneSiblings(job, config))?.previousBridge;
    const previousWillRender = [...dependencies, ...(priorBridge ? [priorBridge] : [])].some((source) =>
      batchScenesReady.includes(source) || ["queued", "generating", "ready"].includes(source.status));
    if (previousWillRender || (job.generatorTemplateId && job.generatorTemplateId !== selectedTemplate.id) || sceneGenerationSeed(job) === RANDOM_GENERATION_SEED || job.status !== "completed"
      || !job.outputRelativePath
      || (!job.latentRelativePath && (job.sceneType === "long-shot" || job.sceneType === "single-shot" || jobs.some((candidate) => continuationSceneId(candidate, jobs) === job.id)))
      || !job.generationSnapshot
      || job.generationSnapshot !== snapshotFor(job)) batchScenesReady.push(job);
    return true;
  };
  jobs.forEach(visitForBatch);

  const generateAll = () => submit(batchScenesReady);

  const generationBlocker = (job: GenerationJob): string | null => {
    const loraBlocker = sceneLoraBlocker(job, selectedTemplate);
    if (loraBlocker) return loraBlocker;
    if (!templateUsable(templateWithSceneLoras(selectedTemplate, job))) return "Prepare the active generator's weights before generating.";
    if (!runtimeReady) return runtimeError ?? generatorRuntime?.detail ?? "The video generator is not ready.";
    if (job.status === "ready") return "Saving this scene.";
    const source = config.generationJobs.find((candidate) => candidate.id === continuationSceneId(job, config.generationJobs));
    const context = job.sceneType === "single-shot" && config.generationJobs.find((candidate) => candidate.id === job.contextSceneId);
    return continuationBlocker(job, config.generationJobs)
      ?? longShotBlocker(job, config, true, true)
      ?? (context && !sceneGenerationPending(context) && (!context.latentRelativePath || context.status !== "completed") ? "Generate or queue the Context video first, or use Generate all." : null)
      ?? (source && !sceneGenerationPending(source) && (!source.latentRelativePath || source.status !== "completed") ? "Generate or queue the selected source scene first, or use Generate all." : null)
      ?? templateSceneBlocker(sceneTypeFor(job), selectedTemplate) ?? sendBlocker(job, config.references, config);
  };

  const changedJobIds = new Set(jobs
    .filter((job) => job.status === "completed"
      && Boolean(job.generationSnapshot)
      && (job.generationSnapshot !== snapshotFor(job)
        || config.generationJobs.some((source) => (source.id === continuationSceneId(job, config.generationJobs) || job.sceneType === "single-shot" && source.id === job.contextSceneId || longShotDependencies(job, sceneSiblings(job, config)).includes(source)) && ["queued", "generating", "ready"].includes(source.status))))
    .map((job) => job.id));
  const selectedIndicator = selected && changedJobIds.has(selected.id) && !selected.generationHistory?.selectedId ? "changed" : selected?.status;
  const selectedCancellable = selected?.status === "queued" || selected?.status === "generating";
  const selectedCancelling = Boolean(selected && cancellingJobIds.has(selected.id));
  const selectedBlocker = selected && !selectedCancellable ? generationBlocker(selected) : null;
  const upscaleTake = selected && selectedUpscaleTake(selected, config);
  const upscaleBlocker = !upscaleTake?.latentRelativePath ? "Select a generated Take with saved latents."
    : selected && sceneGenerationPending(selected) ? "Wait for this scene to finish."
    : selectedTemplate.modelType && selectedTemplate.modelType !== "minimax-h3" ? "Saved latent upscaling requires MiniMax H3."
    : !isTauri() ? "Upscaling requires the desktop app." : null;

  /* --- Keyboard ------------------------------------------------------------
     Scoped to the Generator, so the same keys can mean something else on the
     timeline. F2 puts the caret in the open scene's or shot's name; Delete
     asks first, the way the inspector's delete button always has. Undo is the
     project's (bound once by the workspace), not this screen's. */
  const rename = (target: GeneratorSelection) => {
    setSelection(target);
    requestAnimationFrame(() => {
      const field = titleInput.current;
      if (!field) return;
      field.focus();
      field.select();
    });
  };
  useShortcut("F2", () => { if (!selected) return false; rename({ jobId: selected.id, shotId: openShot?.id ?? null }); }, { scope: root, enabled: Boolean(selected) });
  useShortcut("Delete", () => {
    if (!selected) return false;
    if (openShot) {
      if (selectedShots.length <= 1) return false;
      void confirmRemoveShot(selected, openShot.id);
    } else void confirmRemoveScene(selected);
  }, { scope: root, enabled: Boolean(selected) });

  const generateAllTooltip = cancellable.length > 0
    ? `Cancel ${cancellable.length} ${cancellable.length === 1 ? "generation" : "generations"}`
    : !runtimeReady
      ? runtimeError ?? generatorRuntime?.detail ?? "The video generator is not ready."
      : active.length > 0
        ? "Generation is still being saved."
        : batchScenesReady.length === 0
          ? "Every fixed-seed scene is already up to date."
          : `Generate ${batchScenesReady.length} ${batchScenesReady.length === 1 ? "scene" : "scenes"}`;
  const runtimeLabel = runtimeError ? "Video generator unavailable" : runtimeHeadline(generatorRuntime);
  const availableTemplates = templateSettings.templates.filter((template) => (templateSupportsVideo(template) && templateUsable(template)));

  return <div ref={root} className={`generator-view ${selected ? "" : "generator-view--empty"}`} style={inspectorPane.style}>
    <main className="generator-main">
      <CommandBar
        aria-label="Generator"
        className="generator-command"
        end={<>
          <CommandBarButton icon={<Add16 />} label="Add scene" showLabel onClick={newScene} />
          <CommandBarSeparator />
          <CommandBarButton icon={density === "tiles" ? <GridView16Filled /> : <GridView16 />} label="Tiles" pressed={density === "tiles"} onClick={() => chooseDensity("tiles")} />
          <CommandBarButton icon={density === "list" ? <ListView16Filled /> : <ListView16 />} label="List" pressed={density === "list"} onClick={() => chooseDensity("list")} />
        </>}
        center={cancellable.length > 0
          ? <CommandBarButton
            className="generator-command__cancel"
            icon={<Stop14 />}
            label="Cancel all"
            showLabel
            tooltip={generateAllTooltip}
            onClick={() => void cancelScenes(cancellable)}
          />
          : <CommandBarButton
            className="generator-command__generate"
            icon={<Wand16 />}
            label="Generate all"
            showLabel
            tooltip={generateAllTooltip}
            disabled={active.length > 0}
            onClick={() => void generateAll()}
          />}
      >
        {toolbarStart}
        {/* The generator the next render uses, with its readiness as a glyph
            beside the name; the words for a state that needs attention are
            in the tooltip and the status bar. */}
          <GeneratorSelector
            status={{ state: runtimeError ? "unavailable" : generatorRuntime?.state ?? "checking", label: runtimeLabel, detail: runtimeError ?? generatorRuntime?.detail ?? runtimeLabel }}
            aria-label={`Video generator template: ${selectedTemplate.name}`}
            data-tooltip={selectedTemplate.name}
            value={selectedTemplate.id}
            disabled={availableTemplates.length === 0}
            options={generatorOptions(availableTemplates)}
            onChange={chooseGeneratorTemplate}
          />
      </CommandBar>

      <div className="generator-board-viewport"><div className="generator-board">
        {jobs.length > 0
          ? <SceneBoard
            frameAspectRatio={job => {
              const settings = sceneVideoSettings(job, config);
              const { width, height } = generationDimensions(settings.resolution, settings.aspectRatio);
              return `${width} / ${height}`;
            }}
            assets={config.assets}
            jobs={jobs}
            folderPath={folderPath}
            generationPreviews={generationPreviews}
            generationCompletionTimes={generationCompletionTimes}
            references={config.references}
            selection={{ jobId: selected?.id ?? "", shotId: openShot?.id ?? null }}
            density={density}
            onSelect={setSelection}
            onAddShot={addShot}
            onDuration={setDuration}
            onGenerate={generateScene}
            generationBlocker={generationBlocker}
            changedJobIds={changedJobIds}
            cancellingJobIds={cancellingJobIds}
            onMoveScene={moveScene}
            onMoveShot={moveShot}
            onRename={rename}
            onCreateReference={(job, shotId) => {
              const current = configRef.current;
              const source = current.generationJobs.find(candidate => candidate.id === job.id);
              const reference = source && sceneVideoReference(current, source, shotId);
              if (reference) onChange({ ...current, references: [...current.references, reference] });
            }}
            onHistorySelect={(job, versionId) => {
              onChange(selectSceneGeneration(configRef.current, job.id, versionId));
              setSelection({ jobId: job.id, shotId: null });
            }}
            onMakePrimary={(job, versionId) => {
              onChange(makeSceneGenerationPrimary(configRef.current, job.id, versionId));
              void purgeSceneThumbnails(job);
            }}
            onRemoveGeneration={(job, versionId) => {
              onChange(removeSceneGeneration(configRef.current, job.id, versionId));
              void purgeSceneThumbnails(job);
            }}
            onRemoveDraft={(job) => {
              onChange(removeSceneDraft(configRef.current, job.id));
              setSelection({ jobId: job.id, shotId: null });
            }}
            onDuplicate={(job) => {
              const duplicated = duplicateScene(configRef.current, job.id);
              if (duplicated) { onChange(duplicated.config); setSelection({ jobId: duplicated.id, shotId: null }); }
            }}
            onRemoveScene={(job) => void confirmRemoveScene(job)}
            onRemoveShot={(job, shotId) => void confirmRemoveShot(job, shotId)}
          />
          : <EmptyState
            icon={<Scene32 />}
            title="No scenes yet"
            description="Add a scene, then write what happens in each of its shots."
            action={<button type="button" className="secondary-button" onClick={newScene}>Add a scene</button>}
          />}
      </div></div>

      <ProjectStatus label="Generator status">
        <span role="status">{boardSummary(active.length, queued.length, jobs.length)}</span>
        {(runtimeError || (generatorRuntime && generatorRuntime.state !== "ready"))
          && <span className="generator-status__runtime">{runtimeError ? "Generator unavailable" : runtimeHeadline(generatorRuntime)}</span>}
      </ProjectStatus>
    </main>

    {selected && <Splitter {...inspectorPane.splitterProps} reverse aria-label="Resize inspector" aria-controls="generator-inspector" />}

    {selected && <aside id="generator-inspector" className="generator-panel" aria-label={openShot ? `${openShot.name ?? `Shot ${shotIndex + 1}`} of ${selected.title}` : `Scene: ${selected.title}`}>
      {openShot
        ? <>
          {/* The open shot heads the pane. Its meta line leads back up to the
              scene it belongs to, which is the same thing its header on the
              board opens. */}
          <ItemHeader
            color="var(--clip-generated)"
            icon={<Scene16 />}
            name={<h2 className="generator-panel__name"><input
                ref={titleInput}
                className="ui-item-header__input"
                value={openShot.name ?? ""}
                placeholder={`Shot ${shotIndex + 1}`}
                aria-label={`Rename shot ${shotIndex + 1}`}
                aria-keyshortcuts="F2"
                onChange={(event) => patchShot(selected, openShot.id, { name: event.target.value || null })}
              /></h2>}
            meta={<>
              {`Shot ${shotIndex + 1} · ${seconds(shotEndsAt - openShot.startSeconds)} · in `}
              <button type="button" className="generator-panel__up" data-tooltip={`Back to ${selected.title}`} onClick={() => setSelection({ jobId: selected.id, shotId: null })}>
                {selected.title}
              </button>
            </>}
            actions={selectedShots.length > 1 && <button
              type="button"
              className="icon-button"
              aria-label={`Delete shot ${shotIndex + 1}`}
              aria-keyshortcuts="Delete"
              {...tooltipProps("Delete shot", "Delete")}
              onClick={() => void confirmRemoveShot(selected, openShot.id)}
            ><Delete16 aria-hidden="true" /></button>}
          />
          <div className="panel-scroll">
            <ShotInspector
              key={openShot.id}
              job={selected}
              shots={selectedShots}
              shot={openShot}
              index={shotIndex}
              endsAt={shotEndsAt}
              duration={sceneDurationSeconds(selected)}
              references={isVideoTransition(selected) ? sceneGenerationReferences(selected, config.references) : config.references}
              folderPath={folderPath}
              disabled={false}
              onChange={(updates) => patchShot(selected, openShot.id, updates)}
            />
          </div>
        </>
        : <>
          {/* The title is the one part of a scene Slopus writes for the user,
              so it has to be theirs to change. Blanking it falls back rather
              than saving a nameless scene the schema would reject. */}
          <ItemHeader
            color="var(--clip-generated)"
            icon={<Sparkle16 />}
            name={<h2 className="generator-panel__name"><input
                ref={titleInput}
                className="ui-item-header__input"
                value={selected.title}
                aria-label={`Rename ${selected.title}`}
                aria-keyshortcuts="F2"
                onChange={(event) => updateJob(selected.id, { title: event.target.value || "Untitled scene", updatedAt: new Date().toISOString() })}
              /></h2>}
            meta={sceneMeta(selected, selectedShots.length, selectedIndicator)}
            actions={<button
              type="button"
              className="icon-button"
              aria-label={`Delete scene ${selected.title}`}
              aria-keyshortcuts="Delete"
              {...tooltipProps("Delete scene", "Delete")}
              onClick={() => void confirmRemoveScene(selected)}
            ><Delete16 aria-hidden="true" /></button>}
          />

          <div className="panel-scroll">
            <SceneInspector
              key={selected.id}
              sceneType={sceneTypeFor(selected)}
              job={selected}
              shots={selectedShots}
              template={selectedTemplate}
              usedGeneration={selectedTake ? { seed: sceneUsedSeed(selectedTake), generatorName: selectedTake.generatorName ?? usedGenerator?.name ?? selectedTake.scene.generatorTemplateId ?? undefined } : undefined}
              onUseGenerator={usedGenerator && templateUsable(usedGenerator) ? () => chooseGeneratorTemplate(usedGenerator.id) : undefined}
              onCopyError={setRuntimeError}
              defaultSteps={defaultGenerationSteps}
              effectiveSteps={generationStepsForTemplate(sceneGenerationSteps(selected, defaultGenerationSteps), selectedTemplate, selected.loraOverrides ?? [])}
              defaultLook={inheritedSettings.defaultLook}
              defaultLookSource={parentVideo ? "Video" : "project"}
              disabled={false}
              references={config.references}
              folderPath={folderPath}
              importAvailable={isTauri()}
              importError={startFrameError}
              scenes={config.generationJobs}
              neighborScenes={jobs}
              onAddStartFrame={() => void addFrame(selected, "start")}
              onAddEndFrame={() => void addFrame(selected, "end")}
              onChange={(updates) => changeSceneSettings(selected, updates)}
              onShots={(next) => setShots(selected, next)}
            />
          </div>

        </>}
      <div className="inspector-actions">
        {debugEnabled && !animate && !openShot && <button
          type="button"
          className="secondary-button debug-prompt__toggle"
          aria-expanded={showDebugPrompt}
          aria-haspopup="dialog"
          onClick={() => setShowDebugPrompt(true)}
        >Debug prompt</button>}
        <div className={`scene-generation-controls${!openShot && !selectedCancellable ? " scene-generation-controls--split" : ""}`}>
        <button
          type="button"
          className="primary-button scene-generate-button"
          data-tooltip={selectedCancellable ? `Cancel ${selected.title}` : selectedBlocker ?? `Generate ${selected.title}`}
          disabled={selectedCancellable ? selectedCancelling : Boolean(selectedBlocker)}
          onClick={() => generateScene(selected)}
        >
          {selectedCancellable ? <Stop14 aria-hidden="true" /> : <Sparkle16 aria-hidden="true" />}
          {selectedCancellable ? selectedCancelling ? "Cancelling…" : "Cancel" : "Generate"}
        </button>
        {!openShot && !selectedCancellable && <button ref={generationActionsButton} type="button" className="primary-button scene-generation-options"
          aria-label="Scene generation actions" aria-haspopup="dialog" aria-expanded={generationActionsOpen}
          onClick={() => setGenerationActionsOpen(!generationActionsOpen)}><ChevronDown14 aria-hidden="true" /></button>}
        </div>
        <Flyout open={generationActionsOpen && !openShot && !selectedCancellable} anchor={generationActionsButton} onClose={() => setGenerationActionsOpen(false)}
          placement="top-end" width={240} aria-label="Scene generation actions" className="scene-generation-actions">
          {[1.5, 2, 4].map(scale => <button key={scale} type="button" className="primary-button" disabled={Boolean(upscaleBlocker)} data-tooltip={upscaleBlocker ?? "Create a new Take from the selected Take's saved latents"}
            onClick={() => {
              setGenerationActionsOpen(false);
              try { onGenerate?.([sceneUpscaleSubmission(selected, config, scale, selectedTemplate)]); }
              catch (reason) { setRuntimeError(reason instanceof Error ? reason.message : String(reason)); }
            }}>Upscale {scale}x</button>)}
        </Flyout>
      </div>
    </aside>}

    {debugEnabled && showDebugPrompt && selected && !openShot && <DebugPromptDialog
      sceneTitle={selected.title}
      segments={compileGenerationJobSegments(frameInputs?.job ?? selected, boundRefs, inheritedSettings.defaultLook)}
      onClose={() => setShowDebugPrompt(false)}
    />}
  </div>;
}


const seconds = (value: number): string => `${value.toFixed(1)} s`;

/** The scene header's meta line: "Scene · 2 shots · 6.0 s · Finished". A
 *  draft says nothing about its state, the same as its line on the board. */
const sceneMeta = (job: GenerationJob, shots: number, indicator: SceneIndicatorStatus | undefined) => {
  const parts = ["Scene", shots === 1 ? "1 shot" : `${shots} shots`, seconds(sceneDurationSeconds(job))];
  if (job.status !== "draft" && indicator) parts.push(STATUS_BADGE[indicator]);
  return parts.join(" · ");
};

/** The status bar's one line: "3 scenes · 1 rendering · 2 waiting". */
const boardSummary = (active: number, waiting: number, total: number) => {
  if (total === 0) return "No scenes";
  const parts = [total === 1 ? "1 scene" : `${total} scenes`];
  if (active > 0) parts.push(`${active} rendering`);
  if (waiting > 0) parts.push(`${waiting} waiting`);
  return parts.join(" · ");
};

const runtimeHeadline = (runtime: SlopfabStatus | null) => {
  if (!runtime) return "Checking video engine…";
  switch (runtime.state) {
    case "ready": return "Video generator ready";
    case "demo": return "Preview mode";
    case "modelsMissing": return "Video model files missing";
    case "runtimeMissing": return "Video engine not installed";
    case "incompatible": return "Video engine doesn’t match";
  }
};