AI media harness for planning, generating, and editing locally
TypeScript
Add generator templates and progress diagnostics
Bitti96389c3e339e
diff --git a/src/components/SettingsView.test.tsx b/src/components/SettingsView.test.tsxindex a7ee848..dad1fcd 100644--- a/src/components/SettingsView.test.tsx+++ b/src/components/SettingsView.test.tsx@@ -20,6 +20,7 @@ afterEach(() => {const open = () => render(<SettingsView onClose={() => undefined} />);const tab = (name: string) => screen.getByRole("tab", { name: new RegExp(`^${name}`) });+const editDefaultGenerator = () => fireEvent.click(screen.getByRole("button", { name: "Edit Default generator" }));/* jsdom does no layout, so the one thing that can be checked here is that therule which makes the two tabs the same height is still in the sheet: the@@ -38,6 +39,9 @@ describe("the settings screen", () => {it("opens on the engine, because that is what has to be set before anything renders", async () => {open();expect(tab("Video engine").getAttribute("aria-selected")).toBe("true");+ expect(screen.getByRole("heading", { name: "Generators" })).toBeTruthy();+ expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();+ editDefaultGenerator();expect(screen.getByLabelText(/Transformer weights/)).toBeTruthy();// The other tab's contents are not merely hidden, they are not rendered:// a settings screen that draws both panels is the tall screen tabs replaced.@@ -56,12 +60,16 @@ describe("the settings screen", () => {models: [],});open();+ editDefaultGenerator();await waitFor(() => expect(screen.getByText("CUDA 13")).toBeTruthy());expect(screen.getByText("Platform")).toBeTruthy();});it("swaps panels when a tab is chosen, and follows the arrow keys", () => {open();+ expect(screen.getAllByRole("tab").map((item) => item.textContent?.replace(/\d+$/, ""))).toEqual([+ "Video engine", "Agents", "Appearance", "Diagnostics",+ ]);fireEvent.click(tab("Appearance"));expect(screen.getByRole("radiogroup", { name: "Appearance" })).toBeTruthy();expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();@@ -70,8 +78,8 @@ describe("the settings screen", () => {expect(screen.getByRole("tabpanel").getAttribute("aria-labelledby")).toBe("settings-tab-appearance");fireEvent.keyDown(tab("Appearance"), { key: "ArrowRight" });- expect(tab("Video engine").getAttribute("aria-selected")).toBe("true");- fireEvent.keyDown(tab("Video engine"), { key: "ArrowLeft" });+ expect(tab("Diagnostics").getAttribute("aria-selected")).toBe("true");+ fireEvent.keyDown(tab("Diagnostics"), { key: "ArrowLeft" });expect(tab("Appearance").getAttribute("aria-selected")).toBe("true");});@@ -92,25 +100,90 @@ describe("the settings screen", () => {}expect(screen.queryByText("This computer")).toBeNull();expect(screen.getByRole("heading", { name: "Settings" })).toBeTruthy();+ editDefaultGenerator();expect(screen.getByText("Reads your prompt so the transformer can act on it.")).toBeTruthy();});it("puts the optional tokenizer setting last", () => {const { container } = open();+ editDefaultGenerator();const labels = Array.from(container.querySelectorAll(".settings-path label b")).map((label) => label.textContent);expect(labels.at(-1)).toContain("Tokenizer");});- it("offers Clear all paths only beside the paths", () => {+ it("offers Clear generator paths only on the generator editor page", () => {open();- expect(screen.getByRole("button", { name: /Clear all paths/ })).toBeTruthy();+ expect(screen.queryByRole("button", { name: /Clear generator paths/ })).toBeNull();+ editDefaultGenerator();+ expect(screen.getByRole("button", { name: /Clear generator paths/ })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Generators" }));+ expect(screen.queryByRole("button", { name: /Clear generator paths/ })).toBeNull();fireEvent.click(tab("Appearance"));- expect(screen.queryByRole("button", { name: /Clear all paths/ })).toBeNull();+ expect(screen.queryByRole("button", { name: /Clear generator paths/ })).toBeNull();+ });++ it("replaces the settings tabs with the Generators back button while editing", () => {+ open();+ expect(screen.queryByText("Changes are saved as you type.")).toBeNull();+ editDefaultGenerator();+ const back = screen.getByRole("button", { name: "Generators" });+ expect(screen.queryByRole("tab", { name: "Appearance" })).toBeNull();+ expect(back.closest(".settings-tabs")).not.toBeNull();++ fireEvent.click(back);+ expect(screen.getByRole("tab", { name: "Appearance" })).toBeTruthy();+ });++ it("creates a generator with 20 steps, edits it on its own page, and can make it the default", () => {+ open();+ expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "New generator" }));+ expect((screen.getByLabelText("Generator name") as HTMLInputElement).value).toBe("Generator 2");+ expect((screen.getByLabelText("Generator default steps") as HTMLInputElement).value).toBe("20");++ fireEvent.change(screen.getByLabelText("Generator name"), { target: { value: "Fast draft" } });+ fireEvent.change(screen.getByLabelText("Generator default steps"), { target: { value: "12" } });+ fireEvent.change(screen.getByLabelText(/Transformer weights/), { target: { value: "D:\\Models\\draft.safetensors" } });+ fireEvent.click(screen.getByRole("button", { name: "Generators" }));+ expect(screen.queryByLabelText(/Transformer weights/)).toBeNull();+ fireEvent.click(screen.getByRole("radio", { name: "Use Fast draft as the default generator" }));++ const stored = JSON.parse(localStorage.getItem("polstudio.generator-templates.v1") ?? "null");+ const selected = stored.templates.find((template: { id: string }) => template.id === stored.defaultTemplateId);+ expect(selected).toMatchObject({ name: "Fast draft", defaultSteps: 12, paths: { transformer: "D:\\Models\\draft.safetensors" } });+ });++ it("puts each generator's radio first without a visible Default label", () => {+ open();+ const radio = screen.getByRole("radio", { name: "Use Default as the default generator" });+ const row = radio.closest(".generator-template-item");+ expect(row?.firstElementChild).toBe(radio.closest("label"));+ expect(radio.closest("label")?.textContent).toBe("");+ });++ it("shows where diagnostic logs live and can reveal the current file", async () => {+ Object.defineProperty(window, "__TAURI_INTERNALS__", { configurable: true, value: {} });+ const info = {+ path: "C:\\Users\\Editor\\AppData\\Local\\studio.pol.desktop\\logs\\polstudio.log",+ previousPath: null,+ sessionId: "42-1",+ maxFileBytes: 5_242_880,+ };+ vi.mocked(invoke).mockImplementation(async (command) => command === "diagnostic_log_info" || command === "reveal_diagnostic_log"+ ? info+ : { state: "ready", dllPath: "C:\\PolStudio\\vidfab.dll", version: "1.4.0", platform: "CUDA 13", detail: "Ready.", models: [] });++ open();+ fireEvent.click(tab("Diagnostics"));+ expect(await screen.findByText(info.path)).toBeTruthy();+ expect(screen.getByText(/Prompt text and credentials are not recorded/)).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Show log file" }));+ await waitFor(() => expect(vi.mocked(invoke).mock.calls.map(([command]) => command)).toContain("reveal_diagnostic_log"));});it("configures OpenRouter and local OpenAI-compatible models without requiring a local API key", () => {open();- fireEvent.click(tab("Prompt LLMs"));+ fireEvent.click(tab("Agents"));const openrouter = screen.getByRole("heading", { name: "OpenRouter" }).closest("section")!;expect((within(openrouter).getByLabelText("OpenRouter endpoint") as HTMLInputElement).value).toBe("https://openrouter.ai/api/v1");diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsxindex 04255ad..0d23623 100644--- a/src/components/SettingsView.tsx+++ b/src/components/SettingsView.tsx@@ -1,14 +1,17 @@-import { AlertCircle, Check, FolderSearch, LoaderCircle, Monitor, Moon, RefreshCw, RotateCcw, Sun, X } from "lucide-react";+import { AlertCircle, Check, ChevronLeft, FileText, FolderOpen, FolderSearch, LoaderCircle, Monitor, Moon, Plus, RefreshCw, RotateCcw, Sun, Trash2, X } from "lucide-react";import { useCallback, useEffect, useState } from "react";+import { getDiagnosticLogInfo, revealDiagnosticLog, type DiagnosticLogInfo } from "../lib/diagnostics";import { isTauri } from "../lib/persistence";import { chooseEnginePath, getAgentModels, getEngineStatus, type ModelStatus, type VidfabStatus } from "../lib/runtime";import {EMPTY_ENGINE_SETTINGS, ENGINE_PATH_FIELDS,- isEndpointProviderConfigured, loadAgentEndpointSettings, loadEngineSettings,- saveAgentEndpointSettings, saveEngineSettings,+ createGeneratorTemplate, defaultGeneratorTemplate,+ isEndpointProviderConfigured, loadAgentEndpointSettings,+ loadGeneratorTemplateSettings, saveAgentEndpointSettings, saveGeneratorTemplateSettings,type AgentEndpointSettings, type EndpointProviderId, type EndpointProviderSettings,- type EnginePathField, type EnginePathId, type EngineSettings,+ type EnginePathField, type EnginePathId, type EngineSettings, type GeneratorTemplateSettings,} from "../lib/settings";+import { MAX_GENERATION_STEPS } from "../lib/project";import {applyTheme, loadTheme, saveTheme, systemTheme, watchSystemTheme,type ResolvedTheme, type ThemeChoice,@@ -137,7 +140,7 @@ function PromptLlmSetting({ desktop }: { desktop: boolean }) {};return <div className="llm-settings">- <p className="llm-settings__intro">Configured providers appear in Slop’s prompt LLM list. Endpoints and API keys stay on this computer and are never saved in a project.</p>+ <p className="llm-settings__intro">Configured providers appear in Slop’s agent list. Endpoints and API keys stay on this computer and are never saved in a project.</p>{endpointProviders.map((provider) => {const value = settings[provider.id];const configured = isEndpointProviderConfigured(provider.id, value);@@ -173,6 +176,45 @@ function PromptLlmSetting({ desktop }: { desktop: boolean }) {</div>;}+function DiagnosticsSetting({ desktop }: { desktop: boolean }) {+ const [info, setInfo] = useState<DiagnosticLogInfo | null>(null);+ const [opening, setOpening] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ if (!desktop) return;+ void getDiagnosticLogInfo().then(setInfo).catch((reason) => setError(reason instanceof Error ? reason.message : String(reason)));+ }, [desktop]);++ const reveal = async () => {+ setOpening(true);+ setError(null);+ try {+ const next = await revealDiagnosticLog();+ if (next) setInfo(next);+ } catch (reason) {+ setError(reason instanceof Error ? reason.message : String(reason));+ } finally {+ setOpening(false);+ }+ };++ return <div className="diagnostics-setting">+ <div className="diagnostics-setting__icon"><FileText size={22} aria-hidden="true" /></div>+ <div>+ <h2>Application log</h2>+ <p>PolStudio records startup, runtime checks, generation stages, encoding, file writes, and unexpected errors in a readable text log. The file rotates at 5 MB and keeps one previous file.</p>+ <p>Prompt text and credentials are not recorded. Sensitive fields are redacted again when each record is written.</p>+ <code title={info?.path}>{desktop ? info?.path ?? "Locating the log…" : "Available in the desktop app"}</code>+ {info?.previousPath && <small>A previous rotated log is stored beside this file.</small>}+ <button type="button" className="secondary-button" disabled={!desktop || opening} onClick={() => void reveal()}>+ {opening ? <LoaderCircle className="spin" size={16} /> : <FolderOpen size={16} />} Show log file+ </button>+ {error && <p className="diagnostics-setting__error" role="alert">{error}</p>}+ </div>+ </div>;+}+/* Two things live on this screen and they have nothing to do with each other:how the app looks, and where this computer keeps the model files. Stacked,they made a screen taller than the window — five path fields is a long list —@@ -180,8 +222,9 @@ function PromptLlmSetting({ desktop }: { desktop: boolean }) {each, and neither scrolls on an ordinary window. */const TABS = [{ id: "engine", label: "Video engine" },- { id: "llms", label: "Prompt LLMs" },+ { id: "llms", label: "Agents" },{ id: "appearance", label: "Appearance" },+ { id: "diagnostics", label: "Diagnostics" },] as const;type TabId = (typeof TABS)[number]["id"];@@ -190,14 +233,20 @@ export function SettingsView({ onClose }: { onClose: () => void }) {before anything can be rendered, and its status line answers "is PolStudioready?" without a click. */const [tab, setTab] = useState<TabId>("engine");- const [settings, setSettings] = useState<EngineSettings>(() => loadEngineSettings());+ const [templateSettings, setTemplateSettings] = useState<GeneratorTemplateSettings>(() => loadGeneratorTemplateSettings());+ const [editingTemplateId, setEditingTemplateId] = useState<string | null>(null);const [status, setStatus] = useState<VidfabStatus | null>(null);const [error, setError] = useState<string | null>(null);const desktop = isTauri();- const probe = useCallback(() => {+ const defaultTemplate = defaultGeneratorTemplate(templateSettings);+ const selectedTemplate = templateSettings.templates.find((template) => template.id === editingTemplateId)+ ?? defaultTemplate;+ const settings = selectedTemplate.paths;++ const probe = useCallback((paths?: EngineSettings) => {setStatus(null);- void getEngineStatus().then(setStatus).catch(() => setStatus(null));+ void getEngineStatus(paths).then(setStatus).catch(() => setStatus(null));}, []);/* Saved on every keystroke — there is no Save button here, so a half-typed@@ -205,14 +254,19 @@ export function SettingsView({ onClose }: { onClose: () => void }) {The probe is deliberately NOT per keystroke: it touches the disk and loadsthe engine library. It runs when a field is left or a path is picked. */const update = (id: EnginePathId, value: string) => {- setSettings((current) => {- const next = { ...current, [id]: value };- saveEngineSettings(next);+ setTemplateSettings((current) => {+ const next = {+ ...current,+ templates: current.templates.map((template) => template.id === selectedTemplate.id+ ? { ...template, paths: { ...template.paths, [id]: value } }+ : template),+ };+ saveGeneratorTemplateSettings(next);return next;});};- useEffect(probe, [probe]);+ useEffect(() => { probe(settings); }, [probe, editingTemplateId, templateSettings.defaultTemplateId]);useEffect(() => {const close = (event: KeyboardEvent) => { if (event.key === "Escape") onClose(); };@@ -226,16 +280,63 @@ export function SettingsView({ onClose }: { onClose: () => void }) {const picked = await chooseEnginePath(field);if (!picked) return;update(field.id, picked);- probe();+ probe({ ...settings, [field.id]: picked });} catch (reason) {setError(reason instanceof Error ? reason.message : String(reason));}};const clearAll = () => {- setSettings({ ...EMPTY_ENGINE_SETTINGS });- saveEngineSettings({ ...EMPTY_ENGINE_SETTINGS });- probe();+ setTemplateSettings((current) => {+ const next = {+ ...current,+ templates: current.templates.map((template) => template.id === selectedTemplate.id+ ? { ...template, paths: { ...EMPTY_ENGINE_SETTINGS } }+ : template),+ };+ saveGeneratorTemplateSettings(next);+ return next;+ });+ probe({ ...EMPTY_ENGINE_SETTINGS });+ };++ const updateTemplate = (updates: Partial<Pick<typeof selectedTemplate, "name" | "defaultSteps">>) => {+ setTemplateSettings((current) => {+ const next = {+ ...current,+ templates: current.templates.map((template) => template.id === selectedTemplate.id ? { ...template, ...updates } : template),+ };+ saveGeneratorTemplateSettings(next);+ return next;+ });+ };++ const addTemplate = () => {+ const created = createGeneratorTemplate(`Generator ${templateSettings.templates.length + 1}`);+ setTemplateSettings((current) => {+ const next = { ...current, templates: [...current.templates, created] };+ saveGeneratorTemplateSettings(next);+ return next;+ });+ setEditingTemplateId(created.id);+ };++ const removeTemplate = (id: string) => {+ if (templateSettings.templates.length <= 1) return;+ const remaining = templateSettings.templates.filter((template) => template.id !== id);+ const next: GeneratorTemplateSettings = {+ templates: remaining,+ defaultTemplateId: id === templateSettings.defaultTemplateId ? remaining[0].id : templateSettings.defaultTemplateId,+ };+ setTemplateSettings(next);+ saveGeneratorTemplateSettings(next);+ if (editingTemplateId === id) setEditingTemplateId(null);+ };++ const makeDefault = (id: string) => {+ const next = { ...templateSettings, defaultTemplateId: id };+ setTemplateSettings(next);+ saveGeneratorTemplateSettings(next);};const missing = ENGINE_PATH_FIELDS.filter((field) => field.required && pathState(field, settings[field.id], status) !== "found");@@ -252,7 +353,9 @@ export function SettingsView({ onClose }: { onClose: () => void }) {tablist rather than two buttons that happen to swap the content:the arrow keys move between them, and the panel below is named bythe tab that opened it. */}- <div className="settings-tabs" role="tablist" aria-label="Settings sections">+ {editingTemplateId ? <div className="settings-tabs settings-tabs--editor">+ <button type="button" className="generator-editor__back" onClick={() => setEditingTemplateId(null)}><ChevronLeft size={16} /> Generators</button>+ </div> : <div className="settings-tabs" role="tablist" aria-label="Settings sections">{TABS.map((item, index) => (<buttonkey={item.id}@@ -277,7 +380,7 @@ export function SettingsView({ onClose }: { onClose: () => void }) {{item.id === "engine" && missing.length > 0 && <em title={`${missing.length} model ${missing.length === 1 ? "path" : "paths"} still to set`}>{missing.length}</em>}</button>))}- </div>+ </div>}<div className="settings-view__body">{tab === "llms" && <section@@ -298,61 +401,112 @@ export function SettingsView({ onClose }: { onClose: () => void }) {<AppearanceSetting /></section>}+ {tab === "diagnostics" && <section+ className="settings-section"+ id="settings-panel-diagnostics"+ role="tabpanel"+ aria-labelledby="settings-tab-diagnostics"+ >+ <DiagnosticsSetting desktop={desktop} />+ </section>}+{tab === "engine" && <sectionclassName="settings-section"id="settings-panel-engine"- role="tabpanel"- aria-labelledby="settings-tab-engine"+ role={editingTemplateId ? "region" : "tabpanel"}+ aria-labelledby={editingTemplateId ? "generator-editor-heading" : "settings-tab-engine"}>- <div className={`settings-status settings-status--${status?.state ?? "checking"}`} role="status">- <span><i />{engineHeadline(status, desktop)}</span>- <p>{engineDetail(status, desktop, missing.length)}</p>- {status?.platform && <small className="settings-status__platform"><b>Platform</b>{status.platform}</small>}- </div>- {ENGINE_PATH_FIELDS.map((field) => {- const value = settings[field.id];- const state = pathState(field, value, status);- return (- <div className={`settings-path settings-path--${state}`} key={field.id}>- <label htmlFor={`engine-${field.id}`}>- <b>{field.label}{!field.required && <em>Optional</em>}</b>- <small>{field.hint}</small>- </label>- <div className="settings-path__row">- <input- id={`engine-${field.id}`}- value={value}- spellCheck={false}- placeholder={field.directory ? "Folder on this computer" : "File on this computer"}- onChange={(event) => update(field.id, event.target.value)}- onBlur={probe}- />- <button- type="button"- className="secondary-button"- onClick={() => void browse(field)}- disabled={!desktop}- title={desktop ? `Browse for ${field.label}` : "Browsing for files is available in the desktop app"}- >- <FolderSearch size={16} /> Browse+ {!editingTemplateId ? <section className="generator-templates" aria-labelledby="generators-heading">+ <header>+ <div>+ <h2 id="generators-heading">Generators</h2>+ <p>Choose the generator used by default, or open one to edit its model setup.</p>+ </div>+ <button type="button" className="secondary-button" onClick={addTemplate}><Plus size={16} /> New generator</button>+ </header>+ <div className="generator-template-list" role="list" aria-label="Generators">+ {templateSettings.templates.map((template) => (+ <div className={`generator-template-item${template.id === templateSettings.defaultTemplateId ? " generator-template-item--selected" : ""}`} role="listitem" key={template.id}>+ <label className="generator-template-item__default" title="Use this generator for generation by default">+ <input type="radio" name="default-generator-template" checked={template.id === templateSettings.defaultTemplateId} onChange={() => makeDefault(template.id)} aria-label={`Use ${template.name} as the default generator`} />+ </label>+ <button type="button" className="generator-template-item__open" onClick={() => setEditingTemplateId(template.id)} aria-label={`Edit ${template.name} generator`}>+ <b>{template.name}</b><small>{template.defaultSteps} steps</small></button>- <span className="settings-path__state">- {state === "found" ? <Check size={14} aria-hidden="true" /> : state === "missing" ? <AlertCircle size={14} aria-hidden="true" /> : null}- {stateLabel[state]}- </span>+ <button type="button" className="icon-button" disabled={templateSettings.templates.length === 1} onClick={() => removeTemplate(template.id)} aria-label={`Remove generator ${template.name}`} title={templateSettings.templates.length === 1 ? "At least one generator is required" : `Remove ${template.name}`}><Trash2 size={15} /></button></div>+ ))}+ </div>+ </section> : <div className="generator-editor">+ <header className="generator-editor__head">+ <div>+ <h2 id="generator-editor-heading">Edit generator</h2>+ <p>Set its name, generation steps, and model locations on this computer.</p></div>- );- })}+ </header>+ <div className="generator-template-fields">+ <label>+ <span>Name</span>+ <input aria-label="Generator name" value={selectedTemplate.name} onChange={(event) => updateTemplate({ name: event.target.value })} onBlur={() => { if (!selectedTemplate.name.trim()) updateTemplate({ name: "Untitled generator" }); }} />+ </label>+ <label>+ <span>Default steps</span>+ <input aria-label="Generator default steps" type="number" min={2} max={MAX_GENERATION_STEPS} step={1} value={selectedTemplate.defaultSteps} onChange={(event) => {+ const value = Number(event.target.value);+ if (Number.isInteger(value) && value >= 2 && value <= MAX_GENERATION_STEPS) updateTemplate({ defaultSteps: value });+ }} />+ </label>+ </div>+ <div className={`settings-status settings-status--${status?.state ?? "checking"}`} role="status">+ <span><i />{engineHeadline(status, desktop)}</span>+ <p>{engineDetail(status, desktop, missing.length)}</p>+ {status?.platform && <small className="settings-status__platform"><b>Platform</b>{status.platform}</small>}+ </div>+ {ENGINE_PATH_FIELDS.map((field) => {+ const value = settings[field.id];+ const state = pathState(field, value, status);+ return (+ <div className={`settings-path settings-path--${state}`} key={field.id}>+ <label htmlFor={`engine-${field.id}`}>+ <b>{field.label}{!field.required && <em>Optional</em>}</b>+ <small>{field.hint}</small>+ </label>+ <div className="settings-path__row">+ <input+ id={`engine-${field.id}`}+ value={value}+ spellCheck={false}+ placeholder={field.directory ? "Folder on this computer" : "File on this computer"}+ onChange={(event) => update(field.id, event.target.value)}+ onBlur={() => probe(settings)}+ />+ <button+ type="button"+ className="secondary-button"+ onClick={() => void browse(field)}+ disabled={!desktop}+ title={desktop ? `Browse for ${field.label}` : "Browsing for files is available in the desktop app"}+ >+ <FolderSearch size={16} /> Browse+ </button>+ <span className="settings-path__state">+ {state === "found" ? <Check size={14} aria-hidden="true" /> : state === "missing" ? <AlertCircle size={14} aria-hidden="true" /> : null}+ {stateLabel[state]}+ </span>+ </div>+ </div>+ );+ })}+ </div>}</section>}</div>- <footer className="settings-view__foot">+ {(tab === "diagnostics" || (tab === "engine" && editingTemplateId)) && <footer className="settings-view__foot">{/* Clearing the paths is an engine action, so it is only offered- beside them. The saving note is true of the whole screen. */}- {tab === "engine" && <button className="secondary-button" onClick={clearAll}><RotateCcw size={16} /> Clear all paths</button>}- <span>Changes are saved as you type.</span>- </footer>+ beside them. */}+ {tab === "engine" && editingTemplateId && <button className="secondary-button" onClick={clearAll}><RotateCcw size={16} /> Clear generator paths</button>}+ {tab === "diagnostics" && <span>Logs stay on this computer.</span>}+ </footer>}{error && <div className="toast" role="alert"><strong>Couldn’t open the file picker</strong><span>{error}</span><button onClick={() => setError(null)}>Dismiss</button></div>}</div>diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex 1793bda..aafab1a 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -3,17 +3,22 @@import "@testing-library/jest-dom/vitest";import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { useState } from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { createDraftGenerationJob, createProjectConfig, parseProjectConfig, sceneShots, type ProjectConfig } from "../../lib/project";-import { cancelVidfabGeneration, type VidfabStatus } from "../../lib/runtime";+import { cancelVidfabGeneration, getEngineStatus, type VidfabStatus } from "../../lib/runtime";import { GeneratorView } from "./GeneratorView";vi.mock("../../lib/runtime", async (importOriginal) => ({...await importOriginal<typeof import("../../lib/runtime")>(),cancelVidfabGeneration: vi.fn().mockResolvedValue(true),+ getEngineStatus: vi.fn(),}));-beforeEach(() => vi.clearAllMocks());+beforeAll(() => vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => undefined));+beforeEach(() => {+ localStorage.clear();+ vi.clearAllMocks();+});afterEach(cleanup);const readyRuntime: VidfabStatus = {@@ -212,7 +217,7 @@ describe("Generator scene controls", () => {expect(sceneShots(target).map((shot) => shot.startSeconds)).toEqual([0, 4]);});- it("puts scene length and confirmed removal in the header without a Draft indicator", () => {+ it("selects a scene from its header and keeps confirmed removal in the inspector", () => {const state = setup();expect(screen.queryByText("DRAFT")).not.toBeInTheDocument();expect(screen.queryByText(/^Draft/)).not.toBeInTheDocument();@@ -221,7 +226,14 @@ describe("Generator scene controls", () => {expect(state.latest().generationJobs[0].durationSeconds).toBe(10);expect(screen.queryByText("CHANGED")).not.toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Remove scene First scene" }));+ const scene = screen.getByRole("region", { name: "First scene" });+ expect(within(scene).queryByRole("button", { name: "Remove scene First scene" })).not.toBeInTheDocument();+ expect(within(scene).queryByRole("button", { name: "Settings for First scene" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Shot 1 of First scene" }));+ fireEvent.click(scene.querySelector(".scene-rule")!);+ expect(screen.getByRole("textbox", { name: "Rename First scene" })).toBeInTheDocument();++ fireEvent.click(within(screen.getByRole("complementary", { name: "Scene: First scene" })).getByRole("button", { name: "Remove scene First scene" }));expect(screen.getByRole("alertdialog", { name: "Remove scene?" })).toBeInTheDocument();expect(state.latest().generationJobs.map((job) => job.id)).toEqual(["scene-first", "scene-second"]);fireEvent.click(screen.getByRole("button", { name: "Remove scene" }));@@ -230,11 +242,68 @@ describe("Generator scene controls", () => {it("adds new scenes at the bottom", () => {const state = setup();- fireEvent.click(screen.getByRole("button", { name: "Add Scene" }));+ fireEvent.click(screen.getByRole("button", { name: "Add a scene" }));expect(state.latest().generationJobs.slice(0, 2).map((job) => job.id)).toEqual(["scene-first", "scene-second"]);expect(state.latest().generationJobs.at(-1)?.title).toBe("Untitled scene");});+ it("uses the default generator template's steps for a new scene", () => {+ localStorage.setItem("polstudio.generator-templates.v1", JSON.stringify({+ defaultTemplateId: "draft",+ templates: [{+ id: "draft",+ name: "Draft",+ defaultSteps: 9,+ paths: { transformer: "", textEncoder: "", tokenizer: "", videoVae: "", audioVae: "" },+ }],+ }));+ const state = setup();+ fireEvent.click(screen.getByRole("button", { name: "Add a scene" }));+ expect(state.latest().generationJobs.at(-1)?.steps).toBe(9);+ });++ it("switches the active generator from the ready status control and probes its model paths", async () => {+ localStorage.setItem("polstudio.generator-templates.v1", JSON.stringify({+ defaultTemplateId: "quality",+ templates: [+ {+ id: "quality",+ name: "Quality",+ defaultSteps: 20,+ paths: { transformer: "quality.safetensors", textEncoder: "", tokenizer: "", videoVae: "", audioVae: "" },+ },+ {+ id: "draft",+ name: "Fast draft",+ defaultSteps: 8,+ paths: { transformer: "draft.safetensors", textEncoder: "", tokenizer: "", videoVae: "", audioVae: "" },+ },+ ],+ }));+ vi.mocked(getEngineStatus).mockResolvedValueOnce({+ state: "modelsMissing",+ dllPath: "test",+ version: "test",+ platform: "CUDA 13",+ detail: "Draft weights are missing.",+ models: [],+ });+ setup();++ expect(document.querySelector(".generator-runtime--ready > i")).not.toBeNull();+ expect(screen.getByText("Generator:")).toBeInTheDocument();+ expect(screen.queryByText("Video generator ready")).not.toBeInTheDocument();+ const template = screen.getByRole("combobox", { name: /Video generator template/ });+ expect(template).toHaveTextContent("Quality");+ fireEvent.click(template);+ fireEvent.click(screen.getByRole("option", { name: "Fast draft" }));++ await waitFor(() => expect(document.querySelector(".generator-runtime--modelsMissing > i")).not.toBeNull());+ expect(getEngineStatus).toHaveBeenCalledWith(expect.objectContaining({ transformer: "draft.safetensors" }));+ expect(JSON.parse(localStorage.getItem("polstudio.generator-templates.v1")!).defaultTemplateId).toBe("draft");+ expect(screen.getByText("Video model files missing")).toBeInTheDocument();+ });+it("marks a finished scene yellow when scene settings change", async () => {const state = setup();await finishFirst(state);@@ -340,6 +409,62 @@ describe("Generator scene controls", () => {expect(parseProjectConfig(state.latest())).toBeTruthy();});+ it("keeps Generate All available and skips unchanged completed fixed-seed scenes", async () => {+ const initial = project();+ initial.generationJobs = initial.generationJobs.map((job, index) => ({ ...job, seed: 100 + index }));+ const state = setup(initial);++ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));+ await waitFor(() => expect(state.latest().generationJobs.every((job) => job.status === "queued")).toBe(true));+ state.replace({+ ...state.latest(),+ generationJobs: state.latest().generationJobs.map((job) => ({+ ...job,+ status: "completed",+ stage: "completed",+ progress: 1,+ outputRelativePath: `media/generated/${job.id}.mp4`,+ })),+ });++ const generateAll = screen.getByRole("button", { name: "Generate All" });+ expect(generateAll).toBeEnabled();+ fireEvent.click(generateAll);+ expect(state.latest().generationJobs.map((job) => job.status)).toEqual(["completed", "completed"]);++ const changed = state.latest().generationJobs[0];+ state.replace({+ ...state.latest(),+ generationJobs: state.latest().generationJobs.map((job) => job.id === changed.id+ ? { ...job, shots: sceneShots(job).map((shot, index) => index === 0 ? { ...shot, action: `${shot.action} Changed.` } : shot) }+ : job),+ });+ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));+ await waitFor(() => expect(state.latest().generationJobs.map((job) => job.status)).toEqual(["queued", "completed"]));+ });++ it("regenerates an unchanged completed random-seed scene while skipping fixed-seed output", async () => {+ const initial = project();+ initial.generationJobs[1].seed = 417;+ const state = setup(initial);++ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));+ await waitFor(() => expect(state.latest().generationJobs.every((job) => job.status === "queued")).toBe(true));+ state.replace({+ ...state.latest(),+ generationJobs: state.latest().generationJobs.map((job) => ({+ ...job,+ status: "completed",+ stage: "completed",+ progress: 1,+ outputRelativePath: `media/generated/${job.id}.mp4`,+ })),+ });++ fireEvent.click(screen.getByRole("button", { name: "Generate All" }));+ await waitFor(() => expect(state.latest().generationJobs.map((job) => job.status)).toEqual(["queued", "completed"]));+ });+it("turns active generation actions into per-scene and batch cancellation", async () => {const initial = project();initial.generationJobs = initial.generationJobs.map((job, index) => ({diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex c58cde7..32cc984 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,13 +1,17 @@-import { Plus, Sparkles, Square, Trash2, WandSparkles } from "lucide-react";+import { ChevronDown, Plus, Sparkles, Square, Trash2, WandSparkles } from "lucide-react";import { invoke } from "@tauri-apps/api/core";import { useEffect, useMemo, useRef, useState } from "react";-import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, GENERATION_FRAME_RATE, sceneDurationSeconds, sceneGenerationReferences, sceneGenerationSeed, sceneGenerationSnapshot, sceneGenerationSteps, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, projectItemPath, usableReferenceImages, type GenerationJob, type ProjectConfig, type ProjectReference, type PromptSegment, type SceneShot } from "../../lib/project";+import { describeDiagnosticError, errorContext, writeDiagnostic } from "../../lib/diagnostics";+import { actionReferenceIds, compileGenerationJobPrompt, compileGenerationJobSegments, createDraftGenerationJob, danglingReferenceTokens, GENERATION_FRAME_RATE, RANDOM_GENERATION_SEED, sceneDurationSeconds, sceneGenerationReferences, sceneGenerationSeed, sceneGenerationSnapshot, sceneGenerationSteps, sceneShots, SCENE_MAX_SECONDS, SCENE_MIN_SECONDS, projectItemPath, usableReferenceImages, type GenerationJob, type ProjectConfig, type ProjectReference, type PromptSegment, type SceneShot } from "../../lib/project";import { generationDimensions } from "../../lib/export";import { isTauri } from "../../lib/persistence";-import { cancelVidfabGeneration, enqueueVidfabGeneration, resolveVidfabPlan, type VidfabGenerationRequest, type VidfabStatus } from "../../lib/runtime";+import { cancelVidfabGeneration, enqueueVidfabGeneration, getEngineStatus, resolveVidfabPlan, type VidfabGenerationRequest, type VidfabStatus } from "../../lib/runtime";import { SceneBoard, type GeneratorSelection } from "./SceneBoard";import { SceneInspector, ShotInspector, STEP_SECONDS, writeShots } from "./SceneEditor";import { statusIcon } from "./sceneStatus";+import { forgetShotPosters } from "./ShotThumbnail";+import { purgeTimelineThumbnails } from "../../lib/timelineThumbnails";+import { defaultGeneratorTemplate, loadGeneratorTemplateSettings, saveGeneratorTemplateSettings, type GeneratorTemplate } from "../../lib/settings";interface GeneratorViewProps {config: ProjectConfig;@@ -17,6 +21,7 @@ interface GeneratorViewProps {onChange: (next: ProjectConfig) => void;onOpenTimeline: () => void;selectedJobId?: string;+ onRuntimeChange?: (runtime: VidfabStatus) => void;}type RemovalTarget =@@ -34,8 +39,14 @@ type RemovalTarget =* 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, folderPath, runtime = null, generationCompletionTimes = {}, onChange, selectedJobId }: GeneratorViewProps) {+export function GeneratorView({ config, folderPath, runtime = null, generationCompletionTimes = {}, onChange, selectedJobId, onRuntimeChange }: GeneratorViewProps) {const jobs = config.generationJobs;+ const [templateSettings, setTemplateSettings] = useState(loadGeneratorTemplateSettings);+ const selectedTemplate = defaultGeneratorTemplate(templateSettings);+ const defaultGenerationSteps = selectedTemplate.defaultSteps;+ const [generatorRuntime, setGeneratorRuntime] = useState<VidfabStatus | null>(runtime);+ const [runtimeError, setRuntimeError] = useState<string | null>(null);+ const runtimeProbe = useRef(0);const configRef = useRef(config);configRef.current = config;// A scene is displayed as queued while its plan is resolving, just before@@ -56,6 +67,33 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst [showDebugPrompt, setShowDebugPrompt] = useState(false);const [startFrameError, setStartFrameError] = useState<string | null>(null);+ useEffect(() => {+ setTemplateSettings(loadGeneratorTemplateSettings());+ setGeneratorRuntime(runtime);+ setRuntimeError(null);+ }, [runtime]);++ useEffect(() => () => { runtimeProbe.current += 1; }, []);++ const chooseGeneratorTemplate = (templateId: string) => {+ const template = templateSettings.templates.find((candidate) => candidate.id === templateId);+ if (!template || template.id === templateSettings.defaultTemplateId) return;+ const next = { ...templateSettings, defaultTemplateId: template.id };+ saveGeneratorTemplateSettings(next);+ setTemplateSettings(next);+ setGeneratorRuntime(null);+ setRuntimeError(null);+ const probe = ++runtimeProbe.current;+ void getEngineStatus(template.paths).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));+ });+ };+useEffect(() => { if (selectedJobId) setSelection({ jobId: selectedJobId, shotId: null }); }, [selectedJobId]);/* A scene can be deleted, and a shot can be removed, from under the panel.@@ -69,7 +107,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst queued = jobs.filter((job) => job.status === "queued");const cancellable = jobs.filter((job) => job.status === "queued" || job.status === "generating");const boundRefs = useMemo(() => selected ? sceneGenerationReferences(selected, config.references) : [], [config.references, selected]);- const runtimeReady = runtime?.state === "ready";+ const runtimeReady = generatorRuntime?.state === "ready";const updateJob = (id: string, updates: Partial<GenerationJob>) => {const current = configRef.current;@@ -242,7 +280,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoprompt: compileGenerationJobPrompt(job, bound),// The scene's own length, not a fixed six seconds.frames: Math.round(sceneDurationSeconds(job) * GENERATION_FRAME_RATE),- steps: sceneGenerationSteps(job),+ steps: sceneGenerationSteps(job, defaultGenerationSteps),seed: sceneGenerationSeed(job),canvasWidth: canvas.width,canvasHeight: canvas.height,@@ -255,6 +293,27 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst snapshotFor = (job: GenerationJob, request = requestFor(job)): string =>sceneGenerationSnapshot(job, request);+ const logRequest = (event: string, message: string, request: VidfabGenerationRequest) => writeDiagnostic("info", "generator", event, message, {+ jobId: request.jobId,+ frames: request.frames,+ steps: request.steps,+ canvasWidth: request.canvasWidth,+ canvasHeight: request.canvasHeight,+ referenceCount: request.referencePaths.length,+ inputChars: request.prompt.length,+ });++ const logFailure = (event: string, jobId: string, reason: unknown) => {+ const detail = describeDiagnosticError(reason);+ writeDiagnostic("error", "generator", event, detail, { jobId, ...errorContext(reason) });+ return detail;+ };++ const purgeSceneThumbnails = async (job: GenerationJob) => {+ if (job.outputRelativePath) forgetShotPosters(folderPath, job.outputRelativePath);+ await purgeTimelineThumbnails(folderPath, job.id).catch(() => undefined);+ };+/* The engine's own events are listened for by the project screen(useGenerationEvents), not here: a render outlives this view, and theencode that turns its frames into a file has to happen wherever the user@@ -268,15 +327,23 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo: current);const now = new Date().toISOString();const request = requestFor(job);+ if (runtimeReady) await purgeSceneThumbnails(job);updateJob(job.id, {status: runtimeReady ? "queued" : "draft",stage: "queued",progress: 0,- error: runtimeReady ? null : runtime?.detail ?? "The video engine isn’t available on this computer right now.",+ error: runtimeReady ? null : runtimeError ?? generatorRuntime?.detail ?? "The video engine isn’t available on this computer right now.",generationSnapshot: runtimeReady ? snapshotFor(job, request) : job.generationSnapshot,updatedAt: now,});- if (runtimeReady) await enqueueVidfabGeneration(request, configRef.current);+ if (runtimeReady) {+ logRequest("generation.retry_requested", "Generation retry requested.", request);+ try {+ await enqueueVidfabGeneration(request, configRef.current);+ } catch (reason) {+ updateJob(job.id, { status: "failed", stage: "failed", error: logFailure("generation.retry_failed", job.id, reason) });+ }+ }};/* A scene now starts EMPTY. There is no box that turns a sentence into a@@ -286,12 +353,12 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoUNTITLED_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 the whole- project with the new scene in it. Nothing is auto-bound either way — which+ window hands the request to Claude Code or Codex, which returns a compact+ command batch that PolStudio applies. Nothing is auto-bound either way — whichreferences steer a scene is decided by writing them into a line or by thereferences already named by its shots. */const newScene = () => {- const job = createDraftGenerationJob("");+ const job = createDraftGenerationJob("", { steps: defaultGenerationSteps });onChange({ ...config, generationJobs: [...jobs, job] });setSelection({ jobId: job.id, shotId: null });};@@ -300,6 +367,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst 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 cancelVidfabGeneration(job.id);const generationJobs = current.generationJobs.filter((item) => item.id !== job.id);onChange({ ...current, generationJobs });@@ -311,11 +379,13 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst startDraft = async (job: GenerationJob) => {if (!runtimeReady) return;+ await purgeSceneThumbnails(job);cancellationRequests.current.delete(job.id);setCancellingJobIds((current) => current.has(job.id)? new Set([...current].filter((id) => id !== job.id)): current);const request = requestFor(job);+ logRequest("generation.requested", "Generation requested from the scene board.", request);updateJob(job.id, {status: "queued",stage: "queued",@@ -335,7 +405,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoawait enqueueVidfabGeneration(request, configRef.current);} catch (reason) {if (cancellationRequests.current.has(job.id)) return;- updateJob(job.id, { status: "failed", stage: "failed", error: reason instanceof Error ? reason.message : String(reason) });+ updateJob(job.id, { status: "failed", stage: "failed", error: logFailure("generation.prepare_failed", job.id, reason) });}};@@ -349,7 +419,8 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoconst accepted = await Promise.all(next.map(async (job) => {try {return await cancelVidfabGeneration(job.id);- } catch {+ } catch (reason) {+ logFailure("generation.cancel_failed", job.id, reason);return false;}}));@@ -377,18 +448,31 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoelse void prepareOrRetry(job);};- const draftScenesReady = jobs.filter((job) => job.status === "draft" && !sendBlocker(job, config.references));+ /** 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 = jobs.filter((job) => {+ if (job.status === "queued" || job.status === "generating" || job.status === "ready") return false;+ if (sendBlocker(job, config.references)) return false;+ if (sceneGenerationSeed(job) === RANDOM_GENERATION_SEED) return true;+ return job.status !== "completed"+ || !job.outputRelativePath+ || !job.generationSnapshot+ || job.generationSnapshot !== snapshotFor(job);+ });const generateAll = async () => {- if (!runtimeReady || draftScenesReady.length === 0) return;- draftScenesReady.forEach((job) => cancellationRequests.current.delete(job.id));- const startingIds = new Set(draftScenesReady.map((job) => job.id));+ if (!runtimeReady || batchScenesReady.length === 0) return;+ await Promise.all(batchScenesReady.map(purgeSceneThumbnails));+ batchScenesReady.forEach((job) => cancellationRequests.current.delete(job.id));+ const startingIds = new Set(batchScenesReady.map((job) => job.id));setCancellingJobIds((current) => {const next = new Set([...current].filter((id) => !startingIds.has(id)));return next.size === current.size ? current : next;});const current = configRef.current;- const requests = draftScenesReady.map((job) => ({ job, request: requestFor(job) }));+ const requests = batchScenesReady.map((job) => ({ job, request: requestFor(job) }));+ requests.forEach(({ request }) => logRequest("generation.requested", "Generation requested by Generate All.", request));const ids = new Map(requests.map(({ job, request }) => [job.id, snapshotFor(job, request)]));const now = new Date().toISOString();onChange({@@ -407,13 +491,13 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoawait enqueueVidfabGeneration(request, current);} catch (reason) {if (cancellationRequests.current.has(job.id)) continue;- updateJob(job.id, { status: "failed", stage: "failed", error: reason instanceof Error ? reason.message : String(reason) });+ updateJob(job.id, { status: "failed", stage: "failed", error: logFailure("generation.prepare_failed", job.id, reason) });}}};const generationBlocker = (job: GenerationJob): string | null => {- if (!runtimeReady) return runtime?.detail ?? "The video generator is not ready.";+ if (!runtimeReady) return runtimeError ?? generatorRuntime?.detail ?? "The video generator is not ready.";if (job.status === "ready") return "This scene is being saved now.";return sendBlocker(job, config.references);};@@ -434,25 +518,27 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo</div><div className="generator-heading__actions">{/* One line: the headline already IS the status. */}- <span className={`generator-runtime generator-runtime--${runtime?.state ?? "checking"}`}>- <i aria-hidden="true" /> {runtimeHeadline(runtime)}- </span>- {/* Adds the scene and leaves it empty. PolStudio still writes no words- for anyone — it gives the user somewhere to write them, and the- scene keeps the name UNTITLED_SCENE until they rename it. */}- <button className="secondary-button" onClick={newScene} title="Add an empty scene — you write the shots">- <Plus size={16} aria-hidden="true" /> Add Scene- </button>+ <div+ className={`generator-runtime generator-runtime--${runtimeError ? "unavailable" : generatorRuntime?.state ?? "checking"}`}+ title={runtimeError ?? generatorRuntime?.detail ?? runtimeHeadline(generatorRuntime)}+ >+ <i role="img" aria-label={runtimeError ? "Video generator unavailable" : runtimeHeadline(generatorRuntime)} />+ <span className="generator-runtime__label">Generator:</span>+ <GeneratorTemplateCombobox templates={templateSettings.templates} selected={selectedTemplate} onChange={chooseGeneratorTemplate} />+ {(runtimeError || generatorRuntime?.state !== "ready") && <span className="generator-runtime__status" aria-hidden="true">{runtimeError ? "Unavailable" : runtimeHeadline(generatorRuntime)}</span>}+ </div><buttonclassName={cancellable.length > 0 ? "danger-button generator-heading__cancel" : "primary-button"}- disabled={cancellable.length === 0 && (!runtimeReady || draftScenesReady.length === 0)}+ disabled={cancellable.length === 0 && active.length > 0}title={cancellable.length > 0? `Cancel ${cancellable.length} ${cancellable.length === 1 ? "generation" : "generations"}`: !runtimeReady- ? runtime?.detail ?? "The video generator is not ready."- : draftScenesReady.length === 0- ? "There are no ready draft scenes to generate."- : `Generate ${draftScenesReady.length} draft ${draftScenesReady.length === 1 ? "scene" : "scenes"}`}+ ? 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"}`}onClick={() => cancellable.length > 0 ? void cancelScenes(cancellable) : void generateAll()}>{cancellable.length > 0@@ -469,9 +555,9 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoreferences={config.references}selection={{ jobId: selected?.id ?? "", shotId: openShot?.id ?? null }}onSelect={setSelection}+ onAddScene={newScene}onAddShot={addShot}onDuration={setDuration}- onRemoveScene={(job) => setRemovalTarget({ kind: "scene", job })}onGenerate={generateScene}generationBlocker={generationBlocker}changedJobIds={changedJobIds}@@ -494,8 +580,17 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo<li>You can read the finished prompt before anything is sent.</li><li>Or ask Slop in the bar along the bottom — Claude Code and Codex can write a whole scene from a prompt.</li></ul>- <button className="primary-button job-empty__add" onClick={newScene}><Plus size={16} /> Add an empty scene</button></div>}++ {jobs.length === 0 && <button+ type="button"+ className="shot-card shot-card--add scene-card--add"+ onClick={newScene}+ title="Add an empty scene — you write the shots"+ >+ <Plus size={18} aria-hidden="true" />+ <span>Add a scene</span>+ </button>}</main>{selected && <aside className="generator-panel" aria-label={openShot ? `${openShot.name ?? `Shot ${shotIndex + 1}`} of ${selected.title}` : `Scene: ${selected.title}`}>@@ -542,24 +637,33 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo</>: <><header className="panel-head">- <div className="job-title">- {selected.status !== "draft" && selectedIndicator && <span className={`status-icon status-icon--${selectedIndicator}`}>{statusIcon(selectedIndicator)}</span>}- <div>- {/* The badge is on the scene's own line on the board, where the- eye compares one scene against the next. A second copy of it- an inch away from the first says nothing new. */}- {/* The title is the one part of a scene PolStudio writes for the- user — taken from their first words — so it has to be theirs- to change. Blanking it falls back rather than saving a- nameless scene the schema would reject. */}- <h2><input- className="job-title__name"- value={selected.title}- aria-label={`Rename ${selected.title}`}- title="Rename this scene"- onChange={(event) => updateJob(selected.id, { title: event.target.value || "Untitled scene", updatedAt: new Date().toISOString() })}- /></h2>+ <div className="panel-head__scene-title">+ <div className="job-title">+ {selected.status !== "draft" && selectedIndicator && <span className={`status-icon status-icon--${selectedIndicator}`}>{statusIcon(selectedIndicator)}</span>}+ <div>+ {/* The badge is on the scene's own line on the board, where the+ eye compares one scene against the next. A second copy of it+ an inch away from the first says nothing new. */}+ {/* The title is the one part of a scene PolStudio writes for the+ user — taken from their first words — so it has to be theirs+ to change. Blanking it falls back rather than saving a+ nameless scene the schema would reject. */}+ <h2><input+ className="job-title__name"+ value={selected.title}+ aria-label={`Rename ${selected.title}`}+ title="Rename this scene"+ onChange={(event) => updateJob(selected.id, { title: event.target.value || "Untitled scene", updatedAt: new Date().toISOString() })}+ /></h2>+ </div></div>+ <button+ type="button"+ className="inspector-remove-button"+ aria-label={`Remove scene ${selected.title}`}+ title="Remove this scene"+ onClick={() => setRemovalTarget({ kind: "scene", job: selected })}+ ><Trash2 size={16} aria-hidden="true" /></button></div></header>@@ -568,6 +672,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCokey={selected.id}job={selected}shots={selectedShots}+ defaultSteps={defaultGenerationSteps}disabled={false}references={config.references}importAvailable={isTauri()}@@ -655,3 +760,110 @@ const runtimeHeadline = (runtime: VidfabStatus | null) => {case "incompatible": return "Video engine doesn’t match";}};++function GeneratorTemplateCombobox({ templates, selected, onChange }: {+ templates: GeneratorTemplate[];+ selected: GeneratorTemplate;+ onChange: (id: string) => void;+}) {+ const [open, setOpen] = useState(false);+ const [scrollDistance, setScrollDistance] = useState(0);+ const rootRef = useRef<HTMLDivElement>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const valueRef = useRef<HTMLSpanElement>(null);+ const optionRefs = useRef<Array<HTMLButtonElement | null>>([]);++ useEffect(() => {+ const measure = () => {+ const value = valueRef.current;+ setScrollDistance(value ? Math.max(0, value.scrollWidth - value.clientWidth) : 0);+ };+ measure();+ window.addEventListener("resize", measure);+ return () => window.removeEventListener("resize", measure);+ }, [selected.id, selected.name]);++ useEffect(() => {+ if (!open) return;+ const close = (event: PointerEvent) => {+ if (!rootRef.current?.contains(event.target as Node)) setOpen(false);+ };+ document.addEventListener("pointerdown", close);+ optionRefs.current[templates.findIndex((template) => template.id === selected.id)]?.focus();+ return () => document.removeEventListener("pointerdown", close);+ }, [open, selected.id, templates]);++ const closeAndFocus = () => {+ setOpen(false);+ triggerRef.current?.focus();+ };++ const pick = (id: string) => {+ onChange(id);+ closeAndFocus();+ };++ const moveOptionFocus = (index: number, direction: number) => {+ const next = (index + direction + templates.length) % templates.length;+ optionRefs.current[next]?.focus();+ };++ return <div className={`generator-runtime__select${open ? " generator-runtime__select--open" : ""}`} ref={rootRef}>+ <button+ ref={triggerRef}+ type="button"+ className="generator-runtime__trigger"+ role="combobox"+ aria-label={`Video generator template: ${selected.name}`}+ aria-expanded={open}+ aria-haspopup="listbox"+ aria-controls="generator-template-options"+ onClick={() => setOpen((value) => !value)}+ onKeyDown={(event) => {+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ setOpen(true);+ } else if (event.key === "Escape" && open) {+ event.preventDefault();+ setOpen(false);+ }+ }}+ >+ <span+ ref={valueRef}+ className={`generator-runtime__value${scrollDistance > 0 ? " generator-runtime__value--overflow" : ""}`}+ style={{ "--template-scroll-distance": `-${scrollDistance}px` } as React.CSSProperties}+ title={selected.name}+ ><span>{selected.name}</span></span>+ <ChevronDown size={15} aria-hidden="true" />+ </button>+ {open && <div className="generator-runtime__options" id="generator-template-options" role="listbox" aria-label="Generator templates">+ {templates.map((template, index) => <button+ ref={(element) => { optionRefs.current[index] = element; }}+ type="button"+ role="option"+ aria-selected={template.id === selected.id}+ title={template.name}+ key={template.id}+ onClick={() => pick(template.id)}+ onKeyDown={(event) => {+ if (event.key === "ArrowDown") {+ event.preventDefault();+ moveOptionFocus(index, 1);+ } else if (event.key === "ArrowUp") {+ event.preventDefault();+ moveOptionFocus(index, -1);+ } else if (event.key === "Home" || event.key === "End") {+ event.preventDefault();+ optionRefs.current[event.key === "Home" ? 0 : templates.length - 1]?.focus();+ } else if (event.key === "Escape") {+ event.preventDefault();+ closeAndFocus();+ } else if (event.key === "Tab") {+ setOpen(false);+ }+ }}+ ><span>{template.name}</span>{template.id === selected.id && <i aria-hidden="true" />}</button>)}+ </div>}+ </div>;+}diff --git a/src/components/workspace/SceneBoard.tsx b/src/components/workspace/SceneBoard.tsxindex 7819174..262e939 100644--- a/src/components/workspace/SceneBoard.tsx+++ b/src/components/workspace/SceneBoard.tsx@@ -1,4 +1,4 @@-import { GripVertical, Plus, SlidersHorizontal, Square, Trash2, WandSparkles } from "lucide-react";+import { GripVertical, Plus, Square, WandSparkles } from "lucide-react";import {SCENE_MAX_SECONDS,SCENE_MIN_SECONDS,@@ -50,9 +50,9 @@ export function SceneBoard({references,selection,onSelect,+ onAddScene,onAddShot,onDuration,- onRemoveScene,onGenerate,generationBlocker,changedJobIds,@@ -66,9 +66,9 @@ export function SceneBoard({references: ProjectReference[];selection: GeneratorSelection;onSelect: (selection: GeneratorSelection) => void;+ onAddScene: () => void;onAddShot: (job: GenerationJob) => void;onDuration: (job: GenerationJob, value: number) => void;- onRemoveScene: (job: GenerationJob) => void;onGenerate: (job: GenerationJob) => void;generationBlocker: (job: GenerationJob) => string | null;changedJobIds: ReadonlySet<string>;@@ -107,7 +107,14 @@ export function SceneBoard({}}onDrop={dropScene}>- <header className="scene-rule">+ <header+ className="scene-rule"+ onClick={(event) => {+ const target = event.target;+ if (target instanceof Element && target.closest("button, input, label, [role='button']")) return;+ onSelect({ jobId: job.id, shotId: null });+ }}+ ><spanclassName="scene-rule__drag"role="button"@@ -130,13 +137,19 @@ export function SceneBoard({}}><GripVertical size={17} aria-hidden="true" /></span>- <div className="scene-rule__summary">+ <button+ type="button"+ className="scene-rule__summary"+ aria-label={`Select scene ${job.title}`}+ aria-pressed={sceneOpen}+ onClick={() => onSelect({ jobId: job.id, shotId: null })}+ >{job.status !== "draft" && <span className={`scene-rule__status scene-rule__status--${indicator}`}>{statusIcon(indicator, 15)}</span>}<span className="scene-rule__text"><b>{job.title}</b></span>{job.status !== "draft" && indicator !== "generating" && <span className="scene-rule__badge">{STATUS_BADGE[indicator]}</span>}- </div>+ </button><label className="scene-rule__length"><span>Length</span>@@ -152,22 +165,6 @@ export function SceneBoard({<b>{seconds(duration)}</b></label>- <button- type="button"- className="secondary-button scene-rule__settings-button"- aria-pressed={sceneOpen}- aria-label={`Settings for ${job.title}`}- onClick={() => onSelect({ jobId: job.id, shotId: null })}- ><SlidersHorizontal size={15} aria-hidden="true" /></button>-- <button- type="button"- className="scene-rule__remove"- aria-label={`Remove scene ${job.title}`}- title={`Remove ${job.title}`}- onClick={() => onRemoveScene(job)}- ><Trash2 size={16} aria-hidden="true" /></button>-<buttontype="button"className={`${cancellable ? "danger-button" : "fill-button"} scene-rule__generate`}@@ -243,6 +240,15 @@ export function SceneBoard({</ol></section>;})}+ <button+ type="button"+ className="shot-card shot-card--add scene-card--add"+ onClick={onAddScene}+ title="Add an empty scene — you write the shots"+ >+ <Plus size={18} aria-hidden="true" />+ <span>Add a scene</span>+ </button></div>;}diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxindex 10c1ca2..d4dcb12 100644--- a/src/components/workspace/SceneEditor.tsx+++ b/src/components/workspace/SceneEditor.tsx@@ -266,10 +266,11 @@ export function ShotInspector({ job, shots, shot, index, endsAt, duration, refer/** Scene-wide render controls, the look the description opens with (base guide* §4.1), and the two sound fields defined per prompt (§4.6, §4.7). Length* lives in the scene header where it stays visible. */-export function SceneInspector({ job, shots, references, disabled, importAvailable, importError, onAddStartFrame, onChange, onShots }: {+export function SceneInspector({ job, shots, references, defaultSteps, disabled, importAvailable, importError, onAddStartFrame, onChange, onShots }: {job: GenerationJob;shots: SceneShot[];references: ProjectReference[];+ defaultSteps: number;disabled: boolean;importAvailable: boolean;importError: string | null;@@ -362,7 +363,7 @@ export function SceneInspector({ job, shots, references, disabled, importAvailabminimum={2}maximum={MAX_GENERATION_STEPS}step={1}- value={sceneGenerationSteps(job)}+ value={sceneGenerationSteps(job, defaultSteps)}integerdisabled={disabled}aria-label="Generation step count"diff --git a/src/components/workspace/ShotThumbnail.test.tsx b/src/components/workspace/ShotThumbnail.test.tsxindex bb029a7..0d7e705 100644--- a/src/components/workspace/ShotThumbnail.test.tsx+++ b/src/components/workspace/ShotThumbnail.test.tsx@@ -188,7 +188,7 @@ describe("a shot's picture", () => {const rendering = screen.getByText("Rendering 42%");expect(rendering.tagName).toBe("EM");expect(rendering.nextElementSibling?.classList.contains("shot-thumb__eta")).toBe(true);- expect(rendering.nextElementSibling?.textContent).toMatch(/^About 1m 30s left$/);+ expect(rendering.nextElementSibling?.textContent).toBe("1m 30s left");});it("says a finished scene could not be previewed rather than showing nothing", async () => {diff --git a/src/components/workspace/ShotThumbnail.tsx b/src/components/workspace/ShotThumbnail.tsxindex bbae5d0..9b57039 100644--- a/src/components/workspace/ShotThumbnail.tsx+++ b/src/components/workspace/ShotThumbnail.tsx@@ -236,14 +236,26 @@ function placeholder(job: GenerationJob, failed: boolean, cancelling: boolean):}}+/** Drops every in-memory still derived from one generated file. Regeneration+ * overwrites that file in place, so keeping its old posters would make a fresh+ * render look unchanged until the app restarted. */+export function forgetShotPosters(folderPath: string, relativePath: string): void {+ const file = fileKey(folderPath, relativePath);+ for (const key of POSTERS.keys()) {+ if (key.startsWith(`${file}@`)) POSTERS.delete(key);+ }+ UNREADABLE.delete(file);+ ABSENT.delete(file);+}+export function formatEstimatedTimeLeft(milliseconds: number): string {const totalSeconds = Math.max(1, Math.ceil(milliseconds / 1_000));- if (totalSeconds < 60) return `About ${totalSeconds}s left`;+ if (totalSeconds < 60) return `${totalSeconds}s left`;const hours = Math.floor(totalSeconds / 3_600);const minutes = Math.floor((totalSeconds % 3_600) / 60);const seconds = totalSeconds % 60;- if (hours > 0) return `About ${hours}h ${minutes}m left`;- return `About ${minutes}m ${seconds}s left`;+ if (hours > 0) return `${hours}h ${minutes}m left`;+ return `${minutes}m ${seconds}s left`;}export function ShotThumbnail({ folderPath, job, seconds, endSeconds = sceneDurationSeconds(job), shotNumber, estimatedCompletionAt = null, cancelling = false, onPlay }: {@@ -255,7 +267,7 @@ export function ShotThumbnail({ folderPath, job, seconds, endSeconds = sceneDura/** The next cut (or scene end). Playback never crosses this point. */endSeconds?: number;shotNumber: number;- /** Live rendering estimate derived from observed progress; never persisted. */+ /** Live rendering estimate derived from vidfab timing; never persisted. */estimatedCompletionAt?: number | null;/** Cancel was requested but the engine has not reported its terminal state. */cancelling?: boolean;diff --git a/src/components/workspace/useGenerationEvents.test.tsx b/src/components/workspace/useGenerationEvents.test.tsxindex b9fe636..d3d3f1a 100644--- a/src/components/workspace/useGenerationEvents.test.tsx+++ b/src/components/workspace/useGenerationEvents.test.tsx@@ -17,6 +17,7 @@ const handlers = new Map<string, (event: { payload: unknown }) => void>();beforeEach(() => {handlers.clear();+ localStorage.clear();scope.__TAURI_INTERNALS__ = {};// Cleared, not just re-implemented: one test asserts it was never called.vi.mocked(listen).mockReset();@@ -51,6 +52,21 @@ const emit = async (name: string, payload: unknown) => {});};+const timingProgress = (jobId: string, updates: Record<string, unknown> = {}) => ({+ jobId,+ stage: "denoising",+ step: 0,+ totalSteps: 4,+ plannedSteps: 4,+ elapsedSeconds: 20,+ frames: 360,+ canvasWidth: 416,+ canvasHeight: 416,+ referenceCount: 0,+ timingProfile: "vidfab=1.4.0|platform=CUDA 13|transformer=test.safetensors",+ ...updates,+});+describe("what the app does with the engine's events", () => {it("saves the frames the moment the engine says they are ready, and records the file", async () => {vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 4_200_000, note: null });@@ -154,19 +170,19 @@ describe("what the app does with the engine's events", () => {expect(job().progress).toBeGreaterThan(0.7);});- it("estimates render completion from observed progress and clears it when rendering ends", async () => {+ it("estimates render completion from vidfab elapsed time and completed steps", async () => {const onEstimate = vi.fn();const now = vi.spyOn(Date, "now").mockReturnValue(1_000);const { jobId } = harness(undefined, onEstimate);- await emit("vidfab-progress", { jobId, stage: "denoising", step: 10, totalSteps: 100 });+ await emit("vidfab-progress", timingProgress(jobId));expect(onEstimate).toHaveBeenLastCalledWith(jobId, null);now.mockReturnValue(11_000);- await emit("vidfab-progress", { jobId, stage: "denoising", step: 20, totalSteps: 100 });+ await emit("vidfab-progress", timingProgress(jobId, { step: 1, elapsedSeconds: 30 }));const completionAt = onEstimate.mock.lastCall?.[1];- expect(completionAt).toBeTypeOf("number");- expect(completionAt).toBeGreaterThan(11_000);+ // Ten measured seconds per step and two steps remain.+ expect(completionAt).toBe(31_000);vi.mocked(saveGeneratedScene).mockResolvedValue({ relativePath: "media/generated/job-01.mp4", bytes: 1, note: null });await emit("vidfab-job", { jobId, state: "framesReady", detail: "" });diff --git a/src/components/workspace/useGenerationEvents.ts b/src/components/workspace/useGenerationEvents.tsindex 3bd23c9..10a0509 100644--- a/src/components/workspace/useGenerationEvents.ts+++ b/src/components/workspace/useGenerationEvents.ts@@ -1,5 +1,7 @@import { listen } from "@tauri-apps/api/event";import { useEffect, useRef } from "react";+import { describeDiagnosticError, errorContext, writeDiagnostic } from "../../lib/diagnostics";+import { GenerationTimingEstimator, type CompletedGenerationTiming, type GenerationTimingProgress } from "../../lib/generationTiming";import { saveGeneratedScene } from "../../lib/generatedVideo";import { isTauri } from "../../lib/persistence";import { generationAssetId, type GenerationJob, type ProjectConfig } from "../../lib/project";@@ -24,14 +26,10 @@ interface JobEvent {jobId: string;state: "queued" | "framesReady" | "failed" | "cancelled" | string;detail: string;+ output?: CompletedGenerationTiming | null;}-interface ProgressEvent {- jobId: string;- stage: string;- step: number;- totalSteps: number;-}+type ProgressEvent = GenerationTimingProgress;/** Rendering is most of the wait, so it owns most of the bar; encoding is the* last slice, and it gets its own so a finished render does not sit at 92%@@ -39,14 +37,6 @@ interface ProgressEvent {const RENDER_CEILING = 0.9;const ENCODE_FLOOR = 0.9;const RENDER_PROGRESS_END = RENDER_CEILING - 0.02;-const MAX_ESTIMATE_MS = 24 * 60 * 60 * 1_000;--interface ProgressTiming {- at: number;- progress: number;- /** Overall render progress gained per millisecond. */- rate: number | null;-}export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstimate }: {folderPath: string;@@ -58,9 +48,10 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstim* exact boundary to persist the finished generation without waiting for the* user to click Save. */onCompleted?: (jobId: string) => void;- /** A transient prediction of when rendering (not file encoding) will finish.- * It is deliberately kept out of ProjectConfig: an estimate is live UI- * telemetry, not project data worth saving. */+ /** A transient prediction of when rendering (not file encoding) will finish,+ * based on vidfab's elapsed time and completed steps. It is deliberately+ * kept out of ProjectConfig: an estimate is live UI telemetry, not project+ * data worth saving. */onEstimate?: (jobId: string, completionAt: number | null) => void;}) {/* Held in refs so the subscription is made ONCE. It has to be: re-subscribing@@ -77,7 +68,8 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstim/** Scenes already being encoded, so a repeated event — or a remount in* StrictMode — cannot start a second encode of the same frames. */const saving = useRef(new Set<string>());- const progressTimings = useRef(new Map<string, ProgressTiming>());+ const timingEstimator = useRef<GenerationTimingEstimator | null>(null);+ if (timingEstimator.current === null) timingEstimator.current = new GenerationTimingEstimator();useEffect(() => {if (!isTauri()) return;@@ -106,36 +98,9 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstim}));};const clearEstimate = (jobId: string) => {- progressTimings.current.delete(jobId);+ timingEstimator.current?.clear(jobId);estimate.current?.(jobId, null);};- const updateEstimate = (jobId: string, progress: number) => {- const now = Date.now();- const previous = progressTimings.current.get(jobId);- if (!previous) {- progressTimings.current.set(jobId, { at: now, progress, rate: null });- // Also clears an estimate left by an earlier run of the same scene.- estimate.current?.(jobId, null);- return;- }-- const nextProgress = Math.max(previous.progress, progress);- const elapsed = now - previous.at;- if (nextProgress <= previous.progress || elapsed < 250) return;-- const measuredRate = (nextProgress - previous.progress) / elapsed;- const rate = previous.rate === null- ? measuredRate- : previous.rate * 0.65 + measuredRate * 0.35;- progressTimings.current.set(jobId, { at: now, progress: nextProgress, rate });-- const remainingMs = (RENDER_PROGRESS_END - nextProgress) / rate;- if (!Number.isFinite(remainingMs) || remainingMs <= 0 || remainingMs > MAX_ESTIMATE_MS) {- estimate.current?.(jobId, null);- return;- }- estimate.current?.(jobId, now + remainingMs);- };/** Encode the frames the engine just finished, and write the file.*@@ -147,6 +112,7 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstimconst save = async (jobId: string) => {if (saving.current.has(jobId)) return;saving.current.add(jobId);+ writeDiagnostic("info", "generation", "encoding.started", "Encoding rendered frames into a project video.", { jobId });updateJob(jobId, { status: "ready", stage: "encoding", progress: ENCODE_FLOOR, error: null });try {const saved = await saveGeneratedScene({@@ -178,6 +144,7 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstimrelativePath: saved.relativePath,sourcePath: null,mimeType: "video/mp4",+ hasAudio: saved.hasAudio ?? asset.hasAudio ?? null,} : asset),timeline: {tracks: current.timeline.tracks.map((track) => ({@@ -186,15 +153,20 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstim})),},}));+ writeDiagnostic(saved.note ? "warn" : "info", "generation", "encoding.completed", saved.note ?? "Rendered scene was encoded and written.", {+ jobId, bytes: saved.bytes, relativePath: saved.relativePath, hasAudio: saved.hasAudio ?? null,+ });completed.current?.(jobId);} catch (reason) {/* The render happened and the file did not. Failed is the honest state:there is nothing to insert into the timeline, and the only way to getthis scene is to run it again. */+ const detail = describeDiagnosticError(reason);+ writeDiagnostic("error", "generation", "encoding.failed", detail, { jobId, ...errorContext(reason) });updateJob(jobId, {status: "failed",stage: "failed",- error: `The scene rendered but could not be saved as a video file. ${reason instanceof Error ? reason.message : String(reason)}`,+ error: `The scene rendered but could not be saved as a video file. ${detail}`,});} finally {saving.current.delete(jobId);@@ -207,7 +179,7 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstimconst progress = payload.totalSteps > 0? Math.min(RENDER_PROGRESS_END, 0.12 + (Math.max(0, payload.step) / payload.totalSteps) * (RENDER_CEILING - 0.14)): payload.stage === "delivering" ? RENDER_PROGRESS_END : 0.08;- updateEstimate(payload.jobId, progress);+ estimate.current?.(payload.jobId, timingEstimator.current?.update(payload) ?? null);updateProgress(payload.jobId,progress,@@ -216,7 +188,23 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstim}),listen<JobEvent>("vidfab-job", ({ payload }) => {if (disposed) return;+ writeDiagnostic(payload.state === "failed" ? "error" : payload.state === "cancelled" ? "warn" : "info", "generation", "native_event.received", payload.detail || `Generation state changed to ${payload.state}.`, {+ jobId: payload.jobId, state: payload.state,+ });if (payload.state === "framesReady") {+ if (payload.output) {+ timingEstimator.current?.record(payload.output);+ writeDiagnostic("info", "generation", "timing.calibrated", "Generation timing calibration was updated.", {+ jobId: payload.jobId,+ secondsConditioning: payload.output.secondsConditioning,+ secondsDenoise: payload.output.secondsDenoise,+ secondsVideoDecode: payload.output.secondsVideoDecode,+ secondsAudioDecode: payload.output.secondsAudioDecode,+ secondsTotal: payload.output.secondsTotal,+ stepsComputed: payload.output.stepsComputed,+ stepsSkipped: payload.output.stepsSkipped,+ });+ }clearEstimate(payload.jobId);void save(payload.jobId);return;@@ -229,6 +217,9 @@ export function useGenerationEvents({ folderPath, onChange, onCompleted, onEstim: { status: "queued", stage: "queued" });}),]);+ void subscriptions.catch((reason) => {+ writeDiagnostic("error", "generation", "event_subscription.failed", describeDiagnosticError(reason), errorContext(reason));+ });return () => {disposed = true;void subscriptions.then((unlisten) => unlisten.forEach((stop) => stop()));diff --git a/src/lib/generatedVideo.test.ts b/src/lib/generatedVideo.test.tsindex 8230e32..46c78ea 100644--- a/src/lib/generatedVideo.test.ts+++ b/src/lib/generatedVideo.test.ts@@ -42,8 +42,10 @@ beforeEach(() => {delete scope.VideoFrame;delete scope.AudioEncoder;delete scope.AudioData;+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);});afterEach(() => {+ vi.restoreAllMocks();delete scope.__TAURI_INTERNALS__;delete scope.VideoEncoder;delete scope.VideoFrame;@@ -176,6 +178,7 @@ describe("generated audio at the Rust/webview boundary", () => {await expect(saveGeneratedScene({ folderPath: "C:\\Project", jobId: "job-01" })).resolves.toMatchObject({relativePath: "media/generated/job-01.mp4",note: expect.stringMatching(/without sound/),+ hasAudio: false,});expect(invoked).not.toHaveBeenCalledWith("generated_audio", expect.anything());expect(muxed.configs[0]).not.toHaveProperty("audio");@@ -231,6 +234,7 @@ describe("generated audio at the Rust/webview boundary", () => {await expect(saveGeneratedScene({ folderPath: "C:\\Project", jobId: "job-01" })).resolves.toMatchObject({relativePath: "media/generated/job-01.mp4",note: null,+ hasAudio: true,});expect(muxed.videoChunks).toBe(1);expect(muxed.audioChunks).toBeGreaterThan(0);diff --git a/src/lib/generatedVideo.ts b/src/lib/generatedVideo.tsindex b7581c8..652913f 100644--- a/src/lib/generatedVideo.ts+++ b/src/lib/generatedVideo.ts@@ -1,6 +1,8 @@import { invoke } from "@tauri-apps/api/core";+import { writeDiagnostic } from "./diagnostics";import { bitrateFor, outputCodec } from "./export";import { isTauri } from "./persistence";+import { TIMELINE_THUMBNAIL_INTERVAL_MS, writeTimelineThumbnail } from "./timelineThumbnails";/* Turning a finished render into a file in the project folder.*@@ -41,6 +43,8 @@ export interface SavedGeneration {/** Null when everything the render produced is in the file. A sentence when* something was left out, so a silent video is never silently silent. */note: string | null;+ /** Whether the saved MP4 actually contains an audio stream. */+ hasAudio?: boolean;}/** How often a keyframe is written: every two seconds, so the file can be@@ -55,10 +59,47 @@ const AUDIO_BITRATE = 192_000;/** Generated footage is a MASTER, not a delivery file: it is what every later* export is cut from, so it is encoded at the highest preset the app has. */const GENERATED_QUALITY = "high" as const;+const TIMELINE_THUMBNAIL_WIDTH = 192;+const TIMELINE_THUMBNAIL_JPEG_QUALITY = 0.82;const describe = (reason: unknown) => (reason instanceof Error ? reason.message : String(reason));const tick = () => new Promise((resolve) => setTimeout(resolve, 0));+/** Downsamples one RGBA render frame directly into a small JPEG. Sampling the+ * pixels avoids allocating a second full-resolution canvas merely to shrink+ * it, and this runs only at the timeline cache interval. */+async function timelineThumbnailJpeg(pixels: Uint8Array, width: number, height: number): Promise<Uint8Array | null> {+ try {+ const outputWidth = Math.min(width, TIMELINE_THUMBNAIL_WIDTH);+ const outputHeight = Math.max(1, Math.round(height * outputWidth / width));+ const canvas = document.createElement("canvas");+ canvas.width = outputWidth;+ canvas.height = outputHeight;+ const context = canvas.getContext("2d");+ if (!context) return null;+ const image = context.createImageData(outputWidth, outputHeight);+ for (let y = 0; y < outputHeight; y += 1) {+ const sourceY = Math.min(height - 1, Math.floor(y * height / outputHeight));+ for (let x = 0; x < outputWidth; x += 1) {+ const sourceX = Math.min(width - 1, Math.floor(x * width / outputWidth));+ const source = (sourceY * width + sourceX) * 4;+ const target = (y * outputWidth + x) * 4;+ image.data[target] = pixels[source];+ image.data[target + 1] = pixels[source + 1];+ image.data[target + 2] = pixels[source + 2];+ image.data[target + 3] = pixels[source + 3];+ }+ }+ context.putImageData(image, 0, 0);+ const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", TIMELINE_THUMBNAIL_JPEG_QUALITY));+ return blob ? new Uint8Array(await blob.arrayBuffer()) : null;+ } catch {+ // A missing canvas encoder must not cost the user the rendered video. The+ // timeline can build this disposable cache later from the saved MP4.+ return null;+ }+}+/** What Rust still holds for this scene, or null if nothing does. */export async function renderedSummary(jobId: string): Promise<RenderedSummary | null> {if (!isTauri()) return null;@@ -300,11 +341,18 @@ export async function saveGeneratedScene(options: {if (summary.frameCount <= 0 || summary.width <= 0 || summary.height <= 0) {throw new Error("The render came back with no pictures in it.");}+ writeDiagnostic("info", "generated-video", "render.loaded", "Rendered buffers are available for encoding.", {+ jobId, width: summary.width, height: summary.height, frames: summary.frameCount, fps: summary.fps,+ audioChannels: summary.audioChannels, audioSampleRate: summary.audioSampleRate, audioSamples: summary.audioSamples,+ });try {const fps = summary.fps > 0 ? summary.fps : 24;const bitrate = bitrateFor(summary.width, summary.height, fps, GENERATED_QUALITY);const { codec } = await pickCodec(summary.width, summary.height, fps, bitrate);+ writeDiagnostic("info", "generated-video", "video_encoder.selected", "WebCodecs accepted a video encoder configuration.", {+ jobId, codec, bitrate, fps, width: summary.width, height: summary.height,+ });const sound = await audioConfig(summary);const audioChunks: Array<{ chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }> = [];let note: string | null = null;@@ -319,6 +367,7 @@ export async function saveGeneratedScene(options: {note = "Saved without sound: this computer's encoder would not take the render's audio.";}}+ if (note) writeDiagnostic("warn", "generated-video", "audio.omitted", note, { jobId });const withAudio = audioChunks.length > 0;const { ArrayBufferTarget, Muxer } = await import("mp4-muxer");@@ -347,11 +396,17 @@ export async function saveGeneratedScene(options: {away from the clock. */const timestampUs = (index: number) => Math.round((index * 1_000_000) / fps);const keyframeEvery = Math.max(1, Math.round(fps * KEYFRAME_SECONDS));+ const thumbnailEvery = Math.max(1, Math.round(fps * TIMELINE_THUMBNAIL_INTERVAL_MS / 1_000));+ const timelineThumbnails: Array<{ timeMs: number; bytes: Uint8Array }> = [];try {for (let index = 0; index < summary.frameCount; index += 1) {if (failure.reason) throw failure.reason;const pixels = await renderedFrame(jobId, index);+ if (index % thumbnailEvery === 0) {+ const thumbnail = await timelineThumbnailJpeg(pixels, summary.width, summary.height);+ if (thumbnail) timelineThumbnails.push({ timeMs: Math.round(index * 1_000 / fps), bytes: thumbnail });+ }const frame = makeFrame(pixels, timestampUs(index), timestampUs(index + 1) - timestampUs(index));encoder.encode(frame, { keyFrame: index % keyframeEvery === 0 });frame.close();@@ -371,7 +426,9 @@ export async function saveGeneratedScene(options: {muxer.finalize();const written = await writeGeneratedVideo(folderPath, jobId, new Uint8Array(target.buffer));- return { relativePath: written.relativePath, bytes: written.bytes, note };+ await Promise.allSettled(timelineThumbnails.map((thumbnail) =>+ writeTimelineThumbnail(folderPath, jobId, thumbnail.timeMs, thumbnail.bytes)));+ return { relativePath: written.relativePath, bytes: written.bytes, note, hasAudio: withAudio };} finally {// Whatever happened, the render stops occupying memory here.await releaseRendered(jobId);diff --git a/src/lib/generationTiming.test.ts b/src/lib/generationTiming.test.tsnew file mode 100644index 0000000..56e4ea2--- /dev/null+++ b/src/lib/generationTiming.test.ts@@ -0,0 +1,82 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it } from "vitest";+import { alignedGenerationFrames, GenerationTimingEstimator, type CompletedGenerationTiming, type GenerationTimingProgress } from "./generationTiming";++const progress = (updates: Partial<GenerationTimingProgress> = {}): GenerationTimingProgress => ({+ jobId: "scene-1",+ stage: "denoising",+ step: 0,+ totalSteps: 4,+ plannedSteps: 4,+ elapsedSeconds: 20,+ frames: 360,+ canvasWidth: 416,+ canvasHeight: 416,+ referenceCount: 0,+ timingProfile: "vidfab=1.4.0|platform=CUDA 13|transformer=model.safetensors",+ ...updates,+});++const completed = (updates: Partial<CompletedGenerationTiming> = {}): CompletedGenerationTiming => ({+ frames: alignedGenerationFrames(360),+ width: 416,+ height: 416,+ referenceCount: 0,+ timingProfile: "vidfab=1.4.0|platform=CUDA 13|transformer=model.safetensors",+ secondsConditioning: 5,+ secondsDenoise: 40,+ secondsVideoDecode: 8,+ secondsAudioDecode: 2,+ secondsTotal: 60,+ stepsComputed: 4,+ stepsSkipped: 0,+ ...updates,+});++describe("vidfab generation timing", () => {+ beforeEach(() => localStorage.clear());++ it("matches vidfab frame alignment", () => {+ expect(alignedGenerationFrames(5)).toBe(5);+ expect(alignedGenerationFrames(360)).toBe(362);+ });++ it("waits for two live denoising samples, then uses actual seconds per step", () => {+ const estimator = new GenerationTimingEstimator(null);+ expect(estimator.update(progress(), 1_000)).toBeNull();+ // One completed step in ten seconds, with two steps still to run.+ expect(estimator.update(progress({ step: 1, elapsedSeconds: 30 }), 2_000)).toBe(22_000);+ });++ it("uses successful stage timings for decode overhead on later matching runs", () => {+ const first = new GenerationTimingEstimator();+ first.record(completed(), 100);++ const next = new GenerationTimingEstimator();+ // Historical 10 s/step plus the calibrated 10 s decode tail.+ expect(next.update(progress({ step: 0, elapsedSeconds: 12 }), 1_000)).toBe(41_000);+ expect(next.update(progress({ stage: "videoDecode", step: -1, totalSteps: 0 }), 2_000)).toBe(12_000);+ });++ it("uses planned evaluations and calibrated fixed stages before denoising starts", () => {+ const first = new GenerationTimingEstimator();+ first.record(completed(), 100);+ const next = new GenerationTimingEstimator();++ // The matching run historically took 60 s. Two seconds have elapsed.+ expect(next.update(progress({+ stage: "transformerLoad",+ step: -1,+ totalSteps: 0,+ plannedSteps: 4,+ elapsedSeconds: 2,+ }), 1_000)).toBe(59_000);+ });++ it("does not reuse calibration across a different model profile", () => {+ const estimator = new GenerationTimingEstimator();+ estimator.record(completed(), 100);+ expect(estimator.update(progress({ timingProfile: "another-model" }), 1_000)).toBeNull();+ });+});diff --git a/src/lib/generationTiming.ts b/src/lib/generationTiming.tsnew file mode 100644index 0000000..e95818a--- /dev/null+++ b/src/lib/generationTiming.ts@@ -0,0 +1,205 @@+/**+ * Stage-aware generation timing.+ *+ * vidfab reports elapsed wall time and completed denoising steps while a run+ * is active, then returns the measured duration of each expensive stage. The+ * live samples give an honest seconds-per-step rate; successful runs supply a+ * small machine-local calibration for the work before and after denoising.+ * Nothing here is project data, so none of it belongs in polstudio.json.+ */++const STORAGE_KEY = "polstudio.generation-timing.v1";+const MAX_PROFILES = 32;+const MAX_REMAINING_SECONDS = 24 * 60 * 60;++export interface GenerationTimingProgress {+ jobId: string;+ stage: string;+ step: number;+ totalSteps: number;+ plannedSteps: number;+ elapsedSeconds: number;+ frames: number;+ canvasWidth: number;+ canvasHeight: number;+ referenceCount: number;+ timingProfile: string;+}++export interface CompletedGenerationTiming {+ frames: number;+ width: number;+ height: number;+ referenceCount: number;+ timingProfile: string;+ secondsConditioning: number;+ secondsDenoise: number;+ secondsVideoDecode: number;+ secondsAudioDecode: number;+ secondsTotal: number;+ stepsComputed: number;+ stepsSkipped: number;+}++interface TimingProfile {+ samples: number;+ updatedAt: number;+ secondsConditioning: number;+ secondsPerDenoiseStep: number;+ secondsVideoDecode: number;+ secondsAudioDecode: number;+ /** Loading, references, delivery, and other time not itemized by the ABI. */+ secondsOther: number;+}++interface JobTiming {+ key: string;+ previousDenoise: { completedSteps: number; elapsedSeconds: number } | null;+ secondsPerDenoiseStep: number | null;+}++type ProfileStore = Record<string, TimingProfile>;+type TimingStorage = Pick<Storage, "getItem" | "setItem">;++const finiteNonNegative = (value: number) => Number.isFinite(value) && value >= 0;++/** The frame alignment used by vidfab's resolved plan: 17*k + 5. */+export function alignedGenerationFrames(frames: number): number {+ return Math.ceil((Math.max(5, Math.round(frames)) - 5) / 17) * 17 + 5;+}++function profileKey(profile: string, width: number, height: number, frames: number, references: number): string {+ return [profile || "unknown", `${Math.round(width)}x${Math.round(height)}`, alignedGenerationFrames(frames), `refs=${Math.max(0, Math.round(references))}`].join("|");+}++function readProfiles(storage: TimingStorage | null): ProfileStore {+ if (!storage) return {};+ try {+ const parsed = JSON.parse(storage.getItem(STORAGE_KEY) ?? "{}") as unknown;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};+ return Object.fromEntries(Object.entries(parsed).filter(([, value]) => {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const candidate = value as Partial<TimingProfile>;+ return finiteNonNegative(candidate.samples ?? Number.NaN)+ && finiteNonNegative(candidate.updatedAt ?? Number.NaN)+ && finiteNonNegative(candidate.secondsConditioning ?? Number.NaN)+ && finiteNonNegative(candidate.secondsPerDenoiseStep ?? Number.NaN)+ && finiteNonNegative(candidate.secondsVideoDecode ?? Number.NaN)+ && finiteNonNegative(candidate.secondsAudioDecode ?? Number.NaN)+ && finiteNonNegative(candidate.secondsOther ?? Number.NaN);+ })) as ProfileStore;+ } catch {+ return {};+ }+}++function browserStorage(): TimingStorage | null {+ try {+ return typeof localStorage === "undefined" ? null : localStorage;+ } catch {+ return null;+ }+}++function blend(previous: number, sample: number, hasPrevious: boolean): number {+ return hasPrevious ? previous * 0.75 + sample * 0.25 : sample;+}++export class GenerationTimingEstimator {+ private readonly jobs = new Map<string, JobTiming>();+ private profiles: ProfileStore;++ constructor(private readonly storage: TimingStorage | null = browserStorage()) {+ this.profiles = readProfiles(storage);+ }++ /** Returns an absolute completion timestamp, or null until the estimate has+ * enough real data to be worth showing. */+ update(progress: GenerationTimingProgress, nowMs = Date.now()): number | null {+ if (!finiteNonNegative(progress.elapsedSeconds) || progress.totalSteps < 0 || progress.plannedSteps < 0) return null;+ const totalSteps = progress.totalSteps > 0 ? progress.totalSteps : progress.plannedSteps;+ const key = profileKey(+ progress.timingProfile,+ progress.canvasWidth,+ progress.canvasHeight,+ progress.frames,+ progress.referenceCount,+ );+ let state = this.jobs.get(progress.jobId);+ if (!state || state.key !== key) {+ state = { key, previousDenoise: null, secondsPerDenoiseStep: null };+ this.jobs.set(progress.jobId, state);+ }+ const profile = this.profiles[key];+ let remainingSeconds: number | null = null;++ if (progress.stage === "denoising" && totalSteps > 0 && progress.step >= 0) {+ const completedSteps = Math.min(totalSteps, progress.step + 1);+ const previous = state.previousDenoise;+ if (previous && completedSteps > previous.completedSteps && progress.elapsedSeconds > previous.elapsedSeconds) {+ const measured = (progress.elapsedSeconds - previous.elapsedSeconds)+ / (completedSteps - previous.completedSteps);+ if (measured > 0 && measured < MAX_REMAINING_SECONDS) {+ state.secondsPerDenoiseStep = state.secondsPerDenoiseStep === null+ ? measured+ : state.secondsPerDenoiseStep * 0.7 + measured * 0.3;+ }+ }+ state.previousDenoise = { completedSteps, elapsedSeconds: progress.elapsedSeconds };+ const secondsPerStep = state.secondsPerDenoiseStep ?? profile?.secondsPerDenoiseStep ?? null;+ if (secondsPerStep !== null) {+ const decodeTail = profile ? profile.secondsVideoDecode + profile.secondsAudioDecode : 0;+ remainingSeconds = secondsPerStep * (totalSteps - completedSteps) + decodeTail;+ }+ } else if (progress.stage === "videoDecode") {+ if (profile) remainingSeconds = profile.secondsVideoDecode + profile.secondsAudioDecode;+ } else if (progress.stage === "audioDecode") {+ if (profile) remainingSeconds = profile.secondsAudioDecode;+ } else if (!["delivering", "finished"].includes(progress.stage) && profile && totalSteps > 0) {+ const expectedTotal = profile.secondsConditioning+ + profile.secondsOther+ + profile.secondsPerDenoiseStep * totalSteps+ + profile.secondsVideoDecode+ + profile.secondsAudioDecode;+ remainingSeconds = expectedTotal - progress.elapsedSeconds;+ }++ if (remainingSeconds === null || !Number.isFinite(remainingSeconds)+ || remainingSeconds <= 0 || remainingSeconds > MAX_REMAINING_SECONDS) return null;+ return nowMs + remainingSeconds * 1_000;+ }++ /** Adds one successful run to the profile for this exact engine/model,+ * geometry, aligned frame count, and reference count. */+ record(sample: CompletedGenerationTiming, nowMs = Date.now()): void {+ if (![sample.secondsConditioning, sample.secondsDenoise, sample.secondsVideoDecode,+ sample.secondsAudioDecode, sample.secondsTotal].every(finiteNonNegative)+ || sample.stepsComputed <= 0 || sample.secondsTotal <= 0) return;+ const key = profileKey(sample.timingProfile, sample.width, sample.height, sample.frames, sample.referenceCount);+ const previous = this.profiles[key];+ const hasPrevious = Boolean(previous);+ const itemized = sample.secondsConditioning + sample.secondsDenoise+ + sample.secondsVideoDecode + sample.secondsAudioDecode;+ const next: TimingProfile = {+ samples: Math.min(1_000_000, (previous?.samples ?? 0) + 1),+ updatedAt: nowMs,+ secondsConditioning: blend(previous?.secondsConditioning ?? 0, sample.secondsConditioning, hasPrevious),+ secondsPerDenoiseStep: blend(previous?.secondsPerDenoiseStep ?? 0, sample.secondsDenoise / sample.stepsComputed, hasPrevious),+ secondsVideoDecode: blend(previous?.secondsVideoDecode ?? 0, sample.secondsVideoDecode, hasPrevious),+ secondsAudioDecode: blend(previous?.secondsAudioDecode ?? 0, sample.secondsAudioDecode, hasPrevious),+ secondsOther: blend(previous?.secondsOther ?? 0, Math.max(0, sample.secondsTotal - itemized), hasPrevious),+ };+ this.profiles[key] = next;+ const ordered = Object.entries(this.profiles).sort((left, right) => right[1].updatedAt - left[1].updatedAt);+ this.profiles = Object.fromEntries(ordered.slice(0, MAX_PROFILES));+ try {+ this.storage?.setItem(STORAGE_KEY, JSON.stringify(this.profiles));+ } catch {+ // Losing calibration only means the next launch starts with "Estimating".+ }+ }++ clear(jobId: string): void {+ this.jobs.delete(jobId);+ }+}diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.tsindex 387efc6..ae68541 100644--- a/src/lib/settings.test.ts+++ b/src/lib/settings.test.ts@@ -3,10 +3,42 @@import { beforeEach, describe, expect, it } from "vitest";import {agentEndpointProviderSettings,+ createGeneratorTemplate,+ loadDefaultGenerationSteps,loadAgentEndpointSettings,+ loadEngineSettings,+ loadGeneratorTemplateSettings,saveAgentEndpointSettings,+ saveGeneratorTemplateSettings,} from "./settings";+describe("generator templates", () => {+ beforeEach(() => localStorage.clear());++ it("migrates the former flat engine paths into the Default template", () => {+ localStorage.setItem("polstudio.engine-paths.v1", JSON.stringify({ transformer: "D:\\Models\\main.safetensors" }));+ const settings = loadGeneratorTemplateSettings();+ expect(settings.defaultTemplateId).toBe("default");+ expect(settings.templates).toHaveLength(1);+ expect(settings.templates[0]).toMatchObject({+ id: "default",+ name: "Default",+ defaultSteps: 20,+ paths: { transformer: "D:\\Models\\main.safetensors" },+ });+ });++ it("uses the selected default template for engine paths and step defaults", () => {+ const fast = createGeneratorTemplate("Fast draft");+ fast.defaultSteps = 8;+ fast.paths.transformer = "D:\\Models\\fast.safetensors";+ saveGeneratorTemplateSettings({ templates: [createGeneratorTemplate("Quality"), fast], defaultTemplateId: fast.id });++ expect(loadEngineSettings().transformer).toBe("D:\\Models\\fast.safetensors");+ expect(loadDefaultGenerationSteps()).toBe(8);+ });+});+describe("machine prompt LLM settings", () => {beforeEach(() => localStorage.clear());diff --git a/src/lib/settings.ts b/src/lib/settings.tsindex 4e221b2..afab8bf 100644--- a/src/lib/settings.ts+++ b/src/lib/settings.ts@@ -12,7 +12,7 @@* in src-tauri/src/vidfab.rs. Renaming one here without renaming it there* silently drops that path.*/-import type { ProjectConfig, ProviderSetting } from "./project";+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";@@ -54,34 +54,125 @@ export const EMPTY_ENGINE_SETTINGS: EngineSettings = {};const ENGINE_KEY = "polstudio.engine-paths.v1";+const GENERATOR_TEMPLATES_KEY = "polstudio.generator-templates.v1";-/** 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 {+export interface GeneratorTemplate {+ id: string;+ name: string;+ defaultSteps: number;+ paths: EngineSettings;+}++export interface GeneratorTemplateSettings {+ templates: GeneratorTemplate[];+ defaultTemplateId: string;+}++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"): GeneratorTemplate {+ return {+ id: `generator-template-${crypto.randomUUID()}`,+ name,+ defaultSteps: DEFAULT_GENERATION_STEPS,+ paths: copyPaths(EMPTY_ENGINE_SETTINGS),+ };+}++const initialTemplateSettings = (paths = EMPTY_ENGINE_SETTINGS): GeneratorTemplateSettings => ({+ templates: [{ id: "default", name: "Default", defaultSteps: DEFAULT_GENERATION_STEPS, paths: copyPaths(paths) }],+ defaultTemplateId: "default",+});++const normalizeTemplateSettings = (value: unknown): GeneratorTemplateSettings | null => {+ if (!value || typeof value !== "object") return null;+ const record = value as { templates?: unknown; defaultTemplateId?: 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 defaultSteps = typeof candidate.defaultSteps === "number"+ && Number.isInteger(candidate.defaultSteps)+ && candidate.defaultSteps >= 2+ && candidate.defaultSteps <= MAX_GENERATION_STEPS+ ? candidate.defaultSteps+ : DEFAULT_GENERATION_STEPS;+ return [{ id, name, defaultSteps, paths: pathsFrom(candidate.paths) }];+ });+ if (templates.length === 0) return null;+ const requestedDefault = typeof record.defaultTemplateId === "string" ? record.defaultTemplateId : "";+ return {+ templates,+ defaultTemplateId: templates.some((template) => template.id === requestedDefault) ? requestedDefault : templates[0].id,+ };+};++/** 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 raw = localStorage.getItem(ENGINE_KEY);- if (!raw) return { ...EMPTY_ENGINE_SETTINGS };- const parsed = JSON.parse(raw) as Partial<Record<EnginePathId, unknown>>;- const settings = { ...EMPTY_ENGINE_SETTINGS };- for (const field of ENGINE_PATH_FIELDS) {- const value = parsed?.[field.id];- if (typeof value === "string") settings[field.id] = value;+ const stored = localStorage.getItem(GENERATOR_TEMPLATES_KEY);+ if (stored) {+ const normalized = normalizeTemplateSettings(JSON.parse(stored));+ if (normalized) return normalized;}- return settings;+ const legacy = localStorage.getItem(ENGINE_KEY);+ return initialTemplateSettings(legacy ? pathsFrom(JSON.parse(legacy)) : EMPTY_ENGINE_SETTINGS);} catch {- return { ...EMPTY_ENGINE_SETTINGS };+ return initialTemplateSettings();}}-export function saveEngineSettings(settings: EngineSettings): void {+export function saveGeneratorTemplateSettings(settings: GeneratorTemplateSettings): void {+ const normalized = normalizeTemplateSettings(settings) ?? initialTemplateSettings();try {- localStorage.setItem(ENGINE_KEY, JSON.stringify(settings));+ localStorage.setItem(GENERATOR_TEMPLATES_KEY, JSON.stringify(normalized));} catch {- /* A full or disabled localStorage costs the user the saved paths, not the- session: the values they just typed are still in the fields. */+ /* The current React state remains usable for this session. */}}+export function defaultGeneratorTemplate(settings = loadGeneratorTemplateSettings()): GeneratorTemplate {+ return settings.templates.find((template) => template.id === settings.defaultTemplateId) ?? settings.templates[0];+}++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 `vidfab` 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 "". */diff --git a/src/lib/timelineThumbnails.test.ts b/src/lib/timelineThumbnails.test.tsnew file mode 100644index 0000000..3e144c6--- /dev/null+++ b/src/lib/timelineThumbnails.test.ts@@ -0,0 +1,38 @@+// @vitest-environment jsdom++import { invoke } from "@tauri-apps/api/core";+import { afterEach, describe, expect, it, vi } from "vitest";+import { purgeTimelineThumbnails, timelineThumbnailRelativePath, writeTimelineThumbnail } from "./timelineThumbnails";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));++const scope = globalThis as unknown as Record<string, unknown>;+afterEach(() => {+ delete scope.__TAURI_INTERNALS__;+ vi.clearAllMocks();+});++describe("timeline thumbnail persistence", () => {+ it("uses stable project-relative cache names", () => {+ expect(timelineThumbnailRelativePath("scene-12", 2_000)).toBe("thumbnails/timeline/scene-12/00002000.jpg");+ });++ it("writes raw JPEG bytes and purges only the named scene cache", async () => {+ scope.__TAURI_INTERNALS__ = {};+ const bytes = new Uint8Array([0xff, 0xd8, 0xff]);+ await writeTimelineThumbnail("C:\Project", "scene-12", 2_000, bytes);+ await purgeTimelineThumbnails("C:\Project", "scene-12");++ expect(vi.mocked(invoke)).toHaveBeenNthCalledWith(1, "write_timeline_thumbnail", bytes, {+ headers: {+ "x-thumbnail-folder": encodeURIComponent("C:\Project"),+ "x-thumbnail-job": "scene-12",+ "x-thumbnail-time": "2000",+ },+ });+ expect(vi.mocked(invoke)).toHaveBeenNthCalledWith(2, "purge_timeline_thumbnails", {+ folderPath: "C:\Project",+ jobId: "scene-12",+ });+ });+});diff --git a/src/lib/timelineThumbnails.ts b/src/lib/timelineThumbnails.tsnew file mode 100644index 0000000..5e2e5f7--- /dev/null+++ b/src/lib/timelineThumbnails.ts@@ -0,0 +1,32 @@+import { invoke } from "@tauri-apps/api/core";+import { isTauri } from "./persistence";++/** Timeline stills are anchored to source time, not clip time. Trimming or+ * splitting a clip can therefore reuse the same small cache without moving or+ * regenerating any files. */+export const TIMELINE_THUMBNAIL_INTERVAL_MS = 2_000;++export const timelineThumbnailRelativePath = (jobId: string, timeMs: number): string =>+ `thumbnails/timeline/${jobId}/${Math.max(0, Math.round(timeMs)).toString().padStart(8, "0")}.jpg`;++export async function writeTimelineThumbnail(folderPath: string, jobId: string, timeMs: number, bytes: Uint8Array): Promise<void> {+ if (!isTauri() || bytes.byteLength === 0) return;+ await invoke("write_timeline_thumbnail", bytes, {+ headers: {+ "x-thumbnail-folder": encodeURIComponent(folderPath),+ "x-thumbnail-job": encodeURIComponent(jobId),+ "x-thumbnail-time": String(Math.max(0, Math.round(timeMs))),+ },+ });+}++export async function writeTimelineThumbnailDataUrl(folderPath: string, jobId: string, timeMs: number, dataUrl: string): Promise<void> {+ if (!isTauri()) return;+ const bytes = new Uint8Array(await (await fetch(dataUrl)).arrayBuffer());+ await writeTimelineThumbnail(folderPath, jobId, timeMs, bytes);+}++export async function purgeTimelineThumbnails(folderPath: string, jobId: string): Promise<void> {+ if (!isTauri()) return;+ await invoke("purge_timeline_thumbnails", { folderPath, jobId });+}diff --git a/src/styles/generator.css b/src/styles/generator.cssindex 0b7c335..f61da48 100644--- a/src/styles/generator.css+++ b/src/styles/generator.css@@ -30,7 +30,7 @@align-items: center;gap: var(--space-2);min-height: var(--control-sm);- padding: 0 var(--space-3);+ padding: var(--space-1) var(--space-1) var(--space-1) var(--space-3);border: 1px solid var(--line);border-radius: var(--radius-pill);color: var(--text-muted);@@ -40,7 +40,7 @@line-height: var(--leading-snug);}-.generator-runtime i {+.generator-runtime > i {width: 8px;height: 8px;flex: 0 0 auto;@@ -48,6 +48,158 @@background: currentColor;}+.generator-runtime__label {+ color: var(--text-secondary);+ font-weight: var(--weight-medium);+ white-space: nowrap;+}++.generator-runtime__select {+ position: relative;+ width: 176px;+ flex: 0 0 176px;+}++.generator-runtime__select--open {+ z-index: 20;+}++.generator-runtime__trigger {+ width: 100%;+ min-width: 0;+ min-height: var(--control-sm);+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: 0 var(--space-3);+ overflow: hidden;+ border: 1px solid var(--success-line);+ border-radius: var(--radius-pill);+ outline: 0;+ color: var(--success);+ background: color-mix(in srgb, var(--success) 10%, var(--panel-2));+ font-size: var(--text-sm);+ font-weight: var(--weight-semibold);+ cursor: pointer;+ transition: border-color 0.15s ease, background-color 0.15s ease, box-shadow 0.15s ease;+}++.generator-runtime__trigger:hover,+.generator-runtime__select--open .generator-runtime__trigger {+ border-color: var(--success);+ background: color-mix(in srgb, var(--success) 16%, var(--panel-2));+}++.generator-runtime__trigger:focus-visible {+ border-color: var(--success);+ box-shadow: 0 0 0 2px var(--success-line);+}++.generator-runtime__trigger > svg {+ flex: 0 0 auto;+ transition: transform 0.15s ease;+}++.generator-runtime__select--open .generator-runtime__trigger > svg {+ transform: rotate(180deg);+}++.generator-runtime__value {+ --template-scroll-distance: 0px;+ min-width: 0;+ flex: 1 1 auto;+ overflow: hidden;+ color: inherit;+ text-align: left;+ white-space: nowrap;+}++.generator-runtime__value > span {+ display: inline-block;+ min-width: max-content;+}++.generator-runtime__value--overflow > span {+ animation: generator-template-scroll 4s ease-in-out 0.6s infinite alternate;+}++@keyframes generator-template-scroll {+ 0%, 15% { transform: translateX(0); }+ 85%, 100% { transform: translateX(var(--template-scroll-distance)); }+}++.generator-runtime__options {+ position: absolute;+ top: calc(100% + var(--space-2));+ left: 0;+ width: 176px;+ max-height: 220px;+ overflow-y: auto;+ padding: var(--space-1);+ border: 1px solid var(--success-line);+ border-radius: var(--radius-md);+ background: color-mix(in srgb, var(--success) 9%, var(--panel-2));+ box-shadow: var(--shadow-sm);+ scrollbar-color: var(--success-line) transparent;+}++.generator-runtime__options button {+ width: 100%;+ min-height: var(--control-sm);+ display: grid;+ grid-template-columns: minmax(0, 1fr) 8px;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border: 0;+ border-radius: var(--radius-sm);+ color: var(--text-secondary);+ background: transparent;+ font-size: var(--text-sm);+ font-weight: var(--weight-medium);+ text-align: left;+}++.generator-runtime__options button > span {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.generator-runtime__options button:hover,+.generator-runtime__options button:focus-visible {+ outline: 0;+ color: var(--text-primary);+ background: color-mix(in srgb, var(--success) 14%, transparent);+}++.generator-runtime__options button[aria-selected="true"] {+ color: var(--success);+ background: var(--success-soft);+}++.generator-runtime__options button i {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--success);+ box-shadow: 0 0 8px var(--success-glow);+}++@media (prefers-reduced-motion: reduce) {+ .generator-runtime__value--overflow > span {+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ animation: none;+ }+}++.generator-runtime__status {+ white-space: nowrap;+}+.generator-runtime--ready {border-color: var(--success-line);color: var(--success);@@ -62,7 +214,8 @@.generator-runtime--runtimeMissing,.generator-runtime--modelsMissing,-.generator-runtime--incompatible {+.generator-runtime--incompatible,+.generator-runtime--unavailable {border-color: var(--danger-line);color: var(--danger);background: color-mix(in srgb, var(--danger) 10%, transparent);@@ -144,6 +297,12 @@border: 1px solid var(--line);border-radius: var(--radius-lg);background: var(--panel);+ cursor: pointer;+}++.scene-section--current > .scene-rule {+ border-color: var(--accent);+ background: color-mix(in srgb, var(--accent-soft) 45%, var(--panel));}.generator-heading__cancel {@@ -181,6 +340,16 @@align-items: center;gap: var(--space-3);padding: var(--space-2) 0;+ border: 0;+ border-radius: var(--radius-sm);+ color: inherit;+ background: none;+ text-align: left;+ cursor: pointer;+}++.scene-rule__summary:hover .scene-rule__text b {+ color: var(--accent-bright);}.scene-rule__status {@@ -245,16 +414,6 @@letter-spacing: var(--tracking-label);}-.scene-rule__settings-button {- flex: 0 0 auto;- width: var(--control-sm);- height: var(--control-sm);- min-height: var(--control-sm);- padding: 0;- display: grid;- place-items: center;-}-.scene-rule__length {flex: 0 0 auto;display: flex;@@ -279,24 +438,6 @@font-size: var(--text-2xs);}-.scene-rule__remove {- width: var(--control-sm);- height: var(--control-sm);- flex: 0 0 auto;- display: grid;- place-items: center;- padding: 0;- border: 1px solid var(--line);- border-radius: var(--radius-sm);- color: var(--text-muted);- background: var(--panel-2);-}--.scene-rule__remove:hover {- border-color: var(--danger);- color: var(--danger);-}-.scene-rule__generate {width: auto;flex: 0 0 auto;@@ -651,6 +792,13 @@object-fit: cover;}+.scene-card--add {+ width: min(100%, var(--content-max));+ min-height: 88px;+ flex: 0 0 auto;+ margin: 0 auto;+}+.shot-thumb video {width: 100%;height: 100%;@@ -1343,7 +1491,8 @@letter-spacing: 0;}-.panel-head__shot-title {+.panel-head__shot-title,+.panel-head__scene-title {display: flex;align-items: center;gap: var(--space-2);@@ -1354,6 +1503,15 @@flex: 1 1 auto;}+.panel-head__scene-title .job-title {+ min-width: 0;+ flex: 1 1 auto;+}++.panel-head__scene-title .job-title > div {+ flex: 1 1 auto;+}+.shot-title__name {width: 100%;min-width: 0;@@ -1881,10 +2039,6 @@line-height: var(--leading-normal);}-.job-empty__add {- margin-top: var(--space-5);-}-.job-empty__tips li::before {content: "";position: absolute;diff --git a/src/styles/shell.css b/src/styles/shell.cssindex f68deb5..04b3a84 100644--- a/src/styles/shell.css+++ b/src/styles/shell.css@@ -341,6 +341,141 @@text-align: center;}+/* --- Generator templates ------------------------------------------------- */++.generator-templates {+ margin-bottom: var(--space-4);+ padding: var(--space-4);+ border: 1px solid var(--line);+ border-radius: var(--radius-lg);+ background: var(--wash-1);+}++.generator-templates > header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: var(--space-4);+}++.generator-templates h2 {+ margin: 0;+ color: var(--text-primary);+ font-size: var(--text-lg);+}++.generator-templates header p {+ margin: var(--space-1) 0 0;+ color: var(--text-muted);+ font-size: var(--text-sm);+}++.generator-template-list {+ display: grid;+ gap: var(--space-2);+ margin-top: var(--space-4);+}++.generator-template-item {+ display: grid;+ grid-template-columns: var(--control-sm) minmax(0, 1fr) var(--control-sm);+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-1);+ border: 1px solid var(--line);+ border-radius: var(--radius-sm);+ background: var(--field-bg);+}++.generator-template-item--selected {+ border-color: var(--accent-line-strong);+ background: var(--accent-soft);+}++.generator-template-item__open {+ min-width: 0;+ display: flex;+ align-items: baseline;+ gap: var(--space-2);+ padding: var(--space-2);+ border: 0;+ color: var(--text-primary);+ background: transparent;+ text-align: left;+}++.generator-template-item__open b {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.generator-template-item__open small,+.generator-template-item > label {+ color: var(--text-muted);+ font-size: var(--text-xs);+}++.generator-template-item__default {+ display: flex;+ align-items: center;+ justify-content: center;+ width: var(--control-sm);+ height: var(--control-sm);+ cursor: pointer;+}++.generator-template-fields {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 160px;+ gap: var(--space-3);+ margin-top: var(--space-3);+}++.generator-template-fields label {+ display: grid;+ gap: var(--space-1);+ color: var(--text-muted);+ font-size: var(--text-xs);+}++.generator-template-fields input {+ min-width: 0;+ width: 100%;+ height: var(--field-height);+ padding: 0 var(--space-3);+ border: 1px solid var(--line-strong);+ border-radius: var(--radius-sm);+ color: var(--text-primary);+ background: var(--field-bg);+ font-size: var(--text-sm);+}++.generator-editor__head {+ margin-bottom: var(--space-4);+}++.generator-editor__head h2 {+ margin: 0;+ color: var(--text-primary);+ font-size: var(--text-lg);+}++.generator-editor__head p {+ margin: var(--space-1) 0 0;+ color: var(--text-muted);+ font-size: var(--text-sm);+}++.generator-editor__back {+ padding-inline: var(--space-2);+}++.generator-editor .generator-template-fields {+ margin: 0 0 var(--space-4);+}+.settings-status {padding: var(--space-4);border: 1px solid var(--line);@@ -417,6 +552,65 @@margin-bottom: var(--space-2);}+/* --- Diagnostics ---------------------------------------------------------- */++.diagnostics-setting {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr);+ gap: var(--space-4);+ padding: var(--space-5);+ border: 1px solid var(--line);+ border-radius: var(--radius-lg);+ background: var(--wash-1);+}++.diagnostics-setting__icon {+ width: var(--control-lg);+ height: var(--control-lg);+ display: grid;+ place-items: center;+ border-radius: var(--radius-md);+ color: var(--accent-bright);+ background: var(--accent-soft);+}++.diagnostics-setting h2 {+ margin: 0;+ color: var(--text-primary);+ font-size: var(--text-lg);+}++.diagnostics-setting p {+ margin: var(--space-2) 0 0;+ color: var(--text-muted);+ font-size: var(--text-sm);+ line-height: var(--leading-normal);+}++.diagnostics-setting code {+ display: block;+ margin: var(--space-4) 0 var(--space-3);+ padding: var(--space-3);+ overflow: hidden;+ border: 1px solid var(--line-solid);+ border-radius: var(--radius-sm);+ color: var(--text-secondary);+ background: var(--field-bg);+ font-size: var(--text-xs);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.diagnostics-setting small {+ display: block;+ margin: calc(-1 * var(--space-2)) 0 var(--space-3);+ color: var(--text-faint);+}++.diagnostics-setting__error {+ color: var(--danger) !important;+}+/* --- Appearance -------------------------------------------------------------Three options, always all three visible: "system" is a real choice, not theabsence of one, and a two-state toggle cannot say so. */@@ -748,6 +942,10 @@gap: var(--space-2);}+ .generator-template-fields {+ grid-template-columns: minmax(0, 1fr);+ }+.settings-path__row {flex-direction: column;align-items: stretch;