Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Edit project settings and improve reference icons

Bitti833afb1784cf
diff --git a/docs/project-settings.md b/docs/project-settings.md
new file mode 100644
index 0000000..063c391
--- /dev/null
+++ b/docs/project-settings.md
@@ -0,0 +1,27 @@
+# Project settings
+
+Click the project name in the open workspace to change its name, resolution,
+aspect ratio, or target length. The popup uses the same controls as New project
+and opens with the current values. **Save changes** saves the project; closing
+the popup or pressing Escape before saving discards the pending form edits.
+
+Resolution and aspect ratio update both the project settings and its brief.
+Target length updates the brief. New generation and export use the new canvas
+settings. Existing generated files, scene durations, and timeline clip trims
+are preserved.
+
+The AI agent can apply these settings with `project.set`:
+
+```jsonl
+{"op":"project.set","aspectRatio":"9:16","resolution":"768p","targetSeconds":60}
+{"op":"commit","summary":"Set the project to vertical 768p with a one-minute target length."}
+```
+
+Aspect ratios: `16:9`, `9:16`, `1:1`, `4:5`.
+Resolution keys: `416p`, `544p`, `640p`, `768p`, `1088p`, `1344p`.
+Target length is a whole number from 0 to 600 seconds. The numeric field accepts
+any whole second. The slider uses one-second intervals through 60 seconds and
+ten-second intervals above that, with extra slider space for the first minute.
+Omit fields that should
+stay unchanged. Changing scene lengths or timeline clips uses the separate
+`scene.set` and `clip.set` commands.
diff --git a/docs/reference-icons.md b/docs/reference-icons.md
index d0ca517..3eff922 100644
--- a/docs/reference-icons.md
+++ b/docs/reference-icons.md
@@ -1,5 +1,17 @@
# Built-in reference icons
+Hover over a preset's icon area in **Add a reference** to reveal its generation
+button. It generates or regenerates only that preset and keeps the picker open.
+Hovering the button does not highlight or select the reference card.
+Built-in icon work follows category order: Character, Animal, Product, Location,
+then Style.
+
+Slopus can close immediately while only reference icons are generating.
+An icon is published only after the complete JPEG is written and flushed to a
+temporary file, then atomically replaces its destination. Interrupted temporary
+files are ignored, and an existing icon stays available until its replacement
+is complete. Normal video generation still uses the quit confirmation.
+
Opening **Add a reference** for the first time offers to generate any missing
built-in icons. **Don't ask again** remembers either answer across app launches:
Start enables generation of missing icons on later visits; Cancel disables it.
diff --git a/src-tauri/src/agent.rs b/src-tauri/src/agent.rs
index 27190f3..9a15674 100644
--- a/src-tauri/src/agent.rs
+++ b/src-tauri/src/agent.rs
@@ -54,6 +54,13 @@ For edits, return JSONL only: one compact JSON object per line, followed by one
Use existing stable IDs for updates and concise descriptive IDs for additions. Order dependent commands so their targets exist before use. Omit unchanged fields. The executor derives prompt mirrors, reference bindings, timestamps, and draft state. There are deliberately no commands for file paths, assets, provider settings, generated output, progress, project identity, or schema version. Never claim media was generated or an MP4 exists.
+Use project.set to change the open project's video settings, just like the Project settings popup opened by clicking its name:
+- aspectRatio: "16:9", "9:16", "1:1", or "4:5".
+- resolution: "416p", "544p", "640p", "768p", "1088p", or "1344p". These are stored resolution keys; the pixel dimensions depend on aspectRatio.
+- targetSeconds: the desired total project length in whole seconds, from 0 to 600.
+For example: {"op":"project.set","aspectRatio":"9:16","resolution":"768p","targetSeconds":60}, followed by the required commit line.
+Resolution and aspect ratio update both project settings and the brief. Target length updates the brief; it does not retime scenes or trim timeline clips. Only change scene or clip durations too when the user requests that. Existing generated media keeps its original dimensions; the new settings guide future generation and export.
+
Place scenes and existing media on the timeline when the user is creating or arranging a video:
- Use clip.add with scene for a Generator scene, including a scene created earlier in the same command batch. Slopus derives its generated asset; never invent an asset for it.
- Use clip.add with asset only for an asset id that already exists in the supplied project JSON.
diff --git a/src-tauri/src/agent_commands.rs b/src-tauri/src/agent_commands.rs
index df16637..1de7f28 100644
--- a/src-tauri/src/agent_commands.rs
+++ b/src-tauri/src/agent_commands.rs
@@ -1296,6 +1296,25 @@ mod tests {
assert_eq!(current, original);
}
+ #[test]
+ fn project_video_settings_update_both_mirrors_without_retiming_media() {
+ let current = validate_and_normalize_config(fixture()).unwrap();
+ let commands = parse_jsonl_commands(r#"{"op":"project.set","aspectRatio":"9:16","resolution":"544p","targetSeconds":90}
+{"op":"commit","summary":"Changed the project video settings."}"#).unwrap();
+ let next = execute_commands(&current, &commands.commands).unwrap();
+ assert_eq!(next.settings.aspect_ratio, "9:16");
+ assert_eq!(next.settings.resolution, "544p");
+ assert_eq!(next.brief.aspect_ratio, "9:16");
+ assert_eq!(next.brief.resolution, "544p");
+ assert_eq!(next.brief.target_duration_seconds, 90);
+ assert_eq!(next.timeline, current.timeline);
+ assert_eq!(next.assets, current.assets);
+ for patch in [r#""targetSeconds":601"#, r#""resolution":"8k""#, r#""aspectRatio":"21:9""#] {
+ let command: ProjectCommand = serde_json::from_str(&format!(r#"{{"op":"project.set",{patch}}}"#)).unwrap();
+ assert!(execute_commands(&current, &[command]).is_err());
+ }
+ }
+
#[test]
fn a_small_scene_patch_preserves_render_owned_fields() {
let current = fixture();
diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs
index 16b49d9..b470999 100644
--- a/src-tauri/src/export.rs
+++ b/src-tauri/src/export.rs
@@ -155,14 +155,22 @@ fn authorized_destination(value: &str) -> Result<PathBuf, String> {
/// Writes beside the destination and renames on top of it, so an export that
/// fails half way through cannot leave a truncated file where a playable one
-/// used to be. `fs::rename` replaces the destination on both platforms here.
+/// used to be. Flush the complete file before atomically publishing it.
pub(crate) fn write_atomically(destination: &Path, bytes: &[u8]) -> Result<(), String> {
let mut temporary = destination.as_os_str().to_os_string();
temporary.push(".part");
let temporary = PathBuf::from(temporary);
- fs::write(&temporary, bytes)
- .map_err(|error| format!("Could not write {}: {error}", temporary.to_string_lossy()))?;
- if let Err(error) = fs::rename(&temporary, destination) {
+ use std::io::Write;
+ let written = (|| {
+ let mut file = fs::File::create(&temporary)?;
+ file.write_all(bytes)?;
+ file.sync_all()
+ })();
+ if let Err(error) = written {
+ let _ = fs::remove_file(&temporary);
+ return Err(format!("Could not write {}: {error}", temporary.to_string_lossy()));
+ }
+ if let Err(error) = crate::atomic_replace(&temporary, destination) {
let _ = fs::remove_file(&temporary);
return Err(format!(
"Could not save {}: {error}",
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 3ef2159..a210fde 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -758,11 +758,9 @@ fn validate_and_normalize_config(mut config: ProjectConfig) -> Result<ProjectCon
config.brief.status
));
}
- // The bounds are spelled u32 so the range's element type cannot fall back
- // to i32 — `u32: PartialOrd<i32>` does not exist.
- if !(5u32..=600u32).contains(&config.brief.target_duration_seconds) {
+ if config.brief.target_duration_seconds > 600 {
return Err(format!(
- "Target duration must be between 5 and 600 seconds, received {}.",
+ "Target duration must be between 0 and 600 seconds, received {}.",
config.brief.target_duration_seconds
));
}
@@ -4685,9 +4683,6 @@ mod tests {
rejects("target duration above 600 seconds", |config| {
config.brief.target_duration_seconds = 900;
});
- rejects("target duration below 5 seconds", |config| {
- config.brief.target_duration_seconds = 4;
- });
rejects("unsupported brief aspect ratio", |config| {
config.brief.aspect_ratio = "21:9".into();
});
@@ -5086,7 +5081,7 @@ mod tests {
"rejected valid background color {background_color}"
);
}
- for seconds in [5u32, 60, 600] {
+ for seconds in [0u32, 1, 5, 60, 600] {
let mut config = fixture();
config.brief.target_duration_seconds = seconds;
assert!(
diff --git a/src-tauri/src/reference_icons.rs b/src-tauri/src/reference_icons.rs
index 7bf490e..3754d5d 100644
--- a/src-tauri/src/reference_icons.rs
+++ b/src-tauri/src/reference_icons.rs
@@ -126,6 +126,26 @@ mod tests {
}
}
+ #[test]
+ fn incomplete_writes_are_invisible_and_do_not_replace_a_finished_icon() {
+ let root = tempfile::tempdir().unwrap();
+ let rgba = vec![127; RENDER_SIZE as usize * RENDER_SIZE as usize * 4];
+ save_builtin(root.path(), "saved", &rgba).unwrap();
+ let original = read_builtin(root.path(), "saved").unwrap();
+ let directory = root.path().join("reference-icons");
+ fs::write(directory.join("saved.jpg.part"), [0xff, 0xd8]).unwrap();
+ fs::write(directory.join("interrupted.jpg.part"), [0xff, 0xd8]).unwrap();
+ assert_eq!(list_builtin(root.path()).unwrap(), ["saved"]);
+ assert_eq!(read_builtin(root.path(), "saved").unwrap(), original);
+ assert!(read_builtin(root.path(), "interrupted").is_err());
+ assert!(save_builtin(root.path(), "saved", &[0; 4]).is_err());
+ assert_eq!(read_builtin(root.path(), "saved").unwrap(), original);
+ save_builtin(root.path(), "saved", &vec![255; rgba.len()]).unwrap();
+ let replaced = read_builtin(root.path(), "saved").unwrap();
+ assert_ne!(replaced, original);
+ assert!(replaced.ends_with(&[0xff, 0xd9]));
+ }
+
#[test]
fn rejects_buffers_that_are_not_768_square_rgba() {
assert!(encode_jpeg(&[]).is_err());
diff --git a/src/App.test.tsx b/src/App.test.tsx
index 95c0354..7888aa0 100644
--- a/src/App.test.tsx
+++ b/src/App.test.tsx
@@ -53,7 +53,7 @@ describe("project library controls", () => {
beforeEach(() => localStorage.clear());
afterEach(cleanup);
- it("uses a named, settings-only New Project form with any length from 10 seconds to 10 minutes", async () => {
+ it("uses a named New Project form with numeric length and a slider up to 10 minutes", async () => {
const { container } = render(<App />);
await screen.findByText("Northern Light — Brand Film");
fireEvent.click(screen.getByRole("button", { name: "New project" }));
@@ -64,16 +64,16 @@ describe("project library controls", () => {
expect(screen.queryByText(/Add reference images/)).toBeNull();
expect(screen.queryByText(/Not sure where to start/)).toBeNull();
- const length = screen.getByRole("slider", { name: "Length in seconds" });
- expect(length).toHaveAttribute("min", "10");
- expect(length).toHaveAttribute("max", "600");
+ const length = screen.getByRole("slider", { name: "Length slider" });
+ expect(length).toHaveAttribute("aria-valuemin", "0");
+ expect(length).toHaveAttribute("aria-valuemax", "600");
expect(length).toHaveAttribute("step", "1");
expect(length).toHaveAttribute("aria-valuetext", "30 seconds");
- expect(screen.queryByRole("spinbutton", { name: "Length in seconds" })).toBeNull();
- fireEvent.change(length, { target: { value: "137" } });
+ const number = screen.getByRole("spinbutton", { name: "Length in seconds" });
+ fireEvent.change(number, { target: { value: "137" } });
expect(container.querySelector(".composer__options-value")!.textContent).toContain("2 minutes 17 seconds");
expect(length).toHaveAttribute("aria-valuetext", "2 minutes 17 seconds");
- fireEvent.change(length, { target: { value: "600" } });
+ fireEvent.change(length, { target: { value: "114" } });
expect(length).toHaveAttribute("aria-valuetext", "10 minutes");
expect(screen.getByRole("button", { name: "Create project" })).toBeEnabled();
});
diff --git a/src/App.tsx b/src/App.tsx
index a2f33e3..f893c50 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -92,9 +92,9 @@ function App() {
The video engine runs inside this process, so closing the window ends a
generation outright, and nothing partial is written on the way. The app
queue reports work across all projects; Rust holds the close request back
- only while that list is non-empty, and this is where the question is put
+ only for video work. Icons can be interrupted safely. This is where the question is put
and answered. See the fenced block in src-tauri/src/lib.rs. */
- const ongoingGenerations: OngoingGeneration[] = workItems.filter(isWorkActive).map((item) => ({ id: item.id, title: `${item.title} · ${item.projectName}`, running: item.status !== "queued" }));
+ const ongoingGenerations: OngoingGeneration[] = workItems.filter((item) => item.kind !== "reference-icons" && isWorkActive(item)).map((item) => ({ id: item.id, title: `${item.title} · ${item.projectName}`, running: item.status !== "queued" }));
const [closeRequested, setCloseRequested] = useState(false);
const answerClose = useCallback((confirmed: boolean) => {
diff --git a/src/WorkQueue.integration.test.tsx b/src/WorkQueue.integration.test.tsx
index 77f37b5..3dcbb40 100644
--- a/src/WorkQueue.integration.test.tsx
+++ b/src/WorkQueue.integration.test.tsx
@@ -2,6 +2,7 @@
import "@testing-library/jest-dom/vitest";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { listen } from "@tauri-apps/api/event";
+import { invoke } from "@tauri-apps/api/core";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import App from "./App";
import { saveGeneratedScene } from "./lib/generatedVideo";
@@ -44,6 +45,9 @@ it("keeps icon confirmation available after returning to the library", async ()
await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1));
expect(vi.mocked(enqueueSlopfabGeneration).mock.calls[0][0]).toMatchObject({ stillImage: true, canvasWidth: 768, steps: 20 });
expect(screen.queryByRole("alertdialog", { name: "Generate reference icons?" })).toBeNull();
+ expect(invoke).not.toHaveBeenCalledWith("set_generation_active", { active: true });
+ act(() => handlers.get("app-close-requested")!({ payload: {} }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("answer_app_close", { confirmed: true }));
});
it("cancels automatic generation and exposes the remembered choice in Generator settings", async () => {
@@ -86,6 +90,7 @@ it("keeps the application queue alive while switching projects and saves results
await waitFor(() => expect(saveProject).toHaveBeenCalledWith(expect.objectContaining({ folderPath: first.folderPath, config: expect.objectContaining({ generationJobs: expect.arrayContaining([expect.objectContaining({ status: "completed", outputRelativePath: "media/generated/queued-result.mp4" })]) }) })));
expect(document.querySelector(".project-title")?.textContent).toBe("Second project");
expect(saveGeneratedScene).toHaveBeenCalledWith(expect.objectContaining({ jobId: workId, folderPath: first.folderPath }));
+ expect(invoke).toHaveBeenCalledWith("set_generation_active", { active: true });
expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "Back to project library" }));
fireEvent.click(screen.getByRole("button", { name: "Open First project" }));
diff --git a/src/components/ProjectSettings.test.tsx b/src/components/ProjectSettings.test.tsx
new file mode 100644
index 0000000..9c963a8
--- /dev/null
+++ b/src/components/ProjectSettings.test.tsx
@@ -0,0 +1,102 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { createProjectConfig, type ProjectRecord } from "../lib/project";
+import { ProjectWorkspace } from "./ProjectWorkspace";
+import { PromptComposer } from "./PromptComposer";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
+afterEach(() => { cleanup(); localStorage.clear(); });
+
+const project = (): ProjectRecord => ({ folderPath: "C:/project-settings", config: createProjectConfig({
+ name: "Original", prompt: "Keep this brief", aspectRatio: "16:9", resolution: "768p", targetDurationSeconds: 30,
+}) });
+
+it("opens settings from the project name, saves both settings mirrors, and restores saved values", async () => {
+ const record = project();
+ const onSave = vi.fn(async (_record: ProjectRecord) => undefined);
+ render(<ProjectWorkspace project={record} initialView="references" onBack={vi.fn()} onSave={onSave} />);
+ const opener = screen.getByRole("button", { name: "Edit project settings for Original" });
+ opener.focus(); fireEvent.click(opener);
+ const dialog = within(screen.getByRole("dialog", { name: "Project settings" }));
+ expect(dialog.getByLabelText("Project name")).toHaveValue("Original");
+ expect(dialog.getByLabelText("Aspect Ratio")).toHaveValue("16:9");
+ expect(dialog.getByLabelText("Resolution")).toHaveValue("768p");
+ expect(dialog.getByLabelText("Length in seconds")).toHaveValue(30);
+ fireEvent.change(dialog.getByLabelText("Project name"), { target: { value: "Updated" } });
+ fireEvent.change(dialog.getByLabelText("Aspect Ratio"), { target: { value: "9:16" } });
+ fireEvent.change(dialog.getByLabelText("Resolution"), { target: { value: "544p" } });
+ fireEvent.change(dialog.getByLabelText("Length in seconds"), { target: { value: "90" } });
+ fireEvent.click(dialog.getByRole("button", { name: "Save changes" }));
+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Project settings" })).not.toBeInTheDocument());
+ const saved = onSave.mock.calls[0][0].config;
+ expect(saved).toMatchObject({ name: "Updated", id: record.config.id,
+ brief: { prompt: "Keep this brief", aspectRatio: "9:16", resolution: "544p", targetDurationSeconds: 90 },
+ settings: { aspectRatio: "9:16", resolution: "544p" },
+ });
+ expect(saved.timeline).toEqual(record.config.timeline);
+ expect(saved.generationJobs).toEqual(record.config.generationJobs);
+ expect(opener).toHaveFocus();
+ fireEvent.click(screen.getByRole("button", { name: "Edit project settings for Updated" }));
+ expect(screen.getByLabelText("Resolution")).toHaveValue("544p");
+ expect(screen.getByLabelText("Length in seconds")).toHaveValue(90);
+});
+
+it("cancels pending edits with Escape without saving", () => {
+ const onSave = vi.fn();
+ render(<ProjectWorkspace project={project()} initialView="references" onBack={vi.fn()} onSave={onSave} />);
+ fireEvent.click(screen.getByRole("button", { name: "Edit project settings for Original" }));
+ fireEvent.change(screen.getByLabelText("Aspect Ratio"), { target: { value: "1:1" } });
+ fireEvent.keyDown(window, { key: "Escape" });
+ expect(screen.queryByRole("dialog", { name: "Project settings" })).not.toBeInTheDocument();
+ expect(onSave).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Edit project settings for Original" }));
+ expect(screen.getByLabelText("Aspect Ratio")).toHaveValue("16:9");
+});
+
+it("keeps failed saves open for retry", async () => {
+ const onSave = vi.fn().mockRejectedValueOnce(new Error("Disk unavailable")).mockResolvedValue(undefined);
+ render(<ProjectWorkspace project={project()} initialView="references" onBack={vi.fn()} onSave={onSave} />);
+ fireEvent.click(screen.getByRole("button", { name: "Edit project settings for Original" }));
+ fireEvent.change(screen.getByLabelText("Length in seconds"), { target: { value: "120" } });
+ const dialog = within(screen.getByRole("dialog", { name: "Project settings" }));
+ fireEvent.click(dialog.getByRole("button", { name: "Save changes" }));
+ await waitFor(() => expect(dialog.getByRole("alert")).toHaveTextContent("Disk unavailable"));
+ expect(dialog.getByLabelText("Length in seconds")).toHaveValue(120);
+ fireEvent.click(dialog.getByRole("button", { name: "Save changes" }));
+ await waitFor(() => expect(screen.queryByRole("dialog", { name: "Project settings" })).not.toBeInTheDocument());
+ expect(onSave).toHaveBeenCalledTimes(2);
+});
+
+it("preserves legacy resolution and short project length when opening settings", async () => {
+ const config = project().config;
+ config.settings.resolution = "1080p";
+ config.brief.targetDurationSeconds = 5;
+ const onSubmit = vi.fn(async () => undefined);
+ render(<PromptComposer project={config} busy={false} onClose={vi.fn()} onCreate={onSubmit} />);
+ expect(screen.getByLabelText("Resolution")).toHaveValue("1080p");
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ resolution: "1080p", targetDurationSeconds: 5 }));
+});
+
+it.each([false, true])("supports exact numeric lengths and the two slider intervals (editing=%s)", (editing) => {
+ const onSubmit = vi.fn(async () => undefined);
+ render(<PromptComposer project={editing ? project().config : undefined} busy={false} onClose={vi.fn()} onCreate={onSubmit} />);
+ const slider = screen.getByRole("slider", { name: "Length slider" });
+ const number = screen.getByRole("spinbutton", { name: "Length in seconds" });
+ const save = screen.getByRole("button", { name: editing ? "Save changes" : "Create project" });
+ for (const [position, seconds] of [[0, 0], [1, 1], [59, 59], [60, 60], [61, 70], [62, 80], [114, 600]]) {
+ fireEvent.change(slider, { target: { value: String(position) } });
+ expect(number).toHaveValue(seconds);
+ expect(save).toBeEnabled();
+ }
+ fireEvent.change(number, { target: { value: "73" } });
+ fireEvent.click(save);
+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ targetDurationSeconds: 73 }));
+ for (const value of ["", "-1", "601", "3.5"]) {
+ fireEvent.change(number, { target: { value } });
+ expect(save).toBeDisabled();
+ }
+});
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index d357a5d..b4b1145 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -10,6 +10,7 @@ import { GeneratorView } from "./workspace/GeneratorView";
import { ReferencesView } from "./workspace/ReferencesView";
import { TimelineView, type ConfigUpdate } from "./workspace/TimelineView";
import { UnsavedProjectDialog } from "./UnsavedProjectDialog";
+import { PromptComposer } from "./PromptComposer";
export type ProjectView = "timeline" | "generator" | "references" | "agent" | "export";
@@ -48,6 +49,8 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
const [view, setView] = useState<ProjectView>(initialView);
const [leaving, setLeaving] = useState(false);
const [savingToLeave, setSavingToLeave] = useState(false);
+ const [editingProject, setEditingProject] = useState(false);
+ const [savingProjectSettings, setSavingProjectSettings] = useState(false);
const [selectedGenerationJobId, setSelectedGenerationJobId] = useState<string | undefined>(project.config.generationJobs[0]?.id);
const knownSceneIds = useRef(new Set(project.config.generationJobs.map((job) => job.id)));
const projectItems = items.filter((item) => item.projectKey === projectQueueKey(project));
@@ -79,6 +82,19 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
}, [config.generationJobs, project.folderPath]);
return <div className="project-shell">
+ {editingProject && <PromptComposer project={config} busy={savingProjectSettings} error={saveError} onClose={() => setEditingProject(false)} onCreate={async (input) => {
+ setSavingProjectSettings(true);
+ try {
+ session.update((current) => ({
+ ...current, name: input.name,
+ brief: { ...current.brief, aspectRatio: input.aspectRatio, resolution: input.resolution, targetDurationSeconds: input.targetDurationSeconds },
+ settings: { ...current.settings, aspectRatio: input.aspectRatio, resolution: input.resolution },
+ }));
+ await session.save();
+ setEditingProject(false);
+ } catch { /* Keep the dialog open; the session supplies the save error. */ }
+ finally { setSavingProjectSettings(false); }
+ }} />}
{leaving && <UnsavedProjectDialog name={config.name} busy={savingToLeave} error={saveError} onSave={() => void leave(true)} onDiscard={() => void leave(false)} onBack={() => setLeaving(false)} />}
<header className="project-topbar">
<div className="project-topbar__lead">
@@ -90,7 +106,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
><ArrowLeft size={18} /></button>
{/* The name column is the topbar's elastic column and truncates on narrow
windows, so the full name stays available on hover. */}
- <div className="project-title"><strong title={config.name}>{config.name}</strong></div>
+ <div className="project-title"><button type="button" title={config.name} aria-label={`Edit project settings for ${config.name}`} aria-haspopup="dialog" aria-expanded={editingProject} onClick={() => { session.dismissError(); setEditingProject(true); }}><strong>{config.name}</strong></button></div>
</div>
<nav className="project-nav" aria-label="Project views">
@@ -127,7 +143,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
<div className={`project-content project-content--${view}`}>
{view === "timeline" && <TimelineView config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} onChange={changeConfig} onMeasured={recordMeasurement} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
{view === "generator" && <GeneratorView onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}
- {view === "references" && <ReferencesView config={config} folderPath={project.folderPath} onChange={changeConfig} onRegenerateIcon={(id) => queue.regenerateReferenceIcon(session, id)} onGenerateBuiltinIcons={() => queue.generateBuiltinReferenceIcons(session)} pendingIconIds={new Set(config.references.filter((reference) => queue.isReferenceIconPending(session, reference.id)).map((reference) => reference.id))} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
+ {view === "references" && <ReferencesView config={config} folderPath={project.folderPath} onChange={changeConfig} onRegenerateIcon={(id) => queue.regenerateReferenceIcon(session, id)} onGenerateBuiltinIcons={() => queue.generateBuiltinReferenceIcons(session)} onRegenerateBuiltinIcon={(id) => queue.regenerateBuiltinReferenceIcon(session, id)} pendingBuiltinIconIds={queue.pendingBuiltinIconIds()} pendingIconIds={new Set(config.references.filter((reference) => queue.isReferenceIconPending(session, reference.id)).map((reference) => reference.id))} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
{view === "export" && <ExportView config={config} folderPath={project.folderPath} />}
</div>
<footer className={`project-agent-row${view === "agent" ? " project-agent-row--page" : ""}`}><AgentDock
diff --git a/src/components/PromptComposer.tsx b/src/components/PromptComposer.tsx
index 8b3aecd..574f2ff 100644
--- a/src/components/PromptComposer.tsx
+++ b/src/components/PromptComposer.tsx
@@ -1,13 +1,15 @@
-import { Clapperboard, Clock3, Monitor, WandSparkles, X } from "lucide-react";
+import { Clapperboard, Clock3, Monitor, Save, WandSparkles, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { outputDimensions, resolutionLabel } from "../lib/export";
-import type { AspectRatio, CreateProjectInput, Resolution } from "../lib/project";
+import type { AspectRatio, CreateProjectInput, ProjectConfig, Resolution } from "../lib/project";
import { PROJECT_RESOLUTIONS } from "../lib/project";
interface PromptComposerProps {
busy: boolean;
onCreate: (input: CreateProjectInput) => Promise<void>;
onClose: () => void;
+ project?: ProjectConfig;
+ error?: string | null;
}
const aspectRatioLabels: Record<AspectRatio, string> = {
@@ -29,31 +31,46 @@ const durationLabel = (seconds: number) => {
return `${minutes} ${minutes === 1 ? "minute" : "minutes"}${remainder ? ` ${remainder} seconds` : ""}`;
};
-export function PromptComposer({ busy, onCreate, onClose }: PromptComposerProps) {
- const [name, setName] = useState("Untitled video");
- const [aspectRatio, setAspectRatio] = useState<AspectRatio>("16:9");
- const [resolution, setResolution] = useState<Resolution>(DEFAULT_RESOLUTION);
- const [duration, setDuration] = useState(30);
+export function PromptComposer({ busy, onCreate: onSubmit, onClose, project, error }: PromptComposerProps) {
+ const [name, setName] = useState(project?.name ?? "Untitled video");
+ const [aspectRatio, setAspectRatio] = useState<AspectRatio>(project?.settings.aspectRatio ?? "16:9");
+ const [resolution, setResolution] = useState<Resolution>(project?.settings.resolution ?? DEFAULT_RESOLUTION);
+ const [durationInput, setDurationInput] = useState(String(project?.brief.targetDurationSeconds ?? 30));
+ const duration = Number(durationInput);
+ const dialog = useRef<HTMLDivElement>(null);
const nameInput = useRef<HTMLInputElement>(null);
- const validDuration = Number.isInteger(duration) && duration >= 10 && duration <= 600;
+ const validDuration = durationInput.trim() !== "" && Number.isInteger(duration) && duration >= 0 && duration <= 600;
+ const sliderPosition = Math.max(0, Math.min(114, duration <= 60 ? duration : 60 + (duration - 60) / 10));
+ const resolutions: readonly Resolution[] = project && !PROJECT_RESOLUTIONS.some((value) => value === project.settings.resolution)
+ ? [...PROJECT_RESOLUTIONS, project.settings.resolution] : PROJECT_RESOLUTIONS;
/* Naming is the only authored content required before the Agent takes over. */
useEffect(() => {
+ const opener = document.activeElement as HTMLElement | null;
nameInput.current?.focus({ preventScroll: true });
nameInput.current?.select();
+ return () => { if (opener?.isConnected) opener.focus(); };
}, []);
useEffect(() => {
- const close = (event: KeyboardEvent) => { if (event.key === "Escape" && !busy) onClose(); };
- window.addEventListener("keydown", close);
- return () => window.removeEventListener("keydown", close);
+ const close = (event: KeyboardEvent) => {
+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); if (!busy) onClose(); }
+ if (event.key !== "Tab") return;
+ const controls = Array.from(dialog.current?.querySelectorAll<HTMLElement>("button:not(:disabled), input:not(:disabled), select:not(:disabled)") ?? []);
+ if (!controls.length) { event.preventDefault(); return; }
+ if (!dialog.current?.contains(document.activeElement) || (event.shiftKey ? document.activeElement === controls[0] : document.activeElement === controls.at(-1))) {
+ event.preventDefault(); (event.shiftKey ? controls.at(-1)! : controls[0]).focus();
+ }
+ };
+ window.addEventListener("keydown", close, true);
+ return () => window.removeEventListener("keydown", close, true);
}, [busy, onClose]);
const submit = async () => {
if (busy || !name.trim() || !validDuration) return;
- await onCreate({
+ await onSubmit({
name: name.trim(),
- prompt: "",
+ prompt: project?.brief.prompt ?? "",
aspectRatio,
resolution,
targetDurationSeconds: duration,
@@ -61,16 +78,16 @@ export function PromptComposer({ busy, onCreate, onClose }: PromptComposerProps)
};
return (
- <div className="composer-overlay" role="dialog" aria-modal="true" aria-labelledby="create-heading">
+ <div ref={dialog} className="composer-overlay" role="dialog" aria-modal="true" aria-labelledby="create-heading">
<section className="composer-shell">
<header className="composer-heading">
- <h2 id="create-heading">New project</h2>
- <button className="icon-button icon-button--strong" onClick={onClose} disabled={busy} aria-label="Close new project"><X size={18} /></button>
+ <h2 id="create-heading">{project ? "Project settings" : "New project"}</h2>
+ <button className="icon-button icon-button--strong" onClick={onClose} disabled={busy} aria-label={project ? "Close project settings" : "Close new project"}><X size={18} /></button>
</header>
<div className="composer">
<label className="composer__name-row">
<span>Project name</span>
- <input ref={nameInput} value={name} onChange={(event) => setName(event.target.value)} aria-label="Project name" />
+ <input ref={nameInput} disabled={busy} value={name} onChange={(event) => setName(event.target.value)} aria-label="Project name" />
</label>
<section className="composer__options">
@@ -82,7 +99,7 @@ export function PromptComposer({ busy, onCreate, onClose }: PromptComposerProps)
<div className="composer__options-grid">
<label>
<span><Monitor size={15} /> Aspect Ratio</span>
- <select value={aspectRatio} onChange={(event) => setAspectRatio(event.target.value as AspectRatio)}>
+ <select disabled={busy} value={aspectRatio} onChange={(event) => setAspectRatio(event.target.value as AspectRatio)}>
<option value="16:9">Widescreen 16:9</option>
<option value="9:16">Vertical 9:16</option>
<option value="1:1">Square 1:1</option>
@@ -95,39 +112,47 @@ export function PromptComposer({ busy, onCreate, onClose }: PromptComposerProps)
1376×768 widescreen and 768×1376 vertical. */}
<label>
<span><Clapperboard size={15} /> Resolution</span>
- <select value={resolution} onChange={(event) => setResolution(event.target.value as Resolution)}>
- {PROJECT_RESOLUTIONS.map((option) => {
+ <select disabled={busy} value={resolution} onChange={(event) => setResolution(event.target.value as Resolution)}>
+ {resolutions.map((option) => {
const { width, height } = outputDimensions(option, aspectRatio);
return <option key={option} value={option}>{width} × {height}{option === DEFAULT_RESOLUTION ? " (default)" : ""}</option>;
})}
</select>
</label>
- <label className="composer__duration">
+ <div className="composer__duration">
<span>
<Clock3 size={15} /> Length
- <output htmlFor="project-duration">{durationLabel(duration)}</output>
+ <output htmlFor="project-duration">{validDuration ? durationLabel(duration) : "Enter 0–600 seconds"}</output>
</span>
+ <input id="project-duration" aria-label="Length in seconds" type="number" min={0} max={600} step={1} disabled={busy} value={durationInput} onChange={(event) => setDurationInput(event.target.value)} />
<input
- id="project-duration"
- aria-label="Length in seconds"
+ aria-label="Length slider"
aria-valuetext={durationLabel(duration)}
+ aria-valuemin={0}
+ aria-valuemax={600}
+ aria-valuenow={validDuration ? duration : 0}
type="range"
- min={10}
- max={600}
+ min={0}
+ disabled={busy}
+ max={114}
step={1}
- value={duration}
- onChange={(event) => setDuration(Number(event.target.value))}
+ value={Number.isFinite(sliderPosition) ? sliderPosition : 0}
+ onChange={(event) => {
+ const position = Number(event.target.value);
+ setDurationInput(String(position <= 60 ? position : 60 + (position - 60) * 10));
+ }}
/>
- <small className="composer__duration-scale"><span>10 seconds</span><span>10 minutes</span></small>
- </label>
+ <small className="composer__duration-scale"><span>0 seconds</span><span>10 minutes</span></small>
+ </div>
</div>
</div>
</section>
+ {error && <p role="alert">{error}</p>}
<div className="composer__actions">
<button className="primary-button composer__submit" disabled={busy || !name.trim() || !validDuration} aria-busy={busy} onClick={() => void submit()}>
- {busy ? <span className="spinner" /> : <WandSparkles size={18} />}
- Create project
+ {busy ? <span className="spinner" /> : project ? <Save size={18} /> : <WandSparkles size={18} />}
+ {project ? "Save changes" : "Create project"}
</button>
</div>
</div>
diff --git a/src/components/workspace/ReferencesView.builtins.test.tsx b/src/components/workspace/ReferencesView.builtins.test.tsx
index efbbfce..6019e15 100644
--- a/src/components/workspace/ReferencesView.builtins.test.tsx
+++ b/src/components/workspace/ReferencesView.builtins.test.tsx
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { createProjectConfig } from "../../lib/project";
import { builtinIconVisitAction } from "../../lib/referenceIconSettings";
import { ReferencesView } from "./ReferencesView";
+import { REFERENCE_PRESETS } from "../../lib/reference-presets";
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
beforeEach(() => {
@@ -19,6 +20,33 @@ const open = (generate = vi.fn()) => {
return { generate, ...render(<ReferencesView config={config} folderPath="C:/project" onChange={vi.fn()} onGenerateBuiltinIcons={generate} />) };
};
+it("generates a preset icon without selecting its card and supports regenerating existing artwork", () => {
+ const preset = REFERENCE_PRESETS.find(({ name }) => name === "Abby Sciuto")!;
+ const previous = preset.icon;
+ const config = createProjectConfig({ name: "Icons", prompt: "", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 10 });
+ const onChange = vi.fn();
+ const generate = vi.fn();
+ const props = { config, folderPath: "C:/project", onChange, onRegenerateBuiltinIcon: generate };
+ const view = render(<ReferencesView {...props} />);
+ fireEvent.click(screen.getByRole("button", { name: /^Add a reference/ }));
+ fireEvent.change(screen.getByRole("textbox", { name: "Search reference options" }), { target: { value: preset.name } });
+ const button = screen.getByRole("button", { name: `Generate icon for ${preset.name}` });
+ expect(button.parentElement?.querySelector(".reference-preset-select")?.contains(button)).toBe(false);
+ fireEvent.click(button);
+ expect(generate).toHaveBeenCalledWith(preset.id);
+ expect(onChange).not.toHaveBeenCalled();
+ expect(screen.getByRole("dialog", { name: "Add a reference" })).toBeInTheDocument();
+ view.rerender(<ReferencesView {...props} pendingBuiltinIconIds={new Set([preset.id])} />);
+ expect(button).toBeDisabled();
+ try {
+ preset.icon = "/complete-icon.jpg";
+ view.rerender(<ReferencesView {...props} />);
+ fireEvent.click(screen.getByRole("button", { name: `Regenerate icon for ${preset.name}` }));
+ expect(generate).toHaveBeenCalledTimes(2);
+ expect(onChange).not.toHaveBeenCalled();
+ } finally { preset.icon = previous; }
+});
+
it("asks on the first Add reference visit, explains video priority, and remembers Start", async () => {
const view = open();
expect(screen.queryByRole("alertdialog")).toBeNull();
diff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsx
index 5e2e886..6816a3f 100644
--- a/src/components/workspace/ReferencesView.tsx
+++ b/src/components/workspace/ReferencesView.tsx
@@ -60,12 +60,14 @@ function ClipSecondsInput({ label, value, min, max = Number.MAX_SAFE_INTEGER, on
}} /></label>;
}
-export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon, onGenerateBuiltinIcons, pendingIconIds = new Set<string>(), onOpenGenerator }: {
+export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon, onGenerateBuiltinIcons, onRegenerateBuiltinIcon, pendingBuiltinIconIds = new Set<string>(), pendingIconIds = new Set<string>(), onOpenGenerator }: {
config: ProjectConfig;
folderPath: string;
onChange: (next: ProjectConfig) => void;
onRegenerateIcon?: (referenceId: string) => void;
onGenerateBuiltinIcons?: () => void;
+ onRegenerateBuiltinIcon?: (presetId: string) => void;
+ pendingBuiltinIconIds?: ReadonlySet<string>;
pendingIconIds?: ReadonlySet<string>;
onOpenGenerator?: (jobId: string) => void;
}) {
@@ -374,10 +376,17 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,
{subcategories.map((subcategory) => <button key={subcategory} className={pickerSubcategory === subcategory ? "active" : ""} aria-pressed={pickerSubcategory === subcategory} onClick={() => setPickerSubcategory(subcategory)}>{subcategory}</button>)}
</div>
<div className="reference-preset-grid">
- {visiblePresets.map((preset) => <button key={preset.id} className={hasPresetIcon(preset) ? "reference-preset-card--with-icon" : undefined} onClick={() => choosePreset(preset)}>
- {hasPresetIcon(preset) && <PresetIcon className="reference-preset-icon" preset={preset} />}
- <small>{preset.subcategory}</small><b>{preset.name}</b><span>{preset.prompt}</span>
- </button>)}
+ {visiblePresets.map((preset) => <div className="reference-preset-card" key={preset.id}>
+ <button type="button" className={`reference-preset-select${hasPresetIcon(preset) || onRegenerateBuiltinIcon ? " reference-preset-card--with-icon" : ""}`} onClick={() => choosePreset(preset)}>
+ {(hasPresetIcon(preset) || onRegenerateBuiltinIcon) && <PresetIcon className="reference-preset-icon" preset={preset} />}
+ <small>{preset.subcategory}</small><b>{preset.name}</b><span>{preset.prompt}</span>
+ </button>
+ {onRegenerateBuiltinIcon && <button type="button" className="reference-preset-generate" aria-label={`${hasPresetIcon(preset) ? "Regenerate" : "Generate"} icon for ${preset.name}`} title={pendingBuiltinIconIds.has(preset.id) ? "Icon generation queued or running" : `${hasPresetIcon(preset) ? "Regenerate" : "Generate"} icon`} disabled={pendingBuiltinIconIds.has(preset.id)} onClick={() => {
+ setIconError(null);
+ try { onRegenerateBuiltinIcon(preset.id); }
+ catch (reason) { setIconError(reason instanceof Error ? reason.message : String(reason)); }
+ }}><RefreshCw size={20} aria-hidden="true" /></button>}
+ </div>)}
{visiblePresets.length === 0 && <p>No options match that search.</p>}
</div></>}
</section>
diff --git a/src/lib/builtinIconWork.test.ts b/src/lib/builtinIconWork.test.ts
index 00a5f97..11c6971 100644
--- a/src/lib/builtinIconWork.test.ts
+++ b/src/lib/builtinIconWork.test.ts
@@ -72,3 +72,38 @@ it("stops the remaining catalog after an engine failure instead of repeating it
await work.runNext(Promise.resolve(), () => false);
expect(work.hasRunnable()).toBe(false);
});
+
+it("regenerates existing icons on request and publishes only after the final frame is ready", async () => {
+ vi.mocked(hasBuiltinIcon).mockReturnValue(true);
+ const { work, session } = setup();
+ work.enqueueBuiltins(session, [presets[0]], true);
+ work.enqueueBuiltins(session, [presets[0]], true);
+ expect(work.pendingBuiltinIds()).toEqual(new Set([presets[0].id]));
+ const running = work.runNext(Promise.resolve(), () => false);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ const id = vi.mocked(enqueueSlopfabGeneration).mock.calls[0][0].jobId;
+ work.progressEvent({ jobId: id, step: 10, totalSteps: 20 });
+ expect(saveBuiltinIcon).not.toHaveBeenCalled();
+ work.event({ jobId: id, state: "framesReady", detail: "Ready" });
+ await running;
+ expect(saveBuiltinIcon).toHaveBeenCalledWith(presets[0].id, id);
+ expect(work.pendingBuiltinIds().size).toBe(0);
+ vi.mocked(hasBuiltinIcon).mockReturnValue(false);
+});
+
+it("generates all built-ins in category order even when enqueued in reverse order", async () => {
+ const { work, session } = setup();
+ await work.cancel();
+ const categories = ["character", "animal", "product", "location", "style"] as const;
+ const reversed = [...categories].reverse().map((type) => ({ id: `ordered-${type}`, name: type, prompt: `A ${type}.`, type, subcategory: "Test" }));
+ work.enqueueBuiltins(session, reversed);
+ for (const type of categories) {
+ const running = work.runNext(Promise.resolve(), () => false);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(categories.indexOf(type) + 1));
+ const request = vi.mocked(enqueueSlopfabGeneration).mock.calls.at(-1)![0];
+ expect(request.prompt).toContain(`A ${type}.`);
+ work.event({ jobId: request.jobId, state: "framesReady", detail: "Ready" });
+ await running;
+ }
+ expect(work.hasRunnable()).toBe(false);
+});
diff --git a/src/lib/builtinReferenceIcons.test.ts b/src/lib/builtinReferenceIcons.test.ts
index 9a8962f..d7c9060 100644
--- a/src/lib/builtinReferenceIcons.test.ts
+++ b/src/lib/builtinReferenceIcons.test.ts
@@ -37,3 +37,33 @@ it("discovers saved icons and lazily reads each shared JPEG only once", async ()
expect(revoke).toHaveBeenCalledWith("blob:builtin");
expect(hasBuiltinIcon("test-preset")).toBe(true);
});
+
+it("keeps previous artwork when saving fails and publishes new icons only after saving completes", async () => {
+ vi.stubGlobal("URL", { createObjectURL: vi.fn(() => "blob:previous"), revokeObjectURL: vi.fn() });
+ vi.mocked(invoke).mockResolvedValue(new ArrayBuffer(2));
+ await loadBuiltinIcon("keep-previous");
+ vi.mocked(invoke).mockRejectedValueOnce(new Error("Write interrupted"));
+ await expect(saveBuiltinIcon("keep-previous", "failed-job")).rejects.toThrow("Write interrupted");
+ expect(builtinIconUrl("keep-previous")).toBe("blob:previous");
+ let finish!: () => void;
+ vi.mocked(invoke).mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));
+ const saving = saveBuiltinIcon("new-complete", "job");
+ expect(hasBuiltinIcon("new-complete")).toBe(false);
+ finish(); await saving;
+ expect(hasBuiltinIcon("new-complete")).toBe(true);
+});
+
+it("does not cache an old read that finishes after regeneration", async () => {
+ const create = vi.fn(() => "blob:newest");
+ vi.stubGlobal("URL", { createObjectURL: create, revokeObjectURL: vi.fn() });
+ let finishOld!: (bytes: ArrayBuffer) => void;
+ vi.mocked(invoke).mockImplementationOnce(() => new Promise<ArrayBuffer>((resolve) => { finishOld = resolve; }));
+ const old = loadBuiltinIcon("race");
+ vi.mocked(invoke).mockResolvedValueOnce(undefined);
+ await saveBuiltinIcon("race", "regenerated");
+ vi.mocked(invoke).mockResolvedValueOnce(new ArrayBuffer(20));
+ finishOld(new ArrayBuffer(10));
+ expect(await old).toBe("blob:newest");
+ expect(create).toHaveBeenCalledOnce();
+ expect((create.mock.calls[0] as unknown as [Blob])[0].size).toBe(20);
+});
diff --git a/src/lib/builtinReferenceIcons.ts b/src/lib/builtinReferenceIcons.ts
index d989ef6..50e13cd 100644
--- a/src/lib/builtinReferenceIcons.ts
+++ b/src/lib/builtinReferenceIcons.ts
@@ -4,6 +4,7 @@ import { isTauri } from "./persistence";
let ids = new Set<string>();
const urls = new Map<string, string>();
const pending = new Map<string, Promise<string>>();
+const generations = new Map<string, number>();
const listeners = new Set<() => void>();
let revision = 0;
let refreshing: Promise<void> | undefined;
@@ -27,17 +28,21 @@ export function loadBuiltinIcon(id: string): Promise<string> {
if (cached) return Promise.resolve(cached);
const existing = pending.get(id);
if (existing) return existing;
- const request = invoke<ArrayBuffer>("read_builtin_reference_icon", { presetId: id }).then((bytes) => {
+ const generation = generations.get(id) ?? 0;
+ const request: Promise<string> = invoke<ArrayBuffer>("read_builtin_reference_icon", { presetId: id }).then((bytes) => {
+ if ((generations.get(id) ?? 0) !== generation) return loadBuiltinIcon(id);
const url = URL.createObjectURL(new Blob([bytes], { type: "image/jpeg" }));
urls.set(id, url);
return url;
- }).finally(() => pending.delete(id));
+ }).finally(() => { if (pending.get(id) === request) pending.delete(id); });
pending.set(id, request);
return request;
}
export async function saveBuiltinIcon(presetId: string, jobId: string) {
await invoke("save_builtin_reference_icon", { presetId, jobId });
+ generations.set(presetId, (generations.get(presetId) ?? 0) + 1);
+ pending.delete(presetId);
const previous = urls.get(presetId);
if (previous) { URL.revokeObjectURL(previous); urls.delete(presetId); }
ids.add(presetId);
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 3ba2d50..9ed44fe 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -232,7 +232,7 @@ export const generationBriefSchema = z.object({
/* Blank is a real empty project: no brief and no seeded scene. */
prompt: z.string(),
status: z.enum(["draft", "queued", "generating", "ready", "failed"]),
- targetDurationSeconds: z.number().int().min(5).max(600),
+ targetDurationSeconds: z.number().int().min(0).max(600),
aspectRatio: aspectRatioSchema,
resolution: resolutionSchema,
});
diff --git a/src/lib/referenceIconWork.ts b/src/lib/referenceIconWork.ts
index 12c06b8..6415a4b 100644
--- a/src/lib/referenceIconWork.ts
+++ b/src/lib/referenceIconWork.ts
@@ -9,7 +9,7 @@ import { withEngineSettings } from "./settings";
import { activeReferenceRefmods, referenceRefmodInputs } from "./project";
import { loadReferenceIconAutomation, saveReferenceIconAutomation, subscribeReferenceIconAutomation } from "./referenceIconSettings";
import type { WorkItem } from "./workQueue";
-import { hasPresetIcon, REFERENCE_PRESETS, type ReferencePreset } from "./reference-presets";
+import { hasPresetIcon, REFERENCE_PRESETS, REFERENCE_TYPES, type ReferencePreset } from "./reference-presets";
import { saveBuiltinIcon } from "./builtinReferenceIcons";
type TaskStatus = "queued" | "generating" | "saving" | "completed" | "failed" | "cancelled" | "skipped";
@@ -17,6 +17,7 @@ interface IconTask {
key: string;
session: ProjectSession;
preset?: ReferencePreset;
+ replaceIcon?: boolean;
yielded?: boolean;
referenceId: string;
name: string;
@@ -110,17 +111,26 @@ export class ReferenceIconWork {
if (added) this.wake();
}
- enqueueBuiltins(session: ProjectSession, presets: readonly ReferencePreset[] = REFERENCE_PRESETS) {
+ enqueueBuiltins(session: ProjectSession, presets: readonly ReferencePreset[] = REFERENCE_PRESETS, replaceIcon = false) {
for (const preset of presets) {
const key = `builtin::${preset.id}`;
const previous = this.tasks.get(key);
- if (hasPresetIcon(preset) || (previous && ["queued", "generating", "saving"].includes(previous.status))) continue;
- this.tasks.set(key, { key, session, preset, referenceId: preset.id, name: preset.name, prompt: "", status: "queued", submitted: false, cancelled: false, force: true });
+ if ((!replaceIcon && hasPresetIcon(preset)) || (previous && ["queued", "generating", "saving"].includes(previous.status))) continue;
+ this.tasks.set(key, { key, session, preset, replaceIcon, referenceId: preset.id, name: preset.name, prompt: "", status: "queued", submitted: false, cancelled: false, force: true });
}
this.publish();
this.wake();
}
+ regenerateBuiltin(session: ProjectSession, presetId: string) {
+ const preset = REFERENCE_PRESETS.find(({ id }) => id === presetId);
+ if (preset) this.enqueueBuiltins(session, [preset], true);
+ }
+
+ pendingBuiltinIds(): ReadonlySet<string> {
+ return new Set([...this.tasks.values()].filter((task) => task.preset && ["queued", "generating", "saving"].includes(task.status)).map((task) => task.referenceId));
+ }
+
private referenceFor(task: IconTask): ProjectReference | undefined {
if (!task.preset) return task.session.getSnapshot().config.references.find((reference) => reference.id === task.referenceId);
const preset = task.preset;
@@ -220,7 +230,9 @@ export class ReferenceIconWork {
}
async runNext(ready: Promise<void>, videoWaiting: () => boolean) {
- const task = [...this.tasks.values()].find((task) => this.canRun(task));
+ const runnable = [...this.tasks.values()].filter((task) => this.canRun(task));
+ const categoryOrder = (task: IconTask) => REFERENCE_TYPES.findIndex(({ id }) => id === task.preset?.type);
+ const task = runnable.find((task) => !task.preset) ?? runnable.sort((a, b) => categoryOrder(a) - categoryOrder(b))[0];
if (!task) return;
this.active = task;
task.submitted = false;
@@ -236,7 +248,7 @@ export class ReferenceIconWork {
if (videoWaiting()) { task.status = "queued"; return; }
if (!task.force && loadReferenceIconAutomation() === "disabled") { task.status = "skipped"; return; }
if (!task.force && !task.approved && loadReferenceIconAutomation() === "ask") { task.status = "queued"; return; }
- if (task.preset && hasPresetIcon(task.preset)) { task.status = "skipped"; return; }
+ if (task.preset && !task.replaceIcon && hasPresetIcon(task.preset)) { task.status = "skipped"; return; }
const reference = this.referenceFor(task);
if (!reference || !this.shouldGenerate(reference, task)) { task.status = "skipped"; return; }
task.prompt = referenceIconPrompt(reference);
diff --git a/src/lib/runtime.test.ts b/src/lib/runtime.test.ts
index 0f5ae44..59bea9a 100644
--- a/src/lib/runtime.test.ts
+++ b/src/lib/runtime.test.ts
@@ -18,6 +18,18 @@ const project = () => ({
describe("deterministic browser runtime", () => {
beforeEach(() => localStorage.clear());
+ it("changes project video settings through the same agent command and keeps the brief synchronized", async () => {
+ const record = project();
+ const next = await executeAgentCommands(record.config, [{ op: "project.set", resolution: "544p", aspectRatio: "9:16", targetSeconds: 90 }]);
+ expect(next.settings).toMatchObject({ resolution: "544p", aspectRatio: "9:16" });
+ expect(next.brief).toMatchObject({ resolution: "544p", aspectRatio: "9:16", targetDurationSeconds: 90 });
+ expect(next.timeline).toEqual(record.config.timeline);
+ expect(record.config.brief.targetDurationSeconds).toBe(30);
+ await expect(executeAgentCommands(record.config, [{ op: "project.set", targetSeconds: 601 }])).rejects.toThrow();
+ await expect(executeAgentCommands(record.config, [{ op: "project.set", resolution: "8k" }])).rejects.toThrow();
+ await expect(executeAgentCommands(record.config, [{ op: "project.set", aspectRatio: "21:9" }])).rejects.toThrow();
+ });
+
it("reports explicit demo status and a plan-only generation boundary", async () => {
const record = project();
const status = await getRuntimeStatus();
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index 443ab7d..aa9699b 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -121,6 +121,11 @@ export class WorkQueue {
if (!isTauri()) throw new Error("Icon generation is available in the desktop app.");
this.icons.enqueueBuiltins(session);
}
+ regenerateBuiltinReferenceIcon(session: ProjectSession, presetId: string) {
+ if (!isTauri()) throw new Error("Icon generation is available in the desktop app.");
+ this.icons.regenerateBuiltin(session, presetId);
+ }
+ pendingBuiltinIconIds() { return this.icons.pendingBuiltinIds(); }
forgetProject(record: ProjectRecord) {
if (this.hasActiveProject(record)) throw new Error("Cancel or finish this project's work before deleting it.");
const session = this.projects.get(projectQueueKey(record));
diff --git a/src/styles/library.css b/src/styles/library.css
index a7e7832..f2b434a 100644
--- a/src/styles/library.css
+++ b/src/styles/library.css
@@ -227,13 +227,15 @@
gap: var(--space-4);
}
-.composer__options-grid label {
+.composer__options-grid label,
+.composer__duration {
display: grid;
gap: var(--space-2);
min-width: 0;
}
-.composer__options-grid label > span {
+.composer__options-grid label > span,
+.composer__duration > span {
display: flex;
align-items: center;
gap: var(--space-2);
diff --git a/src/styles/references.css b/src/styles/references.css
index 79cbad3..07af5e2 100644
--- a/src/styles/references.css
+++ b/src/styles/references.css
@@ -1047,7 +1047,11 @@
gap: var(--space-3);
}
-.reference-preset-grid > button {
+.reference-preset-card { position: relative; min-width: 0; }
+
+.reference-preset-select {
+ width: 100%;
+ height: 100%;
min-height: 104px;
padding: var(--space-4);
border: 1px solid var(--line);
@@ -1058,7 +1062,7 @@
overflow: hidden;
}
-.reference-preset-grid > button.reference-preset-card--with-icon {
+.reference-preset-select.reference-preset-card--with-icon {
display: grid;
grid-template-columns: 80px minmax(0, 1fr);
grid-template-rows: auto auto 1fr;
@@ -1085,16 +1089,40 @@
grid-column: 2;
}
-.reference-preset-grid > button:hover {
+.reference-preset-select > .reference-preset-icon { grid-column: 1; margin: 0; }
+
+.reference-preset-select:hover {
border-color: var(--accent);
background: var(--accent-soft);
}
-.reference-preset-grid > button.active {
+.reference-preset-select.active {
border-color: var(--accent-bright);
background: var(--accent-soft);
}
+/* A sibling of the selection button: hovering this area never hovers the card. */
+.reference-preset-generate {
+ position: absolute;
+ left: var(--space-4);
+ top: 50%;
+ transform: translateY(-50%);
+ width: 80px;
+ height: 80px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-sm);
+ color: var(--text-primary);
+ background: var(--panel-2);
+ opacity: 0;
+}
+
+.reference-preset-generate:hover,
+.reference-preset-generate:focus-visible { opacity: 1; }
+
+.reference-preset-generate:disabled:hover { opacity: 1; cursor: progress; }
+
.reference-location-settings {
display: flex;
flex-direction: column;
diff --git a/src/styles/workspace.css b/src/styles/workspace.css
index b0f25b9..c30b9cb 100644
--- a/src/styles/workspace.css
+++ b/src/styles/workspace.css
@@ -62,6 +62,24 @@
text-overflow: ellipsis;
}
+.project-title > button {
+ display: block;
+ width: 100%;
+ min-width: 0;
+ min-height: var(--control-sm);
+ padding: var(--space-1) var(--space-2);
+ border: 1px solid transparent;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ text-align: left;
+}
+
+.project-title > button:hover,
+.project-title > button:focus-visible {
+ border-color: var(--line-strong);
+ background: var(--panel-2);
+}
+
/* Never let the action buttons shrink — a squashed Save is worse than a
shortened project name. `margin-left: auto` still eats any spare width. */
.project-topbar__actions {