Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add native H3 image projects and editor

Bitti9786bfb4a4f9
diff --git a/fixtures/project-v1-image.json b/fixtures/project-v1-image.json
new file mode 100644
index 0000000..64af98a
--- /dev/null
+++ b/fixtures/project-v1-image.json
@@ -0,0 +1,114 @@
+{
+ "schemaVersion": 1,
+ "id": "project-image-1",
+ "name": "Ocean poster",
+ "createdAt": "2026-01-01T00:00:00.000Z",
+ "updatedAt": "2026-01-01T00:00:00.000Z",
+ "thumbnail": null,
+ "settings": {
+ "aspectRatio": "16:9",
+ "resolution": "768p",
+ "frameRate": 30,
+ "backgroundColor": "#10131a"
+ },
+ "brief": {
+ "prompt": "a rocket launch over the ocean at dawn",
+ "status": "draft",
+ "targetDurationSeconds": 60,
+ "aspectRatio": "16:9",
+ "resolution": "768p"
+ },
+ "assets": [],
+ "timeline": {
+ "tracks": [
+ {
+ "id": "track-story",
+ "kind": "video",
+ "name": "Track 1",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
+ {
+ "id": "track-v2",
+ "kind": "video",
+ "name": "Track 2",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
+ {
+ "id": "track-v3",
+ "kind": "video",
+ "name": "Track 3",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ }
+ ]
+ },
+ "references": [],
+ "generationJobs": [],
+ "providerSettings": {},
+ "generationType": "image",
+ "imageScene": {
+ "nodes": [
+ {
+ "id": "image-root",
+ "parentId": null,
+ "kind": "root",
+ "name": "Image",
+ "description": "A rocket launch over the ocean at dawn",
+ "text": "",
+ "box": null,
+ "colors": [
+ "#204060"
+ ]
+ },
+ {
+ "id": "group-rocket",
+ "parentId": "image-root",
+ "kind": "group",
+ "name": "Rocket",
+ "description": "A white rocket surrounded by glowing vapor",
+ "text": "",
+ "box": {
+ "x": 300,
+ "y": 100,
+ "width": 400,
+ "height": 800
+ },
+ "colors": []
+ },
+ {
+ "id": "title",
+ "parentId": "group-rocket",
+ "kind": "text",
+ "name": "Title",
+ "description": "Bold red lettering",
+ "text": "LIFT OFF",
+ "box": {
+ "x": 350,
+ "y": 150,
+ "width": 300,
+ "height": 100
+ },
+ "colors": [
+ "#FF0000"
+ ]
+ }
+ ],
+ "background": "Ocean at dawn",
+ "style": {
+ "mode": "art",
+ "aesthetics": "Minimal poster",
+ "lighting": "Sunrise",
+ "medium": "Illustration",
+ "detail": "Screen print"
+ },
+ "steps": 20,
+ "seed": 42,
+ "referenceIds": [],
+ "outputAssetId": null
+ }
+}
diff --git a/src-tauri/assets/agent-image.md b/src-tauri/assets/agent-image.md
new file mode 100644
index 0000000..376ec96
--- /dev/null
+++ b/src-tauri/assets/agent-image.md
@@ -0,0 +1,11 @@
+This is an IMAGE project. Apply these image-specific instructions instead of video planning instructions. The model is MiniMax H3 in native still-image mode. There is no timeline, soundtrack, scene sequence, or Python worker in this workflow. Use the Agent, Editor and References tabs.
+
+Author the image tree with this command, then a commit line:
+{"op":"image.set","nodes":[...],"background":"environment description","style":{"mode":"photo","aesthetics":"","lighting":"","medium":"","detail":"camera/lens or art style"},"steps":20,"seed":-1,"referenceIds":[]}
+
+All fields are required; copy unchanged authored fields from imageScene in the current project. Do not send outputAssetId: generated results belong to the app. Each node has exactly these fields:
+{"id":"stable-id","parentId":null,"kind":"root","name":"Image","description":"high-level image prompt","text":"","box":null,"colors":[]}
+
+Use exactly one root with parentId null. Other nodes have kind group, object, text or background, and parentId naming an existing node. IDs must be unique and the tree connected and acyclic. Objects, groups and text may carry box {"x":100,"y":100,"width":400,"height":600} in 0–1000 image coordinates; extents must be positive and stay within the image. Box null means automatic placement. A group's description provides context to its children. Text nodes use text for the exact lettering and description for appearance. Colors are hex #RRGGBB strings (up to 16). Names are short tree labels; put visual instructions in description. At most 500 nodes. Style mode is photo or art, steps 1–1000, seed -1 for random or a nonnegative safe integer. Placement is prose guidance to H3, not a guaranteed pixel mask.
+
+Use project.set for project name, resolution and aspectRatio. Use ref.add/ref.set for reusable descriptions, then include their IDs in image.set referenceIds. Bind only existing image/text references. Do not create scene.*, shot.* or clip.* commands for image projects. Preserve the current image composition unless asked to change it. Never invent files or claim to have generated an image: the user runs Generate in the Editor.
diff --git a/src-tauri/src/agent/prompt.rs b/src-tauri/src/agent/prompt.rs
index 68db59b..033a1b5 100644
--- a/src-tauri/src/agent/prompt.rs
+++ b/src-tauri/src/agent/prompt.rs
@@ -26,6 +26,9 @@ pub(super) fn context_prompt(config: &ProjectConfig, prompt: &str) -> Result<Str
/// Include only registered model policies used by this project. A new empty
/// project gets the default policy; unknown persisted models remain inert data.
pub(super) fn project_system_prompt(config: &ProjectConfig) -> String {
+ if config.generation_type == crate::project::GenerationType::Image {
+ return format!("{AGENT_SYSTEM_PROMPT}\n\n{}", include_str!("../../assets/agent-image.md"));
+ }
let mut ids = std::collections::BTreeSet::new();
let models: Vec<_> = config
.generation_jobs
diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs
index 4400eaf..d6b1d5a 100644
--- a/src-tauri/src/app.rs
+++ b/src-tauri/src/app.rs
@@ -84,6 +84,8 @@ pub fn run() {
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.invoke_handler(tauri::generate_handler![
+ commands::artifacts::save_generated_image,
+ commands::artifacts::export_generated_image,
app_updater_enabled,
weights::download_weight,
weights::lora::prepare_lora,
diff --git a/src-tauri/src/commands/artifacts.rs b/src-tauri/src/commands/artifacts.rs
index 5e108b9..d287c9f 100644
--- a/src-tauri/src/commands/artifacts.rs
+++ b/src-tauri/src/commands/artifacts.rs
@@ -132,6 +132,42 @@ pub(crate) fn save_reference_icon(folder_path: String, job_id: String) -> Result
write_reference_icon_frame(&folder_path, &job_id, &reference_icon_pixels(&job_id)?)
}
+/// Preserve the full-resolution still; reference icons intentionally downscale.
+#[tauri::command]
+pub(crate) fn save_generated_image(folder_path: String, job_id: String) -> Result<serde_json::Value, String> {
+ let summary = rendered::summary(&job_id).ok_or("The generated image is no longer in memory.")?;
+ if summary.frame_count != 1 { return Err("Expected a single still image.".into()); }
+ let width = u16::try_from(summary.width).map_err(|_| "Image width exceeds JPEG limits.")?;
+ let height = u16::try_from(summary.height).map_err(|_| "Image height exceeds JPEG limits.")?;
+ let rgba = rendered::frame(&job_id, 0)?.ok_or("The generated image has no pixels.")?;
+ let mut bytes = Vec::new();
+ jpeg_encoder::Encoder::new(&mut bytes, 95).encode(&rgba, width, height, jpeg_encoder::ColorType::Rgba)
+ .map_err(|error| format!("Could not encode image: {error}"))?;
+ let root = ProjectRoot::open(&folder_path)?;
+ let stem = generated_file_stem(&job_id)?;
+ let directory = root.directory("media/generated")?;
+ let relative_path = format!("media/generated/{stem}.jpg");
+ crate::storage::atomic::write_atomically(&directory.join(format!("{stem}.jpg")), &bytes)?;
+ Ok(serde_json::json!({ "relativePath": relative_path, "width": width, "height": height }))
+}
+
+#[tauri::command]
+pub(crate) async fn export_generated_image(app: AppHandle, folder_path: String, relative_path: String) -> Result<bool, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ use tauri_plugin_dialog::DialogExt;
+ let root = ProjectRoot::open(&folder_path)?;
+ let source = root.existing(&relative_path)?;
+ if !relative_path.starts_with("media/generated/") || source.extension().and_then(|s| s.to_str()) != Some("jpg") {
+ return Err("Choose a generated JPEG image to export.".into());
+ }
+ let Some(destination) = app.dialog().file().set_title("Export image").add_filter("JPEG image", &["jpg", "jpeg"]).set_file_name("image.jpg").blocking_save_file() else { return Ok(false); };
+ let destination = destination.into_path().map_err(|_| "Choose a local image destination.")?;
+ let bytes = fs::read(source).map_err(|error| format!("Could not read image: {error}"))?;
+ crate::storage::atomic::write_atomically(&destination, &bytes)?;
+ Ok(true)
+ }).await.map_err(|error| error.to_string())?
+}
+
#[tauri::command]
pub(crate) fn list_builtin_reference_icons(app: AppHandle) -> Result<Vec<String>, String> {
reference_icons::list_builtin(&app_paths::data_directory(&app))
diff --git a/src-tauri/src/commands/generation.rs b/src-tauri/src/commands/generation.rs
index e45a25b..f3ecf7f 100644
--- a/src-tauri/src/commands/generation.rs
+++ b/src-tauri/src/commands/generation.rs
@@ -123,7 +123,9 @@ pub(crate) fn enqueue_slopfab_generation(
folder_path: String,
) -> Result<(), String> {
prepare_continuation_path(&mut request, Some(&folder_path))?;
- request.save_latents_path = Some(generated_latent_destination(&folder_path, &request.job_id)?);
+ if !request.still_image {
+ request.save_latents_path = Some(generated_latent_destination(&folder_path, &request.job_id)?);
+ }
let job_id = request.job_id.clone();
let result = validate_and_normalize_config(config).and_then(|config| {
state.enqueue(
diff --git a/src-tauri/src/project/commands/batch.rs b/src-tauri/src/project/commands/batch.rs
index 8a2801c..8b8ee3c 100644
--- a/src-tauri/src/project/commands/batch.rs
+++ b/src-tauri/src/project/commands/batch.rs
@@ -80,6 +80,18 @@ fn apply_command(
effects: &mut Effects,
) -> Result<(), String> {
match command {
+ ProjectCommand::ImageSet { nodes, background, style, steps, seed, reference_ids } => {
+ if project.generation_type != crate::project::GenerationType::Image { return Err("image.set requires an image project.".into()); }
+ let scene = crate::project::image::ImageScene {
+ nodes: nodes.clone(), background: background.clone(), style: style.clone(), steps: *steps, seed: *seed,
+ reference_ids: reference_ids.clone(), output_asset_id: project.image_scene.as_ref().and_then(|scene| scene.output_asset_id.clone()),
+ };
+ scene.validate()?;
+ for id in reference_ids { if !project.references.iter().any(|reference| &reference.id == id) { return Err(format!("Image reference '{id}' does not exist.")); } }
+ project.image_scene = Some(scene);
+ project.updated_at = timestamp.into();
+ Ok(())
+ }
ProjectCommand::ProjectSet { .. } => {
super::project::apply(project, command, timestamp, effects)
}
diff --git a/src-tauri/src/project/commands/types.rs b/src-tauri/src/project/commands/types.rs
index 706da5c..becdddb 100644
--- a/src-tauri/src/project/commands/types.rs
+++ b/src-tauri/src/project/commands/types.rs
@@ -12,6 +12,16 @@ pub const MAX_COMMANDS_PER_TURN: usize = 100;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", deny_unknown_fields)]
pub enum ProjectCommand {
+ #[serde(rename = "image.set")]
+ ImageSet {
+ nodes: Vec<crate::project::image::ImageNode>,
+ background: String,
+ style: crate::project::image::ImageStyle,
+ steps: u32,
+ seed: i64,
+ #[serde(rename = "referenceIds")]
+ reference_ids: Vec<String>,
+ },
#[serde(rename = "project.set")]
ProjectSet {
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -223,6 +233,7 @@ pub(super) struct CommitLine {
}
pub(super) fn command_name(command: &ProjectCommand) -> &'static str {
match command {
+ ProjectCommand::ImageSet { .. } => "image.set",
ProjectCommand::ProjectSet { .. } => "project.set",
ProjectCommand::ReferenceAdd { .. } => "ref.add",
ProjectCommand::ReferenceSet { .. } => "ref.set",
diff --git a/src-tauri/src/project/image.rs b/src-tauri/src/project/image.rs
new file mode 100644
index 0000000..285ba06
--- /dev/null
+++ b/src-tauri/src/project/image.rs
@@ -0,0 +1,71 @@
+use serde::{Deserialize, Serialize};
+use std::collections::{HashMap, HashSet};
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ImageScene {
+ pub nodes: Vec<ImageNode>,
+ pub background: String,
+ pub style: ImageStyle,
+ pub steps: u32,
+ pub seed: i64,
+ pub reference_ids: Vec<String>,
+ pub output_asset_id: Option<String>,
+}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ImageNode {
+ pub id: String,
+ pub parent_id: Option<String>,
+ pub kind: String,
+ pub name: String,
+ pub description: String,
+ pub text: String,
+ pub r#box: Option<ImageBox>,
+ pub colors: Vec<String>,
+}
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ImageBox { pub x: f64, pub y: f64, pub width: f64, pub height: f64 }
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ImageStyle { pub mode: String, pub aesthetics: String, pub lighting: String, pub medium: String, pub detail: String }
+
+impl ImageScene {
+ pub fn validate(&self) -> Result<(), String> {
+ if self.nodes.is_empty() || self.nodes.len() > 500 || !(1..=1000).contains(&self.steps)
+ || !(-1..=9_007_199_254_740_991).contains(&self.seed)
+ || !matches!(self.style.mode.as_str(), "photo" | "art")
+ || self.reference_ids.len() > 100 || self.reference_ids.iter().any(String::is_empty)
+ || self.output_asset_id.as_ref().is_some_and(String::is_empty) {
+ return Err("Invalid image generation settings.".into());
+ }
+ let nodes: HashMap<_, _> = self.nodes.iter().map(|node| (node.id.as_str(), node)).collect();
+ let roots: Vec<_> = self.nodes.iter().filter(|node| node.kind == "root").collect();
+ if nodes.len() != self.nodes.len() || roots.len() != 1 || roots[0].parent_id.is_some() {
+ return Err("Image nodes must form one connected tree with unique IDs.".into());
+ }
+ for node in &self.nodes {
+ if node.id.is_empty() || node.name.is_empty() || node.name.chars().count() > 120
+ || !matches!(node.kind.as_str(), "root" | "group" | "object" | "text" | "background")
+ || node.colors.len() > 16 || node.colors.iter().any(|color| color.len() != 7 || !color.starts_with('#') || !color[1..].bytes().all(|c| c.is_ascii_hexdigit())) {
+ return Err("Invalid image node.".into());
+ }
+ if let Some(b) = &node.r#box {
+ if ![b.x, b.y, b.width, b.height].iter().all(|v| v.is_finite())
+ || b.x < 0.0 || b.y < 0.0 || b.x > 999.0 || b.y > 999.0
+ || b.width <= 0.0 || b.height <= 0.0 || b.x + b.width > 1000.0 || b.y + b.height > 1000.0 {
+ return Err("Image placement must stay inside the image.".into());
+ }
+ }
+ let mut seen = HashSet::from([node.id.as_str()]);
+ let mut parent = node.parent_id.as_deref();
+ while let Some(id) = parent {
+ if !seen.insert(id) { return Err("Image hierarchy contains a cycle.".into()); }
+ parent = nodes.get(id).ok_or("Image parent does not exist.")?.parent_id.as_deref();
+ }
+ if !seen.contains(roots[0].id.as_str()) { return Err("Image node is disconnected from the root.".into()); }
+ }
+ Ok(())
+ }
+}
diff --git a/src-tauri/src/project/mod.rs b/src-tauri/src/project/mod.rs
index 8feffad..5768f70 100644
--- a/src-tauri/src/project/mod.rs
+++ b/src-tauri/src/project/mod.rs
@@ -2,6 +2,7 @@
pub(crate) mod lifecycle;
pub(crate) mod migrations;
pub(crate) mod model;
+pub(crate) mod image;
pub(crate) mod paths;
pub(crate) mod references;
pub(crate) mod scenes;
diff --git a/src-tauri/src/project/model.rs b/src-tauri/src/project/model.rs
index db7c72e..a0b1f43 100644
--- a/src-tauri/src/project/model.rs
+++ b/src-tauri/src/project/model.rs
@@ -1,8 +1,7 @@
use super::{references::*, scenes::*, timeline::*};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
-/// Project purpose, not the types of media it contains. Only video projects
-/// can currently be created; the other values reserve future format support.
+/// Project purpose, not the types of media it contains. Missing values are video.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum GenerationType {
@@ -21,6 +20,8 @@ pub(crate) struct ProjectConfig {
pub(crate) schema_version: u32,
#[serde(default)]
pub(crate) generation_type: GenerationType,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(crate) image_scene: Option<super::image::ImageScene>,
pub(crate) id: String,
pub(crate) name: String,
pub(crate) created_at: String,
diff --git a/src-tauri/src/project/validation/mod.rs b/src-tauri/src/project/validation/mod.rs
index e59c615..cd51c6e 100644
--- a/src-tauri/src/project/validation/mod.rs
+++ b/src-tauri/src/project/validation/mod.rs
@@ -21,6 +21,9 @@ pub(crate) fn validate_and_normalize_config(
pub(crate) fn validate_checked(
mut config: ProjectConfig,
) -> Result<ProjectConfig, issue::ValidationIssue> {
+ if let Some(scene) = &config.image_scene {
+ scene.validate().map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "imageScene", message))?;
+ }
settings::validate(&mut config).map_err(|message| {
issue::ValidationIssue::new(
"project.invalid",
diff --git a/src/components/ProjectCard.tsx b/src/components/ProjectCard.tsx
index c237475..97b90bf 100644
--- a/src/components/ProjectCard.tsx
+++ b/src/components/ProjectCard.tsx
@@ -57,7 +57,7 @@ export function ProjectCard({ project, index, onOpen, onDelete }: ProjectCardPro
firstVisualMs,
assetsById,
);
- const firstAsset = firstClip ? config.assets.find((asset) => asset.id === firstClip.assetId) : undefined;
+ const firstAsset = config.generationType === "image" ? config.assets.find((asset) => asset.id === config.imageScene?.outputAssetId) : firstClip ? config.assets.find((asset) => asset.id === firstClip.assetId) : undefined;
useEffect(() => {
if (!menuOpen) return;
@@ -84,7 +84,7 @@ export function ProjectCard({ project, index, onOpen, onDelete }: ProjectCardPro
<button className="project-card__art-button" onClick={() => onOpen(project)} aria-label={`Open ${config.name}`}>
<div className={`project-card__art project-card__art--${artwork[index % artwork.length]}${firstAsset ? " project-card__art--media" : ""}`} style={style}>
{firstAsset && <MediaThumbnail
- key={`${firstAsset.id}-${firstClip!.sourceStartMs}`}
+ key={`${firstAsset.id}-${(firstClip?.sourceStartMs ?? 0)}`}
folderPath={project.folderPath}
asset={firstAsset}
posterTimeSeconds={firstClip!.sourceStartMs / 1000}
@@ -115,7 +115,7 @@ export function ProjectCard({ project, index, onOpen, onDelete }: ProjectCardPro
<p className="project-card__path" title={project.folderPath}><Folder size={13} /><span>{project.folderPath}</span></p>
<div className="project-card__meta">
<span><Clock3 size={14} /> Edited {relativeDate(config.updatedAt)}</span>
- <span>{durationLabel(config.brief.targetDurationSeconds)}</span>
+ <span>{config.generationType === "image" ? "Image project" : durationLabel(config.brief.targetDurationSeconds)}</span>
</div>
</div>
</article>
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index 04fa257..3ce8f6b 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -1,4 +1,5 @@
-import { ArrowLeft, BookOpen, Bot, Download, Film, Save, Sparkles } from "lucide-react";
+import { ArrowLeft, BookOpen, Bot, Download, Film, Image, Save, Sparkles } from "lucide-react";
+import { ImageEditor } from "./workspace/ImageEditor";
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import type { GenerationJob, ProjectConfig, ProjectRecord } from "../lib/project";
import { CHECKING_PROVIDERS, executeAgentCommands, type RuntimeStatus, type SlopfabStatus } from "../lib/runtime";
@@ -12,7 +13,7 @@ import { TimelineView, type ConfigUpdate } from "./workspace/TimelineView";
import { UnsavedProjectDialog } from "./UnsavedProjectDialog";
import { PromptComposer } from "./PromptComposer";
-export type ProjectView = "timeline" | "generator" | "references" | "agent" | "export";
+export type ProjectView = "timeline" | "generator" | "references" | "agent" | "export" | "editor";
/** The scene badge includes native generation and the final encoding step. */
export const isGenerationOngoing = (job: GenerationJob) =>
@@ -46,7 +47,8 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
const session = useMemo(() => queue.project(project), [queue, project.folderPath, project.config.id]);
const { config, saving, dirty, saveError } = useSyncExternalStore(session.subscribe, session.getSnapshot);
const items = useSyncExternalStore(queue.subscribe, queue.getSnapshot);
- const [view, setView] = useState<ProjectView>(initialView);
+ const imageProject = config.generationType === "image";
+ const [view, setView] = useState<ProjectView>(imageProject && !["agent", "references"].includes(initialView) ? "editor" : initialView);
const [leaving, setLeaving] = useState(false);
const [savingToLeave, setSavingToLeave] = useState(false);
const [editingProject, setEditingProject] = useState(false);
@@ -110,7 +112,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
</div>
<nav className="project-nav" aria-label="Project views">
- {([ ["agent", Bot, "Agent"], ["timeline", Film, "Timeline"], ["generator", Sparkles, "Generator"], ["references", BookOpen, "References"] ] as const).map(([id, Icon, label]) => {
+ {(imageProject ? ([ ["agent", Bot, "Agent"], ["editor", Image, "Editor"], ["references", BookOpen, "References"] ] as const) : ([ ["agent", Bot, "Agent"], ["timeline", Film, "Timeline"], ["generator", Sparkles, "Generator"], ["references", BookOpen, "References"] ] as const)).map(([id, Icon, label]) => {
const running = id === "generator" ? config.generationJobs.filter(isGenerationOngoing).length : 0;
return <button key={id} type="button" className={view === id ? "active" : ""} aria-current={view === id ? "page" : undefined} onClick={() => setView(id)}>
<Icon size={18} aria-hidden="true" /> {label}
@@ -122,7 +124,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
<div className="project-topbar__actions">
{/* A real view now: it renders the timeline through WebCodecs and writes
an .mp4. It stays honest about what it cannot do inside itself. */}
- <button
+ {!imageProject && <button
className="secondary-button"
type="button"
aria-current={view === "export" ? "page" : undefined}
@@ -130,7 +132,7 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
title="Render the timeline to a video file"
>
<Download size={16} aria-hidden="true" /> Export
- </button>
+ </button>}
{/* The standing "All changes saved" pill is gone; the button itself is
now the only save state there is, so it has to carry it. Off means
the file on disk already matches what is on screen. */}
@@ -141,13 +143,14 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
</header>
<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 === "editor" && imageProject && <ImageEditor config={config} folderPath={project.folderPath} onChange={changeConfig} onGenerate={(template) => queue.enqueueImage(session, template)} onCancel={(id) => queue.cancel(id)} work={projectItems.filter((item) => item.kind === "image").at(-1)} />}
+ {view === "timeline" && <TimelineView config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} onChange={changeConfig} onMeasured={recordMeasurement} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView(imageProject ? "editor" : "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)} 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
- context={view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : view === "references" ? "project references" : view === "export" ? "this export" : "this project"}
+ context={view === "editor" ? "this image composition" : view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : view === "references" ? "project references" : view === "export" ? "this export" : "this project"}
record={{ ...project, config }}
providers={runtime?.providers ?? CHECKING_PROVIDERS}
expanded={view === "agent"}
diff --git a/src/components/PromptComposer.tsx b/src/components/PromptComposer.tsx
index dfe56af..ce0bc00 100644
--- a/src/components/PromptComposer.tsx
+++ b/src/components/PromptComposer.tsx
@@ -20,6 +20,7 @@ const DEFAULT_RESOLUTION: Resolution = "768p";
const LOOKS = SHOT_TAG_GROUPS.find((group) => group.id === "visualStyle")!.options;
export function PromptComposer({ busy, onCreate: onSubmit, onClose, project, error }: PromptComposerProps) {
+ const [generationType, setGenerationType] = useState<"video" | "image">(project?.generationType === "image" ? "image" : "video");
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);
@@ -54,6 +55,7 @@ export function PromptComposer({ busy, onCreate: onSubmit, onClose, project, err
const submit = async () => {
if (busy || !name.trim()) return;
await onSubmit({
+ generationType,
name: name.trim(),
prompt: project?.brief.prompt ?? "",
aspectRatio,
@@ -71,6 +73,11 @@ export function PromptComposer({ busy, onCreate: onSubmit, onClose, project, err
<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">
+ {!project && <label className="composer__name-row"><span>Project type</span><select aria-label="Project type" value={generationType} disabled={busy} onChange={(event) => {
+ const type = event.target.value as "video" | "image";
+ setGenerationType(type);
+ if (name === "Untitled video" || name === "Untitled image") setName(`Untitled ${type}`);
+ }}><option value="video">Video project</option><option value="image">Image project</option></select></label>}
<label className="composer__name-row">
<span>Project name</span>
<input ref={nameInput} disabled={busy} value={name} onChange={(event) => setName(event.target.value)} aria-label="Project name" />
@@ -78,7 +85,7 @@ export function PromptComposer({ busy, onCreate: onSubmit, onClose, project, err
<section className="composer__options">
<div className="composer__options-head">
- <span className="composer__options-title">Video settings</span>
+ <span className="composer__options-title">{generationType === "image" ? "Image settings" : "Video settings"}</span>
</div>
<div className="composer__options-body">
<div className="composer__options-grid">
diff --git a/src/components/WorkQueuePanel.tsx b/src/components/WorkQueuePanel.tsx
index 495010b..4b59de6 100644
--- a/src/components/WorkQueuePanel.tsx
+++ b/src/components/WorkQueuePanel.tsx
@@ -45,7 +45,7 @@ export function WorkQueuePanel({ queue, items, onClose }: { queue: WorkQueue; it
<div className="work-queue__metadata">
<div className="work-queue__detail"><span>{item.detail}</span>{isWorkActive(item) && item.status !== "queued" && <b>{Math.floor(item.progress * 100)}%</b>}</div>
{isWorkActive(item) && item.status !== "queued" && <progress max={1} value={item.progress} aria-label={`${item.title} progress`} />}
- <p className="work-queue__settings">{item.settings.canvasWidth} × {item.settings.canvasHeight} · {item.kind === "reference-icons" ? "JPG icons" : `${(item.settings.frames / GENERATION_FRAME_RATE).toFixed(1)}s`} · {item.settings.steps} steps · {item.settings.seed === -1 ? "Random seed" : `Seed ${item.settings.seed}`}</p>
+ <p className="work-queue__settings">{item.settings.canvasWidth} × {item.settings.canvasHeight} · {item.kind === "reference-icons" ? "JPG icons" : item.kind === "image" ? "JPG image" : `${(item.settings.frames / GENERATION_FRAME_RATE).toFixed(1)}s`} · {item.settings.steps} steps · {item.settings.seed === -1 ? "Random seed" : `Seed ${item.settings.seed}`}</p>
</div>
{item.error && <p className="work-queue__error">{item.error}</p>}
{item.needsSave && <button type="button" className="secondary-button" onClick={() => void queue.retrySave(item.id)}>Retry project save</button>}
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
new file mode 100644
index 0000000..c3f181c
--- /dev/null
+++ b/src/components/workspace/ImageEditor.tsx
@@ -0,0 +1,158 @@
+import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent } from "react";
+import { Box, ChevronDown, ChevronRight, Copy, Download, Image, Plus, Redo2, Sparkles, Square, Trash2, Undo2 } from "lucide-react";
+import { invoke } from "@tauri-apps/api/core";
+import { addImageNode, createImageScene, duplicateImageNode, imageDescendants, imageScenePrompt, removeImageNode, resizeImageNode, type ImageBox, type ImageNode, type ImageScene } from "../../lib/imageScene";
+import { outputDimensions } from "../../lib/export";
+import { isTauri } from "../../lib/persistence";
+import { PROJECT_RESOLUTIONS, type ProjectConfig } from "../../lib/project";
+import { defaultGeneratorTemplate, loadGeneratorTemplateSettings, subscribeGeneratorTemplates, templateNeedsDownload, type GeneratorTemplate } from "../../lib/settings";
+import { isWorkActive, type WorkItem } from "../../lib/workQueue";
+import type { ConfigUpdate } from "./TimelineView";
+import { ReferenceImage } from "./ReferenceImage";
+import "../../styles/image-editor.css";
+
+export function ImageEditor({ config, folderPath, onChange, onGenerate, onCancel, work }: {
+ config: ProjectConfig; folderPath: string; onChange: (update: ConfigUpdate) => void;
+ onGenerate: (template: GeneratorTemplate) => void; onCancel: (id: string) => Promise<void>; work?: WorkItem;
+}) {
+ const scene = useMemo(() => config.imageScene ?? createImageScene(config.brief.prompt), [config.imageScene, config.brief.prompt]);
+ const root = scene.nodes.find((node) => node.kind === "root")!;
+ const [selection, setSelection] = useState(root.id);
+ const selected = scene.nodes.find((node) => node.id === selection) ?? root;
+ const [collapsed, setCollapsed] = useState(new Set<string>());
+ const [templates, setTemplates] = useState(loadGeneratorTemplateSettings);
+ const [templateId, setTemplateId] = useState(() => defaultGeneratorTemplate().id);
+ const imageTemplates = templates.templates.filter((template) => template.mode !== "animate");
+ const template = imageTemplates.find((candidate) => candidate.id === templateId) ?? imageTemplates.find((candidate) => !templateNeedsDownload(candidate)) ?? imageTemplates[0];
+ const [error, setError] = useState<string | null>(null);
+ const [boxes, setBoxes] = useState(true);
+ const [drawKind, setDrawKind] = useState<"object" | "text" | "group" | null>(null);
+ const [zoom, setZoom] = useState(1);
+ const [draftBox, setDraftBox] = useState<ImageBox | null>(null);
+ const undo = useRef<ImageScene[]>([]);
+ const redo = useRef<ImageScene[]>([]);
+ const [, historyChanged] = useState(0);
+ const pointer = useRef<{ x: number; y: number; scene: ImageScene; id?: string; resize: boolean } | null>(null);
+ const active = work && isWorkActive(work);
+ const output = config.assets.find((asset) => asset.id === scene.outputAssetId);
+ const images = config.assets.filter((asset) => asset.kind === "image");
+ const { width, height } = outputDimensions(config.settings.resolution, config.settings.aspectRatio);
+ useEffect(() => subscribeGeneratorTemplates(() => setTemplates(loadGeneratorTemplateSettings())), []);
+
+ const commit = (next: ImageScene) => {
+ if (JSON.stringify(next) === JSON.stringify(scene)) return;
+ undo.current = [...undo.current.slice(-99), scene]; redo.current = [];
+ onChange((current) => ({ ...current, imageScene: { ...next, outputAssetId: current.imageScene?.outputAssetId ?? null } }));
+ historyChanged((value) => value + 1);
+ };
+ const history = (back: boolean) => {
+ const from = back ? undo : redo; const to = back ? redo : undo;
+ const next = from.current.pop(); if (!next) return;
+ to.current.push(scene);
+ onChange((current) => ({ ...current, imageScene: { ...next, outputAssetId: current.imageScene?.outputAssetId ?? null } }));
+ historyChanged((value) => value + 1);
+ };
+ const patchNode = (patch: Partial<ImageNode>) => commit({ ...scene, nodes: scene.nodes.map((node) => node.id === selected.id ? { ...node, ...patch } : node) });
+ const add = (kind: Exclude<ImageNode["kind"], "root">, box?: ImageBox) => {
+ const next = addImageNode(scene, selected.id, kind, box); commit(next); setSelection(next.nodes.at(-1)!.id);
+ setCollapsed((current) => { const next = new Set(current); next.delete(selected.id); return next; });
+ };
+ const attempt = (action: () => void | Promise<unknown>) => {
+ setError(null);
+ try { void Promise.resolve(action()).catch((reason) => setError(String(reason))); }
+ catch (reason) { setError(reason instanceof Error ? reason.message : String(reason)); }
+ };
+ const point = (event: PointerEvent<SVGSVGElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ return { x: Math.round(Math.max(0, Math.min(1000, (event.clientX - bounds.left) / bounds.width * 1000))), y: Math.round(Math.max(0, Math.min(1000, (event.clientY - bounds.top) / bounds.height * 1000))) };
+ };
+ const pointerDown = (event: PointerEvent<SVGSVGElement>) => {
+ if (event.button !== 0 || !boxes) return;
+ const target = event.target as SVGElement;
+ const id = drawKind ? undefined : target.dataset.node;
+ if (!id && !drawKind) { setSelection(root.id); return; }
+ if (id) setSelection(id);
+ pointer.current = { ...point(event), scene, id, resize: target.dataset.resize === "true" };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ };
+ const pointerMove = (event: PointerEvent<SVGSVGElement>) => {
+ const start = pointer.current; if (!start) return;
+ const at = point(event); const original = start.scene.nodes.find((node) => node.id === start.id)?.box;
+ if (original) {
+ const x = start.resize ? original.x : Math.max(0, Math.min(1000 - original.width, original.x + at.x - start.x));
+ const y = start.resize ? original.y : Math.max(0, Math.min(1000 - original.height, original.y + at.y - start.y));
+ setDraftBox({ x, y, width: start.resize ? Math.max(1, Math.min(1000 - x, original.width + at.x - start.x)) : original.width, height: start.resize ? Math.max(1, Math.min(1000 - y, original.height + at.y - start.y)) : original.height });
+ } else setDraftBox({ x: Math.min(start.x, at.x), y: Math.min(start.y, at.y), width: Math.abs(at.x - start.x), height: Math.abs(at.y - start.y) });
+ };
+ const pointerUp = () => {
+ const start = pointer.current;
+ if (start && draftBox && draftBox.width > 0 && draftBox.height > 0) {
+ if (start.id) commit(resizeImageNode(start.scene, start.id, draftBox));
+ else if (drawKind && draftBox.width >= 5 && draftBox.height >= 5) { add(drawKind, draftBox); setDrawKind(null); }
+ }
+ pointer.current = null; setDraftBox(null);
+ };
+ const descendants = imageDescendants(scene, selected.id);
+ const tree = (node: ImageNode, depth: number) => {
+ const children = scene.nodes.filter((child) => child.parentId === node.id);
+ const open = !collapsed.has(node.id);
+ return <div key={node.id} role="treeitem" aria-selected={selected.id === node.id} aria-expanded={children.length ? open : undefined}>
+ <div className={`image-tree__row ${selected.id === node.id ? "selected" : ""}`} style={{ paddingLeft: `calc(var(--space-2) + ${depth} * var(--space-4))` }}>
+ {children.length ? <button className="icon-button" aria-label={`${open ? "Collapse" : "Expand"} ${node.name}`} onClick={() => setCollapsed((current) => { const next = new Set(current); if (open) next.add(node.id); else next.delete(node.id); return next; })}>{open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}</button> : <span className="image-tree__spacer" />}
+ <button className="image-tree__select" onClick={() => setSelection(node.id)}><span>{node.kind === "text" ? "T" : node.kind === "root" ? <Image size={16} /> : <Box size={16} />}</span><span>{node.name}</span></button>
+ </div>
+ {open && children.length > 0 && <div role="group">{children.map((child) => tree(child, depth + 1))}</div>}
+ </div>;
+ };
+ return <div className="image-editor">
+ <aside className="image-tree" aria-label="Image hierarchy">
+ <header><strong>Scene</strong><div className="image-editor__actions"><button className="icon-button" title="Undo" aria-label="Undo image edit" disabled={!undo.current.length} onClick={() => history(true)}><Undo2 size={16} /></button><button className="icon-button" title="Redo" aria-label="Redo image edit" disabled={!redo.current.length} onClick={() => history(false)}><Redo2 size={16} /></button></div></header>
+ <div className="image-tree__add">{(["object", "text", "group", "background"] as const).map((kind) => <button className="secondary-button" key={kind} onClick={() => add(kind)}><Plus size={14} />{kind[0].toUpperCase() + kind.slice(1)}</button>)}</div>
+ <div role="tree" aria-label="Image nodes">{tree(root, 0)}</div>
+ <div className="image-tree__footer"><button className="secondary-button" disabled={selected.kind === "root"} onClick={() => { const next = duplicateImageNode(scene, selected.id); commit(next); setSelection(next.nodes[scene.nodes.length].id); }}><Copy size={15} /> Duplicate</button><button className="icon-button" aria-label="Delete selected node and children" disabled={selected.kind === "root"} onClick={() => { commit(removeImageNode(scene, selected.id)); setSelection(selected.parentId ?? root.id); }}><Trash2 size={16} /></button></div>
+ </aside>
+ <section className="image-center" aria-label="Image panel">
+ <header className="image-toolbar"><button className="primary-button" disabled={active ? work.cancelling || work.status === "encoding" : !isTauri() || !template || templateNeedsDownload(template) || !imageScenePrompt(scene)} onClick={() => attempt(() => active ? onCancel(work.id) : onGenerate(template!))}><Sparkles size={16} />{active ? work.cancelling ? "Cancelling…" : "Cancel" : "Generate"}</button>
+ <label>Generator template<select aria-label="Image generator template" value={template?.id ?? ""} disabled={Boolean(active)} onChange={(event) => { setTemplateId(event.target.value); const next = imageTemplates.find((candidate) => candidate.id === event.target.value); if (next) commit({ ...scene, steps: next.defaultSteps }); }}>
+ {!imageTemplates.length && <option value="">No MiniMax H3 templates</option>}{imageTemplates.map((item) => <option key={item.id} value={item.id} disabled={templateNeedsDownload(item)}>{item.name}{templateNeedsDownload(item) ? " (download in Settings)" : ""}</option>)}
+ </select></label><span className="image-model">MiniMax H3</span>
+ </header>
+ <div className="image-canvas-tools"><button className={`icon-button ${boxes ? "active" : ""}`} aria-label="Show placement boxes" aria-pressed={boxes} onClick={() => { setBoxes(!boxes); setDrawKind(null); }}><Square size={16} /></button>
+ <select aria-label="Canvas tool" value={drawKind ?? "select"} onChange={(event) => { setDrawKind(event.target.value === "select" ? null : event.target.value as typeof drawKind); setBoxes(true); }}><option value="select">Select / move</option><option value="object">Draw object</option><option value="text">Draw text</option><option value="group">Draw group</option></select>
+ <button className="secondary-button" onClick={() => setZoom(1)}>Fit</button><input aria-label="Image zoom" type="range" min="0.5" max="3" step="0.1" value={zoom} onChange={(event) => setZoom(Number(event.target.value))} /><span>{Math.round(zoom * 100)}%</span>
+ <button className="icon-button" aria-label="Export image" title="Export image" disabled={!output || !isTauri()} onClick={() => attempt(() => invoke("export_generated_image", { folderPath, relativePath: output!.relativePath }))}><Download size={16} /></button>
+ </div>
+ <div className="image-viewport"><div className="image-frame" style={{ "--image-ratio": width / height, "--image-zoom": zoom } as CSSProperties}>
+ {output ? <ReferenceImage folderPath={folderPath} relativePath={output.relativePath} sourcePath={output.sourcePath} alt={output.name} /> : <div className="image-empty"><Image size={42} /><strong>Compose your image</strong><span>Add objects, text, and groups, then describe them in the inspector.</span></div>}
+ <svg className={`image-overlay ${drawKind ? "drawing" : ""}`} viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-label="Image placement canvas" onPointerDown={pointerDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={() => { pointer.current = null; setDraftBox(null); }}>
+ {boxes && scene.nodes.filter((node) => node.box).map((node) => {
+ const box = pointer.current?.id === node.id && draftBox ? draftBox : node.box!;
+ return <g key={node.id} className={selected.id === node.id ? "selected" : ""}><rect data-node={node.id} x={box.x} y={box.y} width={box.width} height={box.height} vectorEffect="non-scaling-stroke" /><text x={box.x + 8} y={box.y + 30}>{node.name}</text>{selected.id === node.id && <rect className="image-box-handle" data-node={node.id} data-resize="true" x={box.x + box.width - 16} y={box.y + box.height - 16} width="16" height="16" />}</g>;
+ })}
+ {draftBox && !pointer.current?.id && <rect className="image-box-draft" {...{ x: draftBox.x, y: draftBox.y, width: draftBox.width, height: draftBox.height }} />}
+ </svg>
+ </div></div>
+ <div className="image-status" role="status">{active && <progress value={work.progress} max="1" />}<span>{active ? work.detail : !isTauri() ? "Image generation is available in the desktop app." : `${width} × ${height} · Placement boxes guide the prompt.`}</span></div>
+ {(error || work?.error) && <p className="image-error" role="alert">{error ?? work?.error}</p>}
+ {images.length > 0 && <div className="image-results" aria-label="Generated images">{images.map((asset) => <button key={asset.id} title={asset.name} aria-label={`View ${asset.name}`} aria-pressed={asset.id === scene.outputAssetId} onClick={() => onChange((current) => ({ ...current, thumbnail: asset.relativePath ?? null, imageScene: { ...(current.imageScene ?? scene), outputAssetId: asset.id } }))}><ReferenceImage folderPath={folderPath} relativePath={asset.relativePath} sourcePath={asset.sourcePath} alt={asset.name} /></button>)}</div>}
+ </section>
+ <aside className="image-inspector" aria-label="Image node inspector"><header><strong>Inspector</strong><span>{selected.kind}</span></header><div className="image-inspector__fields">
+ <label>Name<input value={selected.name} maxLength={120} onChange={(event) => { if (event.target.value.trim()) patchNode({ name: event.target.value }); }} /></label>
+ <label>{selected.kind === "root" ? "Prompt (high-level description)" : "Description"}<textarea rows={4} value={selected.description} onChange={(event) => patchNode({ description: event.target.value })} /></label>
+ {selected.kind === "text" && <label>Text to render<input value={selected.text} onChange={(event) => patchNode({ text: event.target.value })} /></label>}
+ {selected.kind !== "root" && <label>Parent<select value={selected.parentId ?? root.id} onChange={(event) => patchNode({ parentId: event.target.value })}>{scene.nodes.filter((node) => !descendants.has(node.id)).map((node) => <option key={node.id} value={node.id}>{node.name}</option>)}</select></label>}
+ {selected.kind === "root" && <>
+ <label>Background (environment)<textarea rows={3} value={scene.background} onChange={(event) => commit({ ...scene, background: event.target.value })} /></label>
+ <h3>Image generation</h3><label>Steps<input type="number" min="1" max="1000" value={scene.steps} onChange={(event) => { const value = Number(event.target.value); if (Number.isInteger(value) && value >= 1 && value <= 1000) commit({ ...scene, steps: value }); }} /></label>
+ <label>Seed (−1 = random)<input type="number" min="-1" max={Number.MAX_SAFE_INTEGER} value={scene.seed} onChange={(event) => { const value = Number(event.target.value); if (Number.isSafeInteger(value) && value >= -1) commit({ ...scene, seed: value }); }} /></label>
+ <label>Aspect ratio<select value={config.settings.aspectRatio} onChange={(event) => { const aspectRatio = event.target.value as ProjectConfig["settings"]["aspectRatio"]; onChange((current) => ({ ...current, settings: { ...current.settings, aspectRatio }, brief: { ...current.brief, aspectRatio } })); }}>{["16:9", "9:16", "1:1", "4:5"].map((ratio) => <option key={ratio}>{ratio}</option>)}</select></label>
+ <label>Resolution<select value={config.settings.resolution} onChange={(event) => { const resolution = event.target.value as ProjectConfig["settings"]["resolution"]; onChange((current) => ({ ...current, settings: { ...current.settings, resolution }, brief: { ...current.brief, resolution } })); }}>{[...new Set([...PROJECT_RESOLUTIONS, config.settings.resolution])].map((resolution) => { const size = outputDimensions(resolution, config.settings.aspectRatio); return <option key={resolution} value={resolution}>{size.width} × {size.height}</option>; })}</select></label>
+ <h3>Style</h3><label>Mode<select value={scene.style.mode} onChange={(event) => commit({ ...scene, style: { ...scene.style, mode: event.target.value as "photo" | "art" } })}><option value="photo">Photo</option><option value="art">Art</option></select></label>
+ {(["aesthetics", "lighting", ...(scene.style.mode === "art" ? ["medium" as const] : []), "detail"] as const).map((field) => <label key={field}>{field === "detail" ? scene.style.mode === "photo" ? "Camera / lens" : "Art style" : field[0].toUpperCase() + field.slice(1)}<input value={scene.style[field]} onChange={(event) => commit({ ...scene, style: { ...scene.style, [field]: event.target.value } })} /></label>)}
+ <h3>References</h3>{config.references.filter((reference) => reference.kind === "image" || reference.kind === "text").map((reference) => <label className="image-check" key={reference.id}><input type="checkbox" checked={scene.referenceIds.includes(reference.id)} onChange={(event) => commit({ ...scene, referenceIds: event.target.checked ? [...scene.referenceIds, reference.id] : scene.referenceIds.filter((id) => id !== reference.id) })} />{reference.name}</label>)}{!config.references.length && <p>Add image or text references in the References tab.</p>}
+ </>}
+ {selected.kind !== "root" && <><h3>Placement (0–1000)</h3><label className="image-check"><input type="checkbox" checked={Boolean(selected.box)} onChange={(event) => patchNode({ box: event.target.checked ? { x: 250, y: 250, width: 500, height: 500 } : null })} />Explicit placement</label>{selected.box && <div className="image-box-fields">{(["x", "y", "width", "height"] as const).map((field) => <label key={field}>{field}<input type="number" min={field === "x" || field === "y" ? 0 : 1} max="1000" value={selected.box![field]} onChange={(event) => { const value = Number(event.target.value); const box = { ...selected.box!, [field]: value }; if (Number.isFinite(value) && box.x >= 0 && box.y >= 0 && box.width > 0 && box.height > 0 && box.x + box.width <= 1000 && box.y + box.height <= 1000) commit(resizeImageNode(scene, selected.id, box)); }} /></label>)}</div>}</>}
+ <h3>Color palette</h3><div className="image-palette">{selected.colors.map((color, index) => <div key={index}><input aria-label={`Palette color ${index + 1}`} type="color" value={color} onChange={(event) => patchNode({ colors: selected.colors.map((old, i) => i === index ? event.target.value : old) })} /><button className="icon-button" aria-label={`Remove color ${index + 1}`} onClick={() => patchNode({ colors: selected.colors.filter((_, i) => i !== index) })}><Trash2 size={13} /></button></div>)}<button className="secondary-button" disabled={selected.colors.length >= (selected.kind === "root" ? 16 : 5)} onClick={() => patchNode({ colors: [...selected.colors, "#808080"] })}><Plus size={14} />Color</button></div>
+ </div></aside>
+ </div>;
+}
diff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsx
index 77117ac..7d1c6ec 100644
--- a/src/components/workspace/ReferencesView.tsx
+++ b/src/components/workspace/ReferencesView.tsx
@@ -137,7 +137,7 @@ export function ReferencesView({ config, folderPath, onChange, onRegenerateIcon,
};
const remove = () => {
if (!selected) return;
- onChange({ ...config, references: config.references.filter((ref) => ref.id !== selected.id), generationJobs: config.generationJobs.map((job) => ({
+ onChange({ ...config, ...(config.imageScene ? { imageScene: { ...config.imageScene, referenceIds: config.imageScene.referenceIds.filter((id) => id !== selected.id) } } : {}), references: config.references.filter((ref) => ref.id !== selected.id), generationJobs: config.generationJobs.map((job) => ({
...job,
referenceIds: job.referenceIds.filter((id) => id !== selected.id),
startFrameReferenceId: job.startFrameReferenceId === selected.id ? undefined : job.startFrameReferenceId,
diff --git a/src/lib/imageScene.ts b/src/lib/imageScene.ts
new file mode 100644
index 0000000..37888c3
--- /dev/null
+++ b/src/lib/imageScene.ts
@@ -0,0 +1,91 @@
+import { z } from "zod";
+
+const boxSchema = z.object({ x: z.number().min(0).max(999), y: z.number().min(0).max(999), width: z.number().positive().max(1000), height: z.number().positive().max(1000) })
+ .refine((box) => box.x + box.width <= 1000 && box.y + box.height <= 1000, "Placement must stay inside the image.");
+export const imageNodeSchema = z.object({
+ id: z.string().min(1), parentId: z.string().min(1).nullable(),
+ kind: z.enum(["root", "group", "object", "text", "background"]),
+ name: z.string().min(1).max(120), description: z.string(), text: z.string(),
+ box: boxSchema.nullable(), colors: z.array(z.string().regex(/^#[0-9a-fA-F]{6}$/)).max(16),
+});
+export const imageSceneSchema = z.object({
+ nodes: z.array(imageNodeSchema).min(1).max(500),
+ background: z.string(),
+ style: z.object({ mode: z.enum(["photo", "art"]), aesthetics: z.string(), lighting: z.string(), medium: z.string(), detail: z.string() }),
+ steps: z.number().int().min(1).max(1000), seed: z.number().int().min(-1).max(Number.MAX_SAFE_INTEGER),
+ referenceIds: z.array(z.string().min(1)).max(100),
+ outputAssetId: z.string().min(1).nullable(),
+}).superRefine((scene, context) => {
+ const ids = new Map(scene.nodes.map((node) => [node.id, node]));
+ const roots = scene.nodes.filter((node) => node.kind === "root");
+ const invalid = ids.size !== scene.nodes.length || roots.length !== 1 || roots[0]?.parentId !== null || scene.nodes.some((node) => {
+ if (node.kind === "root") return false;
+ const seen = new Set([node.id]);
+ let parent = node.parentId;
+ while (parent) {
+ if (seen.has(parent) || !ids.has(parent)) return true;
+ seen.add(parent); parent = ids.get(parent)!.parentId;
+ }
+ return !seen.has(roots[0]?.id);
+ });
+ if (invalid) context.addIssue({ code: z.ZodIssueCode.custom, message: "Image nodes must form one connected tree with unique IDs." });
+});
+export type ImageScene = z.infer<typeof imageSceneSchema>;
+export type ImageNode = z.infer<typeof imageNodeSchema>;
+export type ImageBox = NonNullable<ImageNode["box"]>;
+
+export function createImageScene(prompt = ""): ImageScene {
+ return { nodes: [{ id: "image-root", parentId: null, kind: "root", name: "Image", description: prompt, text: "", box: null, colors: [] }],
+ background: "", style: { mode: "photo", aesthetics: "", lighting: "", medium: "", detail: "" }, steps: 20, seed: -1, referenceIds: [], outputAssetId: null };
+}
+export function imageDescendants(scene: ImageScene, id: string): Set<string> {
+ const ids = new Set([id]);
+ for (let changed = true; changed;) {
+ changed = false;
+ for (const node of scene.nodes) if (node.parentId && ids.has(node.parentId) && !ids.has(node.id)) { ids.add(node.id); changed = true; }
+ }
+ return ids;
+}
+export function addImageNode(scene: ImageScene, parentId: string, kind: Exclude<ImageNode["kind"], "root">, box?: ImageBox): ImageScene {
+ const node: ImageNode = { id: crypto.randomUUID(), parentId, kind, name: kind[0].toUpperCase() + kind.slice(1), description: "", text: "", colors: [], box: box ?? (kind === "background" ? null : { x: 250, y: 250, width: 500, height: 500 }) };
+ return imageSceneSchema.parse({ ...scene, nodes: [...scene.nodes, node] });
+}
+export function removeImageNode(scene: ImageScene, id: string): ImageScene {
+ if (scene.nodes.find((node) => node.id === id)?.kind === "root") return scene;
+ const ids = imageDescendants(scene, id);
+ return { ...scene, nodes: scene.nodes.filter((node) => !ids.has(node.id)) };
+}
+export function duplicateImageNode(scene: ImageScene, id: string): ImageScene {
+ if (scene.nodes.find((node) => node.id === id)?.kind === "root") return scene;
+ const ids = imageDescendants(scene, id);
+ const replacements = new Map([...ids].map((old) => [old, crypto.randomUUID()]));
+ return imageSceneSchema.parse({ ...scene, nodes: [...scene.nodes, ...scene.nodes.filter((node) => ids.has(node.id)).map((node) => ({ ...node, id: replacements.get(node.id)!, parentId: replacements.get(node.parentId!) ?? node.parentId, name: node.id === id ? `${node.name.slice(0, 115)} copy` : node.name }))] });
+}
+/** Moving or resizing a group transforms all its children's placement boxes. */
+export function resizeImageNode(scene: ImageScene, id: string, box: ImageBox): ImageScene {
+ const original = scene.nodes.find((node) => node.id === id)?.box;
+ const descendants = imageDescendants(scene, id);
+ return imageSceneSchema.parse({ ...scene, nodes: scene.nodes.map((node) => {
+ if (node.id === id) return { ...node, box };
+ if (!original || !node.box || !descendants.has(node.id)) return node;
+ const x = Math.max(0, Math.min(999, Math.round(box.x + (node.box.x - original.x) * box.width / original.width)));
+ const y = Math.max(0, Math.min(999, Math.round(box.y + (node.box.y - original.y) * box.height / original.height)));
+ return { ...node, box: { x, y, width: Math.max(1, Math.min(1000 - x, Math.round(node.box.width * box.width / original.width))), height: Math.max(1, Math.min(1000 - y, Math.round(node.box.height * box.height / original.height))) } };
+ }) });
+}
+/** H3 accepts prose, not ImgFab's Ideogram-specific caption JSON. Coordinates
+ * are composition guidance in the prompt, not a guarantee of exact placement. */
+export function imageScenePrompt(scene: ImageScene): string {
+ const lines: string[] = [];
+ const visit = (node: ImageNode, depth: number) => {
+ const placement = node.box ? ` Placement: left ${node.box.x / 10}%, top ${node.box.y / 10}%, width ${node.box.width / 10}%, height ${node.box.height / 10}% of the image.` : "";
+ const text = node.kind === "text" && node.text ? ` Render the exact text ${JSON.stringify(node.text)}.` : "";
+ const colors = node.colors.length ? ` Colors: ${node.colors.join(", ")}.` : "";
+ if (node.description.trim() || text || colors) lines.push(`${" ".repeat(depth)}${node.kind}: ${node.description.trim()}${text}${placement}${colors}`);
+ scene.nodes.filter((child) => child.parentId === node.id).forEach((child) => visit(child, depth + 1));
+ };
+ scene.nodes.filter((node) => node.kind === "root").forEach((node) => visit(node, 0));
+ if (scene.background.trim()) lines.push(`Background: ${scene.background.trim()}`);
+ const style = [scene.style.mode === "photo" ? "Photograph" : scene.style.medium || "Artwork", scene.style.aesthetics, scene.style.lighting, scene.style.detail].filter(Boolean).join(". ");
+ return lines.length ? `Create a single still image.\n${lines.join("\n")}\nStyle: ${style}.` : "";
+}
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 3fab18b..945b9f6 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { createImageScene, imageSceneSchema } from "./imageScene";
import { effectSchemas } from "./effectSettings";
import { normalizeShotTagSelection, shotTagClauses, SHOT_TAG_ID_PATTERN, type ShotTagClauses, type ShotTagSelection } from "./shot-tags";
@@ -8,8 +9,7 @@ export const PROJECT_FILE_NAME = "slopus.json";
* ever written. */
export const LEGACY_PROJECT_FILE_NAMES = ["polstudio.json", "pols.json", "polstudio.project.json"] as const;
export const CURRENT_SCHEMA_VERSION = 1 as const;
-/** Project purpose, independent of the kinds of media it contains.
- * Non-video values reserve format support for future generation workflows. */
+/** Project purpose, independent of the kinds of media it contains. */
export const generationTypeSchema = z.enum(["video", "image", "3d", "music", "speech"]);
export type GenerationType = z.infer<typeof generationTypeSchema>;
export const DEFAULT_GENERATION_STEPS = 20;
@@ -540,6 +540,7 @@ export const providerSettingsSchema = z.record(idSchema, providerSettingSchema);
export const projectConfigSchema = z.object({
schemaVersion: z.literal(CURRENT_SCHEMA_VERSION),
generationType: generationTypeSchema.default("video"),
+ imageScene: imageSceneSchema.nullish(),
id: idSchema,
name: z.string().min(1).max(120),
createdAt: isoDateSchema,
@@ -604,6 +605,7 @@ export type ProjectConfig = z.infer<typeof projectConfigSchema>;
export interface ProjectRecord { folderPath: string; config: ProjectConfig }
export interface PendingReferenceImage { sourcePath: string; name: string }
export interface CreateProjectInput {
+ generationType?: "video" | "image";
name: string;
prompt: string;
aspectRatio: AspectRatio;
@@ -1512,7 +1514,8 @@ export function createProjectConfig(input: CreateProjectInput): ProjectConfig {
const brief = input.prompt.trim();
return projectConfigSchema.parse({
schemaVersion: CURRENT_SCHEMA_VERSION,
- generationType: "video",
+ generationType: input.generationType ?? "video",
+ ...(input.generationType === "image" ? { imageScene: createImageScene(brief) } : {}),
id: crypto.randomUUID(),
name: input.name.trim(),
createdAt: now,
@@ -1532,7 +1535,7 @@ export function createProjectConfig(input: CreateProjectInput): ProjectConfig {
{ id: "track-v3", kind: "video", name: "Track 3", locked: false, muted: false, clips: [] },
] },
references: [],
- generationJobs: brief ? [createDraftGenerationJob(brief, { id: "job-initial-brief", title: "First scene", now })] : [],
+ generationJobs: brief && input.generationType !== "image" ? [createDraftGenerationJob(brief, { id: "job-initial-brief", title: "First scene", now })] : [],
providerSettings: {},
});
}
diff --git a/src/lib/runtime.ts b/src/lib/runtime.ts
index ac1819b..d79505c 100644
--- a/src/lib/runtime.ts
+++ b/src/lib/runtime.ts
@@ -1,4 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
+import { imageSceneSchema, type ImageScene } from "./imageScene";
import { isTauri } from "./persistence";
import type { TemplateLora } from "./loras";
import { refreshDownloadedLoras, refreshDownloadedWeights } from "./weightDownloads";
@@ -40,6 +41,7 @@ export interface SlopfabStatus {
export interface RuntimeStatus { providers: ProviderStatus[]; slopfab: SlopfabStatus }
export type ProjectCommand =
+ | ({ op: "image.set" } & Omit<ImageScene, "outputAssetId">)
| { op: "project.set"; name?: string; prompt?: string; targetSeconds?: number; aspectRatio?: string; resolution?: string; frameRate?: number; backgroundColor?: string }
| { op: "ref.add"; id: string; name: string; text: string; use: string[] }
| { op: "ref.set"; id: string; name?: string; text?: string; use?: string[] }
@@ -308,6 +310,13 @@ function executeDemoCommands(config: ProjectConfig, commands: ProjectCommand[]):
};
for (const command of commands) {
switch (command.op) {
+ case "image.set": {
+ if (next.generationType !== "image") throw new Error("image.set requires an image project.");
+ const { op: _op, ...authored } = command;
+ for (const id of authored.referenceIds) if (!next.references.some((reference) => reference.id === id)) throw new Error(`Image reference '${id}' does not exist.`);
+ next.imageScene = imageSceneSchema.parse({ ...authored, outputAssetId: next.imageScene?.outputAssetId ?? null });
+ break;
+ }
case "project.set":
if (command.name !== undefined) next.name = command.name;
if (command.prompt !== undefined) next.brief.prompt = command.prompt;
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index bfde7e1..d3fbfc0 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -1,4 +1,9 @@
import { listen } from "@tauri-apps/api/event";
+import { invoke } from "@tauri-apps/api/core";
+import { createImageScene, imageScenePrompt } from "./imageScene";
+import { outputDimensions } from "./export";
+import { projectItemPath, referenceImages, referenceRefmodInputs } from "./project";
+import { engineProviderSetting, type GeneratorTemplate } from "./settings";
import { describeDiagnosticError, writeDiagnostic } from "./diagnostics";
import { GenerationTimingEstimator, type CompletedGenerationTiming, type GenerationTimingProgress } from "./generationTiming";
import { releaseRendered, saveGeneratedScene } from "./generatedVideo";
@@ -14,7 +19,7 @@ import { prepareReferenceVideos, releaseReferenceVideos } from "./referenceVideo
export type WorkStatus = "queued" | "preparing" | "generating" | "encoding" | "completed" | "failed" | "cancelled";
export interface GenerationSubmission { job: GenerationJob; request: SlopfabGenerationRequest; snapshot: string }
export interface WorkItem {
- kind?: "reference-icons";
+ kind?: "reference-icons" | "image";
id: string;
projectKey: string;
folderPath: string;
@@ -32,6 +37,7 @@ export interface WorkItem {
settings: { frames: number; steps: number; seed: number; canvasWidth: number; canvasHeight: number };
}
interface PendingWork {
+ image?: boolean;
id: string;
session: ProjectSession;
sceneId: string;
@@ -186,7 +192,42 @@ export class WorkQueue {
if (this.items.some((item) => item.status === "queued" && item.kind !== "reference-icons")) this.icons.yieldToVideo();
void this.pump();
}
+
+ enqueueImage(session: ProjectSession, template: GeneratorTemplate) {
+ if (!isTauri()) throw new Error("Image generation requires the desktop app and MiniMax H3 weights.");
+ if (template.mode === "animate") throw new Error("Choose a MiniMax H3 prompt template for images.");
+ const current = session.getSnapshot().config;
+ if (current.generationType !== "image") throw new Error("Open an image project to generate images.");
+ const scene = current.imageScene ?? createImageScene(current.brief.prompt);
+ const prompt = imageScenePrompt(scene);
+ if (!prompt) throw new Error("Describe the image or add an object before generating.");
+ const projectKey = projectQueueKey(session.record);
+ if (this.items.some((item) => item.projectKey === projectKey && item.kind === "image" && isWorkActive(item))) return;
+ const config = structuredClone({ ...current, providerSettings: { ...current.providerSettings,
+ slopfab: engineProviderSetting(template.paths, current.providerSettings.slopfab, template.attention, template.loras, "prompt", template.additionalSafetensors, false) } });
+ const references = scene.referenceIds.map((id) => {
+ const reference = current.references.find((candidate) => candidate.id === id);
+ if (!reference) throw new Error(`Selected image reference '${id}' no longer exists.`);
+ if (reference.kind === "video" || reference.kind === "audio") throw new Error("Still images accept image and text references.");
+ return reference;
+ });
+ const { width, height } = outputDimensions(current.settings.resolution, current.settings.aspectRatio);
+ const id = `image-${crypto.randomUUID()}`;
+ let finish!: () => void;
+ const done = new Promise<void>((resolve) => { finish = resolve; });
+ const request: SlopfabGenerationRequest = { jobId: id, stillImage: true, frames: 1, prompt: [prompt, ...references.map((reference) => `${reference.name}: ${reference.description}`)].join("\n"),
+ canvasWidth: width, canvasHeight: height, steps: generationStepsWithLoras(scene.steps, config), seed: scene.seed,
+ referencePaths: references.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(session.record.folderPath, image)!)),
+ refmods: referenceRefmodInputs(session.record.folderPath, references),
+ };
+ this.work.set(id, { id, image: true, session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(scene), request, submitted: false, cancelled: false, done, finish });
+ this.items = [...this.items, { id, kind: "image", projectKey, folderPath: session.record.folderPath, projectName: config.name, sceneId: scene.nodes.find((node) => node.kind === "root")!.id,
+ title: "Image · " + config.name, submittedAt: new Date().toISOString(), status: "queued", progress: 0, detail: "Waiting to generate image", error: null, completionAt: null, cancelling: false, needsSave: false,
+ settings: { frames: 1, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];
+ this.publish(); this.icons.yieldToVideo(); void this.pump();
+ }
private updateScene(work: PendingWork, patch: Partial<GenerationJob>, dirty = true) {
+ if (work.image) return;
work.session.update((current) => ({
...current, generationJobs: current.generationJobs.map((job) => job.id === work.sceneId ? { ...job, ...patch, updatedAt: new Date().toISOString() } : job),
}), dirty);
@@ -221,7 +262,7 @@ export class WorkQueue {
work.snapshot = sceneGenerationSnapshot(captured, work.request);
this.updateScene(work, { generationSnapshot: work.snapshot });
}
- await purgeTimelineThumbnails(next.folderPath, work.sceneId).catch(() => undefined);
+ if (!work.image) await purgeTimelineThumbnails(next.folderPath, work.sceneId).catch(() => undefined);
if (work.cancelled) continue;
if (work.request.referenceVideos?.length) {
work.request.referenceVideoIds = await prepareReferenceVideos(next.folderPath, work.request, work.config,
@@ -230,7 +271,7 @@ export class WorkQueue {
if (work.cancelled) continue;
const plan = await resolveSlopfabPlan(work.request, work.config, next.folderPath);
if (work.cancelled) continue;
- this.patch(work.id, { status: "generating", detail: `Generating ${plan.alignedFrames} frames at ${plan.canvasWidth} × ${plan.canvasHeight}` });
+ this.patch(work.id, { status: "generating", detail: `Generating ${work.image ? "image" : `${plan.alignedFrames} frames`} at ${plan.canvasWidth} × ${plan.canvasHeight}` });
this.updateScene(work, { status: "generating", stage: "preparing" }, false);
await enqueueSlopfabGeneration(work.request, work.config, next.folderPath);
work.submitted = true;
@@ -262,7 +303,7 @@ export class WorkQueue {
try { await cancelSlopfabGeneration(work.id); }
catch (reason) {
work.cancelled = false;
- this.patch(work.id, { cancelling: false, detail: "Generating video", error: `Could not cancel: ${describeDiagnosticError(reason)}` });
+ this.patch(work.id, { cancelling: false, detail: work.image ? "Generating image" : "Generating video", error: `Could not cancel: ${describeDiagnosticError(reason)}` });
}
}
cancelScenes(session: ProjectSession, sceneIds: string[]) {
@@ -295,7 +336,7 @@ export class WorkQueue {
const item = this.items.find((candidate) => candidate.id === event.jobId);
if (!work || !item || !["preparing", "generating"].includes(item.status)) return;
const progress = Math.max(item.progress, event.totalSteps > 0 ? Math.min(0.88, 0.12 + Math.max(0, event.step) / event.totalSteps * 0.76) : event.stage === "delivering" ? 0.88 : 0.08);
- this.patch(work.id, { status: "generating", progress, completionAt: this.timing.update(event), detail: item.cancelling ? "Cancelling generation" : event.stage === "starting" || event.stage === "transformerLoad" ? "Loading video engine" : "Generating video" });
+ this.patch(work.id, { status: "generating", progress, completionAt: this.timing.update(event), detail: item.cancelling ? "Cancelling generation" : event.stage === "starting" || event.stage === "transformerLoad" ? "Loading MiniMax H3" : work.image ? "Generating image" : "Generating video" });
this.updateScene(work, { status: "generating", stage: event.stage === "starting" || event.stage === "transformerLoad" ? "preparing" : "generating", progress }, false);
}
private event(event: JobEvent) {
@@ -315,6 +356,7 @@ export class WorkQueue {
// A queued acknowledgement can arrive after progress. It must not rewind it.
}
private async encode(work: PendingWork) {
+ if (work.image) { await this.saveImage(work); return; }
this.patch(work.id, { status: "encoding", progress: 0.9, detail: "Saving video", completionAt: null });
this.updateScene(work, { status: "ready", stage: "encoding", progress: 0.9, error: null }, false);
try {
@@ -352,7 +394,23 @@ export class WorkQueue {
if (this.icons.owns(id)) { await this.icons.retrySave(); return; }
const work = this.work.get(id);
if (!work) return;
- try { await work.session.save(); this.patch(id, { status: "completed", needsSave: false, error: null, detail: "Video saved" }); }
+ try { await work.session.save(); this.patch(id, { status: "completed", needsSave: false, error: null, detail: work.image ? "Image saved" : "Video saved" }); }
catch (reason) { this.patch(id, { error: describeDiagnosticError(reason) }); }
}
+ private async saveImage(work: PendingWork) {
+ this.patch(work.id, { status: "encoding", progress: 0.9, detail: "Saving image", completionAt: null });
+ try {
+ const saved = await invoke<{ relativePath: string; width: number; height: number }>("save_generated_image", { folderPath: work.session.record.folderPath, jobId: work.id });
+ work.session.update((current) => ({ ...current, thumbnail: saved.relativePath,
+ imageScene: { ...(current.imageScene ?? createImageScene()), outputAssetId: work.id },
+ assets: [...current.assets, { id: work.id, kind: "image", name: `Image ${current.assets.filter((asset) => asset.kind === "image").length + 1}`, ...saved, mimeType: "image/jpeg", createdAt: new Date().toISOString() }],
+ }));
+ try { await work.session.save(); this.patch(work.id, { status: "completed", progress: 1, detail: "Image saved" }); }
+ catch (reason) { this.patch(work.id, { status: "failed", progress: 1, needsSave: true, detail: "Image created; project save failed", error: describeDiagnosticError(reason) }); }
+ } catch (reason) { this.fail(work, reason); }
+ finally {
+ try { await releaseRendered(work.id); }
+ finally { work.finish(); }
+ }
+ }
}
diff --git a/src/styles/image-editor.css b/src/styles/image-editor.css
new file mode 100644
index 0000000..16d8930
--- /dev/null
+++ b/src/styles/image-editor.css
@@ -0,0 +1,56 @@
+.project-content--editor { padding: 0; overflow: hidden; }
+.image-editor { display: grid; grid-template-columns: minmax(180px, 240px) minmax(0, 1fr) minmax(220px, 300px); height: 100%; min-height: 0; }
+.image-editor header { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); padding: var(--space-3); border-bottom: 1px solid var(--line-solid); }
+.image-tree, .image-inspector { min-height: 0; overflow: auto; background: var(--panel); }
+.image-tree { display: flex; flex-direction: column; border-right: 1px solid var(--line-solid); }
+.image-tree > [role="tree"] { flex: 1; overflow: auto; }
+.image-inspector { border-left: 1px solid var(--line-solid); }
+.image-editor__actions, .image-tree__footer { display: flex; align-items: center; gap: var(--space-1); }
+.image-tree__add { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-1); padding: var(--space-2); }
+.image-tree__add button { padding-inline: var(--space-2); font-size: var(--text-xs); }
+.image-tree__row { display: flex; align-items: center; min-height: var(--control-md); }
+.image-tree__row.selected { background: var(--panel-3); color: var(--text-primary); box-shadow: inset 3px 0 var(--accent); }
+.image-tree__select { display: flex; gap: var(--space-2); align-items: center; flex: 1; min-width: 0; padding: var(--space-2); text-align: left; border: 0; background: transparent; color: inherit; }
+.image-tree__select span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.image-tree__spacer { width: var(--control-sm); flex-shrink: 0; }
+.image-tree__footer { padding: var(--space-2); border-top: 1px solid var(--line-solid); }
+.image-center { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--bg); }
+.image-editor .image-toolbar { justify-content: flex-start; flex-wrap: wrap; background: var(--panel); }
+.image-toolbar label { display: flex; flex-direction: column; gap: var(--space-1); flex: 1; min-width: 120px; font-size: var(--text-xs); }
+.image-toolbar select { width: 100%; min-width: 0; }
+.image-model { font-size: var(--text-xs); color: var(--text-faint); }
+.image-canvas-tools { display: flex; align-items: center; flex-wrap: wrap; gap: var(--space-2); padding: var(--space-2); border-bottom: 1px solid var(--line-solid); font-size: var(--text-xs); }
+.image-canvas-tools input[type="range"] { width: 72px; min-width: 0; }
+.image-canvas-tools select { width: auto; max-width: 160px; }
+.image-canvas-tools .active { color: var(--accent); }
+.image-viewport { flex: 1; min-height: 0; overflow: auto; container-type: size; display: grid; padding: var(--space-3); }
+.image-frame { position: relative; margin: auto; flex-shrink: 0; width: calc(min(100cqw - 32px, (100cqh - 32px) * var(--image-ratio)) * var(--image-zoom)); aspect-ratio: var(--image-ratio); background: var(--panel); box-shadow: 0 0 0 1px var(--line-solid); }
+.image-frame > img, .image-frame > .reference-image { position: absolute; width: 100%; height: 100%; object-fit: contain; inset: 0; }
+.image-empty { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--space-3); text-align: center; padding: var(--space-4); color: var(--text-faint); }
+.image-empty span { max-width: 300px; font-size: var(--text-sm); }
+.image-overlay { position: absolute; inset: 0; width: 100%; height: 100%; touch-action: none; }
+.image-overlay rect { fill: color-mix(in srgb, var(--accent) 8%, transparent); stroke: var(--accent); stroke-width: 1.5; cursor: move; }
+.image-overlay .selected > rect { stroke-width: 3; }
+.image-overlay text { fill: var(--accent); font: 24px var(--font-sans); paint-order: stroke; stroke: var(--panel); stroke-width: 3px; pointer-events: none; }
+.image-overlay .image-box-handle { fill: var(--accent); cursor: nwse-resize; }
+.image-overlay.drawing, .image-overlay.drawing rect { cursor: crosshair; }
+.image-status { display: flex; flex-direction: column; gap: var(--space-1); padding: var(--space-2) var(--space-3); font-size: var(--text-xs); border-top: 1px solid var(--line-solid); }
+.image-status progress { width: 100%; height: var(--space-1); accent-color: var(--accent); }
+.image-error { margin: 0; padding: var(--space-2) var(--space-3); color: var(--danger); }
+.image-results { display: flex; gap: var(--space-2); overflow-x: auto; padding: var(--space-2); border-top: 1px solid var(--line-solid); }
+.image-results button { flex: 0 0 72px; height: 64px; padding: 0; overflow: hidden; border: 2px solid transparent; background: var(--panel); }
+.image-results button[aria-pressed="true"] { border-color: var(--accent); }
+.image-results img { width: 100%; height: 100%; object-fit: cover; }
+.image-inspector__fields { display: flex; flex-direction: column; gap: var(--space-3); padding: var(--space-3); }
+.image-inspector label { display: flex; flex-direction: column; gap: var(--space-1); font-size: var(--text-sm); }
+.image-inspector input, .image-inspector textarea, .image-inspector select { width: 100%; min-width: 0; }
+.image-inspector textarea { resize: vertical; }
+.image-inspector h3 { margin: var(--space-2) 0 0; font-size: var(--text-sm); color: var(--text-primary); }
+.image-inspector p { font-size: var(--text-sm); margin: 0; }
+.image-inspector .image-check { flex-direction: row; align-items: center; gap: var(--space-2); }
+.image-check input[type="checkbox"] { width: auto; }
+.image-box-fields { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-2); }
+.image-palette { display: flex; flex-wrap: wrap; gap: var(--space-2); }
+.image-palette > div { display: flex; align-items: center; }
+.image-palette input[type="color"] { width: var(--control-sm); height: var(--control-sm); padding: var(--space-1); }
+@media (max-width: 1100px) { .image-editor { grid-template-columns: 180px minmax(0, 1fr) 240px; } .image-model { display: none; } }